Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72ff5df1cc | ||
|
|
4edada583f | ||
|
|
14b72f2862 | ||
|
|
82bbba04be | ||
|
|
7a0c8e51f9 | ||
|
|
ef867db004 | ||
|
|
23e2e4bca5 | ||
|
|
a2a22adad8 | ||
|
|
9d1eb1671e | ||
|
|
5d70cb89cc | ||
|
|
da32237a0e | ||
|
|
c82978c3db | ||
|
|
1b8723ca1f | ||
|
|
2675131f8c | ||
|
|
409acae087 | ||
|
|
f5edac9197 | ||
|
|
7df86fe979 | ||
|
|
b4a0668b24 | ||
|
|
41945912a3 | ||
|
|
faf890d9f0 | ||
|
|
3ceba21bb2 | ||
|
|
b12e0cc2c4 | ||
|
|
01843eb75a | ||
|
|
5e02142a8f | ||
|
|
07ef771a35 | ||
|
|
eb54042032 | ||
|
|
a1c77c053f | ||
|
|
51cbfd27df | ||
|
|
e13ae4c89b | ||
|
|
b2bb912bbb | ||
|
|
126a6bcdac | ||
|
|
bc59336d91 | ||
|
|
b2a5f0a171 | ||
|
|
32204eba71 | ||
|
|
243472901d | ||
|
|
4621214a51 | ||
|
|
8e65da1ba8 | ||
|
|
5c9fdb2c62 | ||
|
|
e51a2c7f21 | ||
|
|
dafa4f0500 | ||
|
|
6c1f863417 | ||
|
|
501b36d8b8 | ||
|
|
9c75b7a4e5 | ||
|
|
be084f07b5 | ||
|
|
bbdbfe9045 | ||
|
|
3bd55acb98 | ||
|
|
c37b13de31 | ||
|
|
d8d1791c1c | ||
|
|
d10e57aa6e | ||
|
|
414d501847 | ||
|
|
4123905aa1 | ||
|
|
df4e71411f | ||
|
|
6759f0eea1 | ||
|
|
4c2dae323e | ||
|
|
a69a1cb528 | ||
|
|
e1679bebc5 | ||
|
|
94b0711efb | ||
|
|
449b874798 | ||
|
|
4d342367b9 | ||
|
|
a5ca0c9b10 | ||
|
|
acf20f7e62 | ||
|
|
e6eaf53c35 | ||
|
|
ce2f7190ed | ||
|
|
aa479cf701 | ||
|
|
d9ed2c447a | ||
|
|
1da0a303cc | ||
|
|
f476c31483 | ||
|
|
9ef1058059 | ||
|
|
4d59e80568 | ||
|
|
859742ac84 | ||
|
|
66f38987ac | ||
|
|
8145a67be6 | ||
|
|
f7956060b3 | ||
|
|
f302b471a7 | ||
|
|
7aedfe2554 | ||
|
|
73799f3d53 | ||
|
|
ec9ec42276 | ||
|
|
4b2dad87fe | ||
|
|
3b08c0753c | ||
|
|
972bd1cff1 | ||
|
|
8a92e79fc0 | ||
|
|
f6f18de10d | ||
|
|
d5abf81563 | ||
|
|
97aa2fefd8 | ||
|
|
9604753b6c | ||
|
|
797ef86d47 | ||
|
|
a30dda167a | ||
|
|
0757503fd1 | ||
|
|
6a0af26fdf | ||
|
|
8adb6c8ac1 | ||
|
|
fbee290a0a | ||
|
|
b1b3cad09b | ||
|
|
a896e0dff0 | ||
|
|
0cb398bcd9 | ||
|
|
17697b9d77 | ||
|
|
5e5813a2a9 | ||
|
|
bafc1b425b | ||
|
|
8c61570a04 | ||
|
|
7c4bdbcfea | ||
|
|
e902af37c5 | ||
|
|
4ba6eafa2d | ||
|
|
747ae02b0e | ||
|
|
ffbb29ddbb | ||
|
|
f1d44a2a0c | ||
|
|
10b63e665d | ||
|
|
a648561f63 | ||
|
|
1c20549cfa | ||
|
|
97f7296b8f | ||
|
|
cebeff45b4 | ||
|
|
6a15594ae8 | ||
|
|
4d70de1976 | ||
|
|
63bbc23e37 | ||
|
|
a0ae5e5fa8 | ||
|
|
965c4ee25a | ||
|
|
999edd0203 | ||
|
|
1c6ed7e70d | ||
|
|
ef9ce984b7 | ||
|
|
40a7b478c5 | ||
|
|
5461179e18 | ||
|
|
bff31bb80f | ||
|
|
ee0faa2e18 | ||
|
|
15c78c1c32 | ||
|
|
132f6e9186 | ||
|
|
d1821ff859 | ||
|
|
3d0a0af893 | ||
|
|
eb87a555b3 | ||
|
|
b57ae35be4 | ||
|
|
96425f6cb9 | ||
|
|
de6f04bf7d | ||
|
|
b96827c51d | ||
|
|
a426c4dbfe | ||
|
|
9b93f33ae3 | ||
|
|
35f0b8d371 | ||
|
|
159f6a0bd8 | ||
|
|
a045cd7649 | ||
|
|
f3af34980a | ||
|
|
c2f107444c | ||
|
|
baf0bf16f0 | ||
|
|
81df63d942 | ||
|
|
a0c290ccc2 | ||
|
|
58112d4d3b | ||
|
|
51869c8bf4 | ||
|
|
5051bbdf15 | ||
|
|
29096cbbac | ||
|
|
c40e720518 | ||
|
|
4e62a14af6 | ||
|
|
cbb80e884f | ||
|
|
3ee1c558b3 |
No files matched your search
@@ -43,7 +43,12 @@ jobs:
|
||||
run: tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"
|
||||
- name: Extract the release notes from CHANGELOG.md
|
||||
run: tools/release_notes.sh "${GITHUB_REF_NAME#v}" > dist/RELEASE_NOTES.md
|
||||
# LUCISV_API_URL is an optional repository Actions variable naming a
|
||||
# direct http://host:port for the Gitea API, so the uploads do not go
|
||||
# through Cloudflare's 100-second origin timeout (0.29.0 and 0.30.0
|
||||
# both died there with a 524). Unset, the public URL is used.
|
||||
- name: Create the release and attach the artifacts
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
LUCISV_API_URL: ${{ vars.LUCISV_API_URL }}
|
||||
run: tools/publish_release.sh "$GITHUB_REF_NAME" dist
|
||||
@@ -7,3 +7,4 @@
|
||||
.DS_Store
|
||||
/.zcode
|
||||
/.claude
|
||||
__pycache__/
|
||||
+927
@@ -4,6 +4,933 @@ 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.56.0 — 2026-09-23
|
||||
|
||||
### Rename keeps implicit connections bound; the MCP server, as a preview
|
||||
|
||||
- **Rename no longer cuts a `.name` or `.*` connection.** Renaming a
|
||||
port `d` → `din` of `leaf` used to leave `leaf u (.*)` binding nothing
|
||||
and turn `.d` into `.din` against a parent with no net `din`; renaming
|
||||
the parent's net cut both bindings — and every case verified clean,
|
||||
because nothing records what an implicit connection binds. Now the
|
||||
binding is written out: `.d` becomes `.din(d)`, a `.*` that bound the
|
||||
port gains `.din(d)` beside it, and a renamed net `n` → `m` gives
|
||||
`.n(m)`. Every rewrite is listed in the rename's warnings; a case the
|
||||
engine cannot read — a `.*` into a module lucisv cannot see or finds
|
||||
declared twice, a list split by `ifdef`s, a hierarchical `bind` target,
|
||||
a `.*` that would start binding the new name — is refused with the
|
||||
reason. The verifier now prints every implicit binding before and after
|
||||
and refuses a mismatch, and accepts only the four spelled connection
|
||||
templates at the exact positions the rewrite writes them. The language
|
||||
server hands the engine one more hop of files (the modules a handed-over
|
||||
file instantiates), so a `.*` into a module declaring neither name is
|
||||
read rather than refused. A `bind` onto a bare instance name resolves
|
||||
through the instance table, so `clk_i`/`rst_ni`/`err_o` renames beside
|
||||
opentitan's fifo binds succeed. On opentitan copies: `prim_count`'s
|
||||
`err_o`, `aes_core`'s `clk_i` and `entropy_src`'s `clk_i` rename cleanly
|
||||
with their `.*` cov binds written out; `prim_fifo_sync`'s `clr_i` is
|
||||
refused over the FPV binds that really target fifo instances — the
|
||||
refusal the old engine silently skipped.
|
||||
(`docs/features/refactor-rename/README.md`, "Implicit connections".)
|
||||
- **`lucisv-mcp`, a Model Context Protocol server for coding agents —
|
||||
preview.** A third binary, `cargo build --release -p lucisv_mcp`, MCP
|
||||
over stdio, built from the same library crates as the editor and the
|
||||
CLI and sharing no code path with either. Twenty-three tools:
|
||||
`project_overview`, `list_units`, `unit_interface` (ports, parameters,
|
||||
a paste-ready instantiation), `outline`, `read_item` (one module,
|
||||
function or `always` block — not the file), `search_symbols`,
|
||||
`defines`, `definition`, `references`, `hierarchy`, `diagnostics`
|
||||
(what `lucisv check` says, with the CLI's JSON field names), and the
|
||||
edit tools `format`, `fix_lint`, `rename`, `expand_wildcard`,
|
||||
`convert_ports`, `organize_imports`, `inline_module`,
|
||||
`propagate_ports`, `remove_port`, `add_port`, `extract_module`,
|
||||
`instantiate` — every edit verified by the same engines, all-or-nothing,
|
||||
re-read before the first write, inside the roots only, with `dry_run`
|
||||
returning the diff. Answers are from disk (never an unsaved buffer),
|
||||
fresh at every call, rendered for a token budget. Try it from a
|
||||
checkout with Claude Code
|
||||
(`claude mcp add lucisv -- /path/to/lucisv-mcp --root .`), Cursor
|
||||
(`.cursor/mcp.json`) or VS Code (`.vscode/mcp.json`, `"type": "stdio"`).
|
||||
Not yet inside the `.vsix` and not yet reading the editor's index
|
||||
cache — those are the next lanes (`docs/mcp/PLAN.md`, `TODO-MCP.md`;
|
||||
feature READMEs `docs/features/mcp-*`).
|
||||
- **CLI:** `--diff` output is unchanged; its printer now lives in
|
||||
`lucisv_core::diff`, shared with the MCP server's `dry_run`.
|
||||
|
||||
## 0.55.0 — 2026-09-17
|
||||
|
||||
### Loop 3, round 2 — find-references reaches a module's internals
|
||||
|
||||
- **References see every cross-file use of a module's nets, variables
|
||||
and instances.** With `module leaf` declaring `logic sig` and another
|
||||
file writing `assign w = u_leaf.sig;` (or a `bind` directive naming
|
||||
`sig` in a connection), Find All References from the declaration
|
||||
answered `leaf.sv` alone — while a rename already edited both files.
|
||||
The two index questions behind references asked the module's
|
||||
*connection* surface (ports and parameters), which cannot hold an
|
||||
internal net; they now ask the *hierarchical* surface, the one a path
|
||||
in another file actually reaches the declaration by. Every answer for
|
||||
a port, parameter, package member, class field or struct field is
|
||||
byte-for-byte what it was. Hover's declaration snippet uses the same
|
||||
lookup and now shows the live line for such a signal in an edited
|
||||
buffer. On the opentitan tree, references on `aes.sv`'s
|
||||
`entropy_masking_req` now list `aes_bind.sv`, and `state_q` in
|
||||
`entropy_src_main_sm.sv` lists its use in `entropy_src_core.sv`.
|
||||
(`docs/features/references-hierarchical-surface/README.md`.)
|
||||
- **A closed declaring file's own uses are in the answer.** The index
|
||||
deliberately posts no in-file references for a module's internal
|
||||
signals (a table sized by every RTL body, for a rarely asked
|
||||
question), so a request from another file into a declaring file
|
||||
nobody has open used to list the cross-file sites and silently omit
|
||||
that file's own `assign … = sig;` lines. That one file is now parsed
|
||||
once, on exactly that request shape — 0.4–1.5 ms on a real design
|
||||
file, the same trade a rename already makes.
|
||||
- **A stale index may omit a location; it can never point at a wrong
|
||||
line.** Three QA rounds found that a span recorded at index time, or
|
||||
computed against one read of a closed file, could be rendered against
|
||||
a different read of the same file after an external edit (another
|
||||
tool, `git checkout`, a build step) and land on a line that no longer
|
||||
holds the name. Each closed file is now read exactly once per
|
||||
request, and every index-time span — closed files and the
|
||||
open-buffer declaration fallback alike — must still spell the name
|
||||
exactly where it is rendered, or it is dropped. Escaped identifiers,
|
||||
UTF-8 boundaries, a deleted declaring file and a name that is both a
|
||||
port and a net are covered by tests; references and rename are
|
||||
asserted to agree with the whole-scope engine.
|
||||
- Cost, accepted and recorded in `docs/perf/README.md`: a references
|
||||
request on a heavily used local net in a 40 000-line buffer now
|
||||
walks the indexed path, 1.22 → 1.54 ms median; every other harness
|
||||
row unchanged.
|
||||
|
||||
## 0.54.0 — 2026-09-12
|
||||
|
||||
### Loop 3, round 1 — a rename correctness fix and a faster first edit
|
||||
|
||||
- **Rename edits a `bind` file's own occurrences.** Renaming a module's
|
||||
internal net that a `bind` directive's connection names bare
|
||||
(`bind aes chk u (.req(entropy_masking_req))`), or reaches by a
|
||||
hierarchical path (`u_aes_core.u_aes_prng_clearing.seed_en`), used to
|
||||
leave the bind file untouched and say nothing — the design no longer
|
||||
elaborated after the rename. The resolver had asked the bind target's
|
||||
connection surface (ports and parameters) for a bare name, and rooted a
|
||||
bind's hierarchical path in the scope the directive is written in,
|
||||
which declares nothing. A bind connection is now a reference on the
|
||||
target's hierarchical surface, a bind's path is rooted at the target
|
||||
(a multi-segment target such as `bind tb.u_aes …` included), and an
|
||||
occurrence the engine cannot resolve is warned about by file and line,
|
||||
never silent. Definition, hover and references answer over bind files
|
||||
the same way. The index store format is bumped (`FACTS_FORMAT` 20): a
|
||||
0.53.0 store is rebuilt once. (Found by the previous round's QA on the
|
||||
opentitan tree.)
|
||||
- **The first request after an edit is ~19 % faster.** On a 40 000-line
|
||||
generated register file the first code-action menu after a
|
||||
one-character change costs 88 ms instead of 109: the lexer's raw and
|
||||
comment-attachment phases are fused (no intermediate token vector), the
|
||||
parser no longer clones a token it is about to discard, and the
|
||||
operator table is filtered by first byte before the longest-match
|
||||
scan. Token stream, diagnostics, AST and symbols are byte-for-byte what
|
||||
they were over 4 807 files; every formatter and linter output is
|
||||
identical.
|
||||
- `--verbose` timing lines carry a third group, `rebuild{…}`, that splits
|
||||
the document rebuild after an edit into its stages.
|
||||
- Known remainder, filed: cross-file *references* from a module's
|
||||
internal net (bind or not) still stop at the connection surface; the
|
||||
rest of the rebuild (the token clone, analysis, external resolution).
|
||||
|
||||
## 0.53.0 — 2026-09-09
|
||||
|
||||
### The 0.52.0 review — one correctness fix
|
||||
|
||||
- **A symlink-aliased directory is indexed once at startup.** 0.52.0's
|
||||
startup scan walks the open file's folder before the rest of the
|
||||
workspace, and the two walks kept separate visited sets: a directory
|
||||
reachable by two spellings (`a_alias -> z_real`) was indexed twice, so
|
||||
go-to-definition offered two targets and a valid rename was refused as
|
||||
ambiguous until the next rescan (found by the independent review of
|
||||
0.52.0). The two walks now share one directory identity; when an alias
|
||||
sorts before the open folder the scan takes the single canonical walk;
|
||||
an alias only the remaining walk can see requests one ordinary rescan
|
||||
so the spellings converge; and a same-named symlink to an open buffer
|
||||
is never a second copy of it. Startup, rescan and restart agree on
|
||||
index paths, definitions, rename and diagnostics across nine alias
|
||||
shapes, and a genuine duplicate declaration is still refused.
|
||||
- The load probe in `tools/perf/` primes a warm store before timing and
|
||||
stamps scan completion from the scan's own end event.
|
||||
- No performance number moved; the CLI is unchanged.
|
||||
|
||||
## 0.52.0 — 2026-09-09
|
||||
|
||||
### Performance take 5 — the review round
|
||||
|
||||
An independent review of 0.51.0 (`docs/performance_take5_review.md`)
|
||||
named four remaining costs with gates; all four are implemented and
|
||||
measured (`docs/perf/README.md`, the 2026-09-08 review-round entry).
|
||||
Behaviour is unchanged everywhere the suites and byte-identity gates can
|
||||
see; two pre-existing gaps the round found are filed, not hidden.
|
||||
|
||||
- **A rename refuses cheaply.** A cursor with no symbol used to read,
|
||||
parse and index every file in the workspace before refusing (2 s on
|
||||
opentitan); an engine-owned preflight now refuses from the request
|
||||
buffer alone in 0.3 ms with the same sentence and precedence. Refusals
|
||||
the workspace index would have to answer stay on the slow road, because
|
||||
a wrong rename refusal is terminal.
|
||||
- **One lint pass per buffer revision.** The diagnostics publish and the
|
||||
quick-fix discovery share one result, keyed by value on every input
|
||||
(rule set, options, width, tab width, waiver *contents*) and cleared by
|
||||
every index change; a cursor move on a 42 000-line file costs 1 ms
|
||||
instead of 23, and the navigation queued behind it likewise.
|
||||
- **The first answer after opening a file.** A workspace start now
|
||||
walks, indexes and publishes the open file's own folders before it
|
||||
discovers the rest of the workspace, one scan, every file once: the
|
||||
first go-to-definition answers in about 80 ms cold and 115 ms warm,
|
||||
correct every session, and a warm start settles under one second.
|
||||
- **Scans under load.** A scan publishes at most once per 512 files
|
||||
instead of once per burst of requests (a publish costs the size of the
|
||||
index): at the same offered load the median request wait falls from
|
||||
112 ms to 2 ms and the scan finishes about twice as fast. An empty
|
||||
navigation answer computed while the index is still growing is no
|
||||
longer an answer — it is asked again at the next publish or at the
|
||||
scan's end — and a cancel for such a request is honoured where it
|
||||
lands.
|
||||
- **Rename reuses the index's own records.** For the files a rename
|
||||
selects but never analyses, the engine now takes the index cache's
|
||||
record instead of parsing, and only when the file's bytes hash to what
|
||||
that record was written for. The hierarchical-tail rename falls from
|
||||
380 to 314 ms, the duplicate-module refusal from 2 s to 0.7 s; every
|
||||
edit and every warning byte-identical.
|
||||
- The CLI is unchanged in this release.
|
||||
|
||||
## 0.51.0 — 2026-09-08
|
||||
|
||||
### Performance take 5 — the implementation round
|
||||
|
||||
The owner's take-5 plan (`docs/performance_take5.md`) implemented end to
|
||||
end, each stage measured against the 0.50.0 reference on opentitan
|
||||
(`docs/perf/README.md`, 2026-09-08). Behaviour is unchanged everywhere the
|
||||
suites and the byte-identity gates can see; what changed is how much work
|
||||
the same answers cost.
|
||||
|
||||
- **Code actions stop repeating work.** A code-action request runs the
|
||||
lint pass and reads the project configuration only when the client asks
|
||||
for quick fixes or fix-all (`only: []` answers at once); the formatter's
|
||||
fence answer is computed only when a finding carries a fix and once per
|
||||
document revision; the four refactoring selectors read the document's
|
||||
own parse instead of re-parsing the buffer; the ports and
|
||||
organize-imports lightbulbs are answered from the plan-time checks with
|
||||
the same titles and counts, the click still recomputing and verifying.
|
||||
On opentitan's 42 192-line generated file a no-offer cursor move fell
|
||||
from 310 ms to 24 ms, and the navigation queued behind it with it; an
|
||||
offering cursor from 22 ms to 5.5 ms.
|
||||
- **Rename reuses its analysis; the verifier is untouched.** A rename
|
||||
parses and analyses each selected file once and builds its after-index
|
||||
from the edited files' fresh records; every check the verifier makes is
|
||||
the same code, re-attacked. The hierarchical-tail rename fell from 780
|
||||
to 388 ms (2.01×), an ordinary rename 141 → 92 ms, the extract command
|
||||
246 → 149 ms. A `--verbose` session now logs a per-stage rename trace.
|
||||
Topology handshake 33 is closed: inline-module's hierarchical-use
|
||||
refusal now sees every file whose tokens write the dissolved instance's
|
||||
name, including a `bind` in a file that instantiates nothing in the
|
||||
chain.
|
||||
- **The CLI's package census parses once.** With `unused-import` on,
|
||||
`check --select error,warning,style` no longer builds a one-file index
|
||||
for every file: the census reads package exports off its one parse and
|
||||
skips the nine files in ten that declare no package. The rule's cost on
|
||||
`hw/ip` fell from 142 ms to 5 ms; every output is byte-identical.
|
||||
- **Startup.** The server asks for the client's settings before its first
|
||||
scan (2 s bound for a client that never answers) and runs one scan at
|
||||
the answered scope — the empty default-scope scan is gone; the index
|
||||
store is not rewritten when nothing changed and is opened at the first
|
||||
step that needs it; the corpus is read a file at a time in its own step
|
||||
rather than all up front; the open buffers' folders are indexed first
|
||||
and the first navigation after opening a file is answered once that
|
||||
folder is published — correct in every session, at ~250–275 ms, where
|
||||
it used to be 84–208 ms or over a second depending on a race. Warm
|
||||
start 1.33 → ~1.05 s, warm idle RSS −15 to −20 %, the store
|
||||
byte-identical across sessions. `--verbose` logs a per-stage scan trace.
|
||||
- **The harness** (`tools/perf/`) records units, status, result counts and
|
||||
edit fingerprints on every row, measures the extract/inline commands for
|
||||
real, and is what every number above was taken with.
|
||||
|
||||
## 0.50.0 — 2026-09-07
|
||||
|
||||
### The format cache key; performance take 4
|
||||
|
||||
- **`uvm-utils-indent` is part of the format cache key.** In 0.49.0 a
|
||||
clean verdict cached under one setting of `[format] uvm-utils-indent`
|
||||
survived a toggle of the option, so `format --check` could exit 0 where
|
||||
`--no-cache --check` would reformat (found by the repository audit,
|
||||
topo handshake 34). The entry carries the option, the store line has it
|
||||
as a fourth field, and a 0.49.0 store is dropped entry by entry and
|
||||
rebuilt — never trusted, never an error. Regression through the real
|
||||
CLI in both toggle directions.
|
||||
- **Performance take 4** (`docs/performance_take4.md`): 0.49.0 against
|
||||
0.43.0 on opentitan, both binaries driven by one client in one hour.
|
||||
0.44.0's `didOpen` fix confirmed in the release build — 14× on the
|
||||
42 192-line file, 3–7× on ordinary RTL; the CLI unchanged and its
|
||||
formatter verdicts byte-identical on all five trees; the findings filed
|
||||
for the next loop: the lazy code-action offer 2–3 ms dearer per cursor
|
||||
move (the extract and inline gates re-parse a buffer the server already
|
||||
holds), the hierarchical-tail rename at 751 ms, the Style lint class
|
||||
1.27× after `unused-import`, the index 14% bigger at codec 19. The
|
||||
measurement harness now lives in `tools/perf/` and runs from a clean
|
||||
checkout.
|
||||
|
||||
## 0.49.0 — 2026-09-06
|
||||
|
||||
### Inline module; the last coverage gaps
|
||||
|
||||
- **Inline module.** With the cursor on `S u_S (...)`, `S`'s body is
|
||||
copied into the instantiating module: ports replaced by the connected
|
||||
names or literals, parameters as `localparam`s with the override or
|
||||
default, internal names prefixed `u_S_` only where the file already
|
||||
spells one of them, comments and attributes carried verbatim, `.name`
|
||||
shorthand connections inside the body expanded when their signal is
|
||||
renamed. Refuses — with a sentence — a `.*` or positional list, an
|
||||
expression connection, an unconnected port, an output into a literal,
|
||||
any hierarchical reference to the instance, a `generate`, `initial`/
|
||||
`final`, macros, directives, interface/`inout`/unpacked ports, and a
|
||||
module declared in the same file. `refactor.inline` action,
|
||||
`lucisv.inlineModule`. Extract → inline round-trips byte-equal after
|
||||
formatting.
|
||||
- **The verifier learns a copy.** A copied region's comments and
|
||||
attributes may be written once per copy in the destination while the
|
||||
copied file must appear in no edit at all; attack tests through the
|
||||
production entry, re-attacked by QA.
|
||||
- **The last coverage gaps.** Six language shapes now parse and format:
|
||||
`->>` non-blocking event triggers (with delay or event control), stream
|
||||
`with [range]` slices, the LRM's other cast bases (`(W+1)'(x)`,
|
||||
`logic [3:0]'(x)`), drive strength on a net declaration (`wire (strong0,
|
||||
weak1) w = a;` — its comment slots also fix a pre-existing refusal on
|
||||
`assign /*c*/ (weak0, pull1) x = y;`), `let` at statement position, and
|
||||
`#(min:typ:max)` clocking skews. `randsequence … endsequence` is a real
|
||||
node — productions, weighted alternatives, `rand join`, `repeat`,
|
||||
`if`/`case`, code blocks — printed one production per line; it was a
|
||||
parse error before and `randsequence` is now a keyword. Comment slots
|
||||
added to `let`, stream concatenations and the clocking grammar: the
|
||||
formatter's gap fuzzer covers 499 gaps at zero failures.
|
||||
- **`[format] uvm-utils-indent`** (editor `lucisv.format.uvmUtilsIndent`),
|
||||
default off: indents the `uvm_field_*` lines between
|
||||
`uvm_object_utils_begin`/`uvm_component_utils_begin` and their `_end`.
|
||||
On over the corpus it changes 21 files, all idempotent, no comment
|
||||
lost. A short comment-free enum body already prints on one line, so no
|
||||
key was added for it; the behaviour is pinned.
|
||||
|
||||
## 0.48.2 — 2026-09-06
|
||||
|
||||
### The 0.48.0 packages, rebuilt from the right commit
|
||||
|
||||
- **0.48.0's packages were built one commit early** — a release-chain
|
||||
slip tagged the version commit before the feature commit landed, and
|
||||
the tag was moved after the build had started — so its extension lacks
|
||||
the DUT-centred hierarchy view its notes describe. **0.48.1 never
|
||||
built**: its tag caught a concurrent lane's half-written verifier
|
||||
edits. 0.48.2 is the 0.48.0 tree, packaged from the commit that has
|
||||
the view. Nothing else changed.
|
||||
|
||||
## 0.48.0 — 2026-09-06
|
||||
|
||||
### A DUT-centred hierarchy view
|
||||
|
||||
- **Star a module as DUT** from the hierarchy pane's row menu (or the
|
||||
`lucisv.hierarchy.starDut` command, or a checked-in
|
||||
`lucisv.hierarchy.duts` setting, whose entries show locked). Each DUT
|
||||
gets two collapsible sections: the DUT with its instance subtree, the
|
||||
DUT at the very top, and the DUT's parents — an upward tree from the
|
||||
DUT through every module that instantiates it, transitively, which is
|
||||
where the DV bench lands. One section holds every other module: those
|
||||
in no DUT's subtree or ancestor chain, re-rooted where their only
|
||||
parents are DUT ancestors, so a monitor beside the DUT under the same
|
||||
bench stays visible. One DUT → three sections; two → five. A module
|
||||
both below one DUT and above another appears in both DUT sections.
|
||||
With nothing starred the pane is exactly as before. Client-only, over
|
||||
the hierarchy snapshot the server already sends.
|
||||
|
||||
## 0.47.0 — 2026-09-06
|
||||
|
||||
### Organize imports, extract module
|
||||
|
||||
- **Organize imports.** Removes the `import pkg::*;` lines nothing in the
|
||||
scope reaches through, merges exact duplicates and sorts the run at the
|
||||
top of a module, package or class; `source.organizeImports`, so an
|
||||
editor's organize-on-save runs it, and `lucisv.organizeImports`. "Used"
|
||||
is the binder's own lookup, read as a superset — over-keeping is the
|
||||
safe direction — and an `export pkg::…` in the same package counts as a
|
||||
use of its import (IEEE 1800 §26.6). It refuses rather than guesses
|
||||
wherever a macro call, a conditional directive, an unknown or
|
||||
twice-declared package, or a base class in another file could hide a
|
||||
use, which is why every opentitan UVM package (all carrying
|
||||
`` `include "uvm_macros.svh" ``) is refused. The same judgement is the
|
||||
new `unused-import` rule (Style, off by default, safe fix).
|
||||
- **Extract module.** Select whole module items and give a name: the
|
||||
items become a new module with ports inferred from dataflow across the
|
||||
selection (read only → `input`, written → `output`, written on both
|
||||
sides → refused), parameters passed through, used imports copied, and
|
||||
the selection replaced by an instantiation rendered from the new
|
||||
module's own text. Written to a new file when the client can create
|
||||
one, below the source module otherwise. Forty-three refusal sentences
|
||||
for what lucisv cannot judge (a routine argument, a hierarchical path
|
||||
crossing the boundary, an interface-typed name, a `typedef` of the
|
||||
source module, …). `refactor.extract` code action, `lucisv.extractModule`,
|
||||
and a name prompt in the VS Code extension. Inline module follows in a
|
||||
later release.
|
||||
- **The verifier's never-dropped ledger follows a move.** For the bytes
|
||||
an extraction moves, a comment or attribute deleted inside the moved
|
||||
region must land exactly once in the file the move names; a deletion
|
||||
outside the region stays an ordinary deletion that must be written
|
||||
back in its own file. Opt-in per edit, four equations, twelve attack
|
||||
pairs through the production entry, re-attacked by QA.
|
||||
|
||||
## 0.46.0 — 2026-09-05
|
||||
|
||||
### Two refactorings: expand `.*`, convert ports to ANSI
|
||||
|
||||
- **Expand `.*`.** A wildcard connection is written out as the named
|
||||
connections it stands for, in the module's declaration order, through
|
||||
the port engine's splice and verifier. The wildcard rule is read
|
||||
strictly (IEEE 1800 §23.3.2.4): a same-named net, variable or port
|
||||
binds; a parameter, genvar, type or instance does not, and that port
|
||||
becomes `.p()` with a warning naming it. Refused inside a `bind`
|
||||
directive, on a positional list, on two `.*`, or when a file does not
|
||||
parse. Code action `lucisv: expand .* (N connections)` and command
|
||||
`lucisv.expandWildcard`.
|
||||
- **Convert ports to ANSI.** A Verilog-2001 header with body
|
||||
declarations becomes an ANSI header (`output b; reg [7:0] b;` →
|
||||
`output reg [7:0] b`, every merge of §23.2.2.2), the absorbed
|
||||
declarations deleted and their comments carried onto the ports. The
|
||||
edit inserts around each header name so nothing that referenced the
|
||||
port moves; twenty-three shapes are refused with a sentence rather
|
||||
than guessed (port expressions, disagreeing ranges, initialisers,
|
||||
directives, a comment that would have to move into a one-line list).
|
||||
Code action `lucisv: convert ports to ANSI (N ports)` and command
|
||||
`lucisv.convertToAnsi`.
|
||||
- **The refactoring verifier's comment rule is stricter, and covers
|
||||
attributes.** Every comment and every `(* … *)` attribute a file had it
|
||||
still has, by exact text and count; a piece a deletion covers is
|
||||
written back exactly as many times as it was deleted, and an edit may
|
||||
not duplicate one nothing touched — which also catches a comment
|
||||
rewritten, truncated or duplicated. Ships with masked-corruption
|
||||
attack tests, re-attacked by QA.
|
||||
|
||||
## 0.45.0 — 2026-09-05
|
||||
|
||||
### Cross-file semantics: type spans, re-exports, hierarchical tails
|
||||
|
||||
- **Type names carry spans.** Every `DataType` and `disable` target knows
|
||||
its range on the AST; the semantic crate's text scanner (`scan.rs`) is
|
||||
deleted. Definition and hover on a type name land exactly, `pkg::t`
|
||||
selecting `t`; a segment the source spells differently from the
|
||||
parser's join is recorded with an empty range rather than guessed.
|
||||
- **Package re-exports are real references.** `export pkg::item;` and
|
||||
`export pkg::*;` bind both halves, the index records each package's
|
||||
re-exports, and definition, hover, completion after `pkg::`, references
|
||||
and rename follow them transitively. On opentitan a name reached only
|
||||
through `export spi_device_reg_pkg::SramDepth;` now resolves.
|
||||
- **Renaming an internal net edits its hierarchical uses in other files.**
|
||||
A module now has a hierarchical surface (nets, variables, instances)
|
||||
read only behind an instance head — `assign w = u_x.sig;` in another
|
||||
file renames with `sig`'s declaration, nested `u_a.u_b.sig` included —
|
||||
while connection lists still see ports and parameters only. Completion
|
||||
after `u_x.` in an expression lists the hierarchical members. Over
|
||||
opentitan's `hw/`, 514 hierarchical references resolve that did not
|
||||
before; a rename that now reaches one more file costs one more file's
|
||||
read.
|
||||
- The index facts format is 19; stores written by earlier releases are
|
||||
rebuilt on first use.
|
||||
|
||||
## 0.44.0 — 2026-09-05
|
||||
|
||||
### Opening a file no longer stalls the editor
|
||||
|
||||
- **`undriven-net` asked the workspace census once per declaration**,
|
||||
ahead of the local guards that silence almost every one, so a
|
||||
`didOpen` — and every keystroke flush — of a large file paid a walk
|
||||
over every indexed file thousands of times. Asked last now, the way
|
||||
its twin `unused-signal` always did. Opening opentitan's 42 192-line
|
||||
`pinmux_reg_top.sv` at workspace scope: 1 742 ms → 117 ms; typical
|
||||
IP files 51–95 ms → 5–8 ms. Same findings in the same order.
|
||||
- **Walk warnings.** An unreadable directory, an unreadable `.gitignore`
|
||||
or a dangling source-file symlink no longer fails a run: the CLI
|
||||
prints `warning: <path>: <message>` on stderr before the report with
|
||||
the exit code unchanged, and the server logs once per scan.
|
||||
- **A typo in `lucisv.lint.select` or `ignore`** is logged once
|
||||
(`lucisv.lint.select: unknown rule: <name>`) instead of silently
|
||||
emptying the selection.
|
||||
- **Inline aggregate types as parameter-override arguments**
|
||||
(`m #(.T(struct packed { logic a; })) u ();`) parse, format and are
|
||||
emitted by the instantiation skeleton.
|
||||
- **Comment slots inside delay lists** (`#( /*a*/ 1 : 2 : 3 )`, gate
|
||||
`#(rise, fall)`), and a line comment after a gate instance's comma
|
||||
now ends the line.
|
||||
|
||||
## 0.43.0 — 2026-09-05
|
||||
|
||||
### The repository analysis's three findings
|
||||
|
||||
- **Atomic writers cannot collide.** In-place writes use an exclusive,
|
||||
per-operation temp file (`.{name}.{pid}.{n}.lucisv-tmp`, created
|
||||
0600 when a target exists and given the target's mode before the bytes
|
||||
land); the CLI deduplicates its inputs by canonical identity, so a
|
||||
symlink alias of a file reaches one worker and is reported once. Two
|
||||
processes on one target remain last-writer-wins, which the formatter's
|
||||
idempotence makes safe.
|
||||
- **One lint-configuration contract.** The editor now honours a project's
|
||||
`[lint] select` and `[lint] ignore` the way the CLI honours its flags:
|
||||
`lucisv.lint.select` when set, else the project's, key by key, with the
|
||||
editor-only severity switches and per-rule toggles applied over whichever
|
||||
stands. A project entry the server cannot use — a rejected `[lint.<rule>]`
|
||||
option, an unknown rule name, a bad waiver directive — is logged once with
|
||||
file and line in `lucisv check`'s wording and dropped; the buffer keeps
|
||||
linting. The CLI's and the server's rule lists are asserted equal over
|
||||
the wire.
|
||||
- **Directory walks terminate on symlink cycles.** Each directory is
|
||||
entered once by identity; a link to a directory already entered is
|
||||
skipped, one not yet entered is followed once, a dangling directory link
|
||||
is skipped and a dangling source-file link is still reported. Both the
|
||||
CLI and the server's index scan.
|
||||
- A comment before a net delay's `#` (`wire /* c */ #5 w;`) now formats.
|
||||
|
||||
## 0.42.0 — 2026-09-05
|
||||
|
||||
### External waiver files, and the two vendor shapes the sweep skipped
|
||||
|
||||
- **External waiver files** in Verible's format: `waive --rule=<rule>
|
||||
[--line=N|N-M] [--location=<pattern>]`, `#` comments. Read from
|
||||
`[lint] waivers` in `lucisv.toml`, `lucisv check --waiver-file` (repeatable)
|
||||
and the editor setting `lucisv.lint.waivers`; the three add up.
|
||||
`--location` is an `--exclude`-style pattern, not a regex, and a
|
||||
regex-looking one is refused by name. Union with inline waivers; unused
|
||||
external waivers are reported under `unused-waiver` at their line of the
|
||||
waiver file by `lucisv check`, after the whole run. The editor's quick
|
||||
fixes and fix-on-save honour external waivers too.
|
||||
- **Rival module/interface headers across an `ifdef`/`else`** (opentitan's
|
||||
`jtag_if.sv`) now parse: the unit is kept verbatim as a whole, the
|
||||
standing directive-split trade, instead of nesting and losing its
|
||||
closer.
|
||||
- **A net delay after the type** (`wire [31:0] #0.1 x = y;`, where the LRM
|
||||
puts it) is accepted and printed where it was written.
|
||||
- Documentation: the repository analysis audit's README and site rewrite
|
||||
(architecture across all eight crates, topo facts at codec 17) is
|
||||
committed; its three findings are planned as TODO §41–§43.
|
||||
|
||||
## 0.41.0 — 2026-09-04
|
||||
|
||||
### Code actions off the fan-out
|
||||
|
||||
- **Lazy port refactorings.** For a client that supports
|
||||
`codeAction/resolve` (VS Code does), the port actions are offered from
|
||||
the buffer and the instantiated module's declaration alone, and the
|
||||
edit is computed when the action is picked. The request VS Code sends
|
||||
on nearly every cursor move no longer reads the module's fan-out:
|
||||
flat at ~55 µs in-process from a 3-file to a 128-file fan-out, where
|
||||
it was linear (15 ms at 128). A resolve for an action that no longer
|
||||
applies is an error, not an empty edit. Clients without resolve
|
||||
support get the edit up front, as before.
|
||||
- **Definitions from the index.** `textDocument/definition` and
|
||||
workspace symbols for a file-scope declaration in a closed file now
|
||||
build the location from the positions the index already records
|
||||
instead of reading the file: 0.4 µs against 28 µs per answer.
|
||||
- **inlayHint at the default scope**: investigated, not changed. The
|
||||
hints missing at that scope belong to a module declared outside what
|
||||
the scope reaches; definition and hover say the same. A scope
|
||||
question, recorded in the feature README.
|
||||
|
||||
## 0.40.0 — 2026-09-04
|
||||
|
||||
### Two parser residues and atomic writes
|
||||
|
||||
- **A bare `begin … end` at module scope, or straight inside
|
||||
`generate … endgenerate`, is recovered** in error-tolerant mode as an
|
||||
unnamed generate block (`ItemKind::GenBlock`) with a diagnostic at the
|
||||
keyword, instead of being refused and taking the rest of the unit with
|
||||
it. The items inside and after the block are now visible to the
|
||||
editor and to every lint rule; `module-begin-block`,
|
||||
`v2001-generate-begin` and `mismatched-labels` read the node. Strict
|
||||
parsing is unchanged, so the formatter still refuses the file exactly
|
||||
as before.
|
||||
- **A half-typed `#(` override or connection whose value would read as
|
||||
the next instance** (`sub #(.W(8), .DEPTH(` ⏎ `u0 (.a(x));`) now costs
|
||||
one error element: `.W(8)` survives, `u0` is an instance with its
|
||||
connections, one diagnostic on the unclosed `(`. The balanced-parens
|
||||
spelling stays ambiguous and is still parsed greedily, by design.
|
||||
- **In-place writes are atomic.** `lucisv format`, `lucisv check --fix`
|
||||
and the cache write a sibling temp file and rename it over the target,
|
||||
so a crash or a full disk never leaves a source file truncated. The
|
||||
target's permissions are kept, a symlink's *target* is what gets
|
||||
replaced, and a read-only file is refused as it always was.
|
||||
|
||||
## 0.39.0 — 2026-09-04
|
||||
|
||||
### The rest of Verible's rules
|
||||
|
||||
Nineteen more rules bring lucisv to **73** — every rule in Verible's
|
||||
published list except the one that needs a compiler. New: `module-begin-
|
||||
block`, `legacy-generate-region`, `legacy-genvar-declaration`,
|
||||
`v2001-generate-begin`, `explicit-function-lifetime`,
|
||||
`explicit-task-lifetime`, `positive-meaning-parameter-name`,
|
||||
`suggest-parentheses` (safe fix), `unpacked-dimensions-range-ordering`,
|
||||
`uvm-macro-semicolon`, `create-object-name-match`,
|
||||
`numeric-format-string-style`, `macro-string-concatenation`,
|
||||
`disable-statement`, `forbidden-macro` (`macros` option),
|
||||
`endif-comment` (safe fix), `forbid-line-continuations`,
|
||||
`dff-name-style`, `proper-parameter-declaration`.
|
||||
`invalid-system-task-function` gains a `symbols` option (Verible's
|
||||
"forbidden-symbol" is the same rule); `void-cast` gains
|
||||
`forbidden_calls`. The two lifetime rules deliberately exempt an
|
||||
out-of-body method definition (`function cls::f()`), which is where
|
||||
almost every finding on a UVM tree would otherwise land. Each rule's
|
||||
documentation cites the Verible rule and default it follows.
|
||||
|
||||
## 0.38.0 — 2026-09-04
|
||||
|
||||
### Lint rule options, and the Style family
|
||||
|
||||
**Per-rule options.** A rule that takes options can be configured in
|
||||
`lucisv.toml` (`[lint.line-length] length = 120`,
|
||||
`[lint.signal-name-style] style_regex = "[a-z_0-9]+"`) and from the
|
||||
editor (`lucisv.lint.options`, one object keyed by rule). Both doors run
|
||||
one validator: a bad key, kind, range or pattern fails `lucisv check`
|
||||
naming the file and line, and is logged and dropped in the editor so a
|
||||
typo cannot switch a rule off. Editor options win over `lucisv.toml`,
|
||||
key by key. `--rules-doc` lists every option with its kind and default.
|
||||
Patterns use a small built-in regex dialect (literals, `.`, classes,
|
||||
groups, alternation, `* + ?`, `\d \w \s`), whole-name anchored, run as
|
||||
a linear-time automaton so no pattern can slow a lint run; anything
|
||||
outside the dialect is refused by name.
|
||||
|
||||
**Eighteen new Style rules** (54 in all): `line-length` (the
|
||||
formatter's width), `posix-eof` (safe fix), `forbid-consecutive-null-
|
||||
statements` (safe fix), `generate-label`, `generate-label-prefix`,
|
||||
`package-filename`, `one-module-per-file` (off), `signal-name-style`
|
||||
(off), `interface-name-style`, `macro-name-style`,
|
||||
`constraint-name-style`, `parameter-type-name-style` (off),
|
||||
`port-name-suffix` (off), `banned-declared-name-patterns` (off),
|
||||
`typedef-enums`, `typedef-structs-unions`, `always-comb` (unsafe fix),
|
||||
`explicit-begin` (off). The four existing naming rules take Verible's
|
||||
option spellings. `typedef-structs-unions` allows a nested anonymous
|
||||
aggregate by default — a deliberate divergence from Verible, because
|
||||
every one of its 3 159 findings on opentitan was a generated register
|
||||
package; `allow_anonymous_nested = false` restores the stricter reading.
|
||||
|
||||
Every rule's toggle in VS Code is regenerated from the registry.
|
||||
|
||||
## 0.37.0 — 2026-09-04
|
||||
|
||||
### Typing a header no longer loses the module
|
||||
|
||||
While you type a port list, a parameter list, a function's argument
|
||||
list, an instantiation's connections, or the header of a `for`/`if`/
|
||||
`while`/`case`, the editor used to lose the whole surrounding module or
|
||||
function: its body re-parsed at file scope, its symbols vanished from
|
||||
the outline and from completion, and the orphaned `endmodule` produced a
|
||||
second error. Recovery now happens inside the list: the element that
|
||||
failed becomes an error element, the ones you already typed stay, the
|
||||
header keeps its node, and the body binds in the right scope. One
|
||||
diagnostic per typo. The strict parse (what the formatter uses) is
|
||||
untouched, so every corpus file formats byte for byte as before.
|
||||
|
||||
Measured over the corpus with every file cut in half: error nodes fall
|
||||
by 11 %; diagnostics rise by 7 % because a module whose header was cut
|
||||
now survives to report its missing `endmodule` instead of vanishing
|
||||
into one error node. Known gap: a half-typed `#(` override whose value
|
||||
can read as a call still collapses its instantiation (filed).
|
||||
|
||||
## 0.36.1 — 2026-09-04
|
||||
|
||||
The 0.36.0 tag never published: its release commit shipped without a
|
||||
CHANGELOG section (the release chain's draft lived in a session
|
||||
scratchpad that a crash had wiped), and the release workflow refuses a
|
||||
version without notes, as designed. 0.36.1 is 0.36.0 plus these notes.
|
||||
|
||||
## 0.36.0 — 2026-09-03
|
||||
|
||||
### The linter grows up: severities, per-rule toggles, and 19 new rules
|
||||
|
||||
Every lint rule now has a **severity** — `error` (would likely fail to
|
||||
compile or elaborate, or silently mis-synthesize), `warning` (a probable
|
||||
bug) or `style` — printed in `lucisv check` output
|
||||
(`FILE:LINE:COL: warning: message [rule]`), carried in the JSON output,
|
||||
mapped to red / yellow / blue in the editor, and shown in
|
||||
`--rules-doc`, which now groups rules by class. `--select`, `--ignore`
|
||||
and `[lint]` in `lucisv.toml` accept a severity word (`--ignore style`).
|
||||
|
||||
**Editor toggles.** VS Code settings gain three master switches
|
||||
(`lucisv.lint.severity.error`, `.warning`, `.style`) and one setting per
|
||||
rule (`lucisv.lint.rules.<rule>`: `default` / `on` / `off`), generated
|
||||
from the rule registry so the list can never drift. Precedence, top to
|
||||
bottom: defaults → `select` → severity switches → per-rule settings →
|
||||
`ignore`. Changing any of them re-checks every open file.
|
||||
|
||||
**New rules — Error**: `mismatched-labels`, `duplicate-declaration`,
|
||||
`undeclared-identifier` (with a project; silent for names that come
|
||||
from macros, `` `include``d fragments or hierarchical paths),
|
||||
`unknown-port`, `unknown-parameter`.
|
||||
**New rules — Warning**: `forbid-defparam`, `invalid-system-task-function`,
|
||||
`truncated-numeric-literal`, `undersized-binary-literal` (safe fix pads),
|
||||
`suspicious-semicolon`, `packed-dimensions-range-ordering`, `module-port`,
|
||||
`module-parameter`, `explicit-function-task-parameter-type`,
|
||||
`plusarg-assignment`, `instance-shadowing`, `forbid-negative-array-dim`,
|
||||
`void-cast`, `incomplete-assignment` (latch inference in `always_comb`).
|
||||
Verible equivalents are named in each rule's documentation; defaults
|
||||
follow Verible's except where the doc says why not. Existing rules
|
||||
re-classified: `multiply-driven` and `wire-reg-mixup` are errors.
|
||||
|
||||
Measured on opentitan: every false-positive class found was closed with
|
||||
a test; `lucisv check` over its `hw/` tree runs in the same time as
|
||||
0.35.0.
|
||||
|
||||
## 0.35.0 — 2026-09-02
|
||||
|
||||
### Format fences reach statements and class bodies
|
||||
|
||||
`// verilog_format: off` / `// lucisv: off` (and the `lucisv:` spelling)
|
||||
now protect statements inside `begin … end`, `fork … join`, function
|
||||
and task bodies and `always`/`initial`/`final` blocks, and items inside
|
||||
a class body — not only items at module scope. A fenced region is
|
||||
copied byte for byte, keeps its own indentation, and is a fixed point
|
||||
under a second pass; an unmatched `off` runs to the end of its own
|
||||
list. `--lines` range formatting honours a fenced statement inside the
|
||||
selected range. Four opentitan files that already carried fences inside
|
||||
functions and class bodies now keep those bytes.
|
||||
|
||||
One rule is applied uniformly: a fence must start its line (whitespace
|
||||
or a finished block comment may precede it). A fence written after code
|
||||
on the same line — `module m; // lucisv: off` — is an ordinary comment,
|
||||
as the fence documentation has said since the feature shipped; it used
|
||||
to open a region at module scope by accident.
|
||||
|
||||
Not yet fenceable, with reasons in the feature README: port lists,
|
||||
case-item label lists, same-line fences, and a property's local
|
||||
declarations.
|
||||
|
||||
## 0.34.0 — 2026-09-02
|
||||
|
||||
### Rename tells you what it could not reach
|
||||
|
||||
- **Macro arguments are named.** A rename now lists every file where the
|
||||
old name appears inside a macro invocation that the rename did not
|
||||
read (`` `uvm_info(..., $sformatf("%0d", sig)) `` in a file with no
|
||||
other relationship to the name), one warning per file, so nothing is
|
||||
silently left behind. Answered from a new per-file census in the
|
||||
index without reading any file (under a millisecond on opentitan).
|
||||
- The index store format changed (`FACTS_FORMAT` 17); it rebuilds once.
|
||||
|
||||
### Grammar
|
||||
|
||||
- **Modport method prototypes** (`modport mp (import task drive(int x),
|
||||
input clk);`) parse, format and resolve: hover on the prototype's
|
||||
name lands on the interface's task.
|
||||
- **Unnamed DPI formals** (`import "DPI-C" function int f(int, chandle);`)
|
||||
parse and format; an unnamed formal anywhere else is still an error.
|
||||
- `const /*c*/ ref` keeps its comment.
|
||||
|
||||
### CLI
|
||||
|
||||
- `lucisv check --rules-doc` prints the generated rule reference.
|
||||
|
||||
### Internal
|
||||
|
||||
- Every file over 1 200 lines was decomposed (parser, formatter, server,
|
||||
semantic and refactor crates) as pure moves with byte-identical
|
||||
output; `vlog_refactor`'s `Scope` moved to the crate root.
|
||||
|
||||
## 0.33.0 — 2026-09-02
|
||||
|
||||
### Assertions are code now
|
||||
|
||||
`property`/`sequence` declarations and concurrent assertions (`assert`,
|
||||
`assume`, `cover`, `restrict property`, `expect`, `cover sequence`,
|
||||
`default disable iff`) were verbatim text: kept byte for byte, invisible
|
||||
to everything else. They are real nodes now — every sequence and
|
||||
property operator (`##`, `[*n]`, `|->`, `|=>`, `throughout`, `within`,
|
||||
`intersect`, `until`, `implies`, `iff`, `nexttime`, `always`,
|
||||
`eventually`, `first_match`, `accept_on`…, property `if`/`case`, typed
|
||||
formals, local variables, match items) with the LRM's precedence, no
|
||||
new reserved words, and a byte-exact fallback for anything the grammar
|
||||
cannot take (it fires on none of 4 792 corpus and opentitan files).
|
||||
|
||||
- **Rename and references see inside assertions.** A signal named only
|
||||
in a property is renamed with its declaration; a property's formal is
|
||||
scoped to the property. Anything that still falls back warns instead
|
||||
of staying silent.
|
||||
- **Formatting**: one rule — the spec's top-level `|->`/`|=>`/`##`/
|
||||
`and`/`or` break one per line when the spec does not fit; everything
|
||||
else inline. 13 corpus and 36 opentitan files move, all inside
|
||||
assertion text; every `` `ASSERT* `` macro invocation is
|
||||
byte-identical.
|
||||
- Properties and sequences appear in document symbols; `undriven-net`
|
||||
sees a net driven or read inside an assertion.
|
||||
- The index store format changed; it rebuilds once after updating.
|
||||
|
||||
## 0.32.0 — 2026-09-02
|
||||
|
||||
### `bind` directives mean something now
|
||||
|
||||
- **Bind targets are real.** `bind top.gen[0].u_core chk u_chk (.clk(clk));`
|
||||
parses and formats with its indexed path; a lone target
|
||||
(`bind prim_fifo_sync …`) is a reference to the module, so go-to-
|
||||
definition and hover work on it. An instance path records nothing —
|
||||
no file knows an elaborated hierarchy, and a guess would be wrong.
|
||||
- **Bind connections resolve where the LRM says they live**: the
|
||||
`.port` half against the module being bound in, the expression half
|
||||
in the *target* module's scope first (then the workspace, then the
|
||||
scope the directive is written in). Hover on `.x(top_sig)` in a bind
|
||||
finds `top_sig` in the target.
|
||||
- The index store format changed (`FACTS_FORMAT` 15); it rebuilds once.
|
||||
|
||||
### Two macro-and-directive shapes that used to leave a file unformattable
|
||||
|
||||
- **A spaced macro call in an expression** — `assign x = \`WIDTH (a + b);`,
|
||||
a parameter override `` `MACRO (1) `` — keeps the author's space
|
||||
between the macro name and its `(`. The gap is token text (a macro
|
||||
defined with formals reads it differently), so the formatter keeps
|
||||
it rather than guessing; the safety net still refuses either
|
||||
rewrite.
|
||||
- **A conditional directive inside a connection value** — `.a(` ⏎
|
||||
`` `ifdef X `` ⏎ … ⏎ `` `endif `` ⏎ `)` — no longer turns the whole
|
||||
instantiation into opaque bytes: the directive region is kept
|
||||
byte-for-byte as a verbatim value, and the instantiation keeps its
|
||||
edge, code lens, hierarchy entry and port references. In opentitan
|
||||
the two `padring` instantiations in `chip_earlgrey_{asic,cw340}.sv`
|
||||
lay out canonically and gain their edges; the `` `ifdef `` that
|
||||
splits two instantiation *heads* (`tb.sv`) stays as it was.
|
||||
|
||||
### Editor
|
||||
|
||||
- **`lucisv.instantiate`** — an execute command
|
||||
(`[uri, position, module]`) that inserts the same instantiation
|
||||
skeleton the inline ghost offers, as plain text through
|
||||
`workspace/applyEdit`. For clients without inline completion; the
|
||||
Neovim README shows the keymap.
|
||||
|
||||
## 0.31.0 — 2026-09-02
|
||||
|
||||
### Comments are never dropped — now at every gap
|
||||
|
||||
A comment written between two tokens that no AST node owned was never
|
||||
deleted, but it was printed one node later, and the safety net refused
|
||||
the whole file for it (exit 2, no output). Three rounds had filed their
|
||||
leftovers (52 covergroup gaps, 41 fragment gaps, 40 constraint gaps) and
|
||||
plain RTL had never been measured. This release gives every such gap an
|
||||
owner: about seventy named comment slots across expressions (`q[/*c*/ i]`,
|
||||
`pkg /*c*/ ::name`, `x /*c*/ inside {…}`, casts, unary/postfix operators),
|
||||
statements (`if`/`case`/`for`/`foreach`/`do…while` headers, `@`/`#`
|
||||
timing, the gap before every `;`, block and generate labels) and
|
||||
declarations (qualifier runs like `pure /*c*/ static`, function/task
|
||||
headers and ports, module/package/class headers, typedefs, enums,
|
||||
structs, declarators, port lists, connections, instantiations).
|
||||
|
||||
Four exhaustive gap fuzzers — a `/*C*/` in every inter-token gap of
|
||||
fixture sets for covergroups (329 gaps), fragments (153), constraints
|
||||
(395) and ordinary RTL (352) — all format and re-format identically, and
|
||||
are the regression gate from here on. The formatter's output for every
|
||||
comment-free construct is unchanged: all 860 corpus files and 3 975
|
||||
opentitan files are byte-identical to 0.30.0. `verify.rs` is untouched;
|
||||
ten new attack pairs assert a comment moved across any newly slotted
|
||||
token is still refused.
|
||||
|
||||
- **Escaped names inside scoped names** (`\my-pkg ::\state-t` as a
|
||||
type, an instantiated module, a `bind` target) now keep their
|
||||
terminating space instead of being refused.
|
||||
|
||||
### Editor
|
||||
|
||||
- **Go to definition on a macro use** (`` `WIDTH ``, `` `uvm_info ``)
|
||||
jumps to the `` `define`` — the file's own definition first, otherwise
|
||||
every workspace candidate the include graph cannot rule out; nothing
|
||||
for a macro nothing defines.
|
||||
- **A cast's type is a reference.** `state_t'(0)` and `pkg::t'(x)` now
|
||||
light up find-all-references, go-to-type-definition and rename of
|
||||
the typedef (`FACTS_FORMAT` 13 → 14: the index rebuilds once).
|
||||
- **Rename warns about what it could not finish.** A `u_x.sig` whose
|
||||
module is indexed nowhere is left unchanged and now *named* — one
|
||||
line per file and unit — instead of silently skipped.
|
||||
|
||||
## 0.30.0 — 2026-09-02
|
||||
|
||||
Two lanes, run in parallel: semantic lints on by default, and the
|
||||
vendor/formal collateral grammar.
|
||||
|
||||
### Semantic lints on by default
|
||||
|
||||
`unused-signal`, `undriven-net` and `multiply-driven` shipped off
|
||||
because a per-file analysis cannot see a signal read or driven from
|
||||
another file's hierarchy. The index now carries a per-file identifier
|
||||
census (`FileFacts::words`, `FACTS_FORMAT` 12 → 13 — one harvest,
|
||||
which also builds the completion word table so the server no longer
|
||||
re-lexes every file at startup: scan time −28 %), and the linter gains
|
||||
a mention oracle: `unused-signal` and `undriven-net` say nothing when
|
||||
the name is mentioned in any other indexed file. The three rules are
|
||||
on whenever an oracle exists — always in the editor, and in the CLI
|
||||
when it walks a project — and stay off for a single file or stdin.
|
||||
With them came the missing off switch: `[lint] select = […]` /
|
||||
`ignore = […]` in `lucisv.toml` (CLI flags win key by key) and
|
||||
`lucisv.lint.select` / `lucisv.lint.ignore` in the editor.
|
||||
|
||||
Measured: corpus `unused-signal` 52 → 44 and `undriven-net` 3 → 0 with
|
||||
every silencing hand-checked as a genuine cross-file use, nothing
|
||||
added; across opentitan — lint-clean under its own tools — 14
|
||||
findings, spot-checked true. Store +14 %.
|
||||
|
||||
### Vendor and formal collateral grammar
|
||||
|
||||
The gap analysis ranked `specify`/UDP/`checker`/`interface class` as
|
||||
Medium on the strength of "13 corpus checker files"; the round's
|
||||
census found those were UVM protocol-checker *filenames*, and that
|
||||
every construct here has zero declarations in the corpus and in
|
||||
opentitan. So this is a completeness round for vendored cell, IO and
|
||||
memory models and formal collateral — and it is proven
|
||||
output-neutral: formatted output is byte-identical for all 860 corpus
|
||||
files and all 3 975 opentitan files against the previous release.
|
||||
|
||||
Five keywords reserved on a measured zero-collision census
|
||||
(`checker`, `endchecker`, `config`, `endconfig`, `library`); five
|
||||
deliberately not (`expect` has 41 real task-call sites — the statement
|
||||
form is recognised only when its parentheses hold a sequence operator).
|
||||
`specify … endspecify`, `primitive … endprimitive` with `table`,
|
||||
`checker … endchecker` and `config … endconfig` parse as opaque blocks
|
||||
that format byte-for-byte and fold in the editor; `library …;` lines
|
||||
parse; `specparam` is a real declaration that hovers and resolves;
|
||||
`alias a = b = c;` parses with every term a reference; `union tagged`
|
||||
formats; `interface class … endclass` parses as a class and
|
||||
`implements` now contributes supertypes to the type hierarchy. Filed:
|
||||
the `tagged` pattern grammar, checker/UDP names as instantiable
|
||||
symbols, the reverse `implements` edge.
|
||||
|
||||
## 0.29.0 — 2026-09-02
|
||||
|
||||
Fragment mode, and `` `define`` continuation.
|
||||
|
||||
The gap analysis had this one wrong in an interesting way: class-body
|
||||
and module-item `` `include`` fragments already parsed, because the
|
||||
file-scope item loop *is* the class-item loop. What did not parse were
|
||||
three narrower shapes — a bare statement list, an enum-member list
|
||||
(riscv-dv's `CUSTOM_1,` file, included between enum members), a
|
||||
covergroup-item list — and all three failed at one call site. They are
|
||||
now `SourceFile::fragment`, detected by a whole-file rule that cannot
|
||||
misfire on a valid file: the first structural item failed (directives,
|
||||
macros and stray `;` do not count, and a tolerant parse that quietly
|
||||
recorded a diagnostic counts as failed — an existing parity test
|
||||
caught `if … else` reading as a generate-if to one parser and a
|
||||
statement to the other), the file does not open with a design-unit
|
||||
keyword, and a shape consumes the file to its end, tried
|
||||
narrowest-first because the wider grammars mis-read the narrower. A
|
||||
fragment formats at indent zero through the existing printers, its
|
||||
declarations bind, and its enum variants are deliberately *not*
|
||||
exported (a package that includes the fragment is the real home of
|
||||
`CUSTOM_1`; resolving it elsewhere would name something that does not
|
||||
exist).
|
||||
|
||||
The other opentitan `.svh` that would not parse was never a fragment
|
||||
problem: a `` `define`` whose formal-argument list spans two lines with
|
||||
no backslash, which every tool accepts. The lexer now continues such a
|
||||
directive until the list closes.
|
||||
|
||||
Opentitan: 12 → 10 failing files, exactly the two predicted, nothing
|
||||
else moved. Corpus baseline 813 → 814 of 820. Comment-gap fuzzer:
|
||||
every remaining failing slot proven to fail identically outside a
|
||||
fragment (§2.9-22). Formatter output unchanged for every file that
|
||||
parsed before.
|
||||
|
||||
## 0.28.0 — 2026-09-02
|
||||
|
||||
Covergroup bodies — round 2 of coverage_gaps C1, closing it.
|
||||
|
||||
@@ -29,6 +29,54 @@ doing anything.
|
||||
- Match the style of the surrounding code (comment density, naming,
|
||||
module layout).
|
||||
|
||||
## File and function size
|
||||
|
||||
Files and functions are sized for a human reader, not a compiler.
|
||||
|
||||
- **Target 300–600 production lines per file.** At 800, consider
|
||||
splitting. Above 1,200, an explicit reason not to split goes in the
|
||||
feature README. Test lines do not count, but a `#[cfg(test)]` block
|
||||
that dwarfs its file moves to its own module or `tests/` file.
|
||||
- **Functions: 10–50 lines.** Investigate anything over 80; anything
|
||||
over 150 needs a reason in a comment (a dispatch table over an enum
|
||||
is the usual one).
|
||||
- Looser for declarative tables, generated code, snapshots and
|
||||
repetitive tests. Complexity matters more than the count: 800 lines
|
||||
of grammar productions read more easily than 250 lines of state.
|
||||
- **The real test is one sentence.** A human should be able to say what
|
||||
a file is responsible for in one sentence and predict which parts a
|
||||
change touches. Several "and" clauses mean the file wants to be
|
||||
several modules.
|
||||
- A split is a **pure move**: public paths stay the same (re-export from
|
||||
the old `mod`), behaviour and output stay byte-identical, the test
|
||||
count does not drop. Measured, not asserted — the corpus and
|
||||
opentitan byte-identity gates are the proof.
|
||||
|
||||
Measured 2026-09-02 (production lines): `vlog_parser/src/parser.rs`
|
||||
8 786, `vlog_formatter/src/format.rs` 5 444, `vlog_parser/src/ast.rs`
|
||||
3 313, `lucisv_server/src/server.rs` 2 559 (+6 300 test),
|
||||
`vlog_semantic/src/bind.rs` 2 378, `vlog_semantic/src/workspace.rs`
|
||||
1 975, `vlog_refactor/src/ports.rs` 1 778,
|
||||
`lucisv_server/src/completion.rs` 1 716 — thirteen files over 800.
|
||||
Every one of them was where feature lanes collided, which is the other
|
||||
reason to split them. **Decomposed the same day by TODO §28** (four
|
||||
lanes, pure moves, output byte-identical): `parser/` (19 modules) and
|
||||
`ast/` (8), `format/` (15), `server/` (11 + tests) and `completion/`
|
||||
(6), `bind/` (8), `workspace/` (5), `ports/` (6), `rename/` (4). Measured
|
||||
after the round (non-blank, non-comment, outside tests): two files over
|
||||
600 — `lucisv_server/src/perf.rs` 895 (one cohesive subsystem; the reason
|
||||
is in the decomposition-server README) and `vlog_parser/src/lexer.rs`
|
||||
762 — and 183 under it. Nothing new may push a file back over the
|
||||
thresholds: a dev adding to a file near 600 puts the code in a new
|
||||
module.
|
||||
|
||||
Re-measured 2026-09-07 at 0.49.0 (same rule, before `mod tests`): four
|
||||
files over 600 — `lucisv_server/src/state.rs` 958 (grew across §37–§49;
|
||||
a decomposition is filed as TODO §55: scope/widen, the document store,
|
||||
the source selectors are three sentences), `perf.rs` 900 (reasoned),
|
||||
`lexer.rs` 763, `vlog_formatter/src/format/stmt.rs` 604 (at the mark; the
|
||||
next statement arm goes in a new module) — and everything else under it.
|
||||
|
||||
## Rust standards
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
@@ -87,6 +135,20 @@ Rules:
|
||||
- Update `TODO.md`: check items your feature completes (leave the item
|
||||
text intact).
|
||||
|
||||
## Runaway guard (never run a suite or sweep bare)
|
||||
|
||||
On 2026-09-03 a background test run consumed 100 GB and crashed the
|
||||
machine. macOS enforces no memory cap, so the cap is ours:
|
||||
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
|
||||
process tree when its resident set or wall clock exceeds the limits
|
||||
(defaults 8 GB / 30 min).
|
||||
|
||||
- **Every `cargo test`, every fuzzer, every corpus or opentitan sweep,
|
||||
and every `lucisv`/`lucisv-server` run over a tree goes through
|
||||
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
|
||||
- A guard kill is a finding: report the command and the limit it hit;
|
||||
do not raise the limit to make it pass.
|
||||
|
||||
## Parallel lanes (the 2-agent loop)
|
||||
|
||||
Up to **two dev/QA lanes may run concurrently** when — and only when —
|
||||
|
||||
Generated
+24
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"vlog_formatter",
|
||||
"vlog_linter",
|
||||
"vlog_parser",
|
||||
"vlog_refactor",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,15 +262,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -264,19 +279,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+2
-1
@@ -9,10 +9,11 @@ members = [
|
||||
"crates/lucisv_core",
|
||||
"crates/lucisv",
|
||||
"crates/lucisv_server",
|
||||
"crates/lucisv_mcp",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.28.0"
|
||||
version = "0.56.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
|
||||
|
||||
Start with the [repository analysis](docs/repository-analysis.md) for a code-based
|
||||
assessment and [dependency topology](docs/topo.md) for interfaces and change
|
||||
impact. The [documentation site source](docs/site/README.md) contains usage
|
||||
guides and references; [CHANGELOG.md](CHANGELOG.md) records releases, and
|
||||
[TODO.md](TODO.md) tracks work in progress.
|
||||
|
||||
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
|
||||
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
|
||||
layout conventions and lint ergonomics borrowed from
|
||||
@@ -80,10 +86,9 @@ run over an unchanged tree skips them: the summary says `N files from cache`,
|
||||
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`, lucisv version)**
|
||||
per file, and only ever records the *already formatted* verdict — a file that
|
||||
would be reformatted, or that failed, is re-checked on every run, so
|
||||
`--check`'s exit codes and `--diff`'s output never go stale. The store is one
|
||||
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
|
||||
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`
|
||||
neither reads nor writes it, and `--cache-dir <PATH>` puts it elsewhere (the
|
||||
@@ -91,6 +96,10 @@ default is relative to the current directory). Content hashing is 64-bit
|
||||
FNV-1a and a lookup never crosses files; `docs/features/format-cache/README.md`
|
||||
states the collision posture, the semantics table and the concurrency story.
|
||||
|
||||
(In v0.49.0 only, `uvm-utils-indent` was missing from this key, so a cached
|
||||
clean verdict survived a toggle of the option — fixed in 0.50.0; a 0.49.0
|
||||
store is simply rebuilt.)
|
||||
|
||||
### Ignore files
|
||||
|
||||
While walking a directory, lucisv reads a `.gitignore` in every directory it
|
||||
@@ -106,6 +115,12 @@ trailing `/` (matches directories only), and `!` negation. **Not** supported:
|
||||
git's "already-tracked files are never ignored" rule. See
|
||||
`docs/features/parallel-files/README.md` for the exact subset.
|
||||
|
||||
Directory walks enter each directory once by identity, so symlink cycles
|
||||
terminate. Inputs resolving to one canonical file path are processed once.
|
||||
Unreadable directories or `.gitignore` files and dangling source links found
|
||||
during a walk warn on stderr and are skipped without changing the exit code;
|
||||
a missing explicitly named input is still an error.
|
||||
|
||||
## Configuration
|
||||
|
||||
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
|
||||
@@ -128,6 +143,10 @@ line-length = 100 # 40..400, same as --line-length
|
||||
indent = 2 # 1..8, same as --indent
|
||||
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
|
||||
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
|
||||
|
||||
[lint]
|
||||
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
|
||||
ignore = ["module-filename"] # removed after selection
|
||||
```
|
||||
|
||||
`filelist` names the project's sources the way the rest of the EDA world
|
||||
@@ -154,10 +173,16 @@ error (exit 2) and nothing is processed. Details:
|
||||
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
|
||||
with a file that sets only `line-length` uses both). `exclude` is the
|
||||
exception: config patterns are *added* to `--exclude`, not replaced by it.
|
||||
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
|
||||
off by default, indents the `` `uvm_field_* `` macros written between
|
||||
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
|
||||
formatting choice lucisv leaves to the project, because it changes bytes
|
||||
in existing UVM code (21 of the 860 corpus files).
|
||||
|
||||
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
|
||||
supported subset (tables, multi-line arrays, string escapes) is a hard error
|
||||
naming the file and line — exit 2, with nothing written. This is deliberate:
|
||||
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
|
||||
arrays, unsupported string escapes) is a hard error naming the file and
|
||||
line — exit 2, with nothing written. This is deliberate:
|
||||
a silently ignored `line_length` typo costs more than a strict parser does.
|
||||
|
||||
## Linting
|
||||
@@ -167,11 +192,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same
|
||||
`lucisv.toml` discovery.
|
||||
|
||||
```bash
|
||||
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
|
||||
lucisv check rtl/ # FILE:LINE:COL: severity: message [rule]
|
||||
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
|
||||
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
|
||||
lucisv check --ignore module-filename rtl/ # everything but these
|
||||
lucisv check --select error rtl/ # a whole severity class, by name
|
||||
lucisv check --fix rtl/ # apply the safe fixes, write files back
|
||||
lucisv check --rules-doc # the generated reference for every rule
|
||||
```
|
||||
|
||||
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
|
||||
@@ -179,35 +206,195 @@ violations remain, 2 error. Unlike the formatter, `check` uses the
|
||||
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
|
||||
what it can see.
|
||||
|
||||
| Rule | Fix | What it wants |
|
||||
|---|---|---|
|
||||
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
|
||||
| `no-trailing-whitespace` | safe | nothing but code before the newline |
|
||||
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
|
||||
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
|
||||
| `always-comb-blocking` | — | `=` inside `always_comb` |
|
||||
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
|
||||
| `module-filename` | — | a one-module file is named after its module |
|
||||
| `unused-waiver` | — | waivers that suppress nothing |
|
||||
| `unused-signal` † | — | no net or variable nothing uses |
|
||||
| `undriven-net` † | — | everything read is driven by something |
|
||||
| `multiply-driven` † | — | one driver per variable |
|
||||
### Severities
|
||||
|
||||
† Off by default — `--select` them. These three read the file's *symbol
|
||||
table*, not just its syntax, which is what lets them tell one `count` from
|
||||
another; they are off because a single-file analysis cannot see a signal used
|
||||
from another file's hierarchy. See
|
||||
`docs/features/semantic-lints/README.md`. The table above is not the whole
|
||||
set — naming-style rules ship too, and
|
||||
`cargo run -p vlog_linter --example rules_markdown` prints the generated
|
||||
reference for every rule with its default.
|
||||
Every rule is in one of three classes, and the class is the word that stands
|
||||
in the diagnostic line, in the JSON `severity` field, and in the editor's
|
||||
squiggle colour:
|
||||
|
||||
| Class | Means | Editor |
|
||||
|---|---|---|
|
||||
| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) |
|
||||
| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) |
|
||||
| `style` | correct, and reads badly | blue (LSP Information) |
|
||||
|
||||
A class name is accepted **wherever a rule name is** — on `--select`, on
|
||||
`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`:
|
||||
|
||||
```bash
|
||||
lucisv check --select error rtl/ # only the compile-breakers
|
||||
lucisv check --ignore style rtl/ # everything but the naming rules
|
||||
```
|
||||
|
||||
Every `error`-class rule follows one discipline: **silence beats a wrong
|
||||
accusation**. Each of them goes quiet whenever the run cannot answer — a file
|
||||
that did not fully parse, a module the project does not hold or holds twice, a
|
||||
name a macro produces, a fragment written to be `` `include``d. That is what
|
||||
makes an editor's red squiggle worth believing.
|
||||
|
||||
### The rules
|
||||
|
||||
| Rule | Severity | Fix | What it wants |
|
||||
|---|---|---|---|
|
||||
| `multiply-driven` † | error | — | one driver per variable |
|
||||
| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file |
|
||||
| `mismatched-labels` | error | — | `end : name` names the block it closes |
|
||||
| `duplicate-declaration` | error | — | each name declared once per scope |
|
||||
| `undeclared-identifier` † | error | — | every name is declared somewhere in the project |
|
||||
| `unknown-port` † | error | — | `.name(…)` is a port the module declares |
|
||||
| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares |
|
||||
| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` |
|
||||
| `always-comb-blocking` | warning | — | `=` inside `always_comb` |
|
||||
| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` |
|
||||
| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path |
|
||||
| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` |
|
||||
| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` |
|
||||
| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` |
|
||||
| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` |
|
||||
| `truncated-numeric-literal` | warning | — | a sized literal fits its width |
|
||||
| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written |
|
||||
| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` |
|
||||
| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension |
|
||||
| `module-port` | warning | — | more than one port is connected by name |
|
||||
| `module-parameter` | warning | — | more than one parameter is overridden by name |
|
||||
| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type |
|
||||
| `void-cast` | warning | — | `void'(…)` wraps a call |
|
||||
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
|
||||
| `undriven-net` † | warning | — | everything read is driven by something |
|
||||
| `unused-signal` † | warning | — | no net or variable nothing uses |
|
||||
| `create-object-name-match` | warning | — | `type_id::create("x")` names the handle `x` |
|
||||
| `forbidden-macro` | warning | — | no macro on the project's forbidden list |
|
||||
| `uvm-macro-semicolon` | warning | — | no `;` after a `` `uvm_* `` macro (off by default) |
|
||||
| `macro-string-concatenation` | warning | — | no `` `` `` inside a plain string (off by default) |
|
||||
| `disable-statement` | warning | — | `disable fork`, not a fork label (off by default) |
|
||||
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
|
||||
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
|
||||
| `empty-item` | style | safe | no `;` standing where an item belongs |
|
||||
| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` |
|
||||
| `module-filename` | style | — | a one-module file is named after its module |
|
||||
| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` |
|
||||
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
|
||||
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
|
||||
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
|
||||
| `line-length` | style | — | no line wider than the width the formatter uses |
|
||||
| `posix-eof` | style | safe | the file ends with a newline |
|
||||
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
|
||||
| `generate-label` | style | — | every generate block carries a `: label` |
|
||||
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
|
||||
| `package-filename` | style | — | a one-package file is named after its package |
|
||||
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
|
||||
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
|
||||
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
|
||||
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
|
||||
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
|
||||
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
|
||||
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
|
||||
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
|
||||
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
|
||||
| `one-module-per-file` | style | — | one `module` per file (off by default) |
|
||||
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
|
||||
| `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) |
|
||||
| `unused-waiver` | style | — | waivers that suppress nothing |
|
||||
| `unused-import` † | style | safe | no `import` nothing in the scope reaches through (off by default; stays off without a project) |
|
||||
| `explicit-function-lifetime` | style | — | `automatic`/`static` on a function outside a class |
|
||||
| `explicit-task-lifetime` | style | — | `automatic`/`static` on a task outside a class |
|
||||
| `positive-meaning-parameter-name` | style | — | no `disable`-prefixed parameter name |
|
||||
| `suggest-parentheses` | style | safe | `a ? (b ? c : d) : e`, parenthesized |
|
||||
| `unpacked-dimensions-range-ordering` | style | — | an unpacked dimension is `[0:N-1]` |
|
||||
| `module-begin-block` | style | — | no `begin`/`end` at module scope |
|
||||
| `v2001-generate-begin` | style | — | no bare `begin` in a generate region |
|
||||
| `forbid-line-continuations` | style | — | no `\` breaking a string literal |
|
||||
| `legacy-generate-region` | style | — | no `generate … endgenerate` wrapper (off) |
|
||||
| `legacy-genvar-declaration` | style | — | a genvar is declared in the `for` header (off) |
|
||||
| `endif-comment` | style | safe | `` `endif `` names what it closes (off by default) |
|
||||
| `numeric-format-string-style` | style | — | a radix prefix matches its specifier (off) |
|
||||
| `proper-parameter-declaration` | style | — | `parameter` in a header, `localparam` in a body (off) |
|
||||
| `dff-name-style` | style | — | a flip-flop is `_q`, its input `_d` (off by default) |
|
||||
|
||||
† On by default when lucisv can see a project (a multi-file CLI run or the
|
||||
language server), and off for a single file or stdin unless `--select` names
|
||||
them. These rules read the file's *symbol table* and ask the project about
|
||||
names, not just the file's syntax; the project-wide identifier census keeps a
|
||||
hierarchical use in another file from becoming a false positive. See
|
||||
`docs/features/semantic-lints-on/README.md` and
|
||||
`docs/features/linter-expansion-1/README.md`.
|
||||
|
||||
`lucisv check --rules-doc` prints the whole reference — every rule, its class,
|
||||
its default, its fix and the paragraph saying why it exists — generated from
|
||||
the registry, so it can never be out of date.
|
||||
|
||||
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
|
||||
that cannot change what the code means), `--unsafe-fixes` widens that — no
|
||||
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
|
||||
that cannot change what the code means), `--unsafe-fixes` widens that to the
|
||||
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
|
||||
`always_comb`, which is a different block at time zero and makes a second
|
||||
driver of its outputs an error — right nearly always, and not lucisv's call to
|
||||
make without being asked. Violations inside a `// verilog_format: off`
|
||||
region are reported but never fixed: `off` means hands-off for the linter too,
|
||||
so `--fix` leaves every byte of a fenced region exactly as written.
|
||||
|
||||
### Rule options
|
||||
|
||||
A rule can be configured in a `[lint.<rule-name>]` table:
|
||||
|
||||
```toml
|
||||
[lint]
|
||||
ignore = ["typedef-structs-unions"]
|
||||
|
||||
[lint.line-length]
|
||||
length = 120 # the linter's limit, if not the formatter's
|
||||
|
||||
[lint.generate-label-prefix]
|
||||
prefix = ["g_", "gen_"] # the label prefixes this project writes
|
||||
|
||||
[lint.parameter-name-style]
|
||||
localparam_style = "CamelCase" # Verible's own default, stricter than ours
|
||||
|
||||
[lint.signal-name-style]
|
||||
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
|
||||
```
|
||||
|
||||
The keys are Verible's wherever it has the same option, so a `.rules.verible`
|
||||
file translates word for word. An option nobody sets reads the default
|
||||
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
|
||||
value of the wrong kind, an integer out of range or a pattern that does not
|
||||
compile **fails the run**, naming the config file and the line — a typo in a
|
||||
lint setting is not something to guess at.
|
||||
|
||||
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
|
||||
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
|
||||
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
|
||||
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
|
||||
against the **whole** name, so `^`/`$` are accepted and redundant.
|
||||
|
||||
Everything else is **refused when the option is read, by name**: counted
|
||||
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
|
||||
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
|
||||
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
|
||||
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
|
||||
worse than an error you can read.
|
||||
|
||||
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
|
||||
length whatever shape the pattern has: no pattern can make `lucisv check` — or
|
||||
an editor session — hang.
|
||||
|
||||
From an editor the same options are one object, `lucisv.lint.options`:
|
||||
|
||||
```json
|
||||
"lucisv.lint.options": {
|
||||
"line-length": { "length": 120 },
|
||||
"typedef-structs-unions": { "allow_anonymous_nested": false }
|
||||
}
|
||||
```
|
||||
|
||||
There the precedence is **the editor's value, then the `lucisv.toml`, then the
|
||||
rule's default — key by key**: a project can set two options and one user
|
||||
override the third without losing the others. (This is the opposite order to
|
||||
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
|
||||
formatting has a byte-exact contract with CI, and which findings you are shown
|
||||
in your own editor is yours to choose.) A bad entry there is *ignored* and
|
||||
reported in the lucisv log rather than fatal, so one typo cannot leave a
|
||||
session with no diagnostics.
|
||||
|
||||
### Waivers
|
||||
|
||||
```systemverilog
|
||||
@@ -221,21 +408,82 @@ wire a; // lucisv: waive no-tabs suppresses that rule on this line
|
||||
works unedited — including waivers naming Verible rules lucisv has not
|
||||
implemented, which are ignored rather than reported. A waiver of lucisv's own
|
||||
that suppresses nothing, names an unknown rule or is malformed is reported
|
||||
under `unused-waiver`. External waiver files are not supported. Full rules:
|
||||
under `unused-waiver`.
|
||||
|
||||
Findings can also be suppressed from **outside** the RTL, in Verible's
|
||||
waiver-file format — one directive per line, `#` comments and blank lines
|
||||
ignored:
|
||||
|
||||
```text
|
||||
# every line of every file
|
||||
waive --rule=no-tabs
|
||||
# one line, or a range with both ends included
|
||||
waive --rule=line-length --line=12
|
||||
waive --rule=line-length --line=12-20
|
||||
# only the files a pattern names
|
||||
waive --rule=no-tabs --location=legacy/top.sv
|
||||
```
|
||||
|
||||
`--rule` is required and names exactly one rule (a severity word is not
|
||||
accepted). `--line` is 1-based. `--location` is matched the way an
|
||||
`--exclude` pattern is — `*` within one path component, a pattern with `/`
|
||||
matching a path suffix, one without matching the file name at any depth — and
|
||||
**not** as a regular expression; a pattern that looks like one (`.*`, `\.`,
|
||||
`[…]`) is an error naming the difference.
|
||||
|
||||
Waiver files come from three places, and they add up: `lucisv check
|
||||
--waiver-file <path>` (repeatable, relative to the working directory),
|
||||
`waivers` under `[lint]` in `lucisv.toml` (relative to that file; read by the
|
||||
CLI and the editor), and the editor setting `lucisv.lint.waivers` (relative to
|
||||
the first workspace folder). External and inline waivers are a union: a
|
||||
finding either covers is suppressed, and one both cover leaves neither
|
||||
reported as dead. A missing file or an unparsable directive fails `lucisv
|
||||
check` with `<file>:<line>: <message>` and exit 2; in an editor the bad line
|
||||
is dropped and the rest of the file applies, and the bad line is written once
|
||||
to the lucisv log whether the file was named by the editor setting or by
|
||||
`lucisv.toml`. Unused external waivers
|
||||
are reported under `unused-waiver` at their line of the waiver file, by
|
||||
`lucisv check` only and only after the whole run.
|
||||
Both front ends read the same configuration, and the editor's settings play
|
||||
the role the CLI's flags play: `lucisv.lint.select` when it is set, else
|
||||
`[lint] select` from the buffer's `lucisv.toml`, else the default set — and
|
||||
the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
|
||||
`lucisv.lint.rules.*` have no project counterpart and apply over whichever
|
||||
selection stands. Project per-rule options are read by both front ends. A
|
||||
project entry lucisv cannot use — an unknown rule name in `[lint]
|
||||
select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
|
||||
file or a directive that does not parse — fails `lucisv check` with
|
||||
`<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
|
||||
once to the lucisv log in the same words, and everything lucisv did
|
||||
understand still lints the buffer. Full rules:
|
||||
`docs/features/linter-core/README.md`.
|
||||
|
||||
## Architecture (the ruff mapping)
|
||||
|
||||
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
|
||||
generic pretty-printing IR, language formatting rules, and a thin CLI:
|
||||
The eight-crate workspace separates source syntax, reusable engines, project
|
||||
inputs, and the CLI/LSP front ends. The formatter follows ruff's separation
|
||||
of document layout from language rules:
|
||||
|
||||
| This repo | ruff equivalent | Role |
|
||||
|---|---|---|
|
||||
| `crates/vlog_parser` | `ruff_python_parser` + `ruff_python_ast` | Hand-written lexer and recursive-descent parser producing a comment-preserving AST |
|
||||
| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer |
|
||||
| `crates/vlog_formatter/src/format.rs` | `ruff_python_formatter` | Per-node formatting rules |
|
||||
| `crates/vlog_formatter/src/format/` | `ruff_python_formatter` | Per-node formatting rules, one module per grammar domain (`item`, `module`, `instance`, `decl`, `stmt`, `expr`, `class`, `cover`, `sva`, …) |
|
||||
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
|
||||
| `crates/lucisv` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
|
||||
| `crates/vlog_semantic` | — | File scopes and references, workspace index, conservative cross-file resolution |
|
||||
| `crates/vlog_refactor` | — | Verified rename/references, ports, imports, extract/inline module, instantiation plans |
|
||||
| `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement |
|
||||
| `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes |
|
||||
| `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities |
|
||||
|
||||
`vlog_parser` and `lucisv_core` have no dependencies. The formatter depends
|
||||
only on the parser; semantic analysis also depends only on the parser.
|
||||
Linting consumes the parser, semantics and `lucisv_core` (for the one
|
||||
`--exclude`-style matcher a waiver file's `--location` shares with the CLI);
|
||||
refactoring consumes the parser and semantics. The CLI reaches
|
||||
semantics through the linter and has no refactoring dependency. The server
|
||||
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
|
||||
including the linter’s and refactor’s formatter dependencies used only by tests.
|
||||
|
||||
Key ideas carried over from ruff/prettier:
|
||||
|
||||
@@ -248,8 +496,15 @@ Key ideas carried over from ruff/prettier:
|
||||
lists, expressions, concatenations) is a `Group`: it renders on one line if
|
||||
it fits within the line limit, otherwise it breaks one-element-per-line.
|
||||
A comment inside a group forces it to break.
|
||||
- **Idempotency as a hard invariant.** The test suite formats every fixture
|
||||
twice and asserts a fixed point.
|
||||
- **Verification on every formatting call.** The engine re-lexes input and
|
||||
output and compares normalized tokens, including comments. It then parses
|
||||
and formats the output again and requires a fixed point. Either check can
|
||||
reject the result; the caller retains the original file. This is a lexical
|
||||
safety net, not compiler elaboration or a proof of hardware equivalence.
|
||||
- **Two parsing modes.** Formatting uses strict parsing. Linting and the
|
||||
editor use tolerant parsing: failed elements become error leaves while
|
||||
valid siblings remain available for analysis. A lexer failure is still
|
||||
all-or-nothing. Neither mode performs cross-file macro expansion.
|
||||
|
||||
## Style
|
||||
|
||||
@@ -297,8 +552,8 @@ both layouts are fixed points of re-formatting:
|
||||
|
||||
### Turning the formatter off
|
||||
|
||||
Items between a `// verilog_format: off` and a `// verilog_format: on`
|
||||
comment are emitted as the exact source bytes they were written with,
|
||||
Everything between a `// verilog_format: off` and a `// verilog_format: on`
|
||||
comment is emitted as the exact source bytes it was written with,
|
||||
indentation included — the escape hatch for hand-aligned tables and the
|
||||
like. `// lucisv: off` / `// lucisv: on` is an accepted alias.
|
||||
|
||||
@@ -312,12 +567,30 @@ module m;
|
||||
endmodule
|
||||
```
|
||||
|
||||
The fence must be a line comment on its own line, and its text must match
|
||||
exactly — `// lucisv: off for now` is an ordinary comment, not a fence. An
|
||||
`off` with no matching `on` runs to the end of the enclosing item list
|
||||
(module body, package body, generate block, or the file). Fences select
|
||||
whole items; one written between two *statements* has no effect yet. Full
|
||||
rules: `docs/features/format-fences/README.md`.
|
||||
A fence works between **items** — module, package and class members, and
|
||||
top-level items — and between **statements**: inside `begin`…`end`,
|
||||
`fork`…`join*`, and function, task, `initial`, `always` and `final` bodies.
|
||||
|
||||
```systemverilog
|
||||
class scoreboard;
|
||||
function void build_phase();
|
||||
// verilog_format: off
|
||||
uvm_config_db#(cfg_t)::set(this, "env.agent", "cfg",
|
||||
cfg.agent_cfg); // hand-wrapped, left alone
|
||||
// verilog_format: on
|
||||
endfunction
|
||||
endclass
|
||||
```
|
||||
|
||||
The fence must be a line comment that begins its own line, and its text must
|
||||
match exactly — `// lucisv: off for now` is an ordinary comment, not a fence,
|
||||
and so is one written after code on the same line (`wire a; // lucisv: off`,
|
||||
`begin // lucisv: off`). An `off` with no matching `on` runs to the end of the
|
||||
enclosing list and no further: the module body, the class body, the
|
||||
`begin`…`end`, the function body, or the file. A fence inside a port list, a
|
||||
parameter list or a `case` **label** list is still an ordinary comment. Full
|
||||
rules: `docs/features/format-fences/README.md` and
|
||||
`docs/features/statement-fences/README.md`.
|
||||
|
||||
### Range formatting (`--lines`)
|
||||
|
||||
@@ -350,12 +623,19 @@ into ranges. Full semantics, including what happens at a range boundary:
|
||||
|
||||
## Supported syntax
|
||||
|
||||
v0.49.0 adds real `randsequence` productions; nonblocking `->>` event
|
||||
triggers with optional timing; streaming `with [range]`; constant-expression
|
||||
and packed-type cast bases; net drive strengths; statement-level `let`; and
|
||||
min:typ:max clocking skews. The parser, formatter and AST consumers share these
|
||||
nodes. See [coverage gaps](docs/coverage_gaps.md) for the dated survey and
|
||||
remaining semantic limits.
|
||||
|
||||
Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
|
||||
- Modules (ANSI and non-ANSI headers), packages, parameter ports,
|
||||
`import`, `timeunit`
|
||||
- Net/variable declarations (`wire`/`reg`/`logic`/`int`/... , signing,
|
||||
packed/unpacked dimensions, net delays), `parameter`/`localparam`,
|
||||
packed/unpacked dimensions, net delays and net drive strengths), `parameter`/`localparam`,
|
||||
`genvar`, `defparam`
|
||||
- `assign` (with delays), `always`/`always_comb`/`always_ff`/`always_latch`,
|
||||
`initial`/`final`
|
||||
@@ -397,24 +677,28 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
methods with `virtual`/`static`/`local`/`protected`/`automatic`, `function
|
||||
new`, `extern` and `pure virtual` prototypes and their out-of-body
|
||||
definitions, plus everything that already works at module scope (`typedef`,
|
||||
`localparam`, `import`, directives, macro items, nested classes). `constraint
|
||||
c { ... }` and `covergroup … endgroup` are **passed through verbatim** — two
|
||||
grammars with no layout convention worth inventing. See
|
||||
`docs/features/classes/README.md`
|
||||
`localparam`, `import`, directives, macro items, nested classes).
|
||||
`constraint c { ... }` and `covergroup … endgroup` are structured too:
|
||||
constraint expressions, `soft`/`dist`, implication, `foreach`, `solve
|
||||
before`, coverpoints, bins, transitions and crosses all format canonically
|
||||
and participate in rename, references and semantic lints. An unrecognized
|
||||
body rewinds to its exact source bytes instead of blocking the surrounding
|
||||
file. See `docs/features/constraint-bodies/README.md` and
|
||||
`docs/features/covergroup-bodies/README.md`
|
||||
- Concurrent assertions (IEEE 1800 §16): `assert`/`assume`/`cover`/`restrict
|
||||
property ( ... )` with an optional `label:` prefix and an action block
|
||||
(`else $error(...)`, `$info(...); else ...`, `else begin ... end`, and any
|
||||
statement that nests blocks: `if (c) begin ... end else ...`,
|
||||
`fork ... join_none`, `case ... endcase`), wherever
|
||||
a module item or a statement can appear — module and package bodies,
|
||||
generate regions, `begin`/`end`, and at file scope. Plus `sequence ...
|
||||
endsequence` and `property ... endproperty` declarations. All of it is
|
||||
**passed through verbatim**, for the same reason `constraint` is: the
|
||||
property/sequence expression language (`|->`, `##[1:3]`, `throughout`,
|
||||
`disable iff`, `$rose`) is a second grammar with no layout convention worth
|
||||
inventing. Only the first line is re-indented to the item's level; the
|
||||
relative layout the source wrote is what survives. See
|
||||
`docs/features/assertions/README.md`
|
||||
`fork ... join_none`, `case ... endcase`), wherever a module item or a
|
||||
statement can appear — module and package bodies, generate regions,
|
||||
`begin`/`end`, and at file scope. `sequence` and `property` declarations,
|
||||
typed formals, local variables, `expect`, `cover sequence`, and `default
|
||||
disable iff` are real nodes. The property/sequence expression grammar uses
|
||||
the LRM precedence table; top-level `|->`/`|=>`/`##`/`and`/`or` operators
|
||||
break one per line when needed. Rename, references, document symbols and
|
||||
semantic lints see inside; an unrecognized construct falls back to its exact
|
||||
source bytes and produces a rename warning. See
|
||||
`docs/features/sva-bodies/README.md`
|
||||
- Dynamic types: queues (`string q[$]`, bounded `[$:N]`), dynamic arrays
|
||||
(`int a[]`), associative arrays (`[*]`, `[string]`, `[key_t]`) — in
|
||||
declarations, class properties, typedefs and function/task arguments; the
|
||||
@@ -423,8 +707,8 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
`docs/features/dynamic-types/README.md`
|
||||
- DV statements (IEEE 1800 §7.12, §9.3.5, §11.12, §12.7.3, §13.4.2, §18.7,
|
||||
§18.16): `randomize() with { ... }` / `std::randomize(x, y) with { ... }`
|
||||
(the call is structural, the constraint block is **passed through
|
||||
verbatim**, exactly as `constraint c { ... }` is), the array-method
|
||||
(the call and its constraint block are structural, with byte-exact fallback
|
||||
for an unrecognized constraint shape), the array-method
|
||||
iterator argument `q.sum() with (item.w)`, `foreach` over a
|
||||
package-scoped or hierarchical array with selects on the way
|
||||
(`foreach (pkg::isa[i])`, `foreach (h[id].sub[k])`, `foreach (a[i][j])`),
|
||||
@@ -464,7 +748,8 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
trailing `;` is reproduced only if the source wrote one. At item and
|
||||
statement position a space before the argument list is accepted too
|
||||
(`` `uvm_field_int (a, UVM_DEFAULT) ``) and is reproduced as written; in
|
||||
*expression* position `` `A (b) `` still parses as a call applied to `(b)`.
|
||||
*expression* position the author-written gap is preserved too, because it
|
||||
can affect how a macro with formals is interpreted.
|
||||
A macro that ends its line is a complete macro, so whatever opens the next
|
||||
line — a declaration, or a statement starting with `@`, `#`, `->` or `{` —
|
||||
is its own item. See `docs/features/item-misc/README.md` and
|
||||
@@ -490,10 +775,17 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
(``sub #(`include "config.vh") u (...)``). See
|
||||
`docs/features/directives-in-lists/README.md` and
|
||||
`docs/features/directives-in-instances/README.md`
|
||||
- Programs, interface classes, `alias`, `union tagged`, `specparam`, library
|
||||
map entries, and statement-form `expect`. `specify`, UDP `primitive`/`table`,
|
||||
`checker`, and `config` blocks are recognized as opaque blocks so vendored
|
||||
simulation models and formal collateral do not block the rest of a file;
|
||||
their internal layout is preserved. See
|
||||
`docs/features/vendor-formal-grammar/README.md`
|
||||
|
||||
Not yet supported (parse errors). Roadmap ordered by measured impact on
|
||||
real RTL — see `docs/features/corpus-check/README.md` for the 820-file
|
||||
corpus baseline this ordering comes from:
|
||||
### Historical syntax roadmap
|
||||
|
||||
This roadmap records how parse coverage was raised, in measured-impact order.
|
||||
See `docs/features/corpus-check/README.md` for the 820-file corpus baseline:
|
||||
|
||||
1. ~~Macro invocation at module-item / statement position
|
||||
(`` `ASSERT_INIT(...) `` style)~~ — **done**; see
|
||||
@@ -574,8 +866,9 @@ corpus baseline this ordering comes from:
|
||||
`docs/features/dv-statements/README.md`. Emptied the `dv-statements`
|
||||
bucket (26 files) and moved the parse rate from 94.1% to 97.1%; 24 of the
|
||||
26 files format, the other 2 advanced to a macro-items blocker and to the
|
||||
`new obj` shallow-copy expression. `specify` blocks, `checker`,
|
||||
`program`, `interface class` and `randsequence` remain unsupported
|
||||
`new obj` shallow-copy expression. `randsequence` remained unsupported at
|
||||
this point; it shipped as real nodes in 0.49.0. The other vendor/formal
|
||||
constructs listed here landed in 0.30.0
|
||||
11. ~~A macro statement that ends its line followed by a symbol on the next
|
||||
one, the `new obj` shallow copy (IEEE 1800 §8.12), and a based number
|
||||
whose digits come from a macro (`` 32'h`DM_ADDR ``)~~ — **done**; see
|
||||
@@ -598,6 +891,11 @@ corpus baseline this ordering comes from:
|
||||
`` `X_EACH_CSR`` (need macro expansion, a deliberate non-goal) and 5
|
||||
files that are not valid standalone Verilog
|
||||
|
||||
Fragment-mode support subsequently raised the current frozen corpus baseline
|
||||
to **814/820 (99.3%)**. The remaining six files require cross-file macro
|
||||
expansion, contain a conditional-split outlier, or are not valid standalone
|
||||
Verilog; none regressed when the vendor/formal and SVA grammars landed.
|
||||
|
||||
Like ruff, `lucisv` refuses to output anything for a file it cannot fully
|
||||
parse, so it can never corrupt code.
|
||||
|
||||
@@ -610,6 +908,25 @@ go-to-definition, references and document/workspace symbols — the full list,
|
||||
and what is deliberately *not* advertised yet, is in
|
||||
`docs/features/lucisv-server/README.md`.
|
||||
|
||||
The editor now offers these refactorings alongside rename and port propagation:
|
||||
|
||||
| Action | Behavior |
|
||||
|---|---|
|
||||
| Expand wildcard | Replace `.*` with declaration-order named connections; unmatched ports become `.p()` with a warning |
|
||||
| Convert ports to ANSI | Merge a legacy module header and its body port declarations, preserving comments and attributes |
|
||||
| Organize imports | Remove unused imports, merge exact duplicates and sort a top-of-scope run; uncertainty keeps the action conservative |
|
||||
| Extract module | Move selected whole module items into a named module, infer its interface, and insert the replacement instance; create a file when supported or append below the source module |
|
||||
| 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).
|
||||
|
||||
In the VS Code hierarchy, **Star as DUT** groups a module’s children and
|
||||
parents into sections alongside Other Modules. Stars persist per workspace;
|
||||
`lucisv.hierarchy.duts` adds team-configured names, which are locked in the menu.
|
||||
|
||||
**VS Code needs no separate binary**: every release on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases) carries a
|
||||
platform-specific `.vsix` with both binaries inside it — pick yours
|
||||
@@ -669,8 +986,11 @@ vim.lsp.enable('lucisv')
|
||||
**Which files the server indexes.** A filelist if the project has one — the
|
||||
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
|
||||
(a path, absolute or relative to the workspace folder) — and then exactly the
|
||||
files it names. Otherwise the workspace folder, walked as the CLI walks it;
|
||||
and with no folder open at all, the current file's own directory. Open buffers
|
||||
files it names. Otherwise the default `lucisv.index.scope = "folder"` starts
|
||||
from open-file folders, widens by `lucisv.index.scopeDepth` (default 2), and stays bounded by
|
||||
the workspace roots; `"workspace"` walks the full roots. With no folder open,
|
||||
the server stays in the current file's directory: depth 0 scans it flat; a
|
||||
positive depth walks its descendants but never climbs to a parent. Open buffers
|
||||
are always indexed on top. A filelist that cannot be read warns and falls back
|
||||
to the folder walk, so the index is never silently empty.
|
||||
|
||||
@@ -701,11 +1021,20 @@ expected; no PRs or review required.
|
||||
|
||||
```bash
|
||||
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
|
||||
cargo test # unit + snapshot + idempotency tests
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
|
||||
```
|
||||
|
||||
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
|
||||
expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
|
||||
expected outputs only for intentional formatting changes with
|
||||
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
|
||||
Table-driven cases live in `crates/vlog_formatter/tests/cases/`; lint cases
|
||||
live in `crates/vlog_linter/tests/cases/`. All tests, fuzzers, and corpus/tree
|
||||
sweeps must run through `tools/guard.sh` (8 GiB RSS / 30 minutes by default),
|
||||
as required by [CLAUDE.md](CLAUDE.md). A guard kill is a finding, not a reason
|
||||
to increase the limit. Documentation build instructions are in
|
||||
[docs/site/README.md](docs/site/README.md).
|
||||
|
||||
## Install and releases
|
||||
|
||||
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
# TODO-MCP — the Model Context Protocol block
|
||||
|
||||
Planned 2026-09-23 by the lead at 0.55.0. The analysis and design are in
|
||||
[`docs/mcp/PLAN.md`](docs/mcp/PLAN.md); read it before touching any lane.
|
||||
This file is the tracking sheet for the block and stays separate from
|
||||
`TODO.md` on purpose: the block is independent of the LSP and CLI lanes, and
|
||||
its lanes collide with nothing in `docs/topo.md` except where a lane below
|
||||
says so.
|
||||
|
||||
Rules that apply to every lane, restated once: CLAUDE.md in full (guard
|
||||
every suite and sweep through `tools/guard.sh`; no `git commit`/`push`; a
|
||||
feature README kept current as you work; no file outside the lane's list;
|
||||
cross-module wants are Handshake requests, not edits); opentitan is
|
||||
read-only; no `sleep` over 60 s; `cargo fmt -p` per package while another
|
||||
lane is live. Each lane is one Opus dev then one Opus QA (owner's ruling
|
||||
2026-09-23: both Opus 5.5), working directly on trunk, then the lead's
|
||||
self-inspection and a commit; no release until every lane is done. A QA
|
||||
"rework" loops inside its lane.
|
||||
|
||||
## Fixed names (the wire shapes every lane pins by test)
|
||||
|
||||
| thing | name |
|
||||
|---|---|
|
||||
| crate / binary | `crates/lucisv_mcp` / `lucisv-mcp` |
|
||||
| arguments | `--root DIR` (repeatable; default cwd), `--filelist FILE`, `--index-cache DIR`, `--verbose`; anything else → `usage:` on stderr, exit 2 (the server's posture) |
|
||||
| vsix entry | `extension/bin/lucisv-mcp[.exe]` (platform), `extension/bin/<vsce-target>/lucisv-mcp[.exe]` (all) |
|
||||
| VS Code provider id | `lucisv.mcp`; settings `lucisv.mcp.enabled` (true), `lucisv.mcp.path` (""); command `lucisv.mcp.copyConfig` |
|
||||
| feature READMEs | `docs/features/mcp-transport`, `mcp-read-tools`, `mcp-navigation`, `mcp-edit-tools`, `mcp-structural-edits`, `mcp-packaging`, `mcp-cache-and-census` |
|
||||
|
||||
## M1. Transport and the read tools
|
||||
|
||||
**Files:** `Cargo.toml` (workspace `members` += `crates/lucisv_mcp`),
|
||||
`Cargo.lock`, everything under `crates/lucisv_mcp/` (`src/main.rs`,
|
||||
`transport.rs`, `rpc.rs`, `project.rs`, `render.rs`, `tools/mod.rs`,
|
||||
`tools/read.rs`, `tests/wire.rs`, `tests/fixtures/`), the two feature
|
||||
READMEs. Nothing else — in particular no change to any library crate; a
|
||||
missing public query is a Handshake entry.
|
||||
|
||||
- [x] crate skeleton: `main.rs` argument contract (table above), the
|
||||
`PARSE_STACK_SIZE` main thread, the ordered loop; `transport.rs`
|
||||
newline-delimited JSON-RPC over stdio (stdout protocol-only, stderr
|
||||
log-only; a line that is not JSON → `-32700`, never a crash)
|
||||
- [x] `rpc.rs`: `initialize` (version negotiation over a listed set, the
|
||||
pinned current revision first; `serverInfo`; `capabilities`;
|
||||
`instructions`), `notifications/initialized`, `ping`, `tools/list`,
|
||||
`tools/call` envelope (`content` text + `structuredContent`,
|
||||
`isError` for refusals), `notifications/cancelled` accepted, unknown
|
||||
method/tool/params → `-32601`/`-32602`
|
||||
- [x] `project.rs`: roots, `Discovery`, filelist-or-walk file set with the
|
||||
1 MiB cap, `IndexBuilder` build, lazy per-file `Semantics`, the
|
||||
per-call stat sweep + `update_file`/`remove_file` + re-walk policy
|
||||
(PLAN §4.4); a path outside every root is refused by name
|
||||
- [x] tools `project_overview`, `list_units`, `unit_interface` (ports,
|
||||
parameters, template via `instantiation_plan`; modports for an
|
||||
interface; exports for a package), `outline`, `read_item` (incl. the
|
||||
`always@<line>` spelling for unlabelled blocks), `search_symbols` —
|
||||
each with `inputSchema`, `annotations` (`readOnlyHint: true`), a
|
||||
one-sentence description written for the agent, and the compact
|
||||
rendering rules of PLAN §4.5
|
||||
- [x] `tests/wire.rs`: spawns the built binary; the handshake; every tool
|
||||
over a fixture tree of ≥ 6 files (a package, two modules with a
|
||||
`.*` instance, an interface with a modport, a class, a file with a
|
||||
parse error); a freshness test (edit a fixture on disk between two
|
||||
calls, second answer reflects it; delete one, it disappears;
|
||||
fingerprint equals a rebuild after each); a malformed-line test; a
|
||||
`--root` outside-path refusal
|
||||
- [x] README `mcp-transport`: Goal, Assumptions (why no `rmcp`; the pinned
|
||||
protocol revisions; sync one-at-a-time), Handshakes (none consumed
|
||||
beyond public APIs — list them), work log; README `mcp-read-tools`
|
||||
likewise, with the rendering rules as its contract
|
||||
- [x] gates through `tools/guard.sh`; sizes reported per file
|
||||
- [x] QA: protocol attacks (an `id` that is a string, a null `id`, a
|
||||
notification with an `id`, a 10 MB line, a request before
|
||||
`initialize`, an unsupported `protocolVersion`), rendering attacks
|
||||
(a unit named with an escaped identifier, a port with a packed and
|
||||
unpacked range, a file with CRLF line endings — line numbers must
|
||||
still be right), the freshness promise under a rename-then-recreate
|
||||
of a file within one second; verdict in the QA logs
|
||||
|
||||
## M2. Navigation, diagnostics, resources
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/nav.rs`, `resources.rs`,
|
||||
`tools/mod.rs` (registry entries only), `rpc.rs` (the three `resources/*`
|
||||
methods), `tests/wire.rs` (additions), the `mcp-navigation` README.
|
||||
Depends on M1 merged.
|
||||
|
||||
- [x] `definition` (selector: `file,line,col` or `name,unit?`; local via
|
||||
`Semantics::definition_of`, cross-file via `resolve_external`;
|
||||
ambiguity is a list), `references` (`vlog_refactor::find_references`,
|
||||
grouped by file, capped with `limit`/`offset`), `hierarchy` (down from
|
||||
`root` or every top-level module; `up` lists parents; parameter
|
||||
overrides as written; `depth`), `diagnostics` (parse errors,
|
||||
missing-closer warnings via the tolerant tree, lint through
|
||||
`select_rules` + the project's `[lint]` config + external waivers +
|
||||
an index-backed `MentionOracle`; the CLI's JSON field names), `defines`
|
||||
(table; one-step expansion when called with `name` + `args`)
|
||||
- [x] resources `lucisv://overview`, `lucisv://unit/{name}`,
|
||||
`lucisv://rules` (`rules_markdown()`), `lucisv://file/{path}/outline`;
|
||||
`resources/templates/list` for the two parameterised ones
|
||||
- [x] the opentitan parity census as an `#[ignore]` test taking the
|
||||
checkout path from an env var: `references`/`definition` on the
|
||||
`references-nav` symbols and `hierarchy` down from `top_earlgrey`
|
||||
compared with the LSP's answers recorded in that README (read-only;
|
||||
`git status` of the checkout identical before and after)
|
||||
- [x] README `mcp-navigation`; work log; gates; sizes
|
||||
- [x] QA: a `bind` connection's bare name, a `u_x.sig` tail, a name that
|
||||
is both a port and an internal net (must list both, not pick), a
|
||||
class member, a macro-only name (`files_naming_in_macros`), a
|
||||
`hierarchy` over a recursive/generate-instantiated module (must
|
||||
terminate with the depth cap), lint options from `lucisv.toml`
|
||||
honoured; verdict
|
||||
|
||||
## M3. Edit tools (wrapping the verified engines)
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/edit.rs`, `apply.rs`, `tools/mod.rs`
|
||||
(entries), `tests/wire.rs` (additions), `tests/fixtures/` (additions), the
|
||||
`mcp-edit-tools` README. Depends on M2 merged and on the ruling for
|
||||
Handshake MCP-1 (the diff lift) — until MCP-1 lands, `apply.rs` carries a
|
||||
private copy of `unified` marked `// TODO(MCP-1)` and the README says so.
|
||||
|
||||
- [x] `apply.rs`: `RefactorEdit` → (`dry_run`) unified diff per file | the
|
||||
all-computed-then-written loop over `write_atomic`, refusing before
|
||||
the first write on any verifier failure; the summary (files, +/-
|
||||
lines, warnings, created); the "written N of M then failed" report
|
||||
- [x] `format` (`files[]` or `file` + `lines`, `dry_run`), `fix_lint`
|
||||
(`apply_fixes` through `fence::protected_regions`, safe fixes only),
|
||||
`rename`, `expand_wildcard`, `convert_ports`, `organize_imports`,
|
||||
`inline_module`, `propagate_ports`, `remove_port`, `add_port`,
|
||||
`extract_module` (`home`: new file / same file; the created file is
|
||||
written too), `instantiate` (text only; `style`) — every one with
|
||||
`destructiveHint: false`, `idempotentHint` where true
|
||||
- [x] the source-set rule: each refactor gets the whole in-scope file set
|
||||
(PLAN §2.1 — the server narrows; MCP does not, so it can never be
|
||||
narrower than the engine needs); the README states the cost on
|
||||
opentitan and M6 measures it
|
||||
- [x] tests: every tool `dry_run` then real on the fixtures; run twice →
|
||||
second run is a no-op with an empty diff; a refusal leaves the
|
||||
fixture tree byte-identical (hash the tree before/after); an
|
||||
`extract_module` into a new file; a rename that touches three files;
|
||||
a `fix_lint` whose finding sits in a format fence (must not touch it)
|
||||
- [x] README `mcp-edit-tools`; Handshake MCP-1 filed there with the exact
|
||||
move; work log; gates; sizes
|
||||
- [x] QA: an edit whose target file changed on disk between the stat
|
||||
sweep and the write (the freshness promise vs the write — the write
|
||||
must be refused, not applied over the newer bytes; the dev states the
|
||||
mechanism); a read-only file; a path through a symlink leaving the
|
||||
root; concurrent `lucisv --check` on the same tree; a CRLF file
|
||||
through `format`; verdict
|
||||
— done 2026-09-23 (Opus, two rounds + lead fixes): pass for the lane;
|
||||
the write path held under a 50 ms writer race, chmod 444, symlinked
|
||||
escapes and a concurrent CLI; `format`/`fix_lint` byte-identical to
|
||||
the CLI. Findings ruled: skipped files refuse a whole-word match;
|
||||
whole-set tools re-walk first. **Open, out of lane:** the engine's
|
||||
rename breaks `.*`/`.name` shorthand connections → M3.5 below.
|
||||
|
||||
## M3.5. Rename vs implicit connections (inserted 2026-09-23 after M3 QA)
|
||||
|
||||
**Files:** `crates/vlog_refactor/src/rename/**`, `crates/vlog_refactor/src/check/**`
|
||||
only if the verifier must learn the shape, `crates/vlog_refactor/tests/`
|
||||
(or the crate's test modules), `docs/features/refactor-rename/README.md`
|
||||
(a dated section), `crates/lucisv_mcp/src/tools/edit.rs` (drop the
|
||||
known-limit sentence) + `tests/qa_m3.rs` (un-ignore finding 1), `TODO.md`
|
||||
(one line under the §8 rope-port refactorings noting the fix). An engine
|
||||
lane: the LSP's rename inherits the fix.
|
||||
|
||||
- [x] `vlog_refactor::rename` rewrites implicit connections: renaming a port
|
||||
`p` → `q` turns `.p` into `.q(p)` and adds `.q(p)` beside a `.*` that
|
||||
bound it (explicit connections beside `.*` are legal); renaming a net
|
||||
`n` → `m` in a module whose instantiations bind it through `.n` or `.*`
|
||||
turns `.n` into `.n(m)` and adds `.n(m)` beside the `.*`; comments and
|
||||
layout of the connection list preserved (append after the last
|
||||
connection, before the closing paren, on its own line when the list is
|
||||
one-per-line); every such rewrite listed in `warnings` so the user
|
||||
sees it; refuse (never guess) when the instantiation's port list
|
||||
cannot be read (`ifdef`-split, error element)
|
||||
- [x] the verifier sees the new edits as intended (no false "moved"
|
||||
refusal); attack tests: `.*` + explicit of the same port; nested
|
||||
instances; a `.name` whose net and port differ; a bind instance
|
||||
- [x] QA: attack the rewrite on opentitan copies (`prim_fifo_sync` ports
|
||||
under `.*` users); LSP parity via `vlog_refactor::rename` directly
|
||||
|
||||
|
||||
## M4. Structural edits (the one new verifier in the block)
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/item.rs`, `tools/mod.rs` (entries),
|
||||
`tests/wire.rs` and `tests/attacks.rs` (new), fixtures, the
|
||||
`mcp-structural-edits` README. Depends on M3 merged.
|
||||
|
||||
- [ ] `replace_item`, `insert_item`, `delete_item` with the PLAN §4.3
|
||||
contracts: bytes outside the span untouched (asserted by the test,
|
||||
not trusted), strict re-parse of the whole file (or no growth in
|
||||
tolerant error count when it did not parse before), one item at the
|
||||
position, the declared name matches unless `rename: true`,
|
||||
`delete_item` refuses over surviving references unless `force`
|
||||
- [ ] `tests/attacks.rs`, written by the dev, every case asserted
|
||||
**refused with the tree byte-identical**: a `text` opening a block it
|
||||
does not close; one that closes the enclosing module; one that
|
||||
re-declares a port; a UTF-8 boundary inside the span; an item inside
|
||||
a format fence; a file with an unterminated string; an `insert_item`
|
||||
after `end` — the CLAUDE.md invariant-4 discipline applied to the
|
||||
block's own verifier
|
||||
- [ ] README `mcp-structural-edits`: the contract as a table, the attack
|
||||
list, what the tool deliberately does not check (semantic sense of
|
||||
the new text)
|
||||
- [ ] gates; sizes (`item.rs` is expected to be the largest file in the
|
||||
crate; if it passes 600 lines the verifier moves to `item/verify.rs`)
|
||||
- [ ] QA: re-attack with at least eight new cases (a `text` that is two
|
||||
items; an empty `text`; a `text` equal to the old bytes — must be a
|
||||
no-op, not a refusal; a macro-bracketed item; a `generate` block
|
||||
target; an item whose leading comment is shared with the previous
|
||||
item's trailing one; a 40 000-line file for timing; `delete_item` on
|
||||
the last item of a module); verdict
|
||||
|
||||
## M5. Packaging and the extension (parallel with M2–M4)
|
||||
|
||||
**Files:** `tools/release.sh`, `tools/audit_artifacts.sh`,
|
||||
`tools/RELEASING.md`, `.gitea/workflows/ci.yml` (two lines: the MCP wire
|
||||
test is already in `cargo test`; add `node --test editors/vscode/*_test.js`),
|
||||
`editors/vscode/{package.json,package-lock.json,extension.js,mcp.js,
|
||||
mcp_test.js,mcp_smoke.js,.vscodeignore,README.md,CHANGELOG.md}`,
|
||||
`docs/site/src/content/docs/guides/agents.md` (new) and the guides index,
|
||||
`README.md` (an "Agents (MCP)" paragraph under Editor setup), the
|
||||
`mcp-packaging` README. May start once M1's binary answers `initialize` on
|
||||
trunk; touches no Rust. `extension.js` changes are limited to requiring
|
||||
`mcp.js` and calling its `activate(context)`.
|
||||
|
||||
- [ ] `release.sh`: stage `lucisv-mcp[.exe]` into `bin/` (platform) and
|
||||
`bin/<target>/` (all); `expect_vsix_bins` lists grow to three;
|
||||
`mcp_smoke.js` run against the host binary and against the one
|
||||
unzipped from the host vsix and the all-platforms vsix (mirror
|
||||
`smoke_embedded_server`); `audit_artifacts.sh` accepts the third name;
|
||||
the universal vsix still asserts no `extension/bin/*`
|
||||
- [ ] `mcp.js`: the three-rung binary ladder reusing `bundledBinary`;
|
||||
the guarded `registerMcpServerDefinitionProvider("lucisv.mcp", …)`
|
||||
with one `McpStdioServerDefinition` per workspace folder (`--root`,
|
||||
`--index-cache <storagePath>`, `cwd`, `version` from `package.json`),
|
||||
re-fired on folder changes; `lucisv.mcp.enabled` / `lucisv.mcp.path`
|
||||
read like `serverPath` (`inspect()`, blank = unset); the
|
||||
`lucisv.mcp.copyConfig` command with the three dialects (Claude Code
|
||||
`.mcp.json`, Cursor, VS Code `.vscode/mcp.json`) naming the resolved
|
||||
binary; `mcp_test.js` with a stubbed `vscode` (the `hierarchyView_test`
|
||||
pattern) covering the ladder, the guard on an old VS Code (no `lm`),
|
||||
and the three snippets
|
||||
- [ ] `package.json`: `contributes.mcpServerDefinitionProviders`, the two
|
||||
settings, the command + palette entry; engine stays `^1.82.0` unless
|
||||
`vsce package` refuses — then bump to `^1.101.0` and record why in the
|
||||
README and CHANGELOG
|
||||
- [ ] docs: the site guide page (install via vsix → nothing to do; Claude
|
||||
Code / Cursor snippets; the standalone `cargo build` line; the tool
|
||||
list generated from `tools/list` output, checked in); `README.md`
|
||||
paragraph; `tools/RELEASING.md` (three binaries; the smoke); the
|
||||
extension README and CHANGELOG
|
||||
- [ ] CI: `node --test editors/vscode/*_test.js` in `ci.yml`
|
||||
- [ ] README `mcp-packaging`; work log; `node --test` green; a local
|
||||
`tools/release.sh` (host only) producing a darwin-arm64 vsix with the
|
||||
three binaries, unzipped and checked
|
||||
- [ ] QA: install the vsix into a clean VS Code profile: the server listed
|
||||
under **MCP: List Servers**, trusted, `project_overview` answered in
|
||||
agent mode; `lucisv.mcp.enabled: false` removes it; a multi-root
|
||||
workspace registers one server per folder; the universal vsix on a
|
||||
machine without `lucisv-mcp` on PATH degrades to a clear output-channel
|
||||
line, not an error dialog; the Claude Code snippet pasted into a
|
||||
`.mcp.json` works from a terminal; rows in `docs/manual-acceptance.md`;
|
||||
verdict
|
||||
|
||||
## M6. Cache reuse, census, closing release
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/{project.rs,cache.rs}` (new `cache.rs`),
|
||||
`tests/` additions, `docs/mcp/census.md` (new), `docs/perf/README.md` (an
|
||||
MCP section), `docs/topo.md` (§1.1 node + §2.8 rows for `lucisv_mcp`, an
|
||||
§1.4 touch-set row), `docs/manual-acceptance.md`, `CHANGELOG.md`,
|
||||
`docs/repository-analysis.md` (the crate count and map row), the
|
||||
`mcp-cache-and-census` README, `TODO-MCP.md` (this file's closing entries).
|
||||
Depends on M4 and M5 merged.
|
||||
|
||||
- [ ] `cache.rs`: the read-only reader of the LSP's `index-cache` (header
|
||||
check on `CACHE_FORMAT`/`FACTS_FORMAT`/version, per-line checksum,
|
||||
`FileFacts::decode`, `record_path`); on `--index-cache DIR` a file
|
||||
whose `content_hash` has a record is `add_facts`'d instead of parsed;
|
||||
MCP's own `index-cache-mcp` written with the same codec on exit and
|
||||
read on start; never a write to the LSP's file (a test opens the
|
||||
store read-only and asserts its bytes after a full MCP session)
|
||||
- [ ] startup timing on opentitan cold / warm-from-LSP-store /
|
||||
warm-from-own-store, and the per-call stat sweep, recorded in
|
||||
`docs/perf/README.md` next to the LSP's scan trace numbers; the
|
||||
whole-set refactor cost from M3 measured on `rename` in `aes`
|
||||
- [ ] the token census (PLAN §8): the three tasks, each run twice (file
|
||||
tools only / with lucisv-mcp) by the same agent model, tokens in and
|
||||
out from the transcripts, written up in `docs/mcp/census.md` with the
|
||||
transcripts' task ids; if a task saved nothing, say so — the number
|
||||
is the deliverable, not its sign
|
||||
- [ ] `instructions` and tool descriptions revised from what the census
|
||||
transcripts show the agent misunderstood; `prompts/*` added only if
|
||||
the census shows a repeated multi-tool sequence worth one prompt
|
||||
- [ ] `docs/topo.md`: the `lucisv_mcp` node (`──▶` the six libraries; `-.spawn
|
||||
contract.->` from `editors/vscode`; `-.builds/packages.->` from
|
||||
`tools/`), the §2.8 rows, the Handshake MCP-1 status (delivered or
|
||||
still open), and MCP-3 filed in §2.9 if M2's hierarchy walk and the
|
||||
server's snapshot drifted
|
||||
- [ ] `CHANGELOG.md` section, `README.md` architecture table row (nine
|
||||
crates), `docs/repository-analysis.md` map row, CLAUDE.md measurement
|
||||
line refreshed with the new crate's sizes
|
||||
- [ ] release **0.56.0** (or the next minor free at the time): tag, CI
|
||||
green, 8 assets, the darwin-arm64 vsix unzipped and checked for three
|
||||
binaries, the MCP smoke in the release log; the install line and the
|
||||
`claude mcp add` line given to the owner
|
||||
- [ ] QA: the read-only promise on the LSP store attacked (a store with a
|
||||
torn last line; one from a different version; one whose record hash
|
||||
matches but whose facts checksum does not — each must be skipped, not
|
||||
trusted, and the file left byte-identical); a cold start with no
|
||||
store directory permission (must still answer, warn on stderr);
|
||||
the census transcripts spot-checked for a tool answer the agent had
|
||||
to correct by reading the file anyway (each is a finding against a
|
||||
tool's rendering); verdict
|
||||
|
||||
## Open questions for the owner (answer before the lane that needs it)
|
||||
|
||||
1. **Engine bump** (M5): if `vsce` accepts the contribution point on
|
||||
`^1.82.0`, keep it; if not, bump to `^1.101.0` and drop VS Code < 1.101
|
||||
users. The lane records which happened; no ruling needed unless the
|
||||
bump is unwelcome.
|
||||
2. **Whole-set refactors** (M3): MCP hands every refactor the full in-scope
|
||||
set. On opentitan that is a parse of ~3 000 files per `rename` unless
|
||||
`KnownFacts` from the cache is threaded through (M6 can). Acceptable for
|
||||
the first release, or should M3 already narrow with
|
||||
`files_mentioning` the way the server does?
|
||||
3. **Structural edits and the formatter** (M4): after `replace_item`, the
|
||||
agent's text is left as written. The alternative — format the replaced
|
||||
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`.
|
||||
+102
-5
@@ -71,6 +71,15 @@ pub struct Options {
|
||||
pub select: Vec<String>,
|
||||
/// `check` only: rules to drop from whatever `--select` left.
|
||||
pub ignore: Vec<String>,
|
||||
/// `check` only: external waiver files, relative to the current
|
||||
/// directory. They *add* to whatever `[lint] waivers` in a `lucisv.toml`
|
||||
/// names — a waiver file suppresses findings and can only ever suppress
|
||||
/// fewer of them by being left out, so there is nothing here for a
|
||||
/// command line flag to override.
|
||||
pub waiver_files: Vec<String>,
|
||||
/// `check` only: print the generated rule reference and exit, reading no
|
||||
/// file at all.
|
||||
pub rules_doc: bool,
|
||||
/// Files, directories, or the single input `-`.
|
||||
pub inputs: Vec<String>,
|
||||
/// `-f`: EDA filelists whose files are added to [`Options::inputs`].
|
||||
@@ -97,6 +106,12 @@ impl Options {
|
||||
if let Some(n) = self.indent.or(file.indent) {
|
||||
config.indent_width = n;
|
||||
}
|
||||
// `[format]` has no CLI flag: these keys change how already-clean
|
||||
// files look, so the project's own config is the only place that
|
||||
// turns one on.
|
||||
if let Some(on) = file.format_uvm_utils_indent {
|
||||
config.uvm_utils_indent = on;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
@@ -188,11 +203,26 @@ OPTIONS:
|
||||
CHECK OPTIONS (`lucisv check` only):
|
||||
--select <RULES> run only these rules (comma-separated, repeatable)
|
||||
--ignore <RULES> drop these rules from the set that would run
|
||||
|
||||
Three rules read the *project* rather than one file — `unused-signal`,
|
||||
`undriven-net`, `multiply-driven`. They run by default over more than one
|
||||
file, where lucisv can ask whether another file mentions a name, and stay
|
||||
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)
|
||||
--waiver-file <PATH> read waiver directives from this file; may be
|
||||
repeated, and adds to whatever `[lint] waivers`
|
||||
in a lucisv.toml already names
|
||||
--rules-doc print the rule reference — every rule, what it
|
||||
reports and whether it has a fix — as Markdown on
|
||||
stdout and exit 0. Generated from the registry, so
|
||||
it always describes the rules this build ships;
|
||||
takes no files and lints nothing
|
||||
|
||||
Suppress a finding with a comment: `// lucisv: waive <rule>` on the line
|
||||
itself or on the line above it, or a `// lucisv: waive-start <rule>` /
|
||||
@@ -200,6 +230,31 @@ CHECK OPTIONS (`lucisv check` only):
|
||||
accepted in place of `lucisv:`. A waiver that suppresses nothing is
|
||||
reported under the `unused-waiver` rule.
|
||||
|
||||
WAIVER FILES:
|
||||
Findings can also be suppressed from outside the RTL, in Verible's waiver
|
||||
file format — one directive per line, `#` comments and blank lines ignored:
|
||||
|
||||
waive --rule=<rule> every line of every file
|
||||
waive --rule=<rule> --line=12 one line
|
||||
waive --rule=<rule> --line=12-20 a range, both ends included
|
||||
waive --rule=<rule> --location=legacy.sv the files that pattern names
|
||||
|
||||
`--rule` is required and names one rule (a severity word is not accepted);
|
||||
`--line` is 1-based and a range includes both ends; `--location` is matched
|
||||
the way an `--exclude` pattern is — `*` within one path component, a
|
||||
pattern with `/` against a path suffix and one without against the file
|
||||
name. Unlike Verible's, it is **not** a regular expression, and a pattern
|
||||
that looks like one is an error rather than a silent mismatch.
|
||||
|
||||
lucisv reads `--waiver-file <PATH>` (relative to the current directory) and
|
||||
every path in `waivers` under `[lint]` in a `lucisv.toml` (relative to that
|
||||
file). An external waiver and an inline one are a union: a finding either
|
||||
covers is suppressed, and neither is then reported as dead. A file that
|
||||
does not exist, or a directive that does not parse, fails the run with
|
||||
`<file>:<line>: message` and exit 2. An external waiver that suppressed
|
||||
nothing anywhere in the run is reported under `unused-waiver`, at the line
|
||||
of the waiver file it was written on.
|
||||
|
||||
IGNORE FILES:
|
||||
While walking a directory, lucisv reads a `.gitignore` in every directory it
|
||||
enters and skips what it names; a deeper file overrides a shallower one and
|
||||
@@ -233,8 +288,13 @@ CONFIGURATION:
|
||||
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
|
||||
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
|
||||
read by lucisv-server only — the CLI reads a filelist only when `-f` names
|
||||
one, so `lucisv rtl/` always means the directory it was given). A command
|
||||
line flag overrides the file.
|
||||
one, so `lucisv rtl/` always means the directory it was given). One table
|
||||
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
|
||||
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
|
||||
paths, resolved against the config file's own directory). A command line
|
||||
flag overrides the file's corresponding key; the other keys still apply —
|
||||
`--waiver-file` is the exception, and adds to `waivers` rather than
|
||||
replacing it.
|
||||
|
||||
RANGE FORMATTING:
|
||||
`--lines` formats one construct at a time: an item whose lines meet a range
|
||||
@@ -281,6 +341,8 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
unsafe_fixes: false,
|
||||
select: Vec::new(),
|
||||
ignore: Vec::new(),
|
||||
waiver_files: Vec::new(),
|
||||
rules_doc: false,
|
||||
inputs: Vec::new(),
|
||||
filelists: Vec::new(),
|
||||
};
|
||||
@@ -360,6 +422,11 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let v = args.next().ok_or("--ignore requires a value")?;
|
||||
opts.ignore.extend(split_rules(&v));
|
||||
}
|
||||
"--waiver-file" => {
|
||||
let v = args.next().ok_or("--waiver-file requires a value")?;
|
||||
opts.waiver_files.push(v);
|
||||
}
|
||||
"--rules-doc" => opts.rules_doc = true,
|
||||
"-h" | "--help" => {
|
||||
print_help();
|
||||
std::process::exit(0);
|
||||
@@ -373,9 +440,16 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
s => opts.inputs.push(s.to_string()),
|
||||
}
|
||||
}
|
||||
// A filelist is an input like any other, so `-f files.f` alone is a
|
||||
// complete command line and needs no positional argument.
|
||||
if opts.inputs.is_empty() && opts.filelists.is_empty() {
|
||||
// `--rules-doc` prints the rule reference and reads nothing, so it is the
|
||||
// one invocation with no input at all — and being given one means the
|
||||
// caller expected files to be linted, which they would not be.
|
||||
if opts.rules_doc {
|
||||
if !opts.inputs.is_empty() || !opts.filelists.is_empty() {
|
||||
return Err("--rules-doc takes no files".to_string());
|
||||
}
|
||||
} else if opts.inputs.is_empty() && opts.filelists.is_empty() {
|
||||
// A filelist is an input like any other, so `-f files.f` alone is a
|
||||
// complete command line and needs no positional argument.
|
||||
return Err("no input files (try `lucisv --help`)".to_string());
|
||||
}
|
||||
// Repeating the flag is the same as one comma-separated list; both spell
|
||||
@@ -418,6 +492,8 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
|
||||
(opts.output_format != OutputFormat::Text, "--output-format"),
|
||||
(!opts.select.is_empty(), "--select"),
|
||||
(!opts.ignore.is_empty(), "--ignore"),
|
||||
(!opts.waiver_files.is_empty(), "--waiver-file"),
|
||||
(opts.rules_doc, "--rules-doc"),
|
||||
];
|
||||
let format_only = [
|
||||
(opts.check, "--check"),
|
||||
@@ -586,4 +662,25 @@ mod tests {
|
||||
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
|
||||
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiver_files_are_collected_in_order_and_are_lint_only() {
|
||||
let opts = parse(&["check", "--waiver-file", "a.waiver", "--waiver-file", "b", "rtl"])
|
||||
.expect("parsed");
|
||||
assert_eq!(opts.waiver_files, vec!["a.waiver", "b"]);
|
||||
assert!(parse(&["check", "rtl"]).unwrap().waiver_files.is_empty());
|
||||
assert!(parse(&["check", "--waiver-file"]).is_err(), "a value is required");
|
||||
assert!(parse(&["--waiver-file", "a.waiver", "rtl"]).is_err(), "not a formatter flag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_doc_is_the_one_check_that_needs_no_input() {
|
||||
assert!(parse(&["check", "--rules-doc"]).unwrap().rules_doc);
|
||||
// ... and refuses one, rather than accepting a path it would not read.
|
||||
assert!(parse(&["check", "--rules-doc", "rtl"]).is_err());
|
||||
assert!(parse(&["check", "--rules-doc", "-f", "a.f"]).is_err());
|
||||
// Lint-only, like every other `check` flag.
|
||||
assert!(parse(&["--rules-doc"]).is_err());
|
||||
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
|
||||
}
|
||||
}
|
||||
+4
-217
@@ -1,218 +1,5 @@
|
||||
//! A small line-oriented unified diff for `--diff`.
|
||||
//!
|
||||
//! The hunks are not a minimal edit script: on a divergence the two
|
||||
//! sides are resynchronized with a bounded forward search. That keeps
|
||||
//! the code short and the memory linear, at the cost of occasionally
|
||||
//! reporting a coarser change than GNU `diff` would.
|
||||
//! `--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.
|
||||
|
||||
/// Unchanged lines printed around each hunk.
|
||||
const CONTEXT: usize = 3;
|
||||
/// Unchanged lines that must line up before the sides count as resynced.
|
||||
const SYNC_RUN: usize = 3;
|
||||
/// How far ahead a resynchronization point is searched for.
|
||||
const MAX_SCAN: usize = 200;
|
||||
/// Pseudo-line standing in for a missing final newline.
|
||||
const NO_NEWLINE: &str = "\\ No newline at end of file";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Tag {
|
||||
Keep,
|
||||
Del,
|
||||
Ins,
|
||||
}
|
||||
|
||||
/// Renders the changes from `old` to `new` as a unified-style diff.
|
||||
/// Returns an empty string if the two texts are equal.
|
||||
pub fn unified(path: &str, old: &str, new: &str) -> String {
|
||||
if old == new {
|
||||
return String::new();
|
||||
}
|
||||
let old = split_lines(old);
|
||||
let new = split_lines(new);
|
||||
let edits = edits(&old, &new);
|
||||
let mut out = format!("--- {path}\n+++ {path}\n");
|
||||
render_hunks(&edits, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Splits into lines *keeping* each terminator, so a final line with no
|
||||
/// newline compares unequal to its terminated twin and shows up as a
|
||||
/// change, exactly as GNU diff treats it.
|
||||
fn split_lines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut rest = text;
|
||||
while !rest.is_empty() {
|
||||
let end = rest.find('\n').map_or(rest.len(), |p| p + 1);
|
||||
lines.push(&rest[..end]);
|
||||
rest = &rest[end..];
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn edits<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(Tag, &'a str)> {
|
||||
let mut out = Vec::new();
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < old.len() && j < new.len() {
|
||||
if old[i] == new[j] {
|
||||
out.push((Tag::Keep, old[i]));
|
||||
i += 1;
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((di, dj)) = resync(old, new, i, j) else { break };
|
||||
out.extend(old[i..i + di].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..j + dj].iter().map(|l| (Tag::Ins, *l)));
|
||||
i += di;
|
||||
j += dj;
|
||||
}
|
||||
out.extend(old[i..].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..].iter().map(|l| (Tag::Ins, *l)));
|
||||
out
|
||||
}
|
||||
|
||||
/// Finds the smallest pair of skip counts that puts the two sides back
|
||||
/// in step, preferring the shortest total divergence.
|
||||
fn resync(old: &[&str], new: &[&str], i: usize, j: usize) -> Option<(usize, usize)> {
|
||||
for d in 1..=MAX_SCAN {
|
||||
for k in 0..=d {
|
||||
for (di, dj) in [(d, k), (k, d)] {
|
||||
if i + di <= old.len() && j + dj <= new.len() && in_step(old, new, i + di, j + dj) {
|
||||
return Some((di, dj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn in_step(old: &[&str], new: &[&str], i: usize, j: usize) -> bool {
|
||||
let available = (old.len() - i).min(new.len() - j);
|
||||
if available == 0 {
|
||||
// Both sides running out together is a valid resync point.
|
||||
return old.len() - i == new.len() - j;
|
||||
}
|
||||
(0..SYNC_RUN.min(available)).all(|k| old[i + k] == new[j + k])
|
||||
}
|
||||
|
||||
fn render_hunks(edits: &[(Tag, &str)], out: &mut String) {
|
||||
// Line numbers each edit occupies on the old and the new side.
|
||||
let mut rows = Vec::with_capacity(edits.len());
|
||||
let (mut old_no, mut new_no) = (1usize, 1usize);
|
||||
for &(tag, text) in edits {
|
||||
rows.push((tag, text, old_no, new_no));
|
||||
match tag {
|
||||
Tag::Keep => {
|
||||
old_no += 1;
|
||||
new_no += 1;
|
||||
}
|
||||
Tag::Del => old_no += 1,
|
||||
Tag::Ins => new_no += 1,
|
||||
}
|
||||
}
|
||||
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let Some(first) = (start..rows.len()).find(|&r| rows[r].0 != Tag::Keep) else { break };
|
||||
let mut last = first;
|
||||
// Extend while the next change is close enough that its context
|
||||
// would touch this hunk's.
|
||||
loop {
|
||||
let reach = (last + 2 * CONTEXT + 1).min(rows.len());
|
||||
match (last + 1..reach).find(|&r| rows[r].0 != Tag::Keep) {
|
||||
Some(next) => last = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
let from = first.saturating_sub(CONTEXT);
|
||||
let to = (last + CONTEXT + 1).min(rows.len());
|
||||
render_one_hunk(&rows[from..to], out);
|
||||
start = to;
|
||||
}
|
||||
}
|
||||
|
||||
fn render_one_hunk(rows: &[(Tag, &str, usize, usize)], out: &mut String) {
|
||||
let old_count = rows.iter().filter(|r| r.0 != Tag::Ins).count();
|
||||
let new_count = rows.iter().filter(|r| r.0 != Tag::Del).count();
|
||||
let (old_start, new_start) = (rows[0].2, rows[0].3);
|
||||
out.push_str(&format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n"));
|
||||
for &(tag, text, _, _) in rows {
|
||||
let sign = match tag {
|
||||
Tag::Keep => ' ',
|
||||
Tag::Del => '-',
|
||||
Tag::Ins => '+',
|
||||
};
|
||||
out.push(sign);
|
||||
match text.strip_suffix('\n') {
|
||||
Some(body) => {
|
||||
out.push_str(body);
|
||||
out.push('\n');
|
||||
}
|
||||
None => {
|
||||
// patch(1) expects the marker bare, on its own line,
|
||||
// directly after the unterminated line.
|
||||
out.push_str(text);
|
||||
out.push('\n');
|
||||
out.push_str(NO_NEWLINE);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn equal_texts_produce_nothing() {
|
||||
assert_eq!(unified("f.sv", "a\nb\n", "a\nb\n"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_line_change_keeps_context() {
|
||||
let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n";
|
||||
let new = "1\n2\n3\n4\nX\n6\n7\n8\n9\n";
|
||||
let d = unified("f.sv", old, new);
|
||||
assert!(d.starts_with("--- f.sv\n+++ f.sv\n@@ -2,7 +2,7 @@\n"), "{d}");
|
||||
assert!(d.contains("\n-5\n+X\n"), "{d}");
|
||||
// Context is bounded: the first and last lines stay out of it.
|
||||
assert!(!d.contains("\n 1\n"), "{d}");
|
||||
assert!(!d.contains("\n 9\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distant_changes_become_separate_hunks() {
|
||||
let old: String = (0..40).map(|i| format!("{i}\n")).collect();
|
||||
let new = old.replace("\n1\n", "\nX\n").replace("\n30\n", "\nY\n");
|
||||
let d = unified("f.sv", &old, &new);
|
||||
assert_eq!(d.matches("@@ ").count(), 2, "{d}");
|
||||
assert!(d.contains("-1\n+X\n") && d.contains("-30\n+Y\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insertions_and_deletions_are_reported_separately() {
|
||||
let d = unified("f.sv", "a\nb\nc\n", "a\nb\nb2\nc\n");
|
||||
assert!(d.contains("+b2\n"), "{d}");
|
||||
assert!(!d.contains("-b\n"), "{d}");
|
||||
|
||||
let d = unified("f.sv", "a\nb\nc\nd\n", "a\nc\nd\n");
|
||||
assert!(d.contains("-b\n"), "{d}");
|
||||
// No insertions in the hunk body (the `+++` header line aside).
|
||||
assert!(!d.lines().skip(2).any(|l| l.starts_with('+')), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_final_newline_matches_patch_format() {
|
||||
// The unterminated line is the change; the marker follows it bare.
|
||||
let d = unified("f.sv", "a\nb", "a\nb\n");
|
||||
assert!(d.contains("-b\n\\ No newline at end of file\n+b\n"), "{d}");
|
||||
let d = unified("f.sv", "a\nb\n", "a\nb");
|
||||
assert!(d.contains("-b\n+b\n\\ No newline at end of file\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wholly_different_texts_diff_as_replacement() {
|
||||
let d = unified("f.sv", "a\nb\n", "x\ny\n");
|
||||
assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}");
|
||||
}
|
||||
}
|
||||
pub use lucisv_core::diff::unified;
|
||||
+467
-38
@@ -5,13 +5,20 @@
|
||||
//! is handed the same `(path, config)` job list `format` gets. Only what
|
||||
//! happens to one file differs.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::config::FileConfig;
|
||||
use rayon::prelude::*;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::Config;
|
||||
use vlog_linter::{apply_fixes, lint, Fix, ParsedSource, Rule, Violation};
|
||||
use vlog_linter::words;
|
||||
use vlog_linter::{
|
||||
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
|
||||
Violation, WaiverUse,
|
||||
};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::args::{Options, OutputFormat};
|
||||
@@ -22,6 +29,327 @@ use crate::args::{Options, OutputFormat};
|
||||
/// cap only bounds a rule that would fight itself forever.
|
||||
const MAX_FIX_ROUNDS: usize = 10;
|
||||
|
||||
/// One file to lint, with the rules the command line and its own
|
||||
/// `lucisv.toml` resolved to.
|
||||
pub struct Job {
|
||||
path: PathBuf,
|
||||
config: Config,
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
/// What this file's `lucisv.toml` configured about each rule, validated
|
||||
/// against the registry when the run was planned.
|
||||
options: RuleOptions,
|
||||
}
|
||||
|
||||
/// A whole `lucisv check` run: what to lint, and what the project says about
|
||||
/// names.
|
||||
pub struct Plan {
|
||||
jobs: Vec<Job>,
|
||||
/// The project's identifier census, built when at least one selected rule
|
||||
/// asks for a workspace and there is more than one file to ask about.
|
||||
census: Option<Census>,
|
||||
/// Every external waiver file the run reads, applied to every job.
|
||||
///
|
||||
/// One set for the whole run rather than one per file, because a
|
||||
/// `--location` pattern names files and a waiver is only *unused* when no
|
||||
/// file in the run matched it — a question only the whole run can answer.
|
||||
external: ExternalWaivers,
|
||||
/// Every rule name any job in the run has switched on, for deciding which
|
||||
/// external waivers never had a chance to fire.
|
||||
enabled: Vec<&'static str>,
|
||||
}
|
||||
|
||||
/// How many of the run's files write each identifier down.
|
||||
///
|
||||
/// The CLI's answer to the question the language server answers from its
|
||||
/// index: it has none, so it builds one — a read and a lex of every file in
|
||||
/// the run, before the first rule sees anything. Only the *counts* are kept;
|
||||
/// a rule asks about one name at a time and never about a file.
|
||||
pub struct Census {
|
||||
files: HashMap<String, u32>,
|
||||
/// Module or interface name → what it declares, `None` for a unit the run
|
||||
/// cannot answer for: a header carrying a compiler directive, or two
|
||||
/// declarations that disagree. Empty when no enabled rule asked for it —
|
||||
/// building it costs a parse of every file in the run.
|
||||
interfaces: HashMap<String, Option<vlog_linter::ModuleInterface>>,
|
||||
/// Package name → the names it exports, `None` for a package the run
|
||||
/// cannot answer for: one declared twice, or one re-exporting from
|
||||
/// another package (only a whole-project index settles that). Empty
|
||||
/// unless `unused-import` is enabled.
|
||||
packages: HashMap<String, Option<Vec<String>>>,
|
||||
}
|
||||
|
||||
/// What one file contributes to a [`Census`]: its words, the units it
|
||||
/// declares, and the packages it exports from.
|
||||
type PerFile = (
|
||||
Vec<String>,
|
||||
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
|
||||
Vec<(String, Option<Vec<String>>)>,
|
||||
);
|
||||
|
||||
/// One file's three contributions, off **one** parse.
|
||||
///
|
||||
/// The word census wants the tokens, the interface table wants the tree and
|
||||
/// the package table wants both — so a run that asks for either table lexes
|
||||
/// and parses the file exactly once and all three read that. A run that asks
|
||||
/// for neither never parses at all: `harvest_text` lexes and stops, which is
|
||||
/// what the word census alone needs.
|
||||
///
|
||||
/// A file that cannot be read contributes nothing, and so does one that does
|
||||
/// not lex (`harvest_text` and a `ParsedSource` with no tokens agree on that).
|
||||
/// The file's own check is what reports the error.
|
||||
fn harvest_one(job: &Job, interfaces: bool, packages: bool) -> PerFile {
|
||||
let Ok(src) = std::fs::read_to_string(&job.path) else {
|
||||
return (Vec::new(), Vec::new(), Vec::new());
|
||||
};
|
||||
if !interfaces && !packages {
|
||||
return (words::harvest_text(&src), Vec::new(), Vec::new());
|
||||
}
|
||||
let parsed = ParsedSource::parse(&src);
|
||||
let declared = match interfaces {
|
||||
true => vlog_linter::module_interfaces(parsed.file()),
|
||||
false => Vec::new(),
|
||||
};
|
||||
let exports = match packages {
|
||||
true => vlog_linter::package_exports_in(&job.path, parsed.file(), parsed.tokens(), &src),
|
||||
false => Vec::new(),
|
||||
};
|
||||
(words::harvest(parsed.tokens()), declared, exports)
|
||||
}
|
||||
|
||||
impl Census {
|
||||
/// The census of every file in the run, harvested in parallel.
|
||||
///
|
||||
/// A file that cannot be read or does not lex contributes nothing, which
|
||||
/// is the same all-or-nothing rule the rest of the run gives it: the
|
||||
/// file's own check reports the error.
|
||||
///
|
||||
/// `interfaces` says whether the run also needs each unit's ports and
|
||||
/// parameters (`unknown-port`, `unknown-parameter`), and `packages`
|
||||
/// whether it needs each package's exported names (`unused-import`).
|
||||
/// Either costs a **parse** of every file on top of the lex the word
|
||||
/// census already pays for, so each is built only when some enabled rule
|
||||
/// asks — measured on opentitan `hw/` in
|
||||
/// `docs/features/linter-expansion-1/README.md`.
|
||||
fn of(jobs: &[Job], interfaces: bool, packages: bool) -> Census {
|
||||
let per_file: Vec<PerFile> =
|
||||
jobs.par_iter().map(|job| harvest_one(job, interfaces, packages)).collect();
|
||||
|
||||
let mut files: HashMap<String, u32> = HashMap::new();
|
||||
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
|
||||
let mut exported: HashMap<String, Option<Vec<String>>> = HashMap::new();
|
||||
for (words, declared, exports) in per_file {
|
||||
for word in words {
|
||||
*files.entry(word).or_default() += 1;
|
||||
}
|
||||
// A package name the run declares twice is a package the run
|
||||
// cannot answer for, whatever the two say — the same rule the
|
||||
// workspace index applies, where two `units` is `Ambiguous`.
|
||||
for (name, names) in exports {
|
||||
exported.entry(name).and_modify(|held| *held = None).or_insert(names);
|
||||
}
|
||||
for (name, interface) in declared {
|
||||
// Two declarations of one name answer only when they agree;
|
||||
// anything else is a question the run cannot settle.
|
||||
units
|
||||
.entry(name)
|
||||
.and_modify(|held| {
|
||||
if *held != interface {
|
||||
*held = None;
|
||||
}
|
||||
})
|
||||
.or_insert(interface);
|
||||
}
|
||||
}
|
||||
Census { files, interfaces: units, packages: exported }
|
||||
}
|
||||
|
||||
/// How many files in the run write `name` down.
|
||||
fn count(&self, name: &str) -> u32 {
|
||||
self.files.get(name).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What the run says `name` declares, or `None` when it cannot say.
|
||||
fn interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
|
||||
self.interfaces.get(name)?.clone()
|
||||
}
|
||||
|
||||
/// What the run says the package `name` exports.
|
||||
fn package(&self, name: &str) -> vlog_linter::Exports {
|
||||
match self.packages.get(name) {
|
||||
Some(Some(names)) => vlog_linter::Exports::Known(names.clone()),
|
||||
Some(None) => vlog_linter::Exports::Ambiguous,
|
||||
None => vlog_linter::Exports::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's view of the census: everything the project says, minus what
|
||||
/// this file says about itself.
|
||||
struct Elsewhere<'a> {
|
||||
census: &'a Census,
|
||||
/// This file's own words, sorted — [`words::harvest`]'s answer over the
|
||||
/// tokens the file was linted from, so the subtraction is exact rather
|
||||
/// than assumed.
|
||||
own: Vec<String>,
|
||||
}
|
||||
|
||||
impl MentionOracle for Elsewhere<'_> {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
|
||||
self.census.count(name) > mine
|
||||
}
|
||||
|
||||
/// The run's interface table, which covers **every** file including this
|
||||
/// one: a module is instantiated as often in the file that declares it as
|
||||
/// anywhere else, and there is nothing to subtract here.
|
||||
fn module_interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
|
||||
self.census.interface(name)
|
||||
}
|
||||
|
||||
/// The run's package table, whole-run for the same reason the interface
|
||||
/// table is: a package is imported as often by the file that declares it
|
||||
/// as by any other, and there is nothing here to subtract.
|
||||
fn package_exports(&self, name: &str) -> vlog_linter::Exports {
|
||||
self.census.package(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the run: the rules for each file, and whether a census is owed.
|
||||
///
|
||||
/// **Precedence is CLI over config, key by key**: `--select` replaces a
|
||||
/// `[lint] select`, `--ignore` replaces a `[lint] ignore`, and a key the
|
||||
/// command line does not mention is the config file's to answer — the same
|
||||
/// ladder `--line-length` and `--indent` already climb.
|
||||
///
|
||||
/// A rule that [`Rule::needs_workspace`] is on by default here exactly when
|
||||
/// the run holds more than one file: one file is one file whatever directory
|
||||
/// it was found in, and a census of it could only ever say what the file
|
||||
/// already says about itself.
|
||||
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
|
||||
let workspace = gathered.len() > 1;
|
||||
let external = external_waivers(opts, gathered.iter().map(|(_, _, file)| file))?;
|
||||
let mut jobs = Vec::with_capacity(gathered.len());
|
||||
for (path, config, file_config) in gathered {
|
||||
let select = pick(&opts.select, file_config.lint_select.as_deref());
|
||||
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
|
||||
let rules = vlog_linter::select_rules(select, ignore, workspace)
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let options = rule_options(&file_config)?;
|
||||
jobs.push(Job { path, config, rules, options });
|
||||
}
|
||||
let asks = |wants: fn(&'static dyn Rule) -> bool| {
|
||||
jobs.iter().any(|job| job.rules.iter().any(|rule| wants(*rule)))
|
||||
};
|
||||
let wanted = asks(|rule| rule.needs_workspace()) || asks(reads_packages);
|
||||
let interfaces = asks(reads_interfaces);
|
||||
let packages = asks(reads_packages);
|
||||
let census = (workspace && wanted)
|
||||
.then(|| Census::of(&jobs, workspace && interfaces, workspace && packages));
|
||||
let mut enabled: Vec<&'static str> =
|
||||
jobs.iter().flat_map(|job| job.rules.iter().map(|rule| rule.name())).collect();
|
||||
enabled.sort_unstable();
|
||||
enabled.dedup();
|
||||
Ok(Plan { jobs, census, external, enabled })
|
||||
}
|
||||
|
||||
/// The run's external waiver files, read once each: `--waiver-file` in flag
|
||||
/// order, then every `[lint] waivers` entry of a config file governing an
|
||||
/// input.
|
||||
///
|
||||
/// The two **add up** rather than override: a waiver file only ever suppresses
|
||||
/// findings, so there is nothing for a command line to take back. A file named
|
||||
/// twice over — the flag and a `lucisv.toml`, or one `lucisv.toml` governing
|
||||
/// five hundred files — is read once, or its directives would each be reported
|
||||
/// unused as many times as the file was read.
|
||||
///
|
||||
/// A file that cannot be read, or a directive that does not parse, fails the
|
||||
/// run naming the file and the line, exactly as a bad `[lint.<rule>]` entry
|
||||
/// does and for the same reason: a user wrote it and is watching.
|
||||
pub fn external_waivers<'a>(
|
||||
opts: &Options,
|
||||
configs: impl Iterator<Item = &'a FileConfig>,
|
||||
) -> Result<ExternalWaivers, String> {
|
||||
let mut paths: Vec<PathBuf> = opts.waiver_files.iter().map(PathBuf::from).collect();
|
||||
for config in configs {
|
||||
for path in config.lint_waivers.iter().flatten() {
|
||||
paths.push(path.clone());
|
||||
}
|
||||
}
|
||||
let mut read: Vec<PathBuf> = Vec::new();
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
for path in paths {
|
||||
// Compared canonically, because the flag's path is relative to the
|
||||
// working directory and a `lucisv.toml`'s is absolute: the same file
|
||||
// named both ways is still one file, and reading it twice would report
|
||||
// each of its dead directives twice. Only the *comparison* is
|
||||
// canonical — the path a diagnostic names stays the one written.
|
||||
let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
|
||||
if read.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
let (file, problems) = ExternalWaivers::read(&path)?;
|
||||
if let Some(problem) = problems.first() {
|
||||
return Err(problem.clone());
|
||||
}
|
||||
waivers.absorb(file);
|
||||
read.push(key);
|
||||
}
|
||||
Ok(waivers)
|
||||
}
|
||||
|
||||
/// The `[lint.<rule>]` entries of one file's config, resolved against the
|
||||
/// registry.
|
||||
///
|
||||
/// The names and the values are checked **here**, where the registry is, and
|
||||
/// the first bad entry fails the run naming the config file and the line it
|
||||
/// was written on — the same treatment a bad `[lint] select` name gets, and
|
||||
/// for the same reason: a user typed it and is watching.
|
||||
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
|
||||
let mut options = RuleOptions::new();
|
||||
for entry in &file_config.lint_options {
|
||||
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
|
||||
let file = file_config
|
||||
.source
|
||||
.as_ref()
|
||||
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
|
||||
// The rule is named as well as the option: the table header two
|
||||
// lines up says which rule it is, and an error a user reads out
|
||||
// of a CI log has no table header beside it.
|
||||
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
|
||||
})?;
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// Whether this rule reads the census's **interface** half, which costs a
|
||||
/// parse of every file in the run rather than a lex.
|
||||
///
|
||||
/// By name, because the alternative is a fourth boolean on the `Rule` trait
|
||||
/// for two rules: `Rule::needs_workspace` already says "this rule asks the
|
||||
/// project something", and which *question* it asks is between the rule and
|
||||
/// the oracle. A name that is not in the registry cannot reach here — the
|
||||
/// rules are `&'static dyn Rule` values from that registry — and a rule added
|
||||
/// to the pair without being added here answers `None` and goes quiet, which
|
||||
/// is the safe direction.
|
||||
fn reads_interfaces(rule: &'static dyn Rule) -> bool {
|
||||
matches!(rule.name(), "unknown-port" | "unknown-parameter")
|
||||
}
|
||||
|
||||
/// The rule that reads the package table, which costs an index of every file
|
||||
/// in the run on top of the word census.
|
||||
fn reads_packages(rule: &'static dyn Rule) -> bool {
|
||||
rule.name() == "unused-import"
|
||||
}
|
||||
|
||||
/// 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] {
|
||||
if cli.is_empty() {
|
||||
config.unwrap_or(&[])
|
||||
} else {
|
||||
cli
|
||||
}
|
||||
}
|
||||
|
||||
/// What linting one file produced.
|
||||
struct Report {
|
||||
path: String,
|
||||
@@ -31,21 +359,51 @@ struct Report {
|
||||
violations: Vec<Violation>,
|
||||
/// Violations whose fix was applied and written back.
|
||||
fixed: usize,
|
||||
/// Which of the run's external waivers suppressed something in this file.
|
||||
/// Merged across every file before the dead ones are reported.
|
||||
used: WaiverUse,
|
||||
/// Set when the file could not be fully checked: unreadable, unwritable,
|
||||
/// or — because the lexer is all-or-nothing — unlexable, in which case
|
||||
/// only the text-level rules saw it.
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// Everything one file's lint pass reads besides the file itself.
|
||||
///
|
||||
/// One value rather than six parameters: every function below the driver
|
||||
/// needs the same set, and the `--fix` loop passes it down another level
|
||||
/// again.
|
||||
struct Pass<'a> {
|
||||
config: &'a Config,
|
||||
rules: &'a [&'static dyn Rule],
|
||||
options: &'a RuleOptions,
|
||||
census: Option<&'a Census>,
|
||||
/// The run's external waiver files. Empty unless `--waiver-file` or a
|
||||
/// `[lint] waivers` named one, and then costing nothing.
|
||||
external: &'a ExternalWaivers,
|
||||
}
|
||||
|
||||
/// Lints every gathered file and reports. Exit 1 if anything is left over,
|
||||
/// 2 if a file could not be read, written, or lexed.
|
||||
pub fn check_files(
|
||||
opts: &Options,
|
||||
jobs: &[(PathBuf, Config)],
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> ExitCode {
|
||||
let mut reports: Vec<Report> =
|
||||
jobs.par_iter().map(|(file, config)| check_one(file, config, opts, rules)).collect();
|
||||
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
let mut reports: Vec<Report> = plan
|
||||
.jobs
|
||||
.par_iter()
|
||||
.map(|job| {
|
||||
let pass = Pass {
|
||||
config: &job.config,
|
||||
rules: &job.rules,
|
||||
options: &job.options,
|
||||
census: plan.census.as_ref(),
|
||||
external: &plan.external,
|
||||
};
|
||||
check_one(&job.path, opts, &pass)
|
||||
})
|
||||
.collect();
|
||||
// The dead external waivers are found once every file has been linted,
|
||||
// and reported against the waiver file, which then sorts in among the
|
||||
// sources like any other path.
|
||||
reports.extend(dead_waivers(&plan.external, &reports, &plan.enabled));
|
||||
// Diagnostics are printed sorted by path, then by position within the
|
||||
// file (`lint` already sorts those), so a run over a directory reads
|
||||
// top to bottom whatever order the walk or the worker pool produced.
|
||||
@@ -53,6 +411,37 @@ pub fn check_files(
|
||||
finish(opts, reports)
|
||||
}
|
||||
|
||||
/// The `unused-waiver` reports for external waivers no file in the run used.
|
||||
///
|
||||
/// **After the whole run**, which is the whole reason this is the CLI's job
|
||||
/// and not the linter's: a `--location` pattern may match a file the run has
|
||||
/// not reached yet, so a waiver is only dead once every file has been asked.
|
||||
fn dead_waivers(
|
||||
external: &ExternalWaivers,
|
||||
reports: &[Report],
|
||||
enabled: &[&'static str],
|
||||
) -> Vec<Report> {
|
||||
if external.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut used = WaiverUse::default();
|
||||
for report in reports {
|
||||
used.merge(&report.used);
|
||||
}
|
||||
external
|
||||
.unused(&used, enabled)
|
||||
.into_iter()
|
||||
.map(|dead| Report {
|
||||
path: dead.path.display().to_string(),
|
||||
index: LineIndex::new(&dead.text),
|
||||
violations: dead.violations,
|
||||
fixed: 0,
|
||||
used: WaiverUse::default(),
|
||||
error: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lints a buffer piped in on stdin. `--stdin-filename` names it, and is
|
||||
/// what the rules that need a file name see.
|
||||
pub fn check_stdin(
|
||||
@@ -60,25 +449,35 @@ pub fn check_stdin(
|
||||
src: &str,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
external: &ExternalWaivers,
|
||||
) -> ExitCode {
|
||||
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
|
||||
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
|
||||
let (violations, lex_error) = run_rules(src, path, config, rules);
|
||||
let pass = Pass { config, rules, options, census: None, external };
|
||||
let (violations, used, lex_error) = run_rules(src, path, &pass);
|
||||
// Nothing is ever written back for stdin, so `--fix` has nothing to do
|
||||
// here; the violations are reported as they are.
|
||||
let error = lex_error.map(|e| format!("{name}: {e}"));
|
||||
let report = Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error };
|
||||
finish(opts, vec![report])
|
||||
let report =
|
||||
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, used, error };
|
||||
// One buffer is a whole run too, so a waiver that covered nothing in it is
|
||||
// as dead as one that covered nothing in a directory.
|
||||
let names: Vec<&'static str> = rules.iter().map(|rule| rule.name()).collect();
|
||||
let mut reports = vec![report];
|
||||
reports.extend(dead_waivers(external, &reports, &names));
|
||||
finish(opts, reports)
|
||||
}
|
||||
|
||||
/// Lints one file, optionally fixing it, and never panics out of its worker.
|
||||
fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn Rule]) -> Report {
|
||||
fn check_one(file: &Path, opts: &Options, pass: &Pass) -> Report {
|
||||
let path = file.display().to_string();
|
||||
let failed = |error: String| Report {
|
||||
path: path.clone(),
|
||||
index: LineIndex::new(""),
|
||||
violations: Vec::new(),
|
||||
fixed: 0,
|
||||
used: WaiverUse::default(),
|
||||
error: Some(error),
|
||||
};
|
||||
|
||||
@@ -88,19 +487,19 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
|
||||
};
|
||||
let outcome = crate::catch_panic(|| {
|
||||
if opts.fix {
|
||||
fix_source(&src, file, config, opts, rules)
|
||||
fix_source(&src, file, opts, pass)
|
||||
} else {
|
||||
let (violations, lex_error) = run_rules(&src, Some(file.to_path_buf()), config, rules);
|
||||
(violations, None, 0, lex_error)
|
||||
let (violations, used, lex_error) = run_rules(&src, Some(file.to_path_buf()), pass);
|
||||
(violations, used, None, 0, lex_error)
|
||||
}
|
||||
});
|
||||
let (violations, rewritten, fixed, lex_error) = match outcome {
|
||||
let (violations, used, rewritten, fixed, lex_error) = match outcome {
|
||||
Ok(outcome) => outcome,
|
||||
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
|
||||
};
|
||||
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
|
||||
if let Some(text) = rewritten {
|
||||
if let Err(e) = std::fs::write(file, &text) {
|
||||
if let Err(e) = write_atomic(file, text.as_bytes()) {
|
||||
return failed(format!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
@@ -109,19 +508,20 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
|
||||
// so the file must not pass as checked. It is an error (exit 2), exactly
|
||||
// as `lucisv format` treats the same file.
|
||||
let error = lex_error.map(|e| format!("{path}: {e}"));
|
||||
Report { path, index, violations, fixed, error }
|
||||
Report { path, index, violations, fixed, used, error }
|
||||
}
|
||||
|
||||
/// Runs the rules over one text. The second half of the answer is the lex
|
||||
/// error when the text does not lex — rendered `line:col: message`, ready
|
||||
/// for a path prefix — because a file with no tokens was only text-linted
|
||||
/// and must be reported as an error, not passed off as clean.
|
||||
/// Runs the rules over one text, reporting which external waivers fired. The
|
||||
/// last part of the answer is the lex error when the text does not lex —
|
||||
/// rendered `line:col: message`, ready for a path prefix — because a file with
|
||||
/// no tokens was only text-linted and must be reported as an error, not passed
|
||||
/// off as clean.
|
||||
fn run_rules(
|
||||
src: &str,
|
||||
path: Option<PathBuf>,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> (Vec<Violation>, Option<String>) {
|
||||
pass: &Pass,
|
||||
) -> (Vec<Violation>, WaiverUse, Option<String>) {
|
||||
let Pass { config, rules, options, census, external } = *pass;
|
||||
// One parse per file (TODO §4): the products are built here, once, and
|
||||
// lent to the context. Under `--fix` each *round* re-enters through this
|
||||
// function with rewritten text — that re-parse is inherent (the old
|
||||
@@ -129,10 +529,24 @@ fn run_rules(
|
||||
// saves a parse; a plain `lucisv check` always does.
|
||||
let parsed = ParsedSource::parse(src);
|
||||
let lex_error = parsed.lex_error().map(|e| format!("lex error: {e}"));
|
||||
// This file's own words, off the tokens it was just lexed from rather
|
||||
// than off a second lex — what the oracle subtracts from the project's
|
||||
// census so a signal never counts as mentioned by its own declaration.
|
||||
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
|
||||
// The indent width the formatter would use is also the width a tab
|
||||
// expands to, so `--indent 4` fixes tabs into four spaces.
|
||||
let ctx = parsed.context(path).with_tab_width(config.indent_width);
|
||||
(lint(&ctx, rules), lex_error)
|
||||
// expands to, so `--indent 4` fixes tabs into four spaces — and the width
|
||||
// it would wrap to is the width `line-length` holds the file to.
|
||||
let ctx = parsed
|
||||
.context(path)
|
||||
.with_tab_width(config.indent_width)
|
||||
.with_line_length(config.max_width)
|
||||
.with_options(options);
|
||||
let ctx = match &elsewhere {
|
||||
Some(elsewhere) => ctx.with_oracle(elsewhere),
|
||||
None => ctx,
|
||||
};
|
||||
let (violations, used) = lint_with(&ctx, rules, external);
|
||||
(violations, used, lex_error)
|
||||
}
|
||||
|
||||
/// The violations whose fix may be applied: everything except a fix that
|
||||
@@ -171,13 +585,15 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
fn fix_source(
|
||||
src: &str,
|
||||
file: &Path,
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
|
||||
pass: &Pass,
|
||||
) -> (Vec<Violation>, WaiverUse, Option<String>, usize, Option<String>) {
|
||||
let mut text = src.to_string();
|
||||
let mut fixed = 0;
|
||||
let (mut violations, mut lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
let mut used = WaiverUse::default();
|
||||
let (mut violations, mut round_used, mut lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), pass);
|
||||
used.merge(&round_used);
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round =
|
||||
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
|
||||
@@ -186,10 +602,14 @@ fn fix_source(
|
||||
}
|
||||
fixed += round.applied;
|
||||
text = round.output;
|
||||
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
(violations, round_used, lex_error) = run_rules(&text, Some(file.to_path_buf()), pass);
|
||||
// A waiver that covered a finding in an earlier round did its job even
|
||||
// though the fix then removed the finding, so usage accumulates over
|
||||
// the rounds rather than being the last round's.
|
||||
used.merge(&round_used);
|
||||
}
|
||||
let rewritten = (text != src).then_some(text);
|
||||
(violations, rewritten, fixed, lex_error)
|
||||
(violations, used, rewritten, fixed, lex_error)
|
||||
}
|
||||
|
||||
/// Prints the run and turns it into an exit code.
|
||||
@@ -220,15 +640,23 @@ fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`.
|
||||
/// Verible's diagnostic line with the severity word in front of the message:
|
||||
/// `FILE:LINE:COL: error|warning|style: message [rule-name]`.
|
||||
///
|
||||
/// The word sits where a compiler puts it, so the line greps and reads the way
|
||||
/// every other tool's does, and `grep ': error:'` is the whole of "show me
|
||||
/// what would not compile".
|
||||
fn print_text(reports: &[Report]) {
|
||||
let mut out = String::new();
|
||||
for report in reports {
|
||||
for violation in &report.violations {
|
||||
let (line, col) = position(report, violation);
|
||||
out.push_str(&format!(
|
||||
"{}:{line}:{col}: {} [{}]\n",
|
||||
report.path, violation.message, violation.rule
|
||||
"{}:{line}:{col}: {}: {} [{}]\n",
|
||||
report.path,
|
||||
violation.severity.as_str(),
|
||||
violation.message,
|
||||
violation.rule
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -244,12 +672,13 @@ fn print_json(reports: &[Report]) {
|
||||
let (line, col) = position(report, violation);
|
||||
let (end_line, end_col) = end_position(report, violation);
|
||||
items.push(format!(
|
||||
"{{\"filename\":{},\"rule\":{},\"message\":{},\
|
||||
"{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\
|
||||
\"location\":{{\"line\":{line},\"column\":{col}}},\
|
||||
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
|
||||
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
|
||||
quote(&report.path),
|
||||
quote(violation.rule),
|
||||
quote(violation.severity.as_str()),
|
||||
quote(&violation.message),
|
||||
violation.span.start,
|
||||
violation.span.end,
|
||||
|
||||
+127
-26
@@ -27,8 +27,9 @@ use std::process::ExitCode;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use args::{Command, Options};
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::cache::{content_hash, Cache, Entry};
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use lucisv_core::filelist;
|
||||
use lucisv_core::walk::{collect_files, EXTENSIONS};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
@@ -84,15 +85,21 @@ fn run(opts: &Options) -> ExitCode {
|
||||
|
||||
/// `lucisv check`: the linter over the same file set the formatter would take.
|
||||
fn run_check(opts: &Options) -> ExitCode {
|
||||
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore) {
|
||||
Ok(rules) => rules,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
// Before any rule is selected and before any path is gathered: the rule
|
||||
// reference is a property of the build, not of a run over files.
|
||||
if opts.rules_doc {
|
||||
print!("{}", vlog_linter::rules_markdown());
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
// The command line's own names are checked before anything is walked, so
|
||||
// a typo'd `--select` fails in milliseconds rather than after the scan.
|
||||
// A `lucisv.toml`'s names are checked per file below, where they are read.
|
||||
if let Err(e) = vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if opts.is_stdin() {
|
||||
let config = match stdin_config(opts) {
|
||||
let (config, file_config) = match stdin_config(opts) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
@@ -104,7 +111,34 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
eprintln!("error: reading stdin: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
return lint::check_stdin(opts, &src, &config, &rules);
|
||||
// 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,
|
||||
@@ -113,12 +147,18 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
lint::check_files(opts, &jobs, &rules)
|
||||
match lint::plan(opts, jobs) {
|
||||
Ok(plan) => lint::check_files(opts, &plan),
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_stdin(opts: &Options) -> ExitCode {
|
||||
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
|
||||
let config = match stdin_config(opts) {
|
||||
let (config, _file_config) = match stdin_config(opts) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
@@ -174,11 +214,11 @@ fn run_files(opts: &Options) -> ExitCode {
|
||||
// The cache is only read here; entries ride back with the results and
|
||||
// are recorded serially below, so nothing is shared mutably.
|
||||
let results: Vec<FileResult> =
|
||||
jobs.par_iter().map(|(file, config)| process_file(file, config, opts, &cache)).collect();
|
||||
jobs.par_iter().map(|(file, config, _)| process_file(file, config, opts, &cache)).collect();
|
||||
|
||||
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];
|
||||
let (file, config, _) = &jobs[index];
|
||||
if let Some(content) = result.clean {
|
||||
cache.record(file, entry_for(content, config));
|
||||
}
|
||||
@@ -277,7 +317,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
|
||||
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
|
||||
} else if opts.check {
|
||||
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
|
||||
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
|
||||
} else {
|
||||
// The bytes now on disk are formatted, so they are what the cache
|
||||
@@ -293,7 +333,12 @@ 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 {
|
||||
Entry { content, line_length: config.max_width, indent: config.indent_width }
|
||||
Entry {
|
||||
content,
|
||||
line_length: config.max_width,
|
||||
indent: config.indent_width,
|
||||
uvm_utils_indent: config.uvm_utils_indent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds rayon's global pool. Worker stacks are sized for the parser's
|
||||
@@ -313,7 +358,7 @@ fn build_pool(opts: &Options) -> Result<(), String> {
|
||||
/// filelists name (exact paths, filtered by neither — they were named).
|
||||
/// Every config file is read here, before anything is written, so a broken
|
||||
/// one aborts the whole run instead of leaving it half applied.
|
||||
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
|
||||
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String> {
|
||||
let mut discovery = Discovery::new(!opts.no_config);
|
||||
let mut files = Vec::new();
|
||||
for input in &opts.inputs {
|
||||
@@ -326,7 +371,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
|
||||
return Err(format!("--lines needs a file, not a directory: {input}"));
|
||||
}
|
||||
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
|
||||
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
|
||||
// The walk's own warnings — an unreadable directory, a source file
|
||||
// that is only a broken link — go to stderr as they are found, before
|
||||
// the report and exactly as a filelist's do. A warning is not a
|
||||
// failure: the exit code is the formatting's alone.
|
||||
let mut warn = |w| eprintln!("warning: {w}");
|
||||
collect_files(input, &exclude, !opts.no_gitignore, &mut files, &mut warn)?;
|
||||
}
|
||||
// Filelists come after the command line's own inputs, in flag order: they
|
||||
// add files, they never replace or reorder what was named directly.
|
||||
@@ -337,8 +387,13 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
|
||||
}
|
||||
let mut jobs = Vec::with_capacity(files.len());
|
||||
for file in files {
|
||||
let config = opts.config_with(&discovery.for_file(&file)?);
|
||||
jobs.push((file, config));
|
||||
// The whole `FileConfig` rides along, not just the formatter settings
|
||||
// it resolves to: `lucisv check` needs its `[lint]` keys too, and
|
||||
// discovering them a second time would read every config file twice
|
||||
// and could answer differently if one changed underneath the run.
|
||||
let file_config = discovery.for_file(&file)?;
|
||||
let config = opts.config_with(&file_config);
|
||||
jobs.push((file, config, file_config));
|
||||
}
|
||||
Ok(jobs)
|
||||
}
|
||||
@@ -370,13 +425,25 @@ fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
|
||||
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
|
||||
let mut seen = HashSet::new();
|
||||
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
|
||||
files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect()
|
||||
}
|
||||
|
||||
/// The key two spellings of one file share: the file's canonical path when it
|
||||
/// is there, and the lexical fold when it is not.
|
||||
///
|
||||
/// Canonical means symlinks resolved, which is the only way to see that
|
||||
/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one
|
||||
/// target otherwise, each rewriting what the other just wrote. A path with no
|
||||
/// file behind it has no canonical form, and the lexical fold is then the
|
||||
/// 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. Lexical, like `lucisv_core`'s own normalization: symlinks are
|
||||
/// deliberately left unresolved, so this is only ever a dedup key and never
|
||||
/// the path lucisv reports.
|
||||
/// 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();
|
||||
@@ -394,13 +461,16 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
|
||||
|
||||
/// The settings for a buffer piped in on stdin: discovery anchors on
|
||||
/// `--stdin-filename`'s directory when given, else on the current one.
|
||||
fn stdin_config(opts: &Options) -> Result<Config, String> {
|
||||
/// The formatter config a stdin buffer is served with, and the `lucisv.toml`
|
||||
/// it came from — the linter needs the file's own `[lint.<rule>]` entries,
|
||||
/// 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() {
|
||||
Some(name) => discovery.for_file(Path::new(name))?,
|
||||
None => discovery.for_dir(Path::new("."))?,
|
||||
};
|
||||
Ok(opts.config_with(&file))
|
||||
Ok((opts.config_with(&file), file))
|
||||
}
|
||||
|
||||
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
|
||||
@@ -554,6 +624,37 @@ mod tests {
|
||||
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dedup_folds_a_symlink_onto_the_file_it_points_at() {
|
||||
// A directory walk lists `b.sv` as a file of its own; lexically the
|
||||
// two names share nothing, and two workers would rewrite one file.
|
||||
let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let real = dir.join("a.sv");
|
||||
let link = dir.join("b.sv");
|
||||
std::fs::write(&real, "module m;\nendmodule\n").expect("seed");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
||||
|
||||
assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real));
|
||||
// Whichever spelling comes first is the one kept and reported.
|
||||
assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link));
|
||||
// And a `..` detour through the same link is still the same file.
|
||||
std::fs::create_dir(dir.join("sub")).expect("sub dir");
|
||||
let detour = dir.join("sub/../b.sv");
|
||||
assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real));
|
||||
|
||||
// A file that is not there has no canonical path: the key is lexical,
|
||||
// which still folds `.` and `..`, and two missing files stay two.
|
||||
let gone = dir.join("gone.sv");
|
||||
let same = dir.join("./sub/../gone.sv");
|
||||
let other = dir.join("other.sv");
|
||||
assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_contained_reports_parse_errors() {
|
||||
let err = format_contained("module", &Config::default(), None).unwrap_err();
|
||||
|
||||
+703
-7
@@ -136,6 +136,57 @@ fn formats_files_in_place() {
|
||||
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// A directory walk lists a symlink as a file of its own, so `b.sv -> a.sv`
|
||||
/// used to put two workers on one file: two report lines for one file, and
|
||||
/// two writers racing to replace it. It is one file now, named once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlink_and_its_target_are_one_file() {
|
||||
let dir = TempDir::new("alias");
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
std::os::unix::fs::symlink(dir.path.join("a.sv"), dir.path.join("b.sv")).expect("symlink");
|
||||
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
let reported = stdout(&out);
|
||||
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
|
||||
assert_eq!(named.len(), 1, "one file, one line: {named:?}");
|
||||
assert!(named[0].ends_with("a.sv"), "the first spelling walked is the one reported: {named:?}");
|
||||
assert!(stderr(&out).contains("1 file would be reformatted"), "{}", stderr(&out));
|
||||
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file reformatted"), "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("b.sv"), FORMATTED, "and the link still reaches it");
|
||||
assert!(
|
||||
std::fs::symlink_metadata(dir.path.join("b.sv")).expect("stat").file_type().is_symlink(),
|
||||
"the link was not replaced by a copy"
|
||||
);
|
||||
}
|
||||
|
||||
/// A directory that links back into itself. Before the walk kept a visited
|
||||
/// set (`docs/features/walk-cycles/README.md`) this run recursed until the
|
||||
/// OS refused the path; now each directory is entered once, so each file is
|
||||
/// named once — under the first spelling that reaches it.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlink_cycle_terminates_and_names_each_file_once() {
|
||||
let dir = TempDir::new("cycle");
|
||||
dir.write("rtl/a.sv", UNFORMATTED);
|
||||
dir.write("rtl/sub/b.sv", UNFORMATTED);
|
||||
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level down.
|
||||
std::os::unix::fs::symlink("../rtl", dir.path.join("rtl/self")).expect("symlink");
|
||||
std::os::unix::fs::symlink("..", dir.path.join("rtl/sub/up")).expect("symlink");
|
||||
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
let reported = stdout(&out);
|
||||
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
|
||||
assert_eq!(named.len(), 2, "two files, two lines: {named:?}");
|
||||
assert!(stderr(&out).contains("2 files would be reformatted"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reports_without_writing() {
|
||||
let dir = TempDir::new("check");
|
||||
@@ -662,7 +713,7 @@ fn a_broken_config_exits_2_before_writing_anything() {
|
||||
for (contents, expected) in [
|
||||
("indent = 99\n", "between 1 and 8"),
|
||||
("line-length = wide\n", "expects an integer"),
|
||||
("[tool.lucisv]\nindent = 2\n", "tables"),
|
||||
("[tool.lucisv]\nindent = 2\n", "unknown table"),
|
||||
("exclude = [\n \"a\",\n]\n", "multi-line arrays are unsupported"),
|
||||
] {
|
||||
dir.write("lucisv.toml", contents);
|
||||
@@ -753,7 +804,9 @@ fn check_reports_violations_and_exits_1() {
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
|
||||
// `FILE:LINE:COL: severity: message [rule]` — the severity word is part
|
||||
// of the line since §33.0, and both of these are style findings.
|
||||
assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}");
|
||||
assert!(text.contains("[no-tabs]"), "{text}");
|
||||
assert!(text.contains("[module-filename]"), "{text}");
|
||||
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
|
||||
@@ -797,6 +850,7 @@ fn check_json_is_one_array_with_positions_and_fixes() {
|
||||
assert!(text.starts_with('['), "{text}");
|
||||
assert!(text.trim_end().ends_with(']'), "{text}");
|
||||
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
|
||||
assert!(text.contains("\"severity\":\"style\""), "{text}");
|
||||
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
|
||||
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
|
||||
assert!(text.contains("\"content\":\" \""), "{text}");
|
||||
@@ -895,6 +949,30 @@ fn check_select_and_ignore_pick_the_rule_set() {
|
||||
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// A severity word stands for its whole class wherever a rule name fits —
|
||||
/// §33.0's headline for the command line.
|
||||
#[test]
|
||||
fn check_select_and_ignore_accept_a_severity_word() {
|
||||
let dir = TempDir::new("check-severity");
|
||||
// `reg` is an error-class finding, the tab and the name are style ones.
|
||||
let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n");
|
||||
|
||||
let out = run(&["check", "--select", "error", &path]);
|
||||
assert_eq!(code(&out), 1, "{}", stdout(&out));
|
||||
let text = stdout(&out);
|
||||
assert_eq!(text.lines().count(), 1, "{text}");
|
||||
assert!(text.contains(": error: "), "{text}");
|
||||
assert!(text.contains("[wire-reg-mixup]"), "{text}");
|
||||
|
||||
let out = run(&["check", "--ignore", "style", &path]);
|
||||
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
|
||||
assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out));
|
||||
|
||||
// Ignoring every class leaves nothing to report.
|
||||
let out = run(&["check", "--ignore", "error,warning,style", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_honors_inline_waivers_and_reports_dead_ones() {
|
||||
let dir = TempDir::new("check-waive");
|
||||
@@ -908,6 +986,89 @@ fn check_honors_inline_waivers_and_reports_dead_ones() {
|
||||
assert!(stdout(&out).contains("[unused-waiver]"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
/// Two tabbed lines, one of which a waiver file's `--line` covers.
|
||||
const TABBED: &str = "module foo;\n\twire a;\n\twire b;\nendmodule\n";
|
||||
|
||||
/// `--waiver-file`: the suppression, the flag repeated, and the dead directive
|
||||
/// reported at the waiver file's own line. TODO §39.
|
||||
#[test]
|
||||
fn check_reads_external_waiver_files() {
|
||||
let dir = TempDir::new("check-waiver-file");
|
||||
let path = dir.write("foo.sv", TABBED);
|
||||
let one = dir.write("one.waiver", "# just line 2\nwaive --rule=no-tabs --line=2\n");
|
||||
let out = run(&["check", "--waiver-file", &one, &path]);
|
||||
assert_eq!(code(&out), 1, "{}", stdout(&out));
|
||||
assert_eq!(stdout(&out).lines().count(), 1, "one tab left: {}", stdout(&out));
|
||||
assert!(stdout(&out).contains("foo.sv:3:1"), "{}", stdout(&out));
|
||||
|
||||
// A second file adds to the first rather than replacing it, and both are
|
||||
// then used, so neither is reported.
|
||||
let two = dir.write("two.waiver", "waive --rule=no-tabs --line=3 --location=foo.sv\n");
|
||||
let out = run(&["check", "--waiver-file", &one, "--waiver-file", &two, &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stdout(&out));
|
||||
|
||||
// A directive that covered nothing is reported against the waiver file.
|
||||
let dead = dir.write("dead.waiver", "waive --rule=no-tabs --location=elsewhere.sv\n");
|
||||
let out = run(&["check", "--waiver-file", &dead, &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("dead.waiver:1:1: style: unused waiver for `no-tabs`"), "{text}");
|
||||
assert!(text.contains("[unused-waiver]"), "{text}");
|
||||
}
|
||||
|
||||
/// The `[lint] waivers` key, and that `--waiver-file` adds to it. TODO §39.
|
||||
#[test]
|
||||
fn check_reads_the_waiver_files_a_config_file_names() {
|
||||
let dir = TempDir::new("check-waiver-toml");
|
||||
let path = dir.write("rtl/foo.sv", TABBED);
|
||||
dir.write("lucisv.toml", "[lint]\nwaivers = [ \"project.waiver\" ]\n");
|
||||
dir.write("project.waiver", "waive --rule=no-tabs --line=2\n");
|
||||
// Relative to the config file, not to the working directory.
|
||||
let out = run_raw(&["check", "--no-cache", &path]);
|
||||
assert_eq!(code(&out), 1, "{}", stdout(&out));
|
||||
assert!(stdout(&out).contains("foo.sv:3:1"), "only line 3 survives: {}", stdout(&out));
|
||||
|
||||
let extra = dir.write("extra.waiver", "waive --rule=no-tabs --line=3\n");
|
||||
let out = run_raw(&["check", "--no-cache", "--waiver-file", &extra, &path]);
|
||||
assert_eq!(code(&out), 0, "the two lists add up: {}", stdout(&out));
|
||||
|
||||
// `--no-config` drops the config file's list with everything else in it.
|
||||
let out = run_raw(&["check", "--no-cache", "--no-config", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert_eq!(stdout(&out).lines().count(), 2, "both tabs are back: {}", stdout(&out));
|
||||
}
|
||||
|
||||
/// A waiver file that cannot be read, or that has a line that does not parse,
|
||||
/// fails the run with `<file>:<line>: message` and exit 2. TODO §39.
|
||||
#[test]
|
||||
fn a_broken_waiver_file_fails_the_run() {
|
||||
let dir = TempDir::new("check-waiver-bad");
|
||||
let path = dir.write("foo.sv", TABBED);
|
||||
|
||||
let out = run(&["check", "--waiver-file", &dir.write("x.waiver", "hush\n"), &path]);
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("x.waiver:1: expected a `waive` directive"), "{}", stderr(&out));
|
||||
|
||||
let bad = dir.write("y.waiver", "# fine\nwaive --rule=no-such-rule\n");
|
||||
let out = run(&["check", "--waiver-file", &bad, &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("y.waiver:2: unknown rule"), "{}", stderr(&out));
|
||||
|
||||
let regexy = dir.write("z.waiver", "waive --rule=no-tabs --location=.*foo.sv\n");
|
||||
let out = run(&["check", "--waiver-file", ®exy, &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("looks like a regular expression"), "{}", stderr(&out));
|
||||
|
||||
let out = run(&[
|
||||
"check",
|
||||
"--waiver-file",
|
||||
&dir.path.join("gone.waiver").display().to_string(),
|
||||
&path,
|
||||
]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("gone.waiver:"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reads_stdin_and_names_it() {
|
||||
let out = run_with_stdin(&["check", "--stdin-filename", "rtl/z.sv", "-"], LINTY);
|
||||
@@ -1106,16 +1267,18 @@ impl TempDir {
|
||||
}
|
||||
}
|
||||
|
||||
/// One hand-written cache line, for the tests that forge entries.
|
||||
/// One hand-written cache line, for the tests that forge entries. The
|
||||
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
|
||||
fn cache_line(
|
||||
path: &str,
|
||||
content: &str,
|
||||
line_length: usize,
|
||||
indent: usize,
|
||||
uvm: bool,
|
||||
version: &str,
|
||||
) -> String {
|
||||
let hash = lucisv_core::cache::content_hash(content.as_bytes());
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{version}\t{path}\n")
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1202,7 +1365,8 @@ fn a_hit_skips_the_work_entirely() {
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 2, "without an entry this file is an error");
|
||||
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, VERSION)).unwrap();
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, false, VERSION))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "a hit does no work at all: {}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
@@ -1227,6 +1391,65 @@ fn a_config_file_change_invalidates_the_entry_too() {
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// A UVM class whose layout depends on `[format] uvm-utils-indent`: with the
|
||||
/// option on, the `` `uvm_field_* `` macro gains a level. Written here as the
|
||||
/// formatter leaves it with the option *off*.
|
||||
const UVM_CLASS: &str = "class c extends uvm_object;\n `uvm_object_utils_begin(c)\n \
|
||||
`uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
|
||||
|
||||
#[test]
|
||||
fn changing_uvm_utils_indent_invalidates_the_entry() {
|
||||
let dir = TempDir::new("cache-uvm");
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
|
||||
let path = dir.write("a.sv", UVM_CLASS);
|
||||
let cache = dir.cache();
|
||||
|
||||
// Clean with the option off, and that verdict is cached.
|
||||
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
|
||||
let flat = dir.read("a.sv");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
// Turning the option on must not hit the entry the option-off run left.
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "uvm-utils-indent is part of the key: {}", stderr(&out));
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
|
||||
// Format under the option on, cache *that*, then flip back off.
|
||||
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
|
||||
assert_ne!(dir.read("a.sv"), flat, "the option really does change the output");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "and the other direction too: {}", stderr(&out));
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_written_before_the_option_joined_the_key_is_rebuilt() {
|
||||
let dir = TempDir::new("cache-oldshape");
|
||||
let path = dir.write("a.sv", FORMATTED);
|
||||
let cache = dir.cache();
|
||||
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
|
||||
|
||||
// The five-field line lucisv wrote before `uvm-utils-indent` was in the
|
||||
// key. Not corruption: the line is dropped on its own and the run
|
||||
// rebuilds the store in the current shape.
|
||||
let hash = lucisv_core::cache::content_hash(FORMATTED.as_bytes());
|
||||
std::fs::write(dir.cache_file(), format!("{hash:016x}\t100\t2\t{VERSION}\t{path}\n")).unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "an older store is never an error: {}", stderr(&out));
|
||||
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
|
||||
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert!(stderr(&out).contains("1 file from cache"), "the store was rebuilt: {}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_from_another_lucisv_version_is_ignored() {
|
||||
let dir = TempDir::new("cache-version");
|
||||
@@ -1236,13 +1459,14 @@ fn an_entry_from_another_lucisv_version_is_ignored() {
|
||||
|
||||
// A forged entry claiming this unformatted file is clean. With this
|
||||
// version's stamp it is believed…
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, VERSION)).unwrap();
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, VERSION))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "the forged entry proves entries are really read");
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
// …and with any other version's stamp it is not.
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, "0.0.0-other"))
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, "0.0.0-other"))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "another version's entry must not be trusted: {}", stderr(&out));
|
||||
@@ -1727,3 +1951,475 @@ fn help_documents_the_filelist_flag() {
|
||||
assert!(text.contains("-f <FILELIST>"), "{text}");
|
||||
assert!(text.contains("read by lucisv-server only"), "the toml key stays server-only: {text}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The semantic rules and the project census (semantic-lints-on, 2026-09-02)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A module whose `dbg_probe` only a *second* file reads, hierarchically.
|
||||
const DUT: &str = "module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n";
|
||||
const TB: &str = "module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n";
|
||||
|
||||
/// The round's headline: over a project the semantic rules run by default,
|
||||
/// and the file that reads `d.dbg_probe` is what keeps `dbg_probe` quiet.
|
||||
/// `dead`, which nothing anywhere writes down twice, is still reported.
|
||||
#[test]
|
||||
fn a_mention_in_another_file_silences_unused_signal_over_a_project() {
|
||||
let dir = TempDir::new("census");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("`dead` is declared but never used"), "{text}");
|
||||
assert!(!text.contains("dbg_probe"), "the other file reads it: {text}");
|
||||
assert_eq!(code(&out), 1);
|
||||
}
|
||||
|
||||
/// One file is not a project: there is nothing to ask, so the rules that
|
||||
/// need a workspace stay off and the run is exactly v0.29.0's.
|
||||
#[test]
|
||||
fn a_single_file_run_leaves_the_semantic_rules_off() {
|
||||
let dir = TempDir::new("alone");
|
||||
let dut = dir.write("dut.sv", DUT);
|
||||
let out = run(&["check", &dut]);
|
||||
assert_eq!(stdout(&out), "");
|
||||
assert_eq!(code(&out), 0);
|
||||
|
||||
// ... and naming the rule still runs it, oracle or no oracle.
|
||||
let named = run(&["check", &dut, "--select", "unused-signal"]);
|
||||
let text = stdout(&named);
|
||||
assert!(text.contains("dbg_probe"), "{text}");
|
||||
assert!(text.contains("dead"), "{text}");
|
||||
assert_eq!(code(&named), 1);
|
||||
}
|
||||
|
||||
/// A stdin buffer has no project either, and no file to build one from.
|
||||
#[test]
|
||||
fn a_stdin_buffer_leaves_the_semantic_rules_off() {
|
||||
let out = run_with_stdin(&["check", "-"], DUT);
|
||||
assert_eq!(stdout(&out), "");
|
||||
assert_eq!(code(&out), 0);
|
||||
let named = run_with_stdin(&["check", "-", "--select", "unused-signal"], DUT);
|
||||
assert!(stdout(&named).contains("dbg_probe"), "{}", stdout(&named));
|
||||
}
|
||||
|
||||
/// The off switch a default-on rule owes its users: `[lint] ignore` in the
|
||||
/// `lucisv.toml` governing the files.
|
||||
#[test]
|
||||
fn a_lint_table_in_the_config_turns_a_rule_off() {
|
||||
let dir = TempDir::new("lint-table");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert_eq!(stdout(&out), "", "the config silenced the rule");
|
||||
assert_eq!(code(&out), 0);
|
||||
}
|
||||
|
||||
/// `[lint] select` replaces the default set, exactly as `--select` does.
|
||||
#[test]
|
||||
fn a_lint_table_can_select_instead_of_ignore() {
|
||||
let dir = TempDir::new("lint-select");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
dir.write("lucisv.toml", "[lint]\nselect = [\"unused-signal\"]\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("`dead` is declared but never used"), "{text}");
|
||||
assert!(!text.contains("dbg_probe"), "{text}");
|
||||
}
|
||||
|
||||
/// Precedence, key by key: the command line beats the config file, and a key
|
||||
/// the command line does not mention stays the config file's.
|
||||
#[test]
|
||||
fn the_command_line_beats_the_lint_table() {
|
||||
let dir = TempDir::new("lint-precedence");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
|
||||
// `--ignore` replaces the config's ignore list, so `unused-signal` is back.
|
||||
let out = run(&["check", &dir.root(), "--ignore", "no-tabs"]);
|
||||
assert!(stdout(&out).contains("`dead` is declared but never used"), "{}", stdout(&out));
|
||||
// `--select` replaces the default set; the config's ignore still applies.
|
||||
let selected = run(&["check", &dir.root(), "--select", "unused-signal,no-tabs"]);
|
||||
assert_eq!(stdout(&selected), "", "the config's ignore survives a CLI select");
|
||||
}
|
||||
|
||||
/// An unknown rule name in a config file fails the run and says what is
|
||||
/// known — the same answer a typo'd `--select` gets, named by file.
|
||||
#[test]
|
||||
fn an_unknown_rule_in_the_lint_table_is_an_error() {
|
||||
let dir = TempDir::new("lint-unknown");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
dir.write("lucisv.toml", "[lint]\nignore = [\"no-such-rule\"]\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stderr(&out);
|
||||
assert!(text.contains("unknown rule: no-such-rule"), "{text}");
|
||||
assert!(text.contains("unused-signal"), "the error lists what is known: {text}");
|
||||
assert_eq!(code(&out), 2);
|
||||
}
|
||||
|
||||
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
|
||||
/// with it — §34.0's headline claim, end to end through the real binary.
|
||||
#[test]
|
||||
fn a_per_rule_lint_table_changes_the_verdict() {
|
||||
let dir = TempDir::new("lint-per-rule");
|
||||
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
|
||||
dir.write("m.sv", &wide);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
|
||||
|
||||
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert_eq!(stdout(&out), "", "the option raised the limit");
|
||||
assert_eq!(code(&out), 0);
|
||||
}
|
||||
|
||||
/// A bad entry fails the run naming the config file and the line, which is
|
||||
/// what tells a user *where* to fix it.
|
||||
#[test]
|
||||
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
|
||||
let dir = TempDir::new("lint-bad-option");
|
||||
dir.write("m.sv", "module m;\nendmodule\n");
|
||||
for (config, wanted) in [
|
||||
("[lint.line-length]\nlength = 10\n", "must be between"),
|
||||
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
|
||||
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
|
||||
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
|
||||
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
|
||||
// An escape from another dialect must be refused rather than read
|
||||
// as a literal, which would silently judge the wrong names (QA,
|
||||
// 2026-09-04).
|
||||
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
|
||||
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
|
||||
] {
|
||||
dir.write("lucisv.toml", config);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stderr(&out);
|
||||
assert!(text.contains(wanted), "{config:?}: {text}");
|
||||
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
|
||||
assert_eq!(code(&out), 2, "{config:?}");
|
||||
}
|
||||
// Every one of them names the rule as well as the option, so an error
|
||||
// read out of a CI log stands on its own.
|
||||
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
|
||||
let text = stderr(&run(&["check", &dir.root()]));
|
||||
assert!(text.contains("rule `line-length`"), "{text}");
|
||||
assert!(text.contains("`length` must be between"), "{text}");
|
||||
}
|
||||
|
||||
/// The width `line-length` holds a file to is the width the formatter is
|
||||
/// configured with, so the two halves of lucisv cannot disagree.
|
||||
#[test]
|
||||
fn line_length_follows_the_formatters_width() {
|
||||
let dir = TempDir::new("lint-width");
|
||||
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
|
||||
dir.write("m.sv", &wide);
|
||||
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
|
||||
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
|
||||
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
|
||||
|
||||
dir.write("lucisv.toml", "line-length = 80\n");
|
||||
let from_config = run(&["check", &dir.root()]);
|
||||
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
|
||||
}
|
||||
|
||||
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
|
||||
#[test]
|
||||
fn a_stdin_buffer_reads_the_rule_options_too() {
|
||||
let dir = TempDir::new("lint-stdin-options");
|
||||
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!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
|
||||
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
|
||||
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
|
||||
}
|
||||
|
||||
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
|
||||
/// RTL signal only inside a macro argument — `` `uvm_info(..., $sformatf("%b",
|
||||
/// dut.sig), ...) ``, the commonest VPI-probe shape there is — must silence
|
||||
/// `unused-signal` for that signal. The lexer hands the whole invocation over
|
||||
/// as one token, so this works only because the census splits it.
|
||||
#[test]
|
||||
fn a_signal_named_only_inside_a_macro_argument_is_not_reported_unused() {
|
||||
let dir = TempDir::new("macroarg");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write(
|
||||
"tb.sv",
|
||||
"module tb;\n dut u_dut ();\n initial begin\n\
|
||||
\x20 `uvm_info(\"tb\", $sformatf(\"probe=%b\", u_dut.dbg_probe), UVM_LOW)\n\
|
||||
\x20 end\nendmodule\n",
|
||||
);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stdout(&out);
|
||||
assert!(!text.contains("dbg_probe"), "the macro argument names it: {text}");
|
||||
assert!(text.contains("`dead` is declared but never used"), "and `dead` still reports: {text}");
|
||||
// The format string is a value: a signal called `probe` in another file
|
||||
// must not be silenced by `"probe=%b"` here.
|
||||
let other = TempDir::new("macroargstring");
|
||||
other.write("a.sv", "module a;\n logic probe;\nendmodule\n");
|
||||
other.write(
|
||||
"b.sv",
|
||||
"module b;\n initial `uvm_info(\"t\", $sformatf(\"probe=%b\", 1'b0), UVM_LOW)\nendmodule\n",
|
||||
);
|
||||
assert!(
|
||||
stdout(&run(&["check", &other.root()])).contains("`probe` is declared but never used"),
|
||||
"a string's contents are not mentions"
|
||||
);
|
||||
}
|
||||
|
||||
/// `lucisv check --rules-doc` prints the generated rule reference and nothing
|
||||
/// else. Generated from the registry, so a rule added without documentation
|
||||
/// still shows up here — which is the whole point of the flag.
|
||||
#[test]
|
||||
fn rules_doc_prints_the_generated_reference() {
|
||||
let out = run(&["check", "--rules-doc"]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
let text = stdout(&out);
|
||||
assert_eq!(text.lines().next(), Some("# lucisv lint rules"), "{text}");
|
||||
for rule in vlog_linter::all_rules() {
|
||||
let heading = format!("\n## {}\n", rule.name());
|
||||
assert_eq!(
|
||||
text.matches(&heading).count(),
|
||||
1,
|
||||
"`{}` wants exactly one section in the reference",
|
||||
rule.name()
|
||||
);
|
||||
}
|
||||
// The flag is the tool now, so it agrees with the library by construction.
|
||||
assert_eq!(text, vlog_linter::rules_markdown());
|
||||
}
|
||||
|
||||
/// The flag lints nothing, so a path beside it is a command line that means
|
||||
/// two different things — refused rather than silently ignored.
|
||||
#[test]
|
||||
fn rules_doc_refuses_files_and_belongs_to_check() {
|
||||
let dir = TempDir::new("rulesdoc");
|
||||
let file = dir.write("m.sv", FORMATTED);
|
||||
let out = run(&["check", "--rules-doc", &file]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("--rules-doc takes no files"), "{}", stderr(&out));
|
||||
let out = run(&["format", "--rules-doc"]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(
|
||||
stderr(&out).contains("--rules-doc is only valid for `lucisv check`"),
|
||||
"{}",
|
||||
stderr(&out)
|
||||
);
|
||||
}
|
||||
|
||||
// --- the walk's own warnings (docs/features/small-items-4/README.md) -------
|
||||
|
||||
/// A tree with the two things the walk can only warn about: a directory it
|
||||
/// cannot read, and a source file that is only a broken link.
|
||||
#[cfg(unix)]
|
||||
fn unwalkable_tree(tag: &str) -> TempDir {
|
||||
use std::os::unix::fs::{symlink, PermissionsExt};
|
||||
let dir = TempDir::new(tag);
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
dir.write("z/late.sv", UNFORMATTED);
|
||||
dir.write("locked/hidden.sv", UNFORMATTED);
|
||||
symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
|
||||
.expect("chmod");
|
||||
dir
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn lock(dir: &TempDir) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
|
||||
.expect("chmod");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn unlock(dir: &TempDir) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ =
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
|
||||
// The finding TODO §45.2 closes: one permission-denied directory used to
|
||||
// propagate `read_dir`'s error and fail the whole run.
|
||||
let dir = unwalkable_tree("walk-warn");
|
||||
let out = run(&[&dir.root()]);
|
||||
unlock(&dir);
|
||||
|
||||
assert_eq!(code(&out), 0, "a warning is not a failure: {}", stderr(&out));
|
||||
let said = stderr(&out);
|
||||
assert_eq!(said.matches("warning: ").count(), 2, "{said}");
|
||||
assert!(said.contains("locked"), "{said}");
|
||||
assert!(said.contains("gone.sv: broken symbolic link"), "{said}");
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED, "the other files were formatted");
|
||||
assert_eq!(dir.read("z/late.sv"), FORMATTED, "including the ones sorted after it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
|
||||
let dir = unwalkable_tree("walk-warn-check");
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
unlock(&dir);
|
||||
|
||||
// `--check` answers on formatting alone: two files would be reformatted.
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
|
||||
assert!(!stdout(&out).contains("warning"), "warnings stay off stdout: {}", stdout(&out));
|
||||
|
||||
// And with nothing left to reformat the run is clean, warnings and all.
|
||||
dir.write("a.sv", FORMATTED);
|
||||
dir.write("z/late.sv", FORMATTED);
|
||||
lock(&dir);
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
unlock(&dir);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
|
||||
// The walk drops the link; a path the user typed is not walked at all, so
|
||||
// "no such file or directory" is still what naming one gets.
|
||||
let dir = TempDir::new("walk-warn-named");
|
||||
std::os::unix::fs::symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
|
||||
let named = dir.path.join("gone.sv").to_string_lossy().into_owned();
|
||||
|
||||
let out = run(&[&named]);
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The package half of the census and `unused-import` (perf5-p3, 2026-09-07)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A package with two exported names, and the two importers the rule has to
|
||||
/// tell apart.
|
||||
const PKG: &str = "package p_pkg;\n localparam int A = 1;\n localparam int B = 2;\nendpackage\n";
|
||||
const USES_PKG: &str = "module uses_pkg;\n import p_pkg::*;\n localparam int C = A;\nendmodule\n";
|
||||
const IGNORES_PKG: &str =
|
||||
"module ignores_pkg;\n import p_pkg::*;\n localparam int C = 1;\nendmodule\n";
|
||||
|
||||
/// The style selection the rule lives in — `unused-import` is `Severity::Style`
|
||||
/// and so is off in a default `check`.
|
||||
const ALL_STYLE: [&str; 2] = ["--select", "error,warning,style"];
|
||||
|
||||
/// The headline: over a project, an import nothing in its file uses is
|
||||
/// reported, and one the file does use is not — and it is the *package
|
||||
/// census* that makes the difference, because the rule can only judge an
|
||||
/// import whose package the run can answer for.
|
||||
#[test]
|
||||
fn an_unused_package_import_is_reported_over_a_project() {
|
||||
let dir = TempDir::new("pkg-census");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let out = run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("unused-import"), "{text}");
|
||||
assert!(text.contains("ignores_pkg.sv"), "{text}");
|
||||
assert!(
|
||||
!text.lines().any(|line| line.contains("uses_pkg.sv") && line.contains("unused-import")),
|
||||
"the file that reads `A` keeps its import: {text}"
|
||||
);
|
||||
assert_eq!(code(&out), 1);
|
||||
}
|
||||
|
||||
/// `unused-import` is a style rule, so a default `check` neither reports it
|
||||
/// nor is changed by the presence of a package in the run.
|
||||
#[test]
|
||||
fn a_default_check_says_nothing_about_imports() {
|
||||
let dir = TempDir::new("pkg-default");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert!(!stdout(&out).contains("unused-import"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
/// A package the run does not contain is a package the run cannot answer
|
||||
/// for, and the rule is silent about every import of it. This is the
|
||||
/// conservative direction the whole feature is built around: an accusation
|
||||
/// needs a known export list.
|
||||
#[test]
|
||||
fn an_import_of_a_package_outside_the_run_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-unknown");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write(
|
||||
"stranger.sv",
|
||||
"module stranger;\n import elsewhere_pkg::*;\n localparam int C = 1;\nendmodule\n",
|
||||
);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("elsewhere_pkg"), "an unknown package is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// A package that re-exports from another one answers `None`: only a whole
|
||||
/// project index settles what a re-export chain lets through, and the CLI's
|
||||
/// one-file census will not guess. Every import of it goes quiet.
|
||||
#[test]
|
||||
fn an_import_of_a_re_exporting_package_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-reexport");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write(
|
||||
"r_pkg.sv",
|
||||
"package r_pkg;\n import p_pkg::*;\n export p_pkg::*;\n localparam int D = 1;\n\
|
||||
endpackage\n",
|
||||
);
|
||||
dir.write(
|
||||
"ignores_r.sv",
|
||||
"module ignores_r;\n import r_pkg::*;\n localparam int C = 1;\nendmodule\n",
|
||||
);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("r_pkg"), "a re-export chain is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// Two files declaring one package name is a name the run cannot answer for,
|
||||
/// whatever the two say — `Census::of`'s merge turns the second contribution
|
||||
/// into `None`, and the rule goes quiet about it.
|
||||
#[test]
|
||||
fn an_import_of_a_package_two_files_declare_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-duplicate");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("p_pkg_copy.sv", "package p_pkg;\n localparam int Z = 9;\nendpackage\n");
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("unused-import"), "a duplicate package is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// The gate is a claim about *cost*, not about answers, so the answers get
|
||||
/// their own end-to-end pin: a run whose only package file is surrounded by
|
||||
/// files holding the word `package` in strings and comments reports exactly
|
||||
/// what a run without those files reports.
|
||||
#[test]
|
||||
fn text_that_merely_says_package_changes_no_finding() {
|
||||
let bare = TempDir::new("pkg-bare");
|
||||
bare.write("p_pkg.sv", PKG);
|
||||
bare.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let plain = stdout(&run(&["check", &bare.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
|
||||
let noisy = TempDir::new("pkg-noisy");
|
||||
noisy.write("p_pkg.sv", PKG);
|
||||
noisy.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
noisy.write(
|
||||
"talker.sv",
|
||||
"// package q_pkg; endpackage\n\
|
||||
module talker;\n initial $display(\"package q_pkg; endpackage\");\nendmodule\n",
|
||||
);
|
||||
let with_noise = stdout(&run(&["check", &noisy.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
for finding in plain.lines().filter(|line| line.contains("unused-import")) {
|
||||
let tail = finding.rsplit('/').next().unwrap_or(finding);
|
||||
assert!(with_noise.contains(tail), "{tail} lost: {with_noise}");
|
||||
}
|
||||
assert_eq!(
|
||||
plain.matches("unused-import").count(),
|
||||
with_noise.matches("unused-import").count(),
|
||||
"{plain}\n---\n{with_noise}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//! 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
|
||||
//! full disk or a `^C` between the two leaves the user's source truncated —
|
||||
//! and lucisv's first invariant is that it never corrupts code. Every
|
||||
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
|
||||
//! gets the bytes, and a `rename` over the target publishes them in one step
|
||||
//! that either happened or did not.
|
||||
//!
|
||||
//! Two threads of one process may write one target: the temp names carry a
|
||||
//! per-process counter as well as the pid and are created with `O_EXCL`, so
|
||||
//! each writer owns its own file and neither can see the other's bytes.
|
||||
//!
|
||||
//! Two *processes* writing one target are not coordinated, and deliberately
|
||||
//! so. Both renames are atomic, the later one wins, and the loser's bytes are
|
||||
//! discarded whole — never merged. Both processes formatted the same input
|
||||
//! and `format` is idempotent, so whichever rename lands last leaves the
|
||||
//! file complete and correctly formatted. A lock would buy nothing and would
|
||||
//! be one more thing to leave behind after a `^C`.
|
||||
//!
|
||||
//! See `docs/features/small-items-3/README.md` and
|
||||
//! `docs/features/atomic-write-coordination/README.md`.
|
||||
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Writes `bytes` to `path`, replacing whatever was there in one step.
|
||||
///
|
||||
/// A temp file beside the target takes the bytes, inherits the target's
|
||||
/// permissions when there is a target, and is renamed onto it — `rename` is
|
||||
/// atomic within a directory on every platform lucisv ships to, so a reader
|
||||
/// sees either the old file or the new one and never a truncated one. A
|
||||
/// failure anywhere after the temp exists removes it before returning.
|
||||
///
|
||||
/// The temp is the caller's alone: [`temp_path`] hands out a name no other
|
||||
/// writer in this process will be given, and the file is created with
|
||||
/// `create_new`, so a name that somehow exists is an error and not a shared
|
||||
/// file. Two threads writing one target therefore both succeed, and the
|
||||
/// target ends up holding one thread's whole buffer.
|
||||
///
|
||||
/// A symlinked target is resolved first: `fs::write` writes *through* a
|
||||
/// symlink, so replacing the link itself would silently redirect it at a new
|
||||
/// file and leave the real one stale. The canonical path is what gets
|
||||
/// replaced, which is also what makes the temp land on the target's own
|
||||
/// filesystem — `rename` cannot cross one.
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
let perms = target_permissions(&target);
|
||||
// A rename replaces a file whatever its mode, so a read-only target would
|
||||
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
|
||||
// a file someone made read-only is asking not to be rewritten in place.
|
||||
if perms.as_ref().is_some_and(fs::Permissions::readonly) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("{} is read-only", path.display()),
|
||||
));
|
||||
}
|
||||
let (tmp, mut file) = create_temp(&target, perms.is_some())?;
|
||||
if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
drop(file);
|
||||
if let Err(e) = fs::rename(&tmp, &target) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many temp names one write tries before giving up.
|
||||
///
|
||||
/// A name is only ever handed out once per process, so a collision means a
|
||||
/// leftover from a *previous* process that crashed mid-write and whose pid
|
||||
/// this process now has. A handful of those may sit in one directory; a
|
||||
/// hundred is a directory to clean up by hand, not a race to retry through.
|
||||
const TEMP_ATTEMPTS: u32 = 32;
|
||||
|
||||
/// Creates the temp file, exclusively, and returns it with its path.
|
||||
///
|
||||
/// `replacing` says there is a target whose mode the temp is about to take.
|
||||
/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does
|
||||
/// not revoke a descriptor someone already opened, so the only way a private
|
||||
/// file's replacement can never be read by anyone else is for the temp to be
|
||||
/// private from the moment it exists. With no target there is no earlier mode
|
||||
/// to honour and the umask decides, as `fs::write` would.
|
||||
fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> {
|
||||
let mut opts = OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if replacing {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = replacing;
|
||||
for _ in 0..TEMP_ATTEMPTS {
|
||||
let tmp = temp_path(target)?;
|
||||
match opts.open(&tmp) {
|
||||
Ok(file) => return Ok((tmp, file)),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()),
|
||||
))
|
||||
}
|
||||
|
||||
/// Puts the target's mode on the temp, then the bytes in it.
|
||||
///
|
||||
/// The order is the point on unix: a 0600 target's replacement must not spend
|
||||
/// even an instant holding the file's contents under the umask's broader
|
||||
/// bits. Chmod does not close the handle opened before it, so a mode without
|
||||
/// an owner-write bit still takes the write. Elsewhere `set_permissions`
|
||||
/// takes a path rather than a handle and the mode goes on after the bytes,
|
||||
/// which is the order this always had.
|
||||
fn fill_temp(
|
||||
file: &mut File,
|
||||
tmp: &Path,
|
||||
perms: Option<fs::Permissions>,
|
||||
bytes: &[u8],
|
||||
) -> io::Result<()> {
|
||||
if cfg!(unix) {
|
||||
copy_mode(file, perms);
|
||||
file.write_all(bytes)
|
||||
} else {
|
||||
file.write_all(bytes)?;
|
||||
if let Some(perms) = perms {
|
||||
let _ = fs::set_permissions(tmp, perms);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts the target's mode on the temp through its open handle, which is what
|
||||
/// lets it happen while the temp is still empty. No target means no earlier
|
||||
/// mode to honour, and the umask's stands.
|
||||
fn copy_mode(file: &File, perms: Option<fs::Permissions>) {
|
||||
if let Some(perms) = perms {
|
||||
let _ = file.set_permissions(perms);
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode the temp must end up with: a file someone made executable, or
|
||||
/// private, keeps its bits, because the temp was created with the process
|
||||
/// umask (or 0600) and not with the target's. `None` means there is no target
|
||||
/// — a new file, which takes the umask as `fs::write` would.
|
||||
fn target_permissions(target: &Path) -> Option<fs::Permissions> {
|
||||
fs::metadata(target).ok().map(|m| m.permissions())
|
||||
}
|
||||
|
||||
/// Names handed out by [`temp_path`], one per call for the life of the
|
||||
/// process. Wrapping after 2^64 names is not a scenario.
|
||||
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The temp file's path: hidden, in the target's own directory, and stamped
|
||||
/// with the process id and a per-process counter — the pid keeps two lucisv
|
||||
/// runs apart, the counter keeps two threads of one run apart, and together
|
||||
/// they mean no two writers anywhere are ever given the same name.
|
||||
fn temp_path(target: &Path) -> io::Result<PathBuf> {
|
||||
let dir = target.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = target
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
|
||||
let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let mut tmp = std::ffi::OsString::from(".");
|
||||
tmp.push(name);
|
||||
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
|
||||
Ok(dir.join(tmp))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A directory that removes itself, the way `cache.rs`'s own tests have
|
||||
/// one — no dependency, and no leftovers under `target/`.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"lucisv-atomic-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
fn file(&self, name: &str) -> PathBuf {
|
||||
self.path.join(name)
|
||||
}
|
||||
|
||||
/// Every name in the directory, so a test can say what is *not* there.
|
||||
fn names(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = fs::read_dir(&self.path)
|
||||
.expect("read dir")
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bytes_land_and_no_temp_file_is_left_behind() {
|
||||
let dir = TempDir::new("plain");
|
||||
let file = dir.file("a.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_exist_yet_is_created() {
|
||||
let dir = TempDir::new("create");
|
||||
let file = dir.file("new.sv");
|
||||
write_atomic(&file, b"hello\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
|
||||
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
|
||||
// A directory standing where the file should be: the write succeeds,
|
||||
// the rename cannot.
|
||||
let dir = TempDir::new("dirtarget");
|
||||
let target = dir.file("occupied");
|
||||
fs::create_dir(&target).expect("create dir");
|
||||
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
|
||||
assert!(err.to_string().len() > 1, "{err}");
|
||||
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_the_same_path_twice_leaves_one_file() {
|
||||
let dir = TempDir::new("twice");
|
||||
let file = dir.file("a.sv");
|
||||
write_atomic(&file, b"one\n").expect("write");
|
||||
write_atomic(&file, b"two\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_targets_permissions_are_preserved() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("modes");
|
||||
for mode in [0o600, 0o755] {
|
||||
let file = dir.file(&format!("m{mode:o}.sv"));
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
|
||||
assert_eq!(got, mode, "mode {mode:o} was not preserved");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_read_only_target_is_refused_and_left_alone() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("readonly");
|
||||
let file = dir.file("ro.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
|
||||
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
|
||||
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
|
||||
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
|
||||
let dir = TempDir::new("symlink");
|
||||
let real = dir.file("real.sv");
|
||||
let link = dir.file("link.sv");
|
||||
fs::write(&real, "old\n").expect("seed");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
||||
write_atomic(&link, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
|
||||
assert!(
|
||||
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
|
||||
"the link is still a link"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
|
||||
}
|
||||
|
||||
/// The audit's probe (`docs/repository-analysis.md` finding 1), which
|
||||
/// used to produce 100 write errors in 200 calls: both threads derived
|
||||
/// the same temp name from the target and the pid, so one deleted the
|
||||
/// other's file under it. Now every writer owns its own temp, so every
|
||||
/// call succeeds and the target holds one writer's whole buffer.
|
||||
#[test]
|
||||
fn two_threads_writing_one_target_never_collide() {
|
||||
const MIB: usize = 1024 * 1024;
|
||||
const ROUNDS: usize = 100;
|
||||
let dir = TempDir::new("race");
|
||||
let file = dir.file("a.sv");
|
||||
fs::write(&file, "seed\n").expect("seed");
|
||||
|
||||
// Three parties: the two writers and this thread, which inspects the
|
||||
// target between rounds. Nobody starts a round until everyone has
|
||||
// finished the last one.
|
||||
let start = std::sync::Arc::new(std::sync::Barrier::new(3));
|
||||
let done = std::sync::Arc::new(std::sync::Barrier::new(3));
|
||||
let writers: Vec<_> = (*b"ab")
|
||||
.into_iter()
|
||||
.map(|tag| {
|
||||
let (path, start, done) = (file.clone(), start.clone(), done.clone());
|
||||
std::thread::spawn(move || {
|
||||
let bytes = vec![tag; MIB];
|
||||
let mut errors = Vec::new();
|
||||
for _ in 0..ROUNDS {
|
||||
start.wait();
|
||||
if let Err(e) = write_atomic(&path, &bytes) {
|
||||
errors.push(e.to_string());
|
||||
}
|
||||
done.wait();
|
||||
}
|
||||
errors
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
for round in 0..ROUNDS {
|
||||
start.wait();
|
||||
done.wait();
|
||||
let got = fs::read(&file).expect("read");
|
||||
assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed");
|
||||
let tag = got[0];
|
||||
assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte");
|
||||
assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left");
|
||||
}
|
||||
|
||||
let errors: Vec<String> =
|
||||
writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect();
|
||||
assert!(
|
||||
errors.is_empty(),
|
||||
"{} write errors in {} calls: {errors:?}",
|
||||
errors.len(),
|
||||
2 * ROUNDS
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_thread_gets_its_own_temp_name() {
|
||||
const PER_THREAD: usize = 200;
|
||||
let dir = TempDir::new("names");
|
||||
let target = dir.file("a.sv");
|
||||
let threads: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let target = target.clone();
|
||||
std::thread::spawn(move || {
|
||||
(0..PER_THREAD)
|
||||
.map(|_| temp_path(&target).expect("temp name"))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let names: Vec<PathBuf> =
|
||||
threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect();
|
||||
let unique: std::collections::HashSet<&PathBuf> = names.iter().collect();
|
||||
assert_eq!(unique.len(), names.len(), "a temp name was handed out twice");
|
||||
}
|
||||
|
||||
/// The mode goes on while the temp is still empty, so a 0600 file's
|
||||
/// replacement never holds its contents under the umask's wider bits.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_temp_takes_the_targets_mode_before_any_bytes() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("modewindow");
|
||||
let target = dir.file("secret.sv");
|
||||
fs::write(&target, "old\n").expect("seed");
|
||||
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
|
||||
|
||||
let perms = target_permissions(&target);
|
||||
let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp");
|
||||
// Born private, before any mode is copied onto it: an fd opened by
|
||||
// someone else in this instant would not see the bytes to come.
|
||||
assert_eq!(
|
||||
fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"the temp was created readable by others"
|
||||
);
|
||||
copy_mode(&file, perms.clone());
|
||||
let meta = fs::metadata(&tmp).expect("stat");
|
||||
assert_eq!(meta.len(), 0, "the mode is set before a single byte is written");
|
||||
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable");
|
||||
// And the chmod does not close the door on the handle opened before it.
|
||||
fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill");
|
||||
assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n");
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
|
||||
/// The same window seen from outside, through a real `write_atomic`: a
|
||||
/// big enough buffer that the temp is usually observable while it is
|
||||
/// being filled. It asserts about what it sees and never about seeing it,
|
||||
/// so a scheduler that hides the window cannot fail the test.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_temp_seen_mid_write_is_never_world_readable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("window");
|
||||
let target = dir.file("secret.sv");
|
||||
fs::write(&target, "old\n").expect("seed");
|
||||
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
|
||||
|
||||
let path = target.clone();
|
||||
let writer = std::thread::spawn(move || {
|
||||
let bytes = vec![b'x'; 8 * 1024 * 1024];
|
||||
write_atomic(&path, &bytes)
|
||||
});
|
||||
while !writer.is_finished() {
|
||||
for entry in fs::read_dir(&dir.path).expect("read dir").flatten() {
|
||||
if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
assert_eq!(
|
||||
meta.permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"a temp for a 0600 target was readable by others"
|
||||
);
|
||||
}
|
||||
}
|
||||
writer.join().expect("writer thread").expect("write");
|
||||
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,9 @@ pub struct Entry {
|
||||
pub line_length: usize,
|
||||
/// The `indent` that verdict was reached under.
|
||||
pub indent: usize,
|
||||
/// The `[format] uvm-utils-indent` that verdict was reached under: it
|
||||
/// changes the output of a UVM class, so it is part of the key.
|
||||
pub uvm_utils_indent: bool,
|
||||
}
|
||||
|
||||
/// The cache for one run: loaded once at startup, written once at exit.
|
||||
@@ -87,10 +90,7 @@ impl Cache {
|
||||
if !ignore.exists() {
|
||||
let _ = std::fs::write(&ignore, "*\n");
|
||||
}
|
||||
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
|
||||
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
|
||||
}
|
||||
|
||||
/// The file's text: one line per entry, sorted by path so that two
|
||||
@@ -107,8 +107,8 @@ impl Cache {
|
||||
let entry = &self.entries[path];
|
||||
let _ = writeln!(
|
||||
text,
|
||||
"{:016x}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent
|
||||
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
|
||||
);
|
||||
}
|
||||
text
|
||||
@@ -140,25 +140,49 @@ fn key(path: &Path) -> Option<&str> {
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// The `(content, line-length, indent)` prefix every store line has ever
|
||||
/// begun with, or `None` when those three fields are not what lucisv writes.
|
||||
fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize, usize)> {
|
||||
Some((u64::from_str_radix(content, 16).ok()?, line_length.parse().ok()?, indent.parse().ok()?))
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// another lucisv version are dropped individually; that is staleness, not
|
||||
/// corruption.
|
||||
/// another lucisv version, and lines written in an older field layout, are
|
||||
/// dropped individually; that is staleness, not corruption.
|
||||
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
|
||||
let mut entries = HashMap::new();
|
||||
for line in text.lines() {
|
||||
let mut fields = line.splitn(5, '\t');
|
||||
let content = u64::from_str_radix(fields.next()?, 16).ok()?;
|
||||
let line_length = fields.next()?.parse().ok()?;
|
||||
let indent = fields.next()?.parse().ok()?;
|
||||
let version = fields.next()?;
|
||||
let path = fields.next()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
entries.insert(path.to_string(), Entry { content, line_length, indent });
|
||||
let fields: Vec<&str> = line.splitn(6, '\t').collect();
|
||||
match fields[..] {
|
||||
[content, line_length, indent, uvm, version, path] => {
|
||||
let (content, line_length, indent) = prefix(content, line_length, indent)?;
|
||||
let uvm_utils_indent = uvm.parse().ok()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
entries.insert(
|
||||
path.to_string(),
|
||||
Entry { content, line_length, indent, uvm_utils_indent },
|
||||
);
|
||||
}
|
||||
}
|
||||
// A store written before `uvm-utils-indent` joined the key: a
|
||||
// well-formed line of that older shape says nothing about the
|
||||
// option, so it is dropped individually, exactly like another
|
||||
// version's entry. (The version field alone already makes such
|
||||
// a store miss; the codec stays self-describing anyway.)
|
||||
// Anything else on five fields is corruption and discards the
|
||||
// file like any other malformed line.
|
||||
[content, line_length, indent, _version, path] => {
|
||||
prefix(content, line_length, indent)?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(entries)
|
||||
@@ -204,7 +228,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn entry(content: u64) -> Entry {
|
||||
Entry { content, line_length: 100, indent: 2 }
|
||||
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -237,9 +261,53 @@ mod tests {
|
||||
assert!(!reloaded.is_clean(&file, entry(0xbeef)));
|
||||
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uvm_utils_indent_alone_is_a_different_entry() {
|
||||
let on = Entry { uvm_utils_indent: true, ..entry(0xdead) };
|
||||
assert_ne!(entry(0xdead), on, "the option is part of equality");
|
||||
|
||||
// …and it survives the round trip through the store, on its own.
|
||||
let dir = TempDir::new("uvm");
|
||||
let file = dir.file("a.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&file, on);
|
||||
cache.store();
|
||||
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
|
||||
|
||||
let reloaded = Cache::load(&dir.path);
|
||||
assert!(reloaded.is_clean(&file, on));
|
||||
assert!(!reloaded.is_clean(&file, entry(0xdead)), "the option must invalidate the entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_without_the_option_is_dropped_but_not_fatal() {
|
||||
// The five-field shape lucisv wrote before `uvm-utils-indent` joined
|
||||
// the key: stale, like another version's entry, never corruption.
|
||||
let dir = TempDir::new("oldshape");
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
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 option must not be trusted");
|
||||
assert!(cache.is_clean(&mine, entry(2)), "and it does not discard the rest of the file");
|
||||
|
||||
// And it is not carried forward.
|
||||
cache.store();
|
||||
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_sorted_and_carries_the_version() {
|
||||
let dir = TempDir::new("format");
|
||||
@@ -257,7 +325,7 @@ mod tests {
|
||||
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
|
||||
assert_eq!(
|
||||
lines[0],
|
||||
format!("{:016x}\t100\t2\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
@@ -280,12 +348,15 @@ mod tests {
|
||||
"0000000000000001\twide\t2\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\t0.2.0\n",
|
||||
"0000000000000001\t100\t2\t0.2.0\t\n",
|
||||
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
|
||||
"\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\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
let good =
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
|
||||
@@ -298,7 +369,8 @@ mod tests {
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t0.0.0-not-this-one\t{}\n{:016x}\t100\t2\t{VERSION}\t{}\n",
|
||||
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
@@ -397,7 +469,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.ends_with(".tmp"))
|
||||
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "{leftovers:?}");
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
|
||||
//!
|
||||
//! Only what a three-key config file needs is supported (comments,
|
||||
//! `key = int`, `key = "string"`, `key = ["a", "b"]`); everything else is
|
||||
//! rejected by name rather than ignored. See
|
||||
//! Only what a small config file needs is supported (comments, `key = int`,
|
||||
//! `key = "string"`, `key = ["a", "b"]`, the table `[lint]` and the per-rule
|
||||
//! `[lint.<rule>]` tables); everything else is rejected by name rather than
|
||||
//! ignored. See
|
||||
//! `docs/features/config-discovery/README.md` for the grammar and the
|
||||
//! reasoning behind not taking a TOML dependency.
|
||||
|
||||
@@ -29,6 +30,54 @@ pub struct FileConfig {
|
||||
/// directory, so every `FileConfig` a `Discovery` hands out carries a
|
||||
/// usable path. See `docs/features/filelist/README.md`.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// `[format] uvm-utils-indent`: indent the `` `uvm_field_* `` macro
|
||||
/// statements written between `` `uvm_*_utils_begin `` and
|
||||
/// `` `uvm_*_utils_end ``. Off for the same reason.
|
||||
pub format_uvm_utils_indent: Option<bool>,
|
||||
/// `[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
|
||||
/// run's rules, with the same error a bad `--select` gets.
|
||||
pub lint_select: Option<Vec<String>>,
|
||||
/// `[lint] ignore`: rules dropped from whatever `select` left.
|
||||
pub lint_ignore: Option<Vec<String>>,
|
||||
/// `[lint] waivers`: external waiver files, in the order written.
|
||||
///
|
||||
/// Like [`FileConfig::filelist`], these name *other files*: [`parse`]
|
||||
/// records them exactly as written and [`Discovery`] resolves each one
|
||||
/// against the config file's own directory, so every `FileConfig` a
|
||||
/// `Discovery` hands out carries usable paths. Nothing here reads them —
|
||||
/// their contents name lint rules, and this crate does not know the rule
|
||||
/// registry any more than it does for `select`.
|
||||
pub lint_waivers: Option<Vec<PathBuf>>,
|
||||
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
|
||||
/// order.
|
||||
///
|
||||
/// Neither the rule names nor the option names or their values are
|
||||
/// checked here — this crate does not know the rule registry, exactly as
|
||||
/// it does not know which rule names `select` may hold. `lucisv check`
|
||||
/// resolves them against `vlog_linter`'s specs and fails the run naming
|
||||
/// this file and the line, which is what [`LintOption::line`] is for.
|
||||
pub lint_options: Vec<LintOption>,
|
||||
/// The config file these settings were read from, when they were read
|
||||
/// from one. `parse` leaves it unset — it is handed text, not a path —
|
||||
/// and [`Discovery`] fills it in, so an error about an entry can name the
|
||||
/// file the user has to edit.
|
||||
pub source: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// One `key = value` written under a `[lint.<rule>]` table, as written.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LintOption {
|
||||
/// The rule named by the table header.
|
||||
pub rule: String,
|
||||
/// The option key.
|
||||
pub key: String,
|
||||
/// The value's text, comment stripped, quotes and all — the linter's own
|
||||
/// parser reads it, because only it knows what kind the key takes.
|
||||
pub raw: String,
|
||||
/// 1-based line the entry was written on.
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
|
||||
@@ -38,19 +87,62 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
|
||||
// Editors on some platforms prepend a BOM; it would otherwise garble
|
||||
// key matching on line 1 into an `unknown key` with invisible cause.
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
// Which table the keys below belong to: the top level until a header
|
||||
// opens one, and then that one until the next header. Nothing closes a
|
||||
// table, which is TOML's own rule.
|
||||
let mut table = Table::Top;
|
||||
for (index, raw) in text.lines().enumerate() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
parse_entry(line, &mut config).map_err(|e| format!("{}: {e}", index + 1))?;
|
||||
parse_entry(line, &mut config, &mut table, index + 1)
|
||||
.map_err(|e| format!("{}: {e}", index + 1))?;
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
/// The table whose keys are being read.
|
||||
enum Table {
|
||||
/// Before any header: the formatter's own keys.
|
||||
Top,
|
||||
/// `[lint]`: `select`, `ignore` and `waivers`.
|
||||
Lint,
|
||||
/// `[format]`: the layout keys that are off by default.
|
||||
Format,
|
||||
/// `[lint.<rule>]`: that rule's options.
|
||||
Rule(String),
|
||||
}
|
||||
|
||||
fn parse_entry(
|
||||
line: &str,
|
||||
config: &mut FileConfig,
|
||||
table: &mut Table,
|
||||
number: usize,
|
||||
) -> Result<(), String> {
|
||||
if line.starts_with('[') {
|
||||
return Err("tables (`[section]`) are unsupported in lucisv.toml".to_string());
|
||||
// `[lint]` carries `select`/`ignore`/`waivers`; `[lint.<rule>]` carries that
|
||||
// rule's options, which are stored raw and checked by whoever knows
|
||||
// the registry.
|
||||
if line == "[lint]" {
|
||||
*table = Table::Lint;
|
||||
return Ok(());
|
||||
}
|
||||
if line == "[format]" {
|
||||
*table = Table::Format;
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(rule) = line.strip_prefix("[lint.").and_then(|r| r.strip_suffix(']')) {
|
||||
if rule.is_empty() || rule.contains('.') || rule.contains(' ') {
|
||||
return Err(format!("`{line}` is not a rule table; write `[lint.<rule-name>]`"));
|
||||
}
|
||||
*table = Table::Rule(rule.to_string());
|
||||
return Ok(());
|
||||
}
|
||||
return Err(format!(
|
||||
"unknown table `{line}` \
|
||||
(the tables are `[format]`, `[lint]` and `[lint.<rule-name>]`)"
|
||||
));
|
||||
}
|
||||
let (key, value) =
|
||||
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
|
||||
@@ -59,6 +151,12 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
if value.is_empty() {
|
||||
return Err(format!("`{key}` has no value"));
|
||||
}
|
||||
match table {
|
||||
Table::Format => return parse_format_entry(key, value, config),
|
||||
Table::Lint => return parse_lint_entry(key, value, config),
|
||||
Table::Rule(rule) => return parse_rule_entry(rule, key, value, config, number),
|
||||
Table::Top => {}
|
||||
}
|
||||
match key {
|
||||
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
|
||||
"indent" => set_int(&mut config.indent, key, value, 1, 8),
|
||||
@@ -76,12 +174,90 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
config.filelist = Some(PathBuf::from(parse_string(value)?));
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
Err(format!("unknown key `{key}` (known keys: line-length, indent, exclude, filelist)"))
|
||||
}
|
||||
_ => Err(format!(
|
||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
||||
uvm-utils-indent under `[format]`; \
|
||||
select, ignore, waivers under `[lint]`; and a rule's own options \
|
||||
under `[lint.<rule-name>]`)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[format]` table: a boolean that defaults to off, because
|
||||
/// it changes how already-clean files are laid out and a project has to opt
|
||||
/// in before anything of its moves.
|
||||
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
let slot = match key {
|
||||
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unknown key `{key}` under `[format]` \
|
||||
(the only key is uvm-utils-indent)"
|
||||
))
|
||||
}
|
||||
};
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
*slot = Some(parse_bool(key, value)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `true` or `false`, and nothing else — a misspelling is a typo the user
|
||||
/// wants to hear about, not a silent `false`.
|
||||
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
|
||||
match value {
|
||||
"true" => Ok(true),
|
||||
"false" => Ok(false),
|
||||
_ => Err(format!("`{key}` expects `true` or `false`, found `{value}`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[lint]` table.
|
||||
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
if key == "waivers" {
|
||||
if config.lint_waivers.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
config.lint_waivers = Some(parse_array(value)?.into_iter().map(PathBuf::from).collect());
|
||||
return Ok(());
|
||||
}
|
||||
let slot = match key {
|
||||
"select" => &mut config.lint_select,
|
||||
"ignore" => &mut config.lint_ignore,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unknown key `{key}` under `[lint]` (known keys: select, ignore, waivers)"
|
||||
))
|
||||
}
|
||||
};
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
*slot = Some(parse_array(value)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One `key = value` of a `[lint.<rule>]` table, kept as written.
|
||||
fn parse_rule_entry(
|
||||
rule: &str,
|
||||
key: &str,
|
||||
value: &str,
|
||||
config: &mut FileConfig,
|
||||
line: usize,
|
||||
) -> Result<(), String> {
|
||||
if config.lint_options.iter().any(|held| held.rule == rule && held.key == key) {
|
||||
return Err(format!("duplicate key `{key}` under `[lint.{rule}]`"));
|
||||
}
|
||||
config.lint_options.push(LintOption {
|
||||
rule: rule.to_string(),
|
||||
key: key.to_string(),
|
||||
raw: value.to_string(),
|
||||
line,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_int(
|
||||
slot: &mut Option<usize>,
|
||||
key: &str,
|
||||
@@ -244,10 +420,18 @@ fn load(path: &Path) -> Result<FileConfig, String> {
|
||||
// `filelist` is the one value that names another file, so it is resolved
|
||||
// here — against the config file's own directory, which `parse` cannot
|
||||
// know. An absolute path is left alone (`join` already does that).
|
||||
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
|
||||
if let Some(filelist) = config.filelist.take() {
|
||||
let dir = path.parent().unwrap_or(Path::new("."));
|
||||
config.filelist = Some(dir.join(filelist));
|
||||
}
|
||||
// `[lint] waivers` names other files the same way, and is resolved the
|
||||
// same way: against the config file's directory, an absolute path left
|
||||
// alone by `join`.
|
||||
if let Some(waivers) = config.lint_waivers.take() {
|
||||
config.lint_waivers = Some(waivers.into_iter().map(|file| dir.join(file)).collect());
|
||||
}
|
||||
// So an error about a `[lint.<rule>]` entry can name the file to edit.
|
||||
config.source = Some(path.to_path_buf());
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
@@ -311,6 +495,34 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
);
|
||||
}
|
||||
|
||||
/// `[lint] waivers` names other files, so it resolves the way `filelist`
|
||||
/// does: against the config file's own directory, absolute paths left
|
||||
/// alone. See `docs/features/waiver-files/README.md`.
|
||||
#[test]
|
||||
fn lint_waivers_are_a_list_resolved_against_the_config_files_directory() {
|
||||
assert_eq!(
|
||||
ok("[lint]\nwaivers = [ \"a.waiver\", \"deep/b.waiver\" ]").lint_waivers,
|
||||
Some(vec![PathBuf::from("a.waiver"), PathBuf::from("deep/b.waiver")])
|
||||
);
|
||||
assert_eq!(
|
||||
ok("[lint]\nselect = [\"no-tabs\"]").lint_waivers,
|
||||
None,
|
||||
"absent unless written"
|
||||
);
|
||||
assert!(err("[lint]\nwaivers = \"a.waiver\"").contains("multi-line arrays"));
|
||||
assert!(err("[lint]\nwaivers = []\nwaivers = []").contains("duplicate key `waivers`"));
|
||||
assert!(err("[lint]\nwaiver = []").contains("unknown key `waiver` under `[lint]`"));
|
||||
|
||||
let tree = TempTree::new();
|
||||
tree.write("lucisv.toml", "[lint]\nwaivers = [ \"rtl/a.waiver\", \"/opt/b.waiver\" ]\n");
|
||||
let deep = tree.write("a/b/x.sv", "");
|
||||
let found = Discovery::new(true).for_file(&deep).unwrap();
|
||||
assert_eq!(
|
||||
found.lint_waivers,
|
||||
Some(vec![tree.path.join("rtl/a.waiver"), PathBuf::from("/opt/b.waiver")])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_file_sets_nothing() {
|
||||
assert_eq!(ok(""), FileConfig::default());
|
||||
@@ -366,7 +578,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
|
||||
#[test]
|
||||
fn unsupported_toml_is_named_not_ignored() {
|
||||
assert!(err("[tool.lucisv]\nindent = 2").contains("tables"));
|
||||
assert!(err("[tool.lucisv]\nindent = 2").contains("unknown table"));
|
||||
assert!(err("exclude = [\n \"a\",\n]").contains("multi-line arrays are unsupported"));
|
||||
assert!(err("exclude = [\"a\\tb\"]").contains("escapes"));
|
||||
assert!(err("indent").contains("expected `key = value`"));
|
||||
@@ -376,6 +588,179 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
fn duplicate_keys_are_rejected() {
|
||||
assert!(err("indent = 2\nindent = 4").contains("duplicate key `indent`"));
|
||||
assert!(err("exclude = []\nexclude = []").contains("duplicate key `exclude`"));
|
||||
assert!(
|
||||
err("[lint]\nignore = [\"a\"]\nignore = [\"b\"]").contains("duplicate key `ignore`")
|
||||
);
|
||||
}
|
||||
|
||||
/// The `[format]` table: the layout keys that change how an already-clean
|
||||
/// file is laid out, and so are off unless a checked-in `lucisv.toml`
|
||||
/// turns them on (TODO §54.3).
|
||||
#[test]
|
||||
fn the_format_table_carries_uvm_utils_indent() {
|
||||
assert_eq!(ok("[format]\nuvm-utils-indent = true").format_uvm_utils_indent, Some(true));
|
||||
assert_eq!(ok("[format]\nuvm-utils-indent = false").format_uvm_utils_indent, Some(false));
|
||||
// Absent unless written — which is what makes the default off.
|
||||
assert_eq!(ok("indent = 4").format_uvm_utils_indent, None);
|
||||
assert_eq!(ok("[format]").format_uvm_utils_indent, None);
|
||||
// The formatter keys still work above the table, and nothing closes
|
||||
// the table but the next header.
|
||||
let mixed = parse(
|
||||
"indent = 4\n\n[format]\nuvm-utils-indent = true\n\n[lint]\nignore = [\"no-tabs\"]",
|
||||
)
|
||||
.expect("parses");
|
||||
assert_eq!(mixed.indent, Some(4));
|
||||
assert_eq!(mixed.format_uvm_utils_indent, Some(true));
|
||||
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
|
||||
}
|
||||
|
||||
/// Everything about the table's shape, the way the `[lint]` table's is
|
||||
/// pinned: an unknown key is named, a non-boolean value is refused, and a
|
||||
/// repeated key is an error rather than a last-one-wins.
|
||||
#[test]
|
||||
fn the_format_table_rejects_what_it_does_not_support() {
|
||||
assert!(err("[format]\nbogus = true").contains("unknown key `bogus` under `[format]`"));
|
||||
assert!(err("[format]\nuvm-utils-indent = \"yes\"")
|
||||
.contains("`uvm-utils-indent` expects `true` or `false`, found `\"yes\"`"));
|
||||
assert!(err("[format]\nuvm-utils-indent = 1").contains("expects `true` or `false`"));
|
||||
assert!(err("[format]\nuvm-utils-indent =").contains("has no value"));
|
||||
assert!(err("[format]\nuvm-utils-indent = true\nuvm-utils-indent = false")
|
||||
.contains("duplicate key `uvm-utils-indent`"));
|
||||
// A key before any table still belongs to the top level, and the
|
||||
// top-level unknown-key message names the table it does belong to.
|
||||
assert!(err("uvm-utils-indent = true").contains("unknown key `uvm-utils-indent`"));
|
||||
assert!(err("uvm-utils-indent = true").contains("`[format]`"));
|
||||
// `[format.<anything>]` is not a table this parser knows.
|
||||
assert!(err("[format.uvm]\nx = 1").contains("unknown table"));
|
||||
}
|
||||
|
||||
/// 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).
|
||||
#[test]
|
||||
fn a_bad_format_key_names_the_file_and_line() {
|
||||
let tree = TempTree::new();
|
||||
let config = tree.write("lucisv.toml", "indent = 2\n\n[format]\nuvm-utils-indnet = true\n");
|
||||
let file = tree.write("x.sv", "");
|
||||
let message = Discovery::new(true).for_file(&file).expect_err("expected an error");
|
||||
assert!(message.starts_with(&format!("{}:4: ", config.display())), "{message}");
|
||||
assert!(message.contains("unknown key `uvm-utils-indnet` under `[format]`"), "{message}");
|
||||
// And the key spelled right loads through the same walk.
|
||||
let good = TempTree::new();
|
||||
good.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
|
||||
let sv = good.write("a/b/x.sv", "");
|
||||
assert_eq!(Discovery::new(true).for_file(&sv).unwrap().format_uvm_utils_indent, Some(true));
|
||||
}
|
||||
|
||||
/// The `[lint]` table: the off switch a round that turns rules on by
|
||||
/// default owes its users (topo §2.9-4).
|
||||
#[test]
|
||||
fn the_lint_table_carries_select_and_ignore() {
|
||||
let config =
|
||||
parse("[lint]\nselect = [\"no-tabs\", \"unused-signal\"]\nignore = [\"no-tabs\"]")
|
||||
.expect("parses");
|
||||
assert_eq!(
|
||||
config.lint_select.as_deref(),
|
||||
Some(&["no-tabs".to_string(), "unused-signal".to_string()][..])
|
||||
);
|
||||
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
|
||||
// Both are absent unless written, and the formatter keys still work
|
||||
// above the table.
|
||||
let mixed = parse("indent = 4\n\n[lint]\nignore = [\"unused-signal\"]").expect("parses");
|
||||
assert_eq!(mixed.indent, Some(4));
|
||||
assert_eq!(mixed.lint_select, None);
|
||||
assert_eq!(parse("indent = 4").expect("parses").lint_ignore, None);
|
||||
}
|
||||
|
||||
/// Rule *names* are not this crate's business — it has no registry to
|
||||
/// check them against — but everything about the table's shape is.
|
||||
#[test]
|
||||
fn the_lint_table_rejects_what_it_does_not_support() {
|
||||
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
|
||||
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
|
||||
assert!(err("[lint.]\nx = 1").contains("not a rule table"));
|
||||
assert!(err("[lint.a.b]\nx = 1").contains("not a rule table"));
|
||||
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
|
||||
// A key before any table still belongs to the top level.
|
||||
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
|
||||
// Nothing closes the table — TOML's own rule, spelled out.
|
||||
assert_eq!(
|
||||
parse("[lint]\nselect = [\"no-tabs\"]").expect("parses").lint_select.as_deref(),
|
||||
Some(&["no-tabs".to_string()][..])
|
||||
);
|
||||
}
|
||||
|
||||
/// The per-rule tables: stored exactly as written, because this crate
|
||||
/// has no idea what a rule is or what its options take.
|
||||
#[test]
|
||||
fn a_rule_table_keeps_its_entries_as_written() {
|
||||
let config = parse(
|
||||
"[lint]\nignore = [\"no-tabs\"]\n\n\
|
||||
[lint.line-length]\nlength = 120\n\n\
|
||||
[lint.signal-name-style]\nstyle_regex = \"[a-z_0-9]+\" # ours\n",
|
||||
)
|
||||
.expect("parses");
|
||||
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
|
||||
let entries: Vec<(&str, &str, &str, usize)> = config
|
||||
.lint_options
|
||||
.iter()
|
||||
.map(|o| (o.rule.as_str(), o.key.as_str(), o.raw.as_str(), o.line))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
entries,
|
||||
vec![
|
||||
("line-length", "length", "120", 5),
|
||||
("signal-name-style", "style_regex", "\"[a-z_0-9]+\"", 8),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A backslash is legal in an option value and refused in a top-level
|
||||
/// string: the linter's own parser reads the former, and a pattern is the
|
||||
/// one value that needs them.
|
||||
#[test]
|
||||
fn a_rule_option_value_is_not_string_checked_here() {
|
||||
let config =
|
||||
parse("[lint.signal-name-style]\nstyle_regex = \"[a-z]\\d+\"\n").expect("parses");
|
||||
assert_eq!(config.lint_options[0].raw, "\"[a-z]\\d+\"");
|
||||
assert!(err("exclude = [\"a\\d\"]").contains("escapes"), "still refused up here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rule_table_rejects_a_repeated_key_and_a_bad_header() {
|
||||
assert!(err("[lint.line-length]\nlength = 1\nlength = 2")
|
||||
.contains("duplicate key `length` under `[lint.line-length]`"));
|
||||
// The same key under two different rules is two different options.
|
||||
let config = parse(
|
||||
"[lint.enum-name-style]\nstyle_regex = \"a\"\n\
|
||||
[lint.module-name-style]\nstyle_regex = \"b\"\n",
|
||||
)
|
||||
.expect("parses");
|
||||
assert_eq!(config.lint_options.len(), 2);
|
||||
assert!(err("[lint.a b]\nx = 1").contains("not a rule table"));
|
||||
}
|
||||
|
||||
/// Nothing closes a table: the keys after a rule header belong to it
|
||||
/// until the next header, and a formatter key written there is that
|
||||
/// rule's option as far as this parser is concerned.
|
||||
#[test]
|
||||
fn a_rule_table_runs_until_the_next_header() {
|
||||
let config =
|
||||
parse("indent = 4\n[lint.line-length]\nlength = 120\nindent = 8\n").expect("parses");
|
||||
assert_eq!(config.indent, Some(4));
|
||||
assert_eq!(config.lint_options.len(), 2);
|
||||
assert_eq!(config.lint_options[1].key, "indent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_config_file_records_where_it_came_from() {
|
||||
let tree = TempTree::new();
|
||||
let written = tree.write("lucisv.toml", "[lint.line-length]\nlength = 120\n");
|
||||
let file = tree.write("x.sv", "");
|
||||
let found = Discovery::new(true).for_file(&file).expect("reads");
|
||||
assert_eq!(found.source.as_deref(), Some(written.as_path()));
|
||||
// `parse` alone has no path to record.
|
||||
assert_eq!(parse("indent = 4").expect("parses").source, None);
|
||||
}
|
||||
|
||||
/// A throwaway directory tree under the system temp dir.
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! 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,
|
||||
//! `docs/features/mcp-edit-tools/README.md`); the CLI re-exports it.
|
||||
//!
|
||||
//! The hunks are not a minimal edit script: on a divergence the two
|
||||
//! sides are resynchronized with a bounded forward search. That keeps
|
||||
//! the code short and the memory linear, at the cost of occasionally
|
||||
//! reporting a coarser change than GNU `diff` would.
|
||||
|
||||
/// Unchanged lines printed around each hunk.
|
||||
const CONTEXT: usize = 3;
|
||||
/// Unchanged lines that must line up before the sides count as resynced.
|
||||
const SYNC_RUN: usize = 3;
|
||||
/// How far ahead a resynchronization point is searched for.
|
||||
const MAX_SCAN: usize = 200;
|
||||
/// Pseudo-line standing in for a missing final newline.
|
||||
const NO_NEWLINE: &str = "\\ No newline at end of file";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Tag {
|
||||
Keep,
|
||||
Del,
|
||||
Ins,
|
||||
}
|
||||
|
||||
/// Renders the changes from `old` to `new` as a unified-style diff.
|
||||
/// Returns an empty string if the two texts are equal.
|
||||
pub fn unified(path: &str, old: &str, new: &str) -> String {
|
||||
if old == new {
|
||||
return String::new();
|
||||
}
|
||||
let old = split_lines(old);
|
||||
let new = split_lines(new);
|
||||
let edits = edits(&old, &new);
|
||||
let mut out = format!("--- {path}\n+++ {path}\n");
|
||||
render_hunks(&edits, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Splits into lines *keeping* each terminator, so a final line with no
|
||||
/// newline compares unequal to its terminated twin and shows up as a
|
||||
/// change, exactly as GNU diff treats it.
|
||||
fn split_lines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut rest = text;
|
||||
while !rest.is_empty() {
|
||||
let end = rest.find('\n').map_or(rest.len(), |p| p + 1);
|
||||
lines.push(&rest[..end]);
|
||||
rest = &rest[end..];
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn edits<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(Tag, &'a str)> {
|
||||
let mut out = Vec::new();
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < old.len() && j < new.len() {
|
||||
if old[i] == new[j] {
|
||||
out.push((Tag::Keep, old[i]));
|
||||
i += 1;
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((di, dj)) = resync(old, new, i, j) else { break };
|
||||
out.extend(old[i..i + di].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..j + dj].iter().map(|l| (Tag::Ins, *l)));
|
||||
i += di;
|
||||
j += dj;
|
||||
}
|
||||
out.extend(old[i..].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..].iter().map(|l| (Tag::Ins, *l)));
|
||||
out
|
||||
}
|
||||
|
||||
/// Finds the smallest pair of skip counts that puts the two sides back
|
||||
/// in step, preferring the shortest total divergence.
|
||||
fn resync(old: &[&str], new: &[&str], i: usize, j: usize) -> Option<(usize, usize)> {
|
||||
for d in 1..=MAX_SCAN {
|
||||
for k in 0..=d {
|
||||
for (di, dj) in [(d, k), (k, d)] {
|
||||
if i + di <= old.len() && j + dj <= new.len() && in_step(old, new, i + di, j + dj) {
|
||||
return Some((di, dj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn in_step(old: &[&str], new: &[&str], i: usize, j: usize) -> bool {
|
||||
let available = (old.len() - i).min(new.len() - j);
|
||||
if available == 0 {
|
||||
// Both sides running out together is a valid resync point.
|
||||
return old.len() - i == new.len() - j;
|
||||
}
|
||||
(0..SYNC_RUN.min(available)).all(|k| old[i + k] == new[j + k])
|
||||
}
|
||||
|
||||
fn render_hunks(edits: &[(Tag, &str)], out: &mut String) {
|
||||
// Line numbers each edit occupies on the old and the new side.
|
||||
let mut rows = Vec::with_capacity(edits.len());
|
||||
let (mut old_no, mut new_no) = (1usize, 1usize);
|
||||
for &(tag, text) in edits {
|
||||
rows.push((tag, text, old_no, new_no));
|
||||
match tag {
|
||||
Tag::Keep => {
|
||||
old_no += 1;
|
||||
new_no += 1;
|
||||
}
|
||||
Tag::Del => old_no += 1,
|
||||
Tag::Ins => new_no += 1,
|
||||
}
|
||||
}
|
||||
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let Some(first) = (start..rows.len()).find(|&r| rows[r].0 != Tag::Keep) else { break };
|
||||
let mut last = first;
|
||||
// Extend while the next change is close enough that its context
|
||||
// would touch this hunk's.
|
||||
loop {
|
||||
let reach = (last + 2 * CONTEXT + 1).min(rows.len());
|
||||
match (last + 1..reach).find(|&r| rows[r].0 != Tag::Keep) {
|
||||
Some(next) => last = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
let from = first.saturating_sub(CONTEXT);
|
||||
let to = (last + CONTEXT + 1).min(rows.len());
|
||||
render_one_hunk(&rows[from..to], out);
|
||||
start = to;
|
||||
}
|
||||
}
|
||||
|
||||
fn render_one_hunk(rows: &[(Tag, &str, usize, usize)], out: &mut String) {
|
||||
let old_count = rows.iter().filter(|r| r.0 != Tag::Ins).count();
|
||||
let new_count = rows.iter().filter(|r| r.0 != Tag::Del).count();
|
||||
let (old_start, new_start) = (rows[0].2, rows[0].3);
|
||||
out.push_str(&format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n"));
|
||||
for &(tag, text, _, _) in rows {
|
||||
let sign = match tag {
|
||||
Tag::Keep => ' ',
|
||||
Tag::Del => '-',
|
||||
Tag::Ins => '+',
|
||||
};
|
||||
out.push(sign);
|
||||
match text.strip_suffix('\n') {
|
||||
Some(body) => {
|
||||
out.push_str(body);
|
||||
out.push('\n');
|
||||
}
|
||||
None => {
|
||||
// patch(1) expects the marker bare, on its own line,
|
||||
// directly after the unterminated line.
|
||||
out.push_str(text);
|
||||
out.push('\n');
|
||||
out.push_str(NO_NEWLINE);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn equal_texts_produce_nothing() {
|
||||
assert_eq!(unified("f.sv", "a\nb\n", "a\nb\n"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_line_change_keeps_context() {
|
||||
let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n";
|
||||
let new = "1\n2\n3\n4\nX\n6\n7\n8\n9\n";
|
||||
let d = unified("f.sv", old, new);
|
||||
assert!(d.starts_with("--- f.sv\n+++ f.sv\n@@ -2,7 +2,7 @@\n"), "{d}");
|
||||
assert!(d.contains("\n-5\n+X\n"), "{d}");
|
||||
// Context is bounded: the first and last lines stay out of it.
|
||||
assert!(!d.contains("\n 1\n"), "{d}");
|
||||
assert!(!d.contains("\n 9\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distant_changes_become_separate_hunks() {
|
||||
let old: String = (0..40).map(|i| format!("{i}\n")).collect();
|
||||
let new = old.replace("\n1\n", "\nX\n").replace("\n30\n", "\nY\n");
|
||||
let d = unified("f.sv", &old, &new);
|
||||
assert_eq!(d.matches("@@ ").count(), 2, "{d}");
|
||||
assert!(d.contains("-1\n+X\n") && d.contains("-30\n+Y\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insertions_and_deletions_are_reported_separately() {
|
||||
let d = unified("f.sv", "a\nb\nc\n", "a\nb\nb2\nc\n");
|
||||
assert!(d.contains("+b2\n"), "{d}");
|
||||
assert!(!d.contains("-b\n"), "{d}");
|
||||
|
||||
let d = unified("f.sv", "a\nb\nc\nd\n", "a\nc\nd\n");
|
||||
assert!(d.contains("-b\n"), "{d}");
|
||||
// No insertions in the hunk body (the `+++` header line aside).
|
||||
assert!(!d.lines().skip(2).any(|l| l.starts_with('+')), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_final_newline_matches_patch_format() {
|
||||
// The unterminated line is the change; the marker follows it bare.
|
||||
let d = unified("f.sv", "a\nb", "a\nb\n");
|
||||
assert!(d.contains("-b\n\\ No newline at end of file\n+b\n"), "{d}");
|
||||
let d = unified("f.sv", "a\nb\n", "a\nb");
|
||||
assert!(d.contains("-b\n+b\n\\ No newline at end of file\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wholly_different_texts_diff_as_replacement() {
|
||||
let d = unified("f.sv", "a\nb\n", "x\ny\n");
|
||||
assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}");
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,17 @@
|
||||
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
|
||||
//! `cache` answers the third question of the same family — whether a file
|
||||
//! needs to be processed at all, and `filelist` answers the first one the way
|
||||
//! an EDA project already does, from a `.f` file. See
|
||||
//! 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
|
||||
//! `docs/features/lucisv-core-lift/README.md`, and
|
||||
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
|
||||
//! for the rules themselves.
|
||||
|
||||
pub mod atomic;
|
||||
pub mod cache;
|
||||
pub mod config;
|
||||
pub mod diff;
|
||||
pub mod filelist;
|
||||
pub mod walk;
|
||||
+759
-25
@@ -2,6 +2,7 @@
|
||||
//! `.gitignore` subset documented in
|
||||
//! `docs/features/parallel-files/README.md`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File extensions lucisv formats when walking a directory.
|
||||
@@ -10,79 +11,390 @@ pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
|
||||
/// The name of the per-directory ignore file that is honoured by default.
|
||||
const GITIGNORE: &str = ".gitignore";
|
||||
|
||||
/// Something the walk could not do and went on regardless: a directory it
|
||||
/// could not read, an ignore file it could not open, a source file that is
|
||||
/// only a broken link.
|
||||
///
|
||||
/// The walk's warning channel exists because none of these is worth failing a
|
||||
/// run over — one unreadable directory used to drop every file already found
|
||||
/// — and because a silent skip loses the user the fact entirely. Rendering is
|
||||
/// the front end's job: the CLI writes `warning: <path>: <message>` to stderr,
|
||||
/// the server logs the same text once per scan.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Warning {
|
||||
/// What could not be used.
|
||||
pub path: PathBuf,
|
||||
/// Why, in the operating system's own words where there are any.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Warning {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}", self.path.display(), self.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `input` to `files`: the file itself, or every Verilog file under
|
||||
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
|
||||
/// to directory walks only — a path named on the command line is always
|
||||
/// formatted.
|
||||
///
|
||||
/// `warn` is called once for everything the walk skipped and wants said; see
|
||||
/// [`Warning`]. Only `input` itself naming nothing is an error — that is the
|
||||
/// user's own typo, and the run has nothing to do.
|
||||
pub fn collect_files(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
files: &mut Vec<PathBuf>,
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
collect_files_with(input, exclude, gitignore, &mut |path, _| files.push(path), warn)
|
||||
}
|
||||
|
||||
/// [`collect_files`] with the size the walk already read handed on beside each
|
||||
/// path.
|
||||
///
|
||||
/// The same walk, the same order, the same warnings — the only difference is
|
||||
/// where a file goes when it is found. A directory walk already calls
|
||||
/// `metadata` on every entry to answer "directory?", so the length is a field
|
||||
/// of a struct it holds anyway; a caller that has to know how big a file is —
|
||||
/// the server's `lucisv.index.maxFileSize` cap — would otherwise ask the
|
||||
/// filesystem the same question a second time, once per file.
|
||||
/// `docs/features/perf5r-first-answer/README.md` measured that second `stat`
|
||||
/// at 6.9 ms of a 165 ms discovery over 3 976 files — small, because the walk
|
||||
/// has just warmed every one of those inodes, and 3 976 system calls that buy
|
||||
/// a number already in hand all the same.
|
||||
///
|
||||
/// **`None` means the walk did not look.** `input` naming a file rather than a
|
||||
/// directory is handed straight over, exactly as [`collect_files`] hands it
|
||||
/// over, with no `metadata` call added to a path that never needed one — so a
|
||||
/// caller that wants a size there asks for it itself. Every path a *directory
|
||||
/// walk* yields carries `Some`.
|
||||
pub fn collect_files_with(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
found: &mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
collect_files_tracked(input, exclude, gitignore, &mut tracker, found, warn)
|
||||
}
|
||||
|
||||
/// [`collect_files_with`] using an existing [`DirectoryTracker`].
|
||||
pub fn collect_files_tracked(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
tracker: &mut DirectoryTracker,
|
||||
found: &mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let path = Path::new(input);
|
||||
if path.is_dir() {
|
||||
let mut walk = Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), files };
|
||||
walk.dir(path).map_err(|e| format!("{input}: {e}"))?;
|
||||
let mut walk =
|
||||
Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn };
|
||||
walk.dir(path);
|
||||
} else if path.is_file() {
|
||||
files.push(path.to_path_buf());
|
||||
found(path.to_path_buf(), None);
|
||||
} else {
|
||||
return Err(format!("{input}: no such file or directory"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`collect_files_with`] over `input`, which lies **under** `root`, finding
|
||||
/// exactly what a walk of `root` would have found there.
|
||||
///
|
||||
/// The difference from walking `input` directly is the `.gitignore` files
|
||||
/// between the two. A walk reads ignore rules from its own starting directory
|
||||
/// downwards, so `collect_files_with("<root>/hw/ip/aes")` never sees the rule
|
||||
/// `<root>/.gitignore` writes about `hw/ip/aes/gen/` — and a caller walking a
|
||||
/// subtree *of a scope whose rung is the root* would then index files that
|
||||
/// scope excludes. This one walks the ancestor chain first: it reads each
|
||||
/// ancestor's `.gitignore` onto the stack with the depth it belongs at, and it
|
||||
/// stops without yielding anything when one of those ancestors is itself
|
||||
/// ignored or excluded — because a walk of `root` would never have descended
|
||||
/// into it.
|
||||
///
|
||||
/// `input` not being under `root` is the caller's mistake and is answered the
|
||||
/// way a walk of an unknown path is: nothing found, and no error, since there
|
||||
/// is no ancestor chain to apply.
|
||||
///
|
||||
/// Everything else is [`collect_files_with`]: the same order, the same cycle
|
||||
/// guard, the same warnings, the same lengths.
|
||||
pub fn collect_files_below(
|
||||
root: &Path,
|
||||
input: &Path,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
found: &mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
collect_files_below_tracked(root, input, exclude, gitignore, &mut tracker, found, warn)
|
||||
}
|
||||
|
||||
/// [`collect_files_below`] using an existing [`DirectoryTracker`].
|
||||
pub fn collect_files_below_tracked(
|
||||
root: &Path,
|
||||
input: &Path,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
tracker: &mut DirectoryTracker,
|
||||
found: &mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let Ok(below) = input.strip_prefix(root) else { return Ok(()) };
|
||||
if !input.is_dir() {
|
||||
return Err(format!("{}: no such file or directory", input.display()));
|
||||
}
|
||||
let mut walk =
|
||||
Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn };
|
||||
// The root's own `.gitignore` sits at depth 0, exactly where a walk of the
|
||||
// root would have put it.
|
||||
walk.push_ignore(root);
|
||||
let mut here = root.to_path_buf();
|
||||
let names: Vec<String> = below.iter().map(|name| name.to_string_lossy().into_owned()).collect();
|
||||
for (at, name) in names.iter().enumerate() {
|
||||
here.push(name);
|
||||
if is_excluded(&here, exclude) {
|
||||
return Ok(());
|
||||
}
|
||||
walk.rel.push(name.clone());
|
||||
if is_ignored(&walk.ignores, &walk.rel, true) {
|
||||
return Ok(());
|
||||
}
|
||||
// Not `input`'s own — `Walk::dir` pushes that one itself, and pushing
|
||||
// it twice would apply its rules at two different depths.
|
||||
if at + 1 < names.len() {
|
||||
walk.push_ignore(&here);
|
||||
}
|
||||
}
|
||||
walk.dir(input);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How a directory is recognised as one the walk has already entered. Two
|
||||
/// names for the same directory — a symlink and its target, or two symlinks
|
||||
/// pointing at one place — must map to the same identity, or a cycle has no
|
||||
/// end. On unix that is `(dev, ino)`, the pair the filesystem itself uses;
|
||||
/// elsewhere it is the canonical path, which resolves symlinks the same way
|
||||
/// at the cost of a real path lookup.
|
||||
#[cfg(unix)]
|
||||
pub type DirId = (u64, u64);
|
||||
#[cfg(not(unix))]
|
||||
pub type DirId = PathBuf;
|
||||
|
||||
/// The identity of the directory at `path`, or `None` when it cannot be
|
||||
/// read — a dangling symlink, or a directory that vanished mid-walk.
|
||||
#[cfg(unix)]
|
||||
pub fn dir_id(path: &Path) -> Option<DirId> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
Some((meta.dev(), meta.ino()))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
pub fn dir_id(path: &Path) -> Option<DirId> {
|
||||
std::fs::canonicalize(path).ok()
|
||||
}
|
||||
|
||||
/// What happened when attempting to enter a directory with [`DirectoryTracker`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DirStatus {
|
||||
/// Entered for the first time.
|
||||
EnteredFirstTime,
|
||||
/// Already visited under the same or an earlier path.
|
||||
AlreadyVisited,
|
||||
/// Previously entered under `recorded`, but `dir < recorded` indicating
|
||||
/// out-of-order traversal relative to a canonical root walk.
|
||||
PrecedenceConflict { recorded: PathBuf },
|
||||
}
|
||||
|
||||
/// Tracks visited directories across one or more walks to ensure cycle termination
|
||||
/// and detect order divergence.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DirectoryTracker {
|
||||
visited: HashMap<DirId, PathBuf>,
|
||||
has_conflict: bool,
|
||||
}
|
||||
|
||||
impl DirectoryTracker {
|
||||
/// Creates an empty directory tracker.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Records `dir` as entered and returns its [`DirStatus`].
|
||||
pub fn enter(&mut self, dir: &Path) -> DirStatus {
|
||||
let Some(id) = dir_id(dir) else {
|
||||
return DirStatus::AlreadyVisited;
|
||||
};
|
||||
match self.visited.entry(id) {
|
||||
std::collections::hash_map::Entry::Vacant(v) => {
|
||||
v.insert(dir.to_path_buf());
|
||||
DirStatus::EnteredFirstTime
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(o) => {
|
||||
let recorded = o.get();
|
||||
if dir < recorded.as_path() {
|
||||
self.has_conflict = true;
|
||||
DirStatus::PrecedenceConflict { recorded: recorded.clone() }
|
||||
} else {
|
||||
DirStatus::AlreadyVisited
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any precedence conflict was observed across walks.
|
||||
pub fn has_conflict(&self) -> bool {
|
||||
self.has_conflict
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `path` names one of the source files lucisv formats.
|
||||
fn is_source(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
|
||||
}
|
||||
|
||||
/// One directory walk. `rel` is the path of the directory currently being
|
||||
/// read, in components relative to the walk root, which is what
|
||||
/// `.gitignore` rules are matched against; `ignores` is the stack of
|
||||
/// ignore files seen from the root down to it.
|
||||
/// ignore files seen from the root down to it; `visited` is every directory
|
||||
/// already entered, by identity rather than by spelling.
|
||||
struct Walk<'a> {
|
||||
exclude: &'a [String],
|
||||
gitignore: bool,
|
||||
ignores: Vec<Ignore>,
|
||||
rel: Vec<String>,
|
||||
files: &'a mut Vec<PathBuf>,
|
||||
tracker: &'a mut DirectoryTracker,
|
||||
/// Where a source file goes when the walk finds one, with the length the
|
||||
/// walk's own `metadata` call already read.
|
||||
found: &'a mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &'a mut dyn FnMut(Warning),
|
||||
}
|
||||
|
||||
impl Walk<'_> {
|
||||
fn dir(&mut self, dir: &Path) -> std::io::Result<()> {
|
||||
let pushed = self.push_ignore(dir)?;
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
fn dir(&mut self, dir: &Path) {
|
||||
if !self.enter(dir) {
|
||||
return;
|
||||
}
|
||||
let pushed = self.push_ignore(dir);
|
||||
self.entries(dir);
|
||||
if pushed {
|
||||
self.ignores.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// One directory's entries, in name order. A directory that cannot be read
|
||||
/// — the permission-denied one somewhere under the start — is said and
|
||||
/// skipped: everything already found stays found and the walk goes on,
|
||||
/// which is the whole reason this channel exists.
|
||||
fn entries(&mut self, dir: &Path) {
|
||||
let read = match std::fs::read_dir(dir) {
|
||||
Ok(read) => read,
|
||||
Err(e) => return self.say(dir, e.to_string()),
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
for entry in read {
|
||||
match entry {
|
||||
Ok(entry) => entries.push(entry),
|
||||
Err(e) => self.say(dir, e.to_string()),
|
||||
}
|
||||
}
|
||||
entries.sort_by_key(|e| e.path());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if is_excluded(&path, self.exclude) {
|
||||
continue;
|
||||
}
|
||||
let is_dir = path.is_dir();
|
||||
// One `metadata` call per entry, exactly as before — it follows
|
||||
// symlinks, so it answers "directory?" for a symlinked directory
|
||||
// the way `is_dir()` did. A dangling symlink has no metadata at
|
||||
// all. One that *names a source file* is warned about and dropped:
|
||||
// §43's QA was right that a silent skip loses the user the fact,
|
||||
// and §45.2 gives that fact a home of its own rather than handing
|
||||
// the path on to fail as "no such file" in the front end. One that
|
||||
// names anything else was never going to be read, and is skipped
|
||||
// as quietly as it always was.
|
||||
let Ok(meta) = std::fs::metadata(&path) else {
|
||||
if is_source(&path) {
|
||||
let why = broken_link_reason(&path);
|
||||
self.say(&path, why);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
self.rel.push(entry.file_name().to_string_lossy().into_owned());
|
||||
if !is_ignored(&self.ignores, &self.rel, is_dir) {
|
||||
if is_dir {
|
||||
self.dir(&path)?;
|
||||
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
if EXTENSIONS.contains(&ext) {
|
||||
self.files.push(path);
|
||||
}
|
||||
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
|
||||
if meta.is_dir() {
|
||||
self.dir(&path);
|
||||
} else if meta.is_file() && is_source(&path) {
|
||||
// The length comes off the `metadata` above — the same
|
||||
// call that answered "directory?" — so a caller wanting it
|
||||
// costs the walk nothing at all.
|
||||
(self.found)(path, Some(meta.len()));
|
||||
}
|
||||
}
|
||||
self.rel.pop();
|
||||
}
|
||||
if pushed {
|
||||
self.ignores.pop();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hand one warning to the front end.
|
||||
fn say(&mut self, path: &Path, message: String) {
|
||||
(self.warn)(Warning { path: path.to_path_buf(), message });
|
||||
}
|
||||
|
||||
/// Records `dir` as entered, and answers whether it had not been entered
|
||||
/// already. Identity, not spelling: `a/loop -> a` and `a/b/up -> ..` name
|
||||
/// a directory the walk is already inside, and following either is the
|
||||
/// cycle that only ends when the OS refuses a path. A symlink to a
|
||||
/// directory the walk has *not* seen is followed once, so
|
||||
/// `rtl -> ../shared/rtl` still contributes its files; the second link to
|
||||
/// one target contributes nothing further, and the files are reported
|
||||
/// under the first spelling that reached them.
|
||||
///
|
||||
/// A directory whose identity cannot be read is not entered.
|
||||
fn enter(&mut self, dir: &Path) -> bool {
|
||||
matches!(self.tracker.enter(dir), DirStatus::EnteredFirstTime)
|
||||
}
|
||||
|
||||
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
|
||||
/// Returns whether anything was pushed, so `dir` can pop it again.
|
||||
fn push_ignore(&mut self, dir: &Path) -> std::io::Result<bool> {
|
||||
///
|
||||
/// An ignore file that cannot be read is said and ignored, for the same
|
||||
/// reason an unreadable directory is: the walk that finds too much is a
|
||||
/// better failure than the walk that finds nothing.
|
||||
fn push_ignore(&mut self, dir: &Path) -> bool {
|
||||
let path = dir.join(GITIGNORE);
|
||||
if !self.gitignore || !path.is_file() {
|
||||
return Ok(false);
|
||||
return false;
|
||||
}
|
||||
let rules = parse_gitignore(&std::fs::read_to_string(&path)?);
|
||||
self.ignores.push(Ignore { base: self.rel.len(), rules });
|
||||
Ok(true)
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => {
|
||||
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
self.say(&path, e.to_string());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a directory entry has no metadata, said the way a person would.
|
||||
///
|
||||
/// A broken symbolic link is what this is nearly always about, and naming it
|
||||
/// as one is worth more than the bare `No such file or directory` the follow
|
||||
/// produced; anything else keeps the operating system's own words.
|
||||
fn broken_link_reason(path: &Path) -> String {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(meta) if meta.file_type().is_symlink() => "broken symbolic link".to_string(),
|
||||
Ok(_) => "cannot be read".to_string(),
|
||||
Err(e) => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +526,8 @@ fn glob_component(pattern: &str, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(unix)]
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn excluded(path: &str, pattern: &str) -> bool {
|
||||
is_excluded(Path::new(path), &[pattern.to_string()])
|
||||
@@ -320,6 +634,393 @@ mod tests {
|
||||
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Symlink cycles — `docs/features/walk-cycles/README.md`
|
||||
//
|
||||
// Every test below builds a real tree with real symlinks, because the
|
||||
// question is what the filesystem answers, not what a mock does. Each
|
||||
// one would run until the OS refused a path before the visited set.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A throwaway directory tree under the system temp dir, removed on
|
||||
/// drop. `remove_dir_all` unlinks a symlink instead of following it, so
|
||||
/// a tree with a cycle in it is cleaned up like any other.
|
||||
#[cfg(unix)]
|
||||
struct TempTree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl TempTree {
|
||||
fn new(tag: &str) -> TempTree {
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv-walk-{}-{tag}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempTree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
std::fs::write(&path, text).expect("write");
|
||||
}
|
||||
|
||||
/// A source file with enough in it to be worth finding.
|
||||
fn source(&self, rel: &str) {
|
||||
self.write(rel, "module m;\nendmodule\n");
|
||||
}
|
||||
|
||||
/// Set `rel`'s permission bits. `0o000` is how a test builds the
|
||||
/// directory the walk cannot read; the test puts them back so the
|
||||
/// temp tree can be removed.
|
||||
fn chmod(&self, rel: &str, mode: u32) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = self.path.join(rel);
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
|
||||
.expect("set permissions");
|
||||
}
|
||||
|
||||
/// `rel` as a symlink to `target`, which is relative to `rel`'s own
|
||||
/// directory — the spelling a checked-in symlink actually uses.
|
||||
fn link(&self, rel: &str, target: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
std::os::unix::fs::symlink(target, &path).expect("symlink");
|
||||
}
|
||||
|
||||
/// The walk from `rel` (empty for the root), as sorted paths
|
||||
/// relative to the tree root. Warnings are dropped; the tests that
|
||||
/// care about them call [`TempTree::warned`].
|
||||
fn walk(&self, rel: &str) -> Vec<String> {
|
||||
self.walked(rel).0
|
||||
}
|
||||
|
||||
/// The same, plus what the walk said, each warning's path made
|
||||
/// relative to the tree root so the assertions read.
|
||||
fn warned(&self, rel: &str) -> (Vec<String>, Vec<String>) {
|
||||
self.walked(rel)
|
||||
}
|
||||
|
||||
fn walked(&self, rel: &str) -> (Vec<String>, Vec<String>) {
|
||||
let start = if rel.is_empty() { self.path.clone() } else { self.path.join(rel) };
|
||||
let mut files = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
collect_files(
|
||||
start.to_str().expect("utf-8 temp path"),
|
||||
&[],
|
||||
true,
|
||||
&mut files,
|
||||
&mut |w| warnings.push(format!("{}: {}", self.rel_of(&w.path), w.message)),
|
||||
)
|
||||
.expect("the walk finishes");
|
||||
let mut out: Vec<String> = files.iter().map(|p| self.rel_of(p)).collect();
|
||||
out.sort();
|
||||
warnings.sort();
|
||||
(out, warnings)
|
||||
}
|
||||
|
||||
fn rel_of(&self, path: &Path) -> String {
|
||||
path.strip_prefix(&self.path).unwrap_or(path).to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_directory_linking_to_itself_is_entered_once() {
|
||||
let tree = TempTree::new("selfloop");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/loop", "../a");
|
||||
assert_eq!(tree.walk(""), ["a/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_link_to_an_ancestor_terminates_from_a_nested_start() {
|
||||
let tree = TempTree::new("uplink");
|
||||
tree.source("root.sv");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/up", "..");
|
||||
// Starting *inside* the cycle: `a` is entered, then `a/up` is the
|
||||
// root, which the walk has not seen yet and so does enter — once.
|
||||
// Its own `a` is the directory already being walked, and stops.
|
||||
assert_eq!(tree.walk("a"), ["a/up/root.sv", "a/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn two_links_to_one_directory_yield_its_files_once() {
|
||||
let tree = TempTree::new("twolinks");
|
||||
tree.source("shared/x.sv");
|
||||
// Sorted after `shared`, so the real directory is the spelling that
|
||||
// reaches the file first; whichever name wins, the file is reported
|
||||
// exactly once.
|
||||
tree.link("z1", "shared");
|
||||
tree.link("z2", "shared");
|
||||
assert_eq!(tree.walk(""), ["shared/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_link_to_a_directory_not_yet_walked_is_still_followed() {
|
||||
let tree = TempTree::new("sibling");
|
||||
tree.source("shared/rtl/x.sv");
|
||||
tree.link("proj/rtl", "../shared/rtl");
|
||||
// The `rtl -> ../shared/rtl` of a real checkout: the target is
|
||||
// outside the walk, so the link is the only way to it.
|
||||
assert_eq!(tree.walk("proj"), ["proj/rtl/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_dangling_source_link_is_warned_about_and_not_handed_on() {
|
||||
// §43's review kept the dangling source link in the file list so the
|
||||
// front end's "no such file" error survived. TODO §45.2 reverses that
|
||||
// on purpose: the warning is now the error's home, so the link is said
|
||||
// once here and never reaches the formatter. A dangling link that
|
||||
// names no source file was never going to be read and stays silent.
|
||||
let tree = TempTree::new("dangling");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/gone.sv", "nowhere.sv");
|
||||
tree.link("a/gonedir", "nowhere");
|
||||
let (files, warnings) = tree.warned("");
|
||||
assert_eq!(files, ["a/x.sv"]);
|
||||
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
|
||||
// The finding this channel exists for: one permission-denied directory
|
||||
// used to propagate `read_dir`'s error out of the whole walk, dropping
|
||||
// every file already found and failing the run.
|
||||
let tree = TempTree::new("unreadable");
|
||||
tree.source("a.sv");
|
||||
tree.source("locked/hidden.sv");
|
||||
tree.source("z/late.sv");
|
||||
tree.chmod("locked", 0o000);
|
||||
let (files, warnings) = tree.warned("");
|
||||
tree.chmod("locked", 0o755);
|
||||
assert_eq!(files, ["a.sv", "z/late.sv"], "the walk finished");
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
assert!(warnings[0].starts_with("locked: "), "the warning names it: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
|
||||
let tree = TempTree::new("lockedignore");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("keep.sv");
|
||||
tree.chmod(".gitignore", 0o000);
|
||||
let (files, warnings) = tree.warned("");
|
||||
tree.chmod(".gitignore", 0o644);
|
||||
assert_eq!(files, ["keep.sv"]);
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
assert!(warnings[0].starts_with(".gitignore: "), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_clean_walk_says_nothing() {
|
||||
let tree = TempTree::new("quiet");
|
||||
tree.source("a/x.sv");
|
||||
tree.source("b/y.sv");
|
||||
assert_eq!(tree.warned(""), (vec!["a/x.sv".to_string(), "b/y.sv".to_string()], Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_cycle_inside_an_ignored_directory_is_never_entered() {
|
||||
let tree = TempTree::new("ignoredcycle");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("keep.sv");
|
||||
tree.source("build/y.sv");
|
||||
tree.link("build/loop", "../build");
|
||||
assert_eq!(tree.walk(""), ["keep.sv"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The metadata hand-off — `docs/features/perf5r-first-answer/README.md`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every path `collect_files_with` yields under `rel`, with its length.
|
||||
#[cfg(unix)]
|
||||
fn walked_with(tree: &TempTree, rel: &str) -> Vec<(String, Option<u64>)> {
|
||||
let start = if rel.is_empty() { tree.path.clone() } else { tree.path.join(rel) };
|
||||
let mut out = Vec::new();
|
||||
collect_files_with(
|
||||
start.to_str().expect("utf-8 temp path"),
|
||||
&[],
|
||||
true,
|
||||
&mut |path, len| out.push((tree.rel_of(&path), len)),
|
||||
&mut |_| {},
|
||||
)
|
||||
.expect("the walk finishes");
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn the_metadata_entry_yields_exactly_the_paths_the_plain_one_does() {
|
||||
// The claim the server's cap rests on: `collect_files` is
|
||||
// `collect_files_with` with the length thrown away, so the two cannot
|
||||
// disagree about which files exist — not about order, not about
|
||||
// `.gitignore`, not about a symlink cycle, not about a broken link.
|
||||
let tree = TempTree::new("handoffsame");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("a.sv");
|
||||
tree.source("rtl/b.sv");
|
||||
tree.source("rtl/deep/c.svh");
|
||||
tree.source("build/hidden.sv");
|
||||
tree.write("rtl/notsource.txt", "x");
|
||||
tree.link("rtl/loop", "..");
|
||||
tree.link("rtl/dangling.sv", "nowhere.sv");
|
||||
|
||||
let mut plain = Vec::new();
|
||||
collect_files(tree.path.to_str().expect("utf-8"), &[], true, &mut plain, &mut |_| {})
|
||||
.expect("the walk finishes");
|
||||
let plain: Vec<String> = plain.iter().map(|p| tree.rel_of(p)).collect();
|
||||
let handed: Vec<String> =
|
||||
walked_with(&tree, "").into_iter().map(|(path, _)| path).collect();
|
||||
assert_eq!(plain, handed, "the same paths in the same order, byte for byte");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_walked_file_carries_the_length_the_walk_already_read() {
|
||||
let tree = TempTree::new("handofflen");
|
||||
tree.write("small.sv", "module m;\nendmodule\n");
|
||||
tree.write("big.sv", &"// pad\n".repeat(500));
|
||||
let found = walked_with(&tree, "");
|
||||
let sizes: Vec<(String, Option<u64>)> = found;
|
||||
assert_eq!(
|
||||
sizes,
|
||||
[("big.sv".to_string(), Some(3_500)), ("small.sv".to_string(), Some(20))],
|
||||
"the length is the file's own, not a guess"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_path_named_directly_is_handed_over_without_a_stat() {
|
||||
// `None` is the walk saying it did not look — the file was named, not
|
||||
// walked to, and adding a `metadata` call for it would be a cost
|
||||
// `collect_files` never paid.
|
||||
let tree = TempTree::new("handoffnamed");
|
||||
tree.source("one.sv");
|
||||
let found = walked_with(&tree, "one.sv");
|
||||
assert_eq!(found, [("one.sv".to_string(), None)]);
|
||||
}
|
||||
|
||||
/// What `collect_files_below(root, root/rel)` finds, relative to the tree.
|
||||
#[cfg(unix)]
|
||||
fn below(tree: &TempTree, rel: &str, exclude: &[&str]) -> Vec<String> {
|
||||
let patterns: Vec<String> = exclude.iter().map(|p| p.to_string()).collect();
|
||||
let mut out = Vec::new();
|
||||
collect_files_below(
|
||||
&tree.path,
|
||||
&tree.path.join(rel),
|
||||
&patterns,
|
||||
true,
|
||||
&mut |path, _| out.push(tree.rel_of(&path)),
|
||||
&mut |_| {},
|
||||
)
|
||||
.expect("the walk finishes");
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// What a walk of the whole tree finds under `rel` — the answer `below`
|
||||
/// has to reproduce.
|
||||
#[cfg(unix)]
|
||||
fn whole_under(tree: &TempTree, rel: &str, exclude: &[&str]) -> Vec<String> {
|
||||
let patterns: Vec<String> = exclude.iter().map(|p| p.to_string()).collect();
|
||||
let mut out = Vec::new();
|
||||
collect_files(tree.path.to_str().expect("utf-8"), &patterns, true, &mut out, &mut |_| {})
|
||||
.expect("the walk finishes");
|
||||
let prefix = format!("{rel}/");
|
||||
let mut under: Vec<String> =
|
||||
out.iter().map(|p| tree.rel_of(p)).filter(|p| p.starts_with(&prefix)).collect();
|
||||
under.sort();
|
||||
under
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_walk_that_starts_below_a_root_still_obeys_that_roots_gitignore() {
|
||||
// The whole reason `collect_files_below` exists. Starting the walk at
|
||||
// `hw/ip/aes` loses every rule written above it, and a scope whose
|
||||
// rung *is* the root would then index files that scope excludes.
|
||||
let tree = TempTree::new("belowignore");
|
||||
tree.write(".gitignore", "gen/\n*_generated.sv\n");
|
||||
tree.write("hw/.gitignore", "vendor/\n");
|
||||
tree.source("hw/ip/aes/rtl/aes.sv");
|
||||
tree.source("hw/ip/aes/rtl/aes_generated.sv");
|
||||
tree.source("hw/ip/aes/gen/made.sv");
|
||||
tree.source("hw/ip/aes/vendor/third.sv");
|
||||
tree.source("hw/ip/aes/dv/tb.sv");
|
||||
|
||||
let seen = below(&tree, "hw/ip/aes", &[]);
|
||||
assert_eq!(seen, ["hw/ip/aes/dv/tb.sv", "hw/ip/aes/rtl/aes.sv"]);
|
||||
assert_eq!(seen, whole_under(&tree, "hw/ip/aes", &[]), "the root walk agrees");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_directory_the_root_walk_never_entered_yields_nothing_below_it() {
|
||||
// An ancestor the root's own rules ignore is an ancestor the root walk
|
||||
// never descended into, so nothing under it is in scope however
|
||||
// directly it is named.
|
||||
let tree = TempTree::new("belowblocked");
|
||||
tree.write(".gitignore", "hw/vendor/\n");
|
||||
tree.source("hw/vendor/ip/aes/aes.sv");
|
||||
tree.source("hw/ip/aes/aes.sv");
|
||||
assert!(below(&tree, "hw/vendor/ip/aes", &[]).is_empty());
|
||||
assert_eq!(below(&tree, "hw/ip/aes", &[]), ["hw/ip/aes/aes.sv"]);
|
||||
// An excluded ancestor is the same answer by the other filter.
|
||||
assert!(below(&tree, "hw/ip/aes", &["ip"]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_negation_below_the_root_still_wins_over_the_root_rule() {
|
||||
// The precedence a root walk gives — deeper file last, so its `!` line
|
||||
// re-includes — must survive the ancestor chain being pre-loaded.
|
||||
let tree = TempTree::new("belownegate");
|
||||
tree.write(".gitignore", "*.sv\n");
|
||||
tree.write("hw/ip/aes/.gitignore", "!keep.sv\n");
|
||||
tree.source("hw/ip/aes/keep.sv");
|
||||
tree.source("hw/ip/aes/drop.sv");
|
||||
let seen = below(&tree, "hw/ip/aes", &[]);
|
||||
assert_eq!(seen, ["hw/ip/aes/keep.sv"]);
|
||||
assert_eq!(seen, whole_under(&tree, "hw/ip/aes", &[]), "the root walk agrees");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_start_that_is_not_under_the_root_finds_nothing() {
|
||||
let tree = TempTree::new("belowoutside");
|
||||
tree.source("a/x.sv");
|
||||
let mut out = Vec::new();
|
||||
collect_files_below(
|
||||
&tree.path.join("a"),
|
||||
&tree.path,
|
||||
&[],
|
||||
true,
|
||||
&mut |path, _| out.push(path),
|
||||
&mut |_| {},
|
||||
)
|
||||
.expect("no error, nothing found");
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_syntax_degrades_to_plain_globbing() {
|
||||
// `**` is just two stars inside one component; documented.
|
||||
@@ -329,4 +1030,37 @@ mod tests {
|
||||
assert!(ignored("x?.sv", "x?.sv"));
|
||||
assert!(!ignored("x?.sv", "xa.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn tracker_detects_precedence_conflict_when_alias_sorts_before() {
|
||||
let tree = TempTree::new("trackconflict");
|
||||
tree.source("z_real/child.sv");
|
||||
tree.link("a_alias", "z_real");
|
||||
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
assert_eq!(tracker.enter(&tree.path.join("z_real")), DirStatus::EnteredFirstTime);
|
||||
assert!(!tracker.has_conflict());
|
||||
|
||||
// Entering a_alias afterwards detects that a_alias sorts before z_real
|
||||
let status = tracker.enter(&tree.path.join("a_alias"));
|
||||
assert!(matches!(status, DirStatus::PrecedenceConflict { .. }));
|
||||
assert!(tracker.has_conflict());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn tracker_allows_alias_sorting_after_without_conflict() {
|
||||
let tree = TempTree::new("trackorder");
|
||||
tree.source("a_real/child.sv");
|
||||
tree.link("z_alias", "a_real");
|
||||
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
assert_eq!(tracker.enter(&tree.path.join("a_real")), DirStatus::EnteredFirstTime);
|
||||
assert!(!tracker.has_conflict());
|
||||
|
||||
// Entering z_alias afterwards: already visited, no precedence conflict
|
||||
assert_eq!(tracker.enter(&tree.path.join("z_alias")), DirStatus::AlreadyVisited);
|
||||
assert!(!tracker.has_conflict());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "lucisv_mcp"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "lucisv as a Model Context Protocol server: project understanding for coding agents over stdio"
|
||||
|
||||
[[bin]]
|
||||
name = "lucisv-mcp"
|
||||
path = "src/main.rs"
|
||||
|
||||
# No new dependencies: the MCP stdio transport is newline-delimited JSON-RPC,
|
||||
# which serde_json (already pinned by the workspace) handles. Why not `rmcp`:
|
||||
# docs/features/mcp-transport/README.md, Assumptions.
|
||||
[dependencies]
|
||||
lucisv_core = { path = "../lucisv_core" }
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_semantic = { path = "../vlog_semantic" }
|
||||
vlog_refactor = { path = "../vlog_refactor" }
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
vlog_linter = { path = "../vlog_linter" }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,415 @@
|
||||
//! The one write path every edit tool goes through.
|
||||
//!
|
||||
//! A tool hands over a [`Plan`] — per file, the text it computed against and
|
||||
//! the text it wants written — and gets back either the unified diff
|
||||
//! (`dry_run`) or a summary of what was written. The write is all-or-nothing
|
||||
//! as far as a filesystem allows: every file's new text exists before the
|
||||
//! first write; every target is checked to lie inside a root; every file is
|
||||
//! re-read and compared with the text the plan was computed against, and a
|
||||
//! file that moved since refuses the **whole** edit before anything is
|
||||
//! written (the write-freshness rule); then each file goes through
|
||||
//! `write_atomic`, in path order. A write that fails after others landed is
|
||||
//! reported as such — "written N of M" — which is the CLI's posture.
|
||||
//! See `docs/features/mcp-edit-tools/README.md`.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::diff::unified;
|
||||
use serde_json::{json, Value};
|
||||
use vlog_refactor::{RefactorEdit, TextEdit};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::tools::Answer;
|
||||
|
||||
/// One file an edit rewrites or creates.
|
||||
pub struct Change {
|
||||
/// The canonical path of the file.
|
||||
pub path: PathBuf,
|
||||
/// The text the edit was computed against; empty for a created file.
|
||||
pub before: String,
|
||||
/// The text to write.
|
||||
pub after: String,
|
||||
/// Whether the file does not exist yet and the edit creates it.
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
/// Everything one edit tool wants written, and what it has to say.
|
||||
#[derive(Default)]
|
||||
pub struct Plan {
|
||||
/// The files to write, in any order.
|
||||
pub changes: Vec<Change>,
|
||||
/// Files the tool looked at and left as they were (`format`, `fix_lint`).
|
||||
pub unchanged: Vec<PathBuf>,
|
||||
/// The engine's sentences about what it deliberately left alone.
|
||||
pub warnings: Vec<String>,
|
||||
/// One line the tool adds to the summary (`fix_lint`'s rules), if any.
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
/// A refactoring's edit, over the texts it was computed against. A file
|
||||
/// the edit names but `texts` does not hold, and an edit that does not
|
||||
/// fit its file, refuse the whole plan.
|
||||
pub fn from_refactor(edit: RefactorEdit, texts: &[(PathBuf, String)]) -> Result<Plan, String> {
|
||||
let mut plan = Plan { warnings: edit.warnings, ..Plan::default() };
|
||||
for (path, edits) in edit.edits {
|
||||
let created = edit.created.contains(&path);
|
||||
let before = match texts.iter().find(|(held, _)| *held == path) {
|
||||
Some((_, text)) => text.clone(),
|
||||
None if created => String::new(),
|
||||
None => {
|
||||
return Err(format!("the edit names `{}`, which was not read", path.display()))
|
||||
}
|
||||
};
|
||||
let after = apply_edits(&before, &edits)
|
||||
.map_err(|why| format!("the edit does not fit `{}`: {why}", path.display()))?;
|
||||
plan.changes.push(Change { path, before, after, created });
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` with `edits` applied, last first so every offset still points at
|
||||
/// the bytes it was computed for. Overlapping edits, an edit past the end
|
||||
/// and one splitting a UTF-8 character are refused, never guessed at.
|
||||
fn apply_edits(text: &str, edits: &[TextEdit]) -> Result<String, String> {
|
||||
let mut sorted: Vec<&TextEdit> = edits.iter().collect();
|
||||
sorted.sort_by_key(|edit| (edit.range.start, edit.range.end));
|
||||
for pair in sorted.windows(2) {
|
||||
if pair[1].range.start < pair[0].range.end {
|
||||
return Err(format!("two edits overlap at byte {}", pair[1].range.start));
|
||||
}
|
||||
}
|
||||
let mut out = text.to_string();
|
||||
for edit in sorted.iter().rev() {
|
||||
let (start, end) = (edit.range.start as usize, edit.range.end as usize);
|
||||
if start > end || end > out.len() {
|
||||
return Err(format!("an edit ends at byte {end}, past the end ({})", out.len()));
|
||||
}
|
||||
if !out.is_char_boundary(start) || !out.is_char_boundary(end) {
|
||||
return Err(format!("an edit at byte {start} splits a character"));
|
||||
}
|
||||
out.replace_range(start..end, &edit.new_text);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Check, then diff or write, then summarise. `dry_run` writes nothing.
|
||||
pub fn run(project: &Project, plan: Plan, dry_run: bool) -> Result<Answer, String> {
|
||||
for change in &plan.changes {
|
||||
contained(project, change)?;
|
||||
}
|
||||
let mut moved: Vec<&Change> =
|
||||
plan.changes.iter().filter(|c| c.created || c.before != c.after).collect();
|
||||
moved.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
let mut unchanged: Vec<String> = plan
|
||||
.changes
|
||||
.iter()
|
||||
.filter(|c| !c.created && c.before == c.after)
|
||||
.map(|c| project.relative(&c.path))
|
||||
.chain(plan.unchanged.iter().map(|path| project.relative(path)))
|
||||
.collect();
|
||||
unchanged.sort();
|
||||
let files: Vec<Written> = moved.iter().map(|change| Written::of(project, change)).collect();
|
||||
if !dry_run {
|
||||
commit(&moved, |path| project.relative(path))?;
|
||||
}
|
||||
Ok(summary(&files, &unchanged, &plan, dry_run))
|
||||
}
|
||||
|
||||
/// A target must lie inside a root: an existing file resolves into one; a
|
||||
/// created file's directory does, and nothing is at its path yet.
|
||||
fn contained(project: &Project, change: &Change) -> Result<(), String> {
|
||||
let shown = change.path.display();
|
||||
let inside = |dir: Option<PathBuf>| {
|
||||
dir.is_some_and(|dir| project.roots().iter().any(|root| dir.starts_with(root)))
|
||||
};
|
||||
if !change.created {
|
||||
let Ok(real) = fs::canonicalize(&change.path) else {
|
||||
return Err(format!("`{shown}` no longer exists; nothing written."));
|
||||
};
|
||||
if !inside(Some(real)) {
|
||||
return Err(format!(
|
||||
"`{shown}` is outside every root; lucisv-mcp only writes inside its roots."
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if !inside(change.path.parent().and_then(|dir| fs::canonicalize(dir).ok())) {
|
||||
return Err(format!(
|
||||
"`{shown}` would be created outside every root; lucisv-mcp only writes inside its roots."
|
||||
));
|
||||
}
|
||||
if fs::symlink_metadata(&change.path).is_ok() {
|
||||
return Err(format!(
|
||||
"`{}` already exists; nothing written.",
|
||||
project.relative(&change.path)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write every change, or none when any target moved since it was read.
|
||||
///
|
||||
/// First every file is re-read and compared byte for byte with the text the
|
||||
/// plan was computed against (a created file must still not exist, a
|
||||
/// read-only one is refused as `write_atomic` would refuse it); one mismatch
|
||||
/// refuses the whole edit before the first write. Then each file is
|
||||
/// written with `write_atomic`, in the order given. A failure part-way is
|
||||
/// reported with what was already written.
|
||||
pub fn commit(changes: &[&Change], shown: impl Fn(&Path) -> String) -> Result<(), String> {
|
||||
for change in changes {
|
||||
let name = shown(&change.path);
|
||||
if change.created {
|
||||
if fs::symlink_metadata(&change.path).is_ok() {
|
||||
return Err(format!("`{name}` already exists; nothing written."));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if fs::metadata(&change.path).is_ok_and(|meta| meta.permissions().readonly()) {
|
||||
return Err(format!("`{name}` is read-only; nothing written."));
|
||||
}
|
||||
match fs::read(&change.path) {
|
||||
Ok(bytes) if bytes == change.before.as_bytes() => {}
|
||||
Ok(_) => {
|
||||
return Err(format!("`{name}` changed on disk since it was read; nothing written."))
|
||||
}
|
||||
Err(e) => return Err(format!("`{name}` cannot be read again ({e}); nothing written.")),
|
||||
}
|
||||
}
|
||||
let mut done: Vec<String> = Vec::new();
|
||||
for change in changes {
|
||||
let name = shown(&change.path);
|
||||
if let Err(e) = write_atomic(&change.path, change.after.as_bytes()) {
|
||||
let list = if done.is_empty() { "nothing".to_string() } else { done.join(", ") };
|
||||
return Err(format!(
|
||||
"written {} of {}: {list}; failed on `{name}`: {e}",
|
||||
done.len(),
|
||||
changes.len()
|
||||
));
|
||||
}
|
||||
done.push(name);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One file of the summary: its name, its diff and the lines it moves.
|
||||
struct Written {
|
||||
file: String,
|
||||
created: bool,
|
||||
diff: String,
|
||||
added: usize,
|
||||
removed: usize,
|
||||
}
|
||||
|
||||
impl Written {
|
||||
fn of(project: &Project, change: &Change) -> Written {
|
||||
let file = project.relative(&change.path);
|
||||
let diff = unified(&file, &change.before, &change.after);
|
||||
// The two header lines are `---`/`+++`; every later line starting
|
||||
// with a sign is one line of the change.
|
||||
let body = diff.lines().skip(2);
|
||||
let added = body.clone().filter(|line| line.starts_with('+')).count();
|
||||
let removed = body.filter(|line| line.starts_with('-')).count();
|
||||
Written { file, created: change.created, diff, added, removed }
|
||||
}
|
||||
}
|
||||
|
||||
/// The text and JSON an edit answers with.
|
||||
fn summary(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Answer {
|
||||
let created = files.iter().filter(|f| f.created).count();
|
||||
let mut text = if files.is_empty() {
|
||||
"unchanged\n".to_string()
|
||||
} else {
|
||||
let tail = if dry_run { " (dry run: nothing written)" } else { "" };
|
||||
format!("files: {} changed, {created} created{tail}\n", files.len() - created)
|
||||
};
|
||||
for file in files {
|
||||
let mark = if file.created { " (created)" } else { "" };
|
||||
text.push_str(&format!(" {} +{} -{}{mark}\n", file.file, file.added, file.removed));
|
||||
}
|
||||
if !unchanged.is_empty() && !files.is_empty() {
|
||||
text.push_str(&format!("unchanged: {}\n", unchanged.join(", ")));
|
||||
}
|
||||
if let Some(note) = &plan.note {
|
||||
text.push_str(note);
|
||||
text.push('\n');
|
||||
}
|
||||
push_warnings(&mut text, &plan.warnings);
|
||||
if dry_run {
|
||||
files.iter().for_each(|file| text.push_str(&file.diff));
|
||||
}
|
||||
Answer { text, structured: structured(files, unchanged, plan, dry_run) }
|
||||
}
|
||||
|
||||
fn push_warnings(text: &mut String, warnings: &[String]) {
|
||||
if warnings.is_empty() {
|
||||
return;
|
||||
}
|
||||
text.push_str("warnings:\n");
|
||||
for warning in warnings {
|
||||
text.push_str(&format!(" {warning}\n"));
|
||||
}
|
||||
}
|
||||
|
||||
fn structured(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Value {
|
||||
let entry = |file: &Written| {
|
||||
let mut entry = json!({ "file": file.file, "added": file.added, "removed": file.removed });
|
||||
if dry_run {
|
||||
entry["diff"] = Value::from(file.diff.clone());
|
||||
}
|
||||
entry
|
||||
};
|
||||
let changed: Vec<Value> = files.iter().filter(|f| !f.created).map(entry).collect();
|
||||
let created: Vec<Value> = files.iter().filter(|f| f.created).map(entry).collect();
|
||||
json!({
|
||||
"changed": changed,
|
||||
"created": created,
|
||||
"unchanged": unchanged,
|
||||
"warnings": plan.warnings,
|
||||
"note": plan.note,
|
||||
"dry_run": dry_run,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-apply-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
fn edit(start: u32, end: u32, text: &str) -> TextEdit {
|
||||
TextEdit { range: TextRange::new(start, end), new_text: text.to_string() }
|
||||
}
|
||||
|
||||
fn change(path: &Path, before: &str, after: &str) -> Change {
|
||||
Change {
|
||||
path: path.to_path_buf(),
|
||||
before: before.into(),
|
||||
after: after.into(),
|
||||
created: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn name(path: &Path) -> String {
|
||||
path.file_name().unwrap().to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_apply_last_first_and_a_misfit_is_refused() {
|
||||
let edits = [edit(8, 11, "xyz!"), edit(0, 3, "q")];
|
||||
assert_eq!(apply_edits("abc def abc", &edits).unwrap(), "q def xyz!");
|
||||
assert_eq!(apply_edits("abc", &[edit(3, 3, "d")]).unwrap(), "abcd");
|
||||
assert!(apply_edits("abcdef", &[edit(0, 3, "x"), edit(2, 4, "y")]).is_err());
|
||||
assert!(apply_edits("abc", &[edit(2, 9, "x")]).is_err());
|
||||
assert!(apply_edits("é", &[edit(1, 2, "x")]).unwrap_err().contains("splits"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_moved_since_it_was_read_refuses_every_write() {
|
||||
let dir = scratch("stale");
|
||||
let (a, b) = (dir.join("a.sv"), dir.join("b.sv"));
|
||||
fs::write(&a, "module a; endmodule\n").unwrap();
|
||||
fs::write(&b, "module b; endmodule // edited meanwhile\n").unwrap();
|
||||
let first = change(&a, "module a; endmodule\n", "module a2; endmodule\n");
|
||||
let second = change(&b, "module b; endmodule\n", "module b2; endmodule\n");
|
||||
let refused = commit(&[&first, &second], name).unwrap_err();
|
||||
assert_eq!(refused, "`b.sv` changed on disk since it was read; nothing written.");
|
||||
// The first file, whose bytes still matched, was not written either.
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "module a; endmodule\n");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_created_file_that_appeared_meanwhile_is_refused_and_a_fresh_edit_lands() {
|
||||
let dir = scratch("create");
|
||||
let a = dir.join("a.sv");
|
||||
fs::write(&a, "module a; endmodule\n").unwrap();
|
||||
let taken = dir.join("n.sv");
|
||||
fs::write(&taken, "// someone else's\n").unwrap();
|
||||
let edit = change(&a, "module a; endmodule\n", "module a; n u_n (); endmodule\n");
|
||||
let new =
|
||||
Change { path: taken.clone(), before: String::new(), after: "x".into(), created: true };
|
||||
let refused = commit(&[&edit, &new], name).unwrap_err();
|
||||
assert_eq!(refused, "`n.sv` already exists; nothing written.");
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "module a; endmodule\n");
|
||||
fs::remove_file(&taken).unwrap();
|
||||
commit(&[&edit, &new], name).unwrap();
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "module a; n u_n (); endmodule\n");
|
||||
assert_eq!(fs::read_to_string(&taken).unwrap(), "x");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_write_that_fails_after_another_landed_says_what_was_written() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = scratch("partial");
|
||||
let shut = dir.join("shut");
|
||||
fs::create_dir(&shut).unwrap();
|
||||
let (a, b) = (dir.join("a.sv"), shut.join("b.sv"));
|
||||
fs::write(&a, "a\n").unwrap();
|
||||
fs::write(&b, "b\n").unwrap();
|
||||
// A read-only file is refused before any write …
|
||||
fs::set_permissions(&b, fs::Permissions::from_mode(0o444)).unwrap();
|
||||
let (first, second) = (change(&a, "a\n", "a2\n"), change(&b, "b\n", "b2\n"));
|
||||
let refused = commit(&[&first, &second], name).unwrap_err();
|
||||
assert_eq!(refused, "`b.sv` is read-only; nothing written.");
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "a\n");
|
||||
// … but a directory that will not take the temp file fails only at
|
||||
// the write, after `a.sv` landed: said, not hidden.
|
||||
fs::set_permissions(&b, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let refused = commit(&[&first, &second], name).unwrap_err();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(refused.starts_with("written 1 of 2: a.sv; failed on `b.sv`: "), "{refused}");
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "a2\n");
|
||||
assert_eq!(fs::read_to_string(&b).unwrap(), "b\n");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_outside_every_root_is_refused_and_nothing_is_written() {
|
||||
let dir = scratch("roots");
|
||||
let (root, outside) = (dir.join("root"), dir.join("outside"));
|
||||
fs::create_dir(&root).unwrap();
|
||||
fs::create_dir(&outside).unwrap();
|
||||
fs::write(root.join("a.sv"), "module a; endmodule\n").unwrap();
|
||||
fs::write(outside.join("b.sv"), "module b; endmodule\n").unwrap();
|
||||
let project = Project::open(vec![root.clone()], None);
|
||||
let create = |path: PathBuf| Change {
|
||||
path,
|
||||
before: String::new(),
|
||||
after: "module n; endmodule\n".into(),
|
||||
created: true,
|
||||
};
|
||||
let refuse = |change: Change| {
|
||||
let plan = Plan { changes: vec![change], ..Plan::default() };
|
||||
run(&project, plan, false).err().unwrap()
|
||||
};
|
||||
let beside = refuse(create(outside.join("n.sv")));
|
||||
assert!(beside.contains("would be created outside every root"), "{beside}");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// A directory inside the root that is a symlink leading out.
|
||||
std::os::unix::fs::symlink(&outside, root.join("link")).unwrap();
|
||||
let through = refuse(create(root.join("link").join("n.sv")));
|
||||
assert!(through.contains("outside every root"), "{through}");
|
||||
}
|
||||
let existing = outside.join("b.sv");
|
||||
let rewritten = refuse(change(&existing, "module b; endmodule\n", "module c; endmodule\n"));
|
||||
assert!(rewritten.contains("outside every root"), "{rewritten}");
|
||||
assert!(!outside.join("n.sv").exists());
|
||||
assert_eq!(fs::read_to_string(&existing).unwrap(), "module b; endmodule\n");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! `lucisv-mcp` — lucisv as a Model Context Protocol server, over stdio.
|
||||
//!
|
||||
//! A coding agent (Claude Code, Cursor, VS Code's agent mode) spawns this
|
||||
//! binary and asks it about a Verilog/SystemVerilog tree: what units exist,
|
||||
//! what a module's ports are, what a file's outline is. Every answer is a
|
||||
//! composition of the library crates' public APIs; nothing here is shared
|
||||
//! with `lucisv-server` or the `lucisv` CLI. See `docs/mcp/PLAN.md` and
|
||||
//! `docs/features/mcp-transport/README.md`.
|
||||
|
||||
mod apply;
|
||||
mod project;
|
||||
mod render;
|
||||
mod resources;
|
||||
mod rpc;
|
||||
mod tools;
|
||||
mod transport;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
/// What someone who spelled an argument wrong is told, on stderr.
|
||||
const USAGE: &str =
|
||||
"usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--verbose]";
|
||||
|
||||
/// The command line, parsed.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Options {
|
||||
/// `--root DIR`, in the order given; empty means the current directory.
|
||||
pub roots: Vec<PathBuf>,
|
||||
/// `--filelist FILE`: overrides the configured `filelist`.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// `--index-cache DIR`: accepted and stored; read from M6 on.
|
||||
pub index_cache: Option<PathBuf>,
|
||||
/// `--verbose`: per-call timing lines on stderr.
|
||||
pub verbose: bool,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let parsed = parse_args(std::env::args().skip(1)).and_then(|mut options| {
|
||||
options.roots = project::canonical_roots(&options.roots)?;
|
||||
Ok(options)
|
||||
});
|
||||
let options = match parsed {
|
||||
Ok(options) => options,
|
||||
Err(problem) => {
|
||||
eprintln!("error: {problem}");
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
// Every parse happens on this thread, so it gets the stack the parser's
|
||||
// recursion limit was sized for (`docs/features/recursion-limit`).
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("lucisv-mcp".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || rpc::serve(options));
|
||||
match spawned.map(|handle| handle.join()) {
|
||||
Ok(Ok(Ok(()))) => ExitCode::SUCCESS,
|
||||
Ok(Ok(Err(problem))) => {
|
||||
eprintln!("lucisv-mcp: {problem}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
eprintln!("lucisv-mcp: the server thread panicked");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
Err(problem) => {
|
||||
eprintln!("lucisv-mcp: cannot start the server thread: {problem}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the argument contract (TODO-MCP "Fixed names"). Anything else is an
|
||||
/// error naming the offending argument.
|
||||
fn parse_args(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut options = Options::default();
|
||||
let mut args = args;
|
||||
while let Some(arg) = args.next() {
|
||||
let mut value = |flag: &str| {
|
||||
args.next().map(PathBuf::from).ok_or_else(|| format!("{flag} needs a value"))
|
||||
};
|
||||
match arg.as_str() {
|
||||
"--root" => options.roots.push(value("--root")?),
|
||||
"--filelist" => options.filelist = Some(value("--filelist")?),
|
||||
"--index-cache" => options.index_cache = Some(value("--index-cache")?),
|
||||
"--verbose" => options.verbose = true,
|
||||
other => return Err(format!("unknown option: {other}")),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Options, String> {
|
||||
parse_args(args.iter().map(|a| a.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_documented_argument_is_read() {
|
||||
let options = parse(&[
|
||||
"--root",
|
||||
"a",
|
||||
"--root",
|
||||
"b",
|
||||
"--filelist",
|
||||
"f.f",
|
||||
"--index-cache",
|
||||
"c",
|
||||
"--verbose",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(options.roots, vec![PathBuf::from("a"), PathBuf::from("b")]);
|
||||
assert_eq!(options.filelist, Some(PathBuf::from("f.f")));
|
||||
assert_eq!(options.index_cache, Some(PathBuf::from("c")));
|
||||
assert!(options.verbose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_argument_or_a_missing_value_is_refused_by_name() {
|
||||
assert_eq!(parse(&["--stdio"]).unwrap_err(), "unknown option: --stdio");
|
||||
assert_eq!(parse(&["--root"]).unwrap_err(), "--root needs a value");
|
||||
assert_eq!(parse(&[]).unwrap(), Options::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! One file, fully analyzed, and a small cache of them keyed by content.
|
||||
//!
|
||||
//! The index answers workspace questions without keeping any file's text;
|
||||
//! a tool that needs a file's outline, a slice of its text or its
|
||||
//! declarations asks for its [`Analysis`] here. The sequence is the language
|
||||
//! server's `Document::new` minus the cross-file overlay: lex once, parse
|
||||
//! tolerantly, read the `` `define`` table off the tokens, analyze, index the
|
||||
//! lines. The overlay (`resolve_external`) depends on the index, which moves
|
||||
//! under a file whose own text did not, so it is computed per call by the
|
||||
//! tool that needs it ([`Analysis::external`]) and never cached here.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
|
||||
|
||||
/// How many analyses are kept. An agent's calls cluster on a handful of
|
||||
/// files; a whole-design answer never needs a file's analysis at all.
|
||||
const CAPACITY: usize = 16;
|
||||
|
||||
/// Everything one file's text yields on its own.
|
||||
pub struct Analysis {
|
||||
/// The text every span below indexes into.
|
||||
pub text: String,
|
||||
/// The line table over `text`.
|
||||
pub lines: LineIndex,
|
||||
/// The tokens `tree` was parsed from; empty when the text does not lex.
|
||||
pub tokens: Vec<Token>,
|
||||
/// Every `` `define``/`` `undef`` the file writes, in source order.
|
||||
pub defines: DefineTable,
|
||||
/// The tolerant parse.
|
||||
pub tree: SourceFile,
|
||||
/// What the parse could not read; empty for a clean file.
|
||||
pub diagnostics: Vec<ParseDiagnostic>,
|
||||
/// The single-file symbol tables.
|
||||
pub semantics: Semantics,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Analyze `text`. Parses, so it must run on a thread with
|
||||
/// `PARSE_STACK_SIZE` of stack.
|
||||
pub fn of(text: String) -> Analysis {
|
||||
// One lex: a file that does not lex takes the all-error path, exactly
|
||||
// as `parse_source_tolerant` would.
|
||||
// The tokens are kept (a clone before the parse consumes them): the
|
||||
// lint pass and the macro lookups read them again.
|
||||
let (tree, diagnostics, tokens) = match tokenize(&text) {
|
||||
Ok(tokens) => {
|
||||
let (tree, diagnostics) = parse_tolerant(tokens.clone(), &text);
|
||||
(tree, diagnostics, tokens)
|
||||
}
|
||||
Err(_) => {
|
||||
let (tree, diagnostics) = parse_source_tolerant(&text);
|
||||
(tree, diagnostics, Vec::new())
|
||||
}
|
||||
};
|
||||
let defines = collect_defines(&tokens);
|
||||
let semantics = analyze(&tree, &text);
|
||||
let lines = LineIndex::new(&text);
|
||||
Analysis { text, lines, tokens, defines, tree, diagnostics, semantics }
|
||||
}
|
||||
|
||||
/// The workspace overlay over this file's references, against `index` as
|
||||
/// it is now. Not cached: the index moves under an unchanged file.
|
||||
pub fn external(&self, index: &WorkspaceIndex) -> ExternalResolutions {
|
||||
resolve_external(&self.semantics, index)
|
||||
}
|
||||
|
||||
/// The token covering byte `offset`, if any.
|
||||
pub fn token_at(&self, offset: u32) -> Option<&Token> {
|
||||
let after = self.tokens.partition_point(|token| token.span.start <= offset);
|
||||
let token = self.tokens.get(after.checked_sub(1)?)?;
|
||||
token.span.contains(offset).then_some(token)
|
||||
}
|
||||
|
||||
/// The text of 1-based line `line`, without its line ending.
|
||||
pub fn line_text(&self, line: u32) -> &str {
|
||||
match self.lines.line_range(line) {
|
||||
Some(range) => self.slice(range.start, range.end).trim_end_matches('\r'),
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1-based first and last line a byte range covers. A range ending
|
||||
/// just after a newline ends on the line before it.
|
||||
pub fn line_span(&self, start: u32, end: u32) -> (u32, u32) {
|
||||
let (first, _) = self.lines.line_col(start);
|
||||
let (last, _) = self.lines.line_col(end.saturating_sub(1).max(start));
|
||||
(first, last)
|
||||
}
|
||||
|
||||
/// The text of a byte range, or an empty string for a range that does
|
||||
/// not fall on character boundaries of this text.
|
||||
pub fn slice(&self, start: u32, end: u32) -> &str {
|
||||
self.text.get(start as usize..end as usize).unwrap_or("")
|
||||
}
|
||||
}
|
||||
|
||||
/// The last few analyses, newest last, each tagged with the content hash it
|
||||
/// was computed from.
|
||||
#[derive(Default)]
|
||||
pub struct Analyses {
|
||||
held: Vec<(PathBuf, u64, Rc<Analysis>)>,
|
||||
}
|
||||
|
||||
impl Analyses {
|
||||
/// The analysis of `path` whose text hashes to `hash`, when one is held.
|
||||
pub fn get(&mut self, path: &Path, hash: u64) -> Option<Rc<Analysis>> {
|
||||
let at = self.held.iter().position(|(p, h, _)| p == path && *h == hash)?;
|
||||
let entry = self.held.remove(at);
|
||||
let analysis = Rc::clone(&entry.2);
|
||||
self.held.push(entry);
|
||||
Some(analysis)
|
||||
}
|
||||
|
||||
/// Keep `analysis` for `path`, dropping any older one of the same file
|
||||
/// and the oldest entry when full.
|
||||
pub fn put(&mut self, path: PathBuf, hash: u64, analysis: Rc<Analysis>) {
|
||||
self.held.retain(|(p, _, _)| *p != path);
|
||||
if self.held.len() >= CAPACITY {
|
||||
self.held.remove(0);
|
||||
}
|
||||
self.held.push((path, hash, analysis));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn line_spans_are_one_based_and_a_trailing_newline_stays_on_its_line() {
|
||||
let analysis = Analysis::of("module a;\nendmodule\n".to_string());
|
||||
assert_eq!(analysis.line_span(0, 20), (1, 2));
|
||||
assert_eq!(analysis.line_span(0, 10), (1, 1));
|
||||
assert_eq!(analysis.slice(0, 6), "module");
|
||||
assert!(analysis.diagnostics.is_empty());
|
||||
assert_eq!(analysis.line_text(2), "endmodule");
|
||||
assert_eq!(analysis.line_text(9), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_and_defines_are_kept_and_a_token_is_found_by_offset() {
|
||||
let analysis = Analysis::of("`define W 8\r\nmodule a; endmodule\r\n".to_string());
|
||||
assert_eq!(analysis.defines.latest("W").map(|d| d.body.as_str()), Some("8"));
|
||||
assert_eq!(analysis.line_text(1), "`define W 8");
|
||||
let module = analysis.token_at(14).map(|t| t.text.as_str());
|
||||
assert_eq!(module, Some("module"));
|
||||
assert!(analysis.token_at(1000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_answers_by_content_and_evicts_the_oldest() {
|
||||
let mut cache = Analyses::default();
|
||||
let a = Rc::new(Analysis::of(String::new()));
|
||||
cache.put(PathBuf::from("a"), 1, Rc::clone(&a));
|
||||
assert!(cache.get(Path::new("a"), 1).is_some());
|
||||
assert!(cache.get(Path::new("a"), 2).is_none());
|
||||
for n in 0..CAPACITY {
|
||||
cache.put(PathBuf::from(format!("f{n}")), 0, Rc::clone(&a));
|
||||
}
|
||||
assert!(cache.get(Path::new("a"), 1).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! 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.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use lucisv_core::cache::content_hash;
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::walk::collect_files_with;
|
||||
|
||||
/// The per-file size cap of a walked tree — the editor's
|
||||
/// `lucisv.index.maxFileSize` default. A larger file is a netlist, not
|
||||
/// something an agent wants summarised.
|
||||
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
|
||||
|
||||
/// A file whose mtime is this close to the moment it was read may have been
|
||||
/// written again within the filesystem's timestamp resolution, so its stamp
|
||||
/// proves nothing: it is re-read (and re-hashed) until it is older than
|
||||
/// this. Git's "racy clean" rule, for the same reason.
|
||||
const RACY: Duration = Duration::from_secs(2);
|
||||
|
||||
/// The files one discovery found, and what it had to say about the rest.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FileSet {
|
||||
/// Canonical paths, sorted, without repeats.
|
||||
pub files: Vec<PathBuf>,
|
||||
/// The filelist the set was read from, when it was.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// Problems worth one line each on stderr and in `project_overview`.
|
||||
pub warnings: Vec<String>,
|
||||
/// Walked files skipped for being over [`MAX_FILE_BYTES`].
|
||||
pub skipped_large: usize,
|
||||
/// Those files' canonical paths: an edit tool must know which files it
|
||||
/// could not read (`docs/features/mcp-edit-tools`, QA finding 2).
|
||||
pub skipped: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// Find the project's files: the filelist (`--filelist`, else the first
|
||||
/// root's configured `filelist`) when there is one that reads, else a walk of
|
||||
/// every root honouring `.gitignore`, each root's `exclude` patterns and the
|
||||
/// size cap. A filelist that does not read falls back to the walk, with a
|
||||
/// warning — the editor's ladder.
|
||||
pub fn discover(roots: &[PathBuf], filelist: Option<&Path>) -> FileSet {
|
||||
let mut set = FileSet::default();
|
||||
let filelist = filelist.map(Path::to_path_buf).or_else(|| configured_filelist(roots));
|
||||
if let Some(path) = filelist {
|
||||
match lucisv_core::filelist::read(&path) {
|
||||
Ok(list) => {
|
||||
set.warnings.extend(list.warnings);
|
||||
set.files = list.files.iter().filter_map(|f| canonical(f)).collect();
|
||||
set.filelist = Some(path);
|
||||
return finish(set);
|
||||
}
|
||||
Err(problem) => {
|
||||
set.warnings.push(format!("{problem} — walking the roots instead"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for root in roots {
|
||||
walk_root(root, roots, &mut set);
|
||||
}
|
||||
finish(set)
|
||||
}
|
||||
|
||||
/// The `filelist` key of the config governing the first root that has one.
|
||||
fn configured_filelist(roots: &[PathBuf]) -> Option<PathBuf> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
|
||||
}
|
||||
|
||||
/// Every source file under one root, as `lucisv` itself would walk it —
|
||||
/// except a file a symlink leads outside every root, which is dropped with a
|
||||
/// warning naming it: the walk is held to the rule `Project::resolve` holds
|
||||
/// a path argument to. (A `--filelist` entry is the user's own choice and
|
||||
/// stays.)
|
||||
fn walk_root(root: &Path, roots: &[PathBuf], set: &mut FileSet) {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let exclude = match discovery.for_dir(root) {
|
||||
Ok(config) => config.exclude.unwrap_or_default(),
|
||||
Err(problem) => {
|
||||
set.warnings.push(problem);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let input = root.to_string_lossy();
|
||||
let mut found: Vec<(PathBuf, Option<u64>)> = Vec::new();
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let walked = collect_files_with(
|
||||
&input,
|
||||
&exclude,
|
||||
true,
|
||||
&mut |path, size| found.push((path, size)),
|
||||
&mut |warning| warnings.push(warning.to_string()),
|
||||
);
|
||||
if let Err(problem) = walked {
|
||||
warnings.push(problem);
|
||||
}
|
||||
set.warnings.extend(warnings);
|
||||
for (path, size) in found {
|
||||
let Some(path) = canonical(&path) else { continue };
|
||||
if !roots.iter().any(|root| path.starts_with(root)) {
|
||||
set.warnings.push(format!(
|
||||
"{}: outside every root (reached through a symlink); not indexed",
|
||||
path.display()
|
||||
));
|
||||
} else if size.unwrap_or(0) > MAX_FILE_BYTES {
|
||||
set.skipped_large += 1;
|
||||
set.skipped.push(path);
|
||||
} else {
|
||||
set.files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut set: FileSet) -> FileSet {
|
||||
set.files.sort();
|
||||
set.files.dedup();
|
||||
set.skipped.sort();
|
||||
set.skipped.dedup();
|
||||
set
|
||||
}
|
||||
|
||||
/// `path` with every symlink resolved, or `None` when it no longer exists.
|
||||
pub fn canonical(path: &Path) -> Option<PathBuf> {
|
||||
fs::canonicalize(path).ok()
|
||||
}
|
||||
|
||||
/// What a file looked like when it was last read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Stamp {
|
||||
/// Its length in bytes.
|
||||
pub size: u64,
|
||||
/// Its modification time, when the filesystem reports one.
|
||||
pub mtime: Option<SystemTime>,
|
||||
/// `content_hash` of its bytes.
|
||||
pub hash: u64,
|
||||
/// When it was read.
|
||||
pub read_at: SystemTime,
|
||||
/// Its ctime and inode — what still moves when a same-size rewrite puts
|
||||
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
|
||||
/// the same problem. Zero off Unix, where size, mtime and the racy rule
|
||||
/// are all there is.
|
||||
pub identity: (i64, i64, u64),
|
||||
/// Whether its text spells `endprogram` — the cheap test that says a
|
||||
/// `Module`-kind unit in it might be a `program` (the semantic layer
|
||||
/// models both as a module).
|
||||
pub program: bool,
|
||||
}
|
||||
|
||||
/// How a file compares with its stamp.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Change {
|
||||
/// Same size, same mtime, and not racy: the stamp still describes it.
|
||||
Same,
|
||||
/// Something moved; the file has to be read to know whether its bytes did.
|
||||
Suspect,
|
||||
/// It is gone, unreadable, or grew past the cap.
|
||||
Gone,
|
||||
}
|
||||
|
||||
impl Stamp {
|
||||
/// Compare the file on disk with this stamp, by one `stat`.
|
||||
pub fn check(&self, path: &Path) -> Change {
|
||||
let Ok(meta) = fs::metadata(path) else {
|
||||
return Change::Gone;
|
||||
};
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
return Change::Gone;
|
||||
}
|
||||
let mtime = meta.modified().ok();
|
||||
let racy = match mtime {
|
||||
Some(mtime) => mtime + RACY > self.read_at,
|
||||
None => true,
|
||||
};
|
||||
let moved = meta.len() != self.size || mtime != self.mtime;
|
||||
if moved || identity(&meta) != self.identity || racy {
|
||||
Change::Suspect
|
||||
} else {
|
||||
Change::Same
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one source file and stamp it. `Err` for a file that is gone or is
|
||||
/// not UTF-8 text — the latter skipped exactly as the language server skips
|
||||
/// it.
|
||||
pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
|
||||
// Stat before reading: a write that lands between the two leaves a stamp
|
||||
// older than the bytes, which the next sweep sees as a change.
|
||||
let meta = fs::metadata(path)?;
|
||||
let read_at = SystemTime::now();
|
||||
let bytes = fs::read(path)?;
|
||||
let hash = content_hash(&bytes);
|
||||
let text = String::from_utf8(bytes)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "not UTF-8 text"))?;
|
||||
let stamp = Stamp {
|
||||
size: meta.len(),
|
||||
mtime: meta.modified().ok(),
|
||||
hash,
|
||||
read_at,
|
||||
identity: identity(&meta),
|
||||
program: text.contains("endprogram"),
|
||||
};
|
||||
Ok((text, stamp))
|
||||
}
|
||||
|
||||
/// A file's ctime (seconds, nanoseconds) and inode number.
|
||||
#[cfg(unix)]
|
||||
fn identity(meta: &fs::Metadata) -> (i64, i64, u64) {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
(meta.ctime(), meta.ctime_nsec(), meta.ino())
|
||||
}
|
||||
|
||||
/// No ctime or inode off Unix: the stamp falls back to size and mtime.
|
||||
#[cfg(not(unix))]
|
||||
fn identity(_: &fs::Metadata) -> (i64, i64, u64) {
|
||||
(0, 0, 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-files-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_honours_gitignore_exclude_and_the_size_cap() {
|
||||
let dir = scratch("walk");
|
||||
fs::write(dir.join("a.sv"), "module a; endmodule\n").unwrap();
|
||||
fs::write(dir.join("big.sv"), vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap();
|
||||
fs::create_dir(dir.join("gen")).unwrap();
|
||||
fs::write(dir.join("gen/g.sv"), "module g; endmodule\n").unwrap();
|
||||
fs::create_dir(dir.join("skip")).unwrap();
|
||||
fs::write(dir.join("skip/s.sv"), "module s; endmodule\n").unwrap();
|
||||
fs::write(dir.join(".gitignore"), "gen/\n").unwrap();
|
||||
fs::write(dir.join("lucisv.toml"), "exclude = [\"skip\"]\n").unwrap();
|
||||
let set = discover(std::slice::from_ref(&dir), None);
|
||||
assert_eq!(set.files, vec![dir.join("a.sv")]);
|
||||
assert_eq!(set.skipped_large, 1);
|
||||
assert_eq!(set.skipped, vec![dir.join("big.sv")]);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_wins_and_an_unreadable_one_falls_back_to_the_walk() {
|
||||
let dir = scratch("filelist");
|
||||
fs::write(dir.join("a.sv"), "module a; endmodule\n").unwrap();
|
||||
fs::write(dir.join("b.sv"), "module b; endmodule\n").unwrap();
|
||||
fs::write(dir.join("files.f"), format!("{}\n", dir.join("b.sv").display())).unwrap();
|
||||
let listed = discover(std::slice::from_ref(&dir), Some(&dir.join("files.f")));
|
||||
assert_eq!(listed.files, vec![dir.join("b.sv")]);
|
||||
assert_eq!(listed.filelist, Some(dir.join("files.f")));
|
||||
let fallback = discover(std::slice::from_ref(&dir), Some(&dir.join("missing.f")));
|
||||
assert_eq!(fallback.files, vec![dir.join("a.sv"), dir.join("b.sv")]);
|
||||
assert!(fallback.warnings[0].contains("walking the roots instead"));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stamp_sees_an_edit_a_deletion_and_distrusts_a_racy_read() {
|
||||
let dir = scratch("stamp");
|
||||
let path = dir.join("a.sv");
|
||||
fs::write(&path, "module a; endmodule\n").unwrap();
|
||||
let (_, stamp) = read_source(&path).unwrap();
|
||||
// Just written: racy, so suspect even though nothing moved.
|
||||
assert_eq!(stamp.check(&path), Change::Suspect);
|
||||
let settled = Stamp { read_at: stamp.read_at + RACY + RACY, ..stamp };
|
||||
assert_eq!(settled.check(&path), Change::Same);
|
||||
fs::write(&path, "module a2; endmodule\n").unwrap();
|
||||
assert_eq!(settled.check(&path), Change::Suspect);
|
||||
fs::remove_file(&path).unwrap();
|
||||
assert_eq!(settled.check(&path), Change::Gone);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
//! 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).
|
||||
|
||||
mod analysis;
|
||||
mod files;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
|
||||
|
||||
pub use analysis::Analysis;
|
||||
pub use files::Stamp;
|
||||
|
||||
use analysis::Analyses;
|
||||
use files::{canonical, discover, read_source, Change, FileSet};
|
||||
|
||||
/// A walk older than this is re-run at the next call, so new files appear.
|
||||
const REWALK_AFTER: Duration = Duration::from_secs(5);
|
||||
|
||||
/// What one freshness sweep did — logged under `--verbose`.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Refresh {
|
||||
/// Files whose bytes changed and were re-indexed.
|
||||
pub changed: usize,
|
||||
/// Files that appeared.
|
||||
pub added: usize,
|
||||
/// Files that went away.
|
||||
pub removed: usize,
|
||||
/// Whether the roots were walked (or the filelist re-read).
|
||||
pub walked: bool,
|
||||
}
|
||||
|
||||
/// Roots, files, index and the analyses of recently asked-about files.
|
||||
pub struct Project {
|
||||
roots: Vec<PathBuf>,
|
||||
filelist_arg: Option<PathBuf>,
|
||||
config: FileConfig,
|
||||
config_problem: Option<String>,
|
||||
files: BTreeMap<PathBuf, Stamp>,
|
||||
index: WorkspaceIndex,
|
||||
analyses: Analyses,
|
||||
walk: FileSet,
|
||||
walked_at: Instant,
|
||||
updated_at: Instant,
|
||||
build: Duration,
|
||||
/// Discovered files that are not UTF-8 text, with why, recomputed by
|
||||
/// every walk.
|
||||
unreadable: Vec<(PathBuf, String)>,
|
||||
/// Whether the current call has already walked the roots — the open, a
|
||||
/// stale or forced walk in `refresh`, or a miss's retry.
|
||||
walked_in_call: bool,
|
||||
}
|
||||
|
||||
/// The canonical form of every `--root`, the current directory when none
|
||||
/// was given, each distinct directory once in the order first given. A root
|
||||
/// that is not a directory is the user's mistake, named. Nested roots stay
|
||||
/// two roots: they are different directories.
|
||||
pub fn canonical_roots(roots: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
|
||||
let given = if roots.is_empty() { vec![PathBuf::from(".")] } else { roots.to_vec() };
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for root in &given {
|
||||
match canonical(root) {
|
||||
Some(path) if path.is_dir() => {
|
||||
if !out.contains(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
_ => return Err(format!("--root {}: not a directory", root.display())),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// Discover the files under `roots` (already canonical) and index them.
|
||||
/// Parses every file, so it runs on the stack-sized thread.
|
||||
pub fn open(roots: Vec<PathBuf>, filelist: Option<PathBuf>) -> Project {
|
||||
let started = Instant::now();
|
||||
let mut discovery = Discovery::new(true);
|
||||
let (config, config_problem) = match roots.first().map(|r| discovery.for_dir(r)) {
|
||||
Some(Ok(config)) => (config, None),
|
||||
Some(Err(problem)) => (FileConfig::default(), Some(problem)),
|
||||
None => (FileConfig::default(), None),
|
||||
};
|
||||
let walk = discover(&roots, filelist.as_deref());
|
||||
let mut builder = IndexBuilder::new();
|
||||
let mut files = BTreeMap::new();
|
||||
let mut unreadable = Vec::new();
|
||||
for path in &walk.files {
|
||||
match read_source(path) {
|
||||
Ok((text, stamp)) => {
|
||||
builder.add_file(path.clone(), &text);
|
||||
files.insert(path.clone(), stamp);
|
||||
}
|
||||
Err(problem) => {
|
||||
unreadable.push((path.clone(), problem.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let now = Instant::now();
|
||||
Project {
|
||||
roots,
|
||||
filelist_arg: filelist,
|
||||
config,
|
||||
config_problem,
|
||||
files,
|
||||
index: builder.finish(),
|
||||
analyses: Analyses::default(),
|
||||
walk,
|
||||
walked_at: now,
|
||||
updated_at: now,
|
||||
build: now - started,
|
||||
unreadable,
|
||||
walked_in_call: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the index up to the disk: stat every file, re-read the ones
|
||||
/// that moved, drop the ones that went, and — when a file went, when
|
||||
/// `force_walk`, or when the last walk is stale — walk again for new
|
||||
/// ones. One merge for the lot.
|
||||
pub fn refresh(&mut self, force_walk: bool) -> Refresh {
|
||||
let mut report = Refresh::default();
|
||||
self.walked_in_call = false;
|
||||
let mut gone: Vec<PathBuf> = Vec::new();
|
||||
let mut records: Vec<FileFacts> = Vec::new();
|
||||
let mut suspects: Vec<PathBuf> = Vec::new();
|
||||
for (path, stamp) in &self.files {
|
||||
match stamp.check(path) {
|
||||
Change::Same => {}
|
||||
Change::Suspect => suspects.push(path.clone()),
|
||||
Change::Gone => gone.push(path.clone()),
|
||||
}
|
||||
}
|
||||
for path in suspects {
|
||||
self.reread(path, &mut records, &mut gone);
|
||||
}
|
||||
report.changed = records.len();
|
||||
for path in &gone {
|
||||
self.files.remove(path);
|
||||
}
|
||||
if force_walk || !gone.is_empty() || self.walked_at.elapsed() > REWALK_AFTER {
|
||||
report.walked = true;
|
||||
report.added = self.rewalk(&mut records, &mut gone);
|
||||
self.walked_in_call = true;
|
||||
}
|
||||
report.removed = gone.len();
|
||||
if !records.is_empty() || !gone.is_empty() {
|
||||
self.index.absorb(records, &gone);
|
||||
self.updated_at = Instant::now();
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
/// 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);
|
||||
if moved {
|
||||
records.push(FileFacts::of(path.clone(), &text));
|
||||
}
|
||||
self.files.insert(path, stamp);
|
||||
}
|
||||
Err(_) => gone.push(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk again: files the walk no longer finds are gone, files it finds
|
||||
/// for the first time are read and recorded. Returns how many were added.
|
||||
fn rewalk(&mut self, records: &mut Vec<FileFacts>, gone: &mut Vec<PathBuf>) -> usize {
|
||||
let walk = discover(&self.roots, self.filelist_arg.as_deref());
|
||||
let wanted: BTreeSet<&PathBuf> = walk.files.iter().collect();
|
||||
let dropped: Vec<PathBuf> =
|
||||
self.files.keys().filter(|path| !wanted.contains(path)).cloned().collect();
|
||||
for path in dropped {
|
||||
self.files.remove(&path);
|
||||
gone.push(path);
|
||||
}
|
||||
let mut added = 0;
|
||||
let mut unreadable = Vec::new();
|
||||
for path in &walk.files {
|
||||
if self.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
match read_source(path) {
|
||||
Ok((text, stamp)) => {
|
||||
records.push(FileFacts::of(path.clone(), &text));
|
||||
self.files.insert(path.clone(), stamp);
|
||||
added += 1;
|
||||
}
|
||||
Err(problem) => unreadable.push((path.clone(), problem.to_string())),
|
||||
}
|
||||
}
|
||||
self.unreadable = unreadable;
|
||||
self.walk = walk;
|
||||
self.walked_at = Instant::now();
|
||||
added
|
||||
}
|
||||
|
||||
/// A by-name lookup found nothing: when this call has not walked yet,
|
||||
/// walk now (a file written since the last walk is otherwise invisible
|
||||
/// for up to `REWALK_AFTER`) and say so, so the caller retries once.
|
||||
pub fn ensure_walked_for_miss(&mut self) -> bool {
|
||||
if self.walked_in_call {
|
||||
return false;
|
||||
}
|
||||
self.refresh(true);
|
||||
true
|
||||
}
|
||||
|
||||
/// The workspace index, as fresh as the last [`Project::refresh`].
|
||||
pub fn index(&self) -> &WorkspaceIndex {
|
||||
&self.index
|
||||
}
|
||||
|
||||
/// The canonical roots, in the order given.
|
||||
pub fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// Every indexed file with its stamp, sorted by path.
|
||||
pub fn files(&self) -> impl Iterator<Item = (&PathBuf, &Stamp)> {
|
||||
self.files.iter()
|
||||
}
|
||||
|
||||
/// The stamp of one indexed file.
|
||||
pub fn stamp(&self, path: &Path) -> Option<&Stamp> {
|
||||
self.files.get(path)
|
||||
}
|
||||
|
||||
/// The config governing the first root, and the problem reading it.
|
||||
pub fn config(&self) -> (&FileConfig, Option<&str>) {
|
||||
(&self.config, self.config_problem.as_deref())
|
||||
}
|
||||
|
||||
/// The last discovery: its filelist, warnings and skipped files.
|
||||
pub fn discovery(&self) -> &FileSet {
|
||||
&self.walk
|
||||
}
|
||||
|
||||
/// Files discovery found but could not read as UTF-8 text.
|
||||
pub fn unreadable(&self) -> Vec<String> {
|
||||
let shown = |(path, why): &(PathBuf, String)| format!("{}: {why}", self.relative(path));
|
||||
self.unreadable.iter().map(shown).collect()
|
||||
}
|
||||
|
||||
/// Every discovered file the index does not hold, with why: over the
|
||||
/// size cap, or not UTF-8 text. An edit over the whole set must not
|
||||
/// pretend these were searched.
|
||||
pub fn skipped(&self) -> Vec<(PathBuf, String)> {
|
||||
let large = self.walk.skipped.iter().map(|path| (path.clone(), "over 1 MiB".to_string()));
|
||||
large.chain(self.unreadable.iter().cloned()).collect()
|
||||
}
|
||||
|
||||
/// How long the startup build took, and how long ago the index last
|
||||
/// changed.
|
||||
pub fn timing(&self) -> (Duration, Duration) {
|
||||
(self.build, self.updated_at.elapsed())
|
||||
}
|
||||
|
||||
/// A path argument, resolved: absolute, or relative to the first root
|
||||
/// 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 given = Path::new(arg);
|
||||
let candidates: Vec<PathBuf> = if given.is_absolute() {
|
||||
vec![given.to_path_buf()]
|
||||
} else {
|
||||
self.roots.iter().map(|root| root.join(given)).collect()
|
||||
};
|
||||
let Some(path) = candidates.iter().find_map(|c| canonical(c)) else {
|
||||
return Err(format!("`{arg}` does not exist under any root."));
|
||||
};
|
||||
if !self.roots.iter().any(|root| path.starts_with(root)) {
|
||||
return Err(format!(
|
||||
"`{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)
|
||||
}
|
||||
|
||||
/// `path` as answers print it: relative to the first root holding it,
|
||||
/// with `/` separators; absolute when no root does.
|
||||
pub fn relative(&self, path: &Path) -> String {
|
||||
relative_to(&self.roots, path)
|
||||
}
|
||||
|
||||
/// The analysis of one file as it is on disk now.
|
||||
pub fn analysis(&mut self, path: &Path) -> Result<Rc<Analysis>, String> {
|
||||
let (text, stamp) =
|
||||
read_source(path).map_err(|e| format!("cannot read `{}`: {e}", self.relative(path)))?;
|
||||
if let Some(held) = self.analyses.get(path, stamp.hash) {
|
||||
return Ok(held);
|
||||
}
|
||||
let analysis = Rc::new(Analysis::of(text));
|
||||
self.analyses.put(path.to_path_buf(), stamp.hash, Rc::clone(&analysis));
|
||||
Ok(analysis)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Project::relative`], for a caller that holds the roots but no project.
|
||||
fn relative_to(roots: &[PathBuf], path: &Path) -> String {
|
||||
let shown = roots.iter().find_map(|root| path.strip_prefix(root).ok()).unwrap_or(path);
|
||||
if shown.is_absolute() {
|
||||
return shown.display().to_string();
|
||||
}
|
||||
let parts: Vec<_> = shown.components().map(|c| c.as_os_str().to_string_lossy()).collect();
|
||||
parts.join("/")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,109 @@
|
||||
//! The freshness promise, against the rebuild oracle: after every update
|
||||
//! path the incrementally maintained index is the index a full build over
|
||||
//! the files now on disk produces (`WorkspaceIndex::fingerprint`).
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-project-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
/// The index a from-scratch build over the project's current files makes.
|
||||
fn rebuilt(project: &Project) -> String {
|
||||
let texts: Vec<(PathBuf, String)> = project
|
||||
.files()
|
||||
.map(|(path, _)| (path.clone(), fs::read_to_string(path).unwrap()))
|
||||
.collect();
|
||||
WorkspaceIndex::build(texts.iter().map(|(p, t)| (p.clone(), t.as_str()))).fingerprint()
|
||||
}
|
||||
|
||||
/// Age every stamp past the racy window, so only a real change is suspect.
|
||||
fn settle(project: &mut Project) {
|
||||
let later = SystemTime::now() + Duration::from_secs(10);
|
||||
for stamp in project.files.values_mut() {
|
||||
stamp.read_at = later;
|
||||
}
|
||||
}
|
||||
|
||||
fn write(dir: &Path, name: &str, text: &str) {
|
||||
fs::write(dir.join(name), text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_update_path_leaves_the_index_a_rebuild_would_make() {
|
||||
let dir = scratch("fingerprint");
|
||||
write(&dir, "a.sv", "module a(input logic x); b u_b(.*); endmodule\n");
|
||||
write(&dir, "b.sv", "module b(input logic x); endmodule\n");
|
||||
let mut project = Project::open(vec![dir.clone()], None);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
settle(&mut project);
|
||||
assert_eq!(project.refresh(false).changed, 0);
|
||||
|
||||
write(&dir, "b.sv", "module b(input logic x, output logic y); endmodule\n");
|
||||
let report = project.refresh(false);
|
||||
assert_eq!((report.changed, report.removed), (1, 0));
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
|
||||
write(&dir, "c.sv", "package c; parameter int W = 4; endpackage\n");
|
||||
let report = project.refresh(true);
|
||||
assert_eq!(report.added, 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
assert_eq!(project.index().units("c").len(), 1);
|
||||
|
||||
fs::remove_file(dir.join("a.sv")).unwrap();
|
||||
let report = project.refresh(false);
|
||||
assert!(report.walked, "a missing file triggers a walk");
|
||||
assert_eq!(report.removed, 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
assert!(project.index().units("a").is_empty());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_removed_and_recreated_between_two_calls_is_one_file_with_new_contents() {
|
||||
let dir = scratch("recreate");
|
||||
write(&dir, "a.sv", "module a; endmodule\n");
|
||||
let mut project = Project::open(vec![dir.clone()], None);
|
||||
settle(&mut project);
|
||||
fs::remove_file(dir.join("a.sv")).unwrap();
|
||||
write(&dir, "a.sv", "module a2; endmodule\n");
|
||||
project.refresh(false);
|
||||
assert!(project.index().units("a").is_empty());
|
||||
assert_eq!(project.index().units("a2").len(), 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_argument_must_land_inside_a_root() {
|
||||
let dir = scratch("resolve");
|
||||
let outside = scratch("resolve-outside");
|
||||
write(&dir, "a.sv", "module a; endmodule\n");
|
||||
write(&outside, "o.sv", "module o; endmodule\n");
|
||||
let project = Project::open(vec![dir.clone()], None);
|
||||
assert_eq!(project.resolve("a.sv").unwrap(), dir.join("a.sv"));
|
||||
assert_eq!(project.relative(&dir.join("a.sv")), "a.sv");
|
||||
let absolute = outside.join("o.sv");
|
||||
let refused = project.resolve(&absolute.to_string_lossy()).unwrap_err();
|
||||
assert!(refused.contains("outside every root"), "{refused}");
|
||||
let dotted = project.resolve("../lucisv-mcp-project-resolve-outside-x/o.sv").unwrap_err();
|
||||
assert!(dotted.contains("does not exist"), "{dotted}");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&absolute, dir.join("link.sv")).unwrap();
|
||||
let linked = project.resolve("link.sv").unwrap_err();
|
||||
assert!(linked.contains("outside every root"), "{linked}");
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
fs::remove_dir_all(outside).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! The rendering rules every tool's text answer follows (PLAN §4.5): the
|
||||
//! token budget is the product.
|
||||
//!
|
||||
//! - paths are root-relative, and a file is named once per group of lines
|
||||
//! about it, never once per line;
|
||||
//! - lines and columns are 1-based, a position is `line:col`, a range is
|
||||
//! `first-last`;
|
||||
//! - lists are capped, the cap is said with `… and N more` and the caller can
|
||||
//! page with `offset`;
|
||||
//! - no prose and no markdown headings: a label is a bare word and a colon,
|
||||
//! a table only where the columns are fixed.
|
||||
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
/// How many entries a list answer holds unless the caller says otherwise.
|
||||
pub const DEFAULT_LIMIT: usize = 200;
|
||||
|
||||
/// A declaration kind as one lower-case word — the keyword that declares it
|
||||
/// where there is one.
|
||||
pub fn kind(kind: SymbolKind) -> &'static str {
|
||||
match kind {
|
||||
SymbolKind::Module => "module",
|
||||
SymbolKind::Interface => "interface",
|
||||
SymbolKind::Modport => "modport",
|
||||
SymbolKind::Clocking => "clocking",
|
||||
SymbolKind::Package => "package",
|
||||
SymbolKind::Port => "port",
|
||||
SymbolKind::Net => "net",
|
||||
SymbolKind::Var => "var",
|
||||
SymbolKind::Param => "parameter",
|
||||
SymbolKind::LocalParam => "localparam",
|
||||
SymbolKind::Genvar => "genvar",
|
||||
SymbolKind::Typedef => "typedef",
|
||||
SymbolKind::EnumVariant => "enum_value",
|
||||
SymbolKind::Function => "function",
|
||||
SymbolKind::Task => "task",
|
||||
SymbolKind::TfArg => "argument",
|
||||
SymbolKind::Instance => "instance",
|
||||
SymbolKind::Block => "block",
|
||||
SymbolKind::StructMember => "field",
|
||||
SymbolKind::Class => "class",
|
||||
SymbolKind::Constraint => "constraint",
|
||||
SymbolKind::Covergroup => "covergroup",
|
||||
SymbolKind::Coverpoint => "coverpoint",
|
||||
SymbolKind::Cross => "cross",
|
||||
SymbolKind::Property => "property",
|
||||
SymbolKind::Sequence => "sequence",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every word [`kind`] can produce — what `read_item` accepts before a `:`.
|
||||
const KIND_WORDS: &[&str] = &[
|
||||
"module",
|
||||
"interface",
|
||||
"modport",
|
||||
"clocking",
|
||||
"package",
|
||||
"port",
|
||||
"net",
|
||||
"var",
|
||||
"parameter",
|
||||
"localparam",
|
||||
"genvar",
|
||||
"typedef",
|
||||
"enum_value",
|
||||
"function",
|
||||
"task",
|
||||
"argument",
|
||||
"instance",
|
||||
"block",
|
||||
"field",
|
||||
"class",
|
||||
"constraint",
|
||||
"covergroup",
|
||||
"coverpoint",
|
||||
"cross",
|
||||
"property",
|
||||
"sequence",
|
||||
];
|
||||
|
||||
/// Whether `word` is one of [`kind`]'s words.
|
||||
pub fn is_kind_word(word: &str) -> bool {
|
||||
KIND_WORDS.contains(&word)
|
||||
}
|
||||
|
||||
/// A line range as the answers print it: `12` or `12-40`.
|
||||
pub fn lines(first: u32, last: u32) -> String {
|
||||
if first == last {
|
||||
first.to_string()
|
||||
} else {
|
||||
format!("{first}-{last}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs of whitespace collapsed to one space, the ends trimmed: a
|
||||
/// declaration shown as one line whatever its source layout.
|
||||
pub fn one_line(text: &str) -> String {
|
||||
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// The window `offset..offset + limit` of a list, and how many entries
|
||||
/// follow it.
|
||||
pub fn page<T>(items: &[T], offset: usize, limit: usize) -> (&[T], usize) {
|
||||
let start = offset.min(items.len());
|
||||
let end = start.saturating_add(limit).min(items.len());
|
||||
(&items[start..end], items.len() - end)
|
||||
}
|
||||
|
||||
/// The line that says a list was cut, or nothing when it was not.
|
||||
pub fn more(out: &mut String, rest: usize) {
|
||||
if rest > 0 {
|
||||
out.push_str(&format!("… and {rest} more\n"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines grouped under the file they are about: the file once, then each
|
||||
/// of its lines indented by two spaces. Entries arrive in any order; groups
|
||||
/// keep the order in which each file first appears.
|
||||
pub fn grouped(entries: &[(String, String)]) -> String {
|
||||
let mut order: Vec<&str> = Vec::new();
|
||||
for (file, _) in entries {
|
||||
if !order.contains(&file.as_str()) {
|
||||
order.push(file);
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for file in order {
|
||||
out.push_str(file);
|
||||
out.push('\n');
|
||||
for (_, line) in entries.iter().filter(|(f, _)| f == file) {
|
||||
out.push_str(" ");
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows whose columns are padded to line up, the last column left ragged.
|
||||
pub fn table(rows: &[Vec<String>]) -> String {
|
||||
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||
let mut widths = vec![0; columns];
|
||||
for row in rows {
|
||||
for (at, cell) in row.iter().enumerate() {
|
||||
widths[at] = widths[at].max(cell.chars().count());
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for row in rows {
|
||||
let mut line = String::new();
|
||||
for (at, cell) in row.iter().enumerate() {
|
||||
if at + 1 < row.len() {
|
||||
// A column that is empty in every row takes no space at all.
|
||||
if widths[at] > 0 {
|
||||
line.push_str(&format!("{cell:<width$} ", width = widths[at]));
|
||||
}
|
||||
} else {
|
||||
line.push_str(cell);
|
||||
}
|
||||
}
|
||||
out.push_str(" ");
|
||||
out.push_str(line.trim_end());
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_kind_word_is_recognised_as_one() {
|
||||
use SymbolKind::*;
|
||||
let all = [
|
||||
Module,
|
||||
Interface,
|
||||
Modport,
|
||||
Clocking,
|
||||
Package,
|
||||
Port,
|
||||
Net,
|
||||
Var,
|
||||
Param,
|
||||
LocalParam,
|
||||
Genvar,
|
||||
Typedef,
|
||||
EnumVariant,
|
||||
Function,
|
||||
Task,
|
||||
TfArg,
|
||||
Instance,
|
||||
Block,
|
||||
StructMember,
|
||||
Class,
|
||||
Constraint,
|
||||
Covergroup,
|
||||
Coverpoint,
|
||||
Cross,
|
||||
Property,
|
||||
Sequence,
|
||||
];
|
||||
for symbol_kind in all {
|
||||
assert!(is_kind_word(kind(symbol_kind)), "{symbol_kind:?}");
|
||||
}
|
||||
assert_eq!(all.len(), KIND_WORDS.len());
|
||||
assert!(!is_kind_word("\\k"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_of_one_line_is_one_number() {
|
||||
assert_eq!(lines(3, 3), "3");
|
||||
assert_eq!(lines(3, 9), "3-9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_says_how_many_entries_follow_it() {
|
||||
let items = [1, 2, 3, 4, 5];
|
||||
assert_eq!(page(&items, 1, 2), (&items[1..3], 2));
|
||||
assert_eq!(page(&items, 9, 2), (&items[5..5], 0));
|
||||
let mut out = String::new();
|
||||
more(&mut out, 2);
|
||||
more(&mut out, 0);
|
||||
assert_eq!(out, "… and 2 more\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_named_once_per_group() {
|
||||
let entries = vec![
|
||||
("b.sv".to_string(), "module b 1".to_string()),
|
||||
("a.sv".to_string(), "module a 1".to_string()),
|
||||
("b.sv".to_string(), "module c 9".to_string()),
|
||||
];
|
||||
assert_eq!(grouped(&entries), "b.sv\n module b 1\n module c 9\na.sv\n module a 1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_columns_line_up_and_empty_columns_vanish() {
|
||||
let rows = vec![
|
||||
vec!["input".into(), "".into(), "logic".into(), "clk".into()],
|
||||
vec!["output".into(), "".into(), "logic [7:0]".into(), "q".into()],
|
||||
];
|
||||
assert_eq!(table(&rows), " input logic clk\n output logic [7:0] q\n");
|
||||
assert_eq!(one_line("a\n b\t c "), "a b c");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! The `lucisv://` resources: the project overview, the lint rule
|
||||
//! reference, one unit's interface and one file's outline — the same answers
|
||||
//! the read tools give, addressable by URI for a host that attaches context
|
||||
//! rather than calling tools.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::tools;
|
||||
|
||||
/// One resource a URI names.
|
||||
pub enum Resource {
|
||||
Overview,
|
||||
Rules,
|
||||
Unit(String),
|
||||
Outline(String),
|
||||
}
|
||||
|
||||
/// The `resources/list` result: the two fixed resources.
|
||||
pub fn list() -> Value {
|
||||
json!({ "resources": [
|
||||
{
|
||||
"uri": "lucisv://overview",
|
||||
"name": "overview",
|
||||
"title": "Project overview",
|
||||
"description": "Files, units by kind, top-level modules and largest files of the indexed project.",
|
||||
"mimeType": "text/plain",
|
||||
},
|
||||
{
|
||||
"uri": "lucisv://rules",
|
||||
"name": "rules",
|
||||
"title": "Lint rules",
|
||||
"description": "Every lucisv lint rule with its severity, default and options.",
|
||||
"mimeType": "text/markdown",
|
||||
},
|
||||
]})
|
||||
}
|
||||
|
||||
/// The `resources/templates/list` result: the two parameterised resources.
|
||||
pub fn templates() -> Value {
|
||||
json!({ "resourceTemplates": [
|
||||
{
|
||||
"uriTemplate": "lucisv://unit/{name}",
|
||||
"name": "unit",
|
||||
"title": "Unit interface",
|
||||
"description": "A module's or interface's parameters, ports and instantiation template; a package's or class's members.",
|
||||
"mimeType": "text/plain",
|
||||
},
|
||||
{
|
||||
"uriTemplate": "lucisv://file/{path}/outline",
|
||||
"name": "outline",
|
||||
"title": "File outline",
|
||||
"description": "The declarations in one root-relative file, with line ranges.",
|
||||
"mimeType": "text/plain",
|
||||
},
|
||||
]})
|
||||
}
|
||||
|
||||
impl Resource {
|
||||
/// The resource `uri` names, or `None` for any other URI.
|
||||
pub fn parse(uri: &str) -> Option<Resource> {
|
||||
let rest = uri.strip_prefix("lucisv://")?;
|
||||
match rest {
|
||||
"overview" => Some(Resource::Overview),
|
||||
"rules" => Some(Resource::Rules),
|
||||
_ => {
|
||||
if let Some(name) = rest.strip_prefix("unit/") {
|
||||
return decoded(name).map(Resource::Unit);
|
||||
}
|
||||
let path = rest.strip_prefix("file/")?.strip_suffix("/outline")?;
|
||||
decoded(path).map(Resource::Outline)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether answering needs the project index (only the rules do not).
|
||||
pub fn needs_project(&self) -> bool {
|
||||
!matches!(self, Resource::Rules)
|
||||
}
|
||||
|
||||
/// Whether answering walks the roots first, as `project_overview` does.
|
||||
pub fn rewalk(&self) -> bool {
|
||||
matches!(self, Resource::Overview)
|
||||
}
|
||||
|
||||
/// The `resources/read` result, or the reason there is no such resource.
|
||||
pub fn read(&self, uri: &str, project: Option<&mut Project>) -> Result<Value, String> {
|
||||
let (mime, text) = match (self, project) {
|
||||
(Resource::Rules, _) => ("text/markdown", vlog_linter::rules_markdown()),
|
||||
(Resource::Overview, Some(project)) => {
|
||||
("text/plain", run(project, "project_overview", None)?)
|
||||
}
|
||||
(Resource::Unit(name), Some(project)) => {
|
||||
// A URI has no `file` argument to pick among declarations.
|
||||
let text = run(project, "unit_interface", Some(("name", name))).map_err(|why| {
|
||||
why.replace(
|
||||
"pass `file` to pick one",
|
||||
"call the unit_interface tool with its file argument to pick one",
|
||||
)
|
||||
})?;
|
||||
("text/plain", text)
|
||||
}
|
||||
(Resource::Outline(path), Some(project)) => {
|
||||
("text/plain", run(project, "outline", Some(("file", path)))?)
|
||||
}
|
||||
(_, None) => return Err("the project is not open".into()),
|
||||
};
|
||||
Ok(json!({ "contents": [{ "uri": uri, "mimeType": mime, "text": text }] }))
|
||||
}
|
||||
}
|
||||
|
||||
/// A read tool's text answer, as the resource's body.
|
||||
fn run(
|
||||
project: &mut Project,
|
||||
tool: &str,
|
||||
argument: Option<(&str, &str)>,
|
||||
) -> Result<String, String> {
|
||||
let tool = tools::find(tool).ok_or_else(|| format!("no tool `{tool}`"))?;
|
||||
let mut arguments = Map::new();
|
||||
if let Some((name, value)) = argument {
|
||||
arguments.insert(name.to_string(), Value::from(value));
|
||||
}
|
||||
let args = tools::validate(tool, arguments)?;
|
||||
(tool.handler)(project, &args).map(|answer| answer.text)
|
||||
}
|
||||
|
||||
/// `%XX` escapes decoded; `None` for a malformed escape, an empty result or
|
||||
/// bytes that are not UTF-8.
|
||||
fn decoded(text: &str) -> Option<String> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut at = 0;
|
||||
while at < bytes.len() {
|
||||
if bytes[at] == b'%' {
|
||||
let hex = text.get(at + 1..at + 3)?;
|
||||
out.push(u8::from_str_radix(hex, 16).ok()?);
|
||||
at += 3;
|
||||
} else {
|
||||
out.push(bytes[at]);
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).ok().filter(|decoded| !decoded.is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parsed(uri: &str) -> Option<String> {
|
||||
Resource::parse(uri).map(|resource| match resource {
|
||||
Resource::Overview => "overview".into(),
|
||||
Resource::Rules => "rules".into(),
|
||||
Resource::Unit(name) => format!("unit {name}"),
|
||||
Resource::Outline(path) => format!("outline {path}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uris_name_their_resource_and_nothing_else_does() {
|
||||
assert_eq!(parsed("lucisv://overview").as_deref(), Some("overview"));
|
||||
assert_eq!(parsed("lucisv://rules").as_deref(), Some("rules"));
|
||||
assert_eq!(parsed("lucisv://unit/leaf").as_deref(), Some("unit leaf"));
|
||||
assert_eq!(parsed("lucisv://unit/%5Cmy-mod%20").as_deref(), Some("unit \\my-mod "));
|
||||
assert_eq!(
|
||||
parsed("lucisv://file/rtl/top.sv/outline").as_deref(),
|
||||
Some("outline rtl/top.sv")
|
||||
);
|
||||
for other in [
|
||||
"lucisv://unit/",
|
||||
"lucisv://unit/%zz",
|
||||
"lucisv://file/rtl/top.sv",
|
||||
"lucisv://file//outline",
|
||||
"file:///etc/passwd",
|
||||
"lucisv://overview/x",
|
||||
] {
|
||||
assert!(parsed(other).is_none(), "{other}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! One synchronous loop, like `lucisv-server`: a request is answered before
|
||||
//! the next line is read, so pipelined requests are answered in order.
|
||||
|
||||
use std::io;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::resources::{self, Resource};
|
||||
use crate::tools;
|
||||
use crate::transport::{Line, Transport};
|
||||
use crate::Options;
|
||||
|
||||
/// The protocol revisions this server speaks, newest first. All are the
|
||||
/// handshake-based ("legacy") era: from `2026-07-28` on, MCP carries the
|
||||
/// version on every request instead of negotiating it in `initialize`, and a
|
||||
/// server of that era is a different server (feature README, Assumptions).
|
||||
pub const PROTOCOL_VERSIONS: &[&str] = &[NEWEST, "2025-06-18"];
|
||||
|
||||
/// What a client asking for a revision we do not speak is offered.
|
||||
const NEWEST: &str = "2025-11-25";
|
||||
|
||||
/// JSON-RPC's own error codes, and the one MCP (after LSP) adds.
|
||||
const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
const METHOD_NOT_FOUND: i64 = -32601;
|
||||
const INVALID_PARAMS: i64 = -32602;
|
||||
const NOT_INITIALIZED: i64 = -32002;
|
||||
/// MCP's "resource not found".
|
||||
const RESOURCE_NOT_FOUND: i64 = -32002;
|
||||
|
||||
/// What the agent is told once, at `initialize`.
|
||||
const INSTRUCTIONS: &str = "lucisv-mcp answers questions about the Verilog/SystemVerilog design under its roots, read from the files on disk (never from unsaved editor buffers). Prefer unit_interface for a module's parameters and ports, outline for what a file declares, and read_item for one module, function or always block over reading whole files; list_units and search_symbols find where things are declared. Paths in answers are relative to the root; lines and columns are 1-based.";
|
||||
|
||||
/// A JSON-RPC error object.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct RpcError {
|
||||
code: i64,
|
||||
message: String,
|
||||
}
|
||||
|
||||
fn fault(code: i64, message: impl Into<String>) -> RpcError {
|
||||
RpcError { code, message: message.into() }
|
||||
}
|
||||
|
||||
/// A response line: exactly one of `result` and `error`.
|
||||
#[derive(Serialize)]
|
||||
struct Response<'a> {
|
||||
jsonrpc: &'static str,
|
||||
id: &'a Value,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
result: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
error: Option<RpcError>,
|
||||
}
|
||||
|
||||
fn response(id: &Value, answer: Result<Value, RpcError>) -> Value {
|
||||
let (result, error) = match answer {
|
||||
Ok(result) => (Some(result), None),
|
||||
Err(error) => (None, Some(error)),
|
||||
};
|
||||
let response = Response { jsonrpc: "2.0", id, result, error };
|
||||
serde_json::to_value(response).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// One incoming line, classified.
|
||||
enum Message {
|
||||
Request {
|
||||
id: Value,
|
||||
method: String,
|
||||
params: Option<Value>,
|
||||
},
|
||||
Notification {
|
||||
method: String,
|
||||
},
|
||||
/// A response to a request we never send: logged, never answered.
|
||||
Response,
|
||||
/// Not a message this protocol has; answered `-32600` with this id.
|
||||
Invalid {
|
||||
id: Value,
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn classify(value: Value) -> Message {
|
||||
let Value::Object(mut object) = value else {
|
||||
return Message::Invalid {
|
||||
id: Value::Null,
|
||||
reason: "a message must be a JSON object".into(),
|
||||
};
|
||||
};
|
||||
let id = object.remove("id");
|
||||
let valid_id = id.as_ref().is_some_and(|id| id.is_string() || id.is_i64() || id.is_u64());
|
||||
// JSON-RPC 2.0 §5: an error answer carries the request's id whenever it
|
||||
// could be read, and `null` only when it could not.
|
||||
let readable_id = if valid_id { id.clone().unwrap_or(Value::Null) } else { Value::Null };
|
||||
if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
|
||||
return Message::Invalid { id: readable_id, reason: "`jsonrpc` must be \"2.0\"".into() };
|
||||
}
|
||||
let Some(method) = object.get("method").and_then(Value::as_str).map(str::to_string) else {
|
||||
if object.contains_key("result") || object.contains_key("error") {
|
||||
return Message::Response;
|
||||
}
|
||||
return Message::Invalid {
|
||||
id: readable_id,
|
||||
reason: "a message needs a string `method`".into(),
|
||||
};
|
||||
};
|
||||
match id {
|
||||
None => Message::Notification { method },
|
||||
Some(id) if valid_id => Message::Request { id, method, params: object.remove("params") },
|
||||
Some(_) => Message::Invalid {
|
||||
id: Value::Null,
|
||||
reason: "`id` must be a string or an integer".into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The server's state across messages.
|
||||
pub struct Server {
|
||||
options: Options,
|
||||
version: Option<&'static str>,
|
||||
project: Option<Project>,
|
||||
}
|
||||
|
||||
/// Run the loop over stdin/stdout until the client closes stdin.
|
||||
/// `options.roots` must already be canonical (`project::canonical_roots`).
|
||||
pub fn serve(options: Options) -> Result<(), String> {
|
||||
let mut transport = Transport::new(io::stdin().lock(), io::stdout().lock());
|
||||
let mut server = Server { options, version: None, project: None };
|
||||
loop {
|
||||
let reply = match transport.read_line().map_err(|e| format!("reading stdin: {e}"))? {
|
||||
Line::Eof => return Ok(()),
|
||||
Line::NotUtf8 => {
|
||||
Some(response(&Value::Null, Err(fault(PARSE_ERROR, "the line is not UTF-8"))))
|
||||
}
|
||||
Line::Text(text) if text.trim().is_empty() => None,
|
||||
Line::Text(text) => server.handle_line(&text),
|
||||
};
|
||||
if let Some(reply) = reply {
|
||||
transport.write_message(&reply).map_err(|e| format!("writing stdout: {e}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Answer one line: `Some` response for a request or a malformed line,
|
||||
/// `None` for a notification or a stray response.
|
||||
pub fn handle_line(&mut self, text: &str) -> Option<Value> {
|
||||
let value: Value = match serde_json::from_str(text) {
|
||||
Ok(value) => value,
|
||||
Err(problem) => {
|
||||
return Some(response(
|
||||
&Value::Null,
|
||||
Err(fault(PARSE_ERROR, format!("parse error: {problem}"))),
|
||||
))
|
||||
}
|
||||
};
|
||||
match classify(value) {
|
||||
Message::Request { id, method, params } => {
|
||||
let started = Instant::now();
|
||||
let answer = self.request(&method, params);
|
||||
if self.options.verbose {
|
||||
eprintln!("lucisv-mcp: {method} {} ms", started.elapsed().as_millis());
|
||||
}
|
||||
Some(response(&id, answer))
|
||||
}
|
||||
Message::Notification { method } => {
|
||||
// `notifications/initialized` and `notifications/cancelled` are
|
||||
// accepted; every other notification is ignored, as the spec
|
||||
// allows. Cancellation cannot interrupt a synchronous call.
|
||||
if self.options.verbose {
|
||||
eprintln!("lucisv-mcp: notification {method}");
|
||||
}
|
||||
None
|
||||
}
|
||||
Message::Response => None,
|
||||
Message::Invalid { id, reason } => {
|
||||
Some(response(&id, Err(fault(INVALID_REQUEST, reason))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Option<Value>) -> Result<Value, RpcError> {
|
||||
match method {
|
||||
"initialize" => Ok(self.initialize(params.as_ref())),
|
||||
"ping" => Ok(json!({})),
|
||||
_ if self.version.is_none() => Err(fault(NOT_INITIALIZED, "server not initialized")),
|
||||
"tools/list" => Ok(tools::list()),
|
||||
"tools/call" => self.call_tool(params),
|
||||
"resources/list" => Ok(resources::list()),
|
||||
"resources/templates/list" => Ok(resources::templates()),
|
||||
"resources/read" => self.read_resource(params),
|
||||
"prompts/list" => Ok(json!({ "prompts": [] })),
|
||||
"prompts/get" => Err(fault(INVALID_PARAMS, "unknown prompt")),
|
||||
other => Err(fault(METHOD_NOT_FOUND, format!("method not found: {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The handshake: echo the client's revision when it is one we speak,
|
||||
/// else offer our newest and let the client decide.
|
||||
fn initialize(&mut self, params: Option<&Value>) -> Value {
|
||||
let asked = params.and_then(|p| p.get("protocolVersion")).and_then(Value::as_str);
|
||||
let version =
|
||||
PROTOCOL_VERSIONS.iter().find(|v| Some(**v) == asked).copied().unwrap_or(NEWEST);
|
||||
self.version = Some(version);
|
||||
json!({
|
||||
"protocolVersion": version,
|
||||
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
|
||||
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
|
||||
"instructions": INSTRUCTIONS,
|
||||
})
|
||||
}
|
||||
|
||||
/// `tools/call`: find the tool, check its arguments, bring the project up
|
||||
/// to the disk, run it. A refusal — including an argument that does not
|
||||
/// fit the schema — is a tool result with `isError`, so the agent reads
|
||||
/// the sentence and can correct itself; only an envelope the method
|
||||
/// cannot read at all, or a tool that does not exist, is a JSON-RPC error.
|
||||
fn call_tool(&mut self, params: Option<Value>) -> Result<Value, RpcError> {
|
||||
let Some(Value::Object(mut params)) = params else {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call params must be an object"));
|
||||
};
|
||||
let Some(Value::String(name)) = params.remove("name") else {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call params need a string `name`"));
|
||||
};
|
||||
let Some(tool) = tools::find(&name) else {
|
||||
return Err(fault(INVALID_PARAMS, format!("unknown tool: {name}")));
|
||||
};
|
||||
let arguments = match params.remove("arguments") {
|
||||
None | Some(Value::Null) => Map::new(),
|
||||
Some(Value::Object(arguments)) => arguments,
|
||||
Some(_) => {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call `arguments` must be an object"))
|
||||
}
|
||||
};
|
||||
let args = match tools::validate(tool, arguments) {
|
||||
Ok(args) => args,
|
||||
Err(refusal) => return Ok(tool_result(Err(refusal))),
|
||||
};
|
||||
let project = self.project(tool.rewalk);
|
||||
Ok(tool_result((tool.handler)(project, &args)))
|
||||
}
|
||||
|
||||
/// `resources/read`: a `lucisv://` URI answered from the project as it is
|
||||
/// on disk now; any other URI, or one naming nothing (a unit or file that
|
||||
/// does not exist), is `-32002` with the reason.
|
||||
fn read_resource(&mut self, params: Option<Value>) -> Result<Value, RpcError> {
|
||||
let Some(uri) = params.as_ref().and_then(|p| p.get("uri")).and_then(Value::as_str) else {
|
||||
return Err(fault(INVALID_PARAMS, "resources/read params need a string `uri`"));
|
||||
};
|
||||
let not_found =
|
||||
|why: &str| fault(RESOURCE_NOT_FOUND, format!("resource not found: {uri}{why}"));
|
||||
let Some(resource) = Resource::parse(uri) else {
|
||||
return Err(not_found(""));
|
||||
};
|
||||
let project = match resource.needs_project() {
|
||||
true => Some(self.project(resource.rewalk())),
|
||||
false => None,
|
||||
};
|
||||
resource.read(uri, project).map_err(|why| not_found(&format!(" ({why})")))
|
||||
}
|
||||
|
||||
/// The project, built on first use and brought up to the disk on every
|
||||
/// later one.
|
||||
fn project(&mut self, rewalk: bool) -> &mut Project {
|
||||
let options = &self.options;
|
||||
let existed = self.project.is_some();
|
||||
let project = self.project.get_or_insert_with(|| open_project(options));
|
||||
if existed {
|
||||
let refresh = project.refresh(rewalk);
|
||||
if options.verbose {
|
||||
eprintln!("lucisv-mcp: refresh {refresh:?}");
|
||||
}
|
||||
}
|
||||
project
|
||||
}
|
||||
}
|
||||
|
||||
/// Discover and index the project, saying on stderr how long it took.
|
||||
fn open_project(options: &Options) -> Project {
|
||||
let project = Project::open(options.roots.clone(), options.filelist.clone());
|
||||
let (build, _) = project.timing();
|
||||
eprintln!("lucisv-mcp: indexed {} files in {} ms", project.files().count(), build.as_millis());
|
||||
project
|
||||
}
|
||||
|
||||
/// A tool's answer as `tools/call` returns it.
|
||||
fn tool_result(answer: Result<tools::Answer, String>) -> Value {
|
||||
match answer {
|
||||
Ok(answer) => json!({
|
||||
"content": [{ "type": "text", "text": answer.text }],
|
||||
"structuredContent": answer.structured,
|
||||
"isError": false,
|
||||
}),
|
||||
Err(refusal) => json!({
|
||||
"content": [{ "type": "text", "text": refusal }],
|
||||
"isError": true,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn server() -> Server {
|
||||
Server { options: Options::default(), version: None, project: None }
|
||||
}
|
||||
|
||||
fn error_code(reply: &Value) -> i64 {
|
||||
reply["error"]["code"].as_i64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handshake_echoes_a_known_revision_and_offers_the_newest_otherwise() {
|
||||
let mut s = server();
|
||||
let reply = s
|
||||
.handle_line(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(reply["result"]["protocolVersion"], "2025-06-18");
|
||||
assert_eq!(reply["result"]["serverInfo"]["name"], "lucisv-mcp");
|
||||
let reply = s
|
||||
.handle_line(r#"{"jsonrpc":"2.0","id":"a","method":"initialize","params":{"protocolVersion":"2026-07-28"}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(reply["result"]["protocolVersion"], NEWEST);
|
||||
assert_eq!(reply["id"], "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_lines_are_answered_with_the_right_code_and_never_crash() {
|
||||
let mut s = server();
|
||||
let reply = s.handle_line("not json").unwrap();
|
||||
assert_eq!((error_code(&reply), reply["id"].clone()), (PARSE_ERROR, Value::Null));
|
||||
assert_eq!(error_code(&s.handle_line("[1,2]").unwrap()), INVALID_REQUEST);
|
||||
assert_eq!(
|
||||
error_code(&s.handle_line(r#"{"jsonrpc":"1.0","id":1,"method":"ping"}"#).unwrap()),
|
||||
INVALID_REQUEST
|
||||
);
|
||||
let null_id = s.handle_line(r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#).unwrap();
|
||||
assert_eq!(error_code(&null_id), INVALID_REQUEST);
|
||||
assert!(s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/cancelled"}"#).is_none());
|
||||
assert!(s.handle_line(r#"{"jsonrpc":"2.0","id":7,"result":{}}"#).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_before_initialize_are_refused_except_ping() {
|
||||
let mut s = server();
|
||||
let ping = s.handle_line(r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#).unwrap();
|
||||
assert_eq!(ping["result"], json!({}));
|
||||
let early = s.handle_line(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#).unwrap();
|
||||
assert_eq!(error_code(&early), NOT_INITIALIZED);
|
||||
s.handle_line(r#"{"jsonrpc":"2.0","id":3,"method":"initialize","params":{}}"#);
|
||||
let unknown = s.handle_line(r#"{"jsonrpc":"2.0","id":4,"method":"sampling/x"}"#).unwrap();
|
||||
assert_eq!(error_code(&unknown), METHOD_NOT_FOUND);
|
||||
let bad_tool = s
|
||||
.handle_line(
|
||||
r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nope"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(error_code(&bad_tool), INVALID_PARAMS);
|
||||
assert!(bad_tool["error"]["message"].as_str().unwrap().contains("nope"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! `defines`: the `` `define`` table — one file's, one macro's every
|
||||
//! definition across the project, or the whole project's — without reading
|
||||
//! the files. Bookkeeping only, like `vlog_parser::defines`: nothing here
|
||||
//! expands a macro (the README says why the one-step expansion is not
|
||||
//! offered).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::defines::{Define, DefineKind};
|
||||
|
||||
use super::source::{self, Texts};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
/// A body longer than this many characters is cut, with `…`.
|
||||
const BODY_CAP: usize = 200;
|
||||
|
||||
pub const DEFINES: Tool = Tool {
|
||||
name: "defines",
|
||||
title: "Macro definitions",
|
||||
description: "The `define table: name, parameters, body (on one line) and file:line — of one `file`, of one macro `name` across the project (every definition; which one a use sees depends on include order, so none is picked), or of the whole project. Prefer it over grepping for `define.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Only this file's table (its `undef`s included), relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Only this macro, written with or without the backtick.",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most entries to return (default 200).",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Entries to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: defines,
|
||||
};
|
||||
|
||||
/// One table row, ready to render.
|
||||
struct Row {
|
||||
file: String,
|
||||
line: u32,
|
||||
define: Define,
|
||||
}
|
||||
|
||||
fn defines(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").map(|name| name.trim_start_matches('`')).filter(|n| !n.is_empty());
|
||||
let (rows, rest, total) = match args.str("file") {
|
||||
Some(file) => in_file(project, file, name, args)?,
|
||||
None => {
|
||||
let mut all = indexed(project, name);
|
||||
if all.is_empty() && name.is_some() && project.ensure_walked_for_miss() {
|
||||
all = indexed(project, name);
|
||||
}
|
||||
let (shown, rest) =
|
||||
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
(rows_of(project, shown), rest, all.len())
|
||||
}
|
||||
};
|
||||
let entries: Vec<(String, String)> = rows
|
||||
.iter()
|
||||
.map(|row| (row.file.clone(), format!("{} {}", row.line, spelled(&row.define))))
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if total == 0 {
|
||||
text = "no defines\n".to_string();
|
||||
}
|
||||
let listed: Vec<Value> = rows.iter().map(row_json).collect();
|
||||
Ok(Answer { text, structured: json!({ "defines": listed, "total": total }) })
|
||||
}
|
||||
|
||||
/// One file's table as it is on disk now, filtered by `name`.
|
||||
fn in_file(
|
||||
project: &mut Project,
|
||||
file: &str,
|
||||
name: Option<&str>,
|
||||
args: &Args,
|
||||
) -> Result<(Vec<Row>, usize, usize), String> {
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let shown_file = project.relative(&path);
|
||||
let all: Vec<&Define> = analysis
|
||||
.defines
|
||||
.entries()
|
||||
.iter()
|
||||
.filter(|define| name.is_none_or(|name| define.name == name))
|
||||
.collect();
|
||||
let (shown, rest) =
|
||||
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let rows = shown
|
||||
.iter()
|
||||
.map(|define| Row {
|
||||
file: shown_file.clone(),
|
||||
line: analysis.lines.line_col(define.span.start).0,
|
||||
define: (*define).clone(),
|
||||
})
|
||||
.collect();
|
||||
Ok((rows, rest, all.len()))
|
||||
}
|
||||
|
||||
/// Every indexed definition (of `name`, when given), in file order.
|
||||
fn indexed(project: &Project, name: Option<&str>) -> Vec<(PathBuf, Define)> {
|
||||
let index = project.index();
|
||||
let of =
|
||||
|file, define: &Define| index.path(file).map(|path| (path.to_path_buf(), define.clone()));
|
||||
match name {
|
||||
Some(name) => index.find_define(name).into_iter().filter_map(|(f, d)| of(f, d)).collect(),
|
||||
None => (0..index.files().len() as u32)
|
||||
.map(vlog_semantic::FileId)
|
||||
.flat_map(|file| {
|
||||
let entries = index.defines(file).map(|table| table.entries()).unwrap_or(&[]);
|
||||
entries
|
||||
.iter()
|
||||
.filter(|d| d.kind == DefineKind::Define)
|
||||
.filter_map(move |d| of(file, d))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows for indexed definitions, each line read off its file now; a
|
||||
/// definition whose file no longer spells its name there is omitted.
|
||||
fn rows_of(project: &Project, shown: &[(PathBuf, Define)]) -> Vec<Row> {
|
||||
let mut texts = Texts::default();
|
||||
shown
|
||||
.iter()
|
||||
.filter_map(|(path, define)| {
|
||||
let line = checked_line(&mut texts, path, define)?;
|
||||
Some(Row { file: project.relative(path), line, define: define.clone() })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_line(texts: &mut Texts, path: &Path, define: &Define) -> Option<u32> {
|
||||
let (text, lines) = texts.get(path)?;
|
||||
let spelled = text.get(define.name_span.as_range())?;
|
||||
(spelled == define.name).then(|| lines.line_col(define.span.start).0)
|
||||
}
|
||||
|
||||
/// A definition as one line: `` `define NAME(a, b) body``, the body capped.
|
||||
fn spelled(define: &Define) -> String {
|
||||
if define.kind == DefineKind::Undef {
|
||||
return format!("`undef {}", define.name);
|
||||
}
|
||||
let mut out = format!("`define {}", define.name);
|
||||
if let Some(params) = &define.params {
|
||||
out.push_str(&format!("({})", params.join(", ")));
|
||||
}
|
||||
let body = source::capped(&define.body, BODY_CAP);
|
||||
if !body.is_empty() {
|
||||
out.push(' ');
|
||||
out.push_str(&body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn row_json(row: &Row) -> Value {
|
||||
let define = &row.define;
|
||||
json!({
|
||||
"file": row.file,
|
||||
"line": row.line,
|
||||
"name": define.name,
|
||||
"kind": if define.kind == DefineKind::Undef { "undef" } else { "define" },
|
||||
"params": define.params,
|
||||
"body": source::capped(&define.body, BODY_CAP),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::defines::collect_defines;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
fn table(text: &str) -> Vec<Define> {
|
||||
collect_defines(&tokenize(text).unwrap()).entries().to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_definition_is_spelled_on_one_line_with_its_parameters() {
|
||||
let all = table("`define ADD(a, b = 1) \\\n ((a) + (b))\n`define W 8\n`undef W\n");
|
||||
assert_eq!(spelled(&all[0]), "`define ADD(a, b = 1) ((a) + (b))");
|
||||
assert_eq!(spelled(&all[1]), "`define W 8");
|
||||
assert_eq!(spelled(&all[2]), "`undef W");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_body_is_cut_at_the_cap() {
|
||||
let body = "x ".repeat(300);
|
||||
let cut = source::capped(&body, BODY_CAP);
|
||||
assert_eq!(cut.chars().count(), BODY_CAP + 1);
|
||||
assert!(cut.ends_with('…'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
//! `diagnostics`: what `lucisv check` would say about one file or the whole
|
||||
//! project — the tolerant parse's errors first, then the lint findings —
|
||||
//! with the CLI's JSON field names, so one contract serves CI and agents.
|
||||
//!
|
||||
//! The lint run is the CLI's, rung for rung: the `lucisv.toml` governing each
|
||||
//! file (`Discovery::for_file`) gives `[lint] select`/`ignore`, the
|
||||
//! `[lint.<rule>]` options, the external `waivers` and the formatter's line
|
||||
//! length; the `rules` argument replaces `select` as `--select` does; the
|
||||
//! workspace rules run, their questions answered by the project index
|
||||
//! ([`Mentions`]). Missing-closer warnings are the language server's own
|
||||
//! (`pairs.rs`, not a library) and are not offered.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use serde_json::{json, Value};
|
||||
use vlog_linter::{
|
||||
lint_with, select_rules, Exports, ExternalWaivers, LintContext, MentionOracle, ModuleInterface,
|
||||
Rule, RuleOptions, Violation, WaiverUse,
|
||||
};
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_semantic::{FileId, PackageExports, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
pub const DIAGNOSTICS: Tool = Tool {
|
||||
name: "diagnostics",
|
||||
title: "Diagnostics",
|
||||
description: "Parse errors and lint findings for one `file`, or for every indexed file, grouped by file as `line:col severity message [rule]` — what `lucisv check` over the whole tree reports (cross-file rules on), under the project's lucisv.toml [lint] settings and waivers. Filter with `rules` (like --select) and `severity`. The whole-project form lints every file and returns the first `limit` findings with the total.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "One file, relative to a root or absolute inside one (default: every indexed file).",
|
||||
},
|
||||
Param {
|
||||
name: "rules",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Comma-separated rule names or severities to run instead of the configured set, like `--select`.",
|
||||
},
|
||||
Param {
|
||||
name: "severity",
|
||||
ty: Ty::Enum(&["error", "warning", "style"]),
|
||||
required: false,
|
||||
description: "Only findings of this severity (parse errors are `error`).",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most findings to return (default 200).",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Findings to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: diagnostics,
|
||||
};
|
||||
|
||||
/// One finding, in the CLI's JSON shape.
|
||||
struct Finding {
|
||||
file: String,
|
||||
rule: String,
|
||||
severity: &'static str,
|
||||
message: String,
|
||||
start: (u32, u32),
|
||||
end: (u32, u32),
|
||||
range: (u32, u32),
|
||||
fix: Value,
|
||||
}
|
||||
|
||||
/// What one config file makes of a lint run.
|
||||
pub(super) struct Run {
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
options: RuleOptions,
|
||||
waivers: ExternalWaivers,
|
||||
line_length: usize,
|
||||
tab_width: usize,
|
||||
/// Which external waivers fired, over every file this run linted.
|
||||
used: RefCell<WaiverUse>,
|
||||
}
|
||||
|
||||
fn diagnostics(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let selected: Option<Vec<String>> = args.str("rules").map(|rules| {
|
||||
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
|
||||
});
|
||||
let mut runs = Runs::new(selected);
|
||||
let mut findings = Vec::new();
|
||||
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);
|
||||
findings = file_findings(project, &mut runs, &path, &analysis, &oracle)?;
|
||||
}
|
||||
None => {
|
||||
let census = Census::of(project.index());
|
||||
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
|
||||
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, &mut runs, &path, &analysis, &oracle)?);
|
||||
}
|
||||
// Only a complete run knows a waiver matched nothing.
|
||||
findings.extend(runs.unused_waivers(project));
|
||||
}
|
||||
}
|
||||
if let Some(severity) = args.str("severity") {
|
||||
findings.retain(|finding| finding.severity == severity);
|
||||
}
|
||||
Ok(render_findings(&findings, args))
|
||||
}
|
||||
|
||||
/// The runs met so far in one call, one per governing config file — shared
|
||||
/// with `fix_lint`, so a fix runs under exactly the rules a finding came from.
|
||||
pub(super) struct Runs {
|
||||
discovery: Discovery,
|
||||
held: BTreeMap<Option<PathBuf>, Rc<Run>>,
|
||||
selected: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Runs {
|
||||
/// No run built yet; `selected` replaces each config's `[lint] select`.
|
||||
pub(super) fn new(selected: Option<Vec<String>>) -> Runs {
|
||||
Runs { discovery: Discovery::new(true), held: BTreeMap::new(), selected }
|
||||
}
|
||||
|
||||
/// The run for the config governing `path`, built on first use. A config
|
||||
/// that does not read, an unknown rule, a bad option or an unreadable
|
||||
/// waiver file is a refusal naming it — `lucisv check` fails the same way.
|
||||
pub(super) fn for_file(&mut self, path: &Path) -> Result<Rc<Run>, String> {
|
||||
let config = self.discovery.for_file(path)?;
|
||||
if let Some(run) = self.held.get(&config.source) {
|
||||
return Ok(Rc::clone(run));
|
||||
}
|
||||
let run = Rc::new(self.build(&config)?);
|
||||
self.held.insert(config.source.clone(), Rc::clone(&run));
|
||||
Ok(run)
|
||||
}
|
||||
|
||||
fn build(&self, config: &FileConfig) -> Result<Run, String> {
|
||||
let select = match &self.selected {
|
||||
Some(selected) => selected.clone(),
|
||||
None => config.lint_select.clone().unwrap_or_default(),
|
||||
};
|
||||
let ignore = config.lint_ignore.clone().unwrap_or_default();
|
||||
let rules = select_rules(&select, &ignore, true)?;
|
||||
let mut options = RuleOptions::new();
|
||||
for entry in &config.lint_options {
|
||||
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
|
||||
let file = config
|
||||
.source
|
||||
.as_ref()
|
||||
.map_or("lucisv.toml".into(), |p| p.display().to_string());
|
||||
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
|
||||
})?;
|
||||
}
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
for path in config.lint_waivers.iter().flatten() {
|
||||
let (file, problems) = ExternalWaivers::read(path)?;
|
||||
if let Some(problem) = problems.first() {
|
||||
return Err(problem.clone());
|
||||
}
|
||||
waivers.absorb(file);
|
||||
}
|
||||
let format = vlog_formatter::Config::default();
|
||||
Ok(Run {
|
||||
rules,
|
||||
options,
|
||||
waivers,
|
||||
line_length: config.line_length.unwrap_or(format.max_width),
|
||||
tab_width: config.indent.unwrap_or(format.indent_width),
|
||||
used: RefCell::new(WaiverUse::default()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Runs {
|
||||
/// One `unused-waiver` finding per external directive that suppressed
|
||||
/// nothing in any file its run linted — the CLI's end-of-run report.
|
||||
fn unused_waivers(&self, project: &Project) -> Vec<Finding> {
|
||||
let mut out = Vec::new();
|
||||
for run in self.held.values() {
|
||||
let enabled: Vec<&'static str> = run.rules.iter().map(|rule| rule.name()).collect();
|
||||
for report in run.waivers.unused(&run.used.borrow(), &enabled) {
|
||||
let lines = LineIndex::new(&report.text);
|
||||
let file = project.relative(&report.path);
|
||||
out.extend(report.violations.iter().map(|v| lint_finding(&file, &lines, v)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's findings: its parse errors, then its lint findings.
|
||||
fn file_findings(
|
||||
project: &Project,
|
||||
runs: &mut Runs,
|
||||
path: &Path,
|
||||
analysis: &Analysis,
|
||||
oracle: &Mentions,
|
||||
) -> Result<Vec<Finding>, String> {
|
||||
let file = project.relative(path);
|
||||
let run = runs.for_file(path)?;
|
||||
let mut out: Vec<Finding> = analysis
|
||||
.diagnostics
|
||||
.iter()
|
||||
.map(|error| Finding {
|
||||
file: file.clone(),
|
||||
rule: "parse-error".into(),
|
||||
severity: "error",
|
||||
message: error.message.clone(),
|
||||
start: (error.line, error.col),
|
||||
end: analysis.lines.line_col(error.span.end),
|
||||
range: (error.span.start, error.span.end),
|
||||
fix: Value::Null,
|
||||
})
|
||||
.collect();
|
||||
let violations = violations(&run, path, analysis, oracle);
|
||||
out.extend(violations.iter().map(|violation| lint_finding(&file, &analysis.lines, violation)));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One file's lint findings under `run`, its waivers applied.
|
||||
pub(super) fn violations(
|
||||
run: &Run,
|
||||
path: &Path,
|
||||
analysis: &Analysis,
|
||||
oracle: &Mentions,
|
||||
) -> Vec<Violation> {
|
||||
let ctx = LintContext::from_parse(
|
||||
&analysis.text,
|
||||
&analysis.tokens,
|
||||
&analysis.tree,
|
||||
&analysis.lines,
|
||||
Some(path.to_path_buf()),
|
||||
)
|
||||
.with_semantics(&analysis.semantics)
|
||||
.with_options(&run.options)
|
||||
.with_line_length(run.line_length)
|
||||
.with_tab_width(run.tab_width)
|
||||
.with_oracle(oracle);
|
||||
let (violations, used) = lint_with(&ctx, &run.rules, &run.waivers);
|
||||
run.used.borrow_mut().merge(&used);
|
||||
violations
|
||||
}
|
||||
|
||||
fn lint_finding(file: &str, lines: &LineIndex, violation: &Violation) -> Finding {
|
||||
let span = violation.span;
|
||||
let fix = violation.fix.as_ref().map_or(Value::Null, |fix| {
|
||||
let edits: Vec<Value> = fix
|
||||
.edits
|
||||
.iter()
|
||||
.map(|(range, content)| json!({"start": range.start, "end": range.end, "content": content}))
|
||||
.collect();
|
||||
json!({ "applicability": fix.applicability.as_str(), "edits": edits })
|
||||
});
|
||||
Finding {
|
||||
file: file.to_string(),
|
||||
rule: violation.rule.to_string(),
|
||||
severity: violation.severity.as_str(),
|
||||
message: violation.message.clone(),
|
||||
start: lines.line_col(span.start),
|
||||
end: lines.line_col(span.end),
|
||||
range: (span.start, span.end),
|
||||
fix,
|
||||
}
|
||||
}
|
||||
|
||||
/// Findings grouped by file, paged; the JSON is the CLI's array shape.
|
||||
fn render_findings(findings: &[Finding], args: &Args) -> Answer {
|
||||
let (shown, rest) =
|
||||
render::page(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = shown
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let line =
|
||||
format!("{}:{} {} {} [{}]", f.start.0, f.start.1, f.severity, f.message, f.rule);
|
||||
(f.file.clone(), line)
|
||||
})
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if findings.is_empty() {
|
||||
text = "no findings\n".to_string();
|
||||
}
|
||||
let listed: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|f| {
|
||||
json!({
|
||||
"filename": f.file, "rule": f.rule, "severity": f.severity, "message": f.message,
|
||||
"location": {"line": f.start.0, "column": f.start.1},
|
||||
"end_location": {"line": f.end.0, "column": f.end.1},
|
||||
"range": {"start": f.range.0, "end": f.range.1},
|
||||
"fix": f.fix,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Answer { text, structured: json!({ "diagnostics": listed, "total": findings.len() }) }
|
||||
}
|
||||
|
||||
/// How many files write each word, and the first of them — the whole-project
|
||||
/// form's answer to "does another file mention this", built once per call
|
||||
/// instead of walking every record per question.
|
||||
struct Census<'a> {
|
||||
words: HashMap<&'a str, (usize, FileId)>,
|
||||
}
|
||||
|
||||
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() {
|
||||
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;
|
||||
}
|
||||
}
|
||||
Census { words }
|
||||
}
|
||||
|
||||
fn outside(&self, name: &str, own: Option<FileId>) -> bool {
|
||||
match self.words.get(name) {
|
||||
Some(&(count, first)) => count > 1 || Some(first) != own,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project index answering the linter's cross-file questions — the
|
||||
/// language server's `IndexMentions`, with the census when one was built.
|
||||
pub(super) struct Mentions<'a> {
|
||||
index: &'a WorkspaceIndex,
|
||||
census: Option<&'a Census<'a>>,
|
||||
/// The linted file itself, subtracted from "elsewhere".
|
||||
own: Option<FileId>,
|
||||
}
|
||||
|
||||
impl<'a> Mentions<'a> {
|
||||
/// The oracle for one file, asking the index per question.
|
||||
pub(super) fn of_file(index: &'a WorkspaceIndex, own: Option<FileId>) -> Mentions<'a> {
|
||||
Mentions { index, census: None, own }
|
||||
}
|
||||
}
|
||||
|
||||
impl MentionOracle for Mentions<'_> {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
match self.census {
|
||||
Some(census) => census.outside(name, self.own),
|
||||
None => self.index.mentioned_outside(name, self.own),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ports and overridable parameters of a module declared exactly once.
|
||||
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
|
||||
let [unit] = self.index.units(name) else { return None };
|
||||
if !unit.kind.is_instantiable() {
|
||||
return None;
|
||||
}
|
||||
let mut interface = ModuleInterface::default();
|
||||
for (member, defs) in self.index.members_of(name) {
|
||||
match defs.first().map(|def| def.kind) {
|
||||
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
|
||||
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(interface)
|
||||
}
|
||||
|
||||
fn package_exports(&self, package: &str) -> Exports {
|
||||
PackageExports::exports(self.index, package)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! The refactorings that act at one position — `rename`, and the six the
|
||||
//! editor offers as code actions at a cursor (`expand_wildcard`,
|
||||
//! `convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`,
|
||||
//! `remove_port`) — plus what every edit tool shares: the `dry_run`
|
||||
//! argument, the whole-set read the engines are handed, and the step from a
|
||||
//! verified `RefactorEdit` to `apply::run`.
|
||||
//!
|
||||
//! Each engine gets **every indexed file**, read from disk at call time
|
||||
//! (`source::WholeSet`, M2's ruling for `references`: a use can resolve
|
||||
//! through a file that never spells its name, so no narrowing is sound).
|
||||
//! The texts read are the texts the write-freshness rule compares against.
|
||||
//! A file the index skipped (over 1 MiB, not UTF-8) is never edited around:
|
||||
//! when its bytes spell a name the edit changes, the edit is refused;
|
||||
//! otherwise it is named under `warnings:` (QA finding 2).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::RefactorEdit;
|
||||
|
||||
use super::select::{target, Target};
|
||||
use super::source::WholeSet;
|
||||
use super::{nav, Answer, Args, Param, Tool, Ty};
|
||||
use crate::apply::{self, Plan};
|
||||
use crate::project::{Analysis, Project};
|
||||
|
||||
/// `dry_run`, which every edit tool takes.
|
||||
pub(super) const DRY_RUN: Param = Param {
|
||||
name: "dry_run",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Return the unified diff and write nothing (default false).",
|
||||
};
|
||||
|
||||
const FILE: Param = Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file holding the position, relative to a root or absolute inside one.",
|
||||
};
|
||||
const LINE: Param = Param {
|
||||
name: "line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based line in `file`; alone it means the line's first non-blank character.",
|
||||
};
|
||||
const COL: Param = Param {
|
||||
name: "col",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based column in bytes on `line`.",
|
||||
};
|
||||
const NAME: Param = Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The name written at the position: with `line`, its occurrence on that line; without, its occurrence in `file`.",
|
||||
};
|
||||
|
||||
/// The position arguments of the six cursor refactorings, then `dry_run`.
|
||||
const AT: &[Param] = &[FILE, LINE, COL, NAME, DRY_RUN];
|
||||
|
||||
/// One engine that acts at a position.
|
||||
type Engine = fn(&[(PathBuf, String)], &Path, u32) -> Result<RefactorEdit, String>;
|
||||
|
||||
/// The names an engine acting at a position changes — what a skipped file
|
||||
/// must not spell.
|
||||
type Stake = fn(&Analysis, u32) -> Vec<String>;
|
||||
|
||||
pub const EXPAND_WILDCARD: Tool = Tool {
|
||||
name: "expand_wildcard",
|
||||
title: "Expand .* connections",
|
||||
description: "Replace one instantiation's `.*` with the named connections it binds, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a `bind` instance, a positional list, and a port list whose binding depends on `ifdef`s, with the reason. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: expand_wildcard,
|
||||
};
|
||||
|
||||
pub const CONVERT_PORTS: Tool = Tool {
|
||||
name: "convert_ports",
|
||||
title: "Convert ports to ANSI",
|
||||
description: "Rewrite a module's non-ANSI header (`module m(a, b); input a; …`) as an ANSI port list, verified before anything is written. Point at the module: `file`+`line` (+`col`, or the module `name`). Refuses a header it cannot convert exactly, with the reason. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: convert_ports,
|
||||
};
|
||||
|
||||
pub const ORGANIZE_IMPORTS: Tool = Tool {
|
||||
name: "organize_imports",
|
||||
title: "Organize imports",
|
||||
description: "Remove the unused `import` items of the scope at a position and sort the rest, verified before anything is written. Point into the scope with `file`+`line`. Refuses where it cannot judge (a macro or `include` in the scope, an unknown package), with the reason. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: organize_imports,
|
||||
};
|
||||
|
||||
pub const INLINE_MODULE: Tool = Tool {
|
||||
name: "inline_module",
|
||||
title: "Inline a module instance",
|
||||
description: "Replace one instantiation with the body of the module it instantiates, its connections substituted, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses what it cannot substitute exactly, with the reason. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: inline_module,
|
||||
};
|
||||
|
||||
pub const PROPAGATE_PORTS: Tool = Tool {
|
||||
name: "propagate_ports",
|
||||
title: "Connect missing ports",
|
||||
description: "Add a named connection for every port one instantiation leaves unconnected, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a positional or `.*` list, and an instance that already connects every port. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: propagate_ports,
|
||||
};
|
||||
|
||||
pub const REMOVE_PORT: Tool = Tool {
|
||||
name: "remove_port",
|
||||
title: "Remove a port",
|
||||
description: "Delete one module port and its connection from every instantiation in the project, verified before anything is written. Point at the port: `file`+`line` (+`col`, or the port `name`). Refuses a port the body still uses, a positional instantiation, and a deletion that would drop a comment. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: remove_port,
|
||||
};
|
||||
|
||||
pub const RENAME: Tool = Tool {
|
||||
name: "rename",
|
||||
title: "Rename a symbol",
|
||||
description: "Rename one declaration and every reference to it across the project, verified before anything is written. Select as for `definition`: `file`+`line`+`col`, `file`+`line`+`name`, `file`+`name`, or `name` (+`unit`). Refuses an invalid or clashing name and a use it cannot account for; a name already `new_name` is `unchanged`. A `.*` or `.name` connection that bound the renamed name is written out explicitly (listed in `warnings`).",
|
||||
params: &[
|
||||
Param { required: false, ..FILE },
|
||||
Param {
|
||||
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
|
||||
..LINE
|
||||
},
|
||||
COL,
|
||||
Param {
|
||||
description: "The name to rename: alone, looked up across the project; with `file`, its occurrence there; with `file` and `line`, its occurrence on that line.",
|
||||
..NAME
|
||||
},
|
||||
Param {
|
||||
name: "unit",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "With a bare `name`: the module, interface, package or class declaring it.",
|
||||
},
|
||||
Param {
|
||||
name: "new_name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The new name.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: true,
|
||||
handler: rename,
|
||||
};
|
||||
|
||||
fn expand_wildcard(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated)
|
||||
}
|
||||
|
||||
fn convert_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::convert_to_ansi, enclosing)
|
||||
}
|
||||
|
||||
fn organize_imports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
// Only the file's own `import` items change; nothing another file spells.
|
||||
at_cursor(project, args, vlog_refactor::organize_imports, |_, _| Vec::new())
|
||||
}
|
||||
|
||||
fn inline_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::inline_module, instantiated)
|
||||
}
|
||||
|
||||
fn propagate_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::propagate_ports, instantiated)
|
||||
}
|
||||
|
||||
fn remove_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let port_and_module = |analysis: &Analysis, offset: u32| {
|
||||
let mut names = name_at(analysis, offset);
|
||||
names.extend(instantiated(analysis, offset));
|
||||
names
|
||||
};
|
||||
at_cursor(project, args, vlog_refactor::remove_port, port_and_module)
|
||||
}
|
||||
|
||||
/// The declared name at a position.
|
||||
fn name_at(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::rename_name_at(&analysis.semantics, offset).into_iter().collect()
|
||||
}
|
||||
|
||||
/// The module an instantiation at a position names, or whose port it is on.
|
||||
fn instantiated(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::port_action_modules_in(&analysis.tree, offset)
|
||||
}
|
||||
|
||||
/// The module whose declaration covers a position.
|
||||
pub(super) fn enclosing(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::enclosing_module(&analysis.text, offset).into_iter().collect()
|
||||
}
|
||||
|
||||
/// Run `engine` at the position the arguments name, over the whole set.
|
||||
fn at_cursor(
|
||||
project: &mut Project,
|
||||
args: &Args,
|
||||
engine: Engine,
|
||||
stake: Stake,
|
||||
) -> Result<Answer, String> {
|
||||
let (path, offset) = cursor(project, args)?;
|
||||
let names = stake(&*project.analysis(&path)?, offset);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = engine(&set.files, &path, offset)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
|
||||
/// The position a cursor refactoring acts at: `file` + `line` alone is the
|
||||
/// line's first non-blank byte; anything else is `definition`'s selector,
|
||||
/// which must name a file.
|
||||
fn cursor(project: &mut Project, args: &Args) -> Result<(PathBuf, u32), String> {
|
||||
if let (Some(file), Some(line), None, None) =
|
||||
(args.str("file"), args.int("line"), args.int("col"), args.str("name"))
|
||||
{
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let line = u32::try_from(line).unwrap_or(u32::MAX);
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
let count = analysis.lines.line_count();
|
||||
return Err(format!("line {line} is past the end ({count} lines) (in `{file}`)"));
|
||||
};
|
||||
let text = analysis.line_text(line);
|
||||
let blank = text.len() - text.trim_start().len();
|
||||
return Ok((path, range.start + blank as u32));
|
||||
}
|
||||
match target(project, args)? {
|
||||
Target::At { path, offset, .. } => Ok((path, offset)),
|
||||
Target::Named { .. } => Err("give the `file` the position is in.".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole set an engine is handed — refused when a file the index
|
||||
/// skipped spells one of `names`, since the edit could not reach it.
|
||||
pub(super) fn whole_set(
|
||||
project: &Project,
|
||||
extra: Option<&Path>,
|
||||
names: &[String],
|
||||
) -> Result<WholeSet, String> {
|
||||
let set = WholeSet::read(project, extra);
|
||||
if let Some((path, why, name)) = set.mentioning(names) {
|
||||
return Err(format!(
|
||||
"`{}` (skipped: {why}) may reference `{name}`; lucisv-mcp will not edit around a file it cannot index; nothing written.",
|
||||
project.relative(path)
|
||||
));
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// A verified edit over the set's texts, diffed or written; the files the
|
||||
/// set left out are named under `warnings:`.
|
||||
pub(super) fn finish(
|
||||
project: &Project,
|
||||
edit: RefactorEdit,
|
||||
set: &WholeSet,
|
||||
args: &Args,
|
||||
) -> Result<Answer, String> {
|
||||
let mut plan = Plan::from_refactor(edit, &set.files)?;
|
||||
plan.warnings.extend(set.warning(project));
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
}
|
||||
|
||||
fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let new_name = args.str("new_name").unwrap_or_default();
|
||||
let (path, offset) = match target(project, args)? {
|
||||
Target::At { path, offset, .. } => (path, offset),
|
||||
Target::Named { name, unit } => nav::declaration_position(project, &name, unit.as_deref())?,
|
||||
};
|
||||
let names = name_at(&*project.analysis(&path)?, offset);
|
||||
// Already renamed: a second identical call is a no-op, not a refusal.
|
||||
if names.first().map(String::as_str) == Some(new_name) {
|
||||
return apply::run(project, Plan::default(), args.flag("dry_run", false));
|
||||
}
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = vlog_refactor::rename(&set.files, &path, offset, new_name)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//! `format` and `fix_lint`: the CLI's `lucisv format` and `lucisv check
|
||||
//! --fix`, per file, through the one write path (`apply.rs`).
|
||||
//!
|
||||
//! `format` is `format_source` (or `format_range` for `lines`) under the
|
||||
//! `lucisv.toml` governing each file — the formatter's own safety net decides,
|
||||
//! and a refusal names the file and writes nothing anywhere. `fix_lint` runs
|
||||
//! the lint pass `diagnostics` runs (the same config ladder, waivers and
|
||||
//! cross-file oracle), applies the **safe** fixes whose edits stay out of
|
||||
//! every `// lucisv: off` fence — the CLI's `--fix` filter — until the file
|
||||
//! stops changing, and refuses a result that parses worse than the input.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::panic::{catch_unwind, AssertUnwindSafe};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
use vlog_linter::{apply_fixes, Fix, Violation};
|
||||
|
||||
use super::diagnostics::{violations, Mentions, Runs};
|
||||
use super::edit::DRY_RUN;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::apply::{self, Change, Plan};
|
||||
use crate::project::{Analysis, Project};
|
||||
|
||||
/// How many fix-then-relint rounds one file gets — the CLI's cap, for the
|
||||
/// CLI's reason: two overlapping fixes land in successive rounds.
|
||||
const MAX_FIX_ROUNDS: usize = 10;
|
||||
|
||||
const FILE: Param = Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "One file, relative to a root or absolute inside one.",
|
||||
};
|
||||
const FILES: Param = Param {
|
||||
name: "files",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Several files, comma-separated, instead of `file`.",
|
||||
};
|
||||
|
||||
pub const FORMAT: Tool = Tool {
|
||||
name: "format",
|
||||
title: "Format files",
|
||||
description: "Format `file` (or the comma-separated `files`) as `lucisv format` does, under each file's lucisv.toml; `lines` (`12-40,55`, one file only) formats just the constructs meeting those lines. The formatter verifies its own output: a file it will not format safely refuses the whole call, naming it. An already formatted file is `unchanged`. `dry_run` returns the diff.",
|
||||
params: &[
|
||||
FILE,
|
||||
FILES,
|
||||
Param {
|
||||
name: "lines",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "1-based line ranges such as `12-40,55`; only with a single file.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: format,
|
||||
};
|
||||
|
||||
pub const FIX_LINT: Tool = Tool {
|
||||
name: "fix_lint",
|
||||
title: "Apply safe lint fixes",
|
||||
description: "Apply the safe automatic fixes of the lint findings in `file` (or the comma-separated `files`), as `lucisv check --fix` does: the project's [lint] config and waivers, never inside a `// lucisv: off` fence, never an unsafe fix. Reports which rules were fixed and how many findings remain (`diagnostics` lists them). `rules` narrows the run like --select. `dry_run` returns the diff.",
|
||||
params: &[
|
||||
FILE,
|
||||
FILES,
|
||||
Param {
|
||||
name: "rules",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Comma-separated rule names or severities to fix instead of the configured set.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: fix_lint,
|
||||
};
|
||||
|
||||
/// The files a call names, resolved, each once, in the order given.
|
||||
fn named_files(project: &Project, args: &Args) -> Result<Vec<PathBuf>, String> {
|
||||
let given: Vec<&str> = match (args.str("file"), args.str("files")) {
|
||||
(Some(_), Some(_)) => return Err("give `file` or `files`, not both.".into()),
|
||||
(Some(file), None) => vec![file],
|
||||
(None, Some(files)) => files.split(',').map(str::trim).filter(|f| !f.is_empty()).collect(),
|
||||
(None, None) => return Err("give a `file`, or comma-separated `files`.".into()),
|
||||
};
|
||||
if given.is_empty() {
|
||||
return Err("`files` names no file.".into());
|
||||
}
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for file in given {
|
||||
let path = project.resolve(file)?;
|
||||
if !out.contains(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A file's text as it is on disk now.
|
||||
fn read(project: &Project, path: &Path) -> Result<String, String> {
|
||||
std::fs::read_to_string(path)
|
||||
.map_err(|e| format!("cannot read `{}`: {e}", project.relative(path)))
|
||||
}
|
||||
|
||||
fn format(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let paths = named_files(project, args)?;
|
||||
let lines = match args.str("lines") {
|
||||
None => None,
|
||||
Some(_) if paths.len() > 1 => return Err("`lines` needs a single file.".into()),
|
||||
Some(spec) => Some(LineRanges::parse(spec).map_err(|e| format!("`lines`: {e}"))?),
|
||||
};
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut plan = Plan::default();
|
||||
for path in paths {
|
||||
let before = read(project, &path)?;
|
||||
let config = formatter_config(&discovery.for_file(&path)?);
|
||||
let after = formatted(&before, &config, lines.as_ref()).map_err(|why| {
|
||||
format!("`{}` was not formatted: {why}; nothing written.", project.relative(&path))
|
||||
})?;
|
||||
plan.changes.push(Change { path, before, after, created: false });
|
||||
}
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
}
|
||||
|
||||
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
|
||||
/// `Options::config_with` with no command-line flags.
|
||||
fn formatter_config(file: &FileConfig) -> Config {
|
||||
let mut config = Config::default();
|
||||
if let Some(width) = file.line_length {
|
||||
config.max_width = width;
|
||||
}
|
||||
if let Some(indent) = file.indent {
|
||||
config.indent_width = indent;
|
||||
}
|
||||
if let Some(on) = file.format_uvm_utils_indent {
|
||||
config.uvm_utils_indent = on;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// Format one text; a formatter panic is an error like any other, never the
|
||||
/// end of the server.
|
||||
fn formatted(text: &str, config: &Config, lines: Option<&LineRanges>) -> Result<String, String> {
|
||||
let run = catch_unwind(AssertUnwindSafe(|| match lines {
|
||||
Some(lines) => format_range(text, config, lines),
|
||||
None => format_source(text, config),
|
||||
}));
|
||||
match run {
|
||||
Ok(Ok(out)) => Ok(out),
|
||||
Ok(Err(e)) => Err(e.to_string()),
|
||||
Err(_) => Err("the formatter panicked".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn fix_lint(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let paths = named_files(project, args)?;
|
||||
let selected: Option<Vec<String>> = args.str("rules").map(|rules| {
|
||||
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
|
||||
});
|
||||
let mut runs = Runs::new(selected);
|
||||
let mut plan = Plan::default();
|
||||
let mut fixed: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
let mut left = 0;
|
||||
for path in paths {
|
||||
let before = read(project, &path)?;
|
||||
let outcome = fix_file(project, &mut runs, &path, &before)?;
|
||||
for (rule, count) in outcome.fixed {
|
||||
*fixed.entry(rule).or_default() += count;
|
||||
}
|
||||
left += outcome.left;
|
||||
plan.changes.push(Change { path, before, after: outcome.text, created: false });
|
||||
}
|
||||
plan.note = Some(fixed_note(&fixed, left));
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
}
|
||||
|
||||
/// What fixing one file came to.
|
||||
struct Fixed {
|
||||
text: String,
|
||||
/// Per rule, how many of its findings the fixes removed.
|
||||
fixed: BTreeMap<&'static str, usize>,
|
||||
/// Findings still reported after the last round.
|
||||
left: usize,
|
||||
}
|
||||
|
||||
/// Fix, re-lint, repeat until nothing more applies; refuse a result whose
|
||||
/// tolerant parse reports more errors than the input's did.
|
||||
fn fix_file(
|
||||
project: &Project,
|
||||
runs: &mut Runs,
|
||||
path: &Path,
|
||||
before: &str,
|
||||
) -> Result<Fixed, String> {
|
||||
let run = runs.for_file(path)?;
|
||||
let oracle = Mentions::of_file(project.index(), project.index().file_id(path));
|
||||
let first = Analysis::of(before.to_string());
|
||||
let errors_before = first.diagnostics.len();
|
||||
let found = violations(&run, path, &first, &oracle);
|
||||
let mut remaining = found.clone();
|
||||
let mut text = before.to_string();
|
||||
let mut errors_after = errors_before;
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round = apply_fixes(&text, &outside_fences(&text, &remaining), false);
|
||||
if round.applied == 0 {
|
||||
break;
|
||||
}
|
||||
text = round.output;
|
||||
let analysis = Analysis::of(text.clone());
|
||||
errors_after = analysis.diagnostics.len();
|
||||
remaining = violations(&run, path, &analysis, &oracle);
|
||||
}
|
||||
if errors_after > errors_before {
|
||||
return Err(format!(
|
||||
"fixing `{}` would leave it with {errors_after} parse errors where it had {errors_before}; nothing written.",
|
||||
project.relative(path)
|
||||
));
|
||||
}
|
||||
let fixed = removed_per_rule(&found, &remaining);
|
||||
Ok(Fixed { text, fixed, left: remaining.len() })
|
||||
}
|
||||
|
||||
/// The findings whose fix may be applied: those whose every edit stays out
|
||||
/// of the fenced regions — the CLI's `fixable_outside_fences`, over
|
||||
/// `fence::protected_regions`, the one answer to which bytes are fenced.
|
||||
fn outside_fences(text: &str, found: &[Violation]) -> Vec<Violation> {
|
||||
let regions = fence::protected_regions(text);
|
||||
found
|
||||
.iter()
|
||||
.filter(|v| v.fix.as_ref().is_some_and(|fix| !touches_fence(fix, ®ions)))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
fix.edits
|
||||
.iter()
|
||||
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
|
||||
}
|
||||
|
||||
/// Per rule, how many fewer findings the fixed text has.
|
||||
fn removed_per_rule(before: &[Violation], after: &[Violation]) -> BTreeMap<&'static str, usize> {
|
||||
let count = |found: &[Violation]| {
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
found.iter().for_each(|v| *counts.entry(v.rule).or_default() += 1);
|
||||
counts
|
||||
};
|
||||
let after = count(after);
|
||||
count(before)
|
||||
.into_iter()
|
||||
.filter_map(|(rule, n)| {
|
||||
let gone = n.saturating_sub(after.get(rule).copied().unwrap_or(0));
|
||||
(gone > 0).then_some((rule, gone))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `fixed: rule ×2, rule ×1; 3 findings left`.
|
||||
fn fixed_note(fixed: &BTreeMap<&'static str, usize>, left: usize) -> String {
|
||||
let listed: Vec<String> = fixed.iter().map(|(rule, n)| format!("{rule} ×{n}")).collect();
|
||||
let fixed = if listed.is_empty() { "nothing".to_string() } else { listed.join(", ") };
|
||||
let plural = if left == 1 { "" } else { "s" };
|
||||
format!("fixed: {fixed}; {left} finding{plural} left")
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
//! `hierarchy`: the instance tree, down from a module (or from every
|
||||
//! top-level module) or up to the modules that instantiate it — read off the
|
||||
//! index's instantiation edges, textual rather than elaborated, exactly the
|
||||
//! census the editor's hierarchy view and call hierarchy draw from.
|
||||
//!
|
||||
//! The walk is cut three ways: by `depth`, by a module already on the path
|
||||
//! (a module that instantiates itself, through `generate` or otherwise, ends
|
||||
//! its branch marked `recursive`), and by [`NODE_CAP`]. A module declared
|
||||
//! more than once is not expanded — which declaration an instance means is
|
||||
//! the elaborator's choice, not ours — and says how many there are.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{
|
||||
Def, FileId, InstanceOccurrence, InstantiationEdge, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use super::source::{self, Texts};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
/// The deepest a walk may go, whatever `depth` asks.
|
||||
const MAX_DEPTH: usize = 20;
|
||||
|
||||
/// The longest overrides text a line shows; the JSON carries all of it.
|
||||
const OVERRIDES_CAP: usize = 200;
|
||||
|
||||
/// The most nodes one walk collects before it stops.
|
||||
const NODE_CAP: usize = 50_000;
|
||||
|
||||
pub const HIERARCHY: Tool = Tool {
|
||||
name: "hierarchy",
|
||||
title: "Instance hierarchy",
|
||||
description: "The instance tree as indented `instance : module #(overrides)` lines, down from `root` (default: every top-level module), or with `direction: up` every `parent.instance` that instantiates `root`, with file:line. Textual, not elaborated: `generate` and `ifdef` branches all appear. Prefer it over reading files to find who instantiates what.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "root",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The module to start from; required for `up` (default for `down`: every module nothing instantiates).",
|
||||
},
|
||||
Param {
|
||||
name: "direction",
|
||||
ty: Ty::Enum(&["down", "up"]),
|
||||
required: false,
|
||||
description: "`down` lists what `root` instantiates (default); `up` lists what instantiates it.",
|
||||
},
|
||||
Param {
|
||||
name: "depth",
|
||||
ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 },
|
||||
required: false,
|
||||
description: "Levels to walk (default 3, at most 20).",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most lines to return (default 200).",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Lines to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: hierarchy,
|
||||
};
|
||||
|
||||
/// One instance under an owner, as the index records it.
|
||||
#[derive(Clone)]
|
||||
struct Child {
|
||||
instance: String,
|
||||
module: String,
|
||||
file: FileId,
|
||||
/// The instantiated module's name at the site.
|
||||
site: TextRange,
|
||||
/// The instance's own name.
|
||||
name: TextRange,
|
||||
/// Where the statement's first instance name starts: the `#(...)`
|
||||
/// belongs to the whole statement and ends before it.
|
||||
first: u32,
|
||||
}
|
||||
|
||||
impl Child {
|
||||
/// One instance of an edge to `module`.
|
||||
fn of(module: &str, edge: &InstantiationEdge, occurrence: &InstanceOccurrence) -> Child {
|
||||
let first =
|
||||
edge.instances.first().map_or(occurrence.name_span.start, |i| i.name_span.start);
|
||||
Child {
|
||||
instance: occurrence.name.clone(),
|
||||
module: module.to_string(),
|
||||
file: edge.file,
|
||||
site: edge.site_span,
|
||||
name: occurrence.name_span,
|
||||
first,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One line of the answer. A root line has no instance.
|
||||
struct Node {
|
||||
depth: usize,
|
||||
/// Down: the instance; up: the instance of the line above it.
|
||||
instance: Option<Child>,
|
||||
/// Down: the instantiated module; up: the instantiating one; root: itself.
|
||||
module: String,
|
||||
root: Option<Def>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
/// A walk in progress: the edges by owner, what it collected, and the path
|
||||
/// of modules above the current node.
|
||||
struct Walk<'a> {
|
||||
index: &'a WorkspaceIndex,
|
||||
below: HashMap<(FileId, u32), Vec<Child>>,
|
||||
max_depth: usize,
|
||||
nodes: Vec<Node>,
|
||||
path: Vec<String>,
|
||||
}
|
||||
|
||||
fn hierarchy(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let up = args.str("direction") == Some("up");
|
||||
let root = args.str("root").filter(|root| !root.is_empty());
|
||||
if up && root.is_none() {
|
||||
return Err("`direction: up` needs a `root`.".into());
|
||||
}
|
||||
if let Some(root) = root {
|
||||
if modules_named(project.index(), root).is_empty() {
|
||||
project.ensure_walked_for_miss();
|
||||
}
|
||||
if modules_named(project.index(), root).is_empty() {
|
||||
return Err(format!("no module or interface `{root}` is indexed."));
|
||||
}
|
||||
}
|
||||
let max_depth = args.count("depth", 3);
|
||||
let index = project.index();
|
||||
let mut walk = Walk::new(index, max_depth, !up);
|
||||
let roots: Vec<(String, Def)> = match root {
|
||||
Some(root) => {
|
||||
modules_named(index, root).into_iter().map(|d| (root.to_string(), d)).collect()
|
||||
}
|
||||
None => top_modules(index),
|
||||
};
|
||||
for (name, def) in roots {
|
||||
walk.root(name, def, up);
|
||||
}
|
||||
Ok(render(project, walk.nodes, up, args))
|
||||
}
|
||||
|
||||
/// Every instantiable declaration of `name`.
|
||||
fn modules_named(index: &WorkspaceIndex, name: &str) -> Vec<Def> {
|
||||
index.units(name).iter().filter(|def| def.kind.is_instantiable()).cloned().collect()
|
||||
}
|
||||
|
||||
/// Every module nothing instantiates, in name order.
|
||||
fn top_modules(index: &WorkspaceIndex) -> Vec<(String, Def)> {
|
||||
index
|
||||
.instantiable_units()
|
||||
.filter(|(_, def)| def.kind == SymbolKind::Module)
|
||||
.filter(|(name, _)| index.instantiations_of(name).is_empty())
|
||||
.map(|(name, def)| (name.to_string(), def.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl<'a> Walk<'a> {
|
||||
/// A walk over `index`; the owner table is built only for `down`.
|
||||
fn new(index: &'a WorkspaceIndex, max_depth: usize, down: bool) -> Walk<'a> {
|
||||
let mut below: HashMap<(FileId, u32), Vec<Child>> = HashMap::new();
|
||||
for (module, edges) in index.instantiations().filter(|_| down) {
|
||||
for edge in edges {
|
||||
let owner = (edge.file, edge.owner.name_span.start);
|
||||
let children =
|
||||
edge.instances.iter().map(|occurrence| Child::of(module, edge, occurrence));
|
||||
below.entry(owner).or_default().extend(children);
|
||||
}
|
||||
}
|
||||
for children in below.values_mut() {
|
||||
children.sort_by_key(|child| child.name.start);
|
||||
}
|
||||
Walk { index, below, max_depth, nodes: Vec::new(), path: Vec::new() }
|
||||
}
|
||||
|
||||
fn full(&self) -> bool {
|
||||
self.nodes.len() >= NODE_CAP
|
||||
}
|
||||
|
||||
/// One root line and its tree.
|
||||
fn root(&mut self, name: String, def: Def, up: bool) {
|
||||
if self.full() {
|
||||
return;
|
||||
}
|
||||
self.path = vec![name.clone()];
|
||||
let line = Node {
|
||||
depth: 0,
|
||||
instance: None,
|
||||
module: name.clone(),
|
||||
root: Some(def.clone()),
|
||||
note: None,
|
||||
};
|
||||
self.nodes.push(line);
|
||||
if up {
|
||||
self.up(&name, 1);
|
||||
} else {
|
||||
self.down(&def, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// The instances `def` declares, and theirs, to `max_depth`.
|
||||
fn down(&mut self, def: &Def, depth: usize) {
|
||||
let children =
|
||||
self.below.get(&(def.file, def.name_span.start)).cloned().unwrap_or_default();
|
||||
for child in children {
|
||||
if self.full() {
|
||||
return;
|
||||
}
|
||||
let declared = modules_named(self.index, &child.module);
|
||||
let recursive = self.path.contains(&child.module);
|
||||
let note = match declared.len() {
|
||||
_ if recursive => Some("recursive".to_string()),
|
||||
0 => Some("not indexed".to_string()),
|
||||
1 => None,
|
||||
n => Some(format!("declared {n} times")),
|
||||
};
|
||||
let expand = note.is_none() && depth < self.max_depth;
|
||||
let module = child.module.clone();
|
||||
self.nodes.push(Node {
|
||||
depth,
|
||||
instance: Some(child),
|
||||
module: module.clone(),
|
||||
root: None,
|
||||
note,
|
||||
});
|
||||
if let (true, [only]) = (expand, declared.as_slice()) {
|
||||
self.path.push(module);
|
||||
self.down(only, depth + 1);
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every instance of `module`, then the instances of their owners.
|
||||
fn up(&mut self, module: &str, depth: usize) {
|
||||
let index = self.index;
|
||||
for edge in index.instantiations_of(module) {
|
||||
for occurrence in &edge.instances {
|
||||
if self.full() {
|
||||
return;
|
||||
}
|
||||
let parent = edge.owner.name.clone();
|
||||
let recursive = self.path.contains(&parent);
|
||||
let child = Child::of(module, edge, occurrence);
|
||||
let note = recursive.then(|| "recursive".to_string());
|
||||
self.nodes.push(Node {
|
||||
depth,
|
||||
instance: Some(child),
|
||||
module: parent.clone(),
|
||||
root: None,
|
||||
note,
|
||||
});
|
||||
if !recursive && depth < self.max_depth {
|
||||
self.path.push(parent.clone());
|
||||
self.up(&parent, depth + 1);
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The collected nodes, paged, as indented lines and as a flat JSON list.
|
||||
fn render(project: &Project, nodes: Vec<Node>, up: bool, args: &Args) -> Answer {
|
||||
let (shown, rest) =
|
||||
render::page(&nodes, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let mut texts = Texts::default();
|
||||
let mut text = String::new();
|
||||
let mut listed: Vec<Value> = Vec::new();
|
||||
for node in shown {
|
||||
let line = Line::of(project, &mut texts, node);
|
||||
text.push_str(&" ".repeat(node.depth));
|
||||
text.push_str(&line.text(node, up));
|
||||
text.push('\n');
|
||||
listed.push(line.json(node, up));
|
||||
}
|
||||
render::more(&mut text, rest);
|
||||
if nodes.len() >= NODE_CAP {
|
||||
text.push_str(&format!("tree cut at {NODE_CAP} nodes; lower `depth` or pick a `root`\n"));
|
||||
}
|
||||
if nodes.is_empty() {
|
||||
text = "no modules\n".to_string();
|
||||
}
|
||||
let direction = if up { "up" } else { "down" };
|
||||
let structured = json!({
|
||||
"direction": direction, "nodes": listed, "total": nodes.len(),
|
||||
"cut": nodes.len() >= NODE_CAP,
|
||||
});
|
||||
Answer { text, structured }
|
||||
}
|
||||
|
||||
/// What one node's line needs from its file: where it is and the overrides.
|
||||
struct Line {
|
||||
file: String,
|
||||
line: u32,
|
||||
overrides: Option<String>,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
fn of(project: &Project, texts: &mut Texts, node: &Node) -> Line {
|
||||
let index = project.index();
|
||||
if let Some(def) = &node.root {
|
||||
let path = index.path(def.file).unwrap_or(Path::new(""));
|
||||
return Line { file: project.relative(path), line: def.lines.name, overrides: None };
|
||||
}
|
||||
let Some(child) = &node.instance else {
|
||||
return Line { file: String::new(), line: 0, overrides: None };
|
||||
};
|
||||
let path = index.path(child.file).unwrap_or(Path::new(""));
|
||||
let file = project.relative(path);
|
||||
let Some((text, lines)) = texts.get(path) else {
|
||||
return Line { file, line: 0, overrides: None };
|
||||
};
|
||||
let line = lines.line_col(child.name.start).0;
|
||||
Line { file, line, overrides: overrides(text, child) }
|
||||
}
|
||||
|
||||
fn text(&self, node: &Node, up: bool) -> String {
|
||||
let mut out = match (&node.instance, up) {
|
||||
(None, _) => format!("{} {}:{}", node.module, self.file, self.line),
|
||||
(Some(child), false) => format!("{} : {}", child.instance, child.module),
|
||||
(Some(child), true) => format!("{}.{}", node.module, child.instance),
|
||||
};
|
||||
if let Some(overrides) = &self.overrides {
|
||||
out.push(' ');
|
||||
out.push_str(&source::capped(overrides, OVERRIDES_CAP));
|
||||
}
|
||||
if up && node.instance.is_some() {
|
||||
out.push_str(&format!(" {}:{}", self.file, self.line));
|
||||
}
|
||||
if let Some(note) = &node.note {
|
||||
out.push_str(&format!(" ({note})"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn json(&self, node: &Node, up: bool) -> Value {
|
||||
let child = node.instance.as_ref();
|
||||
json!({
|
||||
"depth": node.depth,
|
||||
"instance": child.map(|child| child.instance.clone()),
|
||||
"module": child.map_or(node.module.clone(), |child| child.module.clone()),
|
||||
"parent": child.filter(|_| up).map(|_| node.module.clone()),
|
||||
"file": self.file,
|
||||
"line": self.line,
|
||||
"overrides": self.overrides,
|
||||
"note": node.note,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The `#(...)` written between the module name and the instance name,
|
||||
/// comments dropped, on one line — when the file still spells the module
|
||||
/// name at the site.
|
||||
fn overrides(text: &str, child: &Child) -> Option<String> {
|
||||
if text.get(child.site.as_range()) != Some(child.module.as_str()) {
|
||||
return None;
|
||||
}
|
||||
let between = text.get(child.site.end as usize..child.first as usize)?;
|
||||
let written = source::without_comments(between);
|
||||
let written = written.trim();
|
||||
written.starts_with('#').then(|| render::one_line(written))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn child(text: &str, module: &str, instance: &str) -> Child {
|
||||
let site = text.find(module).unwrap() as u32;
|
||||
let name = text.find(instance).unwrap() as u32;
|
||||
Child {
|
||||
instance: instance.to_string(),
|
||||
module: module.to_string(),
|
||||
file: FileId(0),
|
||||
site: TextRange::new(site, site + module.len() as u32),
|
||||
name: TextRange::new(name, name + instance.len() as u32),
|
||||
first: text.find(" u_").unwrap() as u32 + 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overrides_are_sliced_between_the_module_and_the_instance_name() {
|
||||
let text = " fifo #( // sizes\n .Width (8),\n .Depth(2)\n ) u_fifo (.*);";
|
||||
let fifo = child(text, "fifo", "u_fifo");
|
||||
assert_eq!(overrides(text, &fifo).as_deref(), Some("#( .Width (8), .Depth(2) )"));
|
||||
let plain = " fifo u_plain (.*);";
|
||||
assert_eq!(overrides(plain, &child(plain, "fifo", "u_plain")), None);
|
||||
let two = " fifo #(.W(2)) u_a (), u_b ();";
|
||||
assert_eq!(overrides(two, &child(two, "fifo", "u_b")).as_deref(), Some("#(.W(2))"));
|
||||
let mut stale = fifo.clone();
|
||||
stale.module = "other".into();
|
||||
assert_eq!(overrides(text, &stale), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! `unit_interface`: what a unit offers the code that uses it — a module's
|
||||
//! or interface's parameters, ports and instantiation template (plus an
|
||||
//! interface's modports), a package's or class's exported members — without
|
||||
//! the agent reading the file that declares it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_refactor::{instantiation_plan, InstantiationPlan, Layout};
|
||||
use vlog_semantic::{Def, ScopeId, Semantics, Symbol, SymbolKind};
|
||||
|
||||
use super::read_item::child_items;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
pub const UNIT_INTERFACE: Tool = Tool {
|
||||
name: "unit_interface",
|
||||
title: "Unit interface",
|
||||
description: "The interface of one unit by name: a module's or interface's parameters with defaults, ports in declaration order (direction, type, range) and a ready-to-paste instantiation; an interface's modports; a package's or class's members. Prefer it over reading the declaring file. Refuses a name declared in several files unless `file` picks one.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The unit's name; a class inside a package may be written `pkg::cls`.",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The declaring file, when the name is declared more than once.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: unit_interface,
|
||||
};
|
||||
|
||||
/// A unit found in the index: where it is, and what it is.
|
||||
struct Found {
|
||||
path: PathBuf,
|
||||
def: Def,
|
||||
}
|
||||
|
||||
fn unit_interface(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").unwrap_or("");
|
||||
let mut found = candidates(project, name, args.str("file"))?;
|
||||
if found.is_empty() && project.ensure_walked_for_miss() {
|
||||
found = candidates(project, name, args.str("file"))?;
|
||||
}
|
||||
let found = pick(project, found, name, args.str("file"))?;
|
||||
let analysis = project.analysis(&found.path)?;
|
||||
let file = project.relative(&found.path);
|
||||
let kind = super::read::unit_kind(project, &found.path, &found.def);
|
||||
let head = format!("{kind} {name} {file}:{}\n", found.def.lines.name);
|
||||
let short = name.rsplit("::").next().unwrap_or(name);
|
||||
match found.def.kind {
|
||||
SymbolKind::Module | SymbolKind::Interface => {
|
||||
instantiable(&analysis, &found, short, head, &file).map(|mut answer| {
|
||||
answer.structured["kind"] = Value::from(kind);
|
||||
answer
|
||||
})
|
||||
}
|
||||
_ => Ok(members(project, &analysis, &found, short, head, &file)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every indexed declaration of `name` (in `file`, when given). `Err` only
|
||||
/// when `file` itself is refused.
|
||||
fn candidates(project: &Project, name: &str, file: Option<&str>) -> Result<Vec<Found>, String> {
|
||||
let index = project.index();
|
||||
let unit_kinds =
|
||||
[SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class];
|
||||
let mut defs: Vec<Def> = match name.split_once("::") {
|
||||
Some((package, class)) => index.member(package, class).to_vec(),
|
||||
None => index.units(name).to_vec(),
|
||||
};
|
||||
defs.retain(|def| unit_kinds.contains(&def.kind));
|
||||
let mut found: Vec<Found> = defs
|
||||
.into_iter()
|
||||
.filter_map(|def| Some(Found { path: index.path(def.file)?.to_path_buf(), def }))
|
||||
.collect();
|
||||
if let Some(file) = file {
|
||||
let path = project.resolve(file)?;
|
||||
found.retain(|f| f.path == path);
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// The one declaration among `found`, or a refusal that says why there is
|
||||
/// not exactly one.
|
||||
fn pick(
|
||||
project: &Project,
|
||||
mut found: Vec<Found>,
|
||||
name: &str,
|
||||
file: Option<&str>,
|
||||
) -> Result<Found, String> {
|
||||
match found.len() {
|
||||
0 => Err(format!(
|
||||
"no module, interface, package or class named `{name}` is indexed{}; search_symbols finds near names.",
|
||||
file.map_or(String::new(), |f| format!(" in `{f}`"))
|
||||
)),
|
||||
1 => Ok(found.remove(0)),
|
||||
_ => {
|
||||
let sites: Vec<String> = found
|
||||
.iter()
|
||||
.map(|f| format!("{}:{}", project.relative(&f.path), f.def.lines.name))
|
||||
.collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); pass `file` to pick one.",
|
||||
sites.len(),
|
||||
sites.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A module's or interface's parameters, ports, modports and template.
|
||||
fn instantiable(
|
||||
analysis: &Analysis,
|
||||
found: &Found,
|
||||
name: &str,
|
||||
head: String,
|
||||
file: &str,
|
||||
) -> Result<Answer, String> {
|
||||
let plan = instantiation_plan(name, &analysis.text, None)?;
|
||||
let scope = unit_symbol(&analysis.semantics, found, name).and_then(|s| s.child_scope);
|
||||
let ports = port_rows(&plan, analysis, scope);
|
||||
let modports = match (found.def.kind, scope) {
|
||||
(SymbolKind::Interface, Some(scope)) => modports_of(analysis, scope),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let template = plan.render(&Layout::default());
|
||||
let text = interface_text(head, &plan, &ports, &modports, &template);
|
||||
let structured = json!({
|
||||
"name": name,
|
||||
"kind": render::kind(found.def.kind),
|
||||
"file": file,
|
||||
"line": found.def.lines.name,
|
||||
"parameters": plan.params.iter().map(|p| json!({ "name": p.name, "default": p.default })).collect::<Vec<_>>(),
|
||||
"ports": ports.iter().map(PortRow::to_json).collect::<Vec<_>>(),
|
||||
"modports": modports,
|
||||
"template": template,
|
||||
"warnings": plan.warnings,
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// An interface's modports, each as its declaration reads on one line.
|
||||
fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec<String> {
|
||||
analysis
|
||||
.semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.filter(|s| s.scope == scope && s.kind == SymbolKind::Modport)
|
||||
.map(|s| render::one_line(analysis.slice(s.decl_span.start, s.decl_span.end)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text answer: the head line, then each non-empty section.
|
||||
fn interface_text(
|
||||
mut text: String,
|
||||
plan: &InstantiationPlan,
|
||||
ports: &[PortRow],
|
||||
modports: &[String],
|
||||
template: &str,
|
||||
) -> String {
|
||||
if !plan.params.is_empty() {
|
||||
text.push_str("parameters:\n");
|
||||
let rows: Vec<Vec<String>> =
|
||||
plan.params.iter().map(|p| vec![p.name.clone(), default_cell(&p.default)]).collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
}
|
||||
if !ports.is_empty() {
|
||||
text.push_str("ports:\n");
|
||||
let rows: Vec<Vec<String>> = ports
|
||||
.iter()
|
||||
.map(|p| vec![p.dir.clone(), p.written_type(), p.name_with_unpacked()])
|
||||
.collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
}
|
||||
if !modports.is_empty() {
|
||||
text.push_str("modports:\n");
|
||||
for modport in modports {
|
||||
text.push_str(&format!(" {modport}\n"));
|
||||
}
|
||||
}
|
||||
for warning in &plan.warnings {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
text.push_str("template:\n");
|
||||
text.push_str(template);
|
||||
if !template.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn default_cell(default: &str) -> String {
|
||||
if default.is_empty() {
|
||||
"(no default)".to_string()
|
||||
} else {
|
||||
format!("= {}", render::one_line(default))
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit's own symbol in the file's analysis: the declaration at the
|
||||
/// indexed name, else the first of its kind spelling the name.
|
||||
fn unit_symbol<'s>(semantics: &'s Semantics, found: &Found, name: &str) -> Option<&'s Symbol> {
|
||||
let mut candidates = semantics
|
||||
.symbols_named(name)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.filter(|s| s.kind == found.def.kind);
|
||||
let first = candidates.next()?;
|
||||
Some(
|
||||
std::iter::once(first)
|
||||
.chain(candidates)
|
||||
.find(|s| s.name_span == found.def.name_span)
|
||||
.unwrap_or(first),
|
||||
)
|
||||
}
|
||||
|
||||
/// One port as the answer shows it.
|
||||
struct PortRow {
|
||||
dir: String,
|
||||
ty: String,
|
||||
range: String,
|
||||
name: String,
|
||||
unpacked: String,
|
||||
}
|
||||
|
||||
impl PortRow {
|
||||
/// The type as the declaration writes it, packed range included — one
|
||||
/// column, so a long type name widens one column rather than two.
|
||||
fn written_type(&self) -> String {
|
||||
match (self.ty.is_empty(), self.range.is_empty()) {
|
||||
(_, true) => self.ty.clone(),
|
||||
(true, false) => self.range.clone(),
|
||||
(false, false) => format!("{} {}", self.ty, self.range),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_with_unpacked(&self) -> String {
|
||||
if self.unpacked.is_empty() {
|
||||
self.name.clone()
|
||||
} else {
|
||||
format!("{} {}", self.name, self.unpacked)
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"direction": self.dir, "type": self.ty, "range": self.range,
|
||||
"name": self.name, "unpacked": self.unpacked,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The plan's ports with the packed range split off the type, and the
|
||||
/// unpacked dimensions an ANSI port writes after its name.
|
||||
fn port_rows(
|
||||
plan: &InstantiationPlan,
|
||||
analysis: &Analysis,
|
||||
scope: Option<ScopeId>,
|
||||
) -> Vec<PortRow> {
|
||||
plan.ports
|
||||
.iter()
|
||||
.map(|port| {
|
||||
let (ty, range) = match port.ty.find('[') {
|
||||
Some(at) => (port.ty[..at].trim().to_string(), port.ty[at..].trim().to_string()),
|
||||
None => (port.ty.clone(), String::new()),
|
||||
};
|
||||
let unpacked =
|
||||
scope.map_or(String::new(), |scope| unpacked(analysis, scope, &port.name));
|
||||
PortRow { dir: port.dir.clone(), ty, range, name: port.name.clone(), unpacked }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `[..]` groups written right after an ANSI port's name. A non-ANSI
|
||||
/// port (completed in the body) answers nothing here.
|
||||
fn unpacked(analysis: &Analysis, scope: ScopeId, name: &str) -> String {
|
||||
let Some(port) = analysis.semantics.symbols_named(name).find_map(|id| {
|
||||
let s = analysis.semantics.symbol(id)?;
|
||||
(s.scope == scope && s.kind == SymbolKind::Port && s.detail_span.is_none()).then_some(s)
|
||||
}) else {
|
||||
return String::new();
|
||||
};
|
||||
let mut rest = analysis.slice(port.name_span.end, port.decl_span.end).trim_start();
|
||||
let mut out = String::new();
|
||||
while rest.starts_with('[') {
|
||||
let mut depth = 0;
|
||||
let Some(end) = rest.char_indices().find_map(|(at, c)| {
|
||||
depth += match c {
|
||||
'[' => 1,
|
||||
']' => -1,
|
||||
_ => 0,
|
||||
};
|
||||
(depth == 0).then_some(at)
|
||||
}) else {
|
||||
break;
|
||||
};
|
||||
out.push_str(&render::one_line(&rest[..=end]));
|
||||
rest = rest[end + 1..].trim_start();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A package's or class's members, in declaration order, and a class's
|
||||
/// base. `name` is the unit's own name, without a package prefix — which
|
||||
/// two classes in two packages may share, so both answers are read off this
|
||||
/// declaration: a member counts only when it is declared inside
|
||||
/// `found.def.decl_span`, and the base is what this declaration's own
|
||||
/// `extends` writes.
|
||||
fn members(
|
||||
project: &Project,
|
||||
analysis: &Analysis,
|
||||
found: &Found,
|
||||
name: &str,
|
||||
mut text: String,
|
||||
file: &str,
|
||||
) -> Answer {
|
||||
let index = project.index();
|
||||
let within = found.def.decl_span;
|
||||
let mut rows: Vec<(u32, &'static str, String)> = index
|
||||
.members_of(name)
|
||||
.flat_map(|(member, defs)| {
|
||||
defs.iter()
|
||||
.filter(|def| index.path(def.file) == Some(found.path.as_path()))
|
||||
.filter(|def| {
|
||||
within.start <= def.name_span.start && def.name_span.end <= within.end
|
||||
})
|
||||
.map(move |def| (def.lines.name, render::kind(def.kind), member.to_string()))
|
||||
})
|
||||
.collect();
|
||||
rows.sort();
|
||||
let base = class_base(&analysis.tree.items, found.def.name_span);
|
||||
if let Some(base) = &base {
|
||||
text.push_str(&format!("extends {base}\n"));
|
||||
}
|
||||
text.push_str("members:\n");
|
||||
let table: Vec<Vec<String>> = rows
|
||||
.iter()
|
||||
.map(|(line, kind, member)| vec![kind.to_string(), member.clone(), line.to_string()])
|
||||
.collect();
|
||||
text.push_str(&render::table(&table));
|
||||
let structured = json!({
|
||||
"name": name,
|
||||
"kind": render::kind(found.def.kind),
|
||||
"file": file,
|
||||
"line": found.def.lines.name,
|
||||
"extends": base,
|
||||
"members": rows.iter().map(|(line, kind, member)| json!({ "name": member, "kind": kind, "line": line })).collect::<Vec<_>>(),
|
||||
});
|
||||
Answer { text, structured }
|
||||
}
|
||||
|
||||
/// The base the class declared at `name_span` names in its `extends`, read
|
||||
/// off the file's own tree; `None` for a class without one (or a package).
|
||||
fn class_base(items: &[Item], name_span: TextRange) -> Option<String> {
|
||||
let item = items
|
||||
.iter()
|
||||
.find(|item| item.span.start <= name_span.start && name_span.end <= item.span.end)?;
|
||||
if let ItemKind::Class(class) = &item.kind {
|
||||
if class.name_span == name_span {
|
||||
return class.extends.as_ref().map(|extends| extends.name.clone());
|
||||
}
|
||||
}
|
||||
child_items(&item.kind).into_iter().find_map(|items| class_base(items, name_span))
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! 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
|
||||
//! `arguments` go through, so the two cannot disagree.
|
||||
|
||||
mod defines;
|
||||
mod diagnostics;
|
||||
mod edit;
|
||||
mod format;
|
||||
mod hierarchy;
|
||||
mod interface;
|
||||
mod nav;
|
||||
mod read;
|
||||
mod read_item;
|
||||
mod refactor;
|
||||
mod select;
|
||||
mod source;
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
|
||||
/// What a tool hands back: the compact text rendering the agent reads, and
|
||||
/// the same facts as JSON (`structuredContent`).
|
||||
pub struct Answer {
|
||||
pub text: String,
|
||||
pub structured: Value,
|
||||
}
|
||||
|
||||
/// A tool's body. `Err` is a refusal: one sentence, sent as `isError: true`.
|
||||
pub type Handler = fn(&mut Project, &Args) -> Result<Answer, String>;
|
||||
|
||||
/// The JSON type one argument takes.
|
||||
pub enum Ty {
|
||||
/// A string.
|
||||
Str,
|
||||
/// An integer no smaller than the bound.
|
||||
Int { min: i64 },
|
||||
/// One of a fixed set of strings.
|
||||
Enum(&'static [&'static str]),
|
||||
/// `true` or `false`.
|
||||
Bool,
|
||||
/// An integer inside `min..=max`.
|
||||
Range { min: i64, max: i64 },
|
||||
}
|
||||
|
||||
/// One argument a tool takes.
|
||||
pub struct Param {
|
||||
pub name: &'static str,
|
||||
pub ty: Ty,
|
||||
pub required: bool,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
/// One tool, as `tools/list` shows it and `tools/call` runs it.
|
||||
pub struct Tool {
|
||||
pub name: &'static str,
|
||||
pub title: &'static str,
|
||||
pub description: &'static str,
|
||||
pub params: &'static [Param],
|
||||
/// Whether the call walks the roots again before answering, so files
|
||||
/// created since the last walk are counted (`project_overview`).
|
||||
pub rewalk: bool,
|
||||
pub handler: Handler,
|
||||
}
|
||||
|
||||
/// What a tool does to the disk — the annotations a host shows before it
|
||||
/// lets an agent call it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Effect {
|
||||
/// Nothing on disk changes; the same call on the same disk gives the
|
||||
/// same answer.
|
||||
Read,
|
||||
/// Files inside the roots are rewritten (or created). `idempotent` when
|
||||
/// a second identical call writes nothing more.
|
||||
Edit { idempotent: bool },
|
||||
}
|
||||
|
||||
use Effect::{Edit, Read};
|
||||
|
||||
/// Every tool this server offers, in the order `tools/list` gives them.
|
||||
const TOOLS: &[(Tool, Effect)] = &[
|
||||
(read::PROJECT_OVERVIEW, Read),
|
||||
(read::LIST_UNITS, Read),
|
||||
(interface::UNIT_INTERFACE, Read),
|
||||
(read::OUTLINE, Read),
|
||||
(read_item::READ_ITEM, Read),
|
||||
(read::SEARCH_SYMBOLS, Read),
|
||||
(defines::DEFINES, Read),
|
||||
(nav::DEFINITION, Read),
|
||||
(nav::REFERENCES, Read),
|
||||
(hierarchy::HIERARCHY, Read),
|
||||
(diagnostics::DIAGNOSTICS, Read),
|
||||
(format::FORMAT, Edit { idempotent: true }),
|
||||
(format::FIX_LINT, Edit { idempotent: true }),
|
||||
(edit::RENAME, Edit { idempotent: false }),
|
||||
(edit::EXPAND_WILDCARD, Edit { idempotent: true }),
|
||||
(edit::CONVERT_PORTS, Edit { idempotent: true }),
|
||||
(edit::ORGANIZE_IMPORTS, Edit { idempotent: true }),
|
||||
(edit::INLINE_MODULE, Edit { idempotent: false }),
|
||||
(edit::PROPAGATE_PORTS, Edit { idempotent: false }),
|
||||
(edit::REMOVE_PORT, Edit { idempotent: false }),
|
||||
(refactor::ADD_PORT, Edit { idempotent: false }),
|
||||
(refactor::EXTRACT_MODULE, Edit { idempotent: false }),
|
||||
(refactor::INSTANTIATE, Read),
|
||||
];
|
||||
|
||||
/// The tool called `name`.
|
||||
pub fn find(name: &str) -> Option<&'static Tool> {
|
||||
TOOLS.iter().map(|(tool, _)| tool).find(|tool| tool.name == name)
|
||||
}
|
||||
|
||||
/// The `tools/list` result: every tool, no pagination.
|
||||
pub fn list() -> Value {
|
||||
let tools: Vec<Value> = TOOLS.iter().map(|(tool, effect)| describe(tool, *effect)).collect();
|
||||
json!({ "tools": tools })
|
||||
}
|
||||
|
||||
fn describe(tool: &Tool, effect: Effect) -> Value {
|
||||
// No tool consults anything outside the roots (`openWorldHint`), and no
|
||||
// edit tool destroys: each rewrites files inside the roots through a
|
||||
// verified engine, and `dry_run` shows the diff first.
|
||||
let (read_only, idempotent) = match effect {
|
||||
Read => (true, true),
|
||||
Edit { idempotent } => (false, idempotent),
|
||||
};
|
||||
json!({
|
||||
"name": tool.name,
|
||||
"title": tool.title,
|
||||
"description": tool.description,
|
||||
"inputSchema": schema(tool.params),
|
||||
"annotations": {
|
||||
"title": tool.title,
|
||||
"readOnlyHint": read_only,
|
||||
"destructiveHint": false,
|
||||
"idempotentHint": idempotent,
|
||||
"openWorldHint": false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// A JSON Schema object for an argument list: closed, with its required set.
|
||||
fn schema(params: &[Param]) -> Value {
|
||||
let mut properties = Map::new();
|
||||
for param in params {
|
||||
let mut property = match param.ty {
|
||||
Ty::Str => json!({ "type": "string" }),
|
||||
Ty::Int { min } => json!({ "type": "integer", "minimum": min }),
|
||||
Ty::Enum(values) => json!({ "type": "string", "enum": values }),
|
||||
Ty::Bool => json!({ "type": "boolean" }),
|
||||
Ty::Range { min, max } => json!({ "type": "integer", "minimum": min, "maximum": max }),
|
||||
};
|
||||
property["description"] = Value::from(param.description);
|
||||
properties.insert(param.name.to_string(), property);
|
||||
}
|
||||
let required: Vec<&str> =
|
||||
params.iter().filter(|param| param.required).map(|param| param.name).collect();
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": properties,
|
||||
"required": required,
|
||||
"additionalProperties": false,
|
||||
})
|
||||
}
|
||||
|
||||
/// A call's arguments, checked against the tool's list.
|
||||
pub struct Args(Map<String, Value>);
|
||||
|
||||
impl Args {
|
||||
/// A string argument, when given.
|
||||
pub fn str(&self, name: &str) -> Option<&str> {
|
||||
self.0.get(name).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// An integer argument, when given.
|
||||
pub fn int(&self, name: &str) -> Option<i64> {
|
||||
self.0.get(name).and_then(Value::as_i64)
|
||||
}
|
||||
|
||||
/// A boolean argument, or `default`.
|
||||
pub fn flag(&self, name: &str, default: bool) -> bool {
|
||||
self.0.get(name).and_then(Value::as_bool).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// A non-negative integer argument, or `default`.
|
||||
pub fn count(&self, name: &str, default: usize) -> usize {
|
||||
self.int(name).and_then(|n| usize::try_from(n).ok()).unwrap_or(default)
|
||||
}
|
||||
}
|
||||
|
||||
/// Check `arguments` against `tool`'s list. The refusal names the argument
|
||||
/// and what was wrong with it, so the agent can correct the call.
|
||||
pub fn validate(tool: &Tool, arguments: Map<String, Value>) -> Result<Args, String> {
|
||||
for name in arguments.keys() {
|
||||
if !tool.params.iter().any(|param| param.name == name) {
|
||||
let known: Vec<&str> = tool.params.iter().map(|param| param.name).collect();
|
||||
return Err(format!(
|
||||
"`{}` takes no argument `{name}` (it takes: {}).",
|
||||
tool.name,
|
||||
if known.is_empty() { "nothing".to_string() } else { known.join(", ") }
|
||||
));
|
||||
}
|
||||
}
|
||||
for param in tool.params {
|
||||
match arguments.get(param.name) {
|
||||
None | Some(Value::Null) if param.required => {
|
||||
return Err(format!("`{}` needs the argument `{}`.", tool.name, param.name));
|
||||
}
|
||||
None | Some(Value::Null) => {}
|
||||
Some(value) => check_type(tool.name, param, value)?,
|
||||
}
|
||||
}
|
||||
Ok(Args(arguments))
|
||||
}
|
||||
|
||||
fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
|
||||
let fits = match param.ty {
|
||||
Ty::Str => value.is_string(),
|
||||
Ty::Int { min } => value.as_i64().is_some_and(|n| n >= min),
|
||||
Ty::Enum(values) => value.as_str().is_some_and(|s| values.contains(&s)),
|
||||
Ty::Bool => value.is_boolean(),
|
||||
Ty::Range { min, max } => value.as_i64().is_some_and(|n| (min..=max).contains(&n)),
|
||||
};
|
||||
if fits {
|
||||
return Ok(());
|
||||
}
|
||||
let wanted = match param.ty {
|
||||
Ty::Str => "a string".to_string(),
|
||||
Ty::Int { min } => format!("an integer >= {min}"),
|
||||
Ty::Enum(values) => format!("one of {}", values.join(", ")),
|
||||
Ty::Bool => "true or false".to_string(),
|
||||
Ty::Range { min, max } => format!("an integer from {min} to {max}"),
|
||||
};
|
||||
Err(format!("`{tool}` argument `{}` must be {wanted}, not {value}.", param.name))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(value: Value) -> Map<String, Value> {
|
||||
value.as_object().cloned().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_schema_is_closed_and_names_its_required_arguments() {
|
||||
for (tool, _) in TOOLS {
|
||||
let schema = schema(tool.params);
|
||||
assert_eq!(schema["additionalProperties"], false, "{}", tool.name);
|
||||
assert!(schema["required"].is_array(), "{}", tool.name);
|
||||
assert!(!tool.description.is_empty() && tool.description.len() < 600, "{}", tool.name);
|
||||
}
|
||||
let names: Vec<&str> = TOOLS.iter().map(|(tool, _)| tool.name).collect();
|
||||
let mut unique = names.clone();
|
||||
unique.sort_unstable();
|
||||
unique.dedup();
|
||||
assert_eq!(names.len(), unique.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_names_the_offending_argument() {
|
||||
let tool = find("list_units").unwrap();
|
||||
let unknown = validate(tool, args(json!({"nme": "x"}))).err().unwrap();
|
||||
assert!(unknown.contains("`nme`"), "{unknown}");
|
||||
let wrong = validate(tool, args(json!({"kind": "struct"}))).err().unwrap();
|
||||
assert!(wrong.contains("`kind`") && wrong.contains("module"), "{wrong}");
|
||||
let negative = validate(tool, args(json!({"limit": -1}))).err().unwrap();
|
||||
assert!(negative.contains("`limit`"), "{negative}");
|
||||
let missing = validate(find("outline").unwrap(), Map::new()).err().unwrap();
|
||||
assert!(missing.contains("`file`"), "{missing}");
|
||||
assert!(validate(tool, args(json!({"kind": "module", "glob": null}))).is_ok());
|
||||
let references = find("references").unwrap();
|
||||
let flag = validate(references, args(json!({"name": "x", "include_declaration": "no"})));
|
||||
assert!(flag.err().unwrap().contains("true or false"));
|
||||
let given = validate(references, args(json!({"name": "x", "include_declaration": false})));
|
||||
assert!(!given.unwrap().flag("include_declaration", true));
|
||||
let hierarchy = find("hierarchy").unwrap();
|
||||
let deep = validate(hierarchy, args(json!({"depth": 21}))).err().unwrap();
|
||||
assert!(deep.contains("`depth`") && deep.contains("from 1 to 20"), "{deep}");
|
||||
assert!(validate(hierarchy, args(json!({"depth": 20}))).is_ok());
|
||||
assert_eq!(schema(hierarchy.params)["properties"]["depth"]["maximum"], 20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! `definition` and `references`: where a name is declared, and every place
|
||||
//! the declaration is used — the two questions an agent otherwise answers by
|
||||
//! grepping and reading.
|
||||
//!
|
||||
//! Both take one selector ([`target`]): a position (`file` + `line` + `col`,
|
||||
//! or `file` + `line` + the `name` written on that line), a name in a file
|
||||
//! (`file` + `name`), or a bare `name` (with an optional `unit`) looked up in
|
||||
//! the index. `definition` walks the server's ladder — an `` `include`` line,
|
||||
//! a macro use, the file's own symbol table, the workspace overlay — and
|
||||
//! lists every site, never a guess. `references` hands the declaration to
|
||||
//! `vlog_refactor::find_references` over every indexed file
|
||||
//! (`source::WholeSet`).
|
||||
//! The selector itself is `select.rs`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex};
|
||||
|
||||
use super::select::{macro_name, target, Target};
|
||||
use super::source::{self, checked_site, Site, Texts, WholeSet};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
/// The selector's arguments, shared by both tools.
|
||||
const FILE: Param = Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The file holding the position, relative to a root or absolute inside one.",
|
||||
};
|
||||
const LINE: Param = Param {
|
||||
name: "line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
|
||||
};
|
||||
const COL: Param = Param {
|
||||
name: "col",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based column in bytes on `line`.",
|
||||
};
|
||||
const NAME: Param = Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The name: alone, looked up across the project (`` `NAME`` for a macro); with `file`, its first occurrence there; with `file` and `line`, its occurrence on that line.",
|
||||
};
|
||||
const UNIT: Param = Param {
|
||||
name: "unit",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "With a bare `name`: the module, interface, package or class declaring it.",
|
||||
};
|
||||
|
||||
pub const DEFINITION: Tool = Tool {
|
||||
name: "definition",
|
||||
title: "Go to definition",
|
||||
description: "Where a name is declared: every declaration site as file:line:col, its kind and the declaration's own source line (a name declared in several places lists them all, never a guess). Select by position (`file`, `line`, `col`), by `file`+`line`+`name`, or by `name` (and `unit`) across the project; also answers a macro use and an `include` line. Prefer it over grepping for the declaration.",
|
||||
params: &[FILE, LINE, COL, NAME, UNIT],
|
||||
rewalk: false,
|
||||
handler: definition,
|
||||
};
|
||||
|
||||
pub const REFERENCES: Tool = Tool {
|
||||
name: "references",
|
||||
title: "Find references",
|
||||
description: "Every use of one declaration across the project, grouped by file as line:col and the line's text — the same occurrences a rename would edit. Select as for `definition`; a bare `name` must name one declaration. Refuses a name lucisv cannot resolve to one declaration, with the reason.",
|
||||
params: &[
|
||||
FILE,
|
||||
LINE,
|
||||
COL,
|
||||
NAME,
|
||||
UNIT,
|
||||
Param {
|
||||
name: "include_declaration",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "List the declaration itself too (default true).",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most hits to return (default 200).",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Hits to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: true,
|
||||
handler: references,
|
||||
};
|
||||
|
||||
fn definition(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let sites = match target(project, args)? {
|
||||
Target::At { path, analysis, offset } => at_position(project, &path, &analysis, offset)?,
|
||||
Target::Named { name, unit } => {
|
||||
let mut sites = by_name(project, &name, unit.as_deref());
|
||||
if sites.is_empty() && project.ensure_walked_for_miss() {
|
||||
sites = by_name(project, &name, unit.as_deref());
|
||||
}
|
||||
if sites.is_empty() {
|
||||
return Err(format!(
|
||||
"no declaration of `{name}`{} is indexed.",
|
||||
in_unit(unit.as_deref())
|
||||
));
|
||||
}
|
||||
sites
|
||||
}
|
||||
};
|
||||
Ok(source::answer(&sites, "definitions", "no declaration"))
|
||||
}
|
||||
|
||||
fn in_unit(unit: Option<&str>) -> String {
|
||||
unit.map_or(String::new(), |unit| format!(" in `{unit}`"))
|
||||
}
|
||||
|
||||
/// The server's ladder at one position: `` `include`` line, macro use, then
|
||||
/// both symbol layers.
|
||||
fn at_position(
|
||||
project: &Project,
|
||||
path: &Path,
|
||||
analysis: &Analysis,
|
||||
offset: u32,
|
||||
) -> Result<Vec<Site>, String> {
|
||||
let file = project.relative(path);
|
||||
let (line, col) = analysis.lines.line_col(offset);
|
||||
if let Some(token) = analysis.token_at(offset) {
|
||||
if token.kind == TokenKind::Directive && token.text.starts_with("`include") {
|
||||
return included(project, path, token).map(|site| vec![site]);
|
||||
}
|
||||
if let Some(name) = macro_name(token).filter(|_| token.is_macro()) {
|
||||
return macro_sites(project, analysis, &file, name);
|
||||
}
|
||||
}
|
||||
let external = analysis.external(project.index());
|
||||
match external.definition_of(&analysis.semantics, offset) {
|
||||
Some(Definition::Local(symbol)) if !symbol.name_span.is_empty() => {
|
||||
Ok(local_sites(analysis, &file, symbol))
|
||||
}
|
||||
Some(Definition::External(defs)) => {
|
||||
let reference = analysis.semantics.reference_at(offset);
|
||||
let name = reference.map_or("", |reference| reference.name.as_str());
|
||||
Ok(def_sites(project, defs, name))
|
||||
}
|
||||
_ => Err(format!("nothing at {file}:{line}:{col} names a declaration.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A local declaration: its completing declaration first (a non-ANSI port's
|
||||
/// body line), then the name, then every redeclaration the binder folded
|
||||
/// into it (`output y; wire y;` declares `y` twice) — one site per line.
|
||||
fn local_sites(analysis: &Analysis, file: &str, symbol: &Symbol) -> Vec<Site> {
|
||||
let (text, lines) = (&analysis.text, &analysis.lines);
|
||||
let kind = render::kind(symbol.kind);
|
||||
let detail = symbol.detail_span.filter(|span| !span.is_empty());
|
||||
let mut sites: Vec<Site> = detail
|
||||
.into_iter()
|
||||
.chain([symbol.name_span])
|
||||
.map(|span| Site::at(file.to_string(), text, lines, span, kind))
|
||||
.collect();
|
||||
let id = analysis.semantics.symbol_at(symbol.name_span.start);
|
||||
for again in analysis.semantics.duplicates().iter().filter(|d| Some(d.first) == id) {
|
||||
let site =
|
||||
Site::at(file.to_string(), text, lines, again.name_span, render::kind(again.kind));
|
||||
if !sites.iter().any(|known| known.line == site.line) {
|
||||
sites.push(site);
|
||||
}
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// Indexed declarations of `name`, each checked against its file's bytes.
|
||||
fn def_sites(project: &Project, defs: &[Def], name: &str) -> Vec<Site> {
|
||||
let mut texts = Texts::default();
|
||||
let mut sites: Vec<Site> = Vec::new();
|
||||
for def in defs {
|
||||
let Some(path) = project.index().path(def.file) else { continue };
|
||||
let shown = def.detail_span.unwrap_or(def.name_span);
|
||||
let kind = render::kind(def.kind);
|
||||
let site = checked_site(project, &mut texts, path, def.name_span, shown, name, kind);
|
||||
if let Some(site) = site {
|
||||
if !sites.iter().any(|s| (&s.file, s.line, s.col) == (&site.file, site.line, site.col))
|
||||
{
|
||||
sites.push(site);
|
||||
}
|
||||
}
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// An `` `include`` line: the named file beside the including one. No
|
||||
/// include-directory ladder is searched.
|
||||
fn included(project: &Project, path: &Path, token: &Token) -> Result<Site, String> {
|
||||
let written = token.text.trim_start_matches("`include").trim();
|
||||
let spelled = written.trim_matches(|c| c == '"' || c == '<' || c == '>');
|
||||
let beside = path.parent().unwrap_or(Path::new("")).join(spelled);
|
||||
let found = beside.to_str().and_then(|candidate| project.resolve(candidate).ok());
|
||||
let Some(target) = found else {
|
||||
return Err(format!(
|
||||
"`include {written} is not beside `{}` (only the including file's directory is searched).",
|
||||
project.relative(path)
|
||||
));
|
||||
};
|
||||
let text = render::one_line(&token.text);
|
||||
Ok(Site { file: project.relative(&target), line: 1, col: 1, kind: "include", text })
|
||||
}
|
||||
|
||||
/// A macro use: this file's own last definition when it has one, else every
|
||||
/// indexed definition (the include graph is not modelled, so none is picked).
|
||||
fn macro_sites(
|
||||
project: &Project,
|
||||
analysis: &Analysis,
|
||||
file: &str,
|
||||
name: &str,
|
||||
) -> Result<Vec<Site>, String> {
|
||||
if let Some(define) = analysis.defines.latest(name) {
|
||||
let (text, lines) = (&analysis.text, &analysis.lines);
|
||||
return Ok(vec![Site::at(file.to_string(), text, lines, define.name_span, "define")]);
|
||||
}
|
||||
let sites = define_sites(project, name);
|
||||
if sites.is_empty() {
|
||||
return Err(format!("`{name} is not defined in any indexed file."));
|
||||
}
|
||||
Ok(sites)
|
||||
}
|
||||
|
||||
/// Every indexed `` `define`` of `name`.
|
||||
pub(super) fn define_sites(project: &Project, name: &str) -> Vec<Site> {
|
||||
let index = project.index();
|
||||
let mut texts = Texts::default();
|
||||
index
|
||||
.find_define(name)
|
||||
.into_iter()
|
||||
.filter_map(|(file, define)| {
|
||||
let path = index.path(file)?;
|
||||
let span = define.name_span;
|
||||
checked_site(project, &mut texts, path, span, span, name, "define")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Declarations by name: a unit's member when `unit` is given, else every
|
||||
/// unit, exported member and module internal of that name; a macro when the
|
||||
/// name is written `` `NAME`` or nothing else declares it.
|
||||
fn by_name(project: &Project, name: &str, unit: Option<&str>) -> Vec<Site> {
|
||||
if let Some(spelled) = name.strip_prefix('`') {
|
||||
return define_sites(project, spelled);
|
||||
}
|
||||
let defs = declarations(project.index(), name, unit);
|
||||
let sites = def_sites(project, &defs, name);
|
||||
if sites.is_empty() && unit.is_none() {
|
||||
return define_sites(project, name);
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// Every indexed declaration of `name` (in `unit`, when given).
|
||||
fn declarations(index: &WorkspaceIndex, name: &str, unit: Option<&str>) -> Vec<Def> {
|
||||
if let Some(unit) = unit {
|
||||
return index.member_in(unit, name, Surface::Hierarchical).to_vec();
|
||||
}
|
||||
let mut defs: Vec<Def> = index.units(name).to_vec();
|
||||
let exported = index.workspace_symbols(name);
|
||||
let members = exported.iter().filter(|hit| hit.name == name && hit.container.is_some());
|
||||
defs.extend(members.map(|hit| hit.def.clone()));
|
||||
defs.extend(index.hierarchical_declarations(name).map(|(_, def)| def.clone()));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
defs.retain(|def| seen.insert(DefinitionKey::of(def)));
|
||||
defs
|
||||
}
|
||||
|
||||
fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let (path, analysis, offset) = match target(project, args)? {
|
||||
Target::At { path, analysis, offset } => (path, analysis, offset),
|
||||
Target::Named { name, unit } => {
|
||||
let (path, offset) = declaration_position(project, &name, unit.as_deref())?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
(path, analysis, offset)
|
||||
}
|
||||
};
|
||||
if let Some(name) = analysis.token_at(offset).filter(|t| t.is_macro()).and_then(macro_name) {
|
||||
return Err(format!("`{name} is a macro; {MACRO_REFUSAL}"));
|
||||
}
|
||||
let set = WholeSet::read(project, Some(&path));
|
||||
let include = args.flag("include_declaration", true);
|
||||
let found = vlog_refactor::find_references(&set.files, &path, offset, include)
|
||||
.map_err(engine_refusal)?;
|
||||
let partial = set.warning(project);
|
||||
let mut texts = Texts::default();
|
||||
for (held, text) in set.files {
|
||||
texts.hold(held, text);
|
||||
}
|
||||
let hits: Vec<Site> = found
|
||||
.iter()
|
||||
.filter_map(|(file, span)| {
|
||||
let (text, lines) = texts.get(file)?;
|
||||
Some(Site::at(project.relative(file), text, lines, *span, "use"))
|
||||
})
|
||||
.collect();
|
||||
let mut answer = render_hits(&hits, args);
|
||||
// A file the index skipped was not searched: the census is partial.
|
||||
if let Some(partial) = partial {
|
||||
answer.text.push_str(&format!("warning: {partial}\n"));
|
||||
answer.structured["warning"] = Value::from(partial);
|
||||
}
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// The one declaration a bare `name` selects for `references` (and `rename`).
|
||||
pub(super) fn declaration_position(
|
||||
project: &mut Project,
|
||||
name: &str,
|
||||
unit: Option<&str>,
|
||||
) -> Result<(PathBuf, u32), String> {
|
||||
let mut defs = declarations(project.index(), name, unit);
|
||||
if defs.is_empty() && project.ensure_walked_for_miss() {
|
||||
defs = declarations(project.index(), name, unit);
|
||||
}
|
||||
let sites = def_sites(project, &defs, name);
|
||||
match (defs.as_slice(), sites.len()) {
|
||||
([def], 1) => {
|
||||
let path = project.index().path(def.file).map(Path::to_path_buf);
|
||||
path.map(|path| (path, def.name_span.start))
|
||||
.ok_or_else(|| format!("`{name}`'s file is no longer indexed."))
|
||||
}
|
||||
(_, 0)
|
||||
if unit.is_none()
|
||||
&& !define_sites(project, name.trim_start_matches('`')).is_empty() =>
|
||||
{
|
||||
Err(format!("`{name}` is a macro; {MACRO_REFUSAL}"))
|
||||
}
|
||||
(_, 0) => Err(format!("no declaration of `{name}`{} is indexed.", in_unit(unit))),
|
||||
_ => {
|
||||
let listed: Vec<String> =
|
||||
sites.iter().map(|site| format!("{}:{}", site.file, site.line)).collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); pick one with `file` and `line`.",
|
||||
listed.len(),
|
||||
listed.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `references` does not answer for a macro.
|
||||
const MACRO_REFUSAL: &str =
|
||||
"references follows declarations, not macros (`defines` lists its definitions).";
|
||||
|
||||
/// The engine's refusal, said as ours: prefixed, and its rename wording —
|
||||
/// `find_references` shares the rename's resolution — turned into this
|
||||
/// tool's.
|
||||
fn engine_refusal(sentence: String) -> String {
|
||||
const REWORDED: &[(&str, &str)] = &[
|
||||
("there is no symbol to rename at this position", "there is no symbol at this position"),
|
||||
(
|
||||
"nothing outside the project scope can be renamed",
|
||||
"nothing outside the project scope is followed",
|
||||
),
|
||||
("lucisv found nothing to rename for", "lucisv found no occurrence of"),
|
||||
("the rename was abandoned", "the search was abandoned"),
|
||||
("which declaration this rename means", "which declaration this position means"),
|
||||
(", so a rename here would only be half a rename", ", so its uses cannot all be listed"),
|
||||
];
|
||||
let mut out = sentence;
|
||||
for (from, to) in REWORDED {
|
||||
out = out.replace(from, to);
|
||||
}
|
||||
format!("lucisv cannot follow this position: {out}")
|
||||
}
|
||||
|
||||
/// Hits grouped by file, `line:col text`, paged.
|
||||
fn render_hits(hits: &[Site], args: &Args) -> Answer {
|
||||
let (shown, rest) =
|
||||
render::page(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = shown
|
||||
.iter()
|
||||
.map(|hit| (hit.file.clone(), format!("{}:{} {}", hit.line, hit.col, hit.text)))
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if hits.is_empty() {
|
||||
text = "no references\n".to_string();
|
||||
}
|
||||
let listed: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|hit| json!({ "file": hit.file, "line": hit.line, "col": hit.col, "text": hit.text }))
|
||||
.collect();
|
||||
Answer { text, structured: json!({ "hits": listed, "total": hits.len() }) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::engine_refusal;
|
||||
|
||||
#[test]
|
||||
fn engine_refusals_are_prefixed_and_never_speak_of_renaming() {
|
||||
for sentence in [
|
||||
"there is no symbol to rename at this position.",
|
||||
"`x` is declared outside the files lucisv indexes, so a rename here would only be half a rename.",
|
||||
"lucisv found nothing to rename for `x`.",
|
||||
"`x` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.",
|
||||
] {
|
||||
let said = engine_refusal(sentence.to_string());
|
||||
assert!(said.starts_with("lucisv cannot follow this position: "), "{said}");
|
||||
assert!(!said.contains("rename"), "{said}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
//! The whole-project read tools: `project_overview`, `list_units`,
|
||||
//! `outline` and `search_symbols`. Each answers from the index (or from one
|
||||
//! file's analysis) and renders by the rules in `render.rs`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_semantic::{Def, DocumentSymbol, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
const LIMIT: Param = Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most entries to return (default 200).",
|
||||
};
|
||||
const OFFSET: Param = Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Entries to skip, for paging past `… and N more` (default 0).",
|
||||
};
|
||||
|
||||
pub const PROJECT_OVERVIEW: Tool = Tool {
|
||||
name: "project_overview",
|
||||
title: "Project overview",
|
||||
description: "Summarise the Verilog/SystemVerilog project under the roots: file count, units by kind, top-level modules (nothing instantiates them) and the largest files. Call it first to orient yourself instead of listing directories.",
|
||||
params: &[],
|
||||
rewalk: true,
|
||||
handler: project_overview,
|
||||
};
|
||||
|
||||
pub const LIST_UNITS: Tool = Tool {
|
||||
name: "list_units",
|
||||
title: "List design units",
|
||||
description: "List the modules, interfaces, packages, classes and programs declared in the project with their file:line, optionally filtered by kind and a name glob (`*`, `?`). Prefer it over grepping for `module` to find where a unit lives.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "kind",
|
||||
ty: Ty::Enum(&["module", "interface", "package", "class", "program"]),
|
||||
required: false,
|
||||
description: "Only units of this kind.",
|
||||
},
|
||||
Param {
|
||||
name: "glob",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Only names matching this pattern; `*` is any run, `?` one character.",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: list_units,
|
||||
};
|
||||
|
||||
pub const OUTLINE: Tool = Tool {
|
||||
name: "outline",
|
||||
title: "File outline",
|
||||
description: "The declarations in one file as a tree with 1-based line ranges (units, ports, parameters, signals, functions, instances, blocks), plus its parse errors. Prefer it over reading a file to see what it contains; then use read_item for the part you need.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file, relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "depth",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Levels to show; 1 is the file's units only (default: all).",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: outline,
|
||||
};
|
||||
|
||||
pub const SEARCH_SYMBOLS: Tool = Tool {
|
||||
name: "search_symbols",
|
||||
title: "Search symbols",
|
||||
description: "Find declarations whose name contains `query` (case-insensitive) across the project: units, and the ports, parameters and package/class members other files can name. Answers file and line per hit; a module's internal signals are not included (use outline for those).",
|
||||
params: &[
|
||||
Param {
|
||||
name: "query",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "Substring of the name to find; empty matches everything.",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: search_symbols,
|
||||
};
|
||||
|
||||
/// One unit in a listing.
|
||||
struct Unit {
|
||||
name: String,
|
||||
kind: &'static str,
|
||||
file: String,
|
||||
line: u32,
|
||||
}
|
||||
|
||||
/// Every unit the index holds, file-scope ones and the classes a package
|
||||
/// declares (named `pkg::cls`), sorted by file then line.
|
||||
fn units(project: &Project) -> Vec<Unit> {
|
||||
let index = project.index();
|
||||
let mut out = Vec::new();
|
||||
for kind in [SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class]
|
||||
{
|
||||
for (name, def) in index.units_of(kind) {
|
||||
out.push(unit(project, name.to_string(), def));
|
||||
}
|
||||
}
|
||||
for (package, _) in index.units_of(SymbolKind::Package) {
|
||||
for (name, defs) in index.members_of(package) {
|
||||
for def in defs.iter().filter(|def| def.kind == SymbolKind::Class) {
|
||||
out.push(unit(project, format!("{package}::{name}"), def));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| (&a.file, a.line, &a.name).cmp(&(&b.file, b.line, &b.name)));
|
||||
out
|
||||
}
|
||||
|
||||
fn unit(project: &Project, name: String, def: &Def) -> Unit {
|
||||
let path = project.index().path(def.file).unwrap_or(Path::new(""));
|
||||
Unit {
|
||||
name,
|
||||
kind: unit_kind(project, path, def),
|
||||
file: project.relative(path),
|
||||
line: def.lines.name,
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit's kind word, telling a `program` from the module it is modelled as.
|
||||
pub fn unit_kind(project: &Project, path: &Path, def: &Def) -> &'static str {
|
||||
if def.kind == SymbolKind::Module && is_program(project, path, def) {
|
||||
"program"
|
||||
} else {
|
||||
render::kind(def.kind)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `Module`-kind unit was declared with `program`. The semantic
|
||||
/// layer models the two alike, so the keyword is read off the text between
|
||||
/// the declaration's start and its name — only for the rare file whose text
|
||||
/// spells `endprogram` at all.
|
||||
fn is_program(project: &Project, path: &Path, def: &Def) -> bool {
|
||||
if !project.stamp(path).is_some_and(|stamp| stamp.program) {
|
||||
return false;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return false;
|
||||
};
|
||||
let head = text.get(def.decl_span.start as usize..def.name_span.start as usize);
|
||||
head.is_some_and(|head| head.split_whitespace().any(|word| word == "program"))
|
||||
}
|
||||
|
||||
/// 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();
|
||||
let name: Vec<char> = name.chars().collect();
|
||||
// Classic two-pointer match with one backtrack point per `*`.
|
||||
let (mut p, mut n, mut star, mut resume) = (0, 0, None, 0);
|
||||
while n < name.len() {
|
||||
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
|
||||
p += 1;
|
||||
n += 1;
|
||||
} else if p < pattern.len() && pattern[p] == '*' {
|
||||
star = Some(p);
|
||||
resume = n;
|
||||
p += 1;
|
||||
} else if let Some(at) = star {
|
||||
p = at + 1;
|
||||
resume += 1;
|
||||
n = resume;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
fn list_units(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let mut all = matching_units(project, args);
|
||||
// A glob names something the agent expects to exist — often a file it
|
||||
// has just written — so a miss walks once before it is believed.
|
||||
if all.is_empty() && args.str("glob").is_some() && project.ensure_walked_for_miss() {
|
||||
all = matching_units(project, args);
|
||||
}
|
||||
let (shown, rest) =
|
||||
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = shown
|
||||
.iter()
|
||||
.map(|u| (u.file.clone(), format!("{} {} {}", u.kind, u.name, u.line)))
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if all.is_empty() {
|
||||
text = "no units match\n".to_string();
|
||||
}
|
||||
let structured: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|u| json!({ "name": u.name, "kind": u.kind, "file": u.file, "line": u.line }))
|
||||
.collect();
|
||||
Ok(Answer { text, structured: json!({ "units": structured, "total": all.len() }) })
|
||||
}
|
||||
|
||||
/// The units `list_units`'s `kind` and `glob` select.
|
||||
fn matching_units(project: &Project, args: &Args) -> Vec<Unit> {
|
||||
units(project)
|
||||
.into_iter()
|
||||
.filter(|unit| args.str("kind").is_none_or(|kind| unit.kind == kind))
|
||||
.filter(|unit| args.str("glob").is_none_or(|glob| glob_match(glob, &unit.name)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn project_overview(project: &mut Project, _: &Args) -> Result<Answer, String> {
|
||||
let overview = Overview::of(project);
|
||||
Ok(Answer { text: overview.text(), structured: overview.json() })
|
||||
}
|
||||
|
||||
/// What `project_overview` reports, gathered once and rendered twice.
|
||||
struct Overview {
|
||||
roots: Vec<String>,
|
||||
config: Option<String>,
|
||||
filelist: Option<String>,
|
||||
files: usize,
|
||||
skipped_large: usize,
|
||||
by_kind: Vec<(&'static str, usize)>,
|
||||
build_ms: u128,
|
||||
age_s: u64,
|
||||
tops: Vec<String>,
|
||||
more_tops: usize,
|
||||
largest: Vec<(String, u64)>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Overview {
|
||||
fn of(project: &Project) -> Overview {
|
||||
let all = units(project);
|
||||
let kinds = ["module", "interface", "package", "class", "program"];
|
||||
let by_kind = kinds
|
||||
.iter()
|
||||
.map(|&kind| (kind, all.iter().filter(|u| u.kind == kind).count()))
|
||||
.collect();
|
||||
let tops = top_modules(project.index());
|
||||
let (shown, more_tops) = render::page(&tops, 0, DEFAULT_LIMIT);
|
||||
let (config, config_problem) = project.config();
|
||||
let discovery = project.discovery();
|
||||
let (build, age) = project.timing();
|
||||
let mut warnings: Vec<String> = discovery.warnings.clone();
|
||||
warnings.extend(config_problem.map(str::to_string));
|
||||
warnings.extend(project.unreadable().iter().cloned());
|
||||
Overview {
|
||||
roots: project.roots().iter().map(|r| r.display().to_string()).collect(),
|
||||
config: config.source.as_ref().map(|path| path.display().to_string()),
|
||||
filelist: discovery.filelist.as_ref().map(|path| path.display().to_string()),
|
||||
files: project.files().count(),
|
||||
skipped_large: discovery.skipped_large,
|
||||
by_kind,
|
||||
build_ms: build.as_millis(),
|
||||
age_s: age.as_secs(),
|
||||
tops: shown.to_vec(),
|
||||
more_tops,
|
||||
largest: largest_files(project, 10),
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let mut text = format!("roots: {}\n", self.roots.join(", "));
|
||||
text.push_str(&format!("config: {}\n", self.config.as_deref().unwrap_or("none")));
|
||||
text.push_str(&format!(
|
||||
"filelist: {}\n",
|
||||
self.filelist.as_deref().unwrap_or("none (walked)")
|
||||
));
|
||||
text.push_str(&format!(
|
||||
"files: {} indexed, {} over 1 MiB skipped\n",
|
||||
self.files, self.skipped_large
|
||||
));
|
||||
let counts: Vec<String> =
|
||||
self.by_kind.iter().map(|(kind, n)| format!("{n} {kind}")).collect();
|
||||
text.push_str(&format!("units: {}\n", counts.join(", ")));
|
||||
text.push_str(&format!(
|
||||
"index: built in {} ms, last changed {} s ago\n",
|
||||
self.build_ms, self.age_s
|
||||
));
|
||||
text.push_str(&format!("top: {}\n", self.tops.join(" ")));
|
||||
render::more(&mut text, self.more_tops);
|
||||
text.push_str("largest:\n");
|
||||
let rows: Vec<Vec<String>> =
|
||||
self.largest.iter().map(|(file, size)| vec![size.to_string(), file.clone()]).collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
for warning in self.warnings.iter().take(10) {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
render::more(&mut text, self.warnings.len().saturating_sub(10));
|
||||
text
|
||||
}
|
||||
|
||||
fn json(&self) -> Value {
|
||||
let units: serde_json::Map<String, Value> =
|
||||
self.by_kind.iter().map(|(kind, n)| (kind.to_string(), json!(n))).collect();
|
||||
let largest: Vec<Value> = self
|
||||
.largest
|
||||
.iter()
|
||||
.map(|(file, bytes)| json!({ "file": file, "bytes": bytes }))
|
||||
.collect();
|
||||
json!({
|
||||
"roots": self.roots,
|
||||
"config": self.config,
|
||||
"filelist": self.filelist,
|
||||
"files": self.files,
|
||||
"skipped_large": self.skipped_large,
|
||||
"units": units,
|
||||
"index_build_ms": self.build_ms as u64,
|
||||
"index_age_s": self.age_s,
|
||||
"top_modules": self.tops,
|
||||
"more_top_modules": self.more_tops,
|
||||
"largest_files": largest,
|
||||
"warnings": self.warnings,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Modules (programs included) nothing in the index instantiates, by name.
|
||||
fn top_modules(index: &WorkspaceIndex) -> Vec<String> {
|
||||
let mut tops: Vec<String> = index
|
||||
.instantiable_units()
|
||||
.filter(|(_, def)| def.kind == SymbolKind::Module)
|
||||
.filter(|(name, _)| index.instantiations_of(name).is_empty())
|
||||
.map(|(name, _)| name.to_string())
|
||||
.collect();
|
||||
tops.dedup();
|
||||
tops
|
||||
}
|
||||
|
||||
/// The `n` largest indexed files, largest first.
|
||||
fn largest_files(project: &Project, n: usize) -> Vec<(String, u64)> {
|
||||
let mut sizes: Vec<(u64, &Path)> =
|
||||
project.files().map(|(path, stamp)| (stamp.size, path.as_path())).collect();
|
||||
sizes.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1)));
|
||||
sizes.into_iter().take(n).map(|(size, path)| (project.relative(path), size)).collect()
|
||||
}
|
||||
|
||||
fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let path = project.resolve(args.str("file").unwrap_or(""))?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let depth = args.count("depth", usize::MAX);
|
||||
let mut rows: Vec<(usize, String, &'static str, u32, u32)> = Vec::new();
|
||||
flatten(&analysis, &analysis.semantics.document_symbols(), 0, depth, &mut rows);
|
||||
let (shown, rest) =
|
||||
render::page(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let file = project.relative(&path);
|
||||
let mut text = format!("{file}\n");
|
||||
let errors = &analysis.diagnostics;
|
||||
if let Some(first) = errors.first() {
|
||||
text.push_str(&format!(
|
||||
"parse errors: {} (first {}:{} {})\n",
|
||||
errors.len(),
|
||||
first.line,
|
||||
first.col,
|
||||
first.message
|
||||
));
|
||||
}
|
||||
for (level, name, kind, first, last) in shown {
|
||||
let indent = " ".repeat(level + 1);
|
||||
text.push_str(&format!("{indent}{kind} {name} {}\n", render::lines(*first, *last)));
|
||||
}
|
||||
render::more(&mut text, rest);
|
||||
let symbols: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|(level, name, kind, first, last)| {
|
||||
json!({ "name": name, "kind": kind, "depth": level + 1, "lines": [first, last] })
|
||||
})
|
||||
.collect();
|
||||
let parse_errors: Vec<Value> = errors
|
||||
.iter()
|
||||
.map(|e| json!({ "line": e.line, "col": e.col, "message": e.message }))
|
||||
.collect();
|
||||
let structured = json!({
|
||||
"file": file, "parse_errors": parse_errors, "symbols": symbols, "total": rows.len(),
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The outline tree in pre-order, each node with its depth and line range.
|
||||
fn flatten(
|
||||
analysis: &crate::project::Analysis,
|
||||
nodes: &[DocumentSymbol],
|
||||
level: usize,
|
||||
depth: usize,
|
||||
out: &mut Vec<(usize, String, &'static str, u32, u32)>,
|
||||
) {
|
||||
if level >= depth {
|
||||
return;
|
||||
}
|
||||
for node in nodes {
|
||||
let Some(symbol) = analysis.semantics.symbol(node.symbol) else {
|
||||
continue;
|
||||
};
|
||||
let (first, last) = analysis.line_span(symbol.decl_span.start, symbol.decl_span.end);
|
||||
out.push((level, symbol.name.clone(), render::kind(symbol.kind), first, last));
|
||||
flatten(analysis, &node.children, level + 1, depth, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn search_symbols(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let query = args.str("query").unwrap_or("");
|
||||
// A miss may be a file written since the last walk: walk once, then answer.
|
||||
if project.index().workspace_symbols(query).is_empty() {
|
||||
project.ensure_walked_for_miss();
|
||||
}
|
||||
let index = project.index();
|
||||
let hits = index.workspace_symbols(query);
|
||||
let (shown, rest) =
|
||||
render::page(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let mut entries = Vec::new();
|
||||
let mut structured = Vec::new();
|
||||
for hit in shown {
|
||||
let name = match hit.container {
|
||||
Some(unit) => format!("{unit}{}{}", separator(index, unit), hit.name),
|
||||
None => hit.name.to_string(),
|
||||
};
|
||||
let file = project.relative(index.path(hit.def.file).unwrap_or(Path::new("")));
|
||||
// A line and no column: the index records a client (UTF-16) column
|
||||
// for units only, and every column this server prints is a byte one.
|
||||
let line = hit.def.lines.name;
|
||||
entries.push((file.clone(), format!("{} {name} {line}", render::kind(hit.def.kind))));
|
||||
structured.push(json!({
|
||||
"name": name, "kind": render::kind(hit.def.kind), "file": file, "line": line,
|
||||
}));
|
||||
}
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if hits.is_empty() {
|
||||
text = "no symbols match\n".to_string();
|
||||
}
|
||||
Ok(Answer { text, structured: json!({ "symbols": structured, "total": hits.len() }) })
|
||||
}
|
||||
|
||||
/// How a member is spelled after its unit: `unit.x` for a module or
|
||||
/// interface (a hierarchical name), `unit::x` for a package or a class —
|
||||
/// including a class the index holds only as a package member.
|
||||
fn separator(index: &WorkspaceIndex, unit: &str) -> &'static str {
|
||||
match index.units(unit).first().map(|def| def.kind) {
|
||||
Some(kind) if kind.is_instantiable() => ".",
|
||||
_ => "::",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::glob_match;
|
||||
|
||||
#[test]
|
||||
fn globs_match_runs_and_single_characters() {
|
||||
assert!(glob_match("prim_*", "prim_fifo_sync"));
|
||||
assert!(glob_match("*fifo*", "prim_fifo_sync"));
|
||||
assert!(glob_match("a?c", "abc"));
|
||||
assert!(glob_match("*", ""));
|
||||
assert!(!glob_match("a?c", "ac"));
|
||||
assert!(!glob_match("prim_*_async", "prim_fifo_sync"));
|
||||
assert!(glob_match("*_sync", "prim_fifo_sync"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! `read_item`: one item's exact text, sliced out of its file — a module, a
|
||||
//! function, a declaration, an instance, or an unlabelled `always` block
|
||||
//! named by the line it covers.
|
||||
//!
|
||||
//! The slicing rule is the one the M4 structural edits will replace by, so
|
||||
//! it lives here on its own: an item is the parser's `Item` node (its
|
||||
//! attributes included, its leading comments not) that declares the name,
|
||||
//! or — for a declaration a larger construct only *contains* (an ANSI port
|
||||
//! in a module header, a function argument) — the declaration's own span.
|
||||
|
||||
use serde_json::json;
|
||||
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::Symbol;
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
pub const READ_ITEM: Tool = Tool {
|
||||
name: "read_item",
|
||||
title: "Read one item",
|
||||
description: "The exact source text and 1-based line range of one item in a file: `name`, `kind:name` (e.g. `function:crc`), `name@LINE` when a name is declared twice, or `always@LINE` / `initial@LINE` / `final@LINE` / `assign@LINE` for the unlabelled block or assignment covering that line (`@LINE` is the last `@` followed only by digits, so `\\a@b@1` is `\\a@b` on line 1). Prefer it over reading the whole file; outline shows what there is.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file, relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "item",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "`name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: read_item,
|
||||
};
|
||||
|
||||
/// The keywords that name an unlabelled item by the line it covers.
|
||||
const BY_LINE: &[&str] = &["always", "initial", "final", "assign"];
|
||||
|
||||
fn read_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let path = project.resolve(args.str("file").unwrap_or(""))?;
|
||||
let file = project.relative(&path);
|
||||
let analysis = project.analysis(&path)?;
|
||||
let selector = args.str("item").unwrap_or("").trim();
|
||||
let (kind, span) =
|
||||
select(&analysis, selector).map_err(|problem| format!("{problem} in `{file}`."))?;
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
let body = analysis.slice(span.start, span.end);
|
||||
let mut text = format!("{file}:{}\n{body}", render::lines(first, last));
|
||||
if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
let structured = json!({
|
||||
"file": file, "item": selector, "kind": kind, "lines": [first, last], "text": body,
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The item `selector` names in this file: its kind word and byte span, or
|
||||
/// the reason there is not exactly one.
|
||||
pub fn select(analysis: &Analysis, selector: &str) -> Result<(&'static str, TextRange), String> {
|
||||
let (head, line) = split_line(selector)?;
|
||||
if let (Some(keyword), Some(line)) = (BY_LINE.iter().find(|k| **k == head), line) {
|
||||
return by_line(analysis, keyword, line).map(|span| (*keyword, span));
|
||||
}
|
||||
let (kind, name) = split_kind(head);
|
||||
let symbol = match by_name(analysis, name, kind, line) {
|
||||
// An escaped identifier may itself end in `@digits` (`\a@12 `): when
|
||||
// the `@LINE` reading finds nothing, the whole spelling is the name.
|
||||
Err(problem) if line.is_some() && name.starts_with('\\') => {
|
||||
let (_, whole) = split_kind(selector);
|
||||
by_name(analysis, whole, kind, None).map_err(|_| problem)?
|
||||
}
|
||||
answer => answer?,
|
||||
};
|
||||
Ok((render::kind(symbol.kind), item_span(analysis, symbol)))
|
||||
}
|
||||
|
||||
/// `kind:` is a prefix only when it is one of the kind words; otherwise the
|
||||
/// colon is part of the name (`\k:l`, an escaped identifier).
|
||||
fn split_kind(head: &str) -> (Option<&str>, &str) {
|
||||
match head.split_once(':') {
|
||||
Some((kind, name)) if render::is_kind_word(kind) => (Some(kind), name),
|
||||
_ => (None, head),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `head@LINE` at the last `@` when only digits follow it; any other
|
||||
/// `@` belongs to the name (`\a@b`).
|
||||
fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
|
||||
match selector.rsplit_once('@') {
|
||||
Some((head, digits))
|
||||
if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) =>
|
||||
{
|
||||
let line = digits
|
||||
.parse::<u32>()
|
||||
.map_err(|_| format!("`{selector}`: line {digits} is out of range"))?;
|
||||
Ok((head, Some(line)))
|
||||
}
|
||||
_ => Ok((selector, None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one declaration of `name` matching the optional kind word and line.
|
||||
fn by_name<'a>(
|
||||
analysis: &'a Analysis,
|
||||
name: &str,
|
||||
kind: Option<&str>,
|
||||
line: Option<u32>,
|
||||
) -> Result<&'a Symbol, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let matches: Vec<&Symbol> = semantics
|
||||
.symbols_named(name)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.filter(|s| kind.is_none_or(|kind| render::kind(s.kind) == kind))
|
||||
.filter(|s| line.is_none_or(|line| analysis.lines.line_col(s.name_span.start).0 == line))
|
||||
.collect();
|
||||
match matches.as_slice() {
|
||||
[one] => Ok(one),
|
||||
[] => Err(format!("no declaration matches `{name}`{}{}", on_kind(kind), on_line(line))),
|
||||
many => {
|
||||
let options: Vec<String> = many
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let line = analysis.lines.line_col(s.name_span.start).0;
|
||||
format!("{}:{name}@{line}", render::kind(s.kind))
|
||||
})
|
||||
.collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); name one",
|
||||
many.len(),
|
||||
options.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_kind(kind: Option<&str>) -> String {
|
||||
kind.map_or(String::new(), |kind| format!(" of kind `{kind}`"))
|
||||
}
|
||||
|
||||
fn on_line(line: Option<u32>) -> String {
|
||||
line.map_or(String::new(), |line| format!(" on line {line}"))
|
||||
}
|
||||
|
||||
/// The span of the item that declares `symbol` (see the module comment).
|
||||
fn item_span(analysis: &Analysis, symbol: &Symbol) -> TextRange {
|
||||
let target = symbol.detail_span.unwrap_or(symbol.name_span);
|
||||
let mut innermost = None;
|
||||
innermost_item(&analysis.tree.items, target, &mut innermost);
|
||||
match innermost {
|
||||
Some(item) if !is_container(&item.kind) || item.span.end == symbol.decl_span.end => {
|
||||
item.span
|
||||
}
|
||||
_ => symbol.detail_span.unwrap_or(symbol.decl_span),
|
||||
}
|
||||
}
|
||||
|
||||
/// Items that hold other declarations: one of these is the answer only when
|
||||
/// it is the symbol's own declaration, not merely the construct around it.
|
||||
fn is_container(kind: &ItemKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
ItemKind::Module(_)
|
||||
| ItemKind::Package { .. }
|
||||
| ItemKind::Class(_)
|
||||
| ItemKind::Function(_)
|
||||
| ItemKind::Task(_)
|
||||
| ItemKind::Always { .. }
|
||||
| ItemKind::Initial(_)
|
||||
| ItemKind::Final(_)
|
||||
| ItemKind::GenerateRegion { .. }
|
||||
| ItemKind::GenIf(_)
|
||||
| ItemKind::GenFor(_)
|
||||
| ItemKind::GenCase(_)
|
||||
| ItemKind::GenBlock(_)
|
||||
| ItemKind::Covergroup(_)
|
||||
| ItemKind::PropSeqDecl(_)
|
||||
| ItemKind::Clocking(_)
|
||||
| ItemKind::Constraint(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// The deepest item whose span contains `target`.
|
||||
fn innermost_item<'t>(items: &'t [Item], target: TextRange, found: &mut Option<&'t Item>) {
|
||||
for item in items {
|
||||
if item.span.start <= target.start && target.end <= item.span.end {
|
||||
*found = Some(item);
|
||||
for children in child_items(&item.kind) {
|
||||
innermost_item(children, target, found);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The item lists nested directly inside one item.
|
||||
pub(super) fn child_items(kind: &ItemKind) -> Vec<&[Item]> {
|
||||
match kind {
|
||||
ItemKind::Module(module) => vec![&module.items],
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => vec![items],
|
||||
ItemKind::Class(class) => vec![&class.items],
|
||||
ItemKind::GenBlock(block) => vec![&block.items],
|
||||
ItemKind::GenFor(generate) => vec![&generate.body.items],
|
||||
ItemKind::GenCase(generate) => {
|
||||
generate.items.iter().map(|arm| arm.body.items.as_slice()).collect()
|
||||
}
|
||||
ItemKind::GenIf(generate) => gen_if_items(generate),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_if_items(generate: &GenIf) -> Vec<&[Item]> {
|
||||
let mut out: Vec<&[Item]> = vec![&generate.then.items];
|
||||
match generate.els.as_deref() {
|
||||
Some(GenElse::If(_, nested)) => out.extend(gen_if_items(nested)),
|
||||
Some(GenElse::Block(GenBlock { items, .. })) => out.push(items),
|
||||
None => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The unlabelled `keyword` item whose lines cover `line`.
|
||||
fn by_line(analysis: &Analysis, keyword: &str, line: u32) -> Result<TextRange, String> {
|
||||
let mut hits = Vec::new();
|
||||
collect_keyword(&analysis.tree.items, keyword, &mut hits);
|
||||
hits.into_iter()
|
||||
.find(|span| {
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
first <= line && line <= last
|
||||
})
|
||||
.ok_or_else(|| format!("no `{keyword}` item covers line {line}"))
|
||||
}
|
||||
|
||||
fn collect_keyword(items: &[Item], keyword: &str, out: &mut Vec<TextRange>) {
|
||||
for item in items {
|
||||
let hit = match &item.kind {
|
||||
ItemKind::Always { kw, .. } => kw.starts_with(keyword),
|
||||
ItemKind::Initial(_) => keyword == "initial",
|
||||
ItemKind::Final(_) => keyword == "final",
|
||||
ItemKind::ContAssign(_) => keyword == "assign",
|
||||
_ => false,
|
||||
};
|
||||
if hit {
|
||||
out.push(item.span);
|
||||
}
|
||||
for children in child_items(&item.kind) {
|
||||
collect_keyword(children, keyword, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SRC: &str = r"module m #(parameter int W = 8) (input logic clk, input logic [W-1:0] d);
|
||||
logic [W-1:0] q, r;
|
||||
always_ff @(posedge clk)
|
||||
q <= d;
|
||||
function automatic int f(int a);
|
||||
return a;
|
||||
endfunction
|
||||
sub u_sub (.*);
|
||||
endmodule
|
||||
module n; logic q; endmodule
|
||||
";
|
||||
|
||||
fn text(selector: &str) -> Result<String, String> {
|
||||
let analysis = Analysis::of(SRC.to_string());
|
||||
select(&analysis, selector)
|
||||
.map(|(_, span)| analysis.slice(span.start, span.end).to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_slices_its_whole_item_and_a_contained_declaration_only_itself() {
|
||||
assert!(text("m").unwrap().starts_with("module m #("));
|
||||
assert!(text("m").unwrap().ends_with("endmodule"));
|
||||
assert_eq!(
|
||||
text("f").unwrap(),
|
||||
"function automatic int f(int a);\n return a;\nendfunction"
|
||||
);
|
||||
assert_eq!(text("a").unwrap(), "int a");
|
||||
assert_eq!(text("d").unwrap(), "input logic [W-1:0] d");
|
||||
assert_eq!(text("r").unwrap(), "logic [W-1:0] q, r;");
|
||||
assert_eq!(text("u_sub").unwrap(), "sub u_sub (.*);");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_parameter_and_a_non_ansi_port_slice_their_own_declarations() {
|
||||
assert_eq!(text("W").unwrap(), "parameter int W = 8");
|
||||
let analysis =
|
||||
Analysis::of("module k (a, b);\n input [3:0] a;\n output b;\nendmodule\n".into());
|
||||
let (kind, span) = select(&analysis, "a").unwrap();
|
||||
assert_eq!((kind, analysis.slice(span.start, span.end)), ("port", "input [3:0] a;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_count_lines_the_same_way() {
|
||||
let analysis = Analysis::of(
|
||||
"module a;\r\n logic x;\r\n always_comb\r\n x = 1;\r\nendmodule\r\n".into(),
|
||||
);
|
||||
let (_, span) = select(&analysis, "x").unwrap();
|
||||
assert_eq!(analysis.line_span(span.start, span.end), (2, 2));
|
||||
let (_, block) = select(&analysis, "always@4").unwrap();
|
||||
assert_eq!(analysis.line_span(block.start, block.end), (3, 4));
|
||||
assert_eq!(analysis.slice(block.start, block.end), "always_comb\r\n x = 1;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_names_an_unlabelled_block_and_disambiguates_a_name() {
|
||||
assert_eq!(text("always@4").unwrap(), "always_ff @(posedge clk)\n q <= d;");
|
||||
assert!(text("always@1").unwrap_err().contains("no `always` item covers line 1"));
|
||||
let ambiguous = text("q").unwrap_err();
|
||||
assert!(ambiguous.contains("var:q@2") && ambiguous.contains("var:q@10"), "{ambiguous}");
|
||||
assert_eq!(text("q@10").unwrap(), "logic q;");
|
||||
assert_eq!(text("var:q@2").unwrap(), "logic [W-1:0] q, r;");
|
||||
assert!(text("function:m").unwrap_err().contains("of kind `function`"));
|
||||
assert!(text("q@x").unwrap_err().contains("no declaration matches `q@x`"));
|
||||
assert!(text("q@99999999999").unwrap_err().contains("out of range"));
|
||||
assert!(text("nokind:q").unwrap_err().contains("no declaration matches `nokind:q`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_name_ending_in_at_digits_is_its_own_name_when_no_line_matches() {
|
||||
let analysis = Analysis::of("module \\a@12 (input z); endmodule\n".into());
|
||||
let (kind, span) = select(&analysis, "\\a@12").unwrap();
|
||||
assert_eq!(kind, "module");
|
||||
assert!(analysis.slice(span.start, span.end).starts_with("module \\a@12 "));
|
||||
let (_, by_kind) = select(&analysis, "module:\\a@12").unwrap();
|
||||
assert_eq!(by_kind, span);
|
||||
let refused = select(&analysis, "\\b@12").unwrap_err();
|
||||
assert!(refused.contains("`\\b` on line 12"), "{refused}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
//! The refactorings that are not "act at this cursor": `add_port` (a module
|
||||
//! and a declaration), `extract_module` (a line range and a new name), and
|
||||
//! `instantiate`, which writes nothing at all — it answers with the text of
|
||||
//! an instantiation for the agent to place.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{instantiation_plan, module_definition, Home, Layout, ModuleRef};
|
||||
|
||||
use super::edit::{enclosing, finish, whole_set, DRY_RUN};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
|
||||
pub const ADD_PORT: Tool = Tool {
|
||||
name: "add_port",
|
||||
title: "Add a port",
|
||||
description: "Add one ANSI port to a module and a connection for it to every instantiation in the project, verified before anything is written. Name the module by `module`, or by `file`+`line` inside its declaration; `declaration` is the port as written in the header (`input logic [7:0] cfg`). Refuses a port that exists, an ordered instantiation of a different length, and a list split by `ifdef`s. `dry_run` returns the diff.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "module",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The module's name (declared once in the project).",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Instead of `module`: the file declaring it, with `line`.",
|
||||
},
|
||||
Param {
|
||||
name: "line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based line inside the module's declaration in `file`.",
|
||||
},
|
||||
Param {
|
||||
name: "declaration",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "One directed ANSI port declaration, e.g. `input logic [7:0] cfg`.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: true,
|
||||
handler: add_port,
|
||||
};
|
||||
|
||||
pub const EXTRACT_MODULE: Tool = Tool {
|
||||
name: "extract_module",
|
||||
title: "Extract lines into a module",
|
||||
description: "Move the whole items on lines `start_line`..`end_line` of a module into a new module `new_name`, whose ports come from the dataflow across the selection, and instantiate it in their place; verified before anything is written. `home: new_file` (default) creates `new_name.sv` beside the file (refused if it exists); `same_file` writes it below the module. Refuses a partial item and names it cannot carry. `dry_run` returns the diff.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file holding the module, relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "start_line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: true,
|
||||
description: "First line of the selection (1-based).",
|
||||
},
|
||||
Param {
|
||||
name: "end_line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: true,
|
||||
description: "Last line of the selection (1-based, included).",
|
||||
},
|
||||
Param {
|
||||
name: "new_name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The new module's name; nothing in the project may declare it yet.",
|
||||
},
|
||||
Param {
|
||||
name: "home",
|
||||
ty: Ty::Enum(&["new_file", "same_file"]),
|
||||
required: false,
|
||||
description: "Where the new module goes: `new_file` (default) or `same_file`.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: true,
|
||||
handler: extract_module,
|
||||
};
|
||||
|
||||
pub const INSTANTIATE: Tool = Tool {
|
||||
name: "instantiate",
|
||||
title: "Instantiation template",
|
||||
description: "The text of an instantiation of module `name` for the agent to place — parameters with their defaults, the instance name, and each port connected to a same-named signal (`named`) or as `.*` (`wildcard`). Writes nothing. Refuses a module that is not indexed or is declared twice (pass `file` to pick one).",
|
||||
params: &[
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The module (or interface) to instantiate.",
|
||||
},
|
||||
Param {
|
||||
name: "style",
|
||||
ty: Ty::Enum(&["named", "wildcard"]),
|
||||
required: false,
|
||||
description: "`named` connections (default) or `.*`.",
|
||||
},
|
||||
Param {
|
||||
name: "with_params",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Write the `#( … )` parameter overrides (default true).",
|
||||
},
|
||||
Param {
|
||||
name: "instance",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The instance name (default `u_<name>`).",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The file declaring the module, when more than one does.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: instantiate,
|
||||
};
|
||||
|
||||
fn add_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let declaration = args.str("declaration").unwrap_or_default();
|
||||
match (args.str("module"), args.str("file"), args.int("line")) {
|
||||
(Some(name), None, None) => {
|
||||
let set = whole_set(project, None, &[name.to_string()])?;
|
||||
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(name), declaration)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
(None, Some(file), Some(line)) => {
|
||||
let path = project.resolve(file)?;
|
||||
let offset = line_start(project, &path, line)?;
|
||||
let names = enclosing(&*project.analysis(&path)?, offset);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let module = ModuleRef::At { file: &path, offset };
|
||||
let edit = vlog_refactor::add_port(&set.files, module, declaration)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
_ => Err("name the module by `module`, or by `file` and `line`, not both.".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte offset where 1-based `line` of `path` starts; `end` asks for
|
||||
/// where it ends instead (its line ending excluded).
|
||||
fn line_offset(project: &mut Project, path: &Path, line: i64, end: bool) -> Result<u32, String> {
|
||||
let analysis = project.analysis(path)?;
|
||||
let count = analysis.lines.line_count();
|
||||
let range = u32::try_from(line).ok().and_then(|line| analysis.lines.line_range(line));
|
||||
let Some(range) = range else {
|
||||
let file = project.relative(path);
|
||||
return Err(format!("line {line} is past the end of `{file}` ({count} lines)."));
|
||||
};
|
||||
Ok(if end { range.end } else { range.start })
|
||||
}
|
||||
|
||||
fn line_start(project: &mut Project, path: &Path, line: i64) -> Result<u32, String> {
|
||||
line_offset(project, path, line, false)
|
||||
}
|
||||
|
||||
fn extract_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let file = args.str("file").unwrap_or_default();
|
||||
let path = project.resolve(file)?;
|
||||
let (first, last) = (args.int("start_line").unwrap_or(1), args.int("end_line").unwrap_or(1));
|
||||
if last < first {
|
||||
return Err(format!("`end_line` {last} is before `start_line` {first}."));
|
||||
}
|
||||
let start = line_start(project, &path, first)?;
|
||||
let end = line_offset(project, &path, last, true)?;
|
||||
let home = match args.str("home") {
|
||||
Some("same_file") => Home::SameFile,
|
||||
_ => Home::NewFile,
|
||||
};
|
||||
let new_name = args.str("new_name").unwrap_or_default();
|
||||
let names = enclosing(&*project.analysis(&path)?, start);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = vlog_refactor::extract_module(&set.files, &path, start, end, new_name, home)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
|
||||
fn instantiate(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").unwrap_or_default();
|
||||
let path = declaring_file(project, name, args.str("file"))?;
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("cannot read `{}`: {e}", project.relative(&path)))?;
|
||||
let mut plan = instantiation_plan(name, &text, None)?;
|
||||
if !args.flag("with_params", true) {
|
||||
plan.params.clear();
|
||||
}
|
||||
let wildcard = args.str("style") == Some("wildcard");
|
||||
if wildcard {
|
||||
plan.ports.clear();
|
||||
}
|
||||
let instance = match args.str("instance") {
|
||||
Some(instance) => identifier(instance)?.to_string(),
|
||||
None => plan.instance_name(),
|
||||
};
|
||||
// `render_with` numbers the fill-ins: each parameter, then the instance.
|
||||
let instance_hole = plan.params.len() + 1;
|
||||
let mut hole = |n: usize, default: &str| {
|
||||
if n == instance_hole {
|
||||
instance.clone()
|
||||
} else {
|
||||
default.into()
|
||||
}
|
||||
};
|
||||
let mut skeleton = plan.render_with(&layout(project), &mut hole);
|
||||
if wildcard {
|
||||
// With no ports the skeleton ends `u_x ();`.
|
||||
skeleton.truncate(skeleton.len() - "();".len());
|
||||
skeleton.push_str("(.*);");
|
||||
}
|
||||
skeleton.push('\n');
|
||||
let file = project.relative(&path);
|
||||
let structured = serde_json::json!({
|
||||
"module": name, "file": file, "text": skeleton, "warnings": plan.warnings,
|
||||
});
|
||||
let mut text = skeleton;
|
||||
for warning in &plan.warnings {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The one file declaring module `name` — `file` when given (it must be a
|
||||
/// file the index says declares it), else the index's single answer, after
|
||||
/// one walk for a module written since the last one.
|
||||
fn declaring_file(
|
||||
project: &mut Project,
|
||||
name: &str,
|
||||
file: Option<&str>,
|
||||
) -> Result<PathBuf, String> {
|
||||
if let Some(file) = file {
|
||||
let path = project.resolve(file)?;
|
||||
let declares = project.index().units(name).iter().any(|def| {
|
||||
def.kind.is_instantiable() && project.index().path(def.file) == Some(path.as_path())
|
||||
});
|
||||
if !declares {
|
||||
return Err(format!("`{file}` declares no module named `{name}`."));
|
||||
}
|
||||
return Ok(path);
|
||||
}
|
||||
let found = module_definition(project.index(), name).map(Path::to_path_buf);
|
||||
match found {
|
||||
Err(_) if project.ensure_walked_for_miss() => {
|
||||
module_definition(project.index(), name).map(Path::to_path_buf)
|
||||
}
|
||||
found => found,
|
||||
}
|
||||
.map_err(|why| {
|
||||
if why.contains("more than one") {
|
||||
format!("{why} Pass `file` to pick one.")
|
||||
} else {
|
||||
why
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `name`, when it is one SystemVerilog identifier: a simple one
|
||||
/// (`[A-Za-z_][A-Za-z0-9_$]*`, not a keyword) or an escaped one (`\`, then
|
||||
/// printable non-space characters, then one space). Anything else would
|
||||
/// render text that does not parse.
|
||||
fn identifier(name: &str) -> Result<&str, String> {
|
||||
let simple = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
|
||||
&& !vlog_parser::token::is_keyword(name);
|
||||
let escaped = name
|
||||
.strip_prefix('\\')
|
||||
.and_then(|rest| rest.strip_suffix(' '))
|
||||
.is_some_and(|body| !body.is_empty() && body.chars().all(|c| c.is_ascii_graphic()));
|
||||
if simple || escaped {
|
||||
return Ok(name);
|
||||
}
|
||||
Err(format!(
|
||||
"`instance` must be one identifier — `[A-Za-z_][A-Za-z0-9_$]*` and not a keyword, or an escaped identifier `\\name ` ending in one space; `{name}` is not."
|
||||
))
|
||||
}
|
||||
|
||||
/// Column zero, one indentation step as the project's lucisv.toml spells it.
|
||||
fn layout(project: &Project) -> Layout {
|
||||
let indent =
|
||||
project.config().0.indent.unwrap_or(vlog_formatter::Config::default().indent_width);
|
||||
Layout { base: String::new(), step: " ".repeat(indent) }
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! The selector `definition` and `references` share: a position (`file` +
|
||||
//! `line` + `col`, or `file` + `line` + the `name` written on that line), a
|
||||
//! name in a file (`file` + `name`), or a bare `name` (with an optional
|
||||
//! `unit`) looked up in the index. A position is picked by **token**, never
|
||||
//! by text, so a comment, a string or a macro argument cannot stand in for
|
||||
//! the code; and a pick that would be a guess is refused with the choices.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{Definition, ExternalResolutions, Symbol};
|
||||
|
||||
use super::Args;
|
||||
use crate::project::{Analysis, Project};
|
||||
|
||||
/// What a selector points at.
|
||||
pub(super) enum Target {
|
||||
/// A byte position in a file.
|
||||
At { path: PathBuf, analysis: Rc<Analysis>, offset: u32 },
|
||||
/// A name to look up in the index, optionally inside one unit.
|
||||
Named { name: String, unit: Option<String> },
|
||||
}
|
||||
|
||||
/// Read the selector; the refusal says which combination is wanted.
|
||||
pub(super) fn target(project: &mut Project, args: &Args) -> Result<Target, String> {
|
||||
let Some(file) = args.str("file") else {
|
||||
if args.int("line").is_some() || args.int("col").is_some() {
|
||||
return Err("`line` and `col` need `file`.".into());
|
||||
}
|
||||
let Some(name) = args.str("name").filter(|name| !name.is_empty()) else {
|
||||
return Err("give `file` with `line` and `col` (or `name`), or a `name`.".into());
|
||||
};
|
||||
let unit = args.str("unit").map(str::to_string);
|
||||
return Ok(Target::Named { name: name.to_string(), unit });
|
||||
};
|
||||
if args.str("unit").is_some() {
|
||||
return Err("`unit` belongs to the by-name form; drop `file`, `line` and `col`.".into());
|
||||
}
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let shown = project.relative(&path);
|
||||
let offset =
|
||||
offset_in(project, &shown, &analysis, args).map_err(|e| format!("{e} (in `{file}`)"))?;
|
||||
Ok(Target::At { path, analysis, offset })
|
||||
}
|
||||
|
||||
/// The byte offset the position arguments name in one file.
|
||||
fn offset_in(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
args: &Args,
|
||||
) -> Result<u32, String> {
|
||||
let name = args.str("name").filter(|name| !name.is_empty());
|
||||
let line = args.int("line").map(|line| u32::try_from(line).unwrap_or(u32::MAX));
|
||||
let col = args.int("col").map(|col| u32::try_from(col).unwrap_or(u32::MAX));
|
||||
match (line, col, name) {
|
||||
(Some(line), Some(col), _) => at_column(analysis, line, col),
|
||||
(Some(line), None, Some(name)) => on_line(analysis, line, name),
|
||||
(Some(_), None, None) => Err("with `line`, give `col` or the `name` on that line".into()),
|
||||
(None, Some(_), _) => Err("`col` needs `line`".into()),
|
||||
(None, None, Some(name)) => first_occurrence(project, file, analysis, name),
|
||||
(None, None, None) => Err("say what: `line` with `col` or `name`, or a `name`".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `line:col`, refused when the line does not exist or the column lies past
|
||||
/// its end (one past the last byte is the end itself, and allowed).
|
||||
fn at_column(analysis: &Analysis, line: u32, col: u32) -> Result<u32, String> {
|
||||
let lines = analysis.lines.line_count();
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
return Err(format!("line {line} is past the end ({lines} lines)"));
|
||||
};
|
||||
let length = analysis.line_text(line).len() as u32;
|
||||
if col > length.saturating_add(1) {
|
||||
return Err(format!("line {line} is {length} bytes long; `col` {col} is past its end"));
|
||||
}
|
||||
Ok(range.start + col - 1)
|
||||
}
|
||||
|
||||
/// The first token on `line` that spells `name`: an identifier, or a macro
|
||||
/// use when `name` is written `` `NAME``. A name found only inside a macro
|
||||
/// call's argument text is refused — lucisv does not resolve those.
|
||||
fn on_line(analysis: &Analysis, line: u32, name: &str) -> Result<u32, String> {
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
return Err(format!("line {line} is past the end ({} lines)", analysis.lines.line_count()));
|
||||
};
|
||||
let touching =
|
||||
|| analysis.tokens.iter().filter(|t| t.span.end > range.start && t.span.start <= range.end);
|
||||
let wanted_macro = name.strip_prefix('`');
|
||||
let hit = touching().find(|token| match wanted_macro {
|
||||
Some(spelled) => token.is_macro() && macro_name(token) == Some(spelled),
|
||||
None => {
|
||||
token.kind == TokenKind::Ident && !token.is_macro() && token.text.trim_end() == name
|
||||
}
|
||||
});
|
||||
if let Some(token) = hit {
|
||||
return Ok(token.span.start.max(range.start));
|
||||
}
|
||||
let in_argument =
|
||||
touching().any(|t| t.is_macro() && super::source::word_in(&t.text, name).is_some());
|
||||
if wanted_macro.is_none() && in_argument {
|
||||
return Err(format!(
|
||||
"`{name}` on line {line} is inside a macro argument, which lucisv does not resolve; give `col` on a plain use"
|
||||
));
|
||||
}
|
||||
Err(format!("`{name}` is not written on line {line}"))
|
||||
}
|
||||
|
||||
/// Where `name` occurs in a file: its one declaration, else its uses when
|
||||
/// they all name one declaration, else its first macro use.
|
||||
fn first_occurrence(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
name: &str,
|
||||
) -> Result<u32, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let declared: Vec<&Symbol> =
|
||||
semantics.symbols_named(name).filter_map(|id| semantics.symbol(id)).collect();
|
||||
match declared.as_slice() {
|
||||
[one] => return Ok(one.name_span.start),
|
||||
[] => {}
|
||||
many => {
|
||||
let lines: Vec<String> = many
|
||||
.iter()
|
||||
.map(|symbol| analysis.lines.line_col(symbol.name_span.start).0.to_string())
|
||||
.collect();
|
||||
return Err(format!(
|
||||
"`{name}` is declared {} times (lines {}); add `line`",
|
||||
many.len(),
|
||||
lines.join(", ")
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(offset) = one_use(project, file, analysis, name)? {
|
||||
return Ok(offset);
|
||||
}
|
||||
let spelled = name.strip_prefix('`').unwrap_or(name);
|
||||
analysis
|
||||
.tokens
|
||||
.iter()
|
||||
.find(|token| token.is_macro() && macro_name(token) == Some(spelled))
|
||||
.map(|token| token.span.start)
|
||||
.ok_or_else(|| format!("`{name}` is not written here"))
|
||||
}
|
||||
|
||||
/// The first use of `name` in a file that declares none — refused, listing
|
||||
/// a line per declaration, when its uses name different declarations.
|
||||
fn one_use(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
name: &str,
|
||||
) -> Result<Option<u32>, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let mut uses = semantics.references().iter().filter(|reference| reference.name == name);
|
||||
let Some(first) = uses.next() else { return Ok(None) };
|
||||
let external = analysis.external(project.index());
|
||||
let mut targets: Vec<(u32, String)> = Vec::new();
|
||||
for reference in std::iter::once(first).chain(uses) {
|
||||
let offset = reference.name_span.start;
|
||||
let Some(target) = declared_at(project, file, analysis, &external, offset) else {
|
||||
continue;
|
||||
};
|
||||
if !targets.iter().any(|(_, known)| *known == target) {
|
||||
targets.push((analysis.lines.line_col(offset).0, target));
|
||||
}
|
||||
}
|
||||
if targets.len() > 1 {
|
||||
let listed: Vec<String> =
|
||||
targets.iter().map(|(line, target)| format!("line {line} → {target}")).collect();
|
||||
return Err(format!("`{name}` on {}; add `line`", listed.join(", ")));
|
||||
}
|
||||
Ok(Some(first.name_span.start))
|
||||
}
|
||||
|
||||
/// Where the use at `offset` is declared, as `file:line` (several joined
|
||||
/// with ` or `), or `None` when nothing resolves it.
|
||||
fn declared_at(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
external: &ExternalResolutions,
|
||||
offset: u32,
|
||||
) -> Option<String> {
|
||||
match external.definition_of(&analysis.semantics, offset)? {
|
||||
Definition::Local(symbol) => {
|
||||
Some(format!("{file}:{}", analysis.lines.line_col(symbol.name_span.start).0))
|
||||
}
|
||||
Definition::External(defs) => {
|
||||
let index = project.index();
|
||||
let sites: Vec<String> = defs
|
||||
.iter()
|
||||
.filter_map(|def| {
|
||||
let path = index.path(def.file)?;
|
||||
Some(format!("{}:{}", project.relative(path), def.lines.name))
|
||||
})
|
||||
.collect();
|
||||
(!sites.is_empty()).then(|| sites.join(" or "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The macro a use token names: `` `NAME(args) `` → `NAME`.
|
||||
pub(super) fn macro_name(token: &Token) -> Option<&str> {
|
||||
let rest = token.text.strip_prefix('`')?;
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$');
|
||||
let name = &rest[..end.unwrap_or(rest.len())];
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
//! Declaration sites read back off the disk: the navigation tools answer
|
||||
//! with `file:line:col`, the kind, and the declaration's own source line,
|
||||
//! for declarations in files no analysis is held for. One read per file per
|
||||
//! call ([`Texts`]); the index's spans are checked against the bytes before
|
||||
//! they are printed, so a stale span is omitted, never mislocated.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::render;
|
||||
|
||||
/// File texts read during one call, each with its line table.
|
||||
#[derive(Default)]
|
||||
pub struct Texts {
|
||||
held: HashMap<PathBuf, Option<(String, LineIndex)>>,
|
||||
}
|
||||
|
||||
impl Texts {
|
||||
/// The text of `path` and its line table, read on first use; `None` for
|
||||
/// a file that no longer reads as UTF-8.
|
||||
pub fn get(&mut self, path: &Path) -> Option<(&str, &LineIndex)> {
|
||||
let held = self.held.entry(path.to_path_buf()).or_insert_with(|| {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let lines = LineIndex::new(&text);
|
||||
Some((text, lines))
|
||||
});
|
||||
held.as_ref().map(|(text, lines)| (text.as_str(), lines))
|
||||
}
|
||||
|
||||
/// Keep a text the caller already read, so it is not read again.
|
||||
pub fn hold(&mut self, path: PathBuf, text: String) {
|
||||
let lines = LineIndex::new(&text);
|
||||
self.held.insert(path, Some((text, lines)));
|
||||
}
|
||||
}
|
||||
|
||||
/// One place a declaration (or a use) is written.
|
||||
pub struct Site {
|
||||
pub file: String,
|
||||
pub line: u32,
|
||||
pub col: u32,
|
||||
pub kind: &'static str,
|
||||
/// The source line, whitespace collapsed.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Site {
|
||||
/// The site of `span` in `text`: its 1-based line and byte column, and
|
||||
/// that line collapsed to one line of text.
|
||||
pub fn at(
|
||||
file: String,
|
||||
text: &str,
|
||||
lines: &LineIndex,
|
||||
span: TextRange,
|
||||
kind: &'static str,
|
||||
) -> Site {
|
||||
let (line, col) = lines.line_col(span.start);
|
||||
let source = lines
|
||||
.line_range(line)
|
||||
.and_then(|range| text.get(range.start as usize..range.end as usize))
|
||||
.unwrap_or("");
|
||||
Site { file, line, col, kind, text: render::one_line(source) }
|
||||
}
|
||||
|
||||
/// `file:line:col kind: text`.
|
||||
pub fn render(&self) -> String {
|
||||
format!("{}:{}:{} {}: {}", self.file, self.line, self.col, self.kind, self.text)
|
||||
}
|
||||
|
||||
pub fn json(&self) -> Value {
|
||||
json!({
|
||||
"file": self.file, "line": self.line, "col": self.col,
|
||||
"kind": self.kind, "text": self.text,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The site of an indexed span in `path`, when the file's bytes there still
|
||||
/// spell `name`; `shown` is the span whose line is printed (a non-ANSI port's
|
||||
/// body declaration rather than its header name).
|
||||
pub fn checked_site(
|
||||
project: &Project,
|
||||
texts: &mut Texts,
|
||||
path: &Path,
|
||||
name_span: TextRange,
|
||||
shown: TextRange,
|
||||
name: &str,
|
||||
kind: &'static str,
|
||||
) -> Option<Site> {
|
||||
let (text, lines) = texts.get(path)?;
|
||||
if text.get(name_span.as_range()) != Some(name) {
|
||||
return None;
|
||||
}
|
||||
Some(Site::at(project.relative(path), text, lines, shown, kind))
|
||||
}
|
||||
|
||||
/// Sites as a text answer (one per line, or `none_text`) and as JSON under
|
||||
/// `key`, with the total.
|
||||
pub fn answer(sites: &[Site], key: &str, none_text: &str) -> super::Answer {
|
||||
let mut text: String = sites.iter().map(|site| site.render() + "\n").collect();
|
||||
if sites.is_empty() {
|
||||
text = format!("{none_text}\n");
|
||||
}
|
||||
let listed: Vec<Value> = sites.iter().map(Site::json).collect();
|
||||
super::Answer { text, structured: json!({ key: listed, "total": sites.len() }) }
|
||||
}
|
||||
|
||||
/// `text` on one line, cut at `cap` characters with `…`.
|
||||
pub fn capped(text: &str, cap: usize) -> String {
|
||||
let flat = render::one_line(text);
|
||||
if flat.chars().count() <= cap {
|
||||
return flat;
|
||||
}
|
||||
let cut: String = flat.chars().take(cap).collect();
|
||||
format!("{cut}…")
|
||||
}
|
||||
|
||||
/// `text` with its `//` and `/* */` comments replaced by a space; string
|
||||
/// literals are kept whole.
|
||||
pub fn without_comments(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(at) = rest.find(['/', '"']) {
|
||||
out.push_str(&rest[..at]);
|
||||
let tail = &rest[at..];
|
||||
let skip = if let Some(line) = tail.strip_prefix("//") {
|
||||
out.push(' ');
|
||||
2 + line.find('\n').unwrap_or(line.len())
|
||||
} else if let Some(block) = tail.strip_prefix("/*") {
|
||||
out.push(' ');
|
||||
2 + block.find("*/").map_or(block.len(), |end| end + 2)
|
||||
} else if let Some(string) = tail.strip_prefix('"') {
|
||||
let end = 1 + string.find('"').map_or(string.len(), |end| end + 1);
|
||||
out.push_str(&tail[..end]);
|
||||
end
|
||||
} else {
|
||||
out.push('/');
|
||||
1
|
||||
};
|
||||
rest = &tail[skip..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The whole in-scope set a cross-file engine is handed: every indexed file,
|
||||
/// and one more when asked, read from disk now — plus every file the set
|
||||
/// could not include (over the size cap, not UTF-8, no longer readable),
|
||||
/// so an answer never pretends those were searched (QA finding 2 of M3).
|
||||
pub struct WholeSet {
|
||||
/// `(path, text)` for every file read.
|
||||
pub files: Vec<(PathBuf, String)>,
|
||||
/// The files left out, with why.
|
||||
pub skipped: Vec<(PathBuf, String)>,
|
||||
}
|
||||
|
||||
impl WholeSet {
|
||||
/// Read every indexed file and `extra` from disk now. The whole set,
|
||||
/// always (M2's ruling on QA finding 1): a use can resolve through files
|
||||
/// that never spell its name, so no narrowing by name is sound.
|
||||
pub fn read(project: &Project, extra: Option<&Path>) -> WholeSet {
|
||||
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
|
||||
wanted.extend(extra.map(Path::to_path_buf));
|
||||
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped() };
|
||||
for path in wanted {
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => set.files.push((path, text)),
|
||||
Err(e) => set.skipped.push((path, format!("no longer reads: {e}"))),
|
||||
}
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
/// The first skipped file whose bytes spell one of `names` as a whole
|
||||
/// word, with why it was skipped and the name it spells.
|
||||
pub fn mentioning<'n>(&self, names: &'n [String]) -> Option<(&Path, &str, &'n str)> {
|
||||
self.skipped.iter().find_map(|(path, why)| {
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
let name = names.iter().find(|name| word_in_bytes(&bytes, name.as_bytes()))?;
|
||||
Some((path.as_path(), why.as_str(), name.as_str()))
|
||||
})
|
||||
}
|
||||
|
||||
/// One line naming the skipped files (ten at most), or `None` when the
|
||||
/// set is complete.
|
||||
pub fn warning(&self, project: &Project) -> Option<String> {
|
||||
if self.skipped.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let named: Vec<String> = self
|
||||
.skipped
|
||||
.iter()
|
||||
.take(10)
|
||||
.map(|(path, why)| format!("{} ({why})", project.relative(path)))
|
||||
.collect();
|
||||
let more = self.skipped.len().saturating_sub(10);
|
||||
let tail = if more > 0 { format!(" and {more} more") } else { String::new() };
|
||||
Some(format!("not indexed, so not searched or edited: {}{tail}", named.join(", ")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` occurs in `bytes` not glued to an identifier character on
|
||||
/// either side — how an identifier, escaped or not, is written.
|
||||
fn word_in_bytes(bytes: &[u8], name: &[u8]) -> bool {
|
||||
let glued =
|
||||
|b: Option<&u8>| b.is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_' || b == b'$');
|
||||
if name.is_empty() || name.len() > bytes.len() {
|
||||
return false;
|
||||
}
|
||||
bytes.windows(name.len()).enumerate().any(|(at, window)| {
|
||||
window == name
|
||||
&& !glued(at.checked_sub(1).and_then(|before| bytes.get(before)))
|
||||
&& !glued(bytes.get(at + name.len()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `c` may continue an identifier.
|
||||
fn is_ident_char(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || c == '_' || c == '$'
|
||||
}
|
||||
|
||||
/// The byte offset, within `line`, of the first whole-word occurrence of
|
||||
/// `name` — a hit not glued to a neighbouring identifier character.
|
||||
pub fn word_in(line: &str, name: &str) -> Option<usize> {
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut from = 0;
|
||||
while let Some(found) = line.get(from..).and_then(|rest| rest.find(name)) {
|
||||
let start = from + found;
|
||||
let end = start + name.len();
|
||||
let before = line[..start].chars().next_back();
|
||||
let after = line[end..].chars().next();
|
||||
let glued = |c: Option<char>| c.is_some_and(is_ident_char);
|
||||
if !glued(before) && (name.starts_with('\\') || !glued(after)) {
|
||||
return Some(start);
|
||||
}
|
||||
from = start + name.len().max(1);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_word_is_found_whole_and_never_inside_another() {
|
||||
assert_eq!(word_in(" assign data_q = data;", "data"), Some(18));
|
||||
assert_eq!(word_in("data_q", "data"), None);
|
||||
assert_eq!(word_in("x = a.data", "data"), Some(6));
|
||||
assert_eq!(word_in("\\a@1 x", "\\a@1"), Some(0));
|
||||
assert_eq!(word_in("anything", ""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skipped_file_is_searched_for_whole_words_only() {
|
||||
assert!(word_in_bytes(b"leaf u (.d(x));", b"d"));
|
||||
assert!(word_in_bytes(b"\xa9 d", b"d"));
|
||||
assert!(!word_in_bytes(b"data d_q $d dd", b"d"));
|
||||
assert!(word_in_bytes(b"d", b"d"));
|
||||
assert!(!word_in_bytes(b"", b"d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_dropped_and_strings_kept() {
|
||||
let text = "#( // why\n .W(8), /* old: 4 */ .S(\"a//b\"), .D(4 / 2) )";
|
||||
assert_eq!(
|
||||
render::one_line(&without_comments(text)),
|
||||
"#( .W(8), .S(\"a//b\"), .D(4 / 2) )"
|
||||
);
|
||||
assert_eq!(without_comments("a /* open"), "a ");
|
||||
assert_eq!(capped("x y", 2), "x …");
|
||||
assert_eq!(capped("x y", 3), "x y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_site_prints_its_line_collapsed() {
|
||||
let text = "module m;\n logic [3:0] x;\nendmodule\n";
|
||||
let lines = LineIndex::new(text);
|
||||
let site = Site::at("m.sv".into(), text, &lines, TextRange::new(27, 28), "var");
|
||||
assert_eq!(site.render(), "m.sv:2:18 var: logic [3:0] x;");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! Generic over the reader and writer so the loop can be driven by tests
|
||||
//! without a process, and so nothing but `rpc::serve` ever names the real
|
||||
//! stdin/stdout.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
|
||||
/// One line read from the client.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Line {
|
||||
/// A line of text, its terminator removed. May be empty or not JSON; the
|
||||
/// caller decides.
|
||||
Text(String),
|
||||
/// A line that is not UTF-8 — answered as a parse error, never a crash.
|
||||
NotUtf8,
|
||||
/// The client closed its end: the loop is over.
|
||||
Eof,
|
||||
}
|
||||
|
||||
/// Reads client lines and writes server lines.
|
||||
pub struct Transport<R, W> {
|
||||
reader: R,
|
||||
writer: W,
|
||||
}
|
||||
|
||||
impl<R: BufRead, W: Write> Transport<R, W> {
|
||||
/// A transport over one reader and one writer.
|
||||
pub fn new(reader: R, writer: W) -> Transport<R, W> {
|
||||
Transport { reader, writer }
|
||||
}
|
||||
|
||||
/// The next line, without its `\n` or `\r\n`.
|
||||
pub fn read_line(&mut self) -> io::Result<Line> {
|
||||
let mut bytes = Vec::new();
|
||||
if self.reader.read_until(b'\n', &mut bytes)? == 0 {
|
||||
return Ok(Line::Eof);
|
||||
}
|
||||
if bytes.last() == Some(&b'\n') {
|
||||
bytes.pop();
|
||||
}
|
||||
if bytes.last() == Some(&b'\r') {
|
||||
bytes.pop();
|
||||
}
|
||||
Ok(match String::from_utf8(bytes) {
|
||||
Ok(text) => Line::Text(text),
|
||||
Err(_) => Line::NotUtf8,
|
||||
})
|
||||
}
|
||||
|
||||
/// Write one message as one line and flush it, so the client sees it now.
|
||||
///
|
||||
/// `serde_json` escapes every control character inside strings, so a
|
||||
/// serialized value never contains a raw newline — the framing rule the
|
||||
/// spec states ("MUST NOT contain embedded newlines") holds by
|
||||
/// construction.
|
||||
pub fn write_message(&mut self, message: &serde_json::Value) -> io::Result<()> {
|
||||
let mut line = serde_json::to_vec(message).map_err(io::Error::other)?;
|
||||
line.push(b'\n');
|
||||
self.writer.write_all(&line)?;
|
||||
self.writer.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lines_are_split_on_newlines_with_crlf_and_a_missing_last_newline_accepted() {
|
||||
let input: &[u8] = b"{\"a\":1}\r\n\n{\"b\":2}";
|
||||
let mut transport = Transport::new(input, Vec::new());
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{\"a\":1}".into()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text(String::new()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{\"b\":2}".into()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Eof);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_is_not_utf8_is_reported_not_fatal() {
|
||||
let input: &[u8] = b"\xff\xfe\n{}\n";
|
||||
let mut transport = Transport::new(input, Vec::new());
|
||||
assert_eq!(transport.read_line().unwrap(), Line::NotUtf8);
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{}".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_message_with_a_newline_in_a_string_is_still_one_line() {
|
||||
let mut transport = Transport::new(&b""[..], Vec::new());
|
||||
transport.write_message(&serde_json::json!({"text": "a\nb"})).unwrap();
|
||||
let written = String::from_utf8(transport.writer).unwrap();
|
||||
assert_eq!(written, "{\"text\":\"a\\nb\"}\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Shared types for the fixture design.
|
||||
package types_pkg;
|
||||
parameter int DATA_W = 8;
|
||||
typedef logic [DATA_W-1:0] word_t;
|
||||
|
||||
function automatic word_t invert(word_t w);
|
||||
return ~w;
|
||||
endfunction
|
||||
|
||||
class item;
|
||||
rand word_t data;
|
||||
endclass
|
||||
endpackage
|
||||
@@ -0,0 +1,3 @@
|
||||
module broken (input logic a);
|
||||
assign b = ;
|
||||
endmodule
|
||||
@@ -0,0 +1,5 @@
|
||||
interface bus_if;
|
||||
logic req, gnt;
|
||||
modport master (output req, input gnt);
|
||||
modport slave (input req, output gnt);
|
||||
endinterface
|
||||
@@ -0,0 +1,16 @@
|
||||
module leaf #(
|
||||
parameter int W = 8,
|
||||
parameter bit Pass = 1'b1
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q,
|
||||
input logic [3:0] mem [2]
|
||||
);
|
||||
logic [W-1:0] held;
|
||||
|
||||
always_ff @(posedge clk)
|
||||
held <= d;
|
||||
|
||||
assign q = Pass ? held : '0;
|
||||
endmodule
|
||||
@@ -0,0 +1,16 @@
|
||||
module top
|
||||
import types_pkg::*;
|
||||
(
|
||||
input logic clk
|
||||
);
|
||||
logic [3:0] d, q;
|
||||
logic [3:0] mem [2];
|
||||
word_t data;
|
||||
|
||||
leaf #(.W(4)) u_leaf (.*);
|
||||
bus_if u_bus ();
|
||||
|
||||
always_comb begin
|
||||
data = invert(8'h0f);
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
class scoreboard;
|
||||
int count;
|
||||
function void add();
|
||||
count++;
|
||||
endfunction
|
||||
endclass
|
||||
@@ -0,0 +1,3 @@
|
||||
program test_prog (input logic clk);
|
||||
initial $display("start");
|
||||
endprogram
|
||||
@@ -0,0 +1,4 @@
|
||||
module messy(input logic a,output logic b);
|
||||
assign b=a;
|
||||
// keep this comment
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module cell (
|
||||
input logic clk,
|
||||
input logic en,
|
||||
output logic o
|
||||
);
|
||||
assign o = en;
|
||||
endmodule
|
||||
@@ -0,0 +1,4 @@
|
||||
package edit_pkg;
|
||||
parameter int WIDTH = 8;
|
||||
typedef logic [WIDTH-1:0] word_t;
|
||||
endpackage
|
||||
@@ -0,0 +1,9 @@
|
||||
module ext (
|
||||
input logic clk,
|
||||
input logic [7:0] a,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] s;
|
||||
assign s = a + 8'd1;
|
||||
always_ff @(posedge clk) q <= s;
|
||||
endmodule
|
||||
@@ -0,0 +1,9 @@
|
||||
module inl (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
inv u_inv (
|
||||
.i(x),
|
||||
.o(z)
|
||||
);
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
module inv (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
assign o = ~i;
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module leaf (
|
||||
input logic clk,
|
||||
input logic [7:0] d,
|
||||
output logic [7:0] q
|
||||
);
|
||||
always_ff @(posedge clk) q <= d;
|
||||
endmodule
|
||||
@@ -0,0 +1,11 @@
|
||||
module mid (
|
||||
input logic clk,
|
||||
input logic [7:0] din,
|
||||
output logic [7:0] dout
|
||||
);
|
||||
leaf u_leaf (
|
||||
.clk(clk),
|
||||
.d (din),
|
||||
.q (dout)
|
||||
);
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
module old (a, b, y);
|
||||
input a;
|
||||
input b;
|
||||
output y;
|
||||
assign y = a & b;
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module partial (
|
||||
input logic clk,
|
||||
input logic en,
|
||||
output logic o
|
||||
);
|
||||
cell u_c (.clk(clk));
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module spare (
|
||||
input logic clk,
|
||||
input logic unused_i,
|
||||
output logic o
|
||||
);
|
||||
assign o = clk;
|
||||
endmodule
|
||||
@@ -0,0 +1,10 @@
|
||||
module spare_user (
|
||||
input logic clk,
|
||||
output logic o2
|
||||
);
|
||||
spare u_s (
|
||||
.clk (clk),
|
||||
.unused_i(1'b0),
|
||||
.o (o2)
|
||||
);
|
||||
endmodule
|
||||
@@ -0,0 +1,15 @@
|
||||
module top (
|
||||
input logic clk,
|
||||
input logic [7:0] a,
|
||||
output logic [7:0] y
|
||||
);
|
||||
import edit_pkg::word_t;
|
||||
import edit_pkg::WIDTH;
|
||||
word_t w;
|
||||
assign w = a;
|
||||
leaf u_leaf2 (
|
||||
.clk(clk),
|
||||
.d (w),
|
||||
.q (y)
|
||||
);
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module wild (
|
||||
input logic clk,
|
||||
input logic en,
|
||||
output logic o
|
||||
);
|
||||
cell u_cell (.*);
|
||||
endmodule
|
||||
@@ -0,0 +1,2 @@
|
||||
# The chain file is waived for line length.
|
||||
waive --rule=line-length --location=rtl/chain.sv
|
||||
@@ -0,0 +1,7 @@
|
||||
# Lint settings the diagnostics tool must honour.
|
||||
[lint]
|
||||
select = ["line-length", "unused-signal", "no-tabs"]
|
||||
waivers = ["lint/nav.waiver"]
|
||||
|
||||
[lint.line-length]
|
||||
length = 40
|
||||
@@ -0,0 +1,5 @@
|
||||
module chain_a; chain_b u_b (); endmodule
|
||||
module chain_b; chain_c u_c (); endmodule
|
||||
module chain_c; chain_d u_d (); endmodule
|
||||
module chain_d; chain_e u_e (); endmodule
|
||||
module chain_e; missing_m u_missing (); endmodule
|
||||
@@ -0,0 +1,2 @@
|
||||
module checker_m (input logic [3:0] state_q);
|
||||
endmodule
|
||||
@@ -0,0 +1,14 @@
|
||||
`include "defs.svh"
|
||||
module core #(
|
||||
parameter int W = 4
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
logic [W-1:0] state_q;
|
||||
logic spare;
|
||||
always_ff @(posedge clk)
|
||||
state_q <= `ADD(d, 1);
|
||||
assign q = state_q;
|
||||
endmodule
|
||||
@@ -0,0 +1 @@
|
||||
bind core checker_m u_chk (.state_q(state_q));
|
||||
@@ -0,0 +1,2 @@
|
||||
`define NAV_W 4
|
||||
`define ADD(a, b = 1) ((a) + (b))
|
||||
@@ -0,0 +1,6 @@
|
||||
module dual (a, y);
|
||||
input a;
|
||||
output y;
|
||||
wire y;
|
||||
assign y = a;
|
||||
endmodule
|
||||
@@ -0,0 +1,9 @@
|
||||
module top (input logic clk);
|
||||
logic [`NAV_W-1:0] d, q0, q1;
|
||||
logic [`NAV_W-1:0] peek;
|
||||
core #(.W(4)) u_core0 (.clk, .d, .q(q0));
|
||||
core #(
|
||||
.W (8)
|
||||
) u_core1 (.clk, .d, .q(q1));
|
||||
assign peek = u_core0.state_q;
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
module tree #(parameter int N = 4) ();
|
||||
if (N > 1) begin : g_split
|
||||
tree #(.N(N / 2)) u_left ();
|
||||
tree #(.N(N / 2)) u_right ();
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
class env;
|
||||
sb s;
|
||||
function void run();
|
||||
s.count = 0;
|
||||
endfunction
|
||||
endclass
|
||||
@@ -0,0 +1,6 @@
|
||||
class sb;
|
||||
int count;
|
||||
function void add();
|
||||
count++;
|
||||
endfunction
|
||||
endclass
|
||||
@@ -0,0 +1,161 @@
|
||||
//! The opentitan census (TODO-MCP M2): the navigation tools over a real
|
||||
//! checkout, read-only, each answer checked against what the language
|
||||
//! server answers for the same question (`docs/features/references-nav`,
|
||||
//! `references-hierarchical-surface`) and each call's wall time printed.
|
||||
//!
|
||||
//! `#[ignore]`: it needs the checkout. Run with
|
||||
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
|
||||
//! lucisv_mcp --test opentitan -- --ignored --nocapture`.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The checkout: `LUCISV_OPENTITAN`, else the owner's usual path.
|
||||
fn checkout() -> PathBuf {
|
||||
std::env::var_os("LUCISV_OPENTITAN")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/Users/guoliangchen/repo/opentitan"))
|
||||
}
|
||||
|
||||
/// One server over the checkout.
|
||||
struct Session {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
stdout: BufReader<ChildStdout>,
|
||||
next_id: i64,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn over(root: &Path) -> Session {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
|
||||
.args(["--root", root.to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let stdin = child.stdin.take().unwrap();
|
||||
let stdout = BufReader::new(child.stdout.take().unwrap());
|
||||
let mut session = Session { child, stdin, stdout, next_id: 0 };
|
||||
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
|
||||
session
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next_id += 1;
|
||||
let line =
|
||||
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
|
||||
writeln!(self.stdin, "{line}").unwrap();
|
||||
self.stdin.flush().unwrap();
|
||||
let mut answer = String::new();
|
||||
self.stdout.read_line(&mut answer).unwrap();
|
||||
serde_json::from_str(&answer).unwrap()
|
||||
}
|
||||
|
||||
/// A tool call that must succeed, with the wall time printed.
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> Value {
|
||||
let started = Instant::now();
|
||||
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
|
||||
let ms = started.elapsed().as_millis();
|
||||
println!("census: {tool} {arguments} {ms} ms");
|
||||
let result = reply["result"].clone();
|
||||
assert_eq!(result["isError"], false, "{tool}: {result}");
|
||||
result
|
||||
}
|
||||
|
||||
/// [`Session::call`]'s text.
|
||||
fn text(&mut self, tool: &str, arguments: Value) -> String {
|
||||
let result = self.call(tool, arguments);
|
||||
result["content"][0]["text"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// Every `references` hit as `file:line:col`.
|
||||
fn hits(&mut self, arguments: Value) -> Vec<String> {
|
||||
let result = self.call("references", arguments);
|
||||
let hits = result["structuredContent"]["hits"].as_array().unwrap().clone();
|
||||
hits.iter()
|
||||
.map(|h| format!("{}:{}:{}", h["file"].as_str().unwrap(), h["line"], h["col"]))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The language server's answer for the same position (release
|
||||
/// `lucisv-server` over the same checkout, 2026-09-23): every location it
|
||||
/// lists must be in ours.
|
||||
fn assert_covers(ours: &[String], server: &[&str]) {
|
||||
for location in server {
|
||||
assert!(ours.iter().any(|hit| hit == location), "missing {location}: {ours:?}");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// `git status --porcelain` of the checkout, to prove it was only read.
|
||||
fn status(root: &Path) -> Vec<u8> {
|
||||
Command::new("git").arg("-C").arg(root).args(["status", "--porcelain"]).output().unwrap().stdout
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN)"]
|
||||
fn opentitan_navigation_matches_the_language_server() {
|
||||
let root = checkout();
|
||||
let before = status(&root);
|
||||
let mut s = Session::over(&root);
|
||||
// The first call builds the index; its time is the startup cost.
|
||||
s.text("project_overview", json!({}));
|
||||
|
||||
let masking =
|
||||
json!({"file": "hw/ip/aes/rtl/aes.sv", "name": "entropy_masking_req", "limit": 1000});
|
||||
let masking = s.hits(masking);
|
||||
let aes = "hw/ip/aes/rtl/aes.sv";
|
||||
let bind = "hw/ip/aes/dv/sva/aes_bind.sv";
|
||||
let server = [&format!("{bind}:45:27"), &format!("{bind}:54:26"), &format!("{aes}:89:52")];
|
||||
assert_covers(&masking, &server.map(String::as_str));
|
||||
assert_eq!(masking.len(), 6, "{masking:?}");
|
||||
|
||||
let sm = "hw/ip/entropy_src/rtl/entropy_src_main_sm.sv";
|
||||
let state = s.hits(json!({"file": sm, "line": 42, "name": "state_q"}));
|
||||
assert_covers(&state, &["hw/ip/entropy_src/rtl/entropy_src_core.sv:3092:30"]);
|
||||
assert_eq!(state.len(), 5, "{state:?}");
|
||||
|
||||
// The references-nav positions: the `aes` instantiation and its `.clk_i`
|
||||
// in the testbench. The server lists 11 and 9; we list those and the
|
||||
// three top-level `*_pd_main.sv` instantiations it omits (README, work log).
|
||||
let tb = "hw/ip/aes/dv/tb/tb.sv";
|
||||
let instantiated = s.hits(json!({"file": tb, "line": 45, "name": "aes"}));
|
||||
let server = [
|
||||
"hw/ip/aes/dv/cov/aes_cov_bind.sv:8:8",
|
||||
"hw/ip/aes/dv/sva/aes_bind.sv:50:8",
|
||||
"hw/ip/aes/dv/tb/tb.sv:45:3",
|
||||
"hw/ip/aes/pre_dv/aes_tb/rtl/aes_tb.sv:215:3",
|
||||
"hw/ip/aes/rtl/aes.sv:9:8",
|
||||
"hw/ip/aes/rtl/aes_wrap.sv:79:3",
|
||||
];
|
||||
assert_covers(&instantiated, &server);
|
||||
let clock = s.hits(json!({"file": tb, "line": 46, "name": "clk_i"}));
|
||||
assert_covers(&clock, &["hw/ip/aes/rtl/aes.sv:42:53", "hw/ip/aes/rtl/aes.sv:197:31"]);
|
||||
|
||||
let top = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2, "limit": 500}));
|
||||
assert!(top.contains("\n u_aes : aes #("), "{top}");
|
||||
|
||||
let fifo = s.text("definition", json!({"name": "prim_fifo_sync"}));
|
||||
assert!(fifo.starts_with("hw/ip/prim/rtl/prim_fifo_sync.sv:"), "{fifo}");
|
||||
|
||||
let up = s.text("hierarchy", json!({"root": "prim_fifo_sync", "direction": "up", "depth": 1}));
|
||||
assert!(up.contains(".u_"), "{up}");
|
||||
|
||||
s.text("diagnostics", json!({"file": "hw/ip/aes/rtl/aes.sv"}));
|
||||
let clk = json!({"file": "hw/ip/prim/rtl/prim_fifo_sync.sv", "name": "clk_i"});
|
||||
s.text("references", clk);
|
||||
drop(s);
|
||||
assert_eq!(status(&root), before, "the checkout was only read");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -32,9 +32,8 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::tokenize;
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_semantic::{words, SymbolKind, WorkspaceIndex};
|
||||
|
||||
/// One name the workspace index knows, flattened for lookup.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -109,23 +108,49 @@ impl Candidates {
|
||||
/// here, exactly as every file used to be. The two produce the same words
|
||||
/// because they are the same function over the same tokens
|
||||
/// ([`words_of_tokens`]).
|
||||
///
|
||||
/// Test-only since 2026-09-08: a scan holds every file's words and no
|
||||
/// file's text, so it calls [`Candidates::from_words`]. This is that call
|
||||
/// with the lex in front of it, which is what a test building tables from
|
||||
/// a fixture's text wants and what makes the two one function.
|
||||
#[cfg(test)]
|
||||
pub fn build(
|
||||
index: &WorkspaceIndex,
|
||||
sources: &[(PathBuf, String)],
|
||||
mut known: HashMap<PathBuf, Vec<String>>,
|
||||
) -> Candidates {
|
||||
let words = sources
|
||||
.iter()
|
||||
.map(|(path, text)| {
|
||||
let words = known.remove(path).unwrap_or_else(|| words_in(text));
|
||||
(path.clone(), words)
|
||||
})
|
||||
.collect();
|
||||
Candidates::from_words(index, words)
|
||||
}
|
||||
|
||||
/// [`Candidates::build`] for a caller that already holds **every** file's
|
||||
/// words — the form a scan uses.
|
||||
///
|
||||
/// Since 2026-09-08 a scan reads a file's text at the step that indexes it
|
||||
/// and drops it again, so there is no text left to lex when the tables are
|
||||
/// built at the end. There never was any lexing to do: since `FACTS_FORMAT`
|
||||
/// 13 a file's identifier census is one of its facts, so a scan already has
|
||||
/// the words of every file it stepped, cached or parsed, and `build`'s
|
||||
/// `known` covered the whole list. This is that call without the text it
|
||||
/// no longer reads (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
///
|
||||
/// Order-independent: the word counts are a sum and `words` is sorted at
|
||||
/// the end, so a map is as good as a list here.
|
||||
pub fn from_words(index: &WorkspaceIndex, words: HashMap<PathBuf, Vec<String>>) -> Candidates {
|
||||
let mut out = Candidates::default();
|
||||
out.take_index_tables(index);
|
||||
for (path, text) in sources {
|
||||
let words = match known.remove(path) {
|
||||
Some(words) => words,
|
||||
None => words_in(text),
|
||||
};
|
||||
for (path, words) in words {
|
||||
for word in &words {
|
||||
*out.word_files.entry(word.clone()).or_default() += 1;
|
||||
}
|
||||
if !words.is_empty() {
|
||||
out.per_file.insert(path.clone(), words);
|
||||
out.per_file.insert(path, words);
|
||||
}
|
||||
}
|
||||
out.words = out.word_files.keys().cloned().collect();
|
||||
@@ -294,6 +319,17 @@ impl Candidates {
|
||||
self.remask_words();
|
||||
}
|
||||
|
||||
/// How many entries each completion table holds, and what the word table
|
||||
/// weighs — the startup memory question, asked of the one table that
|
||||
/// grows with the corpus rather than with its declarations.
|
||||
///
|
||||
/// A walk, so it is asked once at the end of a traced scan and never on a
|
||||
/// request path (`docs/features/perf5-p4/README.md`).
|
||||
pub fn sizes(&self) -> (usize, usize, usize, usize) {
|
||||
let word_bytes: usize = self.words.iter().map(String::len).sum();
|
||||
(self.units.len(), self.macros.len(), self.words.len(), word_bytes)
|
||||
}
|
||||
|
||||
/// Index names starting with `prefix`, case-insensitively.
|
||||
pub fn units(&self, prefix: &str) -> &[Candidate] {
|
||||
matching(&self.units, prefix, |c| &c.name)
|
||||
@@ -333,6 +369,15 @@ impl Candidates {
|
||||
matching(&self.macros, prefix, |m| &m.name)
|
||||
}
|
||||
|
||||
/// Whether the workspace `` `define``s this exact name.
|
||||
///
|
||||
/// Asked by [`Candidates::words_scan`] so the word tier does not offer a
|
||||
/// macro name as a plain word. The table is sorted by [`word_cmp`], which
|
||||
/// is a total order, so this is a binary search.
|
||||
fn has_macro(&self, name: &str) -> bool {
|
||||
self.macros.binary_search_by(|held| word_cmp(&held.name, name)).is_ok()
|
||||
}
|
||||
|
||||
/// Project words starting with `prefix`, case-insensitively.
|
||||
pub fn words(&self, prefix: &str) -> &[String] {
|
||||
matching(&self.words, prefix, |w| w.as_str())
|
||||
@@ -362,6 +407,17 @@ impl Candidates {
|
||||
|
||||
/// The best `cap` project words holding `query`'s characters in order.
|
||||
///
|
||||
/// A word the workspace `` `define``s is **not** offered here. Since
|
||||
/// 2026-09-02 the census splits a directive line into its words, so a
|
||||
/// `` `define FOO `` puts `FOO` in the word table; the macro tier already
|
||||
/// offers that name and does so **by prefix only**, which is
|
||||
/// fuzzy-completion's own ruling (`the_keyword_template_macro_and_module_
|
||||
/// tiers_did_not_go_fuzzy`). Letting the word tier reach it by
|
||||
/// subsequence would overturn that decision by a side door. The *census*
|
||||
/// keeps the word — it is a name the file writes down, which is the
|
||||
/// question `WorkspaceIndex::files_mentioning` answers — so this is a
|
||||
/// filter on one reader, not a second harvest.
|
||||
///
|
||||
/// The fuzzy sibling of [`Candidates::words`], and the one lookup here
|
||||
/// whose cost is worth stating: an unfiltered scan of opentitan's hundred
|
||||
/// thousand words is milliseconds, which no keystroke can afford, and the
|
||||
@@ -392,6 +448,9 @@ impl Candidates {
|
||||
continue;
|
||||
}
|
||||
survivors += 1;
|
||||
if self.has_macro(word) {
|
||||
continue;
|
||||
}
|
||||
if let Some(score) = query.score(word) {
|
||||
hits.push((word.as_str(), score));
|
||||
}
|
||||
@@ -715,21 +774,20 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
|
||||
/// Every distinct identifier one file's token stream contains.
|
||||
///
|
||||
/// Deduplicated as it is collected, not afterwards: a workspace holds two
|
||||
/// orders of magnitude more identifier *tokens* than distinct identifiers
|
||||
/// (900k against 17k over this repo's corpus), and copying every one of them
|
||||
/// only to sort the copies away costs more than the lexing does.
|
||||
/// **`vlog_semantic::words::harvest_text`, under this crate's old name.** The
|
||||
/// harvest moved out of the server on 2026-09-02 so the completion word table
|
||||
/// and the index's per-file census are one answer rather than two that must be
|
||||
/// kept equal by hand — the semantic lint rules read the census as "does any
|
||||
/// other file mention this name", and a completion list that disagreed with a
|
||||
/// lint finding about what a file contains would be a bug nobody could see.
|
||||
/// See `docs/features/semantic-lints-on/README.md`.
|
||||
///
|
||||
/// `pub(crate)` because a scan lexes each file as it reaches it rather than in
|
||||
/// one pass at the end: no part of a scan may be longer than one file, or the
|
||||
/// message queue goes unanswered for the length of it
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
pub(crate) fn words_in(text: &str) -> Vec<String> {
|
||||
// A file that does not lex contributes nothing rather than being guessed
|
||||
// at with a regex — the same all-or-nothing rule the lexer gives every
|
||||
// other consumer.
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
words_of_tokens(&tokens)
|
||||
words::harvest_text(text)
|
||||
}
|
||||
|
||||
/// [`words_in`] over a token stream the caller already lexed.
|
||||
@@ -739,29 +797,7 @@ pub(crate) fn words_in(text: &str) -> Vec<String> {
|
||||
/// did not lex holds no tokens and contributes nothing here either, which is
|
||||
/// the same all-or-nothing rule from the other side.
|
||||
pub(crate) fn words_of_tokens(tokens: &[Token]) -> Vec<String> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
|
||||
if !seen.contains(token.text.as_str()) {
|
||||
seen.insert(token.text.clone());
|
||||
}
|
||||
}
|
||||
seen.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Whether a token is a word worth offering.
|
||||
///
|
||||
/// `Ident` and `SystemIdent` only, so a comment (lexer trivia) and a string
|
||||
/// literal (one `String` token) can never contribute. Two `Ident` shapes are
|
||||
/// dropped:
|
||||
///
|
||||
/// * a **macro usage** (`` `WIDTH ``) — the text is the whole invocation,
|
||||
/// argument list and all, and the macro *names* have their own table;
|
||||
/// * an **escaped identifier** (`\my-port`) — inserting one needs a trailing
|
||||
/// space to terminate it, which a plain word item has no way to promise.
|
||||
fn is_word(kind: TokenKind, text: &str) -> bool {
|
||||
matches!(kind, TokenKind::Ident | TokenKind::SystemIdent)
|
||||
&& !text.starts_with('`')
|
||||
&& !text.starts_with('\\')
|
||||
words::harvest(tokens)
|
||||
}
|
||||
|
||||
/// Sort by name, case-insensitively first so [`matching`]'s binary search is
|
||||
@@ -1033,6 +1069,36 @@ mod tests {
|
||||
assert!(candidates.words("").len() >= 2, "at least `p` and `K`");
|
||||
}
|
||||
|
||||
/// The 2026-09-02 amendment, from both sides. The word table takes the
|
||||
/// census whole — including the names inside a macro invocation, which is
|
||||
/// how a UVM testbench writes down the RTL signal it reads — and subtracts
|
||||
/// exactly one thing: a name the workspace `` `define``s, which the macro
|
||||
/// tier owns and offers by prefix only.
|
||||
#[test]
|
||||
fn macro_argument_words_are_offered_and_macro_names_are_left_to_their_own_tier() {
|
||||
let candidates = built(&[
|
||||
("/dv/defs.svh", "`define CHECK_IT(a) assert (a)
|
||||
"),
|
||||
(
|
||||
"/dv/tb.sv",
|
||||
"module tb;\n dut u_dut ();\n \x20 `CHECK_IT(u_dut.dbg_probe == other_word)\nendmodule\n",
|
||||
),
|
||||
]);
|
||||
let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect();
|
||||
assert!(names.contains(&"dbg_probe"), "a macro argument is code: {names:?}");
|
||||
assert!(names.contains(&"other_word"), "{names:?}");
|
||||
// The census holds the macro name too — it is a word the file writes
|
||||
// down, and `files_mentioning` must say so ...
|
||||
assert!(names.contains(&"CHECK_IT"), "the table keeps it: {names:?}");
|
||||
// ... but the fuzzy word tier does not offer it, because the macro
|
||||
// tier does, by prefix, and that is fuzzy-completion's ruling.
|
||||
let query = Query::new("chckit");
|
||||
let fuzzy: Vec<&str> =
|
||||
candidates.words_fuzzy(&query, 20).into_iter().map(|(w, _)| w).collect();
|
||||
assert!(!fuzzy.contains(&"CHECK_IT"), "the macro tier owns it: {fuzzy:?}");
|
||||
assert!(candidates.macros("CHECK").iter().any(|m| m.name == "CHECK_IT"), "premise");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_lex_contributes_nothing_and_does_not_stop_the_rest() {
|
||||
let candidates = built(&[
|
||||
|
||||
@@ -14,6 +14,7 @@ use lsp_types::{
|
||||
use vlog_linter::{apply_fixes, rule_by_name, Applicability, Violation};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::lint::LintRun;
|
||||
use crate::state::Document;
|
||||
|
||||
/// The kind of the fix-everything action, namespaced under `source.fixAll` so
|
||||
@@ -27,23 +28,41 @@ pub const FIX_ALL: &str = "source.fixAll.lucisv";
|
||||
/// client, because a fix-on-save request asks for `source.fixAll.lucisv` alone
|
||||
/// and computing every quick fix for it would be work nobody reads.
|
||||
pub fn code_actions(
|
||||
run: &LintRun,
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
range: Range,
|
||||
only: Option<&[CodeActionKind]>,
|
||||
tab_width: usize,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let violations = crate::lint::fixable(run, doc);
|
||||
// Timed apart from the lint pass that found them: a menu that is slow
|
||||
// because it *renders* a thousand fixes is a different problem from one
|
||||
// that is slow because it found them (review round §R1b).
|
||||
let actions = crate::lint_trace::stage(crate::lint_trace::Stage::Serialize, || {
|
||||
offered(uri, doc, range, only, &violations)
|
||||
});
|
||||
crate::lint_trace::saw_actions(actions.len());
|
||||
actions
|
||||
}
|
||||
|
||||
/// The quick fixes and the fix-all action `only` asks for, built from
|
||||
/// violations already found.
|
||||
fn offered(
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
range: Range,
|
||||
only: Option<&[CodeActionKind]>,
|
||||
violations: &[Violation],
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let positions = doc.positions();
|
||||
let violations = crate::lint::fixable(doc, tab_width);
|
||||
let mut actions = Vec::new();
|
||||
if wanted(only, &CodeActionKind::QUICKFIX) {
|
||||
let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range));
|
||||
actions.extend(quick.map(CodeActionOrCommand::CodeAction));
|
||||
}
|
||||
if wanted(only, &CodeActionKind::new(FIX_ALL)) {
|
||||
actions.extend(
|
||||
fix_all(uri, doc, &positions, &violations).map(CodeActionOrCommand::CodeAction),
|
||||
);
|
||||
actions
|
||||
.extend(fix_all(uri, doc, &positions, violations).map(CodeActionOrCommand::CodeAction));
|
||||
}
|
||||
actions
|
||||
}
|
||||
@@ -131,6 +150,18 @@ fn title(violation: &Violation) -> String {
|
||||
format!("lucisv: {what} [{}]", violation.rule)
|
||||
}
|
||||
|
||||
/// Whether a client asking for `only` wants anything [`code_actions`] can
|
||||
/// offer — a quick fix or the fix-all action.
|
||||
///
|
||||
/// The two kinds this module answers for are the only two the **lint pass**
|
||||
/// answers for, so this is the question the dispatcher asks before reading the
|
||||
/// buffer's configuration and running the rules. A client asking for
|
||||
/// `refactor.*` or `source.organizeImports` alone gets neither, and now pays
|
||||
/// for neither (take 5 §P1a).
|
||||
pub fn wants_fixes(only: Option<&[CodeActionKind]>) -> bool {
|
||||
wanted(only, &CodeActionKind::QUICKFIX) || wanted(only, &CodeActionKind::new(FIX_ALL))
|
||||
}
|
||||
|
||||
/// Whether a client asking for `only` wants this kind. A filter is a prefix of
|
||||
/// the kinds it selects (`source` selects `source.fixAll.lucisv`), and no filter
|
||||
/// at all selects everything.
|
||||
@@ -170,7 +201,7 @@ mod tests {
|
||||
fn actions_of(ws: &Workspace) -> Vec<CodeAction> {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
code_actions(&uri(), doc, whole, None, 2)
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, None)
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => action,
|
||||
@@ -248,7 +279,13 @@ mod tests {
|
||||
start: Position { line: 1, character: 0 },
|
||||
end: Position { line: 1, character: 0 },
|
||||
};
|
||||
let actions = code_actions(&uri(), doc, line1, Some(&[CodeActionKind::QUICKFIX]), 2);
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
line1,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
);
|
||||
assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}");
|
||||
}
|
||||
|
||||
@@ -320,14 +357,19 @@ mod tests {
|
||||
start: Position { line: fenced_line, character: 0 },
|
||||
end: Position { line: fenced_line, character: 0 },
|
||||
};
|
||||
let actions = code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2);
|
||||
let actions =
|
||||
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]));
|
||||
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
|
||||
// The unfenced tab one line further down still has one.
|
||||
let at = Range {
|
||||
start: Position { line: 4, character: 0 },
|
||||
end: Position { line: 4, character: 0 },
|
||||
};
|
||||
assert_eq!(code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2).len(), 1);
|
||||
assert_eq!(
|
||||
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]),)
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -370,14 +412,14 @@ mod tests {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let fix_all_only = [CodeActionKind::new(FIX_ALL)];
|
||||
let actions = code_actions(&uri(), doc, whole, Some(&fix_all_only), 2);
|
||||
let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only));
|
||||
assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for");
|
||||
// `source` is a prefix filter for `source.fixAll.lucisv`.
|
||||
let source = [CodeActionKind::SOURCE];
|
||||
assert_eq!(code_actions(&uri(), doc, whole, Some(&source), 2).len(), 1);
|
||||
assert_eq!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source)).len(), 1);
|
||||
// And an unrelated filter selects nothing.
|
||||
let refactor = [CodeActionKind::REFACTOR];
|
||||
assert!(code_actions(&uri(), doc, whole, Some(&refactor), 2).is_empty());
|
||||
assert!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -386,7 +428,13 @@ mod tests {
|
||||
let ws = workspace(text);
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let actions = code_actions(&uri(), doc, whole, Some(&[CodeActionKind::QUICKFIX]), 4);
|
||||
let actions = code_actions(
|
||||
&LintRun::default().with_tab_width(4),
|
||||
&uri(),
|
||||
doc,
|
||||
whole,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
);
|
||||
let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") };
|
||||
assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
@@ -407,4 +455,24 @@ mod tests {
|
||||
assert!(out.contains("é 🎉"), "comments are never dropped: {out:?}");
|
||||
assert_eq!(out, "module m;\n // é 🎉 wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_externally_waived_finding_gets_no_quick_fix_and_fix_all_leaves_it() {
|
||||
// §39 QA's HIGH: `fixable` used `default_rules()` and no waivers, so
|
||||
// fix-on-save rewrote a line a checked-in waiver file had waived.
|
||||
let src = "module m;\n\twire a;\nendmodule\n";
|
||||
let ws = workspace(src);
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let waived = LintRun::default()
|
||||
.with_waivers(std::path::Path::new("team.waiver"), "waive --rule=no-tabs\n");
|
||||
assert!(
|
||||
code_actions(&waived, &uri(), doc, whole, None).is_empty(),
|
||||
"no quick fix and no fix-all for a waived finding"
|
||||
);
|
||||
assert!(
|
||||
!code_actions(&LintRun::default(), &uri(), doc, whole, None).is_empty(),
|
||||
"the same buffer without the waiver is fixable"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,114 @@
|
||||
//! The completion tests' harness: a scratch workspace on disk, and the
|
||||
//! handful of helpers every provider's tests ask through.
|
||||
//!
|
||||
//! `#[cfg(test)]` only; the tests themselves sit at the foot of the file
|
||||
//! whose code they pin.
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
pub(super) const SUB: &str = "\
|
||||
module sub #(
|
||||
parameter int WIDTH = 8
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [WIDTH-1:0] data,
|
||||
output logic ready
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
pub(super) struct Tree {
|
||||
pub(super) path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
pub(super) fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_completion_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
pub(super) fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// A two-file workspace with `top.sv` open, and the cursor at `needle`'s
|
||||
/// end. `sub.sv` declares [`SUB`].
|
||||
pub(super) fn asking(name: &str, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", SUB);
|
||||
opened(tree, top, needle)
|
||||
}
|
||||
|
||||
/// The same, with whatever `tree` already holds and no `sub.sv` implied.
|
||||
pub(super) fn opened(tree: Tree, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
|
||||
opened_named(tree, "top.sv", top, needle)
|
||||
}
|
||||
|
||||
/// The same again, with the buffer's file name spelled out — which is what
|
||||
/// decides its dialect.
|
||||
pub(super) fn opened_named(
|
||||
tree: Tree,
|
||||
file: &str,
|
||||
top: &str,
|
||||
needle: &str,
|
||||
) -> (Tree, Workspace, Uri, Position) {
|
||||
let path = tree.write(file, top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let position = doc.positions().position(offset);
|
||||
(tree, ws, uri, position)
|
||||
}
|
||||
|
||||
pub(super) fn items(response: Option<CompletionResponse>) -> Vec<CompletionItem> {
|
||||
match response {
|
||||
Some(CompletionResponse::List(list)) => list.items,
|
||||
Some(CompletionResponse::Array(items)) => items,
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn inserted(item: &CompletionItem) -> String {
|
||||
match item.text_edit.as_ref().expect("a text edit") {
|
||||
CompletionTextEdit::Edit(edit) => edit.new_text.clone(),
|
||||
CompletionTextEdit::InsertAndReplace(edit) => edit.new_text.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tier an item was filed under, read off its `sortText`.
|
||||
pub(super) fn tier(item: &CompletionItem) -> char {
|
||||
item.sort_text.as_ref().and_then(|s| s.chars().next()).expect("every item is sorted")
|
||||
}
|
||||
|
||||
/// Only the module skeletons — tier 0, the M4 items.
|
||||
pub(super) fn skeletons(items: &[CompletionItem]) -> Vec<&CompletionItem> {
|
||||
items.iter().filter(|item| tier(item) == TIER_MODULE).collect()
|
||||
}
|
||||
|
||||
pub(super) fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a CompletionItem> {
|
||||
items.iter().find(|item| item.label == label)
|
||||
}
|
||||
|
||||
pub(super) fn labels(items: &[CompletionItem]) -> Vec<&str> {
|
||||
items.iter().map(|item| item.label.as_str()).collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,837 @@
|
||||
//! `textDocument/completion` — module hinting, templates, keywords, and every
|
||||
//! name the project uses.
|
||||
//!
|
||||
//! One response, six tiers, ordered by `sortText`:
|
||||
//!
|
||||
//! 0. **module names** — at module-item position only, every module the
|
||||
//! workspace declares whose name contains what is typed. The item inserts
|
||||
//! the **name alone**; the instantiation follows as ghost text once the
|
||||
//! name is spelled exactly and a space follows it (`inline.rs`,
|
||||
//! 2026-08-30);
|
||||
//! 1. **what is visible here** — the declarations the scope chain at the
|
||||
//! cursor binds, from this file's `Semantics`;
|
||||
//! 2. **what the project declares** — packages, their members, typedefs,
|
||||
//! classes, modules and `` `define`` names, from the workspace index;
|
||||
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
||||
//! tabstops, offered only where the construct may be written;
|
||||
//! 4. **keywords** — every reserved word `vlog_parser` knows;
|
||||
//! 5. **project words** — every identifier the in-scope files' *token
|
||||
//! streams* contain, the rope/VS Code word-completion tier.
|
||||
//!
|
||||
//! A name is offered once, by the highest tier that claims it. Nothing is
|
||||
//! offered inside a comment or a string literal, and nothing that only ever
|
||||
//! appears inside one is ever a candidate — see `candidates.rs`.
|
||||
//!
|
||||
//! **Every tier is a table lookup.** No request here reads a file or parses
|
||||
//! one, which is what makes the answer affordable on a keystroke in a
|
||||
//! workspace the size of opentitan. The planning half of the old tier 0 —
|
||||
//! [`plan_for`] and [`module_header`](module::module_header), still here
|
||||
//! because they are still the way an instantiation is planned — is now called by `inline.rs` for exactly
|
||||
//! one module, once the user has spelled its whole name and typed the space
|
||||
//! that says so.
|
||||
//!
|
||||
//! See `docs/features/completion-core/README.md`, for tier 0
|
||||
//! `docs/features/inline-instantiation/README.md` and
|
||||
//! `docs/features/refactor-instantiate/README.md`, and for tier 3
|
||||
//! `docs/features/completion-templates/README.md`.
|
||||
//!
|
||||
//! The module is one directory: this file is the entry point, the response
|
||||
//! under construction (`Items`) and the small helpers every tier shares; the
|
||||
//! rest is one file per answer, in the order `completions` consults them:
|
||||
//!
|
||||
//! * `word` — what is typed: the identifier run at the cursor, the backtick
|
||||
//! or the `.`/`::` before it, and the spine a separator follows;
|
||||
//! * `site` — what may be written here: the module-item and statement gates
|
||||
//! over the token stream's scope chain;
|
||||
//! * `member` — the exclusive answer after a `.` or a `::`, the connection
|
||||
//! list included;
|
||||
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
|
||||
//! `instantiate.rs` share;
|
||||
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
|
||||
//! the response.
|
||||
//!
|
||||
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
|
||||
//! entry points other modules of the crate use keep their paths through the
|
||||
//! re-exports below. Each file's tests sit at its foot, on the harness in
|
||||
//! `harness.rs`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::{
|
||||
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
|
||||
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
|
||||
TextEdit, Uri,
|
||||
};
|
||||
use vlog_parser::token::{Comment, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Symbol, SymbolKind};
|
||||
|
||||
use crate::candidates::Query;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::Template;
|
||||
use member::member_answer;
|
||||
use module::module_tier;
|
||||
use site::{at_module_item, at_statement, enclosing_scopes};
|
||||
use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier};
|
||||
use word::typed_word;
|
||||
|
||||
pub(crate) use module::{nearest_definition, plan_for};
|
||||
// `perf.rs`, the one caller outside this module, is itself test-only; an
|
||||
// unconditional re-export would be an unused import in every other build.
|
||||
#[cfg(test)]
|
||||
pub(crate) use module::module_header;
|
||||
pub(crate) use site::at_instantiation_site;
|
||||
pub(crate) use tiers::layout_at;
|
||||
|
||||
#[cfg(test)]
|
||||
mod harness;
|
||||
mod member;
|
||||
mod module;
|
||||
mod site;
|
||||
mod tiers;
|
||||
mod word;
|
||||
|
||||
/// How many items one response carries, over every tier.
|
||||
///
|
||||
/// Large enough that an *empty* prefix still reaches the last tier — 64
|
||||
/// modules plus 181 keywords plus what one scope binds leaves room — and small
|
||||
/// enough to bound the payload at a few tens of kilobytes. Tiers fill in
|
||||
/// order, so a truncated list loses the least useful end of it and comes back
|
||||
/// `isIncomplete`: the protocol's way of saying "ask me again when you have
|
||||
/// typed more".
|
||||
const LIMIT: usize = 512;
|
||||
|
||||
/// How many characters must be typed before a name may match by
|
||||
/// *subsequence* rather than by prefix.
|
||||
///
|
||||
/// **VS Code's own rule**, which is the whole policy of this round: below
|
||||
/// three characters its widget filters what it holds by prefix, and so does
|
||||
/// the server; from three up both match by subsequence, so `clkenq` reaches
|
||||
/// `clk_osc_en_q`. Matching the client is the point — a server that went
|
||||
/// fuzzy at one character would answer a question the widget then filtered the
|
||||
/// answer to, and one that never went fuzzy is what this round is fixing.
|
||||
///
|
||||
/// The floor is not only manners. A one-character fuzzy query matches most of
|
||||
/// a workspace, which is a list nobody can read, and it is the one query the
|
||||
/// character-mask prefilter cannot help with at all — one bit wide, it rejects
|
||||
/// nothing, so the whole table is scanned. Measured at 2.7 ms over the real
|
||||
/// opentitan word list against the 0.05 ms `clkenq` costs.
|
||||
///
|
||||
/// See `docs/features/fuzzy-completion/README.md`.
|
||||
const FUZZY_MIN: usize = 3;
|
||||
|
||||
/// `sortText` prefixes. The client sorts on these, so they *are* the tier
|
||||
/// order; the name follows so each tier is alphabetical within itself.
|
||||
const TIER_MODULE: char = '0';
|
||||
/// Members, after a `.` or a `::`.
|
||||
///
|
||||
/// The same digit as tier 0 and not a contradiction: the member answer is
|
||||
/// **exclusive**, so no other tier's item is ever in the same response and
|
||||
/// the digit orders members among themselves and nothing else. `'0'` because
|
||||
/// these are not one tier of an answer but the whole of it. A sixth digit
|
||||
/// would say there is a ranking against the other tiers to express, and there
|
||||
/// is not.
|
||||
const TIER_MEMBER: char = '0';
|
||||
const TIER_SCOPE: char = '1';
|
||||
const TIER_INDEX: char = '2';
|
||||
const TIER_TEMPLATE: char = '3';
|
||||
const TIER_KEYWORD: char = '4';
|
||||
const TIER_WORD: char = '5';
|
||||
|
||||
/// What a multi-line item tells the client about its own whitespace.
|
||||
///
|
||||
/// Every skeleton here is laid out at the *site's* indentation already: a
|
||||
/// `Layout`'s `base` is the trigger line's leading whitespace, and every line
|
||||
/// after the first carries it. An editor that "helpfully" indents the
|
||||
/// insertion again would double it — VS Code's `SnippetSession.adjustWhitespace`
|
||||
/// prepends the insertion line's own indentation to every line after the first,
|
||||
/// and it is on by default (`SuggestController._insertSuggestion` passes
|
||||
/// `adjustWhitespace: !(insertTextRules & KeepWhitespace)`). `asIs` is the
|
||||
/// protocol's way of saying "the text is already positioned, do not touch it",
|
||||
/// and `vscode-languageclient` turns it into exactly the `keepWhitespace` flag
|
||||
/// that clears the rule. Single-line items neither need it nor are harmed by
|
||||
/// it; only the two tiers that write more than one line send it.
|
||||
///
|
||||
/// This is the sibling of the fix `inline.rs` had to make differently: an
|
||||
/// inline completion has no such field, so its bodies are *relative* instead.
|
||||
/// See `docs/features/inline-templates/README.md`, 2026-08-25.
|
||||
const KEEP_MY_INDENTATION: InsertTextMode = InsertTextMode::AS_IS;
|
||||
|
||||
/// The completions available at a position, or nothing when the cursor is
|
||||
/// somewhere no name may be written.
|
||||
///
|
||||
/// `snippets` is what the client advertised: without it a module skeleton is
|
||||
/// inserted as plain text, because a literal `${1:clk}` left in a buffer is
|
||||
/// worse than no tabstops at all.
|
||||
pub fn completions(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
snippets: bool,
|
||||
) -> Option<CompletionResponse> {
|
||||
let doc = ws.document(uri)?;
|
||||
let offset = doc.positions().offset(position);
|
||||
// A buffer that does not lex has no token stream, so nothing here can tell
|
||||
// a comment from code — and the commonest way to break the lexer is to
|
||||
// open a string or a block comment and keep typing. Declining is the safe
|
||||
// half of that trade; the buffer lexes again as soon as it is closed.
|
||||
if doc.tokens.is_empty() || in_comment_or_string(doc, offset) {
|
||||
return None;
|
||||
}
|
||||
let word = typed_word(doc, offset)?;
|
||||
|
||||
// A backtick admits exactly one kind of name, so the answer is only that
|
||||
// kind — and the backtick already typed is inside the replaced range, so
|
||||
// it is never doubled.
|
||||
if word.backtick {
|
||||
// The backtick itself is replaced, so the item may carry its own.
|
||||
let replacing = TextRange::new(word.start.saturating_sub(1), offset);
|
||||
let mut items = Items::new(doc, replacing);
|
||||
for entry in ws.candidates().macros(&word.text) {
|
||||
items.simple(
|
||||
&format!("`{}", entry.name),
|
||||
CompletionItemKind::CONSTANT,
|
||||
TIER_INDEX,
|
||||
entry.detail.clone(),
|
||||
);
|
||||
}
|
||||
return items.finish();
|
||||
}
|
||||
|
||||
// A `.` or a `::` admits exactly one kind of name too — a member of what
|
||||
// stands before it — so the answer is only those. See [`member_answer`].
|
||||
if word.sep.is_some() {
|
||||
return member_answer(ws, doc, &word, offset);
|
||||
}
|
||||
|
||||
// Both position gates read the same scope chain, and neither can be true
|
||||
// unless the word starts a line — so a keystroke in the middle of an
|
||||
// expression pays for neither.
|
||||
let starts_a_line = word.at_line_start || word.statement_head;
|
||||
let chain = match starts_a_line {
|
||||
true => enclosing_scopes(&doc.tokens, word.start),
|
||||
false => Vec::new(),
|
||||
};
|
||||
let at_item = word.at_line_start && at_module_item(doc, &chain, word.start);
|
||||
let at_statement = starts_a_line && at_statement(doc, &chain, word.start);
|
||||
|
||||
// Prefix below [`FUZZY_MIN`], subsequence from it up. One `Query` for the
|
||||
// whole request: it folds the typed characters and computes their mask
|
||||
// once, and every tier that scans a table reads the same prepared form.
|
||||
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
|
||||
|
||||
let mut items = Items::new(doc, word.range(offset));
|
||||
module_tier(&mut items, ws, doc, &word, at_item);
|
||||
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
index_tier(&mut items, ws, &word, fuzzy.as_ref());
|
||||
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
|
||||
keyword_tier(&mut items, &word);
|
||||
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
|
||||
// **The `isIncomplete` trap.** VS Code asks the server again on the next
|
||||
// keystroke *only* when the last answer said it was incomplete; otherwise
|
||||
// it filters the list it already holds. A complete two-character prefix
|
||||
// answer would therefore be filtered client-side for the rest of the word,
|
||||
// and the third keystroke — the one that turns fuzzy on — would never
|
||||
// reach here at all. So every answer below the floor says it is
|
||||
// incomplete, whatever the cap did.
|
||||
//
|
||||
// Above the floor the ordinary rule stands, and is sound because the hit
|
||||
// set only ever *shrinks* as characters are appended: if a name holds
|
||||
// `clke` in order it holds `clk` in order, so a complete answer at three
|
||||
// characters really does contain every answer to four.
|
||||
if fuzzy.is_none() {
|
||||
items.incomplete = true;
|
||||
}
|
||||
items.finish()
|
||||
}
|
||||
|
||||
/// The response under construction: the items, the names already spoken for,
|
||||
/// and whether the cap cut anything off.
|
||||
struct Items {
|
||||
/// The bytes every item replaces, as the client reads them.
|
||||
range: Range,
|
||||
items: Vec<CompletionItem>,
|
||||
seen: HashSet<String>,
|
||||
incomplete: bool,
|
||||
}
|
||||
|
||||
impl Items {
|
||||
fn new(doc: &Document, replacing: TextRange) -> Items {
|
||||
Items {
|
||||
range: doc.positions().range(replacing),
|
||||
items: Vec::new(),
|
||||
seen: HashSet::new(),
|
||||
incomplete: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the cap has been reached. Once it has, every further candidate
|
||||
/// only sets [`Items::incomplete`] — which is why the tiers ask first
|
||||
/// rather than building items nobody will see.
|
||||
fn full(&mut self) -> bool {
|
||||
if self.items.len() >= LIMIT {
|
||||
self.incomplete = true;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Add an item, unless a higher tier already offered that name or the
|
||||
/// response is full.
|
||||
fn push(&mut self, item: CompletionItem) {
|
||||
if self.full() || !self.seen.insert(item.label.clone()) {
|
||||
return;
|
||||
}
|
||||
self.items.push(item);
|
||||
}
|
||||
|
||||
/// A plain-text item that inserts exactly its own name.
|
||||
fn simple(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
|
||||
if self.full() || self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
let item = CompletionItem {
|
||||
label: name.to_string(),
|
||||
kind: Some(kind),
|
||||
detail: Some(detail),
|
||||
sort_text: Some(format!("{tier}{name}")),
|
||||
insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
|
||||
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
||||
range: self.range,
|
||||
new_text: name.to_string(),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
/// One template: the skeleton it inserts, the word it is reached by, and
|
||||
/// the shape it expands to.
|
||||
///
|
||||
/// A client that never said it understands snippets gets the same text
|
||||
/// with every hole filled in rather than nothing at all — the M4 ruling,
|
||||
/// applied to a body whose defaults were chosen so that the result parses.
|
||||
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
|
||||
if self.full() || self.seen.contains(template.label) {
|
||||
return;
|
||||
}
|
||||
let item = CompletionItem {
|
||||
label: template.label.to_string(),
|
||||
kind: Some(CompletionItemKind::SNIPPET),
|
||||
detail: Some(format!("{} — template", template.detail)),
|
||||
documentation: Some(Documentation::MarkupContent(MarkupContent {
|
||||
kind: MarkupKind::Markdown,
|
||||
value: format!("```systemverilog\n{}\n```", template.expansion()),
|
||||
})),
|
||||
// The label is prose, so the client must be told what the user
|
||||
// types to reach the item — otherwise `if` would not match
|
||||
// `if begin/end` at all.
|
||||
filter_text: Some(template.prefix.to_string()),
|
||||
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
|
||||
insert_text_format: Some(match snippets {
|
||||
true => InsertTextFormat::SNIPPET,
|
||||
false => InsertTextFormat::PLAIN_TEXT,
|
||||
}),
|
||||
insert_text_mode: Some(KEEP_MY_INDENTATION),
|
||||
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
||||
range: self.range,
|
||||
new_text: template.render(layout, snippets),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
fn finish(self) -> Option<CompletionResponse> {
|
||||
if self.items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(self.into_list())
|
||||
}
|
||||
|
||||
/// The response whether or not anything is in it.
|
||||
///
|
||||
/// [`Items::finish`]'s `None` means "this was not my question", which is
|
||||
/// the right answer for a tiered response nobody filled. For the
|
||||
/// **exclusive** member answer an empty list is the answer — the site
|
||||
/// resolved and holds no matching member — and it has to be sent rather
|
||||
/// than declined, because `None` carries no `isIncomplete` and so cannot
|
||||
/// ask the client to come back with the third character.
|
||||
fn into_list(self) -> CompletionResponse {
|
||||
CompletionResponse::List(CompletionList {
|
||||
is_incomplete: self.incomplete,
|
||||
items: self.items,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The LSP icon a declaration gets in a completion list. The same choices
|
||||
/// `symbols::lsp_kind` makes for the outline, in the other enum.
|
||||
fn completion_kind(kind: SymbolKind) -> CompletionItemKind {
|
||||
match kind {
|
||||
SymbolKind::Module | SymbolKind::Package | SymbolKind::Block => CompletionItemKind::MODULE,
|
||||
SymbolKind::Interface | SymbolKind::Modport => CompletionItemKind::INTERFACE,
|
||||
SymbolKind::Clocking => CompletionItemKind::EVENT,
|
||||
SymbolKind::Port | SymbolKind::StructMember => CompletionItemKind::FIELD,
|
||||
SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar | SymbolKind::Instance => {
|
||||
CompletionItemKind::VARIABLE
|
||||
}
|
||||
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => {
|
||||
CompletionItemKind::CONSTANT
|
||||
}
|
||||
SymbolKind::Typedef => CompletionItemKind::TYPE_PARAMETER,
|
||||
SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER,
|
||||
SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION,
|
||||
SymbolKind::Class => CompletionItemKind::CLASS,
|
||||
SymbolKind::Constraint | SymbolKind::Coverpoint | SymbolKind::Cross => {
|
||||
CompletionItemKind::PROPERTY
|
||||
}
|
||||
SymbolKind::Covergroup => CompletionItemKind::CLASS,
|
||||
// A property and a sequence are named declarations a concurrent
|
||||
// assertion calls by name, so they take the icon a function does.
|
||||
SymbolKind::Property | SymbolKind::Sequence => CompletionItemKind::FUNCTION,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a visible declaration shows beside its name: the line it was declared
|
||||
/// on, which is the cheapest honest summary there is.
|
||||
fn declaration_detail(doc: &Document, symbol: &Symbol) -> String {
|
||||
let line = doc.positions().whole_lines(symbol.decl_span).lines().next().unwrap_or("").trim();
|
||||
match line.is_empty() {
|
||||
true => kind_label(symbol.kind).to_string(),
|
||||
false => shorten(line, 80),
|
||||
}
|
||||
}
|
||||
|
||||
/// `text`, cut to `max` characters on a character boundary.
|
||||
fn shorten(text: &str, max: usize) -> String {
|
||||
match text.char_indices().nth(max) {
|
||||
Some((at, _)) => format!("{}…", &text[..at]),
|
||||
None => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `offset` sits inside a comment or a string literal — the two places
|
||||
/// a completion list has no business appearing.
|
||||
///
|
||||
/// Comments are lexer trivia hanging off the token that follows (or precedes)
|
||||
/// them, so this reads both. A linear pass over the token stream: a scan of a
|
||||
/// few tens of thousands of tokens is tens of microseconds, and a binary
|
||||
/// search would have to reason about which token a comment attached to.
|
||||
fn in_comment_or_string(doc: &Document, offset: u32) -> bool {
|
||||
for token in &doc.tokens {
|
||||
if token.kind == TokenKind::String && token.span.start < offset && offset < token.span.end {
|
||||
return true;
|
||||
}
|
||||
if token.leading.iter().chain(token.trailing.as_ref()).any(|c| in_comment(c, offset)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `offset` is inside `comment`. A `//` comment runs to the end of the
|
||||
/// line, so a cursor at its last byte is still inside it; a `/* */` one ends
|
||||
/// at its marker, and the byte after that is code again.
|
||||
fn in_comment(comment: &Comment, offset: u32) -> bool {
|
||||
if offset <= comment.span.start {
|
||||
return false;
|
||||
}
|
||||
match comment.text.starts_with("//") {
|
||||
true => offset <= comment.span.end,
|
||||
false => offset < comment.span.end,
|
||||
}
|
||||
}
|
||||
|
||||
/// One tabstop: `${n:default}`, or a bare `${n}` when there is no default to
|
||||
/// preselect. The default is escaped, because `$`, `}` and `\` are the snippet
|
||||
/// grammar's own punctuation and a type like `logic [$bits(t)-1:0]` really
|
||||
/// does contain one.
|
||||
///
|
||||
/// `pub(crate)` for `inline.rs`, whose ghost instantiation writes the same
|
||||
/// holes: one spelling of a tabstop, one place to fix an escaping bug.
|
||||
pub(crate) fn snippet_hole(n: usize, default: &str) -> String {
|
||||
if default.is_empty() {
|
||||
return format!("${{{n}}}");
|
||||
}
|
||||
let mut escaped = String::with_capacity(default.len());
|
||||
for ch in default.chars() {
|
||||
if matches!(ch, '$' | '}' | '\\') {
|
||||
escaped.push('\\');
|
||||
}
|
||||
escaped.push(ch);
|
||||
}
|
||||
format!("${{{n}:{escaped}}}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::candidates::starts_with_ignore_case;
|
||||
use crate::completion::harness::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::uri::path_to_uri;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn a_tabstop_default_is_escaped_so_the_snippet_grammar_cannot_read_it() {
|
||||
assert_eq!(snippet_hole(1, ""), "${1}");
|
||||
assert_eq!(snippet_hole(2, "8"), "${2:8}");
|
||||
assert_eq!(snippet_hole(3, "$bits(t)"), "${3:\\$bits(t)}");
|
||||
assert_eq!(snippet_hole(4, "a}b\\c"), "${4:a\\}b\\\\c}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// comments and strings, both ways round
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn nothing_is_offered_inside_a_comment_or_a_string() {
|
||||
for (name, top, needle) in [
|
||||
("line", "module top;\n // wid\nendmodule\n", "// wid"),
|
||||
("block", "module top;\n /* wid */\nendmodule\n", "/* wid"),
|
||||
("trailing", "module top;\n logic a; // wid\nendmodule\n", "// wid"),
|
||||
("string", "module top;\n initial $display(\"wid\");\nendmodule\n", "\"wid"),
|
||||
] {
|
||||
let (_tree, ws, uri, position) = asking(&format!("in{name}"), top, needle);
|
||||
assert!(completions(&ws, &uri, position, true).is_none(), "{name}: {top}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_byte_after_a_block_comment_is_code_again() {
|
||||
// The other half of the boundary: `/* x */w|` is not inside anything.
|
||||
let top = "module top;\n /* c */ wid\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("afterblock", top, "*/ wid");
|
||||
assert!(completions(&ws, &uri, position, true).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_only_a_comment_or_a_string_holds_is_never_a_candidate() {
|
||||
let tree = Tree::new("harvest");
|
||||
tree.write(
|
||||
"other.sv",
|
||||
"module other;\n // widget_in_comment\n logic widget_in_code;\n\
|
||||
initial $display(\"widget_in_string\");\nendmodule\n",
|
||||
);
|
||||
let top = "module top;\n assign x = widget\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= widget");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let labels = labels(&items);
|
||||
assert!(labels.contains(&"widget_in_code"), "{labels:?}");
|
||||
assert!(!labels.contains(&"widget_in_comment"), "a comment is not code: {labels:?}");
|
||||
assert!(!labels.contains(&"widget_in_string"), "a string is not code: {labels:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at() {
|
||||
let top = "module top;\n logic a; /* unterminated\n wid\n";
|
||||
let (_tree, ws, uri, position) = asking("nolex", top, " wid");
|
||||
assert!(completions(&ws, &uri, position, true).is_none());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `define names and the backtick
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_backtick_offers_macro_names_and_only_macro_names() {
|
||||
let tree = Tree::new("macro");
|
||||
tree.write("defs.svh", "`define WIDTH 8\n`define MAX(a, b) 0\n");
|
||||
tree.write("other.sv", "module other;\n logic WIDGET;\nendmodule\n");
|
||||
let top = "module top;\n assign x = `WI\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "`WI");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(labels(&items), ["`WIDTH"], "only a macro may follow a backtick");
|
||||
assert_eq!(inserted(&items[0]), "`WIDTH");
|
||||
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
|
||||
panic!("a plain edit");
|
||||
};
|
||||
assert_eq!(
|
||||
edit.range.start,
|
||||
Position { line: 1, character: 13 },
|
||||
"the typed backtick is replaced, not doubled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_name_without_a_backtick_is_offered_bare() {
|
||||
// Where a macro name is written without one: `` `ifdef NAME ``.
|
||||
let tree = Tree::new("macrobare");
|
||||
tree.write("defs.svh", "`define WIDTH 8\n");
|
||||
let top = "module top;\n assign x = WID\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= WID");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "WIDTH").expect("the macro name");
|
||||
assert_eq!(inserted(item), "WIDTH", "no backtick is invented");
|
||||
assert_eq!(item.detail.as_deref(), Some("`define WIDTH"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// filtering, the cap, and the scope ladder
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_prefix_filters_server_side() {
|
||||
let tree = Tree::new("prefix");
|
||||
tree.write("other.sv", "module other;\n logic aaa_one, bbb_two;\nendmodule\n");
|
||||
let top = "module top;\n assign x = aaa\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= aaa");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(!items.is_empty());
|
||||
for item in &items {
|
||||
assert!(
|
||||
starts_with_ignore_case(&item.label, "aaa"),
|
||||
"{} does not start with the typed prefix",
|
||||
item.label
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_response_is_truncated_and_says_it_is_incomplete() {
|
||||
let mut top = String::from("module top;\n");
|
||||
for i in 0..LIMIT + 40 {
|
||||
top.push_str(&format!(" logic wsig{i:04};\n"));
|
||||
}
|
||||
top.push_str(" assign x = wsig\nendmodule\n");
|
||||
let (_tree, ws, uri, position) = asking("cap", &top, "= wsig");
|
||||
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
|
||||
panic!("a completion list");
|
||||
};
|
||||
assert_eq!(list.items.len(), LIMIT);
|
||||
assert!(list.is_incomplete, "a truncated list must say so");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_outside_the_filelist_contributes_no_words() {
|
||||
// M1's ladder decides what "the project" is, and the word tier is
|
||||
// built from exactly that list.
|
||||
let tree = Tree::new("filelist");
|
||||
tree.write("listed.sv", "module listed;\n logic word_listed;\nendmodule\n");
|
||||
tree.write("unlisted.sv", "module unlisted;\n logic word_unlisted;\nendmodule\n");
|
||||
tree.write("files.f", "listed.sv\n");
|
||||
let top = "module top;\n assign x = word_\nendmodule\n";
|
||||
let path = tree.write("top.sv", top);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
filelist: Some("files.f".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
ws.rebuild_index();
|
||||
let offset = (top.find("= word_").expect("needle") + 7) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let labels = labels(&items);
|
||||
assert!(labels.contains(&"word_listed"), "{labels:?}");
|
||||
assert!(!labels.contains(&"word_unlisted"), "outside the project: {labels:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_edit_contributes_its_own_words_at_once() {
|
||||
// The buffer's own token stream is read per request, so a name typed
|
||||
// a moment ago is a candidate before anything is saved.
|
||||
let top = "module top;\n logic fresh_name;\n assign x = fre\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("unsaved", top, "= fre");
|
||||
// The file on disk is `top` too, so make the buffer differ from it.
|
||||
let edited = "module top;\n logic fresher_name;\n assign x = fre\nendmodule\n";
|
||||
let mut ws = ws;
|
||||
ws.set_document(uri.clone(), edited.to_string());
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(labels(&items).contains(&"fresher_name"), "{:?}", labels(&items));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the performance claim, measured
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// What a keystroke costs over the real corpus, and what the tables cost
|
||||
/// to build. Skipped when `corpus/` is not checked out
|
||||
/// (`tools/corpus_fetch.sh`), exactly like the other corpus tests.
|
||||
///
|
||||
/// The budgets are deliberately loose — a debug build on a loaded machine
|
||||
/// is the worst case this ever runs in — and exist to catch an *order of
|
||||
/// magnitude* regression, not to pin a number. The numbers themselves are
|
||||
/// in `docs/features/completion-core/README.md`.
|
||||
#[test]
|
||||
fn a_keystroke_over_the_whole_corpus_stays_in_budget() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let build = started.elapsed();
|
||||
|
||||
// A buffer that is not on disk: it overlays the walk, so the corpus is
|
||||
// never written to.
|
||||
let top = "module lucisv_probe;\n logic clk;\n assign x = pr\nendmodule\n";
|
||||
let uri = path_to_uri(&corpus.join("lucisv_probe.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find("= pr").expect("needle") + 4) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
// Warm, then the measurement: ten requests, worst one reported. Twice
|
||||
// — once for a typed prefix, once for the empty one, which is the
|
||||
// worst case there is (every tier matches, and the cap does the work).
|
||||
let empty = ws.document(&uri).expect("open").positions().position(offset - 2);
|
||||
let mut worst = std::time::Duration::ZERO;
|
||||
let mut worst_empty = std::time::Duration::ZERO;
|
||||
for round in 0..11 {
|
||||
let started = std::time::Instant::now();
|
||||
let typed = items(completions(&ws, &uri, position, true));
|
||||
let after_typed = started.elapsed();
|
||||
let started = std::time::Instant::now();
|
||||
let all = items(completions(&ws, &uri, empty, true));
|
||||
let after_empty = started.elapsed();
|
||||
assert!(!typed.is_empty());
|
||||
assert_eq!(all.len(), LIMIT, "the empty prefix fills the response");
|
||||
if round > 0 {
|
||||
worst = worst.max(after_typed);
|
||||
worst_empty = worst_empty.max(after_empty);
|
||||
}
|
||||
}
|
||||
// …and the fuzzy path, which is a *scan* of the whole word table
|
||||
// where the two above are a binary search into it. Six characters,
|
||||
// the shape the round is named after.
|
||||
let fuzzy = "module lucisv_probe;\n logic clk;\n assign x = clkenq\nendmodule\n";
|
||||
ws.set_document(uri.clone(), fuzzy.to_string());
|
||||
let offset = (fuzzy.find("= clkenq").expect("needle") + 8) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let mut worst_fuzzy = std::time::Duration::ZERO;
|
||||
for round in 0..11 {
|
||||
let started = std::time::Instant::now();
|
||||
let found = items(completions(&ws, &uri, position, true));
|
||||
let elapsed = started.elapsed();
|
||||
assert!(!found.is_empty(), "the buffer's own `clk` matches at least");
|
||||
if round > 0 {
|
||||
worst_fuzzy = worst_fuzzy.max(elapsed);
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"corpus: {} files, {} words, {} index names; index+tables built in {build:?}; \
|
||||
worst request {worst:?} typed / {worst_empty:?} empty / {worst_fuzzy:?} fuzzy",
|
||||
ws.index().files().len(),
|
||||
ws.candidates().words("").len(),
|
||||
ws.candidates().units("").len(),
|
||||
);
|
||||
assert!(worst < std::time::Duration::from_millis(150), "a keystroke cost {worst:?}");
|
||||
assert!(worst_empty < std::time::Duration::from_millis(150), "{worst_empty:?}");
|
||||
assert!(worst_fuzzy < std::time::Duration::from_millis(150), "{worst_fuzzy:?}");
|
||||
}
|
||||
|
||||
/// What a **member** request costs over the real corpus, against the
|
||||
/// shapes the feature is named for: a generated register struct
|
||||
/// (`uart_reg2hw_t`, eleven fields whose types are eleven more structs in
|
||||
/// the same package), one of its inner registers reached by the
|
||||
/// synthesized key, a package, and a connection list on a real wide
|
||||
/// module.
|
||||
///
|
||||
/// The member answer is a table lookup like every other tier — one
|
||||
/// `member_site` walk over one file's scopes, then one `BTreeMap` scan
|
||||
/// per unit on the chain — so it should be *cheaper* than the tiered
|
||||
/// answer, which scans three tables. Same loose budget, same reason: an
|
||||
/// order of magnitude, not a number.
|
||||
#[test]
|
||||
fn a_member_request_over_the_whole_corpus_stays_in_budget() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let uri = path_to_uri(&corpus.join("lucisv_member_probe.sv")).expect("uri");
|
||||
|
||||
let mut worst = Vec::new();
|
||||
for (what, top, needle) in [
|
||||
(
|
||||
"reg2hw.",
|
||||
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.\n end\nendmodule\n",
|
||||
" reg2hw.",
|
||||
),
|
||||
(
|
||||
"reg2hw.ctrl.",
|
||||
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n",
|
||||
" reg2hw.ctrl.",
|
||||
),
|
||||
(
|
||||
"uart_reg_pkg::",
|
||||
"module lucisv_member_probe;\n initial begin\n $display(uart_reg_pkg::);\n end\nendmodule\n",
|
||||
"uart_reg_pkg::",
|
||||
),
|
||||
// The connection list, against a real wide module in another
|
||||
// file — the position the 2026-09-02 rework exists for.
|
||||
(
|
||||
"uart_core (.",
|
||||
"module lucisv_member_probe;\n uart_core u_core (\n .\n );\nendmodule\n",
|
||||
" .",
|
||||
),
|
||||
] {
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find(needle).expect("needle") + needle.len()) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let mut slowest = std::time::Duration::ZERO;
|
||||
let mut count = 0;
|
||||
for round in 0..11 {
|
||||
let started = std::time::Instant::now();
|
||||
let found = items(completions(&ws, &uri, position, true));
|
||||
let elapsed = started.elapsed();
|
||||
count = found.len();
|
||||
if round > 0 {
|
||||
slowest = slowest.max(elapsed);
|
||||
}
|
||||
}
|
||||
assert!(count > 0, "{what} must list members over the corpus");
|
||||
worst.push(format!("{what} {count} members in {slowest:?}"));
|
||||
assert!(slowest < std::time::Duration::from_millis(150), "{what} cost {slowest:?}");
|
||||
}
|
||||
eprintln!("corpus member requests: {}", worst.join(" / "));
|
||||
}
|
||||
|
||||
/// **QA's own reproduction, against the real file.** `prim_fifo_sync`
|
||||
/// derives `localparam int DepthW = prim_util_pkg::vbits(Depth+1)` in its
|
||||
/// header; six `parameter`s stand above it. A `#(.` list must offer the
|
||||
/// six and not the seventh. Skipped when `corpus/` is not checked out,
|
||||
/// like every other corpus test.
|
||||
#[test]
|
||||
fn the_opentitan_shape_that_found_the_localparam_bug() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let top = "module lucisv_param_probe;\n prim_fifo_sync #(.) u_fifo ();\nendmodule\n";
|
||||
let uri = path_to_uri(&corpus.join("lucisv_param_probe.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find("#(.").expect("needle") + 3) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
let mut found = labels(&answer);
|
||||
found.sort();
|
||||
assert_eq!(
|
||||
found,
|
||||
vec!["Depth", "NeverClears", "OutputZeroIfEmpty", "Pass", "Secure", "Width"],
|
||||
"the six overridable parameters, and not the derived `DepthW`",
|
||||
);
|
||||
// …and `DepthW` is still *there*: a hierarchical read of it is legal
|
||||
// and still resolves, which is what the split deliberately preserved.
|
||||
assert!(
|
||||
ws.index().members_of_chain("prim_fifo_sync").iter().any(|(name, _)| *name == "DepthW"),
|
||||
"the localparam is still exported",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,923 @@
|
||||
//! Tier 0 — module names at module-item position — and the instantiation
|
||||
//! planning that `inline.rs`'s ghost and `instantiate.rs`'s command share.
|
||||
//!
|
||||
//! The tier itself is a table scan: the names the workspace declares, ranked
|
||||
//! above everything else where an instantiation may be written. The planning
|
||||
//! half is the one part of completion that costs a *parse*, and it is here
|
||||
//! rather than in `inline.rs` because there must be exactly one answer to
|
||||
//! "which file, and which header, is this module planned from" —
|
||||
//! `nearest_definition` chooses among duplicate declarations and
|
||||
//! `module_header` slices the declaring file down to its header before the
|
||||
//! plan is built. See `docs/features/inline-instantiation/README.md` and
|
||||
//! `docs/features/refactor-instantiate/README.md`.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::{InstantiationPlan, Site};
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::word::Word;
|
||||
use super::{Items, TIER_MODULE};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
|
||||
/// How many module names one response carries.
|
||||
///
|
||||
/// Its own cap, below [`LIMIT`](super::LIMIT), because tier 0 matches a
|
||||
/// *substring* and so answers far more widely than the prefix tiers: an empty word at item
|
||||
/// position matches all 1 544 modules of opentitan, and letting one tier fill
|
||||
/// the whole response would starve the five below it. It no longer bounds any
|
||||
/// *work* — the tier is a scan of a table and nothing else, where until
|
||||
/// 2026-08-30 each item cost one file read and one header parse.
|
||||
const MODULE_LIMIT: usize = 64;
|
||||
|
||||
/// How far past a module's name [`module_header`] reads looking for the end of
|
||||
/// its header, smallest first.
|
||||
///
|
||||
/// A ladder rather than one bound because the lex is the whole cost of the
|
||||
/// slice and it is linear in what it is handed, so every header would
|
||||
/// otherwise pay for the widest one. The rungs come from measuring opentitan's
|
||||
/// 344 RTL modules: **59% of headers end inside 256 bytes**, 90% inside 2 KB,
|
||||
/// and the largest — `aes_control_fsm_n`, sixty commented ports — is 6.6 KB.
|
||||
/// The top rung is well past that, because a rung that is too small is not a
|
||||
/// wrong answer but a whole-file parse, and for those files that is 2–4 ms
|
||||
/// against the 0.6 ms of lexing 16 KB.
|
||||
const HEADER_WINDOWS: [usize; 3] = [256, 2 * 1024, 16 * 1024];
|
||||
|
||||
/// Tier 0: the names of the modules that could be instantiated here, at
|
||||
/// module-item position only.
|
||||
///
|
||||
/// **Names, not skeletons, since 2026-08-30** (owner ruling). Until then each
|
||||
/// item carried the whole instantiation, which cost one `module_definition`
|
||||
/// lookup, one file read and one header parse *per candidate* — up to
|
||||
/// [`MODULE_LIMIT`] of each, on every keystroke, for a list the user reads one
|
||||
/// line of. The instantiation is now offered by `inline.rs` as ghost text,
|
||||
/// once the name before the cursor is spelled exactly and a space follows it,
|
||||
/// and is planned once.
|
||||
/// See `docs/features/inline-instantiation/README.md`.
|
||||
///
|
||||
/// What survives is the ranking, which is the tier's real job: at a position
|
||||
/// where an instantiation may be written, a module name beats every other kind
|
||||
/// of name, and it is matched as a *substring* so `reg_top` reaches
|
||||
/// `aes_reg_top`.
|
||||
pub(super) fn module_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
at_item: bool,
|
||||
) {
|
||||
if !at_item {
|
||||
return;
|
||||
}
|
||||
// The same names `vlog_refactor::module_names` answers, off the table
|
||||
// built with the index instead of off the index's whole symbol table —
|
||||
// which the old call rebuilt and re-sorted on every keystroke.
|
||||
let names = ws.candidates().modules(&word.text);
|
||||
if names.len() > MODULE_LIMIT {
|
||||
items.incomplete = true;
|
||||
}
|
||||
for name in names.into_iter().take(MODULE_LIMIT) {
|
||||
items.simple(
|
||||
name,
|
||||
CompletionItemKind::MODULE,
|
||||
TIER_MODULE,
|
||||
module_detail(ws.index(), name, doc.path.as_deref()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a module item shows beside its name: where the module is declared.
|
||||
///
|
||||
/// A lookup in the index's unit table — no file is opened. The wording is tier
|
||||
/// 2's, so a module offered by either tier reads the same.
|
||||
///
|
||||
/// **The file named is the one the ghost will read** ([`nearest_definition`]),
|
||||
/// which since round 2 (2026-08-30) is an answer even for a name two files
|
||||
/// declare: `ast_dft` under `top_earlgrey` and `ast_dft` under `top_darjeeling`
|
||||
/// are two different headers, and the popup saying which one is coming is worth
|
||||
/// more than the bare kind label it used to fall back to.
|
||||
fn module_detail(index: &WorkspaceIndex, module: &str, from: Option<&Path>) -> String {
|
||||
// An interface is instantiated exactly as a module is and rides this same
|
||||
// list, so the label is read off what the index actually holds — a card
|
||||
// that said "module" over an `interface` would be the wrong answer this
|
||||
// round exists to remove.
|
||||
let kind = index
|
||||
.units(module)
|
||||
.iter()
|
||||
.find(|def| def.kind.is_instantiable())
|
||||
.map_or(SymbolKind::Module, |def| def.kind);
|
||||
let label = kind_label(kind);
|
||||
let Some(path) = nearest_definition(index, module, from) else {
|
||||
return label.to_string();
|
||||
};
|
||||
match path.file_name().and_then(|name| name.to_str()) {
|
||||
Some(file) => format!("{label} — {file}"),
|
||||
None => label.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file whose declaration of `module` a request made in `from` should be
|
||||
/// planned from.
|
||||
///
|
||||
/// **This never refuses on multiplicity**, which is the whole of what parts it
|
||||
/// from `vlog_refactor::module_definition`. That one errors when a name is
|
||||
/// declared twice and will not guess; in opentitan `ast_dft` and `io_osc` are
|
||||
/// each declared once under `hw/top_earlgrey/ip/ast/rtl` and once under
|
||||
/// `hw/top_darjeeling/ip/ast/rtl`, so refusing meant two whole IP blocks with
|
||||
/// no ghost at all. The owner's ruling of 2026-08-30 is that every indexed
|
||||
/// module expands, so the server chooses instead of declining — and
|
||||
/// `module_definition` keeps its refusal for its own callers, which want an
|
||||
/// error message rather than a guess.
|
||||
///
|
||||
/// The rule is **nearest to the asker**: the declaration whose path shares the
|
||||
/// longest run of leading *path components* with the document being typed in,
|
||||
/// so a buffer under `hw/top_earlgrey/…` is offered top_earlgrey's copy. A tie
|
||||
/// — and a buffer with no path at all — falls to the lexicographically smallest
|
||||
/// path, so the answer never depends on the order the index happened to be
|
||||
/// built in. Where the two declarations have different headers the user gets
|
||||
/// the nearest one's; that is the accepted semantics, not an approximation.
|
||||
///
|
||||
/// A module only one file declares is chosen by exactly this path too, and
|
||||
/// picks that one file — the same answer `module_definition` gives.
|
||||
pub(crate) fn nearest_definition<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
module: &str,
|
||||
from: Option<&Path>,
|
||||
) -> Option<&'i Path> {
|
||||
index
|
||||
.units(module)
|
||||
.iter()
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.filter_map(|def| index.path(def.file))
|
||||
// Most shared leading components first; among those, the *shallowest*
|
||||
// candidate — fewest components of its own past the shared prefix —
|
||||
// then the lexicographically smallest path. The depth key is the QA
|
||||
// round-2 fix: a copy in the asking buffer's own directory and one in
|
||||
// a subdirectory of it share the same prefix with the buffer (the
|
||||
// buffer's filename never matches a directory), and without the depth
|
||||
// key the lexicographic tie-break could prefer the deeper, less
|
||||
// related copy (`rstmgr/dv/rstmgr_cnsty_chk/tb.sv` over the direct
|
||||
// sibling `rstmgr/dv/tb.sv`, because `'r' < 't'`).
|
||||
.min_by_key(|path| {
|
||||
let shared = shared_components(path, from);
|
||||
(Reverse(shared), path.components().count() - shared, *path)
|
||||
})
|
||||
}
|
||||
|
||||
/// How many leading path components `path` and `from` spell the same way.
|
||||
///
|
||||
/// Components, not bytes: `hw/top_earlgrey` and `hw/top_darjeeling` share `hw`
|
||||
/// and nothing else, where a byte-wise prefix would count `hw/top_` as shared
|
||||
/// and rank two unrelated copies by a coincidence of spelling.
|
||||
fn shared_components(path: &Path, from: Option<&Path>) -> usize {
|
||||
let Some(from) = from else { return 0 };
|
||||
path.components().zip(from.components()).take_while(|(ours, theirs)| ours == theirs).count()
|
||||
}
|
||||
|
||||
/// One module's instantiation plan, off its header alone where that is the
|
||||
/// whole of what the plan reads, and off its whole file otherwise.
|
||||
///
|
||||
/// The slice is an optimisation and never an answer of its own. Two things
|
||||
/// send this back to the whole file, and both leave the answer exactly what it
|
||||
/// was before the slice existed:
|
||||
///
|
||||
/// * the slice does not plan at all — [`module_header`] cut a header this
|
||||
/// parser does not read as one;
|
||||
/// * the plan it produced has a port with neither a direction nor a type,
|
||||
/// which is what a **non-ANSI** port list looks like once its body is gone:
|
||||
/// `module m (a); input wire a;` writes the direction below the header, and
|
||||
/// the body is the part the slice drops.
|
||||
///
|
||||
/// `pub(crate)` for `inline.rs`, which plans the one module the user has
|
||||
/// spelled out. One planner on purpose: a second answer to "what is this
|
||||
/// module's instantiation" would eventually disagree with this one, and any
|
||||
/// future non-ghost spelling of the skeleton (a command for clients without
|
||||
/// `inlineCompletion`, say — filed in `docs/topo.md` §2.9) must come through
|
||||
/// here too.
|
||||
pub(crate) fn plan_for(
|
||||
index: &WorkspaceIndex,
|
||||
module: &str,
|
||||
definition: &str,
|
||||
site: Site<'_>,
|
||||
) -> Result<InstantiationPlan, String> {
|
||||
let whole = || vlog_refactor::instantiation_plan(module, definition, Some(site));
|
||||
let Some(header) = module_header(index, module, definition) else { return whole() };
|
||||
match vlog_refactor::instantiation_plan(module, &header, Some(site)) {
|
||||
Ok(plan) if plan.ports.iter().all(|p| !p.dir.is_empty() || !p.ty.is_empty()) => Ok(plan),
|
||||
_ => whole(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text one skeleton is planned from: the declaring file's header alone
|
||||
/// where this function can find it, and the whole file where it cannot.
|
||||
///
|
||||
/// Tier 0 is the one tier that costs a *parse*, and until 2026-08-28 it parsed
|
||||
/// the whole declaring file — three hundred lines of body to read a header a
|
||||
/// few hundred bytes long, [`MODULE_LIMIT`] times per keystroke. A plan reads
|
||||
/// nothing but the header, so nothing but the header needs to be parsed.
|
||||
///
|
||||
/// The prefix is kept **byte for byte**: every span the plan reads is an offset
|
||||
/// into the text it was parsed from, so cutting the front off would move them
|
||||
/// all. Only the body is dropped, and an `endmodule` is written in its place so
|
||||
/// the declaration is closed.
|
||||
///
|
||||
/// **Every declaration of the name is tried, not just a lone one** (round 2,
|
||||
/// 2026-08-30). Until then a name two files declared made this decline outright,
|
||||
/// which cost `ast_dft` and `io_osc` their ghost; it now walks them, because
|
||||
/// the index's span is only ever a *hint* here and the guard below is what
|
||||
/// makes a hint safe. A span from the wrong file either does not spell the
|
||||
/// module's name in this text — declined, and the caller parses the whole file
|
||||
/// instead, exactly as it did before — or it does, in which case the slice is
|
||||
/// taken from a real occurrence of the name in the text actually being read.
|
||||
pub(crate) fn module_header(index: &WorkspaceIndex, module: &str, text: &str) -> Option<String> {
|
||||
index
|
||||
.units(module)
|
||||
.iter()
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.find_map(|def| header_from(module, def.name_span, text))
|
||||
}
|
||||
|
||||
/// The header of the declaration `text` spells at `name`, or `None` when it
|
||||
/// does not spell one there at all.
|
||||
fn header_from(module: &str, name: TextRange, text: &str) -> Option<String> {
|
||||
// The index's span is as of the last scan, and may belong to a sibling
|
||||
// file that declares the same module. A file edited on disk since then has
|
||||
// moved it, and a slice taken at a stale offset would be a different
|
||||
// module's header — so the name has to still be there.
|
||||
if text.get(name.start as usize..name.end as usize) != Some(module) {
|
||||
return None;
|
||||
}
|
||||
let from = name.end as usize;
|
||||
for size in HEADER_WINDOWS {
|
||||
// A window that cuts a block comment or a string in half does not lex,
|
||||
// and one that cuts the port list in half runs out of tokens before
|
||||
// the `;`. Both answer "not in this window" and are asked again at the
|
||||
// next rung; both answer `None` at the last one.
|
||||
let window = text.get(from..text.len().min(from + size))?;
|
||||
if let Ok(tokens) = vlog_parser::tokenize(window) {
|
||||
if let Some(end) = header_end(&tokens) {
|
||||
let head = text.get(..from + end as usize)?;
|
||||
return Some(format!("{head}\nendmodule\n"));
|
||||
}
|
||||
}
|
||||
if from + size >= text.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Where the header that begins just after a module's name ends: the offset
|
||||
/// one past its terminating `;`, in the window's own coordinates.
|
||||
///
|
||||
/// A **whitelist**, not a scan for the first `;`: `module aes import
|
||||
/// aes_pkg::*; #(...) (...);` writes three of them and only the last ends the
|
||||
/// header. Anything this does not recognise — a compiler directive between the
|
||||
/// name and the port list, a header longer than the window — answers `None`,
|
||||
/// and the caller parses the whole file rather than guessing.
|
||||
fn header_end(tokens: &[Token]) -> Option<u32> {
|
||||
let mut at = 0;
|
||||
loop {
|
||||
let token = tokens.get(at)?;
|
||||
match token.text.as_str() {
|
||||
";" => return Some(token.span.end),
|
||||
// A lifetime qualifier: `module automatic foo (...);`.
|
||||
"static" | "automatic" => at += 1,
|
||||
// A package import written into the header, whose own `;` is not
|
||||
// the header's.
|
||||
"import" => at = skip_to_semicolon(tokens, at + 1)?,
|
||||
// The parameter list, the port list, and an attribute instance —
|
||||
// each one parenthesised, each one skipped whole.
|
||||
"#" | "(" => at = skip_parens(tokens, at)?,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the parenthesised group starting at `at`, which a `#` may introduce.
|
||||
fn skip_parens(tokens: &[Token], mut at: usize) -> Option<usize> {
|
||||
while tokens.get(at)?.text == "#" {
|
||||
at += 1;
|
||||
}
|
||||
if tokens.get(at)?.text != "(" {
|
||||
return None;
|
||||
}
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
match tokens.get(at)?.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" if depth == 1 => return Some(at + 1),
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the next `;` written outside any parentheses.
|
||||
fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
match tokens.get(at)?.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
";" if depth == 0 => return Some(at + 1),
|
||||
_ => {}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
//! What may be written here: the module-item gate and the statement gate,
|
||||
//! judged over the token stream's scope chain.
|
||||
//!
|
||||
//! Both are heuristics over `pairs::analyze` — the same scope matcher the
|
||||
//! begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
|
||||
//! an unbalanced one still answers. Tier 0, the templates, `inline.rs`'s
|
||||
//! ghost instantiation and `instantiate.rs` all ask these two questions, and
|
||||
//! they ask them here so there is one answer to "may an instantiation go
|
||||
//! here". The consts at the top are the whole of the grammar the gates know.
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use super::word::line_head_is_blank;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// The scopes a module instantiation may be written directly inside.
|
||||
const ITEM_SCOPES: &[&str] =
|
||||
&["module", "macromodule", "interface", "program", "generate", "begin"];
|
||||
|
||||
/// Scopes that make everything inside them something other than a module item:
|
||||
/// a subprogram body, a class body, a checker-ish declaration, a `case` arm's
|
||||
/// interior, a `fork` block.
|
||||
const NOT_ITEM_SCOPES: &[&str] = &[
|
||||
"function",
|
||||
"task",
|
||||
"class",
|
||||
"covergroup",
|
||||
"property",
|
||||
"sequence",
|
||||
"clocking",
|
||||
"specify",
|
||||
"primitive",
|
||||
"fork",
|
||||
"case",
|
||||
"casex",
|
||||
"casez",
|
||||
"randcase",
|
||||
];
|
||||
|
||||
/// The scopes a *statement* may be written directly inside. A `begin` or a
|
||||
/// `fork` qualifies only when it is procedural (see [`at_statement`]); a
|
||||
/// `function`/`task` body always does.
|
||||
const STATEMENT_SCOPES: &[&str] = &["begin", "fork", "function", "task"];
|
||||
|
||||
/// Keywords that make the `begin` after them procedural, so nothing inside it
|
||||
/// is a module item. `@` is on the list because it is the whole of what stands
|
||||
/// between `always` and its `begin`.
|
||||
const PROCEDURAL: &[&str] =
|
||||
&["always", "always_ff", "always_comb", "always_latch", "initial", "final", "@"];
|
||||
|
||||
/// Tokens that end whatever came before them, stopping the backward scan that
|
||||
/// looks for a [`PROCEDURAL`] keyword.
|
||||
const STATEMENT_END: &[&str] =
|
||||
&["begin", "end", "endcase", "join", "join_any", "join_none", "generate", ";"];
|
||||
|
||||
/// Whether a module instantiation may be written starting at `at`.
|
||||
///
|
||||
/// **Tier 0's own gate**, factored out so `inline.rs`'s ghost instantiation
|
||||
/// asks the identical question: the two features offer the same construct, and
|
||||
/// a second answer to "may an instantiation go here" would eventually disagree
|
||||
/// with this one. Both halves are here — the word must start its line, and the
|
||||
/// scope chain covering it must be one an item belongs to (see
|
||||
/// [`at_module_item`] for what that means and what it cannot see).
|
||||
pub(crate) fn at_instantiation_site(doc: &Document, at: u32) -> bool {
|
||||
if !line_head_is_blank(&doc.text, at) {
|
||||
return false;
|
||||
}
|
||||
at_module_item(doc, &enclosing_scopes(&doc.tokens, at), at)
|
||||
}
|
||||
|
||||
/// Whether `at` is somewhere a module instantiation could be written, judged
|
||||
/// over the token stream.
|
||||
///
|
||||
/// This is a **heuristic, not a parse**, and the README says exactly what it
|
||||
/// gets wrong. It reuses `pairs::analyze` — the same scope matcher the
|
||||
/// begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
|
||||
/// an unbalanced one still answers. Three conditions, all necessary:
|
||||
///
|
||||
/// 1. the innermost scope open here is one of [`ITEM_SCOPES`];
|
||||
/// 2. no scope in the chain is one of [`NOT_ITEM_SCOPES`], so a `begin` inside
|
||||
/// a `function` or a `case` arm is rejected however module-ish its parent;
|
||||
/// 3. the outermost `begin` in the chain is not a procedural one — a
|
||||
/// generate-`for`'s `begin` qualifies, an `always @(...)`'s does not.
|
||||
///
|
||||
/// Parentheses close the door too: an item never starts inside one, which is
|
||||
/// what keeps a port list and a connection list out.
|
||||
pub(super) fn at_module_item(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
|
||||
let tokens = &doc.tokens;
|
||||
if tokens.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(&(innermost, opener)) = chain.first() else { return false };
|
||||
if !ITEM_SCOPES.contains(&innermost) {
|
||||
return false;
|
||||
}
|
||||
if chain.iter().any(|(keyword, _)| NOT_ITEM_SCOPES.contains(keyword)) {
|
||||
return false;
|
||||
}
|
||||
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
|
||||
if let Some(&(_, span)) = outermost_begin {
|
||||
if is_procedural(tokens, span.start) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
balanced(tokens, opener.end, at)
|
||||
}
|
||||
|
||||
/// Whether `at` is somewhere a *statement* could be written, judged over the
|
||||
/// same scope chain [`at_module_item`] reads.
|
||||
///
|
||||
/// Two ways to qualify, and they are the only two this asks about:
|
||||
///
|
||||
/// 1. the innermost open scope is a `function` or a `task`, whose body is
|
||||
/// statements all the way down; or
|
||||
/// 2. it is a `begin`/`fork` whose outermost `begin` is a procedural one — the
|
||||
/// exact inverse of the test that keeps module items out of an `always`.
|
||||
///
|
||||
/// Everything else is refused, `case` arms included: a bare `if` is not a
|
||||
/// legal case item, and a gate that guesses at one would offer a template that
|
||||
/// does not compile. Parentheses close the door here too.
|
||||
pub(super) fn at_statement(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
|
||||
let tokens = &doc.tokens;
|
||||
if tokens.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(&(innermost, opener)) = chain.first() else { return false };
|
||||
if !STATEMENT_SCOPES.contains(&innermost) {
|
||||
return false;
|
||||
}
|
||||
if innermost == "begin" || innermost == "fork" {
|
||||
let in_subprogram = chain.iter().any(|(kw, _)| *kw == "function" || *kw == "task");
|
||||
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
|
||||
let procedural = match outermost_begin {
|
||||
Some(&(_, span)) => is_procedural(tokens, span.start),
|
||||
None => false,
|
||||
};
|
||||
if !in_subprogram && !procedural {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
balanced(tokens, opener.end, at)
|
||||
}
|
||||
|
||||
/// The scopes open at `at`, innermost first, as `(keyword, opener span)`.
|
||||
pub(super) fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)> {
|
||||
let analysis = pairs::analyze(tokens);
|
||||
let mut out: Vec<(&'static str, TextRange)> = analysis
|
||||
.pairs
|
||||
.iter()
|
||||
.filter(|pair| pair.open.end <= at && at <= pair.close.start)
|
||||
.map(|pair| (pair.keyword, pair.open))
|
||||
.chain(
|
||||
analysis
|
||||
.unmatched_open
|
||||
.iter()
|
||||
.filter(|open| open.span.end <= at)
|
||||
.map(|open| (open.keyword, open.span)),
|
||||
)
|
||||
.collect();
|
||||
// Innermost first: the scope that opened last is the one we are in.
|
||||
out.sort_by_key(|(_, span)| std::cmp::Reverse(span.start));
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the `begin` starting at `offset` belongs to a procedural block.
|
||||
///
|
||||
/// Read backwards from the keyword: `always @(posedge clk) begin` reaches `@`
|
||||
/// and then `always`, `initial begin` reaches `initial`, while a generate
|
||||
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
|
||||
/// `generate begin` reaches `generate`. Whichever comes first decides.
|
||||
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
|
||||
// A token starting exactly at `offset` is the first one that starts at or
|
||||
// after it: every earlier token starts before, every later token after.
|
||||
let begin = first_token_from(tokens, offset);
|
||||
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
|
||||
return false;
|
||||
}
|
||||
for token in tokens[..begin].iter().rev() {
|
||||
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
|
||||
return true;
|
||||
}
|
||||
if STATEMENT_END.iter().any(|kw| token.text == *kw) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether every parenthesis opened between `from` and `at` was closed again.
|
||||
pub(super) fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
|
||||
let mut depth = 0i32;
|
||||
// The tokens whose start falls in `[from, at)` are a contiguous run,
|
||||
// because starts rise across the vector — so the filter this replaced was
|
||||
// reading the whole buffer to reach a window the two bounds name outright.
|
||||
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
|
||||
for token in &tokens[window] {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
match token.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
depth == 0
|
||||
}
|
||||
|
||||
/// The whitespace the line holding `offset` begins with.
|
||||
pub(super) fn line_indent(text: &str, offset: u32) -> String {
|
||||
let Some(head) = text.get(..offset as usize) else { return String::new() };
|
||||
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
head.get(line_start..).unwrap_or("").chars().take_while(|c| *c == ' ' || *c == '\t').collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [`is_procedural`] used to sweep the vector for the token starting at
|
||||
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
|
||||
/// two offsets name. Both now binary-search; both must answer exactly what
|
||||
/// the sweeps answered, at every byte and for every window.
|
||||
#[test]
|
||||
fn the_scope_gates_answer_what_their_sweeps_answered() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
|
||||
let tokens = &doc.tokens;
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = tokens.iter().position(|token| token.span.start == offset);
|
||||
let searched = {
|
||||
let begin = first_token_from(tokens, offset);
|
||||
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
|
||||
};
|
||||
assert_eq!(swept, searched, "the token starting at {offset}");
|
||||
}
|
||||
// Every `begin`/`end` opener in the buffer against a spread of cursors
|
||||
// after it: the two bounds are what pick the window out.
|
||||
let openers: Vec<u32> = tokens
|
||||
.iter()
|
||||
.filter(|t| t.text == "begin" || t.text == "(")
|
||||
.map(|t| t.span.end)
|
||||
.collect();
|
||||
assert!(openers.len() > 20, "premise: plenty of windows to check");
|
||||
for from in openers {
|
||||
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
|
||||
let mut depth = 0i32;
|
||||
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
match token.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
//! Tiers 1 to 5: the five ordinary tiers, in the order they fill the
|
||||
//! response.
|
||||
//!
|
||||
//! What the scope chain binds, what the workspace index declares (macro
|
||||
//! names included), the templates, the keywords, and every identifier the
|
||||
//! project's token streams contain. Each is a filter over one table with the
|
||||
//! house matching rule — prefix below `FUZZY_MIN`, subsequence from it up —
|
||||
//! and each stops the moment the response is full. Tier 0 lives in
|
||||
//! `module.rs` because its planning half is a different kind of work; the
|
||||
//! member answer lives in `member.rs` because it is exclusive rather than a
|
||||
//! tier.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Semantics, Symbol};
|
||||
|
||||
use super::site::line_indent;
|
||||
use super::word::Word;
|
||||
use super::{
|
||||
completion_kind, declaration_detail, Items, LIMIT, TIER_INDEX, TIER_KEYWORD, TIER_SCOPE,
|
||||
TIER_WORD,
|
||||
};
|
||||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Candidate, Query, Score};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::{self, Gate, Template};
|
||||
|
||||
/// Tier 1: everything the scope chain at the cursor binds.
|
||||
///
|
||||
/// The one fuzzy tier with no mask table behind it, and deliberately so: what
|
||||
/// a scope chain binds is tens of names computed per request, where a table of
|
||||
/// masks would cost more to build than the scan it saved.
|
||||
pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
|
||||
let visible = visible_symbols(&doc.semantics, word.start);
|
||||
let matched: Vec<&Symbol> = match fuzzy {
|
||||
None => visible
|
||||
.into_iter()
|
||||
.filter(|symbol| starts_with_ignore_case(&symbol.name, &word.text))
|
||||
.collect(),
|
||||
Some(query) => {
|
||||
let mut hits: Vec<(&Symbol, Score)> = visible
|
||||
.into_iter()
|
||||
.filter_map(|symbol| Some((symbol, query.score(&symbol.name)?)))
|
||||
.collect();
|
||||
hits.sort_by(|a, b| rank_cmp((&a.0.name, a.1), (&b.0.name, b.1)));
|
||||
hits.into_iter().map(|(symbol, _)| symbol).collect()
|
||||
}
|
||||
};
|
||||
for symbol in matched {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(
|
||||
&symbol.name,
|
||||
completion_kind(symbol.kind),
|
||||
TIER_SCOPE,
|
||||
declaration_detail(doc, symbol),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every declaration the scope chain covering `offset` binds, innermost scope
|
||||
/// first, each name only once — the inner declaration shadows the outer one,
|
||||
/// which is the rule `vlog_semantic`'s own lookup follows.
|
||||
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
|
||||
let mut out = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut at = innermost_scope(semantics, offset);
|
||||
while let Some(id) = at {
|
||||
let Some(scope) = semantics.scope(id) else { break };
|
||||
for symbol in scope.symbols.iter().filter_map(|&id| semantics.symbol(id)) {
|
||||
if seen.insert(symbol.name.as_str()) {
|
||||
out.push(symbol);
|
||||
}
|
||||
}
|
||||
at = scope.parent;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The smallest scope whose span covers `offset`.
|
||||
pub(super) fn innermost_scope(
|
||||
semantics: &Semantics,
|
||||
offset: u32,
|
||||
) -> Option<vlog_semantic::ScopeId> {
|
||||
semantics
|
||||
.scopes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, scope)| scope.span.contains(offset))
|
||||
.min_by_key(|(_, scope)| scope.span.len())
|
||||
.map(|(i, _)| vlog_semantic::ScopeId(i as u32))
|
||||
}
|
||||
|
||||
/// Tier 2: what the workspace index declares, `` `define`` names included.
|
||||
///
|
||||
/// The index names match fuzzily from [`FUZZY_MIN`](super::FUZZY_MIN) up;
|
||||
/// the macro names do not. That is a deliberate split, not an oversight — see the feature
|
||||
/// README's *What did not go fuzzy*.
|
||||
pub(super) fn index_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
|
||||
let matched: Vec<&Candidate> = match fuzzy {
|
||||
None => ws.candidates().units(&word.text).iter().collect(),
|
||||
Some(query) => {
|
||||
let hits = ws.candidates().units_fuzzy(query, LIMIT);
|
||||
// A full return means the scan kept its best LIMIT and dropped the
|
||||
// rest, so the response is a best-of and has to say so. `full()`
|
||||
// below would only notice if every one of them reached the list,
|
||||
// and a name a higher tier already claimed does not.
|
||||
items.incomplete |= hits.len() >= LIMIT;
|
||||
hits.into_iter().map(|(unit, _)| unit).collect()
|
||||
}
|
||||
};
|
||||
for candidate in matched {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(
|
||||
&candidate.name,
|
||||
completion_kind(candidate.kind),
|
||||
TIER_INDEX,
|
||||
format!("{} — {}", kind_label(candidate.kind), candidate.detail),
|
||||
);
|
||||
}
|
||||
// Bare, with no backtick invented. A macro *use* is spelled with one and
|
||||
// the user types it (see the early return above); the places a macro name
|
||||
// is written without one — `` `ifdef NAME ``, `` `undef NAME `` — are
|
||||
// exactly where this item is the right text.
|
||||
for entry in ws.candidates().macros(&word.text) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(&entry.name, CompletionItemKind::CONSTANT, TIER_INDEX, entry.detail.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 3: the statement, item and declaration templates.
|
||||
///
|
||||
/// Above the keywords because a user who typed `if` almost always wants
|
||||
/// `if (…) begin … end` rather than the three letters they already typed, and
|
||||
/// below both semantic tiers because a name the code actually declares beats a
|
||||
/// skeleton every time. The templates a *position* rules out never reach the
|
||||
/// list at all, so the ranking argument only has to hold where they do.
|
||||
pub(super) fn template_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
snippets: bool,
|
||||
at_item: bool,
|
||||
at_statement: bool,
|
||||
) {
|
||||
if !at_item && !at_statement {
|
||||
return;
|
||||
}
|
||||
let layout = layout_at(ws, doc, word.start);
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
for template in templates::for_dialect(dialect) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
if !offered(template, at_item, at_statement) {
|
||||
continue;
|
||||
}
|
||||
if !starts_with_ignore_case(template.prefix, &word.text) {
|
||||
continue;
|
||||
}
|
||||
items.template(template, &layout, snippets);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a template's gate lets it be written where the cursor is.
|
||||
fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool {
|
||||
match template.gate {
|
||||
Gate::Statement | Gate::ElseTail => at_statement,
|
||||
Gate::Item => at_item,
|
||||
// A declaration is a module item and a block item both.
|
||||
Gate::Declaration => at_item || at_statement,
|
||||
}
|
||||
}
|
||||
|
||||
/// How generated text is indented at `offset`: the line's own indentation, and
|
||||
/// one step as `lucisv.indent` spells it.
|
||||
///
|
||||
/// Private from 2026-08-25 to 2026-09-02: `inline.rs` stopped sharing it when
|
||||
/// ghost text moved to *relative* indentation and let the editor place it
|
||||
/// (see `inline.rs`'s `render`). `pub(crate)` again for `instantiate.rs`,
|
||||
/// whose `workspace/applyEdit` is plain text no editor re-indents, so it needs
|
||||
/// exactly this — the real indentation of the real line.
|
||||
pub(crate) fn layout_at(ws: &Workspace, doc: &Document, offset: u32) -> Layout {
|
||||
let step = " ".repeat(ws.client_settings().indent.unwrap_or(2));
|
||||
Layout { base: line_indent(&doc.text, offset), step }
|
||||
}
|
||||
|
||||
/// Tier 4: every reserved word the lexer knows.
|
||||
pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
|
||||
for keyword in KEYWORDS.iter().filter(|kw| starts_with_ignore_case(kw, &word.text)) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(keyword, CompletionItemKind::KEYWORD, TIER_KEYWORD, "keyword".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 5: identifiers used anywhere in the project scope.
|
||||
///
|
||||
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
|
||||
/// buffer being typed in is harvested afresh from its own token stream, so an
|
||||
/// unsaved edit contributes to its own file's completions immediately.
|
||||
pub(super) fn word_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
// Gathering and sorting the names is the one tier whose *setup* costs
|
||||
// something, so a response that is already full skips it outright.
|
||||
if items.full() {
|
||||
return;
|
||||
}
|
||||
let names: Vec<&str> = match fuzzy {
|
||||
None => {
|
||||
let mut names: Vec<&str> =
|
||||
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
|
||||
names
|
||||
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
Some(query) => {
|
||||
// The table's hits come back ranked; the buffer's own words are
|
||||
// scored here and the two are ranked together, so a name the user
|
||||
// typed a moment ago sits where its match deserves rather than
|
||||
// after everything the table knows.
|
||||
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
|
||||
// A full return is a truncation; see `index_tier`.
|
||||
items.incomplete |= hits.len() >= LIMIT;
|
||||
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
|
||||
hits.sort_by(|a, b| rank_cmp(*a, *b));
|
||||
// A name in both lists is offered once: `Items` drops the second
|
||||
// by label, so no dedup is needed here.
|
||||
hits.into_iter().map(|(name, _)| name).collect()
|
||||
}
|
||||
};
|
||||
for name in names {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(name, CompletionItemKind::TEXT, TIER_WORD, "used in this project".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
|
||||
///
|
||||
/// The live half of the tier: the prebuilt table is as of the last index
|
||||
/// rebuild, and this is the buffer's own token stream, recomputed on every
|
||||
/// change. The filter is `candidates::is_word`'s, in the other direction —
|
||||
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
|
||||
/// identifier.
|
||||
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
|
||||
doc.tokens
|
||||
.iter()
|
||||
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
|
||||
.map(|token| token.text.as_str())
|
||||
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
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 @(posedge clk)", "always_ff with reset", "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 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)", "always @(posedge clk or negedge rst_n)", "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 a project word — 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 word at least");
|
||||
assert_eq!(tier(item), TIER_WORD, "{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 is in the list because the buffer being typed in
|
||||
// holds it as an `Ident` token — behaviour this round did not
|
||||
// touch, pinned here because a golden that quietly lost it would
|
||||
// be a change.
|
||||
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
|
||||
("ce", vec!["ce", "celsius"]),
|
||||
] {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! What is typed: the identifier run ending at the cursor and what stands
|
||||
//! around it — a backtick, a `.` or a `::`, and the spine a separator
|
||||
//! follows.
|
||||
//!
|
||||
//! Everything here reads the buffer's *text* backwards from the cursor and
|
||||
//! nothing else; the token-stream questions (is this an item position, a
|
||||
//! statement position) are `site.rs`'s. The one shape decision made here is
|
||||
//! `Word::sep`: a separator says the response is a member list and nothing
|
||||
//! else, which is why the spine is read this early.
|
||||
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// What may stand between the start of a line and a statement: the `end` of
|
||||
/// the block before it and the `else` that chains onto it. Anything else on
|
||||
/// the line means the word being typed is part of an expression, not the start
|
||||
/// of a statement.
|
||||
const STATEMENT_HEADS: &[&str] = &["end", "else", "end else"];
|
||||
|
||||
/// The identifier the user is part-way through typing, and what stands around
|
||||
/// it.
|
||||
pub(super) struct Word {
|
||||
/// The identifier run, backtick excluded. Empty when the cursor follows
|
||||
/// something that is not an identifier character.
|
||||
pub(super) text: String,
|
||||
/// Where the run starts — the byte after the backtick, when there is one.
|
||||
pub(super) start: u32,
|
||||
/// Whether a `` ` `` immediately precedes the run, making this a macro
|
||||
/// name being typed and nothing else.
|
||||
pub(super) backtick: bool,
|
||||
/// Whether nothing but whitespace precedes the run on its line.
|
||||
///
|
||||
/// Half of the *module* gate, and deliberately blunt: an instantiation is
|
||||
/// written at the start of a line, and a word that is not (`assign x =
|
||||
/// fo|`, `logic fo|`, `.clk(cl|`) is somewhere a module name would be
|
||||
/// wrong. It costs the rare user who writes two items on one line their
|
||||
/// skeleton — a far better failure than offering a fifteen-line
|
||||
/// instantiation in the middle of an expression. Every other tier ignores
|
||||
/// it: a name is a name wherever it is written.
|
||||
pub(super) at_line_start: bool,
|
||||
/// Whether the only thing before the run on its line is [`STATEMENT_HEADS`]
|
||||
/// — the `end` a statement follows, or the `else` it hangs off.
|
||||
///
|
||||
/// Half of the *template* gate, and the reason `end else if` completes: a
|
||||
/// statement is written at the start of a line or right after one of those
|
||||
/// two words, and nowhere else.
|
||||
pub(super) statement_head: bool,
|
||||
/// The `.` or `::` the run immediately follows, when it follows one.
|
||||
///
|
||||
/// Its presence alone decides the shape of the whole response: a
|
||||
/// separator says the user is naming a **member** of what stands before
|
||||
/// it, and nothing else may be written there — so the member answer is
|
||||
/// exclusive, exactly as the backtick's is. A lone `:` (a case item, a
|
||||
/// label, a ternary) is not a separator and is `None`.
|
||||
pub(super) sep: Option<Sep>,
|
||||
/// What stands before the separator, when it is a spine this can read.
|
||||
/// `None` with a `sep` set means the response is nothing at all: there is
|
||||
/// a member question here and no head to answer it about.
|
||||
pub(super) spine: Option<Spine>,
|
||||
}
|
||||
|
||||
/// The two separators that make the run after them a member name.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Sep {
|
||||
/// `handle.`, `vif.cb.`, `this.` — a member of a *value*'s type.
|
||||
Dot,
|
||||
/// `pkg::`, `cls::` — a member of a named unit.
|
||||
Scope,
|
||||
}
|
||||
|
||||
/// The head of a member access as the buffer spells it: the first identifier
|
||||
/// of the chain, and the names between it and the cursor.
|
||||
///
|
||||
/// `item.hdr.` is `head = "item"`, `mids = ["hdr"]` — exactly the two
|
||||
/// arguments [`vlog_semantic::Semantics::member_site`] takes, because they
|
||||
/// are exactly what `bind.rs`'s own `spine` records for the same expression.
|
||||
/// For [`Sep::Scope`] the head is the whole `::` path (`pkg`, `pkg::cls`) and
|
||||
/// `mids` is empty.
|
||||
pub(super) struct Spine {
|
||||
pub(super) head: String,
|
||||
pub(super) mids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Word {
|
||||
/// The bytes a completion replaces: the word as typed.
|
||||
pub(super) fn range(&self, cursor: u32) -> TextRange {
|
||||
TextRange::new(self.start, cursor)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier run ending at the cursor, and the shape of the line it sits
|
||||
/// on. `None` only when the cursor is not on a character boundary of the text
|
||||
/// the server holds.
|
||||
pub(super) fn typed_word(doc: &Document, cursor: u32) -> Option<Word> {
|
||||
let text = doc.text.get(..cursor as usize)?;
|
||||
let head = text.trim_end_matches(is_ident_char);
|
||||
let start = head.len();
|
||||
let backtick = head.ends_with('`');
|
||||
let bare = match backtick {
|
||||
true => head.get(..head.len() - 1)?,
|
||||
false => head,
|
||||
};
|
||||
let line_start = bare.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
let head = bare.get(line_start..)?;
|
||||
let at_line_start = !backtick && line_head_is_blank(&doc.text, start as u32);
|
||||
// `end else` and `end else` are the same head; nothing else is compared,
|
||||
// so one `split_whitespace` join is the whole normalization needed.
|
||||
let words = head.split_whitespace().collect::<Vec<&str>>().join(" ");
|
||||
let statement_head = !backtick && STATEMENT_HEADS.contains(&words.as_str());
|
||||
// A backtick admits only a macro name, and a macro name follows no
|
||||
// separator, so the two questions never both apply.
|
||||
let (sep, spine) = match backtick {
|
||||
true => (None, None),
|
||||
false => separator(bare),
|
||||
};
|
||||
Some(Word {
|
||||
text: text.get(start..)?.to_string(),
|
||||
start: start as u32,
|
||||
backtick,
|
||||
at_line_start,
|
||||
statement_head,
|
||||
sep,
|
||||
spine,
|
||||
})
|
||||
}
|
||||
|
||||
/// The separator `before` ends with, and the head spine standing before that.
|
||||
///
|
||||
/// `::` is checked first, so a `pkg::` is never read as the lone `:` of a
|
||||
/// case item, a block label or a ternary — that one is deliberately **not** a
|
||||
/// separator, and a request there falls through to the ordinary six tiers
|
||||
/// exactly as it always did.
|
||||
fn separator(before: &str) -> (Option<Sep>, Option<Spine>) {
|
||||
if let Some(rest) = before.strip_suffix("::") {
|
||||
return (Some(Sep::Scope), scope_head(rest));
|
||||
}
|
||||
if let Some(rest) = before.strip_suffix('.') {
|
||||
return (Some(Sep::Dot), dot_spine(rest));
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
|
||||
/// The `::` path ending at `before`: `pkg`, `pkg::cls`.
|
||||
fn scope_head(before: &str) -> Option<Spine> {
|
||||
let mut segments = Vec::new();
|
||||
let mut rest = before;
|
||||
loop {
|
||||
let (head, name) = split_ident(rest)?;
|
||||
segments.push(name.to_string());
|
||||
match head.strip_suffix("::") {
|
||||
Some(next) => rest = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
segments.reverse();
|
||||
Some(Spine { head: segments.join("::"), mids: Vec::new() })
|
||||
}
|
||||
|
||||
/// The `.`-joined spine ending at `before`: `item`, `cfg.vif`, `q[i]`,
|
||||
/// `this`, `super`.
|
||||
///
|
||||
/// **What it reads, and nothing else**: identifiers joined by `.`, each
|
||||
/// optionally carrying balanced `[…]` index suffixes, which are stripped —
|
||||
/// `q[i].` and `arr[3][k].` name a member of the element type, which is the
|
||||
/// declared type name either way. Everything else answers `None`, and `None`
|
||||
/// means the response is nothing at all rather than a guess: a call
|
||||
/// (`f().b`), a cast, a concatenation, a macro invocation, a `::`-qualified
|
||||
/// head (`pkg::cls.`, which is not how a class member is written anyway), and
|
||||
/// whitespace anywhere in the spine (`a . b`, legal SystemVerilog nobody
|
||||
/// writes — refusing it costs a popup, accepting it would mean deciding where
|
||||
/// an expression ends by scanning backwards over arbitrary text).
|
||||
fn dot_spine(before: &str) -> Option<Spine> {
|
||||
let mut segments: Vec<String> = Vec::new();
|
||||
let mut rest = before;
|
||||
loop {
|
||||
let (head, name) = split_ident(strip_indices(rest)?)?;
|
||||
segments.push(name.to_string());
|
||||
match head.strip_suffix('.') {
|
||||
Some(next) => rest = next,
|
||||
None => {
|
||||
// A head reached through `::` is a unit, not a value, and
|
||||
// `member_site` resolves the head on the lexical chain.
|
||||
if head.ends_with(':') {
|
||||
return None;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
segments.reverse();
|
||||
let mut mids = segments;
|
||||
let head = mids.remove(0);
|
||||
Some(Spine { head, mids })
|
||||
}
|
||||
|
||||
/// `text` split at the start of the identifier run it ends with, as
|
||||
/// (what precedes it, the identifier). `None` when it does not end with one,
|
||||
/// or when the run starts with a digit — that is a number, not a name.
|
||||
fn split_ident(text: &str) -> Option<(&str, &str)> {
|
||||
let head = text.trim_end_matches(is_ident_char);
|
||||
let name = text.get(head.len()..)?;
|
||||
if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
Some((head, name))
|
||||
}
|
||||
|
||||
/// `text` with every balanced `[…]` it ends with removed. `None` when a `]`
|
||||
/// has no matching `[` — an expression this cannot read, so nothing is
|
||||
/// offered for it.
|
||||
fn strip_indices(text: &str) -> Option<&str> {
|
||||
let mut rest = text;
|
||||
while rest.ends_with(']') {
|
||||
let mut depth = 0usize;
|
||||
let mut opened = None;
|
||||
for (i, byte) in rest.bytes().enumerate().rev() {
|
||||
match byte {
|
||||
b']' => depth += 1,
|
||||
b'[' => {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
opened = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
rest = rest.get(..opened?)?;
|
||||
}
|
||||
Some(rest)
|
||||
}
|
||||
|
||||
fn is_ident_char(ch: char) -> bool {
|
||||
ch.is_ascii_alphanumeric() || ch == '_' || ch == '$'
|
||||
}
|
||||
|
||||
/// Whether nothing but indentation stands before `at` on its line — half of
|
||||
/// the module gate, shared by [`typed_word`] and
|
||||
/// [`at_instantiation_site`](super::site::at_instantiation_site).
|
||||
pub(super) fn line_head_is_blank(text: &str, at: u32) -> bool {
|
||||
let Some(head) = text.get(..at as usize) else { return false };
|
||||
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
head.get(line_start..).is_some_and(|head| head.chars().all(|c| c == ' ' || c == '\t'))
|
||||
}
|
||||
@@ -23,7 +23,20 @@ pub const SOURCE: &str = "lucisv";
|
||||
/// The missing-closer warnings sit between the two: they explain a parse
|
||||
/// error rather than add an opinion, and they exist at all only when the parse
|
||||
/// already failed (`pairs::missing_end_diagnostics`).
|
||||
///
|
||||
/// `#[cfg(test)]` for the same reason `lint::diagnostics` is: the server
|
||||
/// always has a workspace and always calls [`all_in`], so this is the door the
|
||||
/// tests that predate the project-aware pass come in by.
|
||||
#[cfg(test)]
|
||||
pub fn all(doc: &Document) -> Vec<Diagnostic> {
|
||||
all_in(doc, &crate::lint::LintRun::default())
|
||||
}
|
||||
|
||||
/// [`all`] for a lint pass that knows what the project says — the workspace's
|
||||
/// rule selection and its identifier census
|
||||
/// (`docs/features/semantic-lints-on/README.md`). The parse and missing-closer
|
||||
/// halves are unaffected by either; only the lint pass reads `run`.
|
||||
pub fn all_in(doc: &Document, run: &crate::lint::LintRun) -> Vec<Diagnostic> {
|
||||
// A buffer on the large-file fast path was never parsed, so there is
|
||||
// nothing to say about it — and both passes below would read its *text*
|
||||
// (the lint context builds one, the fence filter scans for them), which is
|
||||
@@ -35,7 +48,7 @@ pub fn all(doc: &Document) -> Vec<Diagnostic> {
|
||||
}
|
||||
let mut all = diagnostics(doc);
|
||||
all.extend(crate::pairs::missing_end_diagnostics(doc));
|
||||
all.extend(crate::lint::diagnostics(doc));
|
||||
all.extend(crate::lint::diagnostics_in(doc, run));
|
||||
all
|
||||
}
|
||||
|
||||
@@ -122,11 +135,12 @@ mod tests {
|
||||
#[test]
|
||||
fn one_list_carries_both_sources() {
|
||||
// A file that parses cleanly and violates a lint rule: the publish is
|
||||
// one list, and the lint finding is in it as a warning.
|
||||
// one list, and the lint finding is in it at its rule's own severity
|
||||
// — `no-tabs` is a style rule, so INFORMATION (§33.0).
|
||||
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
|
||||
let published = all(ws.document(&uri).expect("open"));
|
||||
assert_eq!(published.len(), 1);
|
||||
assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING));
|
||||
assert_eq!(published[0].severity, Some(DiagnosticSeverity::INFORMATION));
|
||||
assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into())));
|
||||
}
|
||||
|
||||
@@ -136,12 +150,43 @@ mod tests {
|
||||
let published = all(ws.document(&uri).expect("open"));
|
||||
let severities: Vec<_> = published.iter().map(|d| d.severity).collect();
|
||||
assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}");
|
||||
assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}");
|
||||
assert!(severities.contains(&Some(DiagnosticSeverity::INFORMATION)), "{published:#?}");
|
||||
assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv")));
|
||||
// Errors first: a parse error is what the user must fix.
|
||||
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
|
||||
}
|
||||
|
||||
/// The user-visible contract of header recovery (TODO §32), pinned where
|
||||
/// the user meets it: a typo in a port list costs **one** diagnostic, and
|
||||
/// the module around it survives whole — its name, the ports typed before
|
||||
/// and after the typo, and its body all still in the outline.
|
||||
///
|
||||
/// Before this round the same buffer published two errors (the header, and
|
||||
/// the orphaned `endmodule`), the body re-parsed as file-scope items, and
|
||||
/// the outline had no module in it at all.
|
||||
#[test]
|
||||
fn a_broken_port_list_publishes_one_error_and_keeps_its_module() {
|
||||
let (ws, uri) = doc_of("module m (input a, , input b);\n wire ok;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let diags = diagnostics(doc);
|
||||
assert_eq!(diags.len(), 1, "{diags:#?}");
|
||||
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
|
||||
assert_eq!(diags[0].range.start.line, 0, "the header's own line");
|
||||
|
||||
// The missing-closer pass explains a *parse* failure; there is no
|
||||
// unclosed block here, so it must add nothing.
|
||||
assert!(crate::pairs::missing_end_diagnostics(doc).is_empty());
|
||||
|
||||
let symbols = crate::symbols::document_symbols(doc);
|
||||
assert_eq!(symbols.len(), 1, "the module is still in the outline");
|
||||
assert_eq!(symbols[0].name, "m");
|
||||
let children = symbols[0].children.as_ref().expect("module contents");
|
||||
let names: Vec<&str> = children.iter().map(|c| c.name.as_str()).collect();
|
||||
assert!(names.contains(&"a"), "the port before the typo: {names:?}");
|
||||
assert!(names.contains(&"b"), "the port after it: {names:?}");
|
||||
assert!(names.contains(&"ok"), "the body: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lex_error_gets_a_visible_range() {
|
||||
// The lexer gives up at end of file, which a trailing newline makes
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
//! Extract a selection into a module of its own, on the wire:
|
||||
//! `textDocument/codeAction` under LSP's own `refactor.extract`, and
|
||||
//! `workspace/executeCommand` for the editors that have no lightbulb.
|
||||
//!
|
||||
//! Protocol only. The edit is `vlog_refactor::extract_module`; this module
|
||||
//! decides which files that engine is handed, turns its answer into a
|
||||
//! `WorkspaceEdit`, and turns its refusal into a request error.
|
||||
//!
|
||||
//! **The action carries a command, not an edit** — which is what makes it the
|
||||
//! laziest of the lot rather than merely a lazy one. Extracting needs a *name*
|
||||
//! for the new module, and LSP has no prompt: a code action can carry an
|
||||
//! `edit`, a `command`, or both, and only a command can be intercepted by a
|
||||
//! client that wants to ask the user something first. So the offer is one
|
||||
//! parse of one buffer (`vlog_refactor::extract_site`) plus a `Command` naming
|
||||
//! [`EXTRACT_MODULE`] and the default name `M_extracted`; the VS Code
|
||||
//! extension registers a client-side command of the same name that shows an
|
||||
//! input box and calls the server's with what the user typed, and every other
|
||||
//! client runs the command as sent and gets the default. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
//!
|
||||
//! **The new file.** A module extracted into a file of its own is a
|
||||
//! `CreateFile` resource operation, which only a client that advertises
|
||||
//! `workspace.workspaceEdit.documentChanges` *and* `resourceOperations`
|
||||
//! containing `create` can apply. That capability is read at `initialize`
|
||||
//! ([`crate::server::ClientAbilities::create_files`]) and is the whole of the
|
||||
//! choice between the two homes: a client that can create files gets `N.sv`
|
||||
//! beside `M`'s file, and every other client gets `N` written below `M` in the
|
||||
//! file it came from. The engine says which happened in its warnings.
|
||||
|
||||
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
|
||||
use lsp_types::{
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, Command, CreateFile, DocumentChangeOperation,
|
||||
DocumentChanges, OneOf, OptionalVersionedTextDocumentIdentifier, Range, ResourceOp,
|
||||
TextDocumentEdit, TextEdit, Uri, WorkspaceEdit,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{Home, RefactorEdit};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// Extract a selection into a module: `[uri, range, name]`.
|
||||
pub const EXTRACT_MODULE: &str = "lucisv.extractModule";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![EXTRACT_MODULE.to_string()]
|
||||
}
|
||||
|
||||
/// The kind LSP reserves for an extraction, which is what an editor's
|
||||
/// "Refactor…" menu asks for by name.
|
||||
pub fn kind() -> CodeActionKind {
|
||||
CodeActionKind::REFACTOR_EXTRACT
|
||||
}
|
||||
|
||||
/// The action for a selection, carrying the command that will ask for a name.
|
||||
///
|
||||
/// One parse of the buffer and nothing else: the engine's cheap gate answers
|
||||
/// "there is nothing here" for almost every selection, and where it does find
|
||||
/// something the offer is a `Command`, so no workspace is read until the user
|
||||
/// has picked the action *and* named the module.
|
||||
/// Whether `[start, end)` is a selection lucisv could extract, asked of the
|
||||
/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b).
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes rather than of the empty analysis that path installs — see
|
||||
/// `ports::modules_at` and `docs/features/perf5-p1/README.md`.
|
||||
fn site_at(doc: &Document, start: u32, end: u32) -> Option<vlog_refactor::ExtractSite> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::extract_site(&doc.text, start, end),
|
||||
false => vlog_refactor::extract_site_in(&doc.tree, &doc.diagnostics, &doc.text, start, end),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
if doc.path.is_none() {
|
||||
// An `untitled:` buffer has no directory to put `N.sv` beside and no
|
||||
// path for the engine's file set; nothing is offered rather than
|
||||
// offered and refused.
|
||||
return Vec::new();
|
||||
}
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = site_at(doc, start, end) else { return Vec::new() };
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).unwrap_or(Value::Null),
|
||||
serde_json::to_value(range).unwrap_or(Value::Null),
|
||||
Value::String(site.default_name.clone()),
|
||||
];
|
||||
let title = vlog_refactor::extract_title();
|
||||
vec![CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: title.clone(),
|
||||
kind: Some(kind()),
|
||||
command: Some(Command {
|
||||
title,
|
||||
command: EXTRACT_MODULE.to_string(),
|
||||
arguments: Some(arguments),
|
||||
}),
|
||||
..Default::default()
|
||||
})]
|
||||
}
|
||||
|
||||
/// Run `lucisv.extractModule`, or say why it cannot run.
|
||||
pub fn execute(
|
||||
ws: &Workspace,
|
||||
arguments: &[Value],
|
||||
create_files: bool,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let uri: Uri = argument(arguments, 0, "a document URI")?;
|
||||
let range: Range = argument(arguments, 1, "a range")?;
|
||||
let name: String = argument(arguments, 2, "a name for the new module")?;
|
||||
let doc = ws
|
||||
.document(&uri)
|
||||
.ok_or_else(|| "lucisv can only extract from an open file.".to_string())?;
|
||||
let path = doc
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?;
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = site_at(doc, start, end) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine looks up every module the selection instantiates and every
|
||||
// package it imports, so the file set is those units' own fan-out — plus
|
||||
// the new name's, so a workspace that already declares it is a workspace
|
||||
// the engine can refuse over.
|
||||
let mut units = site.units;
|
||||
units.push(name.clone());
|
||||
let files = ws.module_sources(&path, &units);
|
||||
let home = match create_files {
|
||||
true => Home::NewFile,
|
||||
false => Home::SameFile,
|
||||
};
|
||||
// No preflight here, and the take 5 review round (§61.1) is why: every
|
||||
// refusal one could take is already taken before a scope is built. The
|
||||
// `site_at` gate above **is** `extract_site_in`, which returns `None` on a
|
||||
// parse diagnostic and on every `Region::read` refusal, so neither can
|
||||
// reach the engine; and `extract_module` checks the new name and the
|
||||
// occupied target as its own first two statements, ahead of
|
||||
// `Extraction::plan`. The 805 ms at `aes_wrap.sv` is none of those — it is
|
||||
// `boundary::Crossing::read`, which needs the instantiated modules' port
|
||||
// directions and so needs the scope. See
|
||||
// `docs/features/perf5r-preflight/README.md`.
|
||||
let refactoring = vlog_refactor::extract_module(&files, &path, start, end, &name, home)?;
|
||||
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
/// A whole extraction as a `WorkspaceEdit`.
|
||||
///
|
||||
/// `documentChanges` rather than `changes` whenever a file is created: a
|
||||
/// creation is a resource operation, and the two shapes cannot be mixed in one
|
||||
/// edit. An extraction that creates nothing goes through the ordinary
|
||||
/// `changes` map, which every client understands.
|
||||
pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result<WorkspaceEdit, String> {
|
||||
if refactoring.created.is_empty() {
|
||||
return crate::ports::workspace_edit(ws, refactoring);
|
||||
}
|
||||
let mut operations: Vec<DocumentChangeOperation> = Vec::new();
|
||||
for path in &refactoring.created {
|
||||
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
|
||||
operations.push(DocumentChangeOperation::Op(ResourceOp::Create(CreateFile {
|
||||
uri,
|
||||
options: None,
|
||||
annotation_id: None,
|
||||
})));
|
||||
}
|
||||
for (path, edits) in &refactoring.edits {
|
||||
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
|
||||
// A file the edit creates has no text yet, and the one insertion into
|
||||
// it is at 0:0 — which is what `Positions` over an empty text says.
|
||||
let created = refactoring.created.iter().any(|created| created == path);
|
||||
let text = match created {
|
||||
true => String::new(),
|
||||
false => ws.text_of(path).ok_or_else(|| unaddressable(path))?,
|
||||
};
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
operations.push(DocumentChangeOperation::Edit(TextDocumentEdit {
|
||||
text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
|
||||
edits: edits
|
||||
.iter()
|
||||
.map(|edit| {
|
||||
OneOf::Left(TextEdit {
|
||||
range: positions.range(edit.range),
|
||||
new_text: edit.new_text.clone(),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
}));
|
||||
}
|
||||
Ok(WorkspaceEdit {
|
||||
document_changes: Some(DocumentChanges::Operations(operations)),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn argument<T: serde::de::DeserializeOwned>(
|
||||
arguments: &[Value],
|
||||
n: usize,
|
||||
what: &str,
|
||||
) -> Result<T, String> {
|
||||
arguments
|
||||
.get(n)
|
||||
.and_then(|value| serde_json::from_value(value.clone()).ok())
|
||||
.ok_or_else(|| format!("{EXTRACT_MODULE} wants {what} as argument {}.", n + 1))
|
||||
}
|
||||
|
||||
fn unaddressable(path: &std::path::Path) -> String {
|
||||
format!("lucisv could not address {} as a document; no edits were made.", path.display())
|
||||
}
|
||||
|
||||
const NOTHING: &str = "there is nothing to extract at this selection.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use lsp_types::Position;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_extract_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic [7:0] a,
|
||||
input logic [7:0] b,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] s;
|
||||
assign s = a + b;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn opened(tree: &Tree) -> (Workspace, Uri) {
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// The range of `assign s = a + b;`, as the client speaks it.
|
||||
fn selection() -> Range {
|
||||
Range {
|
||||
start: Position { line: 6, character: 2 },
|
||||
end: Position { line: 6, character: 19 },
|
||||
}
|
||||
}
|
||||
|
||||
fn only(actions: Vec<CodeActionOrCommand>) -> Vec<CodeAction> {
|
||||
actions
|
||||
.into_iter()
|
||||
.filter_map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => Some(action),
|
||||
CodeActionOrCommand::Command(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_of_whole_items_is_offered_the_action_with_a_command_and_a_default_name() {
|
||||
let tree = Tree::new("offer");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let actions = only(code_actions(&ws, &uri, selection()));
|
||||
let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") };
|
||||
assert_eq!(action.title, "lucisv: extract selection into module…");
|
||||
assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_EXTRACT));
|
||||
assert!(action.edit.is_none(), "the offer reads no workspace");
|
||||
let command = action.command.as_ref().expect("a command");
|
||||
assert_eq!(command.command, EXTRACT_MODULE);
|
||||
let arguments = command.arguments.as_ref().expect("arguments");
|
||||
assert_eq!(arguments.len(), 3);
|
||||
assert_eq!(arguments[2], Value::String("top_extracted".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_covers_no_whole_item_is_offered_nothing() {
|
||||
let tree = Tree::new("nothing");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let half = Range {
|
||||
start: Position { line: 6, character: 2 },
|
||||
end: Position { line: 6, character: 8 },
|
||||
};
|
||||
assert!(code_actions(&ws, &uri, half).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_creates_the_new_file_for_a_client_that_can() {
|
||||
let tree = Tree::new("create");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(selection()).expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments, true).expect("extracts");
|
||||
assert!(warnings.iter().any(|w| w.contains("sum.sv")), "{warnings:?}");
|
||||
let Some(DocumentChanges::Operations(ops)) = edit.document_changes else {
|
||||
panic!("a creating edit speaks documentChanges: {edit:?}")
|
||||
};
|
||||
let creates = ops
|
||||
.iter()
|
||||
.filter(|op| matches!(op, DocumentChangeOperation::Op(ResourceOp::Create(_))))
|
||||
.count();
|
||||
assert_eq!(creates, 1, "one file is created: {ops:?}");
|
||||
assert_eq!(ops.len(), 3, "the creation plus one edit per file: {ops:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_writes_the_module_into_the_same_file_for_a_client_that_cannot() {
|
||||
let tree = Tree::new("same");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(selection()).expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments, false).expect("extracts");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.contains("did not say it can create files")),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(edit.document_changes.is_none(), "no resource operation is needed");
|
||||
let changes = edit.changes.as_ref().expect("changes");
|
||||
assert_eq!(changes.len(), 1, "one file is touched");
|
||||
assert_eq!(changes.get(&uri).expect("this file").len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_says_why_when_there_is_nothing_to_extract() {
|
||||
let tree = Tree::new("refuse");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Range {
|
||||
start: Position { line: 0, character: 0 },
|
||||
end: Position { line: 0, character: 3 },
|
||||
})
|
||||
.expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
assert_eq!(execute(&ws, &arguments, true), Err(NOTHING.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_wants_all_three_of_its_arguments() {
|
||||
let tree = Tree::new("arguments");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let short = vec![serde_json::to_value(&uri).expect("uri")];
|
||||
let message = execute(&ws, &short, true).expect_err("a refusal");
|
||||
assert!(message.contains("argument 2"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_asking_only_for_refactor_extract_is_answered() {
|
||||
let filter = [CodeActionKind::REFACTOR_EXTRACT];
|
||||
assert!(crate::code_action::wanted(Some(&filter), &kind()));
|
||||
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Where the extract refusals are actually taken (take 5 review §3 item 5,
|
||||
// TODO §61.1). No preflight was added — every refusal below is already
|
||||
// reached before a scope exists, and these pin that it stays so.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn run(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
range: Range,
|
||||
name: &str,
|
||||
create: bool,
|
||||
) -> Result<(), String> {
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).expect("uri"),
|
||||
serde_json::to_value(range).expect("range"),
|
||||
Value::String(name.to_string()),
|
||||
];
|
||||
execute(ws, &arguments, create).map(|_| ())
|
||||
}
|
||||
|
||||
/// A bad new name is refused by `extract_module`'s own first statement,
|
||||
/// and a selection covering no whole item is refused by the `site_at` gate
|
||||
/// — neither reaches `Extraction::plan`, so neither builds a scope.
|
||||
#[test]
|
||||
fn the_cheap_refusals_reach_the_wire_in_the_engines_words() {
|
||||
let tree = Tree::new("preflightrefusals");
|
||||
let (ws, uri) = opened(&tree);
|
||||
|
||||
let bad = run(&ws, &uri, selection(), "1bad", true).expect_err("a bad name");
|
||||
assert!(bad.contains("plain SystemVerilog identifier"), "{bad}");
|
||||
|
||||
// Half of `assign s = a + b;`, which covers no whole item.
|
||||
let partial = Range {
|
||||
start: Position { line: 6, character: 6 },
|
||||
end: Position { line: 6, character: 19 },
|
||||
};
|
||||
assert_eq!(
|
||||
run(&ws, &uri, partial, "sum", true),
|
||||
Err(NOTHING.to_string()),
|
||||
"the `site_at` gate answers a partial selection before the engine is asked"
|
||||
);
|
||||
}
|
||||
|
||||
/// A file already sitting where the new module would go is refused before
|
||||
/// `Extraction::plan`, and the question is asked of the source set the
|
||||
/// engine was handed rather than of the disk behind its back.
|
||||
#[test]
|
||||
fn an_occupied_target_is_refused_with_the_engines_sentence() {
|
||||
let tree = Tree::new("preflightoccupied");
|
||||
tree.write("sum.sv", "module sum;\nendmodule\n");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let refusal = run(&ws, &uri, selection(), "sum", true).expect_err("occupied");
|
||||
assert!(refusal.contains("there is already a"), "{refusal}");
|
||||
assert!(refusal.contains("sum.sv"), "and it names the file: {refusal}");
|
||||
|
||||
// Into the same file nothing is occupied, so the early check passes
|
||||
// and the engine refuses for its own, later reason: the workspace
|
||||
// already declares that name — an index question, answered by the
|
||||
// stage that owns the index.
|
||||
let deferred = run(&ws, &uri, selection(), "sum", false).expect_err("already declared");
|
||||
assert!(deferred.contains("the workspace already declares"), "{deferred}");
|
||||
}
|
||||
|
||||
/// The control: a whole, movable item still extracts.
|
||||
#[test]
|
||||
fn a_whole_movable_selection_still_extracts() {
|
||||
let tree = Tree::new("preflightok");
|
||||
let (ws, uri) = opened(&tree);
|
||||
assert!(run(&ws, &uri, selection(), "sum", true).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! The fenced regions of an open buffer, asked once per document revision.
|
||||
//!
|
||||
//! `vlog_formatter::fence::protected_regions` takes **text** and parses it
|
||||
//! itself, on purpose: one fence answer for every front end, and none of them
|
||||
//! able to feed it a stale tree. That contract
|
||||
//! (`docs/features/shared-fence-filter/README.md`) is not amended here, and
|
||||
//! `fence.rs` is not touched — the call is still
|
||||
//! `protected_regions(&doc.text)`, byte for byte the same question.
|
||||
//!
|
||||
//! What this module adds is that the answer is computed **once** for a given
|
||||
//! buffer instead of once per `textDocument/codeAction`. That is safe for one
|
||||
//! structural reason: a `Document` is built whole by
|
||||
//! `Workspace::set_document` and thrown away by it, so the text a `Document`
|
||||
//! holds cannot change without a new `Document` — and `answer_request`
|
||||
//! flushes every pending change before a handler runs. There is no revision
|
||||
//! number to compare because there is no way to be looking at the wrong one.
|
||||
//!
|
||||
//! A 42 192-line generated buffer is where this is worth having: the fence
|
||||
//! parse alone measured ~59 ms of that file's code-action cost (take 5 §P1,
|
||||
//! `docs/features/perf5-p1/README.md`).
|
||||
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// The regions of `doc` no tool may edit automatically.
|
||||
///
|
||||
/// Computed on first use and kept for the life of this `Document`. The
|
||||
/// caller borrows the answer rather than a copy of it, so asking twice costs
|
||||
/// a pointer.
|
||||
pub fn of(doc: &Document) -> &[Region] {
|
||||
doc.fences.get_or_init(|| fence::protected_regions(&doc.text))
|
||||
}
|
||||
|
||||
/// Whether the answer is already in hand — asked *before* [`of`], so a
|
||||
/// `--verbose` trace can say whether this request paid the parse or read the
|
||||
/// memo (review round §R1b, `crate::lint_trace`). Decides nothing.
|
||||
pub fn held(doc: &Document) -> bool {
|
||||
doc.fences.get().is_some()
|
||||
}
|
||||
@@ -224,6 +224,14 @@ fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingO
|
||||
if let Some(line_length) = file.line_length {
|
||||
config.max_width = line_length;
|
||||
}
|
||||
// The `[format]` keys follow the same ladder: the editor's own setting
|
||||
// first, then `lucisv.toml`, which outranks it.
|
||||
if let Some(on) = client.uvm_utils_indent {
|
||||
config.uvm_utils_indent = on;
|
||||
}
|
||||
if let Some(on) = file.format_uvm_utils_indent {
|
||||
config.uvm_utils_indent = on;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
@@ -508,6 +516,39 @@ mod tests {
|
||||
assert_eq!(settings.config.max_width, Config::default().max_width);
|
||||
}
|
||||
|
||||
/// The `[format]` keys climb the same ladder — with no rung 3, since the
|
||||
/// protocol has no option for them: `lucisv.toml` > `lucisv.format.*` >
|
||||
/// the built-in default, which is off (TODO §54.3).
|
||||
#[test]
|
||||
fn a_format_key_climbs_the_ladder_from_off() {
|
||||
let uvm = |on: Option<bool>| ClientSettings { uvm_utils_indent: on, ..Default::default() };
|
||||
// Rung 4: nobody asked, so the key never fires.
|
||||
let (ws, uri) = document("module m;\nendmodule\n");
|
||||
assert!(!settings_with(&ws, &uri, &none(), &options(2, true)).config.uvm_utils_indent);
|
||||
// Rung 2: the editor setting is the only thing that spoke.
|
||||
assert!(
|
||||
settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent
|
||||
);
|
||||
// Rung 1: `lucisv.toml` outranks the editor, in both directions.
|
||||
let on = Tree::new("[format]\nuvm-utils-indent = true\n");
|
||||
let (ws, uri) = on.document("module m;\nendmodule\n");
|
||||
let settings = settings_with(&ws, &uri, &uvm(Some(false)), &options(2, true));
|
||||
assert_eq!(settings.problem, None);
|
||||
assert!(settings.config.uvm_utils_indent, "lucisv.toml wins");
|
||||
let off = Tree::new("[format]\nuvm-utils-indent = false\n");
|
||||
let (ws, uri) = off.document("module m;\nendmodule\n");
|
||||
assert!(
|
||||
!settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent
|
||||
);
|
||||
// A config that names other keys is silent about this one, so the
|
||||
// editor setting still answers for it.
|
||||
let other = Tree::new("indent = 4\n");
|
||||
let (ws, uri) = other.document("module m;\nendmodule\n");
|
||||
let settings = settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true));
|
||||
assert_eq!(settings.config.indent_width, 4);
|
||||
assert!(settings.config.uvm_utils_indent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_key_climbs_the_ladder_independently() {
|
||||
// A `lucisv.toml` naming only `indent` must not also claim the width:
|
||||
|
||||
@@ -82,7 +82,7 @@ fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
|
||||
/// several reachable files do — the honest all-candidates list from before
|
||||
/// this feature stands: an empty include graph must never make hover worse
|
||||
/// than it was (`docs/features/include-nav/README.md`).
|
||||
fn narrowed_to_the_include_graph<'a>(
|
||||
pub(crate) fn narrowed_to_the_include_graph<'a>(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
candidates: Vec<(FileId, &'a Define)>,
|
||||
@@ -106,7 +106,7 @@ fn narrowed_to_the_include_graph<'a>(
|
||||
}
|
||||
|
||||
/// The macro's name: the identifier after the backtick, argument list excluded.
|
||||
fn macro_name(token: &Token) -> Option<&str> {
|
||||
pub(crate) fn macro_name(token: &Token) -> Option<&str> {
|
||||
let rest = token.text.strip_prefix('`')?;
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$');
|
||||
let name = match end {
|
||||
@@ -455,7 +455,7 @@ fn span_text(text: &str, span: TextRange) -> Option<&str> {
|
||||
/// to not continue an identifier turns that prefix/suffix match back into a
|
||||
/// miss, without needing anything more than the same "is this still a name
|
||||
/// character" question a lexer already answers for `$`, `_` and alnum.
|
||||
fn spells_exactly(text: &str, span: TextRange, name: &str) -> bool {
|
||||
pub(crate) fn spells_exactly(text: &str, span: TextRange, name: &str) -> bool {
|
||||
if span_text(text, span) != Some(name) {
|
||||
return false;
|
||||
}
|
||||
@@ -1313,6 +1313,45 @@ endmodule
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// TODO §64.1. The same live-span read for a declaration only a
|
||||
/// **hierarchical** path can reach — a module's internal net, named from
|
||||
/// another file as `u_leaf.sig`.
|
||||
///
|
||||
/// `declaration_snippet` reaches it through `live_symbol` →
|
||||
/// `nav::indexed_def_for_symbol`, which asked `WorkspaceIndex::member`
|
||||
/// (the *connection* surface) until §64.1 and so mapped no live symbol
|
||||
/// back to this `Def` at all: the card came out with its heading and no
|
||||
/// fence, on a file that was open and perfectly readable. It now shows the
|
||||
/// live line, which is the same guarantee the port above gets — and the
|
||||
/// guard is untouched, so a buffer whose live text no longer declares the
|
||||
/// name still prints nothing (asserted below).
|
||||
#[test]
|
||||
fn a_hierarchical_only_declaration_is_read_at_its_live_span_too() {
|
||||
let top =
|
||||
"module top;\n leaf u_leaf ();\n wire w;\n assign w = u_leaf.sig;\nendmodule\n";
|
||||
let saved = "module leaf;\n logic [7:0] sig;\nendmodule\n";
|
||||
let (dir, mut ws, uri) = included("livehier", &[("leaf.sv", saved), ("top.sv", top)]);
|
||||
let leaf_uri = path_to_uri(&dir.join("leaf.sv")).expect("uri");
|
||||
let edited =
|
||||
"// two lines\n// pushed it down\nmodule leaf;\n logic [15:0] sig;\nendmodule\n";
|
||||
ws.set_document(leaf_uri.clone(), edited.to_string());
|
||||
|
||||
let body = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover"));
|
||||
assert!(
|
||||
body.contains("```systemverilog\n logic [15:0] sig;\n```"),
|
||||
"the live line, width and all: got {body}"
|
||||
);
|
||||
assert!(!body.contains("[7:0]"), "not the saved one: got {body}");
|
||||
|
||||
// The guard half, on the same shape: the net renamed away in the
|
||||
// buffer leaves the heading and no fence.
|
||||
ws.set_document(leaf_uri, "module leaf;\n logic [15:0] renamed;\nendmodule\n".to_string());
|
||||
let guarded = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover"));
|
||||
assert!(guarded.contains("— declared in"), "today's card, intact: got {guarded}");
|
||||
assert!(!guarded.contains("```"), "and no snippet at all: got {guarded}");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line() {
|
||||
// The file changed on disk under a live index — a rescan the server has
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
//! Organize imports on the wire: `textDocument/codeAction` under LSP's own
|
||||
//! `source.organizeImports` kind, and `workspace/executeCommand` for the
|
||||
//! editors that have no lightbulb.
|
||||
//!
|
||||
//! Protocol only. The edit is `vlog_refactor::organize_imports`; this module
|
||||
//! decides which files that engine is handed, turns its answer into a
|
||||
//! `WorkspaceEdit`, and turns its refusal into a request error.
|
||||
//!
|
||||
//! **The kind is `source.organizeImports` and nothing else.** That is the
|
||||
//! kind an editor's organize-on-save asks for by name, and filing the action
|
||||
//! under a second `refactor.rewrite.*` kind as well would mean a client
|
||||
//! asking for both got the same action twice.
|
||||
//!
|
||||
//! **The file set.** An `import` binds names in the scope that wrote it, so
|
||||
//! the edit never leaves the cursor's own file — but *judging* it needs every
|
||||
//! file that could supply a name through one of those imports: the file
|
||||
//! declaring each imported package, every file declaring a package of that
|
||||
//! name (so an ambiguity the index can see is one the engine sees too), and
|
||||
//! the same again for every package those re-export from (§48). That closure
|
||||
//! is a handful of files on any workspace, which is what lets this run on a
|
||||
//! cursor rather than on a whole-workspace read. See
|
||||
//! `docs/features/organize-imports/README.md`.
|
||||
|
||||
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Position, Uri, WorkspaceEdit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// Organize the imports at a position: `[uri, position]`.
|
||||
pub const ORGANIZE_IMPORTS: &str = "lucisv.organizeImports";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![ORGANIZE_IMPORTS.to_string()]
|
||||
}
|
||||
|
||||
/// The kind LSP reserves for this action, which is what an editor's
|
||||
/// organize-on-save asks for.
|
||||
pub fn kind() -> CodeActionKind {
|
||||
CodeActionKind::SOURCE_ORGANIZE_IMPORTS
|
||||
}
|
||||
|
||||
/// The action at a position, carrying its computed edit — what a client
|
||||
/// without `codeAction/resolve` gets, and what [`resolve`] re-runs.
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() };
|
||||
let Ok((edit, removed, sorted)) = vlog_refactor::organize_counts(&files, &path, offset) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(edit) = crate::ports::workspace_edit(ws, &edit) else { return Vec::new() };
|
||||
vec![CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: vlog_refactor::organize_title(removed, sorted),
|
||||
kind: Some(kind()),
|
||||
edit: Some(edit),
|
||||
..Default::default()
|
||||
})]
|
||||
}
|
||||
|
||||
/// The same action **without** its edit — the offer a client that can
|
||||
/// `codeAction/resolve` is sent.
|
||||
///
|
||||
/// The counts in the title are the engine's own, computed over the same file
|
||||
/// set [`resolve`] will use, so the offer and the resolution cannot disagree
|
||||
/// about what the action promises.
|
||||
pub fn offers(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
offset: u32,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() };
|
||||
let Ok((removed, sorted)) = counts_at(doc, &files, &path, offset) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let title = vlog_refactor::organize_title(removed, sorted);
|
||||
let data = serde_json::to_value(Offer { uri: uri.clone(), position }).ok();
|
||||
vec![CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title,
|
||||
kind: Some(kind()),
|
||||
data,
|
||||
..Default::default()
|
||||
})]
|
||||
}
|
||||
|
||||
/// The two counts the offered title promises, asked of the buffer's own parse,
|
||||
/// analysis and token stream, and **without** verifying the splice.
|
||||
///
|
||||
/// `organize_counts` computes the whole edit and runs `check::verify_splice`,
|
||||
/// which rebuilds the index over every in-scope file and re-analyzes them —
|
||||
/// about two thirds of the offer's cost for an answer the offer discards (take
|
||||
/// 5 §P1c, `docs/features/perf5-p1/README.md`). [`resolve`] and [`execute`]
|
||||
/// still compute and verify the real edit when the user picks the action.
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, exactly as
|
||||
/// [`packages_at`] does.
|
||||
fn counts_at(
|
||||
doc: &Document,
|
||||
files: &[(PathBuf, String)],
|
||||
path: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(usize, usize), String> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::organize_offer(files, path, offset),
|
||||
false => vlog_refactor::organize_offer_in(
|
||||
files,
|
||||
path,
|
||||
&doc.tree,
|
||||
&doc.diagnostics,
|
||||
&doc.semantics,
|
||||
&doc.tokens,
|
||||
offset,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The edit for an offered action, computed now that the user has picked it.
|
||||
pub fn resolve(ws: &Workspace, action: CodeAction) -> Result<CodeAction, String> {
|
||||
if action.edit.is_some() {
|
||||
return Ok(action);
|
||||
}
|
||||
let offer: Offer = action
|
||||
.data
|
||||
.clone()
|
||||
.and_then(|data| serde_json::from_value(data).ok())
|
||||
.ok_or_else(|| NOT_OURS.to_string())?;
|
||||
// A buffer that has grown past the large-file threshold since it was
|
||||
// offered an action is refused here rather than parsed — `ports::resolve`
|
||||
// draws the same line, and for the same reason.
|
||||
let doc = ws.document(&offer.uri).filter(|doc| !doc.large).ok_or_else(|| GONE.to_string())?;
|
||||
let offset = doc.positions().offset(offer.position);
|
||||
code_actions(ws, &offer.uri, offset)
|
||||
.into_iter()
|
||||
.find_map(|offered| match offered {
|
||||
CodeActionOrCommand::CodeAction(found) => Some(found),
|
||||
CodeActionOrCommand::Command(_) => None,
|
||||
})
|
||||
.map(|mut resolved| {
|
||||
resolved.data = action.data;
|
||||
resolved
|
||||
})
|
||||
.ok_or_else(|| GONE.to_string())
|
||||
}
|
||||
|
||||
/// Run `lucisv.organizeImports`, or say why it cannot run.
|
||||
pub fn execute(
|
||||
ws: &Workspace,
|
||||
arguments: &[Value],
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let uri: Uri =
|
||||
arguments.first().and_then(|value| serde_json::from_value(value.clone()).ok()).ok_or_else(
|
||||
|| format!("{ORGANIZE_IMPORTS} wants a document URI as its first argument."),
|
||||
)?;
|
||||
let position: Position = arguments
|
||||
.get(1)
|
||||
.and_then(|value| serde_json::from_value(value.clone()).ok())
|
||||
.ok_or_else(|| format!("{ORGANIZE_IMPORTS} wants a position as its second argument."))?;
|
||||
let doc = ws
|
||||
.document(&uri)
|
||||
.ok_or_else(|| "lucisv can only organize the imports of an open file.".to_string())?;
|
||||
let offset = doc.positions().offset(position);
|
||||
let (path, files) = at(ws, &uri, offset).ok_or_else(|| NOTHING.to_string())?;
|
||||
let refactoring = vlog_refactor::organize_imports(&files, &path, offset)?;
|
||||
Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
/// The cursor's file and the files the engine needs to judge its imports, or
|
||||
/// nothing when there is no import run at this position at all.
|
||||
///
|
||||
/// The cheap gate first: `imported_packages` is one parse of one buffer and
|
||||
/// answers "nothing here" for almost every cursor, which is what keeps a
|
||||
/// `textDocument/codeAction` on every keystroke off the index.
|
||||
/// Every package the scope at `offset` imports, asked of the buffer's own
|
||||
/// parse and its own diagnostics rather than of its text (take 5 §P1b). A
|
||||
/// buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes — see `ports::modules_at` for the whole reason.
|
||||
fn packages_at(doc: &Document, offset: u32) -> Vec<String> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::imported_packages(&doc.text, offset),
|
||||
false => {
|
||||
vlog_refactor::imported_packages_in(&doc.tree, &doc.diagnostics, &doc.text, offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn at(ws: &Workspace, uri: &Uri, offset: u32) -> Option<(PathBuf, Vec<(PathBuf, String)>)> {
|
||||
let doc = ws.document(uri)?;
|
||||
let path = doc.path.clone()?;
|
||||
let packages = packages_at(doc, offset);
|
||||
if packages.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let files = sources(ws, &path, &doc.text, &packages);
|
||||
Some((path, files))
|
||||
}
|
||||
|
||||
/// The buffer, plus every file that declares one of the named packages or one
|
||||
/// of the packages those re-export from.
|
||||
///
|
||||
/// **Every** declaration of a name, not the first: two packages called
|
||||
/// `foo_pkg` is exactly the ambiguity the engine refuses over, and handing it
|
||||
/// one of them would hide the refusal instead of making it.
|
||||
///
|
||||
/// `pub(crate)` for the test that pins exactly this set.
|
||||
pub(crate) fn sources(
|
||||
ws: &Workspace,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
packages: &[String],
|
||||
) -> Vec<(PathBuf, String)> {
|
||||
let mut sources = vec![(path.to_path_buf(), text.to_string())];
|
||||
let mut queue: Vec<String> = packages.to_vec();
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
while let Some(name) = queue.pop() {
|
||||
if seen.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
for def in ws.index().units(&name) {
|
||||
let Some(declared_in) = ws.index().path(def.file) else { continue };
|
||||
if sources.iter().any(|(held, _)| held == declared_in) {
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = ws.text_of(declared_in) {
|
||||
sources.push((declared_in.to_path_buf(), text));
|
||||
}
|
||||
}
|
||||
let onward: Vec<String> =
|
||||
ws.index().reexported_packages(&name).iter().map(|p| (*p).to_string()).collect();
|
||||
queue.extend(onward);
|
||||
seen.push(name);
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
/// What a lazily-offered action carries in place of its edit.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Offer {
|
||||
uri: Uri,
|
||||
position: Position,
|
||||
}
|
||||
|
||||
const GONE: &str = "the action is no longer available.";
|
||||
const NOT_OURS: &str = "this code action carries no lucisv import organization to resolve.";
|
||||
const NOTHING: &str = "there is no import run to organize at this position.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use lsp_types::{Range, TextEdit};
|
||||
use std::fs;
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_imports_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
const A_PKG: &str = "package a_pkg;\n typedef int a_t;\nendpackage\n";
|
||||
const B_PKG: &str = "package b_pkg;\n typedef int b_t;\nendpackage\n";
|
||||
const TOP: &str = "module top;\n import a_pkg::*;\n import b_pkg::*;\n b_t q;\nendmodule\n";
|
||||
|
||||
/// A three-file workspace with `top.sv` open.
|
||||
fn opened(tree: &Tree) -> (Workspace, Uri) {
|
||||
tree.write("a_pkg.sv", A_PKG);
|
||||
tree.write("b_pkg.sv", B_PKG);
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// The byte offset of a needle in `TOP`.
|
||||
fn at(needle: &str) -> u32 {
|
||||
TOP.find(needle).expect("needle") as u32
|
||||
}
|
||||
|
||||
fn edits_of(action: &CodeAction, uri: &Uri) -> Vec<TextEdit> {
|
||||
action
|
||||
.edit
|
||||
.as_ref()
|
||||
.expect("an edit")
|
||||
.changes
|
||||
.as_ref()
|
||||
.expect("changes")
|
||||
.get(uri)
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn only(actions: Vec<CodeActionOrCommand>) -> Vec<CodeAction> {
|
||||
actions
|
||||
.into_iter()
|
||||
.filter_map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => Some(action),
|
||||
CodeActionOrCommand::Command(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_on_the_import_run_is_offered_the_action_with_its_counts() {
|
||||
let tree = Tree::new("offer");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let actions = only(code_actions(&ws, &uri, at("import a_pkg")));
|
||||
let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") };
|
||||
assert_eq!(action.title, "lucisv: organize imports (removes 1, sorts 1)");
|
||||
assert_eq!(action.kind, Some(CodeActionKind::SOURCE_ORGANIZE_IMPORTS));
|
||||
let edits = edits_of(action, &uri);
|
||||
assert_eq!(edits.len(), 1, "{edits:?}");
|
||||
assert_eq!(edits[0].new_text, " import b_pkg::*;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_in_the_body_is_offered_nothing() {
|
||||
let tree = Tree::new("body");
|
||||
let (ws, uri) = opened(&tree);
|
||||
assert!(code_actions(&ws, &uri, at("b_t q")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lazy_offer_carries_no_edit_and_resolve_supplies_one() {
|
||||
let tree = Tree::new("resolve");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let position = Position { line: 1, character: 2 };
|
||||
let offered = only(offers(&ws, &uri, position, at("import a_pkg")));
|
||||
let [offer] = offered.as_slice() else { panic!("one offer, got {offered:?}") };
|
||||
assert!(offer.edit.is_none(), "the offer reads no fan-out");
|
||||
assert!(offer.data.is_some(), "and carries what resolve needs");
|
||||
let resolved = resolve(&ws, offer.clone()).expect("resolves");
|
||||
assert_eq!(resolved.title, offer.title, "the title never changes under the user");
|
||||
assert_eq!(edits_of(&resolved, &uri).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_action_from_somewhere_else_is_not_ours_to_resolve() {
|
||||
let tree = Tree::new("not_ours");
|
||||
let (ws, _) = opened(&tree);
|
||||
let stranger = CodeAction { title: "someone else's".into(), ..Default::default() };
|
||||
assert_eq!(resolve(&ws, stranger), Err(NOT_OURS.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_organizes_at_a_position() {
|
||||
let tree = Tree::new("command");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 1, character: 2 }).expect("position"),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments).expect("organizes");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let edits = edit.changes.as_ref().expect("changes").get(&uri).expect("this file").clone();
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].new_text, " import b_pkg::*;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_says_why_when_there_is_nothing_to_organize() {
|
||||
let tree = Tree::new("nothing");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 3, character: 2 }).expect("position"),
|
||||
];
|
||||
assert_eq!(execute(&ws, &arguments), Err(NOTHING.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_set_is_the_buffer_and_the_packages_it_imports() {
|
||||
let tree = Tree::new("sources");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let path = ws.document(&uri).expect("open").path.clone().expect("path");
|
||||
let files = sources(&ws, &path, TOP, &["a_pkg".to_string(), "b_pkg".to_string()]);
|
||||
let mut names: Vec<String> = files
|
||||
.iter()
|
||||
.map(|(p, _)| p.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, vec!["a_pkg.sv", "b_pkg.sv", "top.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_asking_only_for_organize_imports_is_answered() {
|
||||
// The way organize-on-save asks: `only: ["source.organizeImports"]`.
|
||||
let filter = [CodeActionKind::SOURCE_ORGANIZE_IMPORTS];
|
||||
assert!(crate::code_action::wanted(Some(&filter), &kind()));
|
||||
assert!(!crate::code_action::wanted(
|
||||
Some(&filter),
|
||||
&CodeActionKind::new(crate::ports::REFACTOR_PORTS)
|
||||
));
|
||||
// And a request for the quick fixes alone does not reach us.
|
||||
let quick = [CodeActionKind::QUICKFIX];
|
||||
assert!(!crate::code_action::wanted(Some(&quick), &kind()));
|
||||
let _ = Range::default();
|
||||
}
|
||||
}
|
||||
@@ -116,14 +116,39 @@ pub struct IncludeGraph {
|
||||
|
||||
impl IncludeGraph {
|
||||
/// Scan every in-scope file for its `` `include``s and resolve them.
|
||||
///
|
||||
/// Test-only since 2026-09-08: the scan that used to hold every file's
|
||||
/// text no longer does, and calls [`IncludeGraph::from_includes`] with the
|
||||
/// lines it read at each file's own step. This is that call with the scan
|
||||
/// in front of it — which is what makes it the right thing for a test to
|
||||
/// build a graph from a fixture with, and the two provably one function.
|
||||
#[cfg(test)]
|
||||
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
|
||||
let scanned: Vec<(PathBuf, Vec<Include>)> =
|
||||
sources.iter().map(|(path, text)| (path.clone(), scan(text))).collect();
|
||||
let borrowed: Vec<(&Path, &[Include])> =
|
||||
scanned.iter().map(|(path, found)| (path.as_path(), found.as_slice())).collect();
|
||||
IncludeGraph::from_includes(&borrowed, incdirs)
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::build`] for a caller that has already read each file's
|
||||
/// `` `include`` lines off its text — the form a scan uses.
|
||||
///
|
||||
/// Since 2026-09-08 a scan reads a file's text at the step that indexes it
|
||||
/// and drops it again, so the text is not there to be scanned when the
|
||||
/// graph is built at the end; [`scan`] runs once per file, at that step,
|
||||
/// and the lines it found are what arrives here
|
||||
/// (`docs/features/perf5-p4/README.md` §P4b3). The two entries are the
|
||||
/// same function over the same lines — `build` is this one with the scan
|
||||
/// in front of it — so a graph built either way is the same graph.
|
||||
pub fn from_includes(sources: &[(&Path, &[Include])], incdirs: Vec<PathBuf>) -> IncludeGraph {
|
||||
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
|
||||
// Learned before the edges: `resolve` consults both tables, and an edge
|
||||
// resolved against a half-filled one would be keyed inconsistently.
|
||||
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
|
||||
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.to_path_buf()).collect();
|
||||
graph.relearn(&paths);
|
||||
for (path, text) in sources {
|
||||
graph.rescan_edges(path, text);
|
||||
for (path, found) in sources {
|
||||
graph.rescan_found(path, found);
|
||||
}
|
||||
graph.respell();
|
||||
graph
|
||||
@@ -151,9 +176,11 @@ impl IncludeGraph {
|
||||
self.respell();
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s
|
||||
/// the scope resolves to right now — the form a scan publishing what it
|
||||
/// has indexed so far uses.
|
||||
/// [`IncludeGraph::update_file`] for a batch of files whose `` `include``
|
||||
/// lines have already been read, with the `+incdir+`s the scope resolves
|
||||
/// to right now — the form a scan publishing what it has indexed so far
|
||||
/// uses. The lines come from the step that indexed each file, for the
|
||||
/// reason [`IncludeGraph::from_includes`] gives.
|
||||
///
|
||||
/// `known` is the scan's whole work list rather than the files it has
|
||||
/// reached, so the known-file and folded-spelling tables are complete from
|
||||
@@ -162,11 +189,16 @@ impl IncludeGraph {
|
||||
/// `relearn` for the batch, for the same reason
|
||||
/// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives
|
||||
/// its index tables once.
|
||||
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) {
|
||||
pub fn absorb_includes(
|
||||
&mut self,
|
||||
incdirs: &[PathBuf],
|
||||
known: &[PathBuf],
|
||||
batch: &[(&Path, &[Include])],
|
||||
) {
|
||||
self.incdirs = incdirs.to_vec();
|
||||
self.relearn(known);
|
||||
for (path, text) in batch {
|
||||
self.rescan_edges(path, text);
|
||||
for (path, found) in batch {
|
||||
self.rescan_found(path, found);
|
||||
}
|
||||
self.respell();
|
||||
}
|
||||
@@ -183,8 +215,14 @@ impl IncludeGraph {
|
||||
/// each one lands. A file that includes nothing holds no entry at all,
|
||||
/// which is what keeps `raw` a set of edges rather than a set of files.
|
||||
fn rescan_edges(&mut self, path: &Path, text: &str) {
|
||||
self.rescan_found(path, &scan(text));
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::rescan_edges`] with the file's `` `include`` lines
|
||||
/// already in hand: where the disk says each one lands, held.
|
||||
fn rescan_found(&mut self, path: &Path, found: &[Include]) {
|
||||
let targets: Vec<PathBuf> =
|
||||
scan(text).iter().filter_map(|include| self.found(Some(path), include)).collect();
|
||||
found.iter().filter_map(|include| self.found(Some(path), include)).collect();
|
||||
match targets.is_empty() {
|
||||
true => self.raw.remove(path),
|
||||
false => self.raw.insert(path.to_path_buf(), targets),
|
||||
@@ -230,6 +268,12 @@ impl IncludeGraph {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many resolved edges the graph holds and how many files it knows —
|
||||
/// the two numbers that say what a rebuilt graph weighs.
|
||||
pub fn sizes(&self) -> (usize, usize) {
|
||||
(self.edges.values().map(Vec::len).sum(), self.known.len())
|
||||
}
|
||||
|
||||
/// The `+incdir+` directories an include is looked for in, in filelist
|
||||
/// order — the search rungs past the including file's own directory.
|
||||
pub fn incdirs(&self) -> &[PathBuf] {
|
||||
|
||||
@@ -24,14 +24,17 @@
|
||||
//! `docs/features/index-persistence/README.md` and is the same one
|
||||
//! `lucisv_core::cache` accepts.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use lucisv_core::cache::content_hash;
|
||||
use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT};
|
||||
|
||||
use crate::scan_trace::CacheWork;
|
||||
use crate::settings::ClientSettings;
|
||||
|
||||
/// The store inside the cache directory.
|
||||
@@ -51,6 +54,45 @@ const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
/// The subdirectory of the OS cache directory this server's stores live in.
|
||||
const OS_DIR: [&str; 2] = ["lucisv", "index"];
|
||||
|
||||
/// What one load of the store found — the numbers that decide whether the file
|
||||
/// on disk is *already* the file a compaction would write.
|
||||
///
|
||||
/// [`IndexCache::render`] writes this build's header and then one line per
|
||||
/// path in path order, so a store this build compacted and nothing has
|
||||
/// appended to since comes back with every line kept, no line dropped, no path
|
||||
/// named twice and the paths ascending. Anything else — another version's
|
||||
/// header, a torn line, a record the checksum rejects, two lines for one path,
|
||||
/// a session's appends still unvacuumed — means the file and the render differ,
|
||||
/// and compaction is what makes them the same.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Load {
|
||||
/// Whether the first line was this build's own header.
|
||||
header: bool,
|
||||
/// Record lines the store held below the header.
|
||||
read: usize,
|
||||
/// Of those, the ones that became an entry of their own.
|
||||
kept: usize,
|
||||
/// Lines that were not a record this build can use.
|
||||
dropped: usize,
|
||||
/// Lines naming a path an earlier line had already named.
|
||||
duplicates: usize,
|
||||
/// Whether the paths arrived strictly ascending, the order `render` writes
|
||||
/// them in.
|
||||
ordered: bool,
|
||||
}
|
||||
|
||||
impl Load {
|
||||
/// Whether these lines are exactly the lines [`IndexCache::render`] would
|
||||
/// write from the entries they produced.
|
||||
fn canonical(&self) -> bool {
|
||||
self.header
|
||||
&& self.ordered
|
||||
&& self.dropped == 0
|
||||
&& self.duplicates == 0
|
||||
&& self.kept == self.read
|
||||
}
|
||||
}
|
||||
|
||||
/// What one entry asserts: a file with exactly this content contributed
|
||||
/// exactly these facts.
|
||||
struct Entry {
|
||||
@@ -75,6 +117,18 @@ pub struct IndexCache {
|
||||
/// False for a missing store — which the first write claims — and for one
|
||||
/// from another version, which the first write replaces wholesale.
|
||||
header_ok: bool,
|
||||
/// What [`IndexCache::open`] read out of the store, which is what
|
||||
/// [`IndexCache::already_compact`] asks whether a rewrite would reproduce.
|
||||
load: Load,
|
||||
/// What this cache's own work has cost since it was opened, for the
|
||||
/// startup breakdown (`docs/features/perf5-p4/README.md`).
|
||||
///
|
||||
/// A `Cell` because [`IndexCache::facts_for`] is a `&self` read and the
|
||||
/// hash/decode split is exactly the number §P4a needed. Counted whether
|
||||
/// anything is going to read it or not: four clock reads per file are
|
||||
/// noise beside the decode they bracket, and a flag threaded down here to
|
||||
/// save them would cost more code than time.
|
||||
work: Cell<CacheWork>,
|
||||
}
|
||||
|
||||
impl IndexCache {
|
||||
@@ -96,24 +150,62 @@ impl IndexCache {
|
||||
/// whose tail was cut inside a multi-byte character costs the record that
|
||||
/// was torn and no other. Reading the whole buffer as text would have
|
||||
/// rejected all of it for one bad byte at the end.
|
||||
///
|
||||
/// The load is *counted* as well as performed — lines read, kept, dropped
|
||||
/// and duplicated, and whether the paths arrived in order — because those
|
||||
/// five numbers are what say whether the file already is what
|
||||
/// [`IndexCache::compact`] would write over it.
|
||||
pub fn open(dir: Option<PathBuf>) -> IndexCache {
|
||||
let Some(dir) = dir else { return IndexCache::disabled() };
|
||||
let bytes = std::fs::read(dir.join(FILE)).unwrap_or_default();
|
||||
let mut lines = store_lines(&bytes).into_iter();
|
||||
let header_ok = lines.next() == Some(header().as_bytes());
|
||||
let mut entries = HashMap::new();
|
||||
let mut load = Load { header: header_ok, ordered: true, ..Load::default() };
|
||||
if header_ok {
|
||||
let mut previous: Option<PathBuf> = None;
|
||||
for line in lines {
|
||||
let Ok(line) = std::str::from_utf8(line) else { continue };
|
||||
if let Some((path, entry)) = parse_entry(line) {
|
||||
// A later record for a path wins: the log is appended to
|
||||
// as a rescan goes, so the last one written is the one
|
||||
// that describes the file as the server last saw it.
|
||||
entries.insert(path, entry);
|
||||
load.read += 1;
|
||||
let Ok(line) = std::str::from_utf8(line) else {
|
||||
load.dropped += 1;
|
||||
continue;
|
||||
};
|
||||
let Some((path, entry)) = parse_entry(line) else {
|
||||
load.dropped += 1;
|
||||
continue;
|
||||
};
|
||||
if let Some(previous) = &previous {
|
||||
load.ordered &= *previous < path;
|
||||
}
|
||||
previous = Some(path.clone());
|
||||
// A later record for a path wins: the log is appended to
|
||||
// as a rescan goes, so the last one written is the one
|
||||
// that describes the file as the server last saw it.
|
||||
match entries.insert(path, entry) {
|
||||
Some(_) => load.duplicates += 1,
|
||||
None => load.kept += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
IndexCache { dir: Some(dir), entries, log: None, header_ok }
|
||||
let work = Cell::new(CacheWork { opens: 1, ..CacheWork::default() });
|
||||
IndexCache { dir: Some(dir), entries, log: None, header_ok, load, work }
|
||||
}
|
||||
|
||||
/// What this cache has spent and moved since it was opened.
|
||||
pub fn work(&self) -> CacheWork {
|
||||
self.work.get()
|
||||
}
|
||||
|
||||
/// How many records this cache is holding.
|
||||
pub fn entry_count(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
/// The encoded bytes those records weigh — the retention §P4's memory
|
||||
/// hypothesis is about, since every one of them sits beside a decoded
|
||||
/// copy in the workspace index.
|
||||
pub fn encoded_bytes(&self) -> usize {
|
||||
self.entries.values().map(|entry| entry.facts.len()).sum()
|
||||
}
|
||||
|
||||
/// Where this cache writes. Test-only: production opens a cache from a
|
||||
@@ -123,6 +215,28 @@ impl IndexCache {
|
||||
self.dir.as_deref()
|
||||
}
|
||||
|
||||
/// The entry that asserts *exactly these bytes*, if there is one.
|
||||
///
|
||||
/// The one place the record and the key it is filed under are read
|
||||
/// together: an entry holds the FNV-1a of the bytes its facts were read
|
||||
/// off, and this is the only comparison anything in the server makes
|
||||
/// against it. Both readers below go through here, so "the store answers
|
||||
/// for this text" means one thing in a scan and in a refactoring alike.
|
||||
fn entry_for(&self, path: &Path, text: &str) -> Option<&Entry> {
|
||||
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()))
|
||||
}
|
||||
|
||||
/// [`IndexCache::facts_for`] asked by something that is **not** a scan.
|
||||
///
|
||||
/// The same question, the same entry, the same answer — but the work is
|
||||
/// not counted into [`IndexCache::work`], because that counter is what a
|
||||
/// scan's own trace subtracts to say what *it* did. A refactoring reading
|
||||
/// records between two scans would otherwise show up as decodes the next
|
||||
/// scan never made (review round §R3b, `crate::state::Workspace::known_facts`).
|
||||
pub fn facts_now(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
FileFacts::decode(&self.entry_for(path, text)?.facts)
|
||||
}
|
||||
|
||||
/// The facts a previous session read off this exact text, if it did.
|
||||
///
|
||||
/// The hash is of the text the server is about to index — an open buffer's
|
||||
@@ -133,11 +247,27 @@ impl IndexCache {
|
||||
/// they were written with, which [`IndexCache::open`] drops before it ever
|
||||
/// gets here.
|
||||
pub fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
let entry = self.entries.get(path)?;
|
||||
if entry.content != content_hash(text.as_bytes()) {
|
||||
let looking = Instant::now();
|
||||
let found = self.entry_for(path, text);
|
||||
let mut work = self.work.get();
|
||||
work.lookup_ns += elapsed_ns(looking);
|
||||
let Some(entry) = found else {
|
||||
work.misses += 1;
|
||||
self.work.set(work);
|
||||
return None;
|
||||
};
|
||||
let decoding = Instant::now();
|
||||
let facts = FileFacts::decode(&entry.facts);
|
||||
work.decode_ns += elapsed_ns(decoding);
|
||||
work.decoded_bytes += entry.facts.len();
|
||||
// A record that no longer decodes costs a parse, so it is a miss —
|
||||
// the counters say what the scan actually did, not what it looked up.
|
||||
match facts.is_some() {
|
||||
true => work.hits += 1,
|
||||
false => work.misses += 1,
|
||||
}
|
||||
FileFacts::decode(&entry.facts)
|
||||
self.work.set(work);
|
||||
facts
|
||||
}
|
||||
|
||||
/// Record what parsing `text` found, and write it through immediately.
|
||||
@@ -149,13 +279,36 @@ impl IndexCache {
|
||||
/// the checksum of the facts it was written with) for the same reasons it
|
||||
/// rejects any other malformed record. That is the whole crash-safety
|
||||
/// argument, and it is why records are one line each.
|
||||
///
|
||||
/// **A record the store already holds is not written again.** An open
|
||||
/// buffer is indexed from its own analysis on every scan and its record is
|
||||
/// written through with it, so a warm session appends a line for every
|
||||
/// open buffer that is byte-identical to the line already in the store —
|
||||
/// a duplicate the next load collapses, at the price of making the store
|
||||
/// non-canonical and so owing [`IndexCache::compact`] a full rewrite. The
|
||||
/// test is the exact one: same path, same content hash, same encoded
|
||||
/// facts. Anything that differs by a byte is a new record and is appended
|
||||
/// as it always was.
|
||||
pub fn record(&mut self, facts: &FileFacts, text: &str) {
|
||||
if self.dir.is_none() {
|
||||
return;
|
||||
}
|
||||
let encoding = Instant::now();
|
||||
let Some(encoded) = facts.encode() else { return };
|
||||
let content = content_hash(text.as_bytes());
|
||||
let mut work = self.work.get();
|
||||
work.encode_ns += elapsed_ns(encoding);
|
||||
if self.holds(facts.path(), content, &encoded) {
|
||||
work.repeats += 1;
|
||||
self.work.set(work);
|
||||
return;
|
||||
}
|
||||
let writing = Instant::now();
|
||||
self.append(&line(content, &encoded));
|
||||
work.write_ns += elapsed_ns(writing);
|
||||
work.records += 1;
|
||||
work.written_bytes += encoded.len();
|
||||
self.work.set(work);
|
||||
self.entries.insert(facts.path().to_path_buf(), Entry { content, facts: encoded });
|
||||
}
|
||||
|
||||
@@ -171,7 +324,76 @@ impl IndexCache {
|
||||
/// Atomic and silent: written to a temporary file and renamed, and a
|
||||
/// failure anywhere leaves the previous store standing. A cache that could
|
||||
/// fail a rescan would be worse than no cache.
|
||||
///
|
||||
/// **Skipped when the rewrite would reproduce the file byte for byte**
|
||||
/// ([`IndexCache::already_compact`]). A warm session whose every file hit
|
||||
/// the store appends nothing, so the store it loaded is the store it would
|
||||
/// write, and rewriting 44 MiB to produce the same 44 MiB was 182 ms of a
|
||||
/// 1.33 s start (`docs/features/perf5-p4/README.md`, §P4b (a)).
|
||||
pub fn compact(&mut self) {
|
||||
let before = self.store_bytes();
|
||||
let compacting = Instant::now();
|
||||
let rewriting = !self.already_compact();
|
||||
if rewriting {
|
||||
self.compact_now();
|
||||
}
|
||||
let mut work = self.work.get();
|
||||
work.compact_ns += elapsed_ns(compacting);
|
||||
work.compactions += usize::from(rewriting);
|
||||
work.store_before = before;
|
||||
work.store_after = self.store_bytes();
|
||||
self.work.set(work);
|
||||
}
|
||||
|
||||
/// Whether the store on disk is already exactly what [`IndexCache::render`]
|
||||
/// would write over it.
|
||||
///
|
||||
/// Four things have to hold, and any one of them failing compacts as
|
||||
/// before:
|
||||
///
|
||||
/// * the store was **loaded canonical** — this build's header, every line
|
||||
/// a record this build can read, no path named twice, the paths
|
||||
/// ascending ([`Load::canonical`]);
|
||||
/// * **nothing has been appended since**, so no line is out of order and
|
||||
/// no path has a second one;
|
||||
/// * **no entry's file is gone**, because `render` drops those;
|
||||
/// * there is a directory to write in at all.
|
||||
///
|
||||
/// **Crash safety is untouched.** A session that appended nothing left the
|
||||
/// store exactly as it found it, so what is on disk is already the
|
||||
/// compacted file and there is no half-written state a rewrite would
|
||||
/// resolve; skipping it only means the append log — which has no appends —
|
||||
/// stays as it is. The existence sweep is the one part that costs
|
||||
/// anything, one `stat` per entry, against the whole-store render and
|
||||
/// write it stands in for.
|
||||
fn already_compact(&self) -> bool {
|
||||
self.dir.is_some()
|
||||
&& self.load.canonical()
|
||||
&& self.work.get().records == 0
|
||||
&& self.entries.keys().all(|path| path.exists())
|
||||
}
|
||||
|
||||
/// Whether the store already holds exactly this record — the same path,
|
||||
/// the same content hash and the same encoded facts, byte for byte.
|
||||
///
|
||||
/// Only exactly that counts. A record whose facts differ by a byte under
|
||||
/// the same hash is still written, because the line on disk and the facts
|
||||
/// in hand would then disagree and the store must say what this session
|
||||
/// last saw.
|
||||
fn holds(&self, path: &Path, content: u64, encoded: &str) -> bool {
|
||||
self.entries
|
||||
.get(path)
|
||||
.is_some_and(|entry| entry.content == content && entry.facts == encoded)
|
||||
}
|
||||
|
||||
/// The store file's size on disk, or 0 when there is no store.
|
||||
fn store_bytes(&self) -> u64 {
|
||||
let Some(dir) = self.dir.as_ref() else { return 0 };
|
||||
std::fs::metadata(dir.join(FILE)).map(|meta| meta.len()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`IndexCache::compact`] without the accounting around it.
|
||||
fn compact_now(&mut self) {
|
||||
let Some(dir) = self.dir.clone() else { return };
|
||||
// The append handle must go before the rename, or a later append would
|
||||
// write into the file the rename replaced.
|
||||
@@ -342,6 +564,11 @@ fn line(content: u64, facts: &str) -> String {
|
||||
/// `None` for anything that is not a whole record whose facts still match
|
||||
/// their checksum, which includes the torn last line of a store whose writer
|
||||
/// was killed.
|
||||
/// Nanoseconds since `from`, saturated into the counters' `u64`.
|
||||
fn elapsed_ns(from: Instant) -> u64 {
|
||||
from.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64
|
||||
}
|
||||
|
||||
fn parse_entry(line: &str) -> Option<(PathBuf, Entry)> {
|
||||
let (hash, rest) = line.split_once('\t')?;
|
||||
// Exactly as wide as `line` writes it: a hash that reads as a number but
|
||||
@@ -507,6 +734,42 @@ mod tests {
|
||||
assert!(reopened.facts_for(Path::new("/nowhere.sv"), M).is_none());
|
||||
}
|
||||
|
||||
/// **The R3b tie, both ways.** `facts_now` is the same content key
|
||||
/// `facts_for` is — a record answers for the bytes it was read off and for
|
||||
/// no others — and it leaves the scan's own work counters alone.
|
||||
///
|
||||
/// The stale case is the one that matters: a record written from one text
|
||||
/// must never be handed to a refactoring reading a different text, because
|
||||
/// the refactoring would index it as that file's facts and edit against an
|
||||
/// index describing bytes nobody has.
|
||||
#[test]
|
||||
fn a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work() {
|
||||
let dir = TempDir::new("factsnow");
|
||||
let file = dir.file("m.sv", M);
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.record(&facts(&file, M), M);
|
||||
cache.compact();
|
||||
|
||||
let reopened = IndexCache::open(Some(dir.path.clone()));
|
||||
let before = reopened.work();
|
||||
assert_eq!(reopened.facts_now(&file, M), Some(facts(&file, M)), "these bytes");
|
||||
// Every way the bytes can differ, and the wrong path too.
|
||||
const EDITED: &str = "module m;\n sub u ();\n wire added;\nendmodule\n";
|
||||
assert!(reopened.facts_now(&file, EDITED).is_none(), "a stale record must not be served");
|
||||
assert!(reopened.facts_now(&file, "").is_none(), "nor an empty buffer's");
|
||||
assert!(reopened.facts_now(&file, &M[..M.len() - 1]).is_none(), "nor one byte short");
|
||||
assert!(reopened.facts_now(Path::new("/nowhere.sv"), M).is_none(), "nor another path's");
|
||||
let after = reopened.work();
|
||||
assert_eq!(
|
||||
(after.hits, after.misses, after.decode_ns, after.lookup_ns),
|
||||
(before.hits, before.misses, before.decode_ns, before.lookup_ns),
|
||||
"a refactoring's reads are not a scan's work"
|
||||
);
|
||||
// The counted reader, asked the same questions, answers the same way.
|
||||
assert_eq!(reopened.facts_for(&file, M), reopened.facts_now(&file, M));
|
||||
assert_eq!(reopened.facts_for(&file, EDITED), reopened.facts_now(&file, EDITED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_survives_a_session_that_never_compacted() {
|
||||
// The crash case: records are written through as they are made, so a
|
||||
@@ -720,6 +983,221 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A store two files were recorded into and then compacted — this build's
|
||||
/// header and one line per path in path order, which is what every
|
||||
/// session after a whole rescan finds on disk.
|
||||
fn compacted_store(dir: &TempDir) -> (PathBuf, PathBuf) {
|
||||
let one = dir.file("a.sv", M);
|
||||
let two = dir.file("b.sv", M);
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.record(&facts(&one, M), M);
|
||||
cache.record(&facts(&two, M), M);
|
||||
cache.compact();
|
||||
assert_eq!(cache.work().compactions, 1, "premise: the store was written");
|
||||
(one, two)
|
||||
}
|
||||
|
||||
/// The store's bytes and its modification time — "not rewritten" as
|
||||
/// something a test can see rather than infer.
|
||||
fn store_stamp(dir: &TempDir) -> (Vec<u8>, std::time::SystemTime) {
|
||||
let path = dir.path.join(FILE);
|
||||
let bytes = std::fs::read(&path).expect("read store");
|
||||
let stamp = std::fs::metadata(&path).expect("meta").modified().expect("mtime");
|
||||
(bytes, stamp)
|
||||
}
|
||||
|
||||
/// Rewrite the store's record lines, keeping this build's header.
|
||||
fn rewrite_records(dir: &TempDir, records: &[String]) {
|
||||
let mut text = header();
|
||||
for record in records {
|
||||
text.push('\n');
|
||||
text.push_str(record);
|
||||
}
|
||||
text.push('\n');
|
||||
std::fs::write(dir.path.join(FILE), text).expect("write store");
|
||||
}
|
||||
|
||||
/// The store's record lines, header excluded.
|
||||
fn records_of(dir: &TempDir) -> Vec<String> {
|
||||
dir.store_text().lines().skip(1).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canonical_store_nothing_appended_to_is_not_rewritten() {
|
||||
// §P4b (a): a warm session hits the store for every file, appends
|
||||
// nothing, and would rewrite 44 MiB to produce the same 44 MiB —
|
||||
// 182 ms of a 1.33 s start. What is on disk is already what `render`
|
||||
// writes, so the rewrite is skipped and the file is not touched at
|
||||
// all: not its bytes, not even its modification time.
|
||||
let dir = TempDir::new("alreadycompact");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let before = store_stamp(&dir);
|
||||
|
||||
let mut warm = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(warm.facts_for(&one, M).is_some(), "premise: a warm session that only reads");
|
||||
warm.compact();
|
||||
|
||||
assert_eq!(warm.work().compactions, 0, "the rewrite would have been byte-identical");
|
||||
assert_eq!(store_stamp(&dir), before, "so the store was not touched");
|
||||
// And what is on disk is still a store: the next session reads it.
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_the_store_already_holds_is_not_appended_again() {
|
||||
// An open buffer is indexed from its own analysis on *every* scan and
|
||||
// its record is written through with it, so a warm session would
|
||||
// append a byte-identical duplicate for each open buffer — which
|
||||
// costs the store its canonical shape and so owes the next scan a
|
||||
// whole 44 MiB rewrite. The same record is a no-op; a changed one is
|
||||
// not (`docs/features/perf5-p4/README.md`, §P4b (a)).
|
||||
let dir = TempDir::new("repeatrecord");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let before = store_stamp(&dir);
|
||||
|
||||
let mut warm = IndexCache::open(Some(dir.path.clone()));
|
||||
warm.record(&facts(&one, M), M);
|
||||
assert_eq!(warm.work().records, 0, "nothing was appended");
|
||||
assert_eq!(warm.work().repeats, 1, "and the store was already holding it");
|
||||
assert_eq!(store_stamp(&dir), before, "so the store on disk did not move");
|
||||
warm.compact();
|
||||
assert_eq!(warm.work().compactions, 0, "which leaves it canonical");
|
||||
assert_eq!(store_stamp(&dir), before);
|
||||
|
||||
// One byte of difference and the record is written exactly as before.
|
||||
let edited = "module m;\n sub u ();\n wire w;\nendmodule\n";
|
||||
warm.record(&facts(&one, edited), edited);
|
||||
assert_eq!(warm.work().records, 1, "different bytes are a new record");
|
||||
assert_eq!(warm.work().repeats, 1);
|
||||
warm.compact();
|
||||
assert_eq!(warm.work().compactions, 1, "and the rewrite is owed again");
|
||||
assert_eq!(
|
||||
IndexCache::open(Some(dir.path.clone())).facts_for(&one, edited),
|
||||
Some(facts(&one, edited)),
|
||||
"the newer record is what the next session reads"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_with_two_lines_for_one_path_is_compacted() {
|
||||
// The growth bound the skip must not cost: a session that saved a
|
||||
// file appended a second line for its path, and only a rewrite folds
|
||||
// the two back into one.
|
||||
let dir = TempDir::new("dupline");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
let repeat = records[0].clone();
|
||||
records.push(repeat);
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a duplicated path is not canonical");
|
||||
assert_eq!(records_of(&dir).len(), 2, "one line per path again");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_with_a_line_this_build_cannot_read_is_compacted() {
|
||||
// A record dropped at load — a torn append, bit rot, a checksum that
|
||||
// no longer matches — means the file on disk holds a line `render`
|
||||
// would not write, so the store is not canonical and the rewrite is
|
||||
// what removes it.
|
||||
let dir = TempDir::new("droppedline");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
records.push(format!("{}\tnot a record at all\t{:016x}", "0".repeat(16), 0));
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a dropped line is not canonical");
|
||||
assert_eq!(records_of(&dir).len(), 2, "the unreadable line is gone");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_whose_records_are_out_of_path_order_is_compacted() {
|
||||
// `render` writes paths sorted, so a store that arrives unsorted was
|
||||
// not written by a compaction of this shape and rewriting it is not a
|
||||
// no-op — even though every line in it is a good record.
|
||||
let dir = TempDir::new("unsorted");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
records.reverse();
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "an unsorted store is not canonical");
|
||||
let sorted: Vec<String> = records_of(&dir);
|
||||
assert_eq!(sorted.len(), 2);
|
||||
assert!(sorted[0] < sorted[1], "path order restored: {sorted:?}");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_recorded_one_file_compacts() {
|
||||
// The moment an append happens the store on disk is no longer the
|
||||
// store `render` would write — the appended line is out of order at
|
||||
// best and a second line for its path at worst — so the rewrite is
|
||||
// owed exactly as it always was.
|
||||
let dir = TempDir::new("appended");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let third = dir.file("c.sv", M);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(cache.facts_for(&one, M).is_some(), "the other two still hit");
|
||||
cache.record(&facts(&third, M), M);
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a session that appended must rewrite");
|
||||
assert_eq!(records_of(&dir).len(), 3);
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&third, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_holding_a_file_that_is_gone_is_compacted() {
|
||||
// `render` drops an entry whose file no longer exists, so a store
|
||||
// holding one is not what a rewrite would produce — and the rewrite
|
||||
// is what prunes it, exactly as before.
|
||||
let dir = TempDir::new("goneentry");
|
||||
let (one, two) = compacted_store(&dir);
|
||||
std::fs::remove_file(&two).expect("remove");
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a gone file must still be pruned");
|
||||
assert_eq!(records_of(&dir).len(), 1, "the vanished file's line is gone");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_from_another_version_is_replaced_even_by_a_session_that_wrote_nothing() {
|
||||
// The header is the one line the skip may never leave standing: its
|
||||
// records were dropped at load, so a session that keeps it leaves a
|
||||
// store nobody can read on disk for ever.
|
||||
let dir = TempDir::new("foreignheader");
|
||||
let file = dir.file("m.sv", M);
|
||||
let encoded = facts(&file, M).encode().expect("encodes");
|
||||
let foreign = format!(
|
||||
"lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-build\n{}\n",
|
||||
line(content_hash(M.as_bytes()), &encoded)
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), foreign).expect("write");
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "another version's header is not canonical");
|
||||
let text = dir.store_text();
|
||||
assert_eq!(text, format!("{}\n", header()), "replaced with this build's own: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure() {
|
||||
// The line is well-formed as far as the store is concerned — hash,
|
||||
|
||||
Loaded 100 of 732 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user