Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 23:22:18 -08:00
1155 changed files with 72184 additions and 26028 deletions

No files matched your search

+11 -5
View File
@@ -1,6 +1,8 @@
# 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 macOS runner in host mode (no
# Author: Guoliang Chen, a Senior Digital Design Engineer
# CI: author-stamp check plus the three checks CLAUDE.md requires before any
# work is finished (with `cargo test` run under `tools/guard.sh`), plus the
# extension's JavaScript tests and the corpus gate, enforced on every push. Runs on the self-hosted macOS runner in host mode (no
# containers), so the toolchain is the same one releases are built with —
# and, since 0.65.9, the same checks on Linux (the `linux` job below), where
# the released Linux binaries had never been compiled-and-tested before.
@@ -15,12 +17,14 @@ jobs:
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
- name: author stamps
run: python3 tools/stamp_author.py --check
- name: cargo fmt
run: cargo fmt --all -- --check
- name: cargo clippy
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: cargo test --workspace
run: tools/guard.sh -m 8 -t 1800 -- cargo test --workspace
# The VS Code extension's headless checks (a stubbed `vscode`, no npm
# dependencies): node >= 18 for `--test`; the runner has node 22.
- name: extension tests
@@ -63,4 +67,6 @@ jobs:
- name: cargo clippy
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: cargo test --workspace
run: tools/guard.sh -m 6 -t 1800 -- cargo test --workspace
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+63 -5
View File
@@ -1,3 +1,5 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
# Release: pushing a tag `vX.Y.Z` builds every distribution artifact and
# publishes a Gitea release with the CHANGELOG section for that version as
# its notes. What the release page carries is the seven .vsix packages —
@@ -15,11 +17,16 @@
# workspace version or CHANGELOG.md has no section for it: every release
# ships with real, written notes (see tools/RELEASING.md).
#
# It is gated: tools/gates.sh (fmt, clippy, every crate's suites, the doc
# tests, the corpus gate, the extension's node tests) runs first, and a red
# gate means nothing is built or published. The ci workflow runs on the
# branch push, not the tag, so without this step a tag published whatever
# it pointed at (0.65.0 went out while its ci run was still stuck).
# It is gated in three stages:
# 1. `preflight` checks in seconds that the tag matches Cargo.toml, the VS Code
# extension version files, and a non-empty CHANGELOG.md section before any
# heavy build runs.
# 2. `linux` runs clippy and guarded workspace tests on `linux-x64` so Linux
# portability is verified before building or publishing a release.
# 3. `build-and-publish` runs `tools/gates.sh` (stamp, fmt, clippy, every
# crate's suites, doc-tests, corpus gate, node tests, cross check), builds
# and audits all targets, prunes assets to the seven .vsix files + SHA256SUMS,
# and publishes the Gitea release.
name: release
on:
push:
@@ -27,7 +34,56 @@ on:
- 'v*'
jobs:
preflight:
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
- name: Check tag, versions, and CHANGELOG notes
run: |
tag_ver=${GITHUB_REF_NAME#v}
[ "v$tag_ver" = "$GITHUB_REF_NAME" ] && [ -n "$tag_ver" ] || {
echo "tag $GITHUB_REF_NAME must look like vX.Y.Z" >&2
exit 1
}
crate_ver=$(awk '
/^\[workspace\.package\]/ { in_wp = 1; next }
/^\[/ { in_wp = 0 }
in_wp && /^version[[:space:]]*=/ {
sub(/^[^"]*"/, ""); sub(/".*/, ""); print; exit
}
' Cargo.toml)
[ "$crate_ver" = "$tag_ver" ] || {
echo "tag $GITHUB_REF_NAME does not match Cargo.toml version '$crate_ver'" >&2
exit 1
}
for pinned in \
"$(node -p "require('./editors/vscode/package.json').version")" \
"$(node -p "require('./editors/vscode/package-lock.json').version")" \
"$(node -p "require('./editors/vscode/package-lock.json').packages[''].version")"; do
[ "$pinned" = "$tag_ver" ] || {
echo "editors/vscode version '$pinned' does not match tag $GITHUB_REF_NAME" >&2
exit 1
}
done
tools/release_notes.sh "$tag_ver" >/dev/null
linux:
needs: preflight
runs-on: linux-x64
steps:
- uses: actions/checkout@v4
- name: Install the Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --profile minimal -c clippy,rustfmt
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: cargo clippy
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: tools/guard.sh -m 6 -t 1800 -- cargo test --workspace
build-and-publish:
needs: [preflight, linux]
runs-on: macos-arm64
steps:
- uses: actions/checkout@v4
@@ -67,3 +123,5 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
LUCISV_API_URL: ${{ vars.LUCISV_API_URL }}
run: tools/publish_release.sh "$GITHUB_REF_NAME" dist
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
/target
/corpus
/corpus-check-results.tsv
@@ -8,3 +10,5 @@
/.zcode
/.claude
__pycache__/
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+257
View File
@@ -1,9 +1,264 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# Changelog
All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.67.0 — 2026-11-26
### Twelve bug-fix rounds, measured against 0.66.2
0.67.0 is everything since 0.66.2: twelve rounds of correctness, ordering,
hardening and hygiene fixes, each with its own dev round, QA round and lead
review, and a before/after performance report on OpenTitan `hw`
(`docs/performance_take6.md`). Each paragraph below names the feature README
that holds the detail. Three things to know before upgrading:
- **Formatted output changes.** Over OpenTitan `hw` the formatter's output
differs from 0.66.2 in **413** files in the default style, **576** under
`--style auto` and **972** under `--style lowrisc`; no file gained or lost a
diff, and verification failures are **0** in every style, as before.
- **One new lint rule is on by default** (`missing-port-direction`, an Error),
and two rules report differently; see Linter.
- **Saved state is rebuilt once.** The persisted index (`FACTS_FORMAT` 22 → 23)
of both the language server and `lucisv-mcp --index-cache` is discarded and
rebuilt on first start, and the format cache's lines are re-keyed, so the
first `lucisv` run after upgrading has no cache hits.
### Formatter and safety net
- **`#(…)` parameter ports and named parameter overrides are aligned** like
every other list: type, name and `=` in columns under both `infer` and
`always` alignment (`docs/features/format-alignment-overrides-r6`). Every
file Take 6 sampled from the output change above shows it; class parameter
headers are unchanged.
- **`lowrisc` sets named connections tight to the widest name**: the widest
name's `(` follows it directly (`.err_o(…)`) and narrower names are padded
to that column (`.tl_i (tl_i)`). This is a new `connection-align-min` knob,
`0` for `lowrisc` and `1` for every other preset.
- **Selective `[format]` overrides.** `begin`, `else`, `else-after-label`,
`port-lists`, `list-indent`, `alignment` and `connection-align-min` in
`lucisv.toml` (and the matching `lucisv.format.*` editor settings) layer
over any named preset, and over every candidate under `style = "auto"`. The
CLI, the language server and the MCP `format` tool all honour them. Every
effective knob is now part of the format cache key, so toggling one
re-formats; older cache lines are dropped as stale.
- **Multi-instance declarations** (`p1 u8 (…), u9 (…);`) break symmetrically
under the one-per-line styles (`google`, `lowrisc`, `microsoft`, `nxp`)
instead of the hanging layout; `lucisv` and `ansi` output is unchanged
(`docs/features/parser-formatter-r5`).
- **Files that used to be left unformatted now format:** a comment between a
generate `end` and `else`, an `` `ifdef `` (balanced, or a conditional
`else` arm) between `end` and `else` in procedural and generate `if`, and
attributes on ANSI ports (`(* keep *) input a`).
- **The parser is stricter where it was silently lenient:** empty elements in
concatenations, replications, streaming and assignment patterns
(`{d,, d}`, `{d,}`, `'{4{a,, b}}`), in `case` item lists (`case a,, b:`)
and a trailing `,` after a named call argument (`f(.a(x),)`) are now parse
errors, so such a file is reported and left as it is. Omitted positional
arguments (`f(a, , b)`) are still accepted.
### CLI
- **`--style auto` is twice as fast**: the file is parsed once for all six
candidate presets and only the winner is verified. OpenTitan `hw`,
`--check --no-cache`: 5 564 → **2 806 ms** median, user CPU 49.9 → 21.2 s,
peak RSS 981 → 699 MiB (`docs/features/parser-formatter-r5`, Take 6).
- **`--output-format json` works in format mode** (`lucisv`, `--check`,
`format`): one JSON document with `status`, `exit_code`, `summary` and one
entry per file, with the error's category, line and column. It refuses
`--diff`, `--stdout` and stdin without `--check`. Exit codes are unchanged
(`docs/features/cli-path-r5`).
- **Stdin honours the project config:** `-` / `--stdin-filename` applies the
discovered `lucisv.toml` alike in `format` and `check`, including `[lint]
select` and `ignore` in `check`; an empty `--stdin-filename ""` is refused.
- Path normalisation (`.` and `..`) is one shared function in `lucisv_core`
for filelists, config discovery, includes and the CLI; behaviour is
unchanged, including Windows drive and UNC roots.
### Linter
(`docs/features/linter-hardening-r7`.) 75 rules now (8 error, 24 warning,
43 style). On OpenTitan `hw`, `lucisv check` goes from **1 182 to 1 178**
findings:
- **New: `missing-port-direction`** (Error, on by default, no fix) reports a
non-ANSI header port that no body declaration gives a direction. It stays
silent when the body holds a macro item, an `` `include ``, a verbatim or an
error item. It reports 0 on OpenTitan `hw`.
- **`suspicious-semicolon` exempts the drain idiom `while (<call>);`**
(`while (fifo.try_get(item));`), only when the whole condition is one call:
−5 findings on OpenTitan. `while (busy);` and `while (!q.try_get(x));` are
still reported.
- **`incomplete-assignment` sees a miss in a nested `if`**, and counts a
fully enumerated `case` without `default` as complete only when its selector
is proven to be that wide: +1 finding on OpenTitan, a real latch
(`rom_ctrl/dv/tb/tb.sv:158`).
- **`mismatched-labels`** handles `initial lbl : begin … end : lbl`, and
offers an Unsafe fix that renames a wrong footer to the header's name
(CLI `--fix --unsafe-fixes` only; the editor and MCP apply Safe fixes only).
- Rule options in `[ … ]` lists split on commas outside quotes only, and a
naming-pattern regex nested more than 64 groups deep is refused by name
instead of overflowing the stack.
- **Withdrawn during the round, not shipped:** an autofix for
`uvm-macro-semicolon` (it corrupted code in three QA passes; the rule offers
no fix, as before) and a nested-loop exemption for `instance-shadowing`
(it hid the bug the rule exists for; the 30 OpenTitan hits stay).
### Language server
- **Rename, code-action resolve, `executeCommand` and `willRenameFiles` wait
for a running scan to finish** instead of running against a partly built
index (a module declared twice no longer gets an edit or a refusal at
random); read-only answers from the open buffer still go ahead
(`docs/features/server-ordering-r1`).
- **Rename and port edits carry document versions** (`documentChanges`) when
the client supports them, so an editor can refuse an edit computed against
text it no longer has. A settings push older
than the answer to the startup settings pull no longer overwrites it.
- **The index follows open and closed buffers exactly**
(`docs/features/index-lifecycle-r2`): closing an excluded or unlisted file
removes it, closing an unsaved in-scope file reverts its record to disk, a
buffer opened mid-scan is taken in as if opened before, a large open buffer
keeps its disk record, and a symlinked file is held under one spelling
whichever alias is open.
- **Colours refresh exactly when they change** (`docs/features/lsp-viewport-folding-r9`):
a save that changes how another open file colours (a package type renamed,
a class declared) now refreshes it, and a range answered during a rescan no
longer buys a refresh when the settled answer is the same.
- **A rescan answers between slices of its discovery walk** (512 entries per
slice; `docs/features/server-scaling-r10`). On OpenTitan `hw` a settings
rescan takes 703 → **642 ms** median, a `documentSymbol` sent 5 ms into it
waits 133 → **2.8 ms**, and the store is no longer re-opened (70 → 0 ms).
On 40 000 files the rescan is 12 % faster.
- Refactorings: a rename inside a string with an escaped non-ASCII character
no longer panics; macro-argument carrying is deterministic; renaming a
member of a module declared in two files is refused instead of guessed;
`remove port` no longer counts another module's `.port(…)` in the same file
as a use; `extract module` keeps CRLF line endings
(`docs/features/refactor-correctness-r1`).
- Semantics (`docs/features/semantic-refactor-r8`): a DPI export's name is a
reference; escaped identifiers are in the word census, so a file that only
writes `\my.sig` is found (completion does not offer them); an interface's
named generate blocks are reachable through its ports; an inline nested
struct member resolves; a rename through `bind` handles a bare-instance
target and no longer mistakes a generate-scoped instance for the module's
own; and the refactoring verifier checks each edit of a move on its own.
### MCP server
(`docs/features/mcp-hardening-r3`.)
- **`find` with `refs: true` reuses cached file facts**: on OpenTitan `hw`,
warm, 2.4× faster for a qualified name (1 115 → 474 ms), 2.6× for one
declaration (1 099 → 415 ms) and 3.8× for a name with 300+ declarations
(7 800 → 2 032 ms), with byte-identical answers. A qualified `unit.name`
query is scoped to that unit.
- **`check` accepts a directory or a glob** under a root (`ip/aes/rtl`,
`ip/aes/rtl/*.sv`); unused waivers are reported for the whole design only.
- A file whose modification time is in the future settles instead of being
re-read on every call; `initialize` no longer announces an empty
`prompts` capability.
### Windows
- **UNC workspaces work** (`docs/features/windows-uri-editors-r11`). The
server reads and writes `file://server/share/…` URIs in VS Code's form
(before, they were mangled in both directions), sees through `\\?\` paths,
and returns `\`-separated paths. **This is compile- and link-checked only,
never executed on Windows**: every Windows rule was tested as string code on
macOS.
- **The Windows index cache key changes once**: the workspace root's spelling
changes (`c:/proj` → `c:\proj`), so the index is rebuilt on first start
after upgrading and the old cache directory is left unused.
- On every platform, a `\` in a file name is now written `%5C` and a URI's
`?query#fragment` is no longer read as part of the path.
### Editors
- VS Code: the `lucisv.format.*` override settings above, a toggle for
`missing-port-direction`, `lucisv.mcp.path` pointing at a directory finds
`lucisv-mcp.exe` on Windows, a failing module-view action shows a warning,
and the README's settings table is corrected (`scopeDepth` default `2`, the
eight `lucisv.format.*` rows). Neovim README: references are
workspace-wide and `--stdio` is accepted. `editors/vscode/CHANGELOG.md` has
the editor's view.
### Performance (`docs/performance_take6.md`)
Beyond the numbers above, every other CLI and LSP phase shows no measurable
change; the language server's idle memory after a cold workspace scan fell
531 → 479 MiB (not attributed). Three regressions were found and bisected;
none is fixed in 0.67.0:
- **Formatter peak memory with all workers** rose by about 90–100 MiB
(default 568 → 654 MiB median, `lowrisc` 574 → 674 MiB; with `--threads 1`
it fell 291 → 252 MiB). Cause confirmed, from Round 5: the input's syntax
tree is kept alive while the output is verified. Left as is.
- **`didOpen` of a file over `index.maxFileSize`** costs about 14 ms more
(OpenTitan's 1.3 MB `pinmux_reg_top.sv`: 60–74 → 76–84 ms), from Round 2's
symlink identity map; about 8 ms of it is confirmed.
- **`workspace/symbol`** costs about 2 ms more (1.4–3.2 → 3.8–6.7 ms, same
256 results), from Round 2; the cause is a candidate, not confirmed.
### Project hygiene
- CI and release gates (`docs/features/ci-gates-r4`): `cargo test` runs under
`tools/guard.sh` on macOS and Linux, author stamps are a gate step, a
missing cross toolchain fails `gates.sh` unless `--allow-skip-cross`, and a
release checks tag and versions in a fast `preflight` job and runs the suite
on Linux before building.
- Five more pure-move splits and 23 test modules moved out of their files;
no production file is over 600 lines, and every `#[ignore]` says why
(`docs/features/hygiene-splits-r12`). Documentation and the site sources
were re-synced (`docs/features/docs-sync-r4`).
- **Gates on the release tree:** tests passed per crate — `vlog_parser` 527,
`vlog_semantic` 453, `vlog_refactor` 793, `vlog_formatter` 383,
`vlog_linter` 710, `lucisv_core` 129, `lucisv` 162, `lucisv_server` 2263,
`lucisv_mcp` 400; doc-tests 1, extension 37; corpus 814 / 6, unchanged.
OpenTitan `hw`: 4 039 of 4 046 files format cleanly in every style, 0
verification failures.
## 0.66.2 — 2026-11-24
### Every source file names its author
- **No behaviour change.** Every tracked file that can carry a comment — 880
of them: the Rust sources, the extension's JavaScript, the scripts, the
manifests, the workflows and the documentation — now opens with an author
line and closes with one. The binaries and the formatter's, linter's and
language server's output are what 0.66.1 produced.
- `tools/stamp_author.py` writes the lines and is idempotent; run it after
adding files (`--check` lists what is missing). It leaves alone what a
comment would break or what is regenerated: test fixtures, cases and
snapshots, JSON and JSONL, logs, images, lockfiles, the built site under
`docs/site/dist` and the `LICENSE` files.
- `tools/linux_check.sh --help` reads its own header one line further down,
since the author line now sits under the shebang.
## 0.66.1 — 2026-11-19
### Sticky scroll pins the module instance
- **A module instantiation folds, so its header lines stay pinned** (TODO
§72, `docs/features/instance-folding`). `textDocument/foldingRange` answers
one range per multi-line instantiation from its module-type line, and one
more per instance from the line its name is on when that is a later line,
so both `aes_control_fsm #(` and `) u_aes_control_fsm (` are pinned while
the reader is in the connection list. The closing `);` line stays visible.
What is an instantiation comes from `vlog_semantic::instantiations::sites`;
where it closes is re-read from the tokens, and a statement whose tokens
are not exactly that shape folds nothing.
- Every fold answered before is unchanged and first on a shared start line
(0.66.0 against this tree on 4 933 files: 75 256 ranges identical once the
instance folds are removed). OpenTitan `hw`: 18 200 multi-line
instantiations, none without its fold. Worst file about 2 ms per request
(1.1 ms before).
- Not folded: two-dimensional instance arrays; an instance whose head an
`` `ifdef `` splits.
## 0.66.0 — 2026-11-19
### The overnight queue, complete
@@ -3421,3 +3676,5 @@ compiler directive any more. Details:
[macro items](docs/features/macro-items/README.md),
[directives in lists](docs/features/directives-in-lists/README.md) and
[in instances](docs/features/directives-in-instances/README.md).
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+36
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.
@@ -99,6 +101,38 @@ either goes in a new module. The queue's new modules are all small
`style.rs` / `auto.rs`); `server/dispatch.rs` is 503 and `server/index.rs`
is where four of the eight features met.
Re-measured 2026-11-26 at 0.66.2 (`69383ea`, after `instance-folding`,
`stamp_author`, and Rounds 1–3; same rule: non-blank, non-comment lines before
`#[cfg(test)]`/`mod tests`, excluding `*/tests/`): only test-only
`lucisv_server/src/perf.rs` (907, `#[cfg(test)]` in `main.rs`) exceeds 600;
every non-test production module in the workspace is under 600 (`lexer.rs`
540, top production files `vlog_semantic/src/resolve.rs` 587,
`vlog_parser/src/parser/item.rs` 582, `vlog_parser/src/parser/instance.rs` 569,
`vlog_parser/src/parser/module.rs` 560, `vlog_formatter/src/format/stmt.rs` 556,
`vlog_parser/src/parser/sva.rs` 542, `vlog_refactor/src/extract/flow.rs` 535,
`lucisv_server/src/server/dispatch.rs` 522, `lucisv_server/src/state/discover.rs` 510).
Re-measured 2026-11-26 after Round 12 (`hygiene-splits-r12`, pure moves; same
rule): no production file exceeds 600. Top production files:
`lucisv/src/main.rs` 574, `vlog_parser/src/parser/module.rs` 568,
`parser/split.rs` 554, `parser/sva.rs` 542, `vlog_refactor/src/extract/flow.rs`
535, `parser/class.rs` 518, `parser/covergroup.rs` 517,
`lucisv_server/src/server/dispatch.rs` 515, `state/discover.rs` 515. The round
split `resolve.rs` (587 → 294; `resolve/member.rs` 196, `types.rs` 115),
`parser/item.rs` (589 → 322; `package.rs` 113, `generate.rs` 160),
`parser/instance.rs` (565 → 353; `connection.rs` 218), `format/stmt.rs`
(570 → 400; `case.rs` 94, `timing.rs` 89) and `lexer.rs` (→ 497;
`lexer/number.rs` 114, `define_params.rs` 105, `attach.rs` 54). The `lexer.rs`
540 above was a counting artifact: a `#[cfg(test)]` *field* at line 723 ended
the count 230 lines early, and the file was still 771. This measurement steps over a `#[cfg(test)]`
that is not the test module; counted that way
`vlog_refactor/src/rename/warnings.rs` is 521 (80 by the bare rule),
`rename/mod.rs` 494 and `lucisv_server/src/state/rescan.rs` 483. Test-only
files over 600 (declared under `#[cfg(test)]`, so not production): `perf.rs`
907 (reasoned), and the test modules the round moved out of their files in
`lucisv_server` — `nav/tests.rs` 1 926, `inline/tests.rs` 1 170,
`pairs/tests.rs` 1 009, `ports/tests.rs` 910 and nine more between 611 and 818.
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
@@ -225,3 +259,5 @@ proven independent and run serially. Rules for a parallel wave:
not actually independent, which is a planning failure to record.
- After merging, the lead updates `docs/topo.md` for any edge a lane added
or amended, so the next wave plans against reality.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.66.0"
version = "0.67.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.66.0"
version = "0.67.0"
[[package]]
name = "lucisv_mcp"
version = "0.66.0"
version = "0.67.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.66.0"
version = "0.67.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.66.0"
version = "0.67.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.66.0"
version = "0.67.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.66.0"
version = "0.67.0"
[[package]]
name = "vlog_refactor"
version = "0.66.0"
version = "0.67.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.66.0"
version = "0.67.0"
dependencies = [
"vlog_parser",
]
+5 -1
View File
@@ -1,3 +1,5 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[workspace]
resolver = "2"
members = [
@@ -13,7 +15,7 @@ members = [
]
[workspace.package]
version = "0.66.0"
version = "0.67.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
@@ -44,3 +46,5 @@ serde_json = "=1.0.140"
[profile.release]
lto = true
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+37 -18
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# lucisv — Language Utility for Coding In SystemVerilog
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
@@ -57,6 +59,9 @@ lucisv --no-config rtl/
# pipe through stdin/stdout; --stdin-filename names the buffer in messages
cat foo.sv | lucisv -
cat foo.sv | lucisv --stdin-filename rtl/foo.sv -
# one JSON report (status, exit_code, summary, one entry per file) for CI
lucisv --check --output-format json rtl/
```
### Exit codes (frozen contract — CI may depend on it)
@@ -87,7 +92,10 @@ and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
thread count, where parallelism has already taken the easy win).
An entry is keyed on **(content hash, `line-length`, `indent`,
`uvm-utils-indent`, lucisv version)** per file, and only ever records the *already formatted* verdict — a file that
`uvm-utils-indent`, `style`, each `[format]` override — `begin`, `else`,
`else-after-label`, `port-lists`, `list-indent`, `alignment`,
`connection-align-min` —, lucisv version)** per file (since 0.67.0; lines
written by an older version are dropped as stale), and only ever records the *already formatted* verdict — a file that
would be reformatted, or that failed, is re-checked on every run. The store is one
text file in `.lucisv_cache/` (self-ignoring, like cargo's `target/`); deleting
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
@@ -190,6 +198,15 @@ off by default, indents the `` `uvm_field_* `` macros written between
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; like `style`,
it is a formatting choice lucisv leaves to the project, because it changes
bytes in existing UVM code (21 of the 860 corpus files).
Single layout choices can be overridden on top of the style (since 0.67.0):
`begin`, `else` and `else-after-label` (`same-line` or `own-line`),
`port-lists` (`fit` or `one-per-line`), `list-indent` (`block` or `wrap`),
`alignment` (`infer` or `always`) and `connection-align-min` (0–8, the spaces
before `(` on the widest row of an aligned connection or `#(…)` table). Each
applies over the named style, and under `style = "auto"` over every
candidate; the editor's spellings are `lucisv.format.begin`, `.else`,
`.elseAfterLabel`, `.portLists`, `.listIndent`, `.alignment` and
`.connectionAlignMin`, which a `lucisv.toml` outranks.
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
@@ -563,8 +580,8 @@ 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.
aligns its widest connection tight (`.clk(clk)`) and differs from its guide in
one place: a comment line ends an aligned table.
`auto` formats the file once per preset, at the configured indent and width,
and keeps the output that changes the fewest lines (indentation included, so
@@ -977,9 +994,8 @@ The editor now offers these refactorings alongside rename and port propagation:
| Inline module | Copy a separate-file module body into its instance site with simple named-connection substitution and collision-aware internal renaming |
The [language-tools reference](docs/site/src/content/docs/reference/language-tools.md)
records commands and refusal limits. Inline-module has a known transitive
source-selection gap; review hierarchical uses through wrapper modules before
applying it (topology handshake 33).
records commands and refusal limits (the inline-module transitive source-selection gap,
topology handshake 33, closed in v0.51.0).
In the VS Code hierarchy, **Star as DUT** groups a module’s children and
parents into sections alongside Other Modules. Stars persist per workspace;
@@ -996,7 +1012,7 @@ code --install-extension lucisv-<version>-darwin-arm64.vsix
```
— or take `lucisv-<version>-all.vsix`, which carries all five platforms' binaries
in one file and picks the right pair at startup, when the machine is not known
in one file and picks the right binaries at startup, when the machine is not known
in advance (or is Alpine, which VS Code never offers a Linux package to).
Every other editor (and the universal `lucisv-<version>.vsix`, the fallback
@@ -1004,7 +1020,7 @@ for platforms not listed) finds `lucisv-server` on `PATH`; the binary comes
from the same build as the CLI:
```bash
cargo build --release # target/release/lucisv-server (and target/release/lucisv)
cargo build --release # target/release/{lucisv,lucisv-server,lucisv-mcp}
cp target/release/lucisv-server ~/.local/bin/ # anywhere on PATH
```
@@ -1042,13 +1058,14 @@ vim.lsp.enable('lucisv')
`editors/nvim/README.md`.
**Agents (MCP).** `lucisv-mcp` is lucisv as a Model Context Protocol server
for coding agents: project overview, unit interfaces, outlines, one item's
source, definition/references/hierarchy, diagnostics, and verified edits
(format, lint fixes, rename, the port refactorings, single-item
replace/insert/delete), each with `dry_run`. The platform `.vsix` packages
carry it as a third binary and, on VS Code 1.101+, register it with agent
mode — one server per workspace folder, under **MCP: List Servers**
(`lucisv.mcp.enabled`, `lucisv.mcp.path`). For Claude Code or Cursor, run
for coding agents: nine lean tools in full mode (`hierarchy`, `find`, `outline`,
`read`, `check`, `rename`, `port`, `edit_item`, `format`) and five in
`--read-only` mode (`hierarchy`, `find`, `outline`, `read`, `check`), with no
dry run — edits verify everything in memory before writing all-or-nothing.
The platform `.vsix` packages carry it as a third binary and, on VS Code
1.101+, register it with agent mode — one server per workspace folder, under
**MCP: List Servers** (`lucisv.mcp.enabled`, `lucisv.mcp.path`,
`lucisv.mcp.mode`). For Claude Code or Cursor, run
**lucisv: Copy MCP server config** in VS Code, or by hand:
`cargo build --release -p lucisv_mcp`, then
`claude mcp add lucisv -- lucisv-mcp --root .`. The tool list, the config
@@ -1092,7 +1109,7 @@ expected; no PRs or review required.
## Building
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo build --release # binaries at target/release/{lucisv,lucisv-server,lucisv-mcp}
tools/gates.sh # every gate: fmt, clippy, build, each crate's suites, doc tests, corpus, node
tools/gates.sh --only suites # just the per-crate test suites
```
@@ -1116,8 +1133,8 @@ Prebuilt downloads live on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases): every tagged
version carries **seven `.vsix` packages** — platform-specific ones for
Apple Silicon and Intel macOS, x86-64 and ARM64 Linux (static musl) and
Windows, each with `lucisv` and `lucisv-server` embedded, an
all-platforms one carrying every pair at once for unknown or mixed
Windows, each with `lucisv`, `lucisv-server`, and `lucisv-mcp` embedded, an
all-platforms one carrying every platform's binaries at once for unknown or mixed
machines, plus the universal no-binary fallback — and a `SHA256SUMS` to
verify them with
(`shasum -a 256 -c SHA256SUMS`). Sideload the one for your machine with
@@ -1145,3 +1162,5 @@ where the version number lives, how the `.vsix` is packaged, and what
marketplace publishing would take if it ever happens — is in
[`tools/RELEASING.md`](tools/RELEASING.md). lucisv is MIT licensed
([`LICENSE`](LICENSE)).
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+4
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# ROADMAP — autonomous coverage loop
Running log of the coverage-improvement loop (started 2026-08-20). The metric
@@ -175,3 +177,5 @@ needs macro expansion, a deliberate non-goal) or not valid standalone
Verilog. The stop condition holds before round 1 of a restart, so **no dev
round was dispatched**. The loop resumes only if open question 2 is decided
(a preprocessing model would put ~1.7% back in reach) or the corpus grows.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+4
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# TODO-MCP — the Model Context Protocol block
Planned 2026-09-23 by the lead at 0.55.0. The analysis and design are in
@@ -498,3 +500,5 @@ Feature README `docs/features/mcp-read-only`. One dev (Opus), one QA
item's lines through `format_range` automatically — costs a refusal
path when the safety net objects. Default in this plan: not automatic;
the agent calls `format` with `lines`.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+78 -21
View File
@@ -1,3 +1,5 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# TODO — best practices adopted from ruff and Verible
Curated backlog for lucisv, drawn from `astral-sh/ruff` (architecture, CLI/UX,
@@ -7126,7 +7128,7 @@ resolution now roots an unknown head at a top module. Decide whether
completion should offer `tb.`'s hierarchical members, answering `None` when
the index has no unit of that name. `docs/features/top-rooted-paths`.
- [ ] owner/lead decision; if yes, `completion/member.rs` + tests
- [x] owner/lead decision; if yes, `completion/member.rs` + tests — **WON'T FIX (2026-11-26, Owner Decision #3: "no")**: keep "an unknown head answers nothing" in completion.
## 66. Format Selection that fits where it stands (planned 2026-11-09, owner's order)
@@ -7396,17 +7398,21 @@ indexing, collide with each other and with §70's test files, and wait for
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`
- [x] A comment between a generate `end` and `else` (also a trailing `// c`
after a labelled generate `end` before `else`) is a verification
error: the file is left unformatted. The safety net works; the
formatter should not need it.
- [ ] `` `ifdef `` between `end` and `else` is a parse error.
- [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
(Round 5, `parser-formatter-r5`, topo §2.9-44; released in 0.67.0.)
- [x] `` `ifdef `` between `end` and `else` is a parse error.
(Round 5, `parser-formatter-r5`, topo §2.9-45; released in 0.67.0.)
- [x] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
(Round 5, `parser-formatter-r5`, topo §2.9-46; released in 0.67.0.)
- [x] The server's `line-length` lint falls back to 100 columns under the
`ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken
when 71.1 merges.
- [ ] One-per-line styles give multi-instance declarations
- [x] One-per-line styles give multi-instance declarations
(`p1 u8 (...), u9 (...)`) the hanging layout.
(Round 5, `parser-formatter-r5`, topo §2.9-47; released in 0.67.0.)
- Wave 5 (lead, 2026-11-19): 71.1 shipped as 0.65.6 after a QA FAIL (four
stale answers), a fix round, a QA pass and a last small round. What the
@@ -7422,9 +7428,12 @@ indexing, collide with each other and with §70's test files, and wait for
- [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
- [x] A watcher event naming only a directory leaves stale state; an
excluded buffer stays indexed after close; symlinked files are held
under one or both spellings depending on what was open.
(Round 2, `index-lifecycle-r2`: excluded buffers and symlinks fixed,
topo §2.9-49/51; directory-only events won't-fix, §2.9-48; released in
0.67.0.)
71.3 (viewport highlighting) passed QA with a gap in the default folder
scope (colours wait out a widen, ~630 ms); it is rebased after 71.7 and
closes that in its fix round. Then 71.2.
@@ -7440,18 +7449,25 @@ indexing, collide with each other and with §70's test files, and wait for
- 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
- [x] A request held during a scan is answered against the newest text; a
position-based one can resolve a different symbol when an edit moved
the text under it, and rename edits carry no document version.
- [ ] An unheld buffer opened while a scan runs is never taken in
(Round 1, `server-ordering-r1`, topo §2.9-52; released in 0.67.0.)
- [x] An unheld buffer opened while a scan runs is never taken in
afterwards; closing an unsaved in-scope buffer a rescan had indexed
leaves its text in the index.
- [ ] Renaming a port of a module defined twice gives an edit or a refusal
(Round 2, `index-lifecycle-r2`, topo §2.9-49/50; released in 0.67.0.)
- [x] Renaming a port of a module defined twice gives an edit or a refusal
at random (`qa717/drv/dup.py`).
- [ ] Directory-only watcher events (needs a broader watcher
(Round 1, `refactor-correctness-r1` + `server-ordering-r1`, topo
§2.9-53; released in 0.67.0.)
- [x] Directory-only watcher events (needs a broader watcher
registration — the owner's call), excluded buffers after close (a
cheap fix belongs in the index layer: adding a file is a wide
change), symlink spellings.
(Round 2: excluded buffers and symlinks fixed, topo §2.9-49/51;
directory-only events won't-fix by owner ruling, §2.9-48; released in
0.67.0.)
- §70 closed (lead, 2026-11-19), shipped with 0.65.9. Once ssh was back the
suite proved flaky on Linux (3 of 9 runs): two test helpers that insisted
@@ -7462,39 +7478,80 @@ indexing, collide with each other and with §70's test files, and wait for
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
- [x] A file with an mtime in the future is re-read by `lucisv-mcp` on
every call, forever (67 ms against 7 ms per `find` on 4 000 files).
- [ ] `crates/lucisv/tests/cli.rs:2149` asserts only an empty stdout, no
(Round 3, `mcp-hardening-r3`, topo §2.9-54; released in 0.67.0.)
- [x] `crates/lucisv/tests/cli.rs:2149` asserts only an empty stdout, no
exit code.
- [ ] `crates/lucisv_mcp/tests/qa_m3.rs` uses unix-only APIs with no cfg:
(Round 5, `cli-path-r5`, topo §2.9-55; released in 0.67.0.)
- [x] `crates/lucisv_mcp/tests/qa_m3.rs` uses unix-only APIs with no cfg:
`cargo check --all-targets` for Windows fails there (tests only).
- [ ] The release is still gated on macOS alone; Windows is compile-checked
(Round 3, `mcp-hardening-r3`, topo §2.9-56; released in 0.67.0.)
- [x] The release is still gated on macOS alone; Windows is compile-checked
(`cross`), never executed.
(Round 4, `ci-gates-r4`, topo §2.9-57: the release now waits for a
Linux clippy + test job; Windows is still compile-checked only;
released in 0.67.0.)
- Wave 7 (lead, 2026-11-19): 71.3 shipped as 0.65.10, re-applied onto
0.65.8's message loop by hand and re-validated by a second QA round. Left
open from it:
- [ ] The discovery walk at the start of every scan answers nothing while
- [x] The discovery walk at the start of every scan answers nothing while
it runs: a late open in workspace scope still waits 62–86 ms for
colour and a rescan holds colours 70–159 ms. Making the walk
resumable needs its own identical-result proof (`state/discover.rs`).
- [ ] A `range` answered during a rescan always counts as a guess and
- [x] 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
(Round 9, `lsp-viewport-folding-r9`, topo §2.9-59; released in 0.67.0.)
- [x] An edit in one file that changes how another OPEN file colours sends
no refresh (as before this lane).
(Round 9, `lsp-viewport-folding-r9`, topo §2.9-60; released in 0.67.0.)
- Wave 8 (lead, 2026-11-19): 71.2 shipped as 0.65.11 after four dev rounds
and four QA rounds — two QA failures, so the last round ran with Fable 5.2
as dev and QA (`docs/features/fast-actions`, Review). Left open from it:
- [ ] Inside the startup settings wait, the client's answer to the pull is
- [x] Inside the startup settings wait, the client's answer to the pull is
applied ahead of an older settings push held with it
(`server/startup.rs`, `take_the_answer_out_of_held`; predates the
lane; needs a client whose push and answer disagree in one burst).
- [ ] `tests/fast_actions_bursts.rs`'s oracle accepts an answer the
(Round 1, `server-ordering-r1`, topo §2.9-61; released in 0.67.0.)
- [x] `tests/fast_actions_bursts.rs`'s oracle accepts an answer the
reference gives after any later message of the round: 2–9 % of
injected stale answers pass when a later message restores the state.
- [ ] Whether a large open buffer is in the index depends on when it was
(Round 1, `server-ordering-r1`, topo §2.9-62; released in 0.67.0.)
- [x] Whether a large open buffer is in the index depends on when it was
opened, saved or scanned (predates the lane; 77–98 answers differ
between a settled session and a fresh server on OpenTitan).
- [ ] The 40 000-file rescan after a delete takes either 12.3 s or
(Round 2, `index-lifecycle-r2`, topo §2.9-63; released in 0.67.0.)
- [x] The 40 000-file rescan after a delete takes either 12.3 s or
14.5–15.5 s, on 0.65.10 and on this tree alike; cause not found.
(Round 10: not reproducible on a quiet machine — unimodal 7.4–7.8 s
over 39 runs; closed as such in topo §2.9-64, remainder in #71/#72.)
## 72. Sticky scroll pins the module instance (planned 2026-11-19, owner's order)
Owner: "only the module definition is floating. I want to extend this a
little so that the module instance would be floating as well." Folds come
only from keyword pairs and `` `ifdef `` branches, so nothing delimited by
`( )` pins. Surveyed on OpenTitan `hw` (4 047 files): 162 instances of 50+
lines, none pinned; 132 of them write `#(` on the type line, so the instance
name sits on a later `) u_name (` line. Example:
`hw/ip/aes/rtl/aes_control_fsm_n.sv:382-594`. One lane (dev, then QA),
feature README `docs/features/instance-folding/README.md`.
- [x] `crates/lucisv_server/src/folding/instances.rs` (new): one fold per
multi-line module instantiation from its module-type line, and one more
per instance from the line its name is on when that is a different
line, so both `aes_control_fsm #(` and `) u_aes_control_fsm (` pin
while the reader is in the connection list. The closing line stays
visible, as for every scope fold.
- [x] `crates/lucisv_server/src/folding.rs`: the third source merged through
`in_answer_order`; every fold the server answered before is still
there, unchanged and first on a shared start line.
- [x] Tests in the same change, and `folding/opentitan_sweep.rs` extended:
instances counted independently, existing folds proven unchanged.
- [x] `editors/vscode/README.md`: the sticky-scroll row names the instance.
- [x] Seen in a running VS Code (owner, 2026-11-19, on the local 0.66.1
build). Shipped as 0.66.1.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+5
View File
@@ -1,6 +1,9 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
description = "A Verilog/SystemVerilog formatter, in the spirit of ruff"
@@ -15,3 +18,5 @@ vlog_parser = { path = "../vlog_parser" }
vlog_formatter = { path = "../vlog_formatter" }
vlog_linter = { path = "../vlog_linter" }
rayon = { workspace = true }
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+114 -7
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Hand-rolled command line parsing for the `lucisv` binary.
use lucisv_core::cache;
@@ -18,12 +20,12 @@ pub enum Command {
Check,
}
/// How `lucisv check` renders its diagnostics.
/// How `lucisv` renders its output when `--output-format` is given.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
/// `FILE:LINE:COL: message [rule-name]`, one per line.
/// Human-readable text (`would reformat: PATH`, `FILE:LINE:COL: message [rule]`).
Text,
/// One JSON array of diagnostic objects.
/// Structured JSON report (format mode) or array of diagnostic objects (`check`).
Json,
}
@@ -63,7 +65,7 @@ pub struct Options {
/// `--lines`: format only the constructs meeting these lines. `None` is a
/// whole-file run.
pub lines: Option<LineRanges>,
/// `check` only: how diagnostics are rendered.
/// How diagnostics (`check`) or format reports (`format`) are rendered.
pub output_format: OutputFormat,
/// `check` only: apply safe fixes and write the files back.
pub fix: bool,
@@ -119,6 +121,7 @@ impl Options {
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config.apply_overrides(overrides_from_file(file));
config
}
@@ -210,6 +213,11 @@ OPTIONS:
`auto` lays each file out in the preset it is
already closest to, at the default indent/width
--no-config ignore lucisv.toml / .lucisv.toml files
--output-format <FMT> `text` (default): human-readable text output;
`json`: structured JSON report (format mode) or
array of diagnostic objects (`check` mode). In
format mode, cannot be combined with `--diff`,
`--stdout`, or stdin without `--check`
-h, --help show this help
-V, --version show version
@@ -223,8 +231,6 @@ CHECK OPTIONS (`lucisv check` only):
off for a single file or a stdin buffer, where it cannot. `--select` runs
one either way; `--ignore`, or `ignore` under `[lint]` in lucisv.toml,
turns one off.
--output-format <FMT> `text` (default): FILE:LINE:COL: message [rule];
`json`: one array of diagnostic objects
--fix apply safe fixes and write the files back
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
one yet, so today this changes nothing)
@@ -405,6 +411,9 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
}
"--stdin-filename" => {
let v = args.next().ok_or("--stdin-filename requires a value")?;
if v.is_empty() {
return Err("--stdin-filename requires a non-empty path".to_string());
}
opts.stdin_filename = Some(v);
}
"--line-length" => {
@@ -509,7 +518,6 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
let lint_only = [
(opts.fix, "--fix"),
(opts.unsafe_fixes, "--unsafe-fixes"),
(opts.output_format != OutputFormat::Text, "--output-format"),
(!opts.select.is_empty(), "--select"),
(!opts.ignore.is_empty(), "--ignore"),
(!opts.waiver_files.is_empty(), "--waiver-file"),
@@ -528,6 +536,19 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
return Err(format!("{flag} is only valid for `lucisv check`"));
}
}
if opts.output_format == OutputFormat::Json {
if opts.diff {
return Err("--output-format json cannot be combined with --diff".to_string());
}
if opts.stdout {
return Err("--output-format json cannot be combined with --stdout".to_string());
}
if opts.is_stdin() && !opts.check {
return Err(
"--output-format json requires --check when reading from stdin".to_string()
);
}
}
}
Command::Check => {
for (given, flag) in format_only {
@@ -543,6 +564,20 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
Ok(())
}
/// Map optional `[format]` keys from `lucisv.toml` into [`vlog_formatter::StyleOverrides`].
fn overrides_from_file(file: &FileConfig) -> vlog_formatter::StyleOverrides {
use vlog_formatter::{Alignment, ListIndent, Placement, PortLists, StyleOverrides};
StyleOverrides {
begin: file.format_begin.and_then(Placement::parse),
else_keyword: file.format_else.and_then(Placement::parse),
else_after_label: file.format_else_after_label.and_then(Placement::parse),
port_lists: file.format_port_lists.and_then(PortLists::parse),
list_indent: file.format_list_indent.and_then(ListIndent::parse),
alignment: file.format_alignment.and_then(Alignment::parse),
connection_align_min: file.format_connection_align_min,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -635,6 +670,55 @@ mod tests {
}
}
#[test]
fn the_core_format_override_choices_match_the_formatter() {
use vlog_formatter::{Alignment, ListIndent, Placement, PortLists};
assert_eq!(config::PLACEMENT_NAMES, ["same-line", "own-line"]);
for name in config::PLACEMENT_NAMES {
assert_eq!(Placement::parse(name).map(Placement::as_str), Some(name));
}
assert_eq!(config::PORT_LISTS_NAMES, ["fit", "one-per-line"]);
for name in config::PORT_LISTS_NAMES {
assert_eq!(PortLists::parse(name).map(PortLists::as_str), Some(name));
}
assert_eq!(config::LIST_INDENT_NAMES, ["block", "wrap"]);
for name in config::LIST_INDENT_NAMES {
assert_eq!(ListIndent::parse(name).map(ListIndent::as_str), Some(name));
}
assert_eq!(config::ALIGNMENT_NAMES, ["infer", "always"]);
for name in config::ALIGNMENT_NAMES {
assert_eq!(Alignment::parse(name).map(Alignment::as_str), Some(name));
}
}
#[test]
fn config_with_layers_selective_format_overrides_over_style_and_auto() {
use vlog_formatter::{Alignment, Placement};
let file = FileConfig {
format_style: Some("google"),
format_begin: Some("own-line"),
format_connection_align_min: Some(0),
..Default::default()
};
let cfg = parse(&["rtl"]).unwrap().config_with(&file);
assert_eq!(cfg.style.name, "google");
assert_eq!(cfg.style.begin, Placement::OwnLine);
assert_eq!(cfg.style.connection_align_min, 0);
let cli_lowrisc = parse(&["--style", "lowrisc", "rtl"]).unwrap().config_with(&file);
assert_eq!(cli_lowrisc.style.name, "lowrisc");
assert_eq!(cli_lowrisc.style.begin, Placement::OwnLine);
let auto_file = FileConfig {
format_style: Some("auto"),
format_alignment: Some("always"),
..Default::default()
};
let auto_cfg = parse(&["rtl"]).unwrap().config_with(&auto_file);
assert!(auto_cfg.auto_style);
assert_eq!(auto_cfg.overrides.alignment, Some(Alignment::Always));
}
#[test]
fn config_excludes_are_appended_to_cli_excludes() {
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
@@ -750,4 +834,27 @@ mod tests {
assert!(parse(&["--rules-doc"]).is_err());
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
}
#[test]
fn format_output_format_json_and_stdin_filename_validation() {
assert_eq!(
parse(&["--check", "--output-format", "json", "a.sv"]).unwrap().output_format,
OutputFormat::Json
);
assert_eq!(
parse(&["--output-format", "json", "a.sv"]).unwrap().output_format,
OutputFormat::Json
);
assert_eq!(
parse(&["--check", "--output-format", "json", "-"]).unwrap().output_format,
OutputFormat::Json
);
assert!(parse(&["--diff", "--output-format", "json", "a.sv"]).is_err());
assert!(parse(&["--stdout", "--output-format", "json", "a.sv"]).is_err());
assert!(parse(&["--output-format", "json", "-"]).is_err());
assert!(parse(&["--output-format", "text", "--stdout", "a.sv"]).is_ok());
assert!(parse(&["--stdin-filename", "", "-"]).is_err());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,5 +1,9 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `--diff`'s unified diff. The printer lives in `lucisv_core::diff`, shared
//! with the MCP server's `dry_run` (Handshake MCP-1, a pure move); this module
//! keeps the CLI's `diff::unified` path.
pub use lucisv_core::diff::unified;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+6 -2
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The `lucisv check` driver: lint files, print diagnostics, apply fixes.
//!
//! Everything about *which* files are linted — the walk, `--exclude`,
@@ -342,7 +344,7 @@ fn reads_packages(rule: &'static dyn Rule) -> bool {
}
/// The command line's list when it said anything, else the config file's.
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
pub(crate) fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
if cli.is_empty() {
config.unwrap_or(&[])
} else {
@@ -712,7 +714,7 @@ fn fix_json(violation: &Violation) -> String {
/// A JSON string literal. Hand-rolled: the shape is three fields deep and
/// pulling in a serialization framework for it is not a trade worth making.
fn quote(text: &str) -> String {
pub(crate) fn quote(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
@@ -880,3 +882,5 @@ mod tests {
assert_eq!(quote("bell\u{7}"), "\"bell\\u0007\"");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+310 -75
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! lucisv — a Verilog/SystemVerilog formatter and linter in the spirit of
//! `ruff format` and `ruff check`.
//!
@@ -21,18 +23,22 @@ use std::cell::Cell;
use std::collections::HashSet;
use std::io::Read;
use std::panic::AssertUnwindSafe;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use args::{Command, Options, OutputFormat};
use lucisv_core::atomic::write_atomic;
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
use lucisv_core::path::normalize_under;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use vlog_formatter::{
format_range, format_source, Alignment, Config, FormatError, LineRanges, ListIndent, Placement,
PortLists, VerificationError,
};
use vlog_parser::PARSE_STACK_SIZE;
fn main() -> ExitCode {
@@ -99,46 +105,13 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
if opts.is_stdin() {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
return match run_check_stdin(opts) {
Ok(code) => code,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
ExitCode::from(2)
}
};
let mut src = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
eprintln!("error: reading stdin: {e}");
return ExitCode::from(2);
}
// A stdin buffer is one text with nothing around it: there is no
// census to build and no other file to ask about, so the rules that
// need a project stay off. `--select` still reaches them.
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it exactly as `[lint] select` does.
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
Ok(external) => external,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -156,6 +129,31 @@ fn run_check(opts: &Options) -> ExitCode {
}
}
/// Lints one stdin buffer under the project config governing `--stdin-filename`
/// (or the working directory), applying CLI over config rule selection.
fn run_check_stdin(opts: &Options) -> Result<ExitCode, String> {
let (config, file_config) = stdin_config(opts)?;
let mut src = String::new();
std::io::stdin().read_to_string(&mut src).map_err(|e| format!("reading stdin: {e}"))?;
// A stdin buffer is one text with nothing around it: there is no census
// to build and no other file to ask about, so workspace rules stay off.
let select = lint::pick(&opts.select, file_config.lint_select.as_deref());
let ignore = lint::pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, false).map_err(|e| {
let origin = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string());
format!("{origin}: {e}")
})?;
let options = lint::rule_options(&file_config)?;
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it alongside `[lint] select` and `[lint.<rule>]`.
let external = lint::external_waivers(opts, std::iter::once(&file_config))?;
Ok(lint::check_stdin(opts, &src, &config, &rules, &options, &external))
}
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let (config, _file_config) = match stdin_config(opts) {
@@ -168,15 +166,32 @@ fn run_stdin(opts: &Options) -> ExitCode {
let mut src = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
eprintln!("error: reading stdin: {e}");
if opts.output_format == OutputFormat::Json {
let info = FormatErrorInfo::io(&e);
let entries = [JsonEntry::error(name.to_string(), info)];
print_format_json(&entries, true, 0, 0, 0, 1);
}
return ExitCode::from(2);
}
let out = match format_contained(&src, &config, opts.lines.as_ref()) {
Ok(o) => o,
Err(e) => {
eprintln!("error: {name}: {e}");
Err(info) => {
eprintln!("error: {name}: {}", info.display);
if opts.output_format == OutputFormat::Json {
let entries = [JsonEntry::error(name.to_string(), info)];
print_format_json(&entries, true, 0, 0, 0, 1);
}
return ExitCode::from(2);
}
};
if opts.output_format == OutputFormat::Json {
let changed = usize::from(out != src);
let unchanged = usize::from(out == src);
let status = if changed > 0 { "would-reformat" } else { "unchanged" };
let entries = [JsonEntry::ok(name.to_string(), status, false)];
print_format_json(&entries, true, changed, unchanged, 0, 0);
return if changed > 0 { ExitCode::from(1) } else { ExitCode::SUCCESS };
}
if !opts.read_only() {
print!("{out}");
return ExitCode::SUCCESS;
@@ -216,31 +231,53 @@ fn run_files(opts: &Options) -> ExitCode {
let results: Vec<FileResult> =
jobs.par_iter().map(|(file, config, _)| process_file(file, config, opts, &cache)).collect();
let json = opts.output_format == OutputFormat::Json;
let mut entries = if json { Vec::with_capacity(results.len()) } else { Vec::new() };
let (mut changed, mut unchanged, mut errors, mut cached) = (0usize, 0usize, 0usize, 0usize);
for (index, result) in results.into_iter().enumerate() {
let (file, config, _) = &jobs[index];
if let Some(content) = result.clean {
cache.record(file, entry_for(content, config));
}
let name = || file.display().to_string();
match result.outcome {
Outcome::Unchanged => unchanged += 1,
Outcome::Unchanged => {
unchanged += 1;
if json {
entries.push(JsonEntry::ok(name(), "unchanged", false));
}
}
Outcome::Cached => {
unchanged += 1;
cached += 1;
if json {
entries.push(JsonEntry::ok(name(), "cached", true));
}
}
Outcome::Printed(text) => print!("{text}"),
Outcome::Changed(text) => {
changed += 1;
print!("{text}");
if json {
let status = if opts.read_only() { "would-reformat" } else { "reformatted" };
entries.push(JsonEntry::ok(name(), status, false));
} else {
print!("{text}");
}
}
Outcome::Failed(message) => {
Outcome::Failed(info) => {
errors += 1;
eprintln!("error: {message}");
eprintln!("error: {}: {}", file.display(), info.display);
if json {
entries.push(JsonEntry::error(name(), info));
}
}
}
}
cache.store();
if json {
print_format_json(&entries, opts.read_only(), changed, unchanged, cached, errors);
}
if !opts.stdout {
report(opts, changed, unchanged, cached, errors);
}
@@ -285,8 +322,8 @@ enum Outcome {
/// The file would change, or did. The text is the `--diff` hunk or the
/// `--check` line, and is empty when the file was rewritten in place.
Changed(String),
/// `<path>: <what went wrong>`. The file was left untouched.
Failed(String),
/// What went wrong while reading, formatting, or writing the file.
Failed(FormatErrorInfo),
}
/// Formats one file and, unless the run is read-only, writes it back.
@@ -296,7 +333,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
let name = file.display();
let src = match std::fs::read_to_string(file) {
Ok(s) => s,
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
Err(e) => return FileResult::plain(Outcome::Failed(FormatErrorInfo::io(&e))),
};
let hash = content_hash(src.as_bytes());
if cache.is_clean(file, entry_for(hash, config)) {
@@ -304,7 +341,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
}
let out = match format_contained(&src, config, opts.lines.as_ref()) {
Ok(o) => o,
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
Err(info) => return FileResult::plain(Outcome::Failed(info)),
};
if opts.stdout {
return FileResult::plain(Outcome::Printed(out));
@@ -318,7 +355,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
} else if opts.check {
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
FileResult::plain(Outcome::Failed(FormatErrorInfo::io(&e)))
} else {
// The bytes now on disk are formatted, so they are what the cache
// records — not the input's hash.
@@ -333,12 +370,36 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
/// the key, not the config file that produced them, so identical settings
/// from different `lucisv.toml` files share entries.
fn entry_for(content: u64, config: &Config) -> Entry {
if config.auto_style {
return Entry {
content,
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
style: config.style_name(),
begin: config.overrides.begin.map_or("auto", Placement::as_str),
else_keyword: config.overrides.else_keyword.map_or("auto", Placement::as_str),
else_after_label: config.overrides.else_after_label.map_or("auto", Placement::as_str),
port_lists: config.overrides.port_lists.map_or("auto", PortLists::as_str),
list_indent: config.overrides.list_indent.map_or("auto", ListIndent::as_str),
alignment: config.overrides.alignment.map_or("auto", Alignment::as_str),
connection_align_min: config.overrides.connection_align_min,
};
}
let effective = config.effective_style();
Entry {
content,
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
style: config.style_name(),
begin: effective.begin.as_str(),
else_keyword: effective.else_keyword.as_str(),
else_after_label: effective.else_after_label.as_str(),
port_lists: effective.port_lists.as_str(),
list_indent: effective.list_indent.as_str(),
alignment: effective.alignment.as_str(),
connection_align_min: Some(effective.connection_align_min),
}
}
@@ -439,25 +500,7 @@ fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
/// best two names for it can be compared by. Neither is ever the path lucisv
/// reports: that stays the first spelling seen.
fn identity(cwd: &Path, path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
/// answers for paths that do not exist, where there is nothing to resolve.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
std::fs::canonicalize(path).unwrap_or_else(|_| normalize_under(cwd, path))
}
/// The settings for a buffer piped in on stdin: discovery anchors on
@@ -467,7 +510,7 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
let file = match opts.stdin_filename.as_deref().filter(|s| !s.is_empty()) {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
@@ -498,6 +541,153 @@ fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, error
}
}
/// Structured error detail for `--output-format json` paired with the text
/// display string used on stderr.
#[derive(Debug, Clone, PartialEq, Eq)]
struct FormatErrorInfo {
category: &'static str,
line: Option<u32>,
column: Option<u32>,
message: String,
display: String,
}
impl FormatErrorInfo {
fn io(err: &std::io::Error) -> Self {
let message = err.to_string();
Self { category: "io-error", line: None, column: None, display: message.clone(), message }
}
fn panic(msg: &str) -> Self {
let message = format!("panicked while formatting: {msg}");
Self { category: "panic", line: None, column: None, display: message.clone(), message }
}
fn from_format(err: &FormatError) -> Self {
let display = err.to_string();
match err {
FormatError::Source(vlog_parser::Error::Lex(e)) => Self {
category: "lex-error",
line: Some(e.line),
column: Some(e.col),
message: e.message.clone(),
display,
},
FormatError::Source(vlog_parser::Error::Parse(e)) => Self {
category: "parse-error",
line: Some(e.line),
column: Some(e.col),
message: e.message.clone(),
display,
},
FormatError::Verification(v) => {
let (line, column) = verification_location(v);
Self {
category: "verification-error",
line,
column,
message: display.clone(),
display,
}
}
FormatError::Selection(msg) => Self {
category: "selection-error",
line: None,
column: None,
message: msg.clone(),
display,
},
}
}
}
fn verification_location(err: &VerificationError) -> (Option<u32>, Option<u32>) {
match err {
VerificationError::Lex { error, .. } => (Some(error.line), Some(error.col)),
VerificationError::Reparse(vlog_parser::Error::Lex(e)) => (Some(e.line), Some(e.col)),
VerificationError::Reparse(vlog_parser::Error::Parse(e)) => (Some(e.line), Some(e.col)),
VerificationError::Divergence { expected, got, .. } => {
expected.as_ref().or(got.as_ref()).map_or((None, None), |i| (Some(i.line), Some(i.col)))
}
VerificationError::NotConverged { line, .. } => (u32::try_from(*line).ok(), None),
}
}
struct JsonEntry {
filename: String,
status: &'static str,
cached: bool,
error: Option<FormatErrorInfo>,
}
impl JsonEntry {
fn ok(filename: String, status: &'static str, cached: bool) -> Self {
Self { filename, status, cached, error: None }
}
fn error(filename: String, info: FormatErrorInfo) -> Self {
Self { filename, status: "error", cached: false, error: Some(info) }
}
}
fn format_json_report(
entries: &[JsonEntry],
read_only: bool,
changed: usize,
unchanged: usize,
cached: usize,
errors: usize,
) -> String {
let (status, exit_code) = if errors > 0 {
("error", 2)
} else if read_only && changed > 0 {
("would-reformat", 1)
} else if changed > 0 {
("reformatted", 0)
} else {
("ok", 0)
};
let items: Vec<String> = entries
.iter()
.map(|entry| {
let err = match &entry.error {
Some(info) => format!(
"{{\"category\":{},\"line\":{},\"column\":{},\"message\":{}}}",
lint::quote(info.category),
info.line.map_or_else(|| "null".to_string(), |n| n.to_string()),
info.column.map_or_else(|| "null".to_string(), |n| n.to_string()),
lint::quote(&info.message),
),
None => "null".to_string(),
};
format!(
"{{\"filename\":{},\"status\":{},\"cached\":{},\"error\":{err}}}",
lint::quote(&entry.filename),
lint::quote(entry.status),
entry.cached,
)
})
.collect();
format!(
"{{\"status\":{},\"exit_code\":{exit_code},\
\"summary\":{{\"changed\":{changed},\"unchanged\":{unchanged},\"cached\":{cached},\"errors\":{errors}}},\
\"files\":[{}]}}",
lint::quote(status),
items.join(","),
)
}
fn print_format_json(
entries: &[JsonEntry],
read_only: bool,
changed: usize,
unchanged: usize,
cached: usize,
errors: usize,
) {
println!("{}", format_json_report(entries, read_only, changed, unchanged, cached, errors));
}
/// Formats one source text — all of it, or only the constructs meeting
/// `lines` — reporting a panic inside the formatter as an ordinary error so
/// the rest of the run can continue.
@@ -505,14 +695,14 @@ fn format_contained(
src: &str,
config: &Config,
lines: Option<&LineRanges>,
) -> Result<String, String> {
) -> Result<String, FormatErrorInfo> {
match catch_panic(|| match lines {
Some(lines) => format_range(src, config, lines),
None => format_source(src, config),
}) {
Ok(Ok(out)) => Ok(out),
Ok(Err(e)) => Err(e.to_string()),
Err(msg) => Err(format!("panicked while formatting: {msg}")),
Ok(Err(e)) => Err(FormatErrorInfo::from_format(&e)),
Err(msg) => Err(FormatErrorInfo::panic(&msg)),
}
}
@@ -659,10 +849,55 @@ mod tests {
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
assert!(err.contains("parse error"), "{err}");
assert_eq!(err.category, "parse-error");
assert!(err.display.contains("parse error"), "{}", err.display);
// A range run parses just as strictly: it cannot rescue broken input.
let lines = LineRanges::parse("1").expect("range");
let err = format_contained("module", &Config::default(), Some(&lines)).unwrap_err();
assert!(err.contains("parse error"), "{err}");
assert_eq!(err.category, "parse-error");
assert!(err.display.contains("parse error"), "{}", err.display);
}
#[test]
fn format_error_info_classifies_lex_verification_io_and_panic() {
let lex = format_contained("module m;\n int é;\nendmodule\n", &Config::default(), None)
.unwrap_err();
assert_eq!(lex.category, "lex-error");
assert_eq!((lex.line, lex.column), (Some(2), Some(7)));
let io = FormatErrorInfo::io(&std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
assert_eq!(io.category, "io-error");
assert_eq!((io.line, io.column), (None, None));
let panic_err = FormatErrorInfo::panic("boom");
assert_eq!(panic_err.category, "panic");
assert!(panic_err.message.contains("boom"));
let ver = FormatErrorInfo::from_format(&FormatError::Verification(
VerificationError::NotConverged {
line: 12,
first: "a".to_string(),
second: "b".to_string(),
},
));
assert_eq!(ver.category, "verification-error");
assert_eq!((ver.line, ver.column), (Some(12), None));
let report = format_json_report(
&[
JsonEntry::ok("a.sv".to_string(), "unchanged", false),
JsonEntry::error("b.sv".to_string(), lex),
],
true,
0,
1,
0,
1,
);
assert!(report.contains("\"status\":\"error\""), "{report}");
assert!(report.contains("\"exit_code\":2"), "{report}");
assert!(report.contains("\"category\":\"lex-error\""), "{report}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+314 -2
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
@@ -1190,7 +1192,8 @@ fn flags_of_the_other_tool_are_rejected() {
for args in [
vec!["--fix", &path],
vec!["--select", "no-tabs", &path],
vec!["--output-format", "json", &path],
vec!["--ignore", "no-tabs", &path],
vec!["--waiver-file", "a.waiver", &path],
] {
let out = run(&args);
assert_eq!(code(&out), 2, "{args:?} must not be accepted by the formatter");
@@ -1292,7 +1295,9 @@ fn cache_line(
version: &str,
) -> String {
let hash = lucisv_core::cache::content_hash(content.as_bytes());
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\tlucisv\t{version}\t{path}\n")
format!(
"{hash:016x}\t{line_length}\t{indent}\t{uvm}\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{version}\t{path}\n"
)
}
#[test]
@@ -2147,8 +2152,10 @@ fn a_stdin_buffer_reads_the_rule_options_too() {
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(code(&out), 0, "the config's pattern accepts it: {}", stderr(&out));
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert_eq!(code(&plain), 1, "without the config, macro-name-style fires: {}", stderr(&plain));
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
@@ -2463,3 +2470,308 @@ fn text_that_merely_says_package_changes_no_finding() {
"{plain}\n---\n{with_noise}"
);
}
// ----------------------------------------------------------------------
// Stdin config discovery across format/check and `--output-format json`
// (Round 5A: #11, #55)
// ----------------------------------------------------------------------
fn run_in_with_stdin(dir: &TempDir, args: &[&str], input: &str) -> Output {
let mut child = Command::new(LUCISV)
.args(with_no_cache(args))
.current_dir(&dir.path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn lucisv");
feed(&mut child, input);
child.wait_with_output().expect("run lucisv")
}
#[test]
fn stdin_discovers_config_relative_to_stdin_filename_across_cwd_and_subcommands() {
let dir = TempDir::new("stdin-cwd-discovery");
dir.write("lucisv.toml", "indent = 4\n[lint]\nignore = [\"no-tabs\"]\n");
dir.write("sub/lucisv.toml", "indent = 6\n[lint]\nselect = [\"no-tabs\"]\n");
let sub_dir = TempDir { path: dir.path.join("sub") };
// From root CWD, relative `sub/new.sv` (which does not exist on disk)
// picks up `sub/lucisv.toml` for both format and check.
let fmt_sub =
run_in_with_stdin(&dir, &["format", "--stdin-filename", "sub/new.sv", "-"], UNINDENTED);
assert_eq!(code(&fmt_sub), 0, "{}", stderr(&fmt_sub));
assert_eq!(stdout(&fmt_sub), "module m;\n wire x;\nendmodule\n");
let chk_sub = run_in_with_stdin(
&dir,
&["check", "--stdin-filename", "sub/new.sv", "-"],
"module new;\n\twire a;\nendmodule\n",
);
assert_eq!(code(&chk_sub), 1, "{}", stderr(&chk_sub));
assert!(stdout(&chk_sub).contains("[no-tabs]"), "{}", stdout(&chk_sub));
assert!(
!stdout(&chk_sub).contains("module-filename"),
"select in sub/lucisv.toml governs stdin"
);
// From `sub/` CWD, `../rtl/m.sv` climbs back out of `sub/` to root's config,
// ignoring `sub/lucisv.toml` (`indent = 6`, `select = ["no-tabs"]`).
let fmt_parent =
run_in_with_stdin(&sub_dir, &["--stdin-filename", "../rtl/m.sv", "-"], UNINDENTED);
assert_eq!(code(&fmt_parent), 0, "{}", stderr(&fmt_parent));
assert_eq!(stdout(&fmt_parent), INDENT_4);
let chk_parent = run_in_with_stdin(
&sub_dir,
&["check", "--stdin-filename", "../rtl/m.sv", "-"],
"module m;\n\twire a;\nendmodule\n",
);
assert_eq!(code(&chk_parent), 0, "parent config ignores no-tabs: {}", stderr(&chk_parent));
assert_eq!(stdout(&chk_parent), "");
// Do not drop `sub_dir` (it shares `dir.path`); forget it safely.
std::mem::forget(sub_dir);
// Unknown rule in `lucisv.toml`'s `[lint] select` still fails stdin check with exit 2.
dir.write("bad_lint/lucisv.toml", "[lint]\nselect = [\"no-such-rule\"]\n");
let bad_rule =
run_in_with_stdin(&dir, &["check", "--stdin-filename", "bad_lint/m.sv", "-"], FORMATTED);
assert_eq!(code(&bad_rule), 2);
assert!(stderr(&bad_rule).contains("unknown rule: no-such-rule"), "{}", stderr(&bad_rule));
// An empty `--stdin-filename` is rejected explicitly instead of walking CWD's parent.
let empty = run_with_stdin(&["--stdin-filename", "", "-"], UNINDENTED);
assert_eq!(code(&empty), 2);
assert!(
stderr(&empty).contains("--stdin-filename requires a non-empty path"),
"{}",
stderr(&empty)
);
}
#[test]
fn format_output_format_json_covers_clean_dirty_inplace_cached_and_errors() {
let dir = TempDir::new("format-json");
let clean = dir.write("a_clean.sv", FORMATTED);
let dirty = dir.write("b_dirty.sv", UNFORMATTED);
let bad_parse = dir.write("c_parse.sv", UNPARSEABLE);
let bad_lex = dir.write("d_lex.sv", "module m;\n int é;\nendmodule\n");
// Clean (--check): exit 0, unchanged.
let out = run(&["--check", "--output-format", "json", &clean]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"ok\""), "{text}");
assert!(text.contains("\"exit_code\":0"), "{text}");
assert!(text.contains("\"changed\":0,\"unchanged\":1,\"cached\":0,\"errors\":0"), "{text}");
assert!(text.contains("\"status\":\"unchanged\",\"cached\":false,\"error\":null"), "{text}");
// Dirty (--check): exit 1, would-reformat, file untouched.
let out = run(&["--check", "--output-format", "json", &dirty]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"would-reformat\""), "{text}");
assert!(text.contains("\"exit_code\":1"), "{text}");
assert!(text.contains("\"changed\":1,\"unchanged\":0,\"cached\":0,\"errors\":0"), "{text}");
assert!(
text.contains("\"status\":\"would-reformat\",\"cached\":false,\"error\":null"),
"{text}"
);
assert_eq!(dir.read("b_dirty.sv"), UNFORMATTED);
// Parse error: exit 2, category parse-error with line/column/message.
let out = run(&["--check", "--output-format", "json", &bad_parse]);
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"status\":\"error\""), "{text}");
assert!(text.contains("\"exit_code\":2"), "{text}");
assert!(text.contains("\"category\":\"parse-error\""), "{text}");
assert!(text.contains("\"line\":2,\"column\":1"), "{text}");
assert!(text.contains("expected identifier"), "{text}");
assert_eq!(dir.read("c_parse.sv"), UNPARSEABLE);
// Lex error: exit 2, category lex-error with line/column/message.
let out = run(&["--check", "--output-format", "json", &bad_lex]);
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"category\":\"lex-error\""), "{text}");
assert!(text.contains("\"line\":2,\"column\":7"), "{text}");
// Mixed directory run: deterministic across thread counts, exit 2 wins.
let parallel = run(&["--check", "--output-format", "json", &dir.root()]);
let serial = run(&["--threads", "1", "--check", "--output-format", "json", &dir.root()]);
assert_eq!(code(&parallel), 2);
assert_eq!(parallel.stdout, serial.stdout);
let text = stdout(&parallel);
assert!(text.contains("\"changed\":1,\"unchanged\":1,\"cached\":0,\"errors\":2"), "{text}");
assert_eq!(text.lines().count(), 1, "stdout must be one JSON document: {text}");
// In-place formatting (default format mode without --check) with JSON + cache.
let cache = dir.cache();
let out = run_raw(&["--output-format", "json", "--cache-dir", &cache, &dirty]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"reformatted\""), "{text}");
assert!(text.contains("\"exit_code\":0"), "{text}");
assert_eq!(dir.read("b_dirty.sv"), FORMATTED);
let cached_out =
run_raw(&["--check", "--output-format", "json", "--cache-dir", &cache, &dirty]);
assert_eq!(code(&cached_out), 0, "{}", stderr(&cached_out));
let text = stdout(&cached_out);
assert!(text.contains("\"status\":\"cached\",\"cached\":true"), "{text}");
assert!(text.contains("\"unchanged\":1,\"cached\":1"), "{text}");
}
#[test]
fn format_output_format_json_works_on_stdin_check_and_rejects_conflicts() {
let out = run_with_stdin(&["--check", "--output-format", "json", "-"], FORMATTED);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(
stdout(&out).contains("\"filename\":\"<stdin>\",\"status\":\"unchanged\""),
"{}",
stdout(&out)
);
let out = run_with_stdin(
&["--check", "--output-format", "json", "--stdin-filename", "rtl/top.sv", "-"],
UNFORMATTED,
);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.contains("\"filename\":\"rtl/top.sv\",\"status\":\"would-reformat\""), "{text}");
assert!(text.contains("\"exit_code\":1"), "{text}");
let out = run_with_stdin(&["--check", "--output-format", "json", "-"], UNPARSEABLE);
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("\"category\":\"parse-error\""), "{}", stdout(&out));
let out = run_with_stdin(
&["--check", "--output-format", "json", "-"],
"module m;\n int é;\nendmodule\n",
);
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("\"category\":\"lex-error\""), "{}", stdout(&out));
let dir = TempDir::new("format-json-conflicts");
let file = dir.write("a.sv", UNFORMATTED);
for bad in [
vec!["--diff", "--output-format", "json", &file],
vec!["--stdout", "--output-format", "json", &file],
vec!["--output-format", "json", "-"],
] {
let out = run_with_stdin(&bad, UNFORMATTED);
assert_eq!(code(&out), 2, "{bad:?}");
}
}
#[cfg(unix)]
#[test]
fn format_output_format_json_reports_io_error_on_unreadable_file() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("format-json-io");
let locked = dir.write("locked.sv", FORMATTED);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).expect("chmod");
if std::fs::read_to_string(&locked).is_ok() {
let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755));
eprintln!("skipped: a mode-000 file is readable by this user (root?)");
return;
}
let out = run(&["--check", "--output-format", "json", &locked]);
let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644));
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"status\":\"error\""), "{text}");
assert!(text.contains("\"exit_code\":2"), "{text}");
assert!(text.contains("\"category\":\"io-error\""), "{text}");
assert!(text.contains("\"line\":null,\"column\":null"), "{text}");
}
#[test]
fn changing_any_selective_format_override_invalidates_the_cache_entry() {
let dir = TempDir::new("cache-overrides");
let src = "\
module m;
always_comb
if (a) begin
x = 1;
end
endmodule
";
dir.write("lucisv.toml", "[format]\nbegin = \"same-line\"\n");
let path = dir.write("a.sv", src);
let cache = dir.cache();
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
let warm = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&warm), 0, "{}", stderr(&warm));
assert!(stderr(&warm).contains("1 file from cache"), "{}", stderr(&warm));
// Toggle `begin` -> `own-line`: must miss cache and detect reformat needed.
dir.write("lucisv.toml", "[format]\nbegin = \"own-line\"\n");
let flipped = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&flipped), 1, "{}", stderr(&flipped));
assert!(!stderr(&flipped).contains("from cache"), "{}", stderr(&flipped));
// Format under `own-line`, warm cache, then flip back to `same-line`.
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
let warm_own = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert!(stderr(&warm_own).contains("1 file from cache"), "{}", stderr(&warm_own));
dir.write("lucisv.toml", "[format]\nbegin = \"same-line\"\n");
let back = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&back), 1, "invalidates back too: {}", stderr(&back));
// And under `style = "auto"`: adding `begin = "same-line"` on an Allman
// file (where `auto` with no override chose `ansi` = `own-line`) MUST
// invalidate the cache even though LUCISV's default is `same-line`.
let allman = "\
module m;
always_comb
if (a)
begin
x = 1;
end
endmodule
";
dir.write("lucisv.toml", "[format]\nstyle = \"auto\"\n");
dir.write("a.sv", allman);
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
assert!(
stderr(&run_raw(&["--check", &path, "--cache-dir", &cache])).contains("1 file from cache")
);
dir.write("lucisv.toml", "[format]\nstyle = \"auto\"\nbegin = \"same-line\"\n");
let auto_overridden = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(
code(&auto_overridden),
1,
"override on auto must miss un-overridden auto entry: {}",
stderr(&auto_overridden)
);
}
#[test]
fn an_older_seven_field_store_is_rebuilt() {
let dir = TempDir::new("cache-old7");
let path = dir.write("a.sv", FORMATTED);
let cache = dir.cache();
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
let hash = lucisv_core::cache::content_hash(FORMATTED.as_bytes());
std::fs::write(
dir.cache_file(),
format!("{hash:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{path}\n"),
)
.unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
let warm = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert!(stderr(&warm).contains("1 file from cache"), "{}", stderr(&warm));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+64
View File
@@ -1,3 +1,5 @@
// 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
@@ -169,3 +171,65 @@ fn changing_the_style_invalidates_the_cache_entry() {
let out = run(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
}
#[test]
fn selective_format_overrides_apply_over_preset_and_auto() {
let dir = TempDir::new("overrides");
dir.write(
"lucisv.toml",
"[format]\nstyle = \"google\"\nbegin = \"own-line\"\nalignment = \"always\"\nconnection-align-min = 0\n",
);
let src = "\
module m (input logic clk, input logic [7:0] data);
always_comb if (clk) begin x = 1; end
sub #(.A(1), .LONGER(2)) u (.clk(clk), .data_in(data));
endmodule
";
let path = dir.write("a.sv", src);
let out = run(&["--no-cache", "--stdout", &path]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(
stdout(&out),
"\
module m (
input logic clk,
input logic [7:0] data
);
always_comb
if (clk)
begin
x = 1;
end
sub #(
.A (1),
.LONGER(2)
) u (
.clk (clk),
.data_in(data)
);
endmodule
"
);
// Override layered onto `style = "auto"`.
dir.write("lucisv.toml", "[format]\nstyle = \"auto\"\nelse = \"own-line\"\n");
let cuddled_in = "\
module m (
input logic a,
input logic b
);
always_comb
if (a) begin
x = 1;
end else begin
x = 2;
end
endmodule
";
let auto_path = dir.write("b.sv", cuddled_in);
let out = run(&["--no-cache", "--stdout", &auto_path]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stdout(&out).contains(" else begin\n"), "{}", stdout(&out));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+5
View File
@@ -1,6 +1,9 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv_core"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
description = "Config discovery and file walking, shared by the lucisv CLI and the lucisv language server"
@@ -10,3 +13,5 @@ name = "lucisv_core"
path = "src/lib.rs"
[dependencies]
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Replacing a file's contents without ever leaving it half written.
//!
//! `fs::write` truncates the target and then writes into it, so a crash, a
@@ -449,3 +451,5 @@ mod tests {
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+183 -35
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,7 +14,10 @@ use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use crate::config::STYLE_NAMES;
use crate::config::{
ALIGNMENT_NAMES, CONNECTION_ALIGN_MIN_MAX, LIST_INDENT_NAMES, PLACEMENT_NAMES,
PORT_LISTS_NAMES, STYLE_NAMES,
};
/// The default cache directory, resolved against the current directory.
pub const DEFAULT_DIR: &str = ".lucisv_cache";
@@ -41,6 +46,20 @@ pub struct Entry {
/// [`crate::config::STYLE_NAMES`]: every preset lays files out
/// differently, so it is part of the key.
pub style: &'static str,
/// Effective `begin` placement (`"same-line"`, `"own-line"`, or `"auto"`).
pub begin: &'static str,
/// Effective `else` placement (`"same-line"`, `"own-line"`, or `"auto"`).
pub else_keyword: &'static str,
/// Effective `else-after-label` placement (`"same-line"`, `"own-line"`, or `"auto"`).
pub else_after_label: &'static str,
/// Effective `port-lists` mode (`"fit"`, `"one-per-line"`, or `"auto"`).
pub port_lists: &'static str,
/// Effective `list-indent` mode (`"block"`, `"wrap"`, or `"auto"`).
pub list_indent: &'static str,
/// Effective `alignment` mode (`"infer"`, `"always"`, or `"auto"`).
pub alignment: &'static str,
/// Effective `connection-align-min` (`Some(n)` or `None` for unresolved `"auto"`).
pub connection_align_min: Option<usize>,
}
/// The cache for one run: loaded once at startup, written once at exit.
@@ -111,10 +130,25 @@ impl Cache {
continue;
}
let entry = &self.entries[path];
let conn_min = match entry.connection_align_min {
Some(n) => n.to_string(),
None => "auto".to_string(),
};
let _ = writeln!(
text,
"{:016x}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent, entry.style
"{:016x}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content,
entry.line_length,
entry.indent,
entry.uvm_utils_indent,
entry.style,
entry.begin,
entry.else_keyword,
entry.else_after_label,
entry.port_lists,
entry.list_indent,
entry.alignment,
conn_min
);
}
text
@@ -152,6 +186,32 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize,
Some((u64::from_str_radix(content, 16).ok()?, line_length.parse().ok()?, indent.parse().ok()?))
}
fn known_or_auto(value: &str, choices: &[&'static str]) -> Option<&'static str> {
if value == "auto" {
Some("auto")
} else {
choices.iter().copied().find(|n| *n == value)
}
}
/// Parses `connection_align_min`: `None` here signals corrupt syntax;
/// `Some(None)` means valid `"auto"` or out-of-range value handled alongside
/// unknown choices as stale rather than corrupt.
fn parse_conn_min(value: &str) -> Option<Option<Option<usize>>> {
if value == "auto" {
return Some(Some(None));
}
if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let n: usize = value.parse().ok()?;
if n <= CONNECTION_ALIGN_MIN_MAX {
Some(Some(Some(n)))
} else {
Some(None)
}
}
/// Parses the store. `None` means "this file is not something lucisv wrote"
/// — one malformed line discards the whole cache, because partial trust in
/// a file already caught lying is not worth the branch. Entries from
@@ -160,27 +220,74 @@ 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(7, '\t').collect();
let fields: Vec<&str> = line.split('\t').collect();
match fields[..] {
[content, line_length, indent, uvm, style, version, path] => {
[content, line_length, indent, uvm, style, begin, else_kw, else_lbl, port_lists, list_indent, alignment, conn_min, version, path] =>
{
let (content, line_length, indent) = prefix(content, line_length, indent)?;
let uvm_utils_indent = uvm.parse().ok()?;
let conn_min = parse_conn_min(conn_min)?;
if path.is_empty() {
return None;
}
// 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) {
let style = STYLE_NAMES.into_iter().find(|n| *n == style);
let begin = known_or_auto(begin, &PLACEMENT_NAMES);
let else_keyword = known_or_auto(else_kw, &PLACEMENT_NAMES);
let else_after_label = known_or_auto(else_lbl, &PLACEMENT_NAMES);
let port_lists = known_or_auto(port_lists, &PORT_LISTS_NAMES);
let list_indent = known_or_auto(list_indent, &LIST_INDENT_NAMES);
let alignment = known_or_auto(alignment, &ALIGNMENT_NAMES);
if let (
Some(style),
Some(begin),
Some(else_keyword),
Some(else_after_label),
Some(port_lists),
Some(list_indent),
Some(alignment),
Some(connection_align_min),
true,
) = (
style,
begin,
else_keyword,
else_after_label,
port_lists,
list_indent,
alignment,
conn_min,
version == VERSION,
) {
entries.insert(
path.to_string(),
Entry { content, line_length, indent, uvm_utils_indent, style },
Entry {
content,
line_length,
indent,
uvm_utils_indent,
style,
begin,
else_keyword,
else_after_label,
port_lists,
list_indent,
alignment,
connection_align_min,
},
);
}
}
// A store written before `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.
// Pre-Round-6 seven-field store (`style`, no per-knob fields):
// dropped individually as stale so old caches never pass when
// overrides or defaults differ, without discarding valid entries.
[content, line_length, indent, uvm, _style, _version, path] => {
prefix(content, line_length, indent)?;
uvm.parse::<bool>().ok()?;
if path.is_empty() {
return None;
}
}
// A store written before `style` joined the key.
[content, line_length, indent, uvm, _version, path] => {
prefix(content, line_length, indent)?;
uvm.parse::<bool>().ok()?;
@@ -189,10 +296,6 @@ fn parse(text: &str) -> Option<HashMap<String, Entry>> {
}
}
// 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() {
@@ -245,7 +348,20 @@ mod tests {
}
fn entry(content: u64) -> Entry {
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false, style: "lucisv" }
Entry {
content,
line_length: 100,
indent: 2,
uvm_utils_indent: false,
style: "lucisv",
begin: "same-line",
else_keyword: "same-line",
else_after_label: "same-line",
port_lists: "fit",
list_indent: "block",
alignment: "infer",
connection_align_min: Some(1),
}
}
#[test]
@@ -280,6 +396,14 @@ mod tests {
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { style: "google", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { begin: "own-line", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { else_keyword: "own-line", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { else_after_label: "own-line", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { port_lists: "one-per-line", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { list_indent: "wrap", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { alignment: "always", ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { connection_align_min: Some(0), ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { connection_align_min: None, ..entry(0xdead) }));
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
}
@@ -309,7 +433,8 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
"{:016x}\t100\t2\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -328,32 +453,46 @@ mod tests {
#[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.
// The six-field, seven-field, and unknown-enum shapes: all stale,
// dropped individually without discarding valid 14-field entries.
let dir = TempDir::new("nostyle");
let old = dir.file("old.sv");
let old6 = dir.file("old6.sv");
let old7 = dir.file("old7.sv");
let other = dir.file("other.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tbespoke\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tnxp\t{VERSION}\t{}\n",
{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tbespoke\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tnxp\tsame-line\town-line\town-line\tone-per-line\tblock\talways\t1\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
old6.to_string_lossy(),
2,
other.to_string_lossy(),
old7.to_string_lossy(),
3,
other.to_string_lossy(),
4,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&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");
assert!(!cache.is_clean(&old6, entry(1)), "six-field line must be dropped");
assert!(!cache.is_clean(&old7, entry(2)), "seven-field line must be dropped");
assert!(!cache.is_clean(&other, Entry { style: "lucisv", ..entry(3) }));
let nxp_entry = Entry {
style: "nxp",
else_keyword: "own-line",
else_after_label: "own-line",
port_lists: "one-per-line",
alignment: "always",
..entry(4)
};
assert!(cache.is_clean(&mine, nxp_entry));
assert!(!cache.is_clean(&mine, entry(4)), "the style is part of the key");
cache.store();
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
assert!(!dir.cache_text().contains("old6.sv"), "{}", dir.cache_text());
assert!(!dir.cache_text().contains("old7.sv"), "{}", dir.cache_text());
assert!(!dir.cache_text().contains("other.sv"), "{}", dir.cache_text());
}
@@ -374,7 +513,11 @@ mod tests {
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
assert_eq!(
lines[0],
format!("{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}", 1, a.to_string_lossy()),
format!(
"{:016x}\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}",
1,
a.to_string_lossy()
),
"{text}"
);
}
@@ -402,13 +545,16 @@ mod tests {
"0000000000000001\t100\t2\tyes\tlucisv\t0.2.0\t/a.sv\n",
"0000000000000001\t100\twide\tfalse\tlucisv\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\tlucisv\t0.2.0\t\n",
"0000000000000001\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\tnan\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t0.2.0\t\n",
"0000000000000001\t100\t2\tfalse\tlucisv\tsame-line\t0.2.0\t/a.sv\n",
"\0\0\0\n",
] {
let dir = TempDir::new("corrupt");
let file = dir.file("a.sv");
// A good line first: a bad one anywhere discards all of them.
let good = format!(
"{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
"{:016x}\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}\n",
1,
file.to_string_lossy()
);
@@ -424,8 +570,8 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\tlucisv\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
"{:016x}\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\tlucisv\tsame-line\tsame-line\tsame-line\tfit\tblock\tinfer\t1\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -539,3 +685,5 @@ mod tests {
assert!(!Cache::load(&dir.path).is_clean(&weird, entry(1)));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+111 -32
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a small config file needs is supported (comments, `key = int`,
@@ -8,7 +10,7 @@
//! reasoning behind not taking a TOML dependency.
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
/// Config file names, in the order a directory is probed.
pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
@@ -20,6 +22,26 @@ pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
pub const STYLE_NAMES: [&str; 7] =
["lucisv", "google", "lowrisc", "ansi", "microsoft", "nxp", "auto"];
/// Valid values for `[format] begin`, `else`, and `else-after-label`.
pub const PLACEMENT_NAMES: [&str; 2] = ["same-line", "own-line"];
/// Valid values for `[format] port-lists`.
pub const PORT_LISTS_NAMES: [&str; 2] = ["fit", "one-per-line"];
/// Valid values for `[format] list-indent`.
pub const LIST_INDENT_NAMES: [&str; 2] = ["block", "wrap"];
/// Valid values for `[format] alignment`.
pub const ALIGNMENT_NAMES: [&str; 2] = ["infer", "always"];
/// Inclusive bounds for `[format] connection-align-min`.
pub const CONNECTION_ALIGN_MIN_MIN: usize = 0;
pub const CONNECTION_ALIGN_MIN_MAX: usize = 8;
/// All keys recognized under `[format]`.
const FORMAT_KEYS: &str = "style, uvm-utils-indent, begin, else, else-after-label, \
port-lists, list-indent, alignment, connection-align-min";
/// The settings one config file carries. Every key is optional; an unset
/// key leaves the CLI flag (or the built-in default) in charge.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
@@ -44,6 +66,20 @@ pub struct FileConfig {
/// `[format] style`: the named layout preset, one of [`STYLE_NAMES`].
/// Checked here, so a misspelt name fails the run like a misspelt key.
pub format_style: Option<&'static str>,
/// `[format] begin`: override for `Style::begin`.
pub format_begin: Option<&'static str>,
/// `[format] else`: override for `Style::else_keyword`.
pub format_else: Option<&'static str>,
/// `[format] else-after-label`: override for `Style::else_after_label`.
pub format_else_after_label: Option<&'static str>,
/// `[format] port-lists`: override for `Style::port_lists`.
pub format_port_lists: Option<&'static str>,
/// `[format] list-indent`: override for `Style::list_indent`.
pub format_list_indent: Option<&'static str>,
/// `[format] alignment`: override for `Style::alignment`.
pub format_alignment: Option<&'static str>,
/// `[format] connection-align-min`: override for `Style::connection_align_min`.
pub format_connection_align_min: Option<usize>,
/// `[lint] select`: run exactly these rules, replacing the default set.
/// The names are **not** validated here — this crate does not know the
/// rule registry; `lucisv check` validates them the moment it resolves the
@@ -186,16 +222,15 @@ fn parse_entry(
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
style, uvm-utils-indent under `[format]`; \
{FORMAT_KEYS} under `[format]`; \
select, ignore, waivers under `[lint]`; and a rule's own options \
under `[lint.<rule-name>]`)"
)),
}
}
/// One key of the `[format]` table: 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.
/// One key of the `[format]` table: the named `style`, boolean switches, or
/// selective layout/alignment overrides layered onto the active preset.
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
if key == "style" {
if config.format_style.is_some() {
@@ -204,22 +239,48 @@ fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result
config.format_style = Some(parse_style(&parse_string(value)?)?);
return Ok(());
}
let slot = match key {
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
if key == "connection-align-min" {
return set_int(
&mut config.format_connection_align_min,
key,
value,
CONNECTION_ALIGN_MIN_MIN,
CONNECTION_ALIGN_MIN_MAX,
);
}
if key == "uvm-utils-indent" {
if config.format_uvm_utils_indent.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.format_uvm_utils_indent = Some(parse_bool(key, value)?);
return Ok(());
}
let (slot, choices): (&mut Option<&'static str>, &[&'static str]) = match key {
"begin" => (&mut config.format_begin, &PLACEMENT_NAMES),
"else" => (&mut config.format_else, &PLACEMENT_NAMES),
"else-after-label" => (&mut config.format_else_after_label, &PLACEMENT_NAMES),
"port-lists" => (&mut config.format_port_lists, &PORT_LISTS_NAMES),
"list-indent" => (&mut config.format_list_indent, &LIST_INDENT_NAMES),
"alignment" => (&mut config.format_alignment, &ALIGNMENT_NAMES),
_ => {
return Err(format!(
"unknown key `{key}` under `[format]` \
(known keys: style, uvm-utils-indent)"
))
return Err(format!("unknown key `{key}` under `[format]` (known keys: {FORMAT_KEYS})"))
}
};
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
*slot = Some(parse_bool(key, value)?);
*slot = Some(parse_choice(key, &parse_string(value)?, choices)?);
Ok(())
}
fn parse_choice(key: &str, name: &str, choices: &[&'static str]) -> Result<&'static str, String> {
choices
.iter()
.copied()
.find(|n| *n == name)
.ok_or_else(|| format!("`{key}` expects one of {}, found `{name}`", choices.join(", ")))
}
/// One of [`STYLE_NAMES`], exactly as spelt there.
pub fn parse_style(name: &str) -> Result<&'static str, String> {
STYLE_NAMES.into_iter().find(|n| *n == name).ok_or_else(|| {
@@ -375,7 +436,7 @@ impl Discovery {
if !self.enabled {
return Ok(FileConfig::default());
}
let absolute = self.absolute(path);
let absolute = crate::path::normalize_under(&self.cwd, path);
match absolute.parent() {
Some(dir) => self.for_dir(dir),
None => Ok(FileConfig::default()),
@@ -387,7 +448,7 @@ impl Discovery {
if !self.enabled {
return Ok(FileConfig::default());
}
let start = self.absolute(dir);
let start = crate::path::normalize_under(&self.cwd, dir);
let mut cursor = start.as_path();
// Directories that resolve to the same answer as `cursor` does.
let mut chain: Vec<PathBuf> = Vec::new();
@@ -414,24 +475,6 @@ impl Discovery {
}
Ok(found)
}
/// Resolves `path` against the current directory and folds away `.`
/// and `..` so the upward walk visits real ancestors. Symlinks are
/// deliberately not resolved.
fn absolute(&self, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { self.cwd.join(path) };
let mut out = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
}
fn config_file_in(dir: &Path) -> Option<PathBuf> {
@@ -684,6 +727,40 @@ exclude = [ \"build\", \"*_gen.sv\", ]
assert!(err("[format.uvm]\nx = 1").contains("unknown table"));
}
#[test]
fn the_format_table_carries_all_selective_overrides() {
let cfg = parse(
"[format]\n\
style = \"google\"\n\
begin = \"own-line\"\n\
else = \"own-line\"\n\
else-after-label = \"same-line\"\n\
port-lists = \"fit\"\n\
list-indent = \"block\"\n\
alignment = \"always\"\n\
connection-align-min = 0\n",
)
.expect("parses all overrides");
assert_eq!(cfg.format_style, Some("google"));
assert_eq!(cfg.format_begin, Some("own-line"));
assert_eq!(cfg.format_else, Some("own-line"));
assert_eq!(cfg.format_else_after_label, Some("same-line"));
assert_eq!(cfg.format_port_lists, Some("fit"));
assert_eq!(cfg.format_list_indent, Some("block"));
assert_eq!(cfg.format_alignment, Some("always"));
assert_eq!(cfg.format_connection_align_min, Some(0));
assert!(err("[format]\nbegin = \"bogus\"").contains("`begin` expects"));
assert!(err("[format]\nbegin = own-line").contains("expected a quoted string"));
assert!(err("[format]\nbegin = \"own-line\"\nbegin = \"same-line\"")
.contains("duplicate key `begin`"));
assert!(err("[format]\nconnection-align-min = 9").contains("between 0 and 8"));
assert!(err("[format]\nconnection-align-min = -1").contains("expects an integer"));
assert!(err("[format]\nconnection-align-min = 0\nconnection-align-min = 1")
.contains("duplicate key `connection-align-min`"));
assert!(err("begin = \"own-line\"").contains("unknown key `begin`"));
}
/// The same key in a real config file, so the message a user sees names
/// the file and the line to edit — the ladder `[format]` sits at the top
/// of (`lucisv.toml` outranks the editor setting).
@@ -987,3 +1064,5 @@ exclude = [ \"build\", \"*_gen.sv\", ]
assert_eq!(discovery.for_file(Path::new("y.sv")).unwrap().indent, Some(4));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! A small line-oriented unified diff: the CLI's `--diff` and the MCP
//! server's `dry_run` print the same hunks through this one function.
//! Moved here from `crates/lucisv/src/diff.rs` unchanged (Handshake MCP-1,
@@ -219,3 +221,5 @@ mod tests {
assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+9 -23
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! EDA filelist (`-f`) parsing: the project file every Verilog build
//! already has.
//!
@@ -9,7 +11,7 @@
//! a warning for each problem. See `docs/features/filelist/README.md`.
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
/// How deep `-f` may nest before the reader stops descending.
///
@@ -61,7 +63,7 @@ fn read_with(path: &Path, env: &dyn Fn(&str) -> Option<String>) -> Result<Fileli
listed: HashSet::new(),
depth: 0,
};
let normalized = reader.normalize(path);
let normalized = crate::path::normalize_under(&reader.cwd, path);
reader.seen.insert(normalized);
reader.filelist(path, &text);
Ok(reader.out)
@@ -113,7 +115,7 @@ impl Reader<'_> {
expecting_filelist = true;
} else if let Some(rest) = token.strip_prefix("+incdir+") {
for item in rest.split('+').filter(|s| !s.is_empty()) {
let resolved = self.normalize(&dir.join(item));
let resolved = crate::path::normalize_under(&self.cwd, &dir.join(item));
self.out.incdirs.push(resolved);
}
} else if let Some(rest) = token.strip_prefix("+define+") {
@@ -149,7 +151,7 @@ impl Reader<'_> {
return;
}
let path = dir.join(token);
let normalized = self.normalize(&path);
let normalized = crate::path::normalize_under(&self.cwd, &path);
if !self.seen.insert(normalized) {
self.warn(line, format!("filelist `{token}` was already included, skipping it"));
return;
@@ -171,7 +173,7 @@ impl Reader<'_> {
self.warn(line, format!("no such file `{token}`, skipping it"));
return;
}
let normalized = self.normalize(&path);
let normalized = crate::path::normalize_under(&self.cwd, &path);
if self.listed.insert(normalized.clone()) {
self.out.files.push(normalized);
}
@@ -217,24 +219,6 @@ impl Reader<'_> {
fn warn(&mut self, line: &Line<'_>, what: String) {
self.out.warnings.push(format!("{}:{}: {what}", line.file.display(), line.number));
}
/// Fold `.`/`..` away and resolve against the current directory, so two
/// spellings of one file are one entry. Symlinks are deliberately not
/// resolved, matching `config::Discovery`'s lexical rule.
fn normalize(&self, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { self.cwd.join(path) };
let mut out = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
}
/// Where a warning happened.
@@ -591,3 +575,5 @@ missing.sv
assert_eq!(list.warnings.len(), 2, "{:?}", list.warnings);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+7 -1
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The parts of lucisv that decide *which* files are processed and *with what
//! settings*, shared by the `lucisv` CLI and the `lucisv-server` language server.
//!
@@ -9,7 +11,8 @@
//! an EDA project already does, from a `.f` file. `atomic` is the one write
//! path all of them share: nothing here ever truncates a file it is
//! replacing. `diff` is the unified diff the CLI's `--diff` and the MCP
//! server's `dry_run` both print. See
//! server's `dry_run` both print, and `path` holds the shared lexical `.`/`..`
//! path normalization. See
//! `docs/features/lucisv-core-lift/README.md`, and
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
//! for the rules themselves.
@@ -19,4 +22,7 @@ pub mod cache;
pub mod config;
pub mod diff;
pub mod filelist;
pub mod path;
pub mod walk;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+144
View File
@@ -0,0 +1,144 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Lexical path normalization shared across `lucisv_core`, `lucisv`, and
//! `lucisv_server`.
//!
//! Paths are folded lexically (`.` and `..` resolved component-by-component)
//! without calling `std::fs::canonicalize` so symlinks are never followed and
//! non-existent paths (such as `--stdin-filename` or rename targets) behave
//! identically to existing ones.
use std::path::{Component, Path, PathBuf};
/// Folds `.` and `..` components out of `path` lexically, without touching the
/// filesystem.
///
/// - Leading or excess `..` on a relative path (and after an unrooted Windows
/// drive prefix such as `C:`) are preserved.
/// - `..` immediately after a root directory (`/` on Unix, `C:\` or
/// `\\server\share\` on Windows) is discarded because traversal cannot climb
/// above a root.
/// - A non-empty relative path whose components all cancel (`"."`, `"a/.."`)
/// normalizes to `"."`; an empty path stays empty.
pub fn normalize(path: &Path) -> PathBuf {
let mut parts: Vec<Component<'_>> = Vec::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => match parts.last() {
Some(Component::Normal(_)) => {
parts.pop();
}
Some(Component::RootDir) => {}
Some(Component::Prefix(_)) | Some(Component::ParentDir) | None => {
parts.push(Component::ParentDir);
}
// `CurDir` is never pushed into `parts`.
Some(Component::CurDir) => {}
},
other => parts.push(other),
}
}
if parts.is_empty() {
if path.as_os_str().is_empty() {
return PathBuf::new();
}
return PathBuf::from(".");
}
let mut out = PathBuf::new();
for part in parts {
out.push(part);
}
out
}
/// Resolves `path` against `base` when `path` is relative and normalizes the
/// result lexically.
///
/// An absolute `path` ignores `base` and is normalized directly. On Windows, a
/// root-relative (`\foo`) or drive-relative (`D:foo`) path is joined via
/// [`Path::join`] before normalizing, preserving drive prefixes cleanly.
pub fn normalize_under(base: &Path, path: &Path) -> PathBuf {
if path.is_absolute() {
normalize(path)
} else {
normalize(&base.join(path))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn folds_dots_and_preserves_leading_parent_dirs() {
assert_eq!(normalize(Path::new("")), PathBuf::new());
assert_eq!(normalize(Path::new(".")), PathBuf::from("."));
assert_eq!(normalize(Path::new("././.")), PathBuf::from("."));
assert_eq!(normalize(Path::new("a/..")), PathBuf::from("."));
assert_eq!(normalize(Path::new("a/./b/../c")), PathBuf::from("a/c"));
assert_eq!(normalize(Path::new("./rtl/../rtl/a.sv")), PathBuf::from("rtl/a.sv"));
assert_eq!(normalize(Path::new("../a")), PathBuf::from("../a"));
assert_eq!(normalize(Path::new("a/../../b")), PathBuf::from("../b"));
assert_eq!(normalize(Path::new("../..")), PathBuf::from("../.."));
}
#[test]
fn normalize_under_joins_relative_paths_and_leaves_absolute_ones() {
let base = if cfg!(windows) { Path::new(r"C:\work\proj") } else { Path::new("/work/proj") };
let abs =
if cfg!(windows) { Path::new(r"D:\other\a.sv") } else { Path::new("/other/a.sv") };
assert_eq!(normalize_under(base, Path::new("rtl/./a.sv")), base.join("rtl").join("a.sv"));
assert_eq!(
normalize_under(base, Path::new("../shared/a.sv")),
base.parent().expect("parent").join("shared").join("a.sv")
);
assert_eq!(normalize_under(base, Path::new(".")), base);
assert_eq!(normalize_under(base, Path::new("")), base);
assert_eq!(normalize_under(base, abs), abs);
}
#[cfg(unix)]
#[test]
fn unix_roots_clamp_excess_parent_dirs() {
assert_eq!(normalize(Path::new("/")), PathBuf::from("/"));
assert_eq!(normalize(Path::new("/..")), PathBuf::from("/"));
assert_eq!(normalize(Path::new("/./a/../../b//c/")), PathBuf::from("/b/c"));
assert_eq!(
normalize_under(Path::new("/a/b"), Path::new("/x/../../y")),
PathBuf::from("/y")
);
}
#[cfg(windows)]
#[test]
fn windows_prefixes_and_roots_clamp_or_preserve_parent_dirs() {
assert_eq!(normalize(Path::new(r"C:\")), PathBuf::from(r"C:\"));
assert_eq!(normalize(Path::new(r"C:\..")), PathBuf::from(r"C:\"));
assert_eq!(normalize(Path::new(r"C:\a\..\..\b\c\")), PathBuf::from(r"C:\b\c"));
assert_eq!(
normalize(Path::new(r"\\server\share\a\..\..\b")),
PathBuf::from(r"\\server\share\b")
);
assert_eq!(normalize(Path::new(r"\a\..\..\b")), PathBuf::from(r"\b"));
// Drive-relative paths have no root directory, so climbing past the
// prefix keeps `..` rather than turning into a rooted path.
assert_eq!(normalize(Path::new(r"C:a\..\..\b")), PathBuf::from(r"C:..\b"));
assert_eq!(normalize(Path::new(r"C:.")), PathBuf::from(r"C:"));
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"\other\..\a.sv")),
PathBuf::from(r"C:\a.sv")
);
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"D:rtl\..\a.sv")),
PathBuf::from(r"D:a.sv")
);
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"D:\x\..\..\y.sv")),
PathBuf::from(r"D:\y.sv")
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+8 -1
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! File discovery: directory walking, `--exclude` matching and the
//! `.gitignore` subset documented in
//! `docs/features/parallel-files/README.md`.
@@ -5,6 +7,9 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
mod resumable;
pub use resumable::ResumableWalk;
/// File extensions lucisv formats when walking a directory.
pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
@@ -215,7 +220,7 @@ pub enum DirStatus {
/// Tracks visited directories across one or more walks to ensure cycle termination
/// and detect order divergence.
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DirectoryTracker {
visited: HashMap<DirId, PathBuf>,
has_conflict: bool,
@@ -1103,3 +1108,5 @@ mod tests {
assert!(!tracker.has_conflict());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+246
View File
@@ -0,0 +1,246 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The directory walk of [`collect_files_tracked`](super::collect_files_tracked),
//! a slice at a time.
//!
//! The language server walks the whole workspace at the start of every scan,
//! and until TODO §71's last open item (`docs/features/server-scaling-r10`)
//! it did so in one call that held the workspace for 25–80 ms on OpenTitan
//! and ~260 ms on 40 000 files, answering nothing. This walk is the same
//! walk with its recursion turned into an explicit stack, so the caller can
//! stop it after a bounded number of entries, answer what is waiting, and
//! carry on from exactly where it stopped.
//!
//! **Same walk, not a similar one.** Every filesystem call the recursive walk
//! makes is made here in the same order with the same arguments — `enter`,
//! the directory's `.gitignore`, `read_dir`, then per entry the exclude test,
//! one `metadata`, the ignore test and either a descent or a hand-off — so on
//! a tree that does not change while it runs the two yield the same paths,
//! lengths and warnings in the same order and leave the tracker the same.
//! The module tests prove it for every slice size on trees built to exercise
//! every branch. On a tree that *does* change, each directory is seen as it
//! was when it was read, exactly as the recursive walk sees it; slicing only
//! widens the window.
use std::path::{Path, PathBuf};
use super::{
broken_link_reason, is_excluded, is_ignored, is_source, parse_gitignore, DirStatus,
DirectoryTracker, Ignore, Warning, GITIGNORE,
};
/// One directory being read: its entries still to visit, in name order, and
/// whether entering it pushed a `.gitignore` the walk must pop on leaving.
struct Frame {
entries: std::vec::IntoIter<std::fs::DirEntry>,
pushed: bool,
}
/// A walk of one input, resumable between any two directory entries.
///
/// A file is handed over with the `metadata` the walk read for it — the
/// length [`collect_files_with`](super::collect_files_with) hands over.
/// `None` for an input named rather than walked, exactly as there. Its
/// identity is not taken from it: two entries visited slices apart can see
/// one file as two, so a caller reads identities together after the walk.
///
/// Built by [`ResumableWalk::new`], advanced by [`ResumableWalk::step`] until
/// it reports it is done. The tracker is the caller's and is passed to every
/// step, so several walks — or a walk and a one-shot one — can share one set
/// of directory identities exactly as [`collect_files_tracked`]'s callers do.
///
/// [`collect_files_tracked`]: super::collect_files_tracked
pub struct ResumableWalk {
input: PathBuf,
exclude: Vec<String>,
gitignore: bool,
ignores: Vec<Ignore>,
rel: Vec<String>,
frames: Vec<Frame>,
started: bool,
done: bool,
error: Option<String>,
}
impl ResumableWalk {
/// A walk of `input` that has not touched the filesystem yet.
pub fn new(input: &Path, exclude: Vec<String>, gitignore: bool) -> ResumableWalk {
ResumableWalk {
input: input.to_path_buf(),
exclude,
gitignore,
ignores: Vec::new(),
rel: Vec::new(),
frames: Vec::new(),
started: false,
done: false,
error: None,
}
}
/// Whether the walk has finished.
pub fn is_done(&self) -> bool {
self.done
}
/// What [`collect_files_tracked`](super::collect_files_tracked) would have
/// returned as its error: `input` naming nothing at all.
pub fn error(&self) -> Option<&str> {
self.error.as_deref()
}
/// Visit at most `budget` more entries — starting the walk and leaving a
/// directory count as one each — and report how many were visited; the
/// walk is over when [`ResumableWalk::is_done`] says so. A `budget` of 0
/// is treated as 1, so every step makes progress.
pub fn step(
&mut self,
tracker: &mut DirectoryTracker,
budget: usize,
found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>),
warn: &mut dyn FnMut(Warning),
) -> usize {
let budget = budget.max(1);
let mut visited = 0;
if !self.started {
self.started = true;
self.start(tracker, found, warn);
visited += 1;
}
while !self.done && visited < budget {
visited += 1;
self.next_entry(tracker, found, warn);
}
visited
}
/// The first step: what the input is decides whether there is a walk.
fn start(
&mut self,
tracker: &mut DirectoryTracker,
found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>),
warn: &mut dyn FnMut(Warning),
) {
let input = self.input.clone();
if input.is_dir() {
self.open(&input, tracker, warn);
} else if input.is_file() {
found(input, None);
} else {
self.error = Some(format!("{}: no such file or directory", input.display()));
}
self.done = self.frames.is_empty();
}
/// `Walk::dir`'s first half: enter `dir`, push its ignore file, read it.
/// Returns whether a frame was pushed (the directory was entered).
fn open(
&mut self,
dir: &Path,
tracker: &mut DirectoryTracker,
warn: &mut dyn FnMut(Warning),
) -> bool {
if !matches!(tracker.enter(dir), DirStatus::EnteredFirstTime) {
return false;
}
let pushed = self.push_ignore(dir, warn);
let entries = read_sorted(dir, warn);
self.frames.push(Frame { entries: entries.into_iter(), pushed });
true
}
/// One entry of the innermost directory, or leaving it when it has none.
fn next_entry(
&mut self,
tracker: &mut DirectoryTracker,
found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>),
warn: &mut dyn FnMut(Warning),
) {
let Some(frame) = self.frames.last_mut() else {
self.done = true;
return;
};
let Some(entry) = frame.entries.next() else {
return self.leave();
};
let path = entry.path();
if is_excluded(&path, &self.exclude) {
return;
}
let Ok(meta) = std::fs::metadata(&path) else {
if is_source(&path) {
warn(Warning { path: path.clone(), message: broken_link_reason(&path) });
}
return;
};
self.rel.push(entry.file_name().to_string_lossy().into_owned());
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
if meta.is_dir() {
if self.open(&path, tracker, warn) {
// The name stays on `rel` until this directory is left.
return;
}
} else if meta.is_file() && is_source(&path) {
found(path, Some(&meta));
}
}
self.rel.pop();
}
/// `Walk::dir`'s second half: pop the ignore file, and the directory's
/// own name — which the root never had.
fn leave(&mut self) {
let Some(frame) = self.frames.pop() else { return };
if frame.pushed {
self.ignores.pop();
}
if self.frames.is_empty() {
self.done = true;
} else {
self.rel.pop();
}
}
/// `Walk::push_ignore`, word for word.
fn push_ignore(&mut self, dir: &Path, warn: &mut dyn FnMut(Warning)) -> bool {
let path = dir.join(GITIGNORE);
if !self.gitignore || !path.is_file() {
return false;
}
match std::fs::read_to_string(&path) {
Ok(text) => {
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
true
}
Err(e) => {
warn(Warning { path, message: e.to_string() });
false
}
}
}
}
/// `Walk::entries`' read: every entry of `dir` in path order, each error said.
fn read_sorted(dir: &Path, warn: &mut dyn FnMut(Warning)) -> Vec<std::fs::DirEntry> {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) => {
warn(Warning { path: dir.to_path_buf(), message: e.to_string() });
return Vec::new();
}
};
let mut entries = Vec::new();
for entry in read {
match entry {
Ok(entry) => entries.push(entry),
Err(e) => warn(Warning { path: dir.to_path_buf(), message: e.to_string() }),
}
}
entries.sort_by_key(|e| e.path());
entries
}
#[cfg(test)]
mod tests;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,277 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The identical-result proof at the walk's own level: for every slice size,
//! and for slice sizes that change from step to step, the resumable walk
//! yields exactly what the recursive walk yields — the same events in the
//! same order, the same error, and the same tracker afterwards.
use super::super::collect_files_tracked;
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
/// What a walk said, in the order it said it.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Event {
Found(PathBuf, Option<u64>),
Warned(Warning),
}
/// A scratch tree, removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(tag: &str) -> Tree {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-resumable-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
std::fs::create_dir_all(path.parent().expect("parent")).expect("create parent");
std::fs::write(&path, text).expect("write");
}
#[cfg(unix)]
fn link(&self, rel: &str, target: &str) {
let path = self.path.join(rel);
std::fs::create_dir_all(path.parent().expect("parent")).expect("create parent");
std::os::unix::fs::symlink(target, &path).expect("symlink");
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// Every branch of the walk in one tree: nested `.gitignore` files with a
/// negation and a directory-only rule, an exclude pattern, non-source files,
/// empty directories, and — on unix — a cycle, two aliases of one directory
/// sorting before and after it, and a dangling source link.
fn busy_tree(tag: &str) -> Tree {
let tree = Tree::new(tag);
tree.write(".gitignore", "build/\n*_gen.sv\n");
tree.write("a.sv", "module a;\nendmodule\n");
tree.write("notes.txt", "x");
tree.write("rtl/b.sv", "module b;\nendmodule\n");
tree.write("rtl/b_gen.sv", "module bg;\nendmodule\n");
tree.write("rtl/.gitignore", "!keep_gen.sv\nlocal/\n");
tree.write("rtl/keep_gen.sv", "module k;\nendmodule\n");
tree.write("rtl/local/hidden.sv", "module h;\nendmodule\n");
tree.write("rtl/deep/er/c.svh", "`define C\n");
tree.write("build/out.sv", "module o;\nendmodule\n");
tree.write("skipme/s.sv", "module s;\nendmodule\n");
tree.write("z_real/inc.vh", "`define Z\n");
std::fs::create_dir_all(tree.path.join("empty/inner")).expect("empty dirs");
#[cfg(unix)]
{
tree.link("rtl/loop", "..");
tree.link("a_alias", "z_real");
tree.link("zz_alias", "z_real");
tree.link("rtl/gone.sv", "nowhere.sv");
}
tree
}
/// The recursive walk's events, error and tracker — the oracle.
fn one_shot(input: &Path, exclude: &[String], tracker: DirectoryTracker) -> Outcome {
let mut tracker = tracker;
let mut events = Vec::new();
let error = {
let events = std::cell::RefCell::new(&mut events);
collect_files_tracked(
input.to_str().expect("utf-8 temp path"),
exclude,
true,
&mut tracker,
&mut |path, len| events.borrow_mut().push(Event::Found(path, len)),
&mut |w| events.borrow_mut().push(Event::Warned(w)),
)
.err()
};
Outcome { events, error, tracker, steps: 1 }
}
/// What one walk produced.
#[derive(Debug, PartialEq, Eq)]
struct Outcome {
events: Vec<Event>,
error: Option<String>,
tracker: DirectoryTracker,
/// How many `step` calls it took (not compared).
steps: usize,
}
impl Outcome {
fn same_as(&self, other: &Outcome) -> bool {
self.events == other.events && self.error == other.error && self.tracker == other.tracker
}
}
/// The resumable walk with the budget for each step chosen by `budget`.
fn sliced(
input: &Path,
exclude: &[String],
tracker: DirectoryTracker,
budget: &mut dyn FnMut() -> usize,
) -> Outcome {
let mut tracker = tracker;
let mut events = Vec::new();
let mut walk = ResumableWalk::new(input, exclude.to_vec(), true);
let mut steps = 0;
loop {
steps += 1;
let events = std::cell::RefCell::new(&mut events);
let size = budget();
let visited = walk.step(
&mut tracker,
size,
&mut |path, meta| events.borrow_mut().push(Event::Found(path, meta.map(|m| m.len()))),
&mut |w| events.borrow_mut().push(Event::Warned(w)),
);
assert!(visited >= 1 && visited <= size.max(1), "{visited} of {size}");
if walk.is_done() {
break;
}
assert!(steps < 100_000, "the walk makes progress");
}
assert!(walk.is_done());
Outcome { events, error: walk.error().map(str::to_string), tracker, steps }
}
/// Every fixed slice size from 1 to one past the whole walk.
fn every_slice_size(input: &Path, exclude: &[String], tracker: DirectoryTracker) -> usize {
let oracle = one_shot(input, exclude, tracker.clone());
let longest = sliced(input, exclude, tracker.clone(), &mut || 1).steps;
for size in 1..=longest + 1 {
let got = sliced(input, exclude, tracker.clone(), &mut || size);
assert!(got.same_as(&oracle), "slice size {size}:\n{got:#?}\nvs\n{oracle:#?}");
}
longest
}
#[test]
fn every_slice_size_walks_exactly_what_the_recursive_walk_walks() {
let tree = busy_tree("every");
let exclude = vec!["skipme".to_string()];
let entries = every_slice_size(&tree.path, &exclude, DirectoryTracker::new());
// Premise: the walk is long enough for slicing to matter.
assert!(entries > 20, "{entries} steps");
let oracle = one_shot(&tree.path, &exclude, DirectoryTracker::new());
let found = oracle.events.iter().filter(|e| matches!(e, Event::Found(..))).count();
assert!(found >= 5, "premise: the tree has files to find: {oracle:#?}");
}
#[test]
fn slice_sizes_that_change_between_steps_walk_the_same() {
// Property-style: 200 seeds of a small linear congruential generator pick
// each step's budget between 1 and 7.
let tree = busy_tree("random");
let exclude = vec!["skipme".to_string()];
let oracle = one_shot(&tree.path, &exclude, DirectoryTracker::new());
for seed in 0..200u64 {
let mut state = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
let mut budget = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
1 + ((state >> 33) % 7) as usize
};
let got = sliced(&tree.path, &exclude, DirectoryTracker::new(), &mut budget);
assert!(got.same_as(&oracle), "seed {seed}");
}
}
#[test]
fn a_tracker_another_walk_already_filled_is_honoured_the_same_way() {
// The split startup: the head walk enters a folder first, then the rest
// walks the root with the same tracker — so a directory may already be
// visited, and an alias may be a precedence conflict.
let tree = busy_tree("shared");
let mut tracker = DirectoryTracker::new();
let _ = tracker.enter(&tree.path.join("z_real"));
let _ = tracker.enter(&tree.path.join("rtl"));
every_slice_size(&tree.path, &[], tracker.clone());
#[cfg(unix)]
assert!(
one_shot(&tree.path, &[], tracker).tracker.has_conflict(),
"premise: a_alias sorts first"
);
}
#[test]
fn a_file_a_missing_path_and_an_entered_root_end_as_the_recursive_walk_does() {
let tree = busy_tree("inputs");
every_slice_size(&tree.path.join("a.sv"), &[], DirectoryTracker::new());
every_slice_size(&tree.path.join("nothing-here"), &[], DirectoryTracker::new());
let mut entered = DirectoryTracker::new();
let _ = entered.enter(&tree.path);
every_slice_size(&tree.path, &[], entered);
let missing = one_shot(&tree.path.join("nothing-here"), &[], DirectoryTracker::new());
assert!(missing.error.is_some(), "premise: a missing input is an error");
}
#[test]
#[cfg(unix)]
fn unreadable_directories_and_ignore_files_are_said_at_the_same_point() {
use std::os::unix::fs::PermissionsExt;
let tree = busy_tree("unreadable");
tree.write("locked/x.sv", "module x;\nendmodule\n");
tree.write("shut/.gitignore", "*\n");
tree.write("shut/y.sv", "module y;\nendmodule\n");
let mode = |rel: &str, bits| {
std::fs::set_permissions(tree.path.join(rel), std::fs::Permissions::from_mode(bits))
.expect("chmod")
};
mode("locked", 0o000);
mode("shut/.gitignore", 0o000);
let refused = std::fs::read_dir(tree.path.join("locked")).is_err();
every_slice_size(&tree.path, &[], DirectoryTracker::new());
let oracle = one_shot(&tree.path, &[], DirectoryTracker::new());
mode("locked", 0o755);
mode("shut/.gitignore", 0o644);
if refused {
let warned = oracle.events.iter().filter(|e| matches!(e, Event::Warned(..))).count();
assert!(warned >= 2, "premise: both are said: {oracle:#?}");
} else {
eprintln!("skipped premise: a mode-000 directory is readable by this user (root?)");
}
}
/// QA (2026-11-26): budgets at the edges, a root that is itself a symlink to
/// a directory, an ignored-then-negated directory with its own nested
/// `.gitignore`, and a deep chain — still the recursive walk's events.
#[test]
fn qa_edge_budgets_a_symlinked_root_a_negated_dir_and_a_deep_chain_walk_the_same() {
let tree = busy_tree("qa-edges");
tree.write(".gitignore", "build/\n*_gen.sv\nvendor/\n!vendor/\n");
tree.write("vendor/.gitignore", "*.svh\n!keep.svh\n");
tree.write("vendor/v.sv", "module v;\nendmodule\n");
tree.write("vendor/drop.svh", "`define D\n");
tree.write("vendor/keep.svh", "`define K\n");
let deep: String = (0..40).map(|n| format!("d{n}/")).collect();
tree.write(&format!("{deep}leaf.sv"), "module leaf;\nendmodule\n");
let oracle = one_shot(&tree.path, &[], DirectoryTracker::new());
for budget in [0usize, usize::MAX] {
let got = sliced(&tree.path, &[], DirectoryTracker::new(), &mut || budget);
assert!(got.same_as(&oracle), "budget {budget}");
}
every_slice_size(&tree.path, &[], DirectoryTracker::new());
#[cfg(unix)]
{
let outside = Tree::new("qa-edges-link");
let root = outside.path.join("root_link");
std::os::unix::fs::symlink(&tree.path, &root).expect("symlink");
every_slice_size(&root, &[], DirectoryTracker::new());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+5
View File
@@ -1,6 +1,9 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv_mcp"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
description = "lucisv as a Model Context Protocol server: project understanding for coding agents over stdio"
@@ -21,3 +24,5 @@ vlog_formatter = { path = "../vlog_formatter" }
vlog_linter = { path = "../vlog_linter" }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
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
@@ -361,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
+123 -8
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.
@@ -156,6 +158,10 @@ pub struct Stamp {
/// The same moment by the monotonic clock: what tells a wall clock that
/// was stepped back since the read.
pub read_mono: Instant,
/// When these exact bytes and metadata were first observed on the
/// monotonic clock; preserved across unchanged re-reads so a file with a
/// future timestamp settles after [`RACY`].
pub first_mono: Instant,
/// Its ctime and inode — what still moves when a same-size rewrite puts
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
/// the same problem. `None` off Unix, where size, mtime and the racy rule
@@ -231,23 +237,50 @@ impl Stamp {
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) {
if moved || self.racy(now) || self.clock_stepped_back(now) {
Change::Suspect
} else {
Change::Same
}
}
/// Preserve [`Self::first_mono`] across an unchanged re-read when there
/// was no wall-clock step-back, letting a future timestamp settle after
/// [`RACY`] of monotonic time has elapsed and re-verified the bytes.
pub fn inherit_observation(&mut self, prev: &Stamp) {
let same = self.size == prev.size
&& self.mtime == prev.mtime
&& self.hash == prev.hash
&& self.identity == prev.identity;
let now = Clocks { wall: self.read_at, mono: self.read_mono };
if same && !prev.clock_stepped_back(now) {
self.first_mono = prev.first_mono;
}
}
/// **Invariant: a stamp is trusted on a later match only if every
/// timestamp it trusts (the mtime, and the ctime where there is one) is
/// 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 {
/// settled:**
/// - for a timestamp at or before `read_at`, it must be at least [`RACY`]
/// older than `read_at`;
/// - for a future timestamp (`time > read_at`, e.g. clock skew or NFS), it
/// stays racy until [`RACY`] has elapsed on the monotonic clock between
/// first observation and this read (`read_mono - first_mono >= RACY`),
/// unless the wall clock has caught up to `time` (forcing one re-read
/// back into the normal rule).
fn racy(&self, now: Clocks) -> bool {
let ctime = self.identity.map(|identity| identity.ctime);
[Some(self.mtime), ctime].into_iter().flatten().any(|stamped| match stamped {
Some(time) => time.checked_add(RACY).is_none_or(|settled| settled > self.read_at),
Some(time) if time <= self.read_at => {
time.checked_add(RACY).is_none_or(|settled| settled > self.read_at)
}
Some(time) => {
now.wall >= time
|| self
.read_mono
.checked_duration_since(self.first_mono)
.is_none_or(|elapsed| elapsed < RACY)
}
None => true,
})
}
@@ -271,7 +304,12 @@ impl Stamp {
/// 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 }
Stamp {
read_at: self.read_at + by,
read_mono: self.read_mono + by,
first_mono: self.first_mono + by,
..self
}
}
}
@@ -294,6 +332,7 @@ pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
hash,
read_at: read.wall,
read_mono: read.mono,
first_mono: read.mono,
identity: seen.identity,
program: text.contains("endprogram"),
};
@@ -400,6 +439,7 @@ mod tests {
hash: 7,
read_at: read,
read_mono: mono,
first_mono: mono,
identity: Some(Identity { ctime: Some(read - ctime_age), ino: 42 }),
program: false,
}
@@ -507,4 +547,79 @@ mod tests {
assert_eq!(stamp.compare(seen, now), Change::Suspect, "{seen:?}");
}
}
#[test]
fn future_timestamp_settles_after_racy_and_reacts_to_catchup_stepback_or_edits() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let future = read + Duration::from_secs(600);
let mut initial = stamp_aged(read, mono, old, old);
initial.mtime = Some(future);
// Initial read is racy until monotonic time >= RACY has elapsed at a re-read.
assert_eq!(initial.compare(unchanged(&initial), a_second_later(&initial)), Change::Suspect);
let before_racy = RACY - Duration::from_millis(1);
let mut mid = Stamp {
read_at: read + before_racy,
read_mono: mono + before_racy,
first_mono: mono + before_racy,
..initial
};
mid.inherit_observation(&initial);
assert_eq!(mid.first_mono, mono);
assert_eq!(mid.compare(unchanged(&mid), a_second_later(&mid)), Change::Suspect);
// Once RACY has elapsed and a re-read confirms the same bytes, it settles.
let mut settled =
Stamp { read_at: read + RACY, read_mono: mono + RACY, first_mono: mono + RACY, ..mid };
settled.inherit_observation(&mid);
assert_eq!(settled.first_mono, mono);
assert_eq!(settled.compare(unchanged(&settled), a_second_later(&settled)), Change::Same);
// If the wall clock later catches up to `future`, trigger one re-read.
let caught_up = Clocks { wall: future, mono: mono + Duration::from_secs(600) };
assert_eq!(settled.compare(unchanged(&settled), caught_up), Change::Suspect);
// A hash change or wall-clock step-back resets `first_mono`.
let mut changed =
Stamp { hash: 99, read_at: read + RACY, read_mono: mono + RACY, ..settled };
changed.first_mono = mono + RACY;
changed.inherit_observation(&settled);
assert_eq!(changed.first_mono, mono + RACY);
assert_eq!(changed.compare(unchanged(&changed), a_second_later(&changed)), Change::Suspect);
let mut stepped = Stamp {
read_at: settled.read_at - STEP_BACK - Duration::from_secs(1),
read_mono: settled.read_mono + Duration::from_secs(1),
first_mono: settled.read_mono + Duration::from_secs(1),
..settled
};
stepped.inherit_observation(&settled);
assert_eq!(stepped.first_mono, stepped.read_mono);
}
#[test]
fn real_future_mtime_file_detects_edits_and_settles_with_reobservation() {
let dir = scratch("future-mtime");
let path = dir.join("a.sv");
fs::write(&path, "module a; endmodule\n").unwrap();
let future = SystemTime::now() + Duration::from_secs(3600);
fs::OpenOptions::new().write(true).open(&path).unwrap().set_modified(future).unwrap();
let (_, initial) = read_source(&path).unwrap();
assert_eq!(initial.check(&path), Change::Suspect);
// Simulated re-read after RACY with inherited observation settles on disk.
let mut reobserved = initial.taken_later(RACY);
reobserved.first_mono = initial.first_mono;
assert_eq!(reobserved.check(&path), Change::Same);
// A subsequent edit still turns Suspect immediately.
fs::write(&path, "module a2; endmodule\n").unwrap();
assert_eq!(reobserved.check(&path), Change::Suspect);
fs::remove_dir_all(dir).unwrap();
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+104 -5
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The project one server answers about: its roots, its files, the workspace
//! index over them, and the promise that no answer is older than the disk
//! was when the call arrived (PLAN §4.4).
@@ -179,8 +181,14 @@ impl Project {
/// Re-read one file whose stamp is in doubt; a changed hash is a record.
fn reread(&mut self, path: PathBuf, records: &mut Vec<FileFacts>, gone: &mut Vec<PathBuf>) {
match read_source(&path) {
Ok((text, stamp)) => {
let moved = self.files.get(&path).is_none_or(|old| old.hash != stamp.hash);
Ok((text, mut stamp)) => {
let moved = match self.files.get(&path) {
Some(old) => {
stamp.inherit_observation(old);
old.hash != stamp.hash
}
None => true,
};
if moved {
records.push(FileFacts::of(path.clone(), &text));
}
@@ -238,6 +246,13 @@ impl Project {
&self.index
}
/// Drop one file directly from the held index (test-only helper to exercise
/// sparse tombstoned `FileId`s).
#[cfg(test)]
pub(crate) fn remove_file_from_index(&mut self, path: &Path) -> bool {
self.index.remove_file(path)
}
/// The canonical roots, in the order given.
pub fn roots(&self) -> &[PathBuf] {
&self.roots
@@ -271,6 +286,15 @@ impl Project {
/// holding it; symlinks followed; and refused, by name, unless it lands
/// on a file inside a root.
pub fn resolve(&self, arg: &str) -> Result<PathBuf, String> {
let path = self.resolve_existing(arg)?;
if !path.is_file() {
return Err(format!("`{arg}` is not a file."));
}
Ok(path)
}
/// Resolve an existing file or directory inside one of the project roots.
pub fn resolve_existing(&self, arg: &str) -> Result<PathBuf, String> {
let given = Path::new(arg);
let candidates: Vec<PathBuf> = if given.is_absolute() {
vec![given.to_path_buf()]
@@ -285,9 +309,6 @@ impl Project {
"`{arg}` resolves outside every root; lucisv-mcp only reads inside its roots."
));
}
if !path.is_file() {
return Err(format!("`{arg}` is not a file."));
}
Ok(path)
}
@@ -357,5 +378,83 @@ fn relative_to(roots: &[PathBuf], path: &Path) -> String {
parts.join("/")
}
impl vlog_refactor::KnownFacts for Project {
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
let stamp = self.files.get(path)?;
if stamp.hash != lucisv_core::cache::content_hash(text.as_bytes()) {
return None;
}
self.index.facts_for(path).cloned()
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod r3_tests {
use super::*;
use std::fs;
use std::time::{Duration, SystemTime};
use vlog_refactor::KnownFacts;
#[test]
fn known_facts_matches_exact_bytes_and_invalidates_after_refresh() {
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-project-known-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let file = fs::canonicalize(&dir).unwrap().join("a.sv");
let v1 = "module a; logic s1; endmodule\n";
fs::write(&file, v1).unwrap();
let mut project = Project::open(vec![fs::canonicalize(&dir).unwrap()], None);
assert!(project.facts_for(&file, v1).is_some_and(|f| f.path() == file));
let v2 = "module a; logic s2; endmodule\n";
assert!(project.facts_for(&file, v2).is_none(), "stale text must miss");
fs::write(&file, v2).unwrap();
let refresh = project.refresh(false);
assert_eq!(refresh.changed, 1);
assert!(project.facts_for(&file, v1).is_none(), "old hash invalidated");
assert!(project.facts_for(&file, v2).is_some(), "new hash hits");
fs::remove_file(&file).unwrap();
project.refresh(false);
assert!(project.facts_for(&file, v2).is_none(), "removed file misses");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn project_reread_inherits_observation_for_future_mtime_settlement() {
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-project-future-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let file = fs::canonicalize(&dir).unwrap().join("f.sv");
fs::write(&file, "module f; endmodule\n").unwrap();
let future = SystemTime::now() + Duration::from_secs(3600);
fs::OpenOptions::new().write(true).open(&file).unwrap().set_modified(future).unwrap();
let mut project = Project::open(vec![fs::canonicalize(&dir).unwrap()], None);
let first_mono = project.files[&file].first_mono;
// First refresh sees Suspect and re-reads; hash matches so changed == 0,
// while `first_mono` stays anchored at initial observation.
let r1 = project.refresh(false);
assert_eq!(r1.changed, 0);
assert_eq!(project.files[&file].first_mono, first_mono);
// Once the previous stamp is past RACY relative to `first_mono`, re-read
// settles cleanly and the next `check` sees `Change::Same`.
if let Some(stamp) = project.files.get_mut(&file) {
let mut aged = stamp.taken_later(Duration::from_secs(4));
aged.first_mono = first_mono;
*stamp = aged;
}
assert_eq!(project.files[&file].check(&file), Change::Same);
let _ = fs::remove_dir_all(&dir);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// 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`).
@@ -106,3 +108,5 @@ fn a_path_argument_must_land_inside_a_root() {
fs::remove_dir_all(dir).unwrap();
fs::remove_dir_all(outside).unwrap();
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The rendering rules every tool's text answer follows (PLAN §10.2): the
//! token budget is the product.
//!
@@ -205,3 +207,5 @@ mod tests {
assert_eq!(by_file(&sites), ["b.sv:3,9", "a.sv:1"]);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The `lucisv://` resources: the project overview, the lint rule
//! reference, one unit's outline and one file's outline — the same answers
//! `hierarchy` and `outline` give, addressable by URI for a host that
@@ -176,3 +178,5 @@ mod tests {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+8 -4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The JSON-RPC 2.0 envelope and the MCP methods this server answers: the
//! `initialize` handshake and its version negotiation, `ping`, the tool
//! methods, the `lucisv://` resources, and an empty prompt list.
@@ -226,7 +228,7 @@ impl Server {
self.version = Some(version);
json!({
"protocolVersion": version,
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
"capabilities": { "tools": {}, "resources": {} },
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
"instructions": instructions(self.options.mode),
})
@@ -366,9 +368,9 @@ mod tests {
}
#[test]
fn the_instructions_stay_under_400_bytes() {
assert!(INSTRUCTIONS.len() <= 400, "{}", INSTRUCTIONS.len());
assert!(INSTRUCTIONS_READ_ONLY.len() <= 300, "{}", INSTRUCTIONS_READ_ONLY.len());
fn the_instructions_stay_under_budget() {
assert!(INSTRUCTIONS.len() <= 440, "{}", INSTRUCTIONS.len());
assert!(INSTRUCTIONS_READ_ONLY.len() <= 330, "{}", INSTRUCTIONS_READ_ONLY.len());
}
#[test]
@@ -421,3 +423,5 @@ mod tests {
assert!(bad_tool["error"]["message"].as_str().unwrap().contains("nope"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The declarations the files' own symbol tables hold — every one the
//! semantic model knows and `outline` lists: typedefs, enum values,
//! functions, tasks, genvars, generate blocks and what they declare,
@@ -94,3 +96,5 @@ fn unit_at(items: &[Item], span: TextRange) -> Option<&str> {
let inner = child_items(&item.kind).into_iter().find_map(|items| unit_at(items, span));
inner.or(own.filter(|(_, name_span)| *name_span != span).map(|(name, _)| name))
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+179 -14
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `check`: what `lucisv check` would say about one file or the whole
//! design — the tolerant parse's errors, then the lint findings — one line
//! each, `file:line:col severity message [rule]`, errors first.
@@ -31,7 +33,7 @@ const CAP: usize = 200;
pub const CHECK: Tool = Tool {
name: "check",
description: "Parse errors and lint findings of `file` or the whole design, one per line (file:line:col severity message [rule]), errors first; `ok` when clean.",
description: "Parse errors and lint findings of `file` (path, directory or glob) or the whole design, one per line (file:line:col severity message [rule]), errors first; `ok` when clean.",
params: &[Param { name: "file", ty: Ty::Str, required: false }],
rewalk: false,
handler: check,
@@ -60,13 +62,7 @@ pub(super) struct Run {
fn check(project: &mut Project, args: &Args) -> Result<Answer, String> {
let mut runs = Runs::new();
let mut findings = match args.str("file") {
Some(file) => {
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let own = project.index().file_id(&path);
let oracle = Mentions::of_file(project.index(), own);
file_findings(project, &mut runs, &path, &analysis, &oracle)?
}
Some(raw) => check_target(project, &mut runs, raw.trim())?,
None => project_findings(project, &mut runs)?,
};
if findings.is_empty() {
@@ -78,6 +74,56 @@ fn check(project: &mut Project, args: &Args) -> Result<Answer, String> {
Ok(Answer::lines(render::capped(lines, CAP)))
}
fn check_target(
project: &mut Project,
runs: &mut Runs,
spec: &str,
) -> Result<Vec<Finding>, String> {
if spec.is_empty() {
return Err("`file` is empty.".into());
}
if !spec.contains(['*', '?']) {
let path = project.resolve_existing(spec)?;
if path.is_file() {
let analysis = project.analysis(&path)?;
let own = project.index().file_id(&path);
let oracle = Mentions::of_file(project.index(), own);
return file_findings(project, runs, &path, &analysis, &oracle);
}
let select = |project: &Project| -> Vec<PathBuf> {
project.files().map(|(p, _)| p).filter(|p| p.starts_with(&path)).cloned().collect()
};
let paths = match_with_rewalk(project, select, spec)?;
return lint_paths(project, runs, &paths, false);
}
let pattern = super::glob::normalize_glob(project.roots(), spec)?;
let select = |project: &Project| -> Vec<PathBuf> {
project
.files()
.map(|(p, _)| p)
.filter(|p| super::glob::path_match(&pattern, &project.relative(p)))
.cloned()
.collect()
};
let paths = match_with_rewalk(project, select, spec)?;
lint_paths(project, runs, &paths, false)
}
fn match_with_rewalk(
project: &mut Project,
select: impl Fn(&Project) -> Vec<PathBuf>,
spec: &str,
) -> Result<Vec<PathBuf>, String> {
let mut found = select(project);
if found.is_empty() && project.ensure_walked_for_miss() {
found = select(project);
}
if found.is_empty() {
return Err(format!("no indexed file matches `{spec}`."));
}
Ok(found)
}
fn severity_rank(severity: &str) -> u8 {
match severity {
"error" => 0,
@@ -97,18 +143,29 @@ impl Finding {
/// Every indexed file's findings, and the external waivers nothing used.
fn project_findings(project: &Project, runs: &mut Runs) -> Result<Vec<Finding>, String> {
let census = Census::of(project.index());
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
lint_paths(project, runs, &paths, true)
}
fn lint_paths(
project: &Project,
runs: &mut Runs,
paths: &[PathBuf],
complete: bool,
) -> Result<Vec<Finding>, String> {
let census = Census::of(project.index());
let mut findings = Vec::new();
for path in &paths {
for path in paths {
let Ok(text) = std::fs::read_to_string(path) else { continue };
let analysis = Analysis::of(text);
let own = project.index().file_id(path);
let oracle = Mentions { index: project.index(), census: Some(&census), own };
findings.extend(file_findings(project, runs, path, &analysis, &oracle)?);
}
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
if complete {
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
}
Ok(findings)
}
@@ -262,9 +319,8 @@ struct Census<'a> {
impl<'a> Census<'a> {
fn of(index: &'a WorkspaceIndex) -> Census<'a> {
let mut words: HashMap<&'a str, (usize, FileId)> = HashMap::new();
for (at, path) in index.files().iter().enumerate() {
for (file, path) in index.live_files() {
let Some(facts) = index.facts_for(path) else { continue };
let file = FileId(at as u32);
for word in facts.words() {
words.entry(word.as_str()).or_insert((0, file)).0 += 1;
}
@@ -325,3 +381,112 @@ impl MentionOracle for Mentions<'_> {
PackageExports::exports(self.index, package)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn census_uses_live_file_ids_after_tombstone_at_slot_zero() {
let mut index = WorkspaceIndex::build([
(PathBuf::from("a_excl.sv"), "module a_excl; logic excl_only; endmodule\n"),
(
PathBuf::from("b_live.sv"),
"module b_live; logic own_sig; logic shared_sig; endmodule\n",
),
(PathBuf::from("c_user.sv"), "module c_user; logic shared_sig; endmodule\n"),
]);
assert!(index.remove_file(Path::new("a_excl.sv")));
let b_id = index.file_id(Path::new("b_live.sv")).expect("b_live live");
assert_eq!(b_id, FileId(1));
let census = Census::of(&index);
assert!(!census.outside("excl_only", Some(b_id)));
assert!(
!census.outside("own_sig", Some(b_id)),
"Census::of must keep FileId(1) rather than shifting to FileId(0)"
);
assert!(census.outside("shared_sig", Some(b_id)));
}
#[test]
fn qa_r2_f1_mcp_find_and_check_with_multiple_tombstones_preceding_live_files() {
let dir = std::env::temp_dir().join(format!("lucisv-mcp-qa-r2-f1-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("mkdir");
let dir = std::fs::canonicalize(dir).expect("canon");
let excl0 = dir.join("a0_excl.sv");
let excl1 = dir.join("a1_excl.sv");
let excl2 = dir.join("a2_excl.sv");
std::fs::write(&excl0, "`define EX0 1\nmodule a0; logic ex0_sig; endmodule\n").expect("w");
std::fs::write(&excl1, "`define EX1 1\nmodule a1; logic ex1_sig; endmodule\n").expect("w");
std::fs::write(&excl2, "`define EX2 1\nmodule a2; logic ex2_sig; endmodule\n").expect("w");
std::fs::write(
dir.join("b_live.sv"),
"`define LIVE_MAC 1\nmodule b_live;\n logic own_sig;\n logic shared_sig;\nendmodule\n",
)
.expect("w");
std::fs::write(
dir.join("c_user.sv"),
"module c_user;\n logic shared_sig;\n b_live u1 ();\nendmodule\n",
)
.expect("w");
let mut project = Project::open(vec![dir.clone()], None);
assert!(project.remove_file_from_index(&excl0));
assert!(project.remove_file_from_index(&excl1));
assert!(project.remove_file_from_index(&excl2));
assert_eq!(project.index().files().len(), 2);
assert_eq!(project.index().file_id(&dir.join("b_live.sv")), Some(FileId(3)));
let make_args = |tool: &crate::tools::Tool, v: serde_json::Value| {
crate::tools::validate(tool, v.as_object().cloned().expect("args obj"))
.expect("valid args")
};
let check_tool = crate::tools::find("check", crate::tools::Mode::Full).expect("check tool");
let single = (check_tool.handler)(
&mut project,
&make_args(check_tool, serde_json::json!({ "file": "b_live.sv" })),
)
.expect("single check");
assert!(single.text.contains("own_sig"), "single check flags own_sig: {}", single.text);
assert!(
!single.text.contains("shared_sig"),
"single check ignores shared_sig: {}",
single.text
);
let whole =
(check_tool.handler)(&mut project, &make_args(check_tool, serde_json::json!({})))
.expect("whole check");
assert!(whole.text.contains("own_sig"), "whole check flags own_sig: {}", whole.text);
assert!(
!whole.text.contains("shared_sig"),
"whole check ignores shared_sig: {}",
whole.text
);
let find_tool = crate::tools::find("find", crate::tools::Mode::Full).expect("find tool");
let refs = (find_tool.handler)(
&mut project,
&make_args(find_tool, serde_json::json!({ "name": "b_live", "refs": true })),
)
.expect("find refs");
assert!(refs.text.contains("c_user.sv"), "find refs locates c_user.sv: {}", refs.text);
let err = match (find_tool.handler)(
&mut project,
&make_args(find_tool, serde_json::json!({ "name": "LIVE" })),
) {
Ok(_) => panic!("expected no_declaration error with similar"),
Err(e) => e,
};
assert!(err.contains("LIVE_MAC"), "near match must include LIVE_MAC: {err}");
let _ = std::fs::remove_dir_all(&dir);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+15 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `rename`, and what every design-wide edit shares: the whole-set read the
//! engines are handed, and the step from a verified `RefactorEdit` to a
//! written plan with the name's unresolved mentions listed.
@@ -44,8 +46,16 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
return Ok(Answer::lines(vec!["renamed 0 sites in 0 files".to_string()]));
}
let set = whole_set(project, Some(&path), std::slice::from_ref(&name))?;
let edit = vlog_refactor::rename(&set.files, &path, declaration.offset, new_name)
.map_err(|why| set.rooted(&why))?;
let mut trace = vlog_refactor::RenameTrace::default();
let edit = vlog_refactor::rename_traced_with(
&set.files,
&path,
declaration.offset,
new_name,
project,
&mut trace,
)
.map_err(|why| set.rooted(&why))?;
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
// A member of a module is named bare only where it is declared or used;
@@ -166,7 +176,7 @@ pub(super) fn write_telling(
// `None` — list every mention — for a non-member, and for a member whose
// home set is not known (an include the engine cannot resolve).
let local = match told.member {
true => vlog_refactor::home_set(&set.files, told.home, &edited),
true => vlog_refactor::home_set_for(&set.files, told.home, told.unit, &edited),
false => None,
};
let focus = Focus {
@@ -221,3 +231,5 @@ fn written_ranges(edits: &[TextEdit]) -> Vec<TextRange> {
}
out
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+61 -29
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `find`: where a name is declared and, on `refs`, where each declaration
//! is used — the question an agent otherwise answers by grepping and
//! reading. Declarations come from the index (`names.rs`); uses from
@@ -6,7 +8,7 @@
//! that never spells the name); then the name's unresolved mentions —
//! strings, comments, macro text — that no engine resolved.
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
@@ -46,7 +48,7 @@ fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
if found.is_empty() {
return Err(names::no_declaration(project, name));
}
let name = names::qualified(name).1;
let (qualified_unit, name) = names::qualified(name);
if !args.flag("refs") {
let lines = found.iter().map(|declaration| declaration.render(name)).collect();
return Ok(Answer::lines(render::capped(lines, CAP)));
@@ -54,15 +56,28 @@ fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
// The uses must be searched in every file, so one written since the last
// walk is walked into first.
project.ensure_walked_for_miss();
Ok(Answer::lines(render::capped(with_uses(project, name, &found), CAP)))
Ok(Answer::lines(render::capped(with_uses(project, qualified_unit, name, &found), CAP)))
}
/// Each declaration's line followed by its uses, then the unresolved
/// mentions of the name no engine accounted for.
fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String> {
fn with_uses(
project: &Project,
qualified_unit: Option<&str>,
name: &str,
found: &[Declaration],
) -> Vec<String> {
let set = WholeSet::read(project, None);
let mut lines = Vec::new();
let mut accounted: Vec<(PathBuf, Vec<TextRange>)> = Vec::new();
let queries: Vec<(&Path, u32)> = found
.iter()
.filter(|declaration| !declaration.is_macro())
.take(REFS_CAP)
.map(|declaration| (declaration.path.as_path(), declaration.offset))
.collect();
let mut batch =
vlog_refactor::find_references_batch_with(&set.files, &queries, false, project).into_iter();
let mut searched = 0;
for declaration in found {
lines.push(declaration.render(name));
@@ -70,22 +85,17 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
continue;
}
searched += 1;
let hits = vlog_refactor::find_references(
&set.files,
&declaration.path,
declaration.offset,
false,
);
match hits {
Ok(hits) => {
match batch.next() {
Some(Ok(hits)) => {
lines
.extend(uses(project, &set, &hits).into_iter().map(|line| format!(" {line}")));
account(&mut accounted, hits);
}
Err(why) => {
Some(Err(why)) => {
let why = engine_refusal(&set.rooted(&why));
lines.push(format!(" uses not listed: {why}"));
}
None => {}
}
}
let followed = found.iter().filter(|declaration| !declaration.is_macro()).count();
@@ -93,14 +103,15 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
}
let home = &found[0].path;
let local = member_files(&set, found, &accounted);
let member = member_scope(&set, found, &accounted);
let unit = qualified_unit.or(member.unit.as_deref());
let focus = Focus {
name,
home,
unit: None,
unit,
accounted: &accounted,
named: &[],
local: local.as_deref(),
local: member.local.as_deref(),
};
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
lines.extend(mentions::find(project, files, &focus).block());
@@ -108,29 +119,48 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
lines
}
struct MemberScope {
local: Option<Vec<PathBuf>>,
unit: Option<String>,
}
/// The files a bare mention of a **module member** can mean it in — each
/// declaration's home set (`vlog_refactor::home_set`) with every file the
/// engine found a use in — or `None` when
/// any declaration is not a member (a unit, a package member, a macro), whose
/// every mention is listed (§65.1, lead's inspection: a `state_q` found in forty
/// modules is not news about this one).
fn member_files(
/// declaration's bind-aware home set (`vlog_refactor::home_sets_for`) with
/// every file the engine found a use in — or `None` when any declaration is
/// not a member (a unit, a package member, a macro). Also returns the enclosing
/// unit name when all declarations share one.
fn member_scope(
set: &WholeSet,
found: &[Declaration],
accounted: &[(PathBuf, Vec<TextRange>)],
) -> Option<Vec<PathBuf>> {
) -> MemberScope {
if found.iter().any(Declaration::is_macro) {
return None;
return MemberScope { local: None, unit: None };
}
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
let mut local: Vec<PathBuf> = Vec::new();
let mut targets: Vec<(&Path, String)> = Vec::with_capacity(found.len());
for declaration in found {
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
let Some(text) = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)
else {
return MemberScope { local: None, unit: None };
};
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)?;
local.extend(vlog_refactor::home_set(&set.files, &declaration.path, &hit_files)?);
let Some(unit) =
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)
else {
return MemberScope { local: None, unit: None };
};
targets.push((declaration.path.as_path(), unit));
}
Some(local)
let single_unit = targets
.first()
.map(|(_, u)| u)
.filter(|u| targets.iter().all(|(_, other)| other == *u))
.cloned();
let home_targets: Vec<(&Path, Option<&str>)> =
targets.iter().map(|(p, u)| (*p, Some(u.as_str()))).collect();
let local = vlog_refactor::home_sets_for(&set.files, &home_targets, &hit_files);
MemberScope { local, unit: single_unit }
}
/// The engine's hits, one file per line: `file:12,40`.
@@ -197,3 +227,5 @@ mod tests {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+33 -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`).
@@ -15,7 +17,9 @@ use std::path::{Path, PathBuf};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::fence::{self, Region};
use vlog_formatter::{format_source, Config};
use vlog_formatter::{
format_source, Alignment, Config, ListIndent, Placement, PortLists, StyleOverrides,
};
use vlog_linter::{apply_fixes, Fix, Violation};
use super::diagnostics::{violations, Mentions, Runs};
@@ -132,6 +136,15 @@ pub(super) fn formatter_config(file: &FileConfig) -> Config {
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config.apply_overrides(StyleOverrides {
begin: file.format_begin.and_then(Placement::parse),
else_keyword: file.format_else.and_then(Placement::parse),
else_after_label: file.format_else_after_label.and_then(Placement::parse),
port_lists: file.format_port_lists.and_then(PortLists::parse),
list_indent: file.format_list_indent.and_then(ListIndent::parse),
alignment: file.format_alignment.and_then(Alignment::parse),
connection_align_min: file.format_connection_align_min,
});
config
}
@@ -214,7 +227,24 @@ mod tests {
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);
let overridden = FileConfig {
format_style: Some("google"),
format_begin: Some("own-line"),
format_connection_align_min: Some(0),
..Default::default()
};
let config = formatter_config(&overridden);
assert_eq!(config.style.begin, Placement::OwnLine);
assert_eq!(config.style.connection_align_min, 0);
let auto = FileConfig {
format_style: Some("auto"),
format_else: Some("own-line"),
..Default::default()
};
let auto_cfg = formatter_config(&auto);
assert!(auto_cfg.auto_style);
assert_eq!(auto_cfg.overrides.else_keyword, Some(Placement::OwnLine));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+72
View File
@@ -1,7 +1,11 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Path globs, as `format`'s `files` takes them: `*` and `?` within one
//! path component, `**` for any run of components, and a bare directory
//! for everything below it — the `.gitignore` / `rg -g` reading.
use std::path::{Component, Path, PathBuf};
/// Whether `name` matches a glob of `*` (any run) and `?` (one character).
pub fn glob_match(pattern: &str, name: &str) -> bool {
let pattern: Vec<char> = pattern.chars().collect();
@@ -59,6 +63,72 @@ fn components_match(pattern: &[&str], path: &[&str]) -> bool {
}
}
/// Normalize a glob `spec` relative to `roots`, refusing paths that resolve
/// outside every root (absolute outside roots or escaping via `..`).
pub fn normalize_glob(roots: &[PathBuf], spec: &str) -> Result<String, String> {
let given = Path::new(spec);
if given.is_absolute() {
for root in roots {
if let Ok(rest) = given.strip_prefix(root) {
return normalize_relative_glob(spec, rest);
}
if let Some(root_rel) = strip_canonical_prefix(given, root) {
return normalize_relative_glob(spec, &root_rel);
}
}
return Err(format!(
"`{spec}` resolves outside every root; lucisv-mcp only reads inside its roots."
));
}
normalize_relative_glob(spec, given)
}
fn strip_canonical_prefix(given: &Path, root: &Path) -> Option<PathBuf> {
let mut prefix = PathBuf::new();
let mut iter = given.components();
let mut rest = Vec::new();
while let Some(comp) = iter.next() {
let text = comp.as_os_str().to_string_lossy();
if text.contains(['*', '?']) {
rest.push(comp.as_os_str().to_os_string());
rest.extend(iter.map(|c| c.as_os_str().to_os_string()));
break;
}
prefix.push(comp.as_os_str());
}
let canon = std::fs::canonicalize(&prefix).ok()?;
let rel = canon.strip_prefix(root).ok()?;
let mut out = rel.to_path_buf();
for tail in rest {
out.push(tail);
}
Some(out)
}
fn normalize_relative_glob(raw: &str, path: &Path) -> Result<String, String> {
let mut parts: Vec<String> = Vec::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
if parts.pop().is_none() {
return Err(format!(
"`{raw}` resolves outside every root; lucisv-mcp only reads inside its roots."
));
}
}
Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()),
Component::RootDir | Component::Prefix(_) => {}
}
}
let joined = parts.join("/");
if raw.ends_with('/') && !joined.is_empty() {
Ok(format!("{joined}/"))
} else {
Ok(joined)
}
}
#[cfg(test)]
mod tests {
use super::{glob_match, path_match};
@@ -100,3 +170,5 @@ mod tests {
assert!(!path_match("ip/**", "hw/ip/aes.sv"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `hierarchy`: the project's shape. Without a `root`, the counts and the
//! top modules; with one, the instance tree down from it or every
//! instantiation of it up to `depth` levels — read off the index's
@@ -369,3 +371,5 @@ fn statement(project: &Project, texts: &mut Texts, child: &Child) -> Vec<String>
}
out
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `outline unit:` — what a unit offers the code that uses it: a module's
//! or interface's parameters and ports in declaration order (plus an
//! interface's modports), a package's or class's members — without the
@@ -228,3 +230,5 @@ fn class_base(items: &[Item], name_span: TextRange) -> Option<String> {
}
child_items(&item.kind).into_iter().find_map(|items| class_base(items, name_span))
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `edit_item` — the structural edits under one name (`replace`,
//! `insert_before`, `insert_after`, `delete`), the general token saver: an
//! agent sends one item's text, never the file.
@@ -373,3 +375,5 @@ fn end_spot(analysis: &Analysis, unit: &str, file: &str) -> Result<Spot, String>
/// The keywords that close a unit `end` may name.
const END_WORDS: &[&str] = &["endmodule", "endinterface", "endprogram", "endpackage", "endclass"];
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The verifier's lexical rules — what a splice may do to the token stream
//! and its comments, before any parse is asked:
//!
@@ -173,3 +175,5 @@ fn markers(tokens: &[Token], start: u32, end: u32) -> Vec<&str> {
.map(|e| e.text.trim())
.collect()
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `op: delete`'s macro rule: a name spelled inside a macro call's
//! arguments (`` `ASSERT_KNOWN(k, sig) ``) or a `` `define`` body is a use
//! no lucisv engine resolves — the lexer keeps a macro call as one token and
@@ -106,3 +108,5 @@ mod tests {
assert!(spellings("`define S \"sig\"\n", "sig").is_empty(), "a string is not a use");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+37 -10
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `edit_item op: delete`'s reference rule: an item is not deleted while a
//! name it owns (`verify::owned`) is still used anywhere in the project.
//!
@@ -87,8 +89,18 @@ pub fn check(
census.add(|| format!("{file} (skipped: {why}) may reference `{name}`"));
}
let scan = Scan { project, set: &set, path, analysis, place };
let queries: Vec<(&Path, u32)> = symbols
.iter()
.filter(|symbol| {
within(symbol.name_span, place.removed)
&& mentioned(&set, path, place.removed, &symbol.name)
})
.map(|symbol| (path, symbol.name_span.start))
.collect();
let mut batch =
vlog_refactor::find_references_batch_with(&set.files, &queries, false, project).into_iter();
for symbol in symbols {
scan.uses_of(symbol, &mut census);
scan.uses_of(symbol, &mut batch, &mut census);
}
if census.total > 0 {
return Err(format!("still referenced: {}; nothing written.", census.render()));
@@ -111,7 +123,12 @@ type Accounted = Vec<(PathBuf, TextRange)>;
impl Scan<'_> {
/// Count the uses of one owned declaration that the deletion would leave.
fn uses_of(&self, symbol: &Symbol, census: &mut Census) {
fn uses_of(
&self,
symbol: &Symbol,
batch: &mut impl Iterator<Item = Result<Vec<(PathBuf, TextRange)>, String>>,
census: &mut Census,
) {
let (name, removed) = (&symbol.name, self.place.removed);
if !within(symbol.name_span, removed) {
let line = self.analysis.lines.line_col(symbol.name_span.start).0;
@@ -124,12 +141,26 @@ impl Scan<'_> {
if !mentioned(self.set, self.path, removed, name) {
return;
}
let accounted = self.references(symbol, census);
let found = batch.next().unwrap_or_else(|| {
vlog_refactor::find_references_with(
&self.set.files,
self.path,
symbol.name_span.start,
false,
self.project,
)
});
let accounted = self.references(symbol, found, census);
self.macros(name, &accounted, census);
}
/// The engine's and the file's own uses, counted; what they account for.
fn references(&self, symbol: &Symbol, census: &mut Census) -> Accounted {
fn references(
&self,
symbol: &Symbol,
found: Result<Vec<(PathBuf, TextRange)>, String>,
census: &mut Census,
) -> Accounted {
let (name, removed) = (&symbol.name, self.place.removed);
let mut uses = local_uses(self.analysis, symbol, removed);
let mut accounted: Accounted = self
@@ -140,12 +171,6 @@ impl Scan<'_> {
.filter(|use_| use_.name == *name)
.map(|use_| (self.path.to_path_buf(), use_.name_span))
.collect();
let found = vlog_refactor::find_references(
&self.set.files,
self.path,
symbol.name_span.start,
false,
);
match found {
Ok(hits) => {
for (file, span) in hits {
@@ -260,3 +285,5 @@ fn position(project: &Project, set: &WholeSet, file: &Path, span: TextRange) ->
let (line, col) = LineIndex::new(text).line_col(span.start);
format!("{}:{line}:{col}", project.relative(file))
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Which bytes an item owns: the lines `edit_item`'s inserts and deletes
//! work on, and the span its `replace` replaces when its text brings comments.
//!
@@ -155,3 +157,5 @@ mod tests {
assert_eq!(slice(replace_region(src, item, "logic b;\n// own line")), "logic a;");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `op: delete`'s implicit-connection rule: a `.*` binds a signal without
//! spelling it, so `find_references` (which returns only spans that spell
//! the name) never lists it. For each deleted name, every `.*`
@@ -94,3 +96,5 @@ fn binds(index: &WorkspaceIndex, module: &str, name: &str) -> Option<bool> {
}
Some(index.member(module, name).iter().any(|def| def.kind == SymbolKind::Port))
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The verifier the three structural edits share — the one new piece of
//! logic in the MCP block, so it is guilty until proven innocent: every rule
//! here has an attack in `tests/attacks.rs`.
@@ -573,3 +575,5 @@ mod tests {
assert!(owned_names(&analysis, always).is_empty());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+15 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Unresolved mentions: every whole-word spelling of a name that no engine
//! answer accounted for and that sits where no lucisv engine looks — inside
//! a string literal, a comment, a macro call's text, a `` `define`` body, or
@@ -106,9 +108,7 @@ pub fn find<'t>(
let mut last_line = 0;
let foreign = focus.local.is_some_and(|local| !local.iter().any(|p| p == path));
for (at, _) in spellings(text, focus.name) {
if foreign
&& !text.as_bytes().get((at as usize).wrapping_sub(1)).is_some_and(|&b| b == b'.')
{
if foreign && !text.get(..at as usize).is_some_and(vlog_refactor::after_dot) {
continue;
}
let end = at + focus.name.len() as u32;
@@ -344,4 +344,16 @@ mod tests {
let (a, b) = (Path::new("/hw/ip/es/rtl/a.sv"), Path::new("/hw/ip/es/dv/b.sv"));
assert_eq!(shared_components(a, b), 4);
}
#[test]
fn foreign_files_recognize_dotted_mentions_past_blanks_comments_and_paste() {
assert!(vlog_refactor::after_dot("u_m."));
assert!(vlog_refactor::after_dot("u_m . "));
assert!(vlog_refactor::after_dot("u_m. /* c */ "));
assert!(vlog_refactor::after_dot("u_m.``"));
assert!(!vlog_refactor::after_dot("/* u_m. */ "));
assert!(!vlog_refactor::after_dot("u_m "));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The tool registry: every tool's name, description, argument list and
//! handler, in one table. The argument list is the single source of both the
//! `inputSchema` a host shows the agent and the validation a call's
@@ -313,3 +315,5 @@ mod tests {
assert_eq!(schema(hierarchy.params)["properties"]["depth"], json!({"type": "integer"}));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+31 -4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Names looked up — the by-name half every lean tool shares: every
//! declaration of a name (the index's units, exported members and module
//! internals, every declaration the files' own symbol tables hold, and the
@@ -9,7 +11,7 @@ use std::collections::{BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_semantic::{Def, DefinitionKey, FileId, Surface, SymbolKind, WorkspaceIndex};
use vlog_semantic::{Def, DefinitionKey, Surface, SymbolKind, WorkspaceIndex};
use super::declared::{declared, Local, Wanted};
use super::source::{checked_site, Texts};
@@ -186,8 +188,8 @@ pub fn similar(project: &Project, name: &str, cap: usize) -> Vec<String> {
index.workspace_symbols(name).iter().map(|hit| hit.name.to_string()).collect();
let part = Wanted::Containing(name.to_ascii_lowercase());
names.extend(declared(project, &part).into_iter().map(|local| local.name));
for at in 0..index.files().len() {
let Some(table) = index.defines(FileId(at as u32)) else { continue };
for (file, _) in index.live_files() {
let Some(table) = index.defines(file) else { continue };
let found = table.entries().iter().filter(|d| contains_any_case(&d.name, name));
names.extend(found.map(|define| define.name.clone()));
}
@@ -220,7 +222,10 @@ pub fn ambiguous(name: &str, found: &[&Declaration], pick: &str) -> String {
#[cfg(test)]
mod tests {
use super::qualified;
use super::{qualified, similar};
use crate::project::Project;
use std::fs;
use std::path::PathBuf;
#[test]
fn a_unit_qualifies_a_name_and_an_escaped_name_is_whole() {
@@ -231,4 +236,26 @@ mod tests {
assert_eq!(qualified("\\a.b "), (None, "\\a.b "));
assert_eq!(qualified(".x"), (None, ".x"));
}
#[test]
fn similar_finds_macros_after_tombstoned_slot_zero() {
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-names-tombstone-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let dir = fs::canonicalize(dir).unwrap();
let a_path = dir.join("a_excl.sv");
fs::write(&a_path, "`define EXCL_MAC 1\nmodule a_excl; endmodule\n").unwrap();
fs::write(dir.join("z_mac.sv"), "`define LIVE_MAC 1\nmodule z_mac; endmodule\n").unwrap();
let mut project = Project::open(vec![dir.clone()], None);
assert!(project.remove_file_from_index(&a_path));
assert_eq!(similar(&project, "LIVE", 20), vec!["LIVE_MAC".to_string()]);
assert!(similar(&project, "EXCL", 20).is_empty());
let _ = fs::remove_dir_all(&dir);
let _: PathBuf = dir;
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `outline`: a file's declarations as a tree with line ranges (its parse
//! errors first), or — for `unit` — what a unit offers the code that uses
//! it (`interface.rs`), so an agent reads the shape before the source.
@@ -59,3 +61,5 @@ fn tree(analysis: &Analysis, nodes: &[DocumentSymbol], level: usize, out: &mut V
tree(analysis, &node.children, level + 1, out);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+8 -2
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `port`'s `after`: the new port placed right after a named one, in the
//! layout of the line it follows, and each named connection placed right
//! after the instance's `.after(…)`.
@@ -417,9 +419,11 @@ mod tests {
assert!(typed.contains("`b` takes its direction"), "{typed}");
let arm = refusal(&design("`ifdef X\n input logic a,\n`endif\n output logic y"), "a");
assert!(arm.contains("inside an `ifdef arm"), "{arm}");
let hidden =
let attributed =
refusal(&design(" input logic [7:0] a,\n (* keep *) b,\n output logic y"), "a");
assert!(hidden.contains("`m`'s port list holds `(* keep *) b`"), "{hidden}");
assert!(attributed.contains("`b` takes its direction"), "{attributed}");
let hidden = refusal(&design(" input logic [7:0] a,\n 123 b,\n output logic y"), "a");
assert!(hidden.contains("`m`'s port list holds `123 b`"), "{hidden}");
let mut files = design(" input logic a,\n output logic y");
files[1].1 =
"module top(input logic a, en, output logic y);\n m u_m (a, y);\nendmodule\n".into();
@@ -446,3 +450,5 @@ mod tests {
assert_eq!(appended_expr(".e(x)", "d"), None);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Where a new list element goes after its anchor, and how it is written.
//!
//! The element always goes **after the separator that follows the anchor**
@@ -304,3 +306,5 @@ mod tests {
assert_eq!(split_declaration("input dbg_i").unwrap().ty, "");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The check a placement must pass before anything is written: the placed
//! edit is the engine's verified edit with elements **moved and nothing
//! else**. Per file, against the engine's result:
@@ -308,3 +310,5 @@ mod tests {
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `port`: add a port to a module and connect it by name in every
//! instantiation, or remove one and its connection everywhere — the
//! design-wide edit a file write cannot do safely. `add` is
@@ -144,3 +146,5 @@ fn instantiations(project: &Project, module: &str) -> (usize, usize) {
let files: BTreeSet<_> = edges.iter().map(|edge| edge.file).collect();
(count, files.len())
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `read`: one item's exact source — a slice, never the file — preceded by
//! `file:first–last`. In a named `file` the item is sliced as
//! `read_item::select` slices it; without one the name is looked up
@@ -78,3 +80,5 @@ fn locate(project: &mut Project, selector: &str) -> Result<PathBuf, String> {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The item slicer `read` and `edit_item` share: one item's exact span in
//! a file — a module, a function, a declaration, an instance, or an
//! unlabelled `always` block named by the line it covers.
@@ -317,3 +319,5 @@ module n; logic q; endmodule
assert!(refused.contains("`\\b` on line 12"), "{refused}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Declaration sites read back off the disk: `find` and the by-name tools
//! answer with `file:line` for declarations in files no analysis is held
//! for. One read per file per call ([`Texts`]); the index's spans are
@@ -271,3 +273,5 @@ mod tests {
assert_eq!(capped("x y", 3), "x y");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The MCP stdio transport: one JSON-RPC message per line in, one per line
//! out. stdout carries protocol lines and nothing else; stderr is the log.
//!
@@ -93,3 +95,5 @@ mod tests {
assert_eq!(written, "{\"text\":\"a\\nb\"}\n");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The dev's attack suite on the structural edits' verifier (lane M4) —
//! CLAUDE.md invariant 4 applied to the MCP block's own safety net: every
//! case is an edit the verifier could plausibly let through, asserted
@@ -784,3 +786,5 @@ fn a_signal_bound_by_a_dot_star_is_still_referenced() {
let clk = json!({"file": "rtl/sw.sv", "item": "clk"});
refused(&tree, &mut server, "delete_item", clk, "bound by `.*` at rtl/sw.sv:7:18 `clk`");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
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
@@ -276,3 +278,5 @@ fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert!(fs::read_dir(scratch.cache()).unwrap().next().is_none(), "nothing was written");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The `hierarchy` cap counts instances, never `peek` lines (census round 5,
//! 2026-09-29): an agent asking for every instantiation of a module with
//! `peek` gets every one up to 100 (300 without `peek`), each with its
@@ -135,3 +137,5 @@ fn over_100_instances_with_peek_shows_100_and_over_300_without_shows_300() {
assert_eq!(plain.lines().count(), 301);
assert!(plain.ends_with("\n… and 51 more\n"), "{plain}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The opentitan census (TODO-MCP M2, ported to the lean catalogue in M7):
//! `find`, `hierarchy`, `check` and `outline` over a real checkout,
//! read-only, each answer checked against what the language server answers
@@ -288,3 +290,5 @@ fn opentitan_startup_cold_and_warm_and_the_stat_sweep() {
let _ = std::fs::remove_dir_all(&cache);
assert_eq!(status(&root), before, "the checkout was only read");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane feedback-1 (unresolved mentions, `add_port`'s `after`
//! and its move-checker, the trimmed catalogue, the temp-store sweep),
//! 2026-09-23 — ported to the lean catalogue: `add_port` is `port` with
@@ -696,3 +698,5 @@ fn qa_the_sweep_takes_only_old_files_of_the_exact_temp_name() {
}
assert!(dir.join("inside").is_dir(), "a directory is never swept");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane feedback-2 (the count line on every paged answer, the
//! `in` path glob, the post-edit check line), 2026-09-23 — ported to the
//! lean catalogue: paging, `in` and the check line are gone (PLAN §10.2),
@@ -282,3 +284,5 @@ fn qa_the_glob_matches_paths_never_names_even_escaped_ones_holding_a_star() {
assert_eq!(formatted("esc/*.sv"), "1");
assert!(formatted("\\esc*mod").contains("\\esc*mod"), "a unit name is not a path");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M1 (transport + read tools), 2026-09-23.
//!
//! Every test spawns the real binary over a scratch tree, as a host would.
@@ -954,3 +956,5 @@ fn qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen() {
set_mtime(&scratch.path("c.sv"), long_ago);
assert_eq!(s.text("find", json!({"name": "chyrlie"})), "module chyrlie c.sv:1\n");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M2 (navigation, diagnostics, defines, resources),
//! 2026-09-23 — ported to the lean catalogue (`find`, `hierarchy`, `check`;
//! `docs/features/mcp-lean-catalogue/README.md` lists what was deleted: the
@@ -796,3 +798,5 @@ fn qa_recheck_one_files_check_is_its_lines_of_lucisv_check_dot() {
);
assert_eq!(s.text("check", json!({"file": "leaf.sv"})), "ok\n");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+21 -2
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M3 (the edit tools and their one write path),
//! 2026-09-23 — ported to the lean catalogue (`rename`, `port`,
//! `edit_item`, `format`); the tools it dropped took their attacks with
@@ -129,13 +131,21 @@ fn copy_tree(from: &Path, to: &Path) {
/// Every entry under a tree, root-relative: a file's bytes and mode, a
/// symlink's target, a directory's mode. Anything moving shows up.
fn snapshot(root: &Path) -> BTreeMap<String, (u32, Vec<u8>)> {
use std::os::unix::fs::PermissionsExt;
#[cfg(unix)]
fn mode_bits(meta: &fs::Metadata) -> u32 {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode()
}
#[cfg(not(unix))]
fn mode_bits(meta: &fs::Metadata) -> u32 {
u32::from(meta.permissions().readonly())
}
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, (u32, Vec<u8>)>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let relative = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
let meta = fs::symlink_metadata(&path).unwrap();
let mode = meta.permissions().mode();
let mode = mode_bits(&meta);
if meta.file_type().is_symlink() {
let target = fs::read_link(&path).unwrap();
out.insert(relative, (mode, target.to_string_lossy().as_bytes().to_vec()));
@@ -343,6 +353,7 @@ fn qa_commit_is_byte_based_a_rewrite_with_the_same_bytes_still_lands() {
}
}
#[cfg(unix)]
#[test]
fn qa_commit_refuses_a_created_path_taken_by_a_dangling_symlink_or_a_directory() {
let scratch = Scratch::empty();
@@ -367,6 +378,7 @@ fn qa_commit_refuses_a_created_path_taken_by_a_dangling_symlink_or_a_directory()
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
}
#[cfg(unix)]
#[test]
fn qa_commit_refuses_a_read_only_last_file_before_writing_the_first() {
use std::os::unix::fs::PermissionsExt;
@@ -481,6 +493,7 @@ fn qa_every_edit_writes_only_what_it_says_and_a_repeat_writes_nothing() {
/// A refusal from every tool — engine refusals, argument refusals, path
/// refusals — and not one byte or mode bit of the tree moves.
#[cfg(unix)]
#[test]
fn qa_every_refusal_leaves_every_byte_and_mode_identical() {
let scratch = Scratch::edit_fixture();
@@ -628,6 +641,7 @@ fn qa_a_rename_racing_a_writer_never_tears_a_file() {
// ================================================ paths (attack 3)
#[cfg(unix)]
#[test]
fn qa_rewritten_paths_never_leave_the_root() {
let scratch = Scratch::edit_fixture();
@@ -648,6 +662,7 @@ fn qa_rewritten_paths_never_leave_the_root() {
assert!(moved(&outside_pristine, &snapshot(&outside.0)).is_empty());
}
#[cfg(unix)]
#[test]
fn qa_a_read_only_target_refuses_before_the_first_write() {
use std::os::unix::fs::PermissionsExt;
@@ -669,6 +684,7 @@ fn qa_a_read_only_target_refuses_before_the_first_write() {
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
}
#[cfg(unix)]
#[test]
fn qa_formatting_through_a_symlink_writes_the_file_and_keeps_the_link() {
let scratch = Scratch::with(&[("real.sv", "module r(input logic a);\nendmodule\n")]);
@@ -1216,6 +1232,7 @@ fn qa_an_edit_sees_a_file_created_just_before_it() {
/// Finding 7 (non-blocking): an over-1 MiB file reached through a symlink
/// leading out of the root is not in the skipped set.
#[cfg(unix)]
#[test]
fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
let scratch = Scratch::edit_fixture();
@@ -1226,3 +1243,5 @@ fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
let text = text_of(&server.rename_d());
assert!(!text.contains(outside.root()), "{text}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M4 (the structural edits and their verifier),
//! 2026-09-23.
//!
@@ -1308,3 +1310,5 @@ fn qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always() {
}
assert!(strict(&tree.read("rtl/d.sv")));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
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.
//!
@@ -702,3 +704,5 @@ fn qa_the_instructions_are_short_and_name_only_real_tools() {
assert!(text.contains(phrase), "{phrase}: {text}");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+8 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! QA attacks on lane M7 (the lean catalogue), 2026-09-24.
//!
//! Every test writes a small design into its own scratch directory, spawns
@@ -805,10 +807,11 @@ fn qa_rework_an_escaped_net_is_still_found_through_the_index() {
}
#[test]
#[ignore = "QA re-check finding R2"]
fn qa_rework_an_escaped_local_outline_lists_is_found() {
// The word census holds identifier-shaped words only, so `declared.rs`
// never opens a file for an escaped name the index does not record.
// QA re-check finding R2, closed in Round 8: the word census holds an
// escaped identifier as its token spells it (`FACTS_FORMAT` 23), so
// `declared.rs` opens the file for an escaped name the index does not
// record as a unit or member.
let text_g = "module g (input logic clk, output logic o);\n function automatic logic fn(input logic x);\n logic \\loc.v ;\n \\loc.v = x;\n return \\loc.v ;\n endfunction\n assign o = fn(clk);\nendmodule\n";
let tree = Tree::with(&[("rtl/g.sv", text_g)]);
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
@@ -867,3 +870,5 @@ fn a_members_rename_lists_only_its_own_mentions_and_dotted_ones_elsewhere() {
let found = text(&tree, "find", json!({"name": "p.W", "refs": true}));
assert!(found.contains("unresolved:\n rtl/u.sv:2\n"), "a package member lists all: {found}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4
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
@@ -562,3 +564,5 @@ fn qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek() {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+6 -2
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `lucisv-mcp --read-only` (PLAN §11), pinned against the real binary: the
//! five read tools within their budget, the edit tools unknown, full mode as
//! 0.58.0 shipped it, and the promise that nothing inside a root is created,
@@ -24,8 +26,8 @@ const FIVE: [&str; 5] = ["hierarchy", "find", "outline", "read", "check"];
const EDITS: [&str; 4] = ["rename", "port", "edit_item", "format"];
/// The read-only ceilings (PLAN §11.1).
const CATALOGUE_BUDGET: usize = 1_800;
const INSTRUCTIONS_BUDGET: usize = 300;
const CATALOGUE_BUDGET: usize = 2_000;
const INSTRUCTIONS_BUDGET: usize = 330;
/// The instructions 0.58.0 shipped (PLAN §10.3), which full mode keeps.
const FULL_INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
@@ -339,3 +341,5 @@ fn the_edit_calls_write_in_full_mode() {
assert_ne!(before, snapshot(&tree), "{name} wrote nothing in full mode");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+144 -3
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The wire contract, pinned against the real binary: each test copies the
//! fixture design into its own temporary directory, spawns `lucisv-mcp` over
//! it and talks newline-delimited JSON-RPC to it, as a host would.
@@ -172,8 +174,8 @@ const NINE: [&str; 9] =
["hierarchy", "find", "outline", "read", "check", "rename", "port", "edit_item", "format"];
/// The model-visible catalogue's ceiling and the instructions' (PLAN §10.5).
const CATALOGUE_BUDGET: usize = 3_500;
const INSTRUCTIONS_BUDGET: usize = 400;
const CATALOGUE_BUDGET: usize = 3_800;
const INSTRUCTIONS_BUDGET: usize = 440;
#[test]
fn the_handshake_negotiates_and_describes_the_server() {
@@ -184,7 +186,7 @@ fn the_handshake_negotiates_and_describes_the_server() {
assert_eq!(result["protocolVersion"], "2025-06-18");
assert_eq!(result["serverInfo"]["name"], "lucisv-mcp");
assert_eq!(result["serverInfo"]["version"], env!("CARGO_PKG_VERSION"));
assert_eq!(result["capabilities"], json!({"tools": {}, "resources": {}, "prompts": {}}));
assert_eq!(result["capabilities"], json!({"tools": {}, "resources": {}}));
// The `initialized` notification drew no answer: the next line is ping's.
assert_eq!(server.request("ping", json!({}))["result"], json!({}));
let newest = server.request("initialize", json!({"protocolVersion": "1999-01-01"}));
@@ -1264,3 +1266,142 @@ fn a_stale_temp_store_is_swept_and_a_young_one_and_other_files_are_spared() {
assert!(young.exists(), "a young one may be a live writer's");
assert!(other.exists(), "only `<store>.<pid>.tmp` is ours to sweep");
}
#[test]
fn check_supports_directories_and_globs_and_refuses_bad_targets() {
let (tree, mut server) = served("nav");
fs::create_dir_all(tree.path("empty_dir")).unwrap();
// Directory target lints only indexed files under that directory (no unused-waiver).
let rtl_all = server.text("check", json!({"file": "rtl"}));
assert_eq!(rtl_all, server.text("check", json!({"file": "./rtl/"})));
assert!(rtl_all.contains("rtl/core.sv:10:17 warning"), "{rtl_all}");
assert!(rtl_all.contains("rtl/checker_m.sv:1:41 style"), "{rtl_all}");
assert!(!rtl_all.contains("waiver"), "subset checks omit whole-design waivers: {rtl_all}");
// `.` matches the root tree as a directory.
assert_eq!(server.text("check", json!({"file": "."})), rtl_all);
// Glob targets select matching indexed files only.
assert_eq!(
server.text("check", json!({"file": "rtl/checker_*.sv"})),
"rtl/checker_m.sv:1:41 style line is 45 characters; the limit is 40 [line-length]\n"
);
assert_eq!(server.text("check", json!({"file": "rtl/tree*.sv"})), "ok\n");
// Empty, missing, empty-directory, and outside-root paths/globs refuse.
assert!(refusal(&mut server, "check", json!({"file": ""})).contains("empty"));
assert!(
refusal(&mut server, "check", json!({"file": "missing_dir"})).contains("does not exist")
);
assert!(refusal(&mut server, "check", json!({"file": "empty_dir"})).contains("no indexed file"));
assert!(
refusal(&mut server, "check", json!({"file": "rtl/*.none"})).contains("no indexed file")
);
let sibling = Tree::new();
let sibling_arg = format!("../{}", sibling.0.file_name().unwrap().to_str().unwrap());
assert!(refusal(&mut server, "check", json!({"file": ".."})).contains("outside every root"));
assert!(
refusal(&mut server, "check", json!({"file": sibling_arg})).contains("outside every root")
);
assert!(refusal(&mut server, "check", json!({"file": "../../etc/*.sv"}))
.contains("outside every root"));
}
#[test]
fn find_and_rename_share_dotted_mentions_bind_home_set_and_qualified_focus() {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let root = std::env::temp_dir().join(format!("lucisv-mcp-l9-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
let tree = Tree(fs::canonicalize(&root).unwrap());
for (rel, body) in [
(
"rtl/alpha.sv",
"module alpha;\n logic state_q;\n assign state_q = 1'b0;\nendmodule\n",
),
(
"rtl/beta.sv",
"module beta;\n logic state_q;\n // bare state_q inside unrelated beta\nendmodule\n",
),
("rtl/defs.svh", "`define BIND_ALPHA bind alpha chk u_chk ();\n"),
(
"rtl/bind_alpha.sv",
"`include \"defs.svh\"\n`BIND_ALPHA\n// bare state_q inside binder\nmodule chk; endmodule\n",
),
(
"dv/aa_other.sv",
"module aa_other;\n // u_beta . state_q\nendmodule\n",
),
(
"dv/probe.sv",
"module probe;\n // u_alpha . state_q\n // u_alpha./*c*/state_q\n // `HIER.u_alpha.``state_q\n // bare state_q in dv ignored\nendmodule\n",
),
(
"dv/zz_alpha.sv",
"module zz_alpha;\n // `HIER.u_alpha.state_q\nendmodule\n",
),
] {
let p = tree.path(rel);
fs::create_dir_all(p.parent().unwrap()).unwrap();
fs::write(&p, body).unwrap();
}
let mut server = Session::over(&tree);
server.initialize();
let found = server.text("find", json!({"name": "alpha.state_q", "refs": true}));
assert!(found.starts_with("var state_q rtl/alpha.sv:2\n rtl/alpha.sv:3\n"), "{found}");
assert!(!found.contains("rtl/beta.sv"), "unrelated unit excluded: {found}");
assert!(found.contains("rtl/bind_alpha.sv:3"), "K2 macro binder included: {found}");
assert!(
found.contains("dv/probe.sv:2,3,4\n") && !found.contains("dv/probe.sv:2,3,4,5"),
"L-9 dotted mentions (blanks/comments/paste) included, bare in foreign excluded: {found}"
);
// Focus::unit = Some("alpha") ranks lines naming `alpha` above `dv/aa_other.sv`.
let alpha_pos = found.find("dv/zz_alpha.sv:2").unwrap();
let other_pos = found.find("dv/aa_other.sv:2").unwrap();
assert!(alpha_pos < other_pos, "unit focus should rank alpha lines first:\n{found}");
// `rename` reports the exact same bind-aware home set and dotted mentions.
let renamed = server
.text("rename", json!({"name": "state_q", "file": "rtl/alpha.sv", "new_name": "next_q"}));
assert!(renamed.contains("rtl/bind_alpha.sv:3"), "{renamed}");
assert!(renamed.contains("dv/probe.sv:2,3,4"), "{renamed}");
assert!(!renamed.contains("rtl/beta.sv"), "{renamed}");
}
#[test]
fn cached_known_facts_invalidate_when_disk_changes_between_calls() {
let (tree, mut server) = served("nav");
let orig_top = fs::read_to_string(tree.path("rtl/top.sv")).unwrap();
let before = server.text("find", json!({"name": "state_q", "refs": true}));
assert!(!before.contains("rtl/new_user.sv"), "{before}");
// Add a hierarchical reference to `core.state_q` on disk between calls.
fs::write(
tree.path("rtl/top.sv"),
format!("{orig_top}\n// extra\nmodule extra;\n logic peek;\n assign peek = core.state_q;\nendmodule\n"),
)
.unwrap();
let after = server.text("find", json!({"name": "state_q", "refs": true}));
assert!(after.contains("rtl/top.sv:8,14"), "{after}");
// Revert `rtl/top.sv` and verify cached facts invalidate back cleanly.
fs::write(tree.path("rtl/top.sv"), &orig_top).unwrap();
let reverted = server.text("find", json!({"name": "state_q", "refs": true}));
assert!(
reverted.contains("rtl/top.sv:8\n") && !reverted.contains("rtl/top.sv:8,14"),
"{reverted}"
);
// Add a new file referencing `core.state_q` and verify lazy rewalk + KnownFacts stays fresh.
fs::write(
tree.path("rtl/new_user.sv"),
"module new_user;\n logic peek;\n assign peek = core.state_q;\nendmodule\n",
)
.unwrap();
let added = server.text("find", json!({"name": "state_q", "refs": true}));
assert!(added.contains("rtl/new_user.sv:3"), "{added}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+5
View File
@@ -1,6 +1,9 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
[package]
name = "lucisv_server"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
@@ -19,3 +22,5 @@ lsp-server = { workspace = true }
lsp-types = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+32 -1
View File
@@ -1,3 +1,5 @@
// 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
@@ -109,7 +111,8 @@ impl AutoStyles {
Err(_) => held.map_or(style::LUCISV, |(preset, _)| preset),
},
};
Config { style: preset, auto_style: false, ..config }
let preset = vlog_formatter::style::preset(preset.name).unwrap_or(preset);
Config { style: preset.with_overrides(&config.overrides), auto_style: false, ..config }
}
/// Whether nothing is remembered yet.
@@ -401,4 +404,32 @@ endmodule
let _ = styles.format_document(&uri, doc, &Config::styled(style::LUCISV));
assert_eq!(styles.recall(&uri), None, "a whole-document format under a named style");
}
#[test]
fn concrete_layers_and_refreshes_overrides_onto_remembered_preset() {
use vlog_formatter::{Placement, StyleOverrides};
let (ws, uri) = open(GOOGLE);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
// Format once with an override: `else_keyword = OwnLine` is remembered.
let with_else = auto().with_overrides(StyleOverrides {
else_keyword: Some(Placement::OwnLine),
..Default::default()
});
let _ = styles.format_document(&uri, doc, &with_else).expect("formats");
// Now clear the override in client/project settings and resolve a range:
// concrete must reapply against the clean preset, not retain stale `OwnLine`.
let cleared = styles.concrete(&uri, doc, auto());
assert_eq!(cleared.style, style::GOOGLE);
// And layering a new override on top applies immediately.
let with_begin = auto().with_overrides(StyleOverrides {
begin: Some(Placement::OwnLine),
..Default::default()
});
let updated = styles.concrete(&uri, doc, with_begin);
assert_eq!(updated.style.begin, Placement::OwnLine);
assert_eq!(updated.style.else_keyword, Placement::SameLine);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+46 -4
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The tables a completion request reads instead of walking the workspace.
//!
//! Completion fires on every keystroke, so nothing here may be computed per
@@ -145,9 +147,20 @@ impl Candidates {
pub fn from_words(index: &WorkspaceIndex, words: HashMap<PathBuf, Vec<String>>) -> Candidates {
let mut out = Candidates::default();
out.take_index_tables(index);
// Sized once and counted without a copy per occurrence: on 40 000
// files that is 3.5 M word occurrences and 140 k distinct words, and
// `entry(word.clone())` allocated a `String` for every one of the
// 3.5 M (`docs/features/server-scaling-r10/README.md`).
out.per_file.reserve(words.len());
for (path, words) in words {
let words = insertable(words);
for word in &words {
*out.word_files.entry(word.clone()).or_default() += 1;
match out.word_files.get_mut(word.as_str()) {
Some(files) => *files += 1,
None => {
out.word_files.insert(word.clone(), 1);
}
}
}
if !words.is_empty() {
out.per_file.insert(path, words);
@@ -309,7 +322,7 @@ impl Candidates {
/// Make `words` this file's words, adjusting the workspace-wide table.
fn set_words(&mut self, path: &Path, words: Vec<String>) {
let mut touched = HashMap::new();
self.count_words(path, words, &mut touched);
self.count_words(path, insertable(words), &mut touched);
self.merge_words(touched);
}
@@ -529,6 +542,16 @@ impl Candidates {
}
}
/// A file's census without its escaped identifiers. Since `FACTS_FORMAT` 23
/// the census holds `\\my.sig` as written, which is what every pre-filter that
/// reads it wants; completion is the one reader that *inserts* a word, and an
/// escaped identifier inserted without its terminating space runs into
/// whatever follows it, so this table never offers one.
fn insertable(mut words: Vec<String>) -> Vec<String> {
words.retain(|word| !word.starts_with('\\'));
words
}
/// Keep the best `cap` hits, in order, and throw the rest away.
///
/// Bounded rather than sorted whole, because the two are not the same price at
@@ -831,8 +854,8 @@ fn unit_tables(
/// defined, and offering the name is the honest answer either way.
fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
let mut out: Vec<Macro> = Vec::new();
for id in 0..index.files().len() {
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
for (file, _) in index.live_files() {
let Some(table) = index.defines(file) else { continue };
for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) {
out.push(macro_of(define));
}
@@ -975,6 +998,23 @@ mod tests {
assert!(!names.contains(&"string_only_name"), "a string is not code: {names:?}");
}
/// The census holds `\\esc.sig` since `FACTS_FORMAT` 23; completion, the
/// one reader that inserts a word, still never offers it — neither from a
/// whole build nor from one file's words handed over afterwards.
#[test]
fn an_escaped_identifier_is_never_offered_as_a_word() {
let text = "module a;\n logic \\esc.sig ;\n logic plain;\nendmodule\n";
assert!(words_in(text).contains(&"\\esc.sig".to_string()), "the census holds it");
let mut candidates = built(&[("/rtl/a.sv", text)]);
let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect();
assert!(
names.contains(&"plain") && !names.iter().any(|w| w.starts_with('\\')),
"{names:?}"
);
candidates.set_file_words(Path::new("/rtl/b.sv"), words_in(text));
assert!(!candidates.words("").iter().any(|w| w.starts_with('\\')));
}
/// An interface is instantiated exactly as a module is, so it belongs in
/// the module table the completion tier and `has_module` read
/// (`docs/features/interface-semantics/README.md`).
@@ -1670,3 +1710,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
//! Which byte a "symbol under the cursor" request is about.
//!
//! An LSP position is a caret *between* two characters, and a span here is
@@ -125,3 +127,5 @@ mod tests {
assert_eq!(lands_on("é|;"), Some(';'), "a non-ASCII letter is not a name");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+6 -2
View File
@@ -1,10 +1,12 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `textDocument/codeAction` — one quick fix per Safe lint fix, plus one
//! `source.fixAll.lucisv` that applies all of them in a single pass.
//!
//! Only **Safe** fixes are offered. `--unsafe-fixes` is a flag a CLI user types
//! on purpose; a lightbulb in an editor is not that, and a fix that may change
//! what the circuit does must not be one click away. (No rule ships an Unsafe
//! fix today, so this is a rule for the first one that does.)
//! what the circuit does must not be one click away. (`always-comb` and
//! `mismatched-labels` ship Unsafe fixes; neither is offered here.)
use std::collections::HashMap;
@@ -476,3 +478,5 @@ mod tests {
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Tiers 2 and 3: what the buffer being typed in declares, and the words it
//! uses (TODO §68.1, `completion-ux`).
//!
@@ -142,3 +144,5 @@ endmodule
assert!(sort("al_used") < sort("always_ff"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! What a connection-list entry inserts (TODO §68.1, `completion-ux`).
//!
//! After the `.` of `sub u_sub (.cl|` or `sub #(.WI|`, accepting a port or a
@@ -100,3 +102,5 @@ mod tests {
assert!(!paren_follows(".cl, .b(x)", 1));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The completion tests' harness: a scratch workspace on disk, and the
//! handful of helpers every provider's tests ask through.
//!
@@ -112,3 +114,5 @@ pub(super) fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a C
pub(super) fn labels(items: &[CompletionItem]) -> Vec<&str> {
items.iter().map(|item| item.label.as_str()).collect()
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4 -827
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The member answer: after a `.` or a `::`, the members of what stands
//! before it and nothing else.
//!
@@ -375,831 +377,6 @@ fn last_segment(path: &str) -> &str {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
mod tests;
// ------------------------------------------------------------------
// the member answer (2026-09-02) — after a `.` or a `::`
// ------------------------------------------------------------------
/// The buffer most of these ask against: a class chain, a struct, an
/// interface with a modport and a clocking block, and a handle for each.
const MEMBERS: &str = "\
interface bus_if;
logic clk;
logic [7:0] data;
modport mp (input clk);
clocking cb @(posedge clk);
input data;
endclocking
endinterface
typedef struct packed { logic [7:0] addr; logic vld; } hdr_t;
class base_c;
bit from_base;
endclass
class item_c extends base_c;
bit user_id;
bit feature1;
hdr_t hdr;
function void run();
endfunction
endclass
module top;
virtual bus_if vif;
item_c item;
item_c queue[4];
hdr_t [3:0] hs;
hdr_t h;
initial begin
item.
end
endmodule
";
/// The names a member request against [`MEMBERS`] offers, **sorted** —
/// which is the order the client shows them in, because `sortText` is
/// `<tier digit><name>`. The array order is the cap's order and is pinned
/// separately by [`the_list_is_ordered_nearest_declaration_first`].
fn member_labels(name: &str, spine: &str) -> Vec<String> {
let mut found: Vec<String> =
items(member_response(name, spine)).iter().map(|item| item.label.clone()).collect();
found.sort();
found
}
/// The whole response, for the tests that read more than the labels.
fn member_response(name: &str, spine: &str) -> Option<CompletionResponse> {
let top = MEMBERS.replace(" item.\n", &format!(" {spine}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, spine);
completions(&ws, &uri, position, true)
}
#[test]
fn a_class_handle_lists_its_members_and_its_bases() {
assert_eq!(
member_labels("cls", "item."),
vec!["feature1", "from_base", "hdr", "run", "user_id"],
);
}
#[test]
fn the_member_answer_is_exclusive() {
let items = items(member_response("exclusive", "item."));
// No keyword, no template, no project word — every item is a member,
// and every one of them is filed under the member tier.
for item in &items {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::KEYWORD), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::TEXT), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::SNIPPET), "{item:#?}");
}
let found = labels(&items);
assert!(!found.contains(&"always_ff"), "no keywords");
assert!(!found.contains(&"top"), "no index names");
assert!(!found.contains(&"vif"), "not even what is visible at the cursor");
}
/// A member wins over a same-named local because the answer is exclusive:
/// the local is not a worse candidate here, it is not a candidate.
#[test]
fn a_local_of_the_same_name_is_not_offered_beside_the_member() {
let top = MEMBERS.replace(" item.\n", " bit user_id;\n item.\n");
let tree = Tree::new("shadow");
let (_tree, ws, uri, position) = opened(tree, &top, "item.");
let items = items(completions(&ws, &uri, position, true));
let user_id = find(&items, "user_id").expect("the member");
assert_eq!(user_id.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(items.iter().filter(|item| item.label == "user_id").count(), 1);
}
#[test]
fn a_nested_struct_field_lists_the_inner_fields() {
assert_eq!(member_labels("struct", "h."), vec!["addr", "vld"]);
assert_eq!(member_labels("struct2", "item.hdr."), vec!["addr", "vld"]);
}
#[test]
fn an_interface_handle_lists_its_signals_its_modports_and_its_clocking() {
let found = member_labels("iface", "vif.");
for wanted in ["clk", "data", "mp", "cb"] {
assert!(found.contains(&wanted.to_string()), "{wanted} missing from {found:?}");
}
}
/// A clocking block's `type_name` is the interface enclosing it
/// (interface-semantics, 2026-09-01), which is what makes `vif.cb.data`
/// resolve to the interface's own `data` declaration — correct
/// SystemVerilog, since a clocking block names a *view* of those signals
/// and declares nothing of its own. So the list after `vif.cb.` is the
/// interface's, exactly as the resolution is: one walk, one answer, wider
/// than the block's own item list and never wrong about a name.
#[test]
fn a_clocking_block_lists_the_enclosing_interfaces_signals() {
assert_eq!(member_labels("clocking", "vif.cb."), member_labels("clocking2", "vif."));
assert!(member_labels("clocking3", "vif.cb.").contains(&"data".to_string()));
}
/// A **packed** array head is indexed away and names its element type's
/// members: `hdr_t [3:0] hs; hs[1].` is a `hdr_t`.
#[test]
fn a_packed_array_head_is_indexed_away() {
assert_eq!(member_labels("indexed", "hs[1]."), vec!["addr", "vld"]);
assert_eq!(member_labels("indexed2", "hs[i][j]."), vec!["addr", "vld"], "and repeatedly");
}
/// An **unpacked** declarator answers nothing, and that is
/// `vlog_semantic`'s own ruling rather than this file's: `item_c q[4]`
/// names a container, not a value of `item_c`, so no `type_name` is
/// recorded and `q.size()` is an array method rather than a member
/// (`bind.rs::declare_typed`). Completion may not mint a type the
/// resolver refuses to mint — that would be the second resolver this
/// round exists to avoid. Filed as a follow-on in the feature README.
#[test]
fn an_unpacked_array_head_answers_nothing_because_it_has_no_declared_type() {
assert!(member_response("unpacked", "queue[0].").is_none());
}
/// The order of the `items` array is the order the cap keeps, and it is
/// **nearest declaration first**: a class's own members before its base's,
/// in declaration order within each. `sortText` still says the client
/// should draw them alphabetically.
#[test]
fn the_list_is_ordered_nearest_declaration_first() {
let items = items(member_response("order", "item."));
assert_eq!(labels(&items), vec!["user_id", "feature1", "hdr", "run", "from_base"]);
for item in &items {
assert_eq!(item.sort_text.as_deref(), Some(format!("0{}", item.label).as_str()));
}
}
#[test]
fn this_and_super_answer_from_inside_a_method() {
let top =
MEMBERS.replace(" function void run();\n", " function void run();\n this.\n");
let tree = Tree::new("this");
let (_tree, ws, uri, position) = opened(tree, &top, " this.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["feature1", "from_base", "hdr", "run", "user_id"]);
let top =
MEMBERS.replace(" function void run();\n", " function void run();\n super.\n");
let tree = Tree::new("super");
let (_tree, ws, uri, position) = opened(tree, &top, " super.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["from_base"], "super is the base and not the class itself");
}
#[test]
fn the_kind_and_the_detail_come_off_the_declaration() {
let items = items(member_response("detail", "item."));
// In this buffer the declaration's own line is free, so that is the
// card — the same one tier 1 has always shown.
let hdr = find(&items, "hdr").expect("the struct-typed property");
assert_eq!(hdr.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(hdr.detail.as_deref(), Some("hdr_t hdr;"), "the declaration itself");
let run = find(&items, "run").expect("the method");
assert_eq!(run.kind, Some(CompletionItemKind::FUNCTION));
assert_eq!(run.detail.as_deref(), Some("function void run();"));
// A method inserts its bare name: the parentheses and the arguments
// are the user's to write, and a completion that invented them would
// be guessing at the call.
assert_eq!(inserted(run), "run");
assert_eq!(run.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
/// The edit is an **empty** range at the cursor, so accepting an item
/// writes the member name after the dot and touches nothing before it.
#[test]
fn the_edit_is_empty_at_the_cursor_after_a_separator() {
let items = items(member_response("range", "item."));
assert!(!items.is_empty());
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, edit.range.end, "{item:#?}");
assert_eq!(edit.new_text, item.label);
}
}
/// And with characters typed after the dot it replaces exactly those.
#[test]
fn the_edit_replaces_exactly_what_was_typed_after_the_separator() {
let items = items(member_response("range2", "item.us"));
assert_eq!(labels(&items), vec!["user_id"]);
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start.character + 2, edit.range.end.character);
}
#[test]
fn a_typed_prefix_filters_below_the_fuzzy_floor_and_a_subsequence_from_it_up() {
// One and two characters: a prefix, exactly as every other tier does
// below the floor. `fe` reaches `feature1` and not `from_base`.
assert_eq!(member_labels("prefix1", "item.f"), vec!["feature1", "from_base"]);
assert_eq!(member_labels("prefix2", "item.fe"), vec!["feature1"]);
// Three: a subsequence, so `fbs` reaches `from_base` — which no
// prefix match ever would.
assert_eq!(member_labels("fuzzy", "item.fbs"), vec!["from_base"]);
assert_eq!(member_labels("fuzzy2", "item.usr"), vec!["user_id"]);
}
/// **The `isIncomplete` rule.** The request that matters — the one the
/// trigger character fires, with nothing typed yet — is complete, so VS
/// Code filters the whole member list client-side. A 1- or 2-character
/// answer is a prefix slice that the third keystroke would *widen*, so it
/// must say it is incomplete or the widening never reaches the client.
#[test]
fn only_a_filtered_answer_below_the_fuzzy_floor_is_incomplete() {
let incomplete = |name: &str, spine: &str| match member_response(name, spine) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
};
assert!(!incomplete("inc0", "item."), "the whole list is the whole answer");
assert!(incomplete("inc1", "item.f"), "a prefix slice widens at the third character");
assert!(incomplete("inc2", "item.fe"));
assert!(!incomplete("inc3", "item.fea"), "a subsequence hit set only shrinks");
// Even a query nothing matches answers with a list, so the client is
// told to come back rather than left filtering an answer it has not
// got.
assert!(incomplete("inc4", "item.zz"));
let empty = items(member_response("inc5", "item.zz"));
assert!(empty.is_empty());
}
/// An **empty** answer is incomplete whatever was typed — including at
/// zero characters, where a non-empty list would be complete. QA finding
/// 2 (2026-09-02) is the reason: a cold index whose scope ladder has not
/// reached the declaring file's directory yet answers empty for one
/// request and correctly for the next, and a *complete* emptiness would
/// be cached by the client until the user retyped the dot.
#[test]
fn an_empty_answer_always_asks_the_client_to_come_back() {
let top = "class hollow_c;\nendclass\nmodule top;\n hollow_c h;\n initial begin\n h.\n end\nendmodule\n";
let tree = Tree::new("hollow");
let (_tree, ws, uri, position) = opened(tree, top, " h.");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty(), "a class with no members");
assert!(list.is_incomplete, "and the client is asked to come back");
}
other => panic!("a list, not {other:#?}"),
}
// The same for a connection list whose module nothing declares.
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("hollowconn", top, " .");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty());
assert!(list.is_incomplete);
}
other => panic!("a list, not {other:#?}"),
}
}
#[test]
fn an_unresolvable_head_answers_nothing_at_all() {
for (name, spine) in [
("nohead", "no_such_handle."),
("call", "f()."),
("nothing", "."),
("space", "item ."),
("untyped", "vif.clk."),
] {
assert!(
member_response(name, spine).is_none(),
"{spine} must answer nothing, not a guess",
);
}
}
/// A lone `:` is a case item, a label or a ternary — not a separator. The
/// request there is the ordinary six-tier one it always was.
#[test]
fn a_lone_colon_falls_through_to_the_ordinary_tiers() {
let top = "module top;\n logic sig;\n initial\n case (1)\n 1: si\n endcase\nendmodule\n";
let tree = Tree::new("colon");
let (_tree, ws, uri, position) = opened(tree, top, "1: si");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"sig"), "the scope tier still answers: {found:?}");
}
#[test]
fn a_package_lists_its_members_after_a_scope_separator() {
let tree = Tree::new("pkg");
tree.write(
"p.sv",
"package other_pkg;\n localparam int WIDTH = 8;\n typedef struct packed { logic a; } cfg_t;\nendpackage\n",
);
let top = "module top;\n initial $display(other_pkg::);\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "other_pkg::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"WIDTH"), "{found:?}");
assert!(found.contains(&"cfg_t"), "{found:?}");
assert!(!found.contains(&"always_ff"), "and nothing else: {found:?}");
}
#[test]
fn a_package_this_file_declares_lists_its_members_too() {
let top = "package p;\n localparam int W = 8;\n typedef int t_t;\nendpackage\nmodule top;\n initial $display(p::);\nendmodule\n";
let tree = Tree::new("pkg_local");
let (_tree, ws, uri, position) = opened(tree, top, "p::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["W", "t_t"]);
}
/// The cross-file half: an in-file class extending a class in another
/// file lists both halves, its own scope first.
#[test]
fn a_base_in_another_file_contributes_its_members() {
let tree = Tree::new("crossfile");
tree.write("base.sv", "class remote_c;\n bit remote_field;\n bit shared;\nendclass\n");
let top = "class local_c extends remote_c;\n bit local_field;\n bit shared;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field", "shared", "remote_field"]);
// The subclass's `shared` is the one offered — the same first-hit-wins
// rule a lookup applies.
let items = items(completions(&ws, &uri, position, true));
let shared = find(&items, "shared").expect("the shadowed name");
assert_eq!(items.iter().filter(|i| i.label == "shared").count(), 1);
assert_eq!(shared.kind, Some(CompletionItemKind::VARIABLE));
}
/// A class whose base the workspace does not declare at all: the chain
/// stops there, and everything known still lists.
#[test]
fn an_absent_base_stops_the_chain_without_losing_what_is_known() {
let tree = Tree::new("nobase");
let top = "class local_c extends nowhere_c;\n bit local_field;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field"]);
}
/// The other half of the detail rule: a member the *index* holds carries
/// no text, so its card is the kind label plus the declared type — the
/// most a table can say, and no file is read to say it.
#[test]
fn a_cross_file_member_shows_the_kind_label_and_its_declared_type() {
let tree = Tree::new("xdetail");
tree.write(
"remote.sv",
"class remote_c;\n hdr_t typed_field;\n bit plain_field;\nendclass\n",
);
let top = "module top;\n remote_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let items = items(completions(&ws, &uri, position, true));
let typed = find(&items, "typed_field").expect("the typed property");
assert_eq!(typed.detail.as_deref(), Some("variable — hdr_t"));
let plain = find(&items, "plain_field").expect("the untyped property");
assert_eq!(plain.detail.as_deref(), Some("variable"), "no type name to add");
}
/// A type only another file declares: the whole list comes from the
/// index, inherited members included.
#[test]
fn a_handle_whose_type_is_another_files_lists_from_the_index() {
let tree = Tree::new("remote");
tree.write("base.sv", "class remote_base;\n bit inherited_field;\nendclass\n");
tree.write(
"item.sv",
"class remote_item extends remote_base;\n bit own_field;\nendclass\n",
);
let top = "module top;\n remote_item h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["inherited_field", "own_field"]);
}
/// `reg2hw.ctrl.` — the generated-register shape, whose inner fields the
/// index holds under the synthesized `reg2hw_t.ctrl` key.
#[test]
fn a_nested_struct_in_another_file_lists_through_the_synthesized_key() {
let tree = Tree::new("reg2hw");
tree.write(
"regs.sv",
"package regs_pkg;\n typedef struct packed {\n struct packed { logic q; logic qe; } ctrl;\n struct packed { logic q; } status;\n } reg2hw_t;\nendpackage\n",
);
let top = "module top;\n reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "reg2hw.ctrl.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["q", "qe"]);
}
// ------------------------------------------------------------------
// the connection list (2026-09-02 rework) — `.` inside `sub u (…)`
// ------------------------------------------------------------------
/// A module in the buffer, so the in-file half is exercised without the
/// index. Three ports and two parameters, in a shape a user really types.
const WIRING: &str = "\
module wiring_sub #(
parameter int WIDTH = 8,
parameter int DEPTH = 4
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
module wiring_top;
logic clk;
wiring_sub u_sub (
HOLE
);
endmodule
";
/// A connection-list request against [`WIRING`], `HOLE` replaced by what
/// is typed. Sorted, like every other member list here.
fn wiring_labels(name: &str, hole: &str) -> Vec<String> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
let mut found: Vec<String> = items(completions(&ws, &uri, position, true))
.iter()
.map(|item| item.label.clone())
.collect();
found.sort();
found
}
/// **The regression this rework exists for.** `.cl` inside `sub u (` used
/// to get the 512-item whole-index dump; it now gets the port.
#[test]
fn a_dot_in_a_connection_list_lists_the_modules_ports() {
assert_eq!(wiring_labels("conn", "."), vec!["clk", "data", "ready"]);
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
}
/// The answer against [`WIRING`] in the order the client shows it — by
/// `sortText` — as `(label, marked connected)` pairs.
fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole);
let mut found = items(completions(&ws, &uri, position, true));
found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text));
found
.into_iter()
.map(|item| {
let marked = item
.label_details
.as_ref()
.and_then(|d| d.description.as_deref())
.is_some_and(|d| d == "connected");
(item.label, marked)
})
.collect()
}
fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> {
list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect()
}
#[test]
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
assert_eq!(
wiring_order("newline", ".clk(clk),\n ."),
expected,
"an indented continuation line is the ordinary way this is written",
);
}
/// Already-connected ports sort after the ones still to wire and say so
/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a
/// sixty-port instantiation the ones still to wire are what the user is
/// looking for, but a port connected twice by mistake is findable.
#[test]
fn a_port_already_connected_is_offered_last_and_marked() {
assert_eq!(
wiring_order("taken", ".clk(clk), .data(d), ."),
pairs(&[("ready", false), ("clk", true), ("data", true)]),
"two written, one left, and the two after it",
);
// …and the entry being *re-typed* is not marked, because the dot the
// cursor follows is the one that is skipped.
assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)]));
}
#[test]
fn a_parameter_override_lists_the_parameters_not_the_ports() {
let top = WIRING.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let tree = Tree::new("params");
let (_tree, ws, uri, position) = opened(tree, &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["DEPTH", "WIDTH"]);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// **QA finding 1, 2026-09-02.** The opentitan shape: `prim_fifo_sync`
/// derives its width with a header `localparam`, which is **not
/// overridable** — and until `vlog_semantic` learned
/// [`SymbolKind::LocalParam`] it was bound as a `Param` and offered here.
/// The keyword is sticky, so a continuation entry after `localparam` is
/// one too, and a body `localparam` is never a header entry at all.
#[test]
fn a_localparam_is_never_offered_as_an_override() {
let top = "\
module fifo #(
parameter int Depth = 4,
localparam int DepthW = 3,
DepthX = 4,
parameter int Again = 1
) (
input logic clk
);
localparam int Body = 7;
endmodule
module top;
fifo #(.) u_fifo ();
endmodule
";
let tree = Tree::new("localparam");
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(
found,
vec!["Again", "Depth"],
"only the two `parameter` entries may be overridden",
);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// The same, for a module the **index** answers for — the half QA
/// actually hit, since `prim_fifo_sync` is instantiated from another file.
#[test]
fn a_localparam_in_another_file_is_not_offered_either() {
let tree = Tree::new("xlocalparam");
tree.write(
"fifo.sv",
"module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3\n) (\n input logic clk\n);\nendmodule\n",
);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(labels(&answer), vec!["Depth"]);
// …and the localparam is still *there* to be read hierarchically —
// the split changes what may be offered, never what exists.
assert!(
ws.index().members_of_chain("fifo").iter().any(|(name, _)| *name == "DepthW"),
"a localparam is still exported",
);
}
/// The completion list and the **ghost instantiation** must agree about
/// what is overridable: two answers to "which parameters may be
/// overridden" would eventually offer a name the skeleton omits.
/// `vlog_refactor::instantiation_plan` reads the AST keyword and always
/// did; this pins the two against each other.
#[test]
fn the_override_list_and_the_instantiation_plan_agree() {
let fifo = "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3,\n parameter int Again = 1\n) (\n input logic clk\n);\nendmodule\n";
let tree = Tree::new("planagree");
tree.write("fifo.sv", fifo);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let mut offered = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|s| (*s).to_string())
.collect::<Vec<String>>();
offered.sort();
let plan = vlog_refactor::instantiation_plan("fifo", fifo, None).expect("a plan");
let mut planned: Vec<String> = plan.params.iter().map(|p| p.name.clone()).collect();
planned.sort();
assert_eq!(offered, planned, "the popup and the skeleton name one set");
}
#[test]
fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() {
let top = WIRING.replace(" HOLE\n", " .\n");
let tree = Tree::new("portitem");
let (_tree, ws, uri, position) = opened(tree, &top, " .");
let answer = items(completions(&ws, &uri, position, true));
let data = find(&answer, "data").expect("the port");
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
// `.data(|)`: the parentheses come with it, the cursor inside
// (`completion-ux`, 2026-11-17). Nothing named `data` is visible in
// `wiring_top`, so the placeholder is empty…
assert_eq!(inserted(data), "data(${1})");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET));
// …while `clk` is, so it is pre-filled.
let clk = find(&answer, "clk").expect("the clock");
assert_eq!(inserted(clk), "clk(${1:clk})");
// The declaration line carries the direction and the width, which is
// the whole of what a connection list needs to know.
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
// Exclusive, like every other member answer.
for item in &answer {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
}
}
#[test]
fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() {
// A `(` already after the word: only the name is being re-edited.
let top = WIRING.replace(" HOLE\n", " .da(d)\n");
let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "data").expect("the port")), "data");
// A client without snippet support gets the name, as before.
let top = WIRING.replace(" HOLE\n", " .\n");
let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " .");
let answer = items(completions(&ws, &uri, position, false));
let data = find(&answer, "data").expect("the port");
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
#[test]
fn a_parameter_item_is_pre_filled_from_a_visible_parameter() {
let top = WIRING
.replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n")
.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})");
assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})");
}
/// A **non-ANSI** port list writes its directions in the module body, so
/// the header alone names the ports and the body types them. Both halves
/// bind a `Port`, so the list is the same.
#[test]
fn a_non_ansi_port_list_is_completed_too() {
let top = "module non_ansi (a, b);\n input wire a;\n output wire b;\nendmodule\nmodule top;\n non_ansi u (\n .\n );\nendmodule\n";
let tree = Tree::new("nonansi");
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["a", "b"]);
}
/// A module declared in another file: the ports come out of the index's
/// member table, which exports exactly ports and parameters.
#[test]
fn a_module_in_another_file_lists_its_ports_from_the_index() {
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("xconn", top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "data", "ready"], "SUB's ports, not its parameter");
let clk = find(&answer, "clk").expect("a port");
assert_eq!(clk.kind, Some(CompletionItemKind::FIELD));
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
}
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
/// *expression* the list is the module's **hierarchical** surface — its
/// nets, its variables and its instances as well as its ports and its
/// parameters — because that is what a hierarchical path may name and
/// exactly what the tail resolution will find, so every item offered is
/// an item hover and go-to-definition answer. Behind the `.` of a
/// **connection list** it is the connection surface and nothing more:
/// `.internal(w)` is not a legal connection, and an item the resolution
/// could not find is a wrong answer rather than a generous one.
#[test]
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
let hierarchical = {
let tree = Tree::new("hiersurface_expr");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(
hierarchical,
vec!["clk", "counter", "internal", "u_leaf"],
"the port and the three hierarchical-only members"
);
let connection = {
let tree = Tree::new("hiersurface_conn");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
}
#[test]
fn an_interface_instance_lists_its_ports_too() {
let tree = Tree::new("ifaceconn");
tree.write("bus.sv", "interface bus_if (input logic clk, input logic rst_n);\n logic [7:0] internal;\nendinterface\n");
let top = "module top;\n bus_if u_bus (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "rst_n"], "an interface's ports, not its signals");
}
/// A module nothing declares has no ports to name. The answer is an
/// **empty list** — the same shape a resolved site with no matching
/// member gets, and for the same reason: the question was this one, and
/// the honest answer to it is nothing. Never the whole-index dump.
#[test]
fn a_module_the_workspace_does_not_declare_answers_nothing() {
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("unknownconn", top, " .");
assert!(items(completions(&ws, &uri, position, true)).is_empty());
}
/// …and a `.` that is in no instantiation list at all answers `None`,
/// which is the other half of the same split: not "nothing to offer here"
/// but "this was not a question I can read".
#[test]
fn a_dot_outside_any_instantiation_list_answers_none() {
let top = "module top;\n initial begin\n (.\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("looseconn", top, " (.");
assert!(completions(&ws, &uri, position, true).is_none());
}
/// A `.` inside a *connected expression* is not a connection: `.clk(`
/// opens a paren of its own, and what may be written there is an
/// expression.
#[test]
fn a_dot_inside_a_connected_expression_is_not_a_connection() {
let top = WIRING.replace(" HOLE\n", " .clk(no_such_head.\n");
let tree = Tree::new("nested");
let (_tree, ws, uri, position) = opened(tree, &top, "no_such_head.");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_typed_prefix_in_a_connection_list_follows_the_same_filter_rule() {
// One and two characters: a prefix.
assert_eq!(wiring_labels("cprefix", ".d"), vec!["data"]);
// Three: a subsequence, so `rdy` reaches `ready`.
assert_eq!(wiring_labels("cfuzzy", ".rdy"), vec!["ready"]);
let incomplete = |name: &str, hole: &str| {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
}
};
assert!(!incomplete("cinc0", "."), "the whole port list is the whole answer");
assert!(incomplete("cinc1", ".d"), "a prefix slice widens at the third character");
assert!(!incomplete("cinc3", ".rdy"));
}
/// Nothing about an ordinary identifier request changed.
#[test]
fn a_plain_identifier_still_gets_every_tier() {
let top = "module top;\n logic sig_here;\n assign x = sig\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, "= sig");
let items = items(completions(&ws, &uri, position, true));
let found = labels(&items);
assert!(found.contains(&"sig_here"), "the scope tier: {found:?}");
assert!(items.iter().any(|i| tier(i) == TIER_WORD || tier(i) == TIER_KEYWORD));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,820 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
// ------------------------------------------------------------------
// the member answer (2026-09-02) — after a `.` or a `::`
// ------------------------------------------------------------------
/// The buffer most of these ask against: a class chain, a struct, an
/// interface with a modport and a clocking block, and a handle for each.
const MEMBERS: &str = "\
interface bus_if;
logic clk;
logic [7:0] data;
modport mp (input clk);
clocking cb @(posedge clk);
input data;
endclocking
endinterface
typedef struct packed { logic [7:0] addr; logic vld; } hdr_t;
class base_c;
bit from_base;
endclass
class item_c extends base_c;
bit user_id;
bit feature1;
hdr_t hdr;
function void run();
endfunction
endclass
module top;
virtual bus_if vif;
item_c item;
item_c queue[4];
hdr_t [3:0] hs;
hdr_t h;
initial begin
item.
end
endmodule
";
/// The names a member request against [`MEMBERS`] offers, **sorted** —
/// which is the order the client shows them in, because `sortText` is
/// `<tier digit><name>`. The array order is the cap's order and is pinned
/// separately by [`the_list_is_ordered_nearest_declaration_first`].
fn member_labels(name: &str, spine: &str) -> Vec<String> {
let mut found: Vec<String> =
items(member_response(name, spine)).iter().map(|item| item.label.clone()).collect();
found.sort();
found
}
/// The whole response, for the tests that read more than the labels.
fn member_response(name: &str, spine: &str) -> Option<CompletionResponse> {
let top = MEMBERS.replace(" item.\n", &format!(" {spine}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, spine);
completions(&ws, &uri, position, true)
}
#[test]
fn a_class_handle_lists_its_members_and_its_bases() {
assert_eq!(
member_labels("cls", "item."),
vec!["feature1", "from_base", "hdr", "run", "user_id"],
);
}
#[test]
fn the_member_answer_is_exclusive() {
let items = items(member_response("exclusive", "item."));
// No keyword, no template, no project word — every item is a member,
// and every one of them is filed under the member tier.
for item in &items {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::KEYWORD), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::TEXT), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::SNIPPET), "{item:#?}");
}
let found = labels(&items);
assert!(!found.contains(&"always_ff"), "no keywords");
assert!(!found.contains(&"top"), "no index names");
assert!(!found.contains(&"vif"), "not even what is visible at the cursor");
}
/// A member wins over a same-named local because the answer is exclusive:
/// the local is not a worse candidate here, it is not a candidate.
#[test]
fn a_local_of_the_same_name_is_not_offered_beside_the_member() {
let top = MEMBERS.replace(" item.\n", " bit user_id;\n item.\n");
let tree = Tree::new("shadow");
let (_tree, ws, uri, position) = opened(tree, &top, "item.");
let items = items(completions(&ws, &uri, position, true));
let user_id = find(&items, "user_id").expect("the member");
assert_eq!(user_id.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(items.iter().filter(|item| item.label == "user_id").count(), 1);
}
#[test]
fn a_nested_struct_field_lists_the_inner_fields() {
assert_eq!(member_labels("struct", "h."), vec!["addr", "vld"]);
assert_eq!(member_labels("struct2", "item.hdr."), vec!["addr", "vld"]);
}
#[test]
fn an_interface_handle_lists_its_signals_its_modports_and_its_clocking() {
let found = member_labels("iface", "vif.");
for wanted in ["clk", "data", "mp", "cb"] {
assert!(found.contains(&wanted.to_string()), "{wanted} missing from {found:?}");
}
}
/// A clocking block's `type_name` is the interface enclosing it
/// (interface-semantics, 2026-09-01), which is what makes `vif.cb.data`
/// resolve to the interface's own `data` declaration — correct
/// SystemVerilog, since a clocking block names a *view* of those signals
/// and declares nothing of its own. So the list after `vif.cb.` is the
/// interface's, exactly as the resolution is: one walk, one answer, wider
/// than the block's own item list and never wrong about a name.
#[test]
fn a_clocking_block_lists_the_enclosing_interfaces_signals() {
assert_eq!(member_labels("clocking", "vif.cb."), member_labels("clocking2", "vif."));
assert!(member_labels("clocking3", "vif.cb.").contains(&"data".to_string()));
}
/// A **packed** array head is indexed away and names its element type's
/// members: `hdr_t [3:0] hs; hs[1].` is a `hdr_t`.
#[test]
fn a_packed_array_head_is_indexed_away() {
assert_eq!(member_labels("indexed", "hs[1]."), vec!["addr", "vld"]);
assert_eq!(member_labels("indexed2", "hs[i][j]."), vec!["addr", "vld"], "and repeatedly");
}
/// An **unpacked** declarator answers nothing, and that is
/// `vlog_semantic`'s own ruling rather than this file's: `item_c q[4]`
/// names a container, not a value of `item_c`, so no `type_name` is
/// recorded and `q.size()` is an array method rather than a member
/// (`bind.rs::declare_typed`). Completion may not mint a type the
/// resolver refuses to mint — that would be the second resolver this
/// round exists to avoid. Filed as a follow-on in the feature README.
#[test]
fn an_unpacked_array_head_answers_nothing_because_it_has_no_declared_type() {
assert!(member_response("unpacked", "queue[0].").is_none());
}
/// The order of the `items` array is the order the cap keeps, and it is
/// **nearest declaration first**: a class's own members before its base's,
/// in declaration order within each. `sortText` still says the client
/// should draw them alphabetically.
#[test]
fn the_list_is_ordered_nearest_declaration_first() {
let items = items(member_response("order", "item."));
assert_eq!(labels(&items), vec!["user_id", "feature1", "hdr", "run", "from_base"]);
for item in &items {
assert_eq!(item.sort_text.as_deref(), Some(format!("0{}", item.label).as_str()));
}
}
#[test]
fn this_and_super_answer_from_inside_a_method() {
let top = MEMBERS.replace(" function void run();\n", " function void run();\n this.\n");
let tree = Tree::new("this");
let (_tree, ws, uri, position) = opened(tree, &top, " this.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["feature1", "from_base", "hdr", "run", "user_id"]);
let top = MEMBERS.replace(" function void run();\n", " function void run();\n super.\n");
let tree = Tree::new("super");
let (_tree, ws, uri, position) = opened(tree, &top, " super.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["from_base"], "super is the base and not the class itself");
}
#[test]
fn the_kind_and_the_detail_come_off_the_declaration() {
let items = items(member_response("detail", "item."));
// In this buffer the declaration's own line is free, so that is the
// card — the same one tier 1 has always shown.
let hdr = find(&items, "hdr").expect("the struct-typed property");
assert_eq!(hdr.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(hdr.detail.as_deref(), Some("hdr_t hdr;"), "the declaration itself");
let run = find(&items, "run").expect("the method");
assert_eq!(run.kind, Some(CompletionItemKind::FUNCTION));
assert_eq!(run.detail.as_deref(), Some("function void run();"));
// A method inserts its bare name: the parentheses and the arguments
// are the user's to write, and a completion that invented them would
// be guessing at the call.
assert_eq!(inserted(run), "run");
assert_eq!(run.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
/// The edit is an **empty** range at the cursor, so accepting an item
/// writes the member name after the dot and touches nothing before it.
#[test]
fn the_edit_is_empty_at_the_cursor_after_a_separator() {
let items = items(member_response("range", "item."));
assert!(!items.is_empty());
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, edit.range.end, "{item:#?}");
assert_eq!(edit.new_text, item.label);
}
}
/// And with characters typed after the dot it replaces exactly those.
#[test]
fn the_edit_replaces_exactly_what_was_typed_after_the_separator() {
let items = items(member_response("range2", "item.us"));
assert_eq!(labels(&items), vec!["user_id"]);
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start.character + 2, edit.range.end.character);
}
#[test]
fn a_typed_prefix_filters_below_the_fuzzy_floor_and_a_subsequence_from_it_up() {
// One and two characters: a prefix, exactly as every other tier does
// below the floor. `fe` reaches `feature1` and not `from_base`.
assert_eq!(member_labels("prefix1", "item.f"), vec!["feature1", "from_base"]);
assert_eq!(member_labels("prefix2", "item.fe"), vec!["feature1"]);
// Three: a subsequence, so `fbs` reaches `from_base` — which no
// prefix match ever would.
assert_eq!(member_labels("fuzzy", "item.fbs"), vec!["from_base"]);
assert_eq!(member_labels("fuzzy2", "item.usr"), vec!["user_id"]);
}
/// **The `isIncomplete` rule.** The request that matters — the one the
/// trigger character fires, with nothing typed yet — is complete, so VS
/// Code filters the whole member list client-side. A 1- or 2-character
/// answer is a prefix slice that the third keystroke would *widen*, so it
/// must say it is incomplete or the widening never reaches the client.
#[test]
fn only_a_filtered_answer_below_the_fuzzy_floor_is_incomplete() {
let incomplete = |name: &str, spine: &str| match member_response(name, spine) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
};
assert!(!incomplete("inc0", "item."), "the whole list is the whole answer");
assert!(incomplete("inc1", "item.f"), "a prefix slice widens at the third character");
assert!(incomplete("inc2", "item.fe"));
assert!(!incomplete("inc3", "item.fea"), "a subsequence hit set only shrinks");
// Even a query nothing matches answers with a list, so the client is
// told to come back rather than left filtering an answer it has not
// got.
assert!(incomplete("inc4", "item.zz"));
let empty = items(member_response("inc5", "item.zz"));
assert!(empty.is_empty());
}
/// An **empty** answer is incomplete whatever was typed — including at
/// zero characters, where a non-empty list would be complete. QA finding
/// 2 (2026-09-02) is the reason: a cold index whose scope ladder has not
/// reached the declaring file's directory yet answers empty for one
/// request and correctly for the next, and a *complete* emptiness would
/// be cached by the client until the user retyped the dot.
#[test]
fn an_empty_answer_always_asks_the_client_to_come_back() {
let top = "class hollow_c;\nendclass\nmodule top;\n hollow_c h;\n initial begin\n h.\n end\nendmodule\n";
let tree = Tree::new("hollow");
let (_tree, ws, uri, position) = opened(tree, top, " h.");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty(), "a class with no members");
assert!(list.is_incomplete, "and the client is asked to come back");
}
other => panic!("a list, not {other:#?}"),
}
// The same for a connection list whose module nothing declares.
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("hollowconn", top, " .");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty());
assert!(list.is_incomplete);
}
other => panic!("a list, not {other:#?}"),
}
}
#[test]
fn an_unresolvable_head_answers_nothing_at_all() {
for (name, spine) in [
("nohead", "no_such_handle."),
("call", "f()."),
("nothing", "."),
("space", "item ."),
("untyped", "vif.clk."),
] {
assert!(member_response(name, spine).is_none(), "{spine} must answer nothing, not a guess",);
}
}
/// A lone `:` is a case item, a label or a ternary — not a separator. The
/// request there is the ordinary six-tier one it always was.
#[test]
fn a_lone_colon_falls_through_to_the_ordinary_tiers() {
let top =
"module top;\n logic sig;\n initial\n case (1)\n 1: si\n endcase\nendmodule\n";
let tree = Tree::new("colon");
let (_tree, ws, uri, position) = opened(tree, top, "1: si");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"sig"), "the scope tier still answers: {found:?}");
}
#[test]
fn a_package_lists_its_members_after_a_scope_separator() {
let tree = Tree::new("pkg");
tree.write(
"p.sv",
"package other_pkg;\n localparam int WIDTH = 8;\n typedef struct packed { logic a; } cfg_t;\nendpackage\n",
);
let top = "module top;\n initial $display(other_pkg::);\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "other_pkg::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"WIDTH"), "{found:?}");
assert!(found.contains(&"cfg_t"), "{found:?}");
assert!(!found.contains(&"always_ff"), "and nothing else: {found:?}");
}
#[test]
fn a_package_this_file_declares_lists_its_members_too() {
let top = "package p;\n localparam int W = 8;\n typedef int t_t;\nendpackage\nmodule top;\n initial $display(p::);\nendmodule\n";
let tree = Tree::new("pkg_local");
let (_tree, ws, uri, position) = opened(tree, top, "p::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["W", "t_t"]);
}
/// The cross-file half: an in-file class extending a class in another
/// file lists both halves, its own scope first.
#[test]
fn a_base_in_another_file_contributes_its_members() {
let tree = Tree::new("crossfile");
tree.write("base.sv", "class remote_c;\n bit remote_field;\n bit shared;\nendclass\n");
let top = "class local_c extends remote_c;\n bit local_field;\n bit shared;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field", "shared", "remote_field"]);
// The subclass's `shared` is the one offered — the same first-hit-wins
// rule a lookup applies.
let items = items(completions(&ws, &uri, position, true));
let shared = find(&items, "shared").expect("the shadowed name");
assert_eq!(items.iter().filter(|i| i.label == "shared").count(), 1);
assert_eq!(shared.kind, Some(CompletionItemKind::VARIABLE));
}
/// A class whose base the workspace does not declare at all: the chain
/// stops there, and everything known still lists.
#[test]
fn an_absent_base_stops_the_chain_without_losing_what_is_known() {
let tree = Tree::new("nobase");
let top = "class local_c extends nowhere_c;\n bit local_field;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field"]);
}
/// The other half of the detail rule: a member the *index* holds carries
/// no text, so its card is the kind label plus the declared type — the
/// most a table can say, and no file is read to say it.
#[test]
fn a_cross_file_member_shows_the_kind_label_and_its_declared_type() {
let tree = Tree::new("xdetail");
tree.write(
"remote.sv",
"class remote_c;\n hdr_t typed_field;\n bit plain_field;\nendclass\n",
);
let top = "module top;\n remote_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let items = items(completions(&ws, &uri, position, true));
let typed = find(&items, "typed_field").expect("the typed property");
assert_eq!(typed.detail.as_deref(), Some("variable — hdr_t"));
let plain = find(&items, "plain_field").expect("the untyped property");
assert_eq!(plain.detail.as_deref(), Some("variable"), "no type name to add");
}
/// A type only another file declares: the whole list comes from the
/// index, inherited members included.
#[test]
fn a_handle_whose_type_is_another_files_lists_from_the_index() {
let tree = Tree::new("remote");
tree.write("base.sv", "class remote_base;\n bit inherited_field;\nendclass\n");
tree.write("item.sv", "class remote_item extends remote_base;\n bit own_field;\nendclass\n");
let top = "module top;\n remote_item h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["inherited_field", "own_field"]);
}
/// `reg2hw.ctrl.` — the generated-register shape, whose inner fields the
/// index holds under the synthesized `reg2hw_t.ctrl` key.
#[test]
fn a_nested_struct_in_another_file_lists_through_the_synthesized_key() {
let tree = Tree::new("reg2hw");
tree.write(
"regs.sv",
"package regs_pkg;\n typedef struct packed {\n struct packed { logic q; logic qe; } ctrl;\n struct packed { logic q; } status;\n } reg2hw_t;\nendpackage\n",
);
let top =
"module top;\n reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "reg2hw.ctrl.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["q", "qe"]);
}
// ------------------------------------------------------------------
// the connection list (2026-09-02 rework) — `.` inside `sub u (…)`
// ------------------------------------------------------------------
/// A module in the buffer, so the in-file half is exercised without the
/// index. Three ports and two parameters, in a shape a user really types.
const WIRING: &str = "\
module wiring_sub #(
parameter int WIDTH = 8,
parameter int DEPTH = 4
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
module wiring_top;
logic clk;
wiring_sub u_sub (
HOLE
);
endmodule
";
/// A connection-list request against [`WIRING`], `HOLE` replaced by what
/// is typed. Sorted, like every other member list here.
fn wiring_labels(name: &str, hole: &str) -> Vec<String> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
let mut found: Vec<String> = items(completions(&ws, &uri, position, true))
.iter()
.map(|item| item.label.clone())
.collect();
found.sort();
found
}
/// **The regression this rework exists for.** `.cl` inside `sub u (` used
/// to get the 512-item whole-index dump; it now gets the port.
#[test]
fn a_dot_in_a_connection_list_lists_the_modules_ports() {
assert_eq!(wiring_labels("conn", "."), vec!["clk", "data", "ready"]);
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
}
/// The answer against [`WIRING`] in the order the client shows it — by
/// `sortText` — as `(label, marked connected)` pairs.
fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole);
let mut found = items(completions(&ws, &uri, position, true));
found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text));
found
.into_iter()
.map(|item| {
let marked = item
.label_details
.as_ref()
.and_then(|d| d.description.as_deref())
.is_some_and(|d| d == "connected");
(item.label, marked)
})
.collect()
}
fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> {
list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect()
}
#[test]
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
assert_eq!(
wiring_order("newline", ".clk(clk),\n ."),
expected,
"an indented continuation line is the ordinary way this is written",
);
}
/// Already-connected ports sort after the ones still to wire and say so
/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a
/// sixty-port instantiation the ones still to wire are what the user is
/// looking for, but a port connected twice by mistake is findable.
#[test]
fn a_port_already_connected_is_offered_last_and_marked() {
assert_eq!(
wiring_order("taken", ".clk(clk), .data(d), ."),
pairs(&[("ready", false), ("clk", true), ("data", true)]),
"two written, one left, and the two after it",
);
// …and the entry being *re-typed* is not marked, because the dot the
// cursor follows is the one that is skipped.
assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)]));
}
#[test]
fn a_parameter_override_lists_the_parameters_not_the_ports() {
let top = WIRING.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let tree = Tree::new("params");
let (_tree, ws, uri, position) = opened(tree, &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["DEPTH", "WIDTH"]);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// **QA finding 1, 2026-09-02.** The opentitan shape: `prim_fifo_sync`
/// derives its width with a header `localparam`, which is **not
/// overridable** — and until `vlog_semantic` learned
/// [`SymbolKind::LocalParam`] it was bound as a `Param` and offered here.
/// The keyword is sticky, so a continuation entry after `localparam` is
/// one too, and a body `localparam` is never a header entry at all.
#[test]
fn a_localparam_is_never_offered_as_an_override() {
let top = "\
module fifo #(
parameter int Depth = 4,
localparam int DepthW = 3,
DepthX = 4,
parameter int Again = 1
) (
input logic clk
);
localparam int Body = 7;
endmodule
module top;
fifo #(.) u_fifo ();
endmodule
";
let tree = Tree::new("localparam");
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["Again", "Depth"], "only the two `parameter` entries may be overridden",);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// The same, for a module the **index** answers for — the half QA
/// actually hit, since `prim_fifo_sync` is instantiated from another file.
#[test]
fn a_localparam_in_another_file_is_not_offered_either() {
let tree = Tree::new("xlocalparam");
tree.write(
"fifo.sv",
"module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3\n) (\n input logic clk\n);\nendmodule\n",
);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(labels(&answer), vec!["Depth"]);
// …and the localparam is still *there* to be read hierarchically —
// the split changes what may be offered, never what exists.
assert!(
ws.index().members_of_chain("fifo").iter().any(|(name, _)| *name == "DepthW"),
"a localparam is still exported",
);
}
/// The completion list and the **ghost instantiation** must agree about
/// what is overridable: two answers to "which parameters may be
/// overridden" would eventually offer a name the skeleton omits.
/// `vlog_refactor::instantiation_plan` reads the AST keyword and always
/// did; this pins the two against each other.
#[test]
fn the_override_list_and_the_instantiation_plan_agree() {
let fifo = "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3,\n parameter int Again = 1\n) (\n input logic clk\n);\nendmodule\n";
let tree = Tree::new("planagree");
tree.write("fifo.sv", fifo);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let mut offered = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|s| (*s).to_string())
.collect::<Vec<String>>();
offered.sort();
let plan = vlog_refactor::instantiation_plan("fifo", fifo, None).expect("a plan");
let mut planned: Vec<String> = plan.params.iter().map(|p| p.name.clone()).collect();
planned.sort();
assert_eq!(offered, planned, "the popup and the skeleton name one set");
}
#[test]
fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() {
let top = WIRING.replace(" HOLE\n", " .\n");
let tree = Tree::new("portitem");
let (_tree, ws, uri, position) = opened(tree, &top, " .");
let answer = items(completions(&ws, &uri, position, true));
let data = find(&answer, "data").expect("the port");
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
// `.data(|)`: the parentheses come with it, the cursor inside
// (`completion-ux`, 2026-11-17). Nothing named `data` is visible in
// `wiring_top`, so the placeholder is empty…
assert_eq!(inserted(data), "data(${1})");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET));
// …while `clk` is, so it is pre-filled.
let clk = find(&answer, "clk").expect("the clock");
assert_eq!(inserted(clk), "clk(${1:clk})");
// The declaration line carries the direction and the width, which is
// the whole of what a connection list needs to know.
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
// Exclusive, like every other member answer.
for item in &answer {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
}
}
#[test]
fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() {
// A `(` already after the word: only the name is being re-edited.
let top = WIRING.replace(" HOLE\n", " .da(d)\n");
let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "data").expect("the port")), "data");
// A client without snippet support gets the name, as before.
let top = WIRING.replace(" HOLE\n", " .\n");
let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " .");
let answer = items(completions(&ws, &uri, position, false));
let data = find(&answer, "data").expect("the port");
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
#[test]
fn a_parameter_item_is_pre_filled_from_a_visible_parameter() {
let top = WIRING
.replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n")
.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})");
assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})");
}
/// A **non-ANSI** port list writes its directions in the module body, so
/// the header alone names the ports and the body types them. Both halves
/// bind a `Port`, so the list is the same.
#[test]
fn a_non_ansi_port_list_is_completed_too() {
let top = "module non_ansi (a, b);\n input wire a;\n output wire b;\nendmodule\nmodule top;\n non_ansi u (\n .\n );\nendmodule\n";
let tree = Tree::new("nonansi");
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["a", "b"]);
}
/// A module declared in another file: the ports come out of the index's
/// member table, which exports exactly ports and parameters.
#[test]
fn a_module_in_another_file_lists_its_ports_from_the_index() {
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("xconn", top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "data", "ready"], "SUB's ports, not its parameter");
let clk = find(&answer, "clk").expect("a port");
assert_eq!(clk.kind, Some(CompletionItemKind::FIELD));
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
}
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
/// *expression* the list is the module's **hierarchical** surface — its
/// nets, its variables and its instances as well as its ports and its
/// parameters — because that is what a hierarchical path may name and
/// exactly what the tail resolution will find, so every item offered is
/// an item hover and go-to-definition answer. Behind the `.` of a
/// **connection list** it is the connection surface and nothing more:
/// `.internal(w)` is not a legal connection, and an item the resolution
/// could not find is a wrong answer rather than a generous one.
#[test]
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
let hierarchical = {
let tree = Tree::new("hiersurface_expr");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(
hierarchical,
vec!["clk", "counter", "internal", "u_leaf"],
"the port and the three hierarchical-only members"
);
let connection = {
let tree = Tree::new("hiersurface_conn");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
}
#[test]
fn an_interface_instance_lists_its_ports_too() {
let tree = Tree::new("ifaceconn");
tree.write("bus.sv", "interface bus_if (input logic clk, input logic rst_n);\n logic [7:0] internal;\nendinterface\n");
let top = "module top;\n bus_if u_bus (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "rst_n"], "an interface's ports, not its signals");
}
/// A module nothing declares has no ports to name. The answer is an
/// **empty list** — the same shape a resolved site with no matching
/// member gets, and for the same reason: the question was this one, and
/// the honest answer to it is nothing. Never the whole-index dump.
#[test]
fn a_module_the_workspace_does_not_declare_answers_nothing() {
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("unknownconn", top, " .");
assert!(items(completions(&ws, &uri, position, true)).is_empty());
}
/// …and a `.` that is in no instantiation list at all answers `None`,
/// which is the other half of the same split: not "nothing to offer here"
/// but "this was not a question I can read".
#[test]
fn a_dot_outside_any_instantiation_list_answers_none() {
let top = "module top;\n initial begin\n (.\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("looseconn", top, " (.");
assert!(completions(&ws, &uri, position, true).is_none());
}
/// A `.` inside a *connected expression* is not a connection: `.clk(`
/// opens a paren of its own, and what may be written there is an
/// expression.
#[test]
fn a_dot_inside_a_connected_expression_is_not_a_connection() {
let top = WIRING.replace(" HOLE\n", " .clk(no_such_head.\n");
let tree = Tree::new("nested");
let (_tree, ws, uri, position) = opened(tree, &top, "no_such_head.");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_typed_prefix_in_a_connection_list_follows_the_same_filter_rule() {
// One and two characters: a prefix.
assert_eq!(wiring_labels("cprefix", ".d"), vec!["data"]);
// Three: a subsequence, so `rdy` reaches `ready`.
assert_eq!(wiring_labels("cfuzzy", ".rdy"), vec!["ready"]);
let incomplete = |name: &str, hole: &str| {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
}
};
assert!(!incomplete("cinc0", "."), "the whole port list is the whole answer");
assert!(incomplete("cinc1", ".d"), "a prefix slice widens at the third character");
assert!(!incomplete("cinc3", ".rdy"));
}
/// Nothing about an ordinary identifier request changed.
#[test]
fn a_plain_identifier_still_gets_every_tier() {
let top = "module top;\n logic sig_here;\n assign x = sig\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, "= sig");
let items = items(completions(&ws, &uri, position, true));
let found = labels(&items);
assert!(found.contains(&"sig_here"), "the scope tier: {found:?}");
assert!(items.iter().any(|i| tier(i) == TIER_WORD || tier(i) == TIER_KEYWORD));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `textDocument/completion` — module hinting, templates, keywords, and every
//! name the project uses.
//!
@@ -917,3 +919,5 @@ mod tests {
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4 -586
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Tier 0 — module names at module-item position — and the instantiation
//! planning that `inline.rs`'s ghost and `instantiate.rs`'s command share.
//!
@@ -334,590 +336,6 @@ fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use std::fs;
use std::path::PathBuf;
mod tests;
/// Completion's own view of the three new kinds, and the detail card that
/// used to hard-code "module" over an interface — the C2 wrong answer
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn an_interface_completes_as_an_interface() {
assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT);
let index = vlog_semantic::WorkspaceIndex::build([
(PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"),
(PathBuf::from("/rtl/sub.sv"), SUB),
]);
assert!(module_detail(&index, "bus_if", None).starts_with("interface"));
assert!(module_detail(&index, "sub", None).starts_with("module"));
// The ghost-instantiation lookups reach an interface too.
assert_eq!(
nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()),
Some("/rtl/bus_if.sv".to_string())
);
}
// ------------------------------------------------------------------
// tier 0's header slice (2026-08-28) — it must change no answer
// ------------------------------------------------------------------
/// Every header shape the slice has to survive, as (file text, module).
///
/// The list is the argument that the slice changes nothing: each entry is
/// planned both ways below and the two plans are compared field by field.
const SHAPES: &[(&str, &str)] = &[
// The ordinary ANSI header, params and all.
(SUB, "sub"),
// No ports at all.
("module bare;\nendmodule\n", "bare"),
// An empty port list.
("module empty ();\n logic x;\nendmodule\n", "empty"),
// A package import written into the header: its `;` is not the
// header's, and a slice that stopped there would report no ports.
(
"package p;\n localparam int W = 4;\nendpackage\n\
module imported import p::*; #(\n parameter int W = 8\n) (\n \
input logic clk,\n output logic [W-1:0] q\n);\n \
assign q = '0;\nendmodule\n",
"imported",
),
// Two imports, then a parameter list.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
"twice",
),
// A **non-ANSI** port list: the directions live in the body, which is
// exactly what the slice drops.
(
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
always @* b = |a;\nendmodule\n",
"old",
),
// Non-ANSI with nothing declaring the ports at all.
("module silent (a, b);\nendmodule\n", "silent"),
// A comment and an attribute inside the header.
(
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
input logic clk\n);\nendmodule\n",
"noisy",
),
// A lifetime qualifier.
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
// A second module in the same file, after the one being planned.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"first",
),
// …and before it, so the slice's prefix carries a whole module.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"second",
),
// A compiler directive between the name and the port list, which the
// whitelist refuses outright.
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
// A directive *inside* the port list, which carries a warning the two
// plans must both raise.
(
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
`endif\n);\nendmodule\n",
"ifdefd",
),
// An escaped identifier for the module and for a port.
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
// A header longer than the first rung of the window ladder.
(WIDE, "wide"),
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
// instance, `(* ... *)`, right after the module name and before the
// parameter list — the one shape the "noisy" case above is commented
// as covering but does not (it has two comments, no attribute).
// **Finding, not a regression this round introduced**: a module with
// an attribute anywhere near its header is not indexed as a `Module`
// unit at all (see
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
// so this pins the safe side effect — `module_header` declines before
// its whitelist walk ever runs — rather than the whitelist's own
// handling of attributes, which this shape cannot reach.
(
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
input logic clk\n);\nendmodule\n",
"attributed",
),
// An attribute instance *inside* the port list, attached to one port.
// Same finding as `attributed`: not indexed, so not reached either.
(
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
);\nendmodule\n",
"port_attributed",
),
// A single import declaration naming several packages, comma
// separated (`import a::*, b::*;`) — one statement, not two, and the
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module chained import p::*, q::*; (input logic a);\nendmodule\n",
"chained",
),
// A parameter default whose string literal carries the exact bytes
// the whitelist watches for — `;` and `)` — which must stay inside
// the `String` token and never be mistaken for header punctuation.
(
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
input logic clk\n);\nendmodule\n",
"stringy",
),
// CRLF line endings through the whole header.
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
];
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
input logic port_number_one_with_a_long_name,\n \
input logic port_number_two_with_a_long_name,\n \
input logic port_number_three_with_a_long_name,\n \
input logic port_number_four_with_a_long_name,\n \
input logic port_number_five_with_a_long_name,\n \
output logic port_number_six_with_a_long_name\n);\n \
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
/// The whole argument for the slice: for every shape above, the plan built
/// from the header alone is the plan built from the whole file. Where it
/// would not be — a non-ANSI list, a header the whitelist refuses — the
/// guard in [`plan_for`] sends the question back to the whole file, so the
/// comparison holds there too.
#[test]
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
for (text, module) in SHAPES {
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
let ours = plan_for(&index, module, text, site);
assert_eq!(ours, whole, "{module}");
}
}
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
/// trivially for a shape the whitelist declines — both sides parse the
/// whole file, so a wrong slice could hide behind that. These shapes must
/// actually slice, so the comparison exercises the whitelist walk it is
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
/// `;`/`)` sitting inside a string literal, and CRLF endings.
#[test]
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
module_header(&index, module, text).is_some(),
"{module}: expected the header to actually slice, not fall back whole-file"
);
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
/// differently off its header, and really is sent back to the whole file.
#[test]
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
let path = PathBuf::from("/rtl/old.sv");
let index = WorkspaceIndex::build(vec![(path, text)]);
let header = module_header(&index, "old", text).expect("the header slices");
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
assert!(
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
"premise: the header alone knows nothing about these ports"
);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let guarded = plan_for(&index, "old", text, site).expect("a plan");
assert_eq!(guarded.ports[0].dir, "input");
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
}
/// The whole answer, pinned at the prefixes the hot path is worst at — the
/// empty one and a one-character one, where every tier is at its widest.
/// Tier 0 answers with names, so the pin spells out every module item's
/// label *and* the text it inserts, which is now the label again.
#[test]
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
let tree = Tree::new("pinned");
tree.write("sub.sv", SUB);
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
let (_tree, mut ws, uri, _) =
opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
// Nothing typed, then one character — the two widest requests there
// are. `top` is in the answer because the buffer declares it and the
// index holds it like any other module.
let mut answer = |typed: &str| {
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
+ typed.len() as u32;
let doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
items(completions(&ws, &uri, position, true))
};
for (typed, expected) in
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
{
let items = answer(typed);
let found: Vec<&str> =
skeletons(&items).iter().map(|item| item.label.as_str()).collect();
assert_eq!(found, expected, "module items after typing {typed:?}");
}
// …and the exact text each of them inserts, which is the name and
// nothing else however many ports the module has. The instantiation is
// `inline.rs`'s business now.
let items = answer("");
for name in ["sub", "alpha", "submarine"] {
let item = find(&items, name).expect("the module item");
assert_eq!(inserted(item), name, "the popup inserts the name alone");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(item.insert_text_mode, None, "there is no indentation to keep");
}
}
/// A file edited on disk since the index last read it has moved every span
/// the index holds, so the slice must not take one on trust.
#[test]
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
let text =
"module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
// The same index against a file whose text has shifted underneath it.
let moved = format!("// a line nobody told the index about\n{text}");
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
}
// ------------------------------------------------------------------
// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30)
// ------------------------------------------------------------------
#[test]
fn a_module_name_at_item_position_completes_to_the_name_alone() {
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("nameonly", top, " su");
let items = items(completions(&ws, &uri, position, true));
let modules = skeletons(&items);
assert_eq!(modules.len(), 1, "{items:#?}");
let item = modules[0];
assert_eq!(item.label, "sub");
assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon");
assert_eq!(item.detail.as_deref(), Some("module — sub.sv"));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest");
assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show");
}
#[test]
fn the_snippet_flag_no_longer_changes_the_module_item() {
// The M4 fallback — a plain-text spelling of the skeleton for a client
// that never advertised `snippetSupport` — has nothing left to fall
// back from: the item is a word either way.
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, " su");
for snippets in [true, false] {
let items = items(completions(&ws, &uri, position, snippets));
let item = skeletons(&items)[0];
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "snippets: {snippets}");
}
}
/// The whole point of level 1: the popup no longer reads the files it
/// offers names from. Proved by deleting the declaring file after the
/// index has been built — the old tier answered nothing at all here,
/// because every item needed that file's text.
#[test]
fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() {
let tree = Tree::new("noread");
let sub = tree.write("sub.sv", SUB);
let (_tree, ws, uri, position) =
opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su");
fs::remove_file(&sub).expect("remove the declaring file");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(
skeletons(&items).iter().map(|item| item.label.as_str()).collect::<Vec<_>>(),
["sub"],
"the name comes from the index's table, not from the file: {items:#?}"
);
}
#[test]
fn the_edit_replaces_exactly_the_typed_word() {
let top = "module top;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("replace", top, " su");
let items = items(completions(&ws, &uri, position, true));
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}");
assert_eq!(edit.range.end, Position { line: 1, character: 4 });
}
}
#[test]
fn no_skeleton_is_offered_in_the_middle_of_an_expression() {
// The other tiers answer here — a name is a name wherever it is
// written — but a fifteen-line instantiation is not.
for (name, top, needle) in [
("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"),
("decl", "module top;\n logic su\nendmodule\n", "logic su"),
("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"),
("header", "module top (su\n);\nendmodule\n", "top (su"),
] {
let (_tree, ws, uri, position) = asking(name, top, needle);
let items = items(completions(&ws, &uri, position, true));
assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}");
}
}
#[test]
fn no_skeleton_is_offered_inside_a_procedural_block() {
let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("always", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "module top;\n initial begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("initial", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn no_skeleton_is_offered_inside_a_function_or_a_class() {
let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n";
let (_tree, ws, uri, position) = asking("function", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "package p;\n class c;\n su\n endclass\nendpackage\n";
let (_tree, ws, uri, position) = asking("class", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_generate_block_is_still_item_position() {
let top = "\
module top;
for (genvar i = 0; i < 4; i++) begin : g
su
end
endmodule
";
let (_tree, ws, uri, position) = asking("genfor", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}");
let top = "module top;\n generate\n su\n endgenerate\nendmodule\n";
let (_tree, ws, uri, position) = asking("generate", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1);
}
#[test]
fn no_skeleton_is_offered_outside_a_design_unit() {
let top = "su\nmodule top;\nendmodule\n";
let (_tree, ws, uri, position) = asking("toplevel", top, "su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_prefix_that_matches_no_module_offers_no_skeleton() {
let top = "module top;\n zzz\nendmodule\n";
let (_tree, ws, uri, position) = asking("nomatch", top, " zzz");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() {
// Until 2026-08-30 tier 0 skipped it: there is no single definition to
// build a *skeleton* from, and the skeleton was the item. A name needs
// no definition, so round 1 offered the name and left the detail
// blank. Round 2 (owner ruling, same day) makes the ghost choose a
// copy rather than decline, so the popup names the copy the ghost will
// read — `nearest_definition`'s answer, which for a buffer at the tree
// root is the lexicographically smaller path.
let tree = Tree::new("dup");
tree.write("a.sv", "module dup ();\nendmodule\n");
tree.write("b.sv", "module dup ();\nendmodule\n");
let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "dup").expect("the name is still known");
assert_eq!(tier(item), TIER_MODULE, "{items:#?}");
assert_eq!(item.detail.as_deref(), Some("module — a.sv"));
}
/// The nearest-definition chooser, at the level `inline.rs` consumes it.
///
/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling`
/// share `hw` and nothing more, and a byte-wise prefix would count the
/// `hw/top_` they spell alike and rank the copies by a coincidence.
#[test]
fn the_nearest_definition_is_the_one_sharing_the_most_path_components() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let index =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let asking = |from: &str| {
nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from)))
.expect("a definition")
.to_path_buf()
};
assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey);
assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling);
// Near neither, and no path at all: the tie falls to the smaller path
// rather than to whatever the index happens to hold first.
assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling);
assert_eq!(
nearest_definition(&index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
/// QA round-2 finding, fixed at lead review: a copy in the asking
/// buffer's own directory and one in a subdirectory of it share the same
/// number of leading components with the buffer (its filename never
/// matches a directory), and the lexicographic tie-break alone could pick
/// the deeper, less related copy. The real shape is opentitan's 61-way
/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv`
/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`.
#[test]
fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() {
let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv");
let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv");
let text = "module tb ();\nendmodule\n";
for sources in [
vec![(sibling.clone(), text), (deeper.clone(), text)],
vec![(deeper.clone(), text), (sibling.clone(), text)],
] {
let index = WorkspaceIndex::build(sources);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
sibling.as_path(),
"the shallower copy is the nearer one"
);
}
// …and depth only breaks a tie: a deeper copy that genuinely shares
// more of the asking path still wins.
let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
deeper.as_path(),
"sharing more components outranks being shallow"
);
}
/// The answer is a property of the paths, not of the order the index was
/// built in — which is what makes it the same answer twice in a row, and
/// the same answer in two editors.
#[test]
fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let forwards =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let backwards =
WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]);
for index in [&forwards, &backwards] {
let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv");
assert_eq!(
nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"),
earlgrey.as_path()
);
assert_eq!(
nearest_definition(index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
}
/// A module only one file declares goes through the same chooser and comes
/// back with the file `vlog_refactor::module_definition` picks — the
/// equivalence that says round 2 widened the twice-declared case and moved
/// nothing else.
#[test]
fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() {
let path = PathBuf::from("/rtl/sub.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]);
let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition");
assert_eq!(expected, path.as_path());
for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] {
assert_eq!(
nearest_definition(&index, "sub", from.as_deref()).expect("a definition"),
expected,
"{from:?}"
);
}
// And a name nothing declares is `None` here where it is an `Err`
// there — the same "no answer", spelled the way each caller reads it.
assert!(nearest_definition(&index, "nope", None).is_none());
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,585 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use std::fs;
use std::path::PathBuf;
/// Completion's own view of the three new kinds, and the detail card that
/// used to hard-code "module" over an interface — the C2 wrong answer
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn an_interface_completes_as_an_interface() {
assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT);
let index = vlog_semantic::WorkspaceIndex::build([
(PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"),
(PathBuf::from("/rtl/sub.sv"), SUB),
]);
assert!(module_detail(&index, "bus_if", None).starts_with("interface"));
assert!(module_detail(&index, "sub", None).starts_with("module"));
// The ghost-instantiation lookups reach an interface too.
assert_eq!(
nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()),
Some("/rtl/bus_if.sv".to_string())
);
}
// ------------------------------------------------------------------
// tier 0's header slice (2026-08-28) — it must change no answer
// ------------------------------------------------------------------
/// Every header shape the slice has to survive, as (file text, module).
///
/// The list is the argument that the slice changes nothing: each entry is
/// planned both ways below and the two plans are compared field by field.
const SHAPES: &[(&str, &str)] = &[
// The ordinary ANSI header, params and all.
(SUB, "sub"),
// No ports at all.
("module bare;\nendmodule\n", "bare"),
// An empty port list.
("module empty ();\n logic x;\nendmodule\n", "empty"),
// A package import written into the header: its `;` is not the
// header's, and a slice that stopped there would report no ports.
(
"package p;\n localparam int W = 4;\nendpackage\n\
module imported import p::*; #(\n parameter int W = 8\n) (\n \
input logic clk,\n output logic [W-1:0] q\n);\n \
assign q = '0;\nendmodule\n",
"imported",
),
// Two imports, then a parameter list.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
"twice",
),
// A **non-ANSI** port list: the directions live in the body, which is
// exactly what the slice drops.
(
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
always @* b = |a;\nendmodule\n",
"old",
),
// Non-ANSI with nothing declaring the ports at all.
("module silent (a, b);\nendmodule\n", "silent"),
// A comment and an attribute inside the header.
(
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
input logic clk\n);\nendmodule\n",
"noisy",
),
// A lifetime qualifier.
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
// A second module in the same file, after the one being planned.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"first",
),
// …and before it, so the slice's prefix carries a whole module.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"second",
),
// A compiler directive between the name and the port list, which the
// whitelist refuses outright.
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
// A directive *inside* the port list, which carries a warning the two
// plans must both raise.
(
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
`endif\n);\nendmodule\n",
"ifdefd",
),
// An escaped identifier for the module and for a port.
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
// A header longer than the first rung of the window ladder.
(WIDE, "wide"),
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
// instance, `(* ... *)`, right after the module name and before the
// parameter list — the one shape the "noisy" case above is commented
// as covering but does not (it has two comments, no attribute).
// **Finding, not a regression this round introduced**: a module with
// an attribute anywhere near its header is not indexed as a `Module`
// unit at all (see
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
// so this pins the safe side effect — `module_header` declines before
// its whitelist walk ever runs — rather than the whitelist's own
// handling of attributes, which this shape cannot reach.
(
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
input logic clk\n);\nendmodule\n",
"attributed",
),
// An attribute instance *inside* the port list, attached to one port.
// Same finding as `attributed`: not indexed, so not reached either.
(
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
);\nendmodule\n",
"port_attributed",
),
// A single import declaration naming several packages, comma
// separated (`import a::*, b::*;`) — one statement, not two, and the
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module chained import p::*, q::*; (input logic a);\nendmodule\n",
"chained",
),
// A parameter default whose string literal carries the exact bytes
// the whitelist watches for — `;` and `)` — which must stay inside
// the `String` token and never be mistaken for header punctuation.
(
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
input logic clk\n);\nendmodule\n",
"stringy",
),
// CRLF line endings through the whole header.
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
];
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
input logic port_number_one_with_a_long_name,\n \
input logic port_number_two_with_a_long_name,\n \
input logic port_number_three_with_a_long_name,\n \
input logic port_number_four_with_a_long_name,\n \
input logic port_number_five_with_a_long_name,\n \
output logic port_number_six_with_a_long_name\n);\n \
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
/// The whole argument for the slice: for every shape above, the plan built
/// from the header alone is the plan built from the whole file. Where it
/// would not be — a non-ANSI list, a header the whitelist refuses — the
/// guard in [`plan_for`] sends the question back to the whole file, so the
/// comparison holds there too.
#[test]
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
for (text, module) in SHAPES {
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
let ours = plan_for(&index, module, text, site);
assert_eq!(ours, whole, "{module}");
}
}
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
/// trivially for a shape the whitelist declines — both sides parse the
/// whole file, so a wrong slice could hide behind that. These shapes must
/// actually slice, so the comparison exercises the whitelist walk it is
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
/// `;`/`)` sitting inside a string literal, and CRLF endings.
#[test]
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
module_header(&index, module, text).is_some(),
"{module}: expected the header to actually slice, not fall back whole-file"
);
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
/// differently off its header, and really is sent back to the whole file.
#[test]
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
let path = PathBuf::from("/rtl/old.sv");
let index = WorkspaceIndex::build(vec![(path, text)]);
let header = module_header(&index, "old", text).expect("the header slices");
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
assert!(
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
"premise: the header alone knows nothing about these ports"
);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let guarded = plan_for(&index, "old", text, site).expect("a plan");
assert_eq!(guarded.ports[0].dir, "input");
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
}
/// The whole answer, pinned at the prefixes the hot path is worst at — the
/// empty one and a one-character one, where every tier is at its widest.
/// Tier 0 answers with names, so the pin spells out every module item's
/// label *and* the text it inserts, which is now the label again.
#[test]
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
let tree = Tree::new("pinned");
tree.write("sub.sv", SUB);
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
let (_tree, mut ws, uri, _) = opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
// Nothing typed, then one character — the two widest requests there
// are. `top` is in the answer because the buffer declares it and the
// index holds it like any other module.
let mut answer = |typed: &str| {
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
+ typed.len() as u32;
let doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
items(completions(&ws, &uri, position, true))
};
for (typed, expected) in
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
{
let items = answer(typed);
let found: Vec<&str> = skeletons(&items).iter().map(|item| item.label.as_str()).collect();
assert_eq!(found, expected, "module items after typing {typed:?}");
}
// …and the exact text each of them inserts, which is the name and
// nothing else however many ports the module has. The instantiation is
// `inline.rs`'s business now.
let items = answer("");
for name in ["sub", "alpha", "submarine"] {
let item = find(&items, name).expect("the module item");
assert_eq!(inserted(item), name, "the popup inserts the name alone");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(item.insert_text_mode, None, "there is no indentation to keep");
}
}
/// A file edited on disk since the index last read it has moved every span
/// the index holds, so the slice must not take one on trust.
#[test]
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
let text = "module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
// The same index against a file whose text has shifted underneath it.
let moved = format!("// a line nobody told the index about\n{text}");
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
}
// ------------------------------------------------------------------
// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30)
// ------------------------------------------------------------------
#[test]
fn a_module_name_at_item_position_completes_to_the_name_alone() {
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("nameonly", top, " su");
let items = items(completions(&ws, &uri, position, true));
let modules = skeletons(&items);
assert_eq!(modules.len(), 1, "{items:#?}");
let item = modules[0];
assert_eq!(item.label, "sub");
assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon");
assert_eq!(item.detail.as_deref(), Some("module — sub.sv"));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest");
assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show");
}
#[test]
fn the_snippet_flag_no_longer_changes_the_module_item() {
// The M4 fallback — a plain-text spelling of the skeleton for a client
// that never advertised `snippetSupport` — has nothing left to fall
// back from: the item is a word either way.
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, " su");
for snippets in [true, false] {
let items = items(completions(&ws, &uri, position, snippets));
let item = skeletons(&items)[0];
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "snippets: {snippets}");
}
}
/// The whole point of level 1: the popup no longer reads the files it
/// offers names from. Proved by deleting the declaring file after the
/// index has been built — the old tier answered nothing at all here,
/// because every item needed that file's text.
#[test]
fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() {
let tree = Tree::new("noread");
let sub = tree.write("sub.sv", SUB);
let (_tree, ws, uri, position) =
opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su");
fs::remove_file(&sub).expect("remove the declaring file");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(
skeletons(&items).iter().map(|item| item.label.as_str()).collect::<Vec<_>>(),
["sub"],
"the name comes from the index's table, not from the file: {items:#?}"
);
}
#[test]
fn the_edit_replaces_exactly_the_typed_word() {
let top = "module top;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("replace", top, " su");
let items = items(completions(&ws, &uri, position, true));
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}");
assert_eq!(edit.range.end, Position { line: 1, character: 4 });
}
}
#[test]
fn no_skeleton_is_offered_in_the_middle_of_an_expression() {
// The other tiers answer here — a name is a name wherever it is
// written — but a fifteen-line instantiation is not.
for (name, top, needle) in [
("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"),
("decl", "module top;\n logic su\nendmodule\n", "logic su"),
("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"),
("header", "module top (su\n);\nendmodule\n", "top (su"),
] {
let (_tree, ws, uri, position) = asking(name, top, needle);
let items = items(completions(&ws, &uri, position, true));
assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}");
}
}
#[test]
fn no_skeleton_is_offered_inside_a_procedural_block() {
let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("always", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "module top;\n initial begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("initial", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn no_skeleton_is_offered_inside_a_function_or_a_class() {
let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n";
let (_tree, ws, uri, position) = asking("function", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "package p;\n class c;\n su\n endclass\nendpackage\n";
let (_tree, ws, uri, position) = asking("class", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_generate_block_is_still_item_position() {
let top = "\
module top;
for (genvar i = 0; i < 4; i++) begin : g
su
end
endmodule
";
let (_tree, ws, uri, position) = asking("genfor", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}");
let top = "module top;\n generate\n su\n endgenerate\nendmodule\n";
let (_tree, ws, uri, position) = asking("generate", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1);
}
#[test]
fn no_skeleton_is_offered_outside_a_design_unit() {
let top = "su\nmodule top;\nendmodule\n";
let (_tree, ws, uri, position) = asking("toplevel", top, "su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_prefix_that_matches_no_module_offers_no_skeleton() {
let top = "module top;\n zzz\nendmodule\n";
let (_tree, ws, uri, position) = asking("nomatch", top, " zzz");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() {
// Until 2026-08-30 tier 0 skipped it: there is no single definition to
// build a *skeleton* from, and the skeleton was the item. A name needs
// no definition, so round 1 offered the name and left the detail
// blank. Round 2 (owner ruling, same day) makes the ghost choose a
// copy rather than decline, so the popup names the copy the ghost will
// read — `nearest_definition`'s answer, which for a buffer at the tree
// root is the lexicographically smaller path.
let tree = Tree::new("dup");
tree.write("a.sv", "module dup ();\nendmodule\n");
tree.write("b.sv", "module dup ();\nendmodule\n");
let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "dup").expect("the name is still known");
assert_eq!(tier(item), TIER_MODULE, "{items:#?}");
assert_eq!(item.detail.as_deref(), Some("module — a.sv"));
}
/// The nearest-definition chooser, at the level `inline.rs` consumes it.
///
/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling`
/// share `hw` and nothing more, and a byte-wise prefix would count the
/// `hw/top_` they spell alike and rank the copies by a coincidence.
#[test]
fn the_nearest_definition_is_the_one_sharing_the_most_path_components() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let index = WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let asking = |from: &str| {
nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from)))
.expect("a definition")
.to_path_buf()
};
assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey);
assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling);
// Near neither, and no path at all: the tie falls to the smaller path
// rather than to whatever the index happens to hold first.
assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling);
assert_eq!(
nearest_definition(&index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
/// QA round-2 finding, fixed at lead review: a copy in the asking
/// buffer's own directory and one in a subdirectory of it share the same
/// number of leading components with the buffer (its filename never
/// matches a directory), and the lexicographic tie-break alone could pick
/// the deeper, less related copy. The real shape is opentitan's 61-way
/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv`
/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`.
#[test]
fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() {
let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv");
let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv");
let text = "module tb ();\nendmodule\n";
for sources in [
vec![(sibling.clone(), text), (deeper.clone(), text)],
vec![(deeper.clone(), text), (sibling.clone(), text)],
] {
let index = WorkspaceIndex::build(sources);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
sibling.as_path(),
"the shallower copy is the nearer one"
);
}
// …and depth only breaks a tie: a deeper copy that genuinely shares
// more of the asking path still wins.
let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
deeper.as_path(),
"sharing more components outranks being shallow"
);
}
/// The answer is a property of the paths, not of the order the index was
/// built in — which is what makes it the same answer twice in a row, and
/// the same answer in two editors.
#[test]
fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let forwards =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let backwards =
WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]);
for index in [&forwards, &backwards] {
let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv");
assert_eq!(
nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"),
earlgrey.as_path()
);
assert_eq!(
nearest_definition(index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
}
/// A module only one file declares goes through the same chooser and comes
/// back with the file `vlog_refactor::module_definition` picks — the
/// equivalence that says round 2 widened the twice-declared case and moved
/// nothing else.
#[test]
fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() {
let path = PathBuf::from("/rtl/sub.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]);
let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition");
assert_eq!(expected, path.as_path());
for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] {
assert_eq!(
nearest_definition(&index, "sub", from.as_deref()).expect("a definition"),
expected,
"{from:?}"
);
}
// And a name nothing declares is `None` here where it is an `Err`
// there — the same "no answer", spelled the way each caller reads it.
assert!(nearest_definition(&index, "nope", None).is_none());
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// 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
@@ -102,8 +104,7 @@ pub(super) fn related_tier(
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 {
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);
@@ -339,3 +340,5 @@ mod tests {
assert_eq!(mid.detail.as_deref(), Some("variable — mid_c::zed_mid"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! What may be written here: the module-item gate and the statement gate,
//! judged over the token stream's scope chain.
//!
@@ -262,3 +264,5 @@ mod tests {
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4 -707
View File
@@ -1,3 +1,5 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Tiers 1 to 5: the five ordinary tiers, in the order they fill the
//! response.
//!
@@ -236,711 +238,6 @@ pub(super) fn word_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: O
}
#[cfg(test)]
mod tests {
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use crate::uri::path_to_uri;
mod tests;
// ------------------------------------------------------------------
// tier 3 — templates
// ------------------------------------------------------------------
/// Only the templates — tier 3.
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
items
.iter()
.filter(|item| tier(item) == TIER_TEMPLATE)
.map(|item| item.label.as_str())
.collect()
}
/// The items offered at `needle`'s end in a buffer named `file`.
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
items(completions(&ws, &uri, position, true))
}
#[test]
fn a_statement_template_expands_where_a_statement_may_be_written() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("stmt", "top.sv", top, " if");
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
assert_eq!(
inserted(item),
"if (${1:cond}) begin\n $0\n end",
"the site's own indentation, the condition first and the body last"
);
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
}
#[test]
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
// Dedup is by label, so the labels are prose on purpose: `if` the
// keyword and `if begin/end` the template are two items, in that
// order of specificity.
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("both", "top.sv", top, " if");
let keyword = find(&items, "if").expect("the bare keyword");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(keyword), TIER_KEYWORD);
assert_eq!(tier(template), TIER_TEMPLATE);
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
}
#[test]
fn a_template_ranks_below_a_name_the_code_declares() {
let top = "\
module top;
logic if_enable;
always_comb begin
if
end
endmodule
";
let items = offering("rank", "top.sv", top, " if");
let symbol = find(&items, "if_enable").expect("a declaration in scope");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(symbol), TIER_SCOPE);
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
}
#[test]
fn statement_templates_and_item_templates_swap_places_with_the_position() {
// One prefix, `i`, reaching `if` in one place and `initial` in the
// other — so this is the gate and not the filter.
let inside = offering(
"posstmt",
"top.sv",
"module top;\n always_comb begin\n i\n end\nendmodule\n",
" i",
);
assert!(template_labels(&inside).contains(&"if begin/end"));
assert!(
!template_labels(&inside).contains(&"initial begin/end"),
"an initial block is not a statement: {:?}",
template_labels(&inside)
);
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
assert!(template_labels(&at_item).contains(&"initial begin/end"));
assert!(
!template_labels(&at_item).contains(&"if begin/end"),
"a bare if is not a module item: {:?}",
template_labels(&at_item)
);
}
#[test]
fn an_always_template_is_a_module_item_and_nothing_else() {
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
"and `alw` finds every one of them"
);
let inside = offering(
"alwstmt",
"top.sv",
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
" alw",
);
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
}
#[test]
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
let inside = offering(
"declstmt",
"top.sv",
"module top;\n always_comb begin\n log\n end\nendmodule\n",
" log",
);
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
}
#[test]
fn the_file_name_decides_which_dialect_is_offered() {
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
assert!(template_labels(&sv).contains(&"logic name;"));
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
assert_eq!(template_labels(&reg), ["reg name;", "reg [N:0] name;"]);
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
#[test]
fn an_else_template_follows_an_end_on_the_same_line() {
let top = "\
module top;
always_comb begin
if (a) begin
end el
end
endmodule
";
let items = offering("elsetail", "top.sv", top, "end el");
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
assert_eq!(
inserted(find(&items, "else if").expect("the else-if template")),
"else if (${1:cond}) begin\n $0\n end"
);
}
#[test]
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
// The other half of the same rule: `x = if` is an expression, not a
// place a template belongs — and the general tiers still answer there.
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
let items = offering("midline", "top.sv", top, "x = if");
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
}
#[test]
fn no_template_is_offered_where_a_statement_cannot_go() {
for (name, top, needle) in [
// A generate block is item position, not statement position.
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
// A `case` arm wants `label:`, not a bare statement.
(
"casearm",
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
" if",
),
// Nothing at all is open here.
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
// A port list is not a statement, however much it starts a line.
("ports", "module top (\n if\n);\nendmodule\n", " if"),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
}
}
#[test]
fn a_subprogram_body_is_statement_position() {
for (name, top, needle) in [
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
(
"fnbegin",
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
" if",
),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
}
}
#[test]
fn nothing_templated_is_offered_inside_a_comment() {
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_client_without_snippet_support_gets_the_template_filled_in() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
let items = items(completions(&ws, &uri, position, false));
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
let text = inserted(item);
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
assert_eq!(text, "if (cond) begin\n\n end");
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the inserted text must parse: {text}"
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
let items = offering("tmpldocs", "top.sv", top, " alw");
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
panic!("markdown documentation");
};
// Fenced with the language id the extension's TextMate grammar is
// registered for, so the panel renders highlighted rather than grey.
assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value);
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
}
// ------------------------------------------------------------------
// tier 4 — keywords
// ------------------------------------------------------------------
#[test]
fn every_keyword_the_lexer_knows_is_offered() {
let top = "module top;\n assign x = alw\nendmodule\n";
let (_tree, ws, uri, position) = asking("keyword", top, "= alw");
let items = items(completions(&ws, &uri, position, true));
let keywords: Vec<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]);
let always = find(&items, "always").expect("`always`");
assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD));
assert_eq!(inserted(always), "always");
}
#[test]
fn the_keyword_tier_is_exactly_the_lexers_list() {
let top = "module top;\n assign x = \nendmodule\n";
let (_tree, ws, uri, position) = asking("allkeywords", top, "= ");
let items = items(completions(&ws, &uri, position, true));
let offered: HashSet<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
let known: HashSet<&str> = KEYWORDS.iter().copied().collect();
assert_eq!(offered, known, "no keyword may be missing and none invented");
}
// ------------------------------------------------------------------
// tiers, ordering and dedup
// ------------------------------------------------------------------
#[test]
fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() {
let tree = Tree::new("tiers");
tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n");
tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n");
let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= w");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE);
assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX);
assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD);
assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD);
let scope = find(&items, "w_local").expect("in scope");
let word = find(&items, "w_elsewhere").expect("a project word");
assert!(scope.sort_text < word.sort_text, "the client sorts scope above words");
}
#[test]
fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() {
let tree = Tree::new("dedup");
// The same name, declared here and used elsewhere in the project.
tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n");
let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= shared");
let items = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
items.iter().filter(|i| i.label == "shared_name").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it");
}
#[test]
fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() {
let top = "\
module top #(parameter int WIDTH = 8) (input logic clk);
typedef logic [1:0] pair_t;
logic [WIDTH-1:0] data;
function int f(); return 0; endfunction
assign x =
endmodule
";
let (_tree, ws, uri, position) = asking("kinds", top, "assign x =");
let items = items(completions(&ws, &uri, position, true));
let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind;
assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT));
assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD));
assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER));
assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE));
assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION));
assert_eq!(
find(&items, "data").expect("data").detail.as_deref(),
Some("logic [WIDTH-1:0] data;"),
"the declaration as written"
);
}
#[test]
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
// `inner` is declared in a block the cursor is not in, so it may only
// arrive as one of this file's declarations (tier 2, `completion-ux`)
// — never as a visible declaration.
let top = "\
module top;
initial begin : b
integer inner_only;
end
initial begin
x = inner
end
endmodule
";
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "inner_only").expect("known as a declaration at least");
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
}
// ------------------------------------------------------------------
// fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md
// ------------------------------------------------------------------
/// A workspace holding the name the whole round is about, a scatter to
/// rank it against, and a `ce…` name that only a prefix reaches.
fn typing(name: &str) -> (Tree, Workspace, Uri) {
let tree = Tree::new(name);
tree.write(
"ast.sv",
"module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\
endmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
(tree, ws, uri)
}
/// The response to `typed`, written mid-expression in `top.sv` — the
/// position where no tier is position-gated off.
fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option<CompletionResponse> {
let text = format!("module top;\n assign x = {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset =
(text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32;
let position = ws.document(uri).expect("open").positions().position(offset);
completions(ws, uri, position, true)
}
/// The headline: three characters reach a name no prefix ever would.
#[test]
fn three_characters_reach_a_name_a_prefix_never_would() {
let (_tree, mut ws, uri) = typing("fuzzyhit");
for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] {
let found = items(after_typing(&mut ws, &uri, typed));
let item = find(&found, "clk_osc_en_q")
.unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found)));
assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project");
assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted");
}
}
/// …and the edit still replaces exactly what was typed, which is the
/// whole reason a fuzzy hit is usable at all: `clkenq` becomes
/// `clk_osc_en_q`, not `clkenqclk_osc_en_q`.
#[test]
fn a_fuzzy_hit_replaces_exactly_the_typed_word() {
let (_tree, mut ws, uri) = typing("fuzzyedit");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit");
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
// ` assign x = clkenq` — the word starts at column 13 and the cursor
// is at its end.
assert_eq!(edit.range.start, Position { line: 1, character: 13 });
assert_eq!(edit.range.end, Position { line: 1, character: 19 });
assert_eq!(edit.new_text, "clk_osc_en_q");
assert_eq!(item.filter_text, None, "the client filters on the label, as it should");
}
/// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters
/// in order and must still not reach it.
#[test]
fn two_characters_match_by_prefix_and_nothing_else() {
let (_tree, mut ws, uri) = typing("fuzzyfloor");
for typed in ["c", "ce"] {
let found = items(after_typing(&mut ws, &uri, typed));
assert!(!found.is_empty(), "premise: {typed:?} answers something");
for item in &found {
assert!(
starts_with_ignore_case(&item.label, typed),
"{:?} is not a prefix match for {typed:?}",
item.label
);
}
}
// The discriminator, spelled out: `ce` would reach it if it were fuzzy
// (`c` at 0, `e` at 8), and `cen` — one character more — does.
let two = items(after_typing(&mut ws, &uri, "ce"));
assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two));
assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two));
let three = items(after_typing(&mut ws, &uri, "cen"));
assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three));
}
/// The 1- and 2-character answers, pinned against what they were before
/// fuzzy matching existed. The keyword tier is checked as a set rather
/// than listed, so adding a reserved word to the lexer does not break a
/// test about completion.
#[test]
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `c` itself used to be in the list, because the buffer being
// typed in holds it as an `Ident` token. `completion-ux`
// (2026-11-17) dropped it on purpose: the buffer-word tier skips
// the token under the cursor, and offering the user their own
// half-word back is noise.
("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["celsius"]),
] {
let found = items(after_typing(&mut ws, &uri, typed));
let named: Vec<&str> = found
.iter()
.filter(|item| tier(item) != TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
assert_eq!(named, expected, "the names {typed:?} answers with");
let keywords: Vec<&str> = found
.iter()
.filter(|item| tier(item) == TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
let expected_keywords: Vec<&str> =
KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect();
assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with");
}
}
/// **The `isIncomplete` trap.** VS Code asks again on the next keystroke
/// only when the last answer said it was incomplete, so a complete
/// two-character answer would swallow the third keystroke and fuzzy would
/// never fire at all.
#[test]
fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() {
let (_tree, mut ws, uri) = typing("fuzzyincomplete");
for typed in ["", "c", "ce"] {
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else {
panic!("a completion list for {typed:?}");
};
assert!(list.is_incomplete, "{typed:?} must ask to be asked again");
}
// From the floor up the ordinary rule stands: complete when the whole
// hit set fit, which is sound because appending a character can only
// ever shrink it.
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else {
panic!("a completion list");
};
assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len());
}
/// A prefix match is the best subsequence match there is, and the list
/// says so — asserted on the order of the array, which is what the cap
/// cuts and what a client that does not re-rank shows.
#[test]
fn a_prefix_hit_outranks_a_scattered_one() {
let (_tree, mut ws, uri) = typing("fuzzyrank");
let found = items(after_typing(&mut ws, &uri, "clk"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("clk_osc_en_q") < at("c_l_k_scatter"),
"the prefix hit leads: {:?}",
labels(&found)
);
}
/// Scoring the boundaries is visible in the order, not only in the score:
/// a run that starts after an underscore beats the same letters buried
/// mid-word.
#[test]
fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() {
let tree = Tree::new("fuzzyboundary");
tree.write(
"ast.sv",
"module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "ena"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("osc_ena_ready") < at("xxenaxx_ready"),
"the boundary run leads: {:?}",
labels(&found)
);
drop(tree);
}
/// Dedup survives the change: a name two tiers can reach is offered once,
/// by the better tier, whichever way it was matched.
#[test]
fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() {
let tree = Tree::new("fuzzydedup");
// The same name, declared in this buffer (tier 1) and used in the
// project (tier 5), reachable from `clkenq` by neither prefix.
tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("= clkenq").expect("needle") + 8) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
found.iter().filter(|item| item.label == "clk_osc_en_q").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE));
drop(tree);
}
/// The tiers that did **not** go fuzzy, pinned so the split is a decision
/// and not a drift: keywords, templates and macro names still match by
/// prefix, and the module tier still matches by substring.
#[test]
fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() {
let tree = Tree::new("fuzzyunchanged");
tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n");
tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
// Mid-expression: the macro name is offered bare by tier 2 and must
// not be reachable by subsequence, and neither is a keyword.
let found = items(after_typing(&mut ws, &uri, "clkenq"));
assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found));
let found = items(after_typing(&mut ws, &uri, "alws"));
assert!(labels(&found).is_empty() || !labels(&found).contains(&"always"));
// A backtick still answers by prefix only.
let text = "module top;\n assign x = `CLKENQ\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way");
// …and the module tier is still a substring match, which is wider
// than a prefix and narrower than a subsequence.
let text = "module top;\n osc_en\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("osc_en").expect("needle") + 6) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect();
assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it");
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
fn a_declaration_in_scope_is_reached_by_subsequence() {
let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "clk_osc_en_q").expect("the declaration");
assert_eq!(tier(item), TIER_SCOPE);
assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;"));
}
/// The index tier goes fuzzy too — a package member is reached the same
/// way a project word is.
#[test]
fn a_project_declaration_is_reached_by_subsequence() {
let tree = Tree::new("fuzzyindex");
tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "CLK_OSC_EN_Q").expect("the package member");
assert_eq!(tier(item), TIER_INDEX);
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT));
drop(tree);
}
#[test]
fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() {
let tree = Tree::new("overlay");
let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n");
let top = "module top;\n assign x = ov\nendmodule\n";
let (_tree, mut ws, uri, position) = opened(tree, top, "= ov");
let other_uri = path_to_uri(&other).expect("uri");
ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string());
ws.rebuild_index();
let items = items(completions(&ws, &uri, position, true));
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
@@ -0,0 +1,704 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use crate::uri::path_to_uri;
// ------------------------------------------------------------------
// tier 3 — templates
// ------------------------------------------------------------------
/// Only the templates — tier 3.
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
items
.iter()
.filter(|item| tier(item) == TIER_TEMPLATE)
.map(|item| item.label.as_str())
.collect()
}
/// The items offered at `needle`'s end in a buffer named `file`.
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
items(completions(&ws, &uri, position, true))
}
#[test]
fn a_statement_template_expands_where_a_statement_may_be_written() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("stmt", "top.sv", top, " if");
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
assert_eq!(
inserted(item),
"if (${1:cond}) begin\n $0\n end",
"the site's own indentation, the condition first and the body last"
);
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
}
#[test]
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
// Dedup is by label, so the labels are prose on purpose: `if` the
// keyword and `if begin/end` the template are two items, in that
// order of specificity.
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("both", "top.sv", top, " if");
let keyword = find(&items, "if").expect("the bare keyword");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(keyword), TIER_KEYWORD);
assert_eq!(tier(template), TIER_TEMPLATE);
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
}
#[test]
fn a_template_ranks_below_a_name_the_code_declares() {
let top = "\
module top;
logic if_enable;
always_comb begin
if
end
endmodule
";
let items = offering("rank", "top.sv", top, " if");
let symbol = find(&items, "if_enable").expect("a declaration in scope");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(symbol), TIER_SCOPE);
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
}
#[test]
fn statement_templates_and_item_templates_swap_places_with_the_position() {
// One prefix, `i`, reaching `if` in one place and `initial` in the
// other — so this is the gate and not the filter.
let inside = offering(
"posstmt",
"top.sv",
"module top;\n always_comb begin\n i\n end\nendmodule\n",
" i",
);
assert!(template_labels(&inside).contains(&"if begin/end"));
assert!(
!template_labels(&inside).contains(&"initial begin/end"),
"an initial block is not a statement: {:?}",
template_labels(&inside)
);
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
assert!(template_labels(&at_item).contains(&"initial begin/end"));
assert!(
!template_labels(&at_item).contains(&"if begin/end"),
"a bare if is not a module item: {:?}",
template_labels(&at_item)
);
}
#[test]
fn an_always_template_is_a_module_item_and_nothing_else() {
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
"and `alw` finds every one of them"
);
let inside = offering(
"alwstmt",
"top.sv",
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
" alw",
);
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
}
#[test]
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
let inside = offering(
"declstmt",
"top.sv",
"module top;\n always_comb begin\n log\n end\nendmodule\n",
" log",
);
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
}
#[test]
fn the_file_name_decides_which_dialect_is_offered() {
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
assert!(template_labels(&sv).contains(&"logic name;"));
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
assert_eq!(template_labels(&reg), ["reg name;", "reg [N:0] name;"]);
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
#[test]
fn an_else_template_follows_an_end_on_the_same_line() {
let top = "\
module top;
always_comb begin
if (a) begin
end el
end
endmodule
";
let items = offering("elsetail", "top.sv", top, "end el");
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
assert_eq!(
inserted(find(&items, "else if").expect("the else-if template")),
"else if (${1:cond}) begin\n $0\n end"
);
}
#[test]
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
// The other half of the same rule: `x = if` is an expression, not a
// place a template belongs — and the general tiers still answer there.
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
let items = offering("midline", "top.sv", top, "x = if");
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
}
#[test]
fn no_template_is_offered_where_a_statement_cannot_go() {
for (name, top, needle) in [
// A generate block is item position, not statement position.
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
// A `case` arm wants `label:`, not a bare statement.
(
"casearm",
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
" if",
),
// Nothing at all is open here.
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
// A port list is not a statement, however much it starts a line.
("ports", "module top (\n if\n);\nendmodule\n", " if"),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
}
}
#[test]
fn a_subprogram_body_is_statement_position() {
for (name, top, needle) in [
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
(
"fnbegin",
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
" if",
),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
}
}
#[test]
fn nothing_templated_is_offered_inside_a_comment() {
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_client_without_snippet_support_gets_the_template_filled_in() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
let items = items(completions(&ws, &uri, position, false));
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
let text = inserted(item);
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
assert_eq!(text, "if (cond) begin\n\n end");
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the inserted text must parse: {text}"
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
let items = offering("tmpldocs", "top.sv", top, " alw");
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
panic!("markdown documentation");
};
// Fenced with the language id the extension's TextMate grammar is
// registered for, so the panel renders highlighted rather than grey.
assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value);
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
}
// ------------------------------------------------------------------
// tier 4 — keywords
// ------------------------------------------------------------------
#[test]
fn every_keyword_the_lexer_knows_is_offered() {
let top = "module top;\n assign x = alw\nendmodule\n";
let (_tree, ws, uri, position) = asking("keyword", top, "= alw");
let items = items(completions(&ws, &uri, position, true));
let keywords: Vec<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]);
let always = find(&items, "always").expect("`always`");
assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD));
assert_eq!(inserted(always), "always");
}
#[test]
fn the_keyword_tier_is_exactly_the_lexers_list() {
let top = "module top;\n assign x = \nendmodule\n";
let (_tree, ws, uri, position) = asking("allkeywords", top, "= ");
let items = items(completions(&ws, &uri, position, true));
let offered: HashSet<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
let known: HashSet<&str> = KEYWORDS.iter().copied().collect();
assert_eq!(offered, known, "no keyword may be missing and none invented");
}
// ------------------------------------------------------------------
// tiers, ordering and dedup
// ------------------------------------------------------------------
#[test]
fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() {
let tree = Tree::new("tiers");
tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n");
tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n");
let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= w");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE);
assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX);
assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD);
assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD);
let scope = find(&items, "w_local").expect("in scope");
let word = find(&items, "w_elsewhere").expect("a project word");
assert!(scope.sort_text < word.sort_text, "the client sorts scope above words");
}
#[test]
fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() {
let tree = Tree::new("dedup");
// The same name, declared here and used elsewhere in the project.
tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n");
let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= shared");
let items = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> = items.iter().filter(|i| i.label == "shared_name").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it");
}
#[test]
fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() {
let top = "\
module top #(parameter int WIDTH = 8) (input logic clk);
typedef logic [1:0] pair_t;
logic [WIDTH-1:0] data;
function int f(); return 0; endfunction
assign x =
endmodule
";
let (_tree, ws, uri, position) = asking("kinds", top, "assign x =");
let items = items(completions(&ws, &uri, position, true));
let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind;
assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT));
assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD));
assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER));
assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE));
assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION));
assert_eq!(
find(&items, "data").expect("data").detail.as_deref(),
Some("logic [WIDTH-1:0] data;"),
"the declaration as written"
);
}
#[test]
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
// `inner` is declared in a block the cursor is not in, so it may only
// arrive as one of this file's declarations (tier 2, `completion-ux`)
// — never as a visible declaration.
let top = "\
module top;
initial begin : b
integer inner_only;
end
initial begin
x = inner
end
endmodule
";
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "inner_only").expect("known as a declaration at least");
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
}
// ------------------------------------------------------------------
// fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md
// ------------------------------------------------------------------
/// A workspace holding the name the whole round is about, a scatter to
/// rank it against, and a `ce…` name that only a prefix reaches.
fn typing(name: &str) -> (Tree, Workspace, Uri) {
let tree = Tree::new(name);
tree.write(
"ast.sv",
"module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\
endmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
(tree, ws, uri)
}
/// The response to `typed`, written mid-expression in `top.sv` — the
/// position where no tier is position-gated off.
fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option<CompletionResponse> {
let text = format!("module top;\n assign x = {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32;
let position = ws.document(uri).expect("open").positions().position(offset);
completions(ws, uri, position, true)
}
/// The headline: three characters reach a name no prefix ever would.
#[test]
fn three_characters_reach_a_name_a_prefix_never_would() {
let (_tree, mut ws, uri) = typing("fuzzyhit");
for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] {
let found = items(after_typing(&mut ws, &uri, typed));
let item = find(&found, "clk_osc_en_q")
.unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found)));
assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project");
assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted");
}
}
/// …and the edit still replaces exactly what was typed, which is the
/// whole reason a fuzzy hit is usable at all: `clkenq` becomes
/// `clk_osc_en_q`, not `clkenqclk_osc_en_q`.
#[test]
fn a_fuzzy_hit_replaces_exactly_the_typed_word() {
let (_tree, mut ws, uri) = typing("fuzzyedit");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit");
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
// ` assign x = clkenq` — the word starts at column 13 and the cursor
// is at its end.
assert_eq!(edit.range.start, Position { line: 1, character: 13 });
assert_eq!(edit.range.end, Position { line: 1, character: 19 });
assert_eq!(edit.new_text, "clk_osc_en_q");
assert_eq!(item.filter_text, None, "the client filters on the label, as it should");
}
/// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters
/// in order and must still not reach it.
#[test]
fn two_characters_match_by_prefix_and_nothing_else() {
let (_tree, mut ws, uri) = typing("fuzzyfloor");
for typed in ["c", "ce"] {
let found = items(after_typing(&mut ws, &uri, typed));
assert!(!found.is_empty(), "premise: {typed:?} answers something");
for item in &found {
assert!(
starts_with_ignore_case(&item.label, typed),
"{:?} is not a prefix match for {typed:?}",
item.label
);
}
}
// The discriminator, spelled out: `ce` would reach it if it were fuzzy
// (`c` at 0, `e` at 8), and `cen` — one character more — does.
let two = items(after_typing(&mut ws, &uri, "ce"));
assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two));
assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two));
let three = items(after_typing(&mut ws, &uri, "cen"));
assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three));
}
/// The 1- and 2-character answers, pinned against what they were before
/// fuzzy matching existed. The keyword tier is checked as a set rather
/// than listed, so adding a reserved word to the lexer does not break a
/// test about completion.
#[test]
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `c` itself used to be in the list, because the buffer being
// typed in holds it as an `Ident` token. `completion-ux`
// (2026-11-17) dropped it on purpose: the buffer-word tier skips
// the token under the cursor, and offering the user their own
// half-word back is noise.
("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["celsius"]),
] {
let found = items(after_typing(&mut ws, &uri, typed));
let named: Vec<&str> = found
.iter()
.filter(|item| tier(item) != TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
assert_eq!(named, expected, "the names {typed:?} answers with");
let keywords: Vec<&str> = found
.iter()
.filter(|item| tier(item) == TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
let expected_keywords: Vec<&str> =
KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect();
assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with");
}
}
/// **The `isIncomplete` trap.** VS Code asks again on the next keystroke
/// only when the last answer said it was incomplete, so a complete
/// two-character answer would swallow the third keystroke and fuzzy would
/// never fire at all.
#[test]
fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() {
let (_tree, mut ws, uri) = typing("fuzzyincomplete");
for typed in ["", "c", "ce"] {
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else {
panic!("a completion list for {typed:?}");
};
assert!(list.is_incomplete, "{typed:?} must ask to be asked again");
}
// From the floor up the ordinary rule stands: complete when the whole
// hit set fit, which is sound because appending a character can only
// ever shrink it.
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else {
panic!("a completion list");
};
assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len());
}
/// A prefix match is the best subsequence match there is, and the list
/// says so — asserted on the order of the array, which is what the cap
/// cuts and what a client that does not re-rank shows.
#[test]
fn a_prefix_hit_outranks_a_scattered_one() {
let (_tree, mut ws, uri) = typing("fuzzyrank");
let found = items(after_typing(&mut ws, &uri, "clk"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(at("clk_osc_en_q") < at("c_l_k_scatter"), "the prefix hit leads: {:?}", labels(&found));
}
/// Scoring the boundaries is visible in the order, not only in the score:
/// a run that starts after an underscore beats the same letters buried
/// mid-word.
#[test]
fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() {
let tree = Tree::new("fuzzyboundary");
tree.write(
"ast.sv",
"module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "ena"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("osc_ena_ready") < at("xxenaxx_ready"),
"the boundary run leads: {:?}",
labels(&found)
);
drop(tree);
}
/// Dedup survives the change: a name two tiers can reach is offered once,
/// by the better tier, whichever way it was matched.
#[test]
fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() {
let tree = Tree::new("fuzzydedup");
// The same name, declared in this buffer (tier 1) and used in the
// project (tier 5), reachable from `clkenq` by neither prefix.
tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("= clkenq").expect("needle") + 8) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
found.iter().filter(|item| item.label == "clk_osc_en_q").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE));
drop(tree);
}
/// The tiers that did **not** go fuzzy, pinned so the split is a decision
/// and not a drift: keywords, templates and macro names still match by
/// prefix, and the module tier still matches by substring.
#[test]
fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() {
let tree = Tree::new("fuzzyunchanged");
tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n");
tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
// Mid-expression: the macro name is offered bare by tier 2 and must
// not be reachable by subsequence, and neither is a keyword.
let found = items(after_typing(&mut ws, &uri, "clkenq"));
assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found));
let found = items(after_typing(&mut ws, &uri, "alws"));
assert!(labels(&found).is_empty() || !labels(&found).contains(&"always"));
// A backtick still answers by prefix only.
let text = "module top;\n assign x = `CLKENQ\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way");
// …and the module tier is still a substring match, which is wider
// than a prefix and narrower than a subsequence.
let text = "module top;\n osc_en\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("osc_en").expect("needle") + 6) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect();
assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it");
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
fn a_declaration_in_scope_is_reached_by_subsequence() {
let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "clk_osc_en_q").expect("the declaration");
assert_eq!(tier(item), TIER_SCOPE);
assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;"));
}
/// The index tier goes fuzzy too — a package member is reached the same
/// way a project word is.
#[test]
fn a_project_declaration_is_reached_by_subsequence() {
let tree = Tree::new("fuzzyindex");
tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "CLK_OSC_EN_Q").expect("the package member");
assert_eq!(tier(item), TIER_INDEX);
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT));
drop(tree);
}
#[test]
fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() {
let tree = Tree::new("overlay");
let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n");
let top = "module top;\n assign x = ov\nendmodule\n";
let (_tree, mut ws, uri, position) = opened(tree, top, "= ov");
let other_uri = path_to_uri(&other).expect("uri");
ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string());
ws.rebuild_index();
let items = items(completions(&ws, &uri, position, true));
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
Loaded 100 of 1155 files, more files were not shown because too many files have changed in this diff. Show more