Compare commits

...
48 Commits
Author SHA1 Message Date
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
Guoliang ChenandClaude Mythos 5.2 88546c8b4e Release 0.65.1: releases are gated
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 5m5s
The release workflow runs tools/gates.sh (after ensuring the cached corpus)
before it builds anything, so a tag whose tree fails a gate publishes
nothing; until now only the branch push was checked, by a workflow the
release did not wait for. No product change: the packages are 0.65.0
rebuilt, plus the test-only import fix in 5c00b70.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:23 -07:00
lucioandClaude Fable 5.1 b9ee399ac6 TODO §65: stabilization round 1 — generate-label rename/references, LSP references fan-out to the pd_main tops, the doc-test stall
ci / checks (push) Successful in 1m39s
ci / corpus (push) Successful in 35s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-30 01:44:39 -07:00
884 changed files with 59847 additions and 7412 deletions

No files matched your search

+29 -2
View File
@@ -1,7 +1,11 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
# 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.
# 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:
@@ -41,3 +45,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: cargo test --workspace
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+19
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 —
@@ -14,6 +16,12 @@
# The release fails, deliberately, when the tag does not match the
# workspace version or CHANGELOG.md has no section for it: every release
# ships with real, written notes (see tools/RELEASING.md).
#
# It is gated: tools/gates.sh (fmt, clippy, every crate's suites, the doc
# tests, the corpus gate, the extension's node tests) runs first, and a red
# gate means nothing is built or published. The ci workflow runs on the
# branch push, not the tag, so without this step a tag published whatever
# it pointed at (0.65.0 went out while its ci run was still stuck).
name: release
on:
push:
@@ -25,6 +33,15 @@ jobs:
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
# The corpus is pinned-rev clones cached on the runner host, as in
# ci.yml; gates.sh skips its corpus step when the cache is absent, so
# fetch it here rather than release without that gate.
- name: Ensure the cached corpus
run: |
corpus="$HOME/.cache/lucisv-corpus"
[ -d "$corpus" ] || tools/corpus_fetch.sh "$corpus"
- name: Gate the release
run: tools/gates.sh
- name: Build release artifacts for every target
run: tools/release.sh --cross
- name: Audit the cross-built artifacts
@@ -52,3 +69,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
+868
View File
@@ -1,9 +1,875 @@
<!-- 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.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
No change to the formatter, the linter, the language server or the editor
extension: the packages are 0.65.0 rebuilt. What changed is how a release is
made (`tools/RELEASING.md`).
- **A tag no longer publishes unless every gate is green.** The release
workflow now runs `tools/gates.sh` — `cargo fmt`, `cargo clippy`, each
crate's test suites, the doc tests, the corpus gate and the extension's node
tests — before it builds anything, and a failing gate stops the release.
Until now only the branch push was checked, by a separate workflow the
release did not wait for, so 0.65.0 was published while its checks had not
finished.
- **The build is clean on Rust 1.100.** An unused import in the language
server's test module, which that toolchain's clippy rejects under
`-D warnings`, is gone. It is what turned 0.65.0's checks red after the
fact; the released binaries were never affected.
## 0.65.0 — 2026-11-19
### Module instantiation syntax highlighting
(`docs/features/instantiation-highlighting`; TODO §69.)
- **Every part of a module instantiation gets its own colour.** Module names,
instance names, `.PARAM` overrides, `.port` names and connected signals used
to collapse to the same default foreground colour whenever the instantiated
module lived in another file or a theme left bare semantic tokens unstyled.
The language server now layers AST-guided semantic token overrides (and
cross-file `ExternalResolutions` lookups) over the existing 14-type legend:
- **Module / interface names** (`uart_core`, `pkg::uart_core` with `pkg` as
`namespace`, and lone `bind` targets) highlight as `class`.
- **`#` and parameters share one colour** (`parameter`), distinct from `()`:
the `#` introducing a module, class, `extends`, instantiation or
parameterized-type parameter list, every `.PARAM` override (`.` and name),
and parameter values inside `#(...)` all carry `parameter`. Delay `#`
tokens (`#5`, `#(1:2:3)`) are left unemitted.
- **Instance names** (`u_uart`, gate instances, `bind` instance lists, and
hierarchical uses like `u_uart.sig`) highlight as `function`.
- **Port names** (`.clk_i` dot and name, implicit `.rst_ni`, and wildcard
`.*`), including unfinished entries being typed, highlight as `property`.
- **Port connections** (`clk`, `data_q`) stay `variable` so signals keep one
consistent colour across the file.
- **VS Code: semantic highlighting on by default with theme-safe scope maps.**
`configurationDefaults` enables `editor.semanticHighlighting.enabled` for
`[verilog]` and `[systemverilog]` (user settings still win), and
`contributes.semanticTokenScopes` maps the language's semantic token types to
distinct TextMate scopes so every role renders in colour across Dark+, Dark
Modern, Light+, GitHub Dark, One Dark Pro and Visual Studio Dark.
## 0.64.0 — 2026-11-17
### Completion that keeps up with typing
(`docs/features/completion-ux`, `docs/features/port-entry-grace`; TODO §68.)
- **`begin` + Enter writes the `end`.** The newline on-type answer, when
the line above ends in `begin` (or `begin : label`) and a block is still
open, also inserts `end` on the line after the new one, at the
indentation of the statement that owns the `begin`; the cursor stays on
the new, indented line. Nothing is added when the blocks already balance
(an `end` under the owner or under a `begin` on its own line counts), nor
for a `begin` left open inside an `ifdef` region that has an `else`.
Setting `lucisv.autoEnd` (default on). The VS Code extension sends the
request itself when `editor.formatOnType` is off.
- **`always_ff @(` and `always @(` expand with clock and reset**:
`posedge clk or negedge rst_n`, both names tab stops, as the ghost text
and as the first popup template. The clock-only forms follow.
- **This file's names rank first.** The popup's order is now: the scope at
the cursor, names declared anywhere in this buffer, words used in it,
then the workspace index, templates, keywords and project words.
- **Keyword ghosts.** Two or more letters of a keyword show the rest as
grey inline text (Tab accepts); with the popup open the ghost follows its
selected entry. A word that is exactly a name the buffer declares gets
none. A `.v` file is offered Verilog-2005 keywords only. Setting
`lucisv.inlineKeywords` (default on). The `begin` ghost now also appears
for a `begin` typed inside a block that already balances.
- **Port suggestions.** After `.` in an instance, unconnected ports come
first and already-connected ones follow, marked `connected`; they used to
be left out. Accepting a port inserts `name()` with the cursor inside,
pre-filled with a same-named signal when one is visible; parameter lists
(`#(.`) behave the same.
- **An unfinished connection stays in its own entry.** In the editor's
tolerant parse, a lone `.`, a `.name(` still open at the end of its line
and a trailing `,` are each recovered inside their entry — always with a
diagnostic — so the rest of the list and the file still parse, colour and
lint. Strict parsing, and so the formatter and the CLI, are unchanged.
- **Errors on the connection being typed wait.** Diagnostics that start
inside the entry the last edit touched, in a named-connection list of an
instance, are withheld and published after 1.5 s without typing, on an
edit elsewhere, or on save. A client that pulls diagnostics and supports
it is sent `workspace/diagnostic/refresh`. Nothing outside that entry is
ever withheld.
- **Changed: a trailing `,` in a named connection list (`.a(x),)`) is now
reported in the editor.** The formatter and the CLI always refused it;
the editor's tolerant parse used to accept it silently. Format Selection
elsewhere in such a file now works instead of refusing the whole file.
## 0.63.1 — 2026-11-11
### Sticky scroll shows every layer
(TODO §67.)
- **VS Code: sticky scroll pins the first line of every block you are
inside.** Only the module header used to stay at the top of the editor,
because sticky scroll follows the document outline by default and the
outline stops at declarations. The extension now defaults
`editor.stickyScroll.defaultModel` to `foldingProviderModel` for Verilog
and SystemVerilog, so the pinned lines come from the server's folding
ranges — the module, the `always`, the `case`, the case item, the `if` —
and raises `editor.stickyScroll.maxLineCount` to 10 for those languages
(VS Code's 5 fits exactly that example and nothing deeper). Your own
settings still win.
- Known limit: a layer without `begin` (a one-statement `if`, a case item
with no `begin`) has no fold and so no pinned line; a `begin` on its own
line pins that line, not the `always` above it.
- No engine change: the server, formatter and linter are 0.63.0's.
## 0.63.0 — 2026-11-09
### Format Selection that fits where it stands; comment toggling in VS Code
(`docs/features/selection-formatting`; TODO §66.)
- **Format Selection lays out only the block you selected.** Selecting an
`always` block, a `case` statement or a few statements used to re-lay the
whole enclosing module-level item — at the formatter's own depth, so a
block in a 4-space or tab-indented file moved, and the blank lines at the
selection's edges were eaten. The new engine
(`vlog_formatter::format_selection`) finds the smallest run of sibling
items or statements the selected lines cover, lays out that run alone and
puts it back starting at the leading whitespace it already has (tabs
kept). The parent is not touched. `textDocument/rangeFormatting`,
`rangesFormatting` and the on-type `;` all run on it.
- **A parse error elsewhere in the file no longer refuses the request.** The
selection is formatted when the error lies outside it, and refused only
when it lies inside.
- **How a selection picks its block.** Touching a block's first line takes
the whole block; a selection that starts inside it takes only the
statements it covers, even when it reaches the closing `end`; the `end`
line alone takes the block it closes. A selection of whole module-level
items behaves as before.
- **Still verified.** Every result passes the whole-file equivalence check
and a convergence replay, or the buffer is left unchanged; the verifier
itself is unchanged. CRLF files keep every line ending.
- The on-type `;` now tidies its statement in a buffer whose error is
elsewhere, and no longer adds a final newline to a file without one.
- The reply is still one whole-document edit; the CLI's `--lines` is
unchanged (whole module-level items).
- **VS Code: `Ctrl+/` toggles comments.** The extension now declares the
language's `//` and `/* */` comments, bracket pairs and auto-closing
pairs for Verilog and SystemVerilog, so Toggle Line Comment and Toggle
Block Comment work on one line or a selection.
## 0.62.0 — 2026-10-19
### Paths rooted at a top-level module; a dependable release gate
(`docs/features/top-rooted-paths`, `docs/features/release-gates`,
`docs/features/references-fanout-pd-main`.)
- **A hierarchical path that starts at a top-level module now resolves.**
`tb.dut.u_core.sig` written in a file that does not declare `tb` used to
stop at `tb`; now every segment is a reference — `find_references` and LSP
references list it, and a rename of `dut`, `u_core`, `sig` or a generate
label on the way rewrites the path. `$root.tb…` works; a local `tb`
shadows. The LSP's rename also reads the files of the path's root and the
modules it passes through. **Rooted only when lucisv can prove the head is
a top-level module**: not when the name could come from a wildcard import
(including `import uvm_pkg::*` with `uvm_pkg` outside the project), not
inside a class, not beside a macro that stands where a declaration could,
and not when the name is also a package or several modules share it —
those paths are left unchanged and warned about exactly as before. The
index cache format moves to 22, so a 0.61.0 cache is rebuilt once.
- An unresolved path through the renamed name is warned about once (it was
sometimes named twice).
- **Find All References across blocks is relative to the index scope, by
design.** On a default `folder` scope a module's references and rename
reach only the folders the index covers; the `lucisv.index.scope` setting
now says that a rename of a module instantiated outside the scope leaves
those instantiations unchanged (use `workspace`, or open the file first).
- **`tools/gates.sh`** is the release gate: fmt, clippy, the test build,
each crate's suites, the doc-tests, the corpus gate and the extension
tests, each a separately guarded step with its own log and a summary; a
step the guard kills is retried once and reported as `KILLED → retried`.
- **`tools/guard.sh` fixes:** its memory limit now sees every process in the
tree (a pid-list bug hid everything three or more levels down, so builds
and test-spawned servers were never capped), and a closed stdin no longer
makes the command silently not run.
## 0.61.0 — 2026-10-14
### Call hierarchy from anywhere, functions and tasks as nodes; full-line references in VS Code
(`docs/features/call-hierarchy-everywhere`, `docs/features/vscode-references-view`.)
- **`textDocument/prepareCallHierarchy` answers from any position in a
body.** It answered only on a module name, so Show Call Hierarchy was empty
almost everywhere. Now: an instance name prepares the instantiated module;
a function or task's declaration, call or end label prepares a
`Function`/`Method` item; a position inside a function or task body
prepares that function or task; one inside a module, interface or program
prepares the enclosing module. Module items answer exactly as before.
- **Functions and tasks are call-hierarchy nodes.** `incomingCalls` lists
every call site, grouped by the enclosing function or task (else the
module, interface, program, package or class), over the same files
`references` reads; `outgoingCalls` lists the resolved callees, skipping
system tasks and unresolved names. A function's own name read inside its
body (`clog2 = clog2 + 1`) is its result variable, not recursion. Calls
through `this.`, `super.`, a typed handle and an `import` resolve; virtual
dispatch and calls inside macro bodies are not modelled.
- **`textDocument/prepareTypeHierarchy`** answers the enclosing class
anywhere inside a class body, and the base class on `super`.
- **VS Code: Find All References with whole lines.** VS Code's references
pane starts each preview a few characters before the match. The extension's
new **References** view (lucisv sidebar) lists every reference's full line
with the identifier highlighted, grouped by file, the declaration marked;
`Shift+Alt+F12` opens it in Verilog/SystemVerilog editors while
`lucisv.references.fullLineView` is on (the default). Closed files are read
without opening them on the server.
### Review fixes and housekeeping
- The closing-label fallback of an unnamed block no longer attaches a
mismatched `end : a` (or an `endfunction : g` beside block `g`) to a
same-named block.
- `duplicate-declaration` reports sibling `for` generate blocks of one label,
and a procedural block beside a generate block in either order.
- Rename warnings: a comment between `.` and the name is still a path; a file
that fails to lex is warned about instead of skipped.
- Refactoring messages name a file by its path wherever another file shares
its base name (the `.*` expansion, ANSI conversion, inline and extract too).
- `lucisv_server`'s workspace state is split into seven modules (a pure
move); `tools/release.sh` refuses to build when the extension's
`package.json` / `package-lock.json` versions disagree with the binaries.
## 0.60.0 — 2026-10-08
### Rename and references through a generate block label
TODO §65.1, topo §2.9 row 43 (MCP-14). (`docs/features/generate-label-rename`.)
- **`rename` of a block label rewrites every path through it.** Renaming
`g_lane` in `for (…) begin : g_lane` used to rewrite the label alone,
leaving `g_lane[0].lane_q` (and `u_x.g_lane[1].sig` in another file)
naming a block that no longer existed, with no warning. The label, its
closing `end : g_lane`, and every path segment naming the block — bare,
indexed (`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), behind an instance
path from another file — are now one reference set, renamed all or
nothing; a spelling inside macro text or a string is a warning. A name
declared *inside* a block is likewise renamed through such a path. Named
procedural blocks: `begin : lbl`, `end : lbl` and `disable lbl;` (and the
`lbl: begin … end : lbl` form) are one set.
- **`find_references`** (LSP `textDocument/references`, `lucisv-mcp find
refs`) lists the declaration, the closing label and every segment, same
file and cross-file, with the declaring file open or closed.
- **`lucisv-mcp rename`** no longer refuses a `block`-kind declaration.
- Resolution changes every consumer sees: a `for` generate block's label is a
name of the enclosing module (its genvar is not); `generate … endgenerate`
is not a scope; `blk.x` and `arr[0].field` (a packed struct array) resolve
their tails; an unnamed `genblk1` still names nothing. The index cache
format moves to 21, so a 0.59.0 cache is rebuilt once.
- **A rename says so when a path it cannot resolve spells the name**: a
hierarchical path segment in any file of the rename's set that resolved to
no declaration (`tb.dut.gen_x[0].q`, rooted at a top module) is left
unchanged and warned about with its lines, for every kind of declaration;
and renaming a member one arm of a generate `if`/`case` declares warns
about the same-named member of the arm sharing its label.
- `duplicate-declaration` now also reports a block label beside a net,
variable, parameter or instance of the same name, and such a label is no
longer counted as a read of the net.
- Rename and port warnings name a file by its path whenever another file of
the set shares its base name (two `pwrmgr_if.sv` are two findable lines,
root-relative in `lucisv-mcp`), and a line a path warning names is not
repeated under `unresolved:`. Same-named members are warned about through
every enclosing same-label generate arm (`g.h.x`), and an escaped name's
unresolved paths are found too.
- **Rename warnings and mentions are about the renamed declaration.** For a
member of a module or interface (a net, variable, port, parameter, block,
…), a bare spelling of its name in a macro argument, a `` `define`` body, an
unstructured assertion, a comment or a string is reported only where it can
mean it: in the declaration's **home set** — the declaring file,
everything it `` `include``s, whatever includes it (transitively), and the
files the rename edits. In code, a spelling in the declaring file is
reported after a scope lookup finds the declaration there (an instantiating
module's own same-named signal is not); one in an included fragment always;
a `` `define`` body when the macro is invoked from the home set (through
other macros too — `ASSERT_DEFAULT_CLK`'s `clk_i`); a macro argument inside
a `bind` into the declaring module; and a bare use in the plain code of an
included fragment (`prim_util_memload.svh`'s `mem`) is named as a use the
rename could not edit. Reported wherever they are written: a dotted
spelling (`.state_q`, a possible hierarchical path); a bare macro argument
the macro carries to the declaration — after a `.` (`` `CONN(state_q)``
building `.state_q(state_q)`, `` `FORCE(state_q)`` building
`force u_m.state_q`), into a `bind` into the declaring module, or into a
macro lucisv has no definition of; and the body of a macro that expands to
such a `bind`. Not reported: a body whose spellings are only its own
parameter named like the declaration (unless the body also spells the name
after a `.`, or a default argument spells it), and a backtick inside a
string. Any doubt means no scoping: a module, interface, package or
package member, a declaration outside a module, or one whose home set holds
an include lucisv cannot resolve (a macro-built name, a file outside the
project such as `uvm_macros.svh`) is reported everywhere as before. On
opentitan the `state_q` rename's answer went from 274 lines (61 kB, 230
macro warnings, 229 about other modules) to about 72 lines (12 kB),
`hmac_core.StIdle`'s from 48 lines to 3.
- `duplicate-declaration` also reports a block label beside a port, genvar,
typedef, function or task, and two named procedural blocks of one label in
one scope.
- `lucisv-mcp rename` with many warnings is fast again: rooting the warning
paths was quadratic per warning (a `state_q` rename on opentitan: 125 s →
3.3 s). Naming the files in warnings no longer scans the whole set once per
file either: the engine's part of that rename went from 2.9 s to 2.2 s.
- A use in a file that includes the declaring file (or that it includes) is
no longer reported as "left unchanged" when the rename did rewrite it —
renaming a module whose instantiation sits in a file included beside it
said so wrongly.
## 0.59.0 — 2026-09-29
### MCP read-only mode
@@ -2595,3 +3461,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 -->
+42 -3
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.
@@ -84,11 +86,29 @@ now): largest files `tools/read.rs` 405, `tools/item.rs` 379, `tools/item/verify
`vlog_refactor/src/rename/connections.rs` at 477 and `check/mod.rs` at 426,
and `lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55).
Re-measured 2026-10-14 after TODO §55 (pure move, `docs/features/decomposition-state`):
`state/mod.rs` 63, the largest `state/` file `discover.rs` 412 (`rescan.rs` 411);
files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
`vlog_parser/src/lexer.rs` 771, `vlog_formatter/src/format/stmt.rs` 604.
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.
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
without a comment explaining why), `cargo test` green — all three
before declaring any work finished.
before declaring any work finished. **Before a release, and whenever
the whole workspace is gated, run `tools/gates.sh`** (every gate as a
separate guarded step with kept logs; `--only`/`--skip` for a subset)
instead of a bare `cargo test --workspace`.
- No `unwrap()`/`expect()`/`panic!` in library code paths; return
`Result`. Tests and `main.rs` argument handling may use them.
- Public items get a one-line doc comment. Doc comments say what/why,
@@ -131,6 +151,19 @@ Rules:
## Workflow
- **Agent models**: the lead plans and reviews; coding goes to one dev
agent and verification to one QA agent, **both Claude Opus 5.5**
(`model: "opus"`). This holds for a single lane and for each of two
parallel lanes.
- **Refactor lanes** (pure moves, decompositions): the dev is **Claude
Fable 5.2 at high reasoning effort** — the `refactor-dev` agent in
`.claude/agents/`. Its brief says: no new tests beyond what the move
forces, the gates are the proof, spend the effort on module
boundaries, naming and readability. QA is unchanged (Opus 5.5).
- **Escalation**: a first QA failure gets a normal Opus 5.5 fix round.
When a fix round fails QA a **second** time on the same feature, redo
the round with **Claude Fable 5.2 as both dev and QA**
(`model: "fable"`).
- Do **not** run `git commit` or `git push` — the lead reviews and
commits all work.
- Do not touch files outside your feature's stated scope. If you need a
@@ -155,6 +188,9 @@ process tree when its resident set or wall clock exceeds the limits
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
- The release gate is `tools/gates.sh`, which guards each step with its
own limits and retries a killed step once (shown as `KILLED → retried`);
do not wrap it in another `guard.sh`.
## Parallel lanes (the 2-agent loop)
@@ -176,8 +212,9 @@ proven independent and run serially. Rules for a parallel wave:
while lanes are in flight; the lead merges each lane back only after
that lane's QA verdict and lead review, and re-runs the full gates on
the merged tree before pushing.
- **Roles per lane are unchanged**: one dev (Opus), then one QA
(Sonnet) in the same worktree, then the lead's review — so at most
- **Roles per lane are unchanged**: one dev, then one QA — **both
Claude Opus 5.5** (owner, 2026-11-09; QA was Sonnet before) — in the
same worktree, then the lead's review — so at most
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
its own dev is done. A QA rework loops inside its lane without
blocking the other lane.
@@ -190,3 +227,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.59.0"
version = "0.66.2"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.59.0"
version = "0.66.2"
[[package]]
name = "lucisv_mcp"
version = "0.59.0"
version = "0.66.2"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.59.0"
version = "0.66.2"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.59.0"
version = "0.66.2"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.59.0"
version = "0.66.2"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.59.0"
version = "0.66.2"
[[package]]
name = "vlog_refactor"
version = "0.59.0"
version = "0.66.2"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.59.0"
version = "0.66.2"
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.59.0"
version = "0.66.2"
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
+69 -7
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.
@@ -144,6 +146,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 +178,20 @@ error (exit 2) and nothing is processed. Details:
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
with a file that sets only `line-length` uses both). `exclude` is the
exception: config patterns are *added* to `--exclude`, not replaced by it.
`[format] style` (flag `--style`, editor `lucisv.format.style`) picks one of
the [named styles](#named-styles). The style is resolved first and supplies
the starting indent and line length; an explicit `indent` or `line-length` —
from a flag or from the file — then wins over the preset's, so
`style = "microsoft"` with `indent = 2` is Microsoft's layout at 2 spaces. An
unknown style name is the same hard error as an unknown key, and lists the
valid names. In the editor, `lucisv.toml` outranks the editor settings as for
every formatting key, and a chosen style (other than `lucisv` or `auto`) also
outranks the editor's tab size.
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
off by default, indents the `` `uvm_field_* `` macros written between
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
formatting choice lucisv leaves to the project, because it changes bytes
in existing UVM code (21 of the 860 corpus files).
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; like `style`,
it is a formatting choice lucisv leaves to the project, because it changes
bytes in existing UVM code (21 of the 860 corpus files).
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
@@ -512,7 +526,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 +536,49 @@ configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
through verbatim
### Named styles
`[format] style`, `--style` and the editor's `lucisv.format.style` drop-down
pick one of a handful of house layouts. Every style moves whitespace only —
which line a token starts on and how many spaces precede it — so the same
token-equivalence check guards all of them, and each one is a fixed point of
itself (proved over the 860-file corpus and OpenTitan's 4 061 `hw/` files for
every preset; `docs/features/format-styles/README.md`).
| style | indent | width | `begin` | `else` after `end` | after `end : label` | header & connection lists | list indent | columns |
|---|---|---|---|---|---|---|---|---|
| `lucisv` (default) | 2 | 100 | same line | `end else` | `end : l else` | on one line if it fits | 1 level | kept where you wrote them |
| `google` | 2 | 100 | same line | `end else` | own line | one entry per line | 2 levels | kept where you wrote them |
| `lowrisc` | 2 | 100 | same line | `end else` | own line | one entry per line | 1 level | always aligned |
| `ansi` | 4 | 80 | own line | own line | own line | on one line if it fits | 1 level | kept where you wrote them |
| `microsoft` | 4 | 120 | own line | own line | own line | one entry per line | 1 level | kept where you wrote them |
| `nxp` | 2 | 80 | same line | own line | own line | one entry per line | 1 level | always aligned |
| `auto` | — | — | the preset the file is already closest to | | | | | |
`google` follows the [Google Verilog Style Guide](https://google.github.io/styleguide/verilogguide.html)
and `lowrisc` the [lowRISC Verilog Coding Style Guide](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md)
(OpenTitan's). **`ansi`, `microsoft` and `nxp` are lucisv's educated guesses**
at what those names suggest — C formatters' ANSI/Allman layout, clang-format's
`Microsoft` base style carried over to `begin`/`end`, a conservative RTL house
style — not rules those organisations publish; none of them publishes a Verilog
style that we could find. A `case` item's and a `do`'s `begin` stays on its
own line's end in every style. "Header & connection lists" are module
headers' parameter and port lists and instances' *named* overrides and
connections — not `#(16)`, ordered connections or function ports. `lowrisc`
differs from its guide in two places: the widest aligned connection keeps one
space before its `(`, and a comment line ends an aligned table.
`auto` formats the file once per preset, at the configured indent and width,
and keeps the output that changes the fewest lines (indentation included, so
a one-line edit does not flip a whole file to another preset); it never
guesses an indent or a width, and it is idempotent by construction.
**`auto` picks a layout for the configured indent and width; it never infers them — set `indent` to match the file first.** Because every re-indented line counts as changed, a file written at another indent is closest to whichever preset changes the fewest of its lines once they are all re-indented: a 4-space Allman file (formatted with `--style ansi`) run through `--style auto` at the default indent 2 comes out in the cuddled `lucisv` layout, while with `indent = 4` it stays Allman (and with `line-length = 80` as well, byte for byte). Under
`auto`, range and selection formatting use the style of the whole file, not
of the selected lines; the language server remembers each document's preset
from its last whole-file format, so a keystroke or a selection does not
search again, and a buffer with a parse error keeps its preset. One that has
never resolved — no memory, and it does not parse — gets the default layout.
### Alignment is inferred, not imposed
Hand-aligned columns are how RTL is read, so lucisv reads the spacing you
@@ -1037,11 +1095,13 @@ expected; no PRs or review required.
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
tools/gates.sh # every gate: fmt, clippy, build, each crate's suites, doc tests, corpus, node
tools/gates.sh --only suites # just the per-crate test suites
```
`tools/gates.sh` runs each gate as its own guarded step with a kept log and
prints a summary (`docs/features/release-gates/README.md`).
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
expected outputs only for intentional formatting changes with
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
@@ -1087,3 +1147,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 -->
+591 -2
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,
@@ -5084,11 +5086,14 @@ scope/widen logic, the document store, and the source selectors
(`module_sources`, `rename_sources`) are three sentences. Not planned; the
owner decides where it goes in loop 2.
- [ ] `state.rs` decomposition (pure move, byte-identical output, test
- [x] `state.rs` decomposition (pure move, byte-identical output, test
count unchanged); CLAUDE.md's measurement line refreshed —
**deferred to loop 3 by the lead, 2026-09-07** (958 lines at 0.49.0;
the measurement line already says so); a Fable refactor lane when
the owner schedules it
the owner schedules it — **done 2026-10-14**
(`docs/features/decomposition-state/README.md`: `state/` is ten
modules, largest 412 production lines; the CLAUDE.md measurement
line is the lead's, requested in that README's Handshakes)
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
@@ -6939,3 +6944,587 @@ Nothing else.
(23e2e4b, v0.55.0), CI green on the release commit, 8 assets, the
darwin-arm64 vsix at 0.55.0 with both binaries,
`hierarchySections.js`, `extract.js`, no `*_test.js`.
## 65. Stabilization round 1 (planned 2026-09-30, owner's order) — two correctness gaps, then the doc-test stall
Three lanes, one at a time on trunk, dev (Opus) → QA (Opus) → lead review →
commit. Rules as §63/§64: every suite and sweep through `tools/guard.sh`,
never piped (log to a file, check `guard exit` and the suite count); no
`sleep` over 60 s; never `grep` without a path; opentitan read-only (the
eval clone `~/.cache/lucisv-eval/ot` may be read and, for an edit test,
restored with `git -C … checkout -- <file>`). ~~Ships as 0.60.0.~~
**Release targets (corrected 2026-10-19):** 65.1 shipped in **0.60.0**
(2026-10-08); 65.2, 65.3 and 65.4 are open and target **0.62.0** (wave
below, §65.7); 65.6 is unscheduled.
### 65.1 Rename and references through a generate block label (topo §2.9-43, MCP-14)
`rename` of a generate block label (`for (…) begin : g_lane … end`) rewrites
the label and nothing else: a hierarchical path through it
(`g_lane[0].lane_q`, `u_x.g_lane[1].sig` from another file) keeps the old
name and no longer resolves, with no warning; `find_references` on the label
reports no use. The MCP layer refuses the rename (any `block`-kind
declaration); the LSP and the CLI still perform it. Feature README
`docs/features/generate-label-rename`.
The contract to reach, in `vlog_semantic` (resolution) and `vlog_refactor`
(`find_references`, `rename`, the verifier):
- [x] a path segment that names a generate block — bare (`g.x`), indexed
(`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), and behind an instance
path from another file (`u_x.g[0].x`) — resolves to the block's label
and is a reference to it
- [x] `find_references` on the label lists the declaration, the closing
`end : label` and every such segment, same-file and cross-file, through
the same fan-out §64.1 uses for hierarchical-surface declarations
- [x] `rename` rewrites all of them, all-or-nothing; a closing label is
rewritten with its opening one; a segment it cannot resolve (macro
text, a string) is a warning, as for any other declaration; an
unnamed block (`genblk1`) is not renameable
- [x] named procedural blocks (`begin : lbl` in `always`/`initial`/
functions/tasks): the label, its closing label and `disable lbl;` are
one reference set
- [x] the verifier accepts exactly these rewrites and nothing more:
masked-corruption attack tests for any normalization it gains
(CLAUDE.md invariant 4)
- [x] the LSP (`textDocument/references`, `rename`, `prepareRename`) and
the CLI get it through the engine; `lucisv-mcp`'s refusal of a
`block`-kind rename (`crates/lucisv_mcp/src/tools/edit.rs`) is lifted
and its tests (`tests/qa_m7.rs`) assert the rename instead
- [x] opentitan: a generate label with cross-file uses renamed on the eval
clone — every site rewritten, the files still parse, clone restored
- [x] rename warnings and mentions are scoped to the renamed declaration
(lead's inspection 2026-09-30: a module member's bare spelling
elsewhere is not news; a dotted one and a unit/package name's every
spelling still are)
- [x] QA: attack the index forms, nesting, shadowing (a net and a block of
the same name in different scopes), a label used only in a closing
label, `disable`, an escaped label, a label inside an `ifdef`
### 65.2 LSP `references` omits three `aes` instantiations (topo §2.9-36, MCP-6)
On opentitan, `textDocument/references` at the `aes` instantiation in
`hw/ip/aes/dv/tb/tb.sv` (and at its `.clk_i` connection) answers 11 and 9
locations; the whole-set engine answers 14 and 12 — the same plus the three
top-level instantiations in
`hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`
(`aes #(` and `.clk_i(clkmgr_clocks_i.clk_main_aes)`). Stable after a 30 s
settle, so not an indexing race. Feature README
`docs/features/references-fanout-pd-main`.
- [x] root cause named (the fan-out/scope selection in `lucisv_server` —
`module_select`, `state/` scope widening, or the index's
instantiation facts for those three files; they are large generated
files, check the 1 MiB cap and the word census)
- [x] ~~the LSP answer equals the whole-set engine's for the module name and
for a port of it, from the declaration and from a use; a regression
test with a fixture that reproduces the cause (not only opentitan)~~ — **closed by the owner's ruling 2026-10-19: scope-relative by design.** The LSP answer equals the engine over the same file set (pinned for both scopes in `server/tests/references_scope.rs`); the default `folder` scope does not reach the three tops, `workspace` does (14/12).
- [x] an opentitan test (ignored by default, like `tests/opentitan.rs`)
pinning the 14 and 12
- [x] ~~QA: the same comparison for five other modules instantiated from a
`*_pd_main.sv` top, and for `rename`'s fan-out (does rename see the
three sites?)~~ — not run: no production code changed under the ruling
### 65.3 The combined test command stalls entering the doc-tests
`cargo test --workspace` under `tools/guard.sh`: on 2026-09-29 (0.59.0 gate)
every suite finished in about two minutes and the run then sat 25 minutes
in `Doc-tests vlog_linter` until the guard cut it; on 2026-09-30 an
independent session's run hit its 600 s guard "entering the final doc-test
harness". `cargo test --workspace --doc` alone passes in under a minute.
- [x] reproduce (how often, which doc-test, what the stuck process tree
is — `rustdoc`, `rust_out`, stdin?) and name the cause; `guard.sh`
runs the command with `0<&3` — check what the doc-test harness
inherits as stdin when the gate runs in the background
- [x] fix at the cause (the harness, the doc-test, or the guard), and make
the release gate a script (`tools/gates.sh`) that runs fmt, clippy,
the test build, the suites, the doc-tests, the corpus gate and the
node tests as separate guarded steps with logs kept and a summary
that shows a kill — `tools/RELEASING.md` and CLAUDE.md point at it
- [x] ten consecutive green runs of the gate script recorded
### 65.4 Resolve a hierarchical path rooted at a top-level module name (lead to schedule; from §65.1 QA F1)
A path whose head is a top module declared in another file — `tb.dut.u_x.sig`,
the shape every opentitan DV `force`/`$deposit`/`uvm_hdl_*` path takes
(IEEE 1800 §23.6: a top-level module name is the root of a hierarchical
name) — resolves nothing today: `tb` is bound as a `Target::Lexical` use,
misses in the writing file, and `resolve::member_site`'s `head_site` stops
the spine, so no segment after it is a reference and a rename of `dut`'s
declarations leaves the path behind (since §65.1 with a warning, not
silently). The root lookup belongs in `vlog_semantic/src/resolve.rs`
`head_site`: when the lexical walk misses **and** the head is followed by a
`.`, answer `MemberSite::Unit { path: head, surface: Hierarchical }` so the
workspace's `fold_path` walks `tb` → `dut`'s type → … exactly as it walks an
instance path today — with the head itself recorded as a `Target::Module`-like
use so `tb` stops being `NotFound`. QA's repro: `vlog_refactor/tests/
qa_generate_label.rs` `a_path_rooted_at_another_files_top_module_is_never_silently_left_behind`
(`probe.sv`: `assign o = tb.dut.g_sw[0].buf_q;`), and on opentitan
`hw/ip/keymgr_dpe/dv/env/keymgr_dpe_if.sv:514,515,517` (`force
tb.dut.gen_sw_assigns[i]…`) under `rename gen_sw_assigns`. Watch: a name
that is both a local and a top module (the local wins), `$root.tb…`, and the
index cost of the extra external candidates on every DV path.
- [x] root lookup in `head_site`, the head recorded as a module use
- [x] QA's repro renames the path instead of warning; the §65.1 warning
still fires for a root the workspace does not declare
### 65.6 Rename inside included fragments (lead to schedule; from §65.1 QA final H4)
A module that `` `include``s a fragment of its own body (`prim_ram_1p.sv`
including `prim_util_memload.svh`, every opentitan `*_assert.svh`) has that
fragment's text pasted into its scope, but lucisv analyses the fragment as a
file of its own: a bare `mem` there resolves to nothing, so `rename
prim_ram_1p.mem` edits the module and — since §65.1 — only *warns*
(`prim_util_memload.svh:12,24,32,43: `mem` is used in a file `prim_ram_1p.sv`
includes and was left unchanged`). Renaming there means binding a fragment
in the scope of the file that includes it (the include site's scope chain as
the fragment's outer scope, as `fragment-mode` does for a bare body) and
verifying the edit against that binding; a fragment included from two
modules is two bindings and must agree or be refused. QA's repro:
`vlog_refactor/tests/qa_warning_scope.rs`
`a_bare_use_in_plain_included_code_is_renamed_or_said` (`m_body.svh`:
`assign o = state_q;` included by `m.sv`).
- [ ] a fragment included by exactly one unit is bound in that unit's scope
and renamed with it; one included by several is refused unless every
binding agrees
- [ ] QA's repro renames the fragment's use; the §65.1 warning remains for
what cannot be bound
### 65.7 Wave for 0.62.0 (planned 2026-10-19, owner's order: "fix those that are true")
Two parallel lanes first (disjoint files; neither touches `vlog_semantic`),
then 65.4 serially (it changes `vlog_semantic` resolution, which §65.2's
lane might also need — run after it merges).
**Lane A — §65.2 references fan-out** (Opus dev → QA → lead), files:
`crates/lucisv_server/src/state/sources.rs`, `crates/lucisv_server/src/nav.rs`,
new test files under `crates/lucisv_server/src/server/tests/`, a new
ignored-by-default `crates/lucisv_server/tests/opentitan_references.rs`,
`docs/features/references-fanout-pd-main/README.md`.
- [x] §65.2's checklist above (closed by ruling: scope-relative by design)
**Lane B — §65.3 gate script** (Opus dev → QA → lead), files:
`tools/gates.sh` (new), `tools/guard.sh` (only if the cause is there),
`tools/RELEASING.md`, `docs/features/release-gates/README.md` (new);
CLAUDE.md's pointer is the lead's at merge.
- [x] §65.3's checklist above
**Then — §65.4 top-module-rooted paths** (serial, after lane A merges).
- [x] §65.4's checklist above (conservative by the owner's ruling: a head with an import candidate, inside a class, or beside a macro that could declare it is not rooted)
### 65.8 Completion after a top-rooted path head (deferred from §65.4 H2, 2026-10-19)
`tb.` offers nothing in completion: the completion walk keeps "an unknown
head answers nothing" (two `lucisv_server` completion tests pin it), while
resolution now roots an unknown head at a top module. Decide whether
completion should offer `tb.`'s hierarchical members, answering `None` when
the index has no unit of that name. `docs/features/top-rooted-paths`.
- [ ] owner/lead decision; if yes, `completion/member.rs` + tests
## 66. Format Selection that fits where it stands (planned 2026-11-09, owner's order)
Owner's report: *Format Selection* "fails more than half of the time". The
usual selection is one whole `always` block or one whole `case` statement,
often nested inside blocks the selection does not cover. Reproduced on trunk
(`lucisv --lines`, the engine `textDocument/rangeFormatting` shares): selecting
a `case` re-lays the whole `always` around it; the block is re-indented to the
formatter's own depth × width, so in a file indented any other way it no
longer lines up with its neighbours; a selection inside `generate` re-lays the
whole region; and a file with a parse error anywhere is refused outright.
Owner's rule: do not worry about the parent — the selected block keeps the
indentation level it starts at, and stays functionally the same.
### 66.1 VS Code language configuration (lead, done 2026-11-09)
- [x] `editors/vscode/language-configuration.json` (comment tokens, brackets,
auto-closing and surrounding pairs) wired to both language ids in
`editors/vscode/package.json` — Toggle Line/Block Comment (Ctrl+/) works
without another Verilog extension installed.
### 66.2 Selection formatting (one lane: dev, then QA)
Feature README: `docs/features/selection-formatting/README.md`. Files:
`crates/vlog_formatter/src/selection.rs` (+ a `selection/` split if it nears
600 lines), `crates/vlog_formatter/src/{lib.rs,printer.rs,format/mod.rs}`,
`crates/vlog_formatter/tests/selection.rs`, `crates/lucisv_server/src/format.rs`,
`crates/lucisv_server/src/server/tests/formatting.rs`,
`crates/lucisv_server/tests/e2e.rs`. `verify.rs`, `range.rs`, `fence.rs`, the
parser and the CLI's `--lines` are not touched.
- [x] `format_selection`: the smallest run of sibling items/statements the
selected lines cover, laid out alone at the indentation it was written
at, spliced into otherwise untouched bytes.
- [x] Verified whole-file (`verify_equivalence`, unchanged) and converged by
replaying the located target, not the line numbers.
- [x] Fences outrank the selection; a module/package-level target defers to
`format_range` (header/footer splitting).
- [x] A file that does not parse: the target is located in the tolerant tree
and refused when a diagnostic falls inside it.
- [x] `textDocument/rangeFormatting` / `rangesFormatting` call it.
- [x] Tests: the owner's shapes (whole `always`, whole `case`, inside
`generate`, inside a function), off-grid and tab indentation, partial
selections, comments, fences, broken files, masked-corruption attacks on
the splice.
## 67. Sticky scroll shows every layer (planned 2026-11-11, owner's order)
VS Code pinned only the module header, because sticky scroll follows the
document-symbol outline by default and the outline stops at declarations.
The server's folding ranges already carry every `begin`/`end`, `case`,
`fork`, `generate` and function — one fold per layer, starting on its header
line.
- [x] `editors/vscode/package.json` `configurationDefaults` for both language
ids: `editor.stickyScroll.defaultModel` = `foldingProviderModel` and
`editor.stickyScroll.maxLineCount` = 10 (VS Code's default of 5 is the
owner's example exactly, with nothing to spare). A user's own setting
still wins.
- [x] `crates/lucisv_server/src/folding.rs`: a test pinning that each layer
of the owner's example (module, `always`, `case`, case item, `if`)
starts a fold on its header line.
- [ ] Seen in a running VS Code (owner).
- Known limit: a layer with no `begin` (a one-statement `if`, a case item
without `begin`) has no fold and so no pinned line; a `begin` written on
its own line pins that `begin` line, not the `always` above it.
## 68. Completion that keeps up with typing (planned 2026-11-17, owner's order)
Five asks from the owner, about the VS Code extension. Two serial lanes
(`lucisv_server` depends on `vlog_parser`, so they are not independent):
68.1 first, then 68.2. Each lane: one dev, then one QA, both Opus 5.5.
### 68.1 Lane A — auto-`end`, templates, ranking, keyword ghosts, port items
Feature README: `docs/features/completion-ux/README.md`. Files:
`crates/lucisv_server/src/{on_type.rs,inline.rs,templates.rs,pairs.rs,settings.rs,main.rs}`,
`crates/lucisv_server/src/completion/*`, new modules beside them where a
file is near 600 production lines, `crates/lucisv_server/tests/e2e.rs`,
`editors/vscode/{extension.js,package.json,smoke.js,README.md}` and a new
`editors/vscode/*_test.js` if the extension logic is factored out. No
parser, formatter, linter or semantic crate change.
- [x] **`begin` + Enter writes the `end`** (owner: "more like begin +
<return>, the cursor should be the next line of begin, at the correct
indentation, and ready for the first statement"). The newline on-type
answer, when the line above ends in `begin` (or `begin : label`) and
the file has an unclosed `begin`, also inserts `end` on the line after
the new one, at the indentation of the statement the `begin` belongs
to; the cursor stays on the new, indented line. No `end` when the
blocks already balance. Setting `lucisv.autoEnd` (default on). The
extension sends the request itself when `editor.formatOnType` is off
and puts the cursor back.
- [x] **`always_ff @(` / `always @(` expand with clock and reset**:
`posedge ${1:clk} or negedge ${2:rst_n}`, both tab stops, in the ghost
and as the first popup template; the clock-only form stays available
second.
- [x] **Names from the current file rank first** in the popup: declared
anywhere in this buffer, then words used in it, ahead of other files'
names and of keywords.
- [x] **Keyword ghosts**: a typed prefix of a keyword shows the rest of it
as grey inline text (Tab accepts), following the popup's selected item
when the popup is open. Setting `lucisv.inlineKeywords` (default on).
- [x] **Port items**: unconnected ports first; already-connected ports
listed after them, marked `connected` in the dimmed detail; accepting
a port writes `.name($1)` with the cursor inside the parentheses.
### 68.2 Lane B — no rushed errors on the connection being typed
Feature README: `docs/features/port-entry-grace/README.md`. Files:
`crates/vlog_parser/src/parser/instance.rs` (+ its tests),
`crates/lucisv_server/src/{diagnostics.rs,server/diagnostics.rs,state/*}`.
- [x] Parser recovery keeps an unfinished connection (`.`, `.name(` open to
the end of its line, a missing `,` before the next `.name`) inside its
own entry — still a diagnostic, never silent — so the rest of the file
parses, colours and lints as if the entry were complete.
- [x] The server withholds the diagnostics that fall inside the entry the
last edit touched, and releases them after a quiet period or when the
next edit lands elsewhere.
## 69. Module instantiation syntax highlighting (2026-11-17, owner's order)
Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
`crates/lucisv_server/src/{tokens.rs,tokens/instantiation.rs}`,
`editors/vscode/{package.json,.vscodeignore,semanticTokens_test.js}`,
`docs/features/{lucisv-server,large-file-mode}/README.md`.
- [x] Distinct semantic highlights across module instantiations (14-type wire
legend unchanged): module name (`class`), `#` + `.PARAM` overrides +
parameter values (`parameter`, distinct from `()`), instance name
(`function`), `.port`/`.*` (`property`), and port connections
(`variable`), including unfinished entries while typing.
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
non-white TextMate scopes across themes.
## 70. The tests pass on Linux, and one cleaning round (2026-11-19, owner's order)
Every suite had only ever run on macOS arm64; the Linux and Windows binaries
ship unexecuted. A `linux-x64` Actions runner now exists (`luhpe-linux-x64`,
a resource-capped Docker-in-Docker container on the Gitea host), and the
first trial of the suite in its job image found: clippy red on three unused
imports in `lucisv_server` test modules (their only users are tests compiled
on macOS/Windows alone), and 11 distinct failing tests out of ~5 300 — eight
that set up an unreadable/unwritable path and so cannot fail as root (the
job image's user), one that assumes a case-insensitive filesystem, two
`…_in_linear_time` timing assertions. No product failure among them as far
as the trial shows. One lane, `docs/features/linux-test-portability`;
`tools/linux_check.sh` runs the working tree in that image without a push.
- [x] `cargo clippy --all-targets -- -D warnings` clean on Linux and on
macOS (`crates/lucisv_server/src/hover.rs`, `includes.rs` test modules,
and whatever else the Linux build names).
- [x] The permission-denied tests (`crates/lucisv/tests/cli.rs`,
`crates/lucisv_core/src/walk.rs`, `crates/lucisv_mcp/src/apply.rs` and
`tests/cache.rs`, `tests/qa_m6.rs`, `crates/lucisv_server/src/state/tests/filelist.rs`)
pass both as root and as an unprivileged user: where the platform does
not enforce the permission the test says so and stops, it does not
assert the opposite.
- [x] `crates/lucisv_server/src/file_ops.rs`
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites`
holds on a case-sensitive filesystem or is scoped to the insensitive
ones, with the reason written at the test.
- [x] `crates/lucisv_server/src/large.rs` — the two `…_in_linear_time`
tests pass on the runner **and still fail when the conversion is
quadratic** (shown, not asserted).
- [x] The cleaning round: test code only, driven by what the tools report on
either platform — unused imports and dead helpers, platform assumptions
left implicit, assertions on wall-clock or environment that the runner
shows to be fragile. No test is deleted and the test count does not
drop; no production code and nothing in `verify.rs` changes.
- [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:
- [ ] A comment between a generate `end` and `else` (also a trailing `// c`
after a labelled generate `end` before `else`) is a verification
error: the file is left unformatted. The safety net works; the
formatter should not need it.
- [ ] `` `ifdef `` between `end` and `else` is a parse error.
- [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
- [x] The server's `line-length` lint falls back to 100 columns under the
`ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken
when 71.1 merges.
- [ ] One-per-line styles give multi-instance declarations
(`p1 u8 (...), u9 (...)`) the hanging layout.
- Wave 5 (lead, 2026-11-19): 71.1 shipped as 0.65.6 after a QA FAIL (four
stale answers), a fix round, a QA pass and a last small round. What the
QA rounds and a read-only investigation turned up, all present before this
wave, becomes lane **71.7** (the owner's Find References item, widened):
- [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.
- [ ] A watcher event naming only a directory leaves stale state; an
excluded buffer stays indexed after close; symlinked files are held
under one or both spellings depending on what was open.
71.3 (viewport highlighting) passed QA with a gap in the default folder
scope (colours wait out a widen, ~630 ms); it is rebased after 71.7 and
closes that in its fix round. Then 71.2.
- 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:
- [ ] 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.
- [ ] 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.
- [ ] Renaming a port of a module defined twice gives an edit or a refusal
at random (`qa717/drv/dup.py`).
- [ ] 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.
- §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:
- [ ] 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).
- [ ] `crates/lucisv/tests/cli.rs:2149` asserts only an empty stdout, no
exit code.
- [ ] `crates/lucisv_mcp/tests/qa_m3.rs` uses unix-only APIs with no cfg:
`cargo check --all-targets` for Windows fails there (tests only).
- [ ] The release is still gated on macOS alone; Windows is compile-checked
(`cross`), never executed.
- 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:
- [ ] 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`).
- [ ] A `range` answered during a rescan always counts as a guess and
costs one refresh at settle even when nothing changed.
- [ ] An edit in one file that changes how another OPEN file colours sends
no refresh (as before this lane).
- 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:
- [ ] 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).
- [ ] `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.
- [ ] 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).
- [ ] 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.
## 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 -->
+4
View File
@@ -1,3 +1,5 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv"
version.workspace = true
@@ -15,3 +17,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
+78 -7
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.
@@ -58,6 +60,8 @@ pub struct Options {
pub line_length: Option<usize>,
/// `--indent`, if given; otherwise the config file decides.
pub indent: Option<usize>,
/// `--style`, if given; otherwise the config file decides.
pub style: Option<&'static str>,
/// `--lines`: format only the constructs meeting these lines. `None` is a
/// whole-file run.
pub lines: Option<LineRanges>,
@@ -98,8 +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;
}
@@ -196,6 +205,12 @@ OPTIONS:
filelist, and neither reads nor writes the cache
--line-length <N> maximum line length (default 100)
--indent <N> indent width in spaces (default 2)
--style <NAME> layout preset: lucisv (the default), google,
lowrisc, ansi, microsoft or nxp. It sets the indent
and line length too; --indent/--line-length (or the
config file's keys) still win over the preset's.
`auto` lays each file out in the preset it is
already closest to, at the default indent/width
--no-config ignore lucisv.toml / .lucisv.toml files
-h, --help show this help
-V, --version show version
@@ -275,7 +290,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 +303,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 +352,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
exclude: Vec::new(),
line_length: None,
indent: None,
style: None,
lines: None,
output_format: OutputFormat::Text,
fix: false,
@@ -400,6 +418,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--indent requires a value")?;
opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?);
}
"--style" => {
let v = args.next().ok_or("--style requires a value")?;
opts.style = Some(config::parse_style(&v)?);
}
"--lines" => {
let v = args.next().ok_or("--lines requires a value")?;
line_specs.push(v);
@@ -526,6 +548,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::*;
use vlog_formatter::style;
fn parse(args: &[&str]) -> Result<Options, String> {
parse_from(args.iter().map(|s| s.to_string()))
@@ -568,6 +591,52 @@ mod tests {
assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width);
}
#[test]
fn a_style_sets_the_starting_values_and_explicit_ones_win() {
let none = FileConfig::default();
let opts = parse(&["--style", "microsoft", "rtl"]).unwrap();
let config = opts.config_with(&none);
assert_eq!(config.style, style::MICROSOFT);
assert_eq!((config.indent_width, config.max_width), (4, 120));
// The file's explicit keys beat the flag's preset...
let file = FileConfig { indent: Some(3), ..Default::default() };
assert_eq!(opts.config_with(&file).indent_width, 3);
assert_eq!(opts.config_with(&file).max_width, 120);
// ...and the flag beats the file's style.
let google = FileConfig { format_style: Some("google"), ..Default::default() };
assert_eq!(opts.config_with(&google).style, style::MICROSOFT);
let opts = parse(&["--indent", "2", "rtl"]).unwrap();
let config = opts.config_with(&google);
assert_eq!((config.style, config.indent_width), (style::GOOGLE, 2));
// No style anywhere is exactly the old default.
let config = parse(&["rtl"]).unwrap().config_with(&none);
assert_eq!(config.style, style::LUCISV);
}
#[test]
fn an_unknown_style_names_the_styles() {
let Err(message) = parse(&["--style", "allman", "rtl"]) else { panic!("accepted") };
assert!(message.contains("unknown style `allman`"), "{message}");
assert!(
message.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
"{message}"
);
assert!(parse(&["--style"]).is_err());
}
/// `lucisv_core` keeps its own copy of the names so it can reject a bad
/// `[format] style` without depending on the formatter; this is the test
/// that keeps the copy honest.
#[test]
fn the_core_style_names_are_the_formatter_presets() {
let mut names: Vec<&str> = style::names().collect();
names.push("auto");
assert_eq!(names, config::STYLE_NAMES);
for name in config::STYLE_NAMES {
assert_eq!(Config::named(name).map(|c| c.style_name()), Some(name));
}
}
#[test]
fn config_excludes_are_appended_to_cli_excludes() {
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
@@ -684,3 +753,5 @@ mod tests {
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
}
}
// 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
+4
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`,
@@ -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
+5
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`.
//!
@@ -338,6 +340,7 @@ fn entry_for(content: u64, config: &Config) -> Entry {
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
style: config.style_name(),
}
}
@@ -665,3 +668,5 @@ mod tests {
assert!(err.contains("parse error"), "{err}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+56 -12
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 {
@@ -1268,7 +1283,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 +1294,7 @@ fn cache_line(
version: &str,
) -> String {
let hash = lucisv_core::cache::content_hash(content.as_bytes());
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\tlucisv\t{version}\t{path}\n")
}
#[test]
@@ -1754,6 +1770,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 +1779,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")
}
@@ -2241,11 +2258,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 +2301,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 +2465,5 @@ fn text_that_merely_says_package_changes_no_finding() {
"{plain}\n---\n{with_noise}"
);
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+175
View File
@@ -0,0 +1,175 @@
// 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));
}
// 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
[package]
name = "lucisv_core"
version.workspace = true
@@ -10,3 +12,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
+80 -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,8 @@ use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use crate::config::STYLE_NAMES;
/// The default cache directory, resolved against the current directory.
pub const DEFAULT_DIR: &str = ".lucisv_cache";
@@ -35,6 +39,10 @@ pub struct Entry {
/// The `[format] uvm-utils-indent` that verdict was reached under: it
/// changes the output of a UVM class, so it is part of the key.
pub uvm_utils_indent: bool,
/// The `[format] style` that verdict was reached under, one of
/// [`crate::config::STYLE_NAMES`]: every preset lays files out
/// differently, so it is part of the key.
pub style: &'static str,
}
/// The cache for one run: loaded once at startup, written once at exit.
@@ -107,8 +115,8 @@ impl Cache {
let entry = &self.entries[path];
let _ = writeln!(
text,
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
"{:016x}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent, entry.style
);
}
text
@@ -154,28 +162,39 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize,
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
let mut entries = HashMap::new();
for line in text.lines() {
let fields: Vec<&str> = line.splitn(6, '\t').collect();
let fields: Vec<&str> = line.splitn(7, '\t').collect();
match fields[..] {
[content, line_length, indent, uvm, version, path] => {
[content, line_length, indent, uvm, style, version, path] => {
let (content, line_length, indent) = prefix(content, line_length, indent)?;
let uvm_utils_indent = uvm.parse().ok()?;
if path.is_empty() {
return None;
}
if version == VERSION {
// A style this build does not know is another build's
// entry: stale, not corrupt.
let known = STYLE_NAMES.into_iter().find(|n| *n == style);
if let (Some(style), true) = (known, version == VERSION) {
entries.insert(
path.to_string(),
Entry { content, line_length, indent, uvm_utils_indent },
Entry { content, line_length, indent, uvm_utils_indent, style },
);
}
}
// A store written before `uvm-utils-indent` joined the key: a
// well-formed line of that older shape says nothing about the
// option, so it is dropped individually, exactly like another
// version's entry. (The version field alone already makes such
// a store miss; the codec stays self-describing anyway.)
// Anything else on five fields is corruption and discards the
// file like any other malformed line.
// A store written before `style` joined the key: a well-formed
// line of that older shape says nothing about the style, so it is
// dropped individually, exactly like another version's entry.
[content, line_length, indent, uvm, _version, path] => {
prefix(content, line_length, indent)?;
uvm.parse::<bool>().ok()?;
if path.is_empty() {
return None;
}
}
// And the same for the shape before `uvm-utils-indent` joined it.
// (The version field alone already makes such a store miss; the
// codec stays self-describing anyway.) Anything else on five or
// six fields is corruption and discards the file like any other
// malformed line.
[content, line_length, indent, _version, path] => {
prefix(content, line_length, indent)?;
if path.is_empty() {
@@ -228,7 +247,7 @@ mod tests {
}
fn entry(content: u64) -> Entry {
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false, style: "lucisv" }
}
#[test]
@@ -262,6 +281,7 @@ mod tests {
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { style: "google", ..entry(0xdead) }));
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
}
@@ -276,7 +296,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 +311,7 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -308,6 +328,37 @@ mod tests {
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
}
#[test]
fn a_line_without_the_style_or_with_an_unknown_one_is_dropped_but_not_fatal() {
// The six-field shape lucisv wrote before `style` joined the key, and
// a style this build does not know: both stale, never corruption.
let dir = TempDir::new("nostyle");
let old = dir.file("old.sv");
let other = dir.file("other.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tbespoke\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tnxp\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
other.to_string_lossy(),
3,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&old, entry(1)), "a line without the style must not be trusted");
assert!(!cache.is_clean(&other, Entry { style: "lucisv", ..entry(2) }));
assert!(cache.is_clean(&mine, Entry { style: "nxp", ..entry(3) }));
assert!(!cache.is_clean(&mine, entry(3)), "the style is part of the key");
cache.store();
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
assert!(!dir.cache_text().contains("other.sv"), "{}", dir.cache_text());
}
#[test]
fn the_file_is_sorted_and_carries_the_version() {
let dir = TempDir::new("format");
@@ -325,7 +376,7 @@ mod tests {
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
assert_eq!(
lines[0],
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
format!("{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}", 1, a.to_string_lossy()),
"{text}"
);
}
@@ -350,13 +401,19 @@ mod tests {
"0000000000000001\t100\t2\t0.2.0\t\n",
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
"0000000000000001\t100\t2\tyes\tlucisv\t0.2.0\t/a.sv\n",
"0000000000000001\t100\twide\tfalse\tlucisv\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\tlucisv\t0.2.0\t\n",
"\0\0\0\n",
] {
let dir = TempDir::new("corrupt");
let file = dir.file("a.sv");
// A good line first: a bad one anywhere discards all of them.
let good =
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
let good = format!(
"{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
file.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
@@ -369,8 +426,8 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
"{:016x}\t100\t2\tfalse\tlucisv\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -484,3 +541,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
+60 -6
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`,
@@ -11,7 +13,14 @@ use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
/// Config file names, in the order a directory is probed.
const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
/// The names `[format] style` accepts: the formatter's presets, in its
/// `style::PRESETS` order, then `auto`. This crate knows no Verilog and so
/// does not depend on the formatter; the two lists are held equal by a test
/// in the `lucisv` crate, which sees both.
pub const STYLE_NAMES: [&str; 7] =
["lucisv", "google", "lowrisc", "ansi", "microsoft", "nxp", "auto"];
/// The settings one config file carries. Every key is optional; an unset
/// key leaves the CLI flag (or the built-in default) in charge.
@@ -34,6 +43,9 @@ pub struct FileConfig {
/// statements written between `` `uvm_*_utils_begin `` and
/// `` `uvm_*_utils_end ``. Off for the same reason.
pub format_uvm_utils_indent: Option<bool>,
/// `[format] style`: the named layout preset, one of [`STYLE_NAMES`].
/// Checked here, so a misspelt name fails the run like a misspelt key.
pub format_style: Option<&'static str>,
/// `[lint] select`: run exactly these rules, replacing the default set.
/// The names are **not** validated here — this crate does not know the
/// rule registry; `lucisv check` validates them the moment it resolves the
@@ -176,23 +188,30 @@ fn parse_entry(
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
uvm-utils-indent under `[format]`; \
style, uvm-utils-indent under `[format]`; \
select, ignore, waivers under `[lint]`; and a rule's own options \
under `[lint.<rule-name>]`)"
)),
}
}
/// One key of the `[format]` table: a boolean that defaults to off, because
/// it changes how already-clean files are laid out and a project has to opt
/// in before anything of its moves.
/// One key of the `[format]` table: the named `style`, or a boolean that
/// defaults to off, because it changes how already-clean files are laid out
/// and a project has to opt in before anything of its moves.
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
if key == "style" {
if config.format_style.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.format_style = Some(parse_style(&parse_string(value)?)?);
return Ok(());
}
let slot = match key {
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
_ => {
return Err(format!(
"unknown key `{key}` under `[format]` \
(the only key is uvm-utils-indent)"
(known keys: style, uvm-utils-indent)"
))
}
};
@@ -203,6 +222,13 @@ fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result
Ok(())
}
/// One of [`STYLE_NAMES`], exactly as spelt there.
pub fn parse_style(name: &str) -> Result<&'static str, String> {
STYLE_NAMES.into_iter().find(|n| *n == name).ok_or_else(|| {
format!("unknown style `{name}` (the styles are {})", STYLE_NAMES.join(", "))
})
}
/// `true` or `false`, and nothing else — a misspelling is a typo the user
/// wants to hear about, not a silent `false`.
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
@@ -614,6 +640,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.
@@ -937,3 +989,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
+4
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.
//!
@@ -591,3 +593,5 @@ missing.sv
assert_eq!(list.warnings.len(), 2, "{:?}", list.warnings);
}
}
// 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 parts of lucisv that decide *which* files are processed and *with what
//! settings*, shared by the `lucisv` CLI and the `lucisv-server` language server.
//!
@@ -20,3 +22,5 @@ pub mod config;
pub mod diff;
pub mod filelist;
pub mod walk;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+43
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`.
@@ -731,6 +733,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 +803,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 +853,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 +1105,5 @@ mod tests {
assert!(!tracker.has_conflict());
}
}
// 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
[package]
name = "lucisv_mcp"
version.workspace = true
@@ -21,3 +23,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
+258 -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,16 @@ 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,
/// 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 +180,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 +225,56 @@ 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() || self.clock_stepped_back(now) {
Change::Suspect
} else {
Change::Same
}
}
/// **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
/// at least [`RACY`] older than the moment the stamp was taken** —
/// otherwise a write inside the same timestamp tick, after the read,
/// leaves every one of them as it was. A timestamp that is missing, or
/// later than the read (a clock behind the filesystem's), is racy too.
fn racy(&self) -> bool {
let ctime = self.identity.map(|identity| identity.ctime);
[Some(self.mtime), ctime].into_iter().flatten().any(|stamped| match stamped {
Some(time) => time.checked_add(RACY).is_none_or(|settled| settled > self.read_at),
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, ..self }
}
}
/// Read one source file and stamp it. `Err` for a file that is gone or is
@@ -191,33 +284,43 @@ 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,
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 +376,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 +384,131 @@ 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,
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:?}");
}
}
}
// 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 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).
@@ -359,3 +361,5 @@ fn relative_to(roots: &[PathBuf], path: &Path) -> String {
#[cfg(test)]
mod tests;
// 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
+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.
@@ -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
+7 -1
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.
@@ -161,7 +163,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,
@@ -323,3 +327,5 @@ impl MentionOracle for Mentions<'_> {
PackageExports::exports(self.index, package)
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+56 -12
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.
@@ -45,10 +47,14 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
}
let set = whole_set(project, Some(&path), std::slice::from_ref(&name))?;
let edit = vlog_refactor::rename(&set.files, &path, declaration.offset, new_name)
.map_err(|why| set.rooted(project, &why))?;
.map_err(|why| set.rooted(&why))?;
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
let told = Told { name: &name, home: &path, unit: unit.as_deref() };
// A member of a module is named bare only where it is declared or used;
// the module (or interface, program) itself is named anywhere.
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
let member = unit.is_some() && !unit_itself;
let told = Told { name: &name, home: &path, unit: unit.as_deref(), member };
let done = write_telling(project, edit, &set, &told)?;
let (sites, files) = (render::count(sites, "site"), render::count(done.files, "file"));
let mut lines = vec![format!("renamed {sites} in {files}")];
@@ -62,6 +68,8 @@ struct Picked {
name: String,
path: PathBuf,
offset: u32,
/// The declaration's kind word (`module`, `var`, …).
kind: &'static str,
}
fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String> {
@@ -87,16 +95,9 @@ fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String>
[one] if one.is_macro() => {
Err(format!("`{name}` is a macro; lucisv does not rename macros."))
}
// The engine rewrites no hierarchical path through a block and
// reports none as a use, so the rename could not be complete
// (topo §2.9 MCP-14).
[one] if one.kind == "block" => Err(format!(
"`rename` does not rename generate block labels: paths through the block (`{}[0].…`) would not be rewritten; edit the file.",
names::qualified(name).1
)),
[one] => {
let name = names::qualified(name).1.to_string();
Ok(Picked { name, path: one.path.clone(), offset: one.offset })
Ok(Picked { name, path: one.path.clone(), offset: one.offset, kind: one.kind })
}
many => Err(names::ambiguous(name, many, "pass `file`, and `name@LINE` within one file")),
}
@@ -129,6 +130,10 @@ pub(super) struct Told<'a> {
pub name: &'a str,
pub home: &'a Path,
pub unit: Option<&'a str>,
/// Whether the name is a member of a module or interface: its bare
/// mentions outside its home set (`vlog_refactor::home_set`) are not
/// listed.
pub member: bool,
}
/// What a written edit says after its first line: how many files it wrote,
@@ -151,21 +156,58 @@ pub(super) fn write_telling(
let accounted: Vec<(PathBuf, Vec<TextRange>)> =
edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect();
let plan = Plan::from_refactor(edit, &set.files)?;
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(w)).collect();
let named = path_warned(&warnings);
let written = set.files.iter().map(|(path, text)| {
let change = plan.changes.iter().find(|change| &change.path == path);
(path.as_path(), change.map_or(text.as_str(), |change| change.after.as_str()))
});
let focus = Focus { name: told.name, home: told.home, unit: told.unit, accounted: &accounted };
// The member's home set (the declaring file, what it includes and what
// includes it, and the edited files): where a bare mention can mean it.
let edited: Vec<PathBuf> = plan.changes.iter().map(|change| change.path.clone()).collect();
// `None` — list every mention — for a non-member, and for a member whose
// home set is not known (an include the engine cannot resolve).
let local = match told.member {
true => vlog_refactor::home_set(&set.files, told.home, &edited),
false => None,
};
let focus = Focus {
name: told.name,
home: told.home,
unit: told.unit,
accounted: &accounted,
named: &named,
local: local.as_deref(),
};
let mentions = mentions::find(project, written, &focus);
let done = apply::run(project, &plan)?;
let mut tail = Vec::new();
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(project, w)).collect();
render::warnings(&mut tail, &warnings);
tail.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
tail.extend(mentions.block());
Ok(Done { files: done.changed.len() + done.created.len(), tail })
}
/// The `(file, line)` pairs the engine's unresolved-path warnings name
/// (`rtl/a.sv:3,7: a hierarchical path through …`), so the `unresolved:`
/// block does not list them a second time.
fn path_warned(warnings: &[String]) -> Vec<(String, u32)> {
let mut out = Vec::new();
for warning in warnings {
let Some((head, _)) = warning.split_once(": a hierarchical path through `") else {
continue;
};
let Some((file, lines)) = head.rsplit_once(':') else { continue };
out.extend(
lines
.split(',')
.filter_map(|line| line.parse().ok())
.map(|line| (file.to_string(), line)),
);
}
out
}
/// Where each of one file's edits lands in the text as written: its start
/// shifted by what the edits before it added or removed, its length the
/// new text's.
@@ -181,3 +223,5 @@ fn written_ranges(edits: &[TextEdit]) -> Vec<TextRange> {
}
out
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+39 -2
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
@@ -83,7 +85,7 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
account(&mut accounted, hits);
}
Err(why) => {
let why = engine_refusal(&set.rooted(project, &why));
let why = engine_refusal(&set.rooted(&why));
lines.push(format!(" uses not listed: {why}"));
}
}
@@ -93,13 +95,46 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
}
let home = &found[0].path;
let focus = Focus { name, home, unit: None, accounted: &accounted };
let local = member_files(&set, found, &accounted);
let focus = Focus {
name,
home,
unit: None,
accounted: &accounted,
named: &[],
local: local.as_deref(),
};
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
lines.extend(mentions::find(project, files, &focus).block());
lines.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
lines
}
/// The files a bare mention of a **module member** can mean it in — each
/// declaration's home set (`vlog_refactor::home_set`) with every file the
/// engine found a use in — or `None` when
/// any declaration is not a member (a unit, a package member, a macro), whose
/// every mention is listed (§65.1, lead's inspection: a `state_q` found in forty
/// modules is not news about this one).
fn member_files(
set: &WholeSet,
found: &[Declaration],
accounted: &[(PathBuf, Vec<TextRange>)],
) -> Option<Vec<PathBuf>> {
if found.iter().any(Declaration::is_macro) {
return None;
}
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
let mut local: Vec<PathBuf> = Vec::new();
for declaration in found {
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)?;
local.extend(vlog_refactor::home_set(&set.files, &declaration.path, &hit_files)?);
}
Some(local)
}
/// The engine's hits, one file per line: `file:12,40`.
fn uses(project: &Project, set: &WholeSet, hits: &[(PathBuf, TextRange)]) -> Vec<String> {
let mut sites: Vec<(String, u32)> = Vec::new();
@@ -164,3 +199,5 @@ mod tests {
}
}
}
// 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
//! `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`).
@@ -119,9 +121,10 @@ fn fixed_and_formatted(
}
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
/// `Options::config_with` with no command-line flags.
fn formatter_config(file: &FileConfig) -> Config {
let mut config = Config::default();
/// `Options::config_with` with no command-line flags: the style first, then
/// the explicit keys over the preset's indent and width.
pub(super) fn formatter_config(file: &FileConfig) -> Config {
let mut config = file.format_style.and_then(Config::named).unwrap_or_default();
if let Some(width) = file.line_length {
config.max_width = width;
}
@@ -195,3 +198,27 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
.iter()
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_formatter::style;
/// The MCP `format` tool resolves a `lucisv.toml` the way `lucisv` with no
/// flags does: the style first, the explicit keys over its numbers.
#[test]
fn the_style_comes_first_and_explicit_keys_win() {
let none = formatter_config(&FileConfig::default());
assert_eq!((none.style, none.indent_width, none.max_width), (style::LUCISV, 2, 100));
let ansi = FileConfig { format_style: Some("ansi"), ..Default::default() };
let config = formatter_config(&ansi);
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 4, 80));
let narrowed = FileConfig { indent: Some(2), line_length: Some(90), ..ansi };
let config = formatter_config(&narrowed);
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 2, 90));
let auto = FileConfig { format_style: Some("auto"), ..Default::default() };
assert!(formatter_config(&auto).auto_style);
}
}
// 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
//! 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.
@@ -100,3 +102,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
+4
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.
//!
@@ -260,3 +262,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
+24
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
@@ -52,6 +54,17 @@ pub struct Focus<'a> {
pub unit: Option<&'a str>,
/// Per file, the spans an engine returned (hits) or rewrote (edits).
pub accounted: &'a [(PathBuf, Vec<TextRange>)],
/// `(file, line)` pairs an engine warning already names — a `rename`'s
/// unresolved-path warning — which are not repeated as mentions.
pub named: &'a [(String, u32)],
/// For a member of a module or interface (a net, a port, a block, …):
/// the files where a bare spelling can mean it — its home set: the
/// declaring file, what it includes and what includes it, and the files
/// the edit wrote or the engine found uses in. Elsewhere only a
/// spelling right after a `.` (`".state_q"`, `` `HIER.u.state_q``) is
/// listed. `None` for a name any file may spell bare (a unit, a package
/// member): every mention is listed.
pub local: Option<&'a [PathBuf]>,
}
impl Mentions {
@@ -93,7 +106,13 @@ pub fn find<'t>(
let spans = accounted.map_or(&[][..], |(_, spans)| spans.as_slice());
let lines = LineIndex::new(text);
let mut last_line = 0;
let foreign = focus.local.is_some_and(|local| !local.iter().any(|p| p == path));
for (at, _) in spellings(text, focus.name) {
if foreign
&& !text.as_bytes().get((at as usize).wrapping_sub(1)).is_some_and(|&b| b == b'.')
{
continue;
}
let end = at + focus.name.len() as u32;
if spans.iter().any(|span| span.start <= at && end <= span.end) {
continue;
@@ -109,6 +128,9 @@ pub fn find<'t>(
.unwrap_or("");
let rank = rank(accounted.is_some(), focus.unit, source);
let mention = Mention { file: project.relative(path), line };
if focus.named.iter().any(|(file, at)| *file == mention.file && *at == line) {
continue;
}
found.push((rank, shared_components(path, focus.home), mention));
}
}
@@ -325,3 +347,5 @@ mod tests {
assert_eq!(shared_components(a, b), 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
//! 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
+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
@@ -232,3 +234,5 @@ mod tests {
assert_eq!(qualified(".x"), (None, ".x"));
}
}
// 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
+4
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(…)`.
@@ -446,3 +448,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
+10 -6
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
@@ -63,18 +65,18 @@ fn add_port(
) -> Result<Answer, String> {
let set = whole_set(project, None, &[module.to_string()])?;
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(module), declaration)
.map_err(|why| set.rooted(project, &why))?;
.map_err(|why| set.rooted(&why))?;
let tokens = vlog_parser::tokenize(declaration).unwrap_or_default();
let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default();
let show = &|path: &Path| project.relative(path);
let edit = match after.map(str::trim) {
Some(after) => {
let spec = place::Spec { module, file, after, port: &port, declaration, show };
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(project, &why))?
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(&why))?
}
None => edit,
};
let told = Told { name: &port, home: file, unit: Some(module) };
let told = Told { name: &port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("added port {port} in module {module}: {}", census(count, files));
@@ -89,9 +91,9 @@ fn remove_port(
) -> Result<Answer, String> {
let offset = port_offset(project, module, file, port)?;
let set = whole_set(project, Some(file), &[port.to_string(), module.to_string()])?;
let edit = vlog_refactor::remove_port(&set.files, file, offset)
.map_err(|why| set.rooted(project, &why))?;
let told = Told { name: port, home: file, unit: Some(module) };
let edit =
vlog_refactor::remove_port(&set.files, file, offset).map_err(|why| set.rooted(&why))?;
let told = Told { name: port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("removed port {port} in module {module}: {}", census(count, files));
@@ -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
+48 -12
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
@@ -76,6 +78,10 @@ pub struct WholeSet {
pub files: Vec<(PathBuf, String)>,
/// The files left out, with why.
pub skipped: Vec<(PathBuf, String)>,
/// How an engine sentence names each file of the set, and the
/// root-relative spelling it becomes — built once per set by
/// [`WholeSet::read`] ([`WholeSet::rooted`]).
names: Vec<(String, String)>,
}
impl WholeSet {
@@ -85,13 +91,14 @@ impl WholeSet {
pub fn read(project: &Project, extra: Option<&Path>) -> WholeSet {
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
wanted.extend(extra.map(Path::to_path_buf));
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped() };
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped(), names: Vec::new() };
for path in wanted {
match std::fs::read_to_string(&path) {
Ok(text) => set.files.push((path, text)),
Err(e) => set.skipped.push((path, format!("no longer reads: {e}"))),
}
}
set.names = names_of(project, &set.files);
set
}
@@ -105,18 +112,17 @@ impl WholeSet {
})
}
/// An engine sentence with each bare file name written root-relative
/// (`p1.sv:2` → `rtl/p1.sv:2`), where the name is the base name of
/// exactly one file of the set — the engines name files by base name,
/// and only an unambiguous one can be placed.
pub fn rooted(&self, project: &Project, sentence: &str) -> String {
/// An engine sentence with every file of the set written root-relative.
/// The engines name a file by its base name when that is unique in the
/// set they were handed (`p1.sv:2` → `rtl/p1.sv:2`) and by the path they
/// were given otherwise (`/abs/…/top_a/pwrmgr_if.sv:80` →
/// `top_a/…/pwrmgr_if.sv:80`, generate-label-rename R1). One pass over
/// the set's spellings per sentence; the table itself is built once.
pub fn rooted(&self, sentence: &str) -> String {
let mut out = sentence.to_string();
for (path, _) in &self.files {
let Some(base) = path.file_name().and_then(|name| name.to_str()) else { continue };
let same = self.files.iter().filter(|(other, _)| other.file_name() == path.file_name());
let shown = project.relative(path);
if same.count() == 1 && shown != base {
out = replace_file_name(&out, base, &shown);
for (spelled, shown) in &self.names {
if out.contains(spelled.as_str()) {
out = replace_file_name(&out, spelled, shown);
}
}
out
@@ -140,6 +146,34 @@ impl WholeSet {
}
}
/// Every file's engine spelling and its root-relative one: the full path for
/// a base name several files share, else the base name (skipped when it is
/// already the relative path). Full paths first, so a bare base name never
/// rewrites the tail of one.
fn names_of(project: &Project, files: &[(PathBuf, String)]) -> Vec<(String, String)> {
let mut count: HashMap<&std::ffi::OsStr, usize> = HashMap::new();
for (path, _) in files {
if let Some(base) = path.file_name() {
*count.entry(base).or_default() += 1;
}
}
let (mut full, mut bare) = (Vec::new(), Vec::new());
for (path, _) in files {
let Some(base) = path.file_name() else { continue };
let shown = project.relative(path);
match count.get(base) {
Some(1) => {
if let Some(base) = base.to_str().filter(|base| *base != shown) {
bare.push((base.to_string(), shown));
}
}
_ => full.push((path.display().to_string(), shown)),
}
}
full.extend(bare);
full
}
/// `text` with every occurrence of the file name `base` that stands alone —
/// not the tail of a longer path or name — replaced by `path`.
fn replace_file_name(text: &str, base: &str, path: &str) -> String {
@@ -239,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
+11 -2
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
@@ -544,8 +546,11 @@ const SM: &str = "module main_sm (\n input logic clk_i,\n output logic busy_o
const DV: &str = "module dv_x;\n logic a, b;\n assign a = `HIER.u_a[2].state_q;\n assign b = `HIER.u_a[2].state_q_d;\n assign b = `HIER.u_a[state_q].x;\nendmodule\n";
// Dotted spellings: `state_q` is a member of `main_sm`, so since §65.1's
// scoping of mentions a bare spelling in another file is not listed, and a
// path-like one (`.state_q`) still is — which keeps this CRLF check alive.
const CRLF: &str =
"module c;\r\n // one\r\n // state_q two\r\n string s = \"state_q\";\r\nendmodule\r\n";
"module c;\r\n // one\r\n // u.state_q two\r\n string s = \"u.state_q\";\r\n // state_q bare, not listed\r\nendmodule\r\n";
#[test]
fn qa_mentions_find_every_kind_and_only_whole_words() {
@@ -580,7 +585,9 @@ fn qa_mentions_find_every_kind_and_only_whole_words() {
#[test]
fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
let far: String = (0..60).map(|i| format!("// state_q far {i}\n")).collect::<String>()
// Path-like, so listed from a file that neither declares nor uses the
// member (§65.1's scoping of mentions drops a bare one there).
let far: String = (0..60).map(|i| format!("// u.state_q far {i}\n")).collect::<String>()
+ "module far; endmodule\n";
let files = [("rtl/sm.sv", SM), ("zz/far.sv", far.as_str())];
let (tree, mut server) = served(&files);
@@ -691,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
+11 -2
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
@@ -277,7 +279,10 @@ const MACRO_ARG: &[(&str, &str)] = &[
"top.sv",
"`include \"defs.svh\"\nmodule top (input logic clk);\n logic peek;\n core u_core0 (.clk, .q());\n assign peek = `ID(u_core0.state_q);\nendmodule\n",
),
("third.sv", "module third;\n // state_q is mentioned here\n initial $display(\"state_q\");\nendmodule\n"),
(
"third.sv",
"module third;\n // u_core0.state_q is mentioned here\n initial $display(\"u_core0.state_q\");\n // a bare state_q here is another module's word\nendmodule\n",
),
("m.sv", "module m (input logic a, output logic q);\n /* q */ assign q = a;\nendmodule\n"),
];
@@ -285,7 +290,9 @@ const MACRO_ARG: &[(&str, &str)] = &[
fn qa_uses_never_include_a_comment_a_string_or_macro_text() {
let scratch = Scratch::with(MACRO_ARG);
let mut s = Session::ready(&scratch);
// `third.sv` writes the word only in a comment and a string; `top.sv`
// `third.sv` writes the word only in a comment and a string (dotted —
// a bare spelling in a file that neither declares nor uses the member
// is not listed since §65.1's scoping of mentions); `top.sv`
// only inside a macro call's argument, which the engine does not follow:
// those are the unresolved mentions, never uses.
assert_eq!(
@@ -791,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
+13 -1
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
@@ -706,6 +708,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 +730,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);
@@ -1218,3 +1228,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
+77 -13
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
@@ -717,17 +719,19 @@ fn qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit() {
#[test]
fn qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind() {
// `find g_lane refs` lists no use and `rename` answers `renamed 1 site`,
// leaving `g_lane[0].lane_q` naming a block that no longer exists —
// while `edit_item delete g_lane` sees the use (`rtl/fsm.sv:19:18`).
// `find g_lane refs` used to list no use and `rename` answered `renamed
// 1 site`, leaving `g_lane[0].lane_q` naming a block that no longer
// existed — while `edit_item delete g_lane` saw the use
// (`rtl/fsm.sv:19:18`). Lead's ruling R1 had the MCP layer refuse the
// rename; TODO §65.1 fixed the engine (a path segment through a block is
// a reference to its label), and the refusal is lifted.
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
// Lead's ruling R1: the MCP layer refuses the rename, and the source
// is untouched.
let said = session(&tree, &[("rename", json!({"name": "g_lane", "new_name": "g_ln"}))]);
assert!(said[0].refused, "{}", said[0].text);
let why = &said[0].text;
assert!(why.starts_with("`rename` does not rename generate block labels"), "{why}");
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS);
let found = text(&tree, "find", json!({"name": "g_lane", "refs": true}));
assert_eq!(found, "block g_lane rtl/fsm.sv:12\n rtl/fsm.sv:19\n");
let renamed = text(&tree, "rename", json!({"name": "g_lane", "new_name": "g_ln"}));
assert_eq!(renamed, "renamed 2 sites in 1 file\n");
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS.replace("g_lane", "g_ln"));
assert!(tree.read("rtl/fsm.sv").contains("busy = tmp | g_ln[0].lane_q;"));
}
#[test]
@@ -747,10 +751,15 @@ fn qa_rework_a_shared_base_name_is_named_by_path_or_left_alone() {
assert_eq!(text(&tree, "rename", one), "renamed 2 sites in 1 file\n");
assert!(tree.read("rtl/y/p1.sv").contains("logic d2;"));
assert!(tree.read("rtl/x/p1.sv").contains("logic dup;"));
// The engine's sentences: `p1.sv` is two files, so it stays as said;
// `p1b.sv` is one, so it is named by its path.
// The engine's sentences: `p1.sv` is two files, so the engine names it by
// the path it was given and the answer makes that root-relative (§65.1
// re-check R1 — it used to stay a bare, unplaceable `p1.sv`); `p1b.sv`
// is one, so it is named by its path too.
let added = text(&tree, "port", json!({"module": "sub", "add": "input logic zz"}));
assert!(added.contains("`u_s` at p1.sv:4 connects with `.*` and p1.sv has"), "{added}");
assert!(
added.contains("`u_s` at rtl/y/p1.sv:4 connects with `.*` and rtl/y/p1.sv has"),
"{added}"
);
assert!(added.contains("(rtl/z/p1b.sv:3)"), "{added}");
assert!(!added.contains("rtl/z/rtl/"), "{added}");
}
@@ -807,3 +816,58 @@ fn qa_rework_an_escaped_local_outline_lists_is_found() {
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
assert_eq!(text(&tree, "find", json!({"name": "\\loc.v"})), "var \\loc.v rtl/g.sv:3\n");
}
#[test]
fn a_rename_names_each_same_named_file_by_its_root_relative_path_once() {
// §65.1 re-check R1 and the lead's fifth ruling: two `x_if.sv` holding an
// unresolved path through the label are two findable warning lines, and
// neither line is repeated under `unresolved:`.
let probe = "module probe_IDX (output logic o);\n assign o = tb.dut.g_sw.q;\nendmodule\n";
let (a, b) = (probe.replace("IDX", "a"), probe.replace("IDX", "b"));
let tree = Tree::with(&[
("rtl/dut.sv", "module dut_x;\n if (1) begin : g_sw\n logic q;\n end\nendmodule\n"),
("dv/a/x_if.sv", a.as_str()),
("dv/b/x_if.sv", b.as_str()),
]);
let said = text(&tree, "rename", json!({"name": "g_sw", "new_name": "g_hw"}));
let path_lines: Vec<&str> =
said.lines().filter(|line| line.contains("a hierarchical path through")).collect();
assert_eq!(path_lines.len(), 2, "{said}");
assert!(path_lines[0].starts_with("warning: dv/a/x_if.sv:2: "), "{said}");
assert!(path_lines[1].starts_with("warning: dv/b/x_if.sv:2: "), "{said}");
assert!(!said.contains("unresolved:"), "each line is said once: {said}");
assert!(tree.read("rtl/dut.sv").contains("begin : g_hw"));
}
#[test]
fn a_members_rename_lists_only_its_own_mentions_and_dotted_ones_elsewhere() {
// §65.1, lead's inspection: two modules each with a `state_q`, each
// spelling it in an `ASSERT argument, a comment and a string. Renaming
// `a`'s warns and lists only `a`'s — plus `b`'s dotted spellings, which
// may be paths to it. A package-level name still lists everything.
let defs = "`define ASSERT(n, e) n: assert property (e);\n";
let a = "module a (input logic clk);\n logic state_q;\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(A_T, state_q)\n // state_q is a's\n initial $display(\"state_q\");\nendmodule\n";
let b = "module b (input logic clk);\n logic state_q;\n a u_a (.clk);\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(B_T, state_q)\n `ASSERT(B_P, u_a.state_q)\n // state_q is b's\n initial $display(\"state_q\");\n initial $display(\"u_a.state_q\");\nendmodule\n";
let pkg = "package p;\n localparam int W = 1;\nendpackage\n";
let user = "module u import p::*;\n // W is p's\n localparam int X = W;\nendmodule\n";
let tree = Tree::with(&[
("rtl/defs.svh", defs),
("rtl/a.sv", a),
("rtl/b.sv", b),
("rtl/p.sv", pkg),
("rtl/u.sv", user),
]);
let said = text(&tree, "rename", json!({"name": "a.state_q", "new_name": "state_r"}));
let macro_lines: Vec<&str> = said.lines().filter(|l| l.contains("macro invocation")).collect();
assert_eq!(macro_lines.len(), 2, "{said}");
assert!(
macro_lines[0].contains("rtl/a.sv:4") && macro_lines[1].contains("rtl/b.sv:6"),
"{said}"
);
assert!(said.ends_with("unresolved:\n rtl/a.sv:4,5,6\n rtl/b.sv:6,9\n"), "{said}");
assert!(tree.read("rtl/b.sv").contains("logic state_q;"), "b's own stays");
let found = text(&tree, "find", json!({"name": "p.W", "refs": true}));
assert!(found.contains("unresolved:\n rtl/u.sv:2\n"), "a package member lists all: {found}");
}
// 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
+4
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,
@@ -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
+14 -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.
@@ -795,7 +797,13 @@ fn rename_lists_the_old_names_unresolved_mentions() {
text.contains("\nwarning: `state_q` appears in the body of macro `SM_STATE`"),
"{text}"
);
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4,6\n"), "{text}");
// Line 6 is `tb.…state_q`, a path nothing resolves: the engine's own
// warning names it (§65.1 F1), so it is not repeated as a mention.
assert!(
text.contains("\nwarning: dv/probe_if.sv:6: a hierarchical path through `state_q`"),
"{text}"
);
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4\n"), "{text}");
// The hierarchical use in core.sv is renamed, so it is not a mention;
// the text the block names is left as it was.
assert!(read(&tree, "rtl/core.sv").contains("u_main_sm.main_state_q"));
@@ -894,12 +902,13 @@ fn engine_sentences_name_files_root_relative() {
assert_eq!(before, snapshot(&tree));
let added = server.text("port", json!({"module": "spare", "add": "input logic en"}));
assert!(added.contains("at `u_s` (rtl/spare_user.sv:5)"), "{added}");
// A base name two files share cannot be placed: left as the engine said.
// A base name two files share: the engine names it by its path (§65.1
// re-check R1), which the answer makes root-relative like any other.
let (tree, mut server) = served("edit");
fs::create_dir_all(tree.path("alt")).unwrap();
fs::write(tree.path("alt/cell.sv"), "module cell2; endmodule\n").unwrap();
let twice = refusal(&mut server, "port", json!({"module": "cell", "remove": "en"}));
assert!(twice.contains("inside `cell` at cell.sv:6"), "{twice}");
assert!(twice.contains("inside `cell` at rtl/cell.sv:6"), "{twice}");
}
#[test]
@@ -1257,3 +1266,5 @@ 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");
}
// 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
[package]
name = "lucisv_server"
version.workspace = true
@@ -19,3 +21,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
+408
View File
@@ -0,0 +1,408 @@
// 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),
},
};
Config { style: preset, auto_style: false, ..config }
}
/// Whether nothing is remembered yet.
#[cfg(test)]
pub fn is_empty(&self) -> bool {
self.recent.is_empty()
}
/// Forget what a notification may have made stale: the document a
/// `didOpen`/`didClose` names, the old and new names of a renamed file,
/// a deleted file, and every document when a watched-file event names a
/// `lucisv.toml` or `.lucisv.toml`. Anything else is ignored.
pub fn notice(&mut self, notification: &Notification) {
let params = || notification.params.clone();
match notification.method.as_str() {
DidOpenTextDocument::METHOD => {
if let Ok(p) = serde_json::from_value::<DidOpenTextDocumentParams>(params()) {
self.forget(&p.text_document.uri);
}
}
DidCloseTextDocument::METHOD => {
if let Ok(p) = serde_json::from_value::<DidCloseTextDocumentParams>(params()) {
self.forget(&p.text_document.uri);
}
}
DidRenameFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<RenameFilesParams>(params()) {
self.forget_named(p.files.iter().flat_map(|f| [&f.old_uri, &f.new_uri]));
}
}
DidDeleteFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<DeleteFilesParams>(params()) {
self.forget_named(p.files.iter().map(|f| &f.uri));
}
}
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<DidChangeWatchedFilesParams>(params()) {
if p.changes.iter().any(|c| names_a_config(c.uri.as_str())) {
self.forget_all();
}
}
}
_ => {}
}
}
/// Mark `uri`'s entry replaced when a `didChange` replaced its whole
/// text: a change with no range (full sync), or one that starts at the
/// top and leaves nothing of the old text after it — `result` is exactly
/// its text.
pub fn changed(&mut self, uri: &Uri, changes: &[TextDocumentContentChangeEvent], result: &str) {
let rangeless = changes.iter().any(|c| c.range.is_none());
let from_the_top = changes.last().is_some_and(|c| {
c.range.is_some_and(|r| r.start.line == 0 && r.start.character == 0) && c.text == result
});
if rangeless || from_the_top {
if let Some(entry) = self.recent.iter_mut().find(|e| e.uri == *uri) {
entry.replaced = true;
}
}
}
/// Forget every document: the settings, or a `lucisv.toml`, changed.
pub fn forget_all(&mut self) {
self.recent.clear();
}
fn forget(&mut self, uri: &Uri) {
self.recent.retain(|e| e.uri != *uri);
}
fn forget_named<'a>(&mut self, uris: impl Iterator<Item = &'a String>) {
for uri in uris {
self.recent.retain(|e| e.uri.as_str() != uri);
}
}
/// The remembered preset, and whether it has been marked replaced.
fn recall(&self, uri: &Uri) -> Option<(Style, bool)> {
self.recent.iter().find(|e| e.uri == *uri).map(|e| (e.preset, e.replaced))
}
fn remember(&mut self, uri: &Uri, preset: Style) {
self.forget(uri);
if self.recent.len() == CAPACITY {
self.recent.pop_front();
}
self.recent.push_back(Entry { uri: uri.clone(), preset, replaced: false });
}
}
/// Whether a URI names a config file: `lucisv.toml` or `.lucisv.toml`.
fn names_a_config(uri: &str) -> bool {
let name = uri.rsplit('/').next().unwrap_or(uri);
lucisv_core::config::NAMES.contains(&name)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::Workspace;
use std::str::FromStr;
/// A google-formatted module: one port per line at a 4-space list indent.
const GOOGLE: &str = "\
module m (
input logic a,
output logic b
);
sub u_sub (
.a(a),
.b(b)
);
endmodule
";
fn open(text: &str) -> (Workspace, Uri) {
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
(ws, uri)
}
fn auto() -> Config {
Config::named("auto").expect("auto")
}
#[test]
fn a_whole_document_format_remembers_the_preset_it_used() {
let (ws, uri) = open(GOOGLE);
let mut styles = AutoStyles::default();
let doc = ws.document(&uri).expect("open");
assert_eq!(styles.format_document(&uri, doc, &auto()), Ok(None), "already formatted");
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)));
let concrete = styles.concrete(&uri, doc, auto());
assert_eq!((concrete.style, concrete.auto_style), (style::GOOGLE, false));
}
#[test]
fn a_named_style_is_left_alone_and_nothing_is_remembered() {
let (ws, uri) = open(GOOGLE);
let mut styles = AutoStyles::default();
let doc = ws.document(&uri).expect("open");
let ansi = Config::styled(style::ANSI);
assert_eq!(styles.concrete(&uri, doc, ansi.clone()).style, style::ANSI);
assert!(styles.format_document(&uri, doc, &ansi).is_ok());
assert_eq!(styles.recall(&uri), None);
}
/// The memory is what lets a half-typed buffer keep its file's preset:
/// without it, a buffer that does not parse gets the default's layout.
#[test]
fn a_buffer_that_does_not_parse_uses_the_remembered_preset() {
let broken = GOOGLE.replace("endmodule", " assign x = ;\nendmodule");
let (ws, uri) = open(&broken);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "no memory, no parse");
assert_eq!(styles.recall(&uri), None, "and a fallback is not remembered");
styles.remember(&uri, style::GOOGLE);
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
}
#[test]
fn without_a_memory_a_buffer_that_parses_resolves_once() {
let (ws, uri) = open(GOOGLE);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)), "resolved, then remembered");
}
#[test]
fn the_memory_is_bounded_and_keeps_the_most_recent() {
let mut styles = AutoStyles::default();
let uri = |n: usize| Uri::from_str(&format!("file:///rtl/m{n}.sv")).expect("uri");
for n in 0..CAPACITY + 10 {
styles.remember(&uri(n), style::NXP);
}
assert_eq!(styles.recent.len(), CAPACITY);
assert_eq!(styles.recall(&uri(0)), None, "the oldest is forgotten");
assert_eq!(styles.recall(&uri(CAPACITY + 9)), Some((style::NXP, false)));
// Remembering again moves a document to the back and replaces its preset.
styles.remember(&uri(10), style::ANSI);
styles.remember(&uri(10), style::GOOGLE);
assert_eq!(styles.recall(&uri(10)), Some((style::GOOGLE, false)));
assert_eq!(styles.recent.len(), CAPACITY);
}
fn notification(method: &str, params: serde_json::Value) -> Notification {
Notification { method: method.to_string(), params }
}
#[test]
fn open_close_rename_and_delete_forget_the_document() {
let mut styles = AutoStyles::default();
let (a, b) = (
Uri::from_str("file:///rtl/a.sv").expect("uri"),
Uri::from_str("file:///rtl/b.sv").expect("uri"),
);
let doc = |uri: &Uri| {
serde_json::json!({ "textDocument": {
"uri": uri, "languageId": "systemverilog", "version": 1, "text": "" } })
};
for method in [DidOpenTextDocument::METHOD, DidCloseTextDocument::METHOD] {
styles.remember(&a, style::GOOGLE);
styles.notice(&notification(method, doc(&a)));
assert_eq!(styles.recall(&a), None, "{method}");
}
styles.remember(&a, style::GOOGLE);
styles.remember(&b, style::NXP);
styles.notice(&notification(
DidRenameFiles::METHOD,
serde_json::json!({ "files": [{ "oldUri": a.as_str(), "newUri": b.as_str() }] }),
));
assert!(styles.is_empty(), "both names of a renamed file are forgotten");
styles.remember(&a, style::GOOGLE);
styles.notice(&notification(
DidDeleteFiles::METHOD,
serde_json::json!({ "files": [{ "uri": a.as_str() }] }),
));
assert_eq!(styles.recall(&a), None);
}
#[test]
fn a_config_file_change_or_a_settings_change_forgets_everything() {
let mut styles = AutoStyles::default();
let a = Uri::from_str("file:///rtl/a.sv").expect("uri");
let watched = |name: &str| {
notification(
DidChangeWatchedFiles::METHOD,
serde_json::json!({ "changes": [{ "uri": format!("file:///rtl/{name}"), "type": 2 }] }),
)
};
styles.remember(&a, style::GOOGLE);
styles.notice(&watched("other.sv"));
assert!(!styles.is_empty(), "a source file changing on disk says nothing about presets");
for name in ["lucisv.toml", ".lucisv.toml"] {
styles.remember(&a, style::GOOGLE);
styles.notice(&watched(name));
assert!(styles.is_empty(), "{name}");
}
styles.remember(&a, style::GOOGLE);
styles.forget_all();
assert!(styles.is_empty());
}
/// A whole-buffer change makes the entry a fallback: the next request
/// resolves from the new text if it parses, and keeps the old preset
/// only if it does not. A partial edit leaves the entry alone.
#[test]
fn a_whole_buffer_replacement_resolves_again_when_it_can() {
let lucisv =
"module m (input logic a, output logic b);\n sub u_sub (.a(a), .b(b));\nendmodule\n";
let (ws, uri) = open(lucisv);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
styles.remember(&uri, style::GOOGLE);
let edit: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({
"range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 2 } },
"text": " " })).expect("change");
styles.changed(&uri, &[edit], lucisv);
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE, "a partial edit");
let whole: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({ "text": lucisv })).expect("change");
styles.changed(&uri, std::slice::from_ref(&whole), lucisv);
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, true)));
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "resolved afresh");
assert_eq!(styles.recall(&uri), Some((style::LUCISV, false)));
// A full range from the top counts as a whole replacement too.
let ranged: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 3, "character": 0 } },
"text": lucisv })).expect("change");
styles.changed(&uri, &[ranged], lucisv);
assert_eq!(styles.recall(&uri), Some((style::LUCISV, true)));
}
#[test]
fn a_named_style_request_forgets_the_document() {
let (ws, uri) = open(GOOGLE);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
styles.remember(&uri, style::GOOGLE);
styles.concrete(&uri, doc, Config::styled(style::LUCISV));
assert_eq!(styles.recall(&uri), None, "a range under a named style");
styles.remember(&uri, style::GOOGLE);
let _ = styles.format_document(&uri, doc, &Config::styled(style::LUCISV));
assert_eq!(styles.recall(&uri), None, "a whole-document format under a named style");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+109 -9
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
@@ -197,17 +199,86 @@ impl Candidates {
/// patched: this file's old words are given back and its new ones taken,
/// so nothing else is re-lexed. The result is what a whole
/// [`Candidates::build`] over the same files would have produced.
#[cfg(test)]
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
self.update_words(index, path, words_in(text));
}
/// [`Candidates::update_file`] for a file whose words the caller already
/// has — an open buffer's, read off the tokens it was analyzed from.
#[cfg(test)]
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
self.take_index_tables(index);
self.set_words(path, words);
}
/// [`Candidates::update_words`] in two halves, for a caller that knows
/// which it needs: the word table patched by this file alone…
pub fn set_file_words(&mut self, path: &Path, words: Vec<String>) {
self.set_words(path, words);
}
/// …and the two index-derived tables re-derived for the names one file declared
/// before or declares now — `symbols` its units and connection members,
/// `macros` its `` `define``s ([`FileFacts::declared_names`]) — which are
/// the only entries its update can move.
///
/// Exact because every table here is one block per exact name ([`word_cmp`]
/// is total, so equal keys are equal names) and each block is read off
/// the index for that name alone: the unit block from the symbol listing
/// restricted to the name, in the listing's order and deduplicated the
/// same way; a module name present exactly when some unit of it is
/// instantiable; a macro's entry from its first definition in file order.
/// So a block re-derived here is the block a whole re-derivation gives,
/// and every other block is untouched by an update that does not name it.
///
/// [`FileFacts::declared_names`]: vlog_semantic::FileFacts::declared_names
pub fn refresh_names(
&mut self,
index: &WorkspaceIndex,
symbols: &HashSet<&str>,
macros: &HashSet<&str>,
) {
let (fresh, _) = unit_tables(index, index.symbols_named(symbols));
let mut held = std::mem::take(&mut self.units);
held.retain(|unit| !symbols.contains(unit.name.as_str()));
self.units = merge_by_name(held, fresh, |unit| unit.name.as_str());
self.unit_masks = self.units.iter().map(|unit| char_mask(&unit.name)).collect();
for name in symbols {
let instantiable = index.units(name).iter().any(|def| def.kind.is_instantiable());
match (self.modules.binary_search_by(|held| held.as_str().cmp(name)), instantiable) {
(Ok(at), false) => {
self.modules.remove(at);
}
(Err(at), true) => self.modules.insert(at, name.to_string()),
_ => {}
}
}
let mut fresh: Vec<Macro> = macros
.iter()
.filter_map(|name| index.find_define(name).first().map(|(_, define)| macro_of(define)))
.collect();
sort_by_name(&mut fresh, |m| m.name.as_str());
let mut held = std::mem::take(&mut self.macros);
held.retain(|m| !macros.contains(m.name.as_str()));
self.macros = merge_by_name(held, fresh, |m| m.name.as_str());
}
/// Every table, rendered for comparison — the equivalence witness the
/// incremental tests hold an updated workspace to a rebuilt one with.
#[cfg(test)]
pub fn fingerprint(&self) -> String {
let mut word_files: Vec<(&String, &usize)> = self.word_files.iter().collect();
word_files.sort();
let mut per_file: Vec<(&PathBuf, &Vec<String>)> = self.per_file.iter().collect();
per_file.sort();
format!(
"units {:?}\nunit_masks {:?}\nmodules {:?}\nmacros {:?}\nwords {:?}\n\
word_masks {:?}\nword_files {word_files:?}\nper_file {per_file:?}\n",
self.units, self.unit_masks, self.modules, self.macros, self.words, self.word_masks
)
}
/// [`Candidates::update_words`] for a batch of files — the form a scan
/// publishing what it has indexed so far uses.
///
@@ -715,7 +786,15 @@ fn char_mask(text: &str) -> u32 {
/// tables want the same records. It is paid once per index build rather than
/// once per keystroke, which is the whole point of both.
fn index_tables(index: &WorkspaceIndex) -> (Vec<Candidate>, Vec<String>) {
let symbols = index.workspace_symbols("");
unit_tables(index, index.workspace_symbols(""))
}
/// [`index_tables`] over a given part of the symbol listing — all of it, or
/// the names one update touched — in the listing's own order.
fn unit_tables(
index: &WorkspaceIndex,
symbols: Vec<vlog_semantic::WorkspaceSymbol<'_>>,
) -> (Vec<Candidate>, Vec<String>) {
// `workspace_symbols` sorts by name first — with `str`'s own `Ord`, not a
// case-folded one — so same-named declarations are already adjacent and a
// plain `dedup` leaves one entry per module name, in `str` order. That is
@@ -757,14 +836,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
for id in 0..index.files().len() {
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
out.push(Macro {
name: define.name.clone(),
detail: format!("`define {}{args}", define.name),
});
out.push(macro_of(define));
}
}
sort_by_name(&mut out, |m| m.name.as_str());
@@ -772,6 +844,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 +883,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)
}
@@ -1574,3 +1672,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
+4
View File
@@ -1,3 +1,5 @@
// 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.
//!
@@ -476,3 +478,5 @@ mod tests {
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,148 @@
// 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`).
//!
//! The current file first: a name this buffer declares anywhere — in another
//! module, a sibling block, a function three screens down — and then a word
//! it merely uses, both ahead of what other files declare and ahead of the
//! templates and keywords. Both are read from the buffer's own `Semantics`
//! and token stream, recomputed on every change, so an unsaved declaration
//! ranks as soon as it is typed. Tier 1 (the scope chain) still comes first:
//! what is visible at the cursor is a better answer than what is merely in
//! the file.
use std::collections::HashSet;
use lsp_types::CompletionItemKind;
use vlog_parser::token::TokenKind;
use vlog_semantic::Symbol;
use super::word::Word;
use super::{completion_kind, declaration_detail, Items, TIER_BUFFER_WORD, TIER_DECLARED};
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query};
use crate::state::Document;
/// Tier 2: every declaration in the buffer, whatever scope holds it.
pub(super) fn declared_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
let symbols: Vec<&Symbol> = doc.semantics.symbols().iter().collect();
for symbol in matching(symbols, |symbol| symbol.name.as_str(), word, fuzzy) {
if items.full() {
break;
}
items.simple(
&symbol.name,
completion_kind(symbol.kind),
TIER_DECLARED,
declaration_detail(doc, symbol),
);
}
}
/// Tier 3: every identifier the buffer's token stream holds, except the one
/// being typed — offering the user their own half-word back is noise.
pub(super) fn buffer_word_tier(
items: &mut Items,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
if items.full() {
return;
}
let mut seen = HashSet::new();
let words: Vec<&str> =
buffer_words(doc, word.start).filter(|name| seen.insert(*name)).collect();
for name in matching(words, |name| name, word, fuzzy) {
if items.full() {
break;
}
items.simple(name, CompletionItemKind::TEXT, TIER_BUFFER_WORD, "used in this file".into());
}
}
/// The candidates `word` reaches, in the order they are offered: by prefix
/// below the fuzzy floor (in the buffer's own order), ranked by subsequence
/// score from it up — the house rule every tier applies.
fn matching<'a, T: Copy + 'a>(
candidates: Vec<T>,
name: impl Fn(T) -> &'a str,
word: &Word,
fuzzy: Option<&Query>,
) -> Vec<T> {
match fuzzy {
None => candidates
.into_iter()
.filter(|c| starts_with_ignore_case(name(*c), &word.text))
.collect(),
Some(query) => {
let mut hits: Vec<(T, _)> =
candidates.into_iter().filter_map(|c| Some((c, query.score(name(c))?))).collect();
hits.sort_by(|a, b| rank_cmp((name(a.0), a.1), (name(b.0), b.1)));
hits.into_iter().map(|(c, _)| c).collect()
}
}
}
/// Every identifier the buffer holds, as the project-word tier counts one —
/// `Ident` and `SystemIdent` only, neither a macro usage nor an escaped
/// identifier — but not the token starting at `typing`, the word under the
/// cursor.
fn buffer_words(doc: &Document, typing: u32) -> impl Iterator<Item = &str> {
doc.tokens
.iter()
.filter(move |token| token.span.start != typing)
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
.map(|token| token.text.as_str())
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
}
#[cfg(test)]
mod tests {
use crate::completion::harness::*;
use crate::completion::*;
const TOP: &str = "\
module top;
logic data_q;
always_comb begin
da
end
endmodule
module other;
logic data_other;
assign data_word = 1;
always_comb al_used = 0;
endmodule
";
#[test]
fn this_files_declarations_and_words_rank_after_the_scope_and_before_other_files() {
let (_tree, ws, uri, position) = asking("bufferrank", TOP, " da");
let items = items(completions(&ws, &uri, position, true));
let tier_of = |label: &str| tier(find(&items, label).unwrap_or_else(|| panic!("{label}")));
assert_eq!(tier_of("data_q"), TIER_SCOPE, "visible at the cursor");
assert_eq!(tier_of("data_other"), TIER_DECLARED, "declared in another module of this file");
assert_eq!(tier_of("data_word"), TIER_BUFFER_WORD, "only used in this file");
assert_eq!(tier_of("data"), TIER_INDEX, "a port only `sub.sv` declares");
assert!(TIER_SCOPE < TIER_DECLARED && TIER_DECLARED < TIER_BUFFER_WORD);
assert!(TIER_BUFFER_WORD < TIER_INDEX && TIER_INDEX < TIER_TEMPLATE);
assert!(TIER_TEMPLATE < TIER_KEYWORD && TIER_KEYWORD < TIER_WORD);
}
#[test]
fn a_word_this_file_uses_sorts_ahead_of_the_keywords() {
let top = TOP.replace(" da\n", " al\n");
let (_tree, ws, uri, position) = asking("bufferkw", &top, " al");
let items = items(completions(&ws, &uri, position, true));
let sort = |label: &str| {
find(&items, label)
.and_then(|i| i.sort_text.clone())
.unwrap_or_else(|| panic!("{label}"))
};
assert!(sort("al_used") < sort("always"), "{items:#?}");
assert!(sort("al_used") < sort("always_ff"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,106 @@
// 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
//! parameter writes the whole entry — `.clk(|)` with the cursor inside the
//! parentheses — rather than the bare name. When the instantiating scope can
//! see a net, variable or port of the same name (a parameter, for the
//! parameter list), it is pre-filled as the placeholder: `.clk(${1:clk})`,
//! one Tab to keep it, one keystroke to replace it.
//!
//! The bare name stays the answer where the snippet would be wrong: a client
//! that never said it reads snippets, a `(` already written after the word
//! being replaced (re-editing `.clk(x)`'s name), and a name the snippet
//! grammar would have to escape (an escaped identifier).
use std::collections::HashSet;
use vlog_semantic::SymbolKind;
use super::snippet_hole;
use super::tiers::visible_symbols;
use super::word::Word;
use crate::signature;
use crate::state::Document;
/// A connection-list entry, beyond its name.
pub(super) struct Connection {
/// Whether the list already connects this port elsewhere — it sorts after
/// the rest and is marked `connected`.
pub(super) connected: bool,
/// The snippet accepting it writes, or `None` for the bare name.
pub(super) snippet: Option<String>,
}
/// Everything about the cursor's entry that every candidate's insertion
/// shares: whether to write the parentheses, and the names a placeholder may
/// be pre-filled with.
pub(super) struct EntrySite<'a> {
wrap: bool,
visible: HashSet<&'a str>,
}
impl<'a> EntrySite<'a> {
/// The entry being typed at `word`, in a list of `kind`.
pub(super) fn new(
doc: &'a Document,
word: &Word,
kind: signature::Kind,
snippets: bool,
) -> EntrySite<'a> {
let wrap = snippets && !paren_follows(&doc.text, word.start);
let admits = |symbol_kind: SymbolKind| match kind {
signature::Kind::Ports => {
matches!(symbol_kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port)
}
signature::Kind::Params => {
matches!(symbol_kind, SymbolKind::Param | SymbolKind::LocalParam)
}
};
let visible = match wrap {
true => visible_symbols(&doc.semantics, word.start)
.into_iter()
.filter(|symbol| admits(symbol.kind))
.map(|symbol| symbol.name.as_str())
.collect(),
false => HashSet::new(),
};
EntrySite { wrap, visible }
}
/// The entry for the port or parameter `name`.
pub(super) fn connection(&self, name: &str, connected: bool) -> Connection {
let plain = name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
let snippet = (self.wrap && plain).then(|| {
let fill = if self.visible.contains(name) { name } else { "" };
format!("{name}({})", snippet_hole(1, fill))
});
Connection { connected, snippet }
}
}
/// Whether a `(` follows the identifier run that starts at `start`, past any
/// spaces or tabs — the entry is already written and only its name is being
/// re-edited.
fn paren_follows(text: &str, start: u32) -> bool {
let Some(rest) = text.get(start as usize..) else { return false };
let rest = rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$');
rest.trim_start_matches([' ', '\t']).starts_with('(')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_paren_after_the_word_means_the_entry_is_already_written() {
assert!(paren_follows(".clk(x)", 1));
assert!(paren_follows(".cl (x)", 1));
assert!(!paren_follows(".cl", 1));
assert!(!paren_follows(".cl\n (x)", 1), "only on the same line");
assert!(!paren_follows(".cl, .b(x)", 1));
}
}
// 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
+129 -38
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.
//!
@@ -16,6 +18,7 @@ use lsp_types::CompletionResponse;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
use super::connection::{self, Connection};
use super::site::balanced;
use super::tiers::innermost_scope;
use super::word::{Sep, Word};
@@ -54,6 +57,7 @@ pub(super) fn member_answer(
doc: &Document,
word: &Word,
offset: u32,
snippets: bool,
) -> Option<CompletionResponse> {
let members = match word.spine.as_ref() {
Some(spine) => {
@@ -69,7 +73,7 @@ pub(super) fn member_answer(
// question, and it is the commonest completion position in RTL there
// is: a `.` opening a connection or a parameter override.
None => match word.sep? {
Sep::Dot => connection_members(ws, doc, word)?,
Sep::Dot => connection_members(ws, doc, word, snippets)?,
Sep::Scope => return None,
},
};
@@ -77,7 +81,7 @@ pub(super) fn member_answer(
// Prefix below [`FUZZY_MIN`], subsequence from it up — the house rule, on
// the same `Query` every other tier scores with.
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
let matched: Vec<Member> = match &fuzzy {
let mut matched: Vec<Member> = match &fuzzy {
None => members
.into_iter()
.filter(|member| starts_with_ignore_case(&member.name, &word.text))
@@ -95,12 +99,20 @@ pub(super) fn member_answer(
}
};
// A connection list's already-connected ports go after the rest, each
// group in the order it was matched in (`completion-ux`, TODO §68.1).
matched.sort_by_key(|member| member.connection.as_ref().is_some_and(|c| c.connected));
let mut items = Items::new(doc, word.range(offset));
for member in matched {
if items.full() {
break;
}
items.simple(&member.name, completion_kind(member.kind), TIER_MEMBER, member.detail);
let kind = completion_kind(member.kind);
match member.connection {
Some(connection) => items.connection(&member.name, kind, member.detail, connection),
None => items.simple(&member.name, kind, TIER_MEMBER, member.detail),
}
}
// **The `isIncomplete` trap, in its member form.** The request that
// matters is the one the trigger character fires, with nothing typed
@@ -132,6 +144,9 @@ struct Member {
name: String,
kind: SymbolKind,
detail: String,
/// What a connection list's entry carries beyond its name; `None` for
/// every other member.
connection: Option<Connection>,
}
/// What a member declared **in another file** shows beside its name.
@@ -225,10 +240,17 @@ fn members_at(
/// list to what may legally be written; it never offers a name the
/// resolution could not find.
///
/// Ports already connected earlier in the same list are dropped. `None` — no
/// Ports already connected elsewhere in the same list stay on offer, marked
/// (`completion-ux`, 2026-11-17 — they used to be dropped), and every entry
/// carries the `.name($1)` snippet [`connection::entry`] spells. `None` — no
/// popup — when the cursor is not in such a list at all, or is inside a
/// connected *expression* (`.clk(` opens a paren of its own).
fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec<Member>> {
fn connection_members(
ws: &Workspace,
doc: &Document,
word: &Word,
snippets: bool,
) -> Option<Vec<Member>> {
let dot = word.start.checked_sub(1)?;
let list = signature::enclosing_list(&doc.tokens, word.start)?;
let open = doc.tokens.get(list.open)?.span.end;
@@ -250,27 +272,33 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
signature::Kind::Ports => SymbolKind::Port,
};
let taken = connected_names(&doc.tokens, list.open, dot);
let entry = connection::EntrySite::new(doc, word, list.kind, snippets);
let mut members = Members::new();
let mut push = |name: &str, kind: SymbolKind, detail: String| {
let connection = entry.connection(name, taken.contains(name));
members.push_member(Member {
name: name.to_string(),
kind,
detail,
connection: Some(connection),
});
};
match doc.semantics.instantiable_scope(&list.module) {
// This file declares the module: its own scope is the whole answer,
// and no other file's module of the same name may override it.
Some(scope) => {
let scope = doc.semantics.scope(scope)?;
for symbol in scope.symbols.iter().filter_map(|&id| doc.semantics.symbol(id)) {
if symbol.kind == wanted && !taken.contains(symbol.name.as_str()) {
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
if symbol.kind == wanted {
push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
}
}
}
None => {
for (name, defs) in ws.index().members_of(&list.module) {
let Some(def) = defs.first() else { continue };
if def.kind == wanted && !taken.contains(name) {
members.push(
name,
def.kind,
indexed_detail(def.kind, def.type_name.as_deref()),
);
if def.kind == wanted {
push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
}
@@ -282,12 +310,11 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
/// token at `open`, except the one whose `.` sits at `skip` — the entry being
/// typed, which must stay on offer.
///
/// Dropping them is the friendlier half of a choice the other way round would
/// be simpler: in a sixty-port instantiation the fifty-five already connected
/// are the ones the user is *not* looking for, and a popup that keeps offering
/// them is a popup they scroll past. It cannot mislead — a name dropped here
/// is one the buffer already spells two lines up — and a re-edited entry is
/// still offered, because its own dot is the one `skip` names.
/// In a sixty-port instantiation the fifty-five already connected are the ones
/// the user is *not* looking for, so they sort after the rest and say so; they
/// are not dropped (`completion-ux`, 2026-11-17), because a port connected
/// twice by mistake is exactly the one a user goes looking for. A re-edited
/// entry is not marked, because its own dot is the one `skip` names.
fn connected_names(tokens: &[Token], open: usize, skip: u32) -> HashSet<&str> {
let mut taken = HashSet::new();
let mut depth = 0i32;
@@ -328,8 +355,12 @@ impl Members {
}
fn push(&mut self, name: &str, kind: SymbolKind, detail: String) {
if self.seen.insert(name.to_string()) {
self.out.push(Member { name: name.to_string(), kind, detail });
self.push_member(Member { name: name.to_string(), kind, detail, connection: None });
}
fn push_member(&mut self, member: Member) {
if self.seen.insert(member.name.clone()) {
self.out.push(member);
}
}
@@ -823,28 +854,55 @@ endmodule
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
}
/// The answer against [`WIRING`] in the order the client shows it — by
/// `sortText` — as `(label, marked connected)` pairs.
fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole);
let mut found = items(completions(&ws, &uri, position, true));
found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text));
found
.into_iter()
.map(|item| {
let marked = item
.label_details
.as_ref()
.and_then(|d| d.description.as_deref())
.is_some_and(|d| d == "connected");
(item.label, marked)
})
.collect()
}
fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> {
list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect()
}
#[test]
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
assert_eq!(wiring_labels("comma", ".clk(clk), ."), vec!["data", "ready"]);
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
assert_eq!(
wiring_labels("newline", ".clk(clk),\n ."),
vec!["data", "ready"],
wiring_order("newline", ".clk(clk),\n ."),
expected,
"an indented continuation line is the ordinary way this is written",
);
}
/// Already-connected ports are dropped: in a sixty-port instantiation the
/// ones still to wire are the whole of what the user is looking for.
/// Already-connected ports sort after the ones still to wire and say so
/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a
/// sixty-port instantiation the ones still to wire are what the user is
/// looking for, but a port connected twice by mistake is findable.
#[test]
fn a_port_already_connected_is_not_offered_again() {
fn a_port_already_connected_is_offered_last_and_marked() {
assert_eq!(
wiring_labels("taken", ".clk(clk), .data(d), ."),
vec!["ready"],
"two written, one left",
wiring_order("taken", ".clk(clk), .data(d), ."),
pairs(&[("ready", false), ("clk", true), ("data", true)]),
"two written, one left, and the two after it",
);
// …and the entry being *re-typed* is still offered, because the dot
// the cursor follows is the one that is skipped.
assert_eq!(wiring_labels("retype", ".clk(clk), .data(d), .re"), vec!["ready"]);
// …and the entry being *re-typed* is not marked, because the dot the
// cursor follows is the one that is skipped.
assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)]));
}
#[test]
@@ -945,17 +1003,21 @@ endmodule
}
#[test]
fn a_port_item_inserts_the_bare_name_and_shows_its_declaration() {
fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() {
let top = WIRING.replace(" HOLE\n", " .\n");
let tree = Tree::new("portitem");
let (_tree, ws, uri, position) = opened(tree, &top, " .");
let answer = items(completions(&ws, &uri, position, true));
let data = find(&answer, "data").expect("the port");
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
// The user types the `(` themselves; inventing it would be guessing
// at what is connected.
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
// `.data(|)`: the parentheses come with it, the cursor inside
// (`completion-ux`, 2026-11-17). Nothing named `data` is visible in
// `wiring_top`, so the placeholder is empty…
assert_eq!(inserted(data), "data(${1})");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET));
// …while `clk` is, so it is pre-filled.
let clk = find(&answer, "clk").expect("the clock");
assert_eq!(inserted(clk), "clk(${1:clk})");
// The declaration line carries the direction and the width, which is
// the whole of what a connection list needs to know.
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
@@ -965,6 +1027,33 @@ endmodule
}
}
#[test]
fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() {
// A `(` already after the word: only the name is being re-edited.
let top = WIRING.replace(" HOLE\n", " .da(d)\n");
let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "data").expect("the port")), "data");
// A client without snippet support gets the name, as before.
let top = WIRING.replace(" HOLE\n", " .\n");
let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " .");
let answer = items(completions(&ws, &uri, position, false));
let data = find(&answer, "data").expect("the port");
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
#[test]
fn a_parameter_item_is_pre_filled_from_a_visible_parameter() {
let top = WIRING
.replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n")
.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})");
assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})");
}
/// A **non-ANSI** port list writes its directions in the module body, so
/// the header alone names the ports and the body types them. Both halves
/// bind a `Port`, so the list is the same.
@@ -1116,3 +1205,5 @@ endmodule
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
+105 -19
View File
@@ -1,7 +1,9 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `textDocument/completion` — module hinting, templates, keywords, and every
//! name the project uses.
//!
//! One response, six tiers, ordered by `sortText`:
//! One response, eight tiers, ordered by `sortText`:
//!
//! 0. **module names** — at module-item position only, every module the
//! workspace declares whose name contains what is typed. The item inserts
@@ -10,12 +12,15 @@
//! 2026-08-30);
//! 1. **what is visible here** — the declarations the scope chain at the
//! cursor binds, from this file's `Semantics`;
//! 2. **what the project declares** — packages, their members, typedefs,
//! 2. **what this file declares** — every declaration in the buffer, in any
//! scope (`buffer.rs`, `completion-ux` 2026-11-17);
//! 3. **what this file uses** — every identifier its token stream holds;
//! 4. **what the project declares** — packages, their members, typedefs,
//! classes, modules and `` `define`` names, from the workspace index;
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! 5. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! tabstops, offered only where the construct may be written;
//! 4. **keywords** — every reserved word `vlog_parser` knows;
//! 5. **project words** — every identifier the in-scope files' *token
//! 6. **keywords** — every reserved word `vlog_parser` knows;
//! 7. **project words** — every identifier the in-scope files' *token
//! streams* contain, the rope/VS Code word-completion tier.
//!
//! A name is offered once, by the highest tier that claims it. Nothing is
@@ -47,8 +52,9 @@
//! list included;
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
//! `instantiate.rs` share;
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
//! the response.
//! * `buffer` — tiers 2 and 3, the current file's declarations and words;
//! * `tiers` — the other ordinary tiers, in the order they fill the
//! response.
//!
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
//! entry points other modules of the crate use keep their paths through the
@@ -58,9 +64,9 @@
use std::collections::HashSet;
use lsp_types::{
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
TextEdit, Uri,
CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionList,
CompletionResponse, CompletionTextEdit, Documentation, InsertTextFormat, InsertTextMode,
MarkupContent, MarkupKind, Position, Range, TextEdit, Uri,
};
use vlog_parser::token::{Comment, TokenKind};
use vlog_parser::TextRange;
@@ -71,8 +77,11 @@ use crate::candidates::Query;
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::Template;
use buffer::{buffer_word_tier, declared_tier};
use connection::Connection;
use member::member_answer;
use module::module_tier;
use 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;
@@ -84,13 +93,18 @@ 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;
#[cfg(test)]
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.
@@ -134,11 +148,23 @@ const TIER_MODULE: char = '0';
/// would say there is a ranking against the other tiers to express, and there
/// is not.
const TIER_MEMBER: char = '0';
/// A connection list's already-connected ports: after every port still to
/// connect, inside the same exclusive answer (`completion-ux`).
const TIER_CONNECTED: char = '1';
const TIER_SCOPE: char = '1';
const TIER_INDEX: char = '2';
const TIER_TEMPLATE: char = '3';
const TIER_KEYWORD: char = '4';
const TIER_WORD: char = '5';
/// What this buffer declares anywhere, and then the words it uses — the
/// current file ahead of every other file and of the templates and keywords
/// (`completion-ux`, TODO §68.1).
const TIER_DECLARED: char = '2';
const TIER_BUFFER_WORD: char = '3';
/// 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.
///
@@ -189,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),
@@ -203,7 +230,7 @@ pub fn completions(
// A `.` or a `::` admits exactly one kind of name too — a member of what
// stands before it — so the answer is only those. See [`member_answer`].
if word.sep.is_some() {
return member_answer(ws, doc, &word, offset);
return member_answer(ws, doc, &word, offset, snippets);
}
// Both position gates read the same scope chain, and neither can be true
@@ -225,10 +252,13 @@ pub fn completions(
let mut items = Items::new(doc, word.range(offset));
module_tier(&mut items, ws, doc, &word, at_item);
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
declared_tier(&mut items, doc, &word, fuzzy.as_ref());
buffer_word_tier(&mut items, doc, &word, fuzzy.as_ref());
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);
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
word_tier(&mut items, ws, &word, fuzzy.as_ref());
// **The `isIncomplete` trap.** VS Code asks the server again on the next
// keystroke *only* when the last answer said it was incomplete; otherwise
// it filters the list it already holds. A complete two-character prefix
@@ -255,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 {
@@ -264,6 +298,7 @@ impl Items {
items: Vec::new(),
seen: HashSet::new(),
incomplete: false,
related: 0,
}
}
@@ -271,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;
}
@@ -292,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),
@@ -304,6 +347,43 @@ impl Items {
})),
..Default::default()
};
self.items.push(item);
}
/// A port or parameter after a connection list's `.`: the bare name, or
/// the `name($1)` entry when the connection carries one, and a dimmed
/// `connected` beside the label when the list already connects it.
fn connection(
&mut self,
name: &str,
kind: CompletionItemKind,
detail: String,
connection: Connection,
) {
if self.full() || self.seen.contains(name) {
return;
}
let tier = if connection.connected { TIER_CONNECTED } else { TIER_MEMBER };
let format = match connection.snippet {
Some(_) => InsertTextFormat::SNIPPET,
None => InsertTextFormat::PLAIN_TEXT,
};
let item = CompletionItem {
label: name.to_string(),
kind: Some(kind),
detail: Some(detail),
label_details: connection.connected.then(|| CompletionItemLabelDetails {
detail: None,
description: Some("connected".to_string()),
}),
sort_text: Some(format!("{tier}{name}")),
insert_text_format: Some(format),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range: self.range,
new_text: connection.snippet.unwrap_or_else(|| name.to_string()),
})),
..Default::default()
};
self.push(item);
}
@@ -313,7 +393,11 @@ impl Items {
/// A client that never said it understands snippets gets the same text
/// with every hole filled in rather than nothing at all — the M4 ruling,
/// applied to a body whose defaults were chosen so that the result parses.
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
///
/// `rank` is the template's place in the registry, which is what orders the
/// templates among themselves: the label alone would put `always @(*)`
/// before the clocked blocks.
fn template(&mut self, template: &Template, rank: usize, layout: &Layout, snippets: bool) {
if self.full() || self.seen.contains(template.label) {
return;
}
@@ -329,7 +413,7 @@ impl Items {
// types to reach the item — otherwise `if` would not match
// `if begin/end` at all.
filter_text: Some(template.prefix.to_string()),
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
sort_text: Some(format!("{TIER_TEMPLATE}{rank:03}{}", template.label)),
insert_text_format: Some(match snippets {
true => InsertTextFormat::SNIPPET,
false => InsertTextFormat::PLAIN_TEXT,
@@ -835,3 +919,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
//! Tier 0 — module names at module-item position — and the instantiation
//! planning that `inline.rs`'s ghost and `instantiate.rs`'s command share.
//!
@@ -921,3 +923,5 @@ endmodule
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,345 @@
// 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
+30 -59
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.
//!
@@ -13,7 +15,6 @@
use std::collections::HashSet;
use lsp_types::CompletionItemKind;
use vlog_parser::token::TokenKind;
use vlog_parser::KEYWORDS;
use vlog_refactor::Layout;
use vlog_semantic::{Semantics, Symbol};
@@ -66,7 +67,7 @@ pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy:
/// Every declaration the scope chain covering `offset` binds, innermost scope
/// first, each name only once — the inner declaration shadows the outer one,
/// which is the rule `vlog_semantic`'s own lookup follows.
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
pub(super) fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
let mut out = Vec::new();
let mut seen = HashSet::new();
let mut at = innermost_scope(semantics, offset);
@@ -158,7 +159,7 @@ pub(super) fn template_tier(
}
let layout = layout_at(ws, doc, word.start);
let dialect = templates::dialect(doc.path.as_deref());
for template in templates::for_dialect(dialect) {
for (rank, template) in templates::for_dialect(dialect).enumerate() {
if items.full() {
break;
}
@@ -168,7 +169,7 @@ pub(super) fn template_tier(
if !starts_with_ignore_case(template.prefix, &word.text) {
continue;
}
items.template(template, &layout, snippets);
items.template(template, rank, &layout, snippets);
}
}
@@ -205,45 +206,26 @@ pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
}
}
/// Tier 5: identifiers used anywhere in the project scope.
/// Tier 7: identifiers used anywhere in the project scope.
///
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
/// buffer being typed in is harvested afresh from its own token stream, so an
/// unsaved edit contributes to its own file's completions immediately.
pub(super) fn word_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
/// The prebuilt table is as of the last index rebuild, which is `didSave`. The
/// buffer being typed in is harvested afresh from its own token stream by
/// tier 3 (`buffer.rs`), so an unsaved edit still contributes immediately.
pub(super) fn word_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
// Gathering and sorting the names is the one tier whose *setup* costs
// something, so a response that is already full skips it outright.
if items.full() {
return;
}
// The buffer's own words were offered by tier 3 already, so only the
// prebuilt table is read here; a name in both is offered once anyway,
// because `Items` drops a repeated label.
let names: Vec<&str> = match fuzzy {
None => {
let mut names: Vec<&str> =
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
names
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
names.sort_unstable();
names.dedup();
names
}
None => ws.candidates().words(&word.text).iter().map(String::as_str).collect(),
Some(query) => {
// The table's hits come back ranked; the buffer's own words are
// scored here and the two are ranked together, so a name the user
// typed a moment ago sits where its match deserves rather than
// after everything the table knows.
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
let hits = ws.candidates().words_fuzzy(query, LIMIT);
// A full return is a truncation; see `index_tier`.
items.incomplete |= hits.len() >= LIMIT;
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
hits.sort_by(|a, b| rank_cmp(*a, *b));
// A name in both lists is offered once: `Items` drops the second
// by label, so no dedup is needed here.
hits.into_iter().map(|(name, _)| name).collect()
}
};
@@ -255,21 +237,6 @@ pub(super) fn word_tier(
}
}
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
///
/// The live half of the tier: the prebuilt table is as of the last index
/// rebuild, and this is the buffer's own token stream, recomputed on every
/// change. The filter is `candidates::is_word`'s, in the other direction —
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
/// identifier.
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
doc.tokens
.iter()
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
.map(|token| token.text.as_str())
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -374,7 +341,7 @@ endmodule
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
"and `alw` finds every one of them"
);
@@ -419,7 +386,7 @@ endmodule
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
@@ -637,7 +604,8 @@ endmodule
#[test]
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
// `inner` is declared in a block the cursor is not in, so it may only
// arrive as a project word — never as a visible declaration.
// arrive as one of this file's declarations (tier 2, `completion-ux`)
// — never as a visible declaration.
let top = "\
module top;
initial begin : b
@@ -650,8 +618,8 @@ endmodule
";
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "inner_only").expect("known as a word at least");
assert_eq!(tier(item), TIER_WORD, "{item:#?}");
let item = find(&items, "inner_only").expect("known as a declaration at least");
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
}
// ------------------------------------------------------------------
@@ -750,12 +718,13 @@ endmodule
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `c` itself is in the list because the buffer being typed in
// holds it as an `Ident` token — behaviour this round did not
// touch, pinned here because a golden that quietly lost it would
// be a change.
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["ce", "celsius"]),
// `c` itself used to be in the list, because the buffer being
// typed in holds it as an `Ident` token. `completion-ux`
// (2026-11-17) dropped it on purpose: the buffer-word tier skips
// the token under the cursor, and offering the user their own
// half-word back is noise.
("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["celsius"]),
] {
let found = items(after_typing(&mut ws, &uri, typed));
let named: Vec<&str> = found
@@ -977,3 +946,5 @@ endmodule
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+152
View File
@@ -0,0 +1,152 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! What a completion answer costs on the wire, for a client that can take
//! less (`docs/features/fast-actions/README.md`, "payload").
//!
//! Every item of one answer replaces the same range, and almost every item
//! inserts its own label as plain text — so the `textEdit` each one carries
//! (49 % of a 130 KB answer, measured) and its `insertTextFormat` (8 %) say
//! the same thing five hundred times. LSP 3.17's `CompletionList.itemDefaults`
//! says it once: an item with no `textEdit` replaces `editRange` with its
//! `textEditText`, or with its label when it has none, in
//! `insertTextFormat`. `vscode-languageclient` 9 applies exactly that rule
//! (`protocolConverter.asCompletionInsertText`), and advertises both defaults.
//!
//! **The same edits, fewer bytes.** The rewrite is lossless by construction:
//! an item keeps its own `textEdit` unless its range *is* the default, keeps
//! its own format unless it *is* the default, and moves a `newText` that is
//! not its label into `textEditText`. Done on the serialized answer because
//! `lsp-types` 0.97 has neither field.
use lsp_types::InitializeParams;
use serde_json::{Map, Value};
/// `insertTextFormat: PlainText`, the format nearly every item has.
const PLAIN_TEXT: u64 = 1;
/// Whether the client applies `itemDefaults.editRange` and
/// `itemDefaults.insertTextFormat` — `textDocument.completion.completionList
/// .itemDefaults` listing both. A client that said nothing gets every item
/// whole, which is what every client got before this was read.
pub(crate) fn item_defaults_support(params: &InitializeParams) -> bool {
let listed = params
.capabilities
.text_document
.as_ref()
.and_then(|text_document| text_document.completion.as_ref())
.and_then(|completion| completion.completion_list.as_ref())
.and_then(|list| list.item_defaults.as_ref());
listed.is_some_and(|names| {
["editRange", "insertTextFormat"].iter().all(|wanted| names.iter().any(|n| n == wanted))
})
}
/// Rewrite a serialized `CompletionList` so the range and the format every
/// item shares are said once, in `itemDefaults`. Anything that is not a list
/// with items comes back as it was.
pub(crate) fn with_item_defaults(mut answer: Value) -> Value {
let Some(list) = answer.as_object_mut() else { return answer };
let Some(Value::Array(items)) = list.get_mut("items") else { return answer };
let Some(range) = items.first().and_then(edit_range).cloned() else { return answer };
for item in items.iter_mut().filter_map(Value::as_object_mut) {
lift_edit(item, &range);
if item.get("insertTextFormat").and_then(Value::as_u64) == Some(PLAIN_TEXT) {
item.remove("insertTextFormat");
}
}
let mut defaults = Map::new();
defaults.insert("editRange".to_string(), range);
defaults.insert("insertTextFormat".to_string(), Value::from(PLAIN_TEXT));
list.insert("itemDefaults".to_string(), Value::Object(defaults));
answer
}
/// The range a plain `textEdit` replaces, if the item has one.
fn edit_range(item: &Value) -> Option<&Value> {
let edit = item.get("textEdit")?;
edit.get("newText")?;
edit.get("range")
}
/// Drop `item`'s `textEdit` when it replaces `range`, keeping its text in
/// `textEditText` unless that text is the label.
fn lift_edit(item: &mut Map<String, Value>, range: &Value) {
let Some(edit) = item.get("textEdit") else { return };
if edit.get("range") != Some(range) {
return;
}
let Some(Value::Object(mut edit)) = item.remove("textEdit") else { return };
let new_text = edit.remove("newText").unwrap_or(Value::Null);
if item.get("label") != Some(&new_text) {
item.insert("textEditText".to_string(), new_text);
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn range(line: u32) -> Value {
json!({ "start": { "line": line, "character": 4 }, "end": { "line": line, "character": 6 } })
}
/// The edit an item makes under the LSP 3.17 rule, defaults applied.
fn effective(item: &Value, defaults: &Value) -> (Value, Value, Value) {
let format = item.get("insertTextFormat").unwrap_or(&defaults["insertTextFormat"]).clone();
match item.get("textEdit") {
Some(edit) => (edit["range"].clone(), edit["newText"].clone(), format),
None => (
defaults["editRange"].clone(),
item.get("textEditText").unwrap_or(&item["label"]).clone(),
format,
),
}
}
#[test]
fn every_item_makes_the_same_edit_with_the_defaults_applied() {
let before = json!({ "isIncomplete": true, "items": [
{ "label": "sig", "insertTextFormat": 1,
"textEdit": { "range": range(2), "newText": "sig" } },
{ "label": "if begin/end", "insertTextFormat": 2,
"textEdit": { "range": range(2), "newText": "if (${1:cond}) begin\n$0\nend" } },
{ "label": "`W", "insertTextFormat": 1,
"textEdit": { "range": range(2), "newText": "`W" } },
{ "label": "odd", "insertTextFormat": 1,
"textEdit": { "range": range(7), "newText": "odd" } },
]});
let after = with_item_defaults(before.clone());
let defaults = &after["itemDefaults"];
assert_eq!(defaults["editRange"], range(2));
for (old, new) in
before["items"].as_array().unwrap().iter().zip(after["items"].as_array().unwrap())
{
let old_effect = (
old["textEdit"]["range"].clone(),
old["textEdit"]["newText"].clone(),
old["insertTextFormat"].clone(),
);
assert_eq!(effective(new, defaults), old_effect, "{new}");
}
assert!(after["items"][0].get("textEdit").is_none(), "the label is the text");
assert!(after["items"][0].get("textEditText").is_none());
assert_eq!(after["items"][1]["textEditText"], before["items"][1]["textEdit"]["newText"]);
assert!(after["items"][3].get("textEdit").is_some(), "another range keeps its edit");
assert!(after.to_string().len() < before.to_string().len());
}
#[test]
fn an_answer_that_is_not_a_list_of_edits_is_left_alone() {
for answer in [
Value::Null,
json!([]),
json!({ "isIncomplete": false, "items": [] }),
json!({ "items": [{ "label": "x", "insertText": "x" }] }),
] {
assert_eq!(with_item_defaults(answer.clone()), answer);
}
}
}
// 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 is typed: the identifier run ending at the cursor and what stands
//! around it — a backtick, a `.` or a `::`, and the spine a separator
//! follows.
@@ -244,3 +246,5 @@ pub(super) fn line_head_is_blank(text: &str, at: u32) -> bool {
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
head.get(line_start..).is_some_and(|head| head.chars().all(|c| c == ' ' || c == '\t'))
}
// 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
//! Byte offsets ↔ LSP positions.
//!
//! Everything below the protocol speaks UTF-8 byte offsets; LSP `Position`
@@ -518,3 +520,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
//! The VS Code instance-oriented design hierarchy.
//!
//! LSP call hierarchy deliberately groups a module's calls by target module
@@ -523,3 +525,5 @@ mod tests {
.unwrap_or_else(|| panic!("no module {name}: {modules:#?}"))
}
}
// 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
//! Diagnostics, published on every buffer change.
use lsp_types::{Diagnostic, DiagnosticSeverity};
@@ -199,3 +201,5 @@ mod tests {
assert!(diags[0].range.start < diags[0].range.end, "must be drawable");
}
}
// 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
//! Single-step macro expansion, for hover **display** only.
//!
//! One step means one thing: the definition's body with the call site's
@@ -430,3 +432,5 @@ mod tests {
assert!(!has_macro_use("plain text"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
Loaded 100 of 884 files, more files were not shown because too many files have changed in this diff. Show more