Compare commits

...
44 Commits
Author SHA1 Message Date
Guoliang ChenandClaude Mythos 5.2 58d3db3e3c Release 0.65.6: saving a file no longer re-indexes the workspace
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 16s
release / build-and-publish (push) Failing after 4m55s
TODO §71.1. On OpenTitan hw (4 058 files) every save cost ~160 ms of
whole-index work, twice (the save and VS Code's watcher echo), and watcher
events for files the index could not hold started whole rescans.

- vlog_semantic: resolution records every table lookup per reading file,
  misses included (workspace/dependents.rs, references.rs, replace.rs); an
  update re-resolves the edited file and the readers of keys whose values
  changed in what resolution reads. An unchanged record merges nothing. When
  the readers hold more than an eighth of all references, old results are
  removed in one pass over the postings.
- lucisv_server: watcher events are classified per file (state/watched.rs);
  the include graph keeps every include line as written and re-resolves the
  lines a named path could satisfy, in one pass per event; an event naming
  more paths than half the index takes the single rescan; an open buffer the
  index does not hold joins on its first save; completion tables are rebuilt
  only for the names a file declares. Every save still republishes every open
  buffer. The line-length lint follows the formatting style's width.
- Fixed on the way: removing an included header left other files' include
  edges pointing at it.

Typical saves: comment or watcher echo <0.3 ms, local signal 4 ms, package
member 12 ms; warm startup +40..120 ms for the readers table.

QA failed the first cut on four stale answers found with an independent
fresh-server oracle; all four are fixed and are differential tests. Dev
(three rounds), QA (two rounds) and lead review:
docs/features/localized-reindex/README.md. TODO.md files lane 71.7 from
what the QA rounds and an investigation found in earlier releases too.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.6) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_semantic 435/0,
lucisv_server 2011/0, lucisv_mcp 384/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 08:52:01 -08:00
Guoliang ChenandClaude Mythos 5.2 80017a59f2 Release 0.65.5: named formatting styles
release / build-and-publish (push) Successful in 5m22s
TODO §71.5. One setting picks a house layout — [format] style in
lucisv.toml, --style, the lucisv.format.style drop-down, the server and MCP:
lucisv (default), google, lowrisc, ansi, microsoft, nxp, and auto. Seven
layout rules (indent, width, begin placement, else placement, else after a
labelled end, one-per-line lists, list indent, alignment), one row per style
in one table in crates/vlog_formatter/src/style.rs. google and lowrisc follow
those published guides; ansi, microsoft and nxp are lucisv's guesses and say
so. auto formats with each preset and keeps the result that changes the
fewest lines (crates/vlog_formatter/src/auto.rs); the language server
remembers each document's preset (lucisv_server/src/auto_style.rs) so
selection and on-type formatting do not repeat the search. The style is part
of the format cache key.

Proof: default output byte-identical to 0.65.4 on 4 921 files (corpus +
OpenTitan hw) against an independently rebuilt 0.65.4; every style formatted
three times over the same files with no verification error, crash, token or
comment difference (independent lexer) or second-run change. verify.rs is
untouched.

Dev (three rounds), QA (two rounds, pass with findings) and lead review are
in docs/features/format-styles/README.md. Three one-line calls were added to
lucisv_server/src/server/notification.rs for the memory's invalidation.
TODO.md files the pre-existing bugs QA met on the way.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.5) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_formatter 376/0,
lucisv_server 1996/0, corpus 814/6.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 07:03:20 -08:00
Guoliang ChenandClaude Mythos 5.2 7408face90 TODO §70: the tests are portable to Linux (macOS-verified), and §71's queue
Test code only. The suite had only ever run on macOS; the first Linux trial
found clippy red on three unused imports and 11 failing tests.

- Unused imports (lucisv_server hover.rs, includes.rs test modules): they now
  carry the same cfg as the macOS/Windows-only tests that use them.
- Eight permission-denied tests (lucisv cli, lucisv_core walk, lucisv_mcp
  apply/cache/qa_m6, lucisv_server filelist): each first probes that the
  mode it relies on is enforced and says 'skipped' if not (root ignores
  modes); std only, no uid check.
- file_ops' case-mismatched include test probes the filesystem's case
  sensitivity first.
- large.rs' two linear-time tests bound growth (8x input <= 24x time, best
  of five) instead of wall-clock; shown to fail at ~60-74x on a quadratic
  implementation by dev and QA independently.
- scan_trace's stage-sum lower bound is asserted on the best of three
  sessions (reproduced flaky on macOS under load: 2.21 ms of 5.10 ms).
- walk.rs' TempTree test helper gains the Drop its doc promised.
- tools/linux_check.sh runs the working tree in the luhpe-linux-x64 runner's
  job image, as root or --user, without a push.

Linux: root green and --user green but for the scan_trace flake were seen
once, on 88546c8 plus round 1 of this lane. Nothing since has run there (the
owner's ssh key expired), so TODO §70's Linux line and the ci.yml linux job
stay open. Dev, QA (mutation table) and lead review:
docs/features/linux-test-portability/README.md.

TODO.md also gains §71, the owner's eight-feature queue, with its waves.

Gates: tools/gates.sh PASS on this tree (0.65.4 + this), lucisv_server 1977/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 05:35:13 -08:00
Guoliang ChenandClaude Mythos 5.2 d57496978f Release 0.65.4: `ifdef blocks fold, and pin in sticky scroll
release / build-and-publish (push) Successful in 5m44s
TODO §71.4. Each conditional-compilation branch (`ifdef, `ifndef, `elsif,
`else) is a folding range from its directive line to the line before the
next branch or `endif, kind region, nested to any depth; sticky scroll,
which already follows the server's folds, pins the branch line. Built on the
lexer's directive tokens (folding/directives.rs), so directives in comments,
strings and `define bodies are not folded; no parser or formatter change.
An existing fold is never lost or changed: scope and comment folds are
computed as before and sent first at a shared start line
(folding::in_answer_order).

Proven on OpenTitan hw (4 061 files, 1 061 branch folds) and the corpus
(860 files, 511): non-directive folds byte-identical to 0.65.3 (QA, base
built from git archive), 10 000-case fuzz against an independent model.

Dev, QA (pass with findings, one fix round) and lead review are in
docs/features/ifdef-folding/README.md. Not seen in a running editor.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.4) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree, lucisv_server 1977/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 05:30:49 -08:00
Guoliang ChenandClaude Mythos 5.2 948f8a0b32 Release 0.65.3: comment keywords, and the brackets in comments explained
release / build-and-publish (push) Successful in 5m28s
TODO §71.8. TODO, FIXME, FIX_ME and TBD inside // and /* */ comments are
drawn bold in a new theme colour (lucisv.commentKeyword), as whole words and
never in strings or code; lucisv.commentKeywords.custom adds the user's own
words, .builtIn switches the four off, .caseSensitive ignores case, all live.
Client-side editor decorations: commentScan.js finds comments with the
grammar's own comment and string rules (0 mismatched lines against
vscode-textmate over OpenTitan hw's 1 185 823 lines), commentKeywords.js
matches literally over the visible lines only, with the block-comment state
cached per document.

The brackets sometimes coloured inside comments are VS Code's bracket-pair
colourisation before background tokenization completes, not lucisv (grammar
and semantic tokens measured clean); explained in the notes, not changed.

Dev, QA (pass with findings, one fix round) and lead review are in
docs/features/comment-highlighting/README.md. Not seen in a running editor.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.3) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree (20261119-050504), node 37/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 05:06:35 -08:00
Guoliang ChenandClaude Mythos 5.2 e9f5090632 Release 0.65.2: the Hierarchy pane shows where you are
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 4m59s
TODO §71.6. The rows leading to the file being edited are lit in the
extension's Hierarchy pane: every instance of the module the open file
declares in a light, bright orange with a solid bar and a bold label, each
ancestor a shade dimmer with a narrower bar, down to a floor. A pure module
(hierarchyCurrent.js) computes each module's distance with one breadth-first
search up the instantiation graph; the webview repaints only the rows whose
level changed, with no server request and no tree rebuild. Six theme colours
under contributes.colors and the setting lucisv.hierarchy.highlightCurrent.
hierarchyPalette_test.js computes label contrast (>= 4.5:1 on every level,
six built-in themes) and neighbour distinctness from the shipped defaults.

Dev, QA (pass with findings, one fix round) and lead review are in
docs/features/hierarchy-current-path/README.md. Not seen in a running editor.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.2) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree (20261119-043114), node 12/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 04:32:43 -08:00
Guoliang ChenandClaude Mythos 5.2 88546c8b4e Release 0.65.1: releases are gated
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 5m5s
The release workflow runs tools/gates.sh (after ensuring the cached corpus)
before it builds anything, so a tag whose tree fails a gate publishes
nothing; until now only the branch push was checked, by a workflow the
release did not wait for. No product change: the packages are 0.65.0
rebuilt, plus the test-only import fix in 5c00b70.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.1) and
editors/vscode/CHANGELOG.md. tools/RELEASING.md and docs/topo.md describe
the gated workflow and the new lustudio-arm64 runner.

Gates: tools/gates.sh PASS on this tree (target/gates/20261119-032522),
all fifteen steps, corpus 814/6.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 03:26:51 -08:00
Guoliang ChenandClaude Mythos 5.2 5c00b701fc Drop an unused Notification import from the server tests
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 15s
Rust 1.100's clippy reports it under -D warnings, which failed the ci
checks job on the new lustudio-arm64 runner. Test-only; no behaviour
change.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 03:17:28 -08:00
lucio 464929262b Release 0.65.0: module instantiation syntax highlighting
release / build-and-publish (push) Successful in 3m40s
ci / corpus (push) Successful in 21s
ci / checks (push) Failing after 10s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.0) and
editors/vscode/CHANGELOG.md. TODO §69.
Gates: no local cargo/tools/gates.sh run on this Windows host (the release
relies on Gitea CI). Locally: all 10 VS Code extension node tests pass
(including the new semanticTokens_test.js, 75 checks).
2026-11-19 02:40:10 -08:00
lucio e4db0ac1fc TODO §69: colour module instantiations by role, with # matching parameters
Add AST-guided semantic token overrides in lucisv_server/src/tokens/instantiation.rs
and cross-file overlay lookup in tokens.rs without changing the 14-type wire legend:
- module/interface/extends names -> class (pkg:: prefixes -> namespace)
- parameter-list # (never delays), .PARAM overrides and parameter values -> parameter
- instance names (declarations, gate instances, bind lists, hierarchical uses) -> function
- named port connections (.port, implicit .port, .*) -> property
- port connection signals -> variable

Enable editor.semanticHighlighting.enabled by default for [verilog] and
[systemverilog] in editors/vscode/package.json and contribute semanticTokenScopes
so every role renders with a distinct, non-white colour across VS Code themes.
Add editors/vscode/semanticTokens_test.js (75 checks, passing under node --test).
Rust tests/fmt/clippy deferred to Gitea CI (no cargo toolchain on this Windows host).
2026-11-19 02:38:42 -08:00
lucioandClaude Mythos 5.2 857b82d58a Release 0.64.0: completion that keeps up with typing
ci / checks (push) Successful in 1m35s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 7m3s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.64.0) and
editors/vscode/CHANGELOG.md. TODO §68.1, §68.2.
Gates: no local tools/gates.sh run (owner's call, 2026-11-09: the release
relies on Gitea CI). Locally: every crate suite green in the lanes' dev
and QA runs, corpus 814/6, and on this commit's tree the release
lucisv-server and lucisv-mcp pass smoke.js / mcp_smoke.js (both modes)
and the node tests (9 files). Not yet seen in a running VS Code.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-17 15:46:21 -08:00
lucioandClaude Mythos 5.2 14213f6a93 TODO §68.2: an unfinished port connection stays in its own entry, and its errors wait until you pause
Parser (tolerant mode only, parser/recover_list.rs): a lone '.', a
'.name(' left open at its line end and a trailing ',' in a named list are
recovered inside their entry — always a diagnostic, never silent; strict
mode and valid code are unchanged (1 026 inputs old vs new: identical
strict results and trees, byte-identical CLI output; corpus 814/6).
Server (state/port_grace.rs): diagnostics that start inside the entry the
last edit touched, in a named-connection list of an instance, are withheld
for 1.5 s and released by the loop's timeout, an edit elsewhere or a save;
a pulling client that supports it gets workspace/diagnostic/refresh.
A trailing ',' in a named list is now reported in tolerant mode too.
Dev + QA (Opus 5.5); QA failed one gate (lucisv_mcp qa_f1), one fix
round, re-check passed: parser 521, server 1954, mcp 383, formatter 352.
Not yet seen in a running VS Code. docs/features/port-entry-grace; topo
rows for §68.1 and §68.2.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-17 15:40:58 -08:00
lucioandClaude Mythos 5.2 c1076f9405 TODO §68.1: begin+Enter writes the end, clock+reset templates, this file's names first, keyword ghosts, port items that write .name()
Server (lucisv_server only): on_type/auto_end.rs — the newline answer
adds the owed end at the owning statement's indentation (lucisv.autoEnd);
always_ff @( / always @( ghosts and popup templates lead with posedge clk
or negedge rst_n; completion tiers put names declared and used in this
buffer ahead of the index, templates and keywords (completion/buffer.rs);
inline/keywords.rs ghosts the rest of a keyword and follows the popup's
selected entry (lucisv.inlineKeywords); connection items keep connected
ports as a second group marked 'connected' and insert name($1), pre-filled
with a same-named signal (completion/connection.rs).
Extension: typing.js sends the newline on-type request itself when
editor.formatOnType is off and restores the cursor; the inline-completion
context is converted to LSP shapes.
Dev + QA (Opus 5.5) + one fix round; unit 1823, e2e 102, node 9 files,
smoke OK. Not yet seen in a running VS Code.
docs/features/completion-ux.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-17 14:39:32 -08:00
lucioandClaude Fable 5.2 6844fbecb6 Release 0.63.1: sticky scroll pins every layer's header
ci / checks (push) Successful in 1m36s
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 8m23s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.63.1) and
editors/vscode/CHANGELOG.md. TODO §67.
Gates: no local tools/gates.sh run; lucisv_server's folding tests (16),
clippy and fmt are clean locally, and the release relies on the Gitea CI
run (owner's call, 2026-11-09).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 14:19:28 -08:00
lucioandClaude Fable 5.2 3132c24b21 TODO §67: sticky scroll pins every layer's header (VS Code follows the folding ranges, ten lines deep)
configurationDefaults for verilog and systemverilog:
editor.stickyScroll.defaultModel = foldingProviderModel and
editor.stickyScroll.maxLineCount = 10. The outline model pinned only the
module header; the server's folds already start on each layer's first
line. A folding test pins the owner's example (module, always, case,
case item, if). Not yet seen in a running VS Code.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 14:19:24 -08:00
lucioandClaude Fable 5.2 ea586d29bc Release smoke: the ranges probe expects a block laid out at its own indentation (TODO §66.2)
ci / checks (push) Successful in 1m54s
ci / corpus (push) Successful in 36s
release / build-and-publish (push) Successful in 7m18s
The v0.63.0 release build failed at tools/release.sh's server smoke test:
smoke.js still expected rangesFormatting to re-indent a named line to the
configured depth. Selection formatting keeps a block's written leading
whitespace, so the probe now checks that the named fork is re-laid from
its own two spaces, the named wire stays put and the unnamed block keeps
its bytes. Checked against a local release lucisv-server (smoke: OK).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 19:50:52 -08:00
lucioandClaude Fable 5.2 e115f9fc8f Release 0.63.0: Format Selection that fits where it stands, comment toggling in VS Code
ci / checks (push) Successful in 1m43s
ci / corpus (push) Successful in 35s
release / build-and-publish (push) Failing after 7m5s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.63.0) and
editors/vscode/CHANGELOG.md. TODO §66.1, §66.2.
Gates: the local tools/gates.sh run was not green — vlog_semantic and
vlog_refactor were killed on the 300 s wall clock (a stuck syspolicyd made
each new test binary take up to 40 s to launch); every test that ran
passed, and both suites passed in full when re-run piecewise on d8119aa.
By the owner's call the release relies on the Gitea CI run.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 19:34:10 -08:00
lucioandClaude Fable 5.2 d8119aa9c6 CLAUDE.md: dev and QA both Opus 5.5; refactor devs Fable 5.2; second QA failure escalates to Fable 5.2
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 18:53:04 -08:00
lucioandClaude Fable 5.2 2854bcaa2f TODO §66.2: the server's range, ranges and on-type formatting run on format_selection
textDocument/rangeFormatting, rangesFormatting and the on-type ';' now
format the selected block in place of the enclosing module-level item;
the reply is still one whole-document edit. On-type ';' now answers in a
buffer whose error is elsewhere and adds no final newline. topo: the
server → formatter edge and the selection-formatting row.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 18:53:04 -08:00
lucioandClaude Fable 5.2 3598a9145e TODO §66.2: format_selection lays out only the selected block, at the indentation it already has
A splice: the smallest run of sibling items/statements the selected lines
cover is laid out alone (Printer::print_at with the written leading
whitespace as the base) and replaces its own bytes; the parent is not
re-laid. Whole-file verify_equivalence and convergence still gate the
result; verify.rs is unchanged. A file that does not parse is formatted
when the error lies outside the target. Descent stops only on a unit's
first line; the closing end line alone names its unit. CRLF kept,
including after a trailing // comment. Module-level targets defer to
format_range, which the CLI's --lines still uses.
36 tests in tests/selection.rs; docs/features/selection-formatting.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 18:53:04 -08:00
lucioandClaude Fable 5.2 a8c4a2ecf8 TODO §66.1: the VS Code extension declares the language's comments and brackets (Ctrl+/ toggles comments)
editors/vscode/language-configuration.json for both verilog and
systemverilog: // and /* */, bracket pairs, auto-closing and surrounding
pairs. TODO §66 planned (66.1 here, 66.2 selection formatting).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 18:53:04 -08:00
lucioandClaude Opus 5.5 66bf27617e Release 0.62.0: paths rooted at a top-level module, the release gate script, guard memory at every depth
ci / checks (push) Successful in 1m50s
ci / corpus (push) Successful in 38s
release / build-and-publish (push) Successful in 6m59s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.62.0) and
editors/vscode/CHANGELOG.md. TODO §65.2 (closed by ruling), §65.3, §65.4.
Gates: tools/gates.sh PASS on 9dc567c (15 steps, 5 180 tests, corpus
814/820); CI green on 9dc567c.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:45:28 -07:00
lucioandClaude Opus 5.5 9dc567c72a TODO §65.4: a hierarchical path rooted at a top-level module resolves through the workspace (conservative)
ci / checks (push) Successful in 1m42s
ci / corpus (push) Successful in 32s
`tb.dut.g_sw[0].buf_q` written in a file that does not declare `tb` now
resolves like an instance path: the binder marks a dotted path's head
(Target::PathHead), resolve/root.rs answers a plain lexical miss with a
hierarchical external candidate, head_site roots the spine there, and
fold_path walks it — every hop a module/interface surface. find_references,
LSP references and rename see every segment; $root.tb works; a local `tb`
shadows. FACTS_FORMAT 22.

Rooted only when the root is provable (owner's ruling: conservative): not
when the head has an import candidate (so `import uvm_pkg::*` with uvm_pkg
outside the project stays warned — opentitan's DV force paths behave as
before), not from inside a class, not beside a macro that stands where a
declaration could (item, statement, port list), not when the root name is
also a package or ambiguous. The LSP rename set adds the files of the
path's root and middle hops (sources.rs, WorkspaceIndex::path_units_to).
An unresolved path is warned once.

QA (Opus) x2: F1-F4 and R1 silent-wrong-rename shapes fixed with tests;
QA's attack cases 1-6 each warned or correctly renamed; lucisv check hw
byte-identical to master. Completion after `tb.` deferred (TODO §65.8).
tools/gates.sh: PASS, 15 steps, 5 180 tests, corpus 814/820.
docs/features/top-rooted-paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 15:34:45 -07:00
lucioandClaude Opus 5.5 92875e6c6d TODO §65.3: tools/gates.sh, the release gate; guard.sh enforces memory at every depth and runs with a closed stdin
ci / checks (push) Successful in 1m34s
ci / corpus (push) Successful in 38s
guard.sh fixes (both ours): the memory sum never saw a process three or
more levels down the tree (a doubled space became an empty entry in the
`ps -p` list, which macOS rejects whole), so cargo -> rustc -> linker and
test-spawned servers were never memory-limited — QA re-proved 1.5 GB at
depth 3/4 missed by master, killed in 2-4 s now; a closed stdin skipped
the command silently, now /dev/null. The stall itself is the host's
(syspolicyd on fresh unsigned binaries).

tools/gates.sh runs fmt, clippy, the test build, one suite per workspace
crate, the doc-tests, the corpus gate and the node tests as separate
guarded steps with kept logs and per-step limits; a guard-killed step is
retried once and shown as KILLED -> retried; usage errors exit 2 (lead
fixes after QA: comments/one-line/glob members, an empty crate list, a
missing option value, an empty selection). RELEASING.md step 3, CLAUDE.md
and the README's Building section point at it.

Ten consecutive green runs recorded (healthy host); full gate on master:
PASS, 15 steps, 5 127 tests, corpus 814/820. QA (Sonnet): PASS.
docs/features/release-gates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 06:13:28 -07:00
lucioandClaude Opus 5.5 51b975bf68 TODO §65.2 closed by ruling: LSP references are scope-relative by design; tests pin both scopes
ci / checks (push) Successful in 1m40s
ci / corpus (push) Successful in 32s
Root cause (lane A): not the fan-out. The default index scope (`folder`,
depth 2) opened from hw/ip/aes/dv/tb/tb.sv indexes hw/ip/aes only, so the
three *_pd_main.sv tops are never walked; with index.scope "workspace" the
LSP answers 14/12, equal to the whole-set engine. Ruled out: the 1 MiB cap,
autogen/ignore rules, the multi-line instantiation. The owner kept the
design; the index.scope setting now says a rename of a module instantiated
outside the scope leaves those sites unchanged.

Tests: server/tests/references_scope.rs (3: the LSP equals the engine over
the same file set in both scopes, a module rename reaches the top under
`workspace`), tests/opentitan_references.rs (2, ignored: 14/12 workspace,
11/9 default). lucisv_server 1 865 passed, 0 failed; node 8/8.
docs/features/references-fanout-pd-main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 05:48:40 -07:00
lucioandClaude Opus 5.5 ec492cdd86 TODO §65: correct the release targets (65.1 shipped in 0.60.0; 65.2-65.4 target 0.62.0) and plan the 0.62.0 wave (§65.7)
ci / checks (push) Successful in 2m3s
ci / corpus (push) Successful in 34s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 05:32:31 -07:00
lucioandClaude Opus 5.5 75d2d376cf Release 0.61.0: call hierarchy from anywhere with function/task nodes, type hierarchy inside classes, full-line references view in VS Code
ci / checks (push) Successful in 1m38s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 8m24s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); the notes are in CHANGELOG.md (## 0.61.0) and
editors/vscode/CHANGELOG.md. Gates on the tree: fmt and clippy -D warnings
clean, lucisv_server 1 862 passed 0 failed, per-crate suites green at
ca83f6f, node tests 8/8; CI checks green on 31b7db1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 14:56:33 -07:00
lucioandClaude Opus 5.5 31b7db16a3 LSP: call and type hierarchy answer from anywhere in a body; functions and tasks are call-hierarchy nodes
ci / checks (push) Successful in 1m38s
ci / corpus (push) Successful in 32s
Show Call Hierarchy was empty in VS Code unless the cursor sat on a module
name. prepareCallHierarchy now answers on an instance name (its module),
on a function/task declaration, call or end label (a FUNCTION/METHOD item
with data {kind,name,offset}), inside a function/task body (that one), and
inside a module/interface/program (the enclosing module). Function/task
items: incomingCalls = call sites grouped by the enclosing function/task or
unit, over the same files references reads; outgoingCalls = resolved
callees (system tasks and unresolved names skipped). A function's bare name
in its own body is its result variable, not recursion. Module items keep
instantiation edges, byte-identical. prepareTypeHierarchy answers the
enclosing class inside a class body and the base on `super`.

QA (Opus): old module answers identical at 3 137 positions; outline,
definition, references, hover unchanged at 1 340 queries; findings fixed in
a rework (outgoing over a closed 300-function package 3.0 s -> 18 ms). Two
e2e assertions that pinned the old null flipped (lead's handshake).
lucisv_server 1 862 passed, 0 failed; fmt, clippy -D warnings clean.
docs/features/call-hierarchy-everywhere.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 14:53:38 -07:00
lucioandClaude Opus 5.5 5e4af0be3d VS Code: Find All References with whole source lines (lucisv References view)
VS Code's built-in references pane cuts each preview to ~8 characters
before the match. lucisv.references.show runs the same reference and
definition providers and fills a tree view in the lucisv sidebar: one row
per file (current file first), one row per reference with the trimmed full
line and the identifier highlighted, the declaration marked; a click
selects the exact range. The setting lucisv.references.fullLineView
(default true) binds Shift+Alt+F12 to it in verilog/systemverilog editors
only; Shift+F12 peek is untouched. Closed files are read with
workspace.fs, so no didOpen reaches the server.

QA (Sonnet): PASS with 4 lows (recorded). Node tests 8/8. tools/RELEASING.md
must-ship list names every runtime module (lane handshake).
docs/features/vscode-references-view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 14:14:11 -07:00
lucioandClaude Opus 5.5 41a90917bb Housekeeping: package-lock version follows the release and release.sh checks it; repository analysis refreshed to 0.60.0
ci / checks (push) Successful in 1m33s
ci / corpus (push) Successful in 33s
editors/vscode/package-lock.json said 0.10.2 since 0.10.2; it is 0.60.0
now, and tools/release.sh refuses to build when package.json or either
package-lock.json version differs from `lucisv --version`.
docs/repository-analysis.md: refreshed against 58520e5 (v0.60.0) — a status
row per release 0.50.0-0.60.0, nine MCP tools (five read-only), codec 21,
the generate-block and home-set contracts, the §55 split, and the current
open limits (§65.2-§65.6, review L-5-L-11, handshakes 31/32).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 13:38:04 -07:00
lucioandClaude Opus 5.5 4fae8fb63a TODO §55: split lucisv_server state/mod.rs by responsibility (pure move)
state/mod.rs 986 -> 63 production lines: document.rs (one analyzed
buffer), buffers.rs (open buffers), views.rs (closed-file view cache),
scope.rs (roots, settings, scope ladder), rescan.rs (scan and widen
protocol, 411), incremental.rs (one saved file re-indexed), sources.rs
(file sets for refactorings, 170). The 3 944-line inline test module moved
to state/tests/ (14 topic files). No function body changed; only forced
pub(super) widenings. Lead's line-multiset check: no code line lost or
added. CLAUDE.md measurement refreshed (2026-10-14); a stale test path in
server/tests/folders.rs corrected.

Gates on the merged tree: fmt and clippy -D warnings clean; lucisv_server
1 823 passed, 0 failed, 38 ignored (= before); the lane's workspace run 80
suites, 5 078 passed. Refactor dev Claude Fable 5.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 13:38:04 -07:00
lucioandClaude Opus 5.5 ca83f6f99f Review lows L-1–L-4, L-12, L-13: end labels, duplicate generate labels, dotted comments, lex-failure fallbacks, file naming
- L-1: an unowned block's closing label is a use of a same-named block only
  for block constructs and only when it spells the construct's own opening
  label (use_block_end_label); a mismatched `end : a` or an `endfunction : g`
  beside block `g` records nothing.
- L-2: duplicate-declaration stays silent for two block labels only when
  both may be arms of one generate if/case; sibling `for` blocks and a
  procedural block beside a generate one are reported in either order.
  OpenTitan check: 1 158 findings, identical to 0.60.0.
- L-3: a block comment between `.` and the name is still dotted.
- L-4: a bind file that does not lex counts as binding (K2); a pasted
  fragment that does not lex is said, not skipped.
- L-12: no unchecked slice in rename/arms.rs.
- L-13: expand/ansi/inline/extract messages name files by Scope::name_of.

7 tests (L-3/L-4's fail with the fixes disabled). Per-crate suites under the
guard: 80 suites, 5 085 passed, 0 failed, 51 ignored (one combined run was
cut at 1 800 s in vlog_refactor/tests/corpus.rs with syspolicyd at 95 % —
the §65.3 stall).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 13:33:27 -07:00
lucioandClaude Opus 5.5 58520e586e Release 0.60.0: rename and references through generate block labels; rename warnings scoped to the renamed declaration
ci / checks (push) Successful in 1m37s
ci / corpus (push) Successful in 36s
release / build-and-publish (push) Successful in 8m2s
Version bump; the notes are in CHANGELOG.md (## 0.60.0) and
editors/vscode/CHANGELOG.md. TODO §65.1 plus the independent review's
H-1/H-2 and M-1/M-2 fixes. Gates on the tree: fmt and clippy -D warnings
clean, workspace lib/bins/tests 80 suites 5 078 passed 0 failed, node tests
6/6; doc-tests and the corpus gate run in CI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-08 01:14:59 -07:00
lucioandClaude Opus 5.5 a062f62581 Docs for §65.1 match the code (review M-3)
ci / checks (push) Successful in 1m42s
ci / corpus (push) Successful in 33s
generate-label-rename README: "What changed" covers reworks 1-5 and the
review fixes; the stale "engine and verifier unchanged in code" claim is
replaced (what a rename rewrites is unchanged; the verifier gained no
normalization, only path-qualified file names). Status lists reworks 2-5,
P1/P2, §65.6 and the review; work log entries for M-2 and M-3, including
that QA's P1/P2 were fixed in the tree with no log entry. refactor-rename
README: dated correction. topo row 40: second half answered by row 43.
CHANGELOG: the two scoping bullets merged into one that matches rework 5
plus the H-1/H-2 fix. qa_warning_scope.rs P1/P2 test comments and the
rename module doc updated (comments only; that suite: 24 passed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 02:06:47 -07:00
lucioandClaude Opus 5.5 6d1957076a Refactor messages: count shared file names once per set, not once per file named (review M-2)
Scope::name_of scanned every source on each call, and the define and
macro-argument warning scans named every file of the set before looking for
a site — two quadratic passes. scope::BaseNames counts base names once (kept
on Scope and on the port offers' Files; name_among folded into it).

OpenTitan engine probe, whole hw, entropy_src_main_sm.state_q: 2.95 s ->
2.23 s (defines 326 -> 7 ms, macro arguments 394 -> 77 ms), the same 47
warnings. Workspace: 80 suites, 5 078 passed, 0 failed, 51 ignored; clippy
-D warnings clean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 02:05:33 -07:00
lucioandClaude Opus 5.5 38244e6aaf Rename: an include-related file's use that the rename edits is not said to be left unchanged (review M-1)
ci / checks (push) Successful in 1m51s
ci / corpus (push) Successful in 47s
fragment_use_warnings ignored the rename's edits, so renaming module `m`
while `all.sv` includes `m.sv` and `n.sv` rewrote `n.sv`'s instantiation and
still warned "n.sv:2: `m` is used in a file that includes `m.sv` … and was
left unchanged". Tokens covered by an edit in that file are skipped.

Test: rename_warning_scope.rs (fails with the skip disabled). Workspace:
80 suites, 5 077 passed, 0 failed, 51 ignored (first run cut by the guard at
1 800 s launching a fresh test binary — the §65.3 stall; re-run green).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:37:01 -07:00
lucioandClaude Opus 5.5 eadee02c37 Independent review of the §65.1 working tree (oct_review.md): 2 high (fixed), 3 medium, 13 low findings
ci / checks (push) Successful in 1m43s
ci / corpus (push) Successful in 52s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:41 -07:00
lucioandClaude Opus 5.5 e8e22c2364 Rename warnings: a macro argument the macro carries to the declaration is said wherever it is written (review H-1/H-2)
The home-set scoping dropped a bare macro argument outside the home set
whatever the macro did with it, and never saw a `bind` produced by a macro —
silent missed renames, regressions against 0.59.0 (`CONN(state_q)` building
`.state_q(state_q)` broke the instantiation without a word). New
rename/carry.rs decides per macro and formal position whether an argument is
carried: after a `.` (past blanks and pastes), into a carried position of
another macro, or by a macro that expands to a `bind` into the unit (every
position; its body is news and a file invoking it is home). An undefined
macro's arguments, one past the formals and a macro cycle are doubt and said.

Tests: tests/rename_macro_carry.rs (8), carry.rs unit tests (4). Workspace
lib/bins/tests: 80 suites, 5 076 passed, 0 failed, 51 ignored (guard exit 0).
OpenTitan engine probe against carrying disabled: state_q 47 = 47,
StIdle 0 = 0, cnt_q 13 = 13 warnings, timing unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:41 -07:00
lucioandClaude Opus 5.5 7794d3938b TODO §65.1: rename and references through a generate block label; rename warnings and mentions scoped to the renamed declaration
A path segment naming a block (bare, indexed, nested, cross-file) is now a
reference to its label: vlog_semantic declares a `for` block's label in the
enclosing scope, makes `generate … endgenerate` no scope, gives a block a
member scope, walks an index in a path, and files blocks on a module's
hierarchical surface under `module.label` (FACTS_FORMAT 21). The LSP, CLI
and MCP rename/references get it through the engine; lucisv-mcp's `block`
refusal is lifted. No verifier normalization (attacks in
check/qa_block_paths.rs, qa_block_attacks.rs).

Reworks after QA: unresolved path segments warned in every file of the set;
sibling-arm members warned; a label beside a net is a duplicate-declaration;
function-local block keys never collide; file names path-qualified when base
names collide; rename warnings and lucisv-mcp mentions scoped to the
declaration's home set (rename/home.rs, scoped.rs), falling back to unscoped
on any doubt. TODO §65.4 and §65.6 filed.

docs/features/generate-label-rename. Workspace lib/bins/tests: 79 suites,
5 064 passed, 0 failed, 51 ignored (guard exit 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:23 -07:00
lucioandClaude Fable 5.1 b9ee399ac6 TODO §65: stabilization round 1 — generate-label rename/references, LSP references fan-out to the pd_main tops, the doc-test stall
ci / checks (push) Successful in 1m39s
ci / corpus (push) Successful in 35s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-30 01:44:39 -07:00
lucioandClaude Fable 5.1 5316c0b127 Release 0.59.0: MCP read-only mode (--read-only, five tools, 1 797 bytes) and the hierarchy instance cap
ci / checks (push) Successful in 1m27s
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 7m16s
Version bump; the notes are in CHANGELOG.md (## 0.59.0) and
editors/vscode/CHANGELOG.md. Gates: fmt and clippy -D warnings clean,
72 suites + 6 doc suites (4937 passed, 0 failed), corpus 814/820,
node tests 6/6.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 02:12:33 -07:00
lucioandClaude Fable 5.1 74c56318c0 MCP: hierarchy caps at 300 instances (100 with peek), peek lines no longer count; census round 5 (read-only, same-day base control) written up; 0.59.0 notes dated
ci / checks (push) Successful in 2m11s
ci / corpus (push) Successful in 45s
Round 5 found `hierarchy up` + `peek` cut to 20 of 77 instantiations by
the 300-line cap. Same-day base controls put read-only mode at parity
with file tools (a +8 %, d −8 %) and show the base arm itself moved
22–29 % in six days.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 01:38:54 -07:00
lucioandClaude Fable 5.1 b757e82161 MCP M8: read-only mode — lucisv-mcp --read-only lists five read tools (1 797 bytes), never writes inside a root; full mode unchanged
ci / checks (push) Successful in 1m50s
ci / corpus (push) Successful in 52s
The mode filters the registry; an edit tool name answers unknown-tool.
Extension setting lucisv.mcp.mode (full | read-only; any other value is
read-only and logged), label and copy-config key lucisv-ro, both smokes
in the release script. Tests: tests/read_only.rs, QA lane tests/qa_m8.rs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 01:10:10 -07:00
lucioandClaude Fable 5.1 e992cca577 MCP plan §11 + lane M8: read-only mode (--read-only: five tools, ≤1 800 bytes, never writes inside a root; full mode unchanged)
ci / checks (push) Successful in 1m32s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 00:40:34 -07:00
280 changed files with 44995 additions and 7266 deletions

No files matched your search

+15
View File
@@ -14,6 +14,12 @@
# The release fails, deliberately, when the tag does not match the
# workspace version or CHANGELOG.md has no section for it: every release
# ships with real, written notes (see tools/RELEASING.md).
#
# It is gated: tools/gates.sh (fmt, clippy, every crate's suites, the doc
# tests, the corpus gate, the extension's node tests) runs first, and a red
# gate means nothing is built or published. The ci workflow runs on the
# branch push, not the tag, so without this step a tag published whatever
# it pointed at (0.65.0 went out while its ci run was still stuck).
name: release
on:
push:
@@ -25,6 +31,15 @@ jobs:
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
# The corpus is pinned-rev clones cached on the runner host, as in
# ci.yml; gates.sh skips its corpus step when the cache is absent, so
# fetch it here rather than release without that gate.
- name: Ensure the cached corpus
run: |
corpus="$HOME/.cache/lucisv-corpus"
[ -d "$corpus" ] || tools/corpus_fetch.sh "$corpus"
- name: Gate the release
run: tools/gates.sh
- name: Build release artifacts for every target
run: tools/release.sh --cross
- name: Audit the cross-built artifacts
+569
View File
@@ -4,6 +4,575 @@ 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.65.6 — 2026-11-19
### Saving a file no longer re-indexes the workspace
(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw`
tree, 4 058 files, with the server driven the way VS Code drives it.)
- **What was happening.** Every save cost about 160 ms of whole-index work
whatever was edited — 117 ms of it re-resolving all 470 000 cross-file
references — and VS Code triggered it twice, once for the save and once for
its own file watcher. Watcher events for files the index could not hold (a
generated file in a gitignored directory, a file outside the filelist or
folder scope, a held file reported through a symlinked root or in another
letter case) started a whole rescan with the progress bar, 270–750 ms.
- **Now the index does only what the edit can reach.**
| edit, then save | before | now |
|---|---:|---:|
| a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms |
| a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms |
| a member added to `uart_reg_pkg` | ~167 ms | 12 ms |
| a line above a module 125 files instantiate | ~163 ms | 47 ms |
| a member added to a package 677 files import | ~162 ms | 92 ms |
| a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms |
The index records which names each file looked up — including the ones it
did not find — and re-resolves only the readers of names whose meaning
changed. A save whose index record is unchanged merges nothing.
- **Still wide, on purpose.** Adding or deleting a file; a burst of more
files in one watcher event than half the index holds (a branch switch),
which takes the one rescan it always did; an edit above a declaration many
files use. Every save still re-checks every open file's diagnostics, so a
`lucisv.toml` or waiver edit takes effect at the next save as before — with
200 files open that is most of a save (53 ms, against ~205 ms before).
- **The price.** Every whole rescan costs a few per cent more for the table
that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower,
depending on machine load.
- **How it is known to be right.** After any sequence of edits, everything
the server answers must equal what a freshly started server answers for the
same files. QA built that oracle independently and it failed the first cut
on four stale answers (include links to headers outside the scope, lint
configuration, a file-age check macOS defeats, excluded open buffers); all
four are fixed and are now tests. The final build: 312 hand-written
comparisons and twelve random 300–500-step runs over the corpus and
OpenTitan with no divergence it caused.
- **Also.** The language server's `line-length` lint now follows the chosen
formatting style's width (80 under `ansi` and `nxp`, 120 under
`microsoft`), closing the limit noted in 0.65.5. Removing an included
header no longer leaves other files' include links pointing at it.
- **Known, and next.** Found by this round's QA and present in earlier
releases too: an edit made while a whole rescan is running can be applied
out of order, leaving the server's copy of the buffer wrong until the file
is reopened; a watcher event that names only a directory leaves stale
state; an excluded file stays indexed after it is closed. These are the
next round's work.
## 0.65.5 — 2026-11-19
### Named formatting styles
(`docs/features/format-styles`; TODO §71.5.)
- **One setting picks a house layout.** `[format] style = "<name>"` in
`lucisv.toml`, `--style <name>` on the command line, or the new
`lucisv.format.style` drop-down in VS Code. Seven layout rules, one row per
style, in one table in `crates/vlog_formatter/src/style.rs`:
| style | indent / width | `begin` | `else` | lists | list indent | alignment |
|---|---|---|---|---|---|---|
| `lucisv` (default) | 2 / 100 | same line | same line | fit | 1 level | keep |
| `google` | 2 / 100 | same line | same line | one per line | 2 levels | keep |
| `lowrisc` | 2 / 100 | same line | same line | one per line | 1 level | always |
| `ansi` | 4 / 80 | own line | own line | fit | 1 level | keep |
| `microsoft` | 4 / 120 | own line | own line | one per line | 1 level | keep |
| `nxp` | 2 / 80 | same line | own line | one per line | 1 level | always |
- **Where the styles come from.** `google` follows the Google Verilog Style
Guide and `lowrisc` the lowRISC (OpenTitan) guide, both read for this
release, including `else` on its own line after a labelled `end`. **`ansi`,
`microsoft` and `nxp` are lucisv's educated guesses** — Allman-style
`begin`/`else` after iStyle's and clang-format's styles of those names, and
a conservative aligned RTL style — not rules those organisations publish
for Verilog.
- **The default does not move a byte.** `lucisv` output is identical to
0.65.4 on all 4 921 files of the corpus and OpenTitan's `hw` tree, checked
against an independently rebuilt 0.65.4. An explicit `indent` or
`line-length` still wins over a style's.
- **Every style goes through the same safety net.** Each was formatted three
times over those 4 921 files: no verification error, no crash, no token or
comment difference (checked with a lexer that is not the formatter's), and
no change on a second or third run. `verify.rs` is untouched.
- **`style = "auto"` keeps a file in the layout it is already closest to.**
It formats with each preset and keeps the result that changes the fewest
lines, so a file written the Google way stays that way. It picks a layout
for the configured indent and width and **never infers them** — set
`indent` to match the file first, or a 4-space file formatted at the
default 2 comes out in the default layout. Small edits do not flip a file:
over 500 files and ten kinds of edit, none rewrote more than 12 lines
outside the edit. `auto` costs a search — 2.4 s against 0.4 s on a
42 000-line file for a whole-document format — so the language server
remembers each document's layout, and selection and on-type formatting stay
at 0.1 s after the first request.
- **Known limits.** A declaration with several instances in one statement
gets the older hanging layout under the one-per-line styles. The language
server's `line-length` lint still assumes 100 columns under `ansi`,
`microsoft` and `nxp` (the CLI's `check` follows the style). Switching from
one keep-alignment style to another and back is not always a round trip:
alignment a style added stays.
## 0.65.4 — 2026-11-19
### `` `ifdef `` blocks fold, and pin in sticky scroll
(`docs/features/ifdef-folding`; TODO §71.4.)
- **Every conditional-compilation branch folds on its own.** `` `ifdef ``,
`` `ifndef ``, `` `elsif `` and `` `else `` each fold from their own line to
the line before the next branch (or before `` `endif ``). Collapse the
`` `ifdef `` branch and the `` `else `` line stays visible and separately
collapsible; `` `endif `` stays visible too, the way `end` does for a
`begin` fold. Nesting works to any depth.
- **They pin in sticky scroll.** The floating header lines already follow the
server's folds, so while you scroll inside a long branch its `` `ifdef `` or
`` `else `` line stays at the top with the module and blocks around it.
- **Only real directives count.** The folds are built from the lexer's own
directive tokens, so a directive-looking line inside a comment, a string or
a `` `define `` body is not folded (35 such lines in OpenTitan). An
unterminated `` `ifdef `` folds the branches it finished and never runs to
the end of the file; a stray `` `else `` or `` `endif `` is ignored.
- **No existing fold is lost or changed.** On OpenTitan's `hw` tree (4 061
files) and the 860-file corpus every fold the previous release returned is
still returned, byte for byte, with the 1 061 and 511 branch folds added.
Where a branch would share its start line with an existing fold — a
directive written after code on the same line — the existing fold is sent
first and keeps its place; that never occurs in either tree.
- **Cost:** one extra pass over the tokens: folding all of OpenTitan goes from
29.9 ms to about 34 ms, and a 50 000-branch file answers in 0.2 s.
- **Limits.** Files over the large-file threshold (4 MiB) return no folds, as
before. Not yet seen in a running editor by a human.
## 0.65.3 — 2026-11-19
### Comment keywords, and the brackets in comments explained
(`docs/features/comment-highlighting`; TODO §71.8.)
- **`TODO`, `FIXME`, `FIX_ME` and `TBD` stand out inside comments.** In `//`
and `/* */` comments they are drawn bold in a new theme colour,
`lucisv.commentKeyword` — as whole words only (`TODO_reg` and `$TODO` are
left alone), and never in strings or code.
- **Your own words too.** `lucisv.commentKeywords.custom` adds words that are
highlighted the same way and only in comments (matched literally, up to 50
words of 1–40 characters); `lucisv.commentKeywords.builtIn: false` turns the
four built-ins off, and `lucisv.commentKeywords.caseSensitive: false`
ignores case. Every change applies at once, with no reload.
- **It follows what the editor draws as a comment.** The extension finds
comments with the grammar's own comment and string rules; against VS Code's
real tokenizer that agreed on every one of the 1 185 823 lines of
OpenTitan's `hw` tree. It is client-side, so it paints while the language
server is still starting.
- **Cheap on big files.** Only the lines on screen (and 50 either side) are
searched for words; an edit above the screen re-reads the lines from the
edit down to it (7.9 ms at worst on a 100 000-line file). A file VS Code
itself does not tokenize (over 20 MiB or 300 000 lines) is not painted.
- **Brackets coloured inside comments: explained, not changed.** The `[]` of
a `signal[]` that sometimes lights up in a comment is VS Code's bracket-pair
colourisation, which ignores comments until it has finished tokenizing a
newly opened file in the background and then removes the colour itself.
lucisv's grammar and semantic tokens were measured to colour nothing inside
a comment (309 OpenTitan files, and the large-file path). An extension
cannot change that behaviour short of switching bracket colours off for the
whole language, code included — which stays your choice
(`editor.bracketPairColorization.enabled`, or `colorizedBracketPairs`
under `[systemverilog]`).
- **Not yet seen in a running editor by a human**: the tests are headless.
## 0.65.2 — 2026-11-19
### The Hierarchy pane shows where you are
(`docs/features/hierarchy-current-path`; TODO §71.6.)
- **The rows leading to the file you are editing are lit.** Every instance of
the module the open file declares gets a light, bright orange tint with a
solid bar at its left edge and a bold label; each row above it is one shade
dimmer with a narrower bar, down to a faint floor for distant ancestors. A
module instantiated in several places lights every copy, and where two
chains meet the nearer one wins. It works on a closed tree and on DUT
sections: a section header is tinted when the section holds the file or its
parents.
- **Switching files repaints, it does not reload.** There is no request to the
language server and no rebuild of the tree; only the rows whose shade
changed are touched, so nothing collapses (about 5 ms on a 6 000-module
design).
- **Readable in every built-in theme.** The default tints keep label text at
4.5:1 or better on every lit level in the dark, light and high-contrast
themes, hovered rows included — a test computes that from the shipped
defaults — and the bar's width and style change with the level, so the
grading does not rest on colour alone.
- **Yours to restyle or switch off.** The shades and the bar are theme colours
(`lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`,
`lucisv.hierarchyAncestor`, `lucisv.hierarchyCurrentBar`) for
`workbench.colorCustomizations`; `lucisv.hierarchy.highlightCurrent: false`
turns the highlighting off.
- **Known limits.** Nothing lights when a folder name's letter case differs
between the filelist and the editor, or on Windows network-share paths; in a
recursive design a row can be lit with nothing lit beneath it. Not yet seen
in a running editor by a human: the tests are headless.
## 0.65.1 — 2026-11-19
### Releases are gated
No change to the formatter, the linter, the language server or the editor
extension: the packages are 0.65.0 rebuilt. What changed is how a release is
made (`tools/RELEASING.md`).
- **A tag no longer publishes unless every gate is green.** The release
workflow now runs `tools/gates.sh` — `cargo fmt`, `cargo clippy`, each
crate's test suites, the doc tests, the corpus gate and the extension's node
tests — before it builds anything, and a failing gate stops the release.
Until now only the branch push was checked, by a separate workflow the
release did not wait for, so 0.65.0 was published while its checks had not
finished.
- **The build is clean on Rust 1.100.** An unused import in the language
server's test module, which that toolchain's clippy rejects under
`-D warnings`, is gone. It is what turned 0.65.0's checks red after the
fact; the released binaries were never affected.
## 0.65.0 — 2026-11-19
### Module instantiation syntax highlighting
(`docs/features/instantiation-highlighting`; TODO §69.)
- **Every part of a module instantiation gets its own colour.** Module names,
instance names, `.PARAM` overrides, `.port` names and connected signals used
to collapse to the same default foreground colour whenever the instantiated
module lived in another file or a theme left bare semantic tokens unstyled.
The language server now layers AST-guided semantic token overrides (and
cross-file `ExternalResolutions` lookups) over the existing 14-type legend:
- **Module / interface names** (`uart_core`, `pkg::uart_core` with `pkg` as
`namespace`, and lone `bind` targets) highlight as `class`.
- **`#` and parameters share one colour** (`parameter`), distinct from `()`:
the `#` introducing a module, class, `extends`, instantiation or
parameterized-type parameter list, every `.PARAM` override (`.` and name),
and parameter values inside `#(...)` all carry `parameter`. Delay `#`
tokens (`#5`, `#(1:2:3)`) are left unemitted.
- **Instance names** (`u_uart`, gate instances, `bind` instance lists, and
hierarchical uses like `u_uart.sig`) highlight as `function`.
- **Port names** (`.clk_i` dot and name, implicit `.rst_ni`, and wildcard
`.*`), including unfinished entries being typed, highlight as `property`.
- **Port connections** (`clk`, `data_q`) stay `variable` so signals keep one
consistent colour across the file.
- **VS Code: semantic highlighting on by default with theme-safe scope maps.**
`configurationDefaults` enables `editor.semanticHighlighting.enabled` for
`[verilog]` and `[systemverilog]` (user settings still win), and
`contributes.semanticTokenScopes` maps the language's semantic token types to
distinct TextMate scopes so every role renders in colour across Dark+, Dark
Modern, Light+, GitHub Dark, One Dark Pro and Visual Studio Dark.
## 0.64.0 — 2026-11-17
### Completion that keeps up with typing
(`docs/features/completion-ux`, `docs/features/port-entry-grace`; TODO §68.)
- **`begin` + Enter writes the `end`.** The newline on-type answer, when
the line above ends in `begin` (or `begin : label`) and a block is still
open, also inserts `end` on the line after the new one, at the
indentation of the statement that owns the `begin`; the cursor stays on
the new, indented line. Nothing is added when the blocks already balance
(an `end` under the owner or under a `begin` on its own line counts), nor
for a `begin` left open inside an `ifdef` region that has an `else`.
Setting `lucisv.autoEnd` (default on). The VS Code extension sends the
request itself when `editor.formatOnType` is off.
- **`always_ff @(` and `always @(` expand with clock and reset**:
`posedge clk or negedge rst_n`, both names tab stops, as the ghost text
and as the first popup template. The clock-only forms follow.
- **This file's names rank first.** The popup's order is now: the scope at
the cursor, names declared anywhere in this buffer, words used in it,
then the workspace index, templates, keywords and project words.
- **Keyword ghosts.** Two or more letters of a keyword show the rest as
grey inline text (Tab accepts); with the popup open the ghost follows its
selected entry. A word that is exactly a name the buffer declares gets
none. A `.v` file is offered Verilog-2005 keywords only. Setting
`lucisv.inlineKeywords` (default on). The `begin` ghost now also appears
for a `begin` typed inside a block that already balances.
- **Port suggestions.** After `.` in an instance, unconnected ports come
first and already-connected ones follow, marked `connected`; they used to
be left out. Accepting a port inserts `name()` with the cursor inside,
pre-filled with a same-named signal when one is visible; parameter lists
(`#(.`) behave the same.
- **An unfinished connection stays in its own entry.** In the editor's
tolerant parse, a lone `.`, a `.name(` still open at the end of its line
and a trailing `,` are each recovered inside their entry — always with a
diagnostic — so the rest of the list and the file still parse, colour and
lint. Strict parsing, and so the formatter and the CLI, are unchanged.
- **Errors on the connection being typed wait.** Diagnostics that start
inside the entry the last edit touched, in a named-connection list of an
instance, are withheld and published after 1.5 s without typing, on an
edit elsewhere, or on save. A client that pulls diagnostics and supports
it is sent `workspace/diagnostic/refresh`. Nothing outside that entry is
ever withheld.
- **Changed: a trailing `,` in a named connection list (`.a(x),)`) is now
reported in the editor.** The formatter and the CLI always refused it;
the editor's tolerant parse used to accept it silently. Format Selection
elsewhere in such a file now works instead of refusing the whole file.
## 0.63.1 — 2026-11-11
### Sticky scroll shows every layer
(TODO §67.)
- **VS Code: sticky scroll pins the first line of every block you are
inside.** Only the module header used to stay at the top of the editor,
because sticky scroll follows the document outline by default and the
outline stops at declarations. The extension now defaults
`editor.stickyScroll.defaultModel` to `foldingProviderModel` for Verilog
and SystemVerilog, so the pinned lines come from the server's folding
ranges — the module, the `always`, the `case`, the case item, the `if` —
and raises `editor.stickyScroll.maxLineCount` to 10 for those languages
(VS Code's 5 fits exactly that example and nothing deeper). Your own
settings still win.
- Known limit: a layer without `begin` (a one-statement `if`, a case item
with no `begin`) has no fold and so no pinned line; a `begin` on its own
line pins that line, not the `always` above it.
- No engine change: the server, formatter and linter are 0.63.0's.
## 0.63.0 — 2026-11-09
### Format Selection that fits where it stands; comment toggling in VS Code
(`docs/features/selection-formatting`; TODO §66.)
- **Format Selection lays out only the block you selected.** Selecting an
`always` block, a `case` statement or a few statements used to re-lay the
whole enclosing module-level item — at the formatter's own depth, so a
block in a 4-space or tab-indented file moved, and the blank lines at the
selection's edges were eaten. The new engine
(`vlog_formatter::format_selection`) finds the smallest run of sibling
items or statements the selected lines cover, lays out that run alone and
puts it back starting at the leading whitespace it already has (tabs
kept). The parent is not touched. `textDocument/rangeFormatting`,
`rangesFormatting` and the on-type `;` all run on it.
- **A parse error elsewhere in the file no longer refuses the request.** The
selection is formatted when the error lies outside it, and refused only
when it lies inside.
- **How a selection picks its block.** Touching a block's first line takes
the whole block; a selection that starts inside it takes only the
statements it covers, even when it reaches the closing `end`; the `end`
line alone takes the block it closes. A selection of whole module-level
items behaves as before.
- **Still verified.** Every result passes the whole-file equivalence check
and a convergence replay, or the buffer is left unchanged; the verifier
itself is unchanged. CRLF files keep every line ending.
- The on-type `;` now tidies its statement in a buffer whose error is
elsewhere, and no longer adds a final newline to a file without one.
- The reply is still one whole-document edit; the CLI's `--lines` is
unchanged (whole module-level items).
- **VS Code: `Ctrl+/` toggles comments.** The extension now declares the
language's `//` and `/* */` comments, bracket pairs and auto-closing
pairs for Verilog and SystemVerilog, so Toggle Line Comment and Toggle
Block Comment work on one line or a selection.
## 0.62.0 — 2026-10-19
### Paths rooted at a top-level module; a dependable release gate
(`docs/features/top-rooted-paths`, `docs/features/release-gates`,
`docs/features/references-fanout-pd-main`.)
- **A hierarchical path that starts at a top-level module now resolves.**
`tb.dut.u_core.sig` written in a file that does not declare `tb` used to
stop at `tb`; now every segment is a reference — `find_references` and LSP
references list it, and a rename of `dut`, `u_core`, `sig` or a generate
label on the way rewrites the path. `$root.tb…` works; a local `tb`
shadows. The LSP's rename also reads the files of the path's root and the
modules it passes through. **Rooted only when lucisv can prove the head is
a top-level module**: not when the name could come from a wildcard import
(including `import uvm_pkg::*` with `uvm_pkg` outside the project), not
inside a class, not beside a macro that stands where a declaration could,
and not when the name is also a package or several modules share it —
those paths are left unchanged and warned about exactly as before. The
index cache format moves to 22, so a 0.61.0 cache is rebuilt once.
- An unresolved path through the renamed name is warned about once (it was
sometimes named twice).
- **Find All References across blocks is relative to the index scope, by
design.** On a default `folder` scope a module's references and rename
reach only the folders the index covers; the `lucisv.index.scope` setting
now says that a rename of a module instantiated outside the scope leaves
those instantiations unchanged (use `workspace`, or open the file first).
- **`tools/gates.sh`** is the release gate: fmt, clippy, the test build,
each crate's suites, the doc-tests, the corpus gate and the extension
tests, each a separately guarded step with its own log and a summary; a
step the guard kills is retried once and reported as `KILLED → retried`.
- **`tools/guard.sh` fixes:** its memory limit now sees every process in the
tree (a pid-list bug hid everything three or more levels down, so builds
and test-spawned servers were never capped), and a closed stdin no longer
makes the command silently not run.
## 0.61.0 — 2026-10-14
### Call hierarchy from anywhere, functions and tasks as nodes; full-line references in VS Code
(`docs/features/call-hierarchy-everywhere`, `docs/features/vscode-references-view`.)
- **`textDocument/prepareCallHierarchy` answers from any position in a
body.** It answered only on a module name, so Show Call Hierarchy was empty
almost everywhere. Now: an instance name prepares the instantiated module;
a function or task's declaration, call or end label prepares a
`Function`/`Method` item; a position inside a function or task body
prepares that function or task; one inside a module, interface or program
prepares the enclosing module. Module items answer exactly as before.
- **Functions and tasks are call-hierarchy nodes.** `incomingCalls` lists
every call site, grouped by the enclosing function or task (else the
module, interface, program, package or class), over the same files
`references` reads; `outgoingCalls` lists the resolved callees, skipping
system tasks and unresolved names. A function's own name read inside its
body (`clog2 = clog2 + 1`) is its result variable, not recursion. Calls
through `this.`, `super.`, a typed handle and an `import` resolve; virtual
dispatch and calls inside macro bodies are not modelled.
- **`textDocument/prepareTypeHierarchy`** answers the enclosing class
anywhere inside a class body, and the base class on `super`.
- **VS Code: Find All References with whole lines.** VS Code's references
pane starts each preview a few characters before the match. The extension's
new **References** view (lucisv sidebar) lists every reference's full line
with the identifier highlighted, grouped by file, the declaration marked;
`Shift+Alt+F12` opens it in Verilog/SystemVerilog editors while
`lucisv.references.fullLineView` is on (the default). Closed files are read
without opening them on the server.
### Review fixes and housekeeping
- The closing-label fallback of an unnamed block no longer attaches a
mismatched `end : a` (or an `endfunction : g` beside block `g`) to a
same-named block.
- `duplicate-declaration` reports sibling `for` generate blocks of one label,
and a procedural block beside a generate block in either order.
- Rename warnings: a comment between `.` and the name is still a path; a file
that fails to lex is warned about instead of skipped.
- Refactoring messages name a file by its path wherever another file shares
its base name (the `.*` expansion, ANSI conversion, inline and extract too).
- `lucisv_server`'s workspace state is split into seven modules (a pure
move); `tools/release.sh` refuses to build when the extension's
`package.json` / `package-lock.json` versions disagree with the binaries.
## 0.60.0 — 2026-10-08
### Rename and references through a generate block label
TODO §65.1, topo §2.9 row 43 (MCP-14). (`docs/features/generate-label-rename`.)
- **`rename` of a block label rewrites every path through it.** Renaming
`g_lane` in `for (…) begin : g_lane` used to rewrite the label alone,
leaving `g_lane[0].lane_q` (and `u_x.g_lane[1].sig` in another file)
naming a block that no longer existed, with no warning. The label, its
closing `end : g_lane`, and every path segment naming the block — bare,
indexed (`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), behind an instance
path from another file — are now one reference set, renamed all or
nothing; a spelling inside macro text or a string is a warning. A name
declared *inside* a block is likewise renamed through such a path. Named
procedural blocks: `begin : lbl`, `end : lbl` and `disable lbl;` (and the
`lbl: begin … end : lbl` form) are one set.
- **`find_references`** (LSP `textDocument/references`, `lucisv-mcp find
refs`) lists the declaration, the closing label and every segment, same
file and cross-file, with the declaring file open or closed.
- **`lucisv-mcp rename`** no longer refuses a `block`-kind declaration.
- Resolution changes every consumer sees: a `for` generate block's label is a
name of the enclosing module (its genvar is not); `generate … endgenerate`
is not a scope; `blk.x` and `arr[0].field` (a packed struct array) resolve
their tails; an unnamed `genblk1` still names nothing. The index cache
format moves to 21, so a 0.59.0 cache is rebuilt once.
- **A rename says so when a path it cannot resolve spells the name**: a
hierarchical path segment in any file of the rename's set that resolved to
no declaration (`tb.dut.gen_x[0].q`, rooted at a top module) is left
unchanged and warned about with its lines, for every kind of declaration;
and renaming a member one arm of a generate `if`/`case` declares warns
about the same-named member of the arm sharing its label.
- `duplicate-declaration` now also reports a block label beside a net,
variable, parameter or instance of the same name, and such a label is no
longer counted as a read of the net.
- Rename and port warnings name a file by its path whenever another file of
the set shares its base name (two `pwrmgr_if.sv` are two findable lines,
root-relative in `lucisv-mcp`), and a line a path warning names is not
repeated under `unresolved:`. Same-named members are warned about through
every enclosing same-label generate arm (`g.h.x`), and an escaped name's
unresolved paths are found too.
- **Rename warnings and mentions are about the renamed declaration.** For a
member of a module or interface (a net, variable, port, parameter, block,
…), a bare spelling of its name in a macro argument, a `` `define`` body, an
unstructured assertion, a comment or a string is reported only where it can
mean it: in the declaration's **home set** — the declaring file,
everything it `` `include``s, whatever includes it (transitively), and the
files the rename edits. In code, a spelling in the declaring file is
reported after a scope lookup finds the declaration there (an instantiating
module's own same-named signal is not); one in an included fragment always;
a `` `define`` body when the macro is invoked from the home set (through
other macros too — `ASSERT_DEFAULT_CLK`'s `clk_i`); a macro argument inside
a `bind` into the declaring module; and a bare use in the plain code of an
included fragment (`prim_util_memload.svh`'s `mem`) is named as a use the
rename could not edit. Reported wherever they are written: a dotted
spelling (`.state_q`, a possible hierarchical path); a bare macro argument
the macro carries to the declaration — after a `.` (`` `CONN(state_q)``
building `.state_q(state_q)`, `` `FORCE(state_q)`` building
`force u_m.state_q`), into a `bind` into the declaring module, or into a
macro lucisv has no definition of; and the body of a macro that expands to
such a `bind`. Not reported: a body whose spellings are only its own
parameter named like the declaration (unless the body also spells the name
after a `.`, or a default argument spells it), and a backtick inside a
string. Any doubt means no scoping: a module, interface, package or
package member, a declaration outside a module, or one whose home set holds
an include lucisv cannot resolve (a macro-built name, a file outside the
project such as `uvm_macros.svh`) is reported everywhere as before. On
opentitan the `state_q` rename's answer went from 274 lines (61 kB, 230
macro warnings, 229 about other modules) to about 72 lines (12 kB),
`hmac_core.StIdle`'s from 48 lines to 3.
- `duplicate-declaration` also reports a block label beside a port, genvar,
typedef, function or task, and two named procedural blocks of one label in
one scope.
- `lucisv-mcp rename` with many warnings is fast again: rooting the warning
paths was quadratic per warning (a `state_q` rename on opentitan: 125 s →
3.3 s). Naming the files in warnings no longer scans the whole set once per
file either: the engine's part of that rename went from 2.9 s to 2.2 s.
- A use in a file that includes the declaring file (or that it includes) is
no longer reported as "left unchanged" when the rename did rewrite it —
renaming a module whose instantiation sits in a file included beside it
said so wrongly.
## 0.59.0 — 2026-09-29
### MCP read-only mode
PLAN §11, the owner's request of 2026-09-29: one binary, two modes.
(`docs/features/mcp-read-only`.)
- **`lucisv-mcp --read-only`** offers exactly the five read tools —
`hierarchy`, `find`, `outline`, `read`, `check`, in that order, with the
same descriptions and schemas as full mode. The model-visible catalogue is
1 797 bytes (budget ≤ 1 800) and the instructions 297 bytes (≤ 300), both
pinned by `tests/read_only.rs`.
- The mode filters the tool registry: `tools/call` of `rename`, `port`,
`edit_item` or `format` is the unknown-tool error (`-32602`,
`unknown tool: rename (the server runs --read-only)`); no edit handler is
reachable. Resources answer as in full mode.
- **No write inside a root**, whatever is called: a test snapshots every
path, size and mtime (directories too) of a fixture copy, calls every
full-catalogue tool name (the four edits with valid edit arguments, which
a control test shows do write in full mode) and every resource, and finds
the snapshot unchanged after the server exits. The server's own index
store under `--index-cache` is still written (outside the roots unless
`--index-cache` names a directory inside one).
- **Full mode is byte-identical to 0.58.0** on the wire (`initialize`,
`tools/list`); only the usage line gains `[--read-only]`.
- **Extension:** setting `lucisv.mcp.mode` (`"full"` default, `"read-only"`)
— the definition gains `--read-only` and the label becomes
`lucisv read-only (<folder>)`; a change of the setting re-announces the
servers. **lucisv: Copy MCP server config** follows it (server key
`lucisv-ro`, args ending `--read-only`, the message names the mode).
- `editors/vscode/mcp_smoke.js <binary> --read-only` smokes the mode (five
tools, one `hierarchy`, `rename` refused, files untouched);
`tools/release.sh` runs both smokes on the host binary and on the one
embedded in the package.
- `hierarchy` caps at 300 instances, 100 with `peek`; `peek` lines no
longer count toward the cap (census round 5: `prim_fifo_sync` up with
peek showed 20 of 77 instantiations). Without `peek` the answer is
unchanged.
## 0.58.0 — 2026-09-24
### The lean MCP catalogue: nine tools, short answers, trusted writes
+28 -3
View File
@@ -84,11 +84,19 @@ now): largest files `tools/read.rs` 405, `tools/item.rs` 379, `tools/item/verify
`vlog_refactor/src/rename/connections.rs` at 477 and `check/mod.rs` at 426,
and `lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55).
Re-measured 2026-10-14 after TODO §55 (pure move, `docs/features/decomposition-state`):
`state/mod.rs` 63, the largest `state/` file `discover.rs` 412 (`rescan.rs` 411);
files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
`vlog_parser/src/lexer.rs` 771, `vlog_formatter/src/format/stmt.rs` 604.
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
without a comment explaining why), `cargo test` green — all three
before declaring any work finished.
before declaring any work finished. **Before a release, and whenever
the whole workspace is gated, run `tools/gates.sh`** (every gate as a
separate guarded step with kept logs; `--only`/`--skip` for a subset)
instead of a bare `cargo test --workspace`.
- No `unwrap()`/`expect()`/`panic!` in library code paths; return
`Result`. Tests and `main.rs` argument handling may use them.
- Public items get a one-line doc comment. Doc comments say what/why,
@@ -131,6 +139,19 @@ Rules:
## Workflow
- **Agent models**: the lead plans and reviews; coding goes to one dev
agent and verification to one QA agent, **both Claude Opus 5.5**
(`model: "opus"`). This holds for a single lane and for each of two
parallel lanes.
- **Refactor lanes** (pure moves, decompositions): the dev is **Claude
Fable 5.2 at high reasoning effort** — the `refactor-dev` agent in
`.claude/agents/`. Its brief says: no new tests beyond what the move
forces, the gates are the proof, spend the effort on module
boundaries, naming and readability. QA is unchanged (Opus 5.5).
- **Escalation**: a first QA failure gets a normal Opus 5.5 fix round.
When a fix round fails QA a **second** time on the same feature, redo
the round with **Claude Fable 5.2 as both dev and QA**
(`model: "fable"`).
- Do **not** run `git commit` or `git push` — the lead reviews and
commits all work.
- Do not touch files outside your feature's stated scope. If you need a
@@ -155,6 +176,9 @@ process tree when its resident set or wall clock exceeds the limits
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
- The release gate is `tools/gates.sh`, which guards each step with its
own limits and retries a killed step once (shown as `KILLED → retried`);
do not wrap it in another `guard.sh`.
## Parallel lanes (the 2-agent loop)
@@ -176,8 +200,9 @@ proven independent and run serially. Rules for a parallel wave:
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
- **Roles per lane are unchanged**: one dev, then one QA — **both
Claude Opus 5.5** (owner, 2026-11-09; QA was Sonnet before) — 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.
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.58.0"
version = "0.65.6"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.58.0"
version = "0.65.6"
[[package]]
name = "lucisv_mcp"
version = "0.58.0"
version = "0.65.6"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.58.0"
version = "0.65.6"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.58.0"
version = "0.65.6"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.58.0"
version = "0.65.6"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.58.0"
version = "0.65.6"
[[package]]
name = "vlog_refactor"
version = "0.58.0"
version = "0.65.6"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.58.0"
version = "0.65.6"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.58.0"
version = "0.65.6"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+65 -7
View File
@@ -144,6 +144,9 @@ indent = 2 # 1..8, same as --indent
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
[format]
style = "google" # a named layout, same as --style (see Named styles)
[lint]
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
ignore = ["module-filename"] # removed after selection
@@ -173,11 +176,20 @@ error (exit 2) and nothing is processed. Details:
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
with a file that sets only `line-length` uses both). `exclude` is the
exception: config patterns are *added* to `--exclude`, not replaced by it.
`[format] style` (flag `--style`, editor `lucisv.format.style`) picks one of
the [named styles](#named-styles). The style is resolved first and supplies
the starting indent and line length; an explicit `indent` or `line-length` —
from a flag or from the file — then wins over the preset's, so
`style = "microsoft"` with `indent = 2` is Microsoft's layout at 2 spaces. An
unknown style name is the same hard error as an unknown key, and lists the
valid names. In the editor, `lucisv.toml` outranks the editor settings as for
every formatting key, and a chosen style (other than `lucisv` or `auto`) also
outranks the editor's tab size.
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
off by default, indents the `` `uvm_field_* `` macros written between
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
formatting choice lucisv leaves to the project, because it changes bytes
in existing UVM code (21 of the 860 corpus files).
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; like `style`,
it is a formatting choice lucisv leaves to the project, because it changes
bytes in existing UVM code (21 of the 860 corpus files).
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
@@ -512,7 +524,8 @@ Key ideas carried over from ruff/prettier:
Defaults follow Verible: **2-space indent**, **100-column lines** (both
configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
[Configuration](#configuration)).
[Configuration](#configuration)). The list below is the default `lucisv`
style; the [named styles](#named-styles) change some of it.
- One port / parameter / connection per line once a header doesn't fit
- Cuddled `begin`/`end` (`end else begin`)
@@ -521,6 +534,49 @@ configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
through verbatim
### Named styles
`[format] style`, `--style` and the editor's `lucisv.format.style` drop-down
pick one of a handful of house layouts. Every style moves whitespace only —
which line a token starts on and how many spaces precede it — so the same
token-equivalence check guards all of them, and each one is a fixed point of
itself (proved over the 860-file corpus and OpenTitan's 4 061 `hw/` files for
every preset; `docs/features/format-styles/README.md`).
| style | indent | width | `begin` | `else` after `end` | after `end : label` | header & connection lists | list indent | columns |
|---|---|---|---|---|---|---|---|---|
| `lucisv` (default) | 2 | 100 | same line | `end else` | `end : l else` | on one line if it fits | 1 level | kept where you wrote them |
| `google` | 2 | 100 | same line | `end else` | own line | one entry per line | 2 levels | kept where you wrote them |
| `lowrisc` | 2 | 100 | same line | `end else` | own line | one entry per line | 1 level | always aligned |
| `ansi` | 4 | 80 | own line | own line | own line | on one line if it fits | 1 level | kept where you wrote them |
| `microsoft` | 4 | 120 | own line | own line | own line | one entry per line | 1 level | kept where you wrote them |
| `nxp` | 2 | 80 | same line | own line | own line | one entry per line | 1 level | always aligned |
| `auto` | — | — | the preset the file is already closest to | | | | | |
`google` follows the [Google Verilog Style Guide](https://google.github.io/styleguide/verilogguide.html)
and `lowrisc` the [lowRISC Verilog Coding Style Guide](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md)
(OpenTitan's). **`ansi`, `microsoft` and `nxp` are lucisv's educated guesses**
at what those names suggest — C formatters' ANSI/Allman layout, clang-format's
`Microsoft` base style carried over to `begin`/`end`, a conservative RTL house
style — not rules those organisations publish; none of them publishes a Verilog
style that we could find. A `case` item's and a `do`'s `begin` stays on its
own line's end in every style. "Header & connection lists" are module
headers' parameter and port lists and instances' *named* overrides and
connections — not `#(16)`, ordered connections or function ports. `lowrisc`
differs from its guide in two places: the widest aligned connection keeps one
space before its `(`, and a comment line ends an aligned table.
`auto` formats the file once per preset, at the configured indent and width,
and keeps the output that changes the fewest lines (indentation included, so
a one-line edit does not flip a whole file to another preset); it never
guesses an indent or a width, and it is idempotent by construction.
**`auto` picks a layout for the configured indent and width; it never infers them — set `indent` to match the file first.** Because every re-indented line counts as changed, a file written at another indent is closest to whichever preset changes the fewest of its lines once they are all re-indented: a 4-space Allman file (formatted with `--style ansi`) run through `--style auto` at the default indent 2 comes out in the cuddled `lucisv` layout, while with `indent = 4` it stays Allman (and with `line-length = 80` as well, byte for byte). Under
`auto`, range and selection formatting use the style of the whole file, not
of the selected lines; the language server remembers each document's preset
from its last whole-file format, so a keystroke or a selection does not
search again, and a buffer with a parse error keeps its preset. One that has
never resolved — no memory, and it does not parse — gets the default layout.
### Alignment is inferred, not imposed
Hand-aligned columns are how RTL is read, so lucisv reads the spacing you
@@ -1037,11 +1093,13 @@ expected; no PRs or review required.
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
tools/gates.sh # every gate: fmt, clippy, build, each crate's suites, doc tests, corpus, node
tools/gates.sh --only suites # just the per-crate test suites
```
`tools/gates.sh` runs each gate as its own guarded step with a kept log and
prints a summary (`docs/features/release-gates/README.md`).
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
expected outputs only for intentional formatting changes with
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
+34
View File
@@ -448,6 +448,40 @@ Feature README `docs/features/mcp-lean-catalogue`. One dev (Opus), one QA
(a −1 %, d parity, b +10 %, c +9 % vs the base re-run; 6/6 correct);
gates: 4 922 tests / 0 failed, corpus 814/820
## M8. Read-only mode (0.59; PLAN §11 — owner's request 2026-09-29)
`lucisv-mcp --read-only`: five tools, ≤ 1 800 model-visible bytes,
instructions ≤ 300, never writes inside a root; full mode unchanged.
Feature README `docs/features/mcp-read-only`. One dev (Opus), one QA
(Opus), on trunk.
- [x] server: `--read-only` parsed, in the usage line; the registry
filtered by mode (`tools/list`, `tools/call`); read-only
instructions; the unknown-tool message for the four edit tools
- [x] tests (`tests/wire.rs` or a new `tests/read_only.rs`): names and
order, both budgets, full mode unchanged byte for byte, every
full-catalogue tool name called in read-only mode leaves the tree
untouched (sizes, mtimes, names)
- [x] extension: `lucisv.mcp.mode` setting, label, args, change event,
copy-config (`lucisv-ro` key, `--read-only`), node tests;
`mcp_smoke.js --read-only`; `tools/release.sh` runs both smokes
- [x] docs: feature README; Agents guide (a "Read-only mode" section, the
table's `writes` column already tells the five); extension
README/CHANGELOG; `CHANGELOG.md` 0.59.0 (unreleased);
`docs/topo.md` §2.8; `tools/RELEASING.md`; manual-acceptance rows
- [x] QA: attack the no-write promise (every edit tool name, resources,
malformed calls, a call racing a mode it does not have), the budgets,
full-mode identity against the 0.58.0 binary, the extension tests
- [x] census round 5 (lead): tasks a and d on `--read-only` — done
2026-09-29 (74c5631): 7 runs, all correct; with same-day base controls
a +8 %, d −8 % (parity); found and fixed the `peek` cap defect
(`hierarchy` caps at 300 instances, 100 with `peek`)
- [x] release 0.59.0 — tagged 2026-09-29; gates: clippy -D warnings, fmt,
72 suites + 6 doc suites (4 937 passed, 0 failed), corpus 814/820,
node tests 6/6. The first suite run stalled 25 min in the vlog_linter
doc-test and was cut by the guard; the doc-tests passed in under a
minute as their own gate
## Open questions for the owner (answer before the lane that needs it)
1. **Engine bump** (M5): if `vsce` accepts the contribution point on
+489 -2
View File
@@ -5084,11 +5084,14 @@ scope/widen logic, the document store, and the source selectors
(`module_sources`, `rename_sources`) are three sentences. Not planned; the
owner decides where it goes in loop 2.
- [ ] `state.rs` decomposition (pure move, byte-identical output, test
- [x] `state.rs` decomposition (pure move, byte-identical output, test
count unchanged); CLAUDE.md's measurement line refreshed —
**deferred to loop 3 by the lead, 2026-09-07** (958 lines at 0.49.0;
the measurement line already says so); a Fable refactor lane when
the owner schedules it
the owner schedules it — **done 2026-10-14**
(`docs/features/decomposition-state/README.md`: `state/` is ten
modules, largest 412 production lines; the CLAUDE.md measurement
line is the lead's, requested in that README's Handshakes)
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
@@ -6939,3 +6942,487 @@ Nothing else.
(23e2e4b, v0.55.0), CI green on the release commit, 8 assets, the
darwin-arm64 vsix at 0.55.0 with both binaries,
`hierarchySections.js`, `extract.js`, no `*_test.js`.
## 65. Stabilization round 1 (planned 2026-09-30, owner's order) — two correctness gaps, then the doc-test stall
Three lanes, one at a time on trunk, dev (Opus) → QA (Opus) → lead review →
commit. Rules as §63/§64: every suite and sweep through `tools/guard.sh`,
never piped (log to a file, check `guard exit` and the suite count); no
`sleep` over 60 s; never `grep` without a path; opentitan read-only (the
eval clone `~/.cache/lucisv-eval/ot` may be read and, for an edit test,
restored with `git -C … checkout -- <file>`). ~~Ships as 0.60.0.~~
**Release targets (corrected 2026-10-19):** 65.1 shipped in **0.60.0**
(2026-10-08); 65.2, 65.3 and 65.4 are open and target **0.62.0** (wave
below, §65.7); 65.6 is unscheduled.
### 65.1 Rename and references through a generate block label (topo §2.9-43, MCP-14)
`rename` of a generate block label (`for (…) begin : g_lane … end`) rewrites
the label and nothing else: a hierarchical path through it
(`g_lane[0].lane_q`, `u_x.g_lane[1].sig` from another file) keeps the old
name and no longer resolves, with no warning; `find_references` on the label
reports no use. The MCP layer refuses the rename (any `block`-kind
declaration); the LSP and the CLI still perform it. Feature README
`docs/features/generate-label-rename`.
The contract to reach, in `vlog_semantic` (resolution) and `vlog_refactor`
(`find_references`, `rename`, the verifier):
- [x] a path segment that names a generate block — bare (`g.x`), indexed
(`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), and behind an instance
path from another file (`u_x.g[0].x`) — resolves to the block's label
and is a reference to it
- [x] `find_references` on the label lists the declaration, the closing
`end : label` and every such segment, same-file and cross-file, through
the same fan-out §64.1 uses for hierarchical-surface declarations
- [x] `rename` rewrites all of them, all-or-nothing; a closing label is
rewritten with its opening one; a segment it cannot resolve (macro
text, a string) is a warning, as for any other declaration; an
unnamed block (`genblk1`) is not renameable
- [x] named procedural blocks (`begin : lbl` in `always`/`initial`/
functions/tasks): the label, its closing label and `disable lbl;` are
one reference set
- [x] the verifier accepts exactly these rewrites and nothing more:
masked-corruption attack tests for any normalization it gains
(CLAUDE.md invariant 4)
- [x] the LSP (`textDocument/references`, `rename`, `prepareRename`) and
the CLI get it through the engine; `lucisv-mcp`'s refusal of a
`block`-kind rename (`crates/lucisv_mcp/src/tools/edit.rs`) is lifted
and its tests (`tests/qa_m7.rs`) assert the rename instead
- [x] opentitan: a generate label with cross-file uses renamed on the eval
clone — every site rewritten, the files still parse, clone restored
- [x] rename warnings and mentions are scoped to the renamed declaration
(lead's inspection 2026-09-30: a module member's bare spelling
elsewhere is not news; a dotted one and a unit/package name's every
spelling still are)
- [x] QA: attack the index forms, nesting, shadowing (a net and a block of
the same name in different scopes), a label used only in a closing
label, `disable`, an escaped label, a label inside an `ifdef`
### 65.2 LSP `references` omits three `aes` instantiations (topo §2.9-36, MCP-6)
On opentitan, `textDocument/references` at the `aes` instantiation in
`hw/ip/aes/dv/tb/tb.sv` (and at its `.clk_i` connection) answers 11 and 9
locations; the whole-set engine answers 14 and 12 — the same plus the three
top-level instantiations in
`hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`
(`aes #(` and `.clk_i(clkmgr_clocks_i.clk_main_aes)`). Stable after a 30 s
settle, so not an indexing race. Feature README
`docs/features/references-fanout-pd-main`.
- [x] root cause named (the fan-out/scope selection in `lucisv_server` —
`module_select`, `state/` scope widening, or the index's
instantiation facts for those three files; they are large generated
files, check the 1 MiB cap and the word census)
- [x] ~~the LSP answer equals the whole-set engine's for the module name and
for a port of it, from the declaration and from a use; a regression
test with a fixture that reproduces the cause (not only opentitan)~~ — **closed by the owner's ruling 2026-10-19: scope-relative by design.** The LSP answer equals the engine over the same file set (pinned for both scopes in `server/tests/references_scope.rs`); the default `folder` scope does not reach the three tops, `workspace` does (14/12).
- [x] an opentitan test (ignored by default, like `tests/opentitan.rs`)
pinning the 14 and 12
- [x] ~~QA: the same comparison for five other modules instantiated from a
`*_pd_main.sv` top, and for `rename`'s fan-out (does rename see the
three sites?)~~ — not run: no production code changed under the ruling
### 65.3 The combined test command stalls entering the doc-tests
`cargo test --workspace` under `tools/guard.sh`: on 2026-09-29 (0.59.0 gate)
every suite finished in about two minutes and the run then sat 25 minutes
in `Doc-tests vlog_linter` until the guard cut it; on 2026-09-30 an
independent session's run hit its 600 s guard "entering the final doc-test
harness". `cargo test --workspace --doc` alone passes in under a minute.
- [x] reproduce (how often, which doc-test, what the stuck process tree
is — `rustdoc`, `rust_out`, stdin?) and name the cause; `guard.sh`
runs the command with `0<&3` — check what the doc-test harness
inherits as stdin when the gate runs in the background
- [x] fix at the cause (the harness, the doc-test, or the guard), and make
the release gate a script (`tools/gates.sh`) that runs fmt, clippy,
the test build, the suites, the doc-tests, the corpus gate and the
node tests as separate guarded steps with logs kept and a summary
that shows a kill — `tools/RELEASING.md` and CLAUDE.md point at it
- [x] ten consecutive green runs of the gate script recorded
### 65.4 Resolve a hierarchical path rooted at a top-level module name (lead to schedule; from §65.1 QA F1)
A path whose head is a top module declared in another file — `tb.dut.u_x.sig`,
the shape every opentitan DV `force`/`$deposit`/`uvm_hdl_*` path takes
(IEEE 1800 §23.6: a top-level module name is the root of a hierarchical
name) — resolves nothing today: `tb` is bound as a `Target::Lexical` use,
misses in the writing file, and `resolve::member_site`'s `head_site` stops
the spine, so no segment after it is a reference and a rename of `dut`'s
declarations leaves the path behind (since §65.1 with a warning, not
silently). The root lookup belongs in `vlog_semantic/src/resolve.rs`
`head_site`: when the lexical walk misses **and** the head is followed by a
`.`, answer `MemberSite::Unit { path: head, surface: Hierarchical }` so the
workspace's `fold_path` walks `tb` → `dut`'s type → … exactly as it walks an
instance path today — with the head itself recorded as a `Target::Module`-like
use so `tb` stops being `NotFound`. QA's repro: `vlog_refactor/tests/
qa_generate_label.rs` `a_path_rooted_at_another_files_top_module_is_never_silently_left_behind`
(`probe.sv`: `assign o = tb.dut.g_sw[0].buf_q;`), and on opentitan
`hw/ip/keymgr_dpe/dv/env/keymgr_dpe_if.sv:514,515,517` (`force
tb.dut.gen_sw_assigns[i]…`) under `rename gen_sw_assigns`. Watch: a name
that is both a local and a top module (the local wins), `$root.tb…`, and the
index cost of the extra external candidates on every DV path.
- [x] root lookup in `head_site`, the head recorded as a module use
- [x] QA's repro renames the path instead of warning; the §65.1 warning
still fires for a root the workspace does not declare
### 65.6 Rename inside included fragments (lead to schedule; from §65.1 QA final H4)
A module that `` `include``s a fragment of its own body (`prim_ram_1p.sv`
including `prim_util_memload.svh`, every opentitan `*_assert.svh`) has that
fragment's text pasted into its scope, but lucisv analyses the fragment as a
file of its own: a bare `mem` there resolves to nothing, so `rename
prim_ram_1p.mem` edits the module and — since §65.1 — only *warns*
(`prim_util_memload.svh:12,24,32,43: `mem` is used in a file `prim_ram_1p.sv`
includes and was left unchanged`). Renaming there means binding a fragment
in the scope of the file that includes it (the include site's scope chain as
the fragment's outer scope, as `fragment-mode` does for a bare body) and
verifying the edit against that binding; a fragment included from two
modules is two bindings and must agree or be refused. QA's repro:
`vlog_refactor/tests/qa_warning_scope.rs`
`a_bare_use_in_plain_included_code_is_renamed_or_said` (`m_body.svh`:
`assign o = state_q;` included by `m.sv`).
- [ ] a fragment included by exactly one unit is bound in that unit's scope
and renamed with it; one included by several is refused unless every
binding agrees
- [ ] QA's repro renames the fragment's use; the §65.1 warning remains for
what cannot be bound
### 65.7 Wave for 0.62.0 (planned 2026-10-19, owner's order: "fix those that are true")
Two parallel lanes first (disjoint files; neither touches `vlog_semantic`),
then 65.4 serially (it changes `vlog_semantic` resolution, which §65.2's
lane might also need — run after it merges).
**Lane A — §65.2 references fan-out** (Opus dev → QA → lead), files:
`crates/lucisv_server/src/state/sources.rs`, `crates/lucisv_server/src/nav.rs`,
new test files under `crates/lucisv_server/src/server/tests/`, a new
ignored-by-default `crates/lucisv_server/tests/opentitan_references.rs`,
`docs/features/references-fanout-pd-main/README.md`.
- [x] §65.2's checklist above (closed by ruling: scope-relative by design)
**Lane B — §65.3 gate script** (Opus dev → QA → lead), files:
`tools/gates.sh` (new), `tools/guard.sh` (only if the cause is there),
`tools/RELEASING.md`, `docs/features/release-gates/README.md` (new);
CLAUDE.md's pointer is the lead's at merge.
- [x] §65.3's checklist above
**Then — §65.4 top-module-rooted paths** (serial, after lane A merges).
- [x] §65.4's checklist above (conservative by the owner's ruling: a head with an import candidate, inside a class, or beside a macro that could declare it is not rooted)
### 65.8 Completion after a top-rooted path head (deferred from §65.4 H2, 2026-10-19)
`tb.` offers nothing in completion: the completion walk keeps "an unknown
head answers nothing" (two `lucisv_server` completion tests pin it), while
resolution now roots an unknown head at a top module. Decide whether
completion should offer `tb.`'s hierarchical members, answering `None` when
the index has no unit of that name. `docs/features/top-rooted-paths`.
- [ ] owner/lead decision; if yes, `completion/member.rs` + tests
## 66. Format Selection that fits where it stands (planned 2026-11-09, owner's order)
Owner's report: *Format Selection* "fails more than half of the time". The
usual selection is one whole `always` block or one whole `case` statement,
often nested inside blocks the selection does not cover. Reproduced on trunk
(`lucisv --lines`, the engine `textDocument/rangeFormatting` shares): selecting
a `case` re-lays the whole `always` around it; the block is re-indented to the
formatter's own depth × width, so in a file indented any other way it no
longer lines up with its neighbours; a selection inside `generate` re-lays the
whole region; and a file with a parse error anywhere is refused outright.
Owner's rule: do not worry about the parent — the selected block keeps the
indentation level it starts at, and stays functionally the same.
### 66.1 VS Code language configuration (lead, done 2026-11-09)
- [x] `editors/vscode/language-configuration.json` (comment tokens, brackets,
auto-closing and surrounding pairs) wired to both language ids in
`editors/vscode/package.json` — Toggle Line/Block Comment (Ctrl+/) works
without another Verilog extension installed.
### 66.2 Selection formatting (one lane: dev, then QA)
Feature README: `docs/features/selection-formatting/README.md`. Files:
`crates/vlog_formatter/src/selection.rs` (+ a `selection/` split if it nears
600 lines), `crates/vlog_formatter/src/{lib.rs,printer.rs,format/mod.rs}`,
`crates/vlog_formatter/tests/selection.rs`, `crates/lucisv_server/src/format.rs`,
`crates/lucisv_server/src/server/tests/formatting.rs`,
`crates/lucisv_server/tests/e2e.rs`. `verify.rs`, `range.rs`, `fence.rs`, the
parser and the CLI's `--lines` are not touched.
- [x] `format_selection`: the smallest run of sibling items/statements the
selected lines cover, laid out alone at the indentation it was written
at, spliced into otherwise untouched bytes.
- [x] Verified whole-file (`verify_equivalence`, unchanged) and converged by
replaying the located target, not the line numbers.
- [x] Fences outrank the selection; a module/package-level target defers to
`format_range` (header/footer splitting).
- [x] A file that does not parse: the target is located in the tolerant tree
and refused when a diagnostic falls inside it.
- [x] `textDocument/rangeFormatting` / `rangesFormatting` call it.
- [x] Tests: the owner's shapes (whole `always`, whole `case`, inside
`generate`, inside a function), off-grid and tab indentation, partial
selections, comments, fences, broken files, masked-corruption attacks on
the splice.
## 67. Sticky scroll shows every layer (planned 2026-11-11, owner's order)
VS Code pinned only the module header, because sticky scroll follows the
document-symbol outline by default and the outline stops at declarations.
The server's folding ranges already carry every `begin`/`end`, `case`,
`fork`, `generate` and function — one fold per layer, starting on its header
line.
- [x] `editors/vscode/package.json` `configurationDefaults` for both language
ids: `editor.stickyScroll.defaultModel` = `foldingProviderModel` and
`editor.stickyScroll.maxLineCount` = 10 (VS Code's default of 5 is the
owner's example exactly, with nothing to spare). A user's own setting
still wins.
- [x] `crates/lucisv_server/src/folding.rs`: a test pinning that each layer
of the owner's example (module, `always`, `case`, case item, `if`)
starts a fold on its header line.
- [ ] Seen in a running VS Code (owner).
- Known limit: a layer with no `begin` (a one-statement `if`, a case item
without `begin`) has no fold and so no pinned line; a `begin` written on
its own line pins that `begin` line, not the `always` above it.
## 68. Completion that keeps up with typing (planned 2026-11-17, owner's order)
Five asks from the owner, about the VS Code extension. Two serial lanes
(`lucisv_server` depends on `vlog_parser`, so they are not independent):
68.1 first, then 68.2. Each lane: one dev, then one QA, both Opus 5.5.
### 68.1 Lane A — auto-`end`, templates, ranking, keyword ghosts, port items
Feature README: `docs/features/completion-ux/README.md`. Files:
`crates/lucisv_server/src/{on_type.rs,inline.rs,templates.rs,pairs.rs,settings.rs,main.rs}`,
`crates/lucisv_server/src/completion/*`, new modules beside them where a
file is near 600 production lines, `crates/lucisv_server/tests/e2e.rs`,
`editors/vscode/{extension.js,package.json,smoke.js,README.md}` and a new
`editors/vscode/*_test.js` if the extension logic is factored out. No
parser, formatter, linter or semantic crate change.
- [x] **`begin` + Enter writes the `end`** (owner: "more like begin +
<return>, the cursor should be the next line of begin, at the correct
indentation, and ready for the first statement"). The newline on-type
answer, when the line above ends in `begin` (or `begin : label`) and
the file has an unclosed `begin`, also inserts `end` on the line after
the new one, at the indentation of the statement the `begin` belongs
to; the cursor stays on the new, indented line. No `end` when the
blocks already balance. Setting `lucisv.autoEnd` (default on). The
extension sends the request itself when `editor.formatOnType` is off
and puts the cursor back.
- [x] **`always_ff @(` / `always @(` expand with clock and reset**:
`posedge ${1:clk} or negedge ${2:rst_n}`, both tab stops, in the ghost
and as the first popup template; the clock-only form stays available
second.
- [x] **Names from the current file rank first** in the popup: declared
anywhere in this buffer, then words used in it, ahead of other files'
names and of keywords.
- [x] **Keyword ghosts**: a typed prefix of a keyword shows the rest of it
as grey inline text (Tab accepts), following the popup's selected item
when the popup is open. Setting `lucisv.inlineKeywords` (default on).
- [x] **Port items**: unconnected ports first; already-connected ports
listed after them, marked `connected` in the dimmed detail; accepting
a port writes `.name($1)` with the cursor inside the parentheses.
### 68.2 Lane B — no rushed errors on the connection being typed
Feature README: `docs/features/port-entry-grace/README.md`. Files:
`crates/vlog_parser/src/parser/instance.rs` (+ its tests),
`crates/lucisv_server/src/{diagnostics.rs,server/diagnostics.rs,state/*}`.
- [x] Parser recovery keeps an unfinished connection (`.`, `.name(` open to
the end of its line, a missing `,` before the next `.name`) inside its
own entry — still a diagnostic, never silent — so the rest of the file
parses, colours and lints as if the entry were complete.
- [x] The server withholds the diagnostics that fall inside the entry the
last edit touched, and releases them after a quiet period or when the
next edit lands elsewhere.
## 69. Module instantiation syntax highlighting (2026-11-17, owner's order)
Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
`crates/lucisv_server/src/{tokens.rs,tokens/instantiation.rs}`,
`editors/vscode/{package.json,.vscodeignore,semanticTokens_test.js}`,
`docs/features/{lucisv-server,large-file-mode}/README.md`.
- [x] Distinct semantic highlights across module instantiations (14-type wire
legend unchanged): module name (`class`), `#` + `.PARAM` overrides +
parameter values (`parameter`, distinct from `()`), instance name
(`function`), `.port`/`.*` (`property`), and port connections
(`variable`), including unfinished entries while typing.
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
non-white TextMate scopes across themes.
## 70. The tests pass on Linux, and one cleaning round (2026-11-19, owner's order)
Every suite had only ever run on macOS arm64; the Linux and Windows binaries
ship unexecuted. A `linux-x64` Actions runner now exists (`luhpe-linux-x64`,
a resource-capped Docker-in-Docker container on the Gitea host), and the
first trial of the suite in its job image found: clippy red on three unused
imports in `lucisv_server` test modules (their only users are tests compiled
on macOS/Windows alone), and 11 distinct failing tests out of ~5 300 — eight
that set up an unreadable/unwritable path and so cannot fail as root (the
job image's user), one that assumes a case-insensitive filesystem, two
`…_in_linear_time` timing assertions. No product failure among them as far
as the trial shows. One lane, `docs/features/linux-test-portability`;
`tools/linux_check.sh` runs the working tree in that image without a push.
- [x] `cargo clippy --all-targets -- -D warnings` clean on Linux and on
macOS (`crates/lucisv_server/src/hover.rs`, `includes.rs` test modules,
and whatever else the Linux build names).
- [x] The permission-denied tests (`crates/lucisv/tests/cli.rs`,
`crates/lucisv_core/src/walk.rs`, `crates/lucisv_mcp/src/apply.rs` and
`tests/cache.rs`, `tests/qa_m6.rs`, `crates/lucisv_server/src/state/tests/filelist.rs`)
pass both as root and as an unprivileged user: where the platform does
not enforce the permission the test says so and stops, it does not
assert the opposite.
- [x] `crates/lucisv_server/src/file_ops.rs`
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites`
holds on a case-sensitive filesystem or is scoped to the insensitive
ones, with the reason written at the test.
- [x] `crates/lucisv_server/src/large.rs` — the two `…_in_linear_time`
tests pass on the runner **and still fail when the conversion is
quadratic** (shown, not asserted).
- [x] The cleaning round: test code only, driven by what the tools report on
either platform — unused imports and dead helpers, platform assumptions
left implicit, assertions on wall-clock or environment that the runner
shows to be fragile. No test is deleted and the test count does not
drop; no production code and nothing in `verify.rs` changes.
- [ ] `cargo test --workspace` green on Linux as root and with `--user`,
and `tools/gates.sh` green on macOS.
- [ ] (lead) `.gitea/workflows/ci.yml` gains a `linux` job on `linux-x64`;
`docs/topo.md` and `tools/RELEASING.md` updated.
## 71. The overnight queue (2026-11-19, owner's order) — eight features, one release each
Ordered by the owner on 2026-11-19, to be done unattended after §70 lands:
each item goes through the dev → QA → lead-review loop, is committed, and
ships as its own release — `0.65.2`, `0.65.3`, … `0.65.n` in the order they
finish — and once all are done, `0.66.0`. The lead has the owner's standing
go-ahead to commit, tag and push for this queue. Every feature is tried on
the OpenTitan tree (not only on unit fixtures) before it is called done.
The items are the owner's words, lightly condensed; each gets its own
subsection, plan and `docs/features/<name>/README.md` when its turn comes.
- [x] **71.1 An edit does not re-index the whole database.** (0.65.6, `docs/features/localized-reindex`)
Today every
file edit re-indexes everything. A change to a `define` may have to;
a typical, localized edit must not.
- [ ] **71.2 Actions stay fast on a huge, heavily-dependent tree.** Do the
work dynamically: answer first from what is already in the same file
(hover to a definition in this file), and use the relationship map to
load completion candidates on demand.
- [ ] **71.3 Highlighting does not wait for the index.** Always run a
localized, viewport-only highlight; it may be imperfect and be
corrected later, but basic colours must not wait for the whole
database.
- [x] **71.4 `` `ifdef `` / `` `else `` blocks fold** (0.65.4, `docs/features/ifdef-folding`), and take part in the
sticky-scroll ("floating") bars.
- [x] **71.5 The formatter adapts to the file's own style** (0.65.5, `docs/features/format-styles`: six named styles and `auto`)
— where lines
break, what is grouped, how ports align. If inferring that is too
ambiguous, a setting with a drop-down of named styles instead (ANSI,
Google, Microsoft, NXP — educated guesses), with the rules easy to
read in the source.
- [x] **71.6 The module view shows where you are.** (0.65.2, `docs/features/hierarchy-current-path`; not yet seen in a running editor.)
Highlight the open
file's instance and its parents in different shades — bright light
orange for the instance, dimmer the further up — or anything in that
spirit that makes the hierarchy easy to read.
- [ ] **71.7 Find References sometimes answers "not found"** on a
port/signal, then works after clicking elsewhere and back. VS Code or
the server? Investigate, then fix what is ours.
- [x] **71.8 Comments: no code colours inside them** (0.65.3, `docs/features/comment-highlighting`; the bracket colour is VS Code's, explained not changed)
(the `[]` of
`signal[]` gets highlighted today), **but do highlight `TODO`,
`FIXME`, `FIX_ME`, `TBD`**, plus a user setting for custom words that
are highlighted only in comments.
- [ ] **71.9 Release `0.66.0`** once 71.1–71.8 have each shipped.
### 71 — wave 1 (lead, 2026-11-19): 71.6 runs beside §70
The owner asked not to wait for §70's Linux runs. §70 is test code in the
Rust crates and touches no contract; 71.6 is the extension's hierarchy view
(`editors/vscode/hierarchy*.js`, `package.json`, the extension README and
changelog). Disjoint file sets, and the one edge between the two areas
(`editors/vscode ◀──▶ lucisv_server`, the spawn contract) is touched by
neither — so they run as two lanes: §70 on trunk's tree (already in flight
there), 71.6 in the worktree `../lucisv-wt/71.6` on `lane/71.6-module-view`,
branched from `88546c8`. 71.1–71.3 all live in `lucisv_server`'s state and
indexing, collide with each other and with §70's test files, and wait for
§70 to merge.
- Lane 71.6 owns: `editors/vscode/hierarchyView.js`, `hierarchyModel.js`,
`hierarchySections.js` and their `_test.js` files, new
`editors/vscode/*.js` modules it adds, `editors/vscode/package.json`
(`contributes` only — not `version`), `editors/vscode/.vscodeignore`,
`tools/release.sh`'s runtime-module checks if a new module needs listing,
`docs/features/hierarchy-current-path/README.md`.
- Wave 2 (lead, 2026-11-19): 71.6 shipped as 0.65.2 (`e9f5090`). §70 is still
in flight on trunk's tree, so the next lane is again one that stays out of
the Rust test files: **71.8** (comments), in `../lucisv-wt/71.8` on
`lane/71.8-comments` from `e9f5090`. It owns
`editors/vscode/syntaxes/*`, `language-configuration.json`, new
`editors/vscode/*.js` modules and tests, `extension.js` wiring,
`package.json` `contributes`, `.vscodeignore`, the extension README, and —
only if the stray colour turns out to come from the server's semantic
tokens — `crates/lucisv_server/src/tokens.rs` and `tokens/`, which §70
does not touch. `docs/features/comment-highlighting/README.md`.
- Wave 3 (lead, 2026-11-19): 71.8 shipped as 0.65.3 (`948f8a0`) and 71.4 as
0.65.4 (`d574969`), each from its own worktree; both tagged locally and
**not pushed** — the owner's ssh key left the agent at about 05:00 (its
`AddKeysToAgent 1h`), which also stops `tools/linux_check.sh`. §70 is
committed on macOS evidence with its Linux line left open. 71.5 (formatter
styles) runs in `../lucisv-wt/71.5` from `d574969`. Owed once ssh is back,
in this order: push master and the tags one at a time; re-run §70 on Linux
(root twice, `--user`); add the `linux` job to `ci.yml`.
- Wave 4 (lead, 2026-11-19): 71.5 shipped as 0.65.5 from `../lucisv-wt/71.5`,
rebased onto §70's commit. 71.1 (localized re-index) is with QA in
`../lucisv-wt/71.1`. Found on the way by 71.5's QA, all present in 0.65.4
and filed here, not fixed:
- [ ] A comment between a generate `end` and `else` (also a trailing `// c`
after a labelled generate `end` before `else`) is a verification
error: the file is left unformatted. The safety net works; the
formatter should not need it.
- [ ] `` `ifdef `` between `end` and `else` is a parse error.
- [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
- [x] The server's `line-length` lint falls back to 100 columns under the
`ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken
when 71.1 merges.
- [ ] One-per-line styles give multi-instance declarations
(`p1 u8 (...), u9 (...)`) the hanging layout.
- Wave 5 (lead, 2026-11-19): 71.1 shipped as 0.65.6 after a QA FAIL (four
stale answers), a fix round, a QA pass and a last small round. What the
QA rounds and a read-only investigation turned up, all present before this
wave, becomes lane **71.7** (the owner's Find References item, widened):
- [ ] A caret just past an identifier's last letter asks about the next
character: references, definition, hover and highlight come back
empty (`server/dispatch.rs` `Server::offset`). This is the owner's
"not found, then works after clicking back".
- [ ] A `didChange` arriving during a whole rescan can overtake an older
one still queued (`server/mod.rs` `process_batch`): with incremental
sync the server's buffer is corrupted until the file is reopened.
- [ ] A burst `[request, didOpen]` during the startup scan is re-held at
every file (`server/index.rs` `answer_what_is_waiting`): the scan
takes ~300 s on OpenTitan instead of ~1.7 s.
- [ ] A watcher event naming only a directory leaves stale state; an
excluded buffer stays indexed after close; symlinked files are held
under one or both spellings depending on what was open.
71.3 (viewport highlighting) passed QA with a gap in the default folder
scope (colours wait out a widen, ~630 ms); it is rebased after 71.7 and
closes that in its fix round. Then 71.2.
+74 -7
View File
@@ -1,7 +1,7 @@
//! Hand-rolled command line parsing for the `lucisv` binary.
use lucisv_core::cache;
use lucisv_core::config::FileConfig;
use lucisv_core::config::{self, FileConfig};
use vlog_formatter::{Config, LineRanges};
/// Which tool this invocation runs.
@@ -58,6 +58,8 @@ pub struct Options {
pub line_length: Option<usize>,
/// `--indent`, if given; otherwise the config file decides.
pub indent: Option<usize>,
/// `--style`, if given; otherwise the config file decides.
pub style: Option<&'static str>,
/// `--lines`: format only the constructs meeting these lines. `None` is a
/// whole-file run.
pub lines: Option<LineRanges>,
@@ -98,8 +100,13 @@ impl Options {
}
/// Formatter settings for one file: CLI flag > config file > default.
///
/// The style is resolved first and supplies the starting indent and line
/// length; an explicit `indent`/`line-length`, from the flag or the file,
/// is then written over the preset's, whichever rung named the style.
pub fn config_with(&self, file: &FileConfig) -> Config {
let mut config = Config::default();
let name = self.style.or(file.format_style);
let mut config = name.and_then(Config::named).unwrap_or_default();
if let Some(n) = self.line_length.or(file.line_length) {
config.max_width = n;
}
@@ -196,6 +203,12 @@ OPTIONS:
filelist, and neither reads nor writes the cache
--line-length <N> maximum line length (default 100)
--indent <N> indent width in spaces (default 2)
--style <NAME> layout preset: lucisv (the default), google,
lowrisc, ansi, microsoft or nxp. It sets the indent
and line length too; --indent/--line-length (or the
config file's keys) still win over the preset's.
`auto` lays each file out in the preset it is
already closest to, at the default indent/width
--no-config ignore lucisv.toml / .lucisv.toml files
-h, --help show this help
-V, --version show version
@@ -275,7 +288,7 @@ FILELISTS:
CACHE:
A file whose exact content lucisv has already verified is formatted — under
the same line-length, indent and lucisv version — is skipped on the next run
the same line-length, indent, style and lucisv version — is skipped on the next run
and reported as `N files from cache`. Only that \"already formatted\"
verdict is ever cached: a file that would be reformatted, or that failed,
is re-checked every run. The cache is one text file under `.lucisv_cache/`;
@@ -288,10 +301,12 @@ CONFIGURATION:
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
read by lucisv-server only — the CLI reads a filelist only when `-f` names
one, so `lucisv rtl/` always means the directory it was given). One table
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
paths, resolved against the config file's own directory). A command line
one, so `lucisv rtl/` always means the directory it was given). The
`[format]` table takes `style` (a preset name, as `--style`) and
`uvm-utils-indent` (true/false). The `[lint]` table takes `select` and
`ignore` (arrays of rule names, `--select`/`--ignore` semantics) and
`waivers` (an array of waiver file paths, resolved against the config
file's own directory). A command line
flag overrides the file's corresponding key; the other keys still apply —
`--waiver-file` is the exception, and adds to `waivers` rather than
replacing it.
@@ -335,6 +350,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
exclude: Vec::new(),
line_length: None,
indent: None,
style: None,
lines: None,
output_format: OutputFormat::Text,
fix: false,
@@ -400,6 +416,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--indent requires a value")?;
opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?);
}
"--style" => {
let v = args.next().ok_or("--style requires a value")?;
opts.style = Some(config::parse_style(&v)?);
}
"--lines" => {
let v = args.next().ok_or("--lines requires a value")?;
line_specs.push(v);
@@ -526,6 +546,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::*;
use vlog_formatter::style;
fn parse(args: &[&str]) -> Result<Options, String> {
parse_from(args.iter().map(|s| s.to_string()))
@@ -568,6 +589,52 @@ mod tests {
assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width);
}
#[test]
fn a_style_sets_the_starting_values_and_explicit_ones_win() {
let none = FileConfig::default();
let opts = parse(&["--style", "microsoft", "rtl"]).unwrap();
let config = opts.config_with(&none);
assert_eq!(config.style, style::MICROSOFT);
assert_eq!((config.indent_width, config.max_width), (4, 120));
// The file's explicit keys beat the flag's preset...
let file = FileConfig { indent: Some(3), ..Default::default() };
assert_eq!(opts.config_with(&file).indent_width, 3);
assert_eq!(opts.config_with(&file).max_width, 120);
// ...and the flag beats the file's style.
let google = FileConfig { format_style: Some("google"), ..Default::default() };
assert_eq!(opts.config_with(&google).style, style::MICROSOFT);
let opts = parse(&["--indent", "2", "rtl"]).unwrap();
let config = opts.config_with(&google);
assert_eq!((config.style, config.indent_width), (style::GOOGLE, 2));
// No style anywhere is exactly the old default.
let config = parse(&["rtl"]).unwrap().config_with(&none);
assert_eq!(config.style, style::LUCISV);
}
#[test]
fn an_unknown_style_names_the_styles() {
let Err(message) = parse(&["--style", "allman", "rtl"]) else { panic!("accepted") };
assert!(message.contains("unknown style `allman`"), "{message}");
assert!(
message.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
"{message}"
);
assert!(parse(&["--style"]).is_err());
}
/// `lucisv_core` keeps its own copy of the names so it can reject a bad
/// `[format] style` without depending on the formatter; this is the test
/// that keeps the copy honest.
#[test]
fn the_core_style_names_are_the_formatter_presets() {
let mut names: Vec<&str> = style::names().collect();
names.push("auto");
assert_eq!(names, config::STYLE_NAMES);
for name in config::STYLE_NAMES {
assert_eq!(Config::named(name).map(|c| c.style_name()), Some(name));
}
}
#[test]
fn config_excludes_are_appended_to_cli_excludes() {
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
+1
View File
@@ -338,6 +338,7 @@ fn entry_for(content: u64, config: &Config) -> Entry {
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
style: config.style_name(),
}
}
+28 -2
View File
@@ -1268,7 +1268,8 @@ impl TempDir {
}
/// One hand-written cache line, for the tests that forge entries. The
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`,
/// and the style is always the default, `lucisv`.
fn cache_line(
path: &str,
content: &str,
@@ -1278,7 +1279,7 @@ fn cache_line(
version: &str,
) -> String {
let hash = lucisv_core::cache::content_hash(content.as_bytes());
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\tlucisv\t{version}\t{path}\n")
}
#[test]
@@ -2241,11 +2242,33 @@ fn unlock(dir: &TempDir) {
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
}
/// Whether file modes bind this process: a mode-000 directory refuses to be
/// listed. Root lists it anyway (Linux CI jobs run as root), and there a
/// directory the walk cannot read cannot be built, so the tests below say so
/// and stop instead of asserting a warning that cannot happen.
#[cfg(unix)]
fn listing_is_refused() -> bool {
use std::os::unix::fs::PermissionsExt;
let probe = TempDir::new("mode-probe");
let shut = probe.path.join("shut");
std::fs::create_dir(&shut).expect("probe dir");
std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o000)).expect("chmod");
let refused = std::fs::read_dir(&shut).is_err();
let _ = std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o755));
if !refused {
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
}
refused
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
// The finding TODO §45.2 closes: one permission-denied directory used to
// propagate `read_dir`'s error and fail the whole run.
if !listing_is_refused() {
return;
}
let dir = unwalkable_tree("walk-warn");
let out = run(&[&dir.root()]);
unlock(&dir);
@@ -2262,6 +2285,9 @@ fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted()
#[test]
#[cfg(unix)]
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
if !listing_is_refused() {
return;
}
let dir = unwalkable_tree("walk-warn-check");
let out = run(&["--check", &dir.root()]);
unlock(&dir);
+171
View File
@@ -0,0 +1,171 @@
//! `--style` and `[format] style` through the real `lucisv` binary: the
//! flag, the config key, their precedence over each other and under the
//! explicit `indent`/`line-length`, the error for a name that is not a
//! preset, and the format cache keyed on the style.
use std::path::PathBuf;
use std::process::{Command, Output};
use std::sync::atomic::{AtomicUsize, Ordering};
const LUCISV: &str = env!("CARGO_BIN_EXE_lucisv");
/// One `if`/`else` whose layout every switch of `ansi` changes.
const SOURCE: &str =
"module m;\n initial if (a) begin x = 1; end else begin x = 2; end\nendmodule\n";
const LUCISV_OUT: &str = "\
module m;
initial
if (a) begin
x = 1;
end else begin
x = 2;
end
endmodule
";
const ANSI_OUT: &str = "\
module m;
initial
if (a)
begin
x = 1;
end
else
begin
x = 2;
end
endmodule
";
/// A throwaway directory under the system temp dir, removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> TempDir {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-style-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
// Discovery stops at a `.git`, so no config above the temp dir leaks in.
std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git");
TempDir { path }
}
fn write(&self, rel: &str, contents: &str) -> String {
let path = self.path.join(rel);
std::fs::write(&path, contents).expect("write fixture");
path.to_string_lossy().into_owned()
}
fn read(&self, rel: &str) -> String {
std::fs::read_to_string(self.path.join(rel)).expect("read fixture")
}
fn cache(&self) -> String {
self.path.join("cache").to_string_lossy().into_owned()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn run(args: &[&str]) -> Output {
Command::new(LUCISV).args(args).output().expect("run lucisv")
}
fn code(out: &Output) -> i32 {
out.status.code().expect("exit code")
}
fn stdout(out: &Output) -> String {
String::from_utf8_lossy(&out.stdout).into_owned()
}
fn stderr(out: &Output) -> String {
String::from_utf8_lossy(&out.stderr).into_owned()
}
#[test]
fn the_flag_picks_a_preset() {
let dir = TempDir::new("flag");
let path = dir.write("a.sv", SOURCE);
let out = run(&["--no-cache", "--stdout", "--style", "ansi", &path]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stdout(&out), ANSI_OUT);
let out = run(&["--no-cache", "--stdout", &path]);
assert_eq!(stdout(&out), LUCISV_OUT, "no style is the default layout");
let out = run(&["--no-cache", "--stdout", "--style", "lucisv", &path]);
assert_eq!(stdout(&out), LUCISV_OUT, "and `lucisv` is that same layout");
}
#[test]
fn the_config_key_picks_a_preset_and_the_flag_beats_it() {
let dir = TempDir::new("toml");
dir.write("lucisv.toml", "[format]\nstyle = \"ansi\"\n");
let path = dir.write("a.sv", SOURCE);
assert_eq!(code(&run(&["--no-cache", &path])), 0);
assert_eq!(dir.read("a.sv"), ANSI_OUT);
let out = run(&["--no-cache", "--stdout", "--style", "lucisv", &path]);
assert_eq!(stdout(&out), LUCISV_OUT, "CLI flag > config file");
let out = run(&["--no-cache", "--stdout", "--no-config", &path]);
assert_eq!(stdout(&out), LUCISV_OUT, "--no-config drops the style with the file");
}
#[test]
fn explicit_indent_wins_over_the_presets() {
let dir = TempDir::new("indent");
let path = dir.write("a.sv", SOURCE);
let out = run(&["--no-cache", "--stdout", "--style", "ansi", "--indent", "2", &path]);
assert_eq!(stdout(&out), ANSI_OUT.replace(" ", " "));
// The file's `indent` beats the flag's preset too: an explicit value is
// explicit wherever it was written.
dir.write("lucisv.toml", "indent = 2\n");
let out = run(&["--no-cache", "--stdout", "--style", "ansi", &path]);
assert_eq!(stdout(&out), ANSI_OUT.replace(" ", " "));
}
#[test]
fn an_unknown_style_is_an_error_that_lists_the_presets() {
let dir = TempDir::new("unknown");
let path = dir.write("a.sv", SOURCE);
let out = run(&["--no-cache", "--style", "allman", &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("unknown style `allman`"), "{}", stderr(&out));
assert!(
stderr(&out).contains("lucisv, google, lowrisc, ansi, microsoft, nxp"),
"{}",
stderr(&out)
);
// The same in `lucisv.toml`, naming the file and the line; nothing written.
let config = dir.write("lucisv.toml", "indent = 2\n[format]\nstyle = \"allman\"\n");
let out = run(&["--no-cache", &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains(&format!("{config}:3:")), "{}", stderr(&out));
assert!(stderr(&out).contains("unknown style `allman`"), "{}", stderr(&out));
assert_eq!(dir.read("a.sv"), SOURCE);
}
#[test]
fn changing_the_style_invalidates_the_cache_entry() {
let dir = TempDir::new("cache");
let path = dir.write("a.sv", LUCISV_OUT);
let cache = dir.cache();
let out = run(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let out = run(&["--check", &path, "--cache-dir", &cache]);
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
// The same bytes are not clean under another style, cache or no cache.
let out = run(&["--check", "--style", "ansi", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "the style is part of the key: {}", stderr(&out));
// And a clean verdict under `ansi` is not one under the default.
dir.write("a.sv", ANSI_OUT);
assert_eq!(code(&run(&["--check", "--style", "ansi", &path, "--cache-dir", &cache])), 0);
let out = run(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
}
+76 -21
View File
@@ -12,6 +12,8 @@ use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use crate::config::STYLE_NAMES;
/// The default cache directory, resolved against the current directory.
pub const DEFAULT_DIR: &str = ".lucisv_cache";
@@ -35,6 +37,10 @@ pub struct Entry {
/// The `[format] uvm-utils-indent` that verdict was reached under: it
/// changes the output of a UVM class, so it is part of the key.
pub uvm_utils_indent: bool,
/// The `[format] style` that verdict was reached under, one of
/// [`crate::config::STYLE_NAMES`]: every preset lays files out
/// differently, so it is part of the key.
pub style: &'static str,
}
/// The cache for one run: loaded once at startup, written once at exit.
@@ -107,8 +113,8 @@ impl Cache {
let entry = &self.entries[path];
let _ = writeln!(
text,
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
"{:016x}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent, entry.style
);
}
text
@@ -154,28 +160,39 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize,
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
let mut entries = HashMap::new();
for line in text.lines() {
let fields: Vec<&str> = line.splitn(6, '\t').collect();
let fields: Vec<&str> = line.splitn(7, '\t').collect();
match fields[..] {
[content, line_length, indent, uvm, version, path] => {
[content, line_length, indent, uvm, style, version, path] => {
let (content, line_length, indent) = prefix(content, line_length, indent)?;
let uvm_utils_indent = uvm.parse().ok()?;
if path.is_empty() {
return None;
}
if version == VERSION {
// A style this build does not know is another build's
// entry: stale, not corrupt.
let known = STYLE_NAMES.into_iter().find(|n| *n == style);
if let (Some(style), true) = (known, version == VERSION) {
entries.insert(
path.to_string(),
Entry { content, line_length, indent, uvm_utils_indent },
Entry { content, line_length, indent, uvm_utils_indent, style },
);
}
}
// A store written before `uvm-utils-indent` joined the key: a
// well-formed line of that older shape says nothing about the
// option, so it is dropped individually, exactly like another
// version's entry. (The version field alone already makes such
// a store miss; the codec stays self-describing anyway.)
// Anything else on five fields is corruption and discards the
// file like any other malformed line.
// A store written before `style` joined the key: a well-formed
// line of that older shape says nothing about the style, so it is
// dropped individually, exactly like another version's entry.
[content, line_length, indent, uvm, _version, path] => {
prefix(content, line_length, indent)?;
uvm.parse::<bool>().ok()?;
if path.is_empty() {
return None;
}
}
// And the same for the shape before `uvm-utils-indent` joined it.
// (The version field alone already makes such a store miss; the
// codec stays self-describing anyway.) Anything else on five or
// six fields is corruption and discards the file like any other
// malformed line.
[content, line_length, indent, _version, path] => {
prefix(content, line_length, indent)?;
if path.is_empty() {
@@ -228,7 +245,7 @@ mod tests {
}
fn entry(content: u64) -> Entry {
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false, style: "lucisv" }
}
#[test]
@@ -262,6 +279,7 @@ mod tests {
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { style: "google", ..entry(0xdead) }));
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
}
@@ -276,7 +294,7 @@ mod tests {
let mut cache = Cache::load(&dir.path);
cache.record(&file, on);
cache.store();
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
assert!(dir.cache_text().contains("\t100\t2\ttrue\tlucisv\t"), "{}", dir.cache_text());
let reloaded = Cache::load(&dir.path);
assert!(reloaded.is_clean(&file, on));
@@ -291,7 +309,7 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -308,6 +326,37 @@ mod tests {
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
}
#[test]
fn a_line_without_the_style_or_with_an_unknown_one_is_dropped_but_not_fatal() {
// The six-field shape lucisv wrote before `style` joined the key, and
// a style this build does not know: both stale, never corruption.
let dir = TempDir::new("nostyle");
let old = dir.file("old.sv");
let other = dir.file("other.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tbespoke\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tnxp\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
other.to_string_lossy(),
3,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&old, entry(1)), "a line without the style must not be trusted");
assert!(!cache.is_clean(&other, Entry { style: "lucisv", ..entry(2) }));
assert!(cache.is_clean(&mine, Entry { style: "nxp", ..entry(3) }));
assert!(!cache.is_clean(&mine, entry(3)), "the style is part of the key");
cache.store();
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
assert!(!dir.cache_text().contains("other.sv"), "{}", dir.cache_text());
}
#[test]
fn the_file_is_sorted_and_carries_the_version() {
let dir = TempDir::new("format");
@@ -325,7 +374,7 @@ mod tests {
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
assert_eq!(
lines[0],
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
format!("{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}", 1, a.to_string_lossy()),
"{text}"
);
}
@@ -350,13 +399,19 @@ mod tests {
"0000000000000001\t100\t2\t0.2.0\t\n",
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
"0000000000000001\t100\t2\tyes\tlucisv\t0.2.0\t/a.sv\n",
"0000000000000001\t100\twide\tfalse\tlucisv\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\tlucisv\t0.2.0\t\n",
"\0\0\0\n",
] {
let dir = TempDir::new("corrupt");
let file = dir.file("a.sv");
// A good line first: a bad one anywhere discards all of them.
let good =
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
let good = format!(
"{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
file.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
@@ -369,8 +424,8 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
"{:016x}\t100\t2\tfalse\tlucisv\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
+56 -6
View File
@@ -11,7 +11,14 @@ use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
/// Config file names, in the order a directory is probed.
const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
/// The names `[format] style` accepts: the formatter's presets, in its
/// `style::PRESETS` order, then `auto`. This crate knows no Verilog and so
/// does not depend on the formatter; the two lists are held equal by a test
/// in the `lucisv` crate, which sees both.
pub const STYLE_NAMES: [&str; 7] =
["lucisv", "google", "lowrisc", "ansi", "microsoft", "nxp", "auto"];
/// The settings one config file carries. Every key is optional; an unset
/// key leaves the CLI flag (or the built-in default) in charge.
@@ -34,6 +41,9 @@ pub struct FileConfig {
/// statements written between `` `uvm_*_utils_begin `` and
/// `` `uvm_*_utils_end ``. Off for the same reason.
pub format_uvm_utils_indent: Option<bool>,
/// `[format] style`: the named layout preset, one of [`STYLE_NAMES`].
/// Checked here, so a misspelt name fails the run like a misspelt key.
pub format_style: Option<&'static str>,
/// `[lint] select`: run exactly these rules, replacing the default set.
/// The names are **not** validated here — this crate does not know the
/// rule registry; `lucisv check` validates them the moment it resolves the
@@ -176,23 +186,30 @@ fn parse_entry(
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
uvm-utils-indent under `[format]`; \
style, uvm-utils-indent under `[format]`; \
select, ignore, waivers under `[lint]`; and a rule's own options \
under `[lint.<rule-name>]`)"
)),
}
}
/// One key of the `[format]` table: a boolean that defaults to off, because
/// it changes how already-clean files are laid out and a project has to opt
/// in before anything of its moves.
/// One key of the `[format]` table: the named `style`, or a boolean that
/// defaults to off, because it changes how already-clean files are laid out
/// and a project has to opt in before anything of its moves.
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
if key == "style" {
if config.format_style.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.format_style = Some(parse_style(&parse_string(value)?)?);
return Ok(());
}
let slot = match key {
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
_ => {
return Err(format!(
"unknown key `{key}` under `[format]` \
(the only key is uvm-utils-indent)"
(known keys: style, uvm-utils-indent)"
))
}
};
@@ -203,6 +220,13 @@ fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result
Ok(())
}
/// One of [`STYLE_NAMES`], exactly as spelt there.
pub fn parse_style(name: &str) -> Result<&'static str, String> {
STYLE_NAMES.into_iter().find(|n| *n == name).ok_or_else(|| {
format!("unknown style `{name}` (the styles are {})", STYLE_NAMES.join(", "))
})
}
/// `true` or `false`, and nothing else — a misspelling is a typo the user
/// wants to hear about, not a silent `false`.
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
@@ -614,6 +638,32 @@ exclude = [ \"build\", \"*_gen.sv\", ]
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
}
/// `[format] style` names a preset; anything else is an error that lists
/// the presets, the way an unknown key lists the keys.
#[test]
fn the_format_table_carries_a_style() {
assert_eq!(ok("[format]\nstyle = \"google\"").format_style, Some("google"));
assert_eq!(ok("[format]\nstyle = \"lucisv\" # the default").format_style, Some("lucisv"));
assert_eq!(ok("indent = 4").format_style, None);
for name in STYLE_NAMES {
assert_eq!(ok(&format!("[format]\nstyle = \"{name}\"")).format_style, Some(name));
}
let unknown = err("[format]\nstyle = \"gogle\"");
assert!(unknown.contains("unknown style `gogle`"), "{unknown}");
assert!(
unknown.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
"{unknown}"
);
assert!(err("[format]\nstyle = \"Google\"").contains("unknown style `Google`"));
assert!(err("[format]\nstyle = google").contains("expected a quoted string"));
assert!(
err("[format]\nstyle = \"ansi\"\nstyle = \"nxp\"").contains("duplicate key `style`")
);
// Like `uvm-utils-indent`, it lives in `[format]` and nowhere else.
assert!(err("style = \"google\"").contains("unknown key `style`"));
assert!(err("[lint]\nstyle = \"google\"").contains("unknown key `style` under `[lint]`"));
}
/// Everything about the table's shape, the way the `[lint]` table's is
/// pinned: an unknown key is named, a non-boolean value is refused, and a
/// repeated key is an error rather than a last-one-wins.
+39
View File
@@ -731,6 +731,13 @@ mod tests {
}
}
#[cfg(unix)]
impl Drop for TempTree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
#[cfg(unix)]
fn a_directory_linking_to_itself_is_entered_once() {
@@ -794,12 +801,41 @@ mod tests {
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
}
/// Whether file modes bind this process: a mode-000 `rel` (a directory
/// when `rel` ends in `/`, else a file) refuses to be read. Root reads it
/// anyway (Linux CI jobs run as root), so the unreadable-path tests below
/// cannot build their path there; they say so and stop.
#[cfg(unix)]
fn reading_is_refused(rel: &str) -> bool {
let probe = TempTree::new("mode-probe");
let path = probe.path.join(rel);
if rel.ends_with('/') {
std::fs::create_dir(&path).expect("probe dir");
} else {
probe.write(rel, "");
}
probe.chmod(rel, 0o000);
let refused = if rel.ends_with('/') {
std::fs::read_dir(&path).is_err()
} else {
std::fs::File::open(&path).is_err()
};
probe.chmod(rel, 0o755);
if !refused {
eprintln!("skipped: a mode-000 `{rel}` is readable by this user (root?)");
}
refused
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
// The finding this channel exists for: one permission-denied directory
// used to propagate `read_dir`'s error out of the whole walk, dropping
// every file already found and failing the run.
if !reading_is_refused("shut/") {
return;
}
let tree = TempTree::new("unreadable");
tree.source("a.sv");
tree.source("locked/hidden.sv");
@@ -815,6 +851,9 @@ mod tests {
#[test]
#[cfg(unix)]
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
if !reading_is_refused("shut") {
return;
}
let tree = TempTree::new("lockedignore");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
+23
View File
@@ -274,6 +274,25 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
/// Whether file modes bind this process: a mode-555 directory under `dir`
/// refuses a new file. Root writes it anyway (Linux CI jobs run as root),
/// so there the half of the test below that needs a directory refusing
/// the temp file cannot be built; it says so and stops.
#[cfg(unix)]
fn creating_is_refused(dir: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
let shut = dir.join("mode-probe");
fs::create_dir(&shut).unwrap();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
let refused = fs::write(shut.join("x"), "").is_err();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
fs::remove_dir_all(&shut).unwrap();
if !refused {
eprintln!("skipped: a mode-555 directory takes new files from this user (root?)");
}
refused
}
#[cfg(unix)]
#[test]
fn a_write_that_fails_after_another_landed_says_what_was_written() {
@@ -290,6 +309,10 @@ mod tests {
let refused = commit(&[&first, &second], name).unwrap_err();
assert_eq!(refused, "`b.sv` is read-only; nothing written.");
assert_eq!(fs::read_to_string(&a).unwrap(), "a\n");
if !creating_is_refused(&dir) {
fs::remove_dir_all(dir).unwrap();
return;
}
// … but a directory that will not take the temp file fails only at
// the write, after `a.sv` landed: said, not hidden.
fs::set_permissions(&b, fs::Permissions::from_mode(0o644)).unwrap();
+14 -2
View File
@@ -22,8 +22,7 @@ use std::process::ExitCode;
use vlog_parser::PARSE_STACK_SIZE;
/// What someone who spelled an argument wrong is told, on stderr.
const USAGE: &str =
"usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--verbose]";
const USAGE: &str = "usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--read-only] [--verbose]";
/// The command line, parsed.
#[derive(Debug, Default, PartialEq, Eq)]
@@ -35,6 +34,8 @@ pub struct Options {
/// `--index-cache DIR`: the language server's index cache directory,
/// read at startup; this server's own store is written there on exit.
pub index_cache: Option<PathBuf>,
/// `--read-only`: the five read tools only (PLAN §11).
pub mode: tools::Mode,
/// `--verbose`: per-call timing lines on stderr.
pub verbose: bool,
}
@@ -88,6 +89,7 @@ fn parse_args(args: impl Iterator<Item = String>) -> Result<Options, String> {
"--root" => options.roots.push(value("--root")?),
"--filelist" => options.filelist = Some(value("--filelist")?),
"--index-cache" => options.index_cache = Some(value("--index-cache")?),
"--read-only" => options.mode = tools::Mode::ReadOnly,
"--verbose" => options.verbose = true,
other => return Err(format!("unknown option: {other}")),
}
@@ -114,13 +116,23 @@ mod tests {
"f.f",
"--index-cache",
"c",
"--read-only",
"--verbose",
])
.unwrap();
assert_eq!(options.roots, vec![PathBuf::from("a"), PathBuf::from("b")]);
assert_eq!(options.filelist, Some(PathBuf::from("f.f")));
assert_eq!(options.index_cache, Some(PathBuf::from("c")));
assert_eq!(options.mode, tools::Mode::ReadOnly);
assert!(options.verbose);
assert_eq!(parse(&["--verbose"]).unwrap().mode, tools::Mode::Full);
}
#[test]
fn the_usage_line_names_every_flag() {
for flag in ["--root", "--filelist", "--index-cache", "--read-only", "--verbose"] {
assert!(USAGE.contains(flag), "{flag}");
}
}
#[test]
+3 -1
View File
@@ -111,7 +111,9 @@ fn run(
tool: &str,
argument: Option<(&str, &str)>,
) -> Result<String, String> {
let tool = tools::find(tool).ok_or_else(|| format!("no tool `{tool}`"))?;
// A resource runs read tools only, so it answers the same in either mode.
let tool =
tools::find(tool, tools::Mode::ReadOnly).ok_or_else(|| format!("no tool `{tool}`"))?;
let mut arguments = Map::new();
if let Some((name, value)) = argument {
arguments.insert(name.to_string(), Value::from(value));
+26 -5
View File
@@ -13,7 +13,7 @@ use serde_json::{json, Map, Value};
use crate::project::Project;
use crate::resources::{self, Resource};
use crate::tools;
use crate::tools::{self, Mode};
use crate::transport::{Line, Transport};
use crate::Options;
@@ -38,6 +38,17 @@ const RESOURCE_NOT_FOUND: i64 = -32002;
/// What the agent is told once, at `initialize` (PLAN §10.3, ≤ 400 bytes).
const INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
/// What the agent is told in `--read-only` mode (PLAN §11.1, ≤ 300 bytes).
const INSTRUCTIONS_READ_ONLY: &str = "lucisv-mcp reads the SystemVerilog on disk (save first); it never edits. Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check for issues. Paths root-relative, lines 1-based.";
/// The instructions for `mode`.
fn instructions(mode: Mode) -> &'static str {
match mode {
Mode::Full => INSTRUCTIONS,
Mode::ReadOnly => INSTRUCTIONS_READ_ONLY,
}
}
/// A JSON-RPC error object.
#[derive(Debug, Serialize)]
pub struct RpcError {
@@ -195,7 +206,7 @@ impl Server {
"initialize" => Ok(self.initialize(params.as_ref())),
"ping" => Ok(json!({})),
_ if self.version.is_none() => Err(fault(NOT_INITIALIZED, "server not initialized")),
"tools/list" => Ok(tools::list()),
"tools/list" => Ok(tools::list(self.options.mode)),
"tools/call" => self.call_tool(params),
"resources/list" => Ok(resources::list()),
"resources/templates/list" => Ok(resources::templates()),
@@ -217,7 +228,7 @@ impl Server {
"protocolVersion": version,
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
"instructions": INSTRUCTIONS,
"instructions": instructions(self.options.mode),
})
}
@@ -233,8 +244,8 @@ impl Server {
let Some(Value::String(name)) = params.remove("name") else {
return Err(fault(INVALID_PARAMS, "tools/call params need a string `name`"));
};
let Some(tool) = tools::find(&name) else {
return Err(fault(INVALID_PARAMS, format!("unknown tool: {name}")));
let Some(tool) = tools::find(&name, self.options.mode) else {
return Err(fault(INVALID_PARAMS, unknown_tool(&name, self.options.mode)));
};
let arguments = match params.remove("arguments") {
None | Some(Value::Null) => Map::new(),
@@ -319,6 +330,15 @@ fn open_project(options: &Options) -> Project {
project
}
/// The `-32602` message for a tool `mode` does not offer. In read-only mode
/// it says why, so an agent does not retry an edit the server cannot make.
fn unknown_tool(name: &str, mode: Mode) -> String {
match mode {
Mode::Full => format!("unknown tool: {name}"),
Mode::ReadOnly => format!("unknown tool: {name} (the server runs --read-only)"),
}
}
/// A tool's answer as `tools/call` returns it.
fn tool_result(answer: Result<tools::Answer, String>) -> Value {
match answer {
@@ -348,6 +368,7 @@ mod tests {
#[test]
fn the_instructions_stay_under_400_bytes() {
assert!(INSTRUCTIONS.len() <= 400, "{}", INSTRUCTIONS.len());
assert!(INSTRUCTIONS_READ_ONLY.len() <= 300, "{}", INSTRUCTIONS_READ_ONLY.len());
}
#[test]
+3 -1
View File
@@ -161,7 +161,9 @@ impl Runs {
}
waivers.absorb(file);
}
let format = vlog_formatter::Config::default();
// The width and indent the file would be formatted with, its style's
// included, so the linter and the formatter cannot disagree.
let format = super::format::formatter_config(config);
Ok(Run {
rules,
options,
+52 -12
View File
@@ -45,10 +45,14 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
}
let set = whole_set(project, Some(&path), std::slice::from_ref(&name))?;
let edit = vlog_refactor::rename(&set.files, &path, declaration.offset, new_name)
.map_err(|why| set.rooted(project, &why))?;
.map_err(|why| set.rooted(&why))?;
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
let told = Told { name: &name, home: &path, unit: unit.as_deref() };
// A member of a module is named bare only where it is declared or used;
// the module (or interface, program) itself is named anywhere.
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
let member = unit.is_some() && !unit_itself;
let told = Told { name: &name, home: &path, unit: unit.as_deref(), member };
let done = write_telling(project, edit, &set, &told)?;
let (sites, files) = (render::count(sites, "site"), render::count(done.files, "file"));
let mut lines = vec![format!("renamed {sites} in {files}")];
@@ -62,6 +66,8 @@ struct Picked {
name: String,
path: PathBuf,
offset: u32,
/// The declaration's kind word (`module`, `var`, …).
kind: &'static str,
}
fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String> {
@@ -87,16 +93,9 @@ fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String>
[one] if one.is_macro() => {
Err(format!("`{name}` is a macro; lucisv does not rename macros."))
}
// The engine rewrites no hierarchical path through a block and
// reports none as a use, so the rename could not be complete
// (topo §2.9 MCP-14).
[one] if one.kind == "block" => Err(format!(
"`rename` does not rename generate block labels: paths through the block (`{}[0].…`) would not be rewritten; edit the file.",
names::qualified(name).1
)),
[one] => {
let name = names::qualified(name).1.to_string();
Ok(Picked { name, path: one.path.clone(), offset: one.offset })
Ok(Picked { name, path: one.path.clone(), offset: one.offset, kind: one.kind })
}
many => Err(names::ambiguous(name, many, "pass `file`, and `name@LINE` within one file")),
}
@@ -129,6 +128,10 @@ pub(super) struct Told<'a> {
pub name: &'a str,
pub home: &'a Path,
pub unit: Option<&'a str>,
/// Whether the name is a member of a module or interface: its bare
/// mentions outside its home set (`vlog_refactor::home_set`) are not
/// listed.
pub member: bool,
}
/// What a written edit says after its first line: how many files it wrote,
@@ -151,21 +154,58 @@ pub(super) fn write_telling(
let accounted: Vec<(PathBuf, Vec<TextRange>)> =
edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect();
let plan = Plan::from_refactor(edit, &set.files)?;
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(w)).collect();
let named = path_warned(&warnings);
let written = set.files.iter().map(|(path, text)| {
let change = plan.changes.iter().find(|change| &change.path == path);
(path.as_path(), change.map_or(text.as_str(), |change| change.after.as_str()))
});
let focus = Focus { name: told.name, home: told.home, unit: told.unit, accounted: &accounted };
// The member's home set (the declaring file, what it includes and what
// includes it, and the edited files): where a bare mention can mean it.
let edited: Vec<PathBuf> = plan.changes.iter().map(|change| change.path.clone()).collect();
// `None` — list every mention — for a non-member, and for a member whose
// home set is not known (an include the engine cannot resolve).
let local = match told.member {
true => vlog_refactor::home_set(&set.files, told.home, &edited),
false => None,
};
let focus = Focus {
name: told.name,
home: told.home,
unit: told.unit,
accounted: &accounted,
named: &named,
local: local.as_deref(),
};
let mentions = mentions::find(project, written, &focus);
let done = apply::run(project, &plan)?;
let mut tail = Vec::new();
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(project, w)).collect();
render::warnings(&mut tail, &warnings);
tail.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
tail.extend(mentions.block());
Ok(Done { files: done.changed.len() + done.created.len(), tail })
}
/// The `(file, line)` pairs the engine's unresolved-path warnings name
/// (`rtl/a.sv:3,7: a hierarchical path through …`), so the `unresolved:`
/// block does not list them a second time.
fn path_warned(warnings: &[String]) -> Vec<(String, u32)> {
let mut out = Vec::new();
for warning in warnings {
let Some((head, _)) = warning.split_once(": a hierarchical path through `") else {
continue;
};
let Some((file, lines)) = head.rsplit_once(':') else { continue };
out.extend(
lines
.split(',')
.filter_map(|line| line.parse().ok())
.map(|line| (file.to_string(), line)),
);
}
out
}
/// Where each of one file's edits lands in the text as written: its start
/// shifted by what the edits before it added or removed, its length the
/// new text's.
+35 -2
View File
@@ -83,7 +83,7 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
account(&mut accounted, hits);
}
Err(why) => {
let why = engine_refusal(&set.rooted(project, &why));
let why = engine_refusal(&set.rooted(&why));
lines.push(format!(" uses not listed: {why}"));
}
}
@@ -93,13 +93,46 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
}
let home = &found[0].path;
let focus = Focus { name, home, unit: None, accounted: &accounted };
let local = member_files(&set, found, &accounted);
let focus = Focus {
name,
home,
unit: None,
accounted: &accounted,
named: &[],
local: local.as_deref(),
};
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
lines.extend(mentions::find(project, files, &focus).block());
lines.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
lines
}
/// The files a bare mention of a **module member** can mean it in — each
/// declaration's home set (`vlog_refactor::home_set`) with every file the
/// engine found a use in — or `None` when
/// any declaration is not a member (a unit, a package member, a macro), whose
/// every mention is listed (§65.1, lead's inspection: a `state_q` found in forty
/// modules is not news about this one).
fn member_files(
set: &WholeSet,
found: &[Declaration],
accounted: &[(PathBuf, Vec<TextRange>)],
) -> Option<Vec<PathBuf>> {
if found.iter().any(Declaration::is_macro) {
return None;
}
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
let mut local: Vec<PathBuf> = Vec::new();
for declaration in found {
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)?;
local.extend(vlog_refactor::home_set(&set.files, &declaration.path, &hit_files)?);
}
Some(local)
}
/// The engine's hits, one file per line: `file:12,40`.
fn uses(project: &Project, set: &WholeSet, hits: &[(PathBuf, TextRange)]) -> Vec<String> {
let mut sites: Vec<(String, u32)> = Vec::new();
+26 -3
View File
@@ -119,9 +119,10 @@ fn fixed_and_formatted(
}
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
/// `Options::config_with` with no command-line flags.
fn formatter_config(file: &FileConfig) -> Config {
let mut config = Config::default();
/// `Options::config_with` with no command-line flags: the style first, then
/// the explicit keys over the preset's indent and width.
pub(super) fn formatter_config(file: &FileConfig) -> Config {
let mut config = file.format_style.and_then(Config::named).unwrap_or_default();
if let Some(width) = file.line_length {
config.max_width = width;
}
@@ -195,3 +196,25 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
.iter()
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_formatter::style;
/// The MCP `format` tool resolves a `lucisv.toml` the way `lucisv` with no
/// flags does: the style first, the explicit keys over its numbers.
#[test]
fn the_style_comes_first_and_explicit_keys_win() {
let none = formatter_config(&FileConfig::default());
assert_eq!((none.style, none.indent_width, none.max_width), (style::LUCISV, 2, 100));
let ansi = FileConfig { format_style: Some("ansi"), ..Default::default() };
let config = formatter_config(&ansi);
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 4, 80));
let narrowed = FileConfig { indent: Some(2), line_length: Some(90), ..ansi };
let config = formatter_config(&narrowed);
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 2, 90));
let auto = FileConfig { format_style: Some("auto"), ..Default::default() };
assert!(formatter_config(&auto).auto_style);
}
}
+18 -9
View File
@@ -32,9 +32,16 @@ const MAX_DEPTH: i64 = 20;
/// The most nodes one walk collects before it stops.
const NODE_CAP: usize = 50_000;
/// The most lines an answer holds before `… and N more`.
/// The most lines the overview holds, and the most nodes (tree lines, the
/// root's included) a tree answer without `peek` shows, before
/// `… and N more`.
const CAP: usize = 300;
/// The most nodes a tree answer with `peek` shows. A node's `peek` lines
/// never count — the cap is on instances — but each costs up to 13 lines,
/// so the answer stays short (PLAN §10.1).
const PEEK_CAP: usize = 100;
/// The most source lines `peek` shows of one statement before `…`.
const PEEK_LINES: usize = 12;
@@ -271,14 +278,21 @@ impl<'a> Walk<'a> {
}
/// The nodes as lines, two spaces per level (`up` starts at no indent),
/// each followed by its statement on `peek`; cut whole nodes at [`CAP`].
/// each followed by its statement on `peek`; at most [`CAP`] nodes
/// ([`PEEK_CAP`] with `peek`), then `… and N more` counting the nodes not
/// shown.
fn render_nodes(project: &Project, nodes: &[Node], up: bool, peek: bool) -> Vec<String> {
let mut texts = Texts::default();
let mut lines: Vec<String> = Vec::new();
let cap = if peek { PEEK_CAP } else { CAP };
for (at, node) in nodes.iter().enumerate() {
if at == cap {
lines.push(render::more(nodes.len() - at));
return lines;
}
let level = if up { node.depth - 1 } else { node.depth };
let indent = " ".repeat(level);
let mut block = vec![format!("{indent}{}", node_line(project, &mut texts, node, up))];
lines.push(format!("{indent}{}", node_line(project, &mut texts, node, up)));
if let (true, Some(child)) = (peek, &node.instance) {
let source = statement(project, &mut texts, child);
// A blank line of the statement stays blank: no indent of ours.
@@ -286,13 +300,8 @@ fn render_nodes(project: &Project, nodes: &[Node], up: bool, peek: bool) -> Vec<
true => line,
false => format!("{indent} {line}"),
};
block.extend(source.into_iter().map(shown));
lines.extend(source.into_iter().map(shown));
}
if lines.len() + block.len() > CAP {
lines.push(render::more(nodes.len() - at));
return lines;
}
lines.extend(block);
}
lines
}
+20
View File
@@ -52,6 +52,17 @@ pub struct Focus<'a> {
pub unit: Option<&'a str>,
/// Per file, the spans an engine returned (hits) or rewrote (edits).
pub accounted: &'a [(PathBuf, Vec<TextRange>)],
/// `(file, line)` pairs an engine warning already names — a `rename`'s
/// unresolved-path warning — which are not repeated as mentions.
pub named: &'a [(String, u32)],
/// For a member of a module or interface (a net, a port, a block, …):
/// the files where a bare spelling can mean it — its home set: the
/// declaring file, what it includes and what includes it, and the files
/// the edit wrote or the engine found uses in. Elsewhere only a
/// spelling right after a `.` (`".state_q"`, `` `HIER.u.state_q``) is
/// listed. `None` for a name any file may spell bare (a unit, a package
/// member): every mention is listed.
pub local: Option<&'a [PathBuf]>,
}
impl Mentions {
@@ -93,7 +104,13 @@ pub fn find<'t>(
let spans = accounted.map_or(&[][..], |(_, spans)| spans.as_slice());
let lines = LineIndex::new(text);
let mut last_line = 0;
let foreign = focus.local.is_some_and(|local| !local.iter().any(|p| p == path));
for (at, _) in spellings(text, focus.name) {
if foreign
&& !text.as_bytes().get((at as usize).wrapping_sub(1)).is_some_and(|&b| b == b'.')
{
continue;
}
let end = at + focus.name.len() as u32;
if spans.iter().any(|span| span.start <= at && end <= span.end) {
continue;
@@ -109,6 +126,9 @@ pub fn find<'t>(
.unwrap_or("");
let rank = rank(accounted.is_some(), focus.unit, source);
let mention = Mention { file: project.relative(path), line };
if focus.named.iter().any(|(file, at)| *file == mention.file && *at == line) {
continue;
}
found.push((rank, shared_components(path, focus.home), mention));
}
}
+43 -6
View File
@@ -105,14 +105,39 @@ const TOOLS: &[(Tool, Effect)] = &[
(format::FORMAT, Edit { idempotent: true }),
];
/// The tool called `name`.
pub fn find(name: &str) -> Option<&'static Tool> {
TOOLS.iter().map(|(tool, _)| tool).find(|tool| tool.name == name)
/// Which part of the registry the server offers (PLAN §11).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mode {
/// Every tool, the edits included.
#[default]
Full,
/// `--read-only`: the read tools alone; an edit tool is unknown.
ReadOnly,
}
/// The `tools/list` result: every tool, no pagination.
pub fn list() -> Value {
let tools: Vec<Value> = TOOLS.iter().map(|(tool, effect)| describe(tool, *effect)).collect();
impl Mode {
/// Whether a tool of this effect exists in this mode.
fn offers(self, effect: Effect) -> bool {
matches!((self, effect), (Mode::Full, _) | (Mode::ReadOnly, Read))
}
}
/// The tools `mode` offers, in `tools/list` order.
fn offered(mode: Mode) -> impl Iterator<Item = (&'static Tool, Effect)> {
TOOLS
.iter()
.filter(move |(_, effect)| mode.offers(*effect))
.map(|(tool, effect)| (tool, *effect))
}
/// The tool called `name`, when `mode` offers it.
pub fn find(name: &str, mode: Mode) -> Option<&'static Tool> {
offered(mode).map(|(tool, _)| tool).find(|tool| tool.name == name)
}
/// The `tools/list` result: every tool `mode` offers, no pagination.
pub fn list(mode: Mode) -> Value {
let tools: Vec<Value> = offered(mode).map(|(tool, effect)| describe(tool, effect)).collect();
json!({ "tools": tools })
}
@@ -253,8 +278,20 @@ mod tests {
assert_eq!(names.len(), unique.len());
}
#[test]
fn read_only_mode_offers_the_read_tools_alone_in_order() {
let names = |mode| -> Vec<&str> { offered(mode).map(|(tool, _)| tool.name).collect() };
assert_eq!(names(Mode::ReadOnly), ["hierarchy", "find", "outline", "read", "check"]);
assert_eq!(names(Mode::Full).len(), TOOLS.len());
for edit in ["rename", "port", "edit_item", "format"] {
assert!(find(edit, Mode::ReadOnly).is_none(), "{edit}");
assert!(find(edit, Mode::Full).is_some(), "{edit}");
}
}
#[test]
fn validation_names_the_offending_argument() {
let find = |name| find(name, Mode::Full);
let tool = find("check").unwrap();
let unknown = validate(tool, args(json!({"fil": "x"}))).err().unwrap();
assert!(unknown.contains("`fil`") && unknown.contains("file"), "{unknown}");
+6 -6
View File
@@ -63,18 +63,18 @@ fn add_port(
) -> Result<Answer, String> {
let set = whole_set(project, None, &[module.to_string()])?;
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(module), declaration)
.map_err(|why| set.rooted(project, &why))?;
.map_err(|why| set.rooted(&why))?;
let tokens = vlog_parser::tokenize(declaration).unwrap_or_default();
let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default();
let show = &|path: &Path| project.relative(path);
let edit = match after.map(str::trim) {
Some(after) => {
let spec = place::Spec { module, file, after, port: &port, declaration, show };
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(project, &why))?
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(&why))?
}
None => edit,
};
let told = Told { name: &port, home: file, unit: Some(module) };
let told = Told { name: &port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("added port {port} in module {module}: {}", census(count, files));
@@ -89,9 +89,9 @@ fn remove_port(
) -> Result<Answer, String> {
let offset = port_offset(project, module, file, port)?;
let set = whole_set(project, Some(file), &[port.to_string(), module.to_string()])?;
let edit = vlog_refactor::remove_port(&set.files, file, offset)
.map_err(|why| set.rooted(project, &why))?;
let told = Told { name: port, home: file, unit: Some(module) };
let edit =
vlog_refactor::remove_port(&set.files, file, offset).map_err(|why| set.rooted(&why))?;
let told = Told { name: port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("removed port {port} in module {module}: {}", census(count, files));
+44 -12
View File
@@ -76,6 +76,10 @@ pub struct WholeSet {
pub files: Vec<(PathBuf, String)>,
/// The files left out, with why.
pub skipped: Vec<(PathBuf, String)>,
/// How an engine sentence names each file of the set, and the
/// root-relative spelling it becomes — built once per set by
/// [`WholeSet::read`] ([`WholeSet::rooted`]).
names: Vec<(String, String)>,
}
impl WholeSet {
@@ -85,13 +89,14 @@ impl WholeSet {
pub fn read(project: &Project, extra: Option<&Path>) -> WholeSet {
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
wanted.extend(extra.map(Path::to_path_buf));
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped() };
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped(), names: Vec::new() };
for path in wanted {
match std::fs::read_to_string(&path) {
Ok(text) => set.files.push((path, text)),
Err(e) => set.skipped.push((path, format!("no longer reads: {e}"))),
}
}
set.names = names_of(project, &set.files);
set
}
@@ -105,18 +110,17 @@ impl WholeSet {
})
}
/// An engine sentence with each bare file name written root-relative
/// (`p1.sv:2` → `rtl/p1.sv:2`), where the name is the base name of
/// exactly one file of the set — the engines name files by base name,
/// and only an unambiguous one can be placed.
pub fn rooted(&self, project: &Project, sentence: &str) -> String {
/// An engine sentence with every file of the set written root-relative.
/// The engines name a file by its base name when that is unique in the
/// set they were handed (`p1.sv:2` → `rtl/p1.sv:2`) and by the path they
/// were given otherwise (`/abs/…/top_a/pwrmgr_if.sv:80` →
/// `top_a/…/pwrmgr_if.sv:80`, generate-label-rename R1). One pass over
/// the set's spellings per sentence; the table itself is built once.
pub fn rooted(&self, sentence: &str) -> String {
let mut out = sentence.to_string();
for (path, _) in &self.files {
let Some(base) = path.file_name().and_then(|name| name.to_str()) else { continue };
let same = self.files.iter().filter(|(other, _)| other.file_name() == path.file_name());
let shown = project.relative(path);
if same.count() == 1 && shown != base {
out = replace_file_name(&out, base, &shown);
for (spelled, shown) in &self.names {
if out.contains(spelled.as_str()) {
out = replace_file_name(&out, spelled, shown);
}
}
out
@@ -140,6 +144,34 @@ impl WholeSet {
}
}
/// Every file's engine spelling and its root-relative one: the full path for
/// a base name several files share, else the base name (skipped when it is
/// already the relative path). Full paths first, so a bare base name never
/// rewrites the tail of one.
fn names_of(project: &Project, files: &[(PathBuf, String)]) -> Vec<(String, String)> {
let mut count: HashMap<&std::ffi::OsStr, usize> = HashMap::new();
for (path, _) in files {
if let Some(base) = path.file_name() {
*count.entry(base).or_default() += 1;
}
}
let (mut full, mut bare) = (Vec::new(), Vec::new());
for (path, _) in files {
let Some(base) = path.file_name() else { continue };
let shown = project.relative(path);
match count.get(base) {
Some(1) => {
if let Some(base) = base.to_str().filter(|base| *base != shown) {
bare.push((base.to_string(), shown));
}
}
_ => full.push((path.display().to_string(), shown)),
}
}
full.extend(bare);
full
}
/// `text` with every occurrence of the file name `base` that stands alone —
/// not the tail of a longer path or name — replaced by `path`.
fn replace_file_name(text: &str, base: &str, path: &str) -> String {
+21
View File
@@ -242,11 +242,32 @@ fn a_missing_directory_starts_cold_and_its_own_store_serves_the_next_start() {
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
}
/// Whether file modes bind this process: a mode-555 directory refuses a new
/// file. Root writes it anyway (Linux CI jobs run as root), so there an
/// unwritable cache directory cannot be built; the test says so and stops.
#[cfg(unix)]
fn creating_is_refused(scratch: &Scratch) -> bool {
use std::os::unix::fs::PermissionsExt;
let shut = scratch.0.join("mode-probe");
fs::create_dir_all(&shut).unwrap();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
let refused = fs::write(shut.join("x"), "").is_err();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
fs::remove_dir_all(&shut).unwrap();
if !refused {
eprintln!("skipped: a mode-555 directory takes new files from this user (root?)");
}
refused
}
#[cfg(unix)]
#[test]
fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
if !creating_is_refused(&scratch) {
return;
}
fs::create_dir_all(scratch.cache()).unwrap();
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o555)).unwrap();
let stderr = whole_session(&scratch);
+137
View File
@@ -0,0 +1,137 @@
//! The `hierarchy` cap counts instances, never `peek` lines (census round 5,
//! 2026-09-29): an agent asking for every instantiation of a module with
//! `peek` gets every one up to 100 (300 without `peek`), each with its
//! statement, not a quarter of them. Each test writes a generated design into a scratch directory and
//! talks to the real binary over it.
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::{json, Value};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch design, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn with(files: &[(&str, String)]) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir()
.join(format!("lucisv-mcp-hierarchy-cap-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
for (rel, text) in files {
fs::write(dir.join(rel), text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One `hierarchy` call over `tree` that must succeed: its text.
fn hierarchy(tree: &Tree, arguments: Value) -> String {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", tree.0.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let init = json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "hierarchy_cap", "version": "0"}}});
let params = json!({"name": "hierarchy", "arguments": arguments});
let call = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params});
let mut stdin = child.stdin.take().unwrap();
stdin.write_all(format!("{init}\n{call}\n").as_bytes()).unwrap();
drop(stdin);
let output = child.wait_with_output().unwrap();
let stdout = String::from_utf8(output.stdout).unwrap();
let reply: Value = stdout
.lines()
.map(|line| serde_json::from_str::<Value>(line).unwrap())
.find(|reply| reply["id"] == 1)
.expect("the call is answered");
assert_eq!(reply["result"]["isError"], false, "{reply}");
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
}
/// `count` instantiations of `sub` in `top`, each written over `ports + 2`
/// lines: the header, one line per port, the closer.
fn crowded(count: usize, ports: usize) -> Tree {
let names: Vec<String> = (0..ports).map(|p| format!("p{p}")).collect();
let declared: Vec<String> = names.iter().map(|n| format!("input logic {n}")).collect();
let sub = format!("module sub #(parameter int W = 1) ({});\nendmodule\n", declared.join(", "));
let mut top = format!("module top;\n logic {};\n", names.join(", "));
for i in 0..count {
top.push_str(&format!(" sub #(.W({i})) u_{i:03} (\n"));
for (at, name) in names.iter().enumerate() {
let comma = if at + 1 < names.len() { "," } else { "" };
top.push_str(&format!(" .{name}({name}){comma}\n"));
}
top.push_str(" );\n");
}
top.push_str("endmodule\n");
Tree::with(&[("sub.sv", sub), ("top.sv", top)])
}
/// The tree lines of an answer: every line that is not a peeked statement.
fn node_lines(text: &str, statement_indent: &str) -> Vec<String> {
text.lines().filter(|l| !l.starts_with(statement_indent)).map(str::to_string).collect()
}
#[test]
fn up_with_peek_lists_every_instantiation_whatever_the_statements_cost() {
// 30 instantiations of 14 lines each: peek shows 12 lines and `…` per
// statement, 420 lines in all — every one is still there.
let tree = crowded(30, 12);
let text = hierarchy(&tree, json!({"root": "sub", "up": true, "peek": true}));
let nodes = node_lines(&text, " ");
let expected: Vec<String> =
(0..30).map(|i| format!("top.u_{i:03} top.sv:{}", 3 + i * 14)).collect();
assert_eq!(nodes, expected, "{text}");
assert!(!text.contains("… and "), "{text}");
assert_eq!(text.lines().count(), 30 * 14);
// Each statement: its first 12 lines as written, then `…`.
let first: Vec<&str> = text.lines().skip(1).take(13).collect();
assert_eq!(first[0], " sub #(.W(0)) u_000 (");
assert_eq!(first[11], " .p10(p10),");
assert_eq!(first[12], " …");
}
#[test]
fn over_100_instances_with_peek_shows_100_and_over_300_without_shows_300() {
let tree = crowded(350, 1);
// Up with peek: 350 instantiations, 100 shown, each with its 3-line statement.
let up = hierarchy(&tree, json!({"root": "sub", "up": true, "peek": true}));
let lines: Vec<&str> = up.lines().collect();
assert_eq!(lines.len(), 100 * 4 + 1, "{up}");
assert_eq!(*lines.last().unwrap(), "… and 250 more");
let nodes = node_lines(&up, " ");
assert_eq!(nodes.len(), 101);
assert_eq!(nodes[99], "top.u_099 top.sv:300");
assert_eq!(lines[lines.len() - 2], " );", "the last statement is whole");
// Down with peek: the root line and 99 instances make 100 nodes; 251 are left.
let down = hierarchy(&tree, json!({"root": "top", "peek": true}));
let nodes = node_lines(&down, " ");
assert_eq!(nodes.len(), 101, "{down}");
assert_eq!(nodes[0], "top top.sv:1");
assert_eq!(nodes[99], " u_098: sub top.sv:297");
assert_eq!(nodes[100], "… and 251 more");
// Without peek: 300 lines, then the count.
let plain = hierarchy(&tree, json!({"root": "sub", "up": true}));
assert_eq!(plain.lines().count(), 301);
assert!(plain.ends_with("\n… and 50 more\n"), "{plain}");
let plain = hierarchy(&tree, json!({"root": "top"}));
assert_eq!(plain.lines().count(), 301);
assert!(plain.ends_with("\n… and 51 more\n"), "{plain}");
}
+7 -2
View File
@@ -544,8 +544,11 @@ const SM: &str = "module main_sm (\n input logic clk_i,\n output logic busy_o
const DV: &str = "module dv_x;\n logic a, b;\n assign a = `HIER.u_a[2].state_q;\n assign b = `HIER.u_a[2].state_q_d;\n assign b = `HIER.u_a[state_q].x;\nendmodule\n";
// Dotted spellings: `state_q` is a member of `main_sm`, so since §65.1's
// scoping of mentions a bare spelling in another file is not listed, and a
// path-like one (`.state_q`) still is — which keeps this CRLF check alive.
const CRLF: &str =
"module c;\r\n // one\r\n // state_q two\r\n string s = \"state_q\";\r\nendmodule\r\n";
"module c;\r\n // one\r\n // u.state_q two\r\n string s = \"u.state_q\";\r\n // state_q bare, not listed\r\nendmodule\r\n";
#[test]
fn qa_mentions_find_every_kind_and_only_whole_words() {
@@ -580,7 +583,9 @@ fn qa_mentions_find_every_kind_and_only_whole_words() {
#[test]
fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
let far: String = (0..60).map(|i| format!("// state_q far {i}\n")).collect::<String>()
// Path-like, so listed from a file that neither declares nor uses the
// member (§65.1's scoping of mentions drops a bare one there).
let far: String = (0..60).map(|i| format!("// u.state_q far {i}\n")).collect::<String>()
+ "module far; endmodule\n";
let files = [("rtl/sm.sv", SM), ("zz/far.sv", far.as_str())];
let (tree, mut server) = served(&files);
+7 -2
View File
@@ -277,7 +277,10 @@ const MACRO_ARG: &[(&str, &str)] = &[
"top.sv",
"`include \"defs.svh\"\nmodule top (input logic clk);\n logic peek;\n core u_core0 (.clk, .q());\n assign peek = `ID(u_core0.state_q);\nendmodule\n",
),
("third.sv", "module third;\n // state_q is mentioned here\n initial $display(\"state_q\");\nendmodule\n"),
(
"third.sv",
"module third;\n // u_core0.state_q is mentioned here\n initial $display(\"u_core0.state_q\");\n // a bare state_q here is another module's word\nendmodule\n",
),
("m.sv", "module m (input logic a, output logic q);\n /* q */ assign q = a;\nendmodule\n"),
];
@@ -285,7 +288,9 @@ const MACRO_ARG: &[(&str, &str)] = &[
fn qa_uses_never_include_a_comment_a_string_or_macro_text() {
let scratch = Scratch::with(MACRO_ARG);
let mut s = Session::ready(&scratch);
// `third.sv` writes the word only in a comment and a string; `top.sv`
// `third.sv` writes the word only in a comment and a string (dotted —
// a bare spelling in a file that neither declares nor uses the member
// is not listed since §65.1's scoping of mentions); `top.sv`
// only inside a macro call's argument, which the engine does not follow:
// those are the unresolved mentions, never uses.
assert_eq!(
+21
View File
@@ -444,6 +444,24 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
assert_eq!(fs::read_to_string(&file).unwrap(), "keep me\n");
}
/// Whether file modes bind this process: a mode-000 directory refuses to be
/// listed. Root lists it anyway (Linux CI jobs run as root), so there a cache
/// directory without permission cannot be built; the test says so and stops.
#[cfg(unix)]
fn listing_is_refused(scratch: &Scratch) -> bool {
use std::os::unix::fs::PermissionsExt;
let shut = scratch.0.join("mode-probe");
fs::create_dir_all(&shut).unwrap();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o000)).unwrap();
let refused = fs::read_dir(&shut).is_err();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
fs::remove_dir_all(&shut).unwrap();
if !refused {
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
}
refused
}
/// A cache directory with no permissions at all (mode 000, holding a whole
/// honest editor store): nothing can be read, so the start is cold; the
/// answers are right; the exit says it could not write, once; the store in
@@ -453,6 +471,9 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
fn qa_a_cache_directory_without_permission_is_a_cold_start_that_answers() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
if !listing_is_refused(&scratch) {
return;
}
let (cold, _) = probe(&scratch, None);
scratch.write_editor_store(&honest_store(&scratch));
let before = hash_file(&scratch.editor_store());
+78 -16
View File
@@ -197,7 +197,7 @@ fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
let expected = [
(300, 101), // the root line + 400 instances
(300, 100), // 400 instantiations
(299, 251), // root + 149 two-line blocks; the 150th block would pass 300
(199, 301), // root + 99 two-line blocks: with peek the cap is 100 nodes
(300, 23), // counts line + 322 tops
(300, 20), // 320 declarations
(300, 51), // file:line + 350 ports
@@ -220,9 +220,11 @@ fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
assert_eq!(file, "rtl/big.sv");
number.parse::<u32>().unwrap();
}
// A peek block is never split: the last shown line is a statement.
// A peek block is never split: the last shown line is the 99th
// instance's statement.
let peek: Vec<&str> = said[2].text.lines().collect();
assert_eq!(peek[298], " leaf u_148 (.a(a));");
assert_eq!(peek[197], " u_098: leaf rtl/big.sv:101");
assert_eq!(peek[198], " leaf u_098 (.a(a));");
for line in said[7].text.lines().take(200) {
assert!(line.starts_with("rtl/wide.sv:") && line.ends_with("[unused-signal]"), "{line}");
}
@@ -715,17 +717,19 @@ fn qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit() {
#[test]
fn qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind() {
// `find g_lane refs` lists no use and `rename` answers `renamed 1 site`,
// leaving `g_lane[0].lane_q` naming a block that no longer exists —
// while `edit_item delete g_lane` sees the use (`rtl/fsm.sv:19:18`).
// `find g_lane refs` used to list no use and `rename` answered `renamed
// 1 site`, leaving `g_lane[0].lane_q` naming a block that no longer
// existed — while `edit_item delete g_lane` saw the use
// (`rtl/fsm.sv:19:18`). Lead's ruling R1 had the MCP layer refuse the
// rename; TODO §65.1 fixed the engine (a path segment through a block is
// a reference to its label), and the refusal is lifted.
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
// Lead's ruling R1: the MCP layer refuses the rename, and the source
// is untouched.
let said = session(&tree, &[("rename", json!({"name": "g_lane", "new_name": "g_ln"}))]);
assert!(said[0].refused, "{}", said[0].text);
let why = &said[0].text;
assert!(why.starts_with("`rename` does not rename generate block labels"), "{why}");
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS);
let found = text(&tree, "find", json!({"name": "g_lane", "refs": true}));
assert_eq!(found, "block g_lane rtl/fsm.sv:12\n rtl/fsm.sv:19\n");
let renamed = text(&tree, "rename", json!({"name": "g_lane", "new_name": "g_ln"}));
assert_eq!(renamed, "renamed 2 sites in 1 file\n");
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS.replace("g_lane", "g_ln"));
assert!(tree.read("rtl/fsm.sv").contains("busy = tmp | g_ln[0].lane_q;"));
}
#[test]
@@ -745,10 +749,15 @@ fn qa_rework_a_shared_base_name_is_named_by_path_or_left_alone() {
assert_eq!(text(&tree, "rename", one), "renamed 2 sites in 1 file\n");
assert!(tree.read("rtl/y/p1.sv").contains("logic d2;"));
assert!(tree.read("rtl/x/p1.sv").contains("logic dup;"));
// The engine's sentences: `p1.sv` is two files, so it stays as said;
// `p1b.sv` is one, so it is named by its path.
// The engine's sentences: `p1.sv` is two files, so the engine names it by
// the path it was given and the answer makes that root-relative (§65.1
// re-check R1 — it used to stay a bare, unplaceable `p1.sv`); `p1b.sv`
// is one, so it is named by its path too.
let added = text(&tree, "port", json!({"module": "sub", "add": "input logic zz"}));
assert!(added.contains("`u_s` at p1.sv:4 connects with `.*` and p1.sv has"), "{added}");
assert!(
added.contains("`u_s` at rtl/y/p1.sv:4 connects with `.*` and rtl/y/p1.sv has"),
"{added}"
);
assert!(added.contains("(rtl/z/p1b.sv:3)"), "{added}");
assert!(!added.contains("rtl/z/rtl/"), "{added}");
}
@@ -805,3 +814,56 @@ fn qa_rework_an_escaped_local_outline_lists_is_found() {
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
assert_eq!(text(&tree, "find", json!({"name": "\\loc.v"})), "var \\loc.v rtl/g.sv:3\n");
}
#[test]
fn a_rename_names_each_same_named_file_by_its_root_relative_path_once() {
// §65.1 re-check R1 and the lead's fifth ruling: two `x_if.sv` holding an
// unresolved path through the label are two findable warning lines, and
// neither line is repeated under `unresolved:`.
let probe = "module probe_IDX (output logic o);\n assign o = tb.dut.g_sw.q;\nendmodule\n";
let (a, b) = (probe.replace("IDX", "a"), probe.replace("IDX", "b"));
let tree = Tree::with(&[
("rtl/dut.sv", "module dut_x;\n if (1) begin : g_sw\n logic q;\n end\nendmodule\n"),
("dv/a/x_if.sv", a.as_str()),
("dv/b/x_if.sv", b.as_str()),
]);
let said = text(&tree, "rename", json!({"name": "g_sw", "new_name": "g_hw"}));
let path_lines: Vec<&str> =
said.lines().filter(|line| line.contains("a hierarchical path through")).collect();
assert_eq!(path_lines.len(), 2, "{said}");
assert!(path_lines[0].starts_with("warning: dv/a/x_if.sv:2: "), "{said}");
assert!(path_lines[1].starts_with("warning: dv/b/x_if.sv:2: "), "{said}");
assert!(!said.contains("unresolved:"), "each line is said once: {said}");
assert!(tree.read("rtl/dut.sv").contains("begin : g_hw"));
}
#[test]
fn a_members_rename_lists_only_its_own_mentions_and_dotted_ones_elsewhere() {
// §65.1, lead's inspection: two modules each with a `state_q`, each
// spelling it in an `ASSERT argument, a comment and a string. Renaming
// `a`'s warns and lists only `a`'s — plus `b`'s dotted spellings, which
// may be paths to it. A package-level name still lists everything.
let defs = "`define ASSERT(n, e) n: assert property (e);\n";
let a = "module a (input logic clk);\n logic state_q;\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(A_T, state_q)\n // state_q is a's\n initial $display(\"state_q\");\nendmodule\n";
let b = "module b (input logic clk);\n logic state_q;\n a u_a (.clk);\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(B_T, state_q)\n `ASSERT(B_P, u_a.state_q)\n // state_q is b's\n initial $display(\"state_q\");\n initial $display(\"u_a.state_q\");\nendmodule\n";
let pkg = "package p;\n localparam int W = 1;\nendpackage\n";
let user = "module u import p::*;\n // W is p's\n localparam int X = W;\nendmodule\n";
let tree = Tree::with(&[
("rtl/defs.svh", defs),
("rtl/a.sv", a),
("rtl/b.sv", b),
("rtl/p.sv", pkg),
("rtl/u.sv", user),
]);
let said = text(&tree, "rename", json!({"name": "a.state_q", "new_name": "state_r"}));
let macro_lines: Vec<&str> = said.lines().filter(|l| l.contains("macro invocation")).collect();
assert_eq!(macro_lines.len(), 2, "{said}");
assert!(
macro_lines[0].contains("rtl/a.sv:4") && macro_lines[1].contains("rtl/b.sv:6"),
"{said}"
);
assert!(said.ends_with("unresolved:\n rtl/a.sv:4,5,6\n rtl/b.sv:6,9\n"), "{said}");
assert!(tree.read("rtl/b.sv").contains("logic state_q;"), "b's own stays");
let found = text(&tree, "find", json!({"name": "p.W", "refs": true}));
assert!(found.contains("unresolved:\n rtl/u.sv:2\n"), "a package member lists all: {found}");
}
+557
View File
@@ -0,0 +1,557 @@
//! QA attacks on lane M8 (`--read-only`), 2026-09-29.
//!
//! Every test copies a fixture into its own scratch directory, spawns the
//! real binary over it, writes a whole session to stdin, closes it and reads
//! every answer — the host's view, nothing else. The no-write promise is
//! checked by a snapshot of every entry under the root: a file's size, mtime
//! and bytes, a directory's mtime (which moves when anything is created,
//! renamed or removed in it, a temporary file included).
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::SystemTime;
use serde_json::{json, Value};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// The message a read-only server refuses `name` with.
fn refused(name: &str) -> String {
format!("unknown tool: {name} (the server runs --read-only)")
}
/// A scratch directory, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn empty() -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-m8-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Tree(fs::canonicalize(dir).unwrap())
}
/// A fresh copy of `tests/fixtures/<fixture>`.
fn of(fixture: &str) -> Tree {
let tree = Tree::empty();
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
copy_tree(&source, &tree.0);
tree
}
fn arg(&self) -> &str {
self.0.to_str().unwrap()
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// One entry under a root: a file's size, mtime and bytes; a directory's mtime.
type Entry = (Option<u64>, SystemTime, Option<Vec<u8>>);
fn snapshot(tree: &Tree) -> BTreeMap<String, Entry> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Entry>) {
let relative = |path: &Path| path.strip_prefix(root).unwrap().to_string_lossy().to_string();
let meta = fs::symlink_metadata(dir).unwrap();
out.insert(format!("{}/", relative(dir)), (None, meta.modified().unwrap(), None));
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let meta = fs::symlink_metadata(&path).unwrap();
if meta.is_dir() {
walk(&path, root, out);
} else {
let bytes = fs::read(&path).unwrap();
out.insert(
relative(&path),
(Some(meta.len()), meta.modified().unwrap(), Some(bytes)),
);
}
}
}
let mut out = BTreeMap::new();
walk(&tree.0, &tree.0, &mut out);
out
}
/// Run the binary with `args`, send `lines` (one JSON-RPC message each),
/// close stdin and wait for it to exit.
fn run(args: &[&str], lines: &[Value]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
for line in lines {
// A raw line is passed as a JSON string, everything else serialised.
let text = match line {
Value::String(raw) => raw.clone(),
other => other.to_string(),
};
writeln!(stdin, "{text}").unwrap();
}
drop(stdin);
child.wait_with_output().unwrap()
}
/// Every answer on stdout, by its id as JSON text (`"\"c\""`, `null`).
fn answers(output: &Output) -> BTreeMap<String, Value> {
let stdout = String::from_utf8(output.stdout.clone()).unwrap();
let mut out = BTreeMap::new();
for line in stdout.lines().filter(|l| !l.trim().is_empty()) {
let reply: Value = serde_json::from_str(line).expect("every stdout line is JSON");
out.entry(reply["id"].to_string()).or_insert(reply);
}
out
}
fn request(id: &str, method: &str, params: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
}
fn call(id: &str, name: Value, arguments: Value) -> Value {
request(id, "tools/call", json!({"name": name, "arguments": arguments}))
}
fn initialize(id: &str) -> Value {
request(id, "initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}))
}
/// Every shape of every edit tool, each a real write in full mode
/// (`qa_every_edit_shape_writes_in_full_mode`), on the `edit` fixture.
fn edit_shapes() -> Vec<(&'static str, Value)> {
vec![
("rename", json!({"name": "leaf", "new_name": "leaf2"})),
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
("port", json!({"module": "spare", "add": "input logic en"})),
("port", json!({"module": "spare", "add": "input logic en2", "after": "clk"})),
("port", json!({"module": "spare", "remove": "unused_i"})),
(
"edit_item",
json!({"file": "rtl/mid.sv", "op": "replace", "item": "u_leaf", "text": "leaf u_leaf (.clk(clk), .d(din), .q(dout));"}),
),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_b;"}),
),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_after", "item": "end", "text": "logic spare_a;"}),
),
("edit_item", json!({"file": "rtl/spare_user.sv", "op": "delete", "item": "spare_user"})),
("format", json!({"files": "fmt/messy.sv"})),
("format", json!({"files": "fmt/messy.sv", "fix": true})),
("format", json!({"files": "**/*.sv", "fix": true})),
("format", json!({"files": "rtl"})),
]
}
#[test]
fn qa_every_edit_shape_writes_in_full_mode() {
// The control for the promise: each shape really edits without the flag.
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let lines = [initialize("i"), call("c", json!(name), arguments.clone())];
let output = run(&["--root", tree.arg()], &lines);
let reply = &answers(&output)["\"c\""];
assert_eq!(reply["result"]["isError"], false, "{index} {name} {arguments}: {reply}");
assert_ne!(before, snapshot(&tree), "{index} {name} wrote nothing in full mode");
}
}
/// The malformed and near-miss calls a read-only server must refuse, each
/// with the code and message it must answer.
fn hostile_calls() -> Vec<(Value, i64, String)> {
let mut out = Vec::new();
// Names that differ from an edit tool by case, whitespace or spelling.
for name in [
"Rename",
"RENAME",
" rename",
"rename ",
"rename\n",
"rename\u{0}",
"edit-item",
"editItem",
"Format",
"port ",
"\u{ff52}ename",
"format\t",
] {
out.push((call(&format!("n{}", out.len()), json!(name), json!({})), -32602, refused(name)));
}
// A name that is not a string.
let not_string = "tools/call params need a string `name`".to_string();
for name in [json!(6), json!(["rename"]), json!({"name": "rename"}), json!(null), json!(true)] {
out.push((call(&format!("t{}", out.len()), name, json!({})), -32602, not_string.clone()));
}
// An edit name with malformed or smuggled arguments.
// The name is looked up before the arguments are read.
for arguments in
[json!(null), json!([]), json!("x"), json!({"name": 1}), json!({"mode": "full"})]
{
let line = call(&format!("a{}", out.len()), json!("rename"), arguments);
out.push((line, -32602, refused("rename")));
}
let meta = request(
"meta",
"tools/call",
json!({"name": "format", "arguments": {"files": "rtl"}, "_meta": {"mode": "full"}, "mode": "full"}),
);
out.push((meta, -32602, refused("format")));
out
}
#[test]
fn qa_read_only_never_changes_a_byte_whatever_arrives() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let mut lines = Vec::new();
// Before `initialize`: refused as not initialized, never run.
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
lines.push(call(&format!("early{index}"), json!(name), arguments));
}
lines.push(initialize("init"));
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
// Every edit shape as a request and as a notification (no id).
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
lines.push(call(&format!("edit{index}"), json!(name), arguments.clone()));
let params = json!({"name": name, "arguments": arguments});
lines.push(json!({"jsonrpc": "2.0", "method": "tools/call", "params": params}));
lines.push(
json!({"jsonrpc": "2.0", "method": format!("notifications/{name}"), "params": params}),
);
}
let hostile = hostile_calls();
lines.extend(hostile.iter().map(|(line, _, _)| line.clone()));
// A batch, a duplicate `name` key, a second `initialize` asking for more.
lines.push(json!([call("batched", json!("format"), json!({"files": "rtl"}))]));
lines.push(json!(r#"{"jsonrpc":"2.0","id":"dup","method":"tools/call","params":{"name":"check","name":"format","arguments":{"files":"rtl"}}}"#));
lines.push(request(
"reinit",
"initialize",
json!({"capabilities": {"experimental": {"mode": "full"}}}),
));
lines.push(call("after-reinit", json!("format"), json!({"files": "rtl"})));
for uri in [
"lucisv://overview",
"lucisv://rules",
"lucisv://unit/leaf",
"lucisv://unit/spare",
"lucisv://file/rtl/leaf.sv/outline",
"lucisv://file/fmt%2Fmessy.sv/outline",
"lucisv://format/fmt/messy.sv",
"lucisv://unit/..%2F..%2Fetc",
] {
lines.push(request(&format!("res {uri}"), "resources/read", json!({"uri": uri})));
}
for method in ["notifications/cancelled", "notifications/roots/list_changed", "notifications/x"]
{
lines.push(json!({"jsonrpc": "2.0", "method": method, "params": {"requestId": "edit0"}}));
}
lines.push(call("still", json!("check"), json!({})));
let output = run(&["--root", tree.arg(), "--read-only"], &lines);
assert!(output.status.success(), "{:?}", output.status);
let answers = answers(&output);
for index in 0..edit_shapes().len() {
assert_eq!(answers[&format!("\"early{index}\"")]["error"]["code"], -32002);
}
for (index, (name, _)) in edit_shapes().into_iter().enumerate() {
let reply = &answers[&format!("\"edit{index}\"")];
assert_eq!(reply["error"]["code"], -32602, "{reply}");
assert_eq!(reply["error"]["message"], refused(name), "{reply}");
}
for (line, code, message) in &hostile {
let reply = &answers[&line["id"].to_string()];
assert_eq!(reply["error"]["code"], *code, "{line} -> {reply}");
assert_eq!(reply["error"]["message"], *message, "{line} -> {reply}");
}
assert_eq!(answers["null"]["error"]["code"], -32600, "the batch is refused");
assert_eq!(answers["\"dup\""]["error"]["message"], refused("format"), "last key wins");
assert_eq!(answers["\"after-reinit\""]["error"]["message"], refused("format"));
assert_eq!(answers["\"still\""]["result"]["isError"], false);
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
}
/// The first `tools/list` answer's tool names for a server started with `args`.
fn listed(args: &[&str]) -> (Option<Vec<String>>, Output) {
let output = run(args, &[initialize("i"), request("l", "tools/list", json!({}))]);
let names = answers(&output).get("\"l\"").map(|reply| {
let tools = reply["result"]["tools"].as_array().unwrap();
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
});
(names, output)
}
#[test]
fn qa_argument_order_and_repetition_cannot_undo_read_only() {
let tree = Tree::of("design");
let root = tree.arg();
let five = ["hierarchy", "find", "outline", "read", "check"].map(String::from).to_vec();
for args in [
vec!["--read-only", "--root", root],
vec!["--root", root, "--read-only", "--read-only"],
vec!["--read-only", "--verbose", "--root", root, "--read-only"],
] {
let (names, output) = listed(&args);
assert_eq!(names.as_ref(), Some(&five), "{args:?}: {output:?}");
}
// A value for the flag is refused by the usage rule, never read as full.
for args in [
vec!["--root", root, "--read-only=false"],
vec!["--root", root, "--read-only", "false"],
vec!["--root", root, "--read-only=true"],
vec!["--root", root, "--readonly"],
vec!["--root", root, "--no-read-only"],
] {
let (names, output) = listed(&args);
assert_eq!(names, None, "{args:?} started a server");
assert_eq!(output.status.code(), Some(2), "{args:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("unknown option") && stderr.contains("[--read-only]"), "{stderr}");
}
}
/// The text of every `tools/call` and `resources/read` answer, by id.
fn texts(args: &[&str], lines: &[Value]) -> BTreeMap<String, String> {
let mut session = vec![initialize("i")];
session.extend_from_slice(lines);
let output = run(args, &session);
let mut out = BTreeMap::new();
for (id, reply) in answers(&output) {
let result = &reply["result"];
let text = result["content"][0]["text"]
.as_str()
.or_else(|| result["contents"][0]["text"].as_str())
.map(str::to_string)
.unwrap_or_else(|| reply.to_string());
out.insert(id, text);
}
out.remove("\"i\"");
out
}
#[test]
fn qa_the_read_tools_and_resources_answer_identically_in_both_modes() {
let reads = [
("design", "hierarchy", json!({})),
("design", "hierarchy", json!({"root": "top", "depth": 3, "peek": true})),
("design", "find", json!({"name": "leaf", "refs": true})),
("design", "outline", json!({"file": "rtl/top.sv"})),
("design", "read", json!({"item": "top"})),
("design", "check", json!({})),
("design", "check", json!({"file": "rtl/broken.sv"})),
("design", "find", json!({"nome": "x"})),
("edit", "hierarchy", json!({"root": "leaf", "up": true})),
("edit", "outline", json!({"unit": "spare"})),
("edit", "check", json!({"file": "fmt/messy.sv"})),
("edit", "read", json!({"item": "u_leaf", "file": "rtl/mid.sv"})),
];
for fixture in ["design", "edit"] {
let tree = Tree::of(fixture);
let mut lines: Vec<Value> = reads
.iter()
.enumerate()
.filter(|(_, (f, _, _))| *f == fixture)
.map(|(index, (_, name, arguments))| {
call(&format!("r{index}"), json!(name), arguments.clone())
})
.collect();
for uri in ["lucisv://overview", "lucisv://rules", "lucisv://unit/leaf", "lucisv://nope"] {
lines.push(request(uri, "resources/read", json!({"uri": uri})));
}
for method in ["resources/list", "resources/templates/list", "prompts/list"] {
lines.push(request(method, method, json!({})));
}
let full = texts(&["--root", tree.arg()], &lines);
let read_only = texts(&["--root", tree.arg(), "--read-only"], &lines);
assert_eq!(full.len(), lines.len(), "{fixture}: {full:?}");
assert_eq!(full, read_only, "{fixture}");
}
}
#[test]
fn qa_a_read_only_index_cache_outside_the_root_leaves_the_root_alone() {
// The store is written where it is told (the extension's workspace
// storage); the root is not, even with the store beside it.
let parent = Tree::empty();
let root = parent.0.join("root");
copy_tree(&Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/edit"), &root);
let tree = Tree(root);
let cache = parent.0.join("cache");
let before = snapshot(&tree);
let lines = [
initialize("i"),
call("c", json!("format"), json!({"files": "rtl"})),
call("k", json!("check"), json!({})),
];
let output = run(
&["--root", tree.arg(), "--index-cache", cache.to_str().unwrap(), "--read-only"],
&lines,
);
assert!(output.status.success());
assert_eq!(before, snapshot(&tree));
assert!(cache.join(".gitignore").exists(), "the store directory was written");
}
// ---------------------------------------------------------------------------
// Re-check 2026-09-29: `hierarchy`'s cap counts nodes, never peek lines.
// ---------------------------------------------------------------------------
/// `module name` with `count` instances of `child`, each written over 14
/// lines (header, 12 port lines, closer), so each peek block is cut to 12
/// lines and `…` — 14 answer lines per node.
fn wide_parent(name: &str, child: &str, count: usize) -> (String, String) {
let mut text = format!("module {name};\n");
for i in 0..count {
text.push_str(&format!(" {child} u_{i:03} (\n"));
for p in 0..12 {
let comma = if p < 11 { "," } else { "" };
text.push_str(&format!(" .p{p}(1'b0){comma}\n"));
}
text.push_str(" );\n");
}
text.push_str("endmodule\n");
(format!("{name}.sv"), text)
}
/// A 12-input leaf module.
fn leaf(name: &str) -> (String, String) {
let ports: Vec<String> = (0..12).map(|p| format!("input logic p{p}")).collect();
(format!("{name}.sv"), format!("module {name} ({});\nendmodule\n", ports.join(", ")))
}
/// `dN` declares N instances (N + 1 nodes with its root line); `uN` is
/// instantiated N times (N nodes up). Sizes sit on both caps' boundaries:
/// 300/301 nodes without `peek`, 100/101 with it.
fn boundary_tree() -> Tree {
let tree = Tree::empty();
let files = [
leaf("x"),
leaf("y"),
leaf("u100"),
leaf("u101"),
leaf("u300"),
leaf("u301"),
wide_parent("d99", "x", 99),
wide_parent("d100", "y", 100),
wide_parent("d299", "x", 299),
wide_parent("d300", "y", 300),
wide_parent("h100", "u100", 100),
wide_parent("h101", "u101", 101),
wide_parent("h300", "u300", 300),
wide_parent("h301", "u301", 301),
];
for (path, text) in files {
fs::write(tree.0.join(path), text).unwrap();
}
tree
}
/// Each call's text, in order, from one session in `mode_args`.
fn hierarchy_texts(tree: &Tree, calls: &[Value], mode_args: &[&str]) -> Vec<String> {
let mut args = vec!["--root", tree.arg()];
args.extend_from_slice(mode_args);
let mut lines = vec![initialize("i")];
lines.extend(
calls
.iter()
.enumerate()
.map(|(n, a)| call(&format!("h{n}"), json!("hierarchy"), a.clone())),
);
let answers = answers(&run(&args, &lines));
(0..calls.len())
.map(|n| {
let reply = &answers[&format!("\"h{n}\"")];
assert_eq!(reply["result"]["isError"], false, "{reply}");
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
})
.collect()
}
/// The node cap without `peek` (PLAN §10.1).
const PLAIN_CAP: usize = 300;
/// The node cap with `peek` (M8 rework 3).
const PEEK_CAP: usize = 100;
#[test]
fn qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek() {
let tree = boundary_tree();
// (arguments, nodes in the whole answer, statement indent)
let cases = [
(json!({"root": "d99"}), 100, " "),
(json!({"root": "d100"}), 101, " "),
(json!({"root": "d299"}), 300, " "),
(json!({"root": "d300"}), 301, " "),
(json!({"root": "u100", "up": true}), 100, " "),
(json!({"root": "u101", "up": true}), 101, " "),
(json!({"root": "u300", "up": true}), 300, " "),
(json!({"root": "u301", "up": true}), 301, " "),
];
let mut calls = Vec::new();
for (arguments, _, _) in &cases {
calls.push(arguments.clone());
let mut peeked = arguments.clone();
peeked["peek"] = json!(true);
calls.push(peeked);
}
let full = hierarchy_texts(&tree, &calls, &[]);
assert_eq!(full, hierarchy_texts(&tree, &calls, &["--read-only"]), "the modes disagree");
for (at, (arguments, total, indent)) in cases.iter().enumerate() {
let root_lines = usize::from(arguments["up"] != true);
let cut_line = |cap: usize| (*total > cap).then(|| format!("… and {} more", total - cap));
// Without peek: one line per node, at most 300, then the cut line.
let plain: Vec<&str> = full[2 * at].lines().collect();
let (plain_shown, plain_cut) = ((*total).min(PLAIN_CAP), cut_line(PLAIN_CAP));
assert_eq!(plain.len(), plain_shown + usize::from(plain_cut.is_some()), "{arguments}");
if let Some(cut) = &plain_cut {
assert_eq!(plain.last().copied(), Some(cut.as_str()), "{arguments}");
}
// With peek: the first 100 of the same node lines, then its own cut line.
let peek: Vec<&str> = full[2 * at + 1].lines().collect();
let (shown, cut) = ((*total).min(PEEK_CAP), cut_line(PEEK_CAP));
let nodes: Vec<&str> = peek.iter().copied().filter(|l| !l.starts_with(indent)).collect();
let mut expected: Vec<&str> = plain[..shown].to_vec();
if let Some(cut) = &cut {
expected.push(cut.as_str());
}
assert_eq!(nodes, expected, "{arguments}");
// Every instance node is followed by a whole block: 12 lines, then `…`.
let instances = shown - root_lines;
let cut_lines = usize::from(cut.is_some());
assert_eq!(peek.len(), root_lines + instances * 14 + cut_lines, "{arguments}");
let blocks = peek.iter().filter(|l| l.trim() == "…").count();
assert_eq!(blocks, instances, "{arguments}");
if cut.is_some() {
// The block before the cut line is whole: it ends in `…`.
assert_eq!(peek[peek.len() - 2].trim(), "…", "{arguments}");
}
}
}
+341
View File
@@ -0,0 +1,341 @@
//! `lucisv-mcp --read-only` (PLAN §11), pinned against the real binary: the
//! five read tools within their budget, the edit tools unknown, full mode as
//! 0.58.0 shipped it, and the promise that nothing inside a root is created,
//! written, renamed or removed whatever is called.
use std::collections::BTreeMap;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::time::{Duration, SystemTime};
use serde_json::{json, Value};
/// How long one answer may take before the test calls the server hung.
const ANSWER_TIMEOUT: Duration = Duration::from_secs(60);
/// The five read tools, in the order `tools/list` gives them.
const FIVE: [&str; 5] = ["hierarchy", "find", "outline", "read", "check"];
/// The four edit tools full mode adds after them.
const EDITS: [&str; 4] = ["rename", "port", "edit_item", "format"];
/// The read-only ceilings (PLAN §11.1).
const CATALOGUE_BUDGET: usize = 1_800;
const INSTRUCTIONS_BUDGET: usize = 300;
/// The instructions 0.58.0 shipped (PLAN §10.3), which full mode keeps.
const FULL_INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A fresh directory under the system temp dir, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn empty() -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir()
.join(format!("lucisv-mcp-read-only-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Tree(fs::canonicalize(dir).unwrap())
}
/// A fresh copy of `tests/fixtures/<fixture>`.
fn of(fixture: &str) -> Tree {
let tree = Tree::empty();
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
copy_tree(&source, &tree.0);
tree
}
fn arg(&self) -> &str {
self.0.to_str().unwrap()
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// One running server.
struct Session {
child: Child,
stdin: Option<ChildStdin>,
lines: Receiver<String>,
next_id: i64,
}
impl Session {
fn spawn(args: &[&str]) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdout = child.stdout.take().unwrap();
let (send, lines) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
if send.send(line).is_err() {
break;
}
}
});
let stdin = child.stdin.take();
Session { child, stdin, lines, next_id: 0 }
}
/// A server over `tree`, in read-only mode unless `full`, initialised;
/// returns the `initialize` result too.
fn over(tree: &Tree, full: bool) -> (Session, Value) {
let mut args = vec!["--root", tree.arg()];
if !full {
args.push("--read-only");
}
let mut server = Session::spawn(&args);
let init = server.initialize();
(server, init)
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let id = self.next_id;
let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{line}").unwrap();
stdin.flush().unwrap();
let reply = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
let reply: Value = serde_json::from_str(&reply).expect("every stdout line is JSON");
assert_eq!(reply["id"], id, "answers come back in order");
reply
}
fn initialize(&mut self) -> Value {
let params = json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "read-only", "version": "0"}});
self.request("initialize", params)["result"].clone()
}
fn call(&mut self, tool: &str, arguments: Value) -> Value {
self.request("tools/call", json!({"name": tool, "arguments": arguments}))
}
/// Close stdin and wait for the server to exit (it writes its own index
/// store, when it has one, on the way out).
fn finish(mut self) {
drop(self.stdin.take());
let status = self.child.wait().unwrap();
assert!(status.success(), "{status}");
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// The tools a `tools/list` answer offers.
fn tools(server: &mut Session) -> Vec<Value> {
server.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().clone()
}
fn names(tools: &[Value]) -> Vec<String> {
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
}
/// What the model reads every session: name, description and schema of
/// every tool, compact JSON — the measure `wire.rs` budgets full mode by.
fn visible_bytes(tools: &[Value]) -> usize {
let visible: Vec<Value> = tools
.iter()
.map(|t| json!({"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]}))
.collect();
serde_json::to_string(&visible).unwrap().len()
}
#[test]
fn read_only_offers_the_five_read_tools_in_order_within_both_budgets() {
let tree = Tree::of("design");
let (mut server, init) = Session::over(&tree, false);
let instructions = init["instructions"].as_str().unwrap();
assert!(instructions.len() <= INSTRUCTIONS_BUDGET, "instructions: {}", instructions.len());
assert!(instructions.contains("it never edits"), "{instructions}");
for name in FIVE {
assert!(instructions.contains(name), "{name}: {instructions}");
}
let words: Vec<&str> = instructions.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
for name in EDITS {
assert!(!words.contains(&name), "{name}: {instructions}");
}
let offered = tools(&mut server);
assert_eq!(names(&offered), FIVE);
let bytes = visible_bytes(&offered);
assert!(bytes <= CATALOGUE_BUDGET, "the read-only catalogue is {bytes} bytes");
for tool in &offered {
assert_eq!(tool["annotations"]["readOnlyHint"], true, "{tool}");
}
// The same five, word for word and schema for schema, as full mode's.
let (mut full, _) = Session::over(&tree, true);
assert_eq!(offered[..], tools(&mut full)[..5]);
}
#[test]
fn an_edit_tool_in_read_only_mode_is_an_unknown_tool() {
let tree = Tree::of("edit");
let (mut server, _) = Session::over(&tree, false);
for (name, arguments) in edit_calls() {
let reply = server.call(name, arguments);
assert!(reply.get("result").is_none(), "{name}: {reply}");
assert_eq!(reply["error"]["code"], -32602, "{name}: {reply}");
assert_eq!(
reply["error"]["message"],
format!("unknown tool: {name} (the server runs --read-only)")
);
}
// A read tool still answers after the refusals.
let reply = server.call("check", json!({"file": "rtl/leaf.sv"}));
assert_eq!(reply["result"]["isError"], false, "{reply}");
}
#[test]
fn full_mode_is_the_nine_tools_and_the_058_instructions() {
let tree = Tree::of("design");
let (mut server, init) = Session::over(&tree, true);
assert_eq!(init["instructions"], FULL_INSTRUCTIONS);
let offered = tools(&mut server);
let expected: Vec<&str> = FIVE.iter().chain(EDITS.iter()).copied().collect();
assert_eq!(names(&offered), expected);
let reply = server.call("nope", json!({}));
assert_eq!(reply["error"]["message"], "unknown tool: nope");
}
// ---------------------------------------------------------------------------
// The promise: nothing inside a root changes, whatever is called.
// ---------------------------------------------------------------------------
/// A valid edit for each edit tool on the `edit` fixture — each one writes
/// in full mode (`the_edit_calls_write_in_full_mode`).
fn edit_calls() -> Vec<(&'static str, Value)> {
vec![
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
("port", json!({"module": "spare", "add": "input logic en"})),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_w;"}),
),
("format", json!({"files": "fmt/messy.sv", "fix": true})),
]
}
/// A plausible call of each read tool on the `edit` fixture.
fn read_calls() -> Vec<(&'static str, Value)> {
vec![
("hierarchy", json!({})),
("hierarchy", json!({"root": "top", "depth": 5, "peek": true})),
("hierarchy", json!({"root": "leaf", "up": true})),
("find", json!({"name": "d", "refs": true})),
("outline", json!({"file": "rtl/leaf.sv"})),
("outline", json!({"unit": "leaf"})),
("read", json!({"item": "leaf"})),
("check", json!({})),
("check", json!({"file": "fmt/messy.sv"})),
]
}
/// Every entry under a tree, root-relative: a file's size and mtime, a
/// directory's mtime (which moves when an entry is created, renamed or
/// removed in it, even a temporary one).
fn snapshot(tree: &Tree) -> BTreeMap<String, (Option<u64>, SystemTime)> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, (Option<u64>, SystemTime)>) {
let meta = fs::metadata(dir).unwrap();
let relative = dir.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
out.insert(format!("{relative}/"), (None, meta.modified().unwrap()));
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let meta = fs::metadata(&path).unwrap();
let relative =
path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
out.insert(relative, (Some(meta.len()), meta.modified().unwrap()));
}
}
}
let mut out = BTreeMap::new();
walk(&tree.0, &tree.0, &mut out);
out
}
#[test]
fn read_only_mode_never_touches_the_tree_whatever_is_called() {
let tree = Tree::of("edit");
let cache = Tree::empty();
let before = snapshot(&tree);
let args = ["--root", tree.arg(), "--index-cache", cache.arg(), "--read-only"];
let mut server = Session::spawn(&args);
server.initialize();
for (name, arguments) in read_calls().into_iter().chain(edit_calls()) {
let reply = server.call(name, arguments);
assert!(reply.get("result").is_some() || reply.get("error").is_some(), "{reply}");
}
// Every name again with no arguments, and with arguments it does not take.
for name in FIVE.iter().chain(EDITS.iter()) {
server.call(name, json!({}));
server.call(name, json!({"force": true, "dry_run": false}));
}
for method in ["resources/list", "resources/templates/list"] {
assert!(server.request(method, json!({})).get("result").is_some(), "{method}");
}
for uri in [
"lucisv://overview",
"lucisv://rules",
"lucisv://unit/leaf",
"lucisv://file/rtl/leaf.sv/outline",
] {
let reply = server.request("resources/read", json!({"uri": uri}));
assert!(reply.get("result").is_some(), "{uri}: {reply}");
}
server.finish();
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
// The server's own store is outside the roots, and still written.
assert!(fs::read_dir(&cache.0).unwrap().next().is_some(), "no index store was written");
}
#[test]
fn the_edit_calls_write_in_full_mode() {
// The control for the promise above: the same arguments are real edits.
for (name, arguments) in edit_calls() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let (mut server, _) = Session::over(&tree, true);
let reply = server.call(name, arguments);
assert_eq!(reply["result"]["isError"], false, "{name}: {reply}");
server.finish();
assert_ne!(before, snapshot(&tree), "{name} wrote nothing in full mode");
}
}
+10 -3
View File
@@ -795,7 +795,13 @@ fn rename_lists_the_old_names_unresolved_mentions() {
text.contains("\nwarning: `state_q` appears in the body of macro `SM_STATE`"),
"{text}"
);
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4,6\n"), "{text}");
// Line 6 is `tb.…state_q`, a path nothing resolves: the engine's own
// warning names it (§65.1 F1), so it is not repeated as a mention.
assert!(
text.contains("\nwarning: dv/probe_if.sv:6: a hierarchical path through `state_q`"),
"{text}"
);
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4\n"), "{text}");
// The hierarchical use in core.sv is renamed, so it is not a mention;
// the text the block names is left as it was.
assert!(read(&tree, "rtl/core.sv").contains("u_main_sm.main_state_q"));
@@ -894,12 +900,13 @@ fn engine_sentences_name_files_root_relative() {
assert_eq!(before, snapshot(&tree));
let added = server.text("port", json!({"module": "spare", "add": "input logic en"}));
assert!(added.contains("at `u_s` (rtl/spare_user.sv:5)"), "{added}");
// A base name two files share cannot be placed: left as the engine said.
// A base name two files share: the engine names it by its path (§65.1
// re-check R1), which the answer makes root-relative like any other.
let (tree, mut server) = served("edit");
fs::create_dir_all(tree.path("alt")).unwrap();
fs::write(tree.path("alt/cell.sv"), "module cell2; endmodule\n").unwrap();
let twice = refusal(&mut server, "port", json!({"module": "cell", "remove": "en"}));
assert!(twice.contains("inside `cell` at cell.sv:6"), "{twice}");
assert!(twice.contains("inside `cell` at rtl/cell.sv:6"), "{twice}");
}
#[test]
+404
View File
@@ -0,0 +1,404 @@
//! The preset `style = "auto"` last settled on, per document.
//!
//! Under `auto`, every formatting request needs a concrete preset, and
//! finding one means formatting the whole buffer once per preset. That is
//! fine for a whole-document format, which formats the whole buffer anyway,
//! but not for an on-type `;` or a selection, which would pay it on every
//! keystroke — and on a buffer that does not parse (exactly when on-type
//! runs), no preset can be found at all.
//!
//! So a whole-document format remembers the preset it used, and the range,
//! selection and on-type requests reuse it. Without a memory they resolve
//! once from the buffer — when it parses — and remember that. Without a
//! memory and without a parse they lay out in the default preset's layout,
//! as the formatter itself does. The memory is a small most-recent list.
//!
//! A remembered preset is only right while the buffer is still the text it
//! was resolved from, edited by hand. So it is **forgotten** whenever that
//! may no longer be true: the document is opened, closed, renamed or deleted;
//! it is formatted or laid out under a named style; and — for every document
//! — whenever the settings change or a `lucisv.toml` change is seen.
//! Forgetting costs one search on the next request; remembering wrongly would
//! lay the file out in a preset it no longer uses.
//!
//! A change that replaces the **whole** buffer (a reload from disk, an
//! external formatter, or every change of a full-sync client) marks the
//! entry *replaced* rather than dropping it: the next request resolves
//! afresh from the new text, and only if that text does not parse — so there
//! is nothing to resolve from — does it fall back to the old preset, which is
//! still a better guess than the default layout. A full-sync client's every
//! keystroke is such a change, and a half-typed buffer is exactly when
//! on-type runs; dropping the entry there would lose the file's preset at the
//! moment the memory exists for.
//! See `docs/features/format-styles/README.md`.
use std::collections::VecDeque;
use lsp_server::Notification;
use lsp_types::notification::{
DidChangeWatchedFiles, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, Notification as _,
};
use lsp_types::{
DeleteFilesParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, RenameFilesParams, TextDocumentContentChangeEvent, TextEdit, Uri,
};
use vlog_formatter::{format_auto, style, Config, Style};
use crate::format;
use crate::state::Document;
/// How many documents' presets are remembered.
const CAPACITY: usize = 64;
/// The presets of the most recently formatted documents, newest last.
#[derive(Default)]
pub struct AutoStyles {
recent: VecDeque<Entry>,
}
/// One remembered document.
struct Entry {
uri: Uri,
preset: Style,
/// A change replaced the whole buffer since `preset` was resolved, so it
/// is only a fallback: resolve again when the buffer parses.
replaced: bool,
}
impl AutoStyles {
/// Format a whole buffer. Under `auto` this resolves afresh and
/// remembers the preset it used; under a named style it is
/// [`format::formatting`].
pub fn format_document(
&mut self,
uri: &Uri,
doc: &Document,
config: &Config,
) -> Result<Option<TextEdit>, String> {
if !config.auto_style {
// Formatted under a named style, the buffer may now be in it.
self.forget(uri);
return format::formatting(doc, config);
}
let (formatted, preset) = format_auto(&doc.text, config).map_err(|e| e.to_string())?;
self.remember(uri, preset);
Ok(format::whole_document_edit(doc, formatted))
}
/// `config` made concrete for a range, selection or on-type request on
/// `doc`: unchanged under a named style; under `auto`, the remembered
/// preset, else the one the buffer resolves to (then remembered), else —
/// the buffer does not parse — the default preset's layout.
pub fn concrete(&mut self, uri: &Uri, doc: &Document, config: Config) -> Config {
if !config.auto_style {
self.forget(uri);
return config;
}
let held = self.recall(uri);
let preset = match held {
Some((preset, false)) => preset,
// Nothing trustworthy held: resolve from the buffer when it
// parses; otherwise the old preset if there is one, else the
// default layout. A fallback is never stored as fresh.
_ => match format_auto(&doc.text, &config) {
Ok((_, preset)) => {
self.remember(uri, preset);
preset
}
Err(_) => held.map_or(style::LUCISV, |(preset, _)| preset),
},
};
Config { style: preset, auto_style: false, ..config }
}
/// Whether nothing is remembered yet.
#[cfg(test)]
pub fn is_empty(&self) -> bool {
self.recent.is_empty()
}
/// Forget what a notification may have made stale: the document a
/// `didOpen`/`didClose` names, the old and new names of a renamed file,
/// a deleted file, and every document when a watched-file event names a
/// `lucisv.toml` or `.lucisv.toml`. Anything else is ignored.
pub fn notice(&mut self, notification: &Notification) {
let params = || notification.params.clone();
match notification.method.as_str() {
DidOpenTextDocument::METHOD => {
if let Ok(p) = serde_json::from_value::<DidOpenTextDocumentParams>(params()) {
self.forget(&p.text_document.uri);
}
}
DidCloseTextDocument::METHOD => {
if let Ok(p) = serde_json::from_value::<DidCloseTextDocumentParams>(params()) {
self.forget(&p.text_document.uri);
}
}
DidRenameFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<RenameFilesParams>(params()) {
self.forget_named(p.files.iter().flat_map(|f| [&f.old_uri, &f.new_uri]));
}
}
DidDeleteFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<DeleteFilesParams>(params()) {
self.forget_named(p.files.iter().map(|f| &f.uri));
}
}
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<DidChangeWatchedFilesParams>(params()) {
if p.changes.iter().any(|c| names_a_config(c.uri.as_str())) {
self.forget_all();
}
}
}
_ => {}
}
}
/// Mark `uri`'s entry replaced when a `didChange` replaced its whole
/// text: a change with no range (full sync), or one that starts at the
/// top and leaves nothing of the old text after it — `result` is exactly
/// its text.
pub fn changed(&mut self, uri: &Uri, changes: &[TextDocumentContentChangeEvent], result: &str) {
let rangeless = changes.iter().any(|c| c.range.is_none());
let from_the_top = changes.last().is_some_and(|c| {
c.range.is_some_and(|r| r.start.line == 0 && r.start.character == 0) && c.text == result
});
if rangeless || from_the_top {
if let Some(entry) = self.recent.iter_mut().find(|e| e.uri == *uri) {
entry.replaced = true;
}
}
}
/// Forget every document: the settings, or a `lucisv.toml`, changed.
pub fn forget_all(&mut self) {
self.recent.clear();
}
fn forget(&mut self, uri: &Uri) {
self.recent.retain(|e| e.uri != *uri);
}
fn forget_named<'a>(&mut self, uris: impl Iterator<Item = &'a String>) {
for uri in uris {
self.recent.retain(|e| e.uri.as_str() != uri);
}
}
/// The remembered preset, and whether it has been marked replaced.
fn recall(&self, uri: &Uri) -> Option<(Style, bool)> {
self.recent.iter().find(|e| e.uri == *uri).map(|e| (e.preset, e.replaced))
}
fn remember(&mut self, uri: &Uri, preset: Style) {
self.forget(uri);
if self.recent.len() == CAPACITY {
self.recent.pop_front();
}
self.recent.push_back(Entry { uri: uri.clone(), preset, replaced: false });
}
}
/// Whether a URI names a config file: `lucisv.toml` or `.lucisv.toml`.
fn names_a_config(uri: &str) -> bool {
let name = uri.rsplit('/').next().unwrap_or(uri);
lucisv_core::config::NAMES.contains(&name)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::Workspace;
use std::str::FromStr;
/// A google-formatted module: one port per line at a 4-space list indent.
const GOOGLE: &str = "\
module m (
input logic a,
output logic b
);
sub u_sub (
.a(a),
.b(b)
);
endmodule
";
fn open(text: &str) -> (Workspace, Uri) {
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
(ws, uri)
}
fn auto() -> Config {
Config::named("auto").expect("auto")
}
#[test]
fn a_whole_document_format_remembers_the_preset_it_used() {
let (ws, uri) = open(GOOGLE);
let mut styles = AutoStyles::default();
let doc = ws.document(&uri).expect("open");
assert_eq!(styles.format_document(&uri, doc, &auto()), Ok(None), "already formatted");
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)));
let concrete = styles.concrete(&uri, doc, auto());
assert_eq!((concrete.style, concrete.auto_style), (style::GOOGLE, false));
}
#[test]
fn a_named_style_is_left_alone_and_nothing_is_remembered() {
let (ws, uri) = open(GOOGLE);
let mut styles = AutoStyles::default();
let doc = ws.document(&uri).expect("open");
let ansi = Config::styled(style::ANSI);
assert_eq!(styles.concrete(&uri, doc, ansi.clone()).style, style::ANSI);
assert!(styles.format_document(&uri, doc, &ansi).is_ok());
assert_eq!(styles.recall(&uri), None);
}
/// The memory is what lets a half-typed buffer keep its file's preset:
/// without it, a buffer that does not parse gets the default's layout.
#[test]
fn a_buffer_that_does_not_parse_uses_the_remembered_preset() {
let broken = GOOGLE.replace("endmodule", " assign x = ;\nendmodule");
let (ws, uri) = open(&broken);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "no memory, no parse");
assert_eq!(styles.recall(&uri), None, "and a fallback is not remembered");
styles.remember(&uri, style::GOOGLE);
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
}
#[test]
fn without_a_memory_a_buffer_that_parses_resolves_once() {
let (ws, uri) = open(GOOGLE);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)), "resolved, then remembered");
}
#[test]
fn the_memory_is_bounded_and_keeps_the_most_recent() {
let mut styles = AutoStyles::default();
let uri = |n: usize| Uri::from_str(&format!("file:///rtl/m{n}.sv")).expect("uri");
for n in 0..CAPACITY + 10 {
styles.remember(&uri(n), style::NXP);
}
assert_eq!(styles.recent.len(), CAPACITY);
assert_eq!(styles.recall(&uri(0)), None, "the oldest is forgotten");
assert_eq!(styles.recall(&uri(CAPACITY + 9)), Some((style::NXP, false)));
// Remembering again moves a document to the back and replaces its preset.
styles.remember(&uri(10), style::ANSI);
styles.remember(&uri(10), style::GOOGLE);
assert_eq!(styles.recall(&uri(10)), Some((style::GOOGLE, false)));
assert_eq!(styles.recent.len(), CAPACITY);
}
fn notification(method: &str, params: serde_json::Value) -> Notification {
Notification { method: method.to_string(), params }
}
#[test]
fn open_close_rename_and_delete_forget_the_document() {
let mut styles = AutoStyles::default();
let (a, b) = (
Uri::from_str("file:///rtl/a.sv").expect("uri"),
Uri::from_str("file:///rtl/b.sv").expect("uri"),
);
let doc = |uri: &Uri| {
serde_json::json!({ "textDocument": {
"uri": uri, "languageId": "systemverilog", "version": 1, "text": "" } })
};
for method in [DidOpenTextDocument::METHOD, DidCloseTextDocument::METHOD] {
styles.remember(&a, style::GOOGLE);
styles.notice(&notification(method, doc(&a)));
assert_eq!(styles.recall(&a), None, "{method}");
}
styles.remember(&a, style::GOOGLE);
styles.remember(&b, style::NXP);
styles.notice(&notification(
DidRenameFiles::METHOD,
serde_json::json!({ "files": [{ "oldUri": a.as_str(), "newUri": b.as_str() }] }),
));
assert!(styles.is_empty(), "both names of a renamed file are forgotten");
styles.remember(&a, style::GOOGLE);
styles.notice(&notification(
DidDeleteFiles::METHOD,
serde_json::json!({ "files": [{ "uri": a.as_str() }] }),
));
assert_eq!(styles.recall(&a), None);
}
#[test]
fn a_config_file_change_or_a_settings_change_forgets_everything() {
let mut styles = AutoStyles::default();
let a = Uri::from_str("file:///rtl/a.sv").expect("uri");
let watched = |name: &str| {
notification(
DidChangeWatchedFiles::METHOD,
serde_json::json!({ "changes": [{ "uri": format!("file:///rtl/{name}"), "type": 2 }] }),
)
};
styles.remember(&a, style::GOOGLE);
styles.notice(&watched("other.sv"));
assert!(!styles.is_empty(), "a source file changing on disk says nothing about presets");
for name in ["lucisv.toml", ".lucisv.toml"] {
styles.remember(&a, style::GOOGLE);
styles.notice(&watched(name));
assert!(styles.is_empty(), "{name}");
}
styles.remember(&a, style::GOOGLE);
styles.forget_all();
assert!(styles.is_empty());
}
/// A whole-buffer change makes the entry a fallback: the next request
/// resolves from the new text if it parses, and keeps the old preset
/// only if it does not. A partial edit leaves the entry alone.
#[test]
fn a_whole_buffer_replacement_resolves_again_when_it_can() {
let lucisv =
"module m (input logic a, output logic b);\n sub u_sub (.a(a), .b(b));\nendmodule\n";
let (ws, uri) = open(lucisv);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
styles.remember(&uri, style::GOOGLE);
let edit: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({
"range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 2 } },
"text": " " })).expect("change");
styles.changed(&uri, &[edit], lucisv);
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE, "a partial edit");
let whole: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({ "text": lucisv })).expect("change");
styles.changed(&uri, std::slice::from_ref(&whole), lucisv);
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, true)));
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "resolved afresh");
assert_eq!(styles.recall(&uri), Some((style::LUCISV, false)));
// A full range from the top counts as a whole replacement too.
let ranged: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 3, "character": 0 } },
"text": lucisv })).expect("change");
styles.changed(&uri, &[ranged], lucisv);
assert_eq!(styles.recall(&uri), Some((style::LUCISV, true)));
}
#[test]
fn a_named_style_request_forgets_the_document() {
let (ws, uri) = open(GOOGLE);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
styles.remember(&uri, style::GOOGLE);
styles.concrete(&uri, doc, Config::styled(style::LUCISV));
assert_eq!(styles.recall(&uri), None, "a range under a named style");
styles.remember(&uri, style::GOOGLE);
let _ = styles.format_document(&uri, doc, &Config::styled(style::LUCISV));
assert_eq!(styles.recall(&uri), None, "a whole-document format under a named style");
}
}
+105 -9
View File
@@ -197,17 +197,86 @@ impl Candidates {
/// 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.
#[cfg(test)]
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.
#[cfg(test)]
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
self.take_index_tables(index);
self.set_words(path, words);
}
/// [`Candidates::update_words`] in two halves, for a caller that knows
/// which it needs: the word table patched by this file alone…
pub fn set_file_words(&mut self, path: &Path, words: Vec<String>) {
self.set_words(path, words);
}
/// …and the two index-derived tables re-derived for the names one file declared
/// before or declares now — `symbols` its units and connection members,
/// `macros` its `` `define``s ([`FileFacts::declared_names`]) — which are
/// the only entries its update can move.
///
/// Exact because every table here is one block per exact name ([`word_cmp`]
/// is total, so equal keys are equal names) and each block is read off
/// the index for that name alone: the unit block from the symbol listing
/// restricted to the name, in the listing's order and deduplicated the
/// same way; a module name present exactly when some unit of it is
/// instantiable; a macro's entry from its first definition in file order.
/// So a block re-derived here is the block a whole re-derivation gives,
/// and every other block is untouched by an update that does not name it.
///
/// [`FileFacts::declared_names`]: vlog_semantic::FileFacts::declared_names
pub fn refresh_names(
&mut self,
index: &WorkspaceIndex,
symbols: &HashSet<&str>,
macros: &HashSet<&str>,
) {
let (fresh, _) = unit_tables(index, index.symbols_named(symbols));
let mut held = std::mem::take(&mut self.units);
held.retain(|unit| !symbols.contains(unit.name.as_str()));
self.units = merge_by_name(held, fresh, |unit| unit.name.as_str());
self.unit_masks = self.units.iter().map(|unit| char_mask(&unit.name)).collect();
for name in symbols {
let instantiable = index.units(name).iter().any(|def| def.kind.is_instantiable());
match (self.modules.binary_search_by(|held| held.as_str().cmp(name)), instantiable) {
(Ok(at), false) => {
self.modules.remove(at);
}
(Err(at), true) => self.modules.insert(at, name.to_string()),
_ => {}
}
}
let mut fresh: Vec<Macro> = macros
.iter()
.filter_map(|name| index.find_define(name).first().map(|(_, define)| macro_of(define)))
.collect();
sort_by_name(&mut fresh, |m| m.name.as_str());
let mut held = std::mem::take(&mut self.macros);
held.retain(|m| !macros.contains(m.name.as_str()));
self.macros = merge_by_name(held, fresh, |m| m.name.as_str());
}
/// Every table, rendered for comparison — the equivalence witness the
/// incremental tests hold an updated workspace to a rebuilt one with.
#[cfg(test)]
pub fn fingerprint(&self) -> String {
let mut word_files: Vec<(&String, &usize)> = self.word_files.iter().collect();
word_files.sort();
let mut per_file: Vec<(&PathBuf, &Vec<String>)> = self.per_file.iter().collect();
per_file.sort();
format!(
"units {:?}\nunit_masks {:?}\nmodules {:?}\nmacros {:?}\nwords {:?}\n\
word_masks {:?}\nword_files {word_files:?}\nper_file {per_file:?}\n",
self.units, self.unit_masks, self.modules, self.macros, self.words, self.word_masks
)
}
/// [`Candidates::update_words`] for a batch of files — the form a scan
/// publishing what it has indexed so far uses.
///
@@ -715,7 +784,15 @@ fn char_mask(text: &str) -> u32 {
/// 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("");
unit_tables(index, index.workspace_symbols(""))
}
/// [`index_tables`] over a given part of the symbol listing — all of it, or
/// the names one update touched — in the listing's own order.
fn unit_tables(
index: &WorkspaceIndex,
symbols: Vec<vlog_semantic::WorkspaceSymbol<'_>>,
) -> (Vec<Candidate>, Vec<String>) {
// `workspace_symbols` sorts by name first — with `str`'s own `Ord`, not a
// case-folded one — so same-named declarations are already adjacent and a
// plain `dedup` leaves one entry per module name, in `str` order. That is
@@ -757,14 +834,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
for id in 0..index.files().len() {
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
out.push(Macro {
name: define.name.clone(),
detail: format!("`define {}{args}", define.name),
});
out.push(macro_of(define));
}
}
sort_by_name(&mut out, |m| m.name.as_str());
@@ -772,6 +842,31 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
out
}
/// One `` `define``'s completion entry.
fn macro_of(define: &vlog_parser::defines::Define) -> Macro {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
Macro { name: define.name.clone(), detail: format!("`define {}{args}", define.name) }
}
/// Two lists sorted by [`word_cmp`] with no name in common, as one.
fn merge_by_name<T>(held: Vec<T>, fresh: Vec<T>, name: impl Fn(&T) -> &str) -> Vec<T> {
let mut out = Vec::with_capacity(held.len() + fresh.len());
let mut fresh = fresh.into_iter().peekable();
for item in held {
while let Some(next) =
fresh.next_if(|next| word_cmp(name(next), name(&item)) == Ordering::Less)
{
out.push(next);
}
out.push(item);
}
out.extend(fresh);
out
}
/// Every distinct identifier one file's token stream contains.
///
/// **`vlog_semantic::words::harvest_text`, under this crate's old name.** The
@@ -786,6 +881,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
/// 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`).
#[cfg(test)]
pub(crate) fn words_in(text: &str) -> Vec<String> {
words::harvest_text(text)
}
@@ -0,0 +1,144 @@
//! Tiers 2 and 3: what the buffer being typed in declares, and the words it
//! uses (TODO §68.1, `completion-ux`).
//!
//! The current file first: a name this buffer declares anywhere — in another
//! module, a sibling block, a function three screens down — and then a word
//! it merely uses, both ahead of what other files declare and ahead of the
//! templates and keywords. Both are read from the buffer's own `Semantics`
//! and token stream, recomputed on every change, so an unsaved declaration
//! ranks as soon as it is typed. Tier 1 (the scope chain) still comes first:
//! what is visible at the cursor is a better answer than what is merely in
//! the file.
use std::collections::HashSet;
use lsp_types::CompletionItemKind;
use vlog_parser::token::TokenKind;
use vlog_semantic::Symbol;
use super::word::Word;
use super::{completion_kind, declaration_detail, Items, TIER_BUFFER_WORD, TIER_DECLARED};
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query};
use crate::state::Document;
/// Tier 2: every declaration in the buffer, whatever scope holds it.
pub(super) fn declared_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
let symbols: Vec<&Symbol> = doc.semantics.symbols().iter().collect();
for symbol in matching(symbols, |symbol| symbol.name.as_str(), word, fuzzy) {
if items.full() {
break;
}
items.simple(
&symbol.name,
completion_kind(symbol.kind),
TIER_DECLARED,
declaration_detail(doc, symbol),
);
}
}
/// Tier 3: every identifier the buffer's token stream holds, except the one
/// being typed — offering the user their own half-word back is noise.
pub(super) fn buffer_word_tier(
items: &mut Items,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
if items.full() {
return;
}
let mut seen = HashSet::new();
let words: Vec<&str> =
buffer_words(doc, word.start).filter(|name| seen.insert(*name)).collect();
for name in matching(words, |name| name, word, fuzzy) {
if items.full() {
break;
}
items.simple(name, CompletionItemKind::TEXT, TIER_BUFFER_WORD, "used in this file".into());
}
}
/// The candidates `word` reaches, in the order they are offered: by prefix
/// below the fuzzy floor (in the buffer's own order), ranked by subsequence
/// score from it up — the house rule every tier applies.
fn matching<'a, T: Copy + 'a>(
candidates: Vec<T>,
name: impl Fn(T) -> &'a str,
word: &Word,
fuzzy: Option<&Query>,
) -> Vec<T> {
match fuzzy {
None => candidates
.into_iter()
.filter(|c| starts_with_ignore_case(name(*c), &word.text))
.collect(),
Some(query) => {
let mut hits: Vec<(T, _)> =
candidates.into_iter().filter_map(|c| Some((c, query.score(name(c))?))).collect();
hits.sort_by(|a, b| rank_cmp((name(a.0), a.1), (name(b.0), b.1)));
hits.into_iter().map(|(c, _)| c).collect()
}
}
}
/// Every identifier the buffer holds, as the project-word tier counts one —
/// `Ident` and `SystemIdent` only, neither a macro usage nor an escaped
/// identifier — but not the token starting at `typing`, the word under the
/// cursor.
fn buffer_words(doc: &Document, typing: u32) -> impl Iterator<Item = &str> {
doc.tokens
.iter()
.filter(move |token| token.span.start != typing)
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
.map(|token| token.text.as_str())
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
}
#[cfg(test)]
mod tests {
use crate::completion::harness::*;
use crate::completion::*;
const TOP: &str = "\
module top;
logic data_q;
always_comb begin
da
end
endmodule
module other;
logic data_other;
assign data_word = 1;
always_comb al_used = 0;
endmodule
";
#[test]
fn this_files_declarations_and_words_rank_after_the_scope_and_before_other_files() {
let (_tree, ws, uri, position) = asking("bufferrank", TOP, " da");
let items = items(completions(&ws, &uri, position, true));
let tier_of = |label: &str| tier(find(&items, label).unwrap_or_else(|| panic!("{label}")));
assert_eq!(tier_of("data_q"), TIER_SCOPE, "visible at the cursor");
assert_eq!(tier_of("data_other"), TIER_DECLARED, "declared in another module of this file");
assert_eq!(tier_of("data_word"), TIER_BUFFER_WORD, "only used in this file");
assert_eq!(tier_of("data"), TIER_INDEX, "a port only `sub.sv` declares");
assert!(TIER_SCOPE < TIER_DECLARED && TIER_DECLARED < TIER_BUFFER_WORD);
assert!(TIER_BUFFER_WORD < TIER_INDEX && TIER_INDEX < TIER_TEMPLATE);
assert!(TIER_TEMPLATE < TIER_KEYWORD && TIER_KEYWORD < TIER_WORD);
}
#[test]
fn a_word_this_file_uses_sorts_ahead_of_the_keywords() {
let top = TOP.replace(" da\n", " al\n");
let (_tree, ws, uri, position) = asking("bufferkw", &top, " al");
let items = items(completions(&ws, &uri, position, true));
let sort = |label: &str| {
find(&items, label)
.and_then(|i| i.sort_text.clone())
.unwrap_or_else(|| panic!("{label}"))
};
assert!(sort("al_used") < sort("always"), "{items:#?}");
assert!(sort("al_used") < sort("always_ff"));
}
}
@@ -0,0 +1,102 @@
//! What a connection-list entry inserts (TODO §68.1, `completion-ux`).
//!
//! After the `.` of `sub u_sub (.cl|` or `sub #(.WI|`, accepting a port or a
//! parameter writes the whole entry — `.clk(|)` with the cursor inside the
//! parentheses — rather than the bare name. When the instantiating scope can
//! see a net, variable or port of the same name (a parameter, for the
//! parameter list), it is pre-filled as the placeholder: `.clk(${1:clk})`,
//! one Tab to keep it, one keystroke to replace it.
//!
//! The bare name stays the answer where the snippet would be wrong: a client
//! that never said it reads snippets, a `(` already written after the word
//! being replaced (re-editing `.clk(x)`'s name), and a name the snippet
//! grammar would have to escape (an escaped identifier).
use std::collections::HashSet;
use vlog_semantic::SymbolKind;
use super::snippet_hole;
use super::tiers::visible_symbols;
use super::word::Word;
use crate::signature;
use crate::state::Document;
/// A connection-list entry, beyond its name.
pub(super) struct Connection {
/// Whether the list already connects this port elsewhere — it sorts after
/// the rest and is marked `connected`.
pub(super) connected: bool,
/// The snippet accepting it writes, or `None` for the bare name.
pub(super) snippet: Option<String>,
}
/// Everything about the cursor's entry that every candidate's insertion
/// shares: whether to write the parentheses, and the names a placeholder may
/// be pre-filled with.
pub(super) struct EntrySite<'a> {
wrap: bool,
visible: HashSet<&'a str>,
}
impl<'a> EntrySite<'a> {
/// The entry being typed at `word`, in a list of `kind`.
pub(super) fn new(
doc: &'a Document,
word: &Word,
kind: signature::Kind,
snippets: bool,
) -> EntrySite<'a> {
let wrap = snippets && !paren_follows(&doc.text, word.start);
let admits = |symbol_kind: SymbolKind| match kind {
signature::Kind::Ports => {
matches!(symbol_kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port)
}
signature::Kind::Params => {
matches!(symbol_kind, SymbolKind::Param | SymbolKind::LocalParam)
}
};
let visible = match wrap {
true => visible_symbols(&doc.semantics, word.start)
.into_iter()
.filter(|symbol| admits(symbol.kind))
.map(|symbol| symbol.name.as_str())
.collect(),
false => HashSet::new(),
};
EntrySite { wrap, visible }
}
/// The entry for the port or parameter `name`.
pub(super) fn connection(&self, name: &str, connected: bool) -> Connection {
let plain = name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
let snippet = (self.wrap && plain).then(|| {
let fill = if self.visible.contains(name) { name } else { "" };
format!("{name}({})", snippet_hole(1, fill))
});
Connection { connected, snippet }
}
}
/// Whether a `(` follows the identifier run that starts at `start`, past any
/// spaces or tabs — the entry is already written and only its name is being
/// re-edited.
fn paren_follows(text: &str, start: u32) -> bool {
let Some(rest) = text.get(start as usize..) else { return false };
let rest = rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$');
rest.trim_start_matches([' ', '\t']).starts_with('(')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_paren_after_the_word_means_the_entry_is_already_written() {
assert!(paren_follows(".clk(x)", 1));
assert!(paren_follows(".cl (x)", 1));
assert!(!paren_follows(".cl", 1));
assert!(!paren_follows(".cl\n (x)", 1), "only on the same line");
assert!(!paren_follows(".cl, .b(x)", 1));
}
}
+125 -38
View File
@@ -16,6 +16,7 @@ use lsp_types::CompletionResponse;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
use super::connection::{self, Connection};
use super::site::balanced;
use super::tiers::innermost_scope;
use super::word::{Sep, Word};
@@ -54,6 +55,7 @@ pub(super) fn member_answer(
doc: &Document,
word: &Word,
offset: u32,
snippets: bool,
) -> Option<CompletionResponse> {
let members = match word.spine.as_ref() {
Some(spine) => {
@@ -69,7 +71,7 @@ pub(super) fn member_answer(
// question, and it is the commonest completion position in RTL there
// is: a `.` opening a connection or a parameter override.
None => match word.sep? {
Sep::Dot => connection_members(ws, doc, word)?,
Sep::Dot => connection_members(ws, doc, word, snippets)?,
Sep::Scope => return None,
},
};
@@ -77,7 +79,7 @@ pub(super) fn member_answer(
// Prefix below [`FUZZY_MIN`], subsequence from it up — the house rule, on
// the same `Query` every other tier scores with.
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
let matched: Vec<Member> = match &fuzzy {
let mut matched: Vec<Member> = match &fuzzy {
None => members
.into_iter()
.filter(|member| starts_with_ignore_case(&member.name, &word.text))
@@ -95,12 +97,20 @@ pub(super) fn member_answer(
}
};
// A connection list's already-connected ports go after the rest, each
// group in the order it was matched in (`completion-ux`, TODO §68.1).
matched.sort_by_key(|member| member.connection.as_ref().is_some_and(|c| c.connected));
let mut items = Items::new(doc, word.range(offset));
for member in matched {
if items.full() {
break;
}
items.simple(&member.name, completion_kind(member.kind), TIER_MEMBER, member.detail);
let kind = completion_kind(member.kind);
match member.connection {
Some(connection) => items.connection(&member.name, kind, member.detail, connection),
None => items.simple(&member.name, kind, TIER_MEMBER, member.detail),
}
}
// **The `isIncomplete` trap, in its member form.** The request that
// matters is the one the trigger character fires, with nothing typed
@@ -132,6 +142,9 @@ struct Member {
name: String,
kind: SymbolKind,
detail: String,
/// What a connection list's entry carries beyond its name; `None` for
/// every other member.
connection: Option<Connection>,
}
/// What a member declared **in another file** shows beside its name.
@@ -225,10 +238,17 @@ fn members_at(
/// list to what may legally be written; it never offers a name the
/// resolution could not find.
///
/// Ports already connected earlier in the same list are dropped. `None` — no
/// Ports already connected elsewhere in the same list stay on offer, marked
/// (`completion-ux`, 2026-11-17 — they used to be dropped), and every entry
/// carries the `.name($1)` snippet [`connection::entry`] spells. `None` — no
/// popup — when the cursor is not in such a list at all, or is inside a
/// connected *expression* (`.clk(` opens a paren of its own).
fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec<Member>> {
fn connection_members(
ws: &Workspace,
doc: &Document,
word: &Word,
snippets: bool,
) -> Option<Vec<Member>> {
let dot = word.start.checked_sub(1)?;
let list = signature::enclosing_list(&doc.tokens, word.start)?;
let open = doc.tokens.get(list.open)?.span.end;
@@ -250,27 +270,33 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
signature::Kind::Ports => SymbolKind::Port,
};
let taken = connected_names(&doc.tokens, list.open, dot);
let entry = connection::EntrySite::new(doc, word, list.kind, snippets);
let mut members = Members::new();
let mut push = |name: &str, kind: SymbolKind, detail: String| {
let connection = entry.connection(name, taken.contains(name));
members.push_member(Member {
name: name.to_string(),
kind,
detail,
connection: Some(connection),
});
};
match doc.semantics.instantiable_scope(&list.module) {
// This file declares the module: its own scope is the whole answer,
// and no other file's module of the same name may override it.
Some(scope) => {
let scope = doc.semantics.scope(scope)?;
for symbol in scope.symbols.iter().filter_map(|&id| doc.semantics.symbol(id)) {
if symbol.kind == wanted && !taken.contains(symbol.name.as_str()) {
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
if symbol.kind == wanted {
push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
}
}
}
None => {
for (name, defs) in ws.index().members_of(&list.module) {
let Some(def) = defs.first() else { continue };
if def.kind == wanted && !taken.contains(name) {
members.push(
name,
def.kind,
indexed_detail(def.kind, def.type_name.as_deref()),
);
if def.kind == wanted {
push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
}
@@ -282,12 +308,11 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
/// token at `open`, except the one whose `.` sits at `skip` — the entry being
/// typed, which must stay on offer.
///
/// Dropping them is the friendlier half of a choice the other way round would
/// be simpler: in a sixty-port instantiation the fifty-five already connected
/// are the ones the user is *not* looking for, and a popup that keeps offering
/// them is a popup they scroll past. It cannot mislead — a name dropped here
/// is one the buffer already spells two lines up — and a re-edited entry is
/// still offered, because its own dot is the one `skip` names.
/// In a sixty-port instantiation the fifty-five already connected are the ones
/// the user is *not* looking for, so they sort after the rest and say so; they
/// are not dropped (`completion-ux`, 2026-11-17), because a port connected
/// twice by mistake is exactly the one a user goes looking for. A re-edited
/// entry is not marked, because its own dot is the one `skip` names.
fn connected_names(tokens: &[Token], open: usize, skip: u32) -> HashSet<&str> {
let mut taken = HashSet::new();
let mut depth = 0i32;
@@ -328,8 +353,12 @@ impl Members {
}
fn push(&mut self, name: &str, kind: SymbolKind, detail: String) {
if self.seen.insert(name.to_string()) {
self.out.push(Member { name: name.to_string(), kind, detail });
self.push_member(Member { name: name.to_string(), kind, detail, connection: None });
}
fn push_member(&mut self, member: Member) {
if self.seen.insert(member.name.clone()) {
self.out.push(member);
}
}
@@ -823,28 +852,55 @@ endmodule
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
}
/// The answer against [`WIRING`] in the order the client shows it — by
/// `sortText` — as `(label, marked connected)` pairs.
fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole);
let mut found = items(completions(&ws, &uri, position, true));
found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text));
found
.into_iter()
.map(|item| {
let marked = item
.label_details
.as_ref()
.and_then(|d| d.description.as_deref())
.is_some_and(|d| d == "connected");
(item.label, marked)
})
.collect()
}
fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> {
list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect()
}
#[test]
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
assert_eq!(wiring_labels("comma", ".clk(clk), ."), vec!["data", "ready"]);
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
assert_eq!(
wiring_labels("newline", ".clk(clk),\n ."),
vec!["data", "ready"],
wiring_order("newline", ".clk(clk),\n ."),
expected,
"an indented continuation line is the ordinary way this is written",
);
}
/// Already-connected ports are dropped: in a sixty-port instantiation the
/// ones still to wire are the whole of what the user is looking for.
/// Already-connected ports sort after the ones still to wire and say so
/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a
/// sixty-port instantiation the ones still to wire are what the user is
/// looking for, but a port connected twice by mistake is findable.
#[test]
fn a_port_already_connected_is_not_offered_again() {
fn a_port_already_connected_is_offered_last_and_marked() {
assert_eq!(
wiring_labels("taken", ".clk(clk), .data(d), ."),
vec!["ready"],
"two written, one left",
wiring_order("taken", ".clk(clk), .data(d), ."),
pairs(&[("ready", false), ("clk", true), ("data", true)]),
"two written, one left, and the two after it",
);
// …and the entry being *re-typed* is still offered, because the dot
// the cursor follows is the one that is skipped.
assert_eq!(wiring_labels("retype", ".clk(clk), .data(d), .re"), vec!["ready"]);
// …and the entry being *re-typed* is not marked, because the dot the
// cursor follows is the one that is skipped.
assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)]));
}
#[test]
@@ -945,17 +1001,21 @@ endmodule
}
#[test]
fn a_port_item_inserts_the_bare_name_and_shows_its_declaration() {
fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() {
let top = WIRING.replace(" HOLE\n", " .\n");
let tree = Tree::new("portitem");
let (_tree, ws, uri, position) = opened(tree, &top, " .");
let answer = items(completions(&ws, &uri, position, true));
let data = find(&answer, "data").expect("the port");
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
// The user types the `(` themselves; inventing it would be guessing
// at what is connected.
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
// `.data(|)`: the parentheses come with it, the cursor inside
// (`completion-ux`, 2026-11-17). Nothing named `data` is visible in
// `wiring_top`, so the placeholder is empty…
assert_eq!(inserted(data), "data(${1})");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET));
// …while `clk` is, so it is pre-filled.
let clk = find(&answer, "clk").expect("the clock");
assert_eq!(inserted(clk), "clk(${1:clk})");
// The declaration line carries the direction and the width, which is
// the whole of what a connection list needs to know.
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
@@ -965,6 +1025,33 @@ endmodule
}
}
#[test]
fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() {
// A `(` already after the word: only the name is being re-edited.
let top = WIRING.replace(" HOLE\n", " .da(d)\n");
let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "data").expect("the port")), "data");
// A client without snippet support gets the name, as before.
let top = WIRING.replace(" HOLE\n", " .\n");
let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " .");
let answer = items(completions(&ws, &uri, position, false));
let data = find(&answer, "data").expect("the port");
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
#[test]
fn a_parameter_item_is_pre_filled_from_a_visible_parameter() {
let top = WIRING
.replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n")
.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})");
assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})");
}
/// A **non-ANSI** port list writes its directions in the module body, so
/// the header alone names the ports and the body types them. Both halves
/// bind a `Port`, so the list is the same.
+77 -18
View File
@@ -1,7 +1,7 @@
//! `textDocument/completion` — module hinting, templates, keywords, and every
//! name the project uses.
//!
//! One response, six tiers, ordered by `sortText`:
//! One response, eight tiers, ordered by `sortText`:
//!
//! 0. **module names** — at module-item position only, every module the
//! workspace declares whose name contains what is typed. The item inserts
@@ -10,12 +10,15 @@
//! 2026-08-30);
//! 1. **what is visible here** — the declarations the scope chain at the
//! cursor binds, from this file's `Semantics`;
//! 2. **what the project declares** — packages, their members, typedefs,
//! 2. **what this file declares** — every declaration in the buffer, in any
//! scope (`buffer.rs`, `completion-ux` 2026-11-17);
//! 3. **what this file uses** — every identifier its token stream holds;
//! 4. **what the project declares** — packages, their members, typedefs,
//! classes, modules and `` `define`` names, from the workspace index;
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! 5. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! tabstops, offered only where the construct may be written;
//! 4. **keywords** — every reserved word `vlog_parser` knows;
//! 5. **project words** — every identifier the in-scope files' *token
//! 6. **keywords** — every reserved word `vlog_parser` knows;
//! 7. **project words** — every identifier the in-scope files' *token
//! streams* contain, the rope/VS Code word-completion tier.
//!
//! A name is offered once, by the highest tier that claims it. Nothing is
@@ -47,8 +50,9 @@
//! list included;
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
//! `instantiate.rs` share;
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
//! the response.
//! * `buffer` — tiers 2 and 3, the current file's declarations and words;
//! * `tiers` — the other ordinary tiers, in the order they fill the
//! response.
//!
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
//! entry points other modules of the crate use keep their paths through the
@@ -58,9 +62,9 @@
use std::collections::HashSet;
use lsp_types::{
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
TextEdit, Uri,
CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionList,
CompletionResponse, CompletionTextEdit, Documentation, InsertTextFormat, InsertTextMode,
MarkupContent, MarkupKind, Position, Range, TextEdit, Uri,
};
use vlog_parser::token::{Comment, TokenKind};
use vlog_parser::TextRange;
@@ -71,6 +75,8 @@ use crate::candidates::Query;
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::Template;
use buffer::{buffer_word_tier, declared_tier};
use connection::Connection;
use member::member_answer;
use module::module_tier;
use site::{at_module_item, at_statement, enclosing_scopes};
@@ -85,6 +91,8 @@ pub(crate) use module::module_header;
pub(crate) use site::at_instantiation_site;
pub(crate) use tiers::layout_at;
mod buffer;
mod connection;
#[cfg(test)]
mod harness;
mod member;
@@ -134,11 +142,19 @@ const TIER_MODULE: char = '0';
/// would say there is a ranking against the other tiers to express, and there
/// is not.
const TIER_MEMBER: char = '0';
/// A connection list's already-connected ports: after every port still to
/// connect, inside the same exclusive answer (`completion-ux`).
const TIER_CONNECTED: char = '1';
const TIER_SCOPE: char = '1';
const TIER_INDEX: char = '2';
const TIER_TEMPLATE: char = '3';
const TIER_KEYWORD: char = '4';
const TIER_WORD: char = '5';
/// What this buffer declares anywhere, and then the words it uses — the
/// current file ahead of every other file and of the templates and keywords
/// (`completion-ux`, TODO §68.1).
const TIER_DECLARED: char = '2';
const TIER_BUFFER_WORD: char = '3';
const TIER_INDEX: char = '4';
const TIER_TEMPLATE: char = '5';
const TIER_KEYWORD: char = '6';
const TIER_WORD: char = '7';
/// What a multi-line item tells the client about its own whitespace.
///
@@ -203,7 +219,7 @@ pub fn completions(
// A `.` or a `::` admits exactly one kind of name too — a member of what
// stands before it — so the answer is only those. See [`member_answer`].
if word.sep.is_some() {
return member_answer(ws, doc, &word, offset);
return member_answer(ws, doc, &word, offset, snippets);
}
// Both position gates read the same scope chain, and neither can be true
@@ -225,10 +241,12 @@ pub fn completions(
let mut items = Items::new(doc, word.range(offset));
module_tier(&mut items, ws, doc, &word, at_item);
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
declared_tier(&mut items, doc, &word, fuzzy.as_ref());
buffer_word_tier(&mut items, doc, &word, fuzzy.as_ref());
index_tier(&mut items, ws, &word, fuzzy.as_ref());
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
keyword_tier(&mut items, &word);
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
word_tier(&mut items, ws, &word, fuzzy.as_ref());
// **The `isIncomplete` trap.** VS Code asks the server again on the next
// keystroke *only* when the last answer said it was incomplete; otherwise
// it filters the list it already holds. A complete two-character prefix
@@ -307,13 +325,54 @@ impl Items {
self.push(item);
}
/// A port or parameter after a connection list's `.`: the bare name, or
/// the `name($1)` entry when the connection carries one, and a dimmed
/// `connected` beside the label when the list already connects it.
fn connection(
&mut self,
name: &str,
kind: CompletionItemKind,
detail: String,
connection: Connection,
) {
if self.full() || self.seen.contains(name) {
return;
}
let tier = if connection.connected { TIER_CONNECTED } else { TIER_MEMBER };
let format = match connection.snippet {
Some(_) => InsertTextFormat::SNIPPET,
None => InsertTextFormat::PLAIN_TEXT,
};
let item = CompletionItem {
label: name.to_string(),
kind: Some(kind),
detail: Some(detail),
label_details: connection.connected.then(|| CompletionItemLabelDetails {
detail: None,
description: Some("connected".to_string()),
}),
sort_text: Some(format!("{tier}{name}")),
insert_text_format: Some(format),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range: self.range,
new_text: connection.snippet.unwrap_or_else(|| name.to_string()),
})),
..Default::default()
};
self.push(item);
}
/// One template: the skeleton it inserts, the word it is reached by, and
/// the shape it expands to.
///
/// A client that never said it understands snippets gets the same text
/// with every hole filled in rather than nothing at all — the M4 ruling,
/// applied to a body whose defaults were chosen so that the result parses.
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
///
/// `rank` is the template's place in the registry, which is what orders the
/// templates among themselves: the label alone would put `always @(*)`
/// before the clocked blocks.
fn template(&mut self, template: &Template, rank: usize, layout: &Layout, snippets: bool) {
if self.full() || self.seen.contains(template.label) {
return;
}
@@ -329,7 +388,7 @@ impl Items {
// types to reach the item — otherwise `if` would not match
// `if begin/end` at all.
filter_text: Some(template.prefix.to_string()),
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
sort_text: Some(format!("{TIER_TEMPLATE}{rank:03}{}", template.label)),
insert_text_format: Some(match snippets {
true => InsertTextFormat::SNIPPET,
false => InsertTextFormat::PLAIN_TEXT,
+26 -59
View File
@@ -13,7 +13,6 @@
use std::collections::HashSet;
use lsp_types::CompletionItemKind;
use vlog_parser::token::TokenKind;
use vlog_parser::KEYWORDS;
use vlog_refactor::Layout;
use vlog_semantic::{Semantics, Symbol};
@@ -66,7 +65,7 @@ pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy:
/// Every declaration the scope chain covering `offset` binds, innermost scope
/// first, each name only once — the inner declaration shadows the outer one,
/// which is the rule `vlog_semantic`'s own lookup follows.
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
pub(super) fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
let mut out = Vec::new();
let mut seen = HashSet::new();
let mut at = innermost_scope(semantics, offset);
@@ -158,7 +157,7 @@ pub(super) fn template_tier(
}
let layout = layout_at(ws, doc, word.start);
let dialect = templates::dialect(doc.path.as_deref());
for template in templates::for_dialect(dialect) {
for (rank, template) in templates::for_dialect(dialect).enumerate() {
if items.full() {
break;
}
@@ -168,7 +167,7 @@ pub(super) fn template_tier(
if !starts_with_ignore_case(template.prefix, &word.text) {
continue;
}
items.template(template, &layout, snippets);
items.template(template, rank, &layout, snippets);
}
}
@@ -205,45 +204,26 @@ pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
}
}
/// Tier 5: identifiers used anywhere in the project scope.
/// Tier 7: identifiers used anywhere in the project scope.
///
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
/// buffer being typed in is harvested afresh from its own token stream, so an
/// unsaved edit contributes to its own file's completions immediately.
pub(super) fn word_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
/// The prebuilt table is as of the last index rebuild, which is `didSave`. The
/// buffer being typed in is harvested afresh from its own token stream by
/// tier 3 (`buffer.rs`), so an unsaved edit still contributes immediately.
pub(super) fn word_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
// Gathering and sorting the names is the one tier whose *setup* costs
// something, so a response that is already full skips it outright.
if items.full() {
return;
}
// The buffer's own words were offered by tier 3 already, so only the
// prebuilt table is read here; a name in both is offered once anyway,
// because `Items` drops a repeated label.
let names: Vec<&str> = match fuzzy {
None => {
let mut names: Vec<&str> =
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
names
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
names.sort_unstable();
names.dedup();
names
}
None => ws.candidates().words(&word.text).iter().map(String::as_str).collect(),
Some(query) => {
// The table's hits come back ranked; the buffer's own words are
// scored here and the two are ranked together, so a name the user
// typed a moment ago sits where its match deserves rather than
// after everything the table knows.
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
let hits = ws.candidates().words_fuzzy(query, LIMIT);
// A full return is a truncation; see `index_tier`.
items.incomplete |= hits.len() >= LIMIT;
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
hits.sort_by(|a, b| rank_cmp(*a, *b));
// A name in both lists is offered once: `Items` drops the second
// by label, so no dedup is needed here.
hits.into_iter().map(|(name, _)| name).collect()
}
};
@@ -255,21 +235,6 @@ pub(super) fn word_tier(
}
}
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
///
/// The live half of the tier: the prebuilt table is as of the last index
/// rebuild, and this is the buffer's own token stream, recomputed on every
/// change. The filter is `candidates::is_word`'s, in the other direction —
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
/// identifier.
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
doc.tokens
.iter()
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
.map(|token| token.text.as_str())
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -374,7 +339,7 @@ endmodule
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
"and `alw` finds every one of them"
);
@@ -419,7 +384,7 @@ endmodule
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
@@ -637,7 +602,8 @@ endmodule
#[test]
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
// `inner` is declared in a block the cursor is not in, so it may only
// arrive as a project word — never as a visible declaration.
// arrive as one of this file's declarations (tier 2, `completion-ux`)
// — never as a visible declaration.
let top = "\
module top;
initial begin : b
@@ -650,8 +616,8 @@ endmodule
";
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "inner_only").expect("known as a word at least");
assert_eq!(tier(item), TIER_WORD, "{item:#?}");
let item = find(&items, "inner_only").expect("known as a declaration at least");
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
}
// ------------------------------------------------------------------
@@ -750,12 +716,13 @@ endmodule
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `c` itself is in the list because the buffer being typed in
// holds it as an `Ident` token — behaviour this round did not
// touch, pinned here because a golden that quietly lost it would
// be a change.
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["ce", "celsius"]),
// `c` itself used to be in the list, because the buffer being
// typed in holds it as an `Ident` token. `completion-ux`
// (2026-11-17) dropped it on purpose: the buffer-word tier skips
// the token under the cursor, and offering the user their own
// half-word back is noise.
("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["celsius"]),
] {
let found = items(after_typing(&mut ws, &uri, typed));
let named: Vec<&str> = found
+9
View File
@@ -708,10 +708,19 @@ mod tests {
/// therefore in `includers()`/`include_sources()` — the narrowing must not
/// accidentally depend on the include's target spelling matching the
/// disk's.
///
/// Only a case-insensitive filesystem (macOS, Windows by default) resolves
/// the mismatched spelling at all; on a case-sensitive one (Linux) there
/// is no include to narrow in, so the test checks which it is on and stops
/// there, saying so.
#[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");
if !tree.path.join("rtl/DEFS.svh").is_file() {
eprintln!("skipped: this filesystem is case-sensitive; `DEFS.svh` names no file");
return;
}
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();
+96 -3
View File
@@ -4,7 +4,17 @@
//! `pairs::analyze` already computes for the rainbow and the missing-closer
//! warnings, or a block comment, which the lexer already attached as trivia.
//! This module is the fourth consumer of the first and the second of the
//! second. See `docs/features/references-nav/README.md`.
//! second. See `docs/features/references-nav/README.md`. The third source,
//! the branches of `` `ifdef `` regions, is [`directives`]
//! (`docs/features/ifdef-folding/README.md`).
mod directives;
#[cfg(test)]
mod ifdef_tests;
#[cfg(test)]
mod opentitan_sweep;
use std::collections::HashSet;
use lsp_types::{FoldingRange, FoldingRangeKind};
use vlog_parser::token::Comment;
@@ -13,8 +23,9 @@ use vlog_parser::TextRange;
use crate::pairs::analyze;
use crate::state::Document;
/// Every foldable region in a buffer: one per matched scope pair, plus every
/// block comment that spans more than one line.
/// Every foldable region in a buffer: one per matched scope pair, one per
/// branch of a closed `` `ifdef `` region, plus every block comment that spans
/// more than one line.
///
/// A keyword whose counterpart never arrived is **not** foldable — `analyze`
/// leaves it out of `pairs`, and folding to the end of the file because an
@@ -22,6 +33,15 @@ use crate::state::Document;
/// off. Nothing is capped: a fold list is one range per block, and an editor
/// that asked for it wants all of them.
pub fn folding_ranges(doc: &Document) -> Vec<FoldingRange> {
let scopes = scope_and_comment_folds(doc);
let branches = branch_folds(doc, &scopes);
in_answer_order(scopes, branches)
}
/// The scope-pair and block-comment folds, exactly as they were before
/// branch folds existed: sorted by `(start, end)`, one per pair of lines (a
/// scope pair wins over a comment on the same two lines).
fn scope_and_comment_folds(doc: &Document) -> Vec<FoldingRange> {
let mut out: Vec<FoldingRange> = Vec::new();
for pair in analyze(&doc.tokens).pairs {
// The closing keyword's own line stays visible: LSP hides
@@ -43,6 +63,46 @@ pub fn folding_ranges(doc: &Document) -> Vec<FoldingRange> {
out
}
/// One fold per branch of every closed `` `ifdef `` region, sorted by start
/// line. Conditional-compilation branches follow the scope rule: the next
/// directive's line (`else`, `endif`) stays visible. A branch whose two lines
/// are exactly an existing fold's is left out, so that fold keeps its kind
/// (a `/* */` opened on the directive line stays a `comment`).
fn branch_folds(doc: &Document, existing: &[FoldingRange]) -> Vec<FoldingRange> {
let taken: HashSet<(u32, u32)> = existing.iter().map(|r| (r.start_line, r.end_line)).collect();
let mut out = Vec::new();
for (start, through) in directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start)) {
if !taken.contains(&(start, through)) {
push(&mut out, start, through, FoldingRangeKind::Region);
}
}
out.sort_by_key(|range| range.start_line);
out
}
/// The one place the answer's order is defined: by start line; on a shared
/// start line, every scope or comment fold (in their own `(start, end)`
/// order) before any branch fold.
///
/// The order is load-bearing. VS Code keeps only the *first* range it
/// receives for a start line (`sanitizeRanges`), so whatever comes first is
/// the fold the user gets and the line sticky scroll pins. Putting existing
/// folds first means a branch fold never costs the user a fold they had
/// before — on `module m; `ifdef A` the `module` fold survives and the branch
/// yields. See `docs/features/ifdef-folding/README.md`.
fn in_answer_order(existing: Vec<FoldingRange>, branches: Vec<FoldingRange>) -> Vec<FoldingRange> {
let mut out = Vec::with_capacity(existing.len() + branches.len());
let mut branches = branches.into_iter().peekable();
for range in existing {
while let Some(branch) = branches.next_if(|b| b.start_line < range.start_line) {
out.push(branch);
}
out.push(range);
}
out.extend(branches);
out
}
/// Add one range, unless there is nothing between its two lines to hide.
fn push(out: &mut Vec<FoldingRange>, start_line: u32, end_line: u32, kind: FoldingRangeKind) {
if end_line <= start_line {
@@ -148,6 +208,39 @@ mod tests {
assert_eq!(folds(text), vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")]);
}
#[test]
fn every_layer_a_reader_is_inside_starts_a_fold_on_its_header_line() {
// VS Code's sticky scroll is told (the extension's
// `editor.stickyScroll.defaultModel`) to pin the first line of every
// fold around the top of the viewport. So the header of each layer —
// module, `always`, `case`, the case item, the `if` — must be a fold's
// start line, and each fold must reach the innermost statement.
let text = concat!(
"module m (\n", // 0
" input a\n", // 1
");\n", // 2
" always @(*) begin\n", // 3
" case (st)\n", // 4
" st_1: begin\n", // 5
" if (cond_1) begin\n", // 6
" x = 1;\n", // 7
" y = 2;\n", // 8
" end\n", // 9
" end\n", // 10
" endcase\n", // 11
" end\n", // 12
"endmodule\n", // 13
);
let ranges = folds(text);
for header in [0, 3, 4, 5, 6] {
let fold = ranges.iter().find(|(start, _, _)| *start == header);
let Some((_, end, _)) = fold else {
panic!("no fold starts on line {header}: {ranges:?}")
};
assert!(*end >= 8, "the fold from line {header} must cover line 8, got {ranges:?}");
}
}
#[test]
fn a_scope_that_opens_and_closes_on_one_line_folds_nothing() {
// `end_line <= start_line` means there is no hidden line to gain.
@@ -0,0 +1,85 @@
//! Folding for conditional compilation: one range per branch of every
//! `` `ifdef `` / `` `ifndef `` … `` `endif `` region.
//!
//! No new scan. The lexer already turns each of the five directives into one
//! [`TokenKind::Directive`] token that runs to the end of its line, and only
//! where they really are directives: never in a comment or a string (those are
//! trivia and literals), never inside a `` `define `` body (the whole body,
//! continuation lines included, is the `` `define `` token's own text). A
//! token's first word is all this module reads.
//! See `docs/features/ifdef-folding/README.md`.
use vlog_parser::token::{Token, TokenKind};
/// What one conditional-compilation directive does to the branch structure.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Conditional {
/// `` `ifdef `` / `` `ifndef ``: a region, and its first branch, begin.
Open,
/// `` `elsif `` / `` `else ``: the current branch ends, the next begins.
Next,
/// `` `endif ``: the last branch, and the region, end.
Close,
}
/// `(directive line, last line)` of every branch whose region is closed, in
/// 0-based lines, given the line each token starts on.
///
/// A branch runs from its own directive's line through the line *before*
/// the next directive of the same region, so the `` `else `` and the
/// `` `endif `` stay visible when the branch above them is collapsed — the
/// same rule as `end` under `begin`. Branches with nothing between their two
/// lines come back too (`last <= first`); the caller drops them.
///
/// A region that never closes contributes the branches it *did* finish
/// (an `` `ifdef `` … `` `else `` … end-of-file still folds its first
/// branch) and nothing for the one still open, rather than folding to the end
/// of the file. A stray `` `else `` or `` `endif `` with no region open is
/// ignored.
pub(super) fn branch_spans(tokens: &[Token], line_of: impl Fn(&Token) -> u32) -> Vec<(u32, u32)> {
// The directive line of the branch that is open at each nesting depth.
let mut open: Vec<u32> = Vec::new();
let mut out = Vec::new();
for token in tokens {
let Some(directive) = conditional(token) else { continue };
let at = line_of(token);
match directive {
Conditional::Open => open.push(at),
Conditional::Next => {
if let Some(first) = open.last_mut() {
out.push((*first, at.saturating_sub(1)));
*first = at;
}
}
Conditional::Close => {
if let Some(first) = open.pop() {
out.push((first, at.saturating_sub(1)));
}
}
}
}
out
}
/// The conditional-compilation directive a token is, if it is one.
fn conditional(token: &Token) -> Option<Conditional> {
if token.kind != TokenKind::Directive {
return None;
}
match directive_word(&token.text) {
"ifdef" | "ifndef" => Some(Conditional::Open),
"elsif" | "else" => Some(Conditional::Next),
"endif" => Some(Conditional::Close),
_ => None,
}
}
/// The word a directive's text spells, without its backtick or argument:
/// `` `ifndef FOO `` is `"ifndef"`. The parser keeps the same rule private
/// (`vlog_parser/src/parser/directive.rs`); it is four lines, so it is
/// repeated here rather than widened into the parser's public surface.
fn directive_word(text: &str) -> &str {
let rest = text.strip_prefix('`').unwrap_or("");
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len());
rest.get(..end).unwrap_or("")
}
@@ -0,0 +1,337 @@
//! `` `ifdef `` branch folds, through the whole [`folding_ranges`] answer so
//! every test also sees how they sit beside the scope and comment folds.
use lsp_types::FoldingRangeKind;
use vlog_semantic::WorkspaceIndex;
use super::folding_ranges;
use crate::state::Document;
fn doc_of(text: &str) -> Document {
Document::new(None, text.to_string(), &WorkspaceIndex::default())
}
/// Every fold as `(start line, end line, kind)`, kinds spelled short, after
/// checking the one ordering promise every answer keeps: by start line.
fn folds(text: &str) -> Vec<(u32, u32, &'static str)> {
let ranges = folding_ranges(&doc_of(text));
assert!(ranges.windows(2).all(|w| w[0].start_line <= w[1].start_line), "{ranges:?}");
ranges
.into_iter()
.map(|range| {
let kind = match range.kind {
Some(FoldingRangeKind::Comment) => "comment",
Some(FoldingRangeKind::Region) => "region",
other => panic!("unexpected kind {other:?}"),
};
(range.start_line, range.end_line, kind)
})
.collect()
}
/// The folds as `(start, end)` alone, for tests about lines rather than kinds.
fn lines(text: &str) -> Vec<(u32, u32)> {
folds(text).into_iter().map(|(start, end, _)| (start, end)).collect()
}
#[test]
fn each_branch_folds_from_its_directive_to_the_line_before_the_next() {
// Collapsing the `ifdef` branch leaves `else` on screen and separately
// collapsible; collapsing the `else` branch leaves `endif` on screen.
let text = concat!(
"module m;\n", // 0
"`ifdef A\n", // 1
" wire a;\n", // 2
" wire b;\n", // 3
"`else\n", // 4
" wire c;\n", // 5
"`endif\n", // 6
"endmodule\n", // 7
);
assert_eq!(folds(text), vec![(0, 6, "region"), (1, 3, "region"), (4, 5, "region")]);
}
#[test]
fn an_elsif_chain_gives_every_arm_its_own_fold() {
let text = concat!(
"`ifndef A\n", // 0
" wire a;\n", // 1
"`elsif B\n", // 2
" wire b;\n", // 3
"`elsif C\n", // 4
" wire c;\n", // 5
"`else\n", // 6
" wire d;\n", // 7
"`endif\n", // 8
);
assert_eq!(lines(text), vec![(0, 1), (2, 3), (4, 5), (6, 7)]);
}
#[test]
fn nested_regions_fold_at_every_depth() {
let text = concat!(
"`ifdef A\n", // 0
" `ifdef B\n", // 1
" `ifndef C\n", // 2
" wire c;\n", // 3
" `endif\n", // 4
" `else\n", // 5
" wire nb;\n", // 6
" `endif\n", // 7
"`else\n", // 8
" `ifdef D\n", // 9
" wire d;\n", // 10
" `endif\n", // 11
"`endif\n", // 12
);
assert_eq!(
lines(text),
vec![(0, 7), (1, 4), (2, 3), (5, 6), (8, 11), (9, 10)],
"A, B, C, B's else, A's else, D"
);
}
#[test]
fn a_branch_with_nothing_in_it_folds_nothing() {
let text = concat!(
"`ifdef A\n", // 0
"`else\n", // 1
" wire b;\n", // 2
"`endif\n", // 3
"`ifdef C\n", // 4
"`endif\n", // 5
);
assert_eq!(lines(text), vec![(1, 2)], "only the else branch holds a line");
}
#[test]
fn a_one_line_region_is_one_token_and_folds_nothing() {
// A directive runs to the end of its line, so the `endif` here is the
// `ifdef` token's text, not a directive of its own.
let text = "module m;\n`ifdef A wire a; `else wire b; `endif\nendmodule\n";
let doc = doc_of(text);
let directives = doc.tokens.iter().filter(|t| t.text.starts_with("`ifdef")).count();
assert_eq!(directives, 1);
assert_eq!(lines(text), vec![(0, 1)], "the module only");
}
#[test]
fn an_unterminated_region_folds_only_the_branches_it_finished() {
// Same policy as an unclosed `begin`: never fold to the end of the file.
let text = concat!(
"`ifdef A\n", // 0
" wire a;\n", // 1
"`else\n", // 2
" wire b;\n", // 3
" wire c;\n", // 4
);
assert_eq!(lines(text), vec![(0, 1)]);
assert!(lines("`ifdef A\n wire a;\n wire b;\n").is_empty());
}
#[test]
fn stray_else_and_endif_are_ignored_without_disturbing_what_follows() {
let text = concat!(
"`else\n", // 0
" wire x;\n", // 1
"`endif\n", // 2
"`endif\n", // 3
"`ifdef A\n", // 4
" wire a;\n", // 5
"`endif\n", // 6
"`elsif B\n", // 7
" wire b;\n", // 8
);
assert_eq!(lines(text), vec![(4, 5)]);
}
#[test]
fn directives_between_ports_fold() {
let text = concat!(
"module m (\n", // 0
" input a,\n", // 1
"`ifdef B\n", // 2
" input b,\n", // 3
" input c,\n", // 4
"`endif\n", // 5
" input d\n", // 6
");\n", // 7
"endmodule\n", // 8
);
assert!(lines(text).contains(&(2, 4)), "got {:?}", lines(text));
}
#[test]
fn directives_inside_case_and_generate_fold() {
let text = concat!(
"module m;\n", // 0
" generate\n", // 1
"`ifdef G\n", // 2
" if (A) begin : g\n", // 3
" wire a;\n", // 4
" end\n", // 5
"`endif\n", // 6
" endgenerate\n", // 7
" always_comb begin\n", // 8
" case (s)\n", // 9
" 0: x = 0;\n", // 10
"`ifdef C\n", // 11
" 1: x = 1;\n", // 12
"`else\n", // 13
" 1: x = 2;\n", // 14
"`endif\n", // 15
" endcase\n", // 16
" end\n", // 17
"endmodule\n", // 18
);
assert_eq!(
lines(text),
vec![(0, 17), (1, 6), (2, 5), (3, 4), (8, 16), (9, 15), (11, 12), (13, 14)]
);
}
#[test]
fn a_directive_inside_a_define_body_is_text_not_a_fold() {
let text = concat!(
"`define M \\\n", // 0
" `ifdef X \\\n", // 1
" a = 1; \\\n", // 2
" `else \\\n", // 3
" a = 2; \\\n", // 4
" `endif\n", // 5
"module m;\n", // 6
" wire a;\n", // 7
"endmodule\n", // 8
);
assert_eq!(lines(text), vec![(6, 7)], "the module only");
}
#[test]
fn a_directive_in_a_comment_or_a_string_is_not_one() {
let text = concat!(
"module m;\n", // 0
" // `ifdef A\n", // 1
" /* `ifdef B\n", // 2
" `endif */\n", // 3
" initial $display(\"`ifdef\");\n", // 4
" // `endif\n", // 5
"endmodule\n", // 6
);
assert_eq!(folds(text), vec![(0, 5, "region"), (2, 3, "comment")]);
}
#[test]
fn leading_whitespace_trailing_comments_and_crlf_change_nothing() {
let plain = concat!(
"module m;\n", // 0
" `ifdef A // why\n", // 1
" wire a;\n", // 2
"\t`else /* other */\n", // 3
" wire b;\n", // 4
" `endif // A\n", // 5
"endmodule\n", // 6
);
assert_eq!(lines(plain), vec![(0, 5), (1, 2), (3, 4)]);
assert_eq!(lines(&plain.replace('\n', "\r\n")), lines(plain));
}
#[test]
fn a_region_crossing_a_begin_keeps_both_sets_of_folds() {
// Real RTL opens one `begin` in each arm and closes it once below the
// `endif`. The branch folds cross the `begin` folds; VS Code keeps
// crossing ranges (`sanitizeRanges` adds them at the level of the range
// they cross; see the feature README), so nothing is dropped here and
// nothing is invented either.
let text = concat!(
"module m;\n", // 0
" always_comb begin\n", // 1
"`ifdef A\n", // 2
" if (a) begin\n", // 3
"`else\n", // 4
" if (b) begin\n", // 5
"`endif\n", // 6
" x = 1;\n", // 7
" end\n", // 8
" end\n", // 9
"endmodule\n", // 10
);
// The scope pairing sees three `begin`s and two `end`s, matches the inner
// two (`(5, 7)`, `(3, 8)`) and leaves the `always_comb` one out — that is
// `pairs::analyze`, unchanged by this feature. The branches are added
// beside it: `(2, 3)` crosses `(3, 8)`, `(4, 5)` crosses `(5, 7)`.
assert_eq!(lines(text), vec![(0, 9), (2, 3), (3, 8), (4, 5), (5, 7)]);
}
#[test]
fn branch_folds_are_regions() {
let text = "`ifdef A\n wire a;\n`endif\n";
assert_eq!(folds(text), vec![(0, 1, "region")]);
}
#[test]
fn back_to_back_regions_each_fold() {
let text = concat!(
"`ifdef A\n", // 0
" wire a;\n", // 1
"`endif\n", // 2
"`ifdef B\n", // 3
" wire b;\n", // 4
"`endif\n", // 5
);
assert_eq!(lines(text), vec![(0, 1), (3, 4)]);
}
// A shared start line. VS Code keeps only the first range it receives for a
// start line, so a fold that existed before branch folds must come first and
// the branch fold is the one that yields (QA findings 1 and 2, 2026-11-19).
#[test]
fn a_module_header_sharing_its_line_with_an_ifdef_keeps_its_fold_first() {
let text = "module m; `ifdef A\n a;\n`endif\nendmodule\n";
assert_eq!(lines(text), vec![(0, 2), (0, 1)], "the module first, the branch after it");
}
#[test]
fn a_begin_sharing_its_line_with_an_ifdef_keeps_its_fold_first() {
let text = concat!(
"module m;\n", // 0
"initial begin `ifdef X\n", // 1
" a;\n", // 2
" b;\n", // 3
" `endif\n", // 4
" c;\n", // 5
"end\n", // 6
"endmodule\n", // 7
);
assert_eq!(lines(text), vec![(0, 6), (1, 5), (1, 3)]);
}
#[test]
fn a_comment_opened_on_a_directive_line_keeps_its_fold_first() {
// The comment is the shorter range but the older fold, so it is first,
// and in VS Code the branch from line 0 is the one that yields.
let text = concat!(
"`ifdef A /* c1\n", // 0
" c2 */\n", // 1
" x;\n", // 2
"`else\n", // 3
" b;\n", // 4
"`endif\n", // 5
);
assert_eq!(folds(text), vec![(0, 1, "comment"), (0, 2, "region"), (3, 4, "region")]);
}
#[test]
fn a_comment_spanning_exactly_a_branch_stays_a_comment() {
// Same two lines as the branch: one range, and it keeps the kind it had
// before branch folds existed, so *Fold All Block Comments* still folds it.
let text = concat!(
"`ifdef A /* c1\n", // 0
" c2\n", // 1
" c3 */\n", // 2
"`else\n", // 3
" b;\n", // 4
"`endif\n", // 5
);
assert_eq!(folds(text), vec![(0, 2, "comment"), (3, 4, "region")]);
}
@@ -0,0 +1,232 @@
//! The real-world proof for `` `ifdef `` folding: every `.sv`/`.svh`/`.v`
//! file under an OpenTitan `hw` tree, through [`folding_ranges`], with the
//! ranges checked against the file and the directives counted independently.
//!
//! `#[ignore]`: it parses four thousand files. Run with
//! `LUCISV_OPENTITAN_HW=/path/to/opentitan/hw tools/guard.sh -- cargo test
//! --release -p lucisv_server opentitan_sweep -- --ignored --nocapture`;
//! without the variable it reads `~/.cache/lucisv-opentitan-full/hw`, and it
//! skips (passing, with a line on stderr) when that is not there.
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::WorkspaceIndex;
use lsp_types::FoldingRange;
use super::{branch_folds, directives, folding_ranges, line, scope_and_comment_folds};
use crate::state::Document;
/// The tree: `LUCISV_OPENTITAN_HW`, else the full-tree cache.
fn tree() -> Option<PathBuf> {
let root = std::env::var_os("LUCISV_OPENTITAN_HW").map(PathBuf::from).or_else(|| {
std::env::var_os("HOME")
.map(|home| PathBuf::from(home).join(".cache/lucisv-opentitan-full/hw"))
})?;
root.is_dir().then_some(root)
}
/// Every Verilog source under `dir`, sorted so a run is reproducible.
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
sources(&path, out);
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v")) {
out.push(path);
}
}
}
/// The five words, counted on the token stream by a rule written apart from
/// the one under test.
fn word(token: &Token) -> Option<&'static str> {
if token.kind != TokenKind::Directive {
return None;
}
let mut first = token.text.split(|c: char| !c.is_ascii_alphanumeric() && c != '`' && c != '_');
match first.next()? {
"`ifdef" => Some("ifdef"),
"`ifndef" => Some("ifndef"),
"`elsif" => Some("elsif"),
"`else" => Some("else"),
"`endif" => Some("endif"),
_ => None,
}
}
/// The same five, counted on the raw text: a line whose first non-blank
/// characters spell one. Differs from the token count wherever the lexer knows
/// better — a comment, a `` `define `` body.
fn text_count(text: &str) -> usize {
text.lines()
.filter(|l| {
let l = l.trim_start();
["`ifdef", "`ifndef", "`elsif", "`else", "`endif"].iter().any(|d| {
l.strip_prefix(d).is_some_and(|rest| {
!rest.starts_with(|c: char| c.is_alphanumeric() || c == '_')
})
})
})
.count()
}
#[derive(Default, Debug)]
struct Tally {
files: usize,
unlexed: usize,
tokens: usize,
text_lines: usize,
opens: usize,
nexts: usize,
closes: usize,
/// `else`/`elsif` and `endif` that found a region open — what
/// [`directives::branch_spans`] should emit one span for each of.
nexts_matched: usize,
closes_matched: usize,
/// Regions still open at end of file.
unclosed: usize,
spans: usize,
ranges: usize,
not_first_on_line: usize,
/// Branch folds left out because an existing fold has the same two lines.
same_lines_as_existing: usize,
/// Branch folds that share their start line with an existing fold.
shared_start: usize,
folding: Duration,
branches: Duration,
}
#[test]
#[ignore = "reads an OpenTitan checkout; see the module comment"]
fn every_opentitan_file_folds_its_ifdef_branches_validly() {
let Some(root) = tree() else {
eprintln!("opentitan_sweep: no OpenTitan hw tree; skipped");
return;
};
let mut files = Vec::new();
sources(&root, &mut files);
files.sort();
let mut tally = Tally::default();
let mut slowest: Vec<(Duration, Duration, PathBuf)> = Vec::new();
for path in &files {
let Ok(text) = std::fs::read_to_string(path) else { continue };
let (folding, branches) = sweep_one(path, text, &mut tally);
slowest.push((folding, branches, path.clone()));
}
slowest.sort_by_key(|entry| std::cmp::Reverse(entry.0));
eprintln!("opentitan_sweep: {tally:#?}");
for (folding, branches, path) in slowest.iter().take(5) {
eprintln!(" {folding:?} (branches {branches:?}) {}", path.display());
}
assert!(tally.files > 0);
assert_eq!(tally.spans, tally.nexts_matched + tally.closes_matched, "{tally:#?}");
}
/// Fold one file, check its ranges, and add it to `tally`. Returns the time
/// the whole answer took and the time the branch pass alone took.
fn sweep_one(path: &Path, text: String, tally: &mut Tally) -> (Duration, Duration) {
tally.files += 1;
let by_text = text_count(&text);
tally.text_lines += by_text;
let doc = Document::new(None, text, &WorkspaceIndex::default());
if doc.tokens.is_empty() {
tally.unlexed += 1;
eprintln!(" does not lex: {}", path.display());
}
let lines = doc.line_index.line_col(doc.text.len() as u32).0;
let started = Instant::now();
let ranges = folding_ranges(&doc);
let folding = started.elapsed();
let started = Instant::now();
let spans = directives::branch_spans(&doc.tokens, |t| line(&doc, t.span.start));
let branches = started.elapsed();
tally.folding += folding;
tally.branches += branches;
for range in &ranges {
assert!(range.start_line < range.end_line, "{}: {range:?}", path.display());
assert!(range.end_line < lines, "{}: {range:?} past line {lines}", path.display());
}
check_existing_unchanged(&doc, &ranges, path, tally);
let before = tally.tokens;
let directive_lines = check_directives(&doc, path, tally);
if tally.tokens - before != by_text {
let tokens = tally.tokens - before;
eprintln!(" {by_text} by text, {tokens} by token: {}", path.display());
}
tally.spans += spans.len();
for &(start, end) in spans.iter().filter(|(s, e)| e > s) {
tally.ranges += 1;
assert!(directive_lines.contains(&start), "{}: fold at {start}", path.display());
assert!(
ranges.iter().any(|r| r.start_line == start && r.end_line == end),
"{}: branch {start}..{end} missing from the answer",
path.display()
);
}
(folding, branches)
}
/// Count the directive tokens into `tally` and return the lines they start on.
fn check_directives(doc: &Document, path: &Path, tally: &mut Tally) -> Vec<u32> {
let mut at = Vec::new();
let mut depth = 0usize;
for (i, token) in doc.tokens.iter().enumerate() {
let Some(word) = word(token) else { continue };
tally.tokens += 1;
match word {
"ifdef" | "ifndef" => {
tally.opens += 1;
depth += 1;
}
"elsif" | "else" => {
tally.nexts += 1;
tally.nexts_matched += usize::from(depth > 0);
}
_ => {
tally.closes += 1;
tally.closes_matched += usize::from(depth > 0);
depth = depth.saturating_sub(1);
}
}
let start = line(doc, token.span.start);
let previous = i.checked_sub(1).map(|p| &doc.tokens[p]);
if previous.is_some_and(|p| line(doc, p.span.end.saturating_sub(1)) == start) {
tally.not_first_on_line += 1;
eprintln!(" not first on line {}: {}:{}", start + 1, path.display(), token.text);
}
at.push(start);
}
tally.unclosed += depth;
at
}
/// The answer with its branch folds taken out is exactly the scope and
/// comment folds alone — same ranges, kinds and order — so no fold that
/// existed before this feature is lost, changed or moved.
fn check_existing_unchanged(
doc: &Document,
ranges: &[FoldingRange],
path: &Path,
tally: &mut Tally,
) {
let existing = scope_and_comment_folds(doc);
let branches = branch_folds(doc, &existing);
let rest: Vec<&FoldingRange> = ranges.iter().filter(|r| !branches.contains(r)).collect();
assert_eq!(rest, existing.iter().collect::<Vec<_>>(), "{}", path.display());
assert_eq!(ranges.len(), existing.len() + branches.len(), "{}", path.display());
let spans = directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start));
let kept = spans.iter().filter(|(s, e)| e > s).count();
tally.same_lines_as_existing += kept - branches.len();
for branch in &branches {
if existing.iter().any(|r| r.start_line == branch.start_line) {
tally.shared_start += 1;
eprintln!(" shared start line {}: {}", branch.start_line + 1, path.display());
}
}
}
+142 -13
View File
@@ -6,13 +6,16 @@
//! output, or no edit at all and an error for the user to read. That holds for
//! the range requests too — their output is verified over the whole buffer,
//! and what makes a request a *range* format is which constructs it laid out,
//! not which bytes it was allowed to replace.
//! not which bytes it was allowed to replace. The range requests go through
//! `format_selection`: the smallest run of sibling items or statements the
//! selection covers, laid out at the indentation it was written at — see
//! `docs/features/selection-formatting/README.md`.
use std::path::Path;
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use vlog_formatter::{format_selection, format_source, style, Config, LineRanges, Style};
use crate::settings::ClientSettings;
use crate::state::Document;
@@ -52,6 +55,16 @@ pub struct Settings {
/// Each rung applies only where every rung above it is silent, so a project
/// with no `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did
/// before either existed.
///
/// **The style** (`[format] style`, `lucisv.format.style`) climbs rungs 1, 2
/// and 4 first, and supplies the indent and width the other keys then
/// overwrite. A style that was chosen on rung 1 or 2 also outranks rung 3:
/// `tabSize` is sent whether or not anyone chose it, and the editor's own
/// default of 4 silently undoing `google`'s 2 is not what choosing a style
/// asked for. With no style chosen — or `lucisv`, which is what VS Code sends
/// when nobody touched the drop-down, and which means exactly "what lucisv
/// always did", or `auto`, which chooses a layout but no size — rung 3
/// behaves exactly as it always has.
pub fn settings_for(
doc: &Document,
client: &ClientSettings,
@@ -83,10 +96,16 @@ pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings)
/// invent an edit from it.
pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, String> {
let formatted = format_source(&doc.text, config).map_err(|e| e.to_string())?;
Ok(whole_document_edit(doc, formatted))
}
/// The one edit that turns `doc` into `formatted`, or none when they are
/// already the same text.
pub fn whole_document_edit(doc: &Document, formatted: String) -> Option<TextEdit> {
if formatted == doc.text {
return Ok(None);
return None;
}
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted })
}
/// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request.
@@ -122,10 +141,12 @@ pub fn range_formatting(
///
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
/// before the engine sees them, so overlapping, adjacent, repeated and
/// unsorted input from the client all reach the same answer. No range is
/// formatted on its own — one `format_range` call lays out the union, which is
/// what keeps the all-or-nothing contract (CLAUDE.md invariant #1) whole
/// rather than making it a promise per range.
/// unsorted input from the client all reach the same answer. Each merged span
/// selects its own target (targets that overlap are re-selected from the hull
/// of their spans), but no range is formatted on its own — one
/// `format_selection` call lays out and verifies them all, which is what keeps
/// the all-or-nothing contract (CLAUDE.md invariant #1) whole rather than
/// making it a promise per range.
///
/// The reply is still one whole-document edit: the engine's contract is
/// all-or-nothing over the file, and a partial run's output differs from the
@@ -140,7 +161,7 @@ pub fn ranges_formatting(
return Ok(None);
}
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
let formatted = format_selection(&doc.text, config, &lines).map_err(|e| e.to_string())?;
if formatted == doc.text {
return Ok(None);
}
@@ -179,7 +200,16 @@ fn lines_of(range: Range) -> (u32, u32) {
/// lightbulb the editor requests on every cursor move would be noise.
pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize {
let (file, _problem) = discover(path);
file.indent.or(client.indent).unwrap_or(Config::default().indent_width)
file.indent
.or(client.indent)
.unwrap_or(chosen_style(&file, client).unwrap_or(style::LUCISV).indent)
}
/// The preset a project or a user picked for this buffer, `lucisv.toml`
/// first; `None` when neither did, or when the pick is `auto`, which names
/// no preset and so no indent.
fn chosen_style(file: &FileConfig, client: &ClientSettings) -> Option<Style> {
file.format_style.or(client.style).and_then(style::preset)
}
/// The config file governing `path`, by the CLI's own discovery rule, or the
@@ -208,8 +238,12 @@ fn discover(path: Option<&Path>) -> (FileConfig, Option<String>) {
/// protocol carries no line-length option — so before it existed there was no
/// way to set a width from an editor without a `lucisv.toml`.
fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingOptions) -> Config {
let mut config = Config::default();
if options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
let named = file.format_style.or(client.style).and_then(Config::named);
// `auto` picks a layout and no size, so it leaves the editor's rung alone
// exactly as "no style" and `lucisv` do.
let editor_rung = chosen_style(file, client).is_none_or(|s| s == style::LUCISV);
let mut config = named.unwrap_or_default();
if editor_rung && options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
config.indent_width = options.tab_size as usize;
}
if let Some(indent) = client.indent {
@@ -549,6 +583,68 @@ mod tests {
assert!(settings.config.uvm_utils_indent);
}
/// The style climbs rungs 1, 2 and 4, supplies the starting indent and
/// width, and — once someone actually chose one — outranks `tabSize`.
#[test]
fn a_style_sets_the_starting_values_and_outranks_tab_size() {
let styled = |name| ClientSettings { style: Some(name), ..Default::default() };
let (ws, uri) = document("module m;\nendmodule\n");
let config = |client: &ClientSettings, tab| {
settings_with(&ws, &uri, client, &options(tab, true)).config
};
// No style, and `lucisv` — what VS Code sends by default — are the
// same thing: `tabSize` is the indent, exactly as before styles.
assert_eq!((config(&none(), 4).indent_width, config(&none(), 4).style), (4, style::LUCISV));
assert_eq!(config(&styled("lucisv"), 4).indent_width, 4);
// A chosen style outranks `tabSize`...
let google = config(&styled("google"), 4);
assert_eq!((google.style, google.indent_width, google.max_width), (style::GOOGLE, 2, 100));
// ...but not an explicit `lucisv.indent`, and the width stays the style's.
let both =
ClientSettings { style: Some("microsoft"), indent: Some(2), ..Default::default() };
let microsoft = config(&both, 8);
assert_eq!((microsoft.indent_width, microsoft.max_width), (2, 120));
// A misspelt editor value never got this far: it is dropped on arrival.
assert_eq!(
crate::settings::from_payload(&serde_json::json!({
"lucisv": { "format": { "style": "gogle" } }
}))
.style,
None
);
}
#[test]
fn lucisv_toml_names_the_style_over_the_editor() {
let styled = |name| ClientSettings { style: Some(name), ..Default::default() };
let nxp = Tree::new("[format]\nstyle = \"nxp\"\n");
let (ws, uri) = nxp.document("module m;\nendmodule\n");
let settings = settings_with(&ws, &uri, &styled("microsoft"), &options(4, true));
assert_eq!(settings.problem, None);
let c = settings.config;
assert_eq!((c.style, c.indent_width, c.max_width), (style::NXP, 2, 80));
// The project's `lucisv` beats the editor's `google`, and with it the
// editor's `tabSize` is back in play.
let plain = Tree::new("[format]\nstyle = \"lucisv\"\n");
let (ws, uri) = plain.document("module m;\nendmodule\n");
let c = settings_with(&ws, &uri, &styled("google"), &options(4, true)).config;
assert_eq!((c.style, c.indent_width), (style::LUCISV, 4));
// The lint-fix width follows the style too, below the explicit keys.
let ansi = Tree::new("[format]\nstyle = \"ansi\"\n");
let path = ansi.path.join("m.sv");
assert_eq!(indent_width(Some(&path), &none()), 4);
assert_eq!(indent_width(None, &styled("microsoft")), 4);
let pushed = ClientSettings { indent: Some(3), ..styled("microsoft") };
assert_eq!(indent_width(Some(&path), &pushed), 3);
// A bad name in `lucisv.toml` is the config problem every bad key is.
let bad = Tree::new("[format]\nstyle = \"gogle\"\n");
let (ws, uri) = bad.document("module m;\nendmodule\n");
let settings = settings_with(&ws, &uri, &none(), &options(2, true));
let problem = settings.problem.expect("a problem");
assert!(problem.contains("unknown style `gogle`"), "{problem}");
assert_eq!(settings.config.style, style::LUCISV);
}
#[test]
fn each_key_climbs_the_ladder_independently() {
// A `lucisv.toml` naming only `indent` must not also claim the width:
@@ -700,6 +796,39 @@ mod tests {
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
}
/// A file indented four spaces with a `case` nested in an `always`: the
/// shape VS Code's "Format Selection" most often sends.
const NESTED: &str = "module m;\n always @* begin\n case (s)\n 0: y=a;\n default:y=b;\n endcase\n z = 1;\n end\nendmodule\n";
#[test]
fn a_selected_case_is_laid_out_alone_at_the_indentation_it_starts_at() {
let edit = ranged(NESTED, at(2, 0, 6, 0)).expect("formats").expect("changed");
assert_eq!(
edit.new_text,
"module m;\n always @* begin\n case (s)\n 0: y = a;\n default: y = b;\n endcase\n z = 1;\n end\nendmodule\n"
);
}
#[test]
fn a_tab_indented_selection_keeps_its_tabs() {
let text = "module m;\n\talways @* begin\n\t\tx=1;\n\tend\nendmodule\n";
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
assert_eq!(edit.new_text, "module m;\n\talways @* begin\n\t\tx = 1;\n\tend\nendmodule\n");
}
#[test]
fn a_parse_error_outside_the_selection_does_not_block_it() {
let text = "module m;\n always @* begin\n x=1;\n end\n assign y = ;\nendmodule\n";
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
assert_eq!(
edit.new_text,
"module m;\n always @* begin\n x = 1;\n end\n assign y = ;\nendmodule\n"
);
// Inside it, the request is refused with a message to read.
let message = ranged(text, at(4, 0, 4, 4)).expect_err("must refuse");
assert!(message.contains("syntax error"), "{message}");
}
#[test]
fn an_unparsable_buffer_produces_no_range_edit_either() {
// Range formatting cannot rescue broken input; the strict parse still
@@ -802,7 +931,7 @@ mod tests {
#[test]
fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() {
// No partial output on either path (CLAUDE.md invariant #1), and the
// same message: both are one `format_range` call away from the engine.
// same message: both are one `format_selection` call away from the engine.
let broken = "module m;\n wire ;\nendmodule\n";
let one = ranged(broken, at(0, 0, 0, 9));
let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]);
+84 -23
View File
@@ -30,12 +30,18 @@ use crate::convert::Positions;
use crate::state::Workspace;
use crate::uri::{path_to_uri, uri_to_path};
/// The module the cursor names, as the root of a hierarchy — its own
/// declaration, or an instantiation of it.
mod calls;
mod tf;
/// The root of a hierarchy at the cursor.
///
/// `None` for every other position, which is what stops an editor from opening
/// an empty hierarchy view on a `wire`. A name the workspace index does not
/// hold as a module declines the same way: there is no node to stand on.
/// In order: a module's own declaration name, or the module name of an
/// instantiation (both unchanged since M11); an instance name, which stands
/// for the instantiated module; a function or task the cursor names — its
/// declaration, a call, its end label; the function or task whose body holds
/// the cursor; and the module, interface or program whose body holds it.
/// `None` only where nothing encloses the cursor, which is what stops an
/// editor from opening an empty view.
///
/// A name two files declare returns *both* items rather than a guess, the same
/// answer `textDocument/definition` gives for the same ambiguity — the client
@@ -51,11 +57,27 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
let positions = doc.positions();
return Some(vec![item(uri.clone(), &positions, decl)?]);
}
// The cursor on an instantiation names the module being instantiated.
// The cursor on an instantiation names the module being instantiated —
// through its module name or through one of its instance names.
let sites = instantiations::sites(&doc.tree.items);
let site = sites.iter().find(|site| touches(site.inst.module_span, offset))?;
let items = declarations_of(ws, &site.inst.module);
(!items.is_empty()).then_some(items)
let on_module = sites.iter().find(|site| touches(site.inst.module_span, offset));
let on_instance = || {
sites.iter().find(|site| site.inst.instances.iter().any(|i| touches(i.name_span, offset)))
};
if let Some(site) = on_module.or_else(on_instance) {
let items = declarations_of(ws, &site.inst.module);
if !items.is_empty() {
return Some(items);
}
}
if let Some(items) = tf::prepare(ws, doc, uri, offset) {
return Some(items);
}
let decl = instantiations::declarations(&doc.tree.items)
.into_iter()
.filter(|decl| tf::holds(decl.span, offset))
.min_by_key(|decl| decl.span.end - decl.span.start)?;
Some(vec![item(uri.clone(), &doc.positions(), decl)?])
}
/// Who instantiates this module: one call per **instantiating module**, with
@@ -63,7 +85,14 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
///
/// One name asked of the batch below, which is the only census in this server
/// — the code lens counts what this lists.
///
/// A function or task item (one carrying `data`) is answered by its call
/// sites instead (`hierarchy/calls.rs`); a package or class caller item has
/// no incoming calls.
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
if let Some(data) = tf::Data::of(item) {
return calls::incoming(ws, item, &data);
}
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
}
@@ -131,7 +160,13 @@ pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyI
/// silently. A hierarchy node has nowhere to say "and one more I could not
/// find", and a node pointing at the wrong one of two same-named modules would
/// send the user to the wrong file with no way to tell.
///
/// A function or task item is answered by the calls in its body instead
/// (`hierarchy/calls.rs`). A module item never lists function calls.
pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
if let Some(data) = tf::Data::of(item) {
return calls::outgoing(ws, item, &data);
}
let Some(text) = text_of(ws, &item.uri) else { return Vec::new() };
let (tree, _) = parse_source_tolerant(&text);
let line_index = LineIndex::new(&text);
@@ -431,12 +466,17 @@ endmodule
);
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): the `module`
/// keyword and a connected expression are inside `top` and prepare it,
/// and an instance name stands for the instantiated module. Only a
/// position no module encloses still prepares nothing.
#[test]
fn a_position_on_no_module_prepares_nothing() {
fn a_position_on_no_module_prepares_the_enclosing_one_or_nothing() {
let (_tree, ws, uri) = three("none");
assert!(prepare(&ws, &uri, 0).is_none(), "the `module` keyword");
assert!(prepare(&ws, &uri, at(TOP, "u_a")).is_none(), "the instance name");
assert!(prepare(&ws, &uri, at(TOP, "1'b0")).is_none(), "a connected expression");
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0;
assert_eq!(name(0), "top", "the `module` keyword is inside `top`");
assert_eq!(name(at(TOP, "u_a")), "sub", "the instance name stands for its module");
assert_eq!(name(at(TOP, "1'b0")), "top", "a connected expression is inside `top`");
let (_tree, ws, uri) = workspace("nonmodule", &[("p.sv", "package p;\nendpackage\n")]);
assert!(prepare(&ws, &uri, at("package p;", "p;")).is_none(), "a package is not a module");
}
@@ -448,11 +488,14 @@ endmodule
assert!(prepare(&ws, &uri, at(SUB, "sub") + 3).is_some());
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): no item for
/// `nope`, which nothing declares, but the module the cursor is inside.
#[test]
fn an_instantiation_of_a_module_nothing_declares_prepares_nothing() {
fn an_instantiation_of_a_module_nothing_declares_prepares_the_enclosing_module() {
let top = "module top;\n nope u1 ();\nendmodule\n";
let (_tree, ws, uri) = workspace("undeclared", &[("top.sv", top)]);
assert!(prepare(&ws, &uri, at(top, "nope")).is_none());
let items = prepare(&ws, &uri, at(top, "nope")).expect("the enclosing module");
assert_eq!(shape(&items[0]), ("top".to_string(), "top.sv".to_string(), 0));
}
#[test]
@@ -894,18 +937,38 @@ endmodule
assert_eq!(inner_calls[0].to.name, "sub");
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): a comment or a
/// string inside `top` prepares `top` — never the `sub` its text spells.
#[test]
fn qa_prepare_on_a_string_or_comment_is_null() {
fn qa_prepare_on_a_string_or_comment_is_the_enclosing_module_not_the_text() {
let text = "module top;\n // sub lives here\n string s = \"sub\";\nendmodule\n";
let (_tree, ws, uri) = workspace("qa_string_comment", &[("top.sv", text)]);
let comment_offset = at(text, "// sub");
let string_offset = at(text, "\"sub\"") + 1;
assert!(prepare(&ws, &uri, comment_offset + 3).is_none(), "cursor inside a comment");
assert!(prepare(&ws, &uri, string_offset + 1).is_none(), "cursor inside a string literal");
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0;
assert_eq!(name(comment_offset + 3), "top", "cursor inside a comment");
assert_eq!(name(string_offset + 1), "top", "cursor inside a string literal");
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): the bind target
/// is still not read as a module name, but the cursor is inside the
/// module the `bind` is written in, and that is what it prepares. The
/// fixture moves the `bind` into `harness` so the two cannot coincide.
#[test]
fn qa_prepare_on_a_bind_target_module_name_is_currently_null() {
fn qa_prepare_on_a_bind_target_module_name_is_the_enclosing_module() {
let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n";
let top = "module top;\nendmodule\n";
let chk = "module chk;\nendmodule\n";
let files = [("harness.sv", harness), ("top.sv", top), ("chk.sv", chk)];
let (_tree, ws, uri) = workspace("qa_bind_target2", &files);
let items = prepare(&ws, &uri, at(harness, "bind top") + 5).expect("the enclosing module");
assert_eq!(shape(&items[0]).0, "harness", "not the bind target `top`");
}
/// The M11 QA pin, kept for its history: the answer it pinned is the
/// enclosing module now, which in this fixture is `top` itself.
#[test]
fn qa_prepare_on_a_bind_target_module_name_was_null() {
// `bind top chk u_chk ();` — cursor on `top`, the bind's *target*
// module. `top` is a real, declared module and a genuine reference to
// it, but neither `declarations()` (which only sees `module ...`
@@ -919,10 +982,8 @@ endmodule
let chk = "module chk;\nendmodule\n";
let (_tree, ws, uri) = workspace("qa_bind_target", &[("top.sv", top), ("chk.sv", chk)]);
let target_offset = at(top, "bind top") + 5;
assert!(
prepare(&ws, &uri, target_offset).is_none(),
"pinning today's answer, not endorsing it"
);
let items = prepare(&ws, &uri, target_offset).expect("the enclosing module");
assert_eq!(shape(&items[0]).0, "top", "the module the bind is written in");
}
#[test]
+512
View File
@@ -0,0 +1,512 @@
//! `incomingCalls` and `outgoingCalls` for a function or task item.
//!
//! A call is a *use* of the function's name that the semantic layer resolved
//! to its declaration — in this file through the symbol table, in another
//! file through the workspace overlay — and that is not one of the three
//! uses of a name that are not calls: the `endfunction : f` label, the name
//! of an out-of-body definition (`function void c::f();`), and the Verilog
//! result variable (`f = f + 1;` inside `f`).
//!
//! **Incoming** reads the same files `textDocument/references` reads: the
//! declaring file, every open buffer, and every closed file the index holds a
//! reference posting for. An ambiguous target falls back to the declaring
//! file alone, as references falls back to the cursor's file. Each call is
//! credited to its caller: the enclosing function or task, else the enclosing
//! module, interface, program, package or class.
//!
//! **Outgoing** reads the item's own body and resolves every call in it; a
//! system task, an unresolved name and an ambiguous one are skipped, as an
//! ambiguous instantiation is for a module.
use std::path::{Path, PathBuf};
use lsp_types::{CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, Uri};
use vlog_parser::TextRange;
use vlog_semantic::{
Def, ExternalTarget, Reference, ReferenceId, ScopeId, ScopeKind, Semantics, SymbolId,
SymbolKind as Kind,
};
use super::tf::{self, Analysis, Data};
use crate::nav::indexed_def_for_symbol;
use crate::state::{first_token_from, Document, Workspace};
use crate::uri::path_to_uri;
/// Every call of the function or task an item names, one entry per caller.
pub(super) fn incoming(
ws: &Workspace,
item: &CallHierarchyItem,
data: &Data,
) -> Vec<CallHierarchyIncomingCall> {
let Some((decl, symbol)) = tf::target(ws, item, data) else { return Vec::new() };
let Some(name) = decl.semantics.symbol(symbol).map(|s| s.name.clone()) else {
return Vec::new();
};
// Only a declaration the index holds — a package or class member — can be
// named through the workspace overlay, from another file or from its own
// (`super.f()` reaches a base class's method that way).
let def = decl
.path
.as_ref()
.and_then(|_| indexed_def_for_symbol(ws, &decl, decl.semantics.symbol(symbol)?));
let mut calls = callers(&item.uri, &decl, &name, |reference, id| {
reference.resolved() == Some(symbol) || def.is_some_and(|def| names_def(&decl, id, def))
});
if let Some(elsewhere) = def.and_then(|def| other_files(ws, &decl, def, &name)) {
calls.extend(elsewhere);
}
calls.sort_by(|a, b| {
(a.from.uri.as_str(), super::key(a.from.selection_range))
.cmp(&(b.from.uri.as_str(), super::key(b.from.selection_range)))
});
calls
}
/// The calls written in every file but the declaring one, or `None` when the
/// workspace cannot say which declaration a use names.
///
/// The same files `textDocument/references` reads for an indexed
/// declaration: every open buffer, and every closed file holding a reference
/// posting for it.
fn other_files(
ws: &Workspace,
decl: &Document,
def: &Def,
name: &str,
) -> Option<Vec<CallHierarchyIncomingCall>> {
let declaring = decl.path.as_deref()?;
if declined(ws, def, name, declaring) {
return None;
}
let index = ws.index();
let is_call_of_def = |doc: &Document, id: ReferenceId| names_def(doc, id, def);
let mut calls = Vec::new();
for (_, doc) in ws.open_documents() {
let Some(path) = doc.path.as_deref().filter(|path| *path != declaring) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
calls.extend(callers(&uri, doc, name, |_, id| is_call_of_def(doc, id)));
}
let mut closed: Vec<PathBuf> = index
.references_to(def)
.iter()
.filter_map(|site| index.path(site.file))
.filter(|path| *path != declaring && ws.document_for_path(path).is_none())
.map(Path::to_path_buf)
.collect();
closed.sort();
closed.dedup();
for path in closed {
let (Some(uri), Some(doc)) = (path_to_uri(&path), tf::load_path(ws, &path)) else {
continue;
};
calls.extend(callers(&uri, &doc, name, |_, id| is_call_of_def(&doc, id)));
}
Some(calls)
}
/// Whether the workspace cannot say which declaration a use of `def` names —
/// the index marks its uses ambiguous, or an open buffer other than the
/// declaring file holds a use that could be `def` or another declaration.
/// References declines in exactly these two cases.
///
/// In a consistent workspace neither can hold for a `def` that
/// `indexed_def_for_symbol` accepted (it demands a single record under the
/// very key every use's lookup reads), so this is the defensive half of the
/// contract; the tests reach it with a buffer the index does not hold and
/// with a lookup asked directly.
fn declined(ws: &Workspace, def: &Def, name: &str, declaring: &Path) -> bool {
ws.index().references_are_ambiguous(def)
|| ws.open_documents().any(|(_, doc)| {
doc.path.as_deref().is_some_and(|path| path != declaring)
&& names_it_ambiguously(doc, name, def)
})
}
/// Whether the workspace overlay answered one use with exactly `def`.
fn names_def(doc: &Document, id: ReferenceId, def: &Def) -> bool {
matches!(doc.external.get(id), Some(ExternalTarget::Resolved(found)) if found == def)
}
/// Whether an open buffer holds a use of `name` that could be `def` or
/// another declaration equally — the case references declines.
fn names_it_ambiguously(doc: &Document, name: &str, def: &Def) -> bool {
doc.semantics.references().iter().enumerate().any(|(at, reference)| {
reference.name == name
&& matches!(
doc.external.get(ReferenceId(at as u32)),
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(def)
)
})
}
/// One file's calls, grouped by caller, for the uses `names_target` accepts.
fn callers(
uri: &Uri,
doc: &Document,
name: &str,
names_target: impl Fn(&Reference, ReferenceId) -> bool,
) -> Vec<CallHierarchyIncomingCall> {
let semantics = &doc.semantics;
let mut groups: Vec<(SymbolId, Vec<TextRange>)> = Vec::new();
for (at, reference) in semantics.references().iter().enumerate() {
if reference.name != name || !names_target(reference, ReferenceId(at as u32)) {
continue;
}
if !is_call(doc, reference) {
continue;
}
let Some(caller) = caller_of(semantics, reference.scope) else { continue };
match groups.iter_mut().find(|(held, _)| *held == caller) {
Some((_, spans)) => spans.push(reference.name_span),
None => groups.push((caller, vec![reference.name_span])),
}
}
let positions = doc.positions();
groups
.into_iter()
.filter_map(|(caller, spans)| {
Some(CallHierarchyIncomingCall {
from: caller_item(uri, doc, caller)?,
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
})
})
.collect()
}
/// The declaration a call written in `scope` is credited to: the innermost
/// function or task, else the module, interface, program, package or class.
/// `None` for a call at file scope, which has no honest caller.
fn caller_of(semantics: &Semantics, mut scope: ScopeId) -> Option<SymbolId> {
loop {
let held = semantics.scope(scope)?;
let owner = held.owner;
match held.kind {
ScopeKind::Function
| ScopeKind::Task
| ScopeKind::Module
| ScopeKind::Package
| ScopeKind::Class
if owner.is_some() =>
{
return owner;
}
ScopeKind::File => return None,
_ => scope = held.parent?,
}
}
}
/// The item a caller is shown as. A module caller is the very item the
/// module hierarchy hands out — no `data` — so expanding it walks
/// instantiations, one level up the design.
fn caller_item(uri: &Uri, doc: &Document, caller: SymbolId) -> Option<CallHierarchyItem> {
let symbol = doc.semantics.symbol(caller)?;
match symbol.kind {
Kind::Function | Kind::Task => tf::item(uri.clone(), doc, symbol),
Kind::Package | Kind::Class => tf::container_item(uri.clone(), doc, symbol),
_ => super::item_of(
uri.clone(),
&doc.positions(),
&symbol.name,
symbol.name_span,
symbol.decl_span,
),
}
}
/// Whether a use of a function or task's name is a call of it.
///
/// Three uses are not: an end label (`endfunction : f`, recorded in the
/// scope *around* the function although written inside its extent), the name
/// of an out-of-body definition (recorded as a redeclaration), and the
/// Verilog result variable — a function's own name inside its own body with
/// no `(` after it, written (`f = a;`) or read (`f = f + 1;`).
fn is_call(doc: &Document, reference: &Reference) -> bool {
let semantics = &doc.semantics;
if semantics.duplicates().iter().any(|dup| dup.name_span == reference.name_span) {
return false;
}
let Some(id) = reference.resolved() else { return true };
let Some(symbol) = semantics.symbol(id) else { return true };
if let Some(body) = symbol.child_scope {
let inside = semantics.scope(body).is_some_and(|scope| {
tf::holds(scope.span, reference.name_span.start)
&& tf::holds(scope.span, reference.name_span.end)
});
if inside && !within(semantics, reference.scope, &[body]) {
return false;
}
}
!(symbol.kind == Kind::Function
&& in_own_body(semantics, reference.scope, id)
&& !followed_by_paren(doc, reference.name_span))
}
/// Whether `scope` is, or is nested in, a function body `function` owns — the
/// prototype's own scope or an out-of-body definition's.
fn in_own_body(semantics: &Semantics, mut scope: ScopeId, function: SymbolId) -> bool {
loop {
let Some(held) = semantics.scope(scope) else { return false };
if held.kind == ScopeKind::Function && held.owner == Some(function) {
return true;
}
match held.parent {
Some(parent) => scope = parent,
None => return false,
}
}
}
/// Whether the token after `span` is `(` — what makes a function's own name
/// inside its body a recursive call rather than its result variable.
fn followed_by_paren(doc: &Document, span: TextRange) -> bool {
let next = first_token_from(&doc.tokens, span.end);
doc.tokens.get(next).is_some_and(|token| token.is_sym("("))
}
/// Whether `scope` is one of `bodies` or nested inside one.
fn within(semantics: &Semantics, mut scope: ScopeId, bodies: &[ScopeId]) -> bool {
loop {
if bodies.contains(&scope) {
return true;
}
match semantics.scope(scope).and_then(|held| held.parent) {
Some(parent) => scope = parent,
None => return false,
}
}
}
/// What a callee is, before its item is built: a declaration in the same
/// file, or one the workspace index answered.
#[derive(PartialEq)]
enum Callee {
Local(SymbolId),
Indexed(Def),
}
/// Every function and task the item's body calls, one entry per callee.
pub(super) fn outgoing(
ws: &Workspace,
item: &CallHierarchyItem,
data: &Data,
) -> Vec<CallHierarchyOutgoingCall> {
let Some((doc, symbol)) = tf::target(ws, item, data) else { return Vec::new() };
let groups = callees(&doc, symbol);
let positions = doc.positions();
// Three hundred callees in one closed package are one parse, not three
// hundred.
let mut loaded = tf::Loaded::new(ws);
groups
.into_iter()
.filter_map(|(callee, spans)| {
let to = match callee {
Callee::Local(id) => tf::item(item.uri.clone(), &doc, doc.semantics.symbol(id)?),
Callee::Indexed(def) => loaded.item(&def),
}?;
let from_ranges = spans.into_iter().map(|span| positions.range(span)).collect();
Some(CallHierarchyOutgoingCall { to, from_ranges })
})
.collect()
}
/// The calls written in `symbol`'s bodies, grouped by what they resolve to.
///
/// "Bodies", plural: an `extern` prototype and its out-of-body definition are
/// two scopes owned by one symbol, and the definition is where the calls are.
fn callees(doc: &Analysis, symbol: SymbolId) -> Vec<(Callee, Vec<TextRange>)> {
let semantics = &doc.semantics;
let bodies: Vec<ScopeId> = semantics
.scopes()
.iter()
.enumerate()
.filter(|(_, scope)| scope.owner == Some(symbol))
.filter(|(_, scope)| matches!(scope.kind, ScopeKind::Function | ScopeKind::Task))
.map(|(at, _)| ScopeId(at as u32))
.collect();
let mut groups: Vec<(Callee, Vec<TextRange>)> = Vec::new();
for (at, reference) in semantics.references().iter().enumerate() {
if !within(semantics, reference.scope, &bodies) || !is_call(doc, reference) {
continue;
}
let Some(callee) = callee_of(doc, reference, ReferenceId(at as u32)) else { continue };
match groups.iter_mut().find(|(held, _)| *held == callee) {
Some((_, spans)) => spans.push(reference.name_span),
None => groups.push((callee, vec![reference.name_span])),
}
}
groups
}
/// The function or task one use resolves to, or `None` for anything else —
/// a variable, an unresolved name, a name two files declare.
fn callee_of(doc: &Document, reference: &Reference, id: ReferenceId) -> Option<Callee> {
if let Some(local) = reference.resolved() {
let symbol = doc.semantics.symbol(local)?;
return tf::is_tf(symbol.kind).then_some(Callee::Local(local));
}
match doc.external.get(id)? {
ExternalTarget::Resolved(def) if tf::is_tf(def.kind) => Some(Callee::Indexed(def.clone())),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every use of `name` in `text`, as `(line, is a call)`.
fn classified(text: &str, name: &str) -> Vec<(usize, bool)> {
let doc = Document::new(None, text.to_string(), &vlog_semantic::WorkspaceIndex::default());
doc.semantics
.references()
.iter()
.filter(|reference| reference.name == name)
.map(|r| (text[..r.name_span.start as usize].matches('\n').count(), is_call(&doc, r)))
.collect()
}
#[test]
fn an_end_label_a_result_assignment_and_a_redeclaration_are_not_calls() {
let text = "\
class c;
extern function int f(int a);
endclass
function int c::f(int a);
f = a;
f += 1;
return f(a - 1) + f;
endfunction : f
";
assert_eq!(
classified(text, "f"),
[(3, false), (4, false), (5, false), (6, true), (6, false)],
"the out-of-body name, two result writes, a recursive call, a result read (the \
binder records no use for an out-of-body definition's end label)"
);
}
#[test]
fn the_result_variable_read_in_its_own_body_is_not_a_call() {
// QA finding 1: the classic Verilog-2001 `clog2`.
let text = "\
module lg;
function integer clog2(input integer v);
begin
clog2 = 0;
while (v > 1) begin
clog2 = clog2 + 1;
v = v >> 1;
end
end
endfunction
initial $display(clog2(16));
endmodule
";
assert_eq!(
classified(text, "clog2"),
[(3, false), (5, false), (5, false), (10, true)],
"written, written, read inside its own body; called from the module"
);
}
#[test]
fn a_bare_function_name_in_another_body_is_a_call() {
// A function with no arguments may be called without parentheses.
let text = "\
module m;
function int g(); return 1; endfunction
function int h(); return g + 1; endfunction
function int k(); k = g; endfunction
endmodule
";
assert_eq!(classified(text, "g"), [(2, true), (3, true)]);
assert_eq!(classified(text, "k"), [(3, false)], "`k`'s own result, beside the call");
}
#[test]
fn an_end_label_is_not_a_call_but_a_recursive_call_is() {
let text =
"module m;\n function int f(int a);\n return f(a);\n endfunction : f\nendmodule\n";
assert_eq!(classified(text, "f"), [(2, true), (3, false)]);
}
#[test]
fn a_task_enable_without_parentheses_is_a_call() {
let text = "module m;\n task t; endtask\n initial t;\nendmodule\n";
assert_eq!(classified(text, "t"), [(2, true)]);
}
// ------------------------------------------------------------------
// The two ambiguity fallbacks (QA finding 4)
// ------------------------------------------------------------------
/// Package `p` declared twice, each with `f`; the caller writes `p::f()`.
const Z: &str = "package p;\n function int f(); return 1; endfunction\nendpackage\n";
const USER: &str = "module user;\n int k = p::f();\nendmodule\n";
/// A workspace over `root` holding the two `p`s and, if `user` is set,
/// a closed `user.sv`; plus `z1.f`'s indexed record and `z1.sv`'s path.
fn ambiguous(name: &str, user: bool) -> (std::path::PathBuf, Workspace, Def, PathBuf) {
let root =
std::env::temp_dir().join(format!("lucisv_server_calls_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("src")).expect("dir");
std::fs::write(root.join("src/z1.sv"), Z).expect("z1");
std::fs::write(root.join("src/z2.sv"), Z).expect("z2");
if user {
std::fs::write(root.join("src/user.sv"), USER).expect("user");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![root.join("src")]);
let z1 = root.join("src/z1.sv");
let def = ws
.index()
.member_in("p", "f", vlog_semantic::Surface::Connection)
.iter()
.find(|def| ws.index().path(def.file) == Some(z1.as_path()))
.cloned()
.expect("z1's f");
(root, ws, def, z1)
}
#[test]
fn an_index_that_marks_the_uses_ambiguous_declines() {
let (root, ws, def, z1) = ambiguous("index", true);
assert!(ws.index().references_are_ambiguous(&def), "premise: user.sv is indexed");
assert_eq!(ws.open_documents().count(), 0, "premise: no buffer is open");
assert!(declined(&ws, &def, "f", &z1));
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn an_open_buffer_holding_an_ambiguous_use_declines() {
// The buffer lives outside the indexed folder, so only its own
// overlay — not the index — knows the use is ambiguous.
let (root, mut ws, def, z1) = ambiguous("buffer", false);
assert!(!ws.index().references_are_ambiguous(&def), "premise: nothing indexed uses it");
assert!(!declined(&ws, &def, "f", &z1), "nothing ambiguous yet");
let outside = root.join("user.sv");
let uri = path_to_uri(&outside).expect("uri");
ws.set_document(uri, USER.to_string());
assert!(declined(&ws, &def, "f", &z1));
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn an_ambiguous_use_in_the_declaring_file_itself_does_not_decline() {
let (root, mut ws, def, z1) = ambiguous("declaring", false);
ws.set_document(path_to_uri(&z1).expect("uri"), format!("{Z}{USER}"));
assert!(!declined(&ws, &def, "f", &z1), "the declaring file answers for itself");
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn a_call_at_file_scope_has_no_caller() {
let text = "function int f(); return 1; endfunction\nlocalparam int P = f();\n";
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let call = semantics.references().iter().find(|r| r.name == "f").expect("the call");
assert_eq!(caller_of(&semantics, call.scope), None);
}
}
+416
View File
@@ -0,0 +1,416 @@
//! Function and task items for the call hierarchy: what the cursor names,
//! what encloses it, and how an item handed back by the client is found
//! again.
//!
//! A module item carries no `data` and is re-found by name, exactly as it
//! always was. A function or task item carries a small [`Data`] object — its
//! kind, its name and the byte offset of its name — because two functions of
//! one name are ordinary (every module may declare its own `log2`) and the
//! name alone cannot tell them apart.
//!
//! See `docs/features/call-hierarchy-everywhere/README.md`.
use std::collections::HashMap;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use lsp_types::{CallHierarchyItem, SymbolKind, Uri};
use serde_json::{json, Value};
use vlog_parser::TextRange;
use vlog_semantic::{Def, Definition, ScopeKind, Semantics, Symbol, SymbolId, SymbolKind as Kind};
use crate::nav::indexed_def_for_symbol;
use crate::state::{Document, Workspace};
use crate::uri::{path_to_uri, uri_to_path};
/// What a non-module item carries in `CallHierarchyItem.data`.
///
/// Serialized as `{"kind": "function"|"task"|"package"|"class", "name": …,
/// "offset": …}`, where `offset` is the byte offset of the declared name in
/// the item's file when the item was built.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Data {
pub kind: ItemKind,
pub name: String,
pub offset: u32,
}
/// Which declaration a [`Data`] item stands for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ItemKind {
Function,
Task,
/// A package caller: the body of a package called a function outside any
/// function of its own. It has no calls of its own to expand.
Package,
/// A class caller, for a call written in a class body outside a method.
Class,
}
impl ItemKind {
fn tag(self) -> &'static str {
match self {
ItemKind::Function => "function",
ItemKind::Task => "task",
ItemKind::Package => "package",
ItemKind::Class => "class",
}
}
fn of_tag(tag: &str) -> Option<ItemKind> {
match tag {
"function" => Some(ItemKind::Function),
"task" => Some(ItemKind::Task),
"package" => Some(ItemKind::Package),
"class" => Some(ItemKind::Class),
_ => None,
}
}
/// The semantic kind a function or task item re-finds; `None` for the
/// container kinds, which are never re-found.
fn semantic(self) -> Option<Kind> {
match self {
ItemKind::Function => Some(Kind::Function),
ItemKind::Task => Some(Kind::Task),
ItemKind::Package | ItemKind::Class => None,
}
}
}
impl Data {
/// The JSON object the item carries.
fn to_value(&self) -> Value {
json!({ "kind": self.kind.tag(), "name": self.name, "offset": self.offset })
}
/// The data of an item this server built, or `None` for a module item
/// (which carries none) and for anything it does not recognise.
pub fn of(item: &CallHierarchyItem) -> Option<Data> {
let data = item.data.as_ref()?;
let kind = ItemKind::of_tag(data.get("kind")?.as_str()?)?;
let name = data.get("name")?.as_str()?.to_string();
let offset = u32::try_from(data.get("offset")?.as_u64()?).ok()?;
Some(Data { kind, name, offset })
}
}
/// Whether a declaration is something a call hierarchy can stand on as a
/// function or task.
pub(super) fn is_tf(kind: Kind) -> bool {
matches!(kind, Kind::Function | Kind::Task)
}
/// One file's analysis: the open buffer's own, or one built from the text on
/// disk for a file no editor has open.
pub(super) enum Analysis<'a> {
Open(&'a Document),
Fresh(Box<Document>),
}
impl Deref for Analysis<'_> {
type Target = Document;
fn deref(&self) -> &Document {
match self {
Analysis::Open(doc) => doc,
Analysis::Fresh(doc) => doc,
}
}
}
/// The analysis behind an item's URI: the open buffer, else the file on disk.
pub(super) fn load<'a>(ws: &'a Workspace, uri: &Uri) -> Option<Analysis<'a>> {
match ws.document(uri) {
Some(doc) => Some(Analysis::Open(doc)),
None => load_path(ws, &uri_to_path(uri)?),
}
}
/// The analysis of one path: the open buffer for it, else a fresh analysis
/// of the text on disk against the current index.
pub(super) fn load_path<'a>(ws: &'a Workspace, path: &Path) -> Option<Analysis<'a>> {
if let Some(doc) = ws.document_for_path(path) {
return Some(Analysis::Open(doc));
}
let text = ws.text_of(path)?;
Some(Analysis::Fresh(Box::new(Document::new(Some(path.to_path_buf()), text, ws.index()))))
}
/// The analyses one request has loaded, one per path, so a request that
/// builds items in one closed file many times — `outgoingCalls` on a function
/// calling three hundred functions of one package — parses it once.
///
/// Lives for one request and no longer: nothing here may outlast a change to
/// the text it was built from.
pub(super) struct Loaded<'a> {
ws: &'a Workspace,
held: HashMap<PathBuf, Option<Analysis<'a>>>,
}
impl<'a> Loaded<'a> {
pub fn new(ws: &'a Workspace) -> Loaded<'a> {
Loaded { ws, held: HashMap::new() }
}
/// The analysis of `path`, loaded on first ask.
pub fn get(&mut self, path: &Path) -> Option<&Analysis<'a>> {
let ws = self.ws;
self.held.entry(path.to_path_buf()).or_insert_with(|| load_path(ws, path)).as_ref()
}
}
/// The function or task the cursor names — its declaration, a call, an end
/// label — or, failing that, the one whose body encloses the cursor.
///
/// A call two files could answer returns both declarations, as
/// `textDocument/definition` does; the client asks the user which one.
pub(super) fn prepare(
ws: &Workspace,
doc: &Document,
uri: &Uri,
offset: u32,
) -> Option<Vec<CallHierarchyItem>> {
let named = doc
.external
.definition_of(&doc.semantics, offset)
.or_else(|| doc.external.definition_of(&doc.semantics, offset.checked_sub(1)?));
let items: Vec<CallHierarchyItem> = match named {
Some(Definition::Local(symbol)) if is_tf(symbol.kind) => {
item(uri.clone(), doc, symbol).into_iter().collect()
}
Some(Definition::External(defs)) => {
let mut loaded = Loaded::new(ws);
defs.iter().filter(|def| is_tf(def.kind)).filter_map(|def| loaded.item(def)).collect()
}
_ => Vec::new(),
};
if !items.is_empty() {
return Some(items);
}
let symbol = enclosing(&doc.semantics, offset)?;
Some(vec![item(uri.clone(), doc, doc.semantics.symbol(symbol)?)?])
}
/// The function or task whose body holds `offset`, innermost first.
///
/// An out-of-body method definition (`function void c::f(); … endfunction`)
/// is a scope owned by the prototype's symbol, so its body answers the
/// prototype.
fn enclosing(semantics: &Semantics, offset: u32) -> Option<SymbolId> {
semantics
.scopes()
.iter()
.filter(|scope| matches!(scope.kind, ScopeKind::Function | ScopeKind::Task))
.filter(|scope| holds(scope.span, offset))
.filter(|scope| {
scope.owner.and_then(|id| semantics.symbol(id)).is_some_and(|s| is_tf(s.kind))
})
.min_by_key(|scope| scope.span.end - scope.span.start)
.and_then(|scope| scope.owner)
}
/// The item for a function or task declared in `doc`, reported against `uri`.
pub(super) fn item(uri: Uri, doc: &Document, symbol: &Symbol) -> Option<CallHierarchyItem> {
let kind = if symbol.kind == Kind::Task { ItemKind::Task } else { ItemKind::Function };
let in_class = scope_kind(&doc.semantics, symbol) == Some(ScopeKind::Class);
let lsp_kind = if in_class { SymbolKind::METHOD } else { SymbolKind::FUNCTION };
built(uri, doc, symbol, kind, lsp_kind)
}
/// The item for a package or class that is a caller.
pub(super) fn container_item(
uri: Uri,
doc: &Document,
symbol: &Symbol,
) -> Option<CallHierarchyItem> {
match symbol.kind {
Kind::Package => built(uri, doc, symbol, ItemKind::Package, SymbolKind::PACKAGE),
Kind::Class => built(uri, doc, symbol, ItemKind::Class, SymbolKind::CLASS),
_ => None,
}
}
/// An item with [`Data`], framed against `doc`'s text.
fn built(
uri: Uri,
doc: &Document,
symbol: &Symbol,
kind: ItemKind,
lsp_kind: SymbolKind,
) -> Option<CallHierarchyItem> {
let mut item =
super::item_of(uri, &doc.positions(), &symbol.name, symbol.name_span, symbol.decl_span)?;
item.kind = lsp_kind;
item.detail = container_name(&doc.semantics, symbol);
let data = Data { kind, name: symbol.name.clone(), offset: symbol.name_span.start };
item.data = Some(data.to_value());
Some(item)
}
/// The kind of the scope a declaration is bound in.
fn scope_kind(semantics: &Semantics, symbol: &Symbol) -> Option<ScopeKind> {
semantics.scope(symbol.scope).map(|scope| scope.kind)
}
/// The name of the module, package or class a function is declared in —
/// shown beside the name, so two `log2`s in one list can be told apart.
fn container_name(semantics: &Semantics, symbol: &Symbol) -> Option<String> {
let owner = semantics.scope(symbol.scope)?.owner?;
Some(semantics.symbol(owner)?.name.clone())
}
impl Loaded<'_> {
/// The item for a function or task another file declares, re-found in
/// that file's live analysis so its ranges are the text's as it is now.
pub fn item(&mut self, def: &Def) -> Option<CallHierarchyItem> {
let ws = self.ws;
let path = ws.index().path(def.file)?;
let uri = path_to_uri(path)?;
let doc = self.get(path)?;
let symbol = live_symbol(ws, doc, def)?;
item(uri, doc, doc.semantics.symbol(symbol)?)
}
}
/// The symbol in `doc` that is the indexed declaration `def`: by identity —
/// asked first of the symbol still at the recorded position, which is the
/// answer unless the file moved — and by position as a last resort.
fn live_symbol(ws: &Workspace, doc: &Document, def: &Def) -> Option<SymbolId> {
let candidates: Vec<SymbolId> = doc
.semantics
.symbols()
.iter()
.enumerate()
.filter(|(_, symbol)| symbol.kind == def.kind)
.map(|(at, _)| SymbolId(at as u32))
.collect();
let symbol = |id: &SymbolId| doc.semantics.symbol(*id);
let is_def =
|id: &&SymbolId| symbol(id).and_then(|s| indexed_def_for_symbol(ws, doc, s)) == Some(def);
let at_position = |id: &&SymbolId| symbol(id).is_some_and(|s| s.name_span == def.name_span);
let positioned = candidates.iter().find(at_position);
positioned.filter(is_def).or_else(|| candidates.iter().find(is_def)).or(positioned).copied()
}
/// The declaration a function or task item stands for, in its file's live
/// analysis.
///
/// The recorded offset wins; an edit since the item was built moves it, and
/// then the item's own selection range is tried. Failing both, the name
/// decides only when it is unambiguous: the one declaration of that name and
/// kind whose container is the item's `detail`.
/// Otherwise nothing — two `log2`s in two modules are ordinary, and answering
/// for the wrong one would be a confident wrong hierarchy.
pub(super) fn target<'a>(
ws: &'a Workspace,
item: &CallHierarchyItem,
data: &Data,
) -> Option<(Analysis<'a>, SymbolId)> {
let kind = data.kind.semantic()?;
let doc = load(ws, &item.uri)?;
let candidates: Vec<SymbolId> = doc
.semantics
.symbols_named(&data.name)
.filter(|id| doc.semantics.symbol(*id).is_some_and(|s| s.kind == kind))
.collect();
let starts_at = |offset: u32| {
candidates
.iter()
.find(|id| doc.semantics.symbol(**id).is_some_and(|s| s.name_span.start == offset))
.copied()
};
let selected = doc.positions().offset(item.selection_range.start);
let found = starts_at(data.offset)
.or_else(|| starts_at(selected))
.or_else(|| by_name(&doc.semantics, &candidates, item.detail.as_deref()))?;
Some((doc, found))
}
/// The one candidate a name alone can stand for: the only one declared in
/// the container the item's `detail` names (no container for `$unit`).
///
/// The container is asked even of a lone candidate: when `mb`'s `log2` has
/// been renamed away, `ma`'s is the only `log2` left, and it is still not the
/// function the item stood for.
fn by_name(
semantics: &Semantics,
candidates: &[SymbolId],
detail: Option<&str>,
) -> Option<SymbolId> {
let mut inside = candidates.iter().filter(|id| {
semantics.symbol(**id).is_some_and(|s| container_name(semantics, s).as_deref() == detail)
});
match (inside.next(), inside.next()) {
(Some(one), None) => Some(*one),
_ => None,
}
}
/// Whether `span` holds `offset`, its end included.
pub(super) fn holds(span: TextRange, offset: u32) -> bool {
span.start <= offset && offset <= span.end
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use lsp_types::{Position, Range};
use super::*;
fn bare(data: Option<Value>) -> CallHierarchyItem {
let range = Range::new(Position::new(0, 0), Position::new(0, 1));
CallHierarchyItem {
name: "f".to_string(),
kind: SymbolKind::FUNCTION,
tags: None,
detail: None,
uri: Uri::from_str("file:///x.sv").expect("uri"),
range,
selection_range: range,
data,
}
}
#[test]
fn data_round_trips_through_its_json() {
for kind in [ItemKind::Function, ItemKind::Task, ItemKind::Package, ItemKind::Class] {
let data = Data { kind, name: "f".to_string(), offset: 42 };
assert_eq!(Data::of(&bare(Some(data.to_value()))), Some(data));
}
}
#[test]
fn a_module_item_and_foreign_data_carry_no_data_of_ours() {
assert_eq!(Data::of(&bare(None)), None, "a module item");
for foreign in [
json!({ "kind": "rocket", "name": "f", "offset": 1 }),
json!({ "kind": "function", "name": "f" }),
json!({ "kind": "function", "name": 7, "offset": 1 }),
json!({ "kind": "function", "name": "f", "offset": -1 }),
json!({ "kind": "function", "name": "f", "offset": 5_000_000_000u64 }),
json!("function"),
] {
assert_eq!(Data::of(&bare(Some(foreign.clone()))), None, "{foreign}");
}
}
#[test]
fn the_innermost_function_or_task_encloses_an_offset() {
let text = "module m;\n task t;\n begin\n x = 1;\n end\n endtask\n \
wire w;\nendmodule\n";
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let name = |offset| {
enclosing(&semantics, offset)
.and_then(|id| semantics.symbol(id))
.map(|s| s.name.clone())
};
let at = |needle: &str| text.find(needle).expect("needle") as u32;
assert_eq!(name(at("x = 1")).as_deref(), Some("t"), "through a nested block");
assert_eq!(name(at("endtask") + 7).as_deref(), Some("t"), "the end included");
assert_eq!(name(at("wire")), None, "a module item is in no task");
}
}
+2
View File
@@ -1572,6 +1572,8 @@ mod qa_hover_declarations {
use crate::uri::path_to_uri;
use std::fs;
use std::path::PathBuf;
// Its one user is the case-insensitive-filesystem test below.
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::str::FromStr;
fn temp_dir(tag: &str) -> PathBuf {
+106 -23
View File
@@ -86,7 +86,7 @@ fn include_on_line(line: &str, base: u32) -> Option<Include> {
///
/// 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`]).
/// ([`IncludeGraph::update_held`]).
#[derive(Debug, Default, Clone)]
pub struct IncludeGraph {
/// The `+incdir+` directories of the configured filelist, in filelist
@@ -107,6 +107,11 @@ pub struct IncludeGraph {
/// 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 held file's `` `include`` lines as written, resolved or not — so
/// a file appearing or vanishing anywhere on disk can be answered by
/// re-resolving just the lines that could name it
/// ([`IncludeGraph::refresh_naming`]), without reading a file.
lines: HashMap<PathBuf, Vec<Include>>,
/// 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`
@@ -154,29 +159,81 @@ impl IncludeGraph {
graph
}
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
/// Re-scan one file's `` `include``s, the rest of the graph left standing —
/// for a file whose text changed while the file set did not, a save of a
/// file the index already holds. The known-file and folded-spelling tables
/// are a function of the file set, and every other file's edges a function
/// of its own text and those tables, so only this file's edges are
/// re-scanned and re-spelled (`docs/features/localized-reindex/README.md`).
///
/// `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);
/// Until 2026-11-19 this was `update_file`, which also re-learned both
/// tables and re-spelled every edge — O(files) for an answer that cannot
/// move. Its one honest limit is unchanged: an edge of a *different* file
/// is not re-**resolved** against the disk, which is why the incremental
/// path takes only a file the index already holds.
pub fn update_held(&mut self, path: &Path, text: &str) {
self.rescan_edges(path, text);
self.respell();
self.respell_one(path);
}
/// [`IncludeGraph::update_file`] for a batch of files whose `` `include``
/// Re-resolve the `` `include`` lines of every held file that writes one
/// whose last component could be `path`'s name — the only lines a file
/// appearing, vanishing or moving at `path` can change the answer of,
/// whether or not `path` is in scope: an include is resolved against the
/// disk, not against the scope (`docs/features/localized-reindex`, QA F1).
///
/// The name is compared case-insensitively, so a case-insensitive disk is
/// covered, and a target with no last component (`..`) counts as naming
/// everything. Reads no file: the lines are held.
pub fn refresh_naming(&mut self, path: &Path) {
self.refresh_naming_all(std::slice::from_ref(&path.to_path_buf()));
}
/// [`IncludeGraph::refresh_naming`] for every path of one watcher event
/// at once: one pass over the held lines for the whole set of names, so a
/// burst of ten thousand generated files costs one pass, not ten thousand
/// (QA R2-1). A line is re-resolved exactly when it would have been for
/// one of the paths alone, and re-resolving a file twice gives what once
/// does, so the batch is the same answer.
pub fn refresh_naming_all(&mut self, paths: &[PathBuf]) {
let folded = |name: &std::ffi::OsStr| name.to_string_lossy().to_lowercase();
let names: HashSet<String> =
paths.iter().filter_map(|path| path.file_name()).map(folded).collect();
if names.is_empty() {
return;
}
let could_name = |include: &Include| {
Path::new(&include.target).file_name().is_none_or(|last| names.contains(&folded(last)))
};
let mut naming: Vec<PathBuf> = self
.lines
.iter()
.filter(|(_, lines)| lines.iter().any(could_name))
.map(|(from, _)| from.clone())
.collect();
naming.sort();
for from in naming {
let lines = self.lines.get(&from).cloned().unwrap_or_default();
self.rescan_found(&from, &lines);
self.respell_one(&from);
}
}
/// Re-spell one file's edges from its raw ones.
fn respell_one(&mut self, path: &Path) {
match self.raw.get(path) {
Some(targets) => {
let spelled =
targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect();
self.edges.insert(path.to_path_buf(), spelled);
}
None => {
self.edges.remove(path);
}
}
}
/// [`IncludeGraph::update_held`] for a batch of files whose `` `include``
/// lines have already been read, with the `+incdir+`s the scope resolves
/// to right now — the form a scan publishing what it has indexed so far
/// uses. The lines come from the step that indexed each file, for the
@@ -203,11 +260,29 @@ impl IncludeGraph {
self.respell();
}
/// Take `path` into the file set: known, folded, and every held edge
/// re-spelled against the new set — what [`IncludeGraph::from_includes`]
/// over the old set and `path` would have learned. Its own edges are
/// [`IncludeGraph::update_held`]'s business.
pub fn add_known(&mut self, path: &Path) {
if !self.known.insert(path.to_path_buf()) {
return;
}
if let Some(key) = path.to_str().map(str::to_lowercase) {
self.folded
.entry(key)
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.to_path_buf()));
}
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.lines.remove(path);
self.respell();
}
@@ -223,6 +298,10 @@ impl IncludeGraph {
fn rescan_found(&mut self, path: &Path, found: &[Include]) {
let targets: Vec<PathBuf> =
found.iter().filter_map(|include| self.found(Some(path), include)).collect();
match found.is_empty() {
true => self.lines.remove(path),
false => self.lines.insert(path.to_path_buf(), found.to_vec()),
};
match targets.is_empty() {
true => self.raw.remove(path),
false => self.raw.insert(path.to_path_buf(), targets),
@@ -425,6 +504,9 @@ impl IncludeGraph {
let mut raw: Vec<(&PathBuf, &Vec<PathBuf>)> = self.raw.iter().collect();
raw.sort();
out.push_str(&format!("raw {raw:?}\n"));
let mut lines: Vec<(&PathBuf, &Vec<Include>)> = self.lines.iter().collect();
lines.sort_by_key(|(path, _)| *path);
out.push_str(&format!("lines {lines:?}\n"));
out
}
}
@@ -952,7 +1034,10 @@ mod qa_scope_probe {
}
}
#[cfg(test)]
/// Both probes need `is_file` to succeed for a spelling the file does not
/// have, which only a case-insensitive filesystem does — macOS's and
/// Windows' defaults — so the module is scoped to them.
#[cfg(all(test, any(target_os = "macos", target_os = "windows")))]
mod qa_round2 {
use super::*;
use std::fs;
@@ -963,7 +1048,6 @@ mod qa_round2 {
/// unconditionally once a collision exists, so a third colliding entry is
/// a no-op over an already-`None` slot rather than something that could
/// re-arm it — confirmed here rather than only read off the source.
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn three_files_colliding_on_one_folded_spelling_stay_ambiguous() {
let dir =
@@ -995,7 +1079,6 @@ mod qa_round2 {
/// must come back exactly as before this fix — `folded` only ever learns
/// about in-scope files, so an out-of-scope collision has no entry to
/// find and falls through to the "no match" arm, unchanged.
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn a_case_mismatch_on_a_file_outside_the_graphs_scope_is_unchanged() {
let dir =
+82 -25
View File
@@ -27,16 +27,19 @@
//! because the editor prepends that line's own indentation when it inserts the
//! snippet; see `render`. See `docs/features/inline-templates/README.md`.
use lsp_types::{Position, Range, Uri};
use lsp_types::{Position, Range, SelectedCompletionInfo, Uri};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_refactor::{Layout, Site};
use crate::completion;
use crate::on_type;
use crate::pairs;
use crate::state::{Document, Workspace};
use crate::templates::{self, Dialect};
mod keywords;
/// One line of a body: how many indent steps it sits in, and its text. The
/// same shape `templates.rs` writes its skeletons in.
type Line = (u8, &'static str);
@@ -96,6 +99,13 @@ const BEGIN_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "end")];
const FORK_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "join")];
const GENERATE_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "endgenerate")];
/// The event control of a flop with an async active-low reset, both edges a
/// tabstop. First in both `always` families (TODO §68.1): the commoner flop.
const CLOCK_AND_RESET: &[Line] =
&[(0, "posedge ${1:clk} or negedge ${2:rst_n}) begin"), (1, "$0"), (0, "end")];
/// The clock-only event control, one cycle away.
const CLOCK_ONLY: &[Line] = &[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")];
/// Every construct that offers ghost text.
///
/// The order is the order `triggered` tries them, which only matters when two
@@ -156,19 +166,16 @@ const TRIGGERS: &[Trigger] = &[
opener: EVENT,
dialect: Some(Dialect::SystemVerilog),
gate: Unclosed::Paren,
bodies: &[&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")]],
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY],
},
Trigger {
keyword: "always",
opener: EVENT,
dialect: None,
gate: Unclosed::Paren,
// Two items, clocked first: `always @(` is overwhelmingly a flop, and
// the client cycles to the second with one keystroke.
bodies: &[
&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
&[(0, "*) begin"), (1, "$0"), (0, "end")],
],
// Three items, clocked first: `always @(` is overwhelmingly a flop,
// and the client cycles to the next with one keystroke.
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY, &[(0, "*) begin"), (1, "$0"), (0, "end")]],
},
Trigger {
keyword: "begin",
@@ -237,7 +244,15 @@ pub struct InlineItems {
/// `None` rather than an empty list wherever there is nothing to say: an
/// editor treats both the same, and `null` is the cheaper answer to a request
/// that arrives on every keystroke.
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
///
/// `selected` is the request's `context.selectedCompletionInfo` — the popup's
/// selected entry, when one is showing. Only the keyword ghost reads it.
pub fn inline_completions_in_context(
ws: &Workspace,
uri: &Uri,
position: Position,
selected: Option<&SelectedCompletionInfo>,
) -> Option<InlineItems> {
let doc = ws.document(uri)?;
// No token stream, no answer — the same trade `completion.rs` makes. A
// half-typed string or block comment is what breaks the lexer, and those
@@ -260,14 +275,24 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
return instantiation(ws, doc, name, at);
}
let last = last_token(doc, offset)?;
match doc.tokens.get(last)?.kind {
// A name with nothing after it is not an offer (owner ruling,
// 2026-08-30): `aes` may still be growing into `aes_dft`, and the
// space is the user saying that it is not. No trigger's own last token
// is an `Ident` either, so nothing is lost by stopping here.
TokenKind::Ident => None,
_ => template(ws, doc, last, at),
// A name with nothing after it is not an instantiation offer (owner
// ruling, 2026-08-30): `aes` may still be growing into `aes_dft`, and the
// space is the user saying that it is not. No trigger's own last token is
// an `Ident` either, so only the keyword ghost is asked about one.
if doc.tokens.get(last)?.kind != TokenKind::Ident {
if let Some(items) = template(ws, doc, last, at) {
return Some(items);
}
}
// The fallback: the rest of a keyword the word is a proper prefix of.
keywords::keyword_ghost(ws, doc, last, position, selected)
}
/// [`inline_completions_in_context`] with no popup open — what every test
/// that is not about the popup asks.
#[cfg(test)]
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
inline_completions_in_context(ws, uri, position, None)
}
/// The identifier the user has just finished and armed with a space: the token
@@ -299,7 +324,7 @@ fn template(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<In
return None;
}
let (trigger, opened) = triggered(doc, last)?;
if !unfinished(doc, trigger, opened) {
if !unfinished(doc, trigger, opened, last) {
return None;
}
Some(InlineItems {
@@ -487,13 +512,20 @@ fn triggered(doc: &Document, index: usize) -> Option<(&'static Trigger, Opened)>
}
/// Whether the construct the user opened really is still waiting to be closed.
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened) -> bool {
///
/// `last` is the index of the token just typed — for `begin`, the keyword
/// itself, which is asked the auto-`end` question (`on_type::auto_end`)
/// rather than "is this span unmatched": a `begin` typed inside a balanced
/// block steals that block's `end` in the stack matcher, and would otherwise
/// get no ghost (`completion-ux` fix round, 2026-11-17).
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened, last: usize) -> bool {
let paren = || !paren_is_closed(&doc.tokens, opened.last);
let scope = || {
pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened.keyword)
};
match trigger.gate {
Unclosed::Paren => paren(),
Unclosed::Scope if trigger.keyword == "begin" => on_type::begin_owes_an_end(doc, last),
Unclosed::Scope => scope(),
// The paren check first: it is a flat pass over the tokens, and
// skipping `pairs::analyze` when it already says no is what keeps this
@@ -822,15 +854,16 @@ endmodule
}
#[test]
fn an_always_at_offers_the_clocked_block_first_and_the_star_second() {
fn an_always_at_offers_clock_and_reset_first_then_clock_only_then_the_star() {
let text = "module top;\n always @(\nendmodule\n";
assert_eq!(
all_offered(text, "always @("),
vec![
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend".to_string(),
"posedge ${1:clk}) begin\n\t$0\nend".to_string(),
"*) begin\n\t$0\nend".to_string(),
],
"clocked first: `always @(` is overwhelmingly a flop"
"clocked first: `always @(` is overwhelmingly a flop, and most flops reset"
);
}
@@ -839,7 +872,10 @@ endmodule
let text = "module top;\n always_ff @(\nendmodule\n";
assert_eq!(
offered_in("/rtl/top.sv", text, "always_ff @("),
vec!["posedge ${1:clk}) begin\n\t$0\nend"]
vec![
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend",
"posedge ${1:clk}) begin\n\t$0\nend"
]
);
assert!(
offered_in("/rtl/top.v", text, "always_ff @(").is_empty(),
@@ -930,6 +966,15 @@ endmodule
assert!(offered(text, "initial begin").is_some(), "this one lost its end");
}
#[test]
fn a_begin_typed_inside_a_balanced_block_still_offers_its_end() {
// The new `begin` steals the `always_comb` block's `end` in the stack
// matcher; the gate asks the auto-`end` question instead
// (`completion-ux` fix round, 2026-11-17).
let text = "module top;\n always_comb begin\n if (x) begin\n end\nendmodule\n";
assert_eq!(offered(text, "if (x) begin").as_deref(), Some("\n\t$0\nend"));
}
#[test]
fn a_scope_keyword_that_already_has_its_closer_offers_nothing() {
// The same rule as `begin`, for the three keywords that joined it.
@@ -1019,8 +1064,10 @@ endmodule
fn an_always_without_its_event_control_offers_nothing() {
// The opener is a *sequence*: both `@` and `(` must be there, in that
// order, or the user has not committed to an event-controlled block.
// A bare `always` grows no block — only the keyword ghost's `_ff`,
// which is a different feature with its own setting.
let text = "module top;\n always\nendmodule\n";
assert_eq!(offered(text, " always"), None);
assert_eq!(offered(text, " always").as_deref(), Some("_ff"));
let text = "module top;\n always @\nendmodule\n";
assert_eq!(offered(text, "always @"), None);
let text = "module top;\n always (\nendmodule\n";
@@ -1140,7 +1187,7 @@ endmodule
assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
// ...and the same for a two-symbol opener written tight.
let text = "module top;\n always@(\nendmodule\n";
assert_eq!(all_offered(text, "always@(").len(), 2);
assert_eq!(all_offered(text, "always@(").len(), 3);
}
#[test]
@@ -1532,7 +1579,7 @@ endmodule
// `no_space_between_the_keyword_and_the_paren_still_triggers`, this
// pins the opposite spacing.
let text = "module top;\n always @ (\nendmodule\n";
assert_eq!(all_offered(text, "always @ (").len(), 2);
assert_eq!(all_offered(text, "always @ (").len(), 3);
}
#[test]
@@ -1588,7 +1635,7 @@ endmodule
// counterpart — both must still offer.
let text = "module top;\n if (\n always @(\nendmodule\n";
assert!(offered(text, " if (").is_some());
assert_eq!(all_offered(text, " always @(").len(), 2);
assert_eq!(all_offered(text, " always @(").len(), 3);
}
// ------------------------------------------------------------------
@@ -1629,6 +1676,16 @@ endmodule
serde_json::to_value(&items).expect("serializes"),
serde_json::json!({
"items": [
{
"insertText": {
"kind": "snippet",
"value": "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
},
"range": {
"start": { "line": 1, "character": 11 },
"end": { "line": 1, "character": 11 }
}
},
{
"insertText": {
"kind": "snippet",
+519
View File
@@ -0,0 +1,519 @@
//! Keyword ghosts (TODO §68.1): a typed proper prefix of a keyword shows the
//! rest of it as grey text — `alw` grows `ays_ff`, Tab accepts.
//!
//! The fallback ghost: asked only where no template trigger answered, and
//! only for an identifier-like word of two characters or more that ends
//! exactly at the cursor. Three rules decide which keyword, in order:
//!
//! 1. **The popup's choice.** While VS Code's suggest widget is open it shows
//! an inline item only if it extends the selected entry over the selected
//! entry's range (LSP 3.18 `selectedCompletionInfo`). So with a selection,
//! the ghost is exactly that keyword when it is one, and nothing otherwise.
//! 2. **A fixed priority list** of the words an RTL designer types all day.
//! 3. **Shortest, then alphabetical**, over every keyword of the buffer's
//! dialect.
//!
//! A word that is already a keyword is only extended across an underscore:
//! `always` grows `_ff`, but `for` stays `for` and `end` stays `end` — the
//! keystroke after a finished keyword is a space or a newline far more often
//! than another letter, and a ghost there is noise a stray Tab accepts.
//! See `docs/features/completion-ux/README.md`.
use lsp_types::{Position, Range, SelectedCompletionInfo};
use vlog_parser::token::TokenKind;
use vlog_parser::KEYWORDS;
use super::{InlineItem, InlineItems, SnippetValue};
use crate::state::{Document, Workspace};
use crate::templates::{self, Dialect};
/// The shortest word worth a ghost. One letter is a prefix of half the
/// keyword list, and the ghost would change on every keystroke.
const MIN_WORD: usize = 2;
/// The keywords tried first, in this order, whenever more than one extends
/// the typed word. Everything else falls back to shortest-then-alphabetical.
const PRIORITY: &[&str] = &[
"always_ff",
"always_comb",
"always",
"assign",
"begin",
"logic",
"input",
"output",
"inout",
"module",
"endmodule",
"parameter",
"localparam",
"function",
"endfunction",
"task",
"endtask",
"generate",
"endgenerate",
"genvar",
"case",
"endcase",
"default",
"initial",
"integer",
"posedge",
"negedge",
"typedef",
"struct",
"enum",
"package",
"endpackage",
"interface",
"endinterface",
"foreach",
"forever",
"return",
"automatic",
"unique",
"wire",
"reg",
];
/// The IEEE 1364-2005 reserved words: what a `.v` buffer may be offered. The
/// lexer's list is one list for both dialects, and `logic` grown in a file a
/// Verilog compiler reads is a ghost that hands the user an error.
const VERILOG: &[&str] = &[
"always",
"and",
"assign",
"automatic",
"begin",
"buf",
"bufif0",
"bufif1",
"case",
"casex",
"casez",
"cell",
"cmos",
"config",
"deassign",
"default",
"defparam",
"design",
"disable",
"edge",
"else",
"end",
"endcase",
"endconfig",
"endfunction",
"endgenerate",
"endmodule",
"endprimitive",
"endspecify",
"endtable",
"endtask",
"event",
"for",
"force",
"forever",
"fork",
"function",
"generate",
"genvar",
"highz0",
"highz1",
"if",
"ifnone",
"incdir",
"include",
"initial",
"inout",
"input",
"instance",
"integer",
"join",
"large",
"liblist",
"library",
"localparam",
"macromodule",
"medium",
"module",
"nand",
"negedge",
"nmos",
"nor",
"noshowcancelled",
"not",
"notif0",
"notif1",
"or",
"output",
"parameter",
"pmos",
"posedge",
"primitive",
"pull0",
"pull1",
"pulldown",
"pullup",
"pulsestyle_ondetect",
"pulsestyle_onevent",
"rcmos",
"real",
"realtime",
"reg",
"release",
"repeat",
"rnmos",
"rpmos",
"rtran",
"rtranif0",
"rtranif1",
"scalared",
"showcancelled",
"signed",
"small",
"specify",
"specparam",
"strong0",
"strong1",
"supply0",
"supply1",
"table",
"task",
"time",
"tran",
"tranif0",
"tranif1",
"tri",
"tri0",
"tri1",
"triand",
"trior",
"trireg",
"unsigned",
"use",
"uwire",
"vectored",
"wait",
"wand",
"weak0",
"weak1",
"while",
"wire",
"wor",
"xnor",
"xor",
];
/// The keyword ghost for the word ending at `position`, or `None`.
///
/// `last` is the index of the token ending exactly at the cursor — the
/// caller's `last_token` — and `selected` the popup's selected entry, when
/// the client said one is showing.
pub(super) fn keyword_ghost(
ws: &Workspace,
doc: &Document,
last: usize,
position: Position,
selected: Option<&SelectedCompletionInfo>,
) -> Option<InlineItems> {
if !ws.client_settings().inline_keywords.unwrap_or(true) {
return None;
}
let (word, start) = typed_word(doc, last)?;
// A name this buffer declares is what the user is typing, not the front
// of a keyword: `in`, `re`, `out` as signals stay quiet (fix round).
if doc.semantics.symbols().iter().any(|symbol| symbol.name == word) {
return None;
}
let dialect = templates::dialect(doc.path.as_deref());
// A selection that does not cover exactly the typed word is about some
// other text, and is read as no selection at all — never echoed back.
let word_range = Range { start: doc.positions().position(start), end: position };
let selected = selected.filter(|info| info.range == word_range);
let (keyword, range) = match selected {
// An explicit selection wins over the finished-keyword rule: `end`
// with `endmodule` selected ghosts `endmodule`.
Some(info) => {
let text = info.text.as_str();
(reserved_extension(word, text, dialect).then_some(text)?, info.range)
}
None => (best_keyword(word, dialect)?, Range { start: position, end: position }),
};
// Without a selection the item inserts at the cursor, as every other
// ghost here does; with one it must replace the selection's range with
// the whole word, which is the shape the client compares against.
let value = match selected {
Some(_) => keyword.to_string(),
None => keyword[word.len()..].to_string(),
};
Some(InlineItems {
items: vec![InlineItem { insert_text: SnippetValue { kind: "snippet", value }, range }],
})
}
/// The word a keyword ghost may extend: the token at `last` when it is a
/// plain identifier or a keyword, at least [`MIN_WORD`] long, spelled with
/// identifier characters only, and not a member name after a `.` or `::`.
///
/// A macro use (`` `alw ``), an escaped identifier and a `$system` name all
/// fail the character test or the kind test; a comment and a string never
/// produce a token ending at the cursor at all.
fn typed_word(doc: &Document, last: usize) -> Option<(&str, u32)> {
let token = doc.tokens.get(last)?;
if !matches!(token.kind, TokenKind::Ident | TokenKind::Keyword) {
return None;
}
let text = token.text.as_str();
let plain = text.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
&& text.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !plain || text.len() < MIN_WORD {
return None;
}
let after_separator = last
.checked_sub(1)
.and_then(|i| doc.tokens.get(i))
.is_some_and(|prev| prev.is_sym(".") || prev.is_sym("::") || prev.is_sym("`"));
(!after_separator).then_some((text, token.span.start))
}
/// The keyword to ghost behind `word` with no popup selection to follow.
fn best_keyword(word: &str, dialect: Dialect) -> Option<&'static str> {
if let Some(first) = PRIORITY.iter().copied().find(|kw| extends(word, kw, dialect)) {
return Some(first);
}
KEYWORDS
.iter()
.copied()
.filter(|kw| extends(word, kw, dialect))
.min_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)))
}
/// Whether `keyword` is a reserved word of `dialect` that properly extends
/// `word` — across an underscore only, when `word` is already a keyword.
fn extends(word: &str, keyword: &str, dialect: Dialect) -> bool {
reserved_extension(word, keyword, dialect)
&& (!KEYWORDS.contains(&word) || keyword.as_bytes()[word.len()] == b'_')
}
/// Whether `keyword` is a reserved word of `dialect` that properly extends
/// `word` — the whole test for a keyword the popup has selected.
fn reserved_extension(word: &str, keyword: &str, dialect: Dialect) -> bool {
keyword.len() > word.len()
&& keyword.starts_with(word)
&& KEYWORDS.contains(&keyword)
&& (dialect == Dialect::SystemVerilog || VERILOG.contains(&keyword))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::inline::inline_completions_in_context;
use crate::settings::ClientSettings;
use lsp_types::Uri;
use std::str::FromStr;
/// The ghosts at the end of `needle` in `text`, opened as `/rtl/top.sv`,
/// as `(value, range)` pairs.
fn ghosts(
text: &str,
needle: &str,
selected: Option<SelectedCompletionInfo>,
settings: ClientSettings,
) -> Vec<(String, Range)> {
let uri = Uri::from_str("file:///rtl/top.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_client_settings(settings);
ws.set_document(uri.clone(), text.to_string());
let doc = ws.document(&uri).expect("open");
let offset = (text.find(needle).expect("needle") + needle.len()) as u32;
let position = doc.positions().position(offset);
inline_completions_in_context(&ws, &uri, position, selected.as_ref())
.map(|found| {
found.items.into_iter().map(|item| (item.insert_text.value, item.range)).collect()
})
.unwrap_or_default()
}
fn plain(text: &str, needle: &str) -> Vec<String> {
ghosts(text, needle, None, ClientSettings::default())
.into_iter()
.map(|(value, _)| value)
.collect()
}
fn at(line: u32, character: u32) -> Position {
Position { line, character }
}
#[test]
fn a_keyword_prefix_grows_the_rest_of_the_keyword_at_the_cursor() {
let text = "module top;\n alw\nendmodule\n";
let found = ghosts(text, " alw", None, ClientSettings::default());
let cursor = at(1, 5);
assert_eq!(found, vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })]);
assert_eq!(
plain("module top;\n logic a;\n assign a = 1;\n endm\n", " endm"),
["odule"]
);
}
#[test]
fn the_popups_selection_is_followed_over_its_own_range() {
let text = "module top;\n alw\nendmodule\n";
let range = Range { start: at(1, 2), end: at(1, 5) };
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
assert_eq!(found, vec![("always_comb".to_string(), range)]);
}
#[test]
fn a_selection_that_is_not_a_keyword_extension_silences_the_ghost() {
let text = "module top;\n logic alw_q;\n alw\nendmodule\n";
let range = Range { start: at(2, 2), end: at(2, 5) };
let selected = SelectedCompletionInfo { range, text: "alw_q".to_string() };
assert!(ghosts(text, "\n alw", Some(selected), ClientSettings::default()).is_empty());
}
#[test]
fn no_ghost_after_a_separator_in_a_comment_or_for_one_letter() {
assert!(plain("module top;\n assign x = s.al\nendmodule\n", "s.al").is_empty());
assert!(plain("module top;\n import p::al\nendmodule\n", "p::al").is_empty());
assert!(plain("module top;\n // alw\nendmodule\n", "// alw").is_empty());
assert!(plain("module top;\n a\nendmodule\n", " a").is_empty());
assert!(plain("module top;\n `alw\nendmodule\n", "`alw").is_empty());
}
#[test]
fn no_ghost_when_the_rest_of_the_line_is_written() {
assert!(plain("module top;\n alw x;\nendmodule\n", " alw").is_empty());
}
#[test]
fn the_setting_turns_keyword_ghosts_off_and_leaves_templates_on() {
let off = ClientSettings { inline_keywords: Some(false), ..Default::default() };
let text = "module top;\n alw\nendmodule\n";
assert!(ghosts(text, " alw", None, off.clone()).is_empty());
let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n";
assert_eq!(ghosts(text, "if (", None, off).len(), 1, "the template ghost is untouched");
}
#[test]
fn a_template_trigger_wins_over_the_keyword_ghost() {
// `begin` is a finished keyword and a trigger: its ghost is the block.
let text = "module top;\n initial begin\nendmodule\n";
assert_eq!(plain(text, "initial begin"), ["\n\t$0\nend"]);
}
#[test]
fn the_priority_list_picks_among_several_extensions() {
let sv = Dialect::SystemVerilog;
assert_eq!(best_keyword("al", sv), Some("always_ff"));
assert_eq!(best_keyword("always_c", sv), Some("always_comb"));
assert_eq!(best_keyword("as", sv), Some("assign"));
assert_eq!(best_keyword("lo", sv), Some("logic"));
assert_eq!(best_keyword("endm", sv), Some("endmodule"));
assert_eq!(best_keyword("par", sv), Some("parameter"));
}
#[test]
fn outside_the_list_the_shortest_then_alphabetical_keyword_wins() {
assert_eq!(best_keyword("tr", Dialect::SystemVerilog), Some("tri"), "tri before tran");
assert_eq!(best_keyword("tri", Dialect::SystemVerilog), None, "`tri` is finished");
assert_eq!(best_keyword("xn", Dialect::SystemVerilog), Some("xnor"));
}
#[test]
fn a_finished_keyword_only_grows_across_an_underscore() {
let sv = Dialect::SystemVerilog;
assert_eq!(best_keyword("always", sv), Some("always_ff"));
assert_eq!(best_keyword("end", sv), None, "`end` is finished");
assert_eq!(best_keyword("for", sv), None, "`for` is finished");
assert_eq!(best_keyword("case", sv), None);
}
#[test]
fn a_verilog_buffer_is_only_offered_verilog_words() {
let v = Dialect::Verilog;
assert_eq!(best_keyword("al", v), Some("always"));
assert_eq!(best_keyword("lo", v), Some("localparam"), "no `logic` in a .v file");
assert_eq!(best_keyword("always", v), None, "no `always_ff` either");
}
#[test]
fn every_listed_word_is_a_reserved_word_the_lexer_knows() {
for word in PRIORITY {
assert!(KEYWORDS.contains(word), "{word}");
}
}
/// QA (2026-11-17): the shape an unbridged client sends — VS Code's
/// `Range` serialized by its `toJSON` as `[start, end]`, trigger kind 0 —
/// still decodes (serde reads a struct from a sequence), so the
/// extension's middleware is a spelling fix, not what keeps the request
/// alive.
#[test]
fn qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode() {
let params: lsp_types::InlineCompletionParams = serde_json::from_value(serde_json::json!({
"textDocument": { "uri": "file:///rtl/top.sv" },
"position": { "line": 1, "character": 5 },
"context": {
"triggerKind": 0,
"selectedCompletionInfo": {
"range": [{ "line": 1, "character": 2 }, { "line": 1, "character": 5 }],
"text": "always_comb"
}
}
}))
.expect("decodes");
let selected = params.context.selected_completion_info.expect("kept");
assert_eq!(selected.range, Range { start: at(1, 2), end: at(1, 5) });
}
#[test]
fn nothing_extends_a_word_that_is_no_keyword_prefix() {
assert_eq!(best_keyword("clk", Dialect::SystemVerilog), None);
assert!(extends("al", "always", Dialect::SystemVerilog));
assert!(!extends("Al", "always", Dialect::SystemVerilog), "case matters");
}
#[test]
fn a_name_this_buffer_declares_grows_no_keyword() {
let text = "module top;\n logic re, in;\n assign x = re\nendmodule\n";
assert!(plain(text, "= re").is_empty(), "`re` is a signal here, not `return`");
// An undeclared word still ghosts, expression position or not.
let text = "module top;\n assign x = ou\nendmodule\n";
assert_eq!(plain(text, "= ou"), ["tput"]);
}
#[test]
fn an_explicit_selection_wins_over_the_finished_keyword_rule() {
let text = "module top;\n logic a;\n end\nendmodule\n";
assert!(plain(text, "\n end").is_empty(), "no popup: `end` is finished");
let range = Range { start: at(2, 2), end: at(2, 5) };
let selected = SelectedCompletionInfo { range, text: "endmodule".to_string() };
let found = ghosts(text, "\n end", Some(selected), ClientSettings::default());
assert_eq!(found, vec![("endmodule".to_string(), range)]);
}
#[test]
fn a_selection_over_some_other_range_is_read_as_no_selection() {
let text = "module top;\n alw\nendmodule\n";
let cursor = at(1, 5);
for range in [
Range { start: at(1, 2), end: at(1, 4) },
Range { start: at(1, 3), end: cursor },
Range { start: at(0, 0), end: at(0, 6) },
] {
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
assert_eq!(
found,
vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })],
"{range:?} is never echoed back"
);
}
}
}
+103 -77
View File
@@ -354,6 +354,7 @@ mod tests {
use super::*;
use lsp_types::{Position, Range};
use std::path::PathBuf;
use std::time::{Duration, Instant};
/// A fast-path document over `text`.
fn large(text: &str) -> Document {
@@ -793,51 +794,44 @@ mod tests {
/// 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.
/// The bound is on the **shape** of the cost, not its size: the fastest
/// of five timings at each size, and the largest size (8x the tokens of
/// the smallest) may cost at most [`GROWTH_SLACK`] times 8x the smallest.
/// Linear is ~8x; the quadratic version is ~64x (73x in the release
/// numbers above). A wall-clock ceiling was here first and failed on the
/// CPU-capped Linux runner in debug, where everything is ~15x slower but
/// still 2x for 2x; a ratio holds on any machine. Shown to trip, with the
/// per-call converter put back into `tokens::flatten`, in
/// `docs/features/linux-test-portability/README.md`.
#[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"
);
let sizes = [5_000u32, 10_000, 20_000, 40_000];
let docs: Vec<Document> = sizes
.iter()
.map(|&count| {
// 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");
large(&text)
})
.collect();
for doc in &docs {
assert!(!window(doc, range(0, 1)).tokens.is_empty());
}
let costs = fastest_of_five(&docs, |doc| {
let clock = Instant::now();
let data = crate::tokens::semantic_tokens_in_window(doc, range(0, 1));
let elapsed = clock.elapsed();
assert!(!data.is_empty(), "the window really did colour something");
elapsed
});
assert_grows_linearly(&sizes, &costs, "colouring tokens on one line");
}
/// 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
@@ -848,50 +842,82 @@ mod tests {
///
/// `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.
/// original probe's line lengths so it can live in the normal suite. The
/// hits and the line both grow with `width`, so the walker's work (each
/// byte of the line once) is linear in it and the per-hit rescan's (the
/// line once per hit) quadratic; the bound is the same shape check as the
/// colour test's above, and shown to trip the same way.
#[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 sizes = [100u32, 200, 400, 800];
let docs: Vec<(Document, Vec<TextRange>)> = sizes
.iter()
.map(|&width| {
// 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 hits = references(&doc, 5, true);
assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use");
(doc, hits)
})
.collect();
let costs = fastest_of_five(&docs, |(doc, hits)| {
let positions = doc.positions();
let clock2 = Instant::now();
let clock = Instant::now();
// Exactly what `Server::large_scan` does with them.
let mut walker = positions.walker();
for hit in &hits {
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"
);
}
clock.elapsed()
});
assert_grows_linearly(&sizes, &costs, "locating hits on one line");
}
/// 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;
/// How much faster than its input a linear-time test's cost may grow
/// before it fails: 3x, so 24x for an 8x input, where linear measures
/// ~8x (macOS and the Linux runner alike) and quadratic ~64x.
const GROWTH_SLACK: f64 = 3.0;
/// The fastest of five timings of `run` on each input. The rounds go over
/// all the inputs in turn, so a burst of load from the tests running
/// beside this one slows one sample of each size rather than every sample
/// of one. Five, not three: QA saw 18.2x of the 24x limit at three under
/// 2x CPU oversubscription, and more rounds is the margin that does not
/// loosen what the test can see.
fn fastest_of_five<T>(inputs: &[T], mut run: impl FnMut(&T) -> Duration) -> Vec<Duration> {
let mut fastest = vec![Duration::MAX; inputs.len()];
for _ in 0..5 {
for (best, input) in fastest.iter_mut().zip(inputs) {
*best = (*best).min(run(input));
}
}
fastest
}
/// Fails unless the cost at the largest size is within [`GROWTH_SLACK`]
/// of linear growth from the smallest.
#[track_caller]
fn assert_grows_linearly(sizes: &[u32], costs: &[Duration], what: &str) {
for (size, cost) in sizes.iter().zip(costs) {
eprintln!("{what}: {size} → {cost:?}");
}
let (first, last) = (sizes[0], sizes[sizes.len() - 1]);
let input = f64::from(last) / f64::from(first);
let growth =
costs[costs.len() - 1].as_secs_f64() / costs[0].as_secs_f64().max(f64::MIN_POSITIVE);
assert!(
growth <= GROWTH_SLACK * input,
"{what}: {input}x the input cost {growth:.1}x the time ({costs:?}) — \
more than {GROWTH_SLACK}x linear, the quadratic conversion is back"
);
}
}
+86 -1
View File
@@ -304,7 +304,17 @@ fn configured(
}
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
// The formatter's width ladder, so a line lucisv wrote is never a line
// lucisv calls too long: an explicit width (`lucisv.toml`, then the
// editor), else the chosen style's width (`lucisv.toml`'s `style`, then
// `lucisv.format.style`), else the default. `auto` names no preset and so
// no width — it falls through to the default, as it does in the
// formatter (`docs/features/format-styles/README.md`, Handshakes).
let styled = file.format_style.or(client.style).and_then(vlog_formatter::style::preset);
let width = file
.line_length
.or(client.line_length)
.unwrap_or_else(|| styled.map_or(DEFAULT_LINE_LENGTH, |style| style.line_length));
(options, width, file, problems)
}
@@ -731,6 +741,81 @@ mod tests {
assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown);
}
/// Whether the server flags `line-length` on a line of `columns`
/// characters, in a scratch tree governed by `toml` (none for `None`),
/// with the editor's `lucisv.format.style` set to `editor_style`.
fn flags_a_line_of(
columns: usize,
toml: Option<&str>,
editor_style: Option<&'static str>,
) -> bool {
let dir = std::env::temp_dir().join(format!(
"lucisv_lint_width_{}_{columns}_{}",
std::process::id(),
toml.map_or(0, str::len) + editor_style.map_or(0, str::len) * 1000
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("scratch dir");
if let Some(toml) = toml {
std::fs::write(dir.join("lucisv.toml"), toml).expect("config");
}
let text = format!("module m;\n // {}\nendmodule\n", "x".repeat(columns - 5));
let path = dir.join("m.sv");
std::fs::write(&path, &text).expect("source");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { style: editor_style, ..ClientSettings::default() });
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text);
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
let flagged = diagnostics_in(doc, &run)
.iter()
.any(|d| d.code == Some(NumberOrString::String("line-length".into())));
let _ = std::fs::remove_dir_all(&dir);
flagged
}
/// The width `lucisv check` holds the same file to: the CLI's own ladder,
/// an explicit width over the named style's over the default
/// (`lucisv`'s `Options::config_with`), with the editor's style standing
/// in for `--style`.
fn check_width(explicit: Option<usize>, style: Option<&str>) -> usize {
let config = style.and_then(vlog_formatter::Config::named).unwrap_or_default();
explicit.unwrap_or(config.max_width)
}
#[test]
fn line_length_holds_a_buffer_to_the_width_the_formatter_and_check_use() {
// One rung each, from the top: an explicit width beats a style; a
// project's style; the editor's style; the default; and `auto`, which
// names no width and so takes the default.
let rungs: [(&str, Option<&str>, Option<&'static str>, usize); 5] = [
(
"explicit",
Some("line-length = 120\n[format]\nstyle = \"ansi\"\n"),
None,
check_width(Some(120), Some("ansi")),
),
(
"project style",
Some("[format]\nstyle = \"ansi\"\n"),
None,
check_width(None, Some("ansi")),
),
("editor style", None, Some("microsoft"), check_width(None, Some("microsoft"))),
("default", None, None, check_width(None, None)),
("auto", Some("[format]\nstyle = \"auto\"\n"), None, check_width(None, Some("auto"))),
];
assert_eq!(rungs.map(|r| r.3), [120, 80, 120, 100, 100], "premise: the widths check uses");
for (rung, toml, editor, width) in rungs {
assert!(
!flags_a_line_of(width, toml, editor),
"{rung}: a line of exactly {width} is fine"
);
assert!(flags_a_line_of(width + 1, toml, editor), "{rung}: one column more is flagged");
}
}
#[test]
fn a_tab_becomes_one_warning_carrying_its_rule_name() {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
+40
View File
@@ -6,6 +6,7 @@
//! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See
//! `docs/features/lucisv-server/README.md`.
mod auto_style;
mod candidates;
mod code_action;
mod completion;
@@ -117,6 +118,7 @@ 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(&params);
let diagnostic_refresh = diagnostic_refresh_support(&params);
// 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.
@@ -133,6 +135,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
pull_diagnostics: pull_diagnostics_support(&params),
work_done_progress: work_done_progress_support(&params),
code_lens_refresh: code_lens_refresh_support(&params),
diagnostic_refresh,
show_document: show_document_support(&params),
configuration: configuration_support(&params),
token_server_cancel: token_server_cancel_support(&params),
@@ -645,6 +648,21 @@ fn code_lens_refresh_support(params: &InitializeParams) -> bool {
.unwrap_or(false)
}
/// Whether the client can be asked to pull its diagnostics again
/// (`workspace/diagnostic/refresh`), read from the **raw** `initialize`
/// params.
///
/// Server-initiated, so the spec makes this capability the gate, exactly as
/// for the code-lens refresh. It has to be the raw JSON: the protocol's key is
/// `workspace.diagnostics`, and `lsp-types` 0.97 spells its field
/// `diagnostic` with no rename, so the typed decode never sees what VS Code
/// sends. Anything but a literal `true` means no. Sent when a connection entry
/// held back while it was typed is released
/// (`docs/features/port-entry-grace/README.md`).
fn diagnostic_refresh_support(params: &serde_json::Value) -> bool {
params["capabilities"]["workspace"]["diagnostics"]["refreshSupport"] == true
}
/// Whether the client opens a document the server asks it to.
///
/// This is what makes the instantiation lens actually navigate: an
@@ -1352,6 +1370,28 @@ mod tests {
assert!(!code_lens_refresh_support(&saying(None)), "an empty `codeLens` is not a yes");
}
#[test]
fn diagnostic_refresh_support_is_read_from_the_raw_params_and_only_when_literally_true() {
let saying = |refresh: serde_json::Value| {
serde_json::json!({
"processId": null,
"capabilities": { "workspace": { "diagnostics": { "refreshSupport": refresh } } }
})
};
assert!(diagnostic_refresh_support(&saying(serde_json::json!(true))));
assert!(!diagnostic_refresh_support(&saying(serde_json::json!(false))));
assert!(!diagnostic_refresh_support(&saying(serde_json::json!("yes"))));
assert!(!diagnostic_refresh_support(&saying(serde_json::Value::Null)));
assert!(!diagnostic_refresh_support(&serde_json::json!({ "capabilities": {} })));
assert!(!diagnostic_refresh_support(&serde_json::Value::Null));
// The protocol's key is plural; `lsp-types`' singular field name is
// not what any client sends, and is not read.
let singular = serde_json::json!({
"capabilities": { "workspace": { "diagnostic": { "refreshSupport": true } } }
});
assert!(!diagnostic_refresh_support(&singular));
}
#[test]
fn show_document_support_is_read_from_the_clients_own_capabilities() {
use lsp_types::{
+32 -34
View File
@@ -170,16 +170,10 @@ fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool {
}
// A member is reachable as `unit::name`, as `.name` in a connection list
// or as the tail of a hierarchical path, so the unit that owns the
// declaring scope is what to ask about.
let owner = doc
.semantics
.scope(symbol.scope)
.and_then(|scope| scope.owner)
.and_then(|owner| doc.semantics.symbol(owner));
match owner {
Some(owner) => {
!ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical).is_empty()
}
// declaring scope is what to ask about — under the key the index files
// it by, which for a named block is `module.label`.
match doc.semantics.member_key(symbol.scope) {
Some(key) => !ws.index().member_in(&key, &symbol.name, Surface::Hierarchical).is_empty(),
None => false,
}
}
@@ -262,11 +256,8 @@ fn indexed_def_in_file<'a>(
let defs = if symbol.scope == semantics.file_scope() {
ws.index().units(&symbol.name)
} else {
let owner = semantics
.scope(symbol.scope)
.and_then(|scope| scope.owner)
.and_then(|owner| semantics.symbol(owner))?;
ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical)
let key = semantics.member_key(symbol.scope)?;
ws.index().member_in(&key, &symbol.name, Surface::Hierarchical)
};
if defs.len() != 1 {
return None;
@@ -1510,8 +1501,8 @@ endmodule
);
assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "and the module is a unit");
assert!(
!leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5),
"but a generate-block-scoped net is on neither surface"
leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5),
"and since TODO §65.1 so is a generate-block-scoped net, under `m.g`: `u_m.g.gen_only`"
);
assert!(
!leaves_this_file(&ws, doc, at(text, "assign b") + 7),
@@ -2248,13 +2239,13 @@ endpackage
let _ = fs::remove_dir_all(&dir);
}
/// A net declared inside a **generate block** is on neither surface: its
/// scope is the block's, not the module's (`hierarchical-tail`, "a unit's
/// members are the symbols of its own scope"). So the gate still says no
/// and the answer is still the honest single-file one — the same refusal
/// a rename gives `u_x.g.sig`.
/// A net declared inside a **generate block**. Until TODO §65.1 it was on
/// neither surface and this pinned the honest single-file answer; a named
/// block is now on its module's hierarchical surface and its members under
/// `gleaf.g` (`docs/features/generate-label-rename/README.md`), so the gate
/// says yes and `u_g.g.gsig` in the other file is one of the references.
#[test]
fn a_generate_block_scoped_net_still_never_asks_the_workspace() {
fn a_generate_block_scoped_net_is_found_through_the_instance_path() {
let dir = temp_dir("hier_generate");
let leaf = "\
module gleaf;
@@ -2278,11 +2269,15 @@ endmodule
let decl = at(leaf, "wire gsig") + 5;
let doc = ws.document(&leaf_uri).expect("open");
assert!(!leaves_this_file(&ws, doc, decl), "the index exports it on no surface");
assert!(leaves_this_file(&ws, doc, decl), "the index exports it hierarchically");
assert_eq!(
places(&references(&ws, &leaf_uri, decl, true)),
vec![("gleaf.sv".to_string(), 2), ("gleaf.sv".to_string(), 3)],
"this file only, and `u_g.g.gsig` is left to the editor"
vec![
("gleaf.sv".to_string(), 2),
("gleaf.sv".to_string(), 3),
("guser.sv".to_string(), 3)
],
"this file and `u_g.g.gsig`"
);
let _ = fs::remove_dir_all(&dir);
}
@@ -2941,12 +2936,11 @@ endmodule
}
/// Case (a), sharpened: an **indexed generate array**, not just a named
/// block. `u_g.gen[0].gsig` is still on neither surface — the array
/// index changes how many instances of the scope exist, not which scope
/// `gsig` belongs to — so the honest single-file fallback must hold here
/// too.
/// block. The array index changes how many instances of the scope exist,
/// not which scope `gsig` belongs to — which since TODO §65.1 is exactly
/// why `u_g.gen[0].gsig` is walked as `u_g.gen.gsig` and found.
#[test]
fn qa_a_generate_for_arrays_scoped_net_still_never_asks_the_workspace() {
fn qa_a_generate_for_arrays_scoped_net_is_found_through_the_indexed_path() {
let dir = temp_dir("qa_generate_for");
let leaf = "\
module gfleaf;
@@ -2970,11 +2964,15 @@ endmodule
let decl = at(leaf, "wire gsig") + 5;
let doc = ws.document(&leaf_uri).expect("open");
assert!(!leaves_this_file(&ws, doc, decl), "an indexed generate scope is on no surface");
assert!(leaves_this_file(&ws, doc, decl), "a generate array's scope is exported too");
assert_eq!(
places(&references(&ws, &leaf_uri, decl, true)),
vec![("gfleaf.sv".to_string(), 2), ("gfleaf.sv".to_string(), 3)],
"this file only; `u_g.gen[0].gsig` is left to the editor"
vec![
("gfleaf.sv".to_string(), 2),
("gfleaf.sv".to_string(), 3),
("gfuser.sv".to_string(), 3)
],
"this file and `u_g.gen[0].gsig`"
);
let _ = fs::remove_dir_all(&dir);
}
+42 -17
View File
@@ -28,6 +28,10 @@ use crate::format;
use crate::pairs;
use crate::state::{first_token_from, first_token_reaching, Document};
mod auto_end;
pub(crate) use auto_end::begin_owes_an_end;
/// 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.
pub const NEWLINE: &str = "\n";
@@ -40,12 +44,21 @@ pub const SEMICOLON: &str = ";";
///
/// Never an `Err`: every refusal on this path — an unknown trigger, a client
/// out of step, a buffer the formatter will not touch — is the empty answer.
///
/// `auto_end` is `lucisv.autoEnd`: whether a newline typed after a `begin`
/// that still owes its `end` also writes that `end` (see `auto_end.rs`).
pub fn on_type_formatting(
doc: &Document,
position: Position,
typed: &str,
config: &Config,
auto_end: bool,
) -> Vec<TextEdit> {
if auto_end && typed == NEWLINE {
if let Some(edits) = auto_end::begin_newline_edits(doc, position, config.indent_width) {
return edits;
}
}
let edit = match typed {
NEWLINE => indent_edit(doc, position, config.indent_width),
SEMICOLON => statement_edit(doc, position, config),
@@ -61,9 +74,9 @@ pub fn on_type_formatting(
/// Lay out the statement the `;` just ended, through the range engine.
///
/// The range asked for is the `;`'s **own line** and nothing else. That is not
/// a narrower request than "the statement's lines": `format_range` selects by
/// *unit*, so any line of a statement selects the whole statement (see
/// `docs/features/range-formatting/README.md`). It is, however, a much safer
/// a narrower request than "the statement's lines": `format_selection` selects
/// by *unit*, so any line of a statement selects the whole statement (see
/// `docs/features/selection-formatting/README.md`). It is, however, a much safer
/// one — the `;` closing `module m (\n input a\n);` ends no statement at all,
/// and naming its enclosing node's lines there would ask for the whole module
/// back on a keystroke.
@@ -715,7 +728,7 @@ mod tests {
fn newline_with(text: &str, line: u32, indent_width: usize) -> Vec<TextEdit> {
let at = Position { line, character: 0 };
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width)))
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width), false))
}
/// The `new_text` of the single edit a newline produced, or `None` when it
@@ -732,7 +745,7 @@ mod tests {
let content = source[line as usize].trim_end_matches('\n');
let character = content.rfind(';').expect("the line ends a statement") as u32 + 1;
let at = Position { line, character };
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)))
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false))
}
// ------------------------------------------------------------------
@@ -793,7 +806,7 @@ mod tests {
// it means the client is not talking about a newline it just typed.
let text = "module m;\nwire a;\nendmodule\n";
let at = Position { line: 1, character: 4 };
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2), false));
assert_eq!(edits, Vec::new());
}
@@ -955,7 +968,7 @@ mod tests {
with(text, |doc| {
for line in 1..text.lines().count() as u32 {
let at = Position { line, character: 0 };
for edit in on_type_formatting(doc, at, NEWLINE, &config(2)) {
for edit in on_type_formatting(doc, at, NEWLINE, &config(2), false) {
assert_eq!(edit.range.start, at, "always column zero of the asked-for line");
assert_eq!(edit.range.end.line, line, "and never past that line");
let source = doc.text.lines().nth(line as usize).unwrap_or("");
@@ -1174,13 +1187,25 @@ mod tests {
#[test]
fn a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all() {
// Half-typed code is the normal case on this trigger, not a failure.
assert_eq!(semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1), Vec::new());
// The error is on the keystroke's own line: one elsewhere in the
// buffer no longer refuses (selection-formatting, TODO §66.2).
let text = "module m;\n wire a = ;\nendmodule\n";
let at = Position { line: 1, character: 13 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits, Vec::new());
}
#[test]
fn a_semicolon_still_lays_out_its_statement_when_the_error_is_elsewhere() {
let edits = semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1);
assert_eq!(edits.len(), 1, "{edits:#?}");
assert_eq!(edits[0].new_text, "module m;\n wire a;\n wire ;\nendmodule\n");
}
#[test]
fn a_semicolon_that_is_not_where_the_client_said_answers_nothing() {
let at = Position { line: 1, character: 3 };
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits, Vec::new());
}
@@ -1191,7 +1216,7 @@ mod tests {
assert_eq!(semicolon(text, 1), Vec::new());
let text = "module m;\n string s = \"a;\";\n wire a;\nendmodule\n";
let at = Position { line: 1, character: 16 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits, Vec::new(), "the `;` inside the quotes");
}
@@ -1202,12 +1227,12 @@ mod tests {
// the whole document.
let text = "module m;\n wire a;\nendmodule";
let at = Position { line: 1, character: 11 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits.len(), 1, "{edits:#?}");
// The engine's own canonicalization adds the missing final newline —
// exactly what `textDocument/rangeFormatting` would also do here, and
// not a moved byte this path invented on its own.
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule\n");
// Only the statement moves: the file's tail is outside the splice, so
// the missing final newline stays missing — exactly what
// `textDocument/rangeFormatting` answers here too.
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule");
}
#[test]
@@ -1241,7 +1266,7 @@ mod tests {
// inside a string or a comment.
let text = "`define FOO x = 1;\nmodule m;\nendmodule\n";
let at = Position { line: 0, character: 19 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits, Vec::new(), "no Symbol(;) token ends inside a Directive");
}
@@ -1269,7 +1294,7 @@ mod tests {
// guess at what it meant.
let at = Position { line: 1, character: 9 };
for typed in ["}", ")", "\t", ""] {
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2)));
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2), false));
assert_eq!(edits, Vec::new(), "trigger {typed:?}");
}
}
@@ -0,0 +1,581 @@
//! `begin` + Enter writes the `end` (TODO §68.1).
//!
//! The newline answer's second half. When the line above the one a `\n` just
//! opened ends in `begin` (or `begin : label`) and that block still owes an
//! `end`, the answer is two edits instead of one: the new line's body
//! indentation, as the plain newline answer would give it, and a line after
//! it holding `end` at the indentation of the statement the `begin` belongs
//! to. The cursor's line stays blank, so the user types the first statement
//! where they already are.
//!
//! **Which `begin` owes an `end`.** `pairs::analyze` is a stack matcher, so a
//! `begin` typed inside a block that already balances *steals* that block's
//! `end`: the new inner `begin` comes out matched, and the outer one is
//! reported unclosed. "Is *this* `begin` unmatched" is therefore the wrong
//! question. The one asked here is: is any `begin` at or before this one
//! unclosed — unless this `begin` is matched by an `end` that starts its line
//! at exactly the indentation this answer would have written, which is the
//! block the user already closed. See `docs/features/completion-ux/README.md`.
use lsp_types::{Position, Range, TextEdit};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use super::level_at;
use crate::pairs;
use crate::state::{first_token_from, Document};
/// The keywords whose header a `begin` may be the body of. Reading backwards,
/// one of these is where the header starts.
const HEADER_KEYWORDS: &[&str] = &[
"if",
"for",
"foreach",
"while",
"repeat",
"forever",
"always",
"always_ff",
"always_comb",
"always_latch",
"initial",
"final",
];
/// The words that may stand in front of a header on the same statement:
/// `else if`, `unique case`-style qualifiers, and a bare `else` before its
/// `begin`.
const QUALIFIERS: &[&str] = &["else", "unique", "unique0", "priority"];
/// The edits for a newline typed right after a `begin` that still owes its
/// `end`, or `None` when this newline is not that — the caller then answers
/// the plain indentation question instead.
pub(super) fn begin_newline_edits(
doc: &Document,
position: Position,
indent_width: usize,
) -> Option<Vec<TextEdit>> {
let line = NewLine::at(doc, position)?;
let begin = begin_ending_line_above(doc, line.range.start)?;
let end_indent = owner_indent(doc, begin);
if !owes_an_end(doc, begin, &end_indent) {
return None;
}
let body = body_indent(level_at(doc, line.content), &end_indent, indent_width);
Some(edits(doc, &line, &body, &end_indent))
}
/// The blank line a `\n` just opened, as far as this answer needs it.
struct NewLine {
/// The whole line, its `\r` included when the file has one.
range: TextRange,
/// The end of its leading whitespace.
content: u32,
/// The line ending the file writes, read off the newline just typed.
eol: &'static str,
}
impl NewLine {
/// The line at `position`, when a newline opened it, the cursor sits in
/// its leading whitespace, and nothing but whitespace is on it — Enter
/// pressed in the middle of a line carries text down, and a body that is
/// already written owes nothing.
fn at(doc: &Document, position: Position) -> Option<NewLine> {
let range = doc.line_index.line_range(position.line.checked_add(1)?)?;
let bytes = doc.text.as_bytes();
if range.start == 0 || bytes.get(range.start as usize - 1) != Some(&b'\n') {
return None;
}
let text = doc.text.get(range.start as usize..range.end as usize)?;
let rest = text.trim_start_matches([' ', '\t']);
if !rest.trim_end_matches('\r').is_empty() {
return None;
}
let content = range.start + (text.len() - rest.len()) as u32;
if doc.positions().offset(position) > content {
return None;
}
let crlf = range.start >= 2 && bytes.get(range.start as usize - 2) == Some(&b'\r');
Some(NewLine { range, content, eol: if crlf { "\r\n" } else { "\n" } })
}
}
/// The index of the `begin` the line above `line_start` ends with — the last
/// token on it, or the one before a `: label` — when it does.
///
/// Comments are trivia, not tokens, so `begin // why` ends in `begin` here
/// without a check of its own.
fn begin_ending_line_above(doc: &Document, line_start: u32) -> Option<usize> {
let last = first_token_from(&doc.tokens, line_start).checked_sub(1)?;
let above = doc.line_index.line_col(line_start).0.checked_sub(1)?;
let on_line_above =
|index: usize| doc.tokens.get(index).is_some_and(|token| line_of(doc, token) == above);
let token = doc.tokens.get(last)?;
let begin = match token.kind {
TokenKind::Ident if last >= 2 && doc.tokens.get(last - 1)?.is_sym(":") => last - 2,
_ => last,
};
(doc.tokens.get(begin)?.is_kw("begin") && on_line_above(begin) && on_line_above(last))
.then_some(begin)
}
/// The leading whitespace of the line the statement owning the `begin` at
/// `begin` starts on, as written — tabs stay tabs.
///
/// Read backwards from the `begin` over what may stand between a statement's
/// first token and its body: a parenthesised header, an `@`/`#` control and
/// its operand, and [`HEAD_KEYWORDS`]. Anything else — a `;`, an `end`, a
/// case item's `:` — is where the statement starts. A header with no `(` to
/// match leaves the `begin`'s own line as the answer.
fn owner_indent(doc: &Document, begin: usize) -> String {
let tokens = &doc.tokens;
let mut first = begin;
// Once a header keyword is read, only a qualifier may still precede it:
// `always_comb` on the line above an `if` is the `if`'s *owner*, not part
// of its header.
let mut keyword_seen = false;
while let Some(prev) = first.checked_sub(1) {
let token = &tokens[prev];
let step = match keyword_seen {
true => is_keyword_in(token, QUALIFIERS).then_some(prev),
false => header_step(tokens, prev),
};
let Some(step) = step else { break };
keyword_seen |= is_keyword_in(token, HEADER_KEYWORDS) || is_keyword_in(token, QUALIFIERS);
first = step;
}
line_indent(doc, tokens[first].span.start)
}
/// Where reading a header backwards goes from the token at `prev`: over a
/// parenthesised group to its `(`, onto a header keyword, a qualifier, an
/// `@`/`#`, or the operand right after one — or nowhere, when `prev` is
/// already outside the header.
fn header_step(tokens: &[Token], prev: usize) -> Option<usize> {
let token = &tokens[prev];
if token.is_sym(")") {
return matching_open(tokens, prev);
}
let after_control = prev
.checked_sub(1)
.and_then(|i| tokens.get(i))
.is_some_and(|t| t.is_sym("@") || t.is_sym("#"));
let in_header = is_keyword_in(token, HEADER_KEYWORDS)
|| is_keyword_in(token, QUALIFIERS)
|| token.is_sym("@")
|| token.is_sym("#")
|| after_control;
in_header.then_some(prev)
}
fn is_keyword_in(token: &Token, words: &[&str]) -> bool {
token.kind == TokenKind::Keyword && words.contains(&token.text.as_str())
}
/// The `(` the `)` at `close` closes, counting parentheses only.
fn matching_open(tokens: &[Token], close: usize) -> Option<usize> {
let mut depth = 0u32;
for index in (0..=close).rev() {
let token = &tokens[index];
if token.is_sym(")") {
depth += 1;
} else if token.is_sym("(") {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(index);
}
}
}
None
}
/// Whether the block the `begin` at `begin` opens still needs an `end`
/// written for it. See the module comment for why this is not "is this
/// `begin` unmatched".
///
/// Two layouts count as "already closed": the `end` under the statement (the
/// formatter's own layout) and the `end` under the `begin`'s own line (the GNU
/// layout, `begin` on a line of its own — QA finding 1, fix round
/// 2026-11-17). And an unmatched `begin` inside a `` `ifdef `` that has an
/// `` `else ``/`` `elsif `` arms nothing: two branches each opening a block
/// closed by one shared `end` are an unmatched `begin` to the stack matcher
/// and complete code to the compiler.
fn owes_an_end(doc: &Document, begin: usize, end_indent: &str) -> bool {
let span = doc.tokens[begin].span;
let own_indent = line_indent(doc, span.start);
let analysis = pairs::analyze(&doc.tokens);
let closed_here = analysis.pairs.iter().any(|pair| {
pair.open == span
&& (starts_line_at(doc, pair.close, end_indent)
|| starts_line_at(doc, pair.close, &own_indent))
});
if closed_here {
return false;
}
let branched = branched_regions(&doc.tokens);
analysis.unmatched_open.iter().any(|open| {
open.keyword == "begin"
&& open.span.start <= span.start
&& !branched.iter().any(|region| region.contains(&open.span.start))
})
}
/// Whether the `begin` at token index `begin` opens a block that still needs
/// an `end` — [`owes_an_end`] with the `end` at its owner's indentation. The
/// inline `begin` ghost asks the same question.
pub(crate) fn begin_owes_an_end(doc: &Document, begin: usize) -> bool {
owes_an_end(doc, begin, &owner_indent(doc, begin))
}
/// The byte ranges of every `` `ifdef ``/`` `ifndef `` … `` `endif `` region
/// that holds an `` `else `` or `` `elsif `` of its own. A region never closed
/// runs to the end of the buffer.
fn branched_regions(tokens: &[Token]) -> Vec<std::ops::Range<u32>> {
let mut open: Vec<(u32, bool)> = Vec::new();
let mut out = Vec::new();
for token in tokens {
match conditional(token) {
Some("`ifdef" | "`ifndef") => open.push((token.span.start, false)),
Some("`else" | "`elsif") => {
if let Some(last) = open.last_mut() {
last.1 = true;
}
}
Some("`endif") => {
if let Some((start, true)) = open.pop() {
out.push(start..token.span.end);
}
}
_ => {}
}
}
let end = tokens.last().map_or(0, |token| token.span.end);
out.extend(open.into_iter().filter(|(_, branched)| *branched).map(|(start, _)| start..end));
out
}
/// The conditional-compilation directive a token spells, by its first word.
fn conditional(token: &Token) -> Option<&str> {
let word = token.text.split_whitespace().next()?;
matches!(word, "`ifdef" | "`ifndef" | "`else" | "`elsif" | "`endif").then_some(word)
}
/// Whether `span` is the first thing on its line and that line is indented
/// by exactly `indent`.
fn starts_line_at(doc: &Document, span: TextRange, indent: &str) -> bool {
let line = doc.line_index.line_col(span.start).0;
let Some(range) = doc.line_index.line_range(line) else { return false };
doc.text.get(range.start as usize..span.start as usize) == Some(indent)
}
/// The body line's indentation: the nesting model's answer when it has one
/// that sits inside the `end`, else one step in from the `end`. A file
/// indented with tabs gets one more tab — the model speaks spaces, and mixing
/// the two on adjacent lines would be worse than either.
fn body_indent(level: Option<usize>, end_indent: &str, indent_width: usize) -> String {
if end_indent.contains('\t') {
return format!("{end_indent}\t");
}
match level {
Some(level) if level * indent_width > end_indent.len() => " ".repeat(level * indent_width),
_ => format!("{end_indent}{}", " ".repeat(indent_width)),
}
}
/// The edits themselves: re-indent the new line when it needs it, and write
/// the `end` line after it.
///
/// The `end` goes in at the **start of the following line** whenever there is
/// one, so no edit touches the cursor's own position and an editor applying
/// them leaves the cursor on the body line. The new line being the file's last
/// is the one case with nowhere else to put it, and there the two are one
/// edit.
fn edits(doc: &Document, line: &NewLine, body: &str, end_indent: &str) -> Vec<TextEdit> {
let positions = doc.positions();
let start = positions.position(line.range.start);
let indent = Range { start, end: positions.position(line.content) };
let end_line = format!("{end_indent}end");
if line.range.end as usize >= doc.text.len() {
let new_text = format!("{body}{}{end_line}", line.eol);
return vec![TextEdit {
range: Range { start, end: positions.position(line.range.end) },
new_text,
}];
}
let mut edits = Vec::new();
if doc.text.get(line.range.start as usize..line.content as usize) != Some(body) {
edits.push(TextEdit { range: indent, new_text: body.to_string() });
}
let next = positions.position(line.range.end + 1);
edits.push(TextEdit {
range: Range { start: next, end: next },
new_text: format!("{end_line}{}", line.eol),
});
edits
}
/// The 1-based line a token starts on.
fn line_of(doc: &Document, token: &Token) -> u32 {
doc.line_index.line_col(token.span.start).0
}
/// The leading whitespace of the line holding `offset`.
fn line_indent(doc: &Document, offset: u32) -> String {
let line = doc.line_index.line_col(offset).0;
let Some(range) = doc.line_index.line_range(line) else { return String::new() };
let text = doc.text.get(range.start as usize..range.end as usize).unwrap_or("");
text[..text.len() - text.trim_start_matches([' ', '\t']).len()].to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::on_type::{on_type_formatting, NEWLINE};
use crate::state::Workspace;
use lsp_types::Uri;
use std::str::FromStr;
use vlog_formatter::Config;
/// The buffer after the newline answer for a `\n` that opened `line`
/// (0-based), with `lucisv.autoEnd` as given — and the edits themselves.
fn typed(text: &str, line: u32, auto_end: bool) -> (String, Vec<TextEdit>) {
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let doc = ws.document(&uri).expect("open");
let at = Position { line, character: 0 };
let config = Config { indent_width: 2, ..Config::default() };
let edits = on_type_formatting(doc, at, NEWLINE, &config, auto_end);
(apply(doc, &edits), edits)
}
/// `edits` applied to the buffer, last first so the offsets stay true.
fn apply(doc: &Document, edits: &[TextEdit]) -> String {
let mut spans: Vec<(usize, usize, &str)> = edits
.iter()
.map(|edit| {
let start = doc.positions().offset(edit.range.start) as usize;
let end = doc.positions().offset(edit.range.end) as usize;
(start, end, edit.new_text.as_str())
})
.collect();
spans.sort_by_key(|(start, _, _)| std::cmp::Reverse(*start));
let mut text = doc.text.to_string();
for (start, end, new_text) in spans {
text.replace_range(start..end, new_text);
}
text
}
#[test]
fn a_newline_after_an_unclosed_begin_writes_the_end_under_its_statement() {
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
let (after, edits) = typed(text, 2, true);
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \n end\nendmodule\n");
// Nothing lands on the cursor's own position: the `end` goes in at the
// start of the line after it, so the cursor stays on the body line.
assert!(edits
.iter()
.all(|edit| edit.range.start.line != 2 || edit.range.end.character == 0));
assert_eq!(
edits.last().map(|edit| edit.range.start),
Some(Position { line: 3, character: 0 })
);
}
#[test]
fn a_begin_typed_inside_a_balanced_block_still_gets_its_end() {
// The new `if`'s `begin` steals the `always_comb` block's `end` in the
// stack matcher, and the *outer* `begin` is what comes out unclosed.
let text =
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n";
let (after, _) = typed(text, 4, true);
assert_eq!(
after,
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n \n end\n end\nendmodule\n"
);
}
#[test]
fn a_begin_whose_blocks_already_balance_gets_no_end() {
let text = "module m;\n always_comb begin\n\n end\nendmodule\n";
let (after, edits) = typed(text, 2, true);
assert_eq!(after, "module m;\n always_comb begin\n \n end\nendmodule\n");
assert_eq!(edits.len(), 1, "the indentation alone: {edits:?}");
}
#[test]
fn a_closed_inner_block_with_an_outer_end_missing_gets_no_second_end() {
// The outer `begin` is the unclosed one, but this `begin` already has
// its `end`, at exactly the indentation the answer would write.
let text = "module m;\n always_comb begin\n if (x) begin\n\n end\nendmodule\n";
let (_, edits) = typed(text, 3, true);
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
}
#[test]
fn a_labelled_begin_and_a_trailing_comment_both_count() {
let text = "module m;\n initial begin : boot // first\n\nendmodule\n";
let (after, _) = typed(text, 2, true);
assert_eq!(after, "module m;\n initial begin : boot // first\n \n end\nendmodule\n");
}
#[test]
fn the_end_lines_up_with_the_first_line_of_a_wrapped_header() {
let text = "module m;\n always_comb\n if (a &&\n b) begin\n\nendmodule\n";
let (after, _) = typed(text, 4, true);
assert!(after.contains(" b) begin\n \n end\nendmodule"), "{after}");
}
#[test]
fn an_else_branch_ends_under_the_line_that_holds_the_else() {
let text = "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end else begin\n\n end\nendmodule\n";
let (after, _) = typed(text, 5, true);
assert!(after.contains(" end else begin\n \n end\n end\n"), "{after}");
}
#[test]
fn a_case_item_ends_under_the_item() {
let text = "module m;\n always_comb begin\n case (s)\n 2'b01: begin\n\n endcase\n end\nendmodule\n";
let (after, _) = typed(text, 4, true);
assert!(after.contains(" 2'b01: begin\n \n end\n endcase"), "{after}");
}
#[test]
fn tabs_stay_tabs() {
let text = "module m;\n\talways_comb begin\n\nendmodule\n";
let (after, _) = typed(text, 2, true);
assert_eq!(after, "module m;\n\talways_comb begin\n\t\t\n\tend\nendmodule\n");
}
#[test]
fn a_crlf_file_gets_a_crlf_end_line() {
let text = "module m;\r\n initial begin\r\n\r\nendmodule\r\n";
let (after, _) = typed(text, 2, true);
assert_eq!(after, "module m;\r\n initial begin\r\n \r\n end\r\nendmodule\r\n");
}
#[test]
fn the_last_line_of_the_file_gets_one_edit() {
let text = "module m;\n initial begin\n";
let (after, edits) = typed(text, 2, true);
assert_eq!(after, "module m;\n initial begin\n \n end");
assert_eq!(edits.len(), 1);
}
#[test]
fn nothing_but_the_indent_when_the_setting_is_off() {
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
let (after, _) = typed(text, 2, false);
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \nendmodule\n");
}
#[test]
fn no_end_where_the_line_above_does_not_end_in_begin() {
for text in [
"module m;\n initial begin x = 1;\n\nendmodule\n",
"module m;\n initial // begin\n\nendmodule\n",
"module m;\n initial $display(\"begin\");\n\nendmodule\n",
"module m;\n initial fork\n\nendmodule\n",
] {
let (_, edits) = typed(text, 2, true);
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{text:?}: {edits:?}");
}
}
#[test]
fn no_end_when_enter_carried_text_down_to_the_new_line() {
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
let (_, edits) = typed(text, 2, true);
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
}
#[test]
fn a_begin_two_lines_up_is_not_the_line_above() {
let text = "module m;\n initial begin\n\n\nendmodule\n";
let (_, edits) = typed(text, 3, true);
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
}
/// QA (2026-11-17): buffers just after an Enter on `line`, each of which
/// gets an `end`.
const QA_ARMED: &[(&str, u32)] = &[
("module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n", 4),
("module m;\n generate\n if (P) begin : g\n\n endgenerate\nendmodule\n", 3),
("module m;\n initial fork\n begin\n\n join\nendmodule\n", 3),
("module m;\n initial `MY_MACRO begin\n\nendmodule\n", 2),
("module m;\n initial #5 begin\n\nendmodule\n", 2),
("module m;\n always @* begin\n\nendmodule\n", 2),
("class c;\n function void f();\n if (a) begin\n\n endfunction\nendclass\n", 3),
("module m;\r\n always_comb begin\r\n\r\nendmodule\r\n", 2),
("module m;\n initial begin\n", 2),
];
#[test]
fn qa_asking_again_after_the_answer_is_applied_adds_no_second_end() {
for &(text, line) in QA_ARMED {
let (after, edits) = typed(text, line, true);
assert!(edits.iter().any(|edit| edit.new_text.contains("end")), "{text:?}: {edits:?}");
let (again, second) = typed(&after, line, true);
assert!(
second.iter().all(|edit| !edit.new_text.contains("end")),
"{after:?}: {second:?}"
);
assert_eq!(again, after, "the second answer changes nothing: {text:?}");
}
}
#[test]
fn qa_a_declined_newline_is_exactly_the_plain_indent_answer() {
for (text, line) in [
("module m;\n always_comb begin\n\n end\nendmodule\n", 2),
("`define OPEN begin\n\nmodule m;\nendmodule\n", 1),
("`define BLK(x) if (x) begin \\\n\nmodule m;\nendmodule\n", 1),
("module m;\n initial $display(\"begin\n\nendmodule\n", 2),
("module m;\n`ifdef A\n always_ff @(posedge clk) begin\n`else\n always_ff @(posedge clk or negedge rst_n) begin\n\n`endif\n x <= 1;\n end\nendmodule\n", 5),
("module m;\n always_comb begin\n\nend\nendmodule\n", 2),
("module m;\n initial begin end\n\nendmodule\n", 2),
("module m;\n wire \\begin \n\nendmodule\n", 2),
("module m;\n initial begin\nfoo = 1;\nendmodule\n", 2),
] {
let (_, with) = typed(text, line, true);
let (_, without) = typed(text, line, false);
assert_eq!(with, without, "{text:?}");
}
}
/// Whether any edit writes an `end`.
fn wrote_an_end(edits: &[TextEdit]) -> bool {
edits.iter().any(|edit| edit.new_text.contains("end"))
}
#[test]
fn a_gnu_style_begin_already_closed_under_itself_gets_no_end() {
// Another `begin` above is unclosed (mid-edit), and this block's `end`
// sits under the `begin`'s own line rather than under the `if`.
let text = "module m;\n initial begin\n always_comb\n if (x)\n begin\n\n y = 1;\n end\nendmodule\n";
let (_, edits) = typed(text, 5, true);
assert!(!wrote_an_end(&edits), "{edits:?}");
}
#[test]
fn qa_ifdef_branches_sharing_one_end_get_no_second_end() {
// QA finding 1: two `ifdef` branches each open the `always` block and
// one `end` after the `endif` closes whichever was compiled.
let shared = "module m;\n`ifdef A\n always @(posedge clk) begin\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n if (x)\n begin\n\n y <= 1;\n end\n end\nendmodule\n";
let (_, edits) = typed(shared, 8, true);
assert!(!wrote_an_end(&edits), "after the GNU-style begin: {edits:?}");
// The cursor after the *first* branch's `begin`: that block's `end`
// is the shared one after the `endif`, so writing one would be wrong.
let first = "module m;\n`ifdef A\n always @(posedge clk) begin\n\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n y <= 1;\n end\nendmodule\n";
let (_, edits) = typed(first, 3, true);
assert!(!wrote_an_end(&edits), "inside the first branch: {edits:?}");
}
#[test]
fn an_ifdef_with_no_else_still_arms_the_answer() {
let text = "module m;\n`ifdef A\n initial begin\n\n`endif\nendmodule\n";
let (_, edits) = typed(text, 3, true);
assert!(wrote_an_end(&edits), "{edits:?}");
}
}
+6 -1
View File
@@ -1168,7 +1168,12 @@ mod tests {
#[test]
fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() {
let tree = Tree::new("macrocontrol");
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
// Spelled after a `.`: since §65.1's scoping of rename warnings, a
// *bare* `sig` in `far`'s own macro is `far`'s word, not `sub`'s port,
// and the engine rightly says nothing about it; a dotted one may be a
// path to the port and is still said — once.
let dotted = M_FAR.replace("sig)", "u_far.sig)");
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {dotted}endmodule\n");
let (ws, uri) = macro_workspace(&tree, &far);
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
+44 -2
View File
@@ -53,6 +53,7 @@ impl Server {
let buffers = self.dirty.len();
for (uri, text) in std::mem::take(&mut self.dirty) {
self.set_document(uri.clone(), text);
self.workspace.locate_port_entry(&uri);
crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri));
}
self.timed(started, |took| {
@@ -91,7 +92,7 @@ impl Server {
/// Everything the server has to say about a buffer — the one computation
/// both diagnostic models answer from. A buffer that is not open has
/// nothing said about it.
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
pub(super) fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
// The lint pass is given the project: the rule selection
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
@@ -100,7 +101,48 @@ impl Server {
// (`docs/features/semantic-lints-on/`).
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
self.report_config_problems(&run);
diagnostics::all_in(doc, &run)
// Except what the connection being typed would say, while it is being
// typed (`docs/features/port-entry-grace/README.md`).
self.workspace.port_grace().withhold(uri, doc, diagnostics::all_in(doc, &run))
}
/// Say everything again about each buffer whose connection entry is no
/// longer being typed: its quiet period ran out, or an edit landed in
/// another buffer.
///
/// The generation moves first, so a pulling client's next pull gets the
/// full list rather than "unchanged" against the withheld one; a pulling
/// client that accepts `workspace/diagnostic/refresh` is asked — once per
/// release, however many buffers it covers — to make that pull now. Its
/// answer is ignorable and rides `response`'s fall-through. A pulling
/// client without the capability sees the release at its own next pull.
pub(super) fn release_port_entries(&mut self) {
let due = self.workspace.port_grace_mut().due(std::time::Instant::now());
if due.is_empty() {
return;
}
self.generation += 1;
for uri in &due {
self.publish(uri);
}
if self.abilities.pull_diagnostics && self.abilities.diagnostic_refresh {
use lsp_types::request::{Request as _, WorkspaceDiagnosticRefresh};
self.send_request(WorkspaceDiagnosticRefresh::METHOD, ());
}
}
/// How long the loop may wait for a message before it owes something: a
/// dirty buffer's quiet period, or the end of a connection entry's grace,
/// whichever comes first. `None` is "nothing is owed; wait for ever".
pub(super) fn quiet_wait(&self) -> Option<std::time::Duration> {
let debounce = (!self.dirty.is_empty()).then_some(super::CHANGE_DEBOUNCE);
let now = std::time::Instant::now();
let grace =
self.workspace.port_grace().deadline().map(|at| at.saturating_duration_since(now));
match (debounce, grace) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
+2 -1
View File
@@ -568,7 +568,8 @@ impl Server {
decode(request).and_then(|p: InlineCompletionParams| {
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
inline::inline_completions(&self.workspace, &uri, position)
let selected = p.context.selected_completion_info.as_ref();
inline::inline_completions_in_context(&self.workspace, &uri, position, selected)
.map_or(Ok(Value::Null), to_value)
})
}
+16 -5
View File
@@ -26,7 +26,7 @@ impl Server {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let result = format::formatting(doc, &settings.config);
let result = self.auto_styles.format_document(&uri, doc, &settings.config);
// A broken `lucisv.toml` is a warning, not a failure: the CLI exits 2 on
// one, but an editor that refuses to format because of a typo in a
// config file is an editor the user turns off. The buffer is formatted
@@ -45,7 +45,8 @@ impl Server {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let result = format::range_formatting(doc, &settings.config, params.range);
let config = self.auto_styles.concrete(&uri, doc, settings.config);
let result = format::range_formatting(doc, &config, params.range);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
@@ -65,7 +66,8 @@ impl Server {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let result = format::ranges_formatting(doc, &settings.config, &params.ranges);
let config = self.auto_styles.concrete(&uri, doc, settings.config);
let result = format::ranges_formatting(doc, &config, &params.ranges);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
@@ -98,7 +100,16 @@ impl Server {
return to_value(Vec::<lsp_types::TextEdit>::new());
};
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let edits = on_type::on_type_formatting(doc, at.position, &params.ch, &settings.config);
// Only a `;` lays anything out; a newline needs no preset, so it must
// not pay for finding one.
let config = match params.ch.as_str() {
on_type::SEMICOLON => {
self.auto_styles.concrete(&at.text_document.uri, doc, settings.config)
}
_ => settings.config,
};
let auto_end = self.workspace.client_settings().auto_end.unwrap_or(true);
let edits = on_type::on_type_formatting(doc, at.position, &params.ch, &config, auto_end);
to_value(edits)
}
@@ -131,7 +142,7 @@ impl Server {
// so the ladder runs without its `tabSize` rung.
let settings =
format::settings_without_editor_options(doc, self.workspace.client_settings());
let result = format::formatting(doc, &settings.config);
let result = self.auto_styles.format_document(&uri, doc, &settings.config);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
+99 -15
View File
@@ -18,9 +18,21 @@ use super::batch::opened_in;
use super::client::{notify_on, plural};
use super::progress::IndexWatch;
use super::{Server, INTERLEAVE_ABOVE};
use crate::state::{IndexEvent, Scan, Workspace};
use crate::state::{IndexEvent, OneFile, Scan, Watched, Workspace};
use crate::{design_hierarchy, file_ops};
/// A watcher event naming more than one path per `BURST_DIVISOR` files the
/// index holds takes the whole rescan instead of being sorted path by path.
///
/// Measured on the full OpenTitan `hw` tree (4 058 files, release, one
/// notification of generated files under a gitignored directory, medians of
/// 3): sorting costs ~0.10 ms a path (1 000 paths 0.10 s, 5 000 paths 0.50 s),
/// a cached whole rescan ~0.16 ms an indexed file (0.63–0.65 s) — so the two
/// cross near 1.6 paths per file, and both scale with the tree. Dividing by 2
/// keeps the sorted path at or under ~0.3× the rescan it saves on any tree
/// (QA R2-1: never slower than 7408fac's one rescan per notification).
const BURST_DIVISOR: usize = 2;
impl Server {
/// Rescan the workspace and republish every open buffer against the new
/// index. Every caller changed what the index should contain — a save, a
@@ -59,15 +71,22 @@ impl Server {
/// that file is one the index already holds. Reports whether it ran; a
/// `false` means the caller owes a whole rebuild.
///
/// Everything a rebuild does *after* the scan happens here too, for the
/// same reasons: the code-lens refresh (the file that moved may have
/// changed an instantiation count in any buffer), the diagnostics
/// generation bump (every open buffer's diagnostics are computed against
/// the index), and a republish of every open buffer. The republish stays
/// wholesale rather than narrowing to the buffers that could have moved:
/// a lint reads the index, so any buffer's diagnostics may have changed,
/// and narrowing it correctly needs a dependency graph this server does not
/// have. Worth doing later; wrong to guess at now.
/// When the index moved, everything a rebuild does *after* the scan
/// happens here too, for the same reasons: the code-lens refresh (the file
/// that moved may have changed an instantiation count in any buffer), the
/// hierarchy view's invalidation, the diagnostics generation bump (every
/// open buffer's diagnostics are computed against the index), and a
/// republish of every open buffer. The republish stays wholesale: a lint
/// reads the index, so any buffer's diagnostics may have changed, and it
/// costs ~0.3 ms a buffer on OpenTitan — narrowing it would buy nothing
/// measurable for the one place a stale squiggle could hide
/// (`docs/features/localized-reindex/README.md`).
///
/// When the file's record did **not** move — the watcher's echo of the
/// save that just ran, a save of an unchanged buffer — every answer read
/// off the index alone is the answer it already was, so no lens refresh
/// and no hierarchy invalidation is sent. The republish still is: see
/// below.
///
/// Three things a whole rebuild does that this deliberately does not:
///
@@ -93,19 +112,84 @@ impl Server {
return true;
}
let started = self.timer();
if !self.workspace.update_one(path) {
let outcome = self.workspace.update_one_file(path);
if outcome == OneFile::NotHeld {
// No line: nothing was reindexed, and the caller is about to
// rebuild the whole index — which times itself.
return false;
}
self.refresh_code_lenses();
self.hierarchy_index_changed();
// Lenses and the hierarchy view are read off the index alone, so an
// unchanged record owes them nothing. Diagnostics are not: a lint
// also reads the buffer's `lucisv.toml` and waiver files from disk,
// which no notification reports, and a save has always been when an
// edit to them takes effect (QA F2). So every save republishes.
if outcome == OneFile::Changed {
self.refresh_code_lenses();
self.hierarchy_index_changed();
}
self.republish_all();
// The unchanged case says so inside the parentheses, so every reader
// of the old `reindex_one(<path>) took <ms>` shape still matches.
let unchanged = if outcome == OneFile::Unchanged { ", unchanged" } else { "" };
self.timed(started, |took| {
format!("reindex_one({}{unchanged}) took {took}", path.display())
});
true
}
/// The rescan a watcher event owes, decided file by file
/// ([`Workspace::watched`]): a file the scope provably cannot take — a
/// generated file under a gitignored directory, one outside the folder
/// scope or the filelist — owes nothing; a held file, by whatever
/// spelling the client used, is the one-file update; anything the scope
/// may take and the index does not hold is a whole rebuild, and so are
/// two or more held files, exactly as a checkout always was.
///
/// `named` is every path the event named, any extension: the include
/// lines that could name one are re-resolved first, unless the event takes
/// the whole rescan, which re-resolves all of them (QA F1). An event that owes the index
/// nothing still republishes every open buffer, for the reason
/// [`Server::reindex_one`] gives.
pub(super) fn reindex_watched(
&mut self,
paths: &[std::path::PathBuf],
named: &[std::path::PathBuf],
) {
// A burst — a branch switch, a generator run — is sorted file by file
// only while that is cheaper than the rescan it replaces.
if paths.len().saturating_mul(BURST_DIVISOR) > self.workspace.index().files().len() {
return self.reindex();
}
self.workspace.refresh_includes_naming(named);
let mut held: Vec<std::path::PathBuf> = Vec::new();
for path in paths {
match self.workspace.watched(path) {
Watched::Held(spelled) => held.push(spelled),
Watched::Outside => {}
Watched::Unknown => return self.reindex(),
}
}
held.sort();
held.dedup();
match held.as_slice() {
[] => self.republish_all(),
[one] => {
if !self.reindex_one(one) {
self.reindex();
}
}
_ => self.reindex(),
}
}
/// Every open buffer's diagnostics said again, under a new generation so
/// a pulling client asks again too — what a save owes even when the index
/// did not move. ~0.3 ms a buffer on OpenTitan.
pub(super) fn republish_all(&mut self) {
self.generation += 1;
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
true
}
/// [`Server::reindex`] for a `didOpen` that only ever **added** folders to
+24 -7
View File
@@ -88,6 +88,12 @@ pub struct ClientAbilities {
/// that said nothing is never asked, and keeps the instantiation counts it
/// last requested until it asks again for its own reasons.
pub code_lens_refresh: bool,
/// Whether the client accepts a `workspace/diagnostic/refresh` — what
/// makes a pulling client pull again when a connection entry held back
/// while it was typed is released
/// (`docs/features/port-entry-grace/README.md`). A client that said
/// nothing sees the release at its own next pull.
pub diagnostic_refresh: bool,
/// Whether the client opens a document the server asks it to
/// (`window/showDocument`). This is what lets the instantiation lens
/// navigate; a client without it still gets the sites back as the
@@ -129,6 +135,11 @@ pub struct Server {
/// for a document whenever its text changes, so the warning is said once
/// per file change rather than once per format-on-save.
config_warnings: HashSet<Uri>,
/// The preset `style = "auto"` last settled on for each recently
/// formatted document, so range, selection and on-type requests neither
/// search every preset again nor lose the file's preset while the buffer
/// does not parse (`auto_style.rs`).
auto_styles: crate::auto_style::AutoStyles,
/// Which `[lint]` entries of which `lucisv.toml` have already been
/// reported (§42.2). Interior-mutable because a lint pass runs behind
/// `&self` — the pull models compute diagnostics inside a `map` over the
@@ -316,7 +327,9 @@ impl Server {
///
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
/// flushed here rather than left waiting for a request that may never
/// come — diagnostics are the one answer the client never asks for.
/// come — diagnostics are the one answer the client never asks for. The
/// same wake-up releases a connection entry whose diagnostics were held
/// back while it was typed, once its grace has run out.
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
use std::sync::mpsc::RecvTimeoutError;
loop {
@@ -338,20 +351,24 @@ impl Server {
}
continue;
}
let message = if self.dirty.is_empty() {
match self.queue.recv() {
// A connection entry whose grace ran out while messages kept
// arriving is released here, not only when the wait below times
// out (`docs/features/port-entry-grace/README.md`).
self.release_port_entries();
let message = match self.quiet_wait() {
None => match self.queue.recv() {
Ok(message) => message,
Err(_) => return Ok(()),
}
} else {
match self.queue.recv_timeout(CHANGE_DEBOUNCE) {
},
Some(wait) => match self.queue.recv_timeout(wait) {
Ok(message) => message,
Err(RecvTimeoutError::Timeout) => {
self.flush_dirty();
self.release_port_entries();
continue;
}
Err(RecvTimeoutError::Disconnected) => return Ok(()),
}
},
};
let batch = burst(&self.queue, message);
if self.process_batch(batch)? {
+77 -10
View File
@@ -25,6 +25,7 @@ use serde::de::DeserializeOwned;
use super::batch::{widen_of, Widen};
use super::client::ms;
use super::Server;
use crate::uri::uri_to_path;
use crate::{file_ops, lint, settings, sync, watch};
impl Server {
@@ -51,6 +52,11 @@ impl Server {
self.dirty.retain(|(pending, _)| *pending != uri);
}
}
// A buffer saved, closed or opened afresh holds nothing back any more
// (`docs/features/port-entry-grace/README.md`). Forgotten before the
// flush, so the flush below already publishes everything.
let released = self.forget_port_entry(&method, &notification);
self.auto_styles.notice(&notification);
// Everything but a `didChange` needs the buffers' analyses current —
// a `didSave` rebuilds the index on top of them — so the same flush a
// request gets happens here, with the one exception that *is* the
@@ -58,6 +64,14 @@ impl Server {
if method != DidChangeTextDocument::METHOD {
self.flush_dirty();
}
// A save of a buffer that was not dirty: nothing above said the full
// list, so it is said here, under a new generation for a pulling
// client. (The rescan the save starts says it again; that is the same
// list twice, never a stale one.)
if let Some(uri) = released {
self.generation += 1;
self.publish(&uri);
}
match method.as_str() {
DidOpenTextDocument::METHOD => {
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
@@ -103,7 +117,7 @@ impl Server {
return;
}
let uri = p.text_document.uri;
let text = {
let (text, end) = {
let base = self
.dirty
.iter()
@@ -111,15 +125,30 @@ impl Server {
.map(|(_, text)| text.as_str())
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
.unwrap_or("");
sync::apply_changes(base, &p.content_changes)
sync::apply_changes_at(base, &p.content_changes)
};
self.auto_styles.changed(&uri, &p.content_changes, &text);
// Where the edit ended is where someone is typing: the
// flush looks it up for a connection entry to hold back.
let now = std::time::Instant::now();
self.workspace.port_grace_mut().edited(&uri, end, now);
self.mark_dirty(uri, text);
}
}
DidSaveTextDocument::METHOD => {
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
// A save carrying the text the buffer already holds — the
// normal case, since every change was flushed above — has
// nothing to re-analyze. One carrying different text is a
// change the server missed: analyzed and published here,
// so the buffer's own answer is current whatever the
// reindex below finds moved.
if let Some(text) = p.text {
self.set_document(p.text_document.uri.clone(), text);
let uri = p.text_document.uri.clone();
if self.workspace.document(&uri).is_none_or(|doc| doc.text != text) {
self.set_document(uri.clone(), text);
self.publish(&uri);
}
}
// A save is one of the things that rebuild the index; the
// others are a change to `lucisv.exclude`/`lucisv.filelist`
@@ -142,15 +171,28 @@ impl Server {
// the params carry a list, and a checkout fills it.
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
// Whatever else the event owes, every path it names may
// be what an `include` line was looking for — in scope or
// not, of a source extension or not (QA F1). A rescan
// re-resolves every line anyway, so only the paths that
// do not take one are refreshed here.
let named: Vec<std::path::PathBuf> =
p.changes.iter().filter_map(|change| uri_to_path(&change.uri)).collect();
let filelist = self.workspace.filelist_path();
if watch::touches_scope(&p.changes, filelist.as_deref()) {
// One file named is the incremental case; a checkout
// filling the list, or the filelist itself moving, is
// the whole rebuild.
let one = watch::one_scope_file(&p.changes, filelist.as_deref());
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
self.reindex();
if watch::names_a_config(&p.changes) {
// A `lucisv.toml` moves excludes, the filelist and
// the lint configuration at once — for the client
// that forwards it (ours registers sources only).
self.reindex();
} else if watch::touches_scope(&p.changes, filelist.as_deref()) {
// The filelist itself moving is the whole rebuild;
// anything else is sorted file by file.
match watch::scope_files(&p.changes, filelist.as_deref()) {
Some(paths) => self.reindex_watched(&paths, &named),
None => self.reindex(),
}
} else {
self.workspace.refresh_includes_naming(&named);
}
}
}
@@ -243,6 +285,7 @@ impl Server {
/// about what a setting *does* any more than `settings::from_payload` and
/// `from_section` can disagree about what it says.
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
self.auto_styles.forget_all();
let watched = self.workspace.filelist_path();
let linted = self.lint_selection();
// A `lucisv.lint.options` entry the registry refused is dropped, not
@@ -315,6 +358,23 @@ impl Server {
}
}
/// Forget the connection entry a `didOpen`, `didSave` or `didClose` names,
/// answering the buffer whose full list a save now owes the client. An
/// open publishes on its own and a close clears, so only a save asks.
fn forget_port_entry(&mut self, method: &str, notification: &Notification) -> Option<Uri> {
let ends_typing = [
DidOpenTextDocument::METHOD,
DidSaveTextDocument::METHOD,
DidCloseTextDocument::METHOD,
];
if !ends_typing.contains(&method) {
return None;
}
let uri = document_uri(notification)?;
let held = self.workspace.port_grace_mut().forget(&uri);
(held && method == DidSaveTextDocument::METHOD).then_some(uri)
}
/// The rule selection in force, as a value two settings pushes can be
/// compared by.
///
@@ -346,6 +406,13 @@ fn closing_uri(notification: &Notification) -> Option<Uri> {
.map(|p| p.text_document.uri)
}
/// The `textDocument.uri` a document notification names, read without
/// consuming it; `None` when the params carry none that parses.
fn document_uri(notification: &Notification) -> Option<Uri> {
let uri = notification.params.get("textDocument")?.get("uri")?.as_str()?;
uri.parse().ok()
}
/// The paths behind a `didChangeWorkspaceFolders` list.
///
/// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once
@@ -146,6 +146,7 @@ impl Server {
connection,
workspace: Workspace::default(),
config_warnings: HashSet::new(),
auto_styles: Default::default(),
lint_config_problems: std::cell::RefCell::default(),
said_lint_names: Vec::new(),
abilities,
@@ -125,7 +125,7 @@ fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
// directory is raised on its own and none of them is ever dropped — so
// this is an add like any other, and the widen's own file diff is what
// stops the overlap being read twice
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
// (`state::tests::widen::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
let ip = PathBuf::from("/w");
assert_eq!(
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
@@ -135,6 +135,27 @@ fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
assert!(session.shown().is_empty(), "a clean config says nothing");
}
#[test]
fn a_selection_inside_a_nested_block_lays_out_only_that_block() {
// The owner's report (TODO §66.2): a `case` selected inside an `always`
// in a four-space file. Only the `case` moves, and it stays where it
// starts; the statement after it and the parent keep their bytes.
let tree = Tree::new("rangesnested");
let mut session = Session::new(vec![tree.path.clone()], false);
let text = "module m;\n always @* begin\n case (s)\n 0: y=a;\n endcase\n z = 1;\n end\nendmodule\n";
let uri = session.open(&tree.path.join("m.sv"), text);
let one = range_result(&mut session, &uri, json_range(2, 0, 5, 0));
assert_eq!(
one[0]["newText"],
"module m;\n always @* begin\n case (s)\n 0: y = a;\n endcase\n z = 1;\n end\nendmodule\n",
"{one:#?}"
);
// The multi-range method gives the same answer for the same selection.
assert_eq!(ranges_result(&mut session, &uri, vec![json_range(2, 0, 5, 0)]), one);
assert!(session.shown().is_empty());
}
#[test]
fn one_range_through_the_new_method_answers_what_the_old_method_answers() {
// The two requests are the same engine, and a client must never have
@@ -250,9 +271,11 @@ fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
// user cannot type past would arrive on every semicolon.
let tree = Tree::new("ontypequiet");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
// The error sits on the keystroke's own line: since selection formatting
// (TODO §66.2) an error on *another* line no longer refuses the request.
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a = ;\n");
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
assert_eq!(on_type(&mut session, &uri, ";", 1, 13), serde_json::json!([]));
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
// ...and the whole-document request on the same buffer still does say
// something, so the silence is this path's decision and not a
@@ -626,3 +649,188 @@ fn a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save()
assert_eq!(third, serde_json::json!([]));
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
}
// ------------------------------------------------------------------
// `lucisv.format.style = "auto"`: the preset the server remembers
// ------------------------------------------------------------------
/// A google-formatted buffer: one connection per line at a 4-space indent.
const GOOGLE_BUFFER: &str = "\
module m (
input logic a,
output logic b
);
sub u_sub (
.a(a),
.b(b)
);
endmodule
";
fn push_auto(session: &mut Session) {
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "format": { "style": "auto" } } } }),
);
}
fn format_whole(session: &mut Session, uri: &Uri) -> Value {
session.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"options": { "tabSize": 2, "insertSpaces": true },
}),
)
}
/// After a whole-document format under `auto`, a range in the same buffer
/// keeps the buffer's preset even once a half-typed line elsewhere stops it
/// from parsing — which a fresh search could not do.
#[test]
fn auto_ranges_keep_the_remembered_preset_while_the_buffer_does_not_parse() {
let tree = Tree::new("autorange");
let mut session = Session::new(vec![tree.path.clone()], false);
push_auto(&mut session);
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
assert_eq!(format_whole(&mut session, &uri), serde_json::json!([]), "already google");
let edited = GOOGLE_BUFFER
.replace("endmodule", " sub u_two (.a(a), .b(b));\n assign c = ;\nendmodule");
change(&mut session, &uri, 2, serde_json::json!([{ "text": edited }]));
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
let text = ranged[0]["newText"].as_str().expect("an edit");
assert!(text.contains(" sub u_two (\n .a(a),\n .b(b)\n );\n"), "{text}");
// And the `;` path agrees with it, byte for byte.
let typed = on_type(&mut session, &uri, ";", 8, 27);
assert_eq!(typed, ranged);
}
/// With no memory and a buffer that does not parse there is nothing to
/// resolve from, so the default preset's layout answers — the documented
/// fallback — and nothing is remembered.
#[test]
fn auto_without_a_memory_and_without_a_parse_uses_the_default_layout() {
let tree = Tree::new("autofallback");
let mut session = Session::new(vec![tree.path.clone()], false);
push_auto(&mut session);
let text = GOOGLE_BUFFER
.replace("endmodule", " sub u_two (.a(a), .b(b));\n assign c = ;\nendmodule");
let uri = session.open(&tree.path.join("m.sv"), &text);
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
assert_eq!(ranged, serde_json::json!([]), "the default layout already holds that line");
assert!(session.server.auto_styles.is_empty(), "a fallback is not remembered");
}
/// With no memory and a buffer that parses, the first range request
/// resolves the preset once and remembers it for the next.
#[test]
fn auto_without_a_memory_resolves_from_a_buffer_that_parses() {
let tree = Tree::new("autoresolve");
let mut session = Session::new(vec![tree.path.clone()], false);
push_auto(&mut session);
let text = GOOGLE_BUFFER.replace("endmodule", " sub u_two (.a(a), .b(b));\nendmodule");
let uri = session.open(&tree.path.join("m.sv"), &text);
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
let out = ranged[0]["newText"].as_str().expect("an edit");
assert!(out.contains(" sub u_two (\n .a(a),\n .b(b)\n );\n"), "{out}");
assert!(!session.server.auto_styles.is_empty());
}
/// The google buffer re-laid out lucisv-style, with one unformatted
/// instance on line 3 that the two presets lay out differently.
const LUCISV_BUFFER: &str = "\
module m (input logic a, output logic b);
sub u_sub (.a(a), .b(b));
endmodule
";
fn lucisv_with_instance() -> String {
LUCISV_BUFFER.replace("endmodule", "sub u_two (.a(a), .b(b));\nendmodule")
}
/// The range answer for line 2 (0-based) of the lucisv buffer. A selection
/// keeps the indentation its line was written at, so lucisv's layout of the
/// one-line instance is the line itself — no edit — where google's would
/// break it into four (`auto_without_a_memory_resolves_from_a_buffer_that_parses`).
fn assert_lucisv_layout(session: &mut Session, uri: &Uri) {
let ranged = range_result(session, uri, json_range(2, 0, 2, 0));
assert_eq!(ranged, serde_json::json!([]), "laid out lucisv-style, not google-style");
}
/// R2-1 (a): the buffer replaced wholesale by text in another preset — a
/// reload from disk — is resolved again, not served the old preset.
#[test]
fn auto_a_replaced_buffer_is_resolved_again() {
let tree = Tree::new("autoreplaced");
let mut session = Session::new(vec![tree.path.clone()], false);
push_auto(&mut session);
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
format_whole(&mut session, &uri);
assert!(!session.server.auto_styles.is_empty(), "google remembered");
change(&mut session, &uri, 2, serde_json::json!([{ "text": lucisv_with_instance() }]));
assert_lucisv_layout(&mut session, &uri);
}
/// R2-1 (b): auto → a whole-document format under a named style → auto.
#[test]
fn auto_after_a_named_style_format_does_not_reuse_the_old_preset() {
let tree = Tree::new("autonamed");
let mut session = Session::new(vec![tree.path.clone()], false);
push_auto(&mut session);
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
format_whole(&mut session, &uri);
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "format": { "style": "lucisv" } } } }),
);
assert!(session.server.auto_styles.is_empty(), "a settings change forgets everything");
format_whole(&mut session, &uri);
push_auto(&mut session);
// An incremental edit, so only the settings change and the named format
// can be what made the memory forget.
let text = lucisv_with_instance();
change(
&mut session,
&uri,
2,
serde_json::json!([{ "range": { "start": { "line": 0, "character": 0 },
"end": { "line": 9, "character": 0 } },
"text": text }]),
);
assert_lucisv_layout(&mut session, &uri);
}
/// R2-1 (c): close, then reopen the same URI with other content.
#[test]
fn auto_a_reopened_document_starts_with_no_memory() {
let tree = Tree::new("autoreopen");
let mut session = Session::new(vec![tree.path.clone()], false);
push_auto(&mut session);
let path = tree.path.join("m.sv");
let uri = session.open(&path, GOOGLE_BUFFER);
format_whole(&mut session, &uri);
session.notify(
DidCloseTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
assert!(session.server.auto_styles.is_empty(), "closing forgets");
let uri = session.open(&path, &lucisv_with_instance());
assert_lucisv_layout(&mut session, &uri);
}
/// R2-1 (d): a renamed file's old name is forgotten with it.
#[test]
fn auto_a_rename_forgets_both_names() {
let tree = Tree::new("autorename");
let mut session = Session::new(vec![tree.path.clone()], false);
push_auto(&mut session);
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
format_whole(&mut session, &uri);
let new = crate::uri::path_to_uri(&tree.path.join("n.sv")).expect("uri");
session.notify(
DidRenameFiles::METHOD,
serde_json::json!({ "files": [{ "oldUri": uri.as_str(), "newUri": new.as_str() }] }),
);
assert!(session.server.auto_styles.is_empty());
}
@@ -0,0 +1,691 @@
//! Call hierarchy from wherever the cursor is, and for functions and tasks
//! (`docs/features/call-hierarchy-everywhere/README.md`), driven through the
//! real dispatch.
//!
//! The fixture is a small design: a package of functions (one recursive), a
//! module that imports it and calls through a function, a task and an
//! `always` block, a top that instantiates that module and calls the package
//! with a scoped name, and a class whose methods call each other through
//! `this.` and through a handle.
use lsp_types::request::{CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls};
use lsp_types::{CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall};
use super::*;
const PKG: &str = "\
package util_pkg;
function automatic int add1(int a);
return a + 1;
endfunction : add1
function automatic int fact(int n);
if (n <= 1) return 1;
return n * fact(n - 1);
endfunction
endpackage
";
const CORE: &str = "\
module core (input logic clk, output int q);
import util_pkg::*;
int r;
function automatic int twice(int a);
twice = add1(a) + add1(a);
endfunction
task automatic kick(input int v);
r = twice(v);
$display(\"%0d\", v);
endtask
always_ff @(posedge clk) begin
q <= twice(r);
end
initial kick(3);
endmodule
";
const TOP: &str = "\
// the top of the design
module top;
logic clk;
int q;
core u_core (.clk(clk), .q(q));
int z = util_pkg::add1(2);
endmodule
";
const CLS: &str = "\
class counter;
int n;
extern function void reset();
function void bump();
n++;
endfunction
function void bump_twice();
bump();
this.bump();
endfunction
task run();
counter h;
h = new;
h.bump();
endtask
endclass
class fancy extends counter;
function void bump_more();
super.bump();
endfunction
endclass
function void counter::reset();
bump();
endfunction
";
/// The design on disk, a wide session over it, `core.sv` open.
fn design(name: &str) -> (Tree, Session, Uri) {
let tree = Tree::new(name);
tree.write("util_pkg.sv", PKG);
tree.write("core.sv", CORE);
tree.write("top.sv", TOP);
tree.write("cls.sv", CLS);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("core.sv"), CORE);
session.drain();
(tree, session, uri)
}
/// The LSP position of the `nth` occurrence of `needle` in `text`, `skip`
/// bytes in.
fn pos(text: &str, needle: &str, nth: usize, skip: usize) -> Value {
let mut at = text.find(needle).expect("needle");
for _ in 0..nth {
at = text[at + 1..].find(needle).expect("nth needle") + at + 1;
}
let at = at + skip;
let line = text[..at].matches('\n').count();
let character = at - text[..at].rfind('\n').map_or(0, |nl| nl + 1);
serde_json::json!({ "line": line, "character": character })
}
/// `prepareCallHierarchy` at a position: `None` for a `null` answer.
fn prepare(session: &mut Session, uri: &Uri, position: Value) -> Option<Vec<CallHierarchyItem>> {
let result = session.result(
CallHierarchyPrepare::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "position": position }),
);
serde_json::from_value(result).expect("items or null")
}
/// The one item prepared at a position.
fn one(session: &mut Session, uri: &Uri, position: Value) -> CallHierarchyItem {
let items = prepare(session, uri, position).expect("an item");
assert_eq!(items.len(), 1, "{items:#?}");
items.into_iter().next().expect("one")
}
fn incoming(session: &mut Session, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
let result =
session.result(CallHierarchyIncomingCalls::METHOD, serde_json::json!({ "item": item }));
serde_json::from_value(result).expect("incoming calls")
}
fn outgoing(session: &mut Session, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
let result =
session.result(CallHierarchyOutgoingCalls::METHOD, serde_json::json!({ "item": item }));
serde_json::from_value(result).expect("outgoing calls")
}
/// An item as `(name, file name, selection line)`.
fn shape(item: &CallHierarchyItem) -> (String, String, u32) {
let file = item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string();
(item.name.clone(), file, item.selection_range.start.line)
}
/// Each incoming call as `(caller name, caller file, lines of its ranges)`.
fn callers(calls: &[CallHierarchyIncomingCall]) -> Vec<(String, String, Vec<u32>)> {
calls
.iter()
.map(|call| {
let (name, file, _) = shape(&call.from);
(name, file, call.from_ranges.iter().map(|r| r.start.line).collect())
})
.collect()
}
/// Each outgoing call as `(callee name, callee file, lines of its ranges)`.
fn callees(calls: &[CallHierarchyOutgoingCall]) -> Vec<(String, String, Vec<u32>)> {
calls
.iter()
.map(|call| {
let (name, file, _) = shape(&call.to);
(name, file, call.from_ranges.iter().map(|r| r.start.line).collect())
})
.collect()
}
fn s(text: &str) -> String {
text.to_string()
}
// ----------------------------------------------------------------------
// prepare, every position
// ----------------------------------------------------------------------
#[test]
fn an_instance_name_prepares_the_instantiated_module() {
let (tree, mut session, _) = design("hev_instance");
let top = session.open(&tree.path.join("top.sv"), TOP);
let item = one(&mut session, &top, pos(TOP, "u_core", 0, 2));
assert_eq!(shape(&item), (s("core"), s("core.sv"), 0));
assert_eq!(item.kind, lsp_types::SymbolKind::MODULE);
assert!(item.data.is_none(), "a module item is the M11 item, unchanged");
}
#[test]
fn a_function_declaration_a_call_and_its_end_label_prepare_the_function() {
let (tree, mut session, core) = design("hev_function");
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
let declared = one(&mut session, &pkg, pos(PKG, "add1(int", 0, 1));
let labelled = one(&mut session, &pkg, pos(PKG, ": add1", 0, 3));
let called = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
for item in [&declared, &labelled, &called] {
assert_eq!(shape(item), (s("add1"), s("util_pkg.sv"), 1));
assert_eq!(item.kind, lsp_types::SymbolKind::FUNCTION);
assert_eq!(item.detail.as_deref(), Some("util_pkg"));
let data = item.data.as_ref().expect("data");
assert_eq!(data["kind"], "function");
assert_eq!(data["name"], "add1");
assert!(data["offset"].is_u64(), "{data}");
}
assert_eq!(declared, called, "one item, wherever it was prepared from");
}
#[test]
fn a_cursor_just_past_a_call_name_prepares_the_function() {
let (_tree, mut session, core) = design("hev_caret");
let item = one(&mut session, &core, pos(CORE, "twice(v)", 0, 5));
assert_eq!(shape(&item), (s("twice"), s("core.sv"), 4));
}
#[test]
fn a_task_declaration_and_a_call_prepare_the_task() {
let (_tree, mut session, core) = design("hev_task");
for position in [pos(CORE, "kick(input", 0, 0), pos(CORE, "kick(3)", 0, 1)] {
let item = one(&mut session, &core, position);
assert_eq!(shape(&item), (s("kick"), s("core.sv"), 8));
assert_eq!(item.data.as_ref().expect("data")["kind"], "task");
assert_eq!(item.kind, lsp_types::SymbolKind::FUNCTION);
}
}
#[test]
fn inside_a_function_or_task_body_prepares_it() {
let (_tree, mut session, core) = design("hev_body");
let in_task = one(&mut session, &core, pos(CORE, "$display", 0, 2));
assert_eq!(shape(&in_task), (s("kick"), s("core.sv"), 8), "a system task names no item");
let on_arg = one(&mut session, &core, pos(CORE, "v);", 0, 0));
assert_eq!(shape(&on_arg).0, "kick", "a use of an argument");
let on_keyword = one(&mut session, &core, pos(CORE, "endfunction", 0, 3));
assert_eq!(shape(&on_keyword).0, "twice", "the closing keyword");
}
#[test]
fn inside_a_module_body_prepares_the_module() {
let (_tree, mut session, core) = design("hev_module");
for (what, position) in [
("a net declaration", pos(CORE, "int r", 0, 4)),
("inside an always block", pos(CORE, "q <=", 0, 0)),
("an import", pos(CORE, "import", 0, 2)),
] {
let item = one(&mut session, &core, position);
assert_eq!(shape(&item), (s("core"), s("core.sv"), 0), "{what}");
assert!(item.data.is_none(), "{what}: the module item, as M11 builds it");
}
}
#[test]
fn where_nothing_encloses_the_cursor_prepare_is_null() {
let (tree, mut session, _) = design("hev_null");
let top = session.open(&tree.path.join("top.sv"), TOP);
assert!(prepare(&mut session, &top, pos(TOP, "the top", 0, 0)).is_none(), "a file comment");
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
assert!(
prepare(&mut session, &pkg, pos(PKG, "\n\n", 0, 1)).is_none(),
"a package body outside its functions"
);
let cls = session.open(&tree.path.join("cls.sv"), CLS);
assert!(
prepare(&mut session, &cls, pos(CLS, "int n", 0, 4)).is_none(),
"a class property: the call hierarchy has no class node to open"
);
}
#[test]
fn existing_module_answers_are_unchanged() {
let (tree, mut session, core) = design("hev_unchanged");
let top = session.open(&tree.path.join("top.sv"), TOP);
let declared = one(&mut session, &core, pos(CORE, "module core", 0, 7));
let instantiated = one(&mut session, &top, pos(TOP, "core u_core", 0, 1));
assert_eq!(declared, instantiated);
assert!(declared.data.is_none());
assert_eq!(callers(&incoming(&mut session, &declared)), [(s("top"), s("top.sv"), vec![4])]);
assert!(outgoing(&mut session, &declared).is_empty(), "a module lists no function calls");
}
// ----------------------------------------------------------------------
// incoming and outgoing for functions and tasks
// ----------------------------------------------------------------------
#[test]
fn a_function_called_from_a_task_and_an_always_block() {
let (_tree, mut session, core) = design("hev_twice");
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
let calls = incoming(&mut session, &twice);
assert_eq!(
callers(&calls),
[(s("core"), s("core.sv"), vec![14]), (s("kick"), s("core.sv"), vec![9])],
"the task and the module of the always block; not `twice = …`, which is a result"
);
assert_eq!(calls[0].from.kind, lsp_types::SymbolKind::MODULE);
assert!(calls[0].from.data.is_none(), "a module caller is the M11 item");
assert_eq!(calls[1].from.data.as_ref().expect("data")["kind"], "task");
let from = calls[1].from_ranges[0];
assert_eq!((from.start.character, from.end.character), (8, 13), "the call's name");
}
#[test]
fn a_task_called_from_an_initial_block_and_its_outgoing_calls() {
let (_tree, mut session, core) = design("hev_kick");
let kick = one(&mut session, &core, pos(CORE, "kick(input", 0, 0));
assert_eq!(callers(&incoming(&mut session, &kick)), [(s("core"), s("core.sv"), vec![17])]);
assert_eq!(
callees(&outgoing(&mut session, &kick)),
[(s("twice"), s("core.sv"), vec![9])],
"`$display` is a system task and is skipped"
);
}
#[test]
fn outgoing_calls_resolve_into_another_file_grouped_by_callee() {
let (_tree, mut session, core) = design("hev_out");
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
let calls = outgoing(&mut session, &twice);
assert_eq!(callees(&calls), [(s("add1"), s("util_pkg.sv"), vec![5, 5])]);
assert_eq!(calls[0].to.data.as_ref().expect("data")["kind"], "function");
}
#[test]
fn a_package_function_is_called_from_modules_in_other_files() {
// `util_pkg.sv` and `top.sv` are closed: the item is prepared from the
// call in `core.sv`, and the callers are found the way references are.
let (_tree, mut session, core) = design("hev_cross");
let add1 = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
let calls = incoming(&mut session, &add1);
assert_eq!(
callers(&calls),
[(s("twice"), s("core.sv"), vec![5, 5]), (s("top"), s("top.sv"), vec![5])],
"a function caller in an open file, a module caller in a closed one; the end label is no call"
);
let top = &calls[1].from;
let instantiated = outgoing(&mut session, top);
assert_eq!(
callees(&instantiated),
[(s("core"), s("core.sv"), vec![4])],
"expanding a module caller walks the design, one level down"
);
}
#[test]
fn the_cross_file_answer_matches_references() {
let (_tree, mut session, core) = design("hev_refs");
let add1 = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
let mut from_calls: Vec<(String, u32, u32)> = incoming(&mut session, &add1)
.iter()
.flat_map(|call| {
let file = shape(&call.from).1;
call.from_ranges.iter().map(move |r| (file.clone(), r.start.line, r.start.character))
})
.collect();
let references = session.result(
References::METHOD,
serde_json::json!({
"textDocument": { "uri": core },
"position": pos(CORE, "add1(a)", 0, 0),
"context": { "includeDeclaration": false },
}),
);
let mut from_refs: Vec<(String, u32, u32)> = references
.as_array()
.expect("locations")
.iter()
.map(|loc| {
let file =
loc["uri"].as_str().unwrap_or("").rsplit('/').next().unwrap_or("").to_string();
let start = &loc["range"]["start"];
(
file,
start["line"].as_u64().unwrap_or(0) as u32,
start["character"].as_u64().unwrap_or(0) as u32,
)
})
.filter(|(file, line, _)| !(file == "util_pkg.sv" && *line == 3))
.collect();
from_calls.sort();
from_refs.sort();
assert_eq!(from_calls, from_refs, "every reference but the end label is a call");
}
#[test]
fn a_recursive_function_is_its_own_caller_and_callee() {
let (tree, mut session, _) = design("hev_fact");
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
let fact = one(&mut session, &pkg, pos(PKG, "fact(int", 0, 0));
assert_eq!(callers(&incoming(&mut session, &fact)), [(s("fact"), s("util_pkg.sv"), vec![7])]);
assert_eq!(callees(&outgoing(&mut session, &fact)), [(s("fact"), s("util_pkg.sv"), vec![7])]);
}
#[test]
fn class_methods_called_through_this_a_handle_and_super() {
let (tree, mut session, _) = design("hev_class");
let cls = session.open(&tree.path.join("cls.sv"), CLS);
let bump = one(&mut session, &cls, pos(CLS, "bump();\n n++", 0, 0));
assert_eq!(bump.kind, lsp_types::SymbolKind::METHOD);
assert_eq!(bump.detail.as_deref(), Some("counter"));
assert_eq!(
callers(&incoming(&mut session, &bump)),
[
(s("reset"), s("cls.sv"), vec![24]),
(s("bump_twice"), s("cls.sv"), vec![7, 8]),
(s("run"), s("cls.sv"), vec![13]),
(s("bump_more"), s("cls.sv"), vec![19]),
],
"a bare call and `this.`; a handle; the out-of-body definition's body, \
credited to its prototype; `super.` from a subclass"
);
let twice = one(&mut session, &cls, pos(CLS, "bump_twice", 0, 0));
assert_eq!(callees(&outgoing(&mut session, &twice)), [(s("bump"), s("cls.sv"), vec![7, 8])]);
}
#[test]
fn an_out_of_body_definition_prepares_and_expands_its_prototype() {
let (tree, mut session, _) = design("hev_extern");
let cls = session.open(&tree.path.join("cls.sv"), CLS);
let inside = one(&mut session, &cls, pos(CLS, "bump();\nendfunction", 0, 0));
assert_eq!(shape(&inside).0, "bump", "on the call");
let body = one(&mut session, &cls, pos(CLS, "endfunction\n", 3, 3));
assert_eq!(shape(&body), (s("reset"), s("cls.sv"), 2), "the prototype");
assert_eq!(callees(&outgoing(&mut session, &body)), [(s("bump"), s("cls.sv"), vec![24])]);
}
#[test]
fn a_super_method_call_resolves_through_the_workspace_overlay() {
// `super.bump()` inside `fancy` is answered by the workspace overlay
// (the base class is a file-scope declaration the index holds), not by
// the file's own symbol table — both directions must read both layers.
let (tree, mut session, _) = design("hev_super");
let cls = session.open(&tree.path.join("cls.sv"), CLS);
let more = one(&mut session, &cls, pos(CLS, "bump_more", 0, 0));
assert_eq!(callees(&outgoing(&mut session, &more)), [(s("bump"), s("cls.sv"), vec![19])]);
}
#[test]
fn a_method_called_through_a_handle_from_another_file() {
let pkg = "\
package env_pkg;
class driver;
task drive();
endtask
endclass
endpackage
";
let tb = "\
module tb;
import env_pkg::*;
driver d;
initial begin
d = new;
d.drive();
end
endmodule
";
let tree = Tree::new("hev_handle");
tree.write("env_pkg.sv", pkg);
tree.write("tb.sv", tb);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("env_pkg.sv"), pkg);
session.drain();
let drive = one(&mut session, &uri, pos(pkg, "drive()", 0, 0));
assert_eq!(drive.kind, lsp_types::SymbolKind::METHOD);
assert_eq!(drive.detail.as_deref(), Some("driver"));
assert_eq!(callers(&incoming(&mut session, &drive)), [(s("tb"), s("tb.sv"), vec![5])]);
let tb_uri = session.open(&tree.path.join("tb.sv"), tb);
let from_call = one(&mut session, &tb_uri, pos(tb, "drive()", 0, 1));
assert_eq!(from_call, drive, "the call through the handle prepares the method");
}
#[test]
fn a_unit_scope_function_answers_in_its_own_file_only() {
// A `$unit` function works like any other in the file that declares it.
// A call from *another* file is a documented limit: the semantic layer
// resolves an unqualified value-position name through imports only, so
// `ufn(1)` in `user.sv` names nothing and the cursor there falls back to
// the enclosing module (README, Handshakes).
let unit = "\
function automatic int ufn(int a);
return a;
endfunction
module local_user;
int j = ufn(2);
endmodule
";
let user = "module user;\n int k = ufn(1);\nendmodule\n";
let tree = Tree::new("hev_unit");
tree.write("unit.sv", unit);
tree.write("user.sv", user);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("unit.sv"), unit);
session.drain();
let ufn = one(&mut session, &uri, pos(unit, "ufn", 0, 0));
assert_eq!(shape(&ufn), (s("ufn"), s("unit.sv"), 0));
assert_eq!(ufn.detail, None, "declared at `$unit`, in no container");
assert_eq!(one(&mut session, &uri, pos(unit, "ufn(2)", 0, 0)), ufn);
assert_eq!(
callers(&incoming(&mut session, &ufn)),
[(s("local_user"), s("unit.sv"), vec![4])],
"the call in `user.sv` is not resolved, so it is not listed"
);
let user_uri = session.open(&tree.path.join("user.sv"), user);
let there = one(&mut session, &user_uri, pos(user, "ufn", 0, 0));
assert_eq!(shape(&there).0, "user", "the limit: the enclosing module, not `ufn`");
}
#[test]
fn an_edit_since_the_item_was_built_is_followed() {
// The item's recorded offset no longer matches once a line is added
// above the function; the selection range is stale too, so the item is
// re-found by name — `twice` is the only one, in its container `core`.
let (tree, mut session, core) = design("hev_stale");
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
let edited = format!("// a new first line\n{CORE}");
session.open(&tree.path.join("core.sv"), &edited);
let calls = incoming(&mut session, &twice);
assert_eq!(
callers(&calls),
[(s("core"), s("core.sv"), vec![15]), (s("kick"), s("core.sv"), vec![10])]
);
}
/// QA finding 3: two `log2`s in one file. After an edit moves both, the old
/// item for `mb`'s answers `mb`'s callers (its `detail` breaks the tie); once
/// `mb`'s is renamed away it answers nothing — never `ma`'s.
#[test]
fn a_stale_item_never_answers_for_a_same_named_function_elsewhere() {
let text = "\
module ma;
function int log2(int v); return v; endfunction
int a = log2(1);
endmodule
module mb;
function int log2(int v); return v; endfunction
int b = log2(2);
int c = log2(3);
endmodule
";
let tree = Tree::new("hev_ma_mb");
tree.write("two.sv", text);
let mut session = Session::wide(vec![tree.path.clone()], false);
let path = tree.path.join("two.sv");
let uri = session.open(&path, text);
session.drain();
let in_mb = one(&mut session, &uri, pos(text, "log2(int", 1, 0));
assert_eq!(in_mb.detail.as_deref(), Some("mb"));
let moved = format!("// one\n// two\n// three\n{text}");
session.open(&path, &moved);
assert_eq!(
callers(&incoming(&mut session, &in_mb)),
[(s("mb"), s("two.sv"), vec![9, 10])],
"the tie broken by the container"
);
let renamed = moved.replace(
"log2(int v); return v; endfunction\n int b",
"lg(int v); return v; endfunction\n int b",
);
session.open(&path, &renamed);
assert!(incoming(&mut session, &in_mb).is_empty(), "never `ma`'s `log2`");
assert!(outgoing(&mut session, &in_mb).is_empty());
}
#[test]
fn the_classic_clog2_is_not_its_own_caller() {
// QA finding 1: `clog2 = clog2 + 1;` reads the result variable.
let text = "\
module lg (output integer o);
function integer clog2(input integer v);
begin
clog2 = 0;
while (v > 1) begin
clog2 = clog2 + 1;
v = v >> 1;
end
end
endfunction
initial o = clog2(16);
endmodule
";
let tree = Tree::new("hev_clog2");
tree.write("lg.sv", text);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("lg.sv"), text);
session.drain();
let clog2 = one(&mut session, &uri, pos(text, "clog2(input", 0, 0));
assert_eq!(callers(&incoming(&mut session, &clog2)), [(s("lg"), s("lg.sv"), vec![10])]);
assert!(outgoing(&mut session, &clog2).is_empty(), "no false recursion");
}
#[test]
fn an_untitled_buffer_answers_from_itself() {
let text = "module m;\n function int f(); return 1; endfunction\n int x = f();\nendmodule\n";
let tree = Tree::new("hev_untitled");
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
session.notify(
DidOpenTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "languageId": "systemverilog", "version": 1, "text": text }
}),
);
session.drain();
let f = one(&mut session, &uri, pos(text, "f()", 1, 0));
assert_eq!(f.uri, uri);
assert_eq!(callers(&incoming(&mut session, &f)), [(s("m"), s("untitled:Untitled-1"), vec![2])]);
}
#[test]
fn two_functions_of_one_name_are_told_apart_by_data() {
let text = "\
module a;
function int f(); return 1; endfunction
initial $display(f());
endmodule
module b;
function int f(); return 2; endfunction
int x = f();
int y = f();
endmodule
";
let tree = Tree::new("hev_same_name");
tree.write("two.sv", text);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("two.sv"), text);
session.drain();
let in_b = one(&mut session, &uri, pos(text, "f()", 2, 0));
assert_eq!(shape(&in_b), (s("f"), s("two.sv"), 6), "the declaration in `b`");
assert_eq!(callers(&incoming(&mut session, &in_b)), [(s("b"), s("two.sv"), vec![7, 8])]);
let in_a = one(&mut session, &uri, pos(text, "f()", 0, 0));
assert_eq!(callers(&incoming(&mut session, &in_a)), [(s("a"), s("two.sv"), vec![2])]);
}
#[test]
fn an_item_whose_data_is_not_ours_is_treated_as_a_module_item() {
let (_tree, mut session, core) = design("hev_foreign");
let mut item = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
item.data = Some(serde_json::json!({ "kind": "rocket" }));
assert!(incoming(&mut session, &item).is_empty(), "no module is called `twice`");
assert!(outgoing(&mut session, &item).is_empty());
}
// ----------------------------------------------------------------------
// type hierarchy inside a class body
// ----------------------------------------------------------------------
fn prepare_type(session: &mut Session, uri: &Uri, position: Value) -> Vec<String> {
let result = session.result(
TypeHierarchyPrepare::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "position": position }),
);
match result.as_array() {
Some(items) => {
items.iter().map(|i| i["name"].as_str().unwrap_or("?").to_string()).collect()
}
None => Vec::new(),
}
}
#[test]
fn inside_a_class_body_prepares_the_class_and_super_prepares_its_base() {
let (tree, mut session, core) = design("hev_type");
let cls = session.open(&tree.path.join("cls.sv"), CLS);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "int n", 0, 4)),
["counter"],
"a property"
);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "n++", 0, 0)),
["counter"],
"a method body"
);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "this.bump", 0, 1)),
["counter"],
"`this`"
);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "super.bump", 0, 2)),
["counter"],
"`super`"
);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "super.bump", 0, 7)),
["fancy"],
"the method name after `super.` is inside `fancy`"
);
assert!(prepare_type(&mut session, &core, pos(CORE, "int r", 0, 4)).is_empty(), "a module");
}
@@ -0,0 +1,754 @@
//! The localized reindex held to a whole rebuild through the real server
//! (`docs/features/localized-reindex/README.md`).
//!
//! Every step goes through the notifications an editor sends — a change, a
//! save and the watcher's echo of it for an open buffer; a watcher event alone
//! for a file rewritten, created or deleted on disk — and after every step the
//! server's state is compared with what a whole rebuild over the same disk and
//! the same buffers gives: the index (postings and readers table included),
//! the completion tables, the include graph, every open buffer's cross-file
//! answers, and **the diagnostics last published for every open buffer**. The
//! last is the one the narrowing could get wrong without any table showing it:
//! a buffer the server decided not to republish must still be showing what a
//! fresh analysis would say.
use std::collections::BTreeMap;
use super::*;
/// A session over a scratch tree, with what it last published per buffer.
struct Mirror {
tree: Tree,
session: Session,
open: BTreeMap<PathBuf, (Uri, i32)>,
shown: BTreeMap<String, Value>,
/// Whole rescans seen, so a sweep can say how much of it the narrowed
/// path carried.
rescans: usize,
}
impl Mirror {
fn new(name: &str, files: &[(&str, &str)], open: &[&str]) -> Mirror {
let tree = Tree::new(name);
for (rel, text) in files {
tree.write(rel, text);
}
Mirror::over(tree, open)
}
fn over(tree: Tree, open: &[&str]) -> Mirror {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
Mirror::with(tree, open, wide)
}
fn with(tree: Tree, open: &[&str], settings: ClientSettings) -> Mirror {
// A client that shows a bar, so a whole rescan is visible as one.
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let session = Session::started(vec![tree.path.clone()], abilities, settings);
let mut mirror =
Mirror { tree, session, open: BTreeMap::new(), shown: BTreeMap::new(), rescans: 0 };
for rel in open {
let path = mirror.tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("an open buffer's file is on disk");
let uri = mirror.session.open(&path, &text);
mirror.open.insert(path, (uri, 1));
}
mirror.absorb();
mirror
}
/// Remember the newest diagnostics the server pushed for each buffer, and
/// count the whole rescans (a progress bar begun) among the steps.
fn absorb(&mut self) {
for message in self.session.drain() {
let Message::Notification(n) = message else { continue };
if n.method == PublishDiagnostics::METHOD {
let published: PublishDiagnosticsParams =
serde_json::from_value(n.params).expect("publish params");
let shown = serde_json::to_value(&published.diagnostics).expect("diagnostics");
self.shown.insert(published.uri.as_str().to_string(), shown);
} else if n.method == Progress::METHOD && n.params.to_string().contains("\"begin\"") {
self.rescans += 1;
}
}
}
/// Write `rel` as an editor does: through its buffer when it is open (the
/// change, the save, the disk, the watcher's echo), else on disk alone
/// with the watcher's event.
fn write(&mut self, rel: &str, text: &str) {
let path = self.tree.path.join(rel);
let created = !path.exists();
if let Some((uri, version)) = self.open.get_mut(&path) {
*version += 1;
let change = serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [{ "text": text }],
});
let save = serde_json::json!({ "textDocument": { "uri": uri } });
self.session.notify(DidChangeTextDocument::METHOD, change);
self.tree.write(rel, text);
self.session.notify(DidSaveTextDocument::METHOD, save);
} else {
self.tree.write(rel, text);
}
let kind = if created { FileChangeType::CREATED } else { FileChangeType::CHANGED };
self.event(&path, kind);
}
/// Delete a closed file on disk, as a checkout does.
fn delete(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
assert!(!self.open.contains_key(&path), "the sweep deletes closed files only");
std::fs::remove_file(&path).expect("delete");
self.event(&path, FileChangeType::DELETED);
}
/// Save an open buffer that has not changed, and the watcher's echo — a
/// save the index records nothing about.
fn save_only(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
let (uri, _) = self.open.get(&path).cloned().expect("an open buffer");
let save = serde_json::json!({ "textDocument": { "uri": uri } });
self.session.notify(DidSaveTextDocument::METHOD, save);
self.event(&path, FileChangeType::CHANGED);
}
/// Rewrite an open buffer's file on disk behind the editor's back: the
/// editor reloads the clean buffer (a change carrying the disk's text),
/// and the watcher reports the file. No save.
fn disk_only(&mut self, rel: &str, text: &str) {
let path = self.tree.path.join(rel);
self.tree.write(rel, text);
if let Some((uri, version)) = self.open.get_mut(&path) {
*version += 1;
let change = serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [{ "text": text }],
});
self.session.notify(DidChangeTextDocument::METHOD, change);
}
self.event(&path, FileChangeType::CHANGED);
}
/// Open a file that is on disk, after the startup scan.
fn open_file(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("on disk");
let uri = self.session.open(&path, &text);
self.open.insert(path, (uri, 1));
}
fn event(&mut self, path: &Path, typ: FileChangeType) {
let changes = vec![FileEvent { uri: path_to_uri(path).expect("uri"), typ }];
self.session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
}
/// The whole claim: what the server holds and last showed is what a whole
/// rebuild over the same disk and buffers gives. The rebuild is done in
/// place, so a run that passes goes on from the state it already had.
fn holds(&mut self, step: &str) {
self.absorb();
let workspace = &mut self.session.server.workspace;
let incremental = workspace.derived_fingerprint();
workspace.rebuild_index();
let rebuilt = workspace.derived_fingerprint();
if incremental != rebuilt {
let first = incremental.lines().zip(rebuilt.lines()).find(|(a, b)| a != b);
panic!("{step}: the incremental state is not a rebuild's; first difference {first:?}");
}
for (uri, _) in self.open.values() {
let fresh = self.session.server.diagnostics_of(uri);
let fresh = serde_json::to_value(&fresh).expect("diagnostics");
let shown = self.shown.get(uri.as_str()).cloned().unwrap_or(Value::Null);
assert_eq!(shown, fresh, "{step}: {} shows stale diagnostics", uri.as_str());
}
}
/// Every step, each followed by the check.
fn steps(&mut self, steps: &[(&str, &str)]) {
self.holds("before any step");
for (at, (rel, text)) in steps.iter().enumerate() {
self.write(rel, text);
self.holds(&format!("step {at}, `{rel}`"));
}
}
}
const LEAF: &str =
"module leaf (input logic clk, output logic q);\n logic s;\n assign q = s;\nendmodule\n";
const TOP: &str = "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n";
const TB: &str = "module tb;\n top dut ();\n initial $display(dut.u_leaf.s);\nendmodule\n";
const PKG: &str =
"package cfg_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n";
const USER: &str = "module user import cfg_pkg::*; (input word_t a, output word_t b);\n assign b = a + W;\nendmodule\n";
const DEFS: &str = "`define WIDTH 8\n`define CLOG(x) $clog2(x)\n";
const INCLUDER: &str =
"`include \"defs.svh\"\nmodule includer;\n logic [`WIDTH-1:0] v;\nendmodule\n";
fn design() -> Vec<(&'static str, &'static str)> {
vec![
("rtl/leaf.sv", LEAF),
("rtl/top.sv", TOP),
("dv/tb.sv", TB),
("rtl/cfg_pkg.sv", PKG),
("rtl/user.sv", USER),
("rtl/defs.svh", DEFS),
("rtl/includer.sv", INCLUDER),
]
}
#[test]
fn every_kind_of_edit_to_an_open_module_leaves_the_rebuilt_state_and_every_squiggle() {
let mut mirror =
Mirror::new("lr_module", &design(), &["rtl/leaf.sv", "rtl/top.sv", "dv/tb.sv"]);
let open_leaf = |text: &str| ("rtl/leaf.sv", text.to_string());
let steps = [
// Nothing the index records: a comment after the last token.
open_leaf(&format!("{LEAF}// trailing\n")),
// A body edit, a local signal, a comment above everything.
open_leaf(&LEAF.replace("assign q = s;", "assign q = ~s;")),
open_leaf(&LEAF.replace(" logic s;\n", " logic s;\n logic t;\n")),
open_leaf(&format!("// above\n{LEAF}")),
// The port list: renamed, removed, added — `top` connects by name, so
// its unknown-port squiggles must follow without `top` being saved.
open_leaf(&LEAF.replace("input logic clk", "input logic clock")),
open_leaf(&LEAF.replace("input logic clk, ", "")),
open_leaf(&LEAF.replace("output logic q", "output logic q, input logic en")),
// The signal the testbench names hierarchically, gone and back.
open_leaf(&LEAF.replace("logic s;\n assign q = s;", "logic r;\n assign q = r;")),
// The module renamed away, so `top`'s instantiation resolves nowhere.
open_leaf(&LEAF.replace("module leaf", "module leaf2")),
open_leaf(LEAF),
];
let steps: Vec<(&str, &str)> = steps.iter().map(|(rel, text)| (*rel, text.as_str())).collect();
mirror.steps(&steps);
}
#[test]
fn edits_to_a_closed_package_a_define_header_and_an_include_line_all_hold() {
let mut mirror = Mirror::new("lr_package", &design(), &["rtl/user.sv", "rtl/includer.sv"]);
let user_text = USER.replace("+ W", "+ W + DEPTH");
let pkg_depth =
PKG.replace("localparam int W = 8;", "localparam int W = 8;\n localparam int DEPTH = 4;");
let defs_more = format!("{DEFS}`define DEPTH 4\n");
let includer_none = INCLUDER.replace("`include \"defs.svh\"\n", "");
let pkg_renamed = PKG.replace("package cfg_pkg", "package cfg2_pkg");
let defs_wider = DEFS.replace("8", "16");
let defs_params = DEFS.replace("CLOG(x)", "CLOG(x, y)");
let includer_nowhere = INCLUDER.replace("defs.svh", "nowhere.svh");
let steps: Vec<(&str, &str)> = vec![
// A package member the open user does not name yet, then does.
("rtl/cfg_pkg.sv", &pkg_depth),
("rtl/user.sv", &user_text),
// The package member it names, gone.
("rtl/cfg_pkg.sv", PKG),
// The package renamed.
("rtl/cfg_pkg.sv", &pkg_renamed),
("rtl/cfg_pkg.sv", PKG),
// A define header: a value, a new macro, a parameter list.
("rtl/defs.svh", &defs_wider),
("rtl/defs.svh", &defs_more),
("rtl/defs.svh", &defs_params),
// An include line removed and put back, and one that resolves nowhere.
("rtl/includer.sv", &includer_none),
("rtl/includer.sv", INCLUDER),
("rtl/includer.sv", &includer_nowhere),
("rtl/includer.sv", INCLUDER),
];
mirror.steps(&steps);
}
#[test]
fn a_signal_another_file_mentions_keeps_its_lint_answer_as_the_mention_comes_and_goes() {
// `unused-signal` consults the workspace census: `dbg` is unused in
// `probe.sv` but named by `peek.sv`, which is closed. The open buffer is
// never saved here, so only a republish the narrowing owed can move it.
let probe = "module probe;\n logic dbg;\nendmodule\n";
let peek = "module peek;\n initial $display(probe.dbg);\nendmodule\n";
let mut mirror =
Mirror::new("lr_census", &[("probe.sv", probe), ("peek.sv", peek)], &["probe.sv"]);
mirror.steps(&[
("peek.sv", "module peek;\n initial $display(1);\nendmodule\n"),
("peek.sv", peek),
("peek.sv", &format!("{peek}// a comment that moves nothing\n")),
]);
}
#[test]
fn files_created_and_deleted_beside_open_buffers_hold() {
let mut mirror = Mirror::new("lr_files", &design(), &["rtl/top.sv", "rtl/includer.sv"]);
mirror.holds("before any step");
// A second `leaf` makes the instantiation ambiguous; deleting it heals it.
mirror.write("rtl/zz_leaf.sv", LEAF);
mirror.holds("a duplicate module created");
mirror.delete("rtl/zz_leaf.sv");
mirror.holds("and deleted");
mirror.delete("rtl/defs.svh");
mirror.holds("an included header deleted");
mirror.write("rtl/defs.svh", DEFS);
mirror.holds("and recreated");
}
#[test]
fn a_watcher_event_for_a_file_the_scope_cannot_take_costs_no_rescan() {
// A generated file under a gitignored directory, and a file outside the
// workspace root: neither can change the index, so neither may cost the
// progress bar — and the state is still a rebuild's.
let mut mirror = Mirror::new("lr_outside", &design(), &["rtl/top.sv"]);
mirror.tree.write(".gitignore", "build/\n");
mirror.holds("before any step");
let _ = mirror.session.drain();
mirror.write("build/gen.sv", "module gen;\nendmodule\n");
assert!(mirror.session.progress().is_empty(), "no bar for a gitignored file");
mirror.holds("a generated file under build/");
let outside = Tree::new("lr_outside_elsewhere");
outside.write("far.sv", "module far;\nendmodule\n");
let _ = mirror.session.drain();
mirror.event(&outside.path.join("far.sv"), FileChangeType::CHANGED);
assert!(mirror.session.progress().is_empty(), "no bar for a file outside every root");
mirror.holds("a file outside the root");
// A file the scope does take, appearing, is still the whole rebuild —
// which is also what proves the two assertions above can fail.
mirror.rescans = 0;
mirror.write("rtl/new.sv", "module fresh;\nendmodule\n");
mirror.holds("a new file in scope");
assert_eq!(mirror.rescans, 1, "a file the scope takes appearing is a rescan");
assert!(
mirror.session.server.workspace.index().units("fresh").len() == 1,
"the new file is in the index"
);
}
#[test]
fn a_buffer_opened_from_outside_the_filelist_joins_the_index_on_its_first_save() {
// VS Code restores editors while the startup scan runs; one outside the
// filelist is open but not indexed until something rebuilds. Its first
// save used to be that rebuild, bar and all.
let mut files = design();
files.push(("rtl/waits.sv", "`include \"late.svh\"\nmodule waits;\nendmodule\n"));
files.push(("files.f", "rtl/leaf.sv\nrtl/top.sv\nrtl/cfg_pkg.sv\nrtl/waits.sv\n"));
let tree = Tree::new("lr_filelist");
for (rel, text) in &files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv", "dv/tb.sv"], listed);
mirror.rescans = 0;
mirror.write("dv/tb.sv", &TB.replace("$display", "$write"));
mirror.holds("the first save of the unlisted buffer");
assert_eq!(mirror.rescans, 0, "the buffer was on disk before the scan: no rescan");
assert!(mirror.session.server.workspace.index().units("tb").len() == 1, "and it is indexed");
// A file born after the scan may be what some `include` was waiting
// for — `waits.sv`'s is: its lines are re-resolved, still no rebuild.
mirror.write("rtl/late.svh", "`define LATE 1\n");
let path = mirror.tree.path.join("rtl/late.svh");
let uri = mirror.session.open(&path, "`define LATE 1\n");
mirror.open.insert(path, (uri, 1));
mirror.rescans = 0;
mirror.write("rtl/late.svh", "`define LATE 2\n");
mirror.holds("the first save of a buffer younger than the scan");
assert_eq!(mirror.rescans, 0, "the include waiting for it is re-resolved in place");
let graph = mirror.session.server.workspace.includes();
assert_eq!(graph.reachable(vec![mirror.tree.path.join("rtl/waits.sv")]).len(), 2, "and found");
}
/// QA F1: a header the scope cannot take, appearing and vanishing, moves an
/// in-scope includer's edge — an include is resolved against the disk.
#[test]
fn a_header_outside_the_scope_created_and_deleted_moves_the_includers_edges() {
let files = [
(".gitignore", "gen/\n"),
("rtl/a.sv", "`include \"../gen/h.svh\"\nmodule a;\nendmodule\n"),
("rtl/a_inc.svh", "`include \"../gen/h.svh\"\n`define AW 2\n"),
("rtl/b.sv", "`include \"a_inc.svh\"\nmodule b;\nendmodule\n"),
];
let mut mirror = Mirror::new("lr_f1_ignored", &files, &["rtl/b.sv"]);
mirror.steps(&[("gen/h.svh", "`define GEN_W 4\n")]);
mirror.rescans = 0;
mirror.delete("gen/h.svh");
mirror.holds("the ignored header deleted");
mirror.write("gen/h.svh", "`define GEN_W 5\n");
mirror.holds("and created again");
assert_eq!(mirror.rescans, 0, "the include graph alone, never a rescan");
}
/// QA R2-1: one event naming a burst of files is sorted path by path only
/// while that is cheaper than a rescan (`BURST_DIVISOR`); past it the event
/// takes the whole rescan. The state is a rebuild's on both sides.
#[test]
fn a_burst_of_created_files_is_sorted_below_the_threshold_and_rescanned_above() {
let mut files = design();
files.push((".gitignore", "gen/\n"));
files.push(("rtl/waits.sv", "`include \"../gen/h0.svh\"\nmodule waits;\nendmodule\n"));
let mut mirror = Mirror::new("lr_burst", &files, &["rtl/top.sv"]);
mirror.holds("before any step");
let held = mirror.session.server.workspace.index().files().len();
let burst = |mirror: &mut Mirror, count: usize, tag: &str| {
let changes: Vec<FileEvent> = (0..count)
.map(|k| {
let rel = format!("gen/{tag}{k}.svh");
mirror.tree.write(&rel, &format!("`define {}{k} 1\n", tag.to_uppercase()));
let path = mirror.tree.path.join(rel);
FileEvent { uri: path_to_uri(&path).expect("uri"), typ: FileChangeType::CREATED }
})
.collect();
let params = DidChangeWatchedFilesParams { changes };
mirror.session.notify(DidChangeWatchedFiles::METHOD, params);
};
mirror.rescans = 0;
burst(&mut mirror, held / 2, "h");
mirror.holds("a burst at the threshold, `h0.svh` among it");
assert_eq!(mirror.rescans, 0, "sorted path by path: {held} held, {} named", held / 2);
burst(&mut mirror, held / 2 + 1, "k");
mirror.write("gen/h0.svh", "`define H0 2\n");
mirror.holds("a burst past the threshold");
assert_eq!(mirror.rescans, 1, "one path more is the whole rescan");
}
/// QA F1, filelist mode: an unlisted header under an `+incdir+`.
#[test]
fn an_unlisted_header_under_an_incdir_created_moves_the_includers_edge() {
let files = [
("files.f", "+incdir+inc\nrtl/a.sv\nrtl/top.sv\n"),
("rtl/a.sv", "`include \"h2.svh\"\nmodule a;\nendmodule\n"),
("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"),
];
let tree = Tree::new("lr_f1_incdir");
for (rel, text) in files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed);
mirror.holds("before any step");
mirror.write("inc/h2.svh", "`define H2 1\n");
mirror.holds("the unlisted header created");
mirror.delete("inc/h2.svh");
mirror.holds("and deleted");
}
/// QA F2: a `[lint]` edit in `lucisv.toml`, which no notification reports,
/// takes effect at the next save — even one the index records nothing about.
#[test]
fn a_lint_configuration_edit_takes_effect_at_a_save_that_moves_nothing() {
let lint_me = "module lint_me;\n\twire unused_w; \n reg r;\nendmodule\n";
let mut mirror = Mirror::new("lr_f2_toml", &[("rtl/lint_me.sv", lint_me)], &["rtl/lint_me.sv"]);
mirror.holds("before any step");
let uri = mirror.open.values().next().map(|(uri, _)| uri.as_str().to_string()).expect("open");
assert_ne!(mirror.shown.get(&uri), Some(&Value::Array(Vec::new())), "premise: findings");
mirror.tree.write(
"lucisv.toml",
"[lint]\nignore = [\"no-tabs\", \"no-trailing-whitespace\", \"unused-signal\"]\n",
);
mirror.save_only("rtl/lint_me.sv");
mirror.holds("the save after the lint configuration changed");
mirror.tree.write("lucisv.toml", "[lint]\n");
mirror.save_only("rtl/lint_me.sv");
mirror.holds("and after it changed back");
}
/// QA F3: a file moved in from elsewhere after the scan keeps its old times;
/// opened and saved, it joins the index and its waiting includer finds it.
/// No watcher event is sent for the move — a client that does not watch, or
/// an event coalesced away — so the save alone must re-resolve the includer
/// (the event's own re-resolution is F1's test).
#[test]
fn a_file_moved_in_after_the_scan_joins_and_is_found_by_its_includer() {
let files = [
("files.f", "rtl/a.sv\nrtl/top.sv\n"),
("rtl/a.sv", "`include \"late.svh\"\nmodule a;\nendmodule\n"),
("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"),
];
let elsewhere = Tree::new("lr_f3_elsewhere");
elsewhere.write("late.svh", "`define LATE 7\n");
let tree = Tree::new("lr_f3_moved");
for (rel, text) in files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed);
mirror.holds("before any step");
let moved = mirror.tree.path.join("rtl/late.svh");
std::fs::rename(elsewhere.path.join("late.svh"), &moved).expect("move in");
mirror.open_file("rtl/late.svh");
let (uri, _) = mirror.open[&moved].clone();
let save = serde_json::json!({ "textDocument": { "uri": uri } });
mirror.session.notify(DidSaveTextDocument::METHOD, save);
mirror.holds("opened and saved, with no watcher echo");
}
/// QA F4: an excluded buffer, open and changed on disk, is taken in, as a
/// fresh server takes every open buffer in.
#[test]
fn an_excluded_open_buffer_changed_on_disk_is_taken_in() {
let files = [
("lucisv.toml", "exclude = [\"rtl/b.sv\"]\n"),
("rtl/b.sv", "module b;\nendmodule\n"),
("rtl/top.sv", "module top;\n b u_b ();\nendmodule\n"),
];
let mut mirror = Mirror::new("lr_f4_excluded", &files, &["rtl/top.sv"]);
mirror.holds("before any step");
mirror.open_file("rtl/b.sv");
mirror.disk_only("rtl/b.sv", "module b;\n wire w2;\nendmodule\n");
mirror.holds("the excluded buffer changed on disk");
assert_eq!(mirror.session.server.workspace.index().units("b").len(), 1, "taken in");
}
#[cfg(unix)]
#[test]
fn a_held_file_reported_by_its_real_path_takes_the_one_file_update() {
// The workspace is opened through a symlink; the watcher reports the real
// path. Before this round that was a "file the index does not hold" and a
// whole rescan per save.
let real = Tree::new("lr_real");
for (rel, text) in design() {
real.write(rel, text);
}
let link = Tree::new("lr_link");
std::fs::remove_dir_all(&link.path).expect("make room for the link");
std::os::unix::fs::symlink(&real.path, &link.path).expect("symlink");
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let mut session = Session::wide_with(vec![link.path.clone()], abilities);
let _ = session.drain();
real.write("rtl/leaf.sv", &LEAF.replace("input logic clk", "input logic clock"));
session.watched(&[real.path.join("rtl/leaf.sv")]);
assert!(session.progress().is_empty(), "the one-file path, not a rescan");
let index = session.server.workspace.index();
assert_eq!(index.member("leaf", "clock").len(), 1, "and the update landed");
assert!(
index.files().iter().all(|path| path.starts_with(&link.path)),
"under the link's spelling"
);
let _ = std::fs::remove_file(&link.path);
}
// ----------------------------------------------------------------------
// The seeded sweep
// ----------------------------------------------------------------------
/// xorshift64*: reproducible from a seed, no dependency.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
}
/// One random edit: a line inserted, deleted, duplicated or swapped with its
/// neighbour, or one identifier renamed to another the file already uses —
/// edits that move spans, names and whole declarations.
fn mutate(text: &str, rng: &mut Rng) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let at = rng.below(lines.len() + 1);
match rng.below(6) {
0 => lines.insert(at, " // lucisv sweep".to_string()),
1 if at < lines.len() => {
lines.remove(at);
}
2 if at < lines.len() => {
let line = lines[at].clone();
lines.insert(at, line);
}
3 if at + 1 < lines.len() => lines.swap(at, at + 1),
4 => lines.insert(at, " logic lucisv_sweep_q;".to_string()),
_ => {
let words = vlog_semantic::words::harvest_text(text);
if words.len() >= 2 {
let from = words[rng.below(words.len())].clone();
let to = words[rng.below(words.len())].clone();
if let Some(line) = lines.iter_mut().find(|line| line.contains(from.as_str())) {
*line = line.replacen(from.as_str(), &to, 1);
}
}
}
}
let mut out = lines.join("\n");
out.push('\n');
out
}
/// `steps` seeded mutations over every source file under `tree`, with `open`
/// buffers open, each step checked; now and then a closed file is deleted or
/// a new one created.
fn sweep(tree: Tree, open: usize, seed: u64, steps: usize) {
// `opened` below is also what the lint-configuration step saves.
let mut files: Vec<String> = Vec::new();
collect(&tree.path, &tree.path, &mut files);
files.sort();
assert!(!files.is_empty(), "premise: a tree with sources in it");
let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let opened: Vec<String> = (0..open).map(|_| files[rng.below(files.len())].clone()).collect();
let opened_refs: Vec<&str> = opened.iter().map(String::as_str).collect();
// The setting the event kinds QA found need: a gitignored `gen/` whose
// headers an in-scope file waits for, and excluded names to open.
tree.write(".gitignore", "gen/\n");
tree.write("lucisv.toml", "exclude = [\"sweep_excluded_*\"]\n");
let waits: String = (0..4).map(|k| format!("`include \"gen/h{k}.svh\"\n")).collect();
tree.write("sweep_waits.sv", &format!("{waits}module sweep_waits;\nendmodule\n"));
let elsewhere = Tree::new(&format!("lr_sweep_elsewhere_{seed}"));
let mut mirror = Mirror::over(tree, &opened_refs);
mirror.holds(&format!("seed {seed}: before any step"));
mirror.rescans = 0;
for step in 0..steps {
let rel = files[rng.below(files.len())].clone();
let path = mirror.tree.path.join(&rel);
let label = format!("seed {seed}, step {step}, `{rel}`");
match rng.below(24) {
0 if !mirror.open.contains_key(&path) && path.exists() => mirror.delete(&rel),
1 => mirror.write(&format!("sweep_new_{step}.sv"), "module sweep_new;\nendmodule\n"),
// A header outside the scope, waited for, toggled.
2 => {
let header = format!("gen/h{}.svh", rng.below(4));
match mirror.tree.path.join(&header).exists() {
true => mirror.delete(&header),
false => mirror.write(&header, &format!("`define SWEEP_{step} 1\n")),
}
}
// The lint configuration edited, then a save that moves nothing.
3 => {
let rules = ["no-tabs", "unused-signal", "line-length", "no-trailing-whitespace"];
let ignored: Vec<String> = rules
.iter()
.filter(|_| rng.below(2) == 0)
.map(|r| format!("\"{r}\""))
.collect();
let config = format!(
"exclude = [\"sweep_excluded_*\"]\n[lint]\nignore = [{}]\n",
ignored.join(", ")
);
mirror.tree.write("lucisv.toml", &config);
if let Some(open) = opened.get(rng.below(opened.len().max(1))) {
mirror.save_only(open);
}
}
// A file moved in from elsewhere, old times and all, then opened
// and saved.
4 => {
let name = format!("sweep_moved_{step}.svh");
elsewhere.write(&name, &format!("`define SWEEP_MOVED_{step} 1\n"));
let to = mirror.tree.path.join("gen").join(&name);
std::fs::create_dir_all(mirror.tree.path.join("gen")).expect("gen/");
std::fs::rename(elsewhere.path.join(&name), &to).expect("move in");
mirror.event(&to, FileChangeType::CREATED);
let rel = format!("gen/{name}");
mirror.open_file(&rel);
mirror.save_only(&rel);
}
// An excluded file, opened, then changed on disk.
5 => {
let rel = format!("sweep_excluded_{step}.sv");
mirror.write(&rel, &format!("module sweep_excluded_{step};\nendmodule\n"));
mirror.open_file(&rel);
let text = format!("module sweep_excluded_{step};\n wire w;\nendmodule\n");
mirror.disk_only(&rel, &text);
}
_ => {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let text = match mirror.open.contains_key(&path) {
true => mirror.session.server.workspace.text_of(&path).unwrap_or(text),
false => text,
};
mirror.write(&rel, &mutate(&text, &mut rng));
}
}
mirror.holds(&label);
}
eprintln!(
"seed {seed}: {steps} steps over {} files, {} of them whole rescans",
files.len(),
mirror.rescans
);
}
fn collect(root: &Path, dir: &Path, out: &mut Vec<String>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect(root, &path, out);
} else if crate::watch::watched(&path, None) {
if let Ok(rel) = path.strip_prefix(root) {
out.push(rel.to_string_lossy().into_owned());
}
}
}
}
/// Copy every source file under `from` into `tree` under `prefix`, saying
/// how many — none when `from` is not on this machine.
fn copy_into(tree: &Tree, from: &Path, prefix: &str) -> usize {
let mut files: Vec<String> = Vec::new();
collect(from, from, &mut files);
for rel in &files {
let Ok(text) = std::fs::read_to_string(from.join(rel)) else { continue };
tree.write(&format!("{prefix}{rel}"), &text);
}
files.len()
}
fn home(rel: &str) -> PathBuf {
std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default().join(rel)
}
#[test]
fn a_seeded_sweep_over_the_hand_written_design_holds() {
for seed in 1..=3 {
let tree = Tree::new(&format!("lr_sweep_{seed}"));
for (rel, text) in design() {
tree.write(rel, text);
}
sweep(tree, 3, seed, 25);
}
}
/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_the_corpus -- --ignored --nocapture`
#[test]
#[ignore = "a sweep over ~/.cache/lucisv-corpus, minutes in a debug build"]
fn a_seeded_sweep_over_the_corpus_holds() {
let from = std::env::var_os("LUCISV_CORPUS")
.map(PathBuf::from)
.unwrap_or_else(|| home(".cache/lucisv-corpus"));
for seed in [11, 12, 13] {
let tree = Tree::new(&format!("lr_corpus_{seed}"));
if copy_into(&tree, &from, "") == 0 {
eprintln!("{} not present — skipping", from.display());
return;
}
sweep(tree, 5, seed, 60);
}
}
/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_an_opentitan -- --ignored --nocapture`
#[test]
#[ignore = "a sweep over a sample of OpenTitan, minutes in a debug build"]
fn a_seeded_sweep_over_an_opentitan_sample_holds() {
let hw = std::env::var_os("LUCISV_OPENTITAN")
.map(PathBuf::from)
.unwrap_or_else(|| home(".cache/lucisv-opentitan-full/hw"));
for seed in [21, 22] {
let tree = Tree::new(&format!("lr_opentitan_{seed}"));
let mut copied = 0;
for sub in ["ip/uart/", "ip/gpio/", "ip/prim/rtl/", "ip/prim_generic/rtl/", "ip/tlul/rtl/"]
{
copied += copy_into(&tree, &hw.join(sub), sub);
}
if copied == 0 {
eprintln!("{} not present — skipping", hw.display());
return;
}
sweep(tree, 6, seed, 60);
}
}
+8 -2
View File
@@ -16,8 +16,7 @@ use lsp_server::{Notification, Request, Response};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _, Progress,
PublishDiagnostics, ShowMessage,
DidRenameFiles, DidSaveTextDocument, LogMessage, Progress, PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeActionResolveRequest,
@@ -52,14 +51,21 @@ mod code_action;
mod file_ops;
mod folders;
mod formatting;
mod hierarchy_everywhere;
mod hierarchy_reach;
mod index;
mod large_file;
mod lint_snapshot;
mod localized_reindex;
mod progress;
mod pull_diagnostics;
mod qa_generate_label;
mod qa_rename_implicit;
mod references_scope;
mod references_top_rooted;
mod rename_generate_label;
mod rename_implicit;
mod rename_top_rooted_scope;
mod requests;
mod scan;
mod scan_trace;
@@ -81,17 +81,36 @@ fn an_index_rebuild_moves_the_result_id_too() {
// `inter_file_dependencies: true` is a promise: a save rebuilds the
// index, and what the index says can change what a *different* buffer
// reports. A stale "unchanged" there would be a wrong squiggle.
//
// Since localized-reindex (2026-11-19) the save whose record did not move
// still moves the stamp — a lint reads `lucisv.toml` from disk, and a
// save is when an edit to it takes effect (QA F2) — and so does the save
// of an edit the index has not seen.
let tree = Tree::new("pullreindex");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
let stamp = document_pull(&mut session, &uri, None)["resultId"]
.as_str()
.expect("a result id")
.to_string();
let stamp = |session: &mut Session, previous: Option<&str>| {
document_pull(session, &uri, previous)["resultId"]
.as_str()
.expect("a result id")
.to_string()
};
let first = stamp(&mut session, None);
let save = serde_json::json!({ "textDocument": { "uri": uri } });
session.notify(DidSaveTextDocument::METHOD, save.clone());
let after = document_pull(&mut session, &uri, Some(&first));
assert_eq!(after["kind"], "full", "a save that moved no record: {after:#?}");
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let after = document_pull(&mut session, &uri, Some(&stamp));
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module m;\n\twire ;\n wire extra;\nendmodule\n" }],
}),
);
let edited = stamp(&mut session, Some(&first));
session.notify(DidSaveTextDocument::METHOD, save);
let after = document_pull(&mut session, &uri, Some(&edited));
assert_eq!(after["kind"], "full", "the index moved: {after:#?}");
}
@@ -0,0 +1,86 @@
//! QA attacks on TODO §65.1 over the wire: `references` and `rename` through
//! a block label with the other files closed, and the `member_key` spelling
//! of a block that lives inside a function.
//! `docs/features/generate-label-rename/README.md`, QA log 2026-09-30.
use super::*;
/// `(file name, line)` of every location in a `references` answer.
fn places(found: &Value) -> Vec<(String, u64)> {
let mut out: Vec<(String, u64)> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let uri = l["uri"].as_str().unwrap_or("?");
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
fn position(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
let row = text.lines().nth(line).expect("the line");
let character = row.find(name).expect("the name on that line");
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
"context": { "includeDeclaration": true },
})
}
/// A module `ff` with a block `fb` holding `t`, and — in another file — a
/// function `ff` with a named block `fb` holding its own `t`. The function's
/// `t` is a local: nothing outside the function can name it, and the module's
/// `t` is a different declaration.
const MODULE_FF: &str = "module ff;\n if (1) begin : fb\n logic t;\n end\nendmodule\n";
const USER: &str =
"module user (output logic o);\n ff u_ff ();\n assign o = u_ff.fb.t;\nendmodule\n";
const FUNC: &str = "module host;\n function automatic void ff();\n begin : fb\n logic t;\n t = 1'b0;\n end\n endfunction\nendmodule\n";
#[test]
fn a_function_local_in_a_named_block_is_never_mistaken_for_a_modules_block_member() {
let tree = Tree::new("qa_genlabel_member_key");
tree.write("ff.sv", MODULE_FF);
tree.write("user.sv", USER);
tree.write("host.sv", FUNC);
let mut session = Session::wide(vec![tree.path.clone()], false);
let host = session.open(&tree.path.join("host.sv"), FUNC);
let found = places(&session.result(References::METHOD, position(&host, FUNC, 3, "t;")));
assert_eq!(found, vec![("host.sv".to_string(), 3), ("host.sv".to_string(), 4)]);
let mut params = position(&host, FUNC, 3, "t;");
params["newName"] = serde_json::json!("t2");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
assert_eq!(changes.len(), 1, "only host.sv: {answer:#}");
}
/// Three files: the block's module, an intermediate module instantiating it,
/// and a testbench naming a member through two instances and the block. Only
/// the declaring file is open.
const LEAF: &str = "module leaf;\n for (genvar i = 0; i < 2; i++) begin : g_l\n logic s;\n end : g_l\nendmodule\n";
const MID: &str = "module mid;\n leaf u_leaf ();\nendmodule\n";
const TB: &str = "module tbq (output logic o);\n mid u_mid ();\n assign o = u_mid.u_leaf.g_l[1].s;\nendmodule\n";
#[test]
fn a_two_instance_path_through_a_block_is_renamed_with_every_other_file_closed() {
let tree = Tree::new("qa_genlabel_two_hops");
tree.write("leaf.sv", LEAF);
tree.write("mid.sv", MID);
tree.write("tbq.sv", TB);
let mut session = Session::wide(vec![tree.path.clone()], false);
let leaf = session.open(&tree.path.join("leaf.sv"), LEAF);
let found = places(&session.result(References::METHOD, position(&leaf, LEAF, 1, "g_l")));
let at = |f: &str, l| (f.to_string(), l);
assert_eq!(found, vec![at("leaf.sv", 1), at("leaf.sv", 3), at("tbq.sv", 2)]);
let mut params = position(&leaf, LEAF, 2, "s;");
params["newName"] = serde_json::json!("s_q");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let tb = path_to_uri(&tree.path.join("tbq.sv")).expect("a uri");
assert_eq!(changes.get(tb.as_str()).and_then(Value::as_array).map_or(0, Vec::len), 1);
}
@@ -0,0 +1,170 @@
//! TODO §65.2 over the wire: `references` from a testbench answers within
//! the active index scope, and within an equal file set it answers exactly
//! what the whole-set engine (`vlog_refactor::find_references`) answers.
//! `docs/features/references-fanout-pd-main/README.md`.
//!
//! The fixture is opentitan's shape in miniature: an IP block with `rtl/`
//! and `dv/tb/`, and a generated top two directories away that instantiates
//! the block with a multi-line `blk #( … ) u_blk (`.
use std::path::Path;
use super::*;
const BLK: &str = "module blk #(\n parameter int W = 1\n) (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n";
const TB: &str = "module tb;\n logic clk, rst_n;\n blk #(\n .W ( 2 )\n ) dut (\n .clk_i ( clk ),\n .rst_ni ( rst_n )\n );\nendmodule\n";
const PD_MAIN: &str = "module top_pd_main (\n input logic clk_main_i,\n input logic rst_main_ni\n);\n blk #(\n .W ( 4 )\n ) u_blk (\n // Clock and reset connections\n .clk_i ( clk_main_i ),\n .rst_ni ( rst_main_ni )\n );\nendmodule\n";
/// The three files, at their opentitan-shaped paths.
fn fixture(tag: &str) -> Tree {
let tree = Tree::new(tag);
tree.write("ip/blk/rtl/blk.sv", BLK);
tree.write("ip/blk/dv/tb/tb.sv", TB);
tree.write("top/rtl/autogen/top_pd_main.sv", PD_MAIN);
tree
}
/// `(path relative to the root, line)` of every location in an answer.
fn answered(root: &Path, found: &Value) -> Vec<(String, u64)> {
let mut out: Vec<(String, u64)> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let uri = l["uri"].as_str().unwrap_or("?");
let path =
crate::uri::uri_to_path(&Uri::from_str(uri).expect("a uri")).expect("a path");
let rel = path.strip_prefix(root).unwrap_or(&path).display().to_string();
(rel, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
/// What the whole-set engine answers over `files`, as [`answered`] spells it.
fn engine(
root: &Path,
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Vec<(String, u64)> {
let found =
vlog_refactor::find_references(files, file, offset, true).expect("the engine answers");
let mut out: Vec<(String, u64)> = found
.into_iter()
.map(|(path, range)| {
let text = &files.iter().find(|(p, _)| *p == path).expect("a read file").1;
let line = text[..range.start as usize].matches('\n').count() as u64;
let rel = path.strip_prefix(root).unwrap_or(&path).display().to_string();
(rel, line)
})
.collect();
out.sort();
out
}
/// Every file under the tree — the set the MCP's `references` hands the engine.
fn every_file(tree: &Tree) -> Vec<(PathBuf, String)> {
["ip/blk/rtl/blk.sv", "ip/blk/dv/tb/tb.sv", "top/rtl/autogen/top_pd_main.sv"]
.iter()
.map(|rel| {
let path = tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("read");
(path, text)
})
.collect()
}
/// A references request at the first `needle` on line `line` of `text`, and
/// the byte offset the engine is asked at.
fn at(uri: &Uri, text: &str, line: usize, needle: &str) -> (Value, u32) {
let row = text.lines().nth(line).expect("the line");
let character = row.find(needle).expect("the needle on that line");
let before: usize = text.lines().take(line).map(|l| l.len() + 1).sum();
let params = serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
"context": { "includeDeclaration": true },
});
(params, (before + character) as u32)
}
/// The four positions the §65.2 checklist names: the module name and one of
/// its ports, each from its declaration and from a use.
fn positions(tree: &Tree) -> [(PathBuf, &'static str, usize, &'static str); 4] {
let blk = tree.path.join("ip/blk/rtl/blk.sv");
let tb = tree.path.join("ip/blk/dv/tb/tb.sv");
[
(blk.clone(), BLK, 0, "blk"),
(tb.clone(), TB, 2, "blk"),
(blk, BLK, 3, "clk_i"),
(tb, TB, 5, "clk_i"),
]
}
#[test]
fn over_the_whole_workspace_references_equal_the_whole_set_engine() {
let tree = fixture("refscope_wide");
let mut session = Session::wide(vec![tree.path.clone()], false);
let all = every_file(&tree);
for (path, text, line, needle) in positions(&tree) {
let uri = session.open(&path, text);
let (params, offset) = at(&uri, text, line, needle);
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
let whole = engine(&tree.path, &all, &path, offset);
assert_eq!(lsp, whole, "{needle} at {}:{line}", path.display());
assert!(
lsp.iter().any(|(file, _)| file.ends_with("top_pd_main.sv")),
"the generated top is listed: {lsp:?}"
);
}
}
/// The cause, pinned: under the shipped folder scope a testbench in
/// `ip/blk/dv/tb/` raises to `ip/blk/`, the generated top is not in the
/// index, and `references` answers what the engine answers over the scope —
/// not over every file. Opening the top widens the scope, and the answer
/// becomes the whole set's.
#[test]
fn under_the_folder_scope_references_equal_the_engine_over_the_scope() {
let tree = fixture("refscope_folder");
let mut session = Session::new(vec![tree.path.clone()], false);
let top = tree.path.join("top/rtl/autogen/top_pd_main.sv");
for (path, text, line, needle) in positions(&tree) {
let uri = session.open(&path, text);
let in_index = session.server.workspace.index().files().contains(&top);
assert!(!in_index, "the top is outside the folder scope");
let (params, offset) = at(&uri, text, line, needle);
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
let scoped = engine(&tree.path, &session.server.workspace.sources(), &path, offset);
assert_eq!(lsp, scoped, "{needle} at {}:{line}", path.display());
assert!(!lsp.iter().any(|(file, _)| file.ends_with("top_pd_main.sv")), "{lsp:?}");
}
let _ = session.open(&top, PD_MAIN);
let all = every_file(&tree);
for (path, text, line, needle) in positions(&tree) {
let uri = path_to_uri(&path).expect("uri");
let (params, offset) = at(&uri, text, line, needle);
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
assert_eq!(lsp, engine(&tree.path, &all, &path, offset), "{needle}, widened");
}
}
/// `rename`'s fan-out has no gap of its own: over the whole workspace a
/// module rename from the testbench edits the generated top too.
#[test]
fn over_the_whole_workspace_a_module_rename_edits_the_generated_top() {
let tree = fixture("refscope_rename");
let mut session = Session::wide(vec![tree.path.clone()], false);
let tb = tree.path.join("ip/blk/dv/tb/tb.sv");
let uri = session.open(&tb, TB);
let (mut params, _) = at(&uri, TB, 2, "blk");
params["newName"] = serde_json::json!("blk2");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let top = path_to_uri(&tree.path.join("top/rtl/autogen/top_pd_main.sv")).expect("uri");
assert_eq!(changes.get(top.as_str()).and_then(Value::as_array).map_or(0, Vec::len), 1);
assert_eq!(changes.len(), 3, "blk.sv, tb.sv and the top: {answer:#}");
}
@@ -0,0 +1,106 @@
//! A hierarchical path rooted at a top module another file declares, over
//! the wire (TODO §65.4): `references` at a member of the DUT lists every
//! segment of `tb.dut.g_sw[0].buf_q` in a DV file, whichever side is open,
//! and `rename` rewrites them. `docs/features/top-rooted-paths/README.md`.
use super::*;
const DUT: &str = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n";
const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n";
const PROBE: &str = "module probe (output logic o);\n assign o = tb.dut.g_sw[0].buf_q;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n";
/// The LSP position of the first `name` on 0-based `line` of `text`.
fn at(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
let row = text.lines().nth(line).expect("the line");
let character = row.find(name).expect("the name on that line");
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
})
}
/// `(file name, 0-based line)` of every location in a `references` answer.
fn places(found: &Value) -> Vec<(String, u64)> {
let mut out: Vec<(String, u64)> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let uri = l["uri"].as_str().unwrap_or("?");
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
/// The three-file tree with the named files open; the uris of `dut_a.sv`
/// and `probe.sv`.
fn session_with(tag: &str, open: &[&str]) -> (Tree, Session, Uri, Uri) {
let tree = Tree::new(tag);
let files = [("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)];
for (name, text) in files {
tree.write(name, text);
}
let mut session = Session::wide(vec![tree.path.clone()], false);
for (name, text) in files.into_iter().filter(|(name, _)| open.contains(name)) {
session.open(&tree.path.join(name), text);
}
let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri");
let (dut, probe) = (uri("dut_a.sv"), uri("probe.sv"));
(tree, session, dut, probe)
}
fn expected() -> Vec<(String, u64)> {
let place = |file: &str, line| (file.to_string(), line);
vec![place("dut_a.sv", 2), place("probe.sv", 1), place("probe.sv", 2)]
}
fn references(session: &mut Session, mut params: Value) -> Vec<(String, u64)> {
params["context"] = serde_json::json!({ "includeDeclaration": true });
places(&session.result(References::METHOD, params))
}
#[test]
fn references_at_the_member_list_the_path_in_the_closed_dv_file() {
let (_tree, mut session, dut, _) = session_with("toproot_refs_decl", &["dut_a.sv"]);
assert_eq!(references(&mut session, at(&dut, DUT, 2, "buf_q")), expected());
}
#[test]
fn references_at_the_paths_segment_reach_the_closed_declaration() {
let (_tree, mut session, _, probe) = session_with("toproot_refs_path", &["probe.sv"]);
assert_eq!(references(&mut session, at(&probe, PROBE, 2, "buf_q")), expected());
}
#[test]
fn references_with_both_files_open_are_the_same_set() {
let (_tree, mut session, _, probe) =
session_with("toproot_refs_both", &["dut_a.sv", "probe.sv"]);
assert_eq!(references(&mut session, at(&probe, PROBE, 1, "buf_q")), expected());
}
#[test]
fn references_at_the_root_list_every_path_it_heads() {
let (_tree, mut session, _, probe) = session_with("toproot_refs_root", &["probe.sv"]);
let found = references(&mut session, at(&probe, PROBE, 1, "tb"));
let tb = ("tb.sv".to_string(), 0);
assert_eq!(found, vec![("probe.sv".to_string(), 1), ("probe.sv".to_string(), 2), tb]);
}
#[test]
fn rename_at_the_block_label_rewrites_the_paths_in_the_dv_file() {
let (tree, mut session, dut, _) = session_with("toproot_rename", &["dut_a.sv"]);
let mut params = at(&dut, DUT, 1, "g_sw");
params["newName"] = serde_json::json!("g_hw");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let count = |path: &str| {
let uri = path_to_uri(&tree.path.join(path)).expect("a uri");
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
};
assert_eq!((count("dut_a.sv"), count("probe.sv"), count("tb.sv")), (1, 2, 0), "{answer:#}");
let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten());
assert!(texts.all(|e| e["newText"] == "g_hw"), "{answer:#}");
}
@@ -0,0 +1,152 @@
//! A generate block label over the wire (TODO §65.1, topo §2.9-43).
//!
//! `references`, `prepareRename` and `rename` at a block label reach the
//! closing label and every path through the block — the same-file
//! `g_lane[0].sig` and another file's `u_x.g_lane[1].sig` — through the
//! engine and the index's hierarchical surface, whether the other file is
//! open or closed.
use super::*;
const SUB: &str = "module sub (input logic clk, output logic o);\n for (genvar i = 0; i < 2; i++) begin : g_lane\n logic sig;\n assign sig = clk;\n end : g_lane\n assign o = g_lane[0].sig;\nendmodule\n";
const TOP: &str = "module top (input logic clk, output logic o);\n sub u_x (.clk, .o());\n assign o = u_x.g_lane[1].sig;\nendmodule\n";
/// The LSP position of the `g_lane` on 0-based `line` of `text`.
fn at_label(uri: &Uri, text: &str, line: usize) -> Value {
let row = text.lines().nth(line).expect("the line");
let character = row.find("g_lane").expect("the label on that line");
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
})
}
/// `(file name, line)` of every location in a `references` answer.
fn places(found: &Value) -> Vec<(String, u64)> {
let mut out: Vec<(String, u64)> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let uri = l["uri"].as_str().unwrap_or("?");
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
/// The two-file tree, with `sub.sv` and/or `top.sv` open.
fn session_with(tag: &str, open_sub: bool, open_top: bool) -> (Tree, Session, Uri, Uri) {
let tree = Tree::new(tag);
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri");
let (sub, top) = (uri("sub.sv"), uri("top.sv"));
if open_sub {
session.open(&tree.path.join("sub.sv"), SUB);
}
if open_top {
session.open(&tree.path.join("top.sv"), TOP);
}
(tree, session, sub, top)
}
fn expected() -> Vec<(String, u64)> {
let sub = |line| ("sub.sv".to_string(), line);
vec![sub(1), sub(4), sub(5), ("top.sv".to_string(), 2)]
}
#[test]
fn references_at_the_label_reach_the_closing_label_and_every_path_with_the_user_closed() {
let (_tree, mut session, sub, _) = session_with("genlabel_refs_closed", true, false);
let mut params = at_label(&sub, SUB, 1);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn references_from_the_other_files_segment_are_the_same_set_with_the_declarer_closed() {
// The declaring file is closed, so its own uses (the closing label and
// `g_lane[0].sig`) come from §64.1's one-file re-analysis: a block is a
// hierarchical-only declaration.
let (_tree, mut session, _, top) = session_with("genlabel_refs_open", false, true);
let mut params = at_label(&top, TOP, 2);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn references_with_both_files_open_are_the_same_set() {
let (_tree, mut session, _, top) = session_with("genlabel_refs_both", true, true);
let mut params = at_label(&top, TOP, 2);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn prepare_rename_and_rename_rewrite_every_site_in_both_files() {
let (tree, mut session, sub, _) = session_with("genlabel_rename", true, false);
let prepared = session.result(PrepareRenameRequest::METHOD, at_label(&sub, SUB, 4));
assert_eq!(prepared["placeholder"], "g_lane", "{prepared:#}");
let mut params = at_label(&sub, SUB, 4);
params["newName"] = serde_json::json!("g_ln");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let count = |path: &str| {
let uri = path_to_uri(&tree.path.join(path)).expect("a uri");
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
};
assert_eq!((count("sub.sv"), count("top.sv")), (3, 1), "{answer:#}");
let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten());
assert!(texts.all(|e| e["newText"] == "g_ln"), "{answer:#}");
}
/// A member of a **nested** block is found on the index's `sub.g_a.g_b` key
/// (`Semantics::member_key`), so the reference list from its declaration in
/// an open buffer reaches the closed file's path to it.
#[test]
fn references_at_a_nested_blocks_member_reach_the_path_from_another_file() {
const NSUB: &str = "module nsub;\n if (1) begin : g_a\n for (genvar j = 0; j < 2; j++) begin : g_b\n logic deep;\n end\n end\nendmodule\n";
const NTOP: &str = "module ntop (output logic o);\n nsub u_n ();\n assign o = u_n.g_a.g_b[1].deep;\nendmodule\n";
let tree = Tree::new("genlabel_nested");
tree.write("nsub.sv", NSUB);
tree.write("ntop.sv", NTOP);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("nsub.sv"), NSUB);
let params = serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 3, "character": NSUB.lines().nth(3).and_then(|l| l.find("deep")) },
"context": { "includeDeclaration": true },
});
let found = places(&session.result(References::METHOD, params));
assert_eq!(found, vec![("nsub.sv".to_string(), 3), ("ntop.sv".to_string(), 2)]);
}
/// QA F1 over the wire: an open buffer is always in the rename's set, so its
/// path through the label that resolves to nothing (`tb.u_x.…`, rooted at a
/// top module no file in the tree declares — TODO §65.4 resolves the root
/// when one does) is shown as a warning, unedited.
#[test]
fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() {
const PROBE: &str =
"module probe (output logic o);\n assign o = tb.u_x.g_lane[0].sig;\nendmodule\n";
let (tree, mut session, sub, _) = session_with("genlabel_unresolved", true, false);
tree.write("probe.sv", PROBE);
session.open(&tree.path.join("probe.sv"), PROBE);
let _ = session.drain();
let mut params = at_label(&sub, SUB, 1);
params["newName"] = serde_json::json!("g_ln");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let probe = path_to_uri(&tree.path.join("probe.sv")).expect("a uri");
assert!(answer["changes"].get(probe.as_str()).is_none(), "probe.sv is not edited: {answer:#}");
let shown = session.shown();
assert!(
shown.iter().any(|(_, m)| m.contains("probe.sv:2:") && m.contains("`g_lane`")),
"{shown:?}"
);
assert!(!shown.iter().any(|(_, m)| m.contains("more")), "said once: {shown:?}");
}
@@ -0,0 +1,121 @@
//! A rename through a hierarchical path rooted at a top module, under the
//! shipped **folder** scope (top-rooted-paths QA F3): the rename's file set
//! holds the files declaring every unit the path walks through — the root
//! `tb` and each hop's type — so a three-hop `tb.dut.u_core.sig` is renamed
//! exactly as the whole-set engine renames it, from the declaration or from
//! the segment. A hop outside the scope leaves the path warned about, and a
//! rename from its segment is refused with the accurate reason.
use super::*;
const CORE: &str = "module core;\n logic sig;\nendmodule\n";
const DUT: &str = "module dut_a;\n core u_core ();\n logic top_sig;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n";
const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n";
const PROBE: &str = "module probe;\n initial force tb.dut.u_core.sig = 1'b0;\n initial force tb.dut.top_sig = 1'b0;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n";
/// The opentitan shape: `ip/blk/{rtl,dv}`, with `tb.sv` at `tb_at`.
fn fixture(tag: &str, tb_at: &str) -> Tree {
let tree = Tree::new(tag);
tree.write("ip/blk/rtl/core.sv", CORE);
tree.write("ip/blk/rtl/dut_a.sv", DUT);
tree.write(tb_at, TB);
tree.write("ip/blk/dv/probe.sv", PROBE);
tree
}
/// The LSP position of the first `name` on 0-based `line` of `text`.
fn at(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
let row = text.lines().nth(line).expect("the line");
let character = row.find(name).expect("the name on that line");
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
})
}
/// The number of edits a rename answer makes in each of `files`.
fn edits(tree: &Tree, answer: &Value, files: &[&str]) -> Vec<usize> {
let changes = answer["changes"].as_object().expect("changes");
files
.iter()
.map(|rel| {
let uri = path_to_uri(&tree.path.join(rel)).expect("a uri");
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
})
.collect()
}
fn rename(session: &mut Session, mut params: Value, new: &str) -> Result<Value, String> {
params["newName"] = serde_json::json!(new);
session.request(Rename::METHOD, params).response_result.map_err(|e| format!("{e:?}"))
}
const FILES: [&str; 2] = ["ip/blk/rtl/core.sv", "ip/blk/dv/probe.sv"];
#[test]
fn a_three_hop_path_is_renamed_from_the_declaration() {
let tree = fixture("toproot_scope_decl", "ip/blk/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let core = session.open(&tree.path.join(FILES[0]), CORE);
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}");
assert!(session.shown().is_empty(), "nothing to warn about: {:?}", session.shown());
}
#[test]
fn a_three_hop_path_is_renamed_from_its_segment() {
let tree = fixture("toproot_scope_seg", "ip/blk/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let probe = session.open(&tree.path.join(FILES[1]), PROBE);
let answer = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig2").expect("renames");
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}");
}
#[test]
fn a_member_of_a_generate_block_is_renamed_through_the_path() {
let tree = fixture("toproot_scope_block", "ip/blk/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let dut = session.open(&tree.path.join("ip/blk/rtl/dut_a.sv"), DUT);
let answer = rename(&mut session, at(&dut, DUT, 4, "buf_q"), "buf_r").expect("renames");
let files = ["ip/blk/rtl/dut_a.sv", "ip/blk/dv/probe.sv"];
assert_eq!(edits(&tree, &answer, &files), vec![1, 1], "{answer:#}");
}
/// The LSP rename equals the engine's over the scope's files.
#[test]
fn the_lsp_rename_equals_the_engine_over_the_scope() {
let tree = fixture("toproot_scope_engine", "ip/blk/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let core = session.open(&tree.path.join(FILES[0]), CORE);
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
let sources = session.server.workspace.sources();
let path = tree.path.join(FILES[0]);
let offset = CORE.find("sig").expect("sig") as u32;
let engine = vlog_refactor::rename(&sources, &path, offset, "sig2").expect("engine renames");
let lsp = edits(&tree, &answer, &FILES);
let whole: Vec<usize> =
FILES.iter().map(|rel| engine.edits_for(&tree.path.join(rel)).len()).collect();
assert_eq!(lsp, whole);
}
/// `tb.sv` outside the folder scope: the index cannot resolve the root, so
/// the open probe's path is left and warned about, and a rename asked from
/// its segment is refused for what it is — an unresolved path.
#[test]
fn a_root_outside_the_scope_is_warned_and_refused_accurately() {
let tree = fixture("toproot_scope_out", "top/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let probe = session.open(&tree.path.join(FILES[1]), PROBE);
let core = session.open(&tree.path.join(FILES[0]), CORE);
let in_index =
session.server.workspace.index().files().contains(&tree.path.join("top/dv/tb.sv"));
assert!(!in_index, "premise: the root's file is outside the scope");
let _ = session.drain();
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 0], "{answer:#}");
let shown = session.shown();
assert!(shown.iter().any(|(_, m)| m.contains("probe.sv:2:")), "{shown:?}");
let why = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig3").expect_err("refused");
assert!(why.contains("hierarchical path"), "{why}");
assert!(!why.contains("declared outside"), "{why}");
}
@@ -201,9 +201,22 @@ fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() {
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// Every rescan trigger, one refresh each.
// Every rescan trigger, one refresh each — a save of an edit the index
// has not seen, since a save that moved nothing refreshes nothing
// (localized-reindex, 2026-11-19).
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
assert!(session.requests().is_empty(), "a save that moved nothing asks for nothing");
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n");
session.watched(&[tree.path.join("top.sv")]);
session.notify(
DidChangeConfiguration::METHOD,
@@ -223,9 +236,22 @@ fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() {
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// A save of an edit the index has not seen, so the save path really
// moves the index (a save that moves nothing refreshes nothing anyway).
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n");
session.watched(&[tree.path.join("top.sv")]);
let index = session.server.workspace.index();
let w = index.member_in("sub", "w", vlog_semantic::Surface::Hierarchical);
assert_eq!(w.len(), 1, "premise: the save moved the index");
assert!(session.requests().is_empty(), "silence, on every rescan path");
}
@@ -368,6 +394,14 @@ fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() {
.open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
let _ = session.drain();
// An edit the index has not seen, so the save moves it.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let methods: Vec<String> = session.requests().into_iter().map(|(method, _)| method).collect();
@@ -128,10 +128,29 @@ fn the_stages_add_up_to_the_scan_they_describe() {
// the progress callbacks, the per-file word `Vec`, the staging pushes —
// which is deliberately unattributed rather than silently folded into a
// neighbouring stage.
//
// That slack is about a third of an unloaded scan, so one stall landing in
// it (the 4-CPU Linux runner throttles for tens of ms; QA caught 0.43 on
// macOS beside a looping suite) grows `total` and no stage. The upper
// bound is structural — the stages are disjoint pieces of the scan — and
// holds on every scan; the lower bound is a claim about an undisturbed
// scan, so it is asserted on the best of three: a stall spoils one
// sample, not all of them.
let tree = trace_tree("tracesums", 40);
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let stages = line_of(&scan_lines(&session), "stages");
let total = number(&stages, "total");
let mut best = 0.0f64;
for _ in 0..3 {
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let stages = line_of(&scan_lines(&session), "stages");
let (sum, total) = (named_stage_sum(&stages), number(&stages, "total"));
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
best = best.max(sum / total);
}
assert!(best >= 0.5, "the stages must account for most of it: at best {best:.2} of the scan");
}
/// The sum of every stage a scan's `stages` line names, `total` aside.
fn named_stage_sum(stages: &str) -> f64 {
let named = [
"discovery",
"order",
@@ -157,10 +176,7 @@ fn the_stages_add_up_to_the_scan_they_describe() {
"includes",
"overlay",
];
let sum: f64 = named.iter().map(|key| number(&stages, key)).sum();
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
assert!(sum >= total * 0.5, "the stages must account for most of it: {sum} of {total}");
named.iter().map(|key| number(stages, key)).sum()
}
#[test]
+80 -1
View File
@@ -112,6 +112,11 @@ pub struct ClientSettings {
/// declares — the key changes bytes in files that already format cleanly,
/// so nothing turns it on for a user who did not ask.
pub uvm_utils_indent: Option<bool>,
/// `lucisv.format.style`: the named layout preset, one of
/// `lucisv_core::config::STYLE_NAMES`. Unset — and any name that is not
/// one of them — means "no opinion", so a `lucisv.toml` or the built-in
/// default decides.
pub style: Option<&'static str>,
/// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text.
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
@@ -121,6 +126,14 @@ pub struct ClientSettings {
/// followed by a space. Unset means on, the same way `inline_templates`
/// does — see `docs/features/inline-instantiation/README.md`.
pub inline_instantiation: Option<bool>,
/// `lucisv.inlineKeywords`: whether a typed proper prefix of a keyword
/// grows the rest of it as ghost text. Unset means on, independent of
/// `inline_templates` — see `docs/features/completion-ux/README.md`.
pub inline_keywords: Option<bool>,
/// `lucisv.autoEnd`: whether a newline typed after `begin` also writes
/// the `end` the block still owes. Unset means on — see
/// `docs/features/completion-ux/README.md`.
pub auto_end: Option<bool>,
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
/// the buffer. A plain `bool` rather than an `Option`, because unset and
/// off are the same answer here: an editor with a format-on-save of its
@@ -244,8 +257,11 @@ impl Default for ClientSettings {
exclude: Vec::new(),
filelist: None,
uvm_utils_indent: None,
style: None,
inline_templates: None,
inline_instantiation: None,
inline_keywords: None,
auto_end: None,
format_on_save: false,
max_file_size: DEFAULT_MAX_FILE_SIZE,
log_files: true,
@@ -343,8 +359,11 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
exclude: strings(lucisv.get("exclude")),
filelist: path(lucisv.get("filelist")),
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
style: style(lucisv.get("format").and_then(|f| f.get("style"))),
inline_templates: flag(lucisv.get("inlineTemplates")),
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
inline_keywords: flag(lucisv.get("inlineKeywords")),
auto_end: flag(lucisv.get("autoEnd")),
// Anything that is not `true` leaves the hook declining, wrong-typed
// values included: the safe direction for a setting that rewrites the
// user's buffer on every save is the one that does nothing.
@@ -569,6 +588,13 @@ fn path(value: Option<&Value>) -> Option<String> {
(!text.is_empty()).then(|| text.to_string())
}
/// A preset name `lucisv.toml`'s `[format] style` would accept, or nothing.
/// VS Code's drop-down cannot send anything else; another editor's
/// hand-written misspelling is dropped like every wrong-typed value here.
fn style(value: Option<&Value>) -> Option<&'static str> {
lucisv_core::config::parse_style(value?.as_str()?).ok()
}
/// A JSON integer inside `range`, or nothing.
///
/// `as_u64` rejects null, strings, booleans, negatives and fractions in one
@@ -623,6 +649,8 @@ mod tests {
"filelist": "",
"inlineTemplates": true,
"inlineInstantiation": true,
"inlineKeywords": true,
"autoEnd": true,
"formatOnSave": false,
"index": {
"maxFileSize": 1048576, "logFiles": true,
@@ -814,6 +842,31 @@ mod tests {
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
}
/// The style drop-down offers exactly the names `[format] style` takes,
/// one description each, defaulting to the default style; and each one
/// arrives here as itself, while a name that is not one is dropped.
#[test]
fn the_style_drop_down_is_the_style_names() {
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 style = &manifest["contributes"]["configuration"]["properties"]["lucisv.format.style"];
assert_eq!(style["enum"], json!(lucisv_core::config::STYLE_NAMES));
let descriptions = style["enumDescriptions"].as_array().expect("descriptions");
assert_eq!(descriptions.len(), lucisv_core::config::STYLE_NAMES.len());
assert_eq!(style["default"], json!("lucisv"));
for name in lucisv_core::config::STYLE_NAMES {
let pushed = settings(json!({ "lucisv": { "format": { "style": name } } }));
assert_eq!(pushed.style, Some(name));
}
for junk in [json!("Google"), json!(""), json!(4), json!(null)] {
let pushed = settings(json!({ "lucisv": { "format": { "style": junk } } }));
assert_eq!(pushed.style, None, "{junk}");
}
assert_eq!(settings(json!({ "lucisv": {} })).style, None);
}
/// [`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
@@ -838,7 +891,13 @@ mod tests {
// The two ghost-text settings are the ones whose absence resolves to
// `true` here, so a `false` default in the manifest would make the
// settings UI and the server disagree about a feature being on.
for ghost in ["lucisv.inlineTemplates", "lucisv.inlineInstantiation"] {
// `autoEnd` is the same kind of switch: absent means on.
for ghost in [
"lucisv.inlineTemplates",
"lucisv.inlineInstantiation",
"lucisv.inlineKeywords",
"lucisv.autoEnd",
] {
assert_eq!(properties[ghost]["default"], json!(true), "{ghost}");
assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}");
}
@@ -1103,6 +1162,8 @@ mod tests {
ClientSettings {
inline_templates: Some(true),
inline_instantiation: Some(true),
inline_keywords: Some(true),
auto_end: Some(true),
..Default::default()
},
"the only difference from silence must be the settings whose \
@@ -1141,6 +1202,24 @@ mod tests {
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
}
#[test]
fn inline_keywords_and_auto_end_are_booleans_and_nothing_else() {
let found = settings(json!({ "lucisv": { "inlineKeywords": false, "autoEnd": false } }));
assert_eq!((found.inline_keywords, found.auto_end), (Some(false), Some(false)));
let found = settings(json!({ "lucisv": { "inlineKeywords": true, "autoEnd": true } }));
assert_eq!((found.inline_keywords, found.auto_end), (Some(true), Some(true)));
// Absence is not `false`: both are on unless a client says no.
let found = settings(json!({ "lucisv": {} }));
assert_eq!((found.inline_keywords, found.auto_end), (None, None));
for bad in [json!("false"), json!(0), json!(null), json!([false])] {
let found = settings(json!({ "lucisv": { "inlineKeywords": bad, "autoEnd": bad } }));
assert_eq!((found.inline_keywords, found.auto_end), (None, None), "{bad} ignored");
}
// Independent of the template ghosts: one off leaves the other alone.
let found = settings(json!({ "lucisv": { "inlineKeywords": false } }));
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
}
#[test]
fn format_on_save_is_off_until_a_client_asks_for_it() {
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
+131
View File
@@ -0,0 +1,131 @@
//! The open buffers: installing, closing and finding them, and which
//! text — the buffer's or the disk's — speaks for a path when the index
//! or a refactoring asks.
use std::fs;
use std::path::Path;
use lsp_types::Uri;
use vlog_semantic::FileFacts;
use super::discover::{oversize, Found};
use super::{Document, Workspace};
use crate::uri::uri_to_path;
impl Workspace {
pub fn document(&self, uri: &Uri) -> Option<&Document> {
self.docs.get(uri)
}
/// The open document backed by `path`, if there is one.
pub fn document_for_path(&self, path: &Path) -> Option<&Document> {
self.docs.values().find(|doc| doc.path.as_deref() == Some(path))
}
/// Every open document and its URI.
pub fn open_documents(&self) -> impl Iterator<Item = (&Uri, &Document)> {
self.docs.iter()
}
/// Replace a buffer's contents and re-analyze it.
///
/// Also the one place a directory enters the folder scope: a buffer with a
/// path puts its own directory on the list `scope_dirs` raises. An
/// `untitled:` buffer has no path and contributes none.
///
/// And the one place the **large-file fast path** is chosen: a text over
/// `lucisv.largeFile.threshold` is line-indexed and nothing more. Because
/// the decision lives here it is re-taken on every `didOpen`, `didChange`
/// and text-carrying `didSave`, which is what makes a buffer edited past
/// the threshold — or back under it — change mode at that moment and not
/// before (`docs/features/large-file-mode/README.md`).
pub fn set_document(&mut self, uri: Uri, text: String) {
let path = uri_to_path(&uri);
if let Some(dir) = path.as_deref().and_then(Path::parent) {
if !self.opened_dirs.iter().any(|seen| seen == dir) {
self.opened_dirs.push(dir.to_path_buf());
self.opened_dirs.sort();
}
}
// This path now has a buffer speaking for it, so whatever the view
// cache holds for it is both unwanted and possibly older than the
// edits the buffer carries.
if let Some(path) = path.as_deref() {
self.forget_view(path);
}
let doc = match self.is_large(&text) {
true => Document::large(path, text),
false => Document::new(path, text, &self.index),
};
self.docs.insert(uri, doc);
}
/// Whether a buffer of this text takes the fast path. `0` disables it, and
/// the comparison is strict, so a buffer of exactly the threshold is still
/// analyzed in full.
fn is_large(&self, text: &str) -> bool {
let threshold = self.client.large_file_threshold;
threshold != 0 && text.len() as u64 > threshold
}
/// Whether any open buffer is on the large-file fast path.
///
/// The gate in `server.rs` runs before every request, and this is what
/// keeps that from costing a URI parse per request in the session where
/// nothing is large — which is every session but one.
pub fn has_large_documents(&self) -> bool {
self.docs.values().any(|doc| doc.large)
}
pub fn close_document(&mut self, uri: &Uri) {
let closed = self.docs.remove(uri);
// Disk is the authority again, and a view made before this buffer was
// opened predates every save it made.
if let Some(path) = closed.and_then(|doc| doc.path) {
self.forget_view(&path);
}
}
/// Every open buffer's URI, for republishing diagnostics after a rebuild.
pub fn open_uris(&self) -> Vec<Uri> {
self.docs.keys().cloned().collect()
}
/// The text of a workspace file: the open buffer if there is one, else
/// what is on disk. Same precedence the index rebuild uses, so a location
/// is never computed against text the index did not see.
pub fn text_of(&self, path: &Path) -> Option<String> {
let open = self.docs.values().find(|d| d.path.as_deref() == Some(path));
match open {
Some(doc) => Some(doc.text.clone()),
None => fs::read_to_string(path).ok(),
}
}
/// The text one in-scope file contributes right now, by `collect_sources`'s
/// rules — `None` when it contributes nothing at all.
pub(super) fn current_text(&self, path: &Path) -> Option<String> {
if let Some(doc) = self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) {
// A fast-path buffer contributes nothing, exactly as it does in
// `collect_sources` — indexing it is the parse the fast path
// exists to skip.
return (!doc.large).then(|| doc.text.clone());
}
if oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_some() {
return None;
}
fs::read_to_string(path).ok()
}
/// The index facts and the completion words of the open buffer backing
/// `path`, read off the analysis it already holds — `None` when no buffer
/// does, or when the one that does is on the large-file fast path and has
/// no analysis of its own text to read.
///
/// The buffer is found the same way [`Workspace::current_text`] finds the
/// text, so the two always speak for the same `Document`.
pub(super) fn analysis_of(&self, path: &Path) -> Option<(FileFacts, Vec<String>)> {
let doc = self.docs.values().find(|doc| doc.path.as_deref() == Some(path))?;
(!doc.large).then(|| (doc.facts(path.to_path_buf()), doc.words()))
}
}
+3 -11
View File
@@ -389,18 +389,10 @@ impl Workspace {
// The walk names its inputs as strings; every directory here came
// from a `file:` URI, which cannot carry a non-UTF-8 path.
let Some(input) = root.to_str() else { continue };
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a
// server that comes up empty. The error is reported when the user
// formats a file in this tree (`format::settings_for`).
// A broken `lucisv.toml` excludes nothing, and the client's
// `lucisv.exclude` is appended to it — see `walk_excludes`.
let configuring = trace.now();
let mut exclude =
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `lucisv.exclude` is *appended*, never substituted —
// the CLI appends a config's excludes to `--exclude` the same way,
// and a setting that silently dropped a checked-in exclude would
// put vendored code back in the index for one user only.
exclude.extend(self.client.exclude.iter().cloned());
let exclude = self.walk_excludes(&mut discovery, root);
ScanTrace::add(&mut trace.config_ms, configuring);
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable directory
+232
View File
@@ -0,0 +1,232 @@
//! One open buffer, analyzed once from its text — [`Document`] and
//! everything derived from it — and the two binary searches that find a
//! token in it by offset without sweeping the buffer.
use std::path::PathBuf;
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
use vlog_semantic::{
analyze, resolve_external, ExternalResolutions, FileFacts, Semantics, WorkspaceIndex,
};
use crate::convert::Positions;
/// One open buffer, fully analyzed. Every field is derived from `text`, so a
/// change throws the whole thing away and builds a new one.
pub struct Document {
/// The buffer's path, absent for a `untitled:` document.
pub path: Option<PathBuf>,
pub text: String,
pub line_index: LineIndex,
/// Empty when the file does not lex — the lexer is all-or-nothing.
pub tokens: Vec<Token>,
/// The tolerant parse of `text` — the tree `semantics` was analyzed from,
/// kept so the lint pass reads it instead of parsing the buffer again
/// ("one parse, two tools", `docs/features/one-parse/README.md`).
pub tree: SourceFile,
pub diagnostics: Vec<ParseDiagnostic>,
pub semantics: Semantics,
pub defines: DefineTable,
/// The workspace layer's answers for this file's external candidates.
pub external: ExternalResolutions,
/// Whether this buffer was opened on the **large-file fast path**: every
/// field above except `text` and `line_index` is the empty analysis of an
/// empty file, because nothing lexed it. Handlers that would scan the text
/// itself check this flag; the ones that read the analysis need not, since
/// there is nothing in it to find. See
/// `docs/features/large-file-mode/README.md`.
pub large: bool,
/// The formatter's fence answer for exactly this `text`, computed on
/// first use and never again — a whole tolerant parse the code-action
/// path used to pay for on every request. Filled through
/// [`crate::fences::of`], which is the only thing that may touch it; it
/// is bound to this revision because a change builds a new `Document`.
pub fences: std::sync::OnceLock<Vec<vlog_formatter::fence::Region>>,
/// This buffer's lint findings, kept while every input that produced them
/// is unchanged — read by the diagnostics pass and by quick-fix discovery
/// alike, so one revision is linted once rather than twice (review round
/// §R1a, `crate::lint_snapshot`). Bound to this revision for the same
/// structural reason `fences` is; the inputs that can move *without* a new
/// `Document` are the snapshot's own key, and the index moving is
/// [`Document::refresh_overlay`], which clears it.
pub lint: crate::lint_snapshot::Slot,
}
impl Document {
/// Analyze a buffer from scratch against the current workspace index.
pub fn new(path: Option<PathBuf>, text: String, index: &WorkspaceIndex) -> Document {
// One lex: the tree is built from a clone of the token stream instead
// of re-lexing the buffer (`parse_source_tolerant` is exactly
// `tokenize` + `parse_tolerant`, so the tree is identical). A buffer
// that does not lex keeps the old path, so its all-error tree and its
// lex diagnostic are byte-for-byte what they always were.
use crate::lint_trace::{rebuild, Rebuild};
crate::lint_trace::saw_document();
let (tokens, (tree, diagnostics)) = match rebuild(Rebuild::Lex, || tokenize(&text)) {
Ok(tokens) => {
let parsed = rebuild(Rebuild::Parse, || parse_tolerant(tokens.clone(), &text));
(tokens, parsed)
}
Err(_) => (Vec::new(), rebuild(Rebuild::Parse, || parse_source_tolerant(&text))),
};
let defines = rebuild(Rebuild::Defines, || collect_defines(&tokens));
let semantics = rebuild(Rebuild::Analyze, || analyze(&tree, &text));
let external = rebuild(Rebuild::External, || resolve_external(&semantics, index));
let line_index = rebuild(Rebuild::Lines, || LineIndex::new(&text));
let large = false;
Document {
path,
text,
line_index,
tokens,
tree,
diagnostics,
semantics,
defines,
external,
large,
fences: std::sync::OnceLock::new(),
lint: crate::lint_snapshot::Slot::new(),
}
}
/// Take a buffer on the **fast path**: index its lines and nothing else.
///
/// One newline scan is the whole cost of opening a 100 MB netlist. The
/// derived fields are the analysis of the *empty* file rather than of this
/// one — built by parsing `""`, which costs nothing and needs no new API
/// from `vlog_parser` — so every handler that reads the analysis finds
/// exactly nothing and answers empty without knowing this path exists.
pub fn large(path: Option<PathBuf>, text: String) -> Document {
let (tree, _) = parse_source_tolerant("");
let semantics = analyze(&tree, "");
let line_index = LineIndex::new(&text);
Document {
path,
text,
line_index,
tokens: Vec::new(),
tree,
diagnostics: Vec::new(),
semantics,
defines: DefineTable::default(),
external: ExternalResolutions::default(),
large: true,
fences: std::sync::OnceLock::new(),
lint: crate::lint_snapshot::Slot::new(),
}
}
/// This document's position converter.
pub fn positions(&self) -> Positions<'_> {
Positions::new(&self.text, &self.line_index)
}
/// The source token covering `offset`, found without sweeping the buffer.
pub fn token_at(&self, offset: u32) -> Option<&Token> {
let after = self.tokens.partition_point(|token| token.span.start <= offset);
let token = self.tokens.get(after.checked_sub(1)?)?;
token.span.contains(offset).then_some(token)
}
/// Re-run only the workspace overlay, after the index was rebuilt. The
/// single-file analysis is unaffected by other files, by construction.
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
self.external = resolve_external(&self.semantics, index);
// The index is what the census oracle answers from, so a lint result
// taken under the old one is no longer this buffer's answer. This is
// the whole of the snapshot's index invalidation: every mutation of
// `Workspace::index` ends in the loop that calls this, so there is no
// generation counter to keep in step (review round §R1a).
self.lint.clear();
}
/// What this buffer contributes to the workspace index, read off the
/// analysis it already holds instead of from its text.
///
/// [`FileFacts::of`] is `tokenize` + `parse_tolerant` + `analyze` followed
/// by the fact walk, and the first three are exactly what [`Document::new`]
/// already did to fill `tree`, `defines` and `semantics` — from the same
/// text, with the same functions, down to the lex-failure branch. So this
/// is `FileFacts::of(path, &self.text)` with the parse already paid for,
/// not a second way of computing it
/// (`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus`).
///
/// Never called for a buffer on the large-file fast path: its analysis is
/// the analysis of the empty file, and such a buffer contributes nothing to
/// the index at all (see `collect_sources`).
pub fn facts(&self, path: PathBuf) -> FileFacts {
FileFacts::from_analysis(
path,
&self.tree,
&self.defines,
&self.semantics,
&self.text,
&self.line_index,
&self.tokens,
)
}
/// The completion words this buffer contributes, read off the tokens it was
/// analyzed from rather than by lexing its text a second time.
pub fn words(&self) -> Vec<String> {
crate::candidates::words_of_tokens(&self.tokens)
}
}
// ----------------------------------------------------------------------
// Finding a token by offset without sweeping the buffer
// ----------------------------------------------------------------------
//
// The lexer emits tokens in source order and they never overlap, so
// `span.start` and `span.end` both rise across the vector: `end[i] <=
// start[i+1] <= end[i+1]`. That makes both predicates below monotone, which
// is the whole precondition `partition_point` needs. Every handler that used
// to sweep the vector looking for a token at the cursor is one comparison
// away from one of these two indices — see
// `docs/features/interactive-latency/README.md` for the per-call-site
// argument that each swap returns exactly what the sweep returned.
/// The index of the first token that **reaches** `offset` — the first with
/// `span.end >= offset`. `tokens.len()` when none does.
///
/// Every token before it ends strictly before `offset`, so it cannot cover,
/// end at, or contain `offset`. The token *at* this index is therefore the
/// first candidate any such question has.
pub fn first_token_reaching(tokens: &[Token], offset: u32) -> usize {
tokens.partition_point(|token| token.span.end < offset)
}
/// The index of the first token that **begins** at or after `offset` — the
/// first with `span.start >= offset`. `tokens.len()` when none does.
pub fn first_token_from(tokens: &[Token], offset: u32) -> usize {
tokens.partition_point(|token| token.span.start < offset)
}
/// A buffer of `blocks` repeated blocks, for the tests that check a binary
/// search against the sweep it replaced.
///
/// Deliberately awkward: tokens written with no space between them (`a=b;`),
/// line and block comments, a string, nested `begin`/`end` and several depths
/// of parentheses. The offsets those tests walk are *every byte*, and the ones
/// that could tell a binary search from a sweep are exactly the bytes two
/// tokens share — which only adjacent punctuation produces.
#[cfg(test)]
pub fn mixed_buffer(blocks: usize) -> String {
let mut src = String::from("module mixed (input logic clk, output logic [7:0] q);\n");
for n in 0..blocks {
src.push_str(&format!(
" // block {n}\n \
wire [7:0] w{n};assign w{n}=(q[0]?8'd1:8'd2)+{{4'h0,4'hF}};\n \
/* {n} */ always @(posedge clk) begin\n \
if (w{n}[0]) begin q<=w{n}; end else begin q<=8'd0; end\n \
end\n \
initial $display(\"block {n}\", w{n});\n"
));
}
src.push_str("endmodule\n");
src
}
@@ -0,0 +1,272 @@
//! Re-indexing one saved file the index already holds, patching every
//! table rather than rebuilding it — the cheap path a `didSave` takes
//! before falling back to a whole rescan — and doing only the work the
//! file's change can reach (`docs/features/localized-reindex/README.md`).
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use lucisv_core::walk::dir_id;
use vlog_semantic::FileFacts;
use super::Workspace;
use crate::scan_trace::ScanTrace;
/// What [`Workspace::update_one_file`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OneFile {
/// The index does not hold the file; the caller owes a whole rebuild.
NotHeld,
/// The file's record is the one the index already held — the watcher's
/// echo of a save, or a save that changed nothing the index records — so
/// nothing derived from the index moved and no other buffer's answer can
/// have either.
Unchanged,
/// The index moved, and every open buffer's overlay was refreshed.
Changed,
}
impl Workspace {
/// [`Workspace::update_one_file`], for a test that only asks whether the
/// cheap path was taken.
#[cfg(test)]
pub fn update_one(&mut self, path: &Path) -> bool {
self.update_one_file(path) != OneFile::NotHeld
}
/// Rebuild the index for **one** file, leaving every other file's
/// contribution exactly as it is, and say what moved.
///
/// [`OneFile::NotHeld`] means the caller must fall back to
/// [`Workspace::rebuild_index`]: the file is not one this index already
/// holds, which the cheap path settles only for an open buffer older than
/// the last whole scan ([`Workspace::add_open_buffer`]). A file appearing
/// changes which *other* files exist as far as the include graph is
/// concerned (a `` `include`` that had nothing to resolve to now has
/// something), and answering that takes a walk.
///
/// The four pieces of state a rebuild produces, and what happens to each:
///
/// * **the workspace index** — [`WorkspaceIndex::update_facts`] /
/// [`WorkspaceIndex::remove_file`], which promise the index a whole
/// rebuild over the same file set would have produced, and say when the
/// record did not move at all;
/// * **the completion tables** — the word table patched by this file's
/// words, and the two index-derived ones re-derived for the names this
/// file declared or declares, only when it now declares something
/// different ([`FileFacts::declares_the_same`]);
/// * **the include graph** — this file's edges re-scanned and re-spelled;
/// nothing else in it depends on one file's text;
/// * **every open buffer's overlay** — refreshed when the index moved,
/// because any of them may resolve into the file that moved.
///
/// The text is chosen by `collect_sources`'s rules, for one path: an open
/// buffer beats disk and is never capped; a walked file over
/// `lucisv.index.maxFileSize`, one that has been deleted, and one that
/// cannot be read are all "this file is not in the index any more".
///
/// [`WorkspaceIndex::update_facts`]: vlog_semantic::WorkspaceIndex::update_facts
/// [`WorkspaceIndex::remove_file`]: vlog_semantic::WorkspaceIndex::remove_file
pub fn update_one_file(&mut self, path: &Path) -> OneFile {
if self.index.file_id(path).is_none() {
return self.add_open_buffer(path);
}
// Re-indexing one file *is* the claim that its bytes moved.
self.forget_view(path);
let Some(text) = self.current_text(path) else {
self.remove_one(path);
return OneFile::Changed;
};
// The same rule a whole rebuild follows: when the text came from an
// open buffer, that buffer's finished analysis is the facts and the
// words, and neither is derived from the text a second time.
// `current_text` answers with a buffer's text only when that buffer is
// not on the large-file fast path, so the analysis found here is a
// real one. Otherwise the file is parsed once, and its words come back
// out of the record (`FACTS_FORMAT` 13).
let (facts, words) = self.analysis_of(path).unwrap_or_else(|| {
let facts = FileFacts::of(path.to_path_buf(), &text);
let words = facts.words().to_vec();
(facts, words)
});
let declared = self.declared_by_either(path, &facts);
let moved = self.index.update_facts(facts);
// The include lines are not in the record — `` `include "a.svh"`` and
// `` `include <a.svh>`` can read the same to it — so they are
// re-scanned whatever the record said.
self.includes.update_held(path, &text);
self.write_through(path, &text);
if !moved {
return OneFile::Unchanged;
}
self.candidates.set_file_words(path, words);
if let Some((symbols, macros)) = declared {
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
self.candidates.refresh_names(&self.index, &symbols, &macros);
}
self.refresh_overlays();
OneFile::Changed
}
/// The half of [`Workspace::update_one_file`] for a file the index does
/// not hold, which it can settle only for an open buffer — one opened
/// after the last whole scan took its work list, from outside the
/// filelist or under an `exclude`, which a rebuild would take in because
/// every open buffer is taken in.
///
/// What a rebuild would re-read besides the buffer is every other file's
/// `` `include``s, and the only ones the file's arrival can answer
/// differently are those whose last component could be its name — so those
/// are re-resolved ([`IncludeGraph::refresh_naming`]), from the lines the
/// graph holds, against the disk as it is now. No witness of *when* the
/// file appeared is needed, and none is trusted: a birth time was, until
/// QA showed `mv`, `cp -p` and `tar x` set it back (F3).
///
/// The index is merged whole (every id after the new one moves), which
/// is in memory and reads nothing.
///
/// [`IncludeGraph::refresh_naming`]: crate::includes::IncludeGraph::refresh_naming
fn add_open_buffer(&mut self, path: &Path) -> OneFile {
let Some((facts, words)) = self.analysis_of(path) else { return OneFile::NotHeld };
let Some(text) = self.current_text(path) else { return OneFile::NotHeld };
if self.holds_another_spelling_of(path) {
// A rebuild would take the buffer's spelling *instead of* the
// held one (`discover.rs`'s `Aliased`), which is not an add.
return OneFile::NotHeld;
}
let (symbols, macros) = facts.declared_names();
let symbols: HashSet<String> = symbols.into_iter().map(str::to_string).collect();
let macros: HashSet<String> = macros.into_iter().map(str::to_string).collect();
self.index.update_facts(facts);
self.candidates.set_file_words(path, words);
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
self.candidates.refresh_names(&self.index, &symbols, &macros);
self.includes.add_known(path);
self.includes.update_held(path, &text);
self.includes.refresh_naming(path);
self.write_through(path, &text);
self.refresh_overlays();
OneFile::Changed
}
/// Whether the index holds the file at `path` under another name — a
/// directory alias — by the test the scan's own overlay applies: the same
/// file name, then the same `(dev, ino)`.
fn holds_another_spelling_of(&self, path: &Path) -> bool {
let Some(id) = dir_id(path) else { return false };
let named = |held: &&PathBuf| held.file_name() == path.file_name();
self.index.files().iter().filter(named).any(|held| dir_id(held) == Some(id))
}
/// The half of [`Workspace::update_one_file`] for a held file that is
/// gone, capped or unreadable. The files whose `` `include``s could name
/// it are re-resolved, because their lines resolve against the disk and a
/// deleted file is no longer there to find.
fn remove_one(&mut self, path: &Path) {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
self.includes.refresh_naming(path);
self.refresh_overlays();
}
/// Files appeared, vanished or moved at `paths`, wherever they are: the
/// include lines that could name any of them are re-resolved, in one pass.
/// The whole of what such an event owes the graph for a file the index
/// does not hold.
pub fn refresh_includes_naming(&mut self, paths: &[PathBuf]) {
self.includes.refresh_naming_all(paths);
}
/// The names the held record and `facts` put in the completion tables'
/// listings, both records' together — or `None` when the two declare the
/// same things ([`FileFacts::declares_the_same`]) and no listing can move.
fn declared_by_either(
&self,
path: &Path,
facts: &FileFacts,
) -> Option<(HashSet<String>, HashSet<String>)> {
let held = self.index.facts_for(path)?;
if held.declares_the_same(facts) {
return None;
}
let mut symbols: HashSet<String> = HashSet::new();
let mut macros: HashSet<String> = HashSet::new();
for record in [held, facts] {
let (names, defines) = record.declared_names();
symbols.extend(names.into_iter().map(str::to_string));
macros.extend(defines.into_iter().map(str::to_string));
}
Some((symbols, macros))
}
/// Write the file's record through to the persistent store, so an hour of
/// saves is an hour of work the next session does not repeat. The record
/// is the one the update just made — no second parse — and it is keyed by
/// the text it was made from, which is the buffer's when a buffer beat
/// disk; that record is simply never hit again if the file on disk says
/// something else. A save is the other thing that asks the store
/// something, so it opens a re-open a scan deferred rather than writing
/// into the store the previous rescan left in hand ([`StoreOpen`]).
///
/// [`StoreOpen`]: super::StoreOpen
fn write_through(&mut self, path: &Path, text: &str) {
self.open_store(&mut ScanTrace::default());
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, text);
}
}
/// Re-resolve every open buffer's cross-file references against the index
/// as it now stands, exactly as a rebuild does.
fn refresh_overlays(&mut self) {
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
}
/// [`Workspace::update_one`], then a whole rebuild over the same
/// workspace, asserting the two produced the same thing — the paranoid
/// form, for tests.
///
/// It is the incremental path's whole claim, checked rather than argued:
/// the index's fingerprint (ids, disambiguation order, member tables,
/// edges, define counts, postings and who read what), the completion
/// tables and the include graph. The workspace is left holding the
/// *rebuilt* index, which is the same index, so a test may keep using it.
#[cfg(test)]
pub fn update_one_checked(&mut self, path: &Path) -> bool {
if !self.update_one(path) {
return false;
}
let before = self.derived_fingerprint();
self.rebuild_index();
assert_eq!(before, self.derived_fingerprint(), "incremental state != rebuilt state");
true
}
/// Everything a rebuild derives from the sources, rendered for comparison:
/// the index, the completion tables, the include graph and every open
/// buffer's cross-file answers.
#[cfg(test)]
pub fn derived_fingerprint(&self) -> String {
let mut docs: Vec<(&lsp_types::Uri, &super::Document)> = self.docs.iter().collect();
docs.sort_by_key(|(uri, _)| uri.as_str());
let overlays: Vec<String> = docs
.iter()
.map(|(uri, doc)| {
format!("{} {:?}", uri.as_str(), doc.external.iter().collect::<Vec<_>>())
})
.collect();
format!(
"{}\n{}\n{}\n{}",
self.index.fingerprint(),
self.candidates.fingerprint(),
self.includes.fingerprint(),
overlays.join("\n")
)
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,332 @@
//! The connection being typed: where each buffer's last edit ended, the
//! connection-list entry around it, and the diagnostics held back from that
//! entry while the typing goes on (`docs/features/port-entry-grace/README.md`).
//!
//! Someone typing `.po` into `sub u0 (…)` passes through a lone `.`, a `.p`
//! that names no port, a `.po(` with nothing closed — and every one of those
//! keystrokes used to draw a squiggle. While the last edit sits inside an
//! instantiation's port or parameter list, the diagnostics whose range starts
//! inside the entry around it are withheld from what is published or pulled.
//! Nothing outside that entry is ever withheld, and the entry is released —
//! the full list said again — when the next edit lands outside it, when
//! [`PORT_ENTRY_GRACE`] passes with no edit at all, or when the buffer is
//! saved, closed or reopened.
//!
//! The lookup is a token scan of the buffer just analyzed, no extra parse.
//! The parser's half — keeping the unfinished entry inside its own entry so
//! the rest of the file parses as if it were complete — is in
//! `vlog_parser`'s `recover_list.rs`, and the two agree on where an entry
//! ends: a `,` or the list's `)` at the list's own level, or the end of the
//! line when the next line opens a new `.` entry.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use lsp_types::{Diagnostic, Uri};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use super::Document;
use crate::signature::enclosing_list;
/// How long the diagnostics of the entry being typed are held back after the
/// last edit. Long enough to finish typing a port name and its connection,
/// short enough that a real mistake left behind is shown before the eye has
/// moved on.
pub const PORT_ENTRY_GRACE: Duration = Duration::from_millis(1500);
/// Every buffer's last edit, while it may still be withholding something.
#[derive(Default)]
pub struct PortGrace {
edits: HashMap<Uri, LastEdit>,
}
/// One buffer's last edit.
struct LastEdit {
/// Where the edit ended, in the buffer's newest text.
offset: u32,
/// When it arrived.
at: Instant,
/// Where it stands in the analysis of that text.
state: Located,
/// An edit has since landed in another buffer: release at the next
/// chance rather than when the quiet period ends.
released: bool,
}
/// Whether a buffer's last edit has been looked up in its analysis yet.
enum Located {
/// The buffer is dirty; its analysis is not the text the edit is in.
Pending,
/// The edit is inside this connection-list entry.
Entry(TextRange),
}
impl PortGrace {
/// Note a buffer's edit, `end` being where the last of its changes ended
/// in the new text — `None` for a full-document replacement, which says
/// nothing about where anyone is typing and so withholds nothing.
///
/// An edit is "elsewhere" for every other buffer, so whatever those are
/// withholding is released at the next chance.
pub fn edited(&mut self, uri: &Uri, end: Option<u32>, now: Instant) {
for (other, edit) in self.edits.iter_mut() {
if other != uri {
edit.released = true;
}
}
match end {
Some(offset) => {
let edit = LastEdit { offset, at: now, state: Located::Pending, released: false };
self.edits.insert(uri.clone(), edit);
}
None => {
self.edits.remove(uri);
}
}
}
/// Look a buffer's pending edit up in `doc`, its freshly analyzed text.
/// An edit outside every connection list is forgotten on the spot: it
/// withholds nothing and needs no release.
pub fn locate(&mut self, uri: &Uri, doc: &Document) {
let Some(edit) = self.edits.get_mut(uri) else { return };
if !matches!(edit.state, Located::Pending) {
return;
}
match entry_around(doc, edit.offset) {
Some(entry) => edit.state = Located::Entry(entry),
None => {
self.edits.remove(uri);
}
}
}
/// `diagnostics` without the ones whose range starts inside the entry
/// `uri`'s last edit is in. Everything, when there is no such entry.
pub fn withhold(
&self,
uri: &Uri,
doc: &Document,
diagnostics: Vec<Diagnostic>,
) -> Vec<Diagnostic> {
let Some(entry) = self.entry_of(uri) else { return diagnostics };
let positions = doc.positions();
diagnostics
.into_iter()
.filter(|d| !inside(entry, positions.offset(d.range.start)))
.collect()
}
/// The entry `uri`'s last edit is in, while it is withholding.
pub fn entry_of(&self, uri: &Uri) -> Option<TextRange> {
match self.edits.get(uri)?.state {
Located::Entry(entry) => Some(entry),
Located::Pending => None,
}
}
/// Drop a buffer's edit — it was saved, closed or opened afresh — and say
/// whether it was withholding anything, i.e. whether its full list is
/// owed now.
pub fn forget(&mut self, uri: &Uri) -> bool {
matches!(self.edits.remove(uri), Some(LastEdit { state: Located::Entry(_), .. }))
}
/// When the next release is due: the end of the earliest quiet period,
/// or right away for an entry an edit elsewhere released.
pub fn deadline(&self) -> Option<Instant> {
self.edits.values().filter_map(LastEdit::due_at).min()
}
/// Take every buffer whose release is due at `now`: their full lists are
/// owed to the client.
pub fn due(&mut self, now: Instant) -> Vec<Uri> {
let due: Vec<Uri> = self
.edits
.iter()
.filter(|(_, edit)| edit.due_at().is_some_and(|at| at <= now))
.map(|(uri, _)| uri.clone())
.collect();
for uri in &due {
self.edits.remove(uri);
}
due
}
}
impl LastEdit {
/// When this edit's entry is to be released; `None` while it has no
/// entry yet.
fn due_at(&self) -> Option<Instant> {
if !matches!(self.state, Located::Entry(_)) {
return None;
}
if self.released {
return Some(self.at);
}
Some(self.at.checked_add(PORT_ENTRY_GRACE).unwrap_or(self.at))
}
}
/// Whether `offset` lies in `entry`, both ends included: a diagnostic on the
/// token that ends the entry (the `,` of `.b(y),)`, the `.` that proves a
/// comma missing) is the entry's own news.
fn inside(entry: TextRange, offset: u32) -> bool {
entry.start <= offset && offset <= entry.end
}
/// The extent of the connection-list entry around `offset`, or `None` when
/// `offset` is not inside an instantiation's port or parameter list.
///
/// The entry starts at the last separator before `offset` at the list's own
/// level — a `,`, which it includes, or the list's `(`, which it does not —
/// or at a `.` that opens its own line, which is where the parser ends an
/// entry left open on the line above. It ends at the first `,`, `;` or
/// closing bracket after `offset` at the level `offset` is at, or at the end
/// of `offset`'s line — reaching on to the next line's first token when that
/// is a `.`, the token that proves a `,` is missing. A `;` ends it at any
/// level: no connection list holds one.
pub fn entry_around(doc: &Document, offset: u32) -> Option<TextRange> {
let tokens = &doc.tokens;
let list = enclosing_list(tokens, offset)?;
let next = tokens.partition_point(|t| t.span.start < offset);
// The bracket count above takes a value left open (`.po(`) for the list
// never closing, so a list "around" an edit three items further down is
// only believed when no `;` stands between them: a connection list never
// holds one, and every item after it ends in one.
if tokens.get(list.open + 1..next)?.iter().any(|t| t.is_sym(";")) {
return None;
}
// Only an instance's *named* list: `enclosing_list` also accepts a
// header's `name #(`, a positional list, a call after a block label and a
// function whose return type is a name, and none of those is typed the
// way a `.name(…)` connection is.
if !holds_a_named_entry(tokens, list.open) || in_a_declaration_header(tokens, list.open) {
return None;
}
let (start, depth) = entry_start(tokens, list.open, next);
let (line, _) = doc.line_index.line_col(offset);
let end = entry_end(&tokens[next..], depth, offset, line);
Some(TextRange::new(start, end.max(start)))
}
/// Walk from the list's `(` up to the token at `next`: where the entry there
/// starts, and how many brackets are open inside it at that point.
fn entry_start(tokens: &[Token], open: usize, next: usize) -> (u32, u32) {
let mut start = tokens[open].span.end;
let mut depth = 0u32;
for i in open + 1..next {
let t = &tokens[i];
if t.is_sym(".") && tokens[i - 1].line != t.line {
// A `.` opening its line starts an entry even inside a bracket:
// the parser ends a value left open on the line above here.
start = t.span.start;
depth = 0;
} else if is_open(t) {
depth += 1;
} else if is_close(t) {
depth = depth.saturating_sub(1);
} else if depth == 0 && t.is_sym(",") {
start = t.span.start;
}
}
(start, depth)
}
/// Walk on from `offset` (`after` being the tokens from there on, `depth`
/// the brackets open inside the entry, `line` 1-based): where the entry ends.
fn entry_end(after: &[Token], mut depth: u32, offset: u32, line: u32) -> u32 {
let mut end = offset;
for t in after {
if t.kind == TokenKind::Eof {
break;
}
if t.line != line {
return if t.is_sym(".") { t.span.start } else { end };
}
if is_close(t) {
if depth == 0 {
return t.span.start;
}
depth -= 1;
} else if is_open(t) {
depth += 1;
} else if t.is_sym(";") || (depth == 0 && t.is_sym(",")) {
return t.span.start;
}
end = t.span.end;
}
end
}
/// The keywords whose header lists (`name #(`, `name (`) are declarations,
/// never an instance's connections.
const DECLARATION_HEADERS: &[&str] = &[
"module",
"macromodule",
"interface",
"program",
"class",
"package",
"primitive",
"function",
"task",
"checker",
];
/// Whether the list opened at `open` holds an entry, at its own level, that
/// starts with `.` — the entry being typed counts. A `.` opening its own line
/// counts at any depth, as it does for [`entry_start`]: the parser ends a
/// value left open on the line above there. The walk ends at the list's `)`,
/// a `;`, or the end of the file.
fn holds_a_named_entry(tokens: &[Token], open: usize) -> bool {
let mut depth = 0u32;
for i in open + 1..tokens.len() {
let t = &tokens[i];
let prev = &tokens[i - 1];
if t.kind == TokenKind::Eof || t.is_sym(";") {
return false;
}
if t.is_sym(".") {
let entry_start = i == open + 1
|| prev.line != t.line
|| (depth == 0 && (prev.is_sym(",") || prev.kind == TokenKind::Attribute));
if entry_start {
return true;
}
} else if is_open(t) {
depth += 1;
} else if is_close(t) {
if depth == 0 {
return false;
}
depth -= 1;
}
}
false
}
/// Whether the list opened at `open` belongs to a declaration's header: a
/// [`DECLARATION_HEADERS`] keyword stands between it and the `;` that ended
/// the item before.
fn in_a_declaration_header(tokens: &[Token], open: usize) -> bool {
tokens[..open]
.iter()
.rev()
.take_while(|t| !t.is_sym(";"))
.any(|t| t.kind == TokenKind::Keyword && DECLARATION_HEADERS.contains(&t.text.as_str()))
}
/// True on `(`, `[` or `{`.
fn is_open(t: &Token) -> bool {
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
}
/// True on `)`, `]` or `}`.
fn is_close(t: &Token) -> bool {
t.is_sym(")") || t.is_sym("]") || t.is_sym("}")
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,350 @@
//! The entry bounds, the withhold/release state machine with time injected,
//! and what the parser's half buys the editor: the tokens and the findings
//! after an unfinished entry are those of the completed one.
use std::str::FromStr;
use lsp_types::{DiagnosticSeverity, SemanticToken};
use super::*;
use crate::state::Workspace;
fn uri(name: &str) -> Uri {
Uri::from_str(&format!("file:///rtl/{name}")).expect("uri")
}
/// A workspace holding `text` as `m.sv`.
fn open(text: &str) -> (Workspace, Uri) {
let uri = uri("m.sv");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
(ws, uri)
}
/// `text` with the `|` marking the cursor taken out, and the cursor's offset.
fn cursor(marked: &str) -> (String, u32) {
let at = marked.find('|').expect("a `|` marks the cursor");
(marked.replacen('|', "", 1), at as u32)
}
/// The text of the entry around the `|` in `marked`, or `None`.
fn entry_text(marked: &str) -> Option<String> {
let (text, at) = cursor(marked);
let (ws, uri) = open(&text);
let doc = ws.document(&uri).expect("open");
entry_around(doc, at).map(|r| text[r.as_range()].to_string())
}
// ----------------------------------------------------------------------
// Entry bounds
// ----------------------------------------------------------------------
#[test]
fn the_entry_runs_from_the_comma_before_to_the_close_after() {
let got = entry_text("module m;\n sub u0 (.a(x), .p|);\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .p"));
let got = entry_text("module m;\n sub u0 (.p|, .a(x));\nendmodule\n");
assert_eq!(got.as_deref(), Some(".p"), "the list's own `(` is not the entry's");
}
#[test]
fn a_cursor_inside_a_value_takes_the_whole_entry() {
let got = entry_text("module m;\n sub u0 (.a(x), .b(y|), .c(z));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .b(y)"));
let got = entry_text("module m;\n sub u0 (.a(x), .b({p, q|}), .c(z));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .b({p, q})"), "a `,` inside a bracket is the value's");
}
#[test]
fn an_entry_left_open_ends_with_its_line_and_reaches_the_next_dot() {
// The parser's diagnostic is on the `(`; the next line opens a new entry,
// whose `.` the entry reaches to.
let got = entry_text("module m;\n sub u0 (.a(x), .po(|\n .b(y));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .po(\n "));
// Typing on the line below an entry left open: the entry is that line's.
let got = entry_text("module m;\n sub u0 (.a(x), .po(\n .b(y|));\nendmodule\n");
assert_eq!(got.as_deref(), Some(".b(y)"));
}
#[test]
fn a_missing_comma_is_inside_the_entry_typed_on_either_side_of_it() {
// Typed below: the entry starts at its own line's `.`, which is where the
// parser reports the missing `,`.
let got = entry_text("module m;\n sub u0 (.a(x)\n .b(y|));\nendmodule\n");
assert_eq!(got.as_deref(), Some(".b(y)"));
// Typed above: the entry reaches the next line's `.`.
let got = entry_text("module m;\n sub u0 (.a(x), .po|\n .b(y));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .po\n "));
}
#[test]
fn a_trailing_comma_is_inside_the_entry_after_it() {
let got = entry_text("module m;\n sub u0 (.a(x),|\n );\nendmodule\n");
assert_eq!(got.as_deref(), Some(","));
}
#[test]
fn a_parameter_list_has_entries_too() {
let got = entry_text("module m;\n sub #(.W(8), .D|) u0 (.a(x));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .D"));
let got = entry_text("module m;\n sub #(.W(|\n u0 (.a(x));\nendmodule\n");
assert_eq!(got.as_deref(), Some(".W("), "an override typed open");
}
/// The entry being typed is enough to make a list a named one, and so is
/// any other named entry when the one being typed is still empty.
#[test]
fn a_named_list_is_recognised_from_any_named_entry() {
let got = entry_text("module m;\n sub u0 (.po|);\nendmodule\n");
assert_eq!(got.as_deref(), Some(".po"));
let got = entry_text("module m;\n sub u0 (.|);\nendmodule\n");
assert_eq!(got.as_deref(), Some("."));
let got = entry_text("module m;\n sub u0 (.a(x), |);\nendmodule\n");
assert_eq!(got.as_deref(), Some(", "), "a fresh entry after a `,`");
}
/// QA's list (2026-11-17): every list `enclosing_list` accepts that is not
/// an instance's named list withholds nothing.
#[test]
fn lists_that_are_not_named_connections_withhold_nothing() {
for marked in [
// A module header's parameter list.
"module hm #(parameter W = |) (input logic a);\nendmodule\n",
"interface hi #(parameter W = 1|);\nendinterface\n",
"class hc #(type T = int|);\nendclass\n",
// A positional instance list.
"module m;\n sub u0 (x, y|, z);\nendmodule\n",
// A function declaration with a user-type return.
"module m;\n function automatic my_t f(input a|);\n endfunction\nendmodule\n",
// A call right after a block label.
"module m;\n initial begin : blk\n my_task(a, b|);\n end\nendmodule\n",
// A fresh, still empty instance list: nothing named in it yet.
"module m;\n sub u0 (|);\nendmodule\n",
] {
assert_eq!(entry_text(marked), None, "{marked}");
}
}
#[test]
fn nothing_outside_a_connection_list_is_an_entry() {
for marked in [
"module m;\n wire w|;\nendmodule\n",
"module m;\n sub u0| (.a(x));\nendmodule\n",
"module m;\n sub u0 (.a(x));|\nendmodule\n",
"module m;\n initial f(a, b|);\nendmodule\n",
"module m (input a|, input b);\nendmodule\n",
// A value left open makes the list's bracket look unclosed to the
// end of the file; the `;` after it says the list is over.
"module m;\n sub u0 (.a(x), .po(\n .b(y));\n wire w|;\nendmodule\n",
] {
assert_eq!(entry_text(marked), None, "{marked}");
}
// The next instance's own list is still found, and is its own.
let marked = "module m;\n sub u0 (.a(x), .po(\n .b(y));\n sub u1 (.c|(z));\nendmodule\n";
assert_eq!(entry_text(marked).as_deref(), Some(".c(z)"));
}
// ----------------------------------------------------------------------
// Withholding
// ----------------------------------------------------------------------
/// A module whose port list is fine, so only the instance's entries say
/// anything, plus one unrelated parse error far from the list.
const TYPING: &str =
"module m;\n logic x, y;\n sub u0 (.a(x),\n .po(\n .b(y));\n wire ;\nendmodule\n";
#[test]
fn only_the_entry_being_typed_is_withheld() {
let (mut ws, uri) = open(TYPING);
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
let now = Instant::now();
ws.port_grace_mut().edited(&uri, Some(at), now);
ws.locate_port_entry(&uri);
let doc = ws.document(&uri).expect("open");
let all = crate::diagnostics::all(doc);
let errors: Vec<_> =
all.iter().filter(|d| d.severity == Some(DiagnosticSeverity::ERROR)).collect();
assert_eq!(errors.len(), 2, "the open `(` and the `wire ;`: {all:#?}");
let shown = ws.port_grace().withhold(&uri, doc, all.clone());
assert_eq!(shown.len(), all.len() - 1, "exactly the entry's one: {shown:#?}");
assert!(shown.iter().any(|d| d.range.start.line == 5), "the `wire ;` is still said");
assert!(shown.iter().all(|d| d.range.start.line != 3), "{shown:#?}");
}
#[test]
fn an_edit_outside_every_list_withholds_nothing() {
let (mut ws, uri) = open(TYPING);
let at = TYPING.find("wire ;").expect("wire") as u32 + 4;
ws.port_grace_mut().edited(&uri, Some(at), Instant::now());
ws.locate_port_entry(&uri);
let doc = ws.document(&uri).expect("open");
let all = crate::diagnostics::all(doc);
assert_eq!(ws.port_grace().withhold(&uri, doc, all.clone()), all);
assert_eq!(ws.port_grace().deadline(), None, "no release is owed");
}
#[test]
fn a_whole_document_change_withholds_nothing() {
let (mut ws, uri) = open(TYPING);
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
ws.port_grace_mut().edited(&uri, Some(at), Instant::now());
ws.port_grace_mut().edited(&uri, None, Instant::now());
ws.locate_port_entry(&uri);
assert_eq!(ws.port_grace().entry_of(&uri), None);
}
// ----------------------------------------------------------------------
// The release, with time injected
// ----------------------------------------------------------------------
/// A grace with one located entry in `uri`, edited at `t0`.
fn held(ws: &mut Workspace, uri: &Uri, t0: Instant) {
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
ws.port_grace_mut().edited(uri, Some(at), t0);
ws.locate_port_entry(uri);
assert!(ws.port_grace().entry_of(uri).is_some(), "premise: the edit is in an entry");
}
#[test]
fn the_entry_is_released_when_the_quiet_period_ends() {
let (mut ws, uri) = open(TYPING);
let t0 = Instant::now();
held(&mut ws, &uri, t0);
assert_eq!(ws.port_grace().deadline(), Some(t0 + PORT_ENTRY_GRACE));
let almost = t0 + PORT_ENTRY_GRACE - Duration::from_millis(1);
assert!(ws.port_grace_mut().due(almost).is_empty(), "not a moment early");
assert_eq!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE), vec![uri.clone()]);
assert_eq!(ws.port_grace().entry_of(&uri), None, "released means withholding nothing");
assert_eq!(ws.port_grace().deadline(), None);
}
#[test]
fn another_edit_restarts_the_quiet_period() {
let (mut ws, uri) = open(TYPING);
let t0 = Instant::now();
held(&mut ws, &uri, t0);
let t1 = t0 + Duration::from_millis(1000);
held(&mut ws, &uri, t1);
assert!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE).is_empty());
assert_eq!(ws.port_grace_mut().due(t1 + PORT_ENTRY_GRACE), vec![uri]);
}
#[test]
fn an_unanalyzed_edit_is_not_due() {
let (mut ws, uri) = open(TYPING);
let t0 = Instant::now();
ws.port_grace_mut().edited(&uri, Some(3), t0);
assert_eq!(ws.port_grace().deadline(), None, "pending: the flush has not looked yet");
assert!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE).is_empty());
}
#[test]
fn an_edit_in_another_buffer_releases_at_once() {
let (mut ws, a) = open(TYPING);
let b = uri("other.sv");
let t0 = Instant::now();
held(&mut ws, &a, t0);
let t1 = t0 + Duration::from_millis(100);
ws.port_grace_mut().edited(&b, Some(0), t1);
assert_eq!(ws.port_grace().deadline(), Some(t0), "due already");
assert_eq!(ws.port_grace_mut().due(t1), vec![a]);
}
#[test]
fn forgetting_says_whether_anything_was_held() {
let (mut ws, uri) = open(TYPING);
assert!(!ws.port_grace_mut().forget(&uri), "nothing to forget");
ws.port_grace_mut().edited(&uri, Some(3), Instant::now());
assert!(!ws.port_grace_mut().forget(&uri), "pending withholds nothing");
held(&mut ws, &uri, Instant::now());
assert!(ws.port_grace_mut().forget(&uri));
assert_eq!(ws.port_grace().entry_of(&uri), None);
}
// ----------------------------------------------------------------------
// The parser's half, as the editor sees it
// ----------------------------------------------------------------------
/// The module `sub` and an instance of it with `entry` as its second
/// connection, on a line of its own (line 4, 0-based), then more after it.
fn with_entry(entry: &str) -> String {
format!(
"module sub (input logic a, input logic po, output logic b);\nendmodule\n\
module m;\n logic x, y;\n sub u0 (.a(x),\n {entry}\n .b(y));\n \
assign x = y;\n sub u1 (.a(y), .po(x), .b());\nendmodule\n"
)
}
/// Semantic tokens as absolute `(line, start, length, type, modifiers)`.
fn absolute(tokens: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> {
let (mut line, mut start) = (0u32, 0u32);
tokens
.iter()
.map(|t| {
if t.delta_line > 0 {
start = 0;
}
line += t.delta_line;
start += t.delta_start;
(line, start, t.length, t.token_type, t.token_modifiers_bitset)
})
.collect()
}
/// What the editor shows after the entry's line: the semantic tokens and the
/// diagnostics, the latter as `(line, character, message)`.
type After = (Vec<(u32, u32, u32, u32, u32)>, Vec<(u32, u32, String)>);
fn after_entry(text: &str) -> After {
let (ws, uri) = open(text);
let doc = ws.document(&uri).expect("open");
let entry_line = 5;
let tokens = absolute(&crate::tokens::semantic_tokens(doc))
.into_iter()
.filter(|t| t.0 > entry_line)
.collect();
let diags = crate::diagnostics::all(doc)
.into_iter()
.filter(|d| d.range.start.line > entry_line)
.map(|d| (d.range.start.line, d.range.start.character, d.message))
.collect();
(tokens, diags)
}
/// The owner's ask: the rest of the file colours and lints as the
/// auto-completed version (`.po` → `.po()`) would.
#[test]
fn after_an_unfinished_entry_the_file_reads_as_with_the_entry_completed() {
// An entry the parser had to recover reads on to the next `.` as though
// its `,` had been typed too.
let done = after_entry(&with_entry(".po(),"));
assert!(!done.0.is_empty(), "premise: there are tokens after the entry");
assert!(done.1.is_empty(), "premise: the completed file says nothing: {:?}", done.1);
for unfinished in [".po(", ".", ".po(x"] {
assert_eq!(after_entry(&with_entry(unfinished)), done, "after `{unfinished}`");
}
// `.po` is already a whole (implicit) connection; what it still lacks is
// the `,`, and so does its completion — the same one diagnostic, on the
// `.` of the line after, in both.
let done = after_entry(&with_entry(".po()"));
assert_eq!(done.1.len(), 1, "{:?}", done.1);
for unfinished in [".po", ".p"] {
assert_eq!(after_entry(&with_entry(unfinished)), done, "after `{unfinished}`");
}
}
/// The unfinished entry is one parse error and nothing else: the entries
/// written after it still resolve, so nothing about them is reported.
#[test]
fn an_unfinished_entry_costs_one_error_and_no_cascade() {
for unfinished in [".po(", "."] {
let (ws, uri) = open(&with_entry(unfinished));
let doc = ws.document(&uri).expect("open");
let errors: Vec<_> = crate::diagnostics::all(doc)
.into_iter()
.filter(|d| d.severity == Some(DiagnosticSeverity::ERROR))
.collect();
assert_eq!(errors.len(), 1, "`{unfinished}`: {errors:#?}");
assert_eq!(errors[0].range.start.line, 5, "on the entry's own line");
}
}
+758
View File
@@ -0,0 +1,758 @@
//! Driving a scan, whole or widen, from its work list to the landed
//! tables: `begin_scan`/`begin_widen` take the list, `scan_step` indexes
//! one file, `publish_scan` makes the tables answer for what has been
//! staged so far, and `finish_scan` lands them. The one-shot forms the
//! tests use are at the end.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_semantic::FileFacts;
use super::discover::oversize;
use super::scan::{self, Analyzed, IndexEvent, Scan, ScanKind};
use super::{StoreOpen, Workspace};
use crate::candidates::Candidates;
use crate::includes::{self, IncludeGraph};
use crate::index_cache::IndexCache;
use crate::scan_order::{self, WorkList};
use crate::scan_trace::{CacheWork, ScanTrace};
#[cfg(test)]
use crate::settings::IndexScope;
impl Workspace {
/// Take the work list one scan will run through: resolve the scope and put
/// the user's own neighbourhood at the front of it.
///
/// **No file's text is read here** — only the open buffers', which are in
/// memory already. Everything else is read at the step that indexes it
/// ([`Workspace::scan_step`]), so the first file can be indexed as soon as
/// the walk is done rather than after the whole scope has been read.
///
/// Nothing is indexed here and the live index is untouched, so a scan that
/// is never stepped changes nothing but the view cache and the open cache
/// handle.
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent), trace: bool) -> Scan {
let mut trace = ScanTrace::opened(&mut self.scans, trace, "whole");
// A rescan says nothing about *which* file moved, so nothing held from
// before it can be trusted.
self.views.borrow_mut().clear();
let discovering = trace.now();
let mut skipped = 0usize;
// The cap's skips are reported by `collect_sources` and counted here,
// because the end message names them and the scan is what owns that
// number now.
let mut counting = |event: IndexEvent<'_>, skipped: &mut usize| {
if matches!(event, IndexEvent::Skipped { .. }) {
*skipped += 1;
}
watch(event);
};
let (mut scope, pending) = {
let mut count = |event: IndexEvent<'_>| counting(event, &mut skipped);
self.first_scope(&mut count, &mut trace)
};
ScanTrace::add(&mut trace.discovery_ms, discovering);
let buffered = std::mem::take(&mut scope.buffered);
let analyzed = std::mem::take(&mut scope.analyzed);
let ordering = trace.now();
// The same list the index will be built from, with the user's own
// neighbourhood moved to the front of it.
let WorkList { files: work, head } = self.open_first(std::mem::take(&mut scope.files));
// A scan that has not walked the whole workspace yet cannot ask
// whether its head is a minority of it — the count that would answer
// is the walk it is postponing. `splits_discovery` is what bounds the
// head instead, and it refuses exactly the case `worth_waiting`
// refuses: a buffer whose folder is the workspace.
let head = match pending.is_some() {
true => head,
false => scan_order::worth_waiting(head, work.len()),
};
let paths = work.clone();
ScanTrace::add(&mut trace.order_ms, ordering);
// Re-opened rather than held across rescans: the directory it belongs
// in depends on settings that arrive after startup, and a second
// session over the same workspace may have written records this one
// has not seen. **Deferred** to the first file that asks the store
// anything ([`StoreOpen`]), so a scan with no files reads nothing.
self.store = StoreOpen::Deferred(self.cache_dir());
trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work());
Scan {
kind: ScanKind::Whole,
work,
head,
buffered,
includes: HashMap::new(),
unread: Vec::new(),
paths,
gone: Vec::new(),
analyzed,
incdirs: scope.incdirs,
warnings: scope.warnings,
at: 0,
pending,
staged: Vec::new(),
staged_at: Vec::new(),
words: HashMap::new(),
skipped,
cached: 0,
trace,
}
}
/// Take the work list for a **scope widen**: the files `added` brings into
/// scope that the index does not already hold, plus every open buffer's own
/// analysis.
///
/// The cheap answer to a `didOpen` in a folder the scope had not reached.
/// A whole rescan re-reads, re-hashes and re-merges every file already
/// indexed to learn about a handful of new ones; this reads only the new
/// ones, and [`Workspace::finish_scan`] folds them in beside what is
/// already there. What comes out is the index, the completion tables and
/// the include graph a whole rescan would have produced — **given that the
/// disk files already indexed have not changed since they were indexed**,
/// which is the file watcher's job and is written down in
/// `docs/features/index-scope/README.md`.
///
/// Two halves make that equivalence hold, and both are why this is not
/// simply "index the new files":
///
/// * **every open buffer is re-indexed from the analysis it holds**, so a
/// buffer carrying unsaved edits contributes those edits exactly as a
/// whole rescan's `collect_sources` overlay would. That costs a fact walk
/// and a word set per open buffer (~5 ms for a 1.4 MB buffer, rescan-reuse
/// round) and no parse at all.
/// * **a buffer on the large-file fast path contributes nothing**, so a
/// file the index holds whose buffer has grown past the threshold is
/// taken back out — the one thing a widen removes, and the same rule
/// `collect_sources` follows.
///
/// `added` is the directories that entered [`Workspace::scope_dirs`]; the
/// caller decides that they really are an addition and nothing else
/// (`server.rs`'s `widen_of`).
pub fn begin_widen(
&mut self,
added: &[PathBuf],
watch: &mut dyn FnMut(IndexEvent),
trace: bool,
) -> Scan {
let mut trace = ScanTrace::opened(&mut self.scans, trace, "widen");
let discovering = trace.now();
let held: HashSet<PathBuf> = self.index.files().iter().cloned().collect();
let cap = self.client.max_file_size;
let spoken_for: HashSet<&Path> =
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
let mut skipped = 0usize;
let mut files: Vec<PathBuf> = Vec::new();
let mut warnings: Vec<String> = Vec::new();
// The walk of the *added* directories alone, by the same rung-3 rules
// `folder_files` follows — the whole scope is the union of these walks,
// so the files this one finds beyond what is already indexed are
// exactly the ones the widen owes.
let mut stats = 0usize;
for found in self.widened_files(added, &mut |w| warnings.push(w), &mut trace) {
let path = found.path.clone();
// Already indexed: by another scope directory this walk overlaps,
// or by an earlier scan. Re-reading it is the cost this path
// exists to avoid.
if held.contains(&path) {
continue;
}
if let Some(size) = oversize(&found, cap, &mut stats) {
watch(IndexEvent::Skipped { path: &path, size, cap });
skipped += 1;
continue;
}
if spoken_for.contains(path.as_path()) {
continue;
}
files.push(path);
}
let mut analyzed = Analyzed::default();
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
let mut gone: Vec<PathBuf> = Vec::new();
for doc in self.docs.values() {
let Some(path) = doc.path.clone() else { continue };
files.retain(|taken| taken != &path);
if doc.large {
if held.contains(&path) {
gone.push(path);
}
continue;
}
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
analyzed.words.insert(path.clone(), doc.words());
buffered.insert(path.clone(), doc.text.clone());
files.push(path);
}
ScanTrace::add(&mut trace.discovery_ms, discovering);
let ordering = trace.now();
let WorkList { files: work, head } = self.open_first(files);
let head = scan_order::worth_waiting(head, work.len());
ScanTrace::add(&mut trace.order_ms, ordering);
trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work());
// A whole scan drops the view cache entire, because a rescan claims
// nothing about *which* file moved. A widen names exactly the files it
// is reading, so it drops exactly those — which keeps the cache's own
// rule ("every way a file's text can move drops its entry",
// [`Workspace::file_view`]) literally true rather than nearly so.
for path in &work {
self.views.borrow_mut().retain(|view| &view.path != path);
}
// Which files exist once this widen lands: what the index holds, less
// what it is about to lose, plus what the widen brings in.
let mut paths: Vec<PathBuf> =
held.into_iter().filter(|path| !gone.contains(path)).collect();
paths.extend(work.iter().cloned());
paths.sort();
paths.dedup();
gone.sort();
Scan {
kind: ScanKind::Widen,
work,
head,
buffered,
includes: HashMap::new(),
unread: Vec::new(),
paths,
gone,
analyzed,
// Rung 3 is the only rung an open buffer can widen, and it names no
// `+incdir+`. Carried from the graph in hand rather than assumed
// empty, so folding a widen in never *changes* the search path.
incdirs: self.includes.incdirs().to_vec(),
// A widen resolves no filelist — rung 1 is not a scope an open
// buffer can widen — so the only warnings here are the walk's own.
warnings,
at: 0,
// A widen names the directories it is about to walk, so there is
// never anything left to discover.
pending: None,
staged: Vec::new(),
staged_at: Vec::new(),
words: HashMap::new(),
skipped,
cached: 0,
trace,
}
}
/// Walk the rest of the workspace, once the user's own neighbourhood has
/// been indexed and published — the second half of a split discovery
/// ([`PendingDiscovery`]). Reports whether there was anything to walk.
///
/// **Its own step, indexing nothing.** The step it shares a call with
/// would otherwise report a file against a denominator that grew inside
/// the same call, and a bar whose percentage falls is worse than one that
/// waits (`docs/features/indexing-ux/README.md`). So this discovers, says
/// "there is more", and lets the next step be an ordinary one.
fn discover_the_rest(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
let Some(mut pending) = scan.take_pending() else { return false };
let discovering = scan.trace.now();
let mut skipped = 0usize;
let (files, warnings, walked_skips) = {
let mut counting = |event: IndexEvent<'_>| {
if matches!(event, IndexEvent::Skipped { .. }) {
skipped += 1;
}
watch(event);
};
self.rest_of_scope(&mut pending, &mut counting, &mut scan.trace)
};
debug_assert_eq!(skipped, walked_skips, "the cap reports every skip it counts");
ScanTrace::add(&mut scan.trace.discovery_ms, discovering);
scan.land_discovery(files, warnings, walked_skips, pending.tracker.has_conflict());
scan.trace.measure_work(
scan.work.len(),
held_bytes(&scan.buffered),
scan.skipped,
scan.trace.cache,
);
true
}
/// Open the store a whole rescan asked for, if this is the first thing to
/// need it ([`StoreOpen`]).
///
/// Called from the two places that ask the store anything — a scan's step
/// and a save's write-through — so a rescan that reaches no file never
/// reads it, and the widen behind that rescan still finds it open the
/// moment it reaches one.
pub(super) fn open_store(&mut self, trace: &mut ScanTrace) {
let StoreOpen::Deferred(dir) = std::mem::replace(&mut self.store, StoreOpen::Done) else {
return;
};
let opening = trace.now();
self.cache = IndexCache::open(dir);
ScanTrace::add(&mut trace.cache_open_ms, opening);
// The counters this scan is charged for start where the store it has
// just opened does. A scan that never opens one keeps the baseline
// `measure_work` took, so its delta is the nothing it did.
trace.cache = CacheWork::default();
}
/// Index the next file of `scan`, reporting whether there was one.
///
/// One file is the whole step: **its text is read**, its record is taken —
/// from the open buffer's own analysis, from the persistent cache, or from
/// a parse — its `` `include``s are scanned off that text and its
/// completion words are taken off the record. All three are *staged* on
/// the scan rather than merged, because merging is a pass over the whole
/// workspace and one per file would be quadratic
/// ([`WorkspaceIndex::absorb`]).
///
/// **The text is read here and dropped here** (2026-09-08). Everything the
/// scan will ever want from it — the content hash the store is keyed by,
/// the parse, the include lines — is taken in this one step, so a whole
/// scan reads each file's bytes exactly once and holds one file's text at
/// a time rather than the whole scope's. An **open buffer's** text is not
/// read: it was taken with the work list, beside the analysis that
/// describes the same bytes, so a `didChange` mid-scan cannot make the two
/// disagree. A file that cannot be read is remembered as `unread` and
/// contributes nothing, which is what a file `collect_sources` could not
/// read used to do before the work list existed.
pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
let (done, total) = (scan.at, scan.work.len());
if done == total {
return self.discover_the_rest(scan, watch);
}
scan.at += 1;
// The first file of a scan is the first thing to ask the store
// anything, so it is where the store this scan asked for is opened.
self.open_store(&mut scan.trace);
let path = scan.work[done].clone();
let Some(source) = scan.take_text(&path) else {
scan.unread.push(path);
return true;
};
let text = source.as_str();
let held = scan.analyzed.facts.remove(&path);
let known_words = scan.analyzed.words.remove(&path);
let facts = match held {
// An open buffer's own finished analysis comes first. It is the
// only source of facts that is right when the buffer has unsaved
// edits, which is precisely when the content-keyed cache below has
// nothing to offer. The record is written through all the same, so
// the next session starts from it.
Some(facts) => {
watch(IndexEvent::Analyzed { done, total, path: &path });
scan.trace.buffers += 1;
self.cache.record(&facts, text);
facts
}
// The cache answers for the exact bytes about to be indexed, so a
// hit is the parse and not a guess at it. A miss — a new file, a
// changed one, a record this version cannot read — parses, and
// the result is written through immediately, which is what makes
// an interrupted scan resumable.
None => match self.cache.facts_for(&path, text) {
Some(facts) => {
scan.cached += 1;
watch(IndexEvent::Cached { done, total, path: &path });
facts
}
None => {
watch(IndexEvent::Parsing { done, total, path: &path });
let parsing = scan.trace.now();
let facts = FileFacts::of(path.clone(), text);
ScanTrace::add(&mut scan.trace.parse_ms, parsing);
scan.trace.parse_bytes += text.len();
self.cache.record(&facts, text);
facts
}
},
};
// Read off the record rather than lexed here: since `FACTS_FORMAT` 13
// a file's identifier census *is* one of its facts, so a cached hit
// brings its words with it and a parse harvested them from the tokens
// it already had. That retires the per-file re-lex a scan used to pay
// for the completion word table (TODO §10's deferred item;
// `docs/features/semantic-lints-on/README.md` has the measurement).
// An open buffer's words are still the caller's, read off the tokens
// it was analyzed from.
let words = known_words.unwrap_or_else(|| facts.words().to_vec());
// Scanned here, off the text this step read, because the include graph
// is built when the scan ends and by then the text is gone. It is a
// line scan over bytes already in cache, and it replaces the identical
// scan `IncludeGraph::build` used to run over the same text later.
scan.includes.insert(path.clone(), includes::scan(text));
scan.words.insert(path, words);
scan.staged.push(facts);
scan.staged_at.push(done);
true
}
/// The work list in the order a scan walks it: the open buffers' own
/// files, then the rest of the folders those buffers raise to, then
/// everything else in path order ([`crate::scan_order`]).
///
/// **A reporting and latency decision and nothing else.**
/// `vlog_semantic::IndexBuilder` sorts by path inside `finish` since
/// 2026-08-27, so no insertion order can reach the index: this changes
/// which file the progress bar names first — the user's own, and then
/// what they are looking at across the folder — and changes nothing about
/// the result. Pinned both ends: the builder's own
/// `no_insertion_order_can_change_what_the_builder_produces`, and
/// `the_open_files_are_indexed_first_and_the_index_cannot_tell` here.
/// Re-order what is left of `scan` around the buffers open **now** — the
/// same ranking [`Workspace::begin_scan`] applied, re-applied because a
/// `didOpen` answered mid-scan changed the answer to "where is the user
/// working?".
///
/// Called after the burst carrying that `didOpen` has been applied, so the
/// buffer is installed and the folder it raises to is known. What was
/// already indexed is untouched; only the tail moves, and the finished
/// index cannot tell ([`Scan::reorder`]).
/// **The rest of the workspace is walked first when it has not been.** A
/// split startup is leading with the folder the user *was* in; a `didOpen`
/// says they are somewhere else now, and re-ordering a work list that does
/// not yet contain the new folder would answer the request behind that
/// `didOpen` off a prefix that cannot hold what it is asking about. The
/// walk this order postpones is exactly what makes the new folder
/// nameable, so it happens here
/// (`docs/features/perf5r-first-answer/README.md`).
pub fn open_next(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) {
self.discover_the_rest(scan, watch);
let ordered = self.open_first(scan.remaining());
scan.reorder(ordered);
}
fn open_first(&self, files: Vec<PathBuf>) -> WorkList {
let open: Vec<PathBuf> = self.docs.values().filter_map(|doc| doc.path.clone()).collect();
scan_order::work_list(files, &open, &self.raised_dirs())
}
/// Make every table answer for the files `scan` has taken since the last
/// publish — the moment a mid-scan answer is worth paying a merge for.
///
/// **All three tables together, never one of them.** The index, the
/// completion tables and the include graph are what an answer reads, and a
/// hover that saw a scanned file while a completion or an include link
/// could not would make "the workspace as far as it has been scanned"
/// three different things at once. Each is folded in with the batch form
/// of the incremental update it already had, so one publish is one pass
/// over the index and not one per file.
pub fn publish_scan(&mut self, scan: &mut Scan) {
if scan.staged.is_empty() {
return;
}
let taken = std::mem::take(&mut scan.staged_at);
let absorbing = scan.trace.now();
self.index.absorb(std::mem::take(&mut scan.staged), &[]);
ScanTrace::add(&mut scan.trace.publish_absorb_ms, absorbing);
let completing = scan.trace.now();
let published: Vec<PathBuf> = taken.iter().map(|&at| scan.work[at].clone()).collect();
let words = published
.iter()
.map(|path| (path.clone(), scan.words.get(path).cloned().unwrap_or_default()))
.collect();
self.candidates.absorb(&self.index, words);
ScanTrace::add(&mut scan.trace.publish_candidates_ms, completing);
let including = scan.trace.now();
let found = scan::included(&scan.includes, &published);
self.includes.absorb_includes(&scan.incdirs, &scan.paths, &found);
ScanTrace::add(&mut scan.trace.publish_includes_ms, including);
let refreshing = scan.trace.now();
// Every open buffer resolves against the index, so a buffer whose
// cross-file names the scan has just reached must be able to see them.
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut scan.trace.publish_overlay_ms, refreshing);
scan.trace.saw_publish(taken.len());
}
/// Finish `scan`: the index, the completion tables, the include graph and
/// every open buffer's overlay. Reports the warnings from resolving the
/// scope.
///
/// **What comes out is the index a one-shot scan over the same work list
/// would have produced**, however many times [`Workspace::publish_scan`]
/// ran in between: a publish only ever folds records in, and the index's
/// tables are a pure function of the records it holds
/// ([`WorkspaceIndex::absorb`]).
pub fn finish_scan(&mut self, scan: Scan) -> Vec<String> {
match scan.kind {
ScanKind::Whole => self.finish_whole_scan(scan),
ScanKind::Widen => self.finish_widen(scan),
}
}
/// [`Workspace::finish_scan`] for a whole scan.
fn finish_whole_scan(&mut self, scan: Scan) -> Vec<String> {
let Scan {
mut work, unread, incdirs, warnings, staged, words, includes, mut trace, ..
} = scan;
// What the scan really indexed, which is its work list unless a file
// left the disk between the walk and its own step. Such a file is not
// in scope any more, so it must land in `gone` exactly as it would
// have if the walk had missed it.
work.retain(|path| !unread.contains(path));
let found = scan::included(&includes, &work);
let leaving = trace.now();
// Whatever the last scan left in the index that this one's work list
// does not name is a file that is no longer in scope.
let held: HashSet<&Path> = work.iter().map(PathBuf::as_path).collect();
let gone: Vec<PathBuf> = self
.index
.files()
.iter()
.filter(|path| !held.contains(path.as_path()))
.cloned()
.collect();
ScanTrace::add(&mut trace.gone_ms, leaving);
let absorbing = trace.now();
self.index.absorb(staged, &gone);
ScanTrace::add(&mut trace.absorb_ms, absorbing);
// The one moment the live set of entries is known, so the one moment
// the append log is worth rewriting — and only when this scan reached
// a file at all. A scan with an empty work list asked the store
// nothing and never opened it, so there is nothing of this session's
// in it and nothing to rewrite it from (§P4b (b1)); the rewrite of a
// store that *is* open is itself skipped when it would reproduce the
// file byte for byte ([`IndexCache::compact`], §P4b (a)).
if matches!(self.store, StoreOpen::Done) {
self.cache.compact();
}
let completing = trace.now();
// Built from the words every step took off its own record — the same
// list, so a file the scope ladder excluded contributes no completion
// candidates either, and nothing is lexed twice.
self.candidates = Candidates::from_words(&self.index, words);
ScanTrace::add(&mut trace.candidates_ms, completing);
let including = trace.now();
// Same list again: an `` `include`` in a file the scope excluded is
// not an edge, and a file it excluded is not a hop away from anything.
// The lines themselves were read at each file's own step.
self.includes = IncludeGraph::from_includes(&found, incdirs);
ScanTrace::add(&mut trace.includes_ms, including);
let refreshing = trace.now();
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut trace.overlay_ms, refreshing);
self.landed(trace);
warnings
}
/// Close a scan's trace: the tables it left behind, measured, and the
/// whole thing set aside for the server to log.
///
/// Every size it reads is a walk, so the trace itself decides whether to
/// take them ([`ScanTrace::landed`]); a scan nobody traced sets nothing
/// aside.
fn landed(&mut self, mut trace: ScanTrace) {
trace.landed(self.docs.len(), &self.cache, &self.index, &self.candidates, &self.includes);
if trace.on() {
self.last_trace = trace;
}
}
/// The trace of the scan that just finished, taken away — an inert one
/// when the scan was not being traced.
pub fn take_scan_trace(&mut self) -> ScanTrace {
std::mem::take(&mut self.last_trace)
}
/// [`Workspace::finish_scan`] for a widen: the same three tables, folded
/// into rather than replaced.
///
/// Each table is landed with the batch form of the incremental update it
/// already had, which is the same one [`Workspace::publish_scan`] uses —
/// so what comes out is what a whole scan over the union of the old files
/// and the new ones would have produced. The three claims that makes, one
/// per table:
///
/// * **the index** — [`WorkspaceIndex::absorb`] keeps the records
/// path-sorted and one to a path and merges them the way a whole build
/// does;
/// * **the completion tables** — the two index-derived ones are re-derived
/// from the index, and the word table is patched per file into the same
/// total order a whole build sorts into;
/// * **the include graph** — the known-file and folded-spelling tables are
/// relearned from the whole in-scope list and every held edge is
/// re-spelled against it (the graph is rebuilt from every file's staged
/// include list, [`IncludeGraph::from_includes`]), so a file that is in
/// scope for the first time can lend its spelling to an edge that was
/// resolved before it arrived.
///
/// One thing a whole scan does that this deliberately does not: the
/// persistent store is **not compacted**. A widen does not know the live
/// set of entries — it only added to it — and the next whole rescan
/// rewrites the log anyway.
fn finish_widen(&mut self, scan: Scan) -> Vec<String> {
let Scan {
mut work,
mut paths,
gone,
incdirs,
warnings,
staged,
words,
includes,
mut trace,
unread,
..
} = scan;
// A widen only ever adds, so a file whose text had gone by its own
// step is simply not added — it is in neither list below.
work.retain(|path| !unread.contains(path));
paths.retain(|path| !unread.contains(path));
let found = scan::included(&includes, &work);
let absorbing = trace.now();
self.index.absorb(staged, &gone);
ScanTrace::add(&mut trace.absorb_ms, absorbing);
// Before the additions, so the two never disagree about a path that is
// in both lists — which cannot happen today (a large buffer is in
// neither `work` nor `paths`) and would be a silent wrong answer if it
// ever did.
for path in &gone {
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, &paths);
}
let batch: Vec<(PathBuf, Vec<String>)> = work
.iter()
.map(|path| (path.clone(), words.get(path).cloned().unwrap_or_default()))
.collect();
let completing = trace.now();
self.candidates.absorb(&self.index, batch);
ScanTrace::add(&mut trace.candidates_ms, completing);
let including = trace.now();
self.includes.absorb_includes(&incdirs, &paths, &found);
ScanTrace::add(&mut trace.includes_ms, including);
let refreshing = trace.now();
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut trace.overlay_ms, refreshing);
self.landed(trace);
warnings
}
// ------------------------------------------------------------------
// The one-shot forms: the protocol above run to the end in one call.
// Test-only, every one of them — the server drives the three calls
// itself so that it can answer messages between two of them.
// ------------------------------------------------------------------
/// Adopt the workspace roots and build the index for the first time.
/// Returns whatever the caller should tell the user about the scope.
///
/// The unwatched form. `server.rs` always watches (it has a progress bar
/// to move), so this is reachable from tests alone — of which there are
/// several dozen across this crate, and none of them has an opinion about
/// progress reporting.
#[cfg(test)]
pub fn open_roots(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
self.open_roots_with(roots, &mut |_| {})
}
/// [`Workspace::open_roots`] with `lucisv.index.scope` set to
/// `"workspace"`: adopt the roots and index **all** of them, which is what
/// every session did before 2026-08-27.
///
/// Test-only, and used by the dozens of tests across this crate that are
/// about something other than scope — a hover, a rename, an inlay hint —
/// and want the whole fixture tree in the index without opening a buffer
/// in each of its directories first. Spelling it out at the call site is
/// what keeps "this test wants the wide scope" a statement rather than an
/// accident. The folder scope's own behaviour is tested by the tests named
/// in `docs/features/index-scope/README.md`.
#[cfg(test)]
pub fn open_whole_workspace(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
self.open_whole_workspace_with(roots, &mut |_| {})
}
/// [`Workspace::open_whole_workspace`], watched. Test-only, for the two
/// tests that want the wide scope *and* the events.
#[cfg(test)]
pub fn open_whole_workspace_with(
&mut self,
roots: Vec<PathBuf>,
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
self.client.index_scope = IndexScope::Workspace;
self.open_roots_with(roots, watch)
}
/// [`Workspace::open_roots`], watched — the unwatched form's sibling, and
/// test-only for the same reason: the server drives the scan itself now,
/// one file at a time, so it adopts the roots and steps the scan rather
/// than calling this.
#[cfg(test)]
pub fn open_roots_with(
&mut self,
roots: Vec<PathBuf>,
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
self.adopt_roots(roots);
self.rebuild_index_with(watch)
}
/// Re-scan the workspace and rebuild the index and the completion tables,
/// then refresh every open buffer's overlay. Called on `initialize` and on
/// every `didSave`.
///
/// Returns the warnings from resolving the scope — a filelist naming a
/// file that is gone, say. Rendering them is `server.rs`'s job; this
/// module speaks no protocol.
///
/// The unwatched form, reachable from tests alone for the same reason
/// `open_roots` is.
#[cfg(test)]
pub fn rebuild_index(&mut self) -> Vec<String> {
self.rebuild_index_with(&mut |_| {})
}
/// [`Workspace::rebuild_index`], watched: `watch` is called once for every
/// file the size cap skipped and once for every file about to be parsed,
/// in index order and before the parse, so a caller can report where the
/// rescan has got to.
///
/// The events cover the index build alone. The completion tables and the
/// include graph are built from the same list afterwards and are not
/// reported: they cost a small fraction of the parse, and a bar that went
/// to 100% and then sat there would be worse than one that ends.
///
/// A scan with nothing happening between its files, which is what every
/// caller but the server's message loop wants. The loop drives the same
/// three calls itself and answers messages between two of them
/// (`docs/features/scan-interleave/README.md`) — so "one shot" and
/// "interleaved" are not two scans that have to be kept in step, they are
/// this loop with and without a drain in it.
///
/// Test-only for that reason: the server takes the three calls, and this
/// is what every test that just wants an index calls instead.
#[cfg(test)]
pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec<String> {
let mut scan = self.begin_scan(watch, false);
while self.scan_step(&mut scan, watch) {}
self.finish_scan(scan)
}
/// [`Workspace::begin_widen`] run to the end in one shot, the way
/// [`Workspace::rebuild_index_with`] runs a whole scan. Test-only for the
/// same reason: the server drives the three calls itself.
#[cfg(test)]
pub fn widen_index(&mut self, added: &[PathBuf]) -> Vec<String> {
self.widen_index_with(added, &mut |_| {})
}
/// [`Workspace::widen_index`], watched.
#[cfg(test)]
pub fn widen_index_with(
&mut self,
added: &[PathBuf],
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
let mut scan = self.begin_widen(added, watch, false);
while self.scan_step(&mut scan, watch) {}
self.finish_scan(scan)
}
}
/// How many bytes of buffer text a scan carries for its whole life — every
/// other file's text lives from its own step to the end of that step.
fn held_bytes(buffered: &HashMap<PathBuf, String>) -> usize {
buffered.values().map(String::len).sum()
}
+227
View File
@@ -0,0 +1,227 @@
//! What decides the scope: the workspace roots, the `lucisv.*` settings a
//! client pushed, and the ladder they select — which rung is in force and
//! which directories it walks.
use std::path::{Path, PathBuf};
use super::{StoreOpen, Workspace};
use crate::index_cache::IndexCache;
use crate::settings::{ClientSettings, IndexScope};
impl Workspace {
/// Take the workspace roots without indexing anything.
///
/// The half of [`Workspace::open_roots_with`] that is not a scan, for the
/// caller that drives the scan itself — the server, which runs the startup
/// scan through the same interleaved path every later rescan takes.
pub fn adopt_roots(&mut self, roots: Vec<PathBuf>) {
self.roots = roots;
}
/// Add and remove workspace roots mid-session, reporting whether the set
/// actually moved — which is whether the caller owes a rebuild.
///
/// Removals are applied before additions, so a folder named in both lists
/// (which the protocol does not forbid, and which is how some clients
/// spell "this folder moved") ends up present. Adding a root that is
/// already held and removing one that was never held are both no-ops, and
/// say so by leaving the set equal: `didChangeWorkspaceFolders` is a
/// notification, so there is nowhere to report a disagreement to and
/// nothing to gain from re-scanning for one.
pub fn change_roots(&mut self, added: Vec<PathBuf>, removed: &[PathBuf]) -> bool {
let before = self.roots.clone();
self.roots.retain(|root| !removed.contains(root));
for root in added {
if !self.roots.contains(&root) {
self.roots.push(root);
}
}
self.roots != before
}
/// Whether the client opened a workspace at all.
///
/// Without one there is nothing to walk but the open buffers' own
/// directories, and nothing to clamp the folder scope's climb against.
///
/// Test-only since 2026-08-27: `didOpen` used to branch on it, and now
/// branches on whether the file widened the scope, which is the same
/// question asked of the rung that is actually in force.
#[cfg(test)]
pub fn has_roots(&self) -> bool {
!self.roots.is_empty()
}
/// The workspace folders, in the order the client named them.
///
/// The first one is what a relative path in a setting is resolved against,
/// which is what [`Workspace::filelist_path`] does inline and what
/// `lucisv.lint.waivers` needs too.
pub fn roots(&self) -> &[PathBuf] {
&self.roots
}
/// The directories the folder scope walks: every directory a buffer has
/// been opened from this session, each raised `lucisv.index.scopeDepth`
/// levels. **Empty when the folder scope is not the active rung** — a
/// filelist and the whole-workspace walk are scopes an open buffer cannot
/// widen.
///
/// Public because `server.rs` compares it across a `didOpen` to decide
/// whether the file just opened widened the scope, which is the one thing
/// that makes a `didOpen` worth a rebuild.
pub fn scope_dirs(&self) -> Vec<PathBuf> {
if !self.folder_scoped() {
return Vec::new();
}
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
dirs.sort();
dirs.dedup();
dirs
}
/// Whether rung 3 — the folder scope — is the one in force.
///
/// A filelist outranks it, and so does an explicit
/// `lucisv.index.scope: "workspace"` **when there is a workspace to
/// walk**: with no roots there is nothing that setting could name, so a
/// rootless session is folder-scoped whatever it says.
fn folder_scoped(&self) -> bool {
self.filelist_path().is_none() && !self.walks_the_workspace()
}
/// Whether rung 2 — the walk of every workspace folder — is in force.
pub(super) fn walks_the_workspace(&self) -> bool {
self.client.index_scope == IndexScope::Workspace && !self.roots.is_empty()
}
/// `dir` raised `lucisv.index.scopeDepth` ancestor levels, clamped twice:
/// it never climbs above the workspace root that contains it — the deepest
/// one, for nested roots — and never above the filesystem root, which is
/// where a directory belonging to no root stops.
///
/// The root clamp is what keeps a `scopeDepth` of 5 in a two-deep project
/// from indexing the user's home directory.
///
/// **A rootless session does not climb at all** (2026-08-28). The clamp is
/// the whole reason a raise is safe, and with no workspace folder there is
/// nothing to clamp against: a lone file opened from
/// `~/work/chip/hw/ip/aes/rtl/` would otherwise raise the shipped
/// [`crate::settings::DEFAULT_SCOPE_DEPTH`] into `~/work/chip/hw/ip/` and
/// walk a tree the user never named. The single-file case stays what it
/// has always been — the buffer's own directory, read flat — and a user
/// who wants more opens the folder, which is what gives the climb a floor.
fn raised(&self, dir: &Path) -> PathBuf {
if self.roots.is_empty() {
return dir.to_path_buf();
}
let floor = self
.roots
.iter()
.filter(|root| dir.starts_with(root))
.max_by_key(|root| root.components().count());
let mut out = dir;
for _ in 0..self.client.index_scope_depth {
if Some(out) == floor.map(PathBuf::as_path) {
break;
}
let Some(parent) = out.parent() else { break };
out = parent;
}
out.to_path_buf()
}
/// The directories the open buffers' own folders raise to, whichever rung
/// of the ladder is in force.
///
/// [`Workspace::scope_dirs`] answers the same question *as a scope* and is
/// therefore empty unless rung 3 is in force. This one is an **ordering**
/// question — where in the workspace the user is working — and it has the
/// same answer under a filelist or an explicit `workspace` scope, where it
/// is the only thing that says which part of a 4 000-file walk to index
/// first.
pub(super) fn raised_dirs(&self) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
dirs.sort();
dirs.dedup();
dirs
}
/// The `lucisv.*` settings in force, for the resolution points in
/// `format.rs` to fold in.
pub fn client_settings(&self) -> &ClientSettings {
&self.client
}
/// Adopt the settings a client pushed.
///
/// Returns `true` when the caller must rebuild the index: `exclude`,
/// `filelist`, `index.maxFileSize`, `index.scope` and `index.scopeDepth`
/// are the five that change *which files exist* as far as this server is
/// concerned. `lineLength` and `indent` are read afresh by every
/// formatting request, so they need no invalidation at all — and neither
/// does `index.logFiles`, which changes only how loudly the *next* rescan
/// narrates itself.
///
/// `largeFile.threshold` asks for no rescan either, and deliberately: it
/// is consulted where a `Document` is *built*, so a change to it reaches
/// each open buffer at that buffer's next `didOpen`/`didChange` and not
/// before. A rescan now would index by the mode each buffer is still in,
/// which is the mode the index already reflects
/// (`docs/features/large-file-mode/README.md`).
pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool {
let rescan = self.client.exclude != settings.exclude
|| self.client.filelist != settings.filelist
|| self.client.max_file_size != settings.max_file_size
|| self.client.index_scope != settings.index_scope
|| self.client.index_scope_depth != settings.index_scope_depth;
// Neither cache setting changes *which files exist*, so neither asks
// for a rescan — but both change where, or whether, the cache writes,
// and the cache in hand was opened under the old ones. Dropping it
// here is what makes `persist: false` take effect at once in both
// directions: nothing more is written, and nothing held is read. The
// next whole rescan opens the store the new settings name.
if self.client.index_persist != settings.index_persist
|| self.client.index_cache_path != settings.index_cache_path
{
self.cache = IndexCache::disabled();
// And a deferred re-open goes with it, or the next file to want
// the store would open the directory the old settings named.
self.store = StoreOpen::Done;
}
self.client = settings;
rescan
}
/// Where the persistent index cache should live, by
/// [`crate::index_cache::cache_dir`]'s ladder — the client's setting, the
/// editor's storage folder, this platform's cache directory, or nowhere.
pub(super) fn cache_dir(&self) -> Option<PathBuf> {
// In this crate's own tests nothing falls through to the OS cache
// directory: a unit test must not write into the developer's own
// `~/Library/Caches`, and every test that is *about* the cache names
// a directory of its own — a `cachePath` or a `storagePath` — which
// the ladder below still answers with. The OS rung itself is tested
// where it is written, against `index_cache::cache_dir` directly.
#[cfg(test)]
if self.client.index_cache_path.is_none() && self.storage.is_none() {
return None;
}
crate::index_cache::cache_dir(
&self.client,
self.storage.as_deref(),
&self.roots,
self.filelist_path().as_deref(),
)
}
/// Adopt `initializationOptions.storagePath` — the folder the editor set
/// aside for this workspace's server state.
///
/// Called once, before the first index build, because it is one rung of
/// the ladder that decides where the cache is read from. A client that
/// sends nothing leaves the OS cache directory to decide.
pub fn set_storage_path(&mut self, storage: Option<PathBuf>) {
self.storage = storage;
}
}
+370
View File
@@ -0,0 +1,370 @@
//! The file sets handed to the refactorings: the whole scope, or — for a
//! port edit, a rename, a file rename — the fan-out the index already
//! bounds, so a request reads a handful of files instead of the workspace.
use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;
use vlog_semantic::{Def, FileId};
use super::scan::{HeldAnalyses, Sources};
use super::Workspace;
use crate::module_select::{self, Reach};
use crate::rename_trace::{self, Rung, SelectionTrace, Wanted};
use crate::scan_trace::ScanTrace;
impl Workspace {
/// The in-scope files and their current text — what a refactoring reads.
///
/// The same list `rebuild_index` feeds the index, recomputed rather than
/// kept: a refactoring is a rare, user-initiated request, and a second
/// copy of the workspace in memory is a high price for saving one walk.
///
/// This is the one caller that really does want every file's text at once,
/// so it is where the read a scan no longer does in one pass still
/// happens. A file that cannot be read contributes nothing, exactly as it
/// did when `collect_sources` read them all.
pub fn sources(&self) -> Vec<(PathBuf, String)> {
let Sources { files, mut buffered, .. } =
self.collect_sources(&mut |_| {}, HeldAnalyses::Unused, &mut ScanTrace::new(false));
files
.into_iter()
.filter_map(|path| {
let text = match buffered.remove(&path) {
Some(text) => text,
None => fs::read_to_string(&path).ok()?,
};
Some((path, text))
})
.collect()
}
/// The in-scope files a port refactoring on `modules`, requested in `file`,
/// can read or write — [`Workspace::sources`] narrowed to the fan-out the
/// index already holds.
///
/// A `textDocument/codeAction` arrives on every cursor move and
/// `sources()` reads the whole file set from disk, so a cursor resting on
/// an instantiation used to cost one workspace read per keystroke (3.1 s
/// on OpenTitan, and every queued request waited behind it). The index
/// knows who declares a module and who instantiates it, so the engine can
/// be handed those files and nothing else. Why the smaller set gives the
/// same answer is argued in `docs/features/refactor-ports/README.md`; the
/// four rungs are:
///
/// * **the file the request names**, whatever else it is;
/// * **every file declaring one of `modules`** ([`WorkspaceIndex::units`])
/// — all of them, so a name declared twice still refuses instead of
/// quietly picking the one definer that made it into the set;
/// * **every file that instantiates one** ([`WorkspaceIndex::instantiations_of`])
/// or otherwise refers to one ([`WorkspaceIndex::references_to`]) —
/// between them, every file the plan can edit and every file whose
/// meaning the verifier could see move;
/// * **every open buffer**, because its unsaved text may add or remove an
/// instantiation the saved edges do not know about.
///
/// Each file's text comes from the same place `collect_sources` takes it:
/// the open buffer when there is one, disk otherwise, and neither for a
/// buffer on the large-file fast path or a file over the size cap.
pub fn module_sources(&self, file: &Path, modules: &[String]) -> Vec<(PathBuf, String)> {
self.module_sources_reaching(file, modules, Reach::none())
}
/// [`Workspace::module_sources`] plus the **fifth rung**: every file whose
/// tokens write one of `reach`'s scope names down
/// ([`crate::module_select`], topology handshake 33).
///
/// Only inline-module asks for it, and only because its `no_hierarchy`
/// refusal is about a path *through* the instance it dissolves rather
/// than about either module's name: a testbench two wrapper levels above
/// is in none of the four rungs. The rung can only add files, so every
/// other caller's answer is untouched — and so is its cost, since
/// [`Reach::none`] walks nothing.
pub fn module_sources_reaching(
&self,
file: &Path,
modules: &[String],
reach: Reach<'_>,
) -> Vec<(PathBuf, String)> {
let mut wanted: BTreeSet<PathBuf> = module_select::hierarchical_users(&self.index, reach);
wanted.insert(file.to_path_buf());
for name in modules {
for def in self.index.units(name) {
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
for site in self.index.references_to(def) {
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
}
}
for edge in self.index.instantiations_of(name) {
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
}
}
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
wanted
.into_iter()
.filter_map(|path| {
let text = self.current_text(&path)?;
Some((path, text))
})
.collect()
}
/// The in-scope files a rename of `name` — to `new_name`, when the request
/// carries one — can read, write or refuse over: [`Workspace::sources`]
/// narrowed to what the index already knows about those two spellings.
///
/// A `textDocument/rename` cost 3.6–8.7 s on OpenTitan and a
/// `prepareRename` 2.5–3.0 s, almost all of it re-reading, re-parsing and
/// re-indexing 3 976 files to find the handful that spell one name. The
/// index holds every declaration of a name and every use it resolved, so
/// the engine can be handed those files and nothing else. **Why the
/// smaller set gives the same answer is argued in full in
/// `docs/features/refactor-rename/README.md`**; the rungs are:
///
/// * **the file the request names**, whatever else it is;
/// * **every open buffer**, whose unsaved text the index has not seen —
/// the one place this set deliberately does not trust the index;
/// * per spelling `N` in `{name, new_name}`:
/// * **every file declaring `N`** — as a unit or as a member of one
/// ([`WorkspaceIndex::workspace_symbols`], filtered to the exact
/// name). This is the rung the whole equality argument turns on:
/// `follow_paths` only ever looks a reference's *own* name up, so a
/// set holding every declarer of `N` resolves every reference spelling
/// `N` exactly as the whole workspace does;
/// * **every file declaring `N` on a module's hierarchical surface**
/// ([`WorkspaceIndex::hierarchical_declarations`]) — an internal net
/// is not a workspace symbol, and a hierarchical tail in another file
/// resolves to one;
/// * **every file with a use the index resolved to one of them**
/// ([`WorkspaceIndex::references_to`]) — every file a rename can edit,
/// and every file whose meaning the verifier could see move;
/// * **every file instantiating `N`**
/// ([`WorkspaceIndex::instantiations_of`]), which records a site whose
/// reference resolved to nothing and therefore has no posting;
/// * **every file whose `` `define`` table names `N` or spells it in a
/// macro body**, walked over the tables the index already holds, for
/// the two `` `define`` warnings;
/// * **the units that export `N` as a member**, and every file
/// declaring, referring to or instantiating one of those — how a third
/// file's `.N(...)` connection or `u::N` is reached.
/// * and, for the **new** name only, **every file that spells it in a use
/// this workspace had to look outside that file to answer, including
/// the uses it could not answer at all**
/// ([`WorkspaceIndex::files_spelling`]).
///
/// **Why that last rung is the new name's alone.** It exists because a
/// rename can give a name that meant *nothing* a meaning: `import
/// taken_pkg::*` in a file with no other tie to the rename resolves to
/// nothing today and to the renamed package tomorrow, which the
/// whole-workspace verifier refuses over and the first five rungs cannot
/// see. The old name has no such case, because a rename only ever
/// **removes** declarations of it: a use of the old name that resolves is
/// in that declaration's postings (rung 2, which walks *every* declaration
/// of the name, not only the target's), and one that resolves to nothing
/// still resolves to nothing afterwards — a lookup cannot start
/// succeeding because a candidate was taken away. So the old name's uses
/// are either already in the set or provably unmoved, and scanning for
/// them would buy nothing.
///
/// One escape hatch, and it is the honest one: when the index says a
/// declaration of `N` is named by an **ambiguous** use
/// ([`WorkspaceIndex::references_are_ambiguous`]), the file holding that
/// use is in no posting table, and the whole-workspace rename refuses
/// because of it. Rather than lose that refusal, this hands back
/// `sources()` and the slow path answers.
/// It also says **which rung asked for each file**: [`Wanted`] is a path
/// set that records the first rung to insert a path, so watching the
/// selection cannot change it (take 5 §P2a).
pub fn rename_sources_traced(
&self,
file: &Path,
name: &str,
new_name: Option<&str>,
) -> (Vec<(PathBuf, String)>, SelectionTrace) {
let started = Instant::now();
let elapsed = |at: Instant| at.elapsed().as_secs_f64() * 1000.0;
let mut wanted = Wanted::new();
wanted.insert(file.to_path_buf());
for spelling in [Some(name), new_name].into_iter().flatten() {
if !self.fan_out_of(spelling, &mut wanted) {
let sources = self.sources();
let trace = SelectionTrace::whole_scope(sources.len(), elapsed(started));
return (sources, trace);
}
}
// The sixth rung, and the **new** name's alone. See the doc comment
// above for why the old name does not need it.
if let Some(new_name) = new_name {
wanted.on(Rung::Speller);
self.want_spellers(new_name, &mut wanted);
}
wanted.on(Rung::OpenBuffer);
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
let (mut paths, mut trace) = wanted.finish();
// One hop down: the modules those files instantiate, so a `.*` into
// one is read rather than refused (M3.5). In `selected`, under no rung.
let handed: Vec<&Path> = paths.keys().map(PathBuf::as_path).collect();
for below in module_select::instantiated_by(&self.index, &handed) {
paths.entry(below).or_insert(Rung::Instantiation);
}
// §P2d's census: which rungs asked for files that write neither name
// down, and therefore contribute to this request only by shaping how
// the others resolve. One record lookup per selected file, no read.
trace.indirect =
rename_trace::indirect_census(&self.index, &paths, [name, new_name.unwrap_or(name)]);
let texts: Vec<(PathBuf, String)> = paths
.into_keys()
.filter_map(|path| {
let text = self.current_text(&path)?;
Some((path, text))
})
.collect();
// A file a rung wanted whose text this workspace no longer contributes
// (deleted, oversize, a fast-path buffer) is counted by its rung and
// is not in the input: the rungs total the *wanted* set, `selected`
// the one the engine gets.
trace.selected = texts.len();
trace.ms = elapsed(started);
(texts, trace)
}
/// Add one spelling's fan-out to `wanted`. `false` means the index cannot
/// bound it — see [`Workspace::rename_sources_traced`]'s escape hatch.
fn fan_out_of(&self, name: &str, wanted: &mut Wanted) -> bool {
// Every declaration of the name, wherever it is written. `units` alone
// would miss a port, a parameter or a package member, and those are
// exactly the declarations a `.port` connection or a `pkg::x` reaches
// across files for.
let mut containers: BTreeSet<&str> = BTreeSet::new();
for symbol in self.index.workspace_symbols(name) {
if symbol.name != name {
continue;
}
if self.index.references_are_ambiguous(symbol.def) {
return false;
}
containers.extend(symbol.container);
self.want_declaration(symbol.def, wanted);
}
// And every declaration of it on a module's **hierarchical** surface,
// which `workspace_symbols` deliberately does not list: an internal
// net is not a workspace symbol, but `assign w = u_x.sig;` in another
// file resolves to one and a rename must edit both ends. Without this
// rung the fan-out would hold the file that *names* the net and not
// the file that declares it (`docs/features/hierarchical-tail`).
for (unit, def) in self.index.hierarchical_declarations(name) {
if self.index.references_are_ambiguous(def) {
return false;
}
containers.insert(unit);
self.want_declaration(def, wanted);
}
self.want_sites(name, wanted);
self.want_macro_text(name, wanted);
for unit in containers {
for def in self.index.units(unit) {
self.want_declaration(def, wanted);
}
self.want_sites(unit, wanted);
}
true
}
/// One declaration's own file, and every file the index recorded a use of
/// it in.
fn want_declaration(&self, def: &Def, wanted: &mut Wanted) {
wanted.on(Rung::Declaration);
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
wanted.on(Rung::Reference);
for site in self.index.references_to(def) {
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
}
// A use written as a hierarchical path (`tb.dut.u_core.sig`) resolves
// inside the engine's set only if the set declares every unit the
// path walks through — the top module it is rooted at and each hop's
// type — so their declaring files come too (top-rooted-paths QA F3).
// Only files the index has: a unit outside the scope is not in it,
// and the path stays unresolved and warned about.
wanted.on(Rung::Declaration);
for unit in self.index.path_units_to(def) {
for unit_def in self.index.units(&unit) {
wanted.extend(self.index.path(unit_def.file).map(Path::to_path_buf));
}
}
}
/// Every file that instantiates a name — the census the reference postings
/// cannot speak for, because an instantiation of something the workspace
/// does not declare resolves to nothing and is posted nowhere.
fn want_sites(&self, name: &str, wanted: &mut Wanted) {
wanted.on(Rung::Instantiation);
for edge in self.index.instantiations_of(name) {
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
}
}
/// Every file that spells a name in a use the index had to look outside
/// that file to answer, **including the uses it could not answer at all**
/// ([`WorkspaceIndex::files_spelling`]).
///
/// The rung that closes the rename's one lost refusal (QA, 2026-08-28).
/// A file whose only tie to the new name is `import new_name::*` of a
/// package nothing declares yet holds no declaration, no posting, no
/// instantiation edge and no macro entry — and the rename is exactly what
/// gives that import a meaning, which the whole-workspace verifier refuses
/// over. Only the postings' *keys* miss it; the per-file records keep every
/// external use by the name it spells, so this reads it back.
fn want_spellers(&self, name: &str, wanted: &mut Wanted) {
for file in self.index.files_spelling(name) {
wanted.extend(self.index.path(file).map(Path::to_path_buf));
}
}
/// Every file whose `` `define`` table names the name or spells it in a
/// macro **body** — the two warnings `Scope::define_sites` produces.
///
/// The index holds every file's `DefineTable` already, so this is a walk
/// over tables in memory: no file is read and nothing is parsed. The
/// question is asked with `vlog_refactor::contains_word`, which is the
/// function `define_sites` itself decides with, so the fan-out and the
/// warning cannot disagree about which files carry one.
fn want_macro_text(&self, name: &str, wanted: &mut Wanted) {
wanted.on(Rung::MacroText);
for id in 0..self.index.files().len() {
let file = FileId(id as u32);
let Some(defines) = self.index.defines(file) else { continue };
let touched = defines.entries().iter().any(|define| {
define.name == name || vlog_refactor::contains_word(&define.body, name)
});
if touched {
wanted.extend(self.index.path(file).map(Path::to_path_buf));
}
}
}
/// The in-scope files a `workspace/willRenameFiles` can rewrite: the ones
/// the include graph recorded a resolving `` `include`` in, plus every open
/// buffer.
///
/// `will_rename` reads a file only to scan its `` `include``s and asks the
/// graph where each one lands; a file whose includes all resolve to nothing
/// — or that has none — contributes neither an edit nor a warning, and the
/// graph's edge table is exactly the set of files that have at least one
/// resolving include. So reading the rest was reading the whole workspace
/// to answer "nothing" 3 900 times. Open buffers are added whatever the
/// graph holds: the graph is rebuilt on save, so an `` `include`` typed and
/// not yet saved is in the buffer and not in the edges.
pub fn include_sources(&self) -> Vec<(PathBuf, String)> {
let mut wanted: BTreeSet<PathBuf> = self.includes.includers().cloned().collect();
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
wanted
.into_iter()
.filter_map(|path| {
let text = self.current_text(&path)?;
Some((path, text))
})
.collect()
}
}
@@ -0,0 +1,142 @@
//! A `Document`'s own analysis: the two token searches against the sweep
//! they replaced, what a buffer holds once analyzed, and — TODO §63.2 QA —
//! the trace's arithmetic, attacked with the three shapes TODO.md names: a
//! buffer that fails to lex, a `define` edit that changes the macro table,
//! and (via the server-level parity re-run) an edit that moves a fence.
use super::*;
/// The precondition both binary searches rest on. If the lexer ever emits
/// a token out of order, or two tokens that overlap, `partition_point`'s
/// predicates stop being monotone and every handler that calls
/// [`first_token_reaching`] or [`first_token_from`] starts answering
/// something else. This is the test that would fail first.
#[test]
fn the_token_stream_rises_and_never_overlaps() {
let text = mixed_buffer(20);
let doc = Document::new(None, text, &WorkspaceIndex::default());
assert!(doc.tokens.len() > 500, "premise: a stream worth searching");
for pair in doc.tokens.windows(2) {
assert!(pair[0].span.start <= pair[1].span.start, "{pair:?}");
assert!(pair[0].span.end <= pair[1].span.start, "overlapping tokens: {pair:?}");
assert!(pair[0].span.start <= pair[0].span.end, "an inverted span: {pair:?}");
}
}
/// Both searches, against the sweep they stand in for, at every byte of a
/// buffer full of tokens that touch.
#[test]
fn every_offset_finds_the_token_a_sweep_would_have_found() {
let text = mixed_buffer(20);
let doc = Document::new(None, text.clone(), &WorkspaceIndex::default());
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().position(|t| t.span.end >= offset);
assert_eq!(
first_token_reaching(&doc.tokens, offset),
swept.unwrap_or(doc.tokens.len()),
"first token reaching {offset}"
);
let swept = doc.tokens.iter().position(|t| t.span.start >= offset);
assert_eq!(
first_token_from(&doc.tokens, offset),
swept.unwrap_or(doc.tokens.len()),
"first token from {offset}"
);
}
}
#[test]
fn a_document_analyzes_a_clean_file() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a;\nendmodule\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(doc.diagnostics.is_empty());
assert_eq!(doc.path.as_deref(), Some(Path::new("/rtl/m.sv")));
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"));
assert!(!doc.tokens.is_empty());
}
#[test]
fn a_broken_file_still_analyzes() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire ;\nendmodule\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(!doc.diagnostics.is_empty(), "a broken buffer must report");
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"), "and still bind");
}
#[test]
fn a_file_that_does_not_lex_has_no_tokens_but_has_a_diagnostic() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a; /* unterminated\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(doc.tokens.is_empty());
assert_eq!(doc.diagnostics.len(), 1);
}
#[test]
fn an_untitled_buffer_has_no_path() {
let mut ws = Workspace::default();
ws.set_document(uri("untitled:Untitled-1"), "module m;\nendmodule\n".into());
let doc = ws.document(&uri("untitled:Untitled-1")).expect("open");
assert_eq!(doc.path, None);
}
/// A buffer that never lexes still reports a `Lex` stage (the failed
/// attempt is real work and costs real time) and a `Parse` stage (the
/// `parse_source_tolerant` fallback), and still counts as one document.
/// `defines`/`analyze`/`external`/`lines` all still run over the empty
/// token stream and empty-error tree exactly as the un-instrumented
/// path always did — the wrapping must not skip a stage just because
/// an earlier one errored.
#[test]
fn a_buffer_that_fails_to_lex_still_records_every_rebuild_stage() {
crate::lint_trace::arm();
// An unterminated string literal is an unambiguous lex error that
// does not depend on lexer internals that could drift between
// versions (`vlog_parser::tokenize` is documented all-or-nothing).
let text = "module m;\n string s = \"unterminated\nendmodule\n".to_string();
let doc = Document::new(None, text, &WorkspaceIndex::default());
assert!(doc.tokens.is_empty(), "a lex failure leaves an empty token stream");
assert!(!doc.diagnostics.is_empty(), "a lex failure is a diagnostic");
let trace = crate::lint_trace::disarm().expect("armed");
// Every stage's field is present on the line, whether or not it
// took measurable time (`saw_document`, not a duration, is what
// says a rebuild happened at all — see the flaky test this round
// fixed in `lint_trace.rs`).
let line = trace.line();
assert!(line.contains("documents=1"), "{line}");
for stage in ["lex=", "parse=", "defines=", "analyze=", "external=", "lines=", "publish="] {
assert!(line.contains(stage), "{line}");
}
}
/// A `` `define `` edit changes the macro table `collect_defines`
/// produces, and nothing about wrapping that call in `rebuild` changes
/// which tokens it sees or what it returns: the new revision's table
/// reflects only the new text, never a stale value from the revision
/// before it (`Document::new` builds a fresh `DefineTable` every time,
/// same as before this round).
#[test]
fn a_define_edit_changes_the_macro_table_the_rebuild_reports_on() {
crate::lint_trace::arm();
let before = Document::new(
None,
"`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] w;\nendmodule\n".to_string(),
&WorkspaceIndex::default(),
);
assert_eq!(before.defines.latest("WIDTH").map(|d| d.body.trim()), Some("8"));
assert!(before.defines.latest("DEPTH").is_none());
let after = Document::new(
None,
"`define DEPTH 16\nmodule m;\n wire [`DEPTH-1:0] w;\nendmodule\n".to_string(),
&WorkspaceIndex::default(),
);
assert!(after.defines.latest("WIDTH").is_none(), "no macro survives across documents");
assert_eq!(after.defines.latest("DEPTH").map(|d| d.body.trim()), Some("16"));
let trace = crate::lint_trace::disarm().expect("armed");
let line = trace.line();
assert!(line.contains("documents=2"), "two fresh Document::new calls, two rebuilds: {line}");
}
@@ -0,0 +1,244 @@
//! Rung 1 of the scope ladder: a filelist defines the index exactly, its
//! warnings reach the caller, and its `+incdir+`s reach the include graph.
use super::*;
/// A tree with three packages, one of which a filelist deliberately omits.
fn filelist_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
tree.package("rtl/unlisted.sv", "unlisted");
tree.write("files.f", "// the project\nrtl/a.sv\nrtl/b.sv\n");
tree
}
#[test]
fn a_configured_filelist_defines_the_index_exactly() {
// The point of a filelist: a file sitting in the tree that the project
// does not build is not indexed, however much the walk would find it.
let tree = filelist_tree("filelistkey");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn the_filelist_setting_beats_the_config_key_and_may_be_absolute() {
let tree = filelist_tree("filelistsetting");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
tree.write("other.f", "rtl/unlisted.sv\n");
// Relative: against the workspace root, not the current directory.
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("other.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"], "the setting wins");
// Absolute: taken as written.
let absolute = tree.path.join("other.f");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist(&absolute.display().to_string()));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"]);
}
#[test]
fn a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so() {
// The failure that must never happen: an empty index and no
// explanation because a path in a settings UI has a typo.
let tree = filelist_tree("filelistgone");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("typo.f"));
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"], "the walk ran");
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("typo.f"), "{warnings:?}");
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
}
/// Whether file modes bind this process: a mode-000 directory refuses to be
/// listed. Root lists it anyway (Linux CI jobs run as root), so there the
/// directory the scan cannot read cannot be built; the test says so and stops.
#[cfg(unix)]
fn listing_is_refused() -> bool {
use std::os::unix::fs::PermissionsExt;
let probe = Tree::new("modeprobe");
let shut = probe.path.join("shut");
fs::create_dir(&shut).expect("probe dir");
fs::set_permissions(&shut, fs::Permissions::from_mode(0o000)).expect("chmod");
let refused = fs::read_dir(&shut).is_err();
let _ = fs::set_permissions(&shut, fs::Permissions::from_mode(0o755));
if !refused {
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
}
refused
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
// TODO §45.2: the walk's warnings ride out on the scope's own
// warnings, which the server logs once per scan. Before the channel
// existed the walk returned an error the index simply dropped, so a
// permission-denied directory cost every file after it silently.
use std::os::unix::fs::PermissionsExt;
if !listing_is_refused() {
return;
}
let tree = Tree::new("walkwarn");
tree.package("rtl/a.sv", "a");
tree.package("rtl/z.sv", "z");
tree.package("locked/hidden.sv", "hidden");
std::os::unix::fs::symlink("nowhere.sv", tree.path.join("rtl/gone.sv")).expect("symlink");
let locked = tree.path.join("locked");
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
let mut ws = Workspace::default();
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o755));
assert_eq!(indexed(&ws, &["a", "z", "hidden"]), ["a", "z"], "the scan finished");
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("locked")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("gone.sv: broken symbolic link")), "{warnings:?}");
}
#[test]
fn a_filelists_own_warnings_reach_the_caller() {
let tree = filelist_tree("filelistwarn");
tree.write("files.f", "rtl/a.sv\nrtl/moved.sv\n-nonsense\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a"], "the rest is still indexed");
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("moved.sv")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("-nonsense")), "{warnings:?}");
}
#[test]
fn an_open_buffer_is_indexed_even_when_the_filelist_omits_it() {
// Open buffers overlay every rung of the ladder: a scratch file the
// project does not build still gets its own symbols.
let tree = filelist_tree("filelistbuffer");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
let path = tree.path.join("rtl/unlisted.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package unlisted;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"]);
}
#[test]
fn with_no_workspace_root_the_open_files_own_directory_is_indexed() {
// The single-file case: no folder was opened, so the scope is what
// sits beside the buffer — and nothing below it.
let tree = Tree::new("noroot");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/sibling.sv", "sibling");
tree.package("rtl/deeper/below.sv", "below");
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
assert!(!ws.has_roots(), "the premise: no workspace folder");
let path = tree.path.join("rtl/open.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["open_pkg", "sibling", "below", "far"]),
["open_pkg", "sibling"],
"the buffer and its neighbours only"
);
}
#[test]
fn a_filelist_still_wins_when_there_is_no_workspace_root() {
let tree = filelist_tree("norootfilelist");
let mut ws = Workspace::default();
// With no root a relative setting cannot be anchored, so an absolute
// path is the only sensible way to name one — and it works.
ws.set_client_settings(using_filelist(&tree.path.join("files.f").display().to_string()));
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
}
/// Where `ws` would look for `` `include "<name>" `` written in `from`.
fn resolved_include(ws: &Workspace, from: &Path, name: &str) -> Option<PathBuf> {
let text = format!("`include \"{name}\"\n");
let include = crate::includes::scan(&text).into_iter().next().expect("one include");
ws.includes().resolve(Some(from), &include)
}
/// A tree whose filelist names one `+incdir+` and nests a filelist naming
/// another, with a header in each — plus one only the nested incdir holds.
fn incdir_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/a.sv", "a");
tree.write("first/defs.svh", "`define W 1\n");
tree.write("ip/include/defs.svh", "`define W 2\n");
tree.write("ip/include/ip_only.svh", "`define X 1\n");
tree.write("ip/ip.f", "+incdir+include\n");
tree.write("files.f", "+incdir+first\n-f ip/ip.f\nrtl/a.sv\n");
tree
}
#[test]
fn a_filelists_incdirs_reach_the_include_graph_in_filelist_order() {
// M1 recorded `+incdir+` and used it for nothing; this is the wire
// that spends it. A nested `-f`'s incdirs come through flattened,
// *after* the ones named before the `-f` — which is the order an
// include is searched in, so it is worth pinning here and not only in
// the parser.
let tree = incdir_tree("incdirs");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert!(warnings.is_empty(), "{warnings:?}");
let from = tree.path.join("rtl/a.sv");
assert_eq!(
resolved_include(&ws, &from, "defs.svh"),
Some(tree.path.join("first/defs.svh")),
"the root filelist's incdir is searched before the nested one's"
);
assert_eq!(
resolved_include(&ws, &from, "ip_only.svh"),
Some(tree.path.join("ip/include/ip_only.svh")),
"and the nested one is searched at all"
);
}
#[test]
fn without_a_filelist_there_are_no_incdirs_at_all() {
// Rungs 2 and 3 of the ladder name no include path, so an `` `include``
// there has only the including file's own directory to go on.
let tree = incdir_tree("noincdirs");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"), None);
}
#[test]
fn a_broken_filelist_leaves_the_include_graph_without_incdirs() {
let tree = incdir_tree("badfilelistincdirs");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("typo.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"),
None,
"the walk fallback names no include path"
);
}
@@ -0,0 +1,406 @@
//! The folder scope (index-scope, 2026-08-27): rung 3's climb and the two
//! clamps on it, what outranks it, and the inherited obligations from that
//! round's review.
use super::*;
/// A project laid out the way the owner described it: the file being
/// worked on in `rtl/`, a header folder beside it, and a third folder that
/// has nothing to do with either.
fn two_folder_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/beside.sv", "beside_pkg");
tree.package("rtl/deeper/below.sv", "below_pkg");
tree.package("include/defs.sv", "defs_pkg");
tree.package("elsewhere/far.sv", "far_pkg");
tree
}
/// The four fixture packages, as the ones that are in the index.
fn scoped(ws: &Workspace) -> Vec<String> {
indexed(ws, &["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"])
}
#[test]
fn the_folder_scope_at_depth_zero_is_the_open_files_own_folder_and_everything_under_it() {
// The headline of the index-scope round: a workspace root is open, but
// the index covers the folder the user is working in, not the project.
// At depth 0 — the shipped default until 2026-08-28, and still exactly
// what an explicit `scopeDepth: 0` asks for.
let tree = two_folder_tree("scopedefault");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_roots(vec![tree.path.clone()]);
assert!(scoped(&ws).is_empty(), "premise: nothing is open, so nothing is in scope");
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg"],
"the buffer's own folder and its subtree — and no sibling folder"
);
}
#[test]
fn a_scope_depth_of_one_reaches_the_folder_beside_it() {
// `rtl/` plus `../include`: the layout the setting exists for.
let tree = two_folder_tree("scopedepth");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
"one level up is the whole tree here, sibling folders included"
);
}
#[test]
fn the_climb_stops_at_the_workspace_root() {
// The clamp that keeps a depth of 99 in a two-deep project from
// indexing the user's home directory. Asserted on the directories
// themselves rather than on an index, because the failure this guards
// against is a walk that should never be started.
let tree = two_folder_tree("scopeclamp");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/deeper/below.sv");
assert_eq!(ws.scope_dirs(), vec![tree.path.clone()], "clamped at the root, not above it");
// The deepest containing root wins, so a nested root clamps tighter.
assert!(ws.change_roots(vec![tree.path.join("rtl")], &[]));
assert_eq!(ws.scope_dirs(), vec![tree.path.join("rtl")], "the deepest root is the floor");
}
#[test]
fn a_rootless_session_does_not_climb_at_all() {
// Changed 2026-08-28, with the shipped depth. The climb used to run
// with `/` as its only floor, which was survivable while the shipped
// depth was 0 and nobody climbed by accident. It is not survivable at
// depth 2: a lone file opened from `~/work/chip/hw/ip/aes/rtl/` would
// raise into `~/work/chip/hw/ip/` and walk a tree the user never
// named. The clamp is what makes a raise safe, so with nothing to
// clamp against there is no raise, whatever the depth says.
let tree = two_folder_tree("scoperootless");
for depth in [0, 1, 99] {
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: depth, ..Default::default() });
open(&mut ws, &tree, "rtl/open.sv");
assert!(!ws.has_roots(), "the premise: no workspace folder to clamp against");
assert_eq!(
ws.scope_dirs(),
vec![tree.path.join("rtl")],
"depth {depth}: the buffer's own directory, and nothing above it"
);
}
}
#[test]
fn a_rootless_session_reads_its_own_directory_flat_until_the_depth_is_raised() {
// The `folder_files` exception, from the other side. The *directory*
// is the buffer's own whatever the depth (no root, no climb — see
// above), but the depth still chooses how it is read: 0 reads it flat,
// one level, no `.gitignore`, and a raise means the user has asked for
// a tree, so the tree below the buffer is walked.
let tree = two_folder_tree("scoperootlesswalk");
for (depth, expected) in
[(0, vec!["open_pkg", "beside_pkg"]), (1, vec!["open_pkg", "beside_pkg", "below_pkg"])]
{
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: depth, ..Default::default() });
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(scoped(&ws), expected, "depth {depth}");
}
}
#[test]
fn the_workspace_scope_setting_restores_the_walk_of_every_root() {
// The migration line in the README, pinned: with `scope: "workspace"`
// the index is the whole tree with no buffer open at all — which is
// exactly what this fixture gave before this round.
let tree = two_folder_tree("scopewide");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
..Default::default()
});
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
"every file under the root, no buffer needed"
);
// And the depth is not consulted at all on that rung.
let mut raised = Workspace::default();
raised.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
index_scope_depth: 3,
..Default::default()
});
raised.open_roots(vec![tree.path.clone()]);
assert_eq!(raised.index().files(), ws.index().files(), "the depth changes nothing here");
}
#[test]
fn a_filelist_still_defines_the_scope_exactly_whatever_the_folder_rung_would_say() {
// Rung 1 outranks rung 3 as it always outranked rung 2: the filelist
// is the project file, and it names files in folders no buffer has
// been opened from.
let tree = two_folder_tree("scopefilelist");
tree.write("files.f", "include/defs.sv\nelsewhere/far.sv\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "defs_pkg", "far_pkg"],
"the filelist, plus the open buffer that overlays every rung"
);
assert!(ws.scope_dirs().is_empty(), "and no `didOpen` can widen a filelist");
}
#[test]
fn closing_a_file_never_narrows_the_scope() {
// The decision, pinned: the scope only grows within a session. A
// rebuild after a close must not take away answers the user had a
// moment ago, and no `didClose` costs a rescan.
let tree = two_folder_tree("scopeclose");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
open(&mut ws, &tree, "include/defs.sv");
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"]);
let closed = crate::uri::path_to_uri(&tree.path.join("include/defs.sv")).expect("uri");
ws.close_document(&closed);
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"],
"the closed file's folder is still indexed"
);
}
#[test]
fn the_folder_scope_honours_every_exclude_and_the_gitignores_below_it() {
// Rung 3 walks with the same function rung 2 walks with, so nothing a
// user excluded comes back because the scope narrowed — with **one
// honest exception**, pinned here rather than left to be discovered:
// `lucisv_core`'s walk reads `.gitignore` files from its own starting
// directory downwards, so a rule written at the workspace root does
// not reach a walk that starts below it. The `exclude` patterns are
// matched against whole paths and are unaffected either way. Stated in
// `walked_files` and in `docs/features/index-scope/README.md`.
let tree = Tree::new("scopefilters");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.write(".gitignore", "generated/\n");
tree.write("rtl/.gitignore", "dumps/\n");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/vendor/ip.sv", "vendor_pkg");
tree.package("rtl/dumps/net.sv", "dumps_pkg");
tree.package("rtl/generated/net.sv", "generated_pkg");
tree.package("rtl/scratch/wip.sv", "scratch_pkg");
let names = &["open_pkg", "vendor_pkg", "dumps_pkg", "generated_pkg", "scratch_pkg"];
let mut ws = Workspace::default();
ws.set_client_settings(excluding(&["scratch"]));
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
indexed(&ws, names),
["open_pkg", "generated_pkg"],
"both excludes and the .gitignore inside the scope applied; the one at the \
root, above where this walk starts, did not"
);
// ...and the wide scope, whose walk starts at the root, does apply it.
let mut wide = Workspace::default();
wide.set_client_settings(ClientSettings {
exclude: vec!["scratch".to_string()],
index_scope: IndexScope::Workspace,
..Default::default()
});
wide.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&wide, names), ["open_pkg"], "everything filtered, from the root");
}
#[test]
fn a_folder_added_mid_session_widens_nothing_until_a_file_in_it_is_opened() {
// The interaction between the two ways a scope can move. Under the
// folder rung a workspace folder is a *clamp*, not a work list, so
// adding one changes which files exist only once a buffer in it makes
// it a scope directory.
let first = Tree::new("scopefolderfirst");
first.package("a.sv", "a");
let second = Tree::new("scopefoldersecond");
second.package("b.sv", "b");
let mut ws = Workspace::default();
ws.open_roots(vec![first.path.clone()]);
open(&mut ws, &first, "a.sv");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: the first folder's file");
assert!(ws.change_roots(vec![second.path.clone()], &[]), "the root set moved");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "but no buffer lives there yet");
open(&mut ws, &second, "b.sv");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "opening one widens the scope");
}
#[test]
fn a_scope_or_a_depth_change_asks_for_a_rescan() {
// Both change which files exist, so both join `exclude`, `filelist`
// and the size cap in the rescan test.
let mut ws = Workspace::default();
let wide = ClientSettings { index_scope: IndexScope::Workspace, ..Default::default() };
assert!(ws.set_client_settings(wide.clone()), "a new scope rescans");
assert!(!ws.set_client_settings(wide.clone()), "the same one does not");
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
let deep = ClientSettings { index_scope_depth: 5, ..Default::default() };
assert!(ws.set_client_settings(deep.clone()), "a new depth rescans");
assert!(!ws.set_client_settings(deep), "the same one does not");
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
}
#[test]
fn the_open_files_are_indexed_first_and_the_index_cannot_tell() {
// Two halves of one claim. First: the progress events name the open
// buffers before anything else, which is what makes a big rescan feel
// like it is working on the user's own files.
let tree = Tree::new("scopeorder");
tree.package("rtl/a_first.sv", "a_first");
tree.package("rtl/m_open.sv", "m_open");
tree.package("rtl/z_last.sv", "z_last");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/m_open.sv");
// Every file of the work list, however it got into the index: since
// 2026-08-28 the open buffer goes in from its own analysis and reports
// `Analyzed` rather than `Parsing`, and the claim under test is about
// the *order* the work list is walked in, not about who parses.
let mut seen: Vec<PathBuf> = Vec::new();
ws.rebuild_index_with(&mut |event| match event {
IndexEvent::Parsing { path, .. }
| IndexEvent::Cached { path, .. }
| IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()),
IndexEvent::Skipped { .. } => {}
});
assert_eq!(
seen,
vec![
tree.path.join("rtl/m_open.sv"),
tree.path.join("rtl/a_first.sv"),
tree.path.join("rtl/z_last.sv"),
],
"the open buffer first, then the rest in path order"
);
// Second, and the reason the first is allowed to be true: the index
// is byte-identical to the one the plain path order builds. The
// builder sorts inside `finish`, so the order above is a reporting
// decision and nothing more (`vlog_semantic`'s
// `no_insertion_order_can_change_what_the_builder_produces` is the
// other end of this).
let mut plain = Workspace::default();
plain.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
..Default::default()
});
plain.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().files(), plain.index().files(), "same files, same ids");
assert_eq!(ws.index().counts(), plain.index().counts(), "and the same index");
}
#[test]
fn lowering_the_scope_depth_narrows_the_index_on_the_next_rescan() {
// The scope grows only along the *open* axis — a `didClose` never
// narrows it. A settings change is the other axis and moves both ways,
// because it is a deliberate statement about how much of this machine's
// time to spend. Verified by hand by the previous round's QA; pinned
// here.
let tree = two_folder_tree("depthdown");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert!(scoped(&ws).contains(&"defs_pkg".to_string()), "premise: depth 1 reaches beside");
assert!(
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }),
"lowering the depth asks for a rescan"
);
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "narrowed, not kept");
}
#[test]
fn a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one() {
// Not just "asks for a rescan" — that the index really becomes the
// filelist's files, from a folder scope that was covering something
// else entirely.
let tree = two_folder_tree("filelistmid");
tree.write("files.f", "elsewhere/far.sv\n");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "premise: the folder rung");
assert!(ws.set_client_settings(using_filelist("files.f")), "a rescan is owed");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "far_pkg"],
"rung 1 defines the scope exactly — plus the open buffer, which overlays every rung"
);
}
#[test]
fn a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one() {
// `raised()`'s floor is the deepest root *containing* the directory, and
// there is none here — so the climb stops at `/`, exactly as it does
// with no root at all. Verified by hand by the previous round's QA;
// pinned here, on the directories rather than by walking one.
let inside = Tree::new("outsideroot_in");
inside.package("rtl/a.sv", "a_pkg");
let outside = Tree::new("outsideroot_out");
outside.package("other/b.sv", "b_pkg");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_roots(vec![inside.path.clone()]);
open(&mut ws, &outside, "other/b.sv");
assert_eq!(
ws.scope_dirs(),
vec![outside.path.join("other")],
"at depth 0 it is the buffer's own directory and nothing else"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a_pkg", "b_pkg"]), ["b_pkg"], "the root's own tree is not in it");
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
assert_eq!(
ws.scope_dirs(),
vec![PathBuf::from("/")],
"and with nothing to clamp against the climb stops at the filesystem root"
);
}
@@ -0,0 +1,233 @@
//! Workspace folders added and removed mid-session
//! (`didChangeWorkspaceFolders`): what widens the scan, what narrows it,
//! what changes nothing, and what is left when the last root goes.
use super::*;
#[test]
fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() {
let first = Tree::new("rootsfirst");
first.package("a.sv", "a");
let second = Tree::new("rootssecond");
second.package("b.sv", "b");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![first.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: one folder");
assert!(ws.change_roots(vec![second.path.clone()], &[]), "a new folder moves the set");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "both folders are scanned");
assert!(ws.change_roots(Vec::new(), from_ref(&first.path)), "and so does dropping one");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["b"], "the dropped folder's files are gone");
}
#[test]
fn a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed() {
// Overlap does not duplicate a file's registration: `walked_files`
// walks each root independently and `dedup`s the combined, sorted
// list by path, so a file both roots would reach lands in the index
// once, not twice (a second identical registration would show up as
// an *ambiguous* member — `indexed` below only counts a name found
// exactly once).
//
// It is NOT exclude-proof, though, and that half is a genuine
// consequence of "each root is governed by its own config"
// (documented on `walked_files`): a directory the parent root's
// `lucisv.toml` excludes is added *as a root in its own right* here,
// and nothing excludes a root from itself. QA (2026-08-27): flagged
// in the QA log as a finding, not a bug fix — this is consistent
// with the per-root config model, but it was unreachable before this
// round (roots used to be frozen at `initialize`), so it is worth a
// pin and a name.
let tree = Tree::new("subdirroot");
tree.write("lucisv.toml", "exclude = [\"sub\"]\n");
tree.package("kept.sv", "kept");
tree.package("sub/hidden.sv", "hidden_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["kept", "hidden_pkg"]), ["kept"], "excluded, as configured");
assert!(ws.change_roots(vec![tree.path.join("sub")], &[]));
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["kept", "hidden_pkg"]),
["kept", "hidden_pkg"],
"reachable once through the added root, and only once — not ambiguous"
);
}
/// A workspace whose tree links back into itself. Before the walk kept a
/// visited set (`docs/features/walk-cycles/README.md`) this scan never
/// finished — the editor's index simply never came up. Each directory is
/// entered once now, so each package is registered exactly once: a second
/// registration would make the name *ambiguous*, and `indexed` only
/// counts a name found exactly once.
#[cfg(unix)]
#[test]
fn a_cyclic_workspace_is_scanned_once_and_finishes() {
let tree = Tree::new("cycle");
tree.package("rtl/a.sv", "a");
tree.package("rtl/sub/b.sv", "b");
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level
// down. Either one alone runs until the OS refuses a path.
std::os::unix::fs::symlink("../rtl", tree.path.join("rtl/self")).expect("symlink");
std::os::unix::fs::symlink("..", tree.path.join("rtl/sub/up")).expect("symlink");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"]);
assert_eq!(
ws.walked_files(from_ref(&tree.path), &mut |_| {}, &mut ScanTrace::new(false)).len(),
2,
"two files, once each"
);
}
#[test]
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
// Every no-op shape a client can send. Each must leave the root set
// exactly as it was, and say so — a rescan here is pure cost.
let tree = Tree::new("rootsnoop");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert!(!ws.change_roots(Vec::new(), &[]), "an empty event");
assert!(!ws.change_roots(vec![tree.path.clone()], &[]), "a folder already held");
let never = tree.path.join("never-added");
assert!(!ws.change_roots(Vec::new(), from_ref(&never)), "a folder never held");
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&never)), "and both at once");
assert!(ws.has_roots(), "the root survived every one of them");
}
#[test]
fn a_trailing_slash_in_the_removed_folder_still_matches_the_held_root() {
// `uri_to_path` decodes a URI verbatim, trailing slash and all, and
// `change_roots` compares by `PathBuf` equality — which compares
// components, not raw strings, so `/a/b/` and `/a/b` are already the
// same path as far as `retain`/`contains` are concerned. Pinned
// because the doc README calls this out as a boundary worth
// checking, not because the standard library needed help.
let tree = Tree::new("trailingslash");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let mut with_slash = tree.path.clone().into_os_string();
with_slash.push("/");
assert!(
ws.change_roots(Vec::new(), from_ref(&PathBuf::from(with_slash))),
"the trailing slash must not hide the match"
);
assert!(!ws.has_roots());
}
#[test]
fn a_folder_named_in_both_halves_of_one_event_stays() {
// Removals run first, so "removed and added again" — which is how a
// moved folder reaches some clients — is not a way to lose a root.
let tree = Tree::new("rootsboth");
tree.package("a.sv", "a");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&tree.path)), "no net change");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a"]), ["a"]);
}
#[test]
fn a_folder_added_twice_across_two_events_is_absent_after_one_removal() {
// The root set is a set, not a multiset: `change_roots` dedups on
// push (`if !self.roots.contains(&root)`), so a second add of the
// same path — even from a *later*, separate notification — never
// grows a reference count for it. One removal is therefore always
// enough, however many times a client (redundantly) added it.
// QA (2026-08-27): pinned per the review checklist's multiset-vs-set
// question.
let tree = Tree::new("addedtwice");
let extra = Tree::new("addedtwiceextra");
extra.package("x.sv", "x");
let mut ws = Workspace::default();
// Whole-workspace scope, so the indexed-content assertions below see
// the roots at all — under the default folder scope nothing is
// walked until a buffer opens, and the closing assertion was vacuous
// (QA finding, 2026-08-27, lead-fixed).
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.change_roots(vec![extra.path.clone()], &[]), "the first add moves the set");
assert!(
!ws.change_roots(vec![extra.path.clone()], &[]),
"a second, separate add of the same path is a no-op"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["x"]), vec!["x".to_string()], "present while added");
assert!(
ws.change_roots(Vec::new(), from_ref(&extra.path)),
"one removal is enough to take it out"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["x"]), Vec::<String>::new(), "gone, not merely decremented");
}
#[test]
fn removing_the_last_root_falls_back_to_the_rootless_model() {
// Rung 3 of the ladder is not a startup-only state: a session that
// closes its last folder becomes the single-file case, and an open
// buffer must still resolve against the files beside it.
let tree = Tree::new("rootslast");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/sibling.sv", "sibling");
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["open_pkg", "sibling", "far"]), ["open_pkg", "sibling", "far"]);
let path = tree.path.join("rtl/open.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
assert!(!ws.has_roots(), "the workspace is rootless now");
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["open_pkg", "sibling", "far"]),
["open_pkg", "sibling"],
"the buffer and its neighbours, as if the file had been opened on its own"
);
}
#[test]
fn removing_the_last_root_leaves_a_relative_filelist_unanchored() {
// `filelist_path` anchors a relative setting at `roots.first()`. With
// no roots left there is nothing to anchor it to, and the path comes
// back exactly as the client wrote it — not resolved against the
// folder that is now gone, and not resolved against anything else
// either. Nothing panics: `source_files` still falls back to the
// rootless walk with a warning when that bare path cannot be read
// (`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so`
// covers that fallback). QA (2026-08-27): pinned because this is new
// reachable behaviour this round — losing the last root used to be
// impossible.
let tree = Tree::new("rootslastfilelist");
tree.package("rtl/open.sv", "open_pkg");
tree.write("files.f", "rtl/open.sv\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
ws.filelist_path(),
Some(tree.path.join("files.f")),
"anchored at the root while it exists"
);
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
assert_eq!(
ws.filelist_path(),
Some(PathBuf::from("files.f")),
"with no roots left, the same setting comes back bare — anchored at nothing"
);
}
@@ -0,0 +1,191 @@
//! The incremental path (incremental-index, 2026-08-27): one saved file
//! re-indexed in place, checked against the whole rebuild it stands in for.
use super::*;
#[test]
fn only_a_file_the_index_already_holds_takes_the_incremental_path() {
// The whole gate, from both sides. A file the index holds is one the
// update can replace; anything else is a rebuild's business, because a
// file appearing changes what *other* files' includes resolve to.
let tree = Tree::new("incrgate");
tree.package("rtl/a.sv", "a_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.update_one_checked(&tree.path.join("rtl/a.sv")), "a file the index holds");
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "a file it does not");
assert!(!ws.update_one(&tree.path.join("rtl/a.txt")), "and a path it never would");
// A file that appears is exactly the "not held" case, and stays so
// until something rebuilds.
tree.package("rtl/new.sv", "new_pkg");
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "still not held");
ws.rebuild_index();
assert!(ws.update_one_checked(&tree.path.join("rtl/new.sv")), "held now");
}
#[test]
fn one_files_edit_reaches_every_table_the_index_answers_from() {
// The four pieces of derived state a rebuild produces, checked one by
// one after an update that moves all four: a declaration, an
// instantiation edge, an inheritance edge, a completion word and an
// `` `include`` edge.
let tree = Tree::new("incrtables");
tree.write("rtl/defs.svh", "`define W 8\n");
tree.write("rtl/sub.sv", "module sub;\nendmodule\nclass base;\nendclass\n");
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n sub u1 ();\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let top = tree.path.join("rtl/top.sv");
assert_eq!(ws.index().instantiations_of("sub").len(), 1, "premise: one site");
assert_eq!(
ws.includes().reachable(vec![top.clone()]).len(),
2,
"premise: top.sv reaches defs.svh"
);
assert_eq!(ws.candidates().words("u1").len(), 1, "premise: the instance name is a word");
fs::write(
&top,
"module top;\n logic renamed_wire;\nendmodule\nclass leaf extends base;\nendclass\n",
)
.expect("write");
assert!(ws.update_one_checked(&top));
assert!(ws.index().instantiations_of("sub").is_empty(), "the site went");
assert_eq!(ws.index().subclasses_of("base").len(), 1, "and an inheritance edge came");
assert!(ws.candidates().words("u1").is_empty(), "the old word was given back");
assert_eq!(ws.candidates().words("renamed_wire").len(), 1, "the new one taken");
assert_eq!(ws.includes().reachable(vec![top]).len(), 1, "the include edge went too");
}
#[test]
fn a_file_the_cap_or_the_disk_takes_away_leaves_the_index() {
let tree = Tree::new("incrremove");
tree.package("rtl/keep.sv", "keep_pkg");
tree.package("rtl/gone.sv", "gone_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]).len(), 2, "premise");
// Deleted on disk: the update is a removal.
let gone = tree.path.join("rtl/gone.sv");
fs::remove_file(&gone).expect("remove");
assert!(ws.update_one_checked(&gone), "a held file, even a vanished one");
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]), ["keep_pkg"]);
// And a file that grew past the cap is the same answer for the same
// reason: it is not a file this server reads any more.
let mut ws = Workspace::default();
let tree = Tree::new("incrcap");
tree.package("rtl/keep.sv", "keep_pkg");
fat_package(&tree, "rtl/netlist.sv", "netlist_pkg", 4096);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]).len(), 2, "premise: under no cap");
ws.set_client_settings(wide(capping(1024)));
assert!(ws.update_one_checked(&tree.path.join("rtl/netlist.sv")));
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]), ["keep_pkg"], "the cap took it");
}
#[test]
fn an_open_buffer_beats_disk_on_the_incremental_path_too() {
let tree = Tree::new("incrbuffer");
tree.package("rtl/a.sv", "a_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join("rtl/a.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package buffered_pkg;\n localparam K = 1;\nendpackage\n".to_string());
assert!(ws.update_one_checked(&path));
assert_eq!(
indexed(&ws, &["a_pkg", "buffered_pkg"]),
["buffered_pkg"],
"the buffer's text, not the file's"
);
}
#[test]
fn the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus() {
// The paranoid sweep: take real files out of a real workspace, put a
// mutated version back through the incremental path, and check the
// result against a whole rebuild every time. `update_one_checked` is
// what does the checking; this test is the corpus it does it over.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
// Copied into a scratch tree, because the sweep rewrites files. Every
// fifth file: `update_one_checked` rebuilds the whole workspace to
// check itself, so the sweep costs a full rebuild per mutation and a
// third of the corpus is still hundreds of real files.
let tree = Tree::new("incrcorpus");
let mut copied = 0;
let mut sample: Vec<PathBuf> = Vec::new();
for (n, source) in walk_sources(&corpus).into_iter().step_by(5).enumerate() {
let Ok(text) = fs::read_to_string(&source) else { continue };
let rel = format!("f{n:04}.sv");
tree.write(&rel, &text);
copied += 1;
if n % 31 == 0 {
sample.push(tree.path.join(&rel));
}
}
assert!(copied > 100, "premise: the corpus was really copied ({copied} files)");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(sample.len() > 5, "a sample worth sweeping: {}", sample.len());
for path in &sample {
let text = fs::read_to_string(path).expect("the copy is on disk");
// Four shapes of edit, each checked against a whole rebuild.
assert!(ws.update_one_checked(path), "unchanged");
fs::write(
path,
format!("{text}\nmodule qa_added_module;\n qa_added_sub u1 ();\nendmodule\n"),
)
.expect("write");
assert!(ws.update_one_checked(path), "a declaration and an edge added");
fs::write(path, "class qa_leaf extends qa_base;\nendclass\n").expect("write");
assert!(ws.update_one_checked(path), "replaced wholesale");
fs::write(path, "").expect("write");
assert!(ws.update_one_checked(path), "emptied");
fs::remove_file(path).expect("remove");
assert!(ws.update_one_checked(path), "removed");
}
eprintln!("paranoid sweep: {copied} files, {} of them mutated five ways", sample.len());
}
/// What one file's rescan costs on the incremental path, against the whole
/// rebuild it replaces, over the real corpus.
///
/// `#[ignore]`d like the crate's other measurement probes: it prints
/// numbers rather than asserting one. The numbers themselves are in
/// `docs/features/incremental-index/README.md`.
#[test]
#[ignore]
fn qa_perf_one_file_against_the_whole_rebuild() {
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_whole_workspace(vec![corpus]);
let files = ws.index().files().len();
let one = ws.index().files().last().cloned().expect("a file");
let mut whole = std::time::Duration::MAX;
let mut single = std::time::Duration::MAX;
for _ in 0..3 {
let started = std::time::Instant::now();
ws.rebuild_index();
whole = whole.min(started.elapsed());
let started = std::time::Instant::now();
assert!(ws.update_one(&one));
single = single.min(started.elapsed());
}
eprintln!(
"reindex over {files} files: whole rebuild {whole:?}, one file {single:?} \
({:.0}x)",
whole.as_secs_f64() / single.as_secs_f64().max(f64::MIN_POSITIVE)
);
}
Loaded 100 of 280 files, more files were not shown because too many files have changed in this diff. Show more