Compare commits

...
29 Commits
Author SHA1 Message Date
Guoliang ChenandClaude Mythos 5.2 cfa8d82707 Release 0.67.0: twelve bug-fix rounds, measured against 0.66.2
ci / checks (push) Successful in 1m26s
ci / corpus (push) Successful in 18s
release / preflight (push) Successful in 4s
ci / linux (push) Successful in 6m7s
release / linux (push) Successful in 6m6s
release / build-and-publish (push) Successful in 6m7s
Everything since 0.66.2: Rounds 1-12 (refactor and server ordering, index
lifecycle, MCP hardening, CI gates, CLI/parser/formatter fixes, formatter
alignment and overrides, linter hardening, semantic edge cases, exact
semantic-token refresh, sliced discovery walk, Windows UNC URIs, pure-move
splits) and the Take-6 performance report. This commit is the version bump,
the changelogs and the documentation sync; no source change.

- Version 0.67.0 in Cargo.toml, Cargo.lock and the extension manifests.
- CHANGELOG.md and editors/vscode/CHANGELOG.md: the 0.67.0 sections,
  including the output change, the lint delta, the Windows caveats and the
  three known regressions from Take 6.
- docs/topo.md, docs/repository-analysis.md, README.md, TODO.md and the
  site sources brought up to Rounds 1-12; topo 2.9 handshakes #67-#74 stay
  open as written.
- tools/gates.sh green on this tree: 5 820 tests, corpus 814/6 as before.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 23:04:26 -08:00
Guoliang ChenandClaude Mythos 5.2 2e9da208e3 Take 6: bisect the three regressions to Rounds 5 and 2
Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 22:49:34 -08:00
Guoliang ChenandClaude Mythos 5.2 f2d9ff01dc Take 6: OpenTitan performance report, 0.66.2 against Rounds 1-12
Measures 71d13b5 against aa2259b on OpenTitan hw (CLI, LSP, MCP), with
raw logs and drivers under docs/perf/take6-20261126/. Docs only.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 21:59:18 -08:00
Guoliang ChenandClaude Mythos 5.2 aa2259bfe1 Round 12: pure-move splits and hygiene
Splits resolve.rs, parser/item.rs, parser/instance.rs, format/stmt.rs and
lexer.rs (really 771 lines); moves 23 inline test modules of lucisv_server
to their own files; reasons on all 12 bare #[ignore]; the giant-line
references test times the real request; sites.py default root.
Output over 4,046 OpenTitan files byte-identical to a479faf.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 20:39:56 -08:00
Guoliang ChenandClaude Mythos 5.2 a479faf029 Round 11: Windows UNC file URIs and editor polish
uri.rs: pure-string Posix/Windows flavours; UNC shares read and written as
file://server/share/..., verbatim paths seen through, device and
unspellable hosts refused; Posix identical to trunk except backslash
(%5C) and query/fragment stripping. Windows is compile- and link-checked
only.
Editors: mcp.js finds a directory-qualified path without .exe on Windows;
hierarchyView.js reports failed actions and disposes its listeners;
README and scopeDepth description corrections.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 20:04:07 -08:00
Guoliang ChenandClaude Mythos 5.2 36733e2c7c Round 10: resumable discovery walk and faster whole rescans (#58, #64)
#58: the discovery walk runs in 512-entry slices with requests drained
between them (lucisv_core ResumableWalk, state/walking.rs); identities are
read in one pass at landing. Proved equal to the one-shot walk.
#64: the 40k rescan timing split is not reproducible; the store is kept
across rescans, compaction streams, candidates are cheaper (-12% on 40k,
answers and store byte-identical).
Files topo #71-#74.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 19:29:02 -08:00
Guoliang ChenandClaude Mythos 5.2 dc54b23572 Round 9: exact semantic-token refresh after rescans and cross-file edits (#59, #60)
A range answer is remembered with its tokens and compared at the settle
decision, so a rescan that changed nothing draws no refresh. An edit that
changes the kind of something another open buffer references sends one
workspace/semanticTokens/refresh when that buffer's colours really differ.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 17:50:05 -08:00
Guoliang ChenandClaude Mythos 5.2 532a64546c Round 8: semantic and refactor edge cases (#12, #31, #32, L-5/L-6/L-10)
DPI-export names are semantic references. verify_move reconstructs the
result independently and checks equation 3 per edit, with 16 attack tests.
Interface generate-block members are reachable through a port or virtual
interface; bind to a bare instance name is found; nested struct members
get their container key. Escaped identifiers join FileFacts::words
(FACTS_FORMAT 23); generate-scoped bind shorthand resolves. Scope reuses
index_order. Files topo #68-#70.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 17:18:59 -08:00
Guoliang ChenandClaude Mythos 5.2 e229ff9668 Round 7: linter hardening — missing-port-direction, nested incomplete-assignment, option/regex safety (#41)
New Error-class rule missing-port-direction (75 rules) closes topo #41.
incomplete-assignment walks every path and accepts an enumerated case only
when the selector width is proven. suspicious-semicolon exempts the
while-drain idiom; mismatched-labels reads statement labels and gains an
Unsafe footer fix. Quote-aware option list splitter; regex nesting cap.
The uvm-macro-semicolon autofix was withdrawn after three QA failures and
the instance-shadowing exemption reverted. Files topo #67 (lucisv.toml
array splitting).

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 16:32:41 -08:00
Guoliang Chen 9437966d58 Round 6: Formatter alignment completeness, lowrisc fidelity, selective overrides, and full cache keying 2026-11-26 14:59:53 -08:00
Guoliang Chen 4cf50a0b9c Round 5: CLI path/JSON/stdin and parser/formatter fixes (#1, #11, #42, #44-#47, #55) 2026-11-26 14:35:06 -08:00
Guoliang Chen 6d1c68994c Round 4: CI/release gates, Cargo workspace authors, and docs/site sync (#57, #65, #66, #36, §65.8) 2026-11-26 12:32:13 -08:00
Guoliang Chen 69383eae7f Round 3: MCP hardening and vlog_refactor references/L-9 support (#37, #40, #54, #56) 2026-11-26 12:03:46 -08:00
Guoliang Chen 4d384ec89d Round 2: unified index lifecycle, tombstones, symlinks, and large-file invariant (#48-#51, #63) 2026-11-26 11:14:26 -08:00
Guoliang Chen 8f5a4fb236 Round 1: refactor correctness, UTF-8/determinism, and server ordering (#38, #39, #52, #53, #61, #62) 2026-11-26 09:12:33 -08:00
Guoliang ChenandClaude Mythos 5.2 71d13b5fbe Release 0.66.2: every source file names its author
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 18s
ci / linux (push) Successful in 6m4s
release / build-and-publish (push) Successful in 5m31s
Every tracked file that can carry a comment (880 of them) now opens with
"Author: Guoliang Chen, a Senior Digital Design Engineer" and closes with
"Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love,
luciochen.com", in the file's own comment syntax. No behaviour change: the
diff outside the version bump and changelogs is comment lines only.

- tools/stamp_author.py: writes the lines; idempotent, `--check` lists
  what is missing. Headers go under a shebang and under Markdown front
  matter.
- Left alone: test fixtures, cases and snapshots (byte-exact inputs), JSON
  and JSONL, logs, images, lockfiles, docs/site/dist (regenerated) and the
  LICENSE files (already carry the copyright line).
- tools/linux_check.sh: --help reads its header from line 3, now that the
  author line sits under the shebang.
- tools/gates.sh green on this tree: 5 545 tests, corpus 814/6 as before.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-24 12:11:09 -08:00
Guoliang ChenandClaude Mythos 5.2 3823b85667 Release 0.66.1: sticky scroll pins the module instance
ci / checks (push) Successful in 57s
ci / corpus (push) Successful in 14s
ci / linux (push) Successful in 4m56s
release / build-and-publish (push) Successful in 5m17s
A multi-line module instantiation now answers folding ranges, so VS Code's
sticky scroll pins it (TODO §72, docs/features/instance-folding): one range
from the module-type line, and one more per instance from the line its name
is on when that is a later line, so both `aes_control_fsm #(` and
`) u_aes_control_fsm (` stay pinned inside the connection list. The closing
`);` line stays visible.

- folding/instances.rs: what is an instantiation comes from
  vlog_semantic::instantiations::sites; where it closes is re-read from the
  tokens, and a statement whose tokens are not exactly that shape folds
  nothing.
- folding.rs: in_answer_order is a stable sort by start line over scopes,
  branches, instances; every earlier fold is unchanged and first on a shared
  start line (0.66.0 against this tree on 4 933 files: identical once the
  instance folds are removed).
- OpenTitan hw: 18 200 multi-line instantiations, none without its fold.
- Not folded: two-dimensional instance arrays; an instance whose head an
  `ifdef splits.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 23:22:18 -08:00
Guoliang ChenandClaude Mythos 5.2 10cb6e020f Release 0.66.0: the overnight queue, complete
ci / checks (push) Successful in 57s
ci / corpus (push) Successful in 15s
ci / linux (push) Successful in 4m52s
release / build-and-publish (push) Successful in 5m18s
Closes TODO §71: eight owner-ordered features shipped as 0.65.2–0.65.11.
No engine change since 0.65.11.

- docs/topo.md refreshed through 0.65.11: contracts, server-lane edges,
  packaging rows, open handshakes 44–66, new modules, choke points; stale
  FACTS_FORMAT and state.rs references corrected.
- CLAUDE.md: file sizes re-measured.
- Feature READMEs: five stale facts corrected.
- large.rs: the two linear-time tests re-measure up to three times before
  failing (0.65.11's Linux CI run read 24.9x against a 24x limit under load).

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 21:01:14 -08:00
Guoliang ChenandClaude Mythos 5.2 cc1e2c8b72 Release 0.65.11: actions on the open file no longer wait for the workspace
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 15s
ci / linux (push) Failing after 4m33s
release / build-and-publish (push) Successful in 5m22s
A hover, definition, type definition, highlight, prepare-rename or signature
help on a name the file itself declares, and the outline, folding and
selection ranges, are answered from the open buffer ahead of a scan, a
rescan or a widen (server/ahead.rs, same_file.rs). The precondition is stated
once, on Server::answer_from_the_buffer; ahead::REACH lists the notifications
proved unable to change a buffer and everything else blocks.

Completion offers what the file can reach (imported package members,
inherited class members, included headers' macros) right after its own names
(completion/related.rs), and its answers are half the size (completion/wire.rs).

A new largeFile.threshold re-classifies buffers already open. The client's
answer to a settings pull is now ordered like a notification (amends
scan-ordering); colours answered while anything is held count as unsettled.

TODO 71.2. Four dev rounds, four QA rounds; the last ran with Fable 5.2 as
dev and QA after two QA failures. docs/features/fast-actions.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 20:52:22 -08:00
Guoliang ChenandClaude Mythos 5.2 c1c1407498 Release 0.65.10: highlighting no longer waits for the index
release / build-and-publish (push) Successful in 5m38s
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 16s
ci / linux (push) Successful in 4m44s
TODO §71.3. On OpenTitan the first colours of a newly opened file waited
600-700 ms for the index (building them takes 0.3-6.5 ms), a rescan held
them for most of a second, and the first answer, built from a half-finished
index, was never corrected.

- server/viewport.rs: semanticTokens range, full and full/delta for a buffer
  whose text is current are answered from that buffer alone before the
  request would be held — when no change for it is queued anywhere (held,
  71.7's behind count, set aside ahead of it in its burst) and it is not
  dirty. The handler reads only that document and the remembered token
  answer. Built on 0.65.8's must_hold; the lane's own queue tracking is gone.
- server/index.rs: open_then_widen applies the didOpen, answers the burst's
  colour requests, then widens; reindex_widened answers colour requests
  between its files.
- One workspace/semanticTokens/refresh once the index settles, when an early
  answer differed or was a guess; only for clients with refreshSupport, which
  are also the only ones given early full answers.
- tokens.rs: range classifies only the window's tokens (+1 each side) and
  skips AST items outside it; large.rs's line window is shared.

First colour 2-39 ms (was 600-700); folder-scope late open 611-641 -> 2-32
ms; rescan hold 325-791 -> 70-159 ms. 96.8 % of early tokens already match
the settled answer; the rest resolve through the index.

Dev (two rounds), QA (two rounds: ~10 000 token answers against an exact
oracle, 978 non-colour answers identical to base) and lead review:
docs/features/viewport-highlight/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.10) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree including cross;
lucisv_server 2052/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 13:06:52 -08:00
Guoliang ChenandClaude Mythos 5.2 a8c22dcab0 Release 0.65.9: lucisv-mcp no longer serves stale contents; the suite runs on Linux
ci / linux (push) Failing after 34s
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 16s
release / build-and-publish (push) Successful in 5m22s
TODO §70, closed.

- lucisv_mcp/src/project/files.rs: Stamp's racy rule (re-check by content a
  stamp taken too close to a timestamp it trusts) covered the mtime alone.
  On Linux, where ctime moves in 1 ms ticks, a same-size rewrite that
  restored the old mtime inside the tick of the server's read matched in
  every field and index-based answers came from the old text indefinitely.
  The rule now covers every trusted timestamp (mtime, and ctime where there
  is one), the window is 3 s, and a wall clock stepped back since the read
  distrusts the stamp. The decision is a pure compare(Seen, Clocks) with
  deterministic unit tests.
- Test-only: two stdin helpers tolerate BrokenPipe on the write to a child
  that exits before reading (lucisv cli.rs, lucisv_mcp qa_m8.rs); the
  didOpen latency test's budget is six parses of the same buffer, not 200 ms
  (lucisv_server e2e.rs); qa_m3's server is spawned before its checker
  thread, which removes a hang on a pipe inherited across threads on macOS.
- .gitea/workflows/ci.yml: a linux job on the luhpe-linux-x64 runner —
  clippy and cargo test --workspace on Linux x86-64.
- docs/features/mcp-transport describes the new rule and what it cannot see
  (Windows has no ctime; writable mmaps).

Linux: whole suite green 10/10 as root and 10/10 as a user (dev), 6/6 and
6/6 (QA). QA reproduced the stale read on 0.65.8 (65/65, 87/87 when the stat
was identical) and got 0 here. Dev, QA and lead review:
docs/features/linux-test-portability/README.md, Round 2.

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

Gates: tools/gates.sh PASS on this tree including cross; lucisv_mcp 388/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 13:03:59 -08:00
Guoliang ChenandClaude Mythos 5.2 934d472af2 Release 0.65.8: Find References next to a name, edits kept in order, a startup that could take minutes
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 5m28s
TODO §71.7. Three server bugs, all older than this series.

- A caret just past an identifier's last letter resolved the NEXT character
  (spans are end-exclusive): references, definition, hover and highlight came
  back empty where VS Code considers the caret on the word — the owner's
  'not found, then works after clicking back'. lucisv_server/src/caret.rs;
  nine position-to-symbol requests use it through Server::symbol_offset; the
  References view opens a row with the caret at the name's start.
- process_batch held requests during a scan but applied notifications at
  once, so a didChange could overtake an older one still queued; with
  incremental sync that corrupted the server's copy of the buffer until the
  file was reopened. Rule now: no notification overtakes an older unapplied
  notification (Server::must_hold, the 'behind' count for the burst a scan
  is nested in). Cancels wait whenever anything is held; responses never.
- answer_what_is_waiting acted on a didOpen it had queued but not applied,
  re-holding the same batch at every file of the startup scan (~300-400 s on
  OpenTitan). Scan state now changes only where a message is applied; a held
  batch is handed back at most once per applied didOpen.

An attempt to also drop excluded buffers from the index on close cost 190 ms
per open of an outside file and was reverted after QA measured it.

Dev (two rounds), QA (two rounds, own ordering driver: 9 118 bursts, no
wrong text) and lead review: docs/features/scan-ordering/README.md. TODO.md
files what stays open.

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

Gates: tools/gates.sh PASS on this tree including cross;
lucisv_server 2030/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 11:47:14 -08:00
Guoliang ChenandClaude Mythos 5.2 dbb2349267 Release 0.65.7: 0.65.6, built for every platform
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 5m19s
0.65.6 was tagged and never published: the release build failed to compile
lucisv-server for Windows. lucisv_core::walk::dir_id is a Copy (dev, ino)
pair on unix and an owned PathBuf elsewhere, and 71.1's
Workspace::holds_another_spelling_of moved it inside a closure
(lucisv_server/src/state/incremental.rs). Compared by reference now.

tools/gates.sh gains a `cross` step: cargo check of the three shipped
binaries for x86_64-pc-windows-gnu and x86_64-unknown-linux-musl with the
rustup toolchain release.sh --cross uses (skipped with a note when it is
absent). It fails on the unfixed tree with the release run's own error and
passes on this one. tools/RELEASING.md lists it.

CHANGELOG.md's 0.65.7 section carries 0.65.6's notes in full under a short
account of what happened; the v0.65.6 tag is left where it is.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots).

Gates: tools/gates.sh PASS on this tree including cross; a full local
tools/release.sh --cross and tools/audit_artifacts.sh dist pass (seven .vsix
packages, eighteen binaries).

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 10:52:35 -08:00
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
1155 changed files with 97301 additions and 26143 deletions

No files matched your search

+34 -5
View File
@@ -1,7 +1,11 @@
# CI: the three checks CLAUDE.md requires before any work is finished,
# plus the extension's JavaScript tests and the corpus gate, enforced on
# every push. Runs on the self-hosted mac-arm64 runner in host mode (no
# containers), so the toolchain is the same one releases are built with.
# Author: Guoliang Chen, a Senior Digital Design Engineer
# CI: author-stamp check plus the three checks CLAUDE.md requires before any
# work is finished (with `cargo test` run under `tools/guard.sh`), plus the
# extension's JavaScript tests and the corpus gate, enforced on every push. Runs on the self-hosted macOS runner in host mode (no
# containers), so the toolchain is the same one releases are built with —
# and, since 0.65.9, the same checks on Linux (the `linux` job below), where
# the released Linux binaries had never been compiled-and-tested before.
name: ci
on:
push:
@@ -13,12 +17,14 @@ jobs:
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
- name: author stamps
run: python3 tools/stamp_author.py --check
- name: cargo fmt
run: cargo fmt --all -- --check
- name: cargo clippy
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: cargo test --workspace
run: tools/guard.sh -m 8 -t 1800 -- cargo test --workspace
# The VS Code extension's headless checks (a stubbed `vscode`, no npm
# dependencies): node >= 18 for `--test`; the runner has node 22.
- name: extension tests
@@ -41,3 +47,26 @@ jobs:
run: cargo build --release -p lucisv
- name: Score and gate
run: scripts/corpus_gate.sh "$CORPUS"
# The suite on Linux x86-64: the luhpe-linux-x64 runner starts each job in
# the runner image (as root, 4 CPUs / 8 GB for the whole runner), with no
# Rust in it, so the toolchain is installed per job and the build is cold
# (a few minutes). Clippy is here as well as on macOS because code behind
# cfg(unix)/cfg(target_os) is only compiled on the platform it names: the
# first Linux trial failed clippy on imports macOS never saw. To run the
# same thing from a working tree without a push: tools/linux_check.sh.
linux:
runs-on: linux-x64
steps:
- uses: actions/checkout@v4
- name: Install the Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --profile minimal -c clippy,rustfmt
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: cargo clippy
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: tools/guard.sh -m 6 -t 1800 -- cargo test --workspace
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+63 -5
View File
@@ -1,3 +1,5 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
# Release: pushing a tag `vX.Y.Z` builds every distribution artifact and
# publishes a Gitea release with the CHANGELOG section for that version as
# its notes. What the release page carries is the seven .vsix packages —
@@ -15,11 +17,16 @@
# 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).
# It is gated in three stages:
# 1. `preflight` checks in seconds that the tag matches Cargo.toml, the VS Code
# extension version files, and a non-empty CHANGELOG.md section before any
# heavy build runs.
# 2. `linux` runs clippy and guarded workspace tests on `linux-x64` so Linux
# portability is verified before building or publishing a release.
# 3. `build-and-publish` runs `tools/gates.sh` (stamp, fmt, clippy, every
# crate's suites, doc-tests, corpus gate, node tests, cross check), builds
# and audits all targets, prunes assets to the seven .vsix files + SHA256SUMS,
# and publishes the Gitea release.
name: release
on:
push:
@@ -27,7 +34,56 @@ on:
- 'v*'
jobs:
preflight:
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
- name: Check tag, versions, and CHANGELOG notes
run: |
tag_ver=${GITHUB_REF_NAME#v}
[ "v$tag_ver" = "$GITHUB_REF_NAME" ] && [ -n "$tag_ver" ] || {
echo "tag $GITHUB_REF_NAME must look like vX.Y.Z" >&2
exit 1
}
crate_ver=$(awk '
/^\[workspace\.package\]/ { in_wp = 1; next }
/^\[/ { in_wp = 0 }
in_wp && /^version[[:space:]]*=/ {
sub(/^[^"]*"/, ""); sub(/".*/, ""); print; exit
}
' Cargo.toml)
[ "$crate_ver" = "$tag_ver" ] || {
echo "tag $GITHUB_REF_NAME does not match Cargo.toml version '$crate_ver'" >&2
exit 1
}
for pinned in \
"$(node -p "require('./editors/vscode/package.json').version")" \
"$(node -p "require('./editors/vscode/package-lock.json').version")" \
"$(node -p "require('./editors/vscode/package-lock.json').packages[''].version")"; do
[ "$pinned" = "$tag_ver" ] || {
echo "editors/vscode version '$pinned' does not match tag $GITHUB_REF_NAME" >&2
exit 1
}
done
tools/release_notes.sh "$tag_ver" >/dev/null
linux:
needs: preflight
runs-on: linux-x64
steps:
- uses: actions/checkout@v4
- name: Install the Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --profile minimal -c clippy,rustfmt
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: cargo clippy
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: tools/guard.sh -m 6 -t 1800 -- cargo test --workspace
build-and-publish:
needs: [preflight, linux]
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
@@ -67,3 +123,5 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
LUCISV_API_URL: ${{ vars.LUCISV_API_URL }}
run: tools/publish_release.sh "$GITHUB_REF_NAME" dist
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
/target
/corpus
/corpus-check-results.tsv
@@ -8,3 +10,5 @@
/.zcode
/.claude
__pycache__/
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+762
View File
@@ -1,9 +1,769 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# Changelog
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.67.0 — 2026-11-26
### Twelve bug-fix rounds, measured against 0.66.2
0.67.0 is everything since 0.66.2: twelve rounds of correctness, ordering,
hardening and hygiene fixes, each with its own dev round, QA round and lead
review, and a before/after performance report on OpenTitan `hw`
(`docs/performance_take6.md`). Each paragraph below names the feature README
that holds the detail. Three things to know before upgrading:
- **Formatted output changes.** Over OpenTitan `hw` the formatter's output
differs from 0.66.2 in **413** files in the default style, **576** under
`--style auto` and **972** under `--style lowrisc`; no file gained or lost a
diff, and verification failures are **0** in every style, as before.
- **One new lint rule is on by default** (`missing-port-direction`, an Error),
and two rules report differently; see Linter.
- **Saved state is rebuilt once.** The persisted index (`FACTS_FORMAT` 22 → 23)
of both the language server and `lucisv-mcp --index-cache` is discarded and
rebuilt on first start, and the format cache's lines are re-keyed, so the
first `lucisv` run after upgrading has no cache hits.
### Formatter and safety net
- **`#(…)` parameter ports and named parameter overrides are aligned** like
every other list: type, name and `=` in columns under both `infer` and
`always` alignment (`docs/features/format-alignment-overrides-r6`). Every
file Take 6 sampled from the output change above shows it; class parameter
headers are unchanged.
- **`lowrisc` sets named connections tight to the widest name**: the widest
name's `(` follows it directly (`.err_o(…)`) and narrower names are padded
to that column (`.tl_i (tl_i)`). This is a new `connection-align-min` knob,
`0` for `lowrisc` and `1` for every other preset.
- **Selective `[format]` overrides.** `begin`, `else`, `else-after-label`,
`port-lists`, `list-indent`, `alignment` and `connection-align-min` in
`lucisv.toml` (and the matching `lucisv.format.*` editor settings) layer
over any named preset, and over every candidate under `style = "auto"`. The
CLI, the language server and the MCP `format` tool all honour them. Every
effective knob is now part of the format cache key, so toggling one
re-formats; older cache lines are dropped as stale.
- **Multi-instance declarations** (`p1 u8 (…), u9 (…);`) break symmetrically
under the one-per-line styles (`google`, `lowrisc`, `microsoft`, `nxp`)
instead of the hanging layout; `lucisv` and `ansi` output is unchanged
(`docs/features/parser-formatter-r5`).
- **Files that used to be left unformatted now format:** a comment between a
generate `end` and `else`, an `` `ifdef `` (balanced, or a conditional
`else` arm) between `end` and `else` in procedural and generate `if`, and
attributes on ANSI ports (`(* keep *) input a`).
- **The parser is stricter where it was silently lenient:** empty elements in
concatenations, replications, streaming and assignment patterns
(`{d,, d}`, `{d,}`, `'{4{a,, b}}`), in `case` item lists (`case a,, b:`)
and a trailing `,` after a named call argument (`f(.a(x),)`) are now parse
errors, so such a file is reported and left as it is. Omitted positional
arguments (`f(a, , b)`) are still accepted.
### CLI
- **`--style auto` is twice as fast**: the file is parsed once for all six
candidate presets and only the winner is verified. OpenTitan `hw`,
`--check --no-cache`: 5 564 → **2 806 ms** median, user CPU 49.9 → 21.2 s,
peak RSS 981 → 699 MiB (`docs/features/parser-formatter-r5`, Take 6).
- **`--output-format json` works in format mode** (`lucisv`, `--check`,
`format`): one JSON document with `status`, `exit_code`, `summary` and one
entry per file, with the error's category, line and column. It refuses
`--diff`, `--stdout` and stdin without `--check`. Exit codes are unchanged
(`docs/features/cli-path-r5`).
- **Stdin honours the project config:** `-` / `--stdin-filename` applies the
discovered `lucisv.toml` alike in `format` and `check`, including `[lint]
select` and `ignore` in `check`; an empty `--stdin-filename ""` is refused.
- Path normalisation (`.` and `..`) is one shared function in `lucisv_core`
for filelists, config discovery, includes and the CLI; behaviour is
unchanged, including Windows drive and UNC roots.
### Linter
(`docs/features/linter-hardening-r7`.) 75 rules now (8 error, 24 warning,
43 style). On OpenTitan `hw`, `lucisv check` goes from **1 182 to 1 178**
findings:
- **New: `missing-port-direction`** (Error, on by default, no fix) reports a
non-ANSI header port that no body declaration gives a direction. It stays
silent when the body holds a macro item, an `` `include ``, a verbatim or an
error item. It reports 0 on OpenTitan `hw`.
- **`suspicious-semicolon` exempts the drain idiom `while (<call>);`**
(`while (fifo.try_get(item));`), only when the whole condition is one call:
−5 findings on OpenTitan. `while (busy);` and `while (!q.try_get(x));` are
still reported.
- **`incomplete-assignment` sees a miss in a nested `if`**, and counts a
fully enumerated `case` without `default` as complete only when its selector
is proven to be that wide: +1 finding on OpenTitan, a real latch
(`rom_ctrl/dv/tb/tb.sv:158`).
- **`mismatched-labels`** handles `initial lbl : begin … end : lbl`, and
offers an Unsafe fix that renames a wrong footer to the header's name
(CLI `--fix --unsafe-fixes` only; the editor and MCP apply Safe fixes only).
- Rule options in `[ … ]` lists split on commas outside quotes only, and a
naming-pattern regex nested more than 64 groups deep is refused by name
instead of overflowing the stack.
- **Withdrawn during the round, not shipped:** an autofix for
`uvm-macro-semicolon` (it corrupted code in three QA passes; the rule offers
no fix, as before) and a nested-loop exemption for `instance-shadowing`
(it hid the bug the rule exists for; the 30 OpenTitan hits stay).
### Language server
- **Rename, code-action resolve, `executeCommand` and `willRenameFiles` wait
for a running scan to finish** instead of running against a partly built
index (a module declared twice no longer gets an edit or a refusal at
random); read-only answers from the open buffer still go ahead
(`docs/features/server-ordering-r1`).
- **Rename and port edits carry document versions** (`documentChanges`) when
the client supports them, so an editor can refuse an edit computed against
text it no longer has. A settings push older
than the answer to the startup settings pull no longer overwrites it.
- **The index follows open and closed buffers exactly**
(`docs/features/index-lifecycle-r2`): closing an excluded or unlisted file
removes it, closing an unsaved in-scope file reverts its record to disk, a
buffer opened mid-scan is taken in as if opened before, a large open buffer
keeps its disk record, and a symlinked file is held under one spelling
whichever alias is open.
- **Colours refresh exactly when they change** (`docs/features/lsp-viewport-folding-r9`):
a save that changes how another open file colours (a package type renamed,
a class declared) now refreshes it, and a range answered during a rescan no
longer buys a refresh when the settled answer is the same.
- **A rescan answers between slices of its discovery walk** (512 entries per
slice; `docs/features/server-scaling-r10`). On OpenTitan `hw` a settings
rescan takes 703 → **642 ms** median, a `documentSymbol` sent 5 ms into it
waits 133 → **2.8 ms**, and the store is no longer re-opened (70 → 0 ms).
On 40 000 files the rescan is 12 % faster.
- Refactorings: a rename inside a string with an escaped non-ASCII character
no longer panics; macro-argument carrying is deterministic; renaming a
member of a module declared in two files is refused instead of guessed;
`remove port` no longer counts another module's `.port(…)` in the same file
as a use; `extract module` keeps CRLF line endings
(`docs/features/refactor-correctness-r1`).
- Semantics (`docs/features/semantic-refactor-r8`): a DPI export's name is a
reference; escaped identifiers are in the word census, so a file that only
writes `\my.sig` is found (completion does not offer them); an interface's
named generate blocks are reachable through its ports; an inline nested
struct member resolves; a rename through `bind` handles a bare-instance
target and no longer mistakes a generate-scoped instance for the module's
own; and the refactoring verifier checks each edit of a move on its own.
### MCP server
(`docs/features/mcp-hardening-r3`.)
- **`find` with `refs: true` reuses cached file facts**: on OpenTitan `hw`,
warm, 2.4× faster for a qualified name (1 115 → 474 ms), 2.6× for one
declaration (1 099 → 415 ms) and 3.8× for a name with 300+ declarations
(7 800 → 2 032 ms), with byte-identical answers. A qualified `unit.name`
query is scoped to that unit.
- **`check` accepts a directory or a glob** under a root (`ip/aes/rtl`,
`ip/aes/rtl/*.sv`); unused waivers are reported for the whole design only.
- A file whose modification time is in the future settles instead of being
re-read on every call; `initialize` no longer announces an empty
`prompts` capability.
### Windows
- **UNC workspaces work** (`docs/features/windows-uri-editors-r11`). The
server reads and writes `file://server/share/…` URIs in VS Code's form
(before, they were mangled in both directions), sees through `\\?\` paths,
and returns `\`-separated paths. **This is compile- and link-checked only,
never executed on Windows**: every Windows rule was tested as string code on
macOS.
- **The Windows index cache key changes once**: the workspace root's spelling
changes (`c:/proj` → `c:\proj`), so the index is rebuilt on first start
after upgrading and the old cache directory is left unused.
- On every platform, a `\` in a file name is now written `%5C` and a URI's
`?query#fragment` is no longer read as part of the path.
### Editors
- VS Code: the `lucisv.format.*` override settings above, a toggle for
`missing-port-direction`, `lucisv.mcp.path` pointing at a directory finds
`lucisv-mcp.exe` on Windows, a failing module-view action shows a warning,
and the README's settings table is corrected (`scopeDepth` default `2`, the
eight `lucisv.format.*` rows). Neovim README: references are
workspace-wide and `--stdio` is accepted. `editors/vscode/CHANGELOG.md` has
the editor's view.
### Performance (`docs/performance_take6.md`)
Beyond the numbers above, every other CLI and LSP phase shows no measurable
change; the language server's idle memory after a cold workspace scan fell
531 → 479 MiB (not attributed). Three regressions were found and bisected;
none is fixed in 0.67.0:
- **Formatter peak memory with all workers** rose by about 90–100 MiB
(default 568 → 654 MiB median, `lowrisc` 574 → 674 MiB; with `--threads 1`
it fell 291 → 252 MiB). Cause confirmed, from Round 5: the input's syntax
tree is kept alive while the output is verified. Left as is.
- **`didOpen` of a file over `index.maxFileSize`** costs about 14 ms more
(OpenTitan's 1.3 MB `pinmux_reg_top.sv`: 60–74 → 76–84 ms), from Round 2's
symlink identity map; about 8 ms of it is confirmed.
- **`workspace/symbol`** costs about 2 ms more (1.4–3.2 → 3.8–6.7 ms, same
256 results), from Round 2; the cause is a candidate, not confirmed.
### Project hygiene
- CI and release gates (`docs/features/ci-gates-r4`): `cargo test` runs under
`tools/guard.sh` on macOS and Linux, author stamps are a gate step, a
missing cross toolchain fails `gates.sh` unless `--allow-skip-cross`, and a
release checks tag and versions in a fast `preflight` job and runs the suite
on Linux before building.
- Five more pure-move splits and 23 test modules moved out of their files;
no production file is over 600 lines, and every `#[ignore]` says why
(`docs/features/hygiene-splits-r12`). Documentation and the site sources
were re-synced (`docs/features/docs-sync-r4`).
- **Gates on the release tree:** tests passed per crate — `vlog_parser` 527,
`vlog_semantic` 453, `vlog_refactor` 793, `vlog_formatter` 383,
`vlog_linter` 710, `lucisv_core` 129, `lucisv` 162, `lucisv_server` 2263,
`lucisv_mcp` 400; doc-tests 1, extension 37; corpus 814 / 6, unchanged.
OpenTitan `hw`: 4 039 of 4 046 files format cleanly in every style, 0
verification failures.
## 0.66.2 — 2026-11-24
### Every source file names its author
- **No behaviour change.** Every tracked file that can carry a comment — 880
of them: the Rust sources, the extension's JavaScript, the scripts, the
manifests, the workflows and the documentation — now opens with an author
line and closes with one. The binaries and the formatter's, linter's and
language server's output are what 0.66.1 produced.
- `tools/stamp_author.py` writes the lines and is idempotent; run it after
adding files (`--check` lists what is missing). It leaves alone what a
comment would break or what is regenerated: test fixtures, cases and
snapshots, JSON and JSONL, logs, images, lockfiles, the built site under
`docs/site/dist` and the `LICENSE` files.
- `tools/linux_check.sh --help` reads its own header one line further down,
since the author line now sits under the shebang.
## 0.66.1 — 2026-11-19
### Sticky scroll pins the module instance
- **A module instantiation folds, so its header lines stay pinned** (TODO
§72, `docs/features/instance-folding`). `textDocument/foldingRange` answers
one range per multi-line instantiation from its module-type line, and one
more per instance from the line its name is on when that is a later line,
so both `aes_control_fsm #(` and `) u_aes_control_fsm (` are pinned while
the reader is in the connection list. The closing `);` line stays visible.
What is an instantiation comes from `vlog_semantic::instantiations::sites`;
where it closes is re-read from the tokens, and a statement whose tokens
are not exactly that shape folds nothing.
- Every fold answered before is unchanged and first on a shared start line
(0.66.0 against this tree on 4 933 files: 75 256 ranges identical once the
instance folds are removed). OpenTitan `hw`: 18 200 multi-line
instantiations, none without its fold. Worst file about 2 ms per request
(1.1 ms before).
- Not folded: two-dimensional instance arrays; an instance whose head an
`` `ifdef `` splits.
## 0.66.0 — 2026-11-19
### The overnight queue, complete
0.66.0 closes TODO §71: eight owner-ordered features, each shipped as its own
0.65.x release with a dev round, a QA round and the full gates. Nothing in
the engine changed between 0.65.11 and this release; it adds the topology
and size re-measurement (`docs/topo.md`, `CLAUDE.md`) and is the version to
install. Each line names the release that carries the detail below.
- **Editing and saving no longer re-index the workspace** (0.65.6/0.65.7).
A saved or changed file updates its own records and the files that depend
on it; only a change that can reach everything (a config, a filelist)
rescans.
- **Actions on the open file do not wait for the workspace** (0.65.11).
Hover, go-to-definition, highlights, the outline and folding for names the
file declares answer in milliseconds during a scan or a rescan, and
completion lists what the file can reach first.
- **Highlighting does not wait for the index** (0.65.10). Colours come from
the buffer at once, as a best guess for cross-file names, and are
corrected by one refresh when the index settles.
- **`` `ifdef `` / `` `else `` / `` `endif `` branches fold** and take part
in sticky scroll (0.65.4).
- **Formatter styles** (0.65.5): `auto` follows the file's own style, or
choose `lucisv`, `ansi`, `google`, `lowrisc`, `microsoft` or `nxp`; the presets are one readable
table in `vlog_formatter/src/style.rs`.
- **The module view marks where you are** (0.65.2): the current file's
module and its parents, in shades of orange.
- **Find References next to a name** (0.65.8): a caret just past a name's
last letter now finds it — the cause of "no references" that worked on a
second try — and edits arriving during a rescan are applied in order.
- **Comments are comments** (0.65.3): no bracket or code colouring inside
them, and `TODO`, `FIXME`, `FIX_ME`, `TBD` and your own words
(`lucisv.commentKeywords.custom`) are highlighted.
Also since 0.65.0: releases are gated by `tools/gates.sh`, which
compile-checks Windows and Linux (0.65.1, 0.65.7); CI runs the suite on
Linux as well as macOS, and `lucisv-mcp` no longer serves stale contents
after a same-instant rewrite (0.65.9).
One test change in this release: 0.65.11's Linux CI run failed on a
wall-clock test of the large-file path (24.9x measured against a 24x limit
on a loaded runner; nothing in that path had changed). The test now
re-measures up to three times before failing — a real quadratic regression
measures ~64x every time.
**Not yet seen in a running editor by a human** — every feature above was
verified through the server's protocol and the extension's tests, on
OpenTitan's `hw` tree. Open follow-ups are listed in TODO §71.
## 0.65.11 — 2026-11-19
### Actions on the open file no longer wait for the workspace
(`docs/features/fast-actions`; TODO §71.2. Measured on OpenTitan's `hw` tree
and on generated 20 000- and 40 000-file trees, with the server driven the
way VS Code drives it.)
- **Same-file answers come from the file.** A hover, a go-to-definition, a
type definition, highlights, a rename's first check or a signature help on
a name the file itself declares — and the outline, folding and selection
ranges — are answered from the open buffer at once, even while the index
is being built or rebuilt. Anything that might live in another file still
waits for the index it needs.
| hover on a local name (4 000 / 20 000 / 40 000 files) | 0.65.10 | now |
|---|---:|---:|
| during the startup scan | 547 / 665 / 831 ms | 2.4 / 1.5 / 1.9 ms |
| a new file triggers a rescan, request 5 ms later | 1.2 / 6.0 / 12.3 s | 47 / 167 / 321 ms |
| the same, request read together with the event | 1.2 / 6.0 / 12.3 s | 0.3 / 0.1 / 0.1 ms |
| the same, server busy with a previous delete | 1.3 / 7.0 / 14.3 s | 0.17 / 0.99 / 2.2 s |
- **Every early answer is the settled answer.** A request goes ahead only
when its buffer is open, every older message that could change the buffer
has been applied, its analysis is current, no settings are still on their
way, and the answer is the buffer's alone. 2.9 million early answers were
compared with the answer the finished index gives; none differed.
- **Completion keeps what the file can reach near the top.** Right after the
file's own names it now offers the members of the packages the file
imports, what its class inherits and the macros of the headers it
includes, so a huge workspace no longer pushes them out of the list; such
a name shows the icon and detail of the declaration the file actually
reaches. Completion answers are half the size for VS Code.
- **A new `lucisv.largeFile.threshold` applies to files already open,** the
editor's first settings answer included — not at each file's next edit.
- **Fixed on the way** (present since 0.65.8 and 0.65.10): the editor's
answer to a settings request could be applied ahead of an older settings
change or edit; colours answered while a file-watcher event was waiting
were not refreshed afterwards.
- **What it costs.** Until the editor has answered the server's first
settings request, same-file requests wait (the threshold may change how
the file is read): with an editor that takes 0.5 s to answer, the first
outline arrives after 515 ms — it was 1 043 ms on 0.65.10.
- **Still to come.** Not yet seen in a running editor by a human.
## 0.65.10 — 2026-11-19
### Highlighting no longer waits for the index
(`docs/features/viewport-highlight`; TODO §71.3. Measured on OpenTitan's `hw`
tree with the server driven the way VS Code drives it.)
- **Colours arrive at once.** Building a file's colours takes 0.3–6.5 ms;
nearly all of the wait before first colour was the server holding every
request until the index was ready. A colouring request for a buffer whose
text is current is now answered from that buffer alone, even while a scan
or a widening of the index holds everything else.
| first colour after opening a file | before | now |
|---|---:|---:|
| cold start, whole-workspace scope | 660–685 ms | 3.5–39 ms |
| cold start, folder scope (the default) | 38–74 ms | 3–32 ms |
| a file opened after startup settled, folder scope | 611–641 ms | 2–32 ms |
| a file in a folder not indexed yet, mid-session | 375 ms | 6 ms |
| while a rescan runs | 325–791 ms | 70–159 ms |
The larger figure in each range is a 545 KB file, whose own parse is most
of what remains.
- **Imperfect first, then corrected — once.** Before the index settles,
names that resolve through it (a module or package in another file, an
inherited method) are coloured as local guesses: 96.8 % of tokens already
match the final answer, and nothing is ever coloured as code inside a
comment or a string. When the index settles the server sends one
`workspace/semanticTokens/refresh` and the editor's next answer is the
accurate one. This also fixes colours that used to stay wrong until the
next edit: the first answer was built from a half-finished index and never
revisited (2 745 tokens in one OpenTitan file).
- **The viewport request costs the viewport.** `semanticTokens/range` built
the whole file's tokens and filtered them; it now classifies only the
visible lines (0.3 ms for 60 lines of a 4 000-module buffer, against 98 ms).
- **What it will not do.** A buffer with edits the server has not applied
yet still waits — its existing colours stay on screen. An editor that
cannot be asked to refresh gets early viewport colours only, and its
whole-file answer waits as before. Hover, go-to-definition and every other
request still wait for the index they need; QA compared 978 such answers
with 0.65.8's and they are identical.
- **Still to come.** The file-discovery walk at the start of every scan
answers nothing while it runs, which is what is left of the wait in
whole-workspace scope (62–86 ms for a late open) and during rescans. Not
yet seen in a running editor by a human.
## 0.65.9 — 2026-11-19
### `lucisv-mcp` no longer serves stale contents; the suite runs on Linux
(`docs/features/linux-test-portability`, Round 2; TODO §70.)
- **`lucisv-mcp` no longer answers from a file's old contents after a
same-size rewrite that restores its old modification time.** The server
decides whether a file changed from its size, mtime, change time and
inode, and re-reads a file whose mtime is too fresh to trust — but it did
not apply that caution to the change time. On Linux, where the change time
moves in 1 ms ticks, a file rewritten at the same size with its mtime put
back (`cp -p`, `rsync -t`, `touch -r`, a rename-over) inside the same tick
as the server's read matched in every field, and index-based answers
(`find`, `hierarchy`, `check`) came from the old text until the file
changed again. `read` and `outline` were never affected. The rule now
covers every timestamp the stamp trusts, its window is 3 s (2 s was too
close to FAT's 2-second timestamps), and a wall clock stepped backwards
since a read distrusts the stamp. Reproduced on purpose on 0.65.8 (every
run with an identical stat was stale) and gone on this build across
overlayfs, tmpfs and APFS; ordinary reads cause no extra re-read.
- **What it still cannot see**, now written down in
`docs/features/mcp-transport`: on Windows there is no change time or
inode, so a same-size rewrite that restores the old mtime more than 3 s
after a read goes unseen; and a store through a writable memory map that
the kernel has not yet reflected in the file's timestamps. A tree whose
files carry modification times in the future is re-read on every call.
- **The test suite is stable on Linux, and CI runs it there.** It was green
on Linux most of the time and failed about one run in three: two test
helpers insisted that writing to a child's input succeed (a usage error
exits before reading), one latency test used a fixed 200 ms budget (it now
measures against a parse of the same buffer in the same process), and one
MCP test could hang on macOS under load on a pipe inherited across
threads. Ten consecutive green runs as root and ten as an unprivileged
user, then six and six by QA. `ci.yml` has a `linux` job (clippy and the
whole suite on Linux x86-64) beside the macOS one.
## 0.65.8 — 2026-11-19
### Find References next to a name, edits kept in order, and a startup that could take minutes
(`docs/features/scan-ordering`; TODO §71.7. Three bugs, all older than this
series of releases.)
- **Find All References, Go to Definition, hover, highlight and rename work
with the cursor just after a name.** A double-click, a click on the right
half of a name's last letter, or a click on a row of lucisv's References
view leaves the cursor there, and the server used to look at the character
*after* the name — so VS Code said "No references found" until you clicked
away and back. Nine requests now resolve the name the cursor touches
(hover, definition, type definition, references, document highlight,
prepare-rename, rename, and the call- and type-hierarchy prepares); the
ones with boundary rules of their own (completion, signature help, linked
editing, selection range) are unchanged. The References view now opens a
row with the cursor at the start of the name. Checked on every identifier
of 350 files: the answer at the end of a name equals the answer at its
start, and a rename there never touches the neighbouring token.
- **Edits made while the workspace is re-indexing are applied in order.**
The server held requests during a scan but applied notifications at once,
so a newer edit could overtake an older one still queued — and since the
editor sends edits as differences, the server's copy of the file then
differed from the editor's until the file was closed and reopened: wrong
symbols, wrong diagnostics, wrong references. Edits, opens, closes, saves
and the other notifications the editor sends are now applied in the order
sent. QA's independent driver: 9 118 bursts, 87 % of them sent mid-scan,
no wrong text, no lost or duplicated answer; the same check fails on
0.65.7 at once.
- **Opening a file while the first index is built no longer makes that index
take minutes.** A request followed by a file open in the same batch was
handed back and re-held at every file of the startup scan: about 300–400 s
on OpenTitan instead of 2 s. Now a held batch is handed back at most once
per file actually opened; the same sequence takes 2.6–3.3 s.
- **Known and left for later**, all present before: a request held during a
scan is answered against the newest text, so a position-based request can
land on a different symbol if an edit moved the text under it (and rename
edits carry no document version for the client to reject a stale one by);
deleting a directory is not seen by the server (VS Code reports the folder,
which the client's source-file filter drops); an excluded file stays in the
index after it is closed; symlinked files can be held under two spellings;
renaming a port of a module defined twice gives an edit or a refusal at
random.
## 0.65.7 — 2026-11-19
### 0.65.6, built for every platform
0.65.6 was tagged but never published: it passed every gate on the Mac and
then failed to compile for Windows, so the release stopped before anything
was built for distribution. This release is 0.65.6 with that fixed; its
notes are below, unchanged.
- **The Windows build compiles again.** One comparison in the language
server's new "is this file already held under another spelling" check moved
a directory identity that is a small copyable pair on macOS and Linux but an
owned path on Windows (`lucisv_server/src/state/incremental.rs`).
- **The gates now compile for the other platforms.** `tools/gates.sh` has a
new `cross` step: `cargo check` of the three shipped binaries for Windows
and Linux, with the same toolchain the release build uses. Until now
platform-conditional code was first compiled by the release build itself,
after the gates.
### 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.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
@@ -2916,3 +3676,5 @@ compiler directive any more. Details:
[macro items](docs/features/macro-items/README.md),
[directives in lists](docs/features/directives-in-lists/README.md) and
[in instances](docs/features/directives-in-instances/README.md).
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+46
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# CLAUDE.md — rules for all agents working on lucisv
lucisv is a ruff-style Verilog/SystemVerilog formatter/linter in Rust.
@@ -89,6 +91,48 @@ Re-measured 2026-10-14 after TODO §55 (pure move, `docs/features/decomposition-
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.
Re-measured 2026-11-19 at 0.66.0, after the overnight queue (TODO §71; non-blank,
non-comment lines before `mod tests`): two files over 600 — `perf.rs` 907
(reasoned) and `lexer.rs` 771 — then `vlog_semantic/src/resolve.rs` 587 and
`vlog_parser/src/parser/item.rs` 582, both at the mark: the next addition to
either goes in a new module. The queue's new modules are all small
(`server/ahead.rs`, `same_file.rs`, `completion/related.rs`, `server/viewport.rs`,
`server/caret.rs`, `state/watched.rs`, `folding/directives.rs`, formatter
`style.rs` / `auto.rs`); `server/dispatch.rs` is 503 and `server/index.rs`
is where four of the eight features met.
Re-measured 2026-11-26 at 0.66.2 (`69383ea`, after `instance-folding`,
`stamp_author`, and Rounds 1–3; same rule: non-blank, non-comment lines before
`#[cfg(test)]`/`mod tests`, excluding `*/tests/`): only test-only
`lucisv_server/src/perf.rs` (907, `#[cfg(test)]` in `main.rs`) exceeds 600;
every non-test production module in the workspace is under 600 (`lexer.rs`
540, top production files `vlog_semantic/src/resolve.rs` 587,
`vlog_parser/src/parser/item.rs` 582, `vlog_parser/src/parser/instance.rs` 569,
`vlog_parser/src/parser/module.rs` 560, `vlog_formatter/src/format/stmt.rs` 556,
`vlog_parser/src/parser/sva.rs` 542, `vlog_refactor/src/extract/flow.rs` 535,
`lucisv_server/src/server/dispatch.rs` 522, `lucisv_server/src/state/discover.rs` 510).
Re-measured 2026-11-26 after Round 12 (`hygiene-splits-r12`, pure moves; same
rule): no production file exceeds 600. Top production files:
`lucisv/src/main.rs` 574, `vlog_parser/src/parser/module.rs` 568,
`parser/split.rs` 554, `parser/sva.rs` 542, `vlog_refactor/src/extract/flow.rs`
535, `parser/class.rs` 518, `parser/covergroup.rs` 517,
`lucisv_server/src/server/dispatch.rs` 515, `state/discover.rs` 515. The round
split `resolve.rs` (587 → 294; `resolve/member.rs` 196, `types.rs` 115),
`parser/item.rs` (589 → 322; `package.rs` 113, `generate.rs` 160),
`parser/instance.rs` (565 → 353; `connection.rs` 218), `format/stmt.rs`
(570 → 400; `case.rs` 94, `timing.rs` 89) and `lexer.rs` (→ 497;
`lexer/number.rs` 114, `define_params.rs` 105, `attach.rs` 54). The `lexer.rs`
540 above was a counting artifact: a `#[cfg(test)]` *field* at line 723 ended
the count 230 lines early, and the file was still 771. This measurement steps over a `#[cfg(test)]`
that is not the test module; counted that way
`vlog_refactor/src/rename/warnings.rs` is 521 (80 by the bare rule),
`rename/mod.rs` 494 and `lucisv_server/src/state/rescan.rs` 483. Test-only
files over 600 (declared under `#[cfg(test)]`, so not production): `perf.rs`
907 (reasoned), and the test modules the round moved out of their files in
`lucisv_server` — `nav/tests.rs` 1 926, `inline/tests.rs` 1 170,
`pairs/tests.rs` 1 009, `ports/tests.rs` 910 and nine more between 611 and 818.
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
@@ -215,3 +259,5 @@ proven independent and run serially. Rules for a parallel wave:
not actually independent, which is a planning failure to record.
- After merging, the lead updates `docs/topo.md` for any edge a lane added
or amended, so the next wave plans against reality.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.65.1"
version = "0.67.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.65.1"
version = "0.67.0"
[[package]]
name = "lucisv_mcp"
version = "0.65.1"
version = "0.67.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.65.1"
version = "0.67.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.65.1"
version = "0.67.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.65.1"
version = "0.67.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.65.1"
version = "0.67.0"
[[package]]
name = "vlog_refactor"
version = "0.65.1"
version = "0.67.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.65.1"
version = "0.67.0"
dependencies = [
"vlog_parser",
]
+5 -1
View File
@@ -1,3 +1,5 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[workspace]
resolver = "2"
members = [
@@ -13,7 +15,7 @@ members = [
]
[workspace.package]
version = "0.65.1"
version = "0.67.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
@@ -44,3 +46,5 @@ serde_json = "=1.0.140"
[profile.release]
lto = true
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+95 -20
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# lucisv — Language Utility for Coding In SystemVerilog
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
@@ -57,6 +59,9 @@ lucisv --no-config rtl/
# pipe through stdin/stdout; --stdin-filename names the buffer in messages
cat foo.sv | lucisv -
cat foo.sv | lucisv --stdin-filename rtl/foo.sv -
# one JSON report (status, exit_code, summary, one entry per file) for CI
lucisv --check --output-format json rtl/
```
### Exit codes (frozen contract — CI may depend on it)
@@ -87,7 +92,10 @@ and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
thread count, where parallelism has already taken the easy win).
An entry is keyed on **(content hash, `line-length`, `indent`,
`uvm-utils-indent`, lucisv version)** per file, and only ever records the *already formatted* verdict — a file that
`uvm-utils-indent`, `style`, each `[format]` override — `begin`, `else`,
`else-after-label`, `port-lists`, `list-indent`, `alignment`,
`connection-align-min` —, lucisv version)** per file (since 0.67.0; lines
written by an older version are dropped as stale), and only ever records the *already formatted* verdict — a file that
would be reformatted, or that failed, is re-checked on every run. The store is one
text file in `.lucisv_cache/` (self-ignoring, like cargo's `target/`); deleting
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
@@ -144,6 +152,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 +184,29 @@ 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).
Single layout choices can be overridden on top of the style (since 0.67.0):
`begin`, `else` and `else-after-label` (`same-line` or `own-line`),
`port-lists` (`fit` or `one-per-line`), `list-indent` (`block` or `wrap`),
`alignment` (`infer` or `always`) and `connection-align-min` (0–8, the spaces
before `(` on the widest row of an aligned connection or `#(…)` table). Each
applies over the named style, and under `style = "auto"` over every
candidate; the editor's spellings are `lucisv.format.begin`, `.else`,
`.elseAfterLabel`, `.portLists`, `.listIndent`, `.alignment` and
`.connectionAlignMin`, which a `lucisv.toml` outranks.
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 +541,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 +551,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`
aligns its widest connection tight (`.clk(clk)`) and differs from its guide in
one place: 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
@@ -921,9 +994,8 @@ The editor now offers these refactorings alongside rename and port propagation:
| Inline module | Copy a separate-file module body into its instance site with simple named-connection substitution and collision-aware internal renaming |
The [language-tools reference](docs/site/src/content/docs/reference/language-tools.md)
records commands and refusal limits. Inline-module has a known transitive
source-selection gap; review hierarchical uses through wrapper modules before
applying it (topology handshake 33).
records commands and refusal limits (the inline-module transitive source-selection gap,
topology handshake 33, closed in v0.51.0).
In the VS Code hierarchy, **Star as DUT** groups a module’s children and
parents into sections alongside Other Modules. Stars persist per workspace;
@@ -940,7 +1012,7 @@ code --install-extension lucisv-<version>-darwin-arm64.vsix
```
— or take `lucisv-<version>-all.vsix`, which carries all five platforms' binaries
in one file and picks the right pair at startup, when the machine is not known
in one file and picks the right binaries at startup, when the machine is not known
in advance (or is Alpine, which VS Code never offers a Linux package to).
Every other editor (and the universal `lucisv-<version>.vsix`, the fallback
@@ -948,7 +1020,7 @@ for platforms not listed) finds `lucisv-server` on `PATH`; the binary comes
from the same build as the CLI:
```bash
cargo build --release # target/release/lucisv-server (and target/release/lucisv)
cargo build --release # target/release/{lucisv,lucisv-server,lucisv-mcp}
cp target/release/lucisv-server ~/.local/bin/ # anywhere on PATH
```
@@ -986,13 +1058,14 @@ vim.lsp.enable('lucisv')
`editors/nvim/README.md`.
**Agents (MCP).** `lucisv-mcp` is lucisv as a Model Context Protocol server
for coding agents: project overview, unit interfaces, outlines, one item's
source, definition/references/hierarchy, diagnostics, and verified edits
(format, lint fixes, rename, the port refactorings, single-item
replace/insert/delete), each with `dry_run`. The platform `.vsix` packages
carry it as a third binary and, on VS Code 1.101+, register it with agent
mode — one server per workspace folder, under **MCP: List Servers**
(`lucisv.mcp.enabled`, `lucisv.mcp.path`). For Claude Code or Cursor, run
for coding agents: nine lean tools in full mode (`hierarchy`, `find`, `outline`,
`read`, `check`, `rename`, `port`, `edit_item`, `format`) and five in
`--read-only` mode (`hierarchy`, `find`, `outline`, `read`, `check`), with no
dry run — edits verify everything in memory before writing all-or-nothing.
The platform `.vsix` packages carry it as a third binary and, on VS Code
1.101+, register it with agent mode — one server per workspace folder, under
**MCP: List Servers** (`lucisv.mcp.enabled`, `lucisv.mcp.path`,
`lucisv.mcp.mode`). For Claude Code or Cursor, run
**lucisv: Copy MCP server config** in VS Code, or by hand:
`cargo build --release -p lucisv_mcp`, then
`claude mcp add lucisv -- lucisv-mcp --root .`. The tool list, the config
@@ -1036,7 +1109,7 @@ expected; no PRs or review required.
## Building
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo build --release # binaries at target/release/{lucisv,lucisv-server,lucisv-mcp}
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
```
@@ -1060,8 +1133,8 @@ Prebuilt downloads live on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases): every tagged
version carries **seven `.vsix` packages** — platform-specific ones for
Apple Silicon and Intel macOS, x86-64 and ARM64 Linux (static musl) and
Windows, each with `lucisv` and `lucisv-server` embedded, an
all-platforms one carrying every pair at once for unknown or mixed
Windows, each with `lucisv`, `lucisv-server`, and `lucisv-mcp` embedded, an
all-platforms one carrying every platform's binaries at once for unknown or mixed
machines, plus the universal no-binary fallback — and a `SHA256SUMS` to
verify them with
(`shasum -a 256 -c SHA256SUMS`). Sideload the one for your machine with
@@ -1089,3 +1162,5 @@ where the version number lives, how the `.vsix` is packaged, and what
marketplace publishing would take if it ever happens — is in
[`tools/RELEASING.md`](tools/RELEASING.md). lucisv is MIT licensed
([`LICENSE`](LICENSE)).
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+4
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# ROADMAP — autonomous coverage loop
Running log of the coverage-improvement loop (started 2026-08-20). The metric
@@ -175,3 +177,5 @@ needs macro expansion, a deliberate non-goal) or not valid standalone
Verilog. The stop condition holds before round 1 of a restart, so **no dev
round was dispatched**. The loop resumes only if open question 2 is decided
(a preprocessing model would put ~1.7% back in reach) or the corpus grows.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+4
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# TODO-MCP — the Model Context Protocol block
Planned 2026-09-23 by the lead at 0.55.0. The analysis and design are in
@@ -498,3 +500,5 @@ Feature README `docs/features/mcp-read-only`. One dev (Opus), one QA
item's lines through `format_range` automatically — costs a refusal
path when the safety net objects. Default in this plan: not automatic;
the agent calls `format` with `lines`.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+293 -1
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# TODO — best practices adopted from ruff and Verible
Curated backlog for lucisv, drawn from `astral-sh/ruff` (architecture, CLI/UX,
@@ -7126,7 +7128,7 @@ 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
- [x] owner/lead decision; if yes, `completion/member.rs` + tests — **WON'T FIX (2026-11-26, Owner Decision #3: "no")**: keep "an unknown head answers nothing" in completion.
## 66. Format Selection that fits where it stands (planned 2026-11-09, owner's order)
@@ -7263,3 +7265,293 @@ Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
- [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.
- [x] `cargo test --workspace` green on Linux as root and with `--user`,
and `tools/gates.sh` green on macOS.
- [x] (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.
- [x] **71.2 Actions stay fast on a huge, heavily-dependent tree.** (0.65.11, `docs/features/fast-actions`) 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.
- [x] **71.3 Highlighting does not wait for the index.** (0.65.10, `docs/features/viewport-highlight`)
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.
- [x] **71.7 Find References sometimes answers "not found"** (0.65.8, `docs/features/scan-ordering`: a server bug — the caret just past a name)
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.
- [x] **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:
- [x] 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.
(Round 5, `parser-formatter-r5`, topo §2.9-44; released in 0.67.0.)
- [x] `` `ifdef `` between `end` and `else` is a parse error.
(Round 5, `parser-formatter-r5`, topo §2.9-45; released in 0.67.0.)
- [x] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
(Round 5, `parser-formatter-r5`, topo §2.9-46; released in 0.67.0.)
- [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.
- [x] One-per-line styles give multi-instance declarations
(`p1 u8 (...), u9 (...)`) the hanging layout.
(Round 5, `parser-formatter-r5`, topo §2.9-47; released in 0.67.0.)
- 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):
- [x] 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".
- [x] 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.
- [x] 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.
- [x] 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.
(Round 2, `index-lifecycle-r2`: excluded buffers and symlinks fixed,
topo §2.9-49/51; directory-only events won't-fix, §2.9-48; released in
0.67.0.)
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.
- 0.65.6 never published (lead, 2026-11-19): the release build failed to
compile `lucisv-server` for Windows — `dir_id` is a `Copy` pair on unix and
a `PathBuf` elsewhere, and 71.1's new code moved it in a closure
(`state/incremental.rs`). The gate caught nothing because nothing before
the release build compiles for another platform. Fixed by the lead (one
line) and shipped as 0.65.7 with 0.65.6's notes; `tools/gates.sh` gains a
`cross` step so the next one is caught before the tag. Seven of the eight
§71 items therefore have releases 0.65.2–0.65.5 and 0.65.7.
- Wave 6 (lead, 2026-11-19): 71.7 shipped as 0.65.8. Left open from it and
from its QA, all older than this series:
- [x] A request held during a scan is answered against the newest text; a
position-based one can resolve a different symbol when an edit moved
the text under it, and rename edits carry no document version.
(Round 1, `server-ordering-r1`, topo §2.9-52; released in 0.67.0.)
- [x] An unheld buffer opened while a scan runs is never taken in
afterwards; closing an unsaved in-scope buffer a rescan had indexed
leaves its text in the index.
(Round 2, `index-lifecycle-r2`, topo §2.9-49/50; released in 0.67.0.)
- [x] Renaming a port of a module defined twice gives an edit or a refusal
at random (`qa717/drv/dup.py`).
(Round 1, `refactor-correctness-r1` + `server-ordering-r1`, topo
§2.9-53; released in 0.67.0.)
- [x] Directory-only watcher events (needs a broader watcher
registration — the owner's call), excluded buffers after close (a
cheap fix belongs in the index layer: adding a file is a wide
change), symlink spellings.
(Round 2: excluded buffers and symlinks fixed, topo §2.9-49/51;
directory-only events won't-fix by owner ruling, §2.9-48; released in
0.67.0.)
- §70 closed (lead, 2026-11-19), shipped with 0.65.9. Once ssh was back the
suite proved flaky on Linux (3 of 9 runs): two test helpers that insisted
a write to a child's stdin succeed, a 200 ms wall-clock bound, an MCP test
that could hang on an inherited pipe — and one real bug, `lucisv-mcp`
serving stale contents after a same-tick, same-size rewrite on Linux
(`project/files.rs`, the racy rule covered the mtime alone). All fixed in
lane 70b (`docs/features/linux-test-portability`, Round 2); Linux is green
10/10 as root and as a user (dev) and 6/6 each (QA); `ci.yml` has its
`linux` job. Left open:
- [x] A file with an mtime in the future is re-read by `lucisv-mcp` on
every call, forever (67 ms against 7 ms per `find` on 4 000 files).
(Round 3, `mcp-hardening-r3`, topo §2.9-54; released in 0.67.0.)
- [x] `crates/lucisv/tests/cli.rs:2149` asserts only an empty stdout, no
exit code.
(Round 5, `cli-path-r5`, topo §2.9-55; released in 0.67.0.)
- [x] `crates/lucisv_mcp/tests/qa_m3.rs` uses unix-only APIs with no cfg:
`cargo check --all-targets` for Windows fails there (tests only).
(Round 3, `mcp-hardening-r3`, topo §2.9-56; released in 0.67.0.)
- [x] The release is still gated on macOS alone; Windows is compile-checked
(`cross`), never executed.
(Round 4, `ci-gates-r4`, topo §2.9-57: the release now waits for a
Linux clippy + test job; Windows is still compile-checked only;
released in 0.67.0.)
- Wave 7 (lead, 2026-11-19): 71.3 shipped as 0.65.10, re-applied onto
0.65.8's message loop by hand and re-validated by a second QA round. Left
open from it:
- [x] The discovery walk at the start of every scan answers nothing while
it runs: a late open in workspace scope still waits 62–86 ms for
colour and a rescan holds colours 70–159 ms. Making the walk
resumable needs its own identical-result proof (`state/discover.rs`).
- [x] A `range` answered during a rescan always counts as a guess and
costs one refresh at settle even when nothing changed.
(Round 9, `lsp-viewport-folding-r9`, topo §2.9-59; released in 0.67.0.)
- [x] An edit in one file that changes how another OPEN file colours sends
no refresh (as before this lane).
(Round 9, `lsp-viewport-folding-r9`, topo §2.9-60; released in 0.67.0.)
- Wave 8 (lead, 2026-11-19): 71.2 shipped as 0.65.11 after four dev rounds
and four QA rounds — two QA failures, so the last round ran with Fable 5.2
as dev and QA (`docs/features/fast-actions`, Review). Left open from it:
- [x] Inside the startup settings wait, the client's answer to the pull is
applied ahead of an older settings push held with it
(`server/startup.rs`, `take_the_answer_out_of_held`; predates the
lane; needs a client whose push and answer disagree in one burst).
(Round 1, `server-ordering-r1`, topo §2.9-61; released in 0.67.0.)
- [x] `tests/fast_actions_bursts.rs`'s oracle accepts an answer the
reference gives after any later message of the round: 2–9 % of
injected stale answers pass when a later message restores the state.
(Round 1, `server-ordering-r1`, topo §2.9-62; released in 0.67.0.)
- [x] Whether a large open buffer is in the index depends on when it was
opened, saved or scanned (predates the lane; 77–98 answers differ
between a settled session and a fresh server on OpenTitan).
(Round 2, `index-lifecycle-r2`, topo §2.9-63; released in 0.67.0.)
- [x] The 40 000-file rescan after a delete takes either 12.3 s or
14.5–15.5 s, on 0.65.10 and on this tree alike; cause not found.
(Round 10: not reproducible on a quiet machine — unimodal 7.4–7.8 s
over 39 runs; closed as such in topo §2.9-64, remainder in #71/#72.)
## 72. Sticky scroll pins the module instance (planned 2026-11-19, owner's order)
Owner: "only the module definition is floating. I want to extend this a
little so that the module instance would be floating as well." Folds come
only from keyword pairs and `` `ifdef `` branches, so nothing delimited by
`( )` pins. Surveyed on OpenTitan `hw` (4 047 files): 162 instances of 50+
lines, none pinned; 132 of them write `#(` on the type line, so the instance
name sits on a later `) u_name (` line. Example:
`hw/ip/aes/rtl/aes_control_fsm_n.sv:382-594`. One lane (dev, then QA),
feature README `docs/features/instance-folding/README.md`.
- [x] `crates/lucisv_server/src/folding/instances.rs` (new): one fold per
multi-line module instantiation from its module-type line, and one more
per instance from the line its name is on when that is a different
line, so both `aes_control_fsm #(` and `) u_aes_control_fsm (` pin
while the reader is in the connection list. The closing line stays
visible, as for every scope fold.
- [x] `crates/lucisv_server/src/folding.rs`: the third source merged through
`in_answer_order`; every fold the server answered before is still
there, unchanged and first on a shared start line.
- [x] Tests in the same change, and `folding/opentitan_sweep.rs` extended:
instances counted independently, existing folds proven unchanged.
- [x] `editors/vscode/README.md`: the sticky-scroll row names the instance.
- [x] Seen in a running VS Code (owner, 2026-11-19, on the local 0.66.1
build). Shipped as 0.66.1.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+5
View File
@@ -1,6 +1,9 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
description = "A Verilog/SystemVerilog formatter, in the spirit of ruff"
@@ -15,3 +18,5 @@ vlog_parser = { path = "../vlog_parser" }
vlog_formatter = { path = "../vlog_formatter" }
vlog_linter = { path = "../vlog_linter" }
rayon = { workspace = true }
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+188 -14
View File
@@ -1,7 +1,9 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! 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.
@@ -18,12 +20,12 @@ pub enum Command {
Check,
}
/// How `lucisv check` renders its diagnostics.
/// How `lucisv` renders its output when `--output-format` is given.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
/// `FILE:LINE:COL: message [rule-name]`, one per line.
/// Human-readable text (`would reformat: PATH`, `FILE:LINE:COL: message [rule]`).
Text,
/// One JSON array of diagnostic objects.
/// Structured JSON report (format mode) or array of diagnostic objects (`check`).
Json,
}
@@ -58,10 +60,12 @@ 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>,
/// `check` only: how diagnostics are rendered.
/// How diagnostics (`check`) or format reports (`format`) are rendered.
pub output_format: OutputFormat,
/// `check` only: apply safe fixes and write the files back.
pub fix: bool,
@@ -98,8 +102,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;
}
@@ -112,6 +121,7 @@ impl Options {
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config.apply_overrides(overrides_from_file(file));
config
}
@@ -196,7 +206,18 @@ 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
--output-format <FMT> `text` (default): human-readable text output;
`json`: structured JSON report (format mode) or
array of diagnostic objects (`check` mode). In
format mode, cannot be combined with `--diff`,
`--stdout`, or stdin without `--check`
-h, --help show this help
-V, --version show version
@@ -210,8 +231,6 @@ CHECK OPTIONS (`lucisv check` only):
off for a single file or a stdin buffer, where it cannot. `--select` runs
one either way; `--ignore`, or `ignore` under `[lint]` in lucisv.toml,
turns one off.
--output-format <FMT> `text` (default): FILE:LINE:COL: message [rule];
`json`: one array of diagnostic objects
--fix apply safe fixes and write the files back
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
one yet, so today this changes nothing)
@@ -275,7 +294,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 +307,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 +356,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,
@@ -389,6 +411,9 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
}
"--stdin-filename" => {
let v = args.next().ok_or("--stdin-filename requires a value")?;
if v.is_empty() {
return Err("--stdin-filename requires a non-empty path".to_string());
}
opts.stdin_filename = Some(v);
}
"--line-length" => {
@@ -400,6 +425,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);
@@ -489,7 +518,6 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
let lint_only = [
(opts.fix, "--fix"),
(opts.unsafe_fixes, "--unsafe-fixes"),
(opts.output_format != OutputFormat::Text, "--output-format"),
(!opts.select.is_empty(), "--select"),
(!opts.ignore.is_empty(), "--ignore"),
(!opts.waiver_files.is_empty(), "--waiver-file"),
@@ -508,6 +536,19 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
return Err(format!("{flag} is only valid for `lucisv check`"));
}
}
if opts.output_format == OutputFormat::Json {
if opts.diff {
return Err("--output-format json cannot be combined with --diff".to_string());
}
if opts.stdout {
return Err("--output-format json cannot be combined with --stdout".to_string());
}
if opts.is_stdin() && !opts.check {
return Err(
"--output-format json requires --check when reading from stdin".to_string()
);
}
}
}
Command::Check => {
for (given, flag) in format_only {
@@ -523,9 +564,24 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
Ok(())
}
/// Map optional `[format]` keys from `lucisv.toml` into [`vlog_formatter::StyleOverrides`].
fn overrides_from_file(file: &FileConfig) -> vlog_formatter::StyleOverrides {
use vlog_formatter::{Alignment, ListIndent, Placement, PortLists, StyleOverrides};
StyleOverrides {
begin: file.format_begin.and_then(Placement::parse),
else_keyword: file.format_else.and_then(Placement::parse),
else_after_label: file.format_else_after_label.and_then(Placement::parse),
port_lists: file.format_port_lists.and_then(PortLists::parse),
list_indent: file.format_list_indent.and_then(ListIndent::parse),
alignment: file.format_alignment.and_then(Alignment::parse),
connection_align_min: file.format_connection_align_min,
}
}
#[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 +624,101 @@ 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 the_core_format_override_choices_match_the_formatter() {
use vlog_formatter::{Alignment, ListIndent, Placement, PortLists};
assert_eq!(config::PLACEMENT_NAMES, ["same-line", "own-line"]);
for name in config::PLACEMENT_NAMES {
assert_eq!(Placement::parse(name).map(Placement::as_str), Some(name));
}
assert_eq!(config::PORT_LISTS_NAMES, ["fit", "one-per-line"]);
for name in config::PORT_LISTS_NAMES {
assert_eq!(PortLists::parse(name).map(PortLists::as_str), Some(name));
}
assert_eq!(config::LIST_INDENT_NAMES, ["block", "wrap"]);
for name in config::LIST_INDENT_NAMES {
assert_eq!(ListIndent::parse(name).map(ListIndent::as_str), Some(name));
}
assert_eq!(config::ALIGNMENT_NAMES, ["infer", "always"]);
for name in config::ALIGNMENT_NAMES {
assert_eq!(Alignment::parse(name).map(Alignment::as_str), Some(name));
}
}
#[test]
fn config_with_layers_selective_format_overrides_over_style_and_auto() {
use vlog_formatter::{Alignment, Placement};
let file = FileConfig {
format_style: Some("google"),
format_begin: Some("own-line"),
format_connection_align_min: Some(0),
..Default::default()
};
let cfg = parse(&["rtl"]).unwrap().config_with(&file);
assert_eq!(cfg.style.name, "google");
assert_eq!(cfg.style.begin, Placement::OwnLine);
assert_eq!(cfg.style.connection_align_min, 0);
let cli_lowrisc = parse(&["--style", "lowrisc", "rtl"]).unwrap().config_with(&file);
assert_eq!(cli_lowrisc.style.name, "lowrisc");
assert_eq!(cli_lowrisc.style.begin, Placement::OwnLine);
let auto_file = FileConfig {
format_style: Some("auto"),
format_alignment: Some("always"),
..Default::default()
};
let auto_cfg = parse(&["rtl"]).unwrap().config_with(&auto_file);
assert!(auto_cfg.auto_style);
assert_eq!(auto_cfg.overrides.alignment, Some(Alignment::Always));
}
#[test]
fn config_excludes_are_appended_to_cli_excludes() {
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
@@ -683,4 +834,27 @@ mod tests {
assert!(parse(&["--rules-doc"]).is_err());
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
}
#[test]
fn format_output_format_json_and_stdin_filename_validation() {
assert_eq!(
parse(&["--check", "--output-format", "json", "a.sv"]).unwrap().output_format,
OutputFormat::Json
);
assert_eq!(
parse(&["--output-format", "json", "a.sv"]).unwrap().output_format,
OutputFormat::Json
);
assert_eq!(
parse(&["--check", "--output-format", "json", "-"]).unwrap().output_format,
OutputFormat::Json
);
assert!(parse(&["--diff", "--output-format", "json", "a.sv"]).is_err());
assert!(parse(&["--stdout", "--output-format", "json", "a.sv"]).is_err());
assert!(parse(&["--output-format", "json", "-"]).is_err());
assert!(parse(&["--output-format", "text", "--stdout", "a.sv"]).is_ok());
assert!(parse(&["--stdin-filename", "", "-"]).is_err());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,5 +1,9 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `--diff`'s unified diff. The printer lives in `lucisv_core::diff`, shared
//! with the MCP server's `dry_run` (Handshake MCP-1, a pure move); this module
//! keeps the CLI's `diff::unified` path.
pub use lucisv_core::diff::unified;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+6 -2
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The `lucisv check` driver: lint files, print diagnostics, apply fixes.
//!
//! Everything about *which* files are linted — the walk, `--exclude`,
@@ -342,7 +344,7 @@ fn reads_packages(rule: &'static dyn Rule) -> bool {
}
/// The command line's list when it said anything, else the config file's.
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
pub(crate) fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
if cli.is_empty() {
config.unwrap_or(&[])
} else {
@@ -712,7 +714,7 @@ fn fix_json(violation: &Violation) -> String {
/// A JSON string literal. Hand-rolled: the shape is three fields deep and
/// pulling in a serialization framework for it is not a trade worth making.
fn quote(text: &str) -> String {
pub(crate) fn quote(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
@@ -880,3 +882,5 @@ mod tests {
assert_eq!(quote("bell\u{7}"), "\"bell\\u0007\"");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+311 -75
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! lucisv — a Verilog/SystemVerilog formatter and linter in the spirit of
//! `ruff format` and `ruff check`.
//!
@@ -21,18 +23,22 @@ use std::cell::Cell;
use std::collections::HashSet;
use std::io::Read;
use std::panic::AssertUnwindSafe;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use args::{Command, Options, OutputFormat};
use lucisv_core::atomic::write_atomic;
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
use lucisv_core::path::normalize_under;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use vlog_formatter::{
format_range, format_source, Alignment, Config, FormatError, LineRanges, ListIndent, Placement,
PortLists, VerificationError,
};
use vlog_parser::PARSE_STACK_SIZE;
fn main() -> ExitCode {
@@ -99,46 +105,13 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
if opts.is_stdin() {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
return match run_check_stdin(opts) {
Ok(code) => code,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
ExitCode::from(2)
}
};
let mut src = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
eprintln!("error: reading stdin: {e}");
return ExitCode::from(2);
}
// A stdin buffer is one text with nothing around it: there is no
// census to build and no other file to ask about, so the rules that
// need a project stay off. `--select` still reaches them.
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it exactly as `[lint] select` does.
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
Ok(external) => external,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -156,6 +129,31 @@ fn run_check(opts: &Options) -> ExitCode {
}
}
/// Lints one stdin buffer under the project config governing `--stdin-filename`
/// (or the working directory), applying CLI over config rule selection.
fn run_check_stdin(opts: &Options) -> Result<ExitCode, String> {
let (config, file_config) = stdin_config(opts)?;
let mut src = String::new();
std::io::stdin().read_to_string(&mut src).map_err(|e| format!("reading stdin: {e}"))?;
// A stdin buffer is one text with nothing around it: there is no census
// to build and no other file to ask about, so workspace rules stay off.
let select = lint::pick(&opts.select, file_config.lint_select.as_deref());
let ignore = lint::pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, false).map_err(|e| {
let origin = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string());
format!("{origin}: {e}")
})?;
let options = lint::rule_options(&file_config)?;
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it alongside `[lint] select` and `[lint.<rule>]`.
let external = lint::external_waivers(opts, std::iter::once(&file_config))?;
Ok(lint::check_stdin(opts, &src, &config, &rules, &options, &external))
}
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let (config, _file_config) = match stdin_config(opts) {
@@ -168,15 +166,32 @@ fn run_stdin(opts: &Options) -> ExitCode {
let mut src = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
eprintln!("error: reading stdin: {e}");
if opts.output_format == OutputFormat::Json {
let info = FormatErrorInfo::io(&e);
let entries = [JsonEntry::error(name.to_string(), info)];
print_format_json(&entries, true, 0, 0, 0, 1);
}
return ExitCode::from(2);
}
let out = match format_contained(&src, &config, opts.lines.as_ref()) {
Ok(o) => o,
Err(e) => {
eprintln!("error: {name}: {e}");
Err(info) => {
eprintln!("error: {name}: {}", info.display);
if opts.output_format == OutputFormat::Json {
let entries = [JsonEntry::error(name.to_string(), info)];
print_format_json(&entries, true, 0, 0, 0, 1);
}
return ExitCode::from(2);
}
};
if opts.output_format == OutputFormat::Json {
let changed = usize::from(out != src);
let unchanged = usize::from(out == src);
let status = if changed > 0 { "would-reformat" } else { "unchanged" };
let entries = [JsonEntry::ok(name.to_string(), status, false)];
print_format_json(&entries, true, changed, unchanged, 0, 0);
return if changed > 0 { ExitCode::from(1) } else { ExitCode::SUCCESS };
}
if !opts.read_only() {
print!("{out}");
return ExitCode::SUCCESS;
@@ -216,31 +231,53 @@ fn run_files(opts: &Options) -> ExitCode {
let results: Vec<FileResult> =
jobs.par_iter().map(|(file, config, _)| process_file(file, config, opts, &cache)).collect();
let json = opts.output_format == OutputFormat::Json;
let mut entries = if json { Vec::with_capacity(results.len()) } else { Vec::new() };
let (mut changed, mut unchanged, mut errors, mut cached) = (0usize, 0usize, 0usize, 0usize);
for (index, result) in results.into_iter().enumerate() {
let (file, config, _) = &jobs[index];
if let Some(content) = result.clean {
cache.record(file, entry_for(content, config));
}
let name = || file.display().to_string();
match result.outcome {
Outcome::Unchanged => unchanged += 1,
Outcome::Unchanged => {
unchanged += 1;
if json {
entries.push(JsonEntry::ok(name(), "unchanged", false));
}
}
Outcome::Cached => {
unchanged += 1;
cached += 1;
if json {
entries.push(JsonEntry::ok(name(), "cached", true));
}
}
Outcome::Printed(text) => print!("{text}"),
Outcome::Changed(text) => {
changed += 1;
print!("{text}");
if json {
let status = if opts.read_only() { "would-reformat" } else { "reformatted" };
entries.push(JsonEntry::ok(name(), status, false));
} else {
print!("{text}");
}
}
Outcome::Failed(message) => {
Outcome::Failed(info) => {
errors += 1;
eprintln!("error: {message}");
eprintln!("error: {}: {}", file.display(), info.display);
if json {
entries.push(JsonEntry::error(name(), info));
}
}
}
}
cache.store();
if json {
print_format_json(&entries, opts.read_only(), changed, unchanged, cached, errors);
}
if !opts.stdout {
report(opts, changed, unchanged, cached, errors);
}
@@ -285,8 +322,8 @@ enum Outcome {
/// The file would change, or did. The text is the `--diff` hunk or the
/// `--check` line, and is empty when the file was rewritten in place.
Changed(String),
/// `<path>: <what went wrong>`. The file was left untouched.
Failed(String),
/// What went wrong while reading, formatting, or writing the file.
Failed(FormatErrorInfo),
}
/// Formats one file and, unless the run is read-only, writes it back.
@@ -296,7 +333,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
let name = file.display();
let src = match std::fs::read_to_string(file) {
Ok(s) => s,
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
Err(e) => return FileResult::plain(Outcome::Failed(FormatErrorInfo::io(&e))),
};
let hash = content_hash(src.as_bytes());
if cache.is_clean(file, entry_for(hash, config)) {
@@ -304,7 +341,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
}
let out = match format_contained(&src, config, opts.lines.as_ref()) {
Ok(o) => o,
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
Err(info) => return FileResult::plain(Outcome::Failed(info)),
};
if opts.stdout {
return FileResult::plain(Outcome::Printed(out));
@@ -318,7 +355,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
} else if opts.check {
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
FileResult::plain(Outcome::Failed(FormatErrorInfo::io(&e)))
} else {
// The bytes now on disk are formatted, so they are what the cache
// records — not the input's hash.
@@ -333,11 +370,36 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
/// the key, not the config file that produced them, so identical settings
/// from different `lucisv.toml` files share entries.
fn entry_for(content: u64, config: &Config) -> Entry {
if config.auto_style {
return Entry {
content,
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
style: config.style_name(),
begin: config.overrides.begin.map_or("auto", Placement::as_str),
else_keyword: config.overrides.else_keyword.map_or("auto", Placement::as_str),
else_after_label: config.overrides.else_after_label.map_or("auto", Placement::as_str),
port_lists: config.overrides.port_lists.map_or("auto", PortLists::as_str),
list_indent: config.overrides.list_indent.map_or("auto", ListIndent::as_str),
alignment: config.overrides.alignment.map_or("auto", Alignment::as_str),
connection_align_min: config.overrides.connection_align_min,
};
}
let effective = config.effective_style();
Entry {
content,
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
style: config.style_name(),
begin: effective.begin.as_str(),
else_keyword: effective.else_keyword.as_str(),
else_after_label: effective.else_after_label.as_str(),
port_lists: effective.port_lists.as_str(),
list_indent: effective.list_indent.as_str(),
alignment: effective.alignment.as_str(),
connection_align_min: Some(effective.connection_align_min),
}
}
@@ -438,25 +500,7 @@ fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
/// best two names for it can be compared by. Neither is ever the path lucisv
/// reports: that stays the first spelling seen.
fn identity(cwd: &Path, path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
/// answers for paths that do not exist, where there is nothing to resolve.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
std::fs::canonicalize(path).unwrap_or_else(|_| normalize_under(cwd, path))
}
/// The settings for a buffer piped in on stdin: discovery anchors on
@@ -466,7 +510,7 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
let file = match opts.stdin_filename.as_deref().filter(|s| !s.is_empty()) {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
@@ -497,6 +541,153 @@ fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, error
}
}
/// Structured error detail for `--output-format json` paired with the text
/// display string used on stderr.
#[derive(Debug, Clone, PartialEq, Eq)]
struct FormatErrorInfo {
category: &'static str,
line: Option<u32>,
column: Option<u32>,
message: String,
display: String,
}
impl FormatErrorInfo {
fn io(err: &std::io::Error) -> Self {
let message = err.to_string();
Self { category: "io-error", line: None, column: None, display: message.clone(), message }
}
fn panic(msg: &str) -> Self {
let message = format!("panicked while formatting: {msg}");
Self { category: "panic", line: None, column: None, display: message.clone(), message }
}
fn from_format(err: &FormatError) -> Self {
let display = err.to_string();
match err {
FormatError::Source(vlog_parser::Error::Lex(e)) => Self {
category: "lex-error",
line: Some(e.line),
column: Some(e.col),
message: e.message.clone(),
display,
},
FormatError::Source(vlog_parser::Error::Parse(e)) => Self {
category: "parse-error",
line: Some(e.line),
column: Some(e.col),
message: e.message.clone(),
display,
},
FormatError::Verification(v) => {
let (line, column) = verification_location(v);
Self {
category: "verification-error",
line,
column,
message: display.clone(),
display,
}
}
FormatError::Selection(msg) => Self {
category: "selection-error",
line: None,
column: None,
message: msg.clone(),
display,
},
}
}
}
fn verification_location(err: &VerificationError) -> (Option<u32>, Option<u32>) {
match err {
VerificationError::Lex { error, .. } => (Some(error.line), Some(error.col)),
VerificationError::Reparse(vlog_parser::Error::Lex(e)) => (Some(e.line), Some(e.col)),
VerificationError::Reparse(vlog_parser::Error::Parse(e)) => (Some(e.line), Some(e.col)),
VerificationError::Divergence { expected, got, .. } => {
expected.as_ref().or(got.as_ref()).map_or((None, None), |i| (Some(i.line), Some(i.col)))
}
VerificationError::NotConverged { line, .. } => (u32::try_from(*line).ok(), None),
}
}
struct JsonEntry {
filename: String,
status: &'static str,
cached: bool,
error: Option<FormatErrorInfo>,
}
impl JsonEntry {
fn ok(filename: String, status: &'static str, cached: bool) -> Self {
Self { filename, status, cached, error: None }
}
fn error(filename: String, info: FormatErrorInfo) -> Self {
Self { filename, status: "error", cached: false, error: Some(info) }
}
}
fn format_json_report(
entries: &[JsonEntry],
read_only: bool,
changed: usize,
unchanged: usize,
cached: usize,
errors: usize,
) -> String {
let (status, exit_code) = if errors > 0 {
("error", 2)
} else if read_only && changed > 0 {
("would-reformat", 1)
} else if changed > 0 {
("reformatted", 0)
} else {
("ok", 0)
};
let items: Vec<String> = entries
.iter()
.map(|entry| {
let err = match &entry.error {
Some(info) => format!(
"{{\"category\":{},\"line\":{},\"column\":{},\"message\":{}}}",
lint::quote(info.category),
info.line.map_or_else(|| "null".to_string(), |n| n.to_string()),
info.column.map_or_else(|| "null".to_string(), |n| n.to_string()),
lint::quote(&info.message),
),
None => "null".to_string(),
};
format!(
"{{\"filename\":{},\"status\":{},\"cached\":{},\"error\":{err}}}",
lint::quote(&entry.filename),
lint::quote(entry.status),
entry.cached,
)
})
.collect();
format!(
"{{\"status\":{},\"exit_code\":{exit_code},\
\"summary\":{{\"changed\":{changed},\"unchanged\":{unchanged},\"cached\":{cached},\"errors\":{errors}}},\
\"files\":[{}]}}",
lint::quote(status),
items.join(","),
)
}
fn print_format_json(
entries: &[JsonEntry],
read_only: bool,
changed: usize,
unchanged: usize,
cached: usize,
errors: usize,
) {
println!("{}", format_json_report(entries, read_only, changed, unchanged, cached, errors));
}
/// Formats one source text — all of it, or only the constructs meeting
/// `lines` — reporting a panic inside the formatter as an ordinary error so
/// the rest of the run can continue.
@@ -504,14 +695,14 @@ fn format_contained(
src: &str,
config: &Config,
lines: Option<&LineRanges>,
) -> Result<String, String> {
) -> Result<String, FormatErrorInfo> {
match catch_panic(|| match lines {
Some(lines) => format_range(src, config, lines),
None => format_source(src, config),
}) {
Ok(Ok(out)) => Ok(out),
Ok(Err(e)) => Err(e.to_string()),
Err(msg) => Err(format!("panicked while formatting: {msg}")),
Ok(Err(e)) => Err(FormatErrorInfo::from_format(&e)),
Err(msg) => Err(FormatErrorInfo::panic(&msg)),
}
}
@@ -658,10 +849,55 @@ mod tests {
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
assert!(err.contains("parse error"), "{err}");
assert_eq!(err.category, "parse-error");
assert!(err.display.contains("parse error"), "{}", err.display);
// A range run parses just as strictly: it cannot rescue broken input.
let lines = LineRanges::parse("1").expect("range");
let err = format_contained("module", &Config::default(), Some(&lines)).unwrap_err();
assert!(err.contains("parse error"), "{err}");
assert_eq!(err.category, "parse-error");
assert!(err.display.contains("parse error"), "{}", err.display);
}
#[test]
fn format_error_info_classifies_lex_verification_io_and_panic() {
let lex = format_contained("module m;\n int é;\nendmodule\n", &Config::default(), None)
.unwrap_err();
assert_eq!(lex.category, "lex-error");
assert_eq!((lex.line, lex.column), (Some(2), Some(7)));
let io = FormatErrorInfo::io(&std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
assert_eq!(io.category, "io-error");
assert_eq!((io.line, io.column), (None, None));
let panic_err = FormatErrorInfo::panic("boom");
assert_eq!(panic_err.category, "panic");
assert!(panic_err.message.contains("boom"));
let ver = FormatErrorInfo::from_format(&FormatError::Verification(
VerificationError::NotConverged {
line: 12,
first: "a".to_string(),
second: "b".to_string(),
},
));
assert_eq!(ver.category, "verification-error");
assert_eq!((ver.line, ver.column), (Some(12), None));
let report = format_json_report(
&[
JsonEntry::ok("a.sv".to_string(), "unchanged", false),
JsonEntry::error("b.sv".to_string(), lex),
],
true,
0,
1,
0,
1,
);
assert!(report.contains("\"status\":\"error\""), "{report}");
assert!(report.contains("\"exit_code\":2"), "{report}");
assert!(report.contains("\"category\":\"lex-error\""), "{report}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+365 -13
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! End-to-end tests that drive the real `lucisv` binary.
//!
//! Fixtures use the most trivial Verilog possible so these tests stay
@@ -92,16 +94,29 @@ fn run_in(dir: &TempDir, args: &[&str]) -> Output {
Command::new(LUCISV).args(args).current_dir(&dir.path).output().expect("run lucisv")
}
/// Runs lucisv with the cache switched off, `input` on its stdin.
fn run_with_stdin(args: &[&str], input: &str) -> Output {
let mut child = Command::new(LUCISV)
.args(with_no_cache(args))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn lucisv");
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
child.wait_with_output().expect("run lucisv")
run_with_stdin_raw(&with_no_cache(args), input)
}
/// Writes `input` to the child's stdin and closes it.
///
/// A child that exits without reading — a usage error refuses before it
/// looks at stdin — is legitimate, and the write then races its exit: it
/// fails with `BrokenPipe` when the child is already gone. That one error is
/// not the test's business; the exit code and output the caller asserts on
/// are. (A successful write never meant the child read anything either:
/// every input here is far smaller than a pipe's buffer, so the write lands
/// in the buffer whether or not the child ever reads it.) Any other error is
/// a failure.
fn feed(child: &mut std::process::Child, input: &str) {
let mut stdin = child.stdin.take().expect("stdin");
match stdin.write_all(input.as_bytes()) {
Err(error) if error.kind() != std::io::ErrorKind::BrokenPipe => {
panic!("write stdin: {error:?}")
}
_ => {}
}
}
fn code(out: &Output) -> i32 {
@@ -1177,7 +1192,8 @@ fn flags_of_the_other_tool_are_rejected() {
for args in [
vec!["--fix", &path],
vec!["--select", "no-tabs", &path],
vec!["--output-format", "json", &path],
vec!["--ignore", "no-tabs", &path],
vec!["--waiver-file", "a.waiver", &path],
] {
let out = run(&args);
assert_eq!(code(&out), 2, "{args:?} must not be accepted by the formatter");
@@ -1268,7 +1284,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 +1295,9 @@ 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\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{version}\t{path}\n"
)
}
#[test]
@@ -1754,6 +1773,7 @@ fn lines_neither_reads_nor_writes_the_cache() {
assert!(!fresh.cache_file().exists(), "a range run must not seed the cache");
}
/// Runs lucisv exactly as given, cache and all, `input` on its stdin.
fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
let mut child = Command::new(LUCISV)
.args(args)
@@ -1762,7 +1782,7 @@ fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
.stderr(Stdio::piped())
.spawn()
.expect("spawn lucisv");
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
feed(&mut child, input);
child.wait_with_output().expect("run lucisv")
}
@@ -2132,8 +2152,10 @@ fn a_stdin_buffer_reads_the_rule_options_too() {
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(code(&out), 0, "the config's pattern accepts it: {}", stderr(&out));
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert_eq!(code(&plain), 1, "without the config, macro-name-style fires: {}", stderr(&plain));
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
@@ -2241,11 +2263,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 +2306,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);
@@ -2423,3 +2470,308 @@ fn text_that_merely_says_package_changes_no_finding() {
"{plain}\n---\n{with_noise}"
);
}
// ----------------------------------------------------------------------
// Stdin config discovery across format/check and `--output-format json`
// (Round 5A: #11, #55)
// ----------------------------------------------------------------------
fn run_in_with_stdin(dir: &TempDir, args: &[&str], input: &str) -> Output {
let mut child = Command::new(LUCISV)
.args(with_no_cache(args))
.current_dir(&dir.path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn lucisv");
feed(&mut child, input);
child.wait_with_output().expect("run lucisv")
}
#[test]
fn stdin_discovers_config_relative_to_stdin_filename_across_cwd_and_subcommands() {
let dir = TempDir::new("stdin-cwd-discovery");
dir.write("lucisv.toml", "indent = 4\n[lint]\nignore = [\"no-tabs\"]\n");
dir.write("sub/lucisv.toml", "indent = 6\n[lint]\nselect = [\"no-tabs\"]\n");
let sub_dir = TempDir { path: dir.path.join("sub") };
// From root CWD, relative `sub/new.sv` (which does not exist on disk)
// picks up `sub/lucisv.toml` for both format and check.
let fmt_sub =
run_in_with_stdin(&dir, &["format", "--stdin-filename", "sub/new.sv", "-"], UNINDENTED);
assert_eq!(code(&fmt_sub), 0, "{}", stderr(&fmt_sub));
assert_eq!(stdout(&fmt_sub), "module m;\n wire x;\nendmodule\n");
let chk_sub = run_in_with_stdin(
&dir,
&["check", "--stdin-filename", "sub/new.sv", "-"],
"module new;\n\twire a;\nendmodule\n",
);
assert_eq!(code(&chk_sub), 1, "{}", stderr(&chk_sub));
assert!(stdout(&chk_sub).contains("[no-tabs]"), "{}", stdout(&chk_sub));
assert!(
!stdout(&chk_sub).contains("module-filename"),
"select in sub/lucisv.toml governs stdin"
);
// From `sub/` CWD, `../rtl/m.sv` climbs back out of `sub/` to root's config,
// ignoring `sub/lucisv.toml` (`indent = 6`, `select = ["no-tabs"]`).
let fmt_parent =
run_in_with_stdin(&sub_dir, &["--stdin-filename", "../rtl/m.sv", "-"], UNINDENTED);
assert_eq!(code(&fmt_parent), 0, "{}", stderr(&fmt_parent));
assert_eq!(stdout(&fmt_parent), INDENT_4);
let chk_parent = run_in_with_stdin(
&sub_dir,
&["check", "--stdin-filename", "../rtl/m.sv", "-"],
"module m;\n\twire a;\nendmodule\n",
);
assert_eq!(code(&chk_parent), 0, "parent config ignores no-tabs: {}", stderr(&chk_parent));
assert_eq!(stdout(&chk_parent), "");
// Do not drop `sub_dir` (it shares `dir.path`); forget it safely.
std::mem::forget(sub_dir);
// Unknown rule in `lucisv.toml`'s `[lint] select` still fails stdin check with exit 2.
dir.write("bad_lint/lucisv.toml", "[lint]\nselect = [\"no-such-rule\"]\n");
let bad_rule =
run_in_with_stdin(&dir, &["check", "--stdin-filename", "bad_lint/m.sv", "-"], FORMATTED);
assert_eq!(code(&bad_rule), 2);
assert!(stderr(&bad_rule).contains("unknown rule: no-such-rule"), "{}", stderr(&bad_rule));
// An empty `--stdin-filename` is rejected explicitly instead of walking CWD's parent.
let empty = run_with_stdin(&["--stdin-filename", "", "-"], UNINDENTED);
assert_eq!(code(&empty), 2);
assert!(
stderr(&empty).contains("--stdin-filename requires a non-empty path"),
"{}",
stderr(&empty)
);
}
#[test]
fn format_output_format_json_covers_clean_dirty_inplace_cached_and_errors() {
let dir = TempDir::new("format-json");
let clean = dir.write("a_clean.sv", FORMATTED);
let dirty = dir.write("b_dirty.sv", UNFORMATTED);
let bad_parse = dir.write("c_parse.sv", UNPARSEABLE);
let bad_lex = dir.write("d_lex.sv", "module m;\n int é;\nendmodule\n");
// Clean (--check): exit 0, unchanged.
let out = run(&["--check", "--output-format", "json", &clean]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"ok\""), "{text}");
assert!(text.contains("\"exit_code\":0"), "{text}");
assert!(text.contains("\"changed\":0,\"unchanged\":1,\"cached\":0,\"errors\":0"), "{text}");
assert!(text.contains("\"status\":\"unchanged\",\"cached\":false,\"error\":null"), "{text}");
// Dirty (--check): exit 1, would-reformat, file untouched.
let out = run(&["--check", "--output-format", "json", &dirty]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"would-reformat\""), "{text}");
assert!(text.contains("\"exit_code\":1"), "{text}");
assert!(text.contains("\"changed\":1,\"unchanged\":0,\"cached\":0,\"errors\":0"), "{text}");
assert!(
text.contains("\"status\":\"would-reformat\",\"cached\":false,\"error\":null"),
"{text}"
);
assert_eq!(dir.read("b_dirty.sv"), UNFORMATTED);
// Parse error: exit 2, category parse-error with line/column/message.
let out = run(&["--check", "--output-format", "json", &bad_parse]);
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"status\":\"error\""), "{text}");
assert!(text.contains("\"exit_code\":2"), "{text}");
assert!(text.contains("\"category\":\"parse-error\""), "{text}");
assert!(text.contains("\"line\":2,\"column\":1"), "{text}");
assert!(text.contains("expected identifier"), "{text}");
assert_eq!(dir.read("c_parse.sv"), UNPARSEABLE);
// Lex error: exit 2, category lex-error with line/column/message.
let out = run(&["--check", "--output-format", "json", &bad_lex]);
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"category\":\"lex-error\""), "{text}");
assert!(text.contains("\"line\":2,\"column\":7"), "{text}");
// Mixed directory run: deterministic across thread counts, exit 2 wins.
let parallel = run(&["--check", "--output-format", "json", &dir.root()]);
let serial = run(&["--threads", "1", "--check", "--output-format", "json", &dir.root()]);
assert_eq!(code(&parallel), 2);
assert_eq!(parallel.stdout, serial.stdout);
let text = stdout(&parallel);
assert!(text.contains("\"changed\":1,\"unchanged\":1,\"cached\":0,\"errors\":2"), "{text}");
assert_eq!(text.lines().count(), 1, "stdout must be one JSON document: {text}");
// In-place formatting (default format mode without --check) with JSON + cache.
let cache = dir.cache();
let out = run_raw(&["--output-format", "json", "--cache-dir", &cache, &dirty]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"reformatted\""), "{text}");
assert!(text.contains("\"exit_code\":0"), "{text}");
assert_eq!(dir.read("b_dirty.sv"), FORMATTED);
let cached_out =
run_raw(&["--check", "--output-format", "json", "--cache-dir", &cache, &dirty]);
assert_eq!(code(&cached_out), 0, "{}", stderr(&cached_out));
let text = stdout(&cached_out);
assert!(text.contains("\"status\":\"cached\",\"cached\":true"), "{text}");
assert!(text.contains("\"unchanged\":1,\"cached\":1"), "{text}");
}
#[test]
fn format_output_format_json_works_on_stdin_check_and_rejects_conflicts() {
let out = run_with_stdin(&["--check", "--output-format", "json", "-"], FORMATTED);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(
stdout(&out).contains("\"filename\":\"<stdin>\",\"status\":\"unchanged\""),
"{}",
stdout(&out)
);
let out = run_with_stdin(
&["--check", "--output-format", "json", "--stdin-filename", "rtl/top.sv", "-"],
UNFORMATTED,
);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.contains("\"filename\":\"rtl/top.sv\",\"status\":\"would-reformat\""), "{text}");
assert!(text.contains("\"exit_code\":1"), "{text}");
let out = run_with_stdin(&["--check", "--output-format", "json", "-"], UNPARSEABLE);
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("\"category\":\"parse-error\""), "{}", stdout(&out));
let out = run_with_stdin(
&["--check", "--output-format", "json", "-"],
"module m;\n int é;\nendmodule\n",
);
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("\"category\":\"lex-error\""), "{}", stdout(&out));
let dir = TempDir::new("format-json-conflicts");
let file = dir.write("a.sv", UNFORMATTED);
for bad in [
vec!["--diff", "--output-format", "json", &file],
vec!["--stdout", "--output-format", "json", &file],
vec!["--output-format", "json", "-"],
] {
let out = run_with_stdin(&bad, UNFORMATTED);
assert_eq!(code(&out), 2, "{bad:?}");
}
}
#[cfg(unix)]
#[test]
fn format_output_format_json_reports_io_error_on_unreadable_file() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("format-json-io");
let locked = dir.write("locked.sv", FORMATTED);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).expect("chmod");
if std::fs::read_to_string(&locked).is_ok() {
let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755));
eprintln!("skipped: a mode-000 file is readable by this user (root?)");
return;
}
let out = run(&["--check", "--output-format", "json", &locked]);
let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644));
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"status\":\"error\""), "{text}");
assert!(text.contains("\"exit_code\":2"), "{text}");
assert!(text.contains("\"category\":\"io-error\""), "{text}");
assert!(text.contains("\"line\":null,\"column\":null"), "{text}");
}
#[test]
fn changing_any_selective_format_override_invalidates_the_cache_entry() {
let dir = TempDir::new("cache-overrides");
let src = "\
module m;
always_comb
if (a) begin
x = 1;
end
endmodule
";
dir.write("lucisv.toml", "[format]\nbegin = \"same-line\"\n");
let path = dir.write("a.sv", src);
let cache = dir.cache();
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
let warm = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&warm), 0, "{}", stderr(&warm));
assert!(stderr(&warm).contains("1 file from cache"), "{}", stderr(&warm));
// Toggle `begin` -> `own-line`: must miss cache and detect reformat needed.
dir.write("lucisv.toml", "[format]\nbegin = \"own-line\"\n");
let flipped = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&flipped), 1, "{}", stderr(&flipped));
assert!(!stderr(&flipped).contains("from cache"), "{}", stderr(&flipped));
// Format under `own-line`, warm cache, then flip back to `same-line`.
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
let warm_own = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert!(stderr(&warm_own).contains("1 file from cache"), "{}", stderr(&warm_own));
dir.write("lucisv.toml", "[format]\nbegin = \"same-line\"\n");
let back = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&back), 1, "invalidates back too: {}", stderr(&back));
// And under `style = "auto"`: adding `begin = "same-line"` on an Allman
// file (where `auto` with no override chose `ansi` = `own-line`) MUST
// invalidate the cache even though LUCISV's default is `same-line`.
let allman = "\
module m;
always_comb
if (a)
begin
x = 1;
end
endmodule
";
dir.write("lucisv.toml", "[format]\nstyle = \"auto\"\n");
dir.write("a.sv", allman);
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
assert!(
stderr(&run_raw(&["--check", &path, "--cache-dir", &cache])).contains("1 file from cache")
);
dir.write("lucisv.toml", "[format]\nstyle = \"auto\"\nbegin = \"same-line\"\n");
let auto_overridden = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(
code(&auto_overridden),
1,
"override on auto must miss un-overridden auto entry: {}",
stderr(&auto_overridden)
);
}
#[test]
fn an_older_seven_field_store_is_rebuilt() {
let dir = TempDir::new("cache-old7");
let path = dir.write("a.sv", FORMATTED);
let cache = dir.cache();
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
let hash = lucisv_core::cache::content_hash(FORMATTED.as_bytes());
std::fs::write(
dir.cache_file(),
format!("{hash:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{path}\n"),
)
.unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
let warm = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert!(stderr(&warm).contains("1 file from cache"), "{}", stderr(&warm));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+235
View File
@@ -0,0 +1,235 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `--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));
}
#[test]
fn selective_format_overrides_apply_over_preset_and_auto() {
let dir = TempDir::new("overrides");
dir.write(
"lucisv.toml",
"[format]\nstyle = \"google\"\nbegin = \"own-line\"\nalignment = \"always\"\nconnection-align-min = 0\n",
);
let src = "\
module m (input logic clk, input logic [7:0] data);
always_comb if (clk) begin x = 1; end
sub #(.A(1), .LONGER(2)) u (.clk(clk), .data_in(data));
endmodule
";
let path = dir.write("a.sv", src);
let out = run(&["--no-cache", "--stdout", &path]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(
stdout(&out),
"\
module m (
input logic clk,
input logic [7:0] data
);
always_comb
if (clk)
begin
x = 1;
end
sub #(
.A (1),
.LONGER(2)
) u (
.clk (clk),
.data_in(data)
);
endmodule
"
);
// Override layered onto `style = "auto"`.
dir.write("lucisv.toml", "[format]\nstyle = \"auto\"\nelse = \"own-line\"\n");
let cuddled_in = "\
module m (
input logic a,
input logic b
);
always_comb
if (a) begin
x = 1;
end else begin
x = 2;
end
endmodule
";
let auto_path = dir.write("b.sv", cuddled_in);
let out = run(&["--no-cache", "--stdout", &auto_path]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stdout(&out).contains(" else begin\n"), "{}", stdout(&out));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+5
View File
@@ -1,6 +1,9 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv_core"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
description = "Config discovery and file walking, shared by the lucisv CLI and the lucisv language server"
@@ -10,3 +13,5 @@ name = "lucisv_core"
path = "src/lib.rs"
[dependencies]
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Replacing a file's contents without ever leaving it half written.
//!
//! `fs::write` truncates the target and then writes into it, so a crash, a
@@ -449,3 +451,5 @@ mod tests {
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+224 -21
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The "already formatted" cache: a per-path record of content that a
//! previous run verified is a fixed point, so a repeat run can skip the
//! file entirely.
@@ -12,6 +14,11 @@ use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use crate::config::{
ALIGNMENT_NAMES, CONNECTION_ALIGN_MIN_MAX, LIST_INDENT_NAMES, PLACEMENT_NAMES,
PORT_LISTS_NAMES, STYLE_NAMES,
};
/// The default cache directory, resolved against the current directory.
pub const DEFAULT_DIR: &str = ".lucisv_cache";
@@ -35,6 +42,24 @@ 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,
/// Effective `begin` placement (`"same-line"`, `"own-line"`, or `"auto"`).
pub begin: &'static str,
/// Effective `else` placement (`"same-line"`, `"own-line"`, or `"auto"`).
pub else_keyword: &'static str,
/// Effective `else-after-label` placement (`"same-line"`, `"own-line"`, or `"auto"`).
pub else_after_label: &'static str,
/// Effective `port-lists` mode (`"fit"`, `"one-per-line"`, or `"auto"`).
pub port_lists: &'static str,
/// Effective `list-indent` mode (`"block"`, `"wrap"`, or `"auto"`).
pub list_indent: &'static str,
/// Effective `alignment` mode (`"infer"`, `"always"`, or `"auto"`).
pub alignment: &'static str,
/// Effective `connection-align-min` (`Some(n)` or `None` for unresolved `"auto"`).
pub connection_align_min: Option<usize>,
}
/// The cache for one run: loaded once at startup, written once at exit.
@@ -105,10 +130,25 @@ impl Cache {
continue;
}
let entry = &self.entries[path];
let conn_min = match entry.connection_align_min {
Some(n) => n.to_string(),
None => "auto".to_string(),
};
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{}\t{}\t{}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content,
entry.line_length,
entry.indent,
entry.uvm_utils_indent,
entry.style,
entry.begin,
entry.else_keyword,
entry.else_after_label,
entry.port_lists,
entry.list_indent,
entry.alignment,
conn_min
);
}
text
@@ -146,6 +186,32 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize,
Some((u64::from_str_radix(content, 16).ok()?, line_length.parse().ok()?, indent.parse().ok()?))
}
fn known_or_auto(value: &str, choices: &[&'static str]) -> Option<&'static str> {
if value == "auto" {
Some("auto")
} else {
choices.iter().copied().find(|n| *n == value)
}
}
/// Parses `connection_align_min`: `None` here signals corrupt syntax;
/// `Some(None)` means valid `"auto"` or out-of-range value handled alongside
/// unknown choices as stale rather than corrupt.
fn parse_conn_min(value: &str) -> Option<Option<Option<usize>>> {
if value == "auto" {
return Some(Some(None));
}
if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let n: usize = value.parse().ok()?;
if n <= CONNECTION_ALIGN_MIN_MAX {
Some(Some(Some(n)))
} else {
Some(None)
}
}
/// Parses the store. `None` means "this file is not something lucisv wrote"
/// — one malformed line discards the whole cache, because partial trust in
/// a file already caught lying is not worth the branch. Entries from
@@ -154,28 +220,82 @@ 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.split('\t').collect();
match fields[..] {
[content, line_length, indent, uvm, version, path] => {
[content, line_length, indent, uvm, style, begin, else_kw, else_lbl, port_lists, list_indent, alignment, conn_min, version, path] =>
{
let (content, line_length, indent) = prefix(content, line_length, indent)?;
let uvm_utils_indent = uvm.parse().ok()?;
let conn_min = parse_conn_min(conn_min)?;
if path.is_empty() {
return None;
}
if version == VERSION {
let style = STYLE_NAMES.into_iter().find(|n| *n == style);
let begin = known_or_auto(begin, &PLACEMENT_NAMES);
let else_keyword = known_or_auto(else_kw, &PLACEMENT_NAMES);
let else_after_label = known_or_auto(else_lbl, &PLACEMENT_NAMES);
let port_lists = known_or_auto(port_lists, &PORT_LISTS_NAMES);
let list_indent = known_or_auto(list_indent, &LIST_INDENT_NAMES);
let alignment = known_or_auto(alignment, &ALIGNMENT_NAMES);
if let (
Some(style),
Some(begin),
Some(else_keyword),
Some(else_after_label),
Some(port_lists),
Some(list_indent),
Some(alignment),
Some(connection_align_min),
true,
) = (
style,
begin,
else_keyword,
else_after_label,
port_lists,
list_indent,
alignment,
conn_min,
version == VERSION,
) {
entries.insert(
path.to_string(),
Entry { content, line_length, indent, uvm_utils_indent },
Entry {
content,
line_length,
indent,
uvm_utils_indent,
style,
begin,
else_keyword,
else_after_label,
port_lists,
list_indent,
alignment,
connection_align_min,
},
);
}
}
// 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.
// Pre-Round-6 seven-field store (`style`, no per-knob fields):
// dropped individually as stale so old caches never pass when
// overrides or defaults differ, without discarding valid entries.
[content, line_length, indent, uvm, _style, _version, path] => {
prefix(content, line_length, indent)?;
uvm.parse::<bool>().ok()?;
if path.is_empty() {
return None;
}
}
// A store written before `style` joined the key.
[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.
[content, line_length, indent, _version, path] => {
prefix(content, line_length, indent)?;
if path.is_empty() {
@@ -228,7 +348,20 @@ 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",
begin: "same-line",
else_keyword: "same-line",
else_after_label: "same-line",
port_lists: "fit",
list_indent: "block",
alignment: "infer",
connection_align_min: Some(1),
}
}
#[test]
@@ -262,6 +395,15 @@ 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(&file, Entry { begin: "own-line", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { else_keyword: "own-line", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { else_after_label: "own-line", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { port_lists: "one-per-line", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { list_indent: "wrap", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { alignment: "always", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { connection_align_min: Some(0), ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { connection_align_min: None, ..entry(0xdead) }));
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
}
@@ -276,7 +418,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 +433,8 @@ 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\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -308,6 +451,51 @@ 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, seven-field, and unknown-enum shapes: all stale,
// dropped individually without discarding valid 14-field entries.
let dir = TempDir::new("nostyle");
let old6 = dir.file("old6.sv");
let old7 = dir.file("old7.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\tlucisv\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tbespoke\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tnxp\tsame-line\town-line\town-line\tone-per-line\tblock\talways\t1\t{VERSION}\t{}\n",
1,
old6.to_string_lossy(),
2,
old7.to_string_lossy(),
3,
other.to_string_lossy(),
4,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&old6, entry(1)), "six-field line must be dropped");
assert!(!cache.is_clean(&old7, entry(2)), "seven-field line must be dropped");
assert!(!cache.is_clean(&other, Entry { style: "lucisv", ..entry(3) }));
let nxp_entry = Entry {
style: "nxp",
else_keyword: "own-line",
else_after_label: "own-line",
port_lists: "one-per-line",
alignment: "always",
..entry(4)
};
assert!(cache.is_clean(&mine, nxp_entry));
assert!(!cache.is_clean(&mine, entry(4)), "the style is part of the key");
cache.store();
assert!(!dir.cache_text().contains("old6.sv"), "{}", dir.cache_text());
assert!(!dir.cache_text().contains("old7.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 +513,11 @@ 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\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}",
1,
a.to_string_lossy()
),
"{text}"
);
}
@@ -350,13 +542,22 @@ 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",
"0000000000000001\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\tnan\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t0.2.0\t\n",
"0000000000000001\t100\t2\tfalse\tlucisv\tsame-line\t0.2.0\t/a.sv\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\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\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 +570,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\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -484,3 +685,5 @@ mod tests {
assert!(!Cache::load(&dir.path).is_clean(&weird, entry(1)));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+162 -33
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a small config file needs is supported (comments, `key = int`,
@@ -8,10 +10,37 @@
//! reasoning behind not taking a TOML dependency.
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::path::{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"];
/// Valid values for `[format] begin`, `else`, and `else-after-label`.
pub const PLACEMENT_NAMES: [&str; 2] = ["same-line", "own-line"];
/// Valid values for `[format] port-lists`.
pub const PORT_LISTS_NAMES: [&str; 2] = ["fit", "one-per-line"];
/// Valid values for `[format] list-indent`.
pub const LIST_INDENT_NAMES: [&str; 2] = ["block", "wrap"];
/// Valid values for `[format] alignment`.
pub const ALIGNMENT_NAMES: [&str; 2] = ["infer", "always"];
/// Inclusive bounds for `[format] connection-align-min`.
pub const CONNECTION_ALIGN_MIN_MIN: usize = 0;
pub const CONNECTION_ALIGN_MIN_MAX: usize = 8;
/// All keys recognized under `[format]`.
const FORMAT_KEYS: &str = "style, uvm-utils-indent, begin, else, else-after-label, \
port-lists, list-indent, alignment, connection-align-min";
/// 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 +63,23 @@ 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>,
/// `[format] begin`: override for `Style::begin`.
pub format_begin: Option<&'static str>,
/// `[format] else`: override for `Style::else_keyword`.
pub format_else: Option<&'static str>,
/// `[format] else-after-label`: override for `Style::else_after_label`.
pub format_else_after_label: Option<&'static str>,
/// `[format] port-lists`: override for `Style::port_lists`.
pub format_port_lists: Option<&'static str>,
/// `[format] list-indent`: override for `Style::list_indent`.
pub format_list_indent: Option<&'static str>,
/// `[format] alignment`: override for `Style::alignment`.
pub format_alignment: Option<&'static str>,
/// `[format] connection-align-min`: override for `Style::connection_align_min`.
pub format_connection_align_min: Option<usize>,
/// `[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,33 +222,72 @@ fn parse_entry(
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
uvm-utils-indent under `[format]`; \
{FORMAT_KEYS} 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`, boolean switches, or
/// selective layout/alignment overrides layered onto the active preset.
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
let slot = match key {
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
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(());
}
if key == "connection-align-min" {
return set_int(
&mut config.format_connection_align_min,
key,
value,
CONNECTION_ALIGN_MIN_MIN,
CONNECTION_ALIGN_MIN_MAX,
);
}
if key == "uvm-utils-indent" {
if config.format_uvm_utils_indent.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.format_uvm_utils_indent = Some(parse_bool(key, value)?);
return Ok(());
}
let (slot, choices): (&mut Option<&'static str>, &[&'static str]) = match key {
"begin" => (&mut config.format_begin, &PLACEMENT_NAMES),
"else" => (&mut config.format_else, &PLACEMENT_NAMES),
"else-after-label" => (&mut config.format_else_after_label, &PLACEMENT_NAMES),
"port-lists" => (&mut config.format_port_lists, &PORT_LISTS_NAMES),
"list-indent" => (&mut config.format_list_indent, &LIST_INDENT_NAMES),
"alignment" => (&mut config.format_alignment, &ALIGNMENT_NAMES),
_ => {
return Err(format!(
"unknown key `{key}` under `[format]` \
(the only key is uvm-utils-indent)"
))
return Err(format!("unknown key `{key}` under `[format]` (known keys: {FORMAT_KEYS})"))
}
};
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
*slot = Some(parse_bool(key, value)?);
*slot = Some(parse_choice(key, &parse_string(value)?, choices)?);
Ok(())
}
fn parse_choice(key: &str, name: &str, choices: &[&'static str]) -> Result<&'static str, String> {
choices
.iter()
.copied()
.find(|n| *n == name)
.ok_or_else(|| format!("`{key}` expects one of {}, found `{name}`", choices.join(", ")))
}
/// 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> {
@@ -351,7 +436,7 @@ impl Discovery {
if !self.enabled {
return Ok(FileConfig::default());
}
let absolute = self.absolute(path);
let absolute = crate::path::normalize_under(&self.cwd, path);
match absolute.parent() {
Some(dir) => self.for_dir(dir),
None => Ok(FileConfig::default()),
@@ -363,7 +448,7 @@ impl Discovery {
if !self.enabled {
return Ok(FileConfig::default());
}
let start = self.absolute(dir);
let start = crate::path::normalize_under(&self.cwd, dir);
let mut cursor = start.as_path();
// Directories that resolve to the same answer as `cursor` does.
let mut chain: Vec<PathBuf> = Vec::new();
@@ -390,24 +475,6 @@ impl Discovery {
}
Ok(found)
}
/// Resolves `path` against the current directory and folds away `.`
/// and `..` so the upward walk visits real ancestors. Symlinks are
/// deliberately not resolved.
fn absolute(&self, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { self.cwd.join(path) };
let mut out = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
}
fn config_file_in(dir: &Path) -> Option<PathBuf> {
@@ -614,6 +681,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.
@@ -634,6 +727,40 @@ exclude = [ \"build\", \"*_gen.sv\", ]
assert!(err("[format.uvm]\nx = 1").contains("unknown table"));
}
#[test]
fn the_format_table_carries_all_selective_overrides() {
let cfg = parse(
"[format]\n\
style = \"google\"\n\
begin = \"own-line\"\n\
else = \"own-line\"\n\
else-after-label = \"same-line\"\n\
port-lists = \"fit\"\n\
list-indent = \"block\"\n\
alignment = \"always\"\n\
connection-align-min = 0\n",
)
.expect("parses all overrides");
assert_eq!(cfg.format_style, Some("google"));
assert_eq!(cfg.format_begin, Some("own-line"));
assert_eq!(cfg.format_else, Some("own-line"));
assert_eq!(cfg.format_else_after_label, Some("same-line"));
assert_eq!(cfg.format_port_lists, Some("fit"));
assert_eq!(cfg.format_list_indent, Some("block"));
assert_eq!(cfg.format_alignment, Some("always"));
assert_eq!(cfg.format_connection_align_min, Some(0));
assert!(err("[format]\nbegin = \"bogus\"").contains("`begin` expects"));
assert!(err("[format]\nbegin = own-line").contains("expected a quoted string"));
assert!(err("[format]\nbegin = \"own-line\"\nbegin = \"same-line\"")
.contains("duplicate key `begin`"));
assert!(err("[format]\nconnection-align-min = 9").contains("between 0 and 8"));
assert!(err("[format]\nconnection-align-min = -1").contains("expects an integer"));
assert!(err("[format]\nconnection-align-min = 0\nconnection-align-min = 1")
.contains("duplicate key `connection-align-min`"));
assert!(err("begin = \"own-line\"").contains("unknown key `begin`"));
}
/// The same key in a real config file, so the message a user sees names
/// the file and the line to edit — the ladder `[format]` sits at the top
/// of (`lucisv.toml` outranks the editor setting).
@@ -937,3 +1064,5 @@ exclude = [ \"build\", \"*_gen.sv\", ]
assert_eq!(discovery.for_file(Path::new("y.sv")).unwrap().indent, Some(4));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! A small line-oriented unified diff: the CLI's `--diff` and the MCP
//! server's `dry_run` print the same hunks through this one function.
//! Moved here from `crates/lucisv/src/diff.rs` unchanged (Handshake MCP-1,
@@ -219,3 +221,5 @@ mod tests {
assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+9 -23
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! EDA filelist (`-f`) parsing: the project file every Verilog build
//! already has.
//!
@@ -9,7 +11,7 @@
//! a warning for each problem. See `docs/features/filelist/README.md`.
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
/// How deep `-f` may nest before the reader stops descending.
///
@@ -61,7 +63,7 @@ fn read_with(path: &Path, env: &dyn Fn(&str) -> Option<String>) -> Result<Fileli
listed: HashSet::new(),
depth: 0,
};
let normalized = reader.normalize(path);
let normalized = crate::path::normalize_under(&reader.cwd, path);
reader.seen.insert(normalized);
reader.filelist(path, &text);
Ok(reader.out)
@@ -113,7 +115,7 @@ impl Reader<'_> {
expecting_filelist = true;
} else if let Some(rest) = token.strip_prefix("+incdir+") {
for item in rest.split('+').filter(|s| !s.is_empty()) {
let resolved = self.normalize(&dir.join(item));
let resolved = crate::path::normalize_under(&self.cwd, &dir.join(item));
self.out.incdirs.push(resolved);
}
} else if let Some(rest) = token.strip_prefix("+define+") {
@@ -149,7 +151,7 @@ impl Reader<'_> {
return;
}
let path = dir.join(token);
let normalized = self.normalize(&path);
let normalized = crate::path::normalize_under(&self.cwd, &path);
if !self.seen.insert(normalized) {
self.warn(line, format!("filelist `{token}` was already included, skipping it"));
return;
@@ -171,7 +173,7 @@ impl Reader<'_> {
self.warn(line, format!("no such file `{token}`, skipping it"));
return;
}
let normalized = self.normalize(&path);
let normalized = crate::path::normalize_under(&self.cwd, &path);
if self.listed.insert(normalized.clone()) {
self.out.files.push(normalized);
}
@@ -217,24 +219,6 @@ impl Reader<'_> {
fn warn(&mut self, line: &Line<'_>, what: String) {
self.out.warnings.push(format!("{}:{}: {what}", line.file.display(), line.number));
}
/// Fold `.`/`..` away and resolve against the current directory, so two
/// spellings of one file are one entry. Symlinks are deliberately not
/// resolved, matching `config::Discovery`'s lexical rule.
fn normalize(&self, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { self.cwd.join(path) };
let mut out = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
}
/// Where a warning happened.
@@ -591,3 +575,5 @@ missing.sv
assert_eq!(list.warnings.len(), 2, "{:?}", list.warnings);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+7 -1
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The parts of lucisv that decide *which* files are processed and *with what
//! settings*, shared by the `lucisv` CLI and the `lucisv-server` language server.
//!
@@ -9,7 +11,8 @@
//! an EDA project already does, from a `.f` file. `atomic` is the one write
//! path all of them share: nothing here ever truncates a file it is
//! replacing. `diff` is the unified diff the CLI's `--diff` and the MCP
//! server's `dry_run` both print. See
//! server's `dry_run` both print, and `path` holds the shared lexical `.`/`..`
//! path normalization. See
//! `docs/features/lucisv-core-lift/README.md`, and
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
//! for the rules themselves.
@@ -19,4 +22,7 @@ pub mod cache;
pub mod config;
pub mod diff;
pub mod filelist;
pub mod path;
pub mod walk;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+144
View File
@@ -0,0 +1,144 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Lexical path normalization shared across `lucisv_core`, `lucisv`, and
//! `lucisv_server`.
//!
//! Paths are folded lexically (`.` and `..` resolved component-by-component)
//! without calling `std::fs::canonicalize` so symlinks are never followed and
//! non-existent paths (such as `--stdin-filename` or rename targets) behave
//! identically to existing ones.
use std::path::{Component, Path, PathBuf};
/// Folds `.` and `..` components out of `path` lexically, without touching the
/// filesystem.
///
/// - Leading or excess `..` on a relative path (and after an unrooted Windows
/// drive prefix such as `C:`) are preserved.
/// - `..` immediately after a root directory (`/` on Unix, `C:\` or
/// `\\server\share\` on Windows) is discarded because traversal cannot climb
/// above a root.
/// - A non-empty relative path whose components all cancel (`"."`, `"a/.."`)
/// normalizes to `"."`; an empty path stays empty.
pub fn normalize(path: &Path) -> PathBuf {
let mut parts: Vec<Component<'_>> = Vec::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => match parts.last() {
Some(Component::Normal(_)) => {
parts.pop();
}
Some(Component::RootDir) => {}
Some(Component::Prefix(_)) | Some(Component::ParentDir) | None => {
parts.push(Component::ParentDir);
}
// `CurDir` is never pushed into `parts`.
Some(Component::CurDir) => {}
},
other => parts.push(other),
}
}
if parts.is_empty() {
if path.as_os_str().is_empty() {
return PathBuf::new();
}
return PathBuf::from(".");
}
let mut out = PathBuf::new();
for part in parts {
out.push(part);
}
out
}
/// Resolves `path` against `base` when `path` is relative and normalizes the
/// result lexically.
///
/// An absolute `path` ignores `base` and is normalized directly. On Windows, a
/// root-relative (`\foo`) or drive-relative (`D:foo`) path is joined via
/// [`Path::join`] before normalizing, preserving drive prefixes cleanly.
pub fn normalize_under(base: &Path, path: &Path) -> PathBuf {
if path.is_absolute() {
normalize(path)
} else {
normalize(&base.join(path))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn folds_dots_and_preserves_leading_parent_dirs() {
assert_eq!(normalize(Path::new("")), PathBuf::new());
assert_eq!(normalize(Path::new(".")), PathBuf::from("."));
assert_eq!(normalize(Path::new("././.")), PathBuf::from("."));
assert_eq!(normalize(Path::new("a/..")), PathBuf::from("."));
assert_eq!(normalize(Path::new("a/./b/../c")), PathBuf::from("a/c"));
assert_eq!(normalize(Path::new("./rtl/../rtl/a.sv")), PathBuf::from("rtl/a.sv"));
assert_eq!(normalize(Path::new("../a")), PathBuf::from("../a"));
assert_eq!(normalize(Path::new("a/../../b")), PathBuf::from("../b"));
assert_eq!(normalize(Path::new("../..")), PathBuf::from("../.."));
}
#[test]
fn normalize_under_joins_relative_paths_and_leaves_absolute_ones() {
let base = if cfg!(windows) { Path::new(r"C:\work\proj") } else { Path::new("/work/proj") };
let abs =
if cfg!(windows) { Path::new(r"D:\other\a.sv") } else { Path::new("/other/a.sv") };
assert_eq!(normalize_under(base, Path::new("rtl/./a.sv")), base.join("rtl").join("a.sv"));
assert_eq!(
normalize_under(base, Path::new("../shared/a.sv")),
base.parent().expect("parent").join("shared").join("a.sv")
);
assert_eq!(normalize_under(base, Path::new(".")), base);
assert_eq!(normalize_under(base, Path::new("")), base);
assert_eq!(normalize_under(base, abs), abs);
}
#[cfg(unix)]
#[test]
fn unix_roots_clamp_excess_parent_dirs() {
assert_eq!(normalize(Path::new("/")), PathBuf::from("/"));
assert_eq!(normalize(Path::new("/..")), PathBuf::from("/"));
assert_eq!(normalize(Path::new("/./a/../../b//c/")), PathBuf::from("/b/c"));
assert_eq!(
normalize_under(Path::new("/a/b"), Path::new("/x/../../y")),
PathBuf::from("/y")
);
}
#[cfg(windows)]
#[test]
fn windows_prefixes_and_roots_clamp_or_preserve_parent_dirs() {
assert_eq!(normalize(Path::new(r"C:\")), PathBuf::from(r"C:\"));
assert_eq!(normalize(Path::new(r"C:\..")), PathBuf::from(r"C:\"));
assert_eq!(normalize(Path::new(r"C:\a\..\..\b\c\")), PathBuf::from(r"C:\b\c"));
assert_eq!(
normalize(Path::new(r"\\server\share\a\..\..\b")),
PathBuf::from(r"\\server\share\b")
);
assert_eq!(normalize(Path::new(r"\a\..\..\b")), PathBuf::from(r"\b"));
// Drive-relative paths have no root directory, so climbing past the
// prefix keeps `..` rather than turning into a rooted path.
assert_eq!(normalize(Path::new(r"C:a\..\..\b")), PathBuf::from(r"C:..\b"));
assert_eq!(normalize(Path::new(r"C:.")), PathBuf::from(r"C:"));
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"\other\..\a.sv")),
PathBuf::from(r"C:\a.sv")
);
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"D:rtl\..\a.sv")),
PathBuf::from(r"D:a.sv")
);
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"D:\x\..\..\y.sv")),
PathBuf::from(r"D:\y.sv")
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+47 -1
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! File discovery: directory walking, `--exclude` matching and the
//! `.gitignore` subset documented in
//! `docs/features/parallel-files/README.md`.
@@ -5,6 +7,9 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
mod resumable;
pub use resumable::ResumableWalk;
/// File extensions lucisv formats when walking a directory.
pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
@@ -215,7 +220,7 @@ pub enum DirStatus {
/// Tracks visited directories across one or more walks to ensure cycle termination
/// and detect order divergence.
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DirectoryTracker {
visited: HashMap<DirId, PathBuf>,
has_conflict: bool,
@@ -731,6 +736,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 +806,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 +856,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");
@@ -1064,3 +1108,5 @@ mod tests {
assert!(!tracker.has_conflict());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+246
View File
@@ -0,0 +1,246 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The directory walk of [`collect_files_tracked`](super::collect_files_tracked),
//! a slice at a time.
//!
//! The language server walks the whole workspace at the start of every scan,
//! and until TODO §71's last open item (`docs/features/server-scaling-r10`)
//! it did so in one call that held the workspace for 25–80 ms on OpenTitan
//! and ~260 ms on 40 000 files, answering nothing. This walk is the same
//! walk with its recursion turned into an explicit stack, so the caller can
//! stop it after a bounded number of entries, answer what is waiting, and
//! carry on from exactly where it stopped.
//!
//! **Same walk, not a similar one.** Every filesystem call the recursive walk
//! makes is made here in the same order with the same arguments — `enter`,
//! the directory's `.gitignore`, `read_dir`, then per entry the exclude test,
//! one `metadata`, the ignore test and either a descent or a hand-off — so on
//! a tree that does not change while it runs the two yield the same paths,
//! lengths and warnings in the same order and leave the tracker the same.
//! The module tests prove it for every slice size on trees built to exercise
//! every branch. On a tree that *does* change, each directory is seen as it
//! was when it was read, exactly as the recursive walk sees it; slicing only
//! widens the window.
use std::path::{Path, PathBuf};
use super::{
broken_link_reason, is_excluded, is_ignored, is_source, parse_gitignore, DirStatus,
DirectoryTracker, Ignore, Warning, GITIGNORE,
};
/// One directory being read: its entries still to visit, in name order, and
/// whether entering it pushed a `.gitignore` the walk must pop on leaving.
struct Frame {
entries: std::vec::IntoIter<std::fs::DirEntry>,
pushed: bool,
}
/// A walk of one input, resumable between any two directory entries.
///
/// A file is handed over with the `metadata` the walk read for it — the
/// length [`collect_files_with`](super::collect_files_with) hands over.
/// `None` for an input named rather than walked, exactly as there. Its
/// identity is not taken from it: two entries visited slices apart can see
/// one file as two, so a caller reads identities together after the walk.
///
/// Built by [`ResumableWalk::new`], advanced by [`ResumableWalk::step`] until
/// it reports it is done. The tracker is the caller's and is passed to every
/// step, so several walks — or a walk and a one-shot one — can share one set
/// of directory identities exactly as [`collect_files_tracked`]'s callers do.
///
/// [`collect_files_tracked`]: super::collect_files_tracked
pub struct ResumableWalk {
input: PathBuf,
exclude: Vec<String>,
gitignore: bool,
ignores: Vec<Ignore>,
rel: Vec<String>,
frames: Vec<Frame>,
started: bool,
done: bool,
error: Option<String>,
}
impl ResumableWalk {
/// A walk of `input` that has not touched the filesystem yet.
pub fn new(input: &Path, exclude: Vec<String>, gitignore: bool) -> ResumableWalk {
ResumableWalk {
input: input.to_path_buf(),
exclude,
gitignore,
ignores: Vec::new(),
rel: Vec::new(),
frames: Vec::new(),
started: false,
done: false,
error: None,
}
}
/// Whether the walk has finished.
pub fn is_done(&self) -> bool {
self.done
}
/// What [`collect_files_tracked`](super::collect_files_tracked) would have
/// returned as its error: `input` naming nothing at all.
pub fn error(&self) -> Option<&str> {
self.error.as_deref()
}
/// Visit at most `budget` more entries — starting the walk and leaving a
/// directory count as one each — and report how many were visited; the
/// walk is over when [`ResumableWalk::is_done`] says so. A `budget` of 0
/// is treated as 1, so every step makes progress.
pub fn step(
&mut self,
tracker: &mut DirectoryTracker,
budget: usize,
found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>),
warn: &mut dyn FnMut(Warning),
) -> usize {
let budget = budget.max(1);
let mut visited = 0;
if !self.started {
self.started = true;
self.start(tracker, found, warn);
visited += 1;
}
while !self.done && visited < budget {
visited += 1;
self.next_entry(tracker, found, warn);
}
visited
}
/// The first step: what the input is decides whether there is a walk.
fn start(
&mut self,
tracker: &mut DirectoryTracker,
found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>),
warn: &mut dyn FnMut(Warning),
) {
let input = self.input.clone();
if input.is_dir() {
self.open(&input, tracker, warn);
} else if input.is_file() {
found(input, None);
} else {
self.error = Some(format!("{}: no such file or directory", input.display()));
}
self.done = self.frames.is_empty();
}
/// `Walk::dir`'s first half: enter `dir`, push its ignore file, read it.
/// Returns whether a frame was pushed (the directory was entered).
fn open(
&mut self,
dir: &Path,
tracker: &mut DirectoryTracker,
warn: &mut dyn FnMut(Warning),
) -> bool {
if !matches!(tracker.enter(dir), DirStatus::EnteredFirstTime) {
return false;
}
let pushed = self.push_ignore(dir, warn);
let entries = read_sorted(dir, warn);
self.frames.push(Frame { entries: entries.into_iter(), pushed });
true
}
/// One entry of the innermost directory, or leaving it when it has none.
fn next_entry(
&mut self,
tracker: &mut DirectoryTracker,
found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>),
warn: &mut dyn FnMut(Warning),
) {
let Some(frame) = self.frames.last_mut() else {
self.done = true;
return;
};
let Some(entry) = frame.entries.next() else {
return self.leave();
};
let path = entry.path();
if is_excluded(&path, &self.exclude) {
return;
}
let Ok(meta) = std::fs::metadata(&path) else {
if is_source(&path) {
warn(Warning { path: path.clone(), message: broken_link_reason(&path) });
}
return;
};
self.rel.push(entry.file_name().to_string_lossy().into_owned());
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
if meta.is_dir() {
if self.open(&path, tracker, warn) {
// The name stays on `rel` until this directory is left.
return;
}
} else if meta.is_file() && is_source(&path) {
found(path, Some(&meta));
}
}
self.rel.pop();
}
/// `Walk::dir`'s second half: pop the ignore file, and the directory's
/// own name — which the root never had.
fn leave(&mut self) {
let Some(frame) = self.frames.pop() else { return };
if frame.pushed {
self.ignores.pop();
}
if self.frames.is_empty() {
self.done = true;
} else {
self.rel.pop();
}
}
/// `Walk::push_ignore`, word for word.
fn push_ignore(&mut self, dir: &Path, warn: &mut dyn FnMut(Warning)) -> bool {
let path = dir.join(GITIGNORE);
if !self.gitignore || !path.is_file() {
return false;
}
match std::fs::read_to_string(&path) {
Ok(text) => {
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
true
}
Err(e) => {
warn(Warning { path, message: e.to_string() });
false
}
}
}
}
/// `Walk::entries`' read: every entry of `dir` in path order, each error said.
fn read_sorted(dir: &Path, warn: &mut dyn FnMut(Warning)) -> Vec<std::fs::DirEntry> {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) => {
warn(Warning { path: dir.to_path_buf(), message: e.to_string() });
return Vec::new();
}
};
let mut entries = Vec::new();
for entry in read {
match entry {
Ok(entry) => entries.push(entry),
Err(e) => warn(Warning { path: dir.to_path_buf(), message: e.to_string() }),
}
}
entries.sort_by_key(|e| e.path());
entries
}
#[cfg(test)]
mod tests;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,277 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The identical-result proof at the walk's own level: for every slice size,
//! and for slice sizes that change from step to step, the resumable walk
//! yields exactly what the recursive walk yields — the same events in the
//! same order, the same error, and the same tracker afterwards.
use super::super::collect_files_tracked;
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
/// What a walk said, in the order it said it.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Event {
Found(PathBuf, Option<u64>),
Warned(Warning),
}
/// A scratch tree, removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(tag: &str) -> Tree {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-resumable-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
std::fs::create_dir_all(path.parent().expect("parent")).expect("create parent");
std::fs::write(&path, text).expect("write");
}
#[cfg(unix)]
fn link(&self, rel: &str, target: &str) {
let path = self.path.join(rel);
std::fs::create_dir_all(path.parent().expect("parent")).expect("create parent");
std::os::unix::fs::symlink(target, &path).expect("symlink");
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// Every branch of the walk in one tree: nested `.gitignore` files with a
/// negation and a directory-only rule, an exclude pattern, non-source files,
/// empty directories, and — on unix — a cycle, two aliases of one directory
/// sorting before and after it, and a dangling source link.
fn busy_tree(tag: &str) -> Tree {
let tree = Tree::new(tag);
tree.write(".gitignore", "build/\n*_gen.sv\n");
tree.write("a.sv", "module a;\nendmodule\n");
tree.write("notes.txt", "x");
tree.write("rtl/b.sv", "module b;\nendmodule\n");
tree.write("rtl/b_gen.sv", "module bg;\nendmodule\n");
tree.write("rtl/.gitignore", "!keep_gen.sv\nlocal/\n");
tree.write("rtl/keep_gen.sv", "module k;\nendmodule\n");
tree.write("rtl/local/hidden.sv", "module h;\nendmodule\n");
tree.write("rtl/deep/er/c.svh", "`define C\n");
tree.write("build/out.sv", "module o;\nendmodule\n");
tree.write("skipme/s.sv", "module s;\nendmodule\n");
tree.write("z_real/inc.vh", "`define Z\n");
std::fs::create_dir_all(tree.path.join("empty/inner")).expect("empty dirs");
#[cfg(unix)]
{
tree.link("rtl/loop", "..");
tree.link("a_alias", "z_real");
tree.link("zz_alias", "z_real");
tree.link("rtl/gone.sv", "nowhere.sv");
}
tree
}
/// The recursive walk's events, error and tracker — the oracle.
fn one_shot(input: &Path, exclude: &[String], tracker: DirectoryTracker) -> Outcome {
let mut tracker = tracker;
let mut events = Vec::new();
let error = {
let events = std::cell::RefCell::new(&mut events);
collect_files_tracked(
input.to_str().expect("utf-8 temp path"),
exclude,
true,
&mut tracker,
&mut |path, len| events.borrow_mut().push(Event::Found(path, len)),
&mut |w| events.borrow_mut().push(Event::Warned(w)),
)
.err()
};
Outcome { events, error, tracker, steps: 1 }
}
/// What one walk produced.
#[derive(Debug, PartialEq, Eq)]
struct Outcome {
events: Vec<Event>,
error: Option<String>,
tracker: DirectoryTracker,
/// How many `step` calls it took (not compared).
steps: usize,
}
impl Outcome {
fn same_as(&self, other: &Outcome) -> bool {
self.events == other.events && self.error == other.error && self.tracker == other.tracker
}
}
/// The resumable walk with the budget for each step chosen by `budget`.
fn sliced(
input: &Path,
exclude: &[String],
tracker: DirectoryTracker,
budget: &mut dyn FnMut() -> usize,
) -> Outcome {
let mut tracker = tracker;
let mut events = Vec::new();
let mut walk = ResumableWalk::new(input, exclude.to_vec(), true);
let mut steps = 0;
loop {
steps += 1;
let events = std::cell::RefCell::new(&mut events);
let size = budget();
let visited = walk.step(
&mut tracker,
size,
&mut |path, meta| events.borrow_mut().push(Event::Found(path, meta.map(|m| m.len()))),
&mut |w| events.borrow_mut().push(Event::Warned(w)),
);
assert!(visited >= 1 && visited <= size.max(1), "{visited} of {size}");
if walk.is_done() {
break;
}
assert!(steps < 100_000, "the walk makes progress");
}
assert!(walk.is_done());
Outcome { events, error: walk.error().map(str::to_string), tracker, steps }
}
/// Every fixed slice size from 1 to one past the whole walk.
fn every_slice_size(input: &Path, exclude: &[String], tracker: DirectoryTracker) -> usize {
let oracle = one_shot(input, exclude, tracker.clone());
let longest = sliced(input, exclude, tracker.clone(), &mut || 1).steps;
for size in 1..=longest + 1 {
let got = sliced(input, exclude, tracker.clone(), &mut || size);
assert!(got.same_as(&oracle), "slice size {size}:\n{got:#?}\nvs\n{oracle:#?}");
}
longest
}
#[test]
fn every_slice_size_walks_exactly_what_the_recursive_walk_walks() {
let tree = busy_tree("every");
let exclude = vec!["skipme".to_string()];
let entries = every_slice_size(&tree.path, &exclude, DirectoryTracker::new());
// Premise: the walk is long enough for slicing to matter.
assert!(entries > 20, "{entries} steps");
let oracle = one_shot(&tree.path, &exclude, DirectoryTracker::new());
let found = oracle.events.iter().filter(|e| matches!(e, Event::Found(..))).count();
assert!(found >= 5, "premise: the tree has files to find: {oracle:#?}");
}
#[test]
fn slice_sizes_that_change_between_steps_walk_the_same() {
// Property-style: 200 seeds of a small linear congruential generator pick
// each step's budget between 1 and 7.
let tree = busy_tree("random");
let exclude = vec!["skipme".to_string()];
let oracle = one_shot(&tree.path, &exclude, DirectoryTracker::new());
for seed in 0..200u64 {
let mut state = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
let mut budget = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
1 + ((state >> 33) % 7) as usize
};
let got = sliced(&tree.path, &exclude, DirectoryTracker::new(), &mut budget);
assert!(got.same_as(&oracle), "seed {seed}");
}
}
#[test]
fn a_tracker_another_walk_already_filled_is_honoured_the_same_way() {
// The split startup: the head walk enters a folder first, then the rest
// walks the root with the same tracker — so a directory may already be
// visited, and an alias may be a precedence conflict.
let tree = busy_tree("shared");
let mut tracker = DirectoryTracker::new();
let _ = tracker.enter(&tree.path.join("z_real"));
let _ = tracker.enter(&tree.path.join("rtl"));
every_slice_size(&tree.path, &[], tracker.clone());
#[cfg(unix)]
assert!(
one_shot(&tree.path, &[], tracker).tracker.has_conflict(),
"premise: a_alias sorts first"
);
}
#[test]
fn a_file_a_missing_path_and_an_entered_root_end_as_the_recursive_walk_does() {
let tree = busy_tree("inputs");
every_slice_size(&tree.path.join("a.sv"), &[], DirectoryTracker::new());
every_slice_size(&tree.path.join("nothing-here"), &[], DirectoryTracker::new());
let mut entered = DirectoryTracker::new();
let _ = entered.enter(&tree.path);
every_slice_size(&tree.path, &[], entered);
let missing = one_shot(&tree.path.join("nothing-here"), &[], DirectoryTracker::new());
assert!(missing.error.is_some(), "premise: a missing input is an error");
}
#[test]
#[cfg(unix)]
fn unreadable_directories_and_ignore_files_are_said_at_the_same_point() {
use std::os::unix::fs::PermissionsExt;
let tree = busy_tree("unreadable");
tree.write("locked/x.sv", "module x;\nendmodule\n");
tree.write("shut/.gitignore", "*\n");
tree.write("shut/y.sv", "module y;\nendmodule\n");
let mode = |rel: &str, bits| {
std::fs::set_permissions(tree.path.join(rel), std::fs::Permissions::from_mode(bits))
.expect("chmod")
};
mode("locked", 0o000);
mode("shut/.gitignore", 0o000);
let refused = std::fs::read_dir(tree.path.join("locked")).is_err();
every_slice_size(&tree.path, &[], DirectoryTracker::new());
let oracle = one_shot(&tree.path, &[], DirectoryTracker::new());
mode("locked", 0o755);
mode("shut/.gitignore", 0o644);
if refused {
let warned = oracle.events.iter().filter(|e| matches!(e, Event::Warned(..))).count();
assert!(warned >= 2, "premise: both are said: {oracle:#?}");
} else {
eprintln!("skipped premise: a mode-000 directory is readable by this user (root?)");
}
}
/// QA (2026-11-26): budgets at the edges, a root that is itself a symlink to
/// a directory, an ignored-then-negated directory with its own nested
/// `.gitignore`, and a deep chain — still the recursive walk's events.
#[test]
fn qa_edge_budgets_a_symlinked_root_a_negated_dir_and_a_deep_chain_walk_the_same() {
let tree = busy_tree("qa-edges");
tree.write(".gitignore", "build/\n*_gen.sv\nvendor/\n!vendor/\n");
tree.write("vendor/.gitignore", "*.svh\n!keep.svh\n");
tree.write("vendor/v.sv", "module v;\nendmodule\n");
tree.write("vendor/drop.svh", "`define D\n");
tree.write("vendor/keep.svh", "`define K\n");
let deep: String = (0..40).map(|n| format!("d{n}/")).collect();
tree.write(&format!("{deep}leaf.sv"), "module leaf;\nendmodule\n");
let oracle = one_shot(&tree.path, &[], DirectoryTracker::new());
for budget in [0usize, usize::MAX] {
let got = sliced(&tree.path, &[], DirectoryTracker::new(), &mut || budget);
assert!(got.same_as(&oracle), "budget {budget}");
}
every_slice_size(&tree.path, &[], DirectoryTracker::new());
#[cfg(unix)]
{
let outside = Tree::new("qa-edges-link");
let root = outside.path.join("root_link");
std::os::unix::fs::symlink(&tree.path, &root).expect("symlink");
every_slice_size(&root, &[], DirectoryTracker::new());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+5
View File
@@ -1,6 +1,9 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv_mcp"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
description = "lucisv as a Model Context Protocol server: project understanding for coding agents over stdio"
@@ -21,3 +24,5 @@ vlog_formatter = { path = "../vlog_formatter" }
vlog_linter = { path = "../vlog_linter" }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+27
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The one write path every edit tool goes through.
//!
//! A tool hands over a [`Plan`] — per file, the text it computed against and
@@ -274,6 +276,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 +311,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();
@@ -338,3 +363,5 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The index caches a startup reads instead of parsing (PLAN §6): the
//! language server's `index-cache`, **read only, never written**, and this
//! server's own `index-cache-mcp` beside it, in the same codec, written once
@@ -221,3 +223,5 @@ fn store_lines(bytes: &[u8]) -> Vec<&[u8]> {
#[cfg(test)]
mod tests;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The caches against the rebuild oracle: an index started from records is
//! the index a cold build over the same files makes
//! (`WorkspaceIndex::fingerprint`), and every record that is not exactly
@@ -141,3 +143,5 @@ fn a_record_filed_under_another_path_or_hash_is_not_taken() {
assert!(parse("0000000000000007\tx").is_none(), "no checksum");
assert!(parse("7\tx\t0000000000000000").is_none(), "a hash of the wrong width");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `lucisv-mcp` — lucisv as a Model Context Protocol server, over stdio.
//!
//! A coding agent (Claude Code, Cursor, VS Code's agent mode) spawns this
@@ -142,3 +144,5 @@ mod tests {
assert_eq!(parse(&[]).unwrap(), Options::default());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! One file, fully analyzed, and a small cache of them keyed by content.
//!
//! The index answers workspace questions without keeping any file's text;
@@ -140,3 +142,5 @@ mod tests {
assert!(cache.get(Path::new("a"), 1).is_none());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+369 -28
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Which files the project is made of, and what each one looked like when it
//! was last read: the filelist-or-walk ladder of PLAN §4.4 over
//! `lucisv_core`, and the per-file stamp the freshness sweep compares against.
@@ -5,7 +7,7 @@
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use std::time::{Duration, Instant, SystemTime};
use lucisv_core::cache::content_hash;
use lucisv_core::config::Discovery;
@@ -16,11 +18,25 @@ use lucisv_core::walk::collect_files_with;
/// something an agent wants summarised.
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
/// A file whose mtime is this close to the moment it was read may have been
/// written again within the filesystem's timestamp resolution, so its stamp
/// proves nothing: it is re-read (and re-hashed) until it is older than
/// this. Git's "racy clean" rule, for the same reason.
const RACY: Duration = Duration::from_secs(2);
/// A file whose mtime or ctime is this close to the moment it was read may
/// have been written again within the filesystem's timestamp resolution, so
/// its stamp proves nothing: it is re-read (and re-hashed) until it is older
/// than this. Git's "racy clean" rule, for the same reason.
///
/// The window must outlast the coarsest timestamp a filesystem keeps plus
/// how far its clock can lag the one `read_at` comes from. Linux stamps
/// files from a clock that moves in 1–4 ms ticks; ext3 and many network
/// mounts keep whole seconds, FAT two. Three seconds covers FAT's two with
/// a second to spare. A just-changed file costs a few more re-reads; a
/// window too short costs stale contents.
const RACY: Duration = Duration::from_secs(3);
/// How far the wall clock may fall behind the monotonic one since a read
/// before the stamp stops being trusted: a clock stepped back can give a
/// later write the very timestamp the stamp holds. Large next to the
/// microseconds between the paired clock reads, small next to the margin
/// [`RACY`] keeps over the coarsest timestamps.
const STEP_BACK: Duration = Duration::from_millis(100);
/// The files one discovery found, and what it had to say about the rest.
#[derive(Debug, Default)]
@@ -137,13 +153,20 @@ pub struct Stamp {
pub mtime: Option<SystemTime>,
/// `content_hash` of its bytes.
pub hash: u64,
/// When it was read.
/// When it was read, by the wall clock file timestamps are compared with.
pub read_at: SystemTime,
/// The same moment by the monotonic clock: what tells a wall clock that
/// was stepped back since the read.
pub read_mono: Instant,
/// When these exact bytes and metadata were first observed on the
/// monotonic clock; preserved across unchanged re-reads so a file with a
/// future timestamp settles after [`RACY`].
pub first_mono: Instant,
/// Its ctime and inode — what still moves when a same-size rewrite puts
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
/// the same problem. Zero off Unix, where size, mtime and the racy rule
/// the same problem. `None` off Unix, where size, mtime and the racy rule
/// are all there is.
pub identity: (i64, i64, u64),
pub identity: Option<Identity>,
/// Whether its text spells `endprogram` — the cheap test that says a
/// `Module`-kind unit in it might be a `program` (the semantic layer
/// models both as a module).
@@ -161,6 +184,42 @@ pub enum Change {
Gone,
}
/// A file's inode change time and inode number (Unix only).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Identity {
/// The ctime, `None` when it does not fit a `SystemTime`.
pub ctime: Option<SystemTime>,
/// The inode number.
pub ino: u64,
}
/// What one `stat` says about a file, as far as a stamp is concerned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Seen {
size: u64,
mtime: Option<SystemTime>,
identity: Option<Identity>,
}
impl Seen {
fn of(meta: &fs::Metadata) -> Seen {
Seen { size: meta.len(), mtime: meta.modified().ok(), identity: identity(meta) }
}
}
/// The two clocks, read back to back.
#[derive(Debug, Clone, Copy)]
struct Clocks {
wall: SystemTime,
mono: Instant,
}
impl Clocks {
fn now() -> Clocks {
Clocks { wall: SystemTime::now(), mono: Instant::now() }
}
}
impl Stamp {
/// Compare the file on disk with this stamp, by one `stat`.
pub fn check(&self, path: &Path) -> Change {
@@ -170,18 +229,88 @@ impl Stamp {
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
return Change::Gone;
}
let mtime = meta.modified().ok();
let racy = match mtime {
Some(mtime) => mtime + RACY > self.read_at,
None => true,
};
let moved = meta.len() != self.size || mtime != self.mtime;
if moved || identity(&meta) != self.identity || racy {
self.compare(Seen::of(&meta), Clocks::now())
}
/// The decision [`Stamp::check`] makes, from what the `stat` saw and
/// what the clocks say now.
fn compare(&self, seen: Seen, now: Clocks) -> Change {
let moved =
seen.size != self.size || seen.mtime != self.mtime || seen.identity != self.identity;
if moved || self.racy(now) || self.clock_stepped_back(now) {
Change::Suspect
} else {
Change::Same
}
}
/// Preserve [`Self::first_mono`] across an unchanged re-read when there
/// was no wall-clock step-back, letting a future timestamp settle after
/// [`RACY`] of monotonic time has elapsed and re-verified the bytes.
pub fn inherit_observation(&mut self, prev: &Stamp) {
let same = self.size == prev.size
&& self.mtime == prev.mtime
&& self.hash == prev.hash
&& self.identity == prev.identity;
let now = Clocks { wall: self.read_at, mono: self.read_mono };
if same && !prev.clock_stepped_back(now) {
self.first_mono = prev.first_mono;
}
}
/// **Invariant: a stamp is trusted on a later match only if every
/// timestamp it trusts (the mtime, and the ctime where there is one) is
/// settled:**
/// - for a timestamp at or before `read_at`, it must be at least [`RACY`]
/// older than `read_at`;
/// - for a future timestamp (`time > read_at`, e.g. clock skew or NFS), it
/// stays racy until [`RACY`] has elapsed on the monotonic clock between
/// first observation and this read (`read_mono - first_mono >= RACY`),
/// unless the wall clock has caught up to `time` (forcing one re-read
/// back into the normal rule).
fn racy(&self, now: Clocks) -> bool {
let ctime = self.identity.map(|identity| identity.ctime);
[Some(self.mtime), ctime].into_iter().flatten().any(|stamped| match stamped {
Some(time) if time <= self.read_at => {
time.checked_add(RACY).is_none_or(|settled| settled > self.read_at)
}
Some(time) => {
now.wall >= time
|| self
.read_mono
.checked_duration_since(self.first_mono)
.is_none_or(|elapsed| elapsed < RACY)
}
None => true,
})
}
/// Whether the wall clock is now more than [`STEP_BACK`] behind where
/// the monotonic clock says it would be had it only run forward since
/// the read. After such a step a new write can be stamped with an old
/// time, so no timestamp match means anything until the file is re-read.
fn clock_stepped_back(&self, now: Clocks) -> bool {
let expected = match now.mono.checked_duration_since(self.read_mono) {
Some(elapsed) => self.read_at.checked_add(elapsed),
None => self.read_at.checked_sub(self.read_mono - now.mono),
};
match (expected, now.wall.checked_add(STEP_BACK)) {
(Some(expected), Some(tolerated)) => tolerated < expected,
_ => true,
}
}
/// This stamp as if it had been taken `by` later, on both clocks: how a
/// test ages a stamp past the racy window without waiting for it.
#[cfg(test)]
pub(crate) fn taken_later(self, by: Duration) -> Stamp {
Stamp {
read_at: self.read_at + by,
read_mono: self.read_mono + by,
first_mono: self.first_mono + by,
..self
}
}
}
/// Read one source file and stamp it. `Err` for a file that is gone or is
@@ -191,33 +320,44 @@ pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
// Stat before reading: a write that lands between the two leaves a stamp
// older than the bytes, which the next sweep sees as a change.
let meta = fs::metadata(path)?;
let read_at = SystemTime::now();
let read = Clocks::now();
let bytes = fs::read(path)?;
let hash = content_hash(&bytes);
let text = String::from_utf8(bytes)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "not UTF-8 text"))?;
let seen = Seen::of(&meta);
let stamp = Stamp {
size: meta.len(),
mtime: meta.modified().ok(),
size: seen.size,
mtime: seen.mtime,
hash,
read_at,
identity: identity(&meta),
read_at: read.wall,
read_mono: read.mono,
first_mono: read.mono,
identity: seen.identity,
program: text.contains("endprogram"),
};
Ok((text, stamp))
}
/// A file's ctime (seconds, nanoseconds) and inode number.
/// A file's ctime and inode number.
#[cfg(unix)]
fn identity(meta: &fs::Metadata) -> (i64, i64, u64) {
fn identity(meta: &fs::Metadata) -> Option<Identity> {
use std::os::unix::fs::MetadataExt;
(meta.ctime(), meta.ctime_nsec(), meta.ino())
let nanos = Duration::from_nanos(u64::try_from(meta.ctime_nsec()).unwrap_or(0));
let ctime = match u64::try_from(meta.ctime()) {
Ok(secs) => SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(secs) + nanos),
Err(_) => SystemTime::UNIX_EPOCH
.checked_sub(Duration::from_secs(meta.ctime().unsigned_abs()))
.and_then(|time| time.checked_add(nanos)),
};
Some(Identity { ctime, ino: meta.ino() })
}
/// No ctime or inode off Unix: the stamp falls back to size and mtime.
/// No ctime or inode off Unix (std has no change time on Windows): the
/// stamp falls back to size and mtime, and the racy rule on the mtime.
#[cfg(not(unix))]
fn identity(_: &fs::Metadata) -> (i64, i64, u64) {
(0, 0, 0)
fn identity(_: &fs::Metadata) -> Option<Identity> {
None
}
#[cfg(test)]
@@ -273,7 +413,7 @@ mod tests {
let (_, stamp) = read_source(&path).unwrap();
// Just written: racy, so suspect even though nothing moved.
assert_eq!(stamp.check(&path), Change::Suspect);
let settled = Stamp { read_at: stamp.read_at + RACY + RACY, ..stamp };
let settled = stamp.taken_later(RACY + RACY);
assert_eq!(settled.check(&path), Change::Same);
fs::write(&path, "module a2; endmodule\n").unwrap();
assert_eq!(settled.check(&path), Change::Suspect);
@@ -281,4 +421,205 @@ mod tests {
assert_eq!(settled.check(&path), Change::Gone);
fs::remove_dir_all(dir).unwrap();
}
// The racy rule, decided from values: no file, no waiting, no clock but
// the ones given.
/// A stamp taken at `read` (wall) / `mono`, of a file whose mtime and
/// ctime are `mtime_age` and `ctime_age` before the read.
fn stamp_aged(
read: SystemTime,
mono: Instant,
mtime_age: Duration,
ctime_age: Duration,
) -> Stamp {
Stamp {
size: 20,
mtime: Some(read - mtime_age),
hash: 7,
read_at: read,
read_mono: mono,
first_mono: mono,
identity: Some(Identity { ctime: Some(read - ctime_age), ino: 42 }),
program: false,
}
}
/// What a `stat` of the unchanged file sees.
fn unchanged(stamp: &Stamp) -> Seen {
Seen { size: stamp.size, mtime: stamp.mtime, identity: stamp.identity }
}
/// The clocks a second after the read, both having run forward.
fn a_second_later(stamp: &Stamp) -> Clocks {
let second = Duration::from_secs(1);
Clocks { wall: stamp.read_at + second, mono: stamp.read_mono + second }
}
#[test]
fn a_match_is_trusted_only_when_every_timestamp_was_settled_at_the_read() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let fresh = Duration::from_millis(1);
let cases = [
("neither racy", old, old, Change::Same),
("mtime racy", fresh, old, Change::Suspect),
// The Linux hole: an old mtime put back, a ctime from this tick.
("ctime racy", old, fresh, Change::Suspect),
("both racy", fresh, fresh, Change::Suspect),
("just inside the window", old, RACY - Duration::from_nanos(1), Change::Suspect),
("exactly the window old", old, RACY, Change::Same),
];
for (what, mtime_age, ctime_age, expected) in cases {
let stamp = stamp_aged(read, mono, mtime_age, ctime_age);
assert_eq!(
stamp.compare(unchanged(&stamp), a_second_later(&stamp)),
expected,
"{what}"
);
}
}
#[test]
fn a_timestamp_later_than_the_read_or_missing_is_racy() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let mut ahead = stamp_aged(read, mono, old, old);
ahead.identity = Some(Identity { ctime: Some(read + Duration::from_secs(60)), ino: 42 });
assert_eq!(ahead.compare(unchanged(&ahead), a_second_later(&ahead)), Change::Suspect);
let mut no_ctime = stamp_aged(read, mono, old, old);
no_ctime.identity = Some(Identity { ctime: None, ino: 42 });
assert_eq!(
no_ctime.compare(unchanged(&no_ctime), a_second_later(&no_ctime)),
Change::Suspect
);
let mut no_mtime = stamp_aged(read, mono, old, old);
no_mtime.mtime = None;
assert_eq!(
no_mtime.compare(unchanged(&no_mtime), a_second_later(&no_mtime)),
Change::Suspect
);
// Off Unix there is no ctime to trust: the mtime alone decides.
let mut off_unix = stamp_aged(read, mono, old, old);
off_unix.identity = None;
assert_eq!(off_unix.compare(unchanged(&off_unix), a_second_later(&off_unix)), Change::Same);
}
#[test]
fn a_wall_clock_stepped_back_since_the_read_distrusts_the_stamp() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let stamp = stamp_aged(read, mono, old, old);
let ten = Duration::from_secs(10);
// Ten seconds of real time, but the wall clock shows one: stepped back.
let back = Clocks { wall: read + Duration::from_secs(1), mono: mono + ten };
assert_eq!(stamp.compare(unchanged(&stamp), back), Change::Suspect);
// Behind the read itself.
let behind = Clocks { wall: read - ten, mono: mono + Duration::from_secs(1) };
assert_eq!(stamp.compare(unchanged(&stamp), behind), Change::Suspect);
// A wall clock that ran ahead (a suspend the monotonic clock slept
// through) is no reason to doubt anything.
let ahead = Clocks { wall: read + ten, mono: mono + Duration::from_secs(1) };
assert_eq!(stamp.compare(unchanged(&stamp), ahead), Change::Same);
// Jitter under the tolerance is not a step.
let jitter = Clocks { wall: read + ten - STEP_BACK / 2, mono: mono + ten };
assert_eq!(stamp.compare(unchanged(&stamp), jitter), Change::Same);
// A stamp aged on both clocks at once is not a step either.
let aged = stamp.taken_later(ten);
assert_eq!(aged.compare(unchanged(&aged), a_second_later(&stamp)), Change::Same);
}
#[test]
fn any_moved_field_is_suspect_however_settled() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let stamp = stamp_aged(read, mono, old, old);
let now = a_second_later(&stamp);
let same = unchanged(&stamp);
let identity = stamp.identity.unwrap();
let moved = [
Seen { size: 21, ..same },
Seen { mtime: Some(read), ..same },
Seen { identity: Some(Identity { ino: 43, ..identity }), ..same },
Seen { identity: Some(Identity { ctime: Some(read - old / 2), ..identity }), ..same },
];
for seen in moved {
assert_eq!(stamp.compare(seen, now), Change::Suspect, "{seen:?}");
}
}
#[test]
fn future_timestamp_settles_after_racy_and_reacts_to_catchup_stepback_or_edits() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let future = read + Duration::from_secs(600);
let mut initial = stamp_aged(read, mono, old, old);
initial.mtime = Some(future);
// Initial read is racy until monotonic time >= RACY has elapsed at a re-read.
assert_eq!(initial.compare(unchanged(&initial), a_second_later(&initial)), Change::Suspect);
let before_racy = RACY - Duration::from_millis(1);
let mut mid = Stamp {
read_at: read + before_racy,
read_mono: mono + before_racy,
first_mono: mono + before_racy,
..initial
};
mid.inherit_observation(&initial);
assert_eq!(mid.first_mono, mono);
assert_eq!(mid.compare(unchanged(&mid), a_second_later(&mid)), Change::Suspect);
// Once RACY has elapsed and a re-read confirms the same bytes, it settles.
let mut settled =
Stamp { read_at: read + RACY, read_mono: mono + RACY, first_mono: mono + RACY, ..mid };
settled.inherit_observation(&mid);
assert_eq!(settled.first_mono, mono);
assert_eq!(settled.compare(unchanged(&settled), a_second_later(&settled)), Change::Same);
// If the wall clock later catches up to `future`, trigger one re-read.
let caught_up = Clocks { wall: future, mono: mono + Duration::from_secs(600) };
assert_eq!(settled.compare(unchanged(&settled), caught_up), Change::Suspect);
// A hash change or wall-clock step-back resets `first_mono`.
let mut changed =
Stamp { hash: 99, read_at: read + RACY, read_mono: mono + RACY, ..settled };
changed.first_mono = mono + RACY;
changed.inherit_observation(&settled);
assert_eq!(changed.first_mono, mono + RACY);
assert_eq!(changed.compare(unchanged(&changed), a_second_later(&changed)), Change::Suspect);
let mut stepped = Stamp {
read_at: settled.read_at - STEP_BACK - Duration::from_secs(1),
read_mono: settled.read_mono + Duration::from_secs(1),
first_mono: settled.read_mono + Duration::from_secs(1),
..settled
};
stepped.inherit_observation(&settled);
assert_eq!(stepped.first_mono, stepped.read_mono);
}
#[test]
fn real_future_mtime_file_detects_edits_and_settles_with_reobservation() {
let dir = scratch("future-mtime");
let path = dir.join("a.sv");
fs::write(&path, "module a; endmodule\n").unwrap();
let future = SystemTime::now() + Duration::from_secs(3600);
fs::OpenOptions::new().write(true).open(&path).unwrap().set_modified(future).unwrap();
let (_, initial) = read_source(&path).unwrap();
assert_eq!(initial.check(&path), Change::Suspect);
// Simulated re-read after RACY with inherited observation settles on disk.
let mut reobserved = initial.taken_later(RACY);
reobserved.first_mono = initial.first_mono;
assert_eq!(reobserved.check(&path), Change::Same);
// A subsequent edit still turns Suspect immediately.
fs::write(&path, "module a2; endmodule\n").unwrap();
assert_eq!(reobserved.check(&path), Change::Suspect);
fs::remove_dir_all(dir).unwrap();
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+104 -5
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The project one server answers about: its roots, its files, the workspace
//! index over them, and the promise that no answer is older than the disk
//! was when the call arrived (PLAN §4.4).
@@ -179,8 +181,14 @@ impl Project {
/// Re-read one file whose stamp is in doubt; a changed hash is a record.
fn reread(&mut self, path: PathBuf, records: &mut Vec<FileFacts>, gone: &mut Vec<PathBuf>) {
match read_source(&path) {
Ok((text, stamp)) => {
let moved = self.files.get(&path).is_none_or(|old| old.hash != stamp.hash);
Ok((text, mut stamp)) => {
let moved = match self.files.get(&path) {
Some(old) => {
stamp.inherit_observation(old);
old.hash != stamp.hash
}
None => true,
};
if moved {
records.push(FileFacts::of(path.clone(), &text));
}
@@ -238,6 +246,13 @@ impl Project {
&self.index
}
/// Drop one file directly from the held index (test-only helper to exercise
/// sparse tombstoned `FileId`s).
#[cfg(test)]
pub(crate) fn remove_file_from_index(&mut self, path: &Path) -> bool {
self.index.remove_file(path)
}
/// The canonical roots, in the order given.
pub fn roots(&self) -> &[PathBuf] {
&self.roots
@@ -271,6 +286,15 @@ impl Project {
/// holding it; symlinks followed; and refused, by name, unless it lands
/// on a file inside a root.
pub fn resolve(&self, arg: &str) -> Result<PathBuf, String> {
let path = self.resolve_existing(arg)?;
if !path.is_file() {
return Err(format!("`{arg}` is not a file."));
}
Ok(path)
}
/// Resolve an existing file or directory inside one of the project roots.
pub fn resolve_existing(&self, arg: &str) -> Result<PathBuf, String> {
let given = Path::new(arg);
let candidates: Vec<PathBuf> = if given.is_absolute() {
vec![given.to_path_buf()]
@@ -285,9 +309,6 @@ impl Project {
"`{arg}` resolves outside every root; lucisv-mcp only reads inside its roots."
));
}
if !path.is_file() {
return Err(format!("`{arg}` is not a file."));
}
Ok(path)
}
@@ -357,5 +378,83 @@ fn relative_to(roots: &[PathBuf], path: &Path) -> String {
parts.join("/")
}
impl vlog_refactor::KnownFacts for Project {
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
let stamp = self.files.get(path)?;
if stamp.hash != lucisv_core::cache::content_hash(text.as_bytes()) {
return None;
}
self.index.facts_for(path).cloned()
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod r3_tests {
use super::*;
use std::fs;
use std::time::{Duration, SystemTime};
use vlog_refactor::KnownFacts;
#[test]
fn known_facts_matches_exact_bytes_and_invalidates_after_refresh() {
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-project-known-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let file = fs::canonicalize(&dir).unwrap().join("a.sv");
let v1 = "module a; logic s1; endmodule\n";
fs::write(&file, v1).unwrap();
let mut project = Project::open(vec![fs::canonicalize(&dir).unwrap()], None);
assert!(project.facts_for(&file, v1).is_some_and(|f| f.path() == file));
let v2 = "module a; logic s2; endmodule\n";
assert!(project.facts_for(&file, v2).is_none(), "stale text must miss");
fs::write(&file, v2).unwrap();
let refresh = project.refresh(false);
assert_eq!(refresh.changed, 1);
assert!(project.facts_for(&file, v1).is_none(), "old hash invalidated");
assert!(project.facts_for(&file, v2).is_some(), "new hash hits");
fs::remove_file(&file).unwrap();
project.refresh(false);
assert!(project.facts_for(&file, v2).is_none(), "removed file misses");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn project_reread_inherits_observation_for_future_mtime_settlement() {
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-project-future-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let file = fs::canonicalize(&dir).unwrap().join("f.sv");
fs::write(&file, "module f; endmodule\n").unwrap();
let future = SystemTime::now() + Duration::from_secs(3600);
fs::OpenOptions::new().write(true).open(&file).unwrap().set_modified(future).unwrap();
let mut project = Project::open(vec![fs::canonicalize(&dir).unwrap()], None);
let first_mono = project.files[&file].first_mono;
// First refresh sees Suspect and re-reads; hash matches so changed == 0,
// while `first_mono` stays anchored at initial observation.
let r1 = project.refresh(false);
assert_eq!(r1.changed, 0);
assert_eq!(project.files[&file].first_mono, first_mono);
// Once the previous stamp is past RACY relative to `first_mono`, re-read
// settles cleanly and the next `check` sees `Change::Same`.
if let Some(stamp) = project.files.get_mut(&file) {
let mut aged = stamp.taken_later(Duration::from_secs(4));
aged.first_mono = first_mono;
*stamp = aged;
}
assert_eq!(project.files[&file].check(&file), Change::Same);
let _ = fs::remove_dir_all(&dir);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+6 -3
View File
@@ -1,10 +1,12 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The freshness promise, against the rebuild oracle: after every update
//! path the incrementally maintained index is the index a full build over
//! the files now on disk produces (`WorkspaceIndex::fingerprint`).
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use std::time::Duration;
use vlog_semantic::WorkspaceIndex;
@@ -29,9 +31,8 @@ fn rebuilt(project: &Project) -> String {
/// Age every stamp past the racy window, so only a real change is suspect.
fn settle(project: &mut Project) {
let later = SystemTime::now() + Duration::from_secs(10);
for stamp in project.files.values_mut() {
stamp.read_at = later;
*stamp = stamp.taken_later(Duration::from_secs(10));
}
}
@@ -107,3 +108,5 @@ fn a_path_argument_must_land_inside_a_root() {
fs::remove_dir_all(dir).unwrap();
fs::remove_dir_all(outside).unwrap();
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The rendering rules every tool's text answer follows (PLAN §10.2): the
//! token budget is the product.
//!
@@ -205,3 +207,5 @@ mod tests {
assert_eq!(by_file(&sites), ["b.sv:3,9", "a.sv:1"]);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The `lucisv://` resources: the project overview, the lint rule
//! reference, one unit's outline and one file's outline — the same answers
//! `hierarchy` and `outline` give, addressable by URI for a host that
@@ -176,3 +178,5 @@ mod tests {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+8 -4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The JSON-RPC 2.0 envelope and the MCP methods this server answers: the
//! `initialize` handshake and its version negotiation, `ping`, the tool
//! methods, the `lucisv://` resources, and an empty prompt list.
@@ -226,7 +228,7 @@ impl Server {
self.version = Some(version);
json!({
"protocolVersion": version,
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
"capabilities": { "tools": {}, "resources": {} },
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
"instructions": instructions(self.options.mode),
})
@@ -366,9 +368,9 @@ 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());
fn the_instructions_stay_under_budget() {
assert!(INSTRUCTIONS.len() <= 440, "{}", INSTRUCTIONS.len());
assert!(INSTRUCTIONS_READ_ONLY.len() <= 330, "{}", INSTRUCTIONS_READ_ONLY.len());
}
#[test]
@@ -421,3 +423,5 @@ mod tests {
assert!(bad_tool["error"]["message"].as_str().unwrap().contains("nope"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The declarations the files' own symbol tables hold — every one the
//! semantic model knows and `outline` lists: typedefs, enum values,
//! functions, tasks, genvars, generate blocks and what they declare,
@@ -94,3 +96,5 @@ fn unit_at(items: &[Item], span: TextRange) -> Option<&str> {
let inner = child_items(&item.kind).into_iter().find_map(|items| unit_at(items, span));
inner.or(own.filter(|(_, name_span)| *name_span != span).map(|(name, _)| name))
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+182 -15
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `check`: what `lucisv check` would say about one file or the whole
//! design — the tolerant parse's errors, then the lint findings — one line
//! each, `file:line:col severity message [rule]`, errors first.
@@ -31,7 +33,7 @@ const CAP: usize = 200;
pub const CHECK: Tool = Tool {
name: "check",
description: "Parse errors and lint findings of `file` or the whole design, one per line (file:line:col severity message [rule]), errors first; `ok` when clean.",
description: "Parse errors and lint findings of `file` (path, directory or glob) or the whole design, one per line (file:line:col severity message [rule]), errors first; `ok` when clean.",
params: &[Param { name: "file", ty: Ty::Str, required: false }],
rewalk: false,
handler: check,
@@ -60,13 +62,7 @@ pub(super) struct Run {
fn check(project: &mut Project, args: &Args) -> Result<Answer, String> {
let mut runs = Runs::new();
let mut findings = match args.str("file") {
Some(file) => {
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let own = project.index().file_id(&path);
let oracle = Mentions::of_file(project.index(), own);
file_findings(project, &mut runs, &path, &analysis, &oracle)?
}
Some(raw) => check_target(project, &mut runs, raw.trim())?,
None => project_findings(project, &mut runs)?,
};
if findings.is_empty() {
@@ -78,6 +74,56 @@ fn check(project: &mut Project, args: &Args) -> Result<Answer, String> {
Ok(Answer::lines(render::capped(lines, CAP)))
}
fn check_target(
project: &mut Project,
runs: &mut Runs,
spec: &str,
) -> Result<Vec<Finding>, String> {
if spec.is_empty() {
return Err("`file` is empty.".into());
}
if !spec.contains(['*', '?']) {
let path = project.resolve_existing(spec)?;
if path.is_file() {
let analysis = project.analysis(&path)?;
let own = project.index().file_id(&path);
let oracle = Mentions::of_file(project.index(), own);
return file_findings(project, runs, &path, &analysis, &oracle);
}
let select = |project: &Project| -> Vec<PathBuf> {
project.files().map(|(p, _)| p).filter(|p| p.starts_with(&path)).cloned().collect()
};
let paths = match_with_rewalk(project, select, spec)?;
return lint_paths(project, runs, &paths, false);
}
let pattern = super::glob::normalize_glob(project.roots(), spec)?;
let select = |project: &Project| -> Vec<PathBuf> {
project
.files()
.map(|(p, _)| p)
.filter(|p| super::glob::path_match(&pattern, &project.relative(p)))
.cloned()
.collect()
};
let paths = match_with_rewalk(project, select, spec)?;
lint_paths(project, runs, &paths, false)
}
fn match_with_rewalk(
project: &mut Project,
select: impl Fn(&Project) -> Vec<PathBuf>,
spec: &str,
) -> Result<Vec<PathBuf>, String> {
let mut found = select(project);
if found.is_empty() && project.ensure_walked_for_miss() {
found = select(project);
}
if found.is_empty() {
return Err(format!("no indexed file matches `{spec}`."));
}
Ok(found)
}
fn severity_rank(severity: &str) -> u8 {
match severity {
"error" => 0,
@@ -97,18 +143,29 @@ impl Finding {
/// Every indexed file's findings, and the external waivers nothing used.
fn project_findings(project: &Project, runs: &mut Runs) -> Result<Vec<Finding>, String> {
let census = Census::of(project.index());
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
lint_paths(project, runs, &paths, true)
}
fn lint_paths(
project: &Project,
runs: &mut Runs,
paths: &[PathBuf],
complete: bool,
) -> Result<Vec<Finding>, String> {
let census = Census::of(project.index());
let mut findings = Vec::new();
for path in &paths {
for path in paths {
let Ok(text) = std::fs::read_to_string(path) else { continue };
let analysis = Analysis::of(text);
let own = project.index().file_id(path);
let oracle = Mentions { index: project.index(), census: Some(&census), own };
findings.extend(file_findings(project, runs, path, &analysis, &oracle)?);
}
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
if complete {
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
}
Ok(findings)
}
@@ -161,7 +218,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,
@@ -260,9 +319,8 @@ struct Census<'a> {
impl<'a> Census<'a> {
fn of(index: &'a WorkspaceIndex) -> Census<'a> {
let mut words: HashMap<&'a str, (usize, FileId)> = HashMap::new();
for (at, path) in index.files().iter().enumerate() {
for (file, path) in index.live_files() {
let Some(facts) = index.facts_for(path) else { continue };
let file = FileId(at as u32);
for word in facts.words() {
words.entry(word.as_str()).or_insert((0, file)).0 += 1;
}
@@ -323,3 +381,112 @@ impl MentionOracle for Mentions<'_> {
PackageExports::exports(self.index, package)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn census_uses_live_file_ids_after_tombstone_at_slot_zero() {
let mut index = WorkspaceIndex::build([
(PathBuf::from("a_excl.sv"), "module a_excl; logic excl_only; endmodule\n"),
(
PathBuf::from("b_live.sv"),
"module b_live; logic own_sig; logic shared_sig; endmodule\n",
),
(PathBuf::from("c_user.sv"), "module c_user; logic shared_sig; endmodule\n"),
]);
assert!(index.remove_file(Path::new("a_excl.sv")));
let b_id = index.file_id(Path::new("b_live.sv")).expect("b_live live");
assert_eq!(b_id, FileId(1));
let census = Census::of(&index);
assert!(!census.outside("excl_only", Some(b_id)));
assert!(
!census.outside("own_sig", Some(b_id)),
"Census::of must keep FileId(1) rather than shifting to FileId(0)"
);
assert!(census.outside("shared_sig", Some(b_id)));
}
#[test]
fn qa_r2_f1_mcp_find_and_check_with_multiple_tombstones_preceding_live_files() {
let dir = std::env::temp_dir().join(format!("lucisv-mcp-qa-r2-f1-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("mkdir");
let dir = std::fs::canonicalize(dir).expect("canon");
let excl0 = dir.join("a0_excl.sv");
let excl1 = dir.join("a1_excl.sv");
let excl2 = dir.join("a2_excl.sv");
std::fs::write(&excl0, "`define EX0 1\nmodule a0; logic ex0_sig; endmodule\n").expect("w");
std::fs::write(&excl1, "`define EX1 1\nmodule a1; logic ex1_sig; endmodule\n").expect("w");
std::fs::write(&excl2, "`define EX2 1\nmodule a2; logic ex2_sig; endmodule\n").expect("w");
std::fs::write(
dir.join("b_live.sv"),
"`define LIVE_MAC 1\nmodule b_live;\n logic own_sig;\n logic shared_sig;\nendmodule\n",
)
.expect("w");
std::fs::write(
dir.join("c_user.sv"),
"module c_user;\n logic shared_sig;\n b_live u1 ();\nendmodule\n",
)
.expect("w");
let mut project = Project::open(vec![dir.clone()], None);
assert!(project.remove_file_from_index(&excl0));
assert!(project.remove_file_from_index(&excl1));
assert!(project.remove_file_from_index(&excl2));
assert_eq!(project.index().files().len(), 2);
assert_eq!(project.index().file_id(&dir.join("b_live.sv")), Some(FileId(3)));
let make_args = |tool: &crate::tools::Tool, v: serde_json::Value| {
crate::tools::validate(tool, v.as_object().cloned().expect("args obj"))
.expect("valid args")
};
let check_tool = crate::tools::find("check", crate::tools::Mode::Full).expect("check tool");
let single = (check_tool.handler)(
&mut project,
&make_args(check_tool, serde_json::json!({ "file": "b_live.sv" })),
)
.expect("single check");
assert!(single.text.contains("own_sig"), "single check flags own_sig: {}", single.text);
assert!(
!single.text.contains("shared_sig"),
"single check ignores shared_sig: {}",
single.text
);
let whole =
(check_tool.handler)(&mut project, &make_args(check_tool, serde_json::json!({})))
.expect("whole check");
assert!(whole.text.contains("own_sig"), "whole check flags own_sig: {}", whole.text);
assert!(
!whole.text.contains("shared_sig"),
"whole check ignores shared_sig: {}",
whole.text
);
let find_tool = crate::tools::find("find", crate::tools::Mode::Full).expect("find tool");
let refs = (find_tool.handler)(
&mut project,
&make_args(find_tool, serde_json::json!({ "name": "b_live", "refs": true })),
)
.expect("find refs");
assert!(refs.text.contains("c_user.sv"), "find refs locates c_user.sv: {}", refs.text);
let err = match (find_tool.handler)(
&mut project,
&make_args(find_tool, serde_json::json!({ "name": "LIVE" })),
) {
Ok(_) => panic!("expected no_declaration error with similar"),
Err(e) => e,
};
assert!(err.contains("LIVE_MAC"), "near match must include LIVE_MAC: {err}");
let _ = std::fs::remove_dir_all(&dir);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+15 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `rename`, and what every design-wide edit shares: the whole-set read the
//! engines are handed, and the step from a verified `RefactorEdit` to a
//! written plan with the name's unresolved mentions listed.
@@ -44,8 +46,16 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
return Ok(Answer::lines(vec!["renamed 0 sites in 0 files".to_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(&why))?;
let mut trace = vlog_refactor::RenameTrace::default();
let edit = vlog_refactor::rename_traced_with(
&set.files,
&path,
declaration.offset,
new_name,
project,
&mut trace,
)
.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);
// A member of a module is named bare only where it is declared or used;
@@ -166,7 +176,7 @@ pub(super) fn write_telling(
// `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),
true => vlog_refactor::home_set_for(&set.files, told.home, told.unit, &edited),
false => None,
};
let focus = Focus {
@@ -221,3 +231,5 @@ fn written_ranges(edits: &[TextEdit]) -> Vec<TextRange> {
}
out
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+61 -29
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `find`: where a name is declared and, on `refs`, where each declaration
//! is used — the question an agent otherwise answers by grepping and
//! reading. Declarations come from the index (`names.rs`); uses from
@@ -6,7 +8,7 @@
//! that never spells the name); then the name's unresolved mentions —
//! strings, comments, macro text — that no engine resolved.
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
@@ -46,7 +48,7 @@ fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
if found.is_empty() {
return Err(names::no_declaration(project, name));
}
let name = names::qualified(name).1;
let (qualified_unit, name) = names::qualified(name);
if !args.flag("refs") {
let lines = found.iter().map(|declaration| declaration.render(name)).collect();
return Ok(Answer::lines(render::capped(lines, CAP)));
@@ -54,15 +56,28 @@ fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
// The uses must be searched in every file, so one written since the last
// walk is walked into first.
project.ensure_walked_for_miss();
Ok(Answer::lines(render::capped(with_uses(project, name, &found), CAP)))
Ok(Answer::lines(render::capped(with_uses(project, qualified_unit, name, &found), CAP)))
}
/// Each declaration's line followed by its uses, then the unresolved
/// mentions of the name no engine accounted for.
fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String> {
fn with_uses(
project: &Project,
qualified_unit: Option<&str>,
name: &str,
found: &[Declaration],
) -> Vec<String> {
let set = WholeSet::read(project, None);
let mut lines = Vec::new();
let mut accounted: Vec<(PathBuf, Vec<TextRange>)> = Vec::new();
let queries: Vec<(&Path, u32)> = found
.iter()
.filter(|declaration| !declaration.is_macro())
.take(REFS_CAP)
.map(|declaration| (declaration.path.as_path(), declaration.offset))
.collect();
let mut batch =
vlog_refactor::find_references_batch_with(&set.files, &queries, false, project).into_iter();
let mut searched = 0;
for declaration in found {
lines.push(declaration.render(name));
@@ -70,22 +85,17 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
continue;
}
searched += 1;
let hits = vlog_refactor::find_references(
&set.files,
&declaration.path,
declaration.offset,
false,
);
match hits {
Ok(hits) => {
match batch.next() {
Some(Ok(hits)) => {
lines
.extend(uses(project, &set, &hits).into_iter().map(|line| format!(" {line}")));
account(&mut accounted, hits);
}
Err(why) => {
Some(Err(why)) => {
let why = engine_refusal(&set.rooted(&why));
lines.push(format!(" uses not listed: {why}"));
}
None => {}
}
}
let followed = found.iter().filter(|declaration| !declaration.is_macro()).count();
@@ -93,14 +103,15 @@ 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 local = member_files(&set, found, &accounted);
let member = member_scope(&set, found, &accounted);
let unit = qualified_unit.or(member.unit.as_deref());
let focus = Focus {
name,
home,
unit: None,
unit,
accounted: &accounted,
named: &[],
local: local.as_deref(),
local: member.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());
@@ -108,29 +119,48 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
lines
}
struct MemberScope {
local: Option<Vec<PathBuf>>,
unit: Option<String>,
}
/// 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(
/// declaration's bind-aware home set (`vlog_refactor::home_sets_for`) 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). Also returns the enclosing
/// unit name when all declarations share one.
fn member_scope(
set: &WholeSet,
found: &[Declaration],
accounted: &[(PathBuf, Vec<TextRange>)],
) -> Option<Vec<PathBuf>> {
) -> MemberScope {
if found.iter().any(Declaration::is_macro) {
return None;
return MemberScope { local: None, unit: None };
}
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
let mut local: Vec<PathBuf> = Vec::new();
let mut targets: Vec<(&Path, String)> = Vec::with_capacity(found.len());
for declaration in found {
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
let Some(text) = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)
else {
return MemberScope { local: None, unit: None };
};
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)?);
let Some(unit) =
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)
else {
return MemberScope { local: None, unit: None };
};
targets.push((declaration.path.as_path(), unit));
}
Some(local)
let single_unit = targets
.first()
.map(|(_, u)| u)
.filter(|u| targets.iter().all(|(_, other)| other == *u))
.cloned();
let home_targets: Vec<(&Path, Option<&str>)> =
targets.iter().map(|(p, u)| (*p, Some(u.as_str()))).collect();
let local = vlog_refactor::home_sets_for(&set.files, &home_targets, &hit_files);
MemberScope { local, unit: single_unit }
}
/// The engine's hits, one file per line: `file:12,40`.
@@ -197,3 +227,5 @@ mod tests {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+57 -4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `format`: the CLI's `lucisv format` over a path or a glob, and with
//! `fix` the CLI's `lucisv check --fix` first — each file through the one
//! write path (`apply.rs`).
@@ -15,7 +17,9 @@ use std::path::{Path, PathBuf};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::fence::{self, Region};
use vlog_formatter::{format_source, Config};
use vlog_formatter::{
format_source, Alignment, Config, ListIndent, Placement, PortLists, StyleOverrides,
};
use vlog_linter::{apply_fixes, Fix, Violation};
use super::diagnostics::{violations, Mentions, Runs};
@@ -119,9 +123,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;
}
@@ -131,6 +136,15 @@ fn formatter_config(file: &FileConfig) -> Config {
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config.apply_overrides(StyleOverrides {
begin: file.format_begin.and_then(Placement::parse),
else_keyword: file.format_else.and_then(Placement::parse),
else_after_label: file.format_else_after_label.and_then(Placement::parse),
port_lists: file.format_port_lists.and_then(PortLists::parse),
list_indent: file.format_list_indent.and_then(ListIndent::parse),
alignment: file.format_alignment.and_then(Alignment::parse),
connection_align_min: file.format_connection_align_min,
});
config
}
@@ -195,3 +209,42 @@ 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 overridden = FileConfig {
format_style: Some("google"),
format_begin: Some("own-line"),
format_connection_align_min: Some(0),
..Default::default()
};
let config = formatter_config(&overridden);
assert_eq!(config.style.begin, Placement::OwnLine);
assert_eq!(config.style.connection_align_min, 0);
let auto = FileConfig {
format_style: Some("auto"),
format_else: Some("own-line"),
..Default::default()
};
let auto_cfg = formatter_config(&auto);
assert!(auto_cfg.auto_style);
assert_eq!(auto_cfg.overrides.else_keyword, Some(Placement::OwnLine));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+72
View File
@@ -1,7 +1,11 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Path globs, as `format`'s `files` takes them: `*` and `?` within one
//! path component, `**` for any run of components, and a bare directory
//! for everything below it — the `.gitignore` / `rg -g` reading.
use std::path::{Component, Path, PathBuf};
/// Whether `name` matches a glob of `*` (any run) and `?` (one character).
pub fn glob_match(pattern: &str, name: &str) -> bool {
let pattern: Vec<char> = pattern.chars().collect();
@@ -59,6 +63,72 @@ fn components_match(pattern: &[&str], path: &[&str]) -> bool {
}
}
/// Normalize a glob `spec` relative to `roots`, refusing paths that resolve
/// outside every root (absolute outside roots or escaping via `..`).
pub fn normalize_glob(roots: &[PathBuf], spec: &str) -> Result<String, String> {
let given = Path::new(spec);
if given.is_absolute() {
for root in roots {
if let Ok(rest) = given.strip_prefix(root) {
return normalize_relative_glob(spec, rest);
}
if let Some(root_rel) = strip_canonical_prefix(given, root) {
return normalize_relative_glob(spec, &root_rel);
}
}
return Err(format!(
"`{spec}` resolves outside every root; lucisv-mcp only reads inside its roots."
));
}
normalize_relative_glob(spec, given)
}
fn strip_canonical_prefix(given: &Path, root: &Path) -> Option<PathBuf> {
let mut prefix = PathBuf::new();
let mut iter = given.components();
let mut rest = Vec::new();
while let Some(comp) = iter.next() {
let text = comp.as_os_str().to_string_lossy();
if text.contains(['*', '?']) {
rest.push(comp.as_os_str().to_os_string());
rest.extend(iter.map(|c| c.as_os_str().to_os_string()));
break;
}
prefix.push(comp.as_os_str());
}
let canon = std::fs::canonicalize(&prefix).ok()?;
let rel = canon.strip_prefix(root).ok()?;
let mut out = rel.to_path_buf();
for tail in rest {
out.push(tail);
}
Some(out)
}
fn normalize_relative_glob(raw: &str, path: &Path) -> Result<String, String> {
let mut parts: Vec<String> = Vec::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
if parts.pop().is_none() {
return Err(format!(
"`{raw}` resolves outside every root; lucisv-mcp only reads inside its roots."
));
}
}
Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()),
Component::RootDir | Component::Prefix(_) => {}
}
}
let joined = parts.join("/");
if raw.ends_with('/') && !joined.is_empty() {
Ok(format!("{joined}/"))
} else {
Ok(joined)
}
}
#[cfg(test)]
mod tests {
use super::{glob_match, path_match};
@@ -100,3 +170,5 @@ mod tests {
assert!(!path_match("ip/**", "hw/ip/aes.sv"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `hierarchy`: the project's shape. Without a `root`, the counts and the
//! top modules; with one, the instance tree down from it or every
//! instantiation of it up to `depth` levels — read off the index's
@@ -369,3 +371,5 @@ fn statement(project: &Project, texts: &mut Texts, child: &Child) -> Vec<String>
}
out
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `outline unit:` — what a unit offers the code that uses it: a module's
//! or interface's parameters and ports in declaration order (plus an
//! interface's modports), a package's or class's members — without the
@@ -228,3 +230,5 @@ fn class_base(items: &[Item], name_span: TextRange) -> Option<String> {
}
child_items(&item.kind).into_iter().find_map(|items| class_base(items, name_span))
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `edit_item` — the structural edits under one name (`replace`,
//! `insert_before`, `insert_after`, `delete`), the general token saver: an
//! agent sends one item's text, never the file.
@@ -373,3 +375,5 @@ fn end_spot(analysis: &Analysis, unit: &str, file: &str) -> Result<Spot, String>
/// The keywords that close a unit `end` may name.
const END_WORDS: &[&str] = &["endmodule", "endinterface", "endprogram", "endpackage", "endclass"];
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The verifier's lexical rules — what a splice may do to the token stream
//! and its comments, before any parse is asked:
//!
@@ -173,3 +175,5 @@ fn markers(tokens: &[Token], start: u32, end: u32) -> Vec<&str> {
.map(|e| e.text.trim())
.collect()
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `op: delete`'s macro rule: a name spelled inside a macro call's
//! arguments (`` `ASSERT_KNOWN(k, sig) ``) or a `` `define`` body is a use
//! no lucisv engine resolves — the lexer keeps a macro call as one token and
@@ -106,3 +108,5 @@ mod tests {
assert!(spellings("`define S \"sig\"\n", "sig").is_empty(), "a string is not a use");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+37 -10
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `edit_item op: delete`'s reference rule: an item is not deleted while a
//! name it owns (`verify::owned`) is still used anywhere in the project.
//!
@@ -87,8 +89,18 @@ pub fn check(
census.add(|| format!("{file} (skipped: {why}) may reference `{name}`"));
}
let scan = Scan { project, set: &set, path, analysis, place };
let queries: Vec<(&Path, u32)> = symbols
.iter()
.filter(|symbol| {
within(symbol.name_span, place.removed)
&& mentioned(&set, path, place.removed, &symbol.name)
})
.map(|symbol| (path, symbol.name_span.start))
.collect();
let mut batch =
vlog_refactor::find_references_batch_with(&set.files, &queries, false, project).into_iter();
for symbol in symbols {
scan.uses_of(symbol, &mut census);
scan.uses_of(symbol, &mut batch, &mut census);
}
if census.total > 0 {
return Err(format!("still referenced: {}; nothing written.", census.render()));
@@ -111,7 +123,12 @@ type Accounted = Vec<(PathBuf, TextRange)>;
impl Scan<'_> {
/// Count the uses of one owned declaration that the deletion would leave.
fn uses_of(&self, symbol: &Symbol, census: &mut Census) {
fn uses_of(
&self,
symbol: &Symbol,
batch: &mut impl Iterator<Item = Result<Vec<(PathBuf, TextRange)>, String>>,
census: &mut Census,
) {
let (name, removed) = (&symbol.name, self.place.removed);
if !within(symbol.name_span, removed) {
let line = self.analysis.lines.line_col(symbol.name_span.start).0;
@@ -124,12 +141,26 @@ impl Scan<'_> {
if !mentioned(self.set, self.path, removed, name) {
return;
}
let accounted = self.references(symbol, census);
let found = batch.next().unwrap_or_else(|| {
vlog_refactor::find_references_with(
&self.set.files,
self.path,
symbol.name_span.start,
false,
self.project,
)
});
let accounted = self.references(symbol, found, census);
self.macros(name, &accounted, census);
}
/// The engine's and the file's own uses, counted; what they account for.
fn references(&self, symbol: &Symbol, census: &mut Census) -> Accounted {
fn references(
&self,
symbol: &Symbol,
found: Result<Vec<(PathBuf, TextRange)>, String>,
census: &mut Census,
) -> Accounted {
let (name, removed) = (&symbol.name, self.place.removed);
let mut uses = local_uses(self.analysis, symbol, removed);
let mut accounted: Accounted = self
@@ -140,12 +171,6 @@ impl Scan<'_> {
.filter(|use_| use_.name == *name)
.map(|use_| (self.path.to_path_buf(), use_.name_span))
.collect();
let found = vlog_refactor::find_references(
&self.set.files,
self.path,
symbol.name_span.start,
false,
);
match found {
Ok(hits) => {
for (file, span) in hits {
@@ -260,3 +285,5 @@ fn position(project: &Project, set: &WholeSet, file: &Path, span: TextRange) ->
let (line, col) = LineIndex::new(text).line_col(span.start);
format!("{}:{line}:{col}", project.relative(file))
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Which bytes an item owns: the lines `edit_item`'s inserts and deletes
//! work on, and the span its `replace` replaces when its text brings comments.
//!
@@ -155,3 +157,5 @@ mod tests {
assert_eq!(slice(replace_region(src, item, "logic b;\n// own line")), "logic a;");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `op: delete`'s implicit-connection rule: a `.*` binds a signal without
//! spelling it, so `find_references` (which returns only spans that spell
//! the name) never lists it. For each deleted name, every `.*`
@@ -94,3 +96,5 @@ fn binds(index: &WorkspaceIndex, module: &str, name: &str) -> Option<bool> {
}
Some(index.member(module, name).iter().any(|def| def.kind == SymbolKind::Port))
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The verifier the three structural edits share — the one new piece of
//! logic in the MCP block, so it is guilty until proven innocent: every rule
//! here has an attack in `tests/attacks.rs`.
@@ -573,3 +575,5 @@ mod tests {
assert!(owned_names(&analysis, always).is_empty());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+15 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Unresolved mentions: every whole-word spelling of a name that no engine
//! answer accounted for and that sits where no lucisv engine looks — inside
//! a string literal, a comment, a macro call's text, a `` `define`` body, or
@@ -106,9 +108,7 @@ pub fn find<'t>(
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'.')
{
if foreign && !text.get(..at as usize).is_some_and(vlog_refactor::after_dot) {
continue;
}
let end = at + focus.name.len() as u32;
@@ -344,4 +344,16 @@ mod tests {
let (a, b) = (Path::new("/hw/ip/es/rtl/a.sv"), Path::new("/hw/ip/es/dv/b.sv"));
assert_eq!(shared_components(a, b), 4);
}
#[test]
fn foreign_files_recognize_dotted_mentions_past_blanks_comments_and_paste() {
assert!(vlog_refactor::after_dot("u_m."));
assert!(vlog_refactor::after_dot("u_m . "));
assert!(vlog_refactor::after_dot("u_m. /* c */ "));
assert!(vlog_refactor::after_dot("u_m.``"));
assert!(!vlog_refactor::after_dot("/* u_m. */ "));
assert!(!vlog_refactor::after_dot("u_m "));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The tool registry: every tool's name, description, argument list and
//! handler, in one table. The argument list is the single source of both the
//! `inputSchema` a host shows the agent and the validation a call's
@@ -313,3 +315,5 @@ mod tests {
assert_eq!(schema(hierarchy.params)["properties"]["depth"], json!({"type": "integer"}));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+31 -4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Names looked up — the by-name half every lean tool shares: every
//! declaration of a name (the index's units, exported members and module
//! internals, every declaration the files' own symbol tables hold, and the
@@ -9,7 +11,7 @@ use std::collections::{BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_semantic::{Def, DefinitionKey, FileId, Surface, SymbolKind, WorkspaceIndex};
use vlog_semantic::{Def, DefinitionKey, Surface, SymbolKind, WorkspaceIndex};
use super::declared::{declared, Local, Wanted};
use super::source::{checked_site, Texts};
@@ -186,8 +188,8 @@ pub fn similar(project: &Project, name: &str, cap: usize) -> Vec<String> {
index.workspace_symbols(name).iter().map(|hit| hit.name.to_string()).collect();
let part = Wanted::Containing(name.to_ascii_lowercase());
names.extend(declared(project, &part).into_iter().map(|local| local.name));
for at in 0..index.files().len() {
let Some(table) = index.defines(FileId(at as u32)) else { continue };
for (file, _) in index.live_files() {
let Some(table) = index.defines(file) else { continue };
let found = table.entries().iter().filter(|d| contains_any_case(&d.name, name));
names.extend(found.map(|define| define.name.clone()));
}
@@ -220,7 +222,10 @@ pub fn ambiguous(name: &str, found: &[&Declaration], pick: &str) -> String {
#[cfg(test)]
mod tests {
use super::qualified;
use super::{qualified, similar};
use crate::project::Project;
use std::fs;
use std::path::PathBuf;
#[test]
fn a_unit_qualifies_a_name_and_an_escaped_name_is_whole() {
@@ -231,4 +236,26 @@ mod tests {
assert_eq!(qualified("\\a.b "), (None, "\\a.b "));
assert_eq!(qualified(".x"), (None, ".x"));
}
#[test]
fn similar_finds_macros_after_tombstoned_slot_zero() {
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-names-tombstone-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let dir = fs::canonicalize(dir).unwrap();
let a_path = dir.join("a_excl.sv");
fs::write(&a_path, "`define EXCL_MAC 1\nmodule a_excl; endmodule\n").unwrap();
fs::write(dir.join("z_mac.sv"), "`define LIVE_MAC 1\nmodule z_mac; endmodule\n").unwrap();
let mut project = Project::open(vec![dir.clone()], None);
assert!(project.remove_file_from_index(&a_path));
assert_eq!(similar(&project, "LIVE", 20), vec!["LIVE_MAC".to_string()]);
assert!(similar(&project, "EXCL", 20).is_empty());
let _ = fs::remove_dir_all(&dir);
let _: PathBuf = dir;
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `outline`: a file's declarations as a tree with line ranges (its parse
//! errors first), or — for `unit` — what a unit offers the code that uses
//! it (`interface.rs`), so an agent reads the shape before the source.
@@ -59,3 +61,5 @@ fn tree(analysis: &Analysis, nodes: &[DocumentSymbol], level: usize, out: &mut V
tree(analysis, &node.children, level + 1, out);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+8 -2
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `port`'s `after`: the new port placed right after a named one, in the
//! layout of the line it follows, and each named connection placed right
//! after the instance's `.after(…)`.
@@ -417,9 +419,11 @@ mod tests {
assert!(typed.contains("`b` takes its direction"), "{typed}");
let arm = refusal(&design("`ifdef X\n input logic a,\n`endif\n output logic y"), "a");
assert!(arm.contains("inside an `ifdef arm"), "{arm}");
let hidden =
let attributed =
refusal(&design(" input logic [7:0] a,\n (* keep *) b,\n output logic y"), "a");
assert!(hidden.contains("`m`'s port list holds `(* keep *) b`"), "{hidden}");
assert!(attributed.contains("`b` takes its direction"), "{attributed}");
let hidden = refusal(&design(" input logic [7:0] a,\n 123 b,\n output logic y"), "a");
assert!(hidden.contains("`m`'s port list holds `123 b`"), "{hidden}");
let mut files = design(" input logic a,\n output logic y");
files[1].1 =
"module top(input logic a, en, output logic y);\n m u_m (a, y);\nendmodule\n".into();
@@ -446,3 +450,5 @@ mod tests {
assert_eq!(appended_expr(".e(x)", "d"), None);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Where a new list element goes after its anchor, and how it is written.
//!
//! The element always goes **after the separator that follows the anchor**
@@ -304,3 +306,5 @@ mod tests {
assert_eq!(split_declaration("input dbg_i").unwrap().ty, "");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The check a placement must pass before anything is written: the placed
//! edit is the engine's verified edit with elements **moved and nothing
//! else**. Per file, against the engine's result:
@@ -308,3 +310,5 @@ mod tests {
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `port`: add a port to a module and connect it by name in every
//! instantiation, or remove one and its connection everywhere — the
//! design-wide edit a file write cannot do safely. `add` is
@@ -144,3 +146,5 @@ fn instantiations(project: &Project, module: &str) -> (usize, usize) {
let files: BTreeSet<_> = edges.iter().map(|edge| edge.file).collect();
(count, files.len())
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `read`: one item's exact source — a slice, never the file — preceded by
//! `file:first–last`. In a named `file` the item is sliced as
//! `read_item::select` slices it; without one the name is looked up
@@ -78,3 +80,5 @@ fn locate(project: &mut Project, selector: &str) -> Result<PathBuf, String> {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The item slicer `read` and `edit_item` share: one item's exact span in
//! a file — a module, a function, a declaration, an instance, or an
//! unlabelled `always` block named by the line it covers.
@@ -317,3 +319,5 @@ module n; logic q; endmodule
assert!(refused.contains("`\\b` on line 12"), "{refused}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Declaration sites read back off the disk: `find` and the by-name tools
//! answer with `file:line` for declarations in files no analysis is held
//! for. One read per file per call ([`Texts`]); the index's spans are
@@ -271,3 +273,5 @@ mod tests {
assert_eq!(capped("x y", 3), "x y");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The MCP stdio transport: one JSON-RPC message per line in, one per line
//! out. stdout carries protocol lines and nothing else; stderr is the log.
//!
@@ -93,3 +95,5 @@ mod tests {
assert_eq!(written, "{\"text\":\"a\\nb\"}\n");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The dev's attack suite on the structural edits' verifier (lane M4) —
//! CLAUDE.md invariant 4 applied to the MCP block's own safety net: every
//! case is an edit the verifier could plausibly let through, asserted
@@ -784,3 +786,5 @@ fn a_signal_bound_by_a_dot_star_is_still_referenced() {
let clk = json!({"file": "rtl/sw.sv", "item": "clk"});
refused(&tree, &mut server, "delete_item", clk, "bound by `.*` at rtl/sw.sv:7:18 `clk`");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+25
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The index caches over the wire (TODO-MCP M6, PLAN §6): the language
//! server's `index-cache` is read and never written — its bytes are hashed
//! before and after a whole session that indexes, answers and edits — every
@@ -242,11 +244,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);
@@ -255,3 +278,5 @@ fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert!(fs::read_dir(scratch.cache()).unwrap().next().is_none(), "nothing was written");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! 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
@@ -135,3 +137,5 @@ fn over_100_instances_with_peek_shows_100_and_over_300_without_shows_300() {
assert_eq!(plain.lines().count(), 301);
assert!(plain.ends_with("\n… and 51 more\n"), "{plain}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The opentitan census (TODO-MCP M2, ported to the lean catalogue in M7):
//! `find`, `hierarchy`, `check` and `outline` over a real checkout,
//! read-only, each answer checked against what the language server answers
@@ -288,3 +290,5 @@ fn opentitan_startup_cold_and_warm_and_the_stat_sweep() {
let _ = std::fs::remove_dir_all(&cache);
assert_eq!(status(&root), before, "the checkout was only read");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane feedback-1 (unresolved mentions, `add_port`'s `after`
//! and its move-checker, the trimmed catalogue, the temp-store sweep),
//! 2026-09-23 — ported to the lean catalogue: `add_port` is `port` with
@@ -696,3 +698,5 @@ fn qa_the_sweep_takes_only_old_files_of_the_exact_temp_name() {
}
assert!(dir.join("inside").is_dir(), "a directory is never swept");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane feedback-2 (the count line on every paged answer, the
//! `in` path glob, the post-edit check line), 2026-09-23 — ported to the
//! lean catalogue: paging, `in` and the check line are gone (PLAN §10.2),
@@ -282,3 +284,5 @@ fn qa_the_glob_matches_paths_never_names_even_escaped_ones_holding_a_star() {
assert_eq!(formatted("esc/*.sv"), "1");
assert!(formatted("\\esc*mod").contains("\\esc*mod"), "a unit name is not a path");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M1 (transport + read tools), 2026-09-23.
//!
//! Every test spawns the real binary over a scratch tree, as a host would.
@@ -954,3 +956,5 @@ fn qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen() {
set_mtime(&scratch.path("c.sv"), long_ago);
assert_eq!(s.text("find", json!({"name": "chyrlie"})), "module chyrlie c.sv:1\n");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M2 (navigation, diagnostics, defines, resources),
//! 2026-09-23 — ported to the lean catalogue (`find`, `hierarchy`, `check`;
//! `docs/features/mcp-lean-catalogue/README.md` lists what was deleted: the
@@ -796,3 +798,5 @@ fn qa_recheck_one_files_check_is_its_lines_of_lucisv_check_dot() {
);
assert_eq!(s.text("check", json!({"file": "leaf.sv"})), "ok\n");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+30 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M3 (the edit tools and their one write path),
//! 2026-09-23 — ported to the lean catalogue (`rename`, `port`,
//! `edit_item`, `format`); the tools it dropped took their attacks with
@@ -129,13 +131,21 @@ fn copy_tree(from: &Path, to: &Path) {
/// Every entry under a tree, root-relative: a file's bytes and mode, a
/// symlink's target, a directory's mode. Anything moving shows up.
fn snapshot(root: &Path) -> BTreeMap<String, (u32, Vec<u8>)> {
use std::os::unix::fs::PermissionsExt;
#[cfg(unix)]
fn mode_bits(meta: &fs::Metadata) -> u32 {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode()
}
#[cfg(not(unix))]
fn mode_bits(meta: &fs::Metadata) -> u32 {
u32::from(meta.permissions().readonly())
}
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, (u32, Vec<u8>)>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let relative = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
let meta = fs::symlink_metadata(&path).unwrap();
let mode = meta.permissions().mode();
let mode = mode_bits(&meta);
if meta.file_type().is_symlink() {
let target = fs::read_link(&path).unwrap();
out.insert(relative, (mode, target.to_string_lossy().as_bytes().to_vec()));
@@ -343,6 +353,7 @@ fn qa_commit_is_byte_based_a_rewrite_with_the_same_bytes_still_lands() {
}
}
#[cfg(unix)]
#[test]
fn qa_commit_refuses_a_created_path_taken_by_a_dangling_symlink_or_a_directory() {
let scratch = Scratch::empty();
@@ -367,6 +378,7 @@ fn qa_commit_refuses_a_created_path_taken_by_a_dangling_symlink_or_a_directory()
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
}
#[cfg(unix)]
#[test]
fn qa_commit_refuses_a_read_only_last_file_before_writing_the_first() {
use std::os::unix::fs::PermissionsExt;
@@ -481,6 +493,7 @@ fn qa_every_edit_writes_only_what_it_says_and_a_repeat_writes_nothing() {
/// A refusal from every tool — engine refusals, argument refusals, path
/// refusals — and not one byte or mode bit of the tree moves.
#[cfg(unix)]
#[test]
fn qa_every_refusal_leaves_every_byte_and_mode_identical() {
let scratch = Scratch::edit_fixture();
@@ -628,6 +641,7 @@ fn qa_a_rename_racing_a_writer_never_tears_a_file() {
// ================================================ paths (attack 3)
#[cfg(unix)]
#[test]
fn qa_rewritten_paths_never_leave_the_root() {
let scratch = Scratch::edit_fixture();
@@ -648,6 +662,7 @@ fn qa_rewritten_paths_never_leave_the_root() {
assert!(moved(&outside_pristine, &snapshot(&outside.0)).is_empty());
}
#[cfg(unix)]
#[test]
fn qa_a_read_only_target_refuses_before_the_first_write() {
use std::os::unix::fs::PermissionsExt;
@@ -669,6 +684,7 @@ fn qa_a_read_only_target_refuses_before_the_first_write() {
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
}
#[cfg(unix)]
#[test]
fn qa_formatting_through_a_symlink_writes_the_file_and_keeps_the_link() {
let scratch = Scratch::with(&[("real.sv", "module r(input logic a);\nendmodule\n")]);
@@ -706,6 +722,15 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
copy_tree(&scratch.0, &reference.0);
let status = Command::new(&cli).arg("--no-cache").arg(&reference.0).output().unwrap();
assert!(status.status.success(), "{status:?}");
// The server is spawned before the checker starts, never while it runs.
// A spawn on one thread can inherit a pipe another thread is just
// creating for its child: macOS has no `pipe2`, so close-on-exec is set
// in a second step. Seen once under load (2026-11-19, `lsof`): the
// server held the write end of a `lucisv --check`'s stdout. That
// `output()` never saw EOF, `join` below waited on it, and the server,
// which lives until this test ends, never let go, so the test hung.
// Spawned first, the server cannot hold any of the checker's pipes.
let mut server = Session::over(&scratch);
let stop = Arc::new(AtomicBool::new(false));
let checker = {
let (stop, cli, root) = (Arc::clone(&stop), cli.clone(), scratch.0.clone());
@@ -719,7 +744,6 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
codes
})
};
let mut server = Session::over(&scratch);
for _ in 0..5 {
for (name, text) in &messy {
scratch.write(name, text);
@@ -1208,6 +1232,7 @@ fn qa_an_edit_sees_a_file_created_just_before_it() {
/// Finding 7 (non-blocking): an over-1 MiB file reached through a symlink
/// leading out of the root is not in the skipped set.
#[cfg(unix)]
#[test]
fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
let scratch = Scratch::edit_fixture();
@@ -1218,3 +1243,5 @@ fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
let text = text_of(&server.rename_d());
assert!(!text.contains(outside.root()), "{text}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M4 (the structural edits and their verifier),
//! 2026-09-23.
//!
@@ -1308,3 +1310,5 @@ fn qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always() {
}
assert!(strict(&tree.read("rtl/d.sv")));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+25
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M6 (the index caches and the rule-6 ruling),
//! 2026-09-23.
//!
@@ -444,6 +446,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 +473,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());
@@ -681,3 +704,5 @@ fn qa_the_instructions_are_short_and_name_only_real_tools() {
assert!(text.contains(phrase), "{phrase}: {text}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+8 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M7 (the lean catalogue), 2026-09-24.
//!
//! Every test writes a small design into its own scratch directory, spawns
@@ -805,10 +807,11 @@ fn qa_rework_an_escaped_net_is_still_found_through_the_index() {
}
#[test]
#[ignore = "QA re-check finding R2"]
fn qa_rework_an_escaped_local_outline_lists_is_found() {
// The word census holds identifier-shaped words only, so `declared.rs`
// never opens a file for an escaped name the index does not record.
// QA re-check finding R2, closed in Round 8: the word census holds an
// escaped identifier as its token spells it (`FACTS_FORMAT` 23), so
// `declared.rs` opens the file for an escaped name the index does not
// record as a unit or member.
let text_g = "module g (input logic clk, output logic o);\n function automatic logic fn(input logic x);\n logic \\loc.v ;\n \\loc.v = x;\n return \\loc.v ;\n endfunction\n assign o = fn(clk);\nendmodule\n";
let tree = Tree::with(&[("rtl/g.sv", text_g)]);
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
@@ -867,3 +870,5 @@ fn a_members_rename_lists_only_its_own_mentions_and_dotted_ones_elsewhere() {
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}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+12 -1
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M8 (`--read-only`), 2026-09-29.
//!
//! Every test copies a fixture into its own scratch directory, spawns the
@@ -113,7 +115,14 @@ fn run(args: &[&str], lines: &[Value]) -> Output {
Value::String(raw) => raw.clone(),
other => other.to_string(),
};
writeln!(stdin, "{text}").unwrap();
// A refused argument list exits 2 before reading a byte, so the write
// races that exit and can fail with `BrokenPipe`. That is the child
// being gone, not the test failing: what it said and its exit code
// are what the caller asserts on. Any other error is a failure.
match writeln!(stdin, "{text}") {
Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => break,
result => result.unwrap(),
}
}
drop(stdin);
child.wait_with_output().unwrap()
@@ -555,3 +564,5 @@ fn qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek() {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+6 -2
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `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,
@@ -24,8 +26,8 @@ const FIVE: [&str; 5] = ["hierarchy", "find", "outline", "read", "check"];
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;
const CATALOGUE_BUDGET: usize = 2_000;
const INSTRUCTIONS_BUDGET: usize = 330;
/// 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.";
@@ -339,3 +341,5 @@ fn the_edit_calls_write_in_full_mode() {
assert_ne!(before, snapshot(&tree), "{name} wrote nothing in full mode");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+144 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The wire contract, pinned against the real binary: each test copies the
//! fixture design into its own temporary directory, spawns `lucisv-mcp` over
//! it and talks newline-delimited JSON-RPC to it, as a host would.
@@ -172,8 +174,8 @@ const NINE: [&str; 9] =
["hierarchy", "find", "outline", "read", "check", "rename", "port", "edit_item", "format"];
/// The model-visible catalogue's ceiling and the instructions' (PLAN §10.5).
const CATALOGUE_BUDGET: usize = 3_500;
const INSTRUCTIONS_BUDGET: usize = 400;
const CATALOGUE_BUDGET: usize = 3_800;
const INSTRUCTIONS_BUDGET: usize = 440;
#[test]
fn the_handshake_negotiates_and_describes_the_server() {
@@ -184,7 +186,7 @@ fn the_handshake_negotiates_and_describes_the_server() {
assert_eq!(result["protocolVersion"], "2025-06-18");
assert_eq!(result["serverInfo"]["name"], "lucisv-mcp");
assert_eq!(result["serverInfo"]["version"], env!("CARGO_PKG_VERSION"));
assert_eq!(result["capabilities"], json!({"tools": {}, "resources": {}, "prompts": {}}));
assert_eq!(result["capabilities"], json!({"tools": {}, "resources": {}}));
// The `initialized` notification drew no answer: the next line is ping's.
assert_eq!(server.request("ping", json!({}))["result"], json!({}));
let newest = server.request("initialize", json!({"protocolVersion": "1999-01-01"}));
@@ -1264,3 +1266,142 @@ fn a_stale_temp_store_is_swept_and_a_young_one_and_other_files_are_spared() {
assert!(young.exists(), "a young one may be a live writer's");
assert!(other.exists(), "only `<store>.<pid>.tmp` is ours to sweep");
}
#[test]
fn check_supports_directories_and_globs_and_refuses_bad_targets() {
let (tree, mut server) = served("nav");
fs::create_dir_all(tree.path("empty_dir")).unwrap();
// Directory target lints only indexed files under that directory (no unused-waiver).
let rtl_all = server.text("check", json!({"file": "rtl"}));
assert_eq!(rtl_all, server.text("check", json!({"file": "./rtl/"})));
assert!(rtl_all.contains("rtl/core.sv:10:17 warning"), "{rtl_all}");
assert!(rtl_all.contains("rtl/checker_m.sv:1:41 style"), "{rtl_all}");
assert!(!rtl_all.contains("waiver"), "subset checks omit whole-design waivers: {rtl_all}");
// `.` matches the root tree as a directory.
assert_eq!(server.text("check", json!({"file": "."})), rtl_all);
// Glob targets select matching indexed files only.
assert_eq!(
server.text("check", json!({"file": "rtl/checker_*.sv"})),
"rtl/checker_m.sv:1:41 style line is 45 characters; the limit is 40 [line-length]\n"
);
assert_eq!(server.text("check", json!({"file": "rtl/tree*.sv"})), "ok\n");
// Empty, missing, empty-directory, and outside-root paths/globs refuse.
assert!(refusal(&mut server, "check", json!({"file": ""})).contains("empty"));
assert!(
refusal(&mut server, "check", json!({"file": "missing_dir"})).contains("does not exist")
);
assert!(refusal(&mut server, "check", json!({"file": "empty_dir"})).contains("no indexed file"));
assert!(
refusal(&mut server, "check", json!({"file": "rtl/*.none"})).contains("no indexed file")
);
let sibling = Tree::new();
let sibling_arg = format!("../{}", sibling.0.file_name().unwrap().to_str().unwrap());
assert!(refusal(&mut server, "check", json!({"file": ".."})).contains("outside every root"));
assert!(
refusal(&mut server, "check", json!({"file": sibling_arg})).contains("outside every root")
);
assert!(refusal(&mut server, "check", json!({"file": "../../etc/*.sv"}))
.contains("outside every root"));
}
#[test]
fn find_and_rename_share_dotted_mentions_bind_home_set_and_qualified_focus() {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let root = std::env::temp_dir().join(format!("lucisv-mcp-l9-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
let tree = Tree(fs::canonicalize(&root).unwrap());
for (rel, body) in [
(
"rtl/alpha.sv",
"module alpha;\n logic state_q;\n assign state_q = 1'b0;\nendmodule\n",
),
(
"rtl/beta.sv",
"module beta;\n logic state_q;\n // bare state_q inside unrelated beta\nendmodule\n",
),
("rtl/defs.svh", "`define BIND_ALPHA bind alpha chk u_chk ();\n"),
(
"rtl/bind_alpha.sv",
"`include \"defs.svh\"\n`BIND_ALPHA\n// bare state_q inside binder\nmodule chk; endmodule\n",
),
(
"dv/aa_other.sv",
"module aa_other;\n // u_beta . state_q\nendmodule\n",
),
(
"dv/probe.sv",
"module probe;\n // u_alpha . state_q\n // u_alpha./*c*/state_q\n // `HIER.u_alpha.``state_q\n // bare state_q in dv ignored\nendmodule\n",
),
(
"dv/zz_alpha.sv",
"module zz_alpha;\n // `HIER.u_alpha.state_q\nendmodule\n",
),
] {
let p = tree.path(rel);
fs::create_dir_all(p.parent().unwrap()).unwrap();
fs::write(&p, body).unwrap();
}
let mut server = Session::over(&tree);
server.initialize();
let found = server.text("find", json!({"name": "alpha.state_q", "refs": true}));
assert!(found.starts_with("var state_q rtl/alpha.sv:2\n rtl/alpha.sv:3\n"), "{found}");
assert!(!found.contains("rtl/beta.sv"), "unrelated unit excluded: {found}");
assert!(found.contains("rtl/bind_alpha.sv:3"), "K2 macro binder included: {found}");
assert!(
found.contains("dv/probe.sv:2,3,4\n") && !found.contains("dv/probe.sv:2,3,4,5"),
"L-9 dotted mentions (blanks/comments/paste) included, bare in foreign excluded: {found}"
);
// Focus::unit = Some("alpha") ranks lines naming `alpha` above `dv/aa_other.sv`.
let alpha_pos = found.find("dv/zz_alpha.sv:2").unwrap();
let other_pos = found.find("dv/aa_other.sv:2").unwrap();
assert!(alpha_pos < other_pos, "unit focus should rank alpha lines first:\n{found}");
// `rename` reports the exact same bind-aware home set and dotted mentions.
let renamed = server
.text("rename", json!({"name": "state_q", "file": "rtl/alpha.sv", "new_name": "next_q"}));
assert!(renamed.contains("rtl/bind_alpha.sv:3"), "{renamed}");
assert!(renamed.contains("dv/probe.sv:2,3,4"), "{renamed}");
assert!(!renamed.contains("rtl/beta.sv"), "{renamed}");
}
#[test]
fn cached_known_facts_invalidate_when_disk_changes_between_calls() {
let (tree, mut server) = served("nav");
let orig_top = fs::read_to_string(tree.path("rtl/top.sv")).unwrap();
let before = server.text("find", json!({"name": "state_q", "refs": true}));
assert!(!before.contains("rtl/new_user.sv"), "{before}");
// Add a hierarchical reference to `core.state_q` on disk between calls.
fs::write(
tree.path("rtl/top.sv"),
format!("{orig_top}\n// extra\nmodule extra;\n logic peek;\n assign peek = core.state_q;\nendmodule\n"),
)
.unwrap();
let after = server.text("find", json!({"name": "state_q", "refs": true}));
assert!(after.contains("rtl/top.sv:8,14"), "{after}");
// Revert `rtl/top.sv` and verify cached facts invalidate back cleanly.
fs::write(tree.path("rtl/top.sv"), &orig_top).unwrap();
let reverted = server.text("find", json!({"name": "state_q", "refs": true}));
assert!(
reverted.contains("rtl/top.sv:8\n") && !reverted.contains("rtl/top.sv:8,14"),
"{reverted}"
);
// Add a new file referencing `core.state_q` and verify lazy rewalk + KnownFacts stays fresh.
fs::write(
tree.path("rtl/new_user.sv"),
"module new_user;\n logic peek;\n assign peek = core.state_q;\nendmodule\n",
)
.unwrap();
let added = server.text("find", json!({"name": "state_q", "refs": true}));
assert!(added.contains("rtl/new_user.sv:3"), "{added}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+5
View File
@@ -1,6 +1,9 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv_server"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
@@ -19,3 +22,5 @@ lsp-server = { workspace = true }
lsp-types = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+435
View File
@@ -0,0 +1,435 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! 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),
},
};
let preset = vlog_formatter::style::preset(preset.name).unwrap_or(preset);
Config { style: preset.with_overrides(&config.overrides), 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");
}
#[test]
fn concrete_layers_and_refreshes_overrides_onto_remembered_preset() {
use vlog_formatter::{Placement, StyleOverrides};
let (ws, uri) = open(GOOGLE);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
// Format once with an override: `else_keyword = OwnLine` is remembered.
let with_else = auto().with_overrides(StyleOverrides {
else_keyword: Some(Placement::OwnLine),
..Default::default()
});
let _ = styles.format_document(&uri, doc, &with_else).expect("formats");
// Now clear the override in client/project settings and resolve a range:
// concrete must reapply against the clean preset, not retain stale `OwnLine`.
let cleared = styles.concrete(&uri, doc, auto());
assert_eq!(cleared.style, style::GOOGLE);
// And layering a new override on top applies immediately.
let with_begin = auto().with_overrides(StyleOverrides {
begin: Some(Placement::OwnLine),
..Default::default()
});
let updated = styles.concrete(&uri, doc, with_begin);
assert_eq!(updated.style.begin, Placement::OwnLine);
assert_eq!(updated.style.else_keyword, Placement::SameLine);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+151 -13
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The tables a completion request reads instead of walking the workspace.
//!
//! Completion fires on every keystroke, so nothing here may be computed per
@@ -145,9 +147,20 @@ impl Candidates {
pub fn from_words(index: &WorkspaceIndex, words: HashMap<PathBuf, Vec<String>>) -> Candidates {
let mut out = Candidates::default();
out.take_index_tables(index);
// Sized once and counted without a copy per occurrence: on 40 000
// files that is 3.5 M word occurrences and 140 k distinct words, and
// `entry(word.clone())` allocated a `String` for every one of the
// 3.5 M (`docs/features/server-scaling-r10/README.md`).
out.per_file.reserve(words.len());
for (path, words) in words {
let words = insertable(words);
for word in &words {
*out.word_files.entry(word.clone()).or_default() += 1;
match out.word_files.get_mut(word.as_str()) {
Some(files) => *files += 1,
None => {
out.word_files.insert(word.clone(), 1);
}
}
}
if !words.is_empty() {
out.per_file.insert(path, words);
@@ -197,17 +210,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.
///
@@ -240,7 +322,7 @@ impl Candidates {
/// Make `words` this file's words, adjusting the workspace-wide table.
fn set_words(&mut self, path: &Path, words: Vec<String>) {
let mut touched = HashMap::new();
self.count_words(path, words, &mut touched);
self.count_words(path, insertable(words), &mut touched);
self.merge_words(touched);
}
@@ -460,6 +542,16 @@ impl Candidates {
}
}
/// A file's census without its escaped identifiers. Since `FACTS_FORMAT` 23
/// the census holds `\\my.sig` as written, which is what every pre-filter that
/// reads it wants; completion is the one reader that *inserts* a word, and an
/// escaped identifier inserted without its terminating space runs into
/// whatever follows it, so this table never offers one.
fn insertable(mut words: Vec<String>) -> Vec<String> {
words.retain(|word| !word.starts_with('\\'));
words
}
/// Keep the best `cap` hits, in order, and throw the rest away.
///
/// Bounded rather than sorted whole, because the two are not the same price at
@@ -715,7 +807,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
@@ -754,17 +854,10 @@ fn index_tables(index: &WorkspaceIndex) -> (Vec<Candidate>, Vec<String>) {
/// defined, and offering the name is the honest answer either way.
fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
let mut out: Vec<Macro> = Vec::new();
for id in 0..index.files().len() {
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
for (file, _) in index.live_files() {
let Some(table) = index.defines(file) 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 +865,31 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
out
}
/// One `` `define``'s completion entry.
pub(crate) 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 +904,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)
}
@@ -879,6 +998,23 @@ mod tests {
assert!(!names.contains(&"string_only_name"), "a string is not code: {names:?}");
}
/// The census holds `\\esc.sig` since `FACTS_FORMAT` 23; completion, the
/// one reader that inserts a word, still never offers it — neither from a
/// whole build nor from one file's words handed over afterwards.
#[test]
fn an_escaped_identifier_is_never_offered_as_a_word() {
let text = "module a;\n logic \\esc.sig ;\n logic plain;\nendmodule\n";
assert!(words_in(text).contains(&"\\esc.sig".to_string()), "the census holds it");
let mut candidates = built(&[("/rtl/a.sv", text)]);
let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect();
assert!(
names.contains(&"plain") && !names.iter().any(|w| w.starts_with('\\')),
"{names:?}"
);
candidates.set_file_words(Path::new("/rtl/b.sv"), words_in(text));
assert!(!candidates.words("").iter().any(|w| w.starts_with('\\')));
}
/// An interface is instantiated exactly as a module is, so it belongs in
/// the module table the completion tier and `has_module` read
/// (`docs/features/interface-semantics/README.md`).
@@ -1574,3 +1710,5 @@ mod tests {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+131
View File
@@ -0,0 +1,131 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Which byte a "symbol under the cursor" request is about.
//!
//! An LSP position is a caret *between* two characters, and a span here is
//! end-exclusive, so a caret just past an identifier's last letter names the
//! character **after** the name. VS Code calls that caret "on the word" — a
//! double-click, a click on the right half of the last letter, or a jump that
//! selects the name all leave it there, and its own word highlight and the
//! title of a references search both use the word before it. Asking about the
//! next character instead answered `[]`, and VS Code said "No references
//! found" for a name it was showing as selected
//! (`docs/features/scan-ordering/README.md`, A1).
//!
//! The rule is VS Code's: a caret touching a name on its right edge is on
//! that name — unless a name also starts at the caret, which then wins
//! (`a|b` cannot happen; `a|.b` is on `a`, `a.|b` is on `b`).
/// The byte offset a request about the name under the cursor should resolve,
/// given the caret's byte offset in `text`.
///
/// Moves one byte left when the caret is just past a name and not at the
/// start of another; every other caret is returned unchanged. A name is an
/// identifier, keyword, system task, macro or number written with
/// [`is_name_byte`] — or an escaped identifier, `\` up to the whitespace that
/// ends it, whose own characters can be anything.
pub fn symbol_offset(text: &str, caret: u32) -> u32 {
let bytes = text.as_bytes();
let at = caret as usize;
if at == 0 || at > bytes.len() || bytes.get(at).copied().is_some_and(is_name_byte) {
return caret;
}
let before = bytes[at - 1];
if is_name_byte(before) || ends_an_escaped_identifier(bytes, at) {
return caret - 1;
}
caret
}
/// Whether `byte` can be part of a simple identifier (IEEE 1800-2017 §5.6):
/// a letter, a digit, `_` or `$`. A system task's leading `$` and a macro
/// name after its backtick are covered by the same set.
fn is_name_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}
/// Whether the caret at `at` sits on the whitespace (or the end of the text)
/// that terminates an escaped identifier — a `\` followed by at least one
/// non-whitespace byte, all of it before the caret.
fn ends_an_escaped_identifier(bytes: &[u8], at: usize) -> bool {
if bytes.get(at).is_some_and(|b| !b.is_ascii_whitespace()) {
return false;
}
let start = bytes[..at].iter().rposition(u8::is_ascii_whitespace).map_or(0, |ws| ws + 1);
at - start >= 2 && bytes[start] == b'\\'
}
#[cfg(test)]
mod tests {
use super::symbol_offset;
/// The offset `symbol_offset` picks for the caret written as `|` in
/// `marked`, as the character it lands on (`None` past the end).
fn lands_on(marked: &str) -> Option<char> {
let caret = marked.find('|').expect("a caret") as u32;
let text = marked.replacen('|', "", 1);
let at = symbol_offset(&text, caret) as usize;
text[at..].chars().next()
}
#[test]
fn a_caret_just_past_a_name_is_on_its_last_letter() {
assert_eq!(lands_on("logic tx|,"), Some('x'));
assert_eq!(lands_on("assign y = tx|;"), Some('x'));
assert_eq!(lands_on("tx|"), Some('x'), "at the end of the text");
assert_eq!(lands_on("logic tx|\nwire w;"), Some('x'), "at the end of a line");
assert_eq!(lands_on("logic tx|\r\nwire w;"), Some('x'), "before a CRLF");
}
#[test]
fn a_caret_on_or_inside_a_name_is_left_alone() {
assert_eq!(lands_on("logic |tx;"), Some('t'), "at the start");
assert_eq!(lands_on("logic t|x;"), Some('x'), "in the middle");
}
#[test]
fn a_caret_touching_two_names_takes_the_one_that_starts_there() {
// VS Code's word at `a|.b` is `a`; at `a.|b` it is `b`.
assert_eq!(lands_on("u_a|.sig"), Some('a'), "before the dot: the instance");
assert_eq!(lands_on("u_a.|sig"), Some('s'), "after the dot: the member");
assert_eq!(lands_on(".clk|(clk_i)"), Some('k'), "a port name before its paren");
assert_eq!(lands_on(".clk(|clk_i)"), Some('c'), "the signal after the paren");
assert_eq!(lands_on("mem|[3]"), Some('m'), "a name before an index");
}
#[test]
fn a_caret_after_anything_but_a_name_is_left_alone() {
assert_eq!(lands_on("a = b;|"), None, "past a semicolon at the end");
assert_eq!(lands_on("a = b; |"), None, "past whitespace");
assert_eq!(lands_on("f(x)|;"), Some(';'), "past a paren");
assert_eq!(lands_on("|"), None, "an empty text");
assert_eq!(lands_on("|tx"), Some('t'), "the very start");
}
#[test]
fn system_tasks_macros_and_keywords_are_names_too() {
assert_eq!(lands_on("$display|("), Some('y'));
assert_eq!(lands_on("`WIDTH|-1"), Some('H'));
assert_eq!(lands_on("begin|\n"), Some('n'), "so a keyword pair highlights");
}
#[test]
fn an_escaped_identifier_ends_at_its_whitespace() {
// `\a+b ` is one name whose last byte is not an identifier byte.
assert_eq!(lands_on(r"assign \a+b+ |= 1;"), Some('='), "past the space: not on it");
assert_eq!(lands_on(r"assign \a+b+| = 1;"), Some('+'), "on the space that ends it");
assert_eq!(lands_on(r"\bus[0]|"), Some(']'), "at the end of the text");
assert_eq!(lands_on(r"x = a \| b;"), Some(' '), "a lone backslash is not a name");
}
#[test]
fn non_ascii_text_before_the_name_does_not_move_the_byte() {
// The caret arrives as a byte offset already converted from UTF-16;
// the rule reads bytes, and a multi-byte character is never a name.
assert_eq!(lands_on("// é\nlogic tx|;"), Some('x'));
assert_eq!(lands_on("é|tx"), Some('t'), "a name starting after a non-ASCII letter");
assert_eq!(lands_on("é|;"), Some(';'), "a non-ASCII letter is not a name");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+6 -2
View File
@@ -1,10 +1,12 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `textDocument/codeAction` — one quick fix per Safe lint fix, plus one
//! `source.fixAll.lucisv` that applies all of them in a single pass.
//!
//! Only **Safe** fixes are offered. `--unsafe-fixes` is a flag a CLI user types
//! on purpose; a lightbulb in an editor is not that, and a fix that may change
//! what the circuit does must not be one click away. (No rule ships an Unsafe
//! fix today, so this is a rule for the first one that does.)
//! what the circuit does must not be one click away. (`always-comb` and
//! `mismatched-labels` ship Unsafe fixes; neither is offered here.)
use std::collections::HashMap;
@@ -476,3 +478,5 @@ mod tests {
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Tiers 2 and 3: what the buffer being typed in declares, and the words it
//! uses (TODO §68.1, `completion-ux`).
//!
@@ -142,3 +144,5 @@ endmodule
assert!(sort("al_used") < sort("always_ff"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! 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
@@ -100,3 +102,5 @@ mod tests {
assert!(!paren_follows(".cl, .b(x)", 1));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The completion tests' harness: a scratch workspace on disk, and the
//! handful of helpers every provider's tests ask through.
//!
@@ -112,3 +114,5 @@ pub(super) fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a C
pub(super) fn labels(items: &[CompletionItem]) -> Vec<&str> {
items.iter().map(|item| item.label.as_str()).collect()
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4 -827
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The member answer: after a `.` or a `::`, the members of what stands
//! before it and nothing else.
//!
@@ -375,831 +377,6 @@ fn last_segment(path: &str) -> &str {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
mod tests;
// ------------------------------------------------------------------
// the member answer (2026-09-02) — after a `.` or a `::`
// ------------------------------------------------------------------
/// The buffer most of these ask against: a class chain, a struct, an
/// interface with a modport and a clocking block, and a handle for each.
const MEMBERS: &str = "\
interface bus_if;
logic clk;
logic [7:0] data;
modport mp (input clk);
clocking cb @(posedge clk);
input data;
endclocking
endinterface
typedef struct packed { logic [7:0] addr; logic vld; } hdr_t;
class base_c;
bit from_base;
endclass
class item_c extends base_c;
bit user_id;
bit feature1;
hdr_t hdr;
function void run();
endfunction
endclass
module top;
virtual bus_if vif;
item_c item;
item_c queue[4];
hdr_t [3:0] hs;
hdr_t h;
initial begin
item.
end
endmodule
";
/// The names a member request against [`MEMBERS`] offers, **sorted** —
/// which is the order the client shows them in, because `sortText` is
/// `<tier digit><name>`. The array order is the cap's order and is pinned
/// separately by [`the_list_is_ordered_nearest_declaration_first`].
fn member_labels(name: &str, spine: &str) -> Vec<String> {
let mut found: Vec<String> =
items(member_response(name, spine)).iter().map(|item| item.label.clone()).collect();
found.sort();
found
}
/// The whole response, for the tests that read more than the labels.
fn member_response(name: &str, spine: &str) -> Option<CompletionResponse> {
let top = MEMBERS.replace(" item.\n", &format!(" {spine}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, spine);
completions(&ws, &uri, position, true)
}
#[test]
fn a_class_handle_lists_its_members_and_its_bases() {
assert_eq!(
member_labels("cls", "item."),
vec!["feature1", "from_base", "hdr", "run", "user_id"],
);
}
#[test]
fn the_member_answer_is_exclusive() {
let items = items(member_response("exclusive", "item."));
// No keyword, no template, no project word — every item is a member,
// and every one of them is filed under the member tier.
for item in &items {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::KEYWORD), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::TEXT), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::SNIPPET), "{item:#?}");
}
let found = labels(&items);
assert!(!found.contains(&"always_ff"), "no keywords");
assert!(!found.contains(&"top"), "no index names");
assert!(!found.contains(&"vif"), "not even what is visible at the cursor");
}
/// A member wins over a same-named local because the answer is exclusive:
/// the local is not a worse candidate here, it is not a candidate.
#[test]
fn a_local_of_the_same_name_is_not_offered_beside_the_member() {
let top = MEMBERS.replace(" item.\n", " bit user_id;\n item.\n");
let tree = Tree::new("shadow");
let (_tree, ws, uri, position) = opened(tree, &top, "item.");
let items = items(completions(&ws, &uri, position, true));
let user_id = find(&items, "user_id").expect("the member");
assert_eq!(user_id.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(items.iter().filter(|item| item.label == "user_id").count(), 1);
}
#[test]
fn a_nested_struct_field_lists_the_inner_fields() {
assert_eq!(member_labels("struct", "h."), vec!["addr", "vld"]);
assert_eq!(member_labels("struct2", "item.hdr."), vec!["addr", "vld"]);
}
#[test]
fn an_interface_handle_lists_its_signals_its_modports_and_its_clocking() {
let found = member_labels("iface", "vif.");
for wanted in ["clk", "data", "mp", "cb"] {
assert!(found.contains(&wanted.to_string()), "{wanted} missing from {found:?}");
}
}
/// A clocking block's `type_name` is the interface enclosing it
/// (interface-semantics, 2026-09-01), which is what makes `vif.cb.data`
/// resolve to the interface's own `data` declaration — correct
/// SystemVerilog, since a clocking block names a *view* of those signals
/// and declares nothing of its own. So the list after `vif.cb.` is the
/// interface's, exactly as the resolution is: one walk, one answer, wider
/// than the block's own item list and never wrong about a name.
#[test]
fn a_clocking_block_lists_the_enclosing_interfaces_signals() {
assert_eq!(member_labels("clocking", "vif.cb."), member_labels("clocking2", "vif."));
assert!(member_labels("clocking3", "vif.cb.").contains(&"data".to_string()));
}
/// A **packed** array head is indexed away and names its element type's
/// members: `hdr_t [3:0] hs; hs[1].` is a `hdr_t`.
#[test]
fn a_packed_array_head_is_indexed_away() {
assert_eq!(member_labels("indexed", "hs[1]."), vec!["addr", "vld"]);
assert_eq!(member_labels("indexed2", "hs[i][j]."), vec!["addr", "vld"], "and repeatedly");
}
/// An **unpacked** declarator answers nothing, and that is
/// `vlog_semantic`'s own ruling rather than this file's: `item_c q[4]`
/// names a container, not a value of `item_c`, so no `type_name` is
/// recorded and `q.size()` is an array method rather than a member
/// (`bind.rs::declare_typed`). Completion may not mint a type the
/// resolver refuses to mint — that would be the second resolver this
/// round exists to avoid. Filed as a follow-on in the feature README.
#[test]
fn an_unpacked_array_head_answers_nothing_because_it_has_no_declared_type() {
assert!(member_response("unpacked", "queue[0].").is_none());
}
/// The order of the `items` array is the order the cap keeps, and it is
/// **nearest declaration first**: a class's own members before its base's,
/// in declaration order within each. `sortText` still says the client
/// should draw them alphabetically.
#[test]
fn the_list_is_ordered_nearest_declaration_first() {
let items = items(member_response("order", "item."));
assert_eq!(labels(&items), vec!["user_id", "feature1", "hdr", "run", "from_base"]);
for item in &items {
assert_eq!(item.sort_text.as_deref(), Some(format!("0{}", item.label).as_str()));
}
}
#[test]
fn this_and_super_answer_from_inside_a_method() {
let top =
MEMBERS.replace(" function void run();\n", " function void run();\n this.\n");
let tree = Tree::new("this");
let (_tree, ws, uri, position) = opened(tree, &top, " this.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["feature1", "from_base", "hdr", "run", "user_id"]);
let top =
MEMBERS.replace(" function void run();\n", " function void run();\n super.\n");
let tree = Tree::new("super");
let (_tree, ws, uri, position) = opened(tree, &top, " super.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["from_base"], "super is the base and not the class itself");
}
#[test]
fn the_kind_and_the_detail_come_off_the_declaration() {
let items = items(member_response("detail", "item."));
// In this buffer the declaration's own line is free, so that is the
// card — the same one tier 1 has always shown.
let hdr = find(&items, "hdr").expect("the struct-typed property");
assert_eq!(hdr.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(hdr.detail.as_deref(), Some("hdr_t hdr;"), "the declaration itself");
let run = find(&items, "run").expect("the method");
assert_eq!(run.kind, Some(CompletionItemKind::FUNCTION));
assert_eq!(run.detail.as_deref(), Some("function void run();"));
// A method inserts its bare name: the parentheses and the arguments
// are the user's to write, and a completion that invented them would
// be guessing at the call.
assert_eq!(inserted(run), "run");
assert_eq!(run.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
/// The edit is an **empty** range at the cursor, so accepting an item
/// writes the member name after the dot and touches nothing before it.
#[test]
fn the_edit_is_empty_at_the_cursor_after_a_separator() {
let items = items(member_response("range", "item."));
assert!(!items.is_empty());
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, edit.range.end, "{item:#?}");
assert_eq!(edit.new_text, item.label);
}
}
/// And with characters typed after the dot it replaces exactly those.
#[test]
fn the_edit_replaces_exactly_what_was_typed_after_the_separator() {
let items = items(member_response("range2", "item.us"));
assert_eq!(labels(&items), vec!["user_id"]);
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start.character + 2, edit.range.end.character);
}
#[test]
fn a_typed_prefix_filters_below_the_fuzzy_floor_and_a_subsequence_from_it_up() {
// One and two characters: a prefix, exactly as every other tier does
// below the floor. `fe` reaches `feature1` and not `from_base`.
assert_eq!(member_labels("prefix1", "item.f"), vec!["feature1", "from_base"]);
assert_eq!(member_labels("prefix2", "item.fe"), vec!["feature1"]);
// Three: a subsequence, so `fbs` reaches `from_base` — which no
// prefix match ever would.
assert_eq!(member_labels("fuzzy", "item.fbs"), vec!["from_base"]);
assert_eq!(member_labels("fuzzy2", "item.usr"), vec!["user_id"]);
}
/// **The `isIncomplete` rule.** The request that matters — the one the
/// trigger character fires, with nothing typed yet — is complete, so VS
/// Code filters the whole member list client-side. A 1- or 2-character
/// answer is a prefix slice that the third keystroke would *widen*, so it
/// must say it is incomplete or the widening never reaches the client.
#[test]
fn only_a_filtered_answer_below_the_fuzzy_floor_is_incomplete() {
let incomplete = |name: &str, spine: &str| match member_response(name, spine) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
};
assert!(!incomplete("inc0", "item."), "the whole list is the whole answer");
assert!(incomplete("inc1", "item.f"), "a prefix slice widens at the third character");
assert!(incomplete("inc2", "item.fe"));
assert!(!incomplete("inc3", "item.fea"), "a subsequence hit set only shrinks");
// Even a query nothing matches answers with a list, so the client is
// told to come back rather than left filtering an answer it has not
// got.
assert!(incomplete("inc4", "item.zz"));
let empty = items(member_response("inc5", "item.zz"));
assert!(empty.is_empty());
}
/// An **empty** answer is incomplete whatever was typed — including at
/// zero characters, where a non-empty list would be complete. QA finding
/// 2 (2026-09-02) is the reason: a cold index whose scope ladder has not
/// reached the declaring file's directory yet answers empty for one
/// request and correctly for the next, and a *complete* emptiness would
/// be cached by the client until the user retyped the dot.
#[test]
fn an_empty_answer_always_asks_the_client_to_come_back() {
let top = "class hollow_c;\nendclass\nmodule top;\n hollow_c h;\n initial begin\n h.\n end\nendmodule\n";
let tree = Tree::new("hollow");
let (_tree, ws, uri, position) = opened(tree, top, " h.");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty(), "a class with no members");
assert!(list.is_incomplete, "and the client is asked to come back");
}
other => panic!("a list, not {other:#?}"),
}
// The same for a connection list whose module nothing declares.
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("hollowconn", top, " .");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty());
assert!(list.is_incomplete);
}
other => panic!("a list, not {other:#?}"),
}
}
#[test]
fn an_unresolvable_head_answers_nothing_at_all() {
for (name, spine) in [
("nohead", "no_such_handle."),
("call", "f()."),
("nothing", "."),
("space", "item ."),
("untyped", "vif.clk."),
] {
assert!(
member_response(name, spine).is_none(),
"{spine} must answer nothing, not a guess",
);
}
}
/// A lone `:` is a case item, a label or a ternary — not a separator. The
/// request there is the ordinary six-tier one it always was.
#[test]
fn a_lone_colon_falls_through_to_the_ordinary_tiers() {
let top = "module top;\n logic sig;\n initial\n case (1)\n 1: si\n endcase\nendmodule\n";
let tree = Tree::new("colon");
let (_tree, ws, uri, position) = opened(tree, top, "1: si");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"sig"), "the scope tier still answers: {found:?}");
}
#[test]
fn a_package_lists_its_members_after_a_scope_separator() {
let tree = Tree::new("pkg");
tree.write(
"p.sv",
"package other_pkg;\n localparam int WIDTH = 8;\n typedef struct packed { logic a; } cfg_t;\nendpackage\n",
);
let top = "module top;\n initial $display(other_pkg::);\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "other_pkg::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"WIDTH"), "{found:?}");
assert!(found.contains(&"cfg_t"), "{found:?}");
assert!(!found.contains(&"always_ff"), "and nothing else: {found:?}");
}
#[test]
fn a_package_this_file_declares_lists_its_members_too() {
let top = "package p;\n localparam int W = 8;\n typedef int t_t;\nendpackage\nmodule top;\n initial $display(p::);\nendmodule\n";
let tree = Tree::new("pkg_local");
let (_tree, ws, uri, position) = opened(tree, top, "p::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["W", "t_t"]);
}
/// The cross-file half: an in-file class extending a class in another
/// file lists both halves, its own scope first.
#[test]
fn a_base_in_another_file_contributes_its_members() {
let tree = Tree::new("crossfile");
tree.write("base.sv", "class remote_c;\n bit remote_field;\n bit shared;\nendclass\n");
let top = "class local_c extends remote_c;\n bit local_field;\n bit shared;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field", "shared", "remote_field"]);
// The subclass's `shared` is the one offered — the same first-hit-wins
// rule a lookup applies.
let items = items(completions(&ws, &uri, position, true));
let shared = find(&items, "shared").expect("the shadowed name");
assert_eq!(items.iter().filter(|i| i.label == "shared").count(), 1);
assert_eq!(shared.kind, Some(CompletionItemKind::VARIABLE));
}
/// A class whose base the workspace does not declare at all: the chain
/// stops there, and everything known still lists.
#[test]
fn an_absent_base_stops_the_chain_without_losing_what_is_known() {
let tree = Tree::new("nobase");
let top = "class local_c extends nowhere_c;\n bit local_field;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field"]);
}
/// The other half of the detail rule: a member the *index* holds carries
/// no text, so its card is the kind label plus the declared type — the
/// most a table can say, and no file is read to say it.
#[test]
fn a_cross_file_member_shows_the_kind_label_and_its_declared_type() {
let tree = Tree::new("xdetail");
tree.write(
"remote.sv",
"class remote_c;\n hdr_t typed_field;\n bit plain_field;\nendclass\n",
);
let top = "module top;\n remote_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let items = items(completions(&ws, &uri, position, true));
let typed = find(&items, "typed_field").expect("the typed property");
assert_eq!(typed.detail.as_deref(), Some("variable — hdr_t"));
let plain = find(&items, "plain_field").expect("the untyped property");
assert_eq!(plain.detail.as_deref(), Some("variable"), "no type name to add");
}
/// A type only another file declares: the whole list comes from the
/// index, inherited members included.
#[test]
fn a_handle_whose_type_is_another_files_lists_from_the_index() {
let tree = Tree::new("remote");
tree.write("base.sv", "class remote_base;\n bit inherited_field;\nendclass\n");
tree.write(
"item.sv",
"class remote_item extends remote_base;\n bit own_field;\nendclass\n",
);
let top = "module top;\n remote_item h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["inherited_field", "own_field"]);
}
/// `reg2hw.ctrl.` — the generated-register shape, whose inner fields the
/// index holds under the synthesized `reg2hw_t.ctrl` key.
#[test]
fn a_nested_struct_in_another_file_lists_through_the_synthesized_key() {
let tree = Tree::new("reg2hw");
tree.write(
"regs.sv",
"package regs_pkg;\n typedef struct packed {\n struct packed { logic q; logic qe; } ctrl;\n struct packed { logic q; } status;\n } reg2hw_t;\nendpackage\n",
);
let top = "module top;\n reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "reg2hw.ctrl.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["q", "qe"]);
}
// ------------------------------------------------------------------
// the connection list (2026-09-02 rework) — `.` inside `sub u (…)`
// ------------------------------------------------------------------
/// A module in the buffer, so the in-file half is exercised without the
/// index. Three ports and two parameters, in a shape a user really types.
const WIRING: &str = "\
module wiring_sub #(
parameter int WIDTH = 8,
parameter int DEPTH = 4
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
module wiring_top;
logic clk;
wiring_sub u_sub (
HOLE
);
endmodule
";
/// A connection-list request against [`WIRING`], `HOLE` replaced by what
/// is typed. Sorted, like every other member list here.
fn wiring_labels(name: &str, hole: &str) -> Vec<String> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
let mut found: Vec<String> = items(completions(&ws, &uri, position, true))
.iter()
.map(|item| item.label.clone())
.collect();
found.sort();
found
}
/// **The regression this rework exists for.** `.cl` inside `sub u (` used
/// to get the 512-item whole-index dump; it now gets the port.
#[test]
fn a_dot_in_a_connection_list_lists_the_modules_ports() {
assert_eq!(wiring_labels("conn", "."), vec!["clk", "data", "ready"]);
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() {
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
assert_eq!(
wiring_order("newline", ".clk(clk),\n ."),
expected,
"an indented continuation line is the ordinary way this is written",
);
}
/// 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_offered_last_and_marked() {
assert_eq!(
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 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]
fn a_parameter_override_lists_the_parameters_not_the_ports() {
let top = WIRING.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let tree = Tree::new("params");
let (_tree, ws, uri, position) = opened(tree, &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["DEPTH", "WIDTH"]);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// **QA finding 1, 2026-09-02.** The opentitan shape: `prim_fifo_sync`
/// derives its width with a header `localparam`, which is **not
/// overridable** — and until `vlog_semantic` learned
/// [`SymbolKind::LocalParam`] it was bound as a `Param` and offered here.
/// The keyword is sticky, so a continuation entry after `localparam` is
/// one too, and a body `localparam` is never a header entry at all.
#[test]
fn a_localparam_is_never_offered_as_an_override() {
let top = "\
module fifo #(
parameter int Depth = 4,
localparam int DepthW = 3,
DepthX = 4,
parameter int Again = 1
) (
input logic clk
);
localparam int Body = 7;
endmodule
module top;
fifo #(.) u_fifo ();
endmodule
";
let tree = Tree::new("localparam");
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(
found,
vec!["Again", "Depth"],
"only the two `parameter` entries may be overridden",
);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// The same, for a module the **index** answers for — the half QA
/// actually hit, since `prim_fifo_sync` is instantiated from another file.
#[test]
fn a_localparam_in_another_file_is_not_offered_either() {
let tree = Tree::new("xlocalparam");
tree.write(
"fifo.sv",
"module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3\n) (\n input logic clk\n);\nendmodule\n",
);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(labels(&answer), vec!["Depth"]);
// …and the localparam is still *there* to be read hierarchically —
// the split changes what may be offered, never what exists.
assert!(
ws.index().members_of_chain("fifo").iter().any(|(name, _)| *name == "DepthW"),
"a localparam is still exported",
);
}
/// The completion list and the **ghost instantiation** must agree about
/// what is overridable: two answers to "which parameters may be
/// overridden" would eventually offer a name the skeleton omits.
/// `vlog_refactor::instantiation_plan` reads the AST keyword and always
/// did; this pins the two against each other.
#[test]
fn the_override_list_and_the_instantiation_plan_agree() {
let fifo = "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3,\n parameter int Again = 1\n) (\n input logic clk\n);\nendmodule\n";
let tree = Tree::new("planagree");
tree.write("fifo.sv", fifo);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let mut offered = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|s| (*s).to_string())
.collect::<Vec<String>>();
offered.sort();
let plan = vlog_refactor::instantiation_plan("fifo", fifo, None).expect("a plan");
let mut planned: Vec<String> = plan.params.iter().map(|p| p.name.clone()).collect();
planned.sort();
assert_eq!(offered, planned, "the popup and the skeleton name one set");
}
#[test]
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));
// `.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,"));
// Exclusive, like every other member answer.
for item in &answer {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
}
}
#[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.
#[test]
fn a_non_ansi_port_list_is_completed_too() {
let top = "module non_ansi (a, b);\n input wire a;\n output wire b;\nendmodule\nmodule top;\n non_ansi u (\n .\n );\nendmodule\n";
let tree = Tree::new("nonansi");
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["a", "b"]);
}
/// A module declared in another file: the ports come out of the index's
/// member table, which exports exactly ports and parameters.
#[test]
fn a_module_in_another_file_lists_its_ports_from_the_index() {
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("xconn", top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "data", "ready"], "SUB's ports, not its parameter");
let clk = find(&answer, "clk").expect("a port");
assert_eq!(clk.kind, Some(CompletionItemKind::FIELD));
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
}
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
/// *expression* the list is the module's **hierarchical** surface — its
/// nets, its variables and its instances as well as its ports and its
/// parameters — because that is what a hierarchical path may name and
/// exactly what the tail resolution will find, so every item offered is
/// an item hover and go-to-definition answer. Behind the `.` of a
/// **connection list** it is the connection surface and nothing more:
/// `.internal(w)` is not a legal connection, and an item the resolution
/// could not find is a wrong answer rather than a generous one.
#[test]
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
let hierarchical = {
let tree = Tree::new("hiersurface_expr");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(
hierarchical,
vec!["clk", "counter", "internal", "u_leaf"],
"the port and the three hierarchical-only members"
);
let connection = {
let tree = Tree::new("hiersurface_conn");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
}
#[test]
fn an_interface_instance_lists_its_ports_too() {
let tree = Tree::new("ifaceconn");
tree.write("bus.sv", "interface bus_if (input logic clk, input logic rst_n);\n logic [7:0] internal;\nendinterface\n");
let top = "module top;\n bus_if u_bus (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "rst_n"], "an interface's ports, not its signals");
}
/// A module nothing declares has no ports to name. The answer is an
/// **empty list** — the same shape a resolved site with no matching
/// member gets, and for the same reason: the question was this one, and
/// the honest answer to it is nothing. Never the whole-index dump.
#[test]
fn a_module_the_workspace_does_not_declare_answers_nothing() {
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("unknownconn", top, " .");
assert!(items(completions(&ws, &uri, position, true)).is_empty());
}
/// …and a `.` that is in no instantiation list at all answers `None`,
/// which is the other half of the same split: not "nothing to offer here"
/// but "this was not a question I can read".
#[test]
fn a_dot_outside_any_instantiation_list_answers_none() {
let top = "module top;\n initial begin\n (.\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("looseconn", top, " (.");
assert!(completions(&ws, &uri, position, true).is_none());
}
/// A `.` inside a *connected expression* is not a connection: `.clk(`
/// opens a paren of its own, and what may be written there is an
/// expression.
#[test]
fn a_dot_inside_a_connected_expression_is_not_a_connection() {
let top = WIRING.replace(" HOLE\n", " .clk(no_such_head.\n");
let tree = Tree::new("nested");
let (_tree, ws, uri, position) = opened(tree, &top, "no_such_head.");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_typed_prefix_in_a_connection_list_follows_the_same_filter_rule() {
// One and two characters: a prefix.
assert_eq!(wiring_labels("cprefix", ".d"), vec!["data"]);
// Three: a subsequence, so `rdy` reaches `ready`.
assert_eq!(wiring_labels("cfuzzy", ".rdy"), vec!["ready"]);
let incomplete = |name: &str, hole: &str| {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
}
};
assert!(!incomplete("cinc0", "."), "the whole port list is the whole answer");
assert!(incomplete("cinc1", ".d"), "a prefix slice widens at the third character");
assert!(!incomplete("cinc3", ".rdy"));
}
/// Nothing about an ordinary identifier request changed.
#[test]
fn a_plain_identifier_still_gets_every_tier() {
let top = "module top;\n logic sig_here;\n assign x = sig\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, "= sig");
let items = items(completions(&ws, &uri, position, true));
let found = labels(&items);
assert!(found.contains(&"sig_here"), "the scope tier: {found:?}");
assert!(items.iter().any(|i| tier(i) == TIER_WORD || tier(i) == TIER_KEYWORD));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,820 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
// ------------------------------------------------------------------
// the member answer (2026-09-02) — after a `.` or a `::`
// ------------------------------------------------------------------
/// The buffer most of these ask against: a class chain, a struct, an
/// interface with a modport and a clocking block, and a handle for each.
const MEMBERS: &str = "\
interface bus_if;
logic clk;
logic [7:0] data;
modport mp (input clk);
clocking cb @(posedge clk);
input data;
endclocking
endinterface
typedef struct packed { logic [7:0] addr; logic vld; } hdr_t;
class base_c;
bit from_base;
endclass
class item_c extends base_c;
bit user_id;
bit feature1;
hdr_t hdr;
function void run();
endfunction
endclass
module top;
virtual bus_if vif;
item_c item;
item_c queue[4];
hdr_t [3:0] hs;
hdr_t h;
initial begin
item.
end
endmodule
";
/// The names a member request against [`MEMBERS`] offers, **sorted** —
/// which is the order the client shows them in, because `sortText` is
/// `<tier digit><name>`. The array order is the cap's order and is pinned
/// separately by [`the_list_is_ordered_nearest_declaration_first`].
fn member_labels(name: &str, spine: &str) -> Vec<String> {
let mut found: Vec<String> =
items(member_response(name, spine)).iter().map(|item| item.label.clone()).collect();
found.sort();
found
}
/// The whole response, for the tests that read more than the labels.
fn member_response(name: &str, spine: &str) -> Option<CompletionResponse> {
let top = MEMBERS.replace(" item.\n", &format!(" {spine}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, spine);
completions(&ws, &uri, position, true)
}
#[test]
fn a_class_handle_lists_its_members_and_its_bases() {
assert_eq!(
member_labels("cls", "item."),
vec!["feature1", "from_base", "hdr", "run", "user_id"],
);
}
#[test]
fn the_member_answer_is_exclusive() {
let items = items(member_response("exclusive", "item."));
// No keyword, no template, no project word — every item is a member,
// and every one of them is filed under the member tier.
for item in &items {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::KEYWORD), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::TEXT), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::SNIPPET), "{item:#?}");
}
let found = labels(&items);
assert!(!found.contains(&"always_ff"), "no keywords");
assert!(!found.contains(&"top"), "no index names");
assert!(!found.contains(&"vif"), "not even what is visible at the cursor");
}
/// A member wins over a same-named local because the answer is exclusive:
/// the local is not a worse candidate here, it is not a candidate.
#[test]
fn a_local_of_the_same_name_is_not_offered_beside_the_member() {
let top = MEMBERS.replace(" item.\n", " bit user_id;\n item.\n");
let tree = Tree::new("shadow");
let (_tree, ws, uri, position) = opened(tree, &top, "item.");
let items = items(completions(&ws, &uri, position, true));
let user_id = find(&items, "user_id").expect("the member");
assert_eq!(user_id.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(items.iter().filter(|item| item.label == "user_id").count(), 1);
}
#[test]
fn a_nested_struct_field_lists_the_inner_fields() {
assert_eq!(member_labels("struct", "h."), vec!["addr", "vld"]);
assert_eq!(member_labels("struct2", "item.hdr."), vec!["addr", "vld"]);
}
#[test]
fn an_interface_handle_lists_its_signals_its_modports_and_its_clocking() {
let found = member_labels("iface", "vif.");
for wanted in ["clk", "data", "mp", "cb"] {
assert!(found.contains(&wanted.to_string()), "{wanted} missing from {found:?}");
}
}
/// A clocking block's `type_name` is the interface enclosing it
/// (interface-semantics, 2026-09-01), which is what makes `vif.cb.data`
/// resolve to the interface's own `data` declaration — correct
/// SystemVerilog, since a clocking block names a *view* of those signals
/// and declares nothing of its own. So the list after `vif.cb.` is the
/// interface's, exactly as the resolution is: one walk, one answer, wider
/// than the block's own item list and never wrong about a name.
#[test]
fn a_clocking_block_lists_the_enclosing_interfaces_signals() {
assert_eq!(member_labels("clocking", "vif.cb."), member_labels("clocking2", "vif."));
assert!(member_labels("clocking3", "vif.cb.").contains(&"data".to_string()));
}
/// A **packed** array head is indexed away and names its element type's
/// members: `hdr_t [3:0] hs; hs[1].` is a `hdr_t`.
#[test]
fn a_packed_array_head_is_indexed_away() {
assert_eq!(member_labels("indexed", "hs[1]."), vec!["addr", "vld"]);
assert_eq!(member_labels("indexed2", "hs[i][j]."), vec!["addr", "vld"], "and repeatedly");
}
/// An **unpacked** declarator answers nothing, and that is
/// `vlog_semantic`'s own ruling rather than this file's: `item_c q[4]`
/// names a container, not a value of `item_c`, so no `type_name` is
/// recorded and `q.size()` is an array method rather than a member
/// (`bind.rs::declare_typed`). Completion may not mint a type the
/// resolver refuses to mint — that would be the second resolver this
/// round exists to avoid. Filed as a follow-on in the feature README.
#[test]
fn an_unpacked_array_head_answers_nothing_because_it_has_no_declared_type() {
assert!(member_response("unpacked", "queue[0].").is_none());
}
/// The order of the `items` array is the order the cap keeps, and it is
/// **nearest declaration first**: a class's own members before its base's,
/// in declaration order within each. `sortText` still says the client
/// should draw them alphabetically.
#[test]
fn the_list_is_ordered_nearest_declaration_first() {
let items = items(member_response("order", "item."));
assert_eq!(labels(&items), vec!["user_id", "feature1", "hdr", "run", "from_base"]);
for item in &items {
assert_eq!(item.sort_text.as_deref(), Some(format!("0{}", item.label).as_str()));
}
}
#[test]
fn this_and_super_answer_from_inside_a_method() {
let top = MEMBERS.replace(" function void run();\n", " function void run();\n this.\n");
let tree = Tree::new("this");
let (_tree, ws, uri, position) = opened(tree, &top, " this.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["feature1", "from_base", "hdr", "run", "user_id"]);
let top = MEMBERS.replace(" function void run();\n", " function void run();\n super.\n");
let tree = Tree::new("super");
let (_tree, ws, uri, position) = opened(tree, &top, " super.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["from_base"], "super is the base and not the class itself");
}
#[test]
fn the_kind_and_the_detail_come_off_the_declaration() {
let items = items(member_response("detail", "item."));
// In this buffer the declaration's own line is free, so that is the
// card — the same one tier 1 has always shown.
let hdr = find(&items, "hdr").expect("the struct-typed property");
assert_eq!(hdr.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(hdr.detail.as_deref(), Some("hdr_t hdr;"), "the declaration itself");
let run = find(&items, "run").expect("the method");
assert_eq!(run.kind, Some(CompletionItemKind::FUNCTION));
assert_eq!(run.detail.as_deref(), Some("function void run();"));
// A method inserts its bare name: the parentheses and the arguments
// are the user's to write, and a completion that invented them would
// be guessing at the call.
assert_eq!(inserted(run), "run");
assert_eq!(run.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
/// The edit is an **empty** range at the cursor, so accepting an item
/// writes the member name after the dot and touches nothing before it.
#[test]
fn the_edit_is_empty_at_the_cursor_after_a_separator() {
let items = items(member_response("range", "item."));
assert!(!items.is_empty());
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, edit.range.end, "{item:#?}");
assert_eq!(edit.new_text, item.label);
}
}
/// And with characters typed after the dot it replaces exactly those.
#[test]
fn the_edit_replaces_exactly_what_was_typed_after_the_separator() {
let items = items(member_response("range2", "item.us"));
assert_eq!(labels(&items), vec!["user_id"]);
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start.character + 2, edit.range.end.character);
}
#[test]
fn a_typed_prefix_filters_below_the_fuzzy_floor_and_a_subsequence_from_it_up() {
// One and two characters: a prefix, exactly as every other tier does
// below the floor. `fe` reaches `feature1` and not `from_base`.
assert_eq!(member_labels("prefix1", "item.f"), vec!["feature1", "from_base"]);
assert_eq!(member_labels("prefix2", "item.fe"), vec!["feature1"]);
// Three: a subsequence, so `fbs` reaches `from_base` — which no
// prefix match ever would.
assert_eq!(member_labels("fuzzy", "item.fbs"), vec!["from_base"]);
assert_eq!(member_labels("fuzzy2", "item.usr"), vec!["user_id"]);
}
/// **The `isIncomplete` rule.** The request that matters — the one the
/// trigger character fires, with nothing typed yet — is complete, so VS
/// Code filters the whole member list client-side. A 1- or 2-character
/// answer is a prefix slice that the third keystroke would *widen*, so it
/// must say it is incomplete or the widening never reaches the client.
#[test]
fn only_a_filtered_answer_below_the_fuzzy_floor_is_incomplete() {
let incomplete = |name: &str, spine: &str| match member_response(name, spine) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
};
assert!(!incomplete("inc0", "item."), "the whole list is the whole answer");
assert!(incomplete("inc1", "item.f"), "a prefix slice widens at the third character");
assert!(incomplete("inc2", "item.fe"));
assert!(!incomplete("inc3", "item.fea"), "a subsequence hit set only shrinks");
// Even a query nothing matches answers with a list, so the client is
// told to come back rather than left filtering an answer it has not
// got.
assert!(incomplete("inc4", "item.zz"));
let empty = items(member_response("inc5", "item.zz"));
assert!(empty.is_empty());
}
/// An **empty** answer is incomplete whatever was typed — including at
/// zero characters, where a non-empty list would be complete. QA finding
/// 2 (2026-09-02) is the reason: a cold index whose scope ladder has not
/// reached the declaring file's directory yet answers empty for one
/// request and correctly for the next, and a *complete* emptiness would
/// be cached by the client until the user retyped the dot.
#[test]
fn an_empty_answer_always_asks_the_client_to_come_back() {
let top = "class hollow_c;\nendclass\nmodule top;\n hollow_c h;\n initial begin\n h.\n end\nendmodule\n";
let tree = Tree::new("hollow");
let (_tree, ws, uri, position) = opened(tree, top, " h.");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty(), "a class with no members");
assert!(list.is_incomplete, "and the client is asked to come back");
}
other => panic!("a list, not {other:#?}"),
}
// The same for a connection list whose module nothing declares.
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("hollowconn", top, " .");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty());
assert!(list.is_incomplete);
}
other => panic!("a list, not {other:#?}"),
}
}
#[test]
fn an_unresolvable_head_answers_nothing_at_all() {
for (name, spine) in [
("nohead", "no_such_handle."),
("call", "f()."),
("nothing", "."),
("space", "item ."),
("untyped", "vif.clk."),
] {
assert!(member_response(name, spine).is_none(), "{spine} must answer nothing, not a guess",);
}
}
/// A lone `:` is a case item, a label or a ternary — not a separator. The
/// request there is the ordinary six-tier one it always was.
#[test]
fn a_lone_colon_falls_through_to_the_ordinary_tiers() {
let top =
"module top;\n logic sig;\n initial\n case (1)\n 1: si\n endcase\nendmodule\n";
let tree = Tree::new("colon");
let (_tree, ws, uri, position) = opened(tree, top, "1: si");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"sig"), "the scope tier still answers: {found:?}");
}
#[test]
fn a_package_lists_its_members_after_a_scope_separator() {
let tree = Tree::new("pkg");
tree.write(
"p.sv",
"package other_pkg;\n localparam int WIDTH = 8;\n typedef struct packed { logic a; } cfg_t;\nendpackage\n",
);
let top = "module top;\n initial $display(other_pkg::);\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "other_pkg::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"WIDTH"), "{found:?}");
assert!(found.contains(&"cfg_t"), "{found:?}");
assert!(!found.contains(&"always_ff"), "and nothing else: {found:?}");
}
#[test]
fn a_package_this_file_declares_lists_its_members_too() {
let top = "package p;\n localparam int W = 8;\n typedef int t_t;\nendpackage\nmodule top;\n initial $display(p::);\nendmodule\n";
let tree = Tree::new("pkg_local");
let (_tree, ws, uri, position) = opened(tree, top, "p::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["W", "t_t"]);
}
/// The cross-file half: an in-file class extending a class in another
/// file lists both halves, its own scope first.
#[test]
fn a_base_in_another_file_contributes_its_members() {
let tree = Tree::new("crossfile");
tree.write("base.sv", "class remote_c;\n bit remote_field;\n bit shared;\nendclass\n");
let top = "class local_c extends remote_c;\n bit local_field;\n bit shared;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field", "shared", "remote_field"]);
// The subclass's `shared` is the one offered — the same first-hit-wins
// rule a lookup applies.
let items = items(completions(&ws, &uri, position, true));
let shared = find(&items, "shared").expect("the shadowed name");
assert_eq!(items.iter().filter(|i| i.label == "shared").count(), 1);
assert_eq!(shared.kind, Some(CompletionItemKind::VARIABLE));
}
/// A class whose base the workspace does not declare at all: the chain
/// stops there, and everything known still lists.
#[test]
fn an_absent_base_stops_the_chain_without_losing_what_is_known() {
let tree = Tree::new("nobase");
let top = "class local_c extends nowhere_c;\n bit local_field;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field"]);
}
/// The other half of the detail rule: a member the *index* holds carries
/// no text, so its card is the kind label plus the declared type — the
/// most a table can say, and no file is read to say it.
#[test]
fn a_cross_file_member_shows_the_kind_label_and_its_declared_type() {
let tree = Tree::new("xdetail");
tree.write(
"remote.sv",
"class remote_c;\n hdr_t typed_field;\n bit plain_field;\nendclass\n",
);
let top = "module top;\n remote_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let items = items(completions(&ws, &uri, position, true));
let typed = find(&items, "typed_field").expect("the typed property");
assert_eq!(typed.detail.as_deref(), Some("variable — hdr_t"));
let plain = find(&items, "plain_field").expect("the untyped property");
assert_eq!(plain.detail.as_deref(), Some("variable"), "no type name to add");
}
/// A type only another file declares: the whole list comes from the
/// index, inherited members included.
#[test]
fn a_handle_whose_type_is_another_files_lists_from_the_index() {
let tree = Tree::new("remote");
tree.write("base.sv", "class remote_base;\n bit inherited_field;\nendclass\n");
tree.write("item.sv", "class remote_item extends remote_base;\n bit own_field;\nendclass\n");
let top = "module top;\n remote_item h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["inherited_field", "own_field"]);
}
/// `reg2hw.ctrl.` — the generated-register shape, whose inner fields the
/// index holds under the synthesized `reg2hw_t.ctrl` key.
#[test]
fn a_nested_struct_in_another_file_lists_through_the_synthesized_key() {
let tree = Tree::new("reg2hw");
tree.write(
"regs.sv",
"package regs_pkg;\n typedef struct packed {\n struct packed { logic q; logic qe; } ctrl;\n struct packed { logic q; } status;\n } reg2hw_t;\nendpackage\n",
);
let top =
"module top;\n reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "reg2hw.ctrl.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["q", "qe"]);
}
// ------------------------------------------------------------------
// the connection list (2026-09-02 rework) — `.` inside `sub u (…)`
// ------------------------------------------------------------------
/// A module in the buffer, so the in-file half is exercised without the
/// index. Three ports and two parameters, in a shape a user really types.
const WIRING: &str = "\
module wiring_sub #(
parameter int WIDTH = 8,
parameter int DEPTH = 4
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
module wiring_top;
logic clk;
wiring_sub u_sub (
HOLE
);
endmodule
";
/// A connection-list request against [`WIRING`], `HOLE` replaced by what
/// is typed. Sorted, like every other member list here.
fn wiring_labels(name: &str, hole: &str) -> Vec<String> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
let mut found: Vec<String> = items(completions(&ws, &uri, position, true))
.iter()
.map(|item| item.label.clone())
.collect();
found.sort();
found
}
/// **The regression this rework exists for.** `.cl` inside `sub u (` used
/// to get the 512-item whole-index dump; it now gets the port.
#[test]
fn a_dot_in_a_connection_list_lists_the_modules_ports() {
assert_eq!(wiring_labels("conn", "."), vec!["clk", "data", "ready"]);
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() {
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
assert_eq!(
wiring_order("newline", ".clk(clk),\n ."),
expected,
"an indented continuation line is the ordinary way this is written",
);
}
/// 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_offered_last_and_marked() {
assert_eq!(
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 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]
fn a_parameter_override_lists_the_parameters_not_the_ports() {
let top = WIRING.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let tree = Tree::new("params");
let (_tree, ws, uri, position) = opened(tree, &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["DEPTH", "WIDTH"]);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// **QA finding 1, 2026-09-02.** The opentitan shape: `prim_fifo_sync`
/// derives its width with a header `localparam`, which is **not
/// overridable** — and until `vlog_semantic` learned
/// [`SymbolKind::LocalParam`] it was bound as a `Param` and offered here.
/// The keyword is sticky, so a continuation entry after `localparam` is
/// one too, and a body `localparam` is never a header entry at all.
#[test]
fn a_localparam_is_never_offered_as_an_override() {
let top = "\
module fifo #(
parameter int Depth = 4,
localparam int DepthW = 3,
DepthX = 4,
parameter int Again = 1
) (
input logic clk
);
localparam int Body = 7;
endmodule
module top;
fifo #(.) u_fifo ();
endmodule
";
let tree = Tree::new("localparam");
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["Again", "Depth"], "only the two `parameter` entries may be overridden",);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// The same, for a module the **index** answers for — the half QA
/// actually hit, since `prim_fifo_sync` is instantiated from another file.
#[test]
fn a_localparam_in_another_file_is_not_offered_either() {
let tree = Tree::new("xlocalparam");
tree.write(
"fifo.sv",
"module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3\n) (\n input logic clk\n);\nendmodule\n",
);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(labels(&answer), vec!["Depth"]);
// …and the localparam is still *there* to be read hierarchically —
// the split changes what may be offered, never what exists.
assert!(
ws.index().members_of_chain("fifo").iter().any(|(name, _)| *name == "DepthW"),
"a localparam is still exported",
);
}
/// The completion list and the **ghost instantiation** must agree about
/// what is overridable: two answers to "which parameters may be
/// overridden" would eventually offer a name the skeleton omits.
/// `vlog_refactor::instantiation_plan` reads the AST keyword and always
/// did; this pins the two against each other.
#[test]
fn the_override_list_and_the_instantiation_plan_agree() {
let fifo = "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3,\n parameter int Again = 1\n) (\n input logic clk\n);\nendmodule\n";
let tree = Tree::new("planagree");
tree.write("fifo.sv", fifo);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let mut offered = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|s| (*s).to_string())
.collect::<Vec<String>>();
offered.sort();
let plan = vlog_refactor::instantiation_plan("fifo", fifo, None).expect("a plan");
let mut planned: Vec<String> = plan.params.iter().map(|p| p.name.clone()).collect();
planned.sort();
assert_eq!(offered, planned, "the popup and the skeleton name one set");
}
#[test]
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));
// `.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,"));
// Exclusive, like every other member answer.
for item in &answer {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
}
}
#[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.
#[test]
fn a_non_ansi_port_list_is_completed_too() {
let top = "module non_ansi (a, b);\n input wire a;\n output wire b;\nendmodule\nmodule top;\n non_ansi u (\n .\n );\nendmodule\n";
let tree = Tree::new("nonansi");
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["a", "b"]);
}
/// A module declared in another file: the ports come out of the index's
/// member table, which exports exactly ports and parameters.
#[test]
fn a_module_in_another_file_lists_its_ports_from_the_index() {
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("xconn", top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "data", "ready"], "SUB's ports, not its parameter");
let clk = find(&answer, "clk").expect("a port");
assert_eq!(clk.kind, Some(CompletionItemKind::FIELD));
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
}
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
/// *expression* the list is the module's **hierarchical** surface — its
/// nets, its variables and its instances as well as its ports and its
/// parameters — because that is what a hierarchical path may name and
/// exactly what the tail resolution will find, so every item offered is
/// an item hover and go-to-definition answer. Behind the `.` of a
/// **connection list** it is the connection surface and nothing more:
/// `.internal(w)` is not a legal connection, and an item the resolution
/// could not find is a wrong answer rather than a generous one.
#[test]
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
let hierarchical = {
let tree = Tree::new("hiersurface_expr");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(
hierarchical,
vec!["clk", "counter", "internal", "u_leaf"],
"the port and the three hierarchical-only members"
);
let connection = {
let tree = Tree::new("hiersurface_conn");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
}
#[test]
fn an_interface_instance_lists_its_ports_too() {
let tree = Tree::new("ifaceconn");
tree.write("bus.sv", "interface bus_if (input logic clk, input logic rst_n);\n logic [7:0] internal;\nendinterface\n");
let top = "module top;\n bus_if u_bus (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "rst_n"], "an interface's ports, not its signals");
}
/// A module nothing declares has no ports to name. The answer is an
/// **empty list** — the same shape a resolved site with no matching
/// member gets, and for the same reason: the question was this one, and
/// the honest answer to it is nothing. Never the whole-index dump.
#[test]
fn a_module_the_workspace_does_not_declare_answers_nothing() {
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("unknownconn", top, " .");
assert!(items(completions(&ws, &uri, position, true)).is_empty());
}
/// …and a `.` that is in no instantiation list at all answers `None`,
/// which is the other half of the same split: not "nothing to offer here"
/// but "this was not a question I can read".
#[test]
fn a_dot_outside_any_instantiation_list_answers_none() {
let top = "module top;\n initial begin\n (.\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("looseconn", top, " (.");
assert!(completions(&ws, &uri, position, true).is_none());
}
/// A `.` inside a *connected expression* is not a connection: `.clk(`
/// opens a paren of its own, and what may be written there is an
/// expression.
#[test]
fn a_dot_inside_a_connected_expression_is_not_a_connection() {
let top = WIRING.replace(" HOLE\n", " .clk(no_such_head.\n");
let tree = Tree::new("nested");
let (_tree, ws, uri, position) = opened(tree, &top, "no_such_head.");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_typed_prefix_in_a_connection_list_follows_the_same_filter_rule() {
// One and two characters: a prefix.
assert_eq!(wiring_labels("cprefix", ".d"), vec!["data"]);
// Three: a subsequence, so `rdy` reaches `ready`.
assert_eq!(wiring_labels("cfuzzy", ".rdy"), vec!["ready"]);
let incomplete = |name: &str, hole: &str| {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
}
};
assert!(!incomplete("cinc0", "."), "the whole port list is the whole answer");
assert!(incomplete("cinc1", ".d"), "a prefix slice widens at the third character");
assert!(!incomplete("cinc3", ".rdy"));
}
/// Nothing about an ordinary identifier request changed.
#[test]
fn a_plain_identifier_still_gets_every_tier() {
let top = "module top;\n logic sig_here;\n assign x = sig\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, "= sig");
let items = items(completions(&ws, &uri, position, true));
let found = labels(&items);
assert!(found.contains(&"sig_here"), "the scope tier: {found:?}");
assert!(items.iter().any(|i| tier(i) == TIER_WORD || tier(i) == TIER_KEYWORD));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+33 -6
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `textDocument/completion` — module hinting, templates, keywords, and every
//! name the project uses.
//!
@@ -79,6 +81,7 @@ use buffer::{buffer_word_tier, declared_tier};
use connection::Connection;
use member::member_answer;
use module::module_tier;
use related::{related_macros, related_tier};
use site::{at_module_item, at_statement, enclosing_scopes};
use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier};
use word::typed_word;
@@ -90,6 +93,7 @@ pub(crate) use module::{nearest_definition, plan_for};
pub(crate) use module::module_header;
pub(crate) use site::at_instantiation_site;
pub(crate) use tiers::layout_at;
pub(crate) use wire::{item_defaults_support, with_item_defaults};
mod buffer;
mod connection;
@@ -97,8 +101,10 @@ mod connection;
mod harness;
mod member;
mod module;
mod related;
mod site;
mod tiers;
mod wire;
mod word;
/// How many items one response carries, over every tier.
@@ -151,10 +157,14 @@ const TIER_SCOPE: char = '1';
/// (`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 the file is related to — the packages it imports, the classes its
/// class extends, the headers it includes — below the file itself and above
/// the rest of the workspace (`related.rs`).
const TIER_RELATED: char = '4';
const TIER_INDEX: char = '5';
const TIER_TEMPLATE: char = '6';
const TIER_KEYWORD: char = '7';
const TIER_WORD: char = '8';
/// What a multi-line item tells the client about its own whitespace.
///
@@ -205,6 +215,7 @@ pub fn completions(
// The backtick itself is replaced, so the item may carry its own.
let replacing = TextRange::new(word.start.saturating_sub(1), offset);
let mut items = Items::new(doc, replacing);
related_macros(&mut items, ws, doc, &word.text);
for entry in ws.candidates().macros(&word.text) {
items.simple(
&format!("`{}", entry.name),
@@ -243,6 +254,7 @@ pub fn completions(
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());
related_tier(&mut items, ws, 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);
@@ -273,6 +285,10 @@ struct Items {
items: Vec<CompletionItem>,
seen: HashSet<String>,
incomplete: bool,
/// How many of `items` the related tier added — which [`LIMIT`] does not
/// count, so every other tier fills exactly as far as it would without
/// them (`related.rs`).
related: usize,
}
impl Items {
@@ -282,6 +298,7 @@ impl Items {
items: Vec::new(),
seen: HashSet::new(),
incomplete: false,
related: 0,
}
}
@@ -289,7 +306,7 @@ impl Items {
/// only sets [`Items::incomplete`] — which is why the tiers ask first
/// rather than building items nobody will see.
fn full(&mut self) -> bool {
if self.items.len() >= LIMIT {
if self.items.len() - self.related >= LIMIT {
self.incomplete = true;
return true;
}
@@ -310,6 +327,14 @@ impl Items {
if self.full() || self.seen.contains(name) {
return;
}
self.unlimited(name, kind, tier, detail);
}
/// [`Items::simple`] past the cap: the caller has its own.
fn unlimited(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
if !self.seen.insert(name.to_string()) {
return;
}
let item = CompletionItem {
label: name.to_string(),
kind: Some(kind),
@@ -322,7 +347,7 @@ impl Items {
})),
..Default::default()
};
self.push(item);
self.items.push(item);
}
/// A port or parameter after a connection list's `.`: the bare name, or
@@ -894,3 +919,5 @@ mod tests {
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4 -586
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Tier 0 — module names at module-item position — and the instantiation
//! planning that `inline.rs`'s ghost and `instantiate.rs`'s command share.
//!
@@ -334,590 +336,6 @@ fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use std::fs;
use std::path::PathBuf;
mod tests;
/// Completion's own view of the three new kinds, and the detail card that
/// used to hard-code "module" over an interface — the C2 wrong answer
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn an_interface_completes_as_an_interface() {
assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT);
let index = vlog_semantic::WorkspaceIndex::build([
(PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"),
(PathBuf::from("/rtl/sub.sv"), SUB),
]);
assert!(module_detail(&index, "bus_if", None).starts_with("interface"));
assert!(module_detail(&index, "sub", None).starts_with("module"));
// The ghost-instantiation lookups reach an interface too.
assert_eq!(
nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()),
Some("/rtl/bus_if.sv".to_string())
);
}
// ------------------------------------------------------------------
// tier 0's header slice (2026-08-28) — it must change no answer
// ------------------------------------------------------------------
/// Every header shape the slice has to survive, as (file text, module).
///
/// The list is the argument that the slice changes nothing: each entry is
/// planned both ways below and the two plans are compared field by field.
const SHAPES: &[(&str, &str)] = &[
// The ordinary ANSI header, params and all.
(SUB, "sub"),
// No ports at all.
("module bare;\nendmodule\n", "bare"),
// An empty port list.
("module empty ();\n logic x;\nendmodule\n", "empty"),
// A package import written into the header: its `;` is not the
// header's, and a slice that stopped there would report no ports.
(
"package p;\n localparam int W = 4;\nendpackage\n\
module imported import p::*; #(\n parameter int W = 8\n) (\n \
input logic clk,\n output logic [W-1:0] q\n);\n \
assign q = '0;\nendmodule\n",
"imported",
),
// Two imports, then a parameter list.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
"twice",
),
// A **non-ANSI** port list: the directions live in the body, which is
// exactly what the slice drops.
(
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
always @* b = |a;\nendmodule\n",
"old",
),
// Non-ANSI with nothing declaring the ports at all.
("module silent (a, b);\nendmodule\n", "silent"),
// A comment and an attribute inside the header.
(
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
input logic clk\n);\nendmodule\n",
"noisy",
),
// A lifetime qualifier.
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
// A second module in the same file, after the one being planned.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"first",
),
// …and before it, so the slice's prefix carries a whole module.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"second",
),
// A compiler directive between the name and the port list, which the
// whitelist refuses outright.
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
// A directive *inside* the port list, which carries a warning the two
// plans must both raise.
(
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
`endif\n);\nendmodule\n",
"ifdefd",
),
// An escaped identifier for the module and for a port.
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
// A header longer than the first rung of the window ladder.
(WIDE, "wide"),
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
// instance, `(* ... *)`, right after the module name and before the
// parameter list — the one shape the "noisy" case above is commented
// as covering but does not (it has two comments, no attribute).
// **Finding, not a regression this round introduced**: a module with
// an attribute anywhere near its header is not indexed as a `Module`
// unit at all (see
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
// so this pins the safe side effect — `module_header` declines before
// its whitelist walk ever runs — rather than the whitelist's own
// handling of attributes, which this shape cannot reach.
(
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
input logic clk\n);\nendmodule\n",
"attributed",
),
// An attribute instance *inside* the port list, attached to one port.
// Same finding as `attributed`: not indexed, so not reached either.
(
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
);\nendmodule\n",
"port_attributed",
),
// A single import declaration naming several packages, comma
// separated (`import a::*, b::*;`) — one statement, not two, and the
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module chained import p::*, q::*; (input logic a);\nendmodule\n",
"chained",
),
// A parameter default whose string literal carries the exact bytes
// the whitelist watches for — `;` and `)` — which must stay inside
// the `String` token and never be mistaken for header punctuation.
(
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
input logic clk\n);\nendmodule\n",
"stringy",
),
// CRLF line endings through the whole header.
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
];
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
input logic port_number_one_with_a_long_name,\n \
input logic port_number_two_with_a_long_name,\n \
input logic port_number_three_with_a_long_name,\n \
input logic port_number_four_with_a_long_name,\n \
input logic port_number_five_with_a_long_name,\n \
output logic port_number_six_with_a_long_name\n);\n \
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
/// The whole argument for the slice: for every shape above, the plan built
/// from the header alone is the plan built from the whole file. Where it
/// would not be — a non-ANSI list, a header the whitelist refuses — the
/// guard in [`plan_for`] sends the question back to the whole file, so the
/// comparison holds there too.
#[test]
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
for (text, module) in SHAPES {
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
let ours = plan_for(&index, module, text, site);
assert_eq!(ours, whole, "{module}");
}
}
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
/// trivially for a shape the whitelist declines — both sides parse the
/// whole file, so a wrong slice could hide behind that. These shapes must
/// actually slice, so the comparison exercises the whitelist walk it is
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
/// `;`/`)` sitting inside a string literal, and CRLF endings.
#[test]
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
module_header(&index, module, text).is_some(),
"{module}: expected the header to actually slice, not fall back whole-file"
);
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
/// differently off its header, and really is sent back to the whole file.
#[test]
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
let path = PathBuf::from("/rtl/old.sv");
let index = WorkspaceIndex::build(vec![(path, text)]);
let header = module_header(&index, "old", text).expect("the header slices");
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
assert!(
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
"premise: the header alone knows nothing about these ports"
);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let guarded = plan_for(&index, "old", text, site).expect("a plan");
assert_eq!(guarded.ports[0].dir, "input");
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
}
/// The whole answer, pinned at the prefixes the hot path is worst at — the
/// empty one and a one-character one, where every tier is at its widest.
/// Tier 0 answers with names, so the pin spells out every module item's
/// label *and* the text it inserts, which is now the label again.
#[test]
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
let tree = Tree::new("pinned");
tree.write("sub.sv", SUB);
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
let (_tree, mut ws, uri, _) =
opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
// Nothing typed, then one character — the two widest requests there
// are. `top` is in the answer because the buffer declares it and the
// index holds it like any other module.
let mut answer = |typed: &str| {
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
+ typed.len() as u32;
let doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
items(completions(&ws, &uri, position, true))
};
for (typed, expected) in
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
{
let items = answer(typed);
let found: Vec<&str> =
skeletons(&items).iter().map(|item| item.label.as_str()).collect();
assert_eq!(found, expected, "module items after typing {typed:?}");
}
// …and the exact text each of them inserts, which is the name and
// nothing else however many ports the module has. The instantiation is
// `inline.rs`'s business now.
let items = answer("");
for name in ["sub", "alpha", "submarine"] {
let item = find(&items, name).expect("the module item");
assert_eq!(inserted(item), name, "the popup inserts the name alone");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(item.insert_text_mode, None, "there is no indentation to keep");
}
}
/// A file edited on disk since the index last read it has moved every span
/// the index holds, so the slice must not take one on trust.
#[test]
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
let text =
"module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
// The same index against a file whose text has shifted underneath it.
let moved = format!("// a line nobody told the index about\n{text}");
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
}
// ------------------------------------------------------------------
// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30)
// ------------------------------------------------------------------
#[test]
fn a_module_name_at_item_position_completes_to_the_name_alone() {
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("nameonly", top, " su");
let items = items(completions(&ws, &uri, position, true));
let modules = skeletons(&items);
assert_eq!(modules.len(), 1, "{items:#?}");
let item = modules[0];
assert_eq!(item.label, "sub");
assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon");
assert_eq!(item.detail.as_deref(), Some("module — sub.sv"));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest");
assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show");
}
#[test]
fn the_snippet_flag_no_longer_changes_the_module_item() {
// The M4 fallback — a plain-text spelling of the skeleton for a client
// that never advertised `snippetSupport` — has nothing left to fall
// back from: the item is a word either way.
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, " su");
for snippets in [true, false] {
let items = items(completions(&ws, &uri, position, snippets));
let item = skeletons(&items)[0];
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "snippets: {snippets}");
}
}
/// The whole point of level 1: the popup no longer reads the files it
/// offers names from. Proved by deleting the declaring file after the
/// index has been built — the old tier answered nothing at all here,
/// because every item needed that file's text.
#[test]
fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() {
let tree = Tree::new("noread");
let sub = tree.write("sub.sv", SUB);
let (_tree, ws, uri, position) =
opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su");
fs::remove_file(&sub).expect("remove the declaring file");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(
skeletons(&items).iter().map(|item| item.label.as_str()).collect::<Vec<_>>(),
["sub"],
"the name comes from the index's table, not from the file: {items:#?}"
);
}
#[test]
fn the_edit_replaces_exactly_the_typed_word() {
let top = "module top;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("replace", top, " su");
let items = items(completions(&ws, &uri, position, true));
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}");
assert_eq!(edit.range.end, Position { line: 1, character: 4 });
}
}
#[test]
fn no_skeleton_is_offered_in_the_middle_of_an_expression() {
// The other tiers answer here — a name is a name wherever it is
// written — but a fifteen-line instantiation is not.
for (name, top, needle) in [
("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"),
("decl", "module top;\n logic su\nendmodule\n", "logic su"),
("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"),
("header", "module top (su\n);\nendmodule\n", "top (su"),
] {
let (_tree, ws, uri, position) = asking(name, top, needle);
let items = items(completions(&ws, &uri, position, true));
assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}");
}
}
#[test]
fn no_skeleton_is_offered_inside_a_procedural_block() {
let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("always", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "module top;\n initial begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("initial", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn no_skeleton_is_offered_inside_a_function_or_a_class() {
let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n";
let (_tree, ws, uri, position) = asking("function", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "package p;\n class c;\n su\n endclass\nendpackage\n";
let (_tree, ws, uri, position) = asking("class", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_generate_block_is_still_item_position() {
let top = "\
module top;
for (genvar i = 0; i < 4; i++) begin : g
su
end
endmodule
";
let (_tree, ws, uri, position) = asking("genfor", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}");
let top = "module top;\n generate\n su\n endgenerate\nendmodule\n";
let (_tree, ws, uri, position) = asking("generate", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1);
}
#[test]
fn no_skeleton_is_offered_outside_a_design_unit() {
let top = "su\nmodule top;\nendmodule\n";
let (_tree, ws, uri, position) = asking("toplevel", top, "su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_prefix_that_matches_no_module_offers_no_skeleton() {
let top = "module top;\n zzz\nendmodule\n";
let (_tree, ws, uri, position) = asking("nomatch", top, " zzz");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() {
// Until 2026-08-30 tier 0 skipped it: there is no single definition to
// build a *skeleton* from, and the skeleton was the item. A name needs
// no definition, so round 1 offered the name and left the detail
// blank. Round 2 (owner ruling, same day) makes the ghost choose a
// copy rather than decline, so the popup names the copy the ghost will
// read — `nearest_definition`'s answer, which for a buffer at the tree
// root is the lexicographically smaller path.
let tree = Tree::new("dup");
tree.write("a.sv", "module dup ();\nendmodule\n");
tree.write("b.sv", "module dup ();\nendmodule\n");
let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "dup").expect("the name is still known");
assert_eq!(tier(item), TIER_MODULE, "{items:#?}");
assert_eq!(item.detail.as_deref(), Some("module — a.sv"));
}
/// The nearest-definition chooser, at the level `inline.rs` consumes it.
///
/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling`
/// share `hw` and nothing more, and a byte-wise prefix would count the
/// `hw/top_` they spell alike and rank the copies by a coincidence.
#[test]
fn the_nearest_definition_is_the_one_sharing_the_most_path_components() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let index =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let asking = |from: &str| {
nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from)))
.expect("a definition")
.to_path_buf()
};
assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey);
assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling);
// Near neither, and no path at all: the tie falls to the smaller path
// rather than to whatever the index happens to hold first.
assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling);
assert_eq!(
nearest_definition(&index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
/// QA round-2 finding, fixed at lead review: a copy in the asking
/// buffer's own directory and one in a subdirectory of it share the same
/// number of leading components with the buffer (its filename never
/// matches a directory), and the lexicographic tie-break alone could pick
/// the deeper, less related copy. The real shape is opentitan's 61-way
/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv`
/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`.
#[test]
fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() {
let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv");
let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv");
let text = "module tb ();\nendmodule\n";
for sources in [
vec![(sibling.clone(), text), (deeper.clone(), text)],
vec![(deeper.clone(), text), (sibling.clone(), text)],
] {
let index = WorkspaceIndex::build(sources);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
sibling.as_path(),
"the shallower copy is the nearer one"
);
}
// …and depth only breaks a tie: a deeper copy that genuinely shares
// more of the asking path still wins.
let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
deeper.as_path(),
"sharing more components outranks being shallow"
);
}
/// The answer is a property of the paths, not of the order the index was
/// built in — which is what makes it the same answer twice in a row, and
/// the same answer in two editors.
#[test]
fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let forwards =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let backwards =
WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]);
for index in [&forwards, &backwards] {
let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv");
assert_eq!(
nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"),
earlgrey.as_path()
);
assert_eq!(
nearest_definition(index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
}
/// A module only one file declares goes through the same chooser and comes
/// back with the file `vlog_refactor::module_definition` picks — the
/// equivalence that says round 2 widened the twice-declared case and moved
/// nothing else.
#[test]
fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() {
let path = PathBuf::from("/rtl/sub.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]);
let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition");
assert_eq!(expected, path.as_path());
for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] {
assert_eq!(
nearest_definition(&index, "sub", from.as_deref()).expect("a definition"),
expected,
"{from:?}"
);
}
// And a name nothing declares is `None` here where it is an `Err`
// there — the same "no answer", spelled the way each caller reads it.
assert!(nearest_definition(&index, "nope", None).is_none());
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,585 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use std::fs;
use std::path::PathBuf;
/// Completion's own view of the three new kinds, and the detail card that
/// used to hard-code "module" over an interface — the C2 wrong answer
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn an_interface_completes_as_an_interface() {
assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT);
let index = vlog_semantic::WorkspaceIndex::build([
(PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"),
(PathBuf::from("/rtl/sub.sv"), SUB),
]);
assert!(module_detail(&index, "bus_if", None).starts_with("interface"));
assert!(module_detail(&index, "sub", None).starts_with("module"));
// The ghost-instantiation lookups reach an interface too.
assert_eq!(
nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()),
Some("/rtl/bus_if.sv".to_string())
);
}
// ------------------------------------------------------------------
// tier 0's header slice (2026-08-28) — it must change no answer
// ------------------------------------------------------------------
/// Every header shape the slice has to survive, as (file text, module).
///
/// The list is the argument that the slice changes nothing: each entry is
/// planned both ways below and the two plans are compared field by field.
const SHAPES: &[(&str, &str)] = &[
// The ordinary ANSI header, params and all.
(SUB, "sub"),
// No ports at all.
("module bare;\nendmodule\n", "bare"),
// An empty port list.
("module empty ();\n logic x;\nendmodule\n", "empty"),
// A package import written into the header: its `;` is not the
// header's, and a slice that stopped there would report no ports.
(
"package p;\n localparam int W = 4;\nendpackage\n\
module imported import p::*; #(\n parameter int W = 8\n) (\n \
input logic clk,\n output logic [W-1:0] q\n);\n \
assign q = '0;\nendmodule\n",
"imported",
),
// Two imports, then a parameter list.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
"twice",
),
// A **non-ANSI** port list: the directions live in the body, which is
// exactly what the slice drops.
(
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
always @* b = |a;\nendmodule\n",
"old",
),
// Non-ANSI with nothing declaring the ports at all.
("module silent (a, b);\nendmodule\n", "silent"),
// A comment and an attribute inside the header.
(
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
input logic clk\n);\nendmodule\n",
"noisy",
),
// A lifetime qualifier.
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
// A second module in the same file, after the one being planned.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"first",
),
// …and before it, so the slice's prefix carries a whole module.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"second",
),
// A compiler directive between the name and the port list, which the
// whitelist refuses outright.
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
// A directive *inside* the port list, which carries a warning the two
// plans must both raise.
(
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
`endif\n);\nendmodule\n",
"ifdefd",
),
// An escaped identifier for the module and for a port.
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
// A header longer than the first rung of the window ladder.
(WIDE, "wide"),
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
// instance, `(* ... *)`, right after the module name and before the
// parameter list — the one shape the "noisy" case above is commented
// as covering but does not (it has two comments, no attribute).
// **Finding, not a regression this round introduced**: a module with
// an attribute anywhere near its header is not indexed as a `Module`
// unit at all (see
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
// so this pins the safe side effect — `module_header` declines before
// its whitelist walk ever runs — rather than the whitelist's own
// handling of attributes, which this shape cannot reach.
(
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
input logic clk\n);\nendmodule\n",
"attributed",
),
// An attribute instance *inside* the port list, attached to one port.
// Same finding as `attributed`: not indexed, so not reached either.
(
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
);\nendmodule\n",
"port_attributed",
),
// A single import declaration naming several packages, comma
// separated (`import a::*, b::*;`) — one statement, not two, and the
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module chained import p::*, q::*; (input logic a);\nendmodule\n",
"chained",
),
// A parameter default whose string literal carries the exact bytes
// the whitelist watches for — `;` and `)` — which must stay inside
// the `String` token and never be mistaken for header punctuation.
(
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
input logic clk\n);\nendmodule\n",
"stringy",
),
// CRLF line endings through the whole header.
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
];
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
input logic port_number_one_with_a_long_name,\n \
input logic port_number_two_with_a_long_name,\n \
input logic port_number_three_with_a_long_name,\n \
input logic port_number_four_with_a_long_name,\n \
input logic port_number_five_with_a_long_name,\n \
output logic port_number_six_with_a_long_name\n);\n \
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
/// The whole argument for the slice: for every shape above, the plan built
/// from the header alone is the plan built from the whole file. Where it
/// would not be — a non-ANSI list, a header the whitelist refuses — the
/// guard in [`plan_for`] sends the question back to the whole file, so the
/// comparison holds there too.
#[test]
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
for (text, module) in SHAPES {
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
let ours = plan_for(&index, module, text, site);
assert_eq!(ours, whole, "{module}");
}
}
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
/// trivially for a shape the whitelist declines — both sides parse the
/// whole file, so a wrong slice could hide behind that. These shapes must
/// actually slice, so the comparison exercises the whitelist walk it is
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
/// `;`/`)` sitting inside a string literal, and CRLF endings.
#[test]
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
module_header(&index, module, text).is_some(),
"{module}: expected the header to actually slice, not fall back whole-file"
);
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
/// differently off its header, and really is sent back to the whole file.
#[test]
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
let path = PathBuf::from("/rtl/old.sv");
let index = WorkspaceIndex::build(vec![(path, text)]);
let header = module_header(&index, "old", text).expect("the header slices");
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
assert!(
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
"premise: the header alone knows nothing about these ports"
);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let guarded = plan_for(&index, "old", text, site).expect("a plan");
assert_eq!(guarded.ports[0].dir, "input");
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
}
/// The whole answer, pinned at the prefixes the hot path is worst at — the
/// empty one and a one-character one, where every tier is at its widest.
/// Tier 0 answers with names, so the pin spells out every module item's
/// label *and* the text it inserts, which is now the label again.
#[test]
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
let tree = Tree::new("pinned");
tree.write("sub.sv", SUB);
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
let (_tree, mut ws, uri, _) = opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
// Nothing typed, then one character — the two widest requests there
// are. `top` is in the answer because the buffer declares it and the
// index holds it like any other module.
let mut answer = |typed: &str| {
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
+ typed.len() as u32;
let doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
items(completions(&ws, &uri, position, true))
};
for (typed, expected) in
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
{
let items = answer(typed);
let found: Vec<&str> = skeletons(&items).iter().map(|item| item.label.as_str()).collect();
assert_eq!(found, expected, "module items after typing {typed:?}");
}
// …and the exact text each of them inserts, which is the name and
// nothing else however many ports the module has. The instantiation is
// `inline.rs`'s business now.
let items = answer("");
for name in ["sub", "alpha", "submarine"] {
let item = find(&items, name).expect("the module item");
assert_eq!(inserted(item), name, "the popup inserts the name alone");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(item.insert_text_mode, None, "there is no indentation to keep");
}
}
/// A file edited on disk since the index last read it has moved every span
/// the index holds, so the slice must not take one on trust.
#[test]
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
let text = "module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
// The same index against a file whose text has shifted underneath it.
let moved = format!("// a line nobody told the index about\n{text}");
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
}
// ------------------------------------------------------------------
// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30)
// ------------------------------------------------------------------
#[test]
fn a_module_name_at_item_position_completes_to_the_name_alone() {
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("nameonly", top, " su");
let items = items(completions(&ws, &uri, position, true));
let modules = skeletons(&items);
assert_eq!(modules.len(), 1, "{items:#?}");
let item = modules[0];
assert_eq!(item.label, "sub");
assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon");
assert_eq!(item.detail.as_deref(), Some("module — sub.sv"));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest");
assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show");
}
#[test]
fn the_snippet_flag_no_longer_changes_the_module_item() {
// The M4 fallback — a plain-text spelling of the skeleton for a client
// that never advertised `snippetSupport` — has nothing left to fall
// back from: the item is a word either way.
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, " su");
for snippets in [true, false] {
let items = items(completions(&ws, &uri, position, snippets));
let item = skeletons(&items)[0];
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "snippets: {snippets}");
}
}
/// The whole point of level 1: the popup no longer reads the files it
/// offers names from. Proved by deleting the declaring file after the
/// index has been built — the old tier answered nothing at all here,
/// because every item needed that file's text.
#[test]
fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() {
let tree = Tree::new("noread");
let sub = tree.write("sub.sv", SUB);
let (_tree, ws, uri, position) =
opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su");
fs::remove_file(&sub).expect("remove the declaring file");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(
skeletons(&items).iter().map(|item| item.label.as_str()).collect::<Vec<_>>(),
["sub"],
"the name comes from the index's table, not from the file: {items:#?}"
);
}
#[test]
fn the_edit_replaces_exactly_the_typed_word() {
let top = "module top;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("replace", top, " su");
let items = items(completions(&ws, &uri, position, true));
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}");
assert_eq!(edit.range.end, Position { line: 1, character: 4 });
}
}
#[test]
fn no_skeleton_is_offered_in_the_middle_of_an_expression() {
// The other tiers answer here — a name is a name wherever it is
// written — but a fifteen-line instantiation is not.
for (name, top, needle) in [
("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"),
("decl", "module top;\n logic su\nendmodule\n", "logic su"),
("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"),
("header", "module top (su\n);\nendmodule\n", "top (su"),
] {
let (_tree, ws, uri, position) = asking(name, top, needle);
let items = items(completions(&ws, &uri, position, true));
assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}");
}
}
#[test]
fn no_skeleton_is_offered_inside_a_procedural_block() {
let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("always", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "module top;\n initial begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("initial", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn no_skeleton_is_offered_inside_a_function_or_a_class() {
let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n";
let (_tree, ws, uri, position) = asking("function", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "package p;\n class c;\n su\n endclass\nendpackage\n";
let (_tree, ws, uri, position) = asking("class", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_generate_block_is_still_item_position() {
let top = "\
module top;
for (genvar i = 0; i < 4; i++) begin : g
su
end
endmodule
";
let (_tree, ws, uri, position) = asking("genfor", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}");
let top = "module top;\n generate\n su\n endgenerate\nendmodule\n";
let (_tree, ws, uri, position) = asking("generate", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1);
}
#[test]
fn no_skeleton_is_offered_outside_a_design_unit() {
let top = "su\nmodule top;\nendmodule\n";
let (_tree, ws, uri, position) = asking("toplevel", top, "su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_prefix_that_matches_no_module_offers_no_skeleton() {
let top = "module top;\n zzz\nendmodule\n";
let (_tree, ws, uri, position) = asking("nomatch", top, " zzz");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() {
// Until 2026-08-30 tier 0 skipped it: there is no single definition to
// build a *skeleton* from, and the skeleton was the item. A name needs
// no definition, so round 1 offered the name and left the detail
// blank. Round 2 (owner ruling, same day) makes the ghost choose a
// copy rather than decline, so the popup names the copy the ghost will
// read — `nearest_definition`'s answer, which for a buffer at the tree
// root is the lexicographically smaller path.
let tree = Tree::new("dup");
tree.write("a.sv", "module dup ();\nendmodule\n");
tree.write("b.sv", "module dup ();\nendmodule\n");
let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "dup").expect("the name is still known");
assert_eq!(tier(item), TIER_MODULE, "{items:#?}");
assert_eq!(item.detail.as_deref(), Some("module — a.sv"));
}
/// The nearest-definition chooser, at the level `inline.rs` consumes it.
///
/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling`
/// share `hw` and nothing more, and a byte-wise prefix would count the
/// `hw/top_` they spell alike and rank the copies by a coincidence.
#[test]
fn the_nearest_definition_is_the_one_sharing_the_most_path_components() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let index = WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let asking = |from: &str| {
nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from)))
.expect("a definition")
.to_path_buf()
};
assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey);
assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling);
// Near neither, and no path at all: the tie falls to the smaller path
// rather than to whatever the index happens to hold first.
assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling);
assert_eq!(
nearest_definition(&index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
/// QA round-2 finding, fixed at lead review: a copy in the asking
/// buffer's own directory and one in a subdirectory of it share the same
/// number of leading components with the buffer (its filename never
/// matches a directory), and the lexicographic tie-break alone could pick
/// the deeper, less related copy. The real shape is opentitan's 61-way
/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv`
/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`.
#[test]
fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() {
let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv");
let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv");
let text = "module tb ();\nendmodule\n";
for sources in [
vec![(sibling.clone(), text), (deeper.clone(), text)],
vec![(deeper.clone(), text), (sibling.clone(), text)],
] {
let index = WorkspaceIndex::build(sources);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
sibling.as_path(),
"the shallower copy is the nearer one"
);
}
// …and depth only breaks a tie: a deeper copy that genuinely shares
// more of the asking path still wins.
let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
deeper.as_path(),
"sharing more components outranks being shallow"
);
}
/// The answer is a property of the paths, not of the order the index was
/// built in — which is what makes it the same answer twice in a row, and
/// the same answer in two editors.
#[test]
fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let forwards =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let backwards =
WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]);
for index in [&forwards, &backwards] {
let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv");
assert_eq!(
nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"),
earlgrey.as_path()
);
assert_eq!(
nearest_definition(index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
}
/// A module only one file declares goes through the same chooser and comes
/// back with the file `vlog_refactor::module_definition` picks — the
/// equivalence that says round 2 widened the twice-declared case and moved
/// nothing else.
#[test]
fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() {
let path = PathBuf::from("/rtl/sub.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]);
let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition");
assert_eq!(expected, path.as_path());
for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] {
assert_eq!(
nearest_definition(&index, "sub", from.as_deref()).expect("a definition"),
expected,
"{from:?}"
);
}
// And a name nothing declares is `None` here where it is an `Err`
// there — the same "no answer", spelled the way each caller reads it.
assert!(nearest_definition(&index, "nope", None).is_none());
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,344 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The **related** tier: what this file is related to through the workspace
//! index, ranked above the rest of the workspace and below the file itself
//! (`docs/features/fast-actions/README.md`, completion through the
//! relationship map).
//!
//! The tier-5 table answers "every package member, typedef, class and module
//! the workspace declares whose name matches", alphabetically, until the
//! response is full — so in a workspace of tens of thousands of files the
//! members of the one package this file actually imports were cut off behind
//! names from files it has nothing to do with (measured: 46 of 47 matching
//! `aes_pkg` names offered at `ae` in 4 000 files, 11 of 47 in 40 000). What a
//! file is related to is known without reading anything: the packages its
//! scope chain imports, the classes its enclosing class extends, the headers
//! its `` `include``s reach. Those names come first.
//!
//! **No item is taken away.** A related item does not count against
//! [`LIMIT`](super::LIMIT): the tiers after it fill exactly as far as they
//! did before, and a name the related tier claimed is skipped by them
//! without being counted, so every label of the old answer is still offered,
//! with the same edit and format (the completion-equivalence test holds the
//! server to that). **What does change** for a name the related tier claims
//! is its icon and its detail: they now describe the declaration the file is
//! related to — the member of the package it imports, the macro of the header
//! it includes, the member of the class it extends — where the workspace tier
//! described the first declaration of that name in the whole workspace
//! (`NumRegs` of whichever register package sorts first; a module of the name
//! where the imported package declares a function). The tier has its own
//! cap, [`RELATED_LIMIT`], past which it says the answer is incomplete.
use lsp_types::CompletionItemKind;
use vlog_parser::defines::DefineKind;
use vlog_semantic::{Def, ScopeKind, Semantics, SymbolKind};
use super::tiers::innermost_scope;
use super::word::Word;
use super::{completion_kind, Items, TIER_RELATED};
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query, Score};
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
/// How many related names one response carries at most.
///
/// A package of a few hundred members is the large case (`aes_pkg` has 259
/// on its connection surface); at an empty prefix the related tier would
/// otherwise double a response that is already incomplete.
pub(super) const RELATED_LIMIT: usize = 256;
/// One related name: what to show, and how it ranks.
struct Related {
name: String,
kind: SymbolKind,
detail: String,
}
impl Items {
/// Add a related item, unless a higher tier already offered that name or
/// the tier is full. Not counted against [`LIMIT`](super::LIMIT).
fn related(&mut self, name: &str, kind: CompletionItemKind, detail: String) {
if self.seen.contains(name) {
return;
}
if self.related >= RELATED_LIMIT {
self.incomplete = true;
return;
}
self.related += 1;
self.unlimited(name, kind, TIER_RELATED, detail);
}
}
/// The related tier for a name being typed: the members of every package
/// the scope chain at the cursor imports, and of the classes the enclosing
/// class extends.
pub(super) fn related_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
let mut found = imported(ws, &doc.semantics, word.start);
found.extend(inherited(ws, &doc.semantics, word.start));
let mut matched: Vec<(Related, Option<Score>)> = found
.into_iter()
.filter_map(|related| match fuzzy {
None => starts_with_ignore_case(&related.name, &word.text).then_some((related, None)),
Some(query) => query.score(&related.name).map(|score| (related, Some(score))),
})
.collect();
matched.sort_by(|(a, sa), (b, sb)| match (sa, sb) {
(Some(sa), Some(sb)) => rank_cmp((&a.name, *sa), (&b.name, *sb)),
_ => a.name.cmp(&b.name),
});
for (related, _) in matched {
items.related(&related.name, completion_kind(related.kind), related.detail);
}
}
/// The related tier after a backtick: the macros the headers this buffer
/// reaches through its `` `include``s define, ahead of every other macro in
/// the workspace.
pub(super) fn related_macros(items: &mut Items, ws: &Workspace, doc: &Document, prefix: &str) {
let mut names: Vec<(String, String)> = Vec::new();
for path in crate::includes::reachable_from(ws, doc) {
let Some(table) = ws.index_file_id(&path).and_then(|file| ws.index().defines(file)) else {
continue;
};
let defines = table.entries().iter().filter(|d| d.kind == DefineKind::Define);
for define in defines.filter(|d| starts_with_ignore_case(&d.name, prefix)) {
names.push((define.name.clone(), crate::candidates::macro_of(define).detail));
}
}
names.sort();
names.dedup_by(|a, b| a.0 == b.0);
for (name, detail) in names {
items.related(&format!("`{name}"), CompletionItemKind::CONSTANT, detail);
}
}
/// Every member of every package imported by a scope enclosing `offset`,
/// innermost scope first, a wildcard bringing all of a package's members and
/// an explicit import the one it names.
fn imported(ws: &Workspace, semantics: &Semantics, offset: u32) -> Vec<Related> {
let mut out = Vec::new();
let mut at = innermost_scope(semantics, offset).or(Some(semantics.file_scope()));
while let Some(id) = at {
let Some(scope) = semantics.scope(id) else { break };
at = scope.parent;
for import in &scope.imports {
for (name, defs) in ws.index().members_of(&import.package) {
if import.item.as_deref().is_some_and(|item| item != name) {
continue;
}
let Some(def) = defs.first() else { continue };
out.push(Related {
name: name.to_string(),
kind: def.kind,
detail: format!("{} — {}::{name}", kind_label(def.kind), import.package),
});
}
}
}
out
}
/// Every member the enclosing class inherits, as the index's member chain for
/// that class lists it — its own members included, which the scope tier has
/// already claimed — each named after the class that **declares** it, the
/// way the workspace tier names a member (`base_c::count`).
fn inherited(ws: &Workspace, semantics: &Semantics, offset: u32) -> Vec<Related> {
let mut at = innermost_scope(semantics, offset);
while let Some(id) = at {
let Some(scope) = semantics.scope(id) else { break };
if scope.kind == ScopeKind::Class {
let Some(key) = semantics.member_key(id) else { return Vec::new() };
let index = ws.index();
return index
.members_of_chain(&key)
.into_iter()
.map(|(name, def)| {
let owner = declaring_class(ws, &key, name, def).unwrap_or(&key);
Related {
name: name.to_string(),
kind: def.kind,
detail: format!("{} — {owner}::{name}", kind_label(def.kind)),
}
})
.collect();
}
at = scope.parent;
}
Vec::new()
}
/// Which class of `class`'s `extends` chain declares `def` as `name`: the
/// class itself, then its base, then that base's base — each hop the one
/// `vlog_semantic`'s `base_chain` takes, a recorded base or else the class a
/// typedef aliases (`typedef mid_c alias_t; class leaf_c extends alias_t;`).
/// `None` only for a chain the index cannot follow, and the caller then
/// names the class it started from.
fn declaring_class<'a>(
ws: &'a Workspace,
class: &'a str,
name: &str,
def: &Def,
) -> Option<&'a str> {
let index = ws.index();
let mut hop = Some(class);
let mut seen: Vec<&str> = Vec::new();
while let Some(unit) = hop.filter(|unit| !seen.contains(unit)) {
if index.members_of(unit).any(|(member, defs)| member == name && defs.first() == Some(def))
{
return Some(unit);
}
seen.push(unit);
hop = index.base_of(unit).or_else(|| aliased_class(ws, unit)).map(last_segment);
}
None
}
/// The class a typedef names, when `unit` is a typedef the index holds once —
/// the alias hop of `vlog_semantic`'s `base_chain` (`aliased_unit`), read
/// through the index's public tables.
fn aliased_class<'a>(ws: &'a Workspace, unit: &str) -> Option<&'a str> {
match ws.index().units(unit) {
[def] if def.kind == SymbolKind::Typedef => def.type_name.as_deref(),
_ => None,
}
}
/// The last `::` segment of a possibly qualified class path — the name the
/// member and inheritance tables are keyed by.
fn last_segment(path: &str) -> &str {
path.rsplit("::").next().unwrap_or(path)
}
#[cfg(test)]
mod tests {
use crate::completion::harness::*;
use crate::completion::*;
/// A package the buffer imports, and one it does not, both holding names
/// that start alike.
fn two_packages(name: &str) -> Tree {
let tree = Tree::new(name);
tree.write(
"near.sv",
"package near_pkg;\n localparam int ZED_NEAR = 1;\n typedef logic zed_t;\nendpackage\n",
);
tree.write("far.sv", "package far_pkg;\n localparam int ZED_FAR = 2;\nendpackage\n");
tree
}
#[test]
fn an_imported_packages_members_rank_above_the_rest_of_the_workspace() {
let top = "module top;\n import near_pkg::*;\n assign x = ze\nendmodule\n";
let (_tree, ws, uri, position) = opened(two_packages("rel_import"), top, "= ze");
let items = items(completions(&ws, &uri, position, true));
let near = find(&items, "ZED_NEAR").expect("the imported member");
let far = find(&items, "ZED_FAR").expect("the other package's member is still offered");
assert_eq!(tier(near), TIER_RELATED);
assert_eq!(tier(far), TIER_INDEX);
assert!(near.sort_text < far.sort_text, "related above the workspace");
assert_eq!(near.detail.as_deref(), Some("localparam — near_pkg::ZED_NEAR"));
assert_eq!(tier(find(&items, "zed_t").expect("the typedef")), TIER_RELATED);
}
#[test]
fn an_explicit_import_relates_the_one_name_it_imports() {
let top = "module top;\n import near_pkg::zed_t;\n assign x = ze\nendmodule\n";
let (_tree, ws, uri, position) = opened(two_packages("rel_explicit"), top, "= ze");
let items = items(completions(&ws, &uri, position, true));
// The binder makes an explicitly imported name a declaration of this
// scope, so it is offered by the scope tier, above even this one.
assert!(tier(find(&items, "zed_t").expect("imported")) <= TIER_RELATED);
assert_eq!(tier(find(&items, "ZED_NEAR").expect("still offered")), TIER_INDEX);
}
#[test]
fn related_items_take_nothing_from_the_tiers_after_them() {
// More project names than the cap, and an import whose members all
// match too: the workspace tiers still fill the whole cap.
let tree = two_packages("rel_cap");
let mut many = String::from("package many_pkg;\n");
for i in 0..LIMIT + 40 {
many.push_str(&format!(" localparam int ZED_{i:04} = {i};\n"));
}
many.push_str("endpackage\n");
tree.write("many.sv", &many);
let top = "module top;\n import near_pkg::*;\n assign x = ZE\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= ZE");
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
panic!("a list");
};
let related = list.items.iter().filter(|i| tier(i) == TIER_RELATED).count();
assert_eq!(related, 2, "the two near_pkg names");
assert_eq!(list.items.len() - related, LIMIT, "the cap counts the others only");
assert!(list.is_incomplete);
}
#[test]
fn a_class_relates_what_it_inherits() {
let tree = Tree::new("rel_class");
tree.write(
"base.sv",
"class base_c;\n int zed_count;\n function void zed_reset();\n endfunction\nendclass\n",
);
let top = "class derived_c extends base_c;\n function void go();\n ze\n endfunction\nendclass\n";
let (_tree, ws, uri, position) = opened(tree, top, " ze");
let items = items(completions(&ws, &uri, position, true));
let count = find(&items, "zed_count").expect("inherited");
assert_eq!(tier(count), TIER_RELATED);
assert_eq!(tier(find(&items, "zed_reset").expect("inherited")), TIER_RELATED);
// Named after the class that declares it, as the workspace tier
// names a member — not after the class that inherits it.
assert_eq!(count.detail.as_deref(), Some("variable — base_c::zed_count"));
}
#[test]
fn a_backtick_ranks_what_the_included_headers_define_first() {
let tree = Tree::new("rel_macro");
tree.write("near.svh", "`define ZED_NEAR 1\n");
tree.write("far.svh", "`define ZED_FAR 2\n");
let top = "`include \"near.svh\"\nmodule top;\n assign x = `ZE\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "`ZE");
let items = items(completions(&ws, &uri, position, true));
let near = find(&items, "`ZED_NEAR").expect("the included header's macro");
let far = find(&items, "`ZED_FAR").expect("every other macro is still offered");
assert_eq!(tier(near), TIER_RELATED);
assert!(near.sort_text < far.sort_text);
assert_eq!(near.detail.as_deref(), Some("`define ZED_NEAR"), "the detail tier 5 gives");
}
#[test]
fn a_member_two_classes_up_names_the_class_that_declares_it() {
let tree = Tree::new("rel_grand");
tree.write("base.sv", "class root_c;\n int zed_deep;\nendclass\nclass mid_c extends root_c;\n int zed_mid;\nendclass\n");
let top =
"class leaf_c extends mid_c;\n function void go();\n ze\n endfunction\nendclass\n";
let (_tree, ws, uri, position) = opened(tree, top, " ze");
let items = items(completions(&ws, &uri, position, true));
let detail = |label: &str| find(&items, label).and_then(|i| i.detail.clone());
assert_eq!(detail("zed_deep").as_deref(), Some("variable — root_c::zed_deep"));
assert_eq!(detail("zed_mid").as_deref(), Some("variable — mid_c::zed_mid"));
}
#[test]
fn a_member_reached_through_a_typedef_alias_names_the_class_that_declares_it() {
// QA R2: `leaf_c extends alias_t`, and `alias_t` is a typedef of
// `mid_c` — the member is `mid_c`'s.
let tree = Tree::new("rel_alias");
tree.write("base.sv", "class mid_c;\n int zed_mid;\nendclass\ntypedef mid_c alias_t;\n");
let top = "class leaf_c extends alias_t;\n function void go();\n ze\n endfunction\nendclass\n";
let (_tree, ws, uri, position) = opened(tree, top, " ze");
let items = items(completions(&ws, &uri, position, true));
let mid = find(&items, "zed_mid").expect("inherited through the alias");
assert_eq!(tier(mid), TIER_RELATED);
assert_eq!(mid.detail.as_deref(), Some("variable — mid_c::zed_mid"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! What may be written here: the module-item gate and the statement gate,
//! judged over the token stream's scope chain.
//!
@@ -262,3 +264,5 @@ mod tests {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4 -707
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Tiers 1 to 5: the five ordinary tiers, in the order they fill the
//! response.
//!
@@ -236,711 +238,6 @@ pub(super) fn word_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: O
}
#[cfg(test)]
mod tests {
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use crate::uri::path_to_uri;
mod tests;
// ------------------------------------------------------------------
// tier 3 — templates
// ------------------------------------------------------------------
/// Only the templates — tier 3.
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
items
.iter()
.filter(|item| tier(item) == TIER_TEMPLATE)
.map(|item| item.label.as_str())
.collect()
}
/// The items offered at `needle`'s end in a buffer named `file`.
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
items(completions(&ws, &uri, position, true))
}
#[test]
fn a_statement_template_expands_where_a_statement_may_be_written() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("stmt", "top.sv", top, " if");
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
assert_eq!(
inserted(item),
"if (${1:cond}) begin\n $0\n end",
"the site's own indentation, the condition first and the body last"
);
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
}
#[test]
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
// Dedup is by label, so the labels are prose on purpose: `if` the
// keyword and `if begin/end` the template are two items, in that
// order of specificity.
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("both", "top.sv", top, " if");
let keyword = find(&items, "if").expect("the bare keyword");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(keyword), TIER_KEYWORD);
assert_eq!(tier(template), TIER_TEMPLATE);
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
}
#[test]
fn a_template_ranks_below_a_name_the_code_declares() {
let top = "\
module top;
logic if_enable;
always_comb begin
if
end
endmodule
";
let items = offering("rank", "top.sv", top, " if");
let symbol = find(&items, "if_enable").expect("a declaration in scope");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(symbol), TIER_SCOPE);
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
}
#[test]
fn statement_templates_and_item_templates_swap_places_with_the_position() {
// One prefix, `i`, reaching `if` in one place and `initial` in the
// other — so this is the gate and not the filter.
let inside = offering(
"posstmt",
"top.sv",
"module top;\n always_comb begin\n i\n end\nendmodule\n",
" i",
);
assert!(template_labels(&inside).contains(&"if begin/end"));
assert!(
!template_labels(&inside).contains(&"initial begin/end"),
"an initial block is not a statement: {:?}",
template_labels(&inside)
);
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
assert!(template_labels(&at_item).contains(&"initial begin/end"));
assert!(
!template_labels(&at_item).contains(&"if begin/end"),
"a bare if is not a module item: {:?}",
template_labels(&at_item)
);
}
#[test]
fn an_always_template_is_a_module_item_and_nothing_else() {
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
"and `alw` finds every one of them"
);
let inside = offering(
"alwstmt",
"top.sv",
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
" alw",
);
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
}
#[test]
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
let inside = offering(
"declstmt",
"top.sv",
"module top;\n always_comb begin\n log\n end\nendmodule\n",
" log",
);
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
}
#[test]
fn the_file_name_decides_which_dialect_is_offered() {
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
assert!(template_labels(&sv).contains(&"logic name;"));
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
assert_eq!(template_labels(&reg), ["reg name;", "reg [N:0] name;"]);
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
#[test]
fn an_else_template_follows_an_end_on_the_same_line() {
let top = "\
module top;
always_comb begin
if (a) begin
end el
end
endmodule
";
let items = offering("elsetail", "top.sv", top, "end el");
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
assert_eq!(
inserted(find(&items, "else if").expect("the else-if template")),
"else if (${1:cond}) begin\n $0\n end"
);
}
#[test]
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
// The other half of the same rule: `x = if` is an expression, not a
// place a template belongs — and the general tiers still answer there.
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
let items = offering("midline", "top.sv", top, "x = if");
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
}
#[test]
fn no_template_is_offered_where_a_statement_cannot_go() {
for (name, top, needle) in [
// A generate block is item position, not statement position.
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
// A `case` arm wants `label:`, not a bare statement.
(
"casearm",
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
" if",
),
// Nothing at all is open here.
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
// A port list is not a statement, however much it starts a line.
("ports", "module top (\n if\n);\nendmodule\n", " if"),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
}
}
#[test]
fn a_subprogram_body_is_statement_position() {
for (name, top, needle) in [
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
(
"fnbegin",
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
" if",
),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
}
}
#[test]
fn nothing_templated_is_offered_inside_a_comment() {
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_client_without_snippet_support_gets_the_template_filled_in() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
let items = items(completions(&ws, &uri, position, false));
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
let text = inserted(item);
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
assert_eq!(text, "if (cond) begin\n\n end");
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the inserted text must parse: {text}"
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
let items = offering("tmpldocs", "top.sv", top, " alw");
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
panic!("markdown documentation");
};
// Fenced with the language id the extension's TextMate grammar is
// registered for, so the panel renders highlighted rather than grey.
assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value);
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
}
// ------------------------------------------------------------------
// tier 4 — keywords
// ------------------------------------------------------------------
#[test]
fn every_keyword_the_lexer_knows_is_offered() {
let top = "module top;\n assign x = alw\nendmodule\n";
let (_tree, ws, uri, position) = asking("keyword", top, "= alw");
let items = items(completions(&ws, &uri, position, true));
let keywords: Vec<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]);
let always = find(&items, "always").expect("`always`");
assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD));
assert_eq!(inserted(always), "always");
}
#[test]
fn the_keyword_tier_is_exactly_the_lexers_list() {
let top = "module top;\n assign x = \nendmodule\n";
let (_tree, ws, uri, position) = asking("allkeywords", top, "= ");
let items = items(completions(&ws, &uri, position, true));
let offered: HashSet<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
let known: HashSet<&str> = KEYWORDS.iter().copied().collect();
assert_eq!(offered, known, "no keyword may be missing and none invented");
}
// ------------------------------------------------------------------
// tiers, ordering and dedup
// ------------------------------------------------------------------
#[test]
fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() {
let tree = Tree::new("tiers");
tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n");
tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n");
let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= w");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE);
assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX);
assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD);
assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD);
let scope = find(&items, "w_local").expect("in scope");
let word = find(&items, "w_elsewhere").expect("a project word");
assert!(scope.sort_text < word.sort_text, "the client sorts scope above words");
}
#[test]
fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() {
let tree = Tree::new("dedup");
// The same name, declared here and used elsewhere in the project.
tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n");
let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= shared");
let items = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
items.iter().filter(|i| i.label == "shared_name").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it");
}
#[test]
fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() {
let top = "\
module top #(parameter int WIDTH = 8) (input logic clk);
typedef logic [1:0] pair_t;
logic [WIDTH-1:0] data;
function int f(); return 0; endfunction
assign x =
endmodule
";
let (_tree, ws, uri, position) = asking("kinds", top, "assign x =");
let items = items(completions(&ws, &uri, position, true));
let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind;
assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT));
assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD));
assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER));
assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE));
assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION));
assert_eq!(
find(&items, "data").expect("data").detail.as_deref(),
Some("logic [WIDTH-1:0] data;"),
"the declaration as written"
);
}
#[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 one of this file's declarations (tier 2, `completion-ux`)
// — never as a visible declaration.
let top = "\
module top;
initial begin : b
integer inner_only;
end
initial begin
x = inner
end
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 declaration at least");
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
}
// ------------------------------------------------------------------
// fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md
// ------------------------------------------------------------------
/// A workspace holding the name the whole round is about, a scatter to
/// rank it against, and a `ce…` name that only a prefix reaches.
fn typing(name: &str) -> (Tree, Workspace, Uri) {
let tree = Tree::new(name);
tree.write(
"ast.sv",
"module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\
endmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
(tree, ws, uri)
}
/// The response to `typed`, written mid-expression in `top.sv` — the
/// position where no tier is position-gated off.
fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option<CompletionResponse> {
let text = format!("module top;\n assign x = {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset =
(text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32;
let position = ws.document(uri).expect("open").positions().position(offset);
completions(ws, uri, position, true)
}
/// The headline: three characters reach a name no prefix ever would.
#[test]
fn three_characters_reach_a_name_a_prefix_never_would() {
let (_tree, mut ws, uri) = typing("fuzzyhit");
for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] {
let found = items(after_typing(&mut ws, &uri, typed));
let item = find(&found, "clk_osc_en_q")
.unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found)));
assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project");
assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted");
}
}
/// …and the edit still replaces exactly what was typed, which is the
/// whole reason a fuzzy hit is usable at all: `clkenq` becomes
/// `clk_osc_en_q`, not `clkenqclk_osc_en_q`.
#[test]
fn a_fuzzy_hit_replaces_exactly_the_typed_word() {
let (_tree, mut ws, uri) = typing("fuzzyedit");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit");
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
// ` assign x = clkenq` — the word starts at column 13 and the cursor
// is at its end.
assert_eq!(edit.range.start, Position { line: 1, character: 13 });
assert_eq!(edit.range.end, Position { line: 1, character: 19 });
assert_eq!(edit.new_text, "clk_osc_en_q");
assert_eq!(item.filter_text, None, "the client filters on the label, as it should");
}
/// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters
/// in order and must still not reach it.
#[test]
fn two_characters_match_by_prefix_and_nothing_else() {
let (_tree, mut ws, uri) = typing("fuzzyfloor");
for typed in ["c", "ce"] {
let found = items(after_typing(&mut ws, &uri, typed));
assert!(!found.is_empty(), "premise: {typed:?} answers something");
for item in &found {
assert!(
starts_with_ignore_case(&item.label, typed),
"{:?} is not a prefix match for {typed:?}",
item.label
);
}
}
// The discriminator, spelled out: `ce` would reach it if it were fuzzy
// (`c` at 0, `e` at 8), and `cen` — one character more — does.
let two = items(after_typing(&mut ws, &uri, "ce"));
assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two));
assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two));
let three = items(after_typing(&mut ws, &uri, "cen"));
assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three));
}
/// The 1- and 2-character answers, pinned against what they were before
/// fuzzy matching existed. The keyword tier is checked as a set rather
/// than listed, so adding a reserved word to the lexer does not break a
/// test about completion.
#[test]
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `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
.iter()
.filter(|item| tier(item) != TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
assert_eq!(named, expected, "the names {typed:?} answers with");
let keywords: Vec<&str> = found
.iter()
.filter(|item| tier(item) == TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
let expected_keywords: Vec<&str> =
KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect();
assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with");
}
}
/// **The `isIncomplete` trap.** VS Code asks again on the next keystroke
/// only when the last answer said it was incomplete, so a complete
/// two-character answer would swallow the third keystroke and fuzzy would
/// never fire at all.
#[test]
fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() {
let (_tree, mut ws, uri) = typing("fuzzyincomplete");
for typed in ["", "c", "ce"] {
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else {
panic!("a completion list for {typed:?}");
};
assert!(list.is_incomplete, "{typed:?} must ask to be asked again");
}
// From the floor up the ordinary rule stands: complete when the whole
// hit set fit, which is sound because appending a character can only
// ever shrink it.
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else {
panic!("a completion list");
};
assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len());
}
/// A prefix match is the best subsequence match there is, and the list
/// says so — asserted on the order of the array, which is what the cap
/// cuts and what a client that does not re-rank shows.
#[test]
fn a_prefix_hit_outranks_a_scattered_one() {
let (_tree, mut ws, uri) = typing("fuzzyrank");
let found = items(after_typing(&mut ws, &uri, "clk"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("clk_osc_en_q") < at("c_l_k_scatter"),
"the prefix hit leads: {:?}",
labels(&found)
);
}
/// Scoring the boundaries is visible in the order, not only in the score:
/// a run that starts after an underscore beats the same letters buried
/// mid-word.
#[test]
fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() {
let tree = Tree::new("fuzzyboundary");
tree.write(
"ast.sv",
"module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "ena"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("osc_ena_ready") < at("xxenaxx_ready"),
"the boundary run leads: {:?}",
labels(&found)
);
drop(tree);
}
/// Dedup survives the change: a name two tiers can reach is offered once,
/// by the better tier, whichever way it was matched.
#[test]
fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() {
let tree = Tree::new("fuzzydedup");
// The same name, declared in this buffer (tier 1) and used in the
// project (tier 5), reachable from `clkenq` by neither prefix.
tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("= clkenq").expect("needle") + 8) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
found.iter().filter(|item| item.label == "clk_osc_en_q").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE));
drop(tree);
}
/// The tiers that did **not** go fuzzy, pinned so the split is a decision
/// and not a drift: keywords, templates and macro names still match by
/// prefix, and the module tier still matches by substring.
#[test]
fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() {
let tree = Tree::new("fuzzyunchanged");
tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n");
tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
// Mid-expression: the macro name is offered bare by tier 2 and must
// not be reachable by subsequence, and neither is a keyword.
let found = items(after_typing(&mut ws, &uri, "clkenq"));
assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found));
let found = items(after_typing(&mut ws, &uri, "alws"));
assert!(labels(&found).is_empty() || !labels(&found).contains(&"always"));
// A backtick still answers by prefix only.
let text = "module top;\n assign x = `CLKENQ\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way");
// …and the module tier is still a substring match, which is wider
// than a prefix and narrower than a subsequence.
let text = "module top;\n osc_en\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("osc_en").expect("needle") + 6) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect();
assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it");
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
fn a_declaration_in_scope_is_reached_by_subsequence() {
let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "clk_osc_en_q").expect("the declaration");
assert_eq!(tier(item), TIER_SCOPE);
assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;"));
}
/// The index tier goes fuzzy too — a package member is reached the same
/// way a project word is.
#[test]
fn a_project_declaration_is_reached_by_subsequence() {
let tree = Tree::new("fuzzyindex");
tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "CLK_OSC_EN_Q").expect("the package member");
assert_eq!(tier(item), TIER_INDEX);
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT));
drop(tree);
}
#[test]
fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() {
let tree = Tree::new("overlay");
let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n");
let top = "module top;\n assign x = ov\nendmodule\n";
let (_tree, mut ws, uri, position) = opened(tree, top, "= ov");
let other_uri = path_to_uri(&other).expect("uri");
ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string());
ws.rebuild_index();
let items = items(completions(&ws, &uri, position, true));
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,704 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use crate::uri::path_to_uri;
// ------------------------------------------------------------------
// tier 3 — templates
// ------------------------------------------------------------------
/// Only the templates — tier 3.
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
items
.iter()
.filter(|item| tier(item) == TIER_TEMPLATE)
.map(|item| item.label.as_str())
.collect()
}
/// The items offered at `needle`'s end in a buffer named `file`.
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
items(completions(&ws, &uri, position, true))
}
#[test]
fn a_statement_template_expands_where_a_statement_may_be_written() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("stmt", "top.sv", top, " if");
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
assert_eq!(
inserted(item),
"if (${1:cond}) begin\n $0\n end",
"the site's own indentation, the condition first and the body last"
);
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
}
#[test]
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
// Dedup is by label, so the labels are prose on purpose: `if` the
// keyword and `if begin/end` the template are two items, in that
// order of specificity.
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("both", "top.sv", top, " if");
let keyword = find(&items, "if").expect("the bare keyword");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(keyword), TIER_KEYWORD);
assert_eq!(tier(template), TIER_TEMPLATE);
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
}
#[test]
fn a_template_ranks_below_a_name_the_code_declares() {
let top = "\
module top;
logic if_enable;
always_comb begin
if
end
endmodule
";
let items = offering("rank", "top.sv", top, " if");
let symbol = find(&items, "if_enable").expect("a declaration in scope");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(symbol), TIER_SCOPE);
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
}
#[test]
fn statement_templates_and_item_templates_swap_places_with_the_position() {
// One prefix, `i`, reaching `if` in one place and `initial` in the
// other — so this is the gate and not the filter.
let inside = offering(
"posstmt",
"top.sv",
"module top;\n always_comb begin\n i\n end\nendmodule\n",
" i",
);
assert!(template_labels(&inside).contains(&"if begin/end"));
assert!(
!template_labels(&inside).contains(&"initial begin/end"),
"an initial block is not a statement: {:?}",
template_labels(&inside)
);
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
assert!(template_labels(&at_item).contains(&"initial begin/end"));
assert!(
!template_labels(&at_item).contains(&"if begin/end"),
"a bare if is not a module item: {:?}",
template_labels(&at_item)
);
}
#[test]
fn an_always_template_is_a_module_item_and_nothing_else() {
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
"and `alw` finds every one of them"
);
let inside = offering(
"alwstmt",
"top.sv",
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
" alw",
);
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
}
#[test]
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
let inside = offering(
"declstmt",
"top.sv",
"module top;\n always_comb begin\n log\n end\nendmodule\n",
" log",
);
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
}
#[test]
fn the_file_name_decides_which_dialect_is_offered() {
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
assert!(template_labels(&sv).contains(&"logic name;"));
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
assert_eq!(template_labels(&reg), ["reg name;", "reg [N:0] name;"]);
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
#[test]
fn an_else_template_follows_an_end_on_the_same_line() {
let top = "\
module top;
always_comb begin
if (a) begin
end el
end
endmodule
";
let items = offering("elsetail", "top.sv", top, "end el");
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
assert_eq!(
inserted(find(&items, "else if").expect("the else-if template")),
"else if (${1:cond}) begin\n $0\n end"
);
}
#[test]
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
// The other half of the same rule: `x = if` is an expression, not a
// place a template belongs — and the general tiers still answer there.
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
let items = offering("midline", "top.sv", top, "x = if");
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
}
#[test]
fn no_template_is_offered_where_a_statement_cannot_go() {
for (name, top, needle) in [
// A generate block is item position, not statement position.
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
// A `case` arm wants `label:`, not a bare statement.
(
"casearm",
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
" if",
),
// Nothing at all is open here.
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
// A port list is not a statement, however much it starts a line.
("ports", "module top (\n if\n);\nendmodule\n", " if"),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
}
}
#[test]
fn a_subprogram_body_is_statement_position() {
for (name, top, needle) in [
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
(
"fnbegin",
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
" if",
),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
}
}
#[test]
fn nothing_templated_is_offered_inside_a_comment() {
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_client_without_snippet_support_gets_the_template_filled_in() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
let items = items(completions(&ws, &uri, position, false));
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
let text = inserted(item);
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
assert_eq!(text, "if (cond) begin\n\n end");
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the inserted text must parse: {text}"
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
let items = offering("tmpldocs", "top.sv", top, " alw");
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
panic!("markdown documentation");
};
// Fenced with the language id the extension's TextMate grammar is
// registered for, so the panel renders highlighted rather than grey.
assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value);
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
}
// ------------------------------------------------------------------
// tier 4 — keywords
// ------------------------------------------------------------------
#[test]
fn every_keyword_the_lexer_knows_is_offered() {
let top = "module top;\n assign x = alw\nendmodule\n";
let (_tree, ws, uri, position) = asking("keyword", top, "= alw");
let items = items(completions(&ws, &uri, position, true));
let keywords: Vec<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]);
let always = find(&items, "always").expect("`always`");
assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD));
assert_eq!(inserted(always), "always");
}
#[test]
fn the_keyword_tier_is_exactly_the_lexers_list() {
let top = "module top;\n assign x = \nendmodule\n";
let (_tree, ws, uri, position) = asking("allkeywords", top, "= ");
let items = items(completions(&ws, &uri, position, true));
let offered: HashSet<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
let known: HashSet<&str> = KEYWORDS.iter().copied().collect();
assert_eq!(offered, known, "no keyword may be missing and none invented");
}
// ------------------------------------------------------------------
// tiers, ordering and dedup
// ------------------------------------------------------------------
#[test]
fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() {
let tree = Tree::new("tiers");
tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n");
tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n");
let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= w");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE);
assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX);
assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD);
assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD);
let scope = find(&items, "w_local").expect("in scope");
let word = find(&items, "w_elsewhere").expect("a project word");
assert!(scope.sort_text < word.sort_text, "the client sorts scope above words");
}
#[test]
fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() {
let tree = Tree::new("dedup");
// The same name, declared here and used elsewhere in the project.
tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n");
let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= shared");
let items = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> = items.iter().filter(|i| i.label == "shared_name").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it");
}
#[test]
fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() {
let top = "\
module top #(parameter int WIDTH = 8) (input logic clk);
typedef logic [1:0] pair_t;
logic [WIDTH-1:0] data;
function int f(); return 0; endfunction
assign x =
endmodule
";
let (_tree, ws, uri, position) = asking("kinds", top, "assign x =");
let items = items(completions(&ws, &uri, position, true));
let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind;
assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT));
assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD));
assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER));
assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE));
assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION));
assert_eq!(
find(&items, "data").expect("data").detail.as_deref(),
Some("logic [WIDTH-1:0] data;"),
"the declaration as written"
);
}
#[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 one of this file's declarations (tier 2, `completion-ux`)
// — never as a visible declaration.
let top = "\
module top;
initial begin : b
integer inner_only;
end
initial begin
x = inner
end
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 declaration at least");
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
}
// ------------------------------------------------------------------
// fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md
// ------------------------------------------------------------------
/// A workspace holding the name the whole round is about, a scatter to
/// rank it against, and a `ce…` name that only a prefix reaches.
fn typing(name: &str) -> (Tree, Workspace, Uri) {
let tree = Tree::new(name);
tree.write(
"ast.sv",
"module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\
endmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
(tree, ws, uri)
}
/// The response to `typed`, written mid-expression in `top.sv` — the
/// position where no tier is position-gated off.
fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option<CompletionResponse> {
let text = format!("module top;\n assign x = {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32;
let position = ws.document(uri).expect("open").positions().position(offset);
completions(ws, uri, position, true)
}
/// The headline: three characters reach a name no prefix ever would.
#[test]
fn three_characters_reach_a_name_a_prefix_never_would() {
let (_tree, mut ws, uri) = typing("fuzzyhit");
for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] {
let found = items(after_typing(&mut ws, &uri, typed));
let item = find(&found, "clk_osc_en_q")
.unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found)));
assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project");
assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted");
}
}
/// …and the edit still replaces exactly what was typed, which is the
/// whole reason a fuzzy hit is usable at all: `clkenq` becomes
/// `clk_osc_en_q`, not `clkenqclk_osc_en_q`.
#[test]
fn a_fuzzy_hit_replaces_exactly_the_typed_word() {
let (_tree, mut ws, uri) = typing("fuzzyedit");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit");
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
// ` assign x = clkenq` — the word starts at column 13 and the cursor
// is at its end.
assert_eq!(edit.range.start, Position { line: 1, character: 13 });
assert_eq!(edit.range.end, Position { line: 1, character: 19 });
assert_eq!(edit.new_text, "clk_osc_en_q");
assert_eq!(item.filter_text, None, "the client filters on the label, as it should");
}
/// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters
/// in order and must still not reach it.
#[test]
fn two_characters_match_by_prefix_and_nothing_else() {
let (_tree, mut ws, uri) = typing("fuzzyfloor");
for typed in ["c", "ce"] {
let found = items(after_typing(&mut ws, &uri, typed));
assert!(!found.is_empty(), "premise: {typed:?} answers something");
for item in &found {
assert!(
starts_with_ignore_case(&item.label, typed),
"{:?} is not a prefix match for {typed:?}",
item.label
);
}
}
// The discriminator, spelled out: `ce` would reach it if it were fuzzy
// (`c` at 0, `e` at 8), and `cen` — one character more — does.
let two = items(after_typing(&mut ws, &uri, "ce"));
assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two));
assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two));
let three = items(after_typing(&mut ws, &uri, "cen"));
assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three));
}
/// The 1- and 2-character answers, pinned against what they were before
/// fuzzy matching existed. The keyword tier is checked as a set rather
/// than listed, so adding a reserved word to the lexer does not break a
/// test about completion.
#[test]
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `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
.iter()
.filter(|item| tier(item) != TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
assert_eq!(named, expected, "the names {typed:?} answers with");
let keywords: Vec<&str> = found
.iter()
.filter(|item| tier(item) == TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
let expected_keywords: Vec<&str> =
KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect();
assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with");
}
}
/// **The `isIncomplete` trap.** VS Code asks again on the next keystroke
/// only when the last answer said it was incomplete, so a complete
/// two-character answer would swallow the third keystroke and fuzzy would
/// never fire at all.
#[test]
fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() {
let (_tree, mut ws, uri) = typing("fuzzyincomplete");
for typed in ["", "c", "ce"] {
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else {
panic!("a completion list for {typed:?}");
};
assert!(list.is_incomplete, "{typed:?} must ask to be asked again");
}
// From the floor up the ordinary rule stands: complete when the whole
// hit set fit, which is sound because appending a character can only
// ever shrink it.
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else {
panic!("a completion list");
};
assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len());
}
/// A prefix match is the best subsequence match there is, and the list
/// says so — asserted on the order of the array, which is what the cap
/// cuts and what a client that does not re-rank shows.
#[test]
fn a_prefix_hit_outranks_a_scattered_one() {
let (_tree, mut ws, uri) = typing("fuzzyrank");
let found = items(after_typing(&mut ws, &uri, "clk"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(at("clk_osc_en_q") < at("c_l_k_scatter"), "the prefix hit leads: {:?}", labels(&found));
}
/// Scoring the boundaries is visible in the order, not only in the score:
/// a run that starts after an underscore beats the same letters buried
/// mid-word.
#[test]
fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() {
let tree = Tree::new("fuzzyboundary");
tree.write(
"ast.sv",
"module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "ena"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("osc_ena_ready") < at("xxenaxx_ready"),
"the boundary run leads: {:?}",
labels(&found)
);
drop(tree);
}
/// Dedup survives the change: a name two tiers can reach is offered once,
/// by the better tier, whichever way it was matched.
#[test]
fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() {
let tree = Tree::new("fuzzydedup");
// The same name, declared in this buffer (tier 1) and used in the
// project (tier 5), reachable from `clkenq` by neither prefix.
tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("= clkenq").expect("needle") + 8) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
found.iter().filter(|item| item.label == "clk_osc_en_q").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE));
drop(tree);
}
/// The tiers that did **not** go fuzzy, pinned so the split is a decision
/// and not a drift: keywords, templates and macro names still match by
/// prefix, and the module tier still matches by substring.
#[test]
fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() {
let tree = Tree::new("fuzzyunchanged");
tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n");
tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
// Mid-expression: the macro name is offered bare by tier 2 and must
// not be reachable by subsequence, and neither is a keyword.
let found = items(after_typing(&mut ws, &uri, "clkenq"));
assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found));
let found = items(after_typing(&mut ws, &uri, "alws"));
assert!(labels(&found).is_empty() || !labels(&found).contains(&"always"));
// A backtick still answers by prefix only.
let text = "module top;\n assign x = `CLKENQ\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way");
// …and the module tier is still a substring match, which is wider
// than a prefix and narrower than a subsequence.
let text = "module top;\n osc_en\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("osc_en").expect("needle") + 6) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect();
assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it");
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
fn a_declaration_in_scope_is_reached_by_subsequence() {
let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "clk_osc_en_q").expect("the declaration");
assert_eq!(tier(item), TIER_SCOPE);
assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;"));
}
/// The index tier goes fuzzy too — a package member is reached the same
/// way a project word is.
#[test]
fn a_project_declaration_is_reached_by_subsequence() {
let tree = Tree::new("fuzzyindex");
tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "CLK_OSC_EN_Q").expect("the package member");
assert_eq!(tier(item), TIER_INDEX);
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT));
drop(tree);
}
#[test]
fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() {
let tree = Tree::new("overlay");
let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n");
let top = "module top;\n assign x = ov\nendmodule\n";
let (_tree, mut ws, uri, position) = opened(tree, top, "= ov");
let other_uri = path_to_uri(&other).expect("uri");
ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string());
ws.rebuild_index();
let items = items(completions(&ws, &uri, position, true));
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
Loaded 100 of 1155 files, more files were not shown because too many files have changed in this diff. Show more