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 |
No files matched your search
@@ -7,3 +7,4 @@
|
||||
.DS_Store
|
||||
/.zcode
|
||||
/.claude
|
||||
__pycache__/
|
||||
+530
@@ -4,6 +4,536 @@ 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
|
||||
|
||||
@@ -70,6 +70,13 @@ is in the decomposition-server README) and `vlog_parser/src/lexer.rs`
|
||||
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]`
|
||||
|
||||
Generated
+24
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.40.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.40.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.40.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,15 +262,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.40.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.40.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.40.0"
|
||||
version = "0.56.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.40.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.40.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.40.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
|
||||
@@ -158,11 +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 other than `[lint]`, 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
|
||||
@@ -275,6 +295,7 @@ makes an editor's red squiggle worth believing.
|
||||
| `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 |
|
||||
@@ -387,13 +408,61 @@ 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 |
|
||||
|---|---|---|
|
||||
@@ -401,7 +470,20 @@ generic pretty-printing IR, language formatting rules, and a thin CLI:
|
||||
| `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/` | `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:
|
||||
|
||||
@@ -414,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
|
||||
|
||||
@@ -534,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`
|
||||
@@ -771,8 +867,8 @@ See `docs/features/corpus-check/README.md` for the 820-file corpus baseline:
|
||||
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. `randsequence` remained unsupported at
|
||||
this point; the other vendor/formal constructs listed here landed later in
|
||||
0.30.0
|
||||
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
|
||||
@@ -812,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
|
||||
@@ -871,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.
|
||||
|
||||
@@ -903,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`.
|
||||
@@ -71,6 +71,12 @@ 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,
|
||||
@@ -100,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
|
||||
}
|
||||
|
||||
@@ -203,6 +215,9 @@ CHECK OPTIONS (`lucisv check` only):
|
||||
--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
|
||||
@@ -215,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
|
||||
@@ -250,8 +290,11 @@ CONFIGURATION:
|
||||
read by lucisv-server only — the CLI reads a filelist only when `-f` names
|
||||
one, so `lucisv rtl/` always means the directory it was given). One table
|
||||
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
|
||||
`--select`/`--ignore` semantics). A command line flag overrides the file's
|
||||
corresponding key; the other keys still apply.
|
||||
`--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
|
||||
@@ -298,6 +341,7 @@ 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(),
|
||||
@@ -378,6 +422,10 @@ 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();
|
||||
@@ -444,6 +492,7 @@ 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 = [
|
||||
@@ -614,6 +663,16 @@ mod tests {
|
||||
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);
|
||||
|
||||
+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;
|
||||
+254
-66
@@ -16,7 +16,8 @@ use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::Config;
|
||||
use vlog_linter::words;
|
||||
use vlog_linter::{
|
||||
apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, RuleOptions, Violation,
|
||||
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
|
||||
Violation, WaiverUse,
|
||||
};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
@@ -46,6 +47,15 @@ pub struct Plan {
|
||||
/// 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.
|
||||
@@ -61,6 +71,49 @@ pub struct Census {
|
||||
/// 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 {
|
||||
@@ -71,34 +124,29 @@ impl Census {
|
||||
/// file's own check reports the error.
|
||||
///
|
||||
/// `interfaces` says whether the run also needs each unit's ports and
|
||||
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
|
||||
/// of every file on top of the lex the word census already pays for, so
|
||||
/// it 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) -> Census {
|
||||
type PerFile = (Vec<String>, Vec<(String, Option<vlog_linter::ModuleInterface>)>);
|
||||
let per_file: Vec<PerFile> = jobs
|
||||
.par_iter()
|
||||
.map(|job| {
|
||||
let Ok(src) = std::fs::read_to_string(&job.path) else {
|
||||
return (Vec::new(), Vec::new());
|
||||
};
|
||||
if !interfaces {
|
||||
return (words::harvest_text(&src), Vec::new());
|
||||
}
|
||||
// One lex for both halves: the parse is what the interface
|
||||
// table needs, and its tokens are the word census's.
|
||||
let parsed = ParsedSource::parse(&src);
|
||||
(words::harvest(parsed.tokens()), vlog_linter::module_interfaces(parsed.file()))
|
||||
})
|
||||
.collect();
|
||||
/// 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();
|
||||
for (words, declared) in per_file {
|
||||
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.
|
||||
@@ -112,7 +160,7 @@ impl Census {
|
||||
.or_insert(interface);
|
||||
}
|
||||
}
|
||||
Census { files, interfaces: units }
|
||||
Census { files, interfaces: units, packages: exported }
|
||||
}
|
||||
|
||||
/// How many files in the run write `name` down.
|
||||
@@ -124,6 +172,15 @@ impl Census {
|
||||
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
|
||||
@@ -148,6 +205,13 @@ impl MentionOracle for Elsewhere<'_> {
|
||||
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.
|
||||
@@ -163,6 +227,7 @@ impl MentionOracle for Elsewhere<'_> {
|
||||
/// 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());
|
||||
@@ -172,10 +237,64 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
|
||||
let options = rule_options(&file_config)?;
|
||||
jobs.push(Job { path, config, rules, options });
|
||||
}
|
||||
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
|
||||
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
|
||||
let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces));
|
||||
Ok(Plan { jobs, census })
|
||||
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
|
||||
@@ -216,6 +335,12 @@ 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() {
|
||||
@@ -234,12 +359,30 @@ 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, plan: &Plan) -> ExitCode {
|
||||
@@ -247,9 +390,20 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
.jobs
|
||||
.par_iter()
|
||||
.map(|job| {
|
||||
check_one(&job.path, &job.config, opts, &job.rules, &job.options, plan.census.as_ref())
|
||||
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.
|
||||
@@ -257,6 +411,37 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
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(
|
||||
@@ -265,32 +450,34 @@ pub fn check_stdin(
|
||||
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, options, None);
|
||||
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],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> 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),
|
||||
};
|
||||
|
||||
@@ -300,14 +487,13 @@ fn check_one(
|
||||
};
|
||||
let outcome = crate::catch_panic(|| {
|
||||
if opts.fix {
|
||||
fix_source(&src, file, config, opts, rules, options, census)
|
||||
fix_source(&src, file, opts, pass)
|
||||
} else {
|
||||
let (violations, lex_error) =
|
||||
run_rules(&src, Some(file.to_path_buf()), config, rules, options, census);
|
||||
(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}")),
|
||||
};
|
||||
@@ -322,21 +508,20 @@ fn check_one(
|
||||
// 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],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> (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
|
||||
@@ -360,7 +545,8 @@ fn run_rules(
|
||||
Some(elsewhere) => ctx.with_oracle(elsewhere),
|
||||
None => ctx,
|
||||
};
|
||||
(lint(&ctx, rules), lex_error)
|
||||
let (violations, used) = lint_with(&ctx, rules, external);
|
||||
(violations, used, lex_error)
|
||||
}
|
||||
|
||||
/// The violations whose fix may be applied: everything except a fix that
|
||||
@@ -399,16 +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],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> (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, options, census);
|
||||
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);
|
||||
@@ -417,11 +602,14 @@ fn fix_source(
|
||||
}
|
||||
fixed += round.applied;
|
||||
text = round.output;
|
||||
(violations, lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
|
||||
(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.
|
||||
|
||||
@@ -128,7 +128,17 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
return lint::check_stdin(opts, &src, &config, &rules, &options);
|
||||
// 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,
|
||||
@@ -323,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
|
||||
@@ -356,7 +371,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, 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.
|
||||
@@ -405,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();
|
||||
@@ -592,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();
|
||||
|
||||
+416
-5
@@ -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");
|
||||
@@ -935,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);
|
||||
@@ -1133,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]
|
||||
@@ -1229,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));
|
||||
@@ -1254,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");
|
||||
@@ -1263,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));
|
||||
@@ -2012,3 +2209,217 @@ fn rules_doc_refuses_files_and_belongs_to_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}"
|
||||
);
|
||||
}
|
||||
@@ -7,11 +7,24 @@
|
||||
//! gets the bytes, and a `rename` over the target publishes them in one step
|
||||
//! that either happened or did not.
|
||||
//!
|
||||
//! See `docs/features/small-items-3/README.md`.
|
||||
//! 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;
|
||||
use std::io;
|
||||
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.
|
||||
///
|
||||
@@ -21,6 +34,12 @@ use std::path::{Path, PathBuf};
|
||||
/// 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
|
||||
@@ -28,26 +47,22 @@ use std::path::{Path, PathBuf};
|
||||
/// 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 fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) {
|
||||
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 = temp_path(&target)?;
|
||||
if let Err(e) = fs::write(&tmp, bytes) {
|
||||
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);
|
||||
}
|
||||
// A file someone made read-only, or executable, keeps its mode: the temp
|
||||
// was created with the process umask, not with the target's bits. No
|
||||
// target means a new file, which takes the umask as `fs::write` would.
|
||||
if let Ok(meta) = fs::metadata(&target) {
|
||||
let _ = fs::set_permissions(&tmp, meta.permissions());
|
||||
}
|
||||
drop(file);
|
||||
if let Err(e) = fs::rename(&tmp, &target) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
@@ -55,16 +70,106 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
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 so two lucisv runs over one tree cannot collide.
|
||||
/// 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!(".{}.lucisv-tmp", std::process::id()));
|
||||
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
|
||||
Ok(dir.join(tmp))
|
||||
}
|
||||
|
||||
@@ -199,4 +304,148 @@ mod tests {
|
||||
);
|
||||
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.
|
||||
@@ -104,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
|
||||
@@ -137,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)
|
||||
@@ -201,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]
|
||||
@@ -234,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");
|
||||
@@ -254,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}"
|
||||
);
|
||||
}
|
||||
@@ -277,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:?}");
|
||||
@@ -295,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,
|
||||
|
||||
@@ -30,6 +30,10 @@ 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
|
||||
@@ -37,6 +41,15 @@ pub struct FileConfig {
|
||||
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.
|
||||
///
|
||||
@@ -93,8 +106,10 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
|
||||
enum Table {
|
||||
/// Before any header: the formatter's own keys.
|
||||
Top,
|
||||
/// `[lint]`: `select` and `ignore`.
|
||||
/// `[lint]`: `select`, `ignore` and `waivers`.
|
||||
Lint,
|
||||
/// `[format]`: the layout keys that are off by default.
|
||||
Format,
|
||||
/// `[lint.<rule>]`: that rule's options.
|
||||
Rule(String),
|
||||
}
|
||||
@@ -106,13 +121,17 @@ fn parse_entry(
|
||||
number: usize,
|
||||
) -> Result<(), String> {
|
||||
if line.starts_with('[') {
|
||||
// `[lint]` carries `select`/`ignore`; `[lint.<rule>]` carries that
|
||||
// `[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>]`"));
|
||||
@@ -121,7 +140,8 @@ fn parse_entry(
|
||||
return Ok(());
|
||||
}
|
||||
return Err(format!(
|
||||
"unknown table `{line}` (the tables are `[lint]` and `[lint.<rule-name>]`)"
|
||||
"unknown table `{line}` \
|
||||
(the tables are `[format]`, `[lint]` and `[lint.<rule-name>]`)"
|
||||
));
|
||||
}
|
||||
let (key, value) =
|
||||
@@ -132,6 +152,7 @@ fn parse_entry(
|
||||
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 => {}
|
||||
@@ -155,19 +176,59 @@ fn parse_entry(
|
||||
}
|
||||
_ => Err(format!(
|
||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
||||
select, ignore under `[lint]`; and a rule's own options under \
|
||||
`[lint.<rule-name>]`)"
|
||||
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)"))
|
||||
return Err(format!(
|
||||
"unknown key `{key}` under `[lint]` (known keys: select, ignore, waivers)"
|
||||
))
|
||||
}
|
||||
};
|
||||
if slot.is_some() {
|
||||
@@ -359,10 +420,16 @@ 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)
|
||||
@@ -428,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());
|
||||
@@ -498,6 +593,65 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@
|
||||
//! needs to be processed at all, and `filelist` answers the first one the way
|
||||
//! 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. See
|
||||
//! 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.
|
||||
@@ -16,5 +17,6 @@
|
||||
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
@@ -108,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();
|
||||
@@ -293,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)
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionResponse;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{MemberSite, Semantics, SymbolKind, WorkspaceIndex};
|
||||
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::site::balanced;
|
||||
use super::tiers::innermost_scope;
|
||||
@@ -168,6 +168,14 @@ fn members_at(
|
||||
site: &MemberSite,
|
||||
) -> Vec<Member> {
|
||||
let mut members = Members::new();
|
||||
// A cross-file site says which surface its own tail resolution reads, and
|
||||
// the list follows it: behind `u_x.` in an *expression* that is the
|
||||
// module's hierarchical surface — its nets, variables and instances as
|
||||
// well as its ports and parameters — which is exactly what the in-file
|
||||
// `MemberSite::Scope` half above offers for an instance this file
|
||||
// declares. A connection list's `.` never arrives here; it is
|
||||
// `connection_members` below, and it is the connection surface.
|
||||
let mut surface = Surface::Connection;
|
||||
let base = match site {
|
||||
MemberSite::Scope(scope) => {
|
||||
let (scopes, base) = semantics.member_scopes(*scope);
|
||||
@@ -181,10 +189,13 @@ fn members_at(
|
||||
// overlay's own inheritance chase does.
|
||||
base.map(|path| last_segment(&path).to_string())
|
||||
}
|
||||
MemberSite::Unit(unit) => Some(unit.clone()),
|
||||
MemberSite::Unit { path, surface: reads } => {
|
||||
surface = *reads;
|
||||
Some(path.clone())
|
||||
}
|
||||
};
|
||||
if let Some(unit) = base {
|
||||
for (name, def) in index.members_of_chain(&unit) {
|
||||
for (name, def) in index.members_of_chain_in(&unit, surface) {
|
||||
members.push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
|
||||
}
|
||||
}
|
||||
@@ -983,6 +994,53 @@ endmodule
|
||||
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
|
||||
}
|
||||
|
||||
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
|
||||
/// *expression* the list is the module's **hierarchical** surface — its
|
||||
/// nets, its variables and its instances as well as its ports and its
|
||||
/// parameters — because that is what a hierarchical path may name and
|
||||
/// exactly what the tail resolution will find, so every item offered is
|
||||
/// an item hover and go-to-definition answer. Behind the `.` of a
|
||||
/// **connection list** it is the connection surface and nothing more:
|
||||
/// `.internal(w)` is not a legal connection, and an item the resolution
|
||||
/// could not find is a wrong answer rather than a generous one.
|
||||
#[test]
|
||||
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
|
||||
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
|
||||
let hierarchical = {
|
||||
let tree = Tree::new("hiersurface_expr");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("leaf.sv", "module leaf;\nendmodule\n");
|
||||
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
|
||||
let mut found = labels(&items(completions(&ws, &uri, position, true)))
|
||||
.iter()
|
||||
.map(|l| l.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
found.sort();
|
||||
found
|
||||
};
|
||||
assert_eq!(
|
||||
hierarchical,
|
||||
vec!["clk", "counter", "internal", "u_leaf"],
|
||||
"the port and the three hierarchical-only members"
|
||||
);
|
||||
|
||||
let connection = {
|
||||
let tree = Tree::new("hiersurface_conn");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("leaf.sv", "module leaf;\nendmodule\n");
|
||||
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, " .");
|
||||
let mut found = labels(&items(completions(&ws, &uri, position, true)))
|
||||
.iter()
|
||||
.map(|l| l.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
found.sort();
|
||||
found
|
||||
};
|
||||
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_instance_lists_its_ports_too() {
|
||||
let tree = Tree::new("ifaceconn");
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -755,6 +755,92 @@ endmodule
|
||||
assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the default scope (TODO §37.2 / `performance_take2.md` §4b, §8)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// An opentitan-shaped tree: an IP block with its RTL and its testbench,
|
||||
/// and a shared library folder outside that block. Opening
|
||||
/// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to
|
||||
/// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is
|
||||
/// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against
|
||||
/// `hw/dv/sv/common_ifs/pins_if.sv`.
|
||||
fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) {
|
||||
const TB: &str =
|
||||
"module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n";
|
||||
let tree = Tree::new(name);
|
||||
fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs");
|
||||
fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs");
|
||||
fs::create_dir_all(tree.path.join("dv/common")).expect("dirs");
|
||||
tree.write("ip/aes/rtl/sub.sv", SUB);
|
||||
tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n");
|
||||
let tb = tree.write("ip/aes/dv/tb/tb.sv", TB);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
// The shipped default: no `index.scope`, `scopeDepth` 2.
|
||||
ws.set_client_settings(crate::settings::ClientSettings::default());
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&tb).expect("uri");
|
||||
ws.set_document(uri.clone(), TB.to_string());
|
||||
ws.rebuild_index();
|
||||
(tree, ws, uri, TB)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_scope_hints_a_module_the_didopen_widen_reached() {
|
||||
// `performance_take2.md` §4b measured 0 hints at the default scope
|
||||
// where the workspace scope gives 4, and §8 filed it as a correctness
|
||||
// gap. It is not one: the hints that scope answers are exactly the
|
||||
// instantiations whose module the widen reached.
|
||||
let (tree, ws, uri, _) = default_scoped("default_scope");
|
||||
assert!(
|
||||
ws.index().files().iter().any(|f| f.ends_with("sub.sv")),
|
||||
"the widen reached the block's own RTL: {:?}",
|
||||
ws.index().files()
|
||||
);
|
||||
assert!(
|
||||
!ws.index().files().iter().any(|f| f.ends_with("far.sv")),
|
||||
"and not the library folder beside it"
|
||||
);
|
||||
|
||||
let hints = inlay_hints(&ws, &uri, everything());
|
||||
let labels: Vec<String> = hints
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let InlayHintLabel::String(s) = h.label else { panic!("string") };
|
||||
s
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted");
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() {
|
||||
// The other half of the same finding: the `far` instantiation gets no
|
||||
// hints — and go-to-definition and hover give nothing for it either.
|
||||
// The zero is the scope's, not this module's; inlay uses the same
|
||||
// `module_definition` lookup its neighbours do.
|
||||
let (tree, ws, uri, tb) = default_scoped("out_of_scope");
|
||||
let hints = inlay_hints(&ws, &uri, everything());
|
||||
assert!(
|
||||
hints.iter().all(|hint| hint.position.line != 2),
|
||||
"nothing on the `far` line: {hints:#?}"
|
||||
);
|
||||
|
||||
let far = tb.find("far u_far").expect("the instantiation") as u32;
|
||||
assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer");
|
||||
assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover");
|
||||
|
||||
// And the moment the scope reaches it, all three answer.
|
||||
let mut wide = Workspace::default();
|
||||
wide.open_whole_workspace(vec![tree.path.clone()]);
|
||||
wide.set_document(uri.clone(), tb.to_string());
|
||||
let hints = inlay_hints(&wide, &uri, everything());
|
||||
assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}");
|
||||
assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1);
|
||||
}
|
||||
|
||||
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
|
||||
/// timing assertions in a shared CI runner are flaky by nature. Run with
|
||||
/// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`.
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Inline a module at the cursor, on the wire: `textDocument/codeAction` under
|
||||
//! LSP's own `refactor.inline`, and `workspace/executeCommand` for the editors
|
||||
//! that have no lightbulb.
|
||||
//!
|
||||
//! Protocol only. The edit is `vlog_refactor::inline_module`; this module
|
||||
//! decides which files that engine is handed, turns its answer into a
|
||||
//! `WorkspaceEdit` and its refusal into a request error.
|
||||
//!
|
||||
//! **The action carries a command, not an edit**, for the same reason the
|
||||
//! extraction's does — laziness rather than a prompt. Answering "what would
|
||||
//! inlining `S` here look like" means reading `S`'s file, every file that
|
||||
//! spells it, and analyzing all of them; a `textDocument/codeAction` arrives
|
||||
//! on every cursor move. So the offer is one parse of one buffer
|
||||
//! (`vlog_refactor::inline_site`) plus a `Command` naming [`INLINE_MODULE`],
|
||||
//! and the workspace is not touched until the user picks the action. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
|
||||
// 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, Position, Range, Uri, WorkspaceEdit,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::module_select::Reach;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// Inline the module instantiated at a position: `[uri, position]`.
|
||||
pub const INLINE_MODULE: &str = "lucisv.inlineModule";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![INLINE_MODULE.to_string()]
|
||||
}
|
||||
|
||||
/// The kind LSP reserves for an inline, which is what an editor's "Refactor…"
|
||||
/// menu asks for by name.
|
||||
pub fn kind() -> CodeActionKind {
|
||||
CodeActionKind::REFACTOR_INLINE
|
||||
}
|
||||
|
||||
/// The action for the cursor, carrying the command that does the work.
|
||||
/// Whether the cursor is on an instantiation lucisv could inline, 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, offset: u32) -> Option<vlog_refactor::InlineSite> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::inline_site(&doc.text, offset),
|
||||
false => vlog_refactor::inline_site_in(&doc.tree, &doc.diagnostics, &doc.text, offset),
|
||||
}
|
||||
}
|
||||
|
||||
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 path for the engine's file set; nothing
|
||||
// is offered rather than offered and refused.
|
||||
return Vec::new();
|
||||
}
|
||||
let offset = doc.positions().offset(range.start);
|
||||
let Some(site) = site_at(doc, offset) else { return Vec::new() };
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).unwrap_or(Value::Null),
|
||||
serde_json::to_value(range.start).unwrap_or(Value::Null),
|
||||
];
|
||||
let title = vlog_refactor::inline_title(&site.module);
|
||||
vec![CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: title.clone(),
|
||||
kind: Some(kind()),
|
||||
command: Some(Command {
|
||||
title,
|
||||
command: INLINE_MODULE.to_string(),
|
||||
arguments: Some(arguments),
|
||||
}),
|
||||
..Default::default()
|
||||
})]
|
||||
}
|
||||
|
||||
/// Run `lucisv.inlineModule`, or say why it cannot run.
|
||||
pub fn execute(
|
||||
ws: &Workspace,
|
||||
arguments: &[Value],
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let uri: Uri = argument(arguments, 0, "a document URI")?;
|
||||
let position: Position = argument(arguments, 1, "a position")?;
|
||||
let doc =
|
||||
ws.document(&uri).ok_or_else(|| "lucisv can only inline in an open file.".to_string())?;
|
||||
let path = doc
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?;
|
||||
let offset = doc.positions().offset(position);
|
||||
let Some(site) = site_at(doc, offset) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine reads the instantiated module's declaration and refuses over
|
||||
// any hierarchical path into the instance, so the file set is the two
|
||||
// units' own fan-out — the declaring file, and every file the index says
|
||||
// mentions either name — **plus the fifth rung**: every file whose tokens
|
||||
// write the instance's own name down. A file naming
|
||||
// `u_wrapper.u_top.u_sub.s` reaches this instance through modules it does
|
||||
// not itself instantiate, and the first four rungs have nothing that asks
|
||||
// for it (topology handshake 33). The rung is the exact census
|
||||
// `no_hierarchy` can refuse from, so this set answers that refusal the way
|
||||
// the whole workspace would.
|
||||
let scopes = [site.instance.clone()];
|
||||
let files = ws.module_sources_reaching(&path, &site.units, Reach { scopes: &scopes });
|
||||
let refactoring = vlog_refactor::inline_module(&files, &path, offset)?;
|
||||
Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
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!("{INLINE_MODULE} wants {what} as argument {}.", n + 1))
|
||||
}
|
||||
|
||||
const NOTHING: &str = "there is no module instantiation at this position to inline.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
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_inline_{}_{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) {
|
||||
fs::write(self.path.join(rel), text).expect("write");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
const SUB: &str = "\
|
||||
module sub (
|
||||
input logic a,
|
||||
output logic q
|
||||
);
|
||||
logic s; // the and
|
||||
assign s = a;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
sub u_sub (
|
||||
.a(x),
|
||||
.q(z)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn opened(tree: &Tree) -> (Workspace, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// The cursor on the `sub` of `sub u_sub (`.
|
||||
fn cursor() -> Range {
|
||||
let at = Position { line: 4, character: 4 };
|
||||
Range { start: at, end: at }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_on_an_instantiation_is_offered_the_action_with_its_command() {
|
||||
let tree = Tree::new("offer");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let actions = code_actions(&ws, &uri, cursor());
|
||||
let [CodeActionOrCommand::CodeAction(action)] = actions.as_slice() else {
|
||||
panic!("one action, got {actions:?}")
|
||||
};
|
||||
assert_eq!(action.title, "lucisv: inline `sub` here");
|
||||
assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_INLINE));
|
||||
assert!(action.edit.is_none(), "the offer reads no workspace");
|
||||
let command = action.command.as_ref().expect("a command");
|
||||
assert_eq!(command.command, INLINE_MODULE);
|
||||
assert_eq!(command.arguments.as_ref().expect("arguments").len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_on_anything_else_is_offered_nothing() {
|
||||
let tree = Tree::new("nothing");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let elsewhere = Range {
|
||||
start: Position { line: 1, character: 4 },
|
||||
end: Position { line: 1, character: 4 },
|
||||
};
|
||||
assert!(code_actions(&ws, &uri, elsewhere).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_replaces_the_instantiation_with_the_body() {
|
||||
let tree = Tree::new("run");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(cursor().start).expect("position"),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments).expect("inlines");
|
||||
let changes = edit.changes.as_ref().expect("changes");
|
||||
assert_eq!(changes.len(), 1, "only the file the cursor is in is edited");
|
||||
let written = &changes.get(&uri).expect("this file")[0].new_text;
|
||||
assert!(written.contains("assign s = x;"), "{written}");
|
||||
assert!(written.contains("// the and"), "{written}");
|
||||
assert!(warnings.iter().any(|w| w.contains("still declared where it was")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_says_why_when_there_is_nothing_to_inline() {
|
||||
let tree = Tree::new("refuse");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 1, character: 4 }).expect("position"),
|
||||
];
|
||||
assert_eq!(execute(&ws, &arguments), Err(NOTHING.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_wants_both_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).expect_err("a refusal");
|
||||
assert!(message.contains("argument 2"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_asking_only_for_refactor_inline_is_answered() {
|
||||
let filter = [CodeActionKind::REFACTOR_INLINE];
|
||||
assert!(crate::code_action::wanted(Some(&filter), &kind()));
|
||||
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
|
||||
}
|
||||
}
|
||||
@@ -10,19 +10,34 @@
|
||||
//! table `lucisv.toml` now carries. See
|
||||
//! `docs/features/semantic-lints-on/README.md` and
|
||||
//! `docs/features/server-lint/README.md`.
|
||||
//!
|
||||
//! Since §42 the two halves of that selection are one contract: the editor's
|
||||
//! settings play the role the CLI's flags play, and the project's `[lint]`
|
||||
//! table is what stands when the editor says nothing —
|
||||
//! `docs/features/lint-config-contract/README.md`, and [`project`] for the
|
||||
//! project's half.
|
||||
|
||||
mod project;
|
||||
|
||||
pub use project::{ConfigProblems, ProblemLog, ProjectLint};
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
|
||||
use lucisv_core::config::FileConfig;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_linter::{
|
||||
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
|
||||
RuleOptions, Severity, Violation,
|
||||
default_rules, lint_with, workspace_rules, Exports, ExternalWaivers, LintContext,
|
||||
MentionOracle, ModuleInterface, Rule, RuleOptions, Severity, Violation,
|
||||
};
|
||||
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::diagnostics::SOURCE;
|
||||
use crate::lint_snapshot::{Key, Slot};
|
||||
use crate::lint_trace::{self, Fences, Reuse, Stage};
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
@@ -41,6 +56,33 @@ pub struct LintRun<'a> {
|
||||
/// The width `line-length` holds this buffer to — the width the formatter
|
||||
/// would wrap it to, so the two halves of lucisv cannot disagree.
|
||||
line_length: usize,
|
||||
/// The width a `no-tabs` fix writes where a tab was — the same ladder
|
||||
/// `format::indent_width` walks, read off the `FileConfig` this pass
|
||||
/// already discovered.
|
||||
///
|
||||
/// On the run rather than passed to [`fixable`] since the review round's
|
||||
/// §R1a: the diagnostics pass and the quick-fix pass must build the *same*
|
||||
/// `LintContext` to share one snapshot. Nothing published moves — the
|
||||
/// width reaches only `no-tabs`' fix *text*, and the diagnostics path
|
||||
/// never reads a fix.
|
||||
tab_width: usize,
|
||||
/// The external waiver files in force for this buffer, from its
|
||||
/// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is
|
||||
/// configured, and then costing the pass nothing.
|
||||
external: ExternalWaivers,
|
||||
/// Those files' paths and contents, in the order they were read — the
|
||||
/// snapshot key's row 7. Empty when no waiver file is configured.
|
||||
///
|
||||
/// **Written in the same step as `external`**, by `waiver_files` and by
|
||||
/// `with_waivers` and by nothing else, so a run can never carry a waiver
|
||||
/// its key cannot see. A run whose key missed a waiver would offer a fix
|
||||
/// for a finding the waiver had silenced, which is the stale-fix failure
|
||||
/// this whole key exists to prevent.
|
||||
waiver_texts: Vec<(PathBuf, String)>,
|
||||
/// What the buffer's `lucisv.toml` asked for and did not get. Reported by
|
||||
/// whoever can talk to the client — [`ProblemLog`] keeps it to once per
|
||||
/// (config file, message) — and never fatal here: §42.2.
|
||||
problems: ConfigProblems,
|
||||
}
|
||||
|
||||
impl Default for LintRun<'_> {
|
||||
@@ -50,6 +92,10 @@ impl Default for LintRun<'_> {
|
||||
oracle: None,
|
||||
options: RuleOptions::new(),
|
||||
line_length: DEFAULT_LINE_LENGTH,
|
||||
tab_width: DEFAULT_TAB_WIDTH,
|
||||
external: ExternalWaivers::default(),
|
||||
waiver_texts: Vec::new(),
|
||||
problems: ConfigProblems::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,6 +104,11 @@ impl Default for LintRun<'_> {
|
||||
/// editor says otherwise — `vlog_formatter::Config`'s own default.
|
||||
const DEFAULT_LINE_LENGTH: usize = 100;
|
||||
|
||||
/// The indent width a buffer's fixes are written at when neither its
|
||||
/// `lucisv.toml` nor the editor says otherwise — `vlog_formatter::Config`'s
|
||||
/// own default, which is what `format::indent_width` falls back to.
|
||||
const DEFAULT_TAB_WIDTH: usize = 2;
|
||||
|
||||
impl<'a> LintRun<'a> {
|
||||
/// The pass this workspace's settings and index describe for one buffer.
|
||||
///
|
||||
@@ -68,18 +119,67 @@ impl<'a> LintRun<'a> {
|
||||
/// cross-file evidence behind them, which is the false-positive mode this
|
||||
/// whole round exists to close.
|
||||
pub fn for_document(ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
|
||||
let index = ws.index();
|
||||
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let rules = enabled_rules(ws.client_settings(), workspace);
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
let (options, line_length) = configured(ws.client_settings(), doc);
|
||||
LintRun { rules, oracle, options, line_length }
|
||||
// Two stages, so `--verbose` can say which of them the request spent
|
||||
// its milliseconds in: everything read from disk, then everything
|
||||
// decided from what was read (review round §R1b, `crate::lint_trace`).
|
||||
let found = lint_trace::stage(Stage::Config, || Discovered::read(ws, doc));
|
||||
lint_trace::saw_config(found.file.source.is_some(), found.texts.len());
|
||||
lint_trace::stage(Stage::Build, || found.into_run(ws, doc))
|
||||
}
|
||||
|
||||
/// What this buffer's `lucisv.toml` asked for and did not get, for a
|
||||
/// caller that can tell the user about it.
|
||||
pub fn config_problems(&self) -> &ConfigProblems {
|
||||
&self.problems
|
||||
}
|
||||
|
||||
/// A run carrying this waiver file — for the tests that pin what a waiver
|
||||
/// keeps out of the code actions.
|
||||
///
|
||||
/// Takes the file's **text**, not a parsed `ExternalWaivers`, for the same
|
||||
/// reason `waiver_files` returns both: the waivers a run lints with and
|
||||
/// the texts its snapshot key holds must be written in one step, or a run
|
||||
/// could carry waivers its key cannot see. The bad-line messages are
|
||||
/// dropped here; the caller asserts about them itself where it cares.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_waivers(mut self, path: &Path, text: &str) -> Self {
|
||||
self.external.absorb(ExternalWaivers::parse(path, text).0);
|
||||
self.waiver_texts.push((path.to_path_buf(), text.to_string()));
|
||||
self
|
||||
}
|
||||
|
||||
/// A run whose fixes are written at this indent width — for the tests
|
||||
/// that pin what a `no-tabs` fix writes. The server itself reads the
|
||||
/// width off the buffer's own configuration in [`Discovered::read`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_tab_width(mut self, tab_width: usize) -> Self {
|
||||
self.tab_width = tab_width;
|
||||
self
|
||||
}
|
||||
|
||||
/// What this run would lint with, as the snapshot compares it.
|
||||
///
|
||||
/// Every field is an argument of the `lint_with` call it guards; the
|
||||
/// buffer itself and the workspace index are settled by identity and by
|
||||
/// `Document::refresh_overlay` instead. The feature README's table is the
|
||||
/// whole argument.
|
||||
fn key(&self) -> Key {
|
||||
Key {
|
||||
rules: self.rules.iter().map(|rule| rule.name()).collect(),
|
||||
options: self.options.clone(),
|
||||
line_length: self.line_length,
|
||||
tab_width: self.tab_width,
|
||||
has_oracle: self.oracle.is_some(),
|
||||
waivers: self.waiver_texts.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// This run's context over a buffer's own parse products.
|
||||
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
|
||||
let ctx = context(doc).with_options(&self.options).with_line_length(self.line_length);
|
||||
let ctx = context(doc)
|
||||
.with_options(&self.options)
|
||||
.with_line_length(self.line_length)
|
||||
.with_tab_width(self.tab_width);
|
||||
match &self.oracle {
|
||||
Some(oracle) => ctx.with_oracle(oracle),
|
||||
None => ctx,
|
||||
@@ -87,6 +187,76 @@ impl<'a> LintRun<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything one lint pass reads **from disk**: the `lucisv.toml` governing
|
||||
/// the buffer, what its `[lint]` table said, and the external waiver files in
|
||||
/// force.
|
||||
///
|
||||
/// Split out of [`LintRun::for_document`] so the I/O has a name and a stage of
|
||||
/// its own on the `--verbose` channel — "config read plus lint" was as far as
|
||||
/// take 5 §P1 could attribute the pinmux menu's 23 ms, and that is two
|
||||
/// answers. Nothing about *what* is read changed: the calls below are
|
||||
/// `for_document`'s own, in its own order, so the messages a config problem
|
||||
/// produces arrive in the order §42.2 fixed.
|
||||
struct Discovered {
|
||||
options: RuleOptions,
|
||||
line_length: usize,
|
||||
tab_width: usize,
|
||||
file: FileConfig,
|
||||
project: ProjectLint,
|
||||
external: ExternalWaivers,
|
||||
/// Each waiver file's path and the text it was parsed from — the
|
||||
/// snapshot key's only I/O-derived field.
|
||||
texts: Vec<(PathBuf, String)>,
|
||||
messages: Vec<String>,
|
||||
}
|
||||
|
||||
impl Discovered {
|
||||
/// One discovery for the whole pass: the selection, the options, the
|
||||
/// width, the indent and the waiver paths all read the same `FileConfig`,
|
||||
/// so reading the project's rules costs no extra stat and no extra open.
|
||||
fn read(ws: &Workspace, doc: &Document) -> Discovered {
|
||||
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
|
||||
let (project, bad_names) = ProjectLint::read(&file);
|
||||
messages.extend(bad_names);
|
||||
let (mut external, bad_waivers, mut texts) = waiver_files(&project_waivers(&file));
|
||||
messages.extend(bad_waivers);
|
||||
// The editor's own waiver files are read separately and their
|
||||
// problems dropped: `notification::apply_settings` already said them
|
||||
// once, where the setting arrived.
|
||||
let editor = waiver_files(&editor_waivers(ws.client_settings(), ws.roots()));
|
||||
external.absorb(editor.0);
|
||||
texts.extend(editor.2);
|
||||
// `format::indent_width` stays the one authority on the indent ladder
|
||||
// (`lucisv.toml` > `lucisv.indent` > the formatter's default): reading
|
||||
// it here rather than spelling the ladder a second time costs a second
|
||||
// `Discovery` walk, which the R1b trace measures at hundredths of a
|
||||
// millisecond against a 21 ms pass.
|
||||
let tab_width = crate::format::indent_width(doc.path.as_deref(), ws.client_settings());
|
||||
Discovered { options, line_length, tab_width, file, project, external, texts, messages }
|
||||
}
|
||||
|
||||
/// What this buffer's index and settings make of it: the census oracle and
|
||||
/// the rule ladder, neither of which touches the filesystem.
|
||||
fn into_run<'a>(self, ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
|
||||
let index = ws.index();
|
||||
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
let rules = enabled_rules(ws.client_settings(), &self.project, workspace);
|
||||
let problems = ConfigProblems::new(&self.file, self.messages);
|
||||
LintRun {
|
||||
rules,
|
||||
oracle,
|
||||
options: self.options,
|
||||
line_length: self.line_length,
|
||||
tab_width: self.tab_width,
|
||||
external: self.external,
|
||||
waiver_texts: self.texts,
|
||||
problems,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-rule options and the line width governing one buffer.
|
||||
///
|
||||
/// **Precedence for an option, highest first: the editor, then the buffer's
|
||||
@@ -109,51 +279,158 @@ impl<'a> LintRun<'a> {
|
||||
/// reads it per formatting request: a `lucisv.toml` edited while the server
|
||||
/// runs takes effect at the next publish, and the read is a few stats beside
|
||||
/// a parse and an analysis the same pass already paid for.
|
||||
fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize) {
|
||||
fn configured(
|
||||
client: &ClientSettings,
|
||||
doc: &Document,
|
||||
) -> (RuleOptions, usize, FileConfig, Vec<String>) {
|
||||
let file = doc
|
||||
.path
|
||||
.as_deref()
|
||||
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
|
||||
.unwrap_or_default();
|
||||
let mut options = RuleOptions::new();
|
||||
let mut problems = Vec::new();
|
||||
for entry in &file.lint_options {
|
||||
// A broken entry in the file is dropped here rather than reported:
|
||||
// `format::settings_for` already surfaces a `lucisv.toml` problem to
|
||||
// the user, and `lucisv check` fails the run over it with file and
|
||||
// line, which is where a config error belongs.
|
||||
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
|
||||
// A broken entry in the file is dropped rather than fatal — an editor
|
||||
// cannot fail a run — but it is *said*, in the words `lucisv check`
|
||||
// fails with, once per (config file, entry): §42.2. Silently dropping
|
||||
// it left a user's option doing nothing with nothing to read about it.
|
||||
if let Err(problem) = options.set_raw(&entry.rule, &entry.key, &entry.raw) {
|
||||
let source = file
|
||||
.source
|
||||
.as_ref()
|
||||
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
|
||||
problems.push(format!("{source}:{}: rule `{}` {problem}", entry.line, entry.rule));
|
||||
}
|
||||
}
|
||||
options.overlay(&client.lint_options);
|
||||
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
|
||||
(options, width)
|
||||
(options, width, file, problems)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings say.
|
||||
/// The waiver files governing one buffer: its `lucisv.toml`'s `[lint] waivers`
|
||||
/// first, then `lucisv.lint.waivers` from the editor.
|
||||
///
|
||||
/// The two **add up**, the way they do on the command line — a waiver file
|
||||
/// only ever suppresses findings, so there is nothing here for one list to
|
||||
/// take back from the other. A relative setting path is resolved against the
|
||||
/// first workspace root, exactly as `lucisv.filelist` is; a `lucisv.toml`'s
|
||||
/// paths were already resolved against that file's own directory.
|
||||
pub fn waiver_paths(client: &ClientSettings, roots: &[PathBuf], file: &FileConfig) -> Vec<PathBuf> {
|
||||
let mut paths = project_waivers(file);
|
||||
paths.extend(editor_waivers(client, roots));
|
||||
paths
|
||||
}
|
||||
|
||||
/// The `[lint] waivers` of one config file, already resolved by `Discovery`
|
||||
/// against that file's own directory.
|
||||
///
|
||||
/// Read apart from the editor's since §42.2, because a problem in one of
|
||||
/// *these* is the project's and belongs in the output channel with the
|
||||
/// `lucisv.toml` that named it, while a problem in the editor's was already
|
||||
/// said where the setting arrived.
|
||||
fn project_waivers(file: &FileConfig) -> Vec<PathBuf> {
|
||||
file.lint_waivers.iter().flatten().cloned().collect()
|
||||
}
|
||||
|
||||
/// The waiver files `lucisv.lint.waivers` names, a relative one anchored at
|
||||
/// the first workspace root exactly as `lucisv.filelist` is.
|
||||
fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
|
||||
client
|
||||
.lint_waivers
|
||||
.iter()
|
||||
.map(|setting| {
|
||||
let path = Path::new(setting);
|
||||
match roots.first() {
|
||||
Some(root) if path.is_relative() => root.join(path),
|
||||
_ => path.to_path_buf(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Those files, read: the waivers and one message per file or line that could
|
||||
/// not be used.
|
||||
///
|
||||
/// **Nothing here is fatal.** A push arrives on a socket and a bad path in it
|
||||
/// must never cost a user every diagnostic in their file — this module's
|
||||
/// standing rule, and `settings::rule_options`'. The messages are logged once,
|
||||
/// when the settings arrive (`server::notification::apply_settings`); the lint
|
||||
/// pass, which runs on every keystroke, drops them silently rather than
|
||||
/// logging the same line a hundred times.
|
||||
pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>) {
|
||||
let (waivers, problems, _) = waiver_files(paths);
|
||||
(waivers, problems)
|
||||
}
|
||||
|
||||
/// [`external_waivers`], keeping each file's **text** as well.
|
||||
///
|
||||
/// The text is what the lint snapshot's key holds (review round §R1a): a
|
||||
/// waiver file is not watched — `watch::SOURCE_GLOB` covers sources and the
|
||||
/// filelist alone — so comparing its contents is the only thing that ever
|
||||
/// notices one being rewritten under a running server.
|
||||
///
|
||||
/// One read, not two. `ExternalWaivers::read` is `read_to_string` followed by
|
||||
/// `ExternalWaivers::parse`, and both halves are public, so the bytes are
|
||||
/// taken once and handed to the parser; the sentence an unreadable file
|
||||
/// produces is `read`'s own, byte for byte.
|
||||
fn waiver_files(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>, Vec<(PathBuf, String)>) {
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
let mut problems = Vec::new();
|
||||
let mut texts = Vec::new();
|
||||
for path in paths {
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => {
|
||||
let (file, bad) = ExternalWaivers::parse(path, &text);
|
||||
problems.extend(bad);
|
||||
waivers.absorb(file);
|
||||
texts.push((path.clone(), text));
|
||||
}
|
||||
Err(problem) => problems.push(format!("{}: {problem}", path.display())),
|
||||
}
|
||||
}
|
||||
(waivers, problems, texts)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings and
|
||||
/// the buffer's own `lucisv.toml` say.
|
||||
///
|
||||
/// **The one ladder**, top rung last — every rung may undo the one above it:
|
||||
///
|
||||
/// 1. the base set is what the rules themselves declare: `default_on`, plus
|
||||
/// the `needs_workspace` rules when `has_oracle`;
|
||||
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
|
||||
/// `--select` replaces it on the command line;
|
||||
/// `--select` replaces it on the command line; when the editor names
|
||||
/// nothing, the project's `[lint] select` replaces it instead — the flag
|
||||
/// when there is one, else the file, which is `lucisv check`'s own `pick`;
|
||||
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
|
||||
/// that class;
|
||||
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
|
||||
/// one rule — the per-rule word beats the class word, which is what makes
|
||||
/// "all style off except `no-tabs`" expressible;
|
||||
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
|
||||
/// one a user reaches for when nothing else worked.
|
||||
/// one a user reaches for when nothing else worked; when the editor names
|
||||
/// nothing there either, the project's `[lint] ignore` removes instead.
|
||||
///
|
||||
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
|
||||
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
|
||||
let base = if settings.lint_select.is_empty() {
|
||||
/// Rungs 3 and 4 are the **editor's alone**: a `lucisv.toml` has no such
|
||||
/// keys, and the command line has no such flags. Rungs 2 and 5 are decided
|
||||
/// independently — a project that selects and a user who only ignores keep
|
||||
/// both halves. Every list accepts a severity word wherever a rule name fits,
|
||||
/// the project's as much as the editor's.
|
||||
pub fn enabled_rules(
|
||||
settings: &ClientSettings,
|
||||
project: &ProjectLint,
|
||||
has_oracle: bool,
|
||||
) -> Vec<&'static dyn Rule> {
|
||||
let select = pick(&settings.lint_select, &project.select);
|
||||
let base = if select.is_empty() {
|
||||
if has_oracle {
|
||||
workspace_rules()
|
||||
} else {
|
||||
default_rules()
|
||||
}
|
||||
} else {
|
||||
named(&settings.lint_select)
|
||||
named(select)
|
||||
};
|
||||
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
|
||||
|
||||
@@ -172,12 +449,22 @@ pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'stati
|
||||
on.remove(rule.name());
|
||||
}
|
||||
}
|
||||
for rule in named(&settings.lint_ignore) {
|
||||
for rule in named(pick(&settings.lint_ignore, &project.ignore)) {
|
||||
on.remove(rule.name());
|
||||
}
|
||||
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
|
||||
}
|
||||
|
||||
/// The editor's list when it said anything, else the project's — the twin of
|
||||
/// `lucisv/src/lint.rs`'s `pick`, which is the whole of §42's contract.
|
||||
fn pick<'a>(editor: &'a [String], project: &'a [String]) -> &'a [String] {
|
||||
if editor.is_empty() {
|
||||
project
|
||||
} else {
|
||||
editor
|
||||
}
|
||||
}
|
||||
|
||||
/// Every rule a list of `--select`-style words names, unknown words skipped —
|
||||
/// they were already dropped when the settings were parsed, and a name that
|
||||
/// survived that filter always resolves.
|
||||
@@ -236,6 +523,18 @@ impl MentionOracle for IndexMentions<'_> {
|
||||
}
|
||||
Some(interface)
|
||||
}
|
||||
|
||||
/// Every name a package exports, read off the index's member table — the
|
||||
/// same `WorkspaceIndex` answer `vlog_refactor`'s organize-imports engine
|
||||
/// gets, so the squiggle and the lightbulb cannot disagree about which
|
||||
/// import is dead.
|
||||
///
|
||||
/// `Unknown` for a package the index does not hold and `Ambiguous` for one
|
||||
/// it holds twice; `vlog_semantic::import_usage` refuses to judge in either
|
||||
/// case rather than guess.
|
||||
fn package_exports(&self, package: &str) -> Exports {
|
||||
vlog_semantic::PackageExports::exports(self.index, package)
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's own parse products, lent to the linter — "one parse, two
|
||||
@@ -256,16 +555,48 @@ fn context(doc: &Document) -> LintContext<'_> {
|
||||
///
|
||||
/// This is the diagnostics path, which never looks at a fix, so the width a
|
||||
/// `no-tabs` fix would expand a tab to is left at the linter's own default.
|
||||
pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
lint(&run.context(doc), &run.rules)
|
||||
/// The external waivers apply here exactly as the inline ones do, as a union.
|
||||
/// Which of them *fired* is discarded: only a whole run can tell whether a
|
||||
/// waiver was dead, and a server never has one — it lints the buffers a user
|
||||
/// happens to have open. `lucisv check` is what reports an unused external
|
||||
/// waiver; see `docs/features/waiver-files/README.md`.
|
||||
pub fn violations_in(doc: &Document, run: &LintRun) -> Arc<[Violation]> {
|
||||
found(doc, run)
|
||||
}
|
||||
|
||||
/// The findings a code action may offer a fix for, with their fixes built for
|
||||
/// `tab_width`.
|
||||
/// The one place `vlog_linter::lint_with` is called for an open buffer.
|
||||
///
|
||||
/// The code-action path passes the indent width of the `lucisv.toml` governing
|
||||
/// the buffer, so a quick fix that replaces a tab writes exactly what `lucisv`
|
||||
/// would have written there.
|
||||
/// One place, so there is one snapshot to read (review round §R1a) and one
|
||||
/// site that says on the `--verbose` channel what a pass ran, what it found,
|
||||
/// and whether it ran at all. Both doors — the diagnostics publish and
|
||||
/// quick-fix discovery — arrive here with the *same* context, which is why the
|
||||
/// tab width lives on the [`LintRun`] rather than being handed to [`fixable`].
|
||||
fn found(doc: &Document, run: &LintRun) -> Arc<[Violation]> {
|
||||
let key = run.key();
|
||||
let (violations, hit) = lint_trace::stage(Stage::Lint, || {
|
||||
snapshot(doc).read_or(&key, || lint_with(&run.context(doc), &run.rules, &run.external).0)
|
||||
});
|
||||
let reuse = if hit { Reuse::Hit } else { Reuse::Miss };
|
||||
lint_trace::saw_lint(run.rules.len(), violations.len(), reuse);
|
||||
violations
|
||||
}
|
||||
|
||||
/// The slot this buffer's findings are kept in.
|
||||
///
|
||||
/// A field on the `Document`, so it is dropped with the buffer and cannot
|
||||
/// outlive the text it was computed from: `Workspace::set_document` builds a
|
||||
/// new `Document` for every flushed change. One per open document and nothing
|
||||
/// else — no map, no eviction, no second analysis cache.
|
||||
fn snapshot(doc: &Document) -> &Slot {
|
||||
&doc.lint
|
||||
}
|
||||
|
||||
/// The findings a code action may offer a fix for.
|
||||
///
|
||||
/// The fixes are written at the run's own indent width — the `lucisv.toml`
|
||||
/// governing the buffer, else `lucisv.indent`, else the formatter's default —
|
||||
/// so a quick fix that replaces a tab writes exactly what `lucisv` would have
|
||||
/// written there.
|
||||
///
|
||||
/// A finding whose fix would edit bytes inside a `// verilog_format: off`
|
||||
/// region is dropped here, so the editor keeps the same promise `lucisv check
|
||||
@@ -274,15 +605,39 @@ pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
/// just has no lightbulb. Which bytes count as fenced is
|
||||
/// [`fence::protected_regions`]' answer, the one the CLI asks too; see
|
||||
/// `docs/features/shared-fence-filter/README.md`.
|
||||
pub fn fixable(doc: &Document, tab_width: usize) -> Vec<Violation> {
|
||||
let found = lint(&context(doc).with_tab_width(tab_width), &default_rules());
|
||||
// One tolerant parse per code-action request: `protected_regions` takes
|
||||
// text and parses internally, on purpose — one fence answer for every
|
||||
// front end, none of which can feed it a stale tree (see
|
||||
// `docs/features/shared-fence-filter/README.md`). The per-keystroke
|
||||
// diagnostics path pays nothing, because it never reads a fix.
|
||||
let regions = fence::protected_regions(&doc.text);
|
||||
found.into_iter().filter(|violation| !fix_touches_fence(violation, ®ions)).collect()
|
||||
pub fn fixable(run: &LintRun, doc: &Document) -> Arc<[Violation]> {
|
||||
// The buffer's own run: its enabled rules and its external waiver files,
|
||||
// so a fix is never offered — nor applied by fix-on-save — for a finding
|
||||
// the diagnostics pass would not have shown. Found by §39's QA: with
|
||||
// `default_rules()` and no waivers here, `source.fixAll.lucisv` rewrote a
|
||||
// line a checked-in waiver file had waived.
|
||||
let violations = found(doc, run);
|
||||
// The fence answer is a whole second tolerant parse of the buffer:
|
||||
// `protected_regions` takes text and parses internally, on purpose — one
|
||||
// fence answer for every front end, none of which can feed it a stale tree
|
||||
// (see `docs/features/shared-fence-filter/README.md`). It protects
|
||||
// *fixes*, so a pass whose findings carry no fix has nothing to protect
|
||||
// and nothing to ask: the filter below would be the identity. Skipping it
|
||||
// there is take 5 §P1a. The per-keystroke diagnostics path pays nothing
|
||||
// either, because it never reads a fix.
|
||||
if !violations.iter().any(|violation| violation.fix.is_some()) {
|
||||
lint_trace::saw_fences(Fences::Skipped);
|
||||
return violations;
|
||||
}
|
||||
// Asked once per document revision rather than once per request: the text
|
||||
// a `Document` holds cannot change without a new `Document` (§P1b,
|
||||
// `crate::fences`). The question itself is unchanged — still
|
||||
// `protected_regions` over this buffer's text.
|
||||
let held = crate::fences::held(doc);
|
||||
let regions = lint_trace::stage(Stage::Fence, || crate::fences::of(doc));
|
||||
lint_trace::saw_fences(if held { Fences::Memo } else { Fences::Computed });
|
||||
// The snapshot's own findings when the fence drops nothing, which is every
|
||||
// buffer with no `// lucisv: off` region in it: the filter would be the
|
||||
// identity, and copying the findings to prove it would undo the reuse.
|
||||
if !violations.iter().any(|violation| fix_touches_fence(violation, regions)) {
|
||||
return violations;
|
||||
}
|
||||
violations.iter().filter(|v| !fix_touches_fence(v, regions)).cloned().collect()
|
||||
}
|
||||
|
||||
/// True when a violation carries a fix any edit of which lands in a fenced
|
||||
@@ -359,6 +714,23 @@ mod tests {
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_answers_what_a_package_exports() {
|
||||
// The handshake `unused-import` reads: the server's oracle hands the
|
||||
// rule the very member table `vlog_refactor`'s engine reads, so a
|
||||
// squiggle and a lightbulb cannot disagree about a dead import.
|
||||
let index = WorkspaceIndex::build([(
|
||||
PathBuf::from("/rtl/a_pkg.sv"),
|
||||
"package a_pkg;\n typedef int a_t;\nendpackage\n",
|
||||
)]);
|
||||
let oracle = IndexMentions { index: &index, own: None };
|
||||
match oracle.package_exports("a_pkg") {
|
||||
Exports::Known(names) => assert!(names.iter().any(|n| n == "a_t"), "{names:?}"),
|
||||
other => panic!("an indexed package is known: {other:?}"),
|
||||
}
|
||||
assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_becomes_one_warning_carrying_its_rule_name() {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
|
||||
@@ -449,7 +821,7 @@ mod tests {
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let diags = diagnostics(doc);
|
||||
assert_eq!(diags.len(), 2, "both tabs are reported: {diags:#?}");
|
||||
let offered = fixable(doc, 2);
|
||||
let offered = fixable(&LintRun::default(), doc);
|
||||
assert_eq!(offered.len(), 1, "only the unfenced one may be fixed: {offered:#?}");
|
||||
let free = text.find("\twire b").expect("the unfenced tab") as u32;
|
||||
assert_eq!(offered[0].span.start, free);
|
||||
@@ -469,7 +841,7 @@ mod tests {
|
||||
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
|
||||
"still reported"
|
||||
);
|
||||
assert!(fixable(doc, 2).is_empty(), "and still not fixable");
|
||||
assert!(fixable(&LintRun::default(), doc).is_empty(), "and still not fixable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -548,8 +920,14 @@ mod tests {
|
||||
/// be true of the result).
|
||||
#[test]
|
||||
fn the_enabled_rules_ladder_is_the_documented_one() {
|
||||
// The project's half of the ladder is `lint::project`'s own table
|
||||
// test; this one holds it empty, which is the editor-only ladder
|
||||
// §33.1 wrote.
|
||||
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
|
||||
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
|
||||
enabled_rules(settings, &ProjectLint::default(), oracle)
|
||||
.into_iter()
|
||||
.map(|rule| rule.name())
|
||||
.collect()
|
||||
};
|
||||
let with = |f: &dyn Fn(&mut ClientSettings)| {
|
||||
let mut settings = ClientSettings::default();
|
||||
@@ -711,7 +1089,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_unfenced_file_offers_every_fix() {
|
||||
let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n");
|
||||
assert_eq!(fixable(ws.document(&uri).expect("open"), 2).len(), 1);
|
||||
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -719,9 +1097,133 @@ mod tests {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
for width in [2usize, 4] {
|
||||
let found = fixable(doc, width);
|
||||
let found = fixable(&LintRun::default().with_tab_width(width), doc);
|
||||
let fix = found[0].fix.as_ref().expect("no-tabs offers a fix");
|
||||
assert_eq!(fix.edits[0].1, " ".repeat(width));
|
||||
}
|
||||
}
|
||||
|
||||
/// The two waiver lists add up, and only the setting's relative paths are
|
||||
/// anchored at the first root — a `lucisv.toml`'s were resolved against
|
||||
/// that file's own directory before they got here. TODO §39.
|
||||
#[test]
|
||||
fn the_config_files_waivers_come_first_and_the_settings_are_rooted() {
|
||||
let file = FileConfig {
|
||||
lint_waivers: Some(vec![PathBuf::from("/proj/rtl/project.waiver")]),
|
||||
..Default::default()
|
||||
};
|
||||
let client = ClientSettings {
|
||||
lint_waivers: vec!["team.waiver".to_string(), "/etc/global.waiver".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
let roots = vec![PathBuf::from("/work/top")];
|
||||
assert_eq!(
|
||||
waiver_paths(&client, &roots, &file),
|
||||
vec![
|
||||
PathBuf::from("/proj/rtl/project.waiver"),
|
||||
PathBuf::from("/work/top/team.waiver"),
|
||||
PathBuf::from("/etc/global.waiver"),
|
||||
]
|
||||
);
|
||||
// With no root at all a relative path is left as written rather than
|
||||
// guessed at, exactly as `filelist_path` leaves it.
|
||||
assert_eq!(
|
||||
waiver_paths(&client, &[], &FileConfig::default()),
|
||||
vec![PathBuf::from("team.waiver"), PathBuf::from("/etc/global.waiver")]
|
||||
);
|
||||
assert!(waiver_paths(&ClientSettings::default(), &roots, &FileConfig::default()).is_empty());
|
||||
}
|
||||
|
||||
/// The run's indent width is the formatter's own ladder, read through
|
||||
/// `format::indent_width` rather than spelled a second time — pinned at
|
||||
/// each rung, because the width is a fix's bytes and this lane moved
|
||||
/// where it is read (review round §R1a).
|
||||
#[test]
|
||||
fn the_runs_tab_width_is_the_formatters_own_ladder() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_indent", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(dir.join("m.sv"), "module m;\n\twire a;\nendmodule\n").expect("write");
|
||||
let path = dir.join("m.sv");
|
||||
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
|
||||
|
||||
// Rung by rung: the built-in default, the editor's setting, and a
|
||||
// `lucisv.toml` that outranks it.
|
||||
let rungs: Vec<(Option<&str>, Option<usize>, usize)> = vec![
|
||||
(None, None, 2),
|
||||
(None, Some(8), 8),
|
||||
(Some("indent = 4\n"), Some(8), 4),
|
||||
(Some("indent = 3\n"), None, 3),
|
||||
];
|
||||
for (toml, editor, want) in rungs {
|
||||
match toml {
|
||||
Some(text) => std::fs::write(dir.join("lucisv.toml"), text).expect("write"),
|
||||
None => {
|
||||
let _ = std::fs::remove_file(dir.join("lucisv.toml"));
|
||||
}
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { indent: editor, ..Default::default() });
|
||||
ws.set_document(uri.clone(), "module m;\n\twire a;\nendmodule\n".to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let run = LintRun::for_document(&ws, doc);
|
||||
assert_eq!(run.tab_width, want, "toml={toml:?} editor={editor:?}");
|
||||
assert_eq!(
|
||||
run.tab_width,
|
||||
crate::format::indent_width(Some(&path), ws.client_settings()),
|
||||
"the two readings of the ladder agree"
|
||||
);
|
||||
assert_eq!(
|
||||
fixable(&run, doc)[0].fix.as_ref().expect("a fix").edits[0].1,
|
||||
" ".repeat(want)
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The snapshot is a memo and not a second implementation: what it hands
|
||||
/// back is what a pass computed from scratch would have, violation for
|
||||
/// violation, and both doors get the same object.
|
||||
#[test]
|
||||
fn a_reused_snapshot_is_what_a_fresh_pass_would_have_found() {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a; \nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let run = LintRun::default();
|
||||
let fresh: Vec<Violation> = lint_with(&run.context(doc), &run.rules, &run.external).0;
|
||||
let first = violations_in(doc, &run);
|
||||
let second = fixable(&run, doc);
|
||||
assert!(Arc::ptr_eq(&first, &second), "the diagnostics and the fixes are one pass");
|
||||
assert_eq!(first.len(), fresh.len(), "{fresh:#?}");
|
||||
for (held, made) in first.iter().zip(&fresh) {
|
||||
assert_eq!(
|
||||
(held.rule, held.span, &held.message),
|
||||
(made.rule, made.span, &made.message)
|
||||
);
|
||||
assert_eq!(
|
||||
held.fix.as_ref().map(|fix| &fix.edits),
|
||||
made.fix.as_ref().map(|fix| &fix.edits),
|
||||
"the fix bytes are the fresh pass's too"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A waiver file that is missing, and one with a bad line, are both
|
||||
/// described rather than fatal — and the good directives of the second
|
||||
/// still apply. TODO §39.
|
||||
#[test]
|
||||
fn a_bad_waiver_file_is_described_and_its_good_directives_still_apply() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_waiver_paths_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let good = dir.join("good.waiver");
|
||||
std::fs::write(&good, "waive --rule=no-tabs\nwaive --rule=nope\n").expect("write");
|
||||
|
||||
let (waivers, problems) = external_waivers(&[good.clone(), dir.join("missing.waiver")]);
|
||||
assert!(!waivers.is_empty(), "the good directive survived its neighbour");
|
||||
assert_eq!(problems.len(), 2, "{problems:?}");
|
||||
assert!(problems[0].contains("good.waiver:2: unknown rule `nope`"), "{problems:?}");
|
||||
assert!(problems[1].contains("missing.waiver"), "{problems:?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
//! What a buffer's `lucisv.toml` says about linting, and what could not be
|
||||
//! used from it.
|
||||
//!
|
||||
//! The contract (§42): **the editor's settings play the role the CLI's flags
|
||||
//! play**. `lucisv check` picks the flag when one was given and the project
|
||||
//! file otherwise (`lucisv/src/lint.rs`'s `pick`); the server picks
|
||||
//! `lucisv.lint.select` when it is non-empty and `[lint] select` otherwise,
|
||||
//! key by key, so one buffer linted two ways is linted the same way. See
|
||||
//! `docs/features/lint-config-contract/README.md`.
|
||||
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use lucisv_core::config::FileConfig;
|
||||
|
||||
/// The selection a buffer's `lucisv.toml` carries: `[lint] select` and
|
||||
/// `[lint] ignore`, exactly as `--select` and `--ignore` carry them.
|
||||
///
|
||||
/// [`ProjectLint::default`] — both lists empty — is a buffer with no config
|
||||
/// file, or one whose `[lint]` table says nothing about rules: the editor's
|
||||
/// settings and the base set then decide everything, which is what this
|
||||
/// server did before §42.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct ProjectLint {
|
||||
/// `[lint] select`: run exactly these rules, replacing the base set —
|
||||
/// unless the editor named some, which outranks it.
|
||||
pub select: Vec<String>,
|
||||
/// `[lint] ignore`: rules dropped from whatever `select` left — unless
|
||||
/// the editor named some.
|
||||
pub ignore: Vec<String>,
|
||||
}
|
||||
|
||||
impl ProjectLint {
|
||||
/// One config file's selection, with every name the registry does not
|
||||
/// know dropped and reported.
|
||||
///
|
||||
/// `lucisv check` *fails the run* over an unknown name, which an editor
|
||||
/// cannot do — but it must not silently obey a typo either: a
|
||||
/// `select = ["no-tab"]` taken at face value would resolve to no rules at
|
||||
/// all and blank the file's squiggles, which reads as "lucisv is happy"
|
||||
/// rather than "lucisv could not understand your config". So the name is
|
||||
/// dropped, said once, and the rest of the list still applies; a `select`
|
||||
/// left empty by the dropping falls back to the base set.
|
||||
pub fn read(file: &FileConfig) -> (ProjectLint, Vec<String>) {
|
||||
let mut problems = Vec::new();
|
||||
let select = known(file, "select", file.lint_select.as_deref(), &mut problems);
|
||||
let ignore = known(file, "ignore", file.lint_ignore.as_deref(), &mut problems);
|
||||
(ProjectLint { select, ignore }, problems)
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of one `[lint]` list that name something, the others reported.
|
||||
fn known(
|
||||
file: &FileConfig,
|
||||
key: &str,
|
||||
list: Option<&[String]>,
|
||||
problems: &mut Vec<String>,
|
||||
) -> Vec<String> {
|
||||
let mut kept = Vec::new();
|
||||
for name in list.unwrap_or(&[]) {
|
||||
if vlog_linter::rules_named(name).is_some() {
|
||||
kept.push(name.clone());
|
||||
} else {
|
||||
// No line number: `lucisv_core::config` records one per
|
||||
// `[lint.<rule>]` entry, because those are checked one by one,
|
||||
// and the list keys are one value each.
|
||||
problems.push(format!("{}: [lint] {key}: unknown rule: {name}", source_of(file)));
|
||||
}
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// The config file's path as an error should name it.
|
||||
fn source_of(file: &FileConfig) -> String {
|
||||
file.source.as_ref().map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string())
|
||||
}
|
||||
|
||||
/// What one buffer's `lucisv.toml` asked for and did not get: a
|
||||
/// `[lint.<rule>]` entry the registry refused, a name in `[lint] select` that
|
||||
/// is not a rule, a `[lint] waivers` file that is not there or holds a
|
||||
/// directive that does not parse.
|
||||
///
|
||||
/// Every message is written the way `lucisv check` writes it —
|
||||
/// `<file>:<line>: <message>` — so the same mistake reads the same in CI and
|
||||
/// in an editor's output channel. **Nothing here is fatal**: the entry is
|
||||
/// dropped and the buffer is still linted with everything that was
|
||||
/// understood, because a server cannot fail a run the way a command can.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct ConfigProblems {
|
||||
/// The config file they came from. `None` — no config file was found —
|
||||
/// means there is nothing to complain about and `messages` is empty.
|
||||
source: Option<PathBuf>,
|
||||
/// A stamp of that file's lint content, so an edited config gets a fresh
|
||||
/// hearing: see [`ProblemLog`].
|
||||
stamp: u64,
|
||||
/// The messages, in file order.
|
||||
messages: Vec<String>,
|
||||
}
|
||||
|
||||
impl ConfigProblems {
|
||||
/// The problems found in this config file.
|
||||
pub fn new(file: &FileConfig, messages: Vec<String>) -> ConfigProblems {
|
||||
ConfigProblems { source: file.source.clone(), stamp: stamp_of(file), messages }
|
||||
}
|
||||
|
||||
/// Whether anything at all could not be used.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.messages.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stamp over everything in a config file that [`ConfigProblems`] can be
|
||||
/// about, so that editing the file re-arms the report and editing a source
|
||||
/// beside it does not.
|
||||
///
|
||||
/// A hash rather than a modification time: the file is re-read on every lint
|
||||
/// pass anyway (`configured`), and a hash of what was parsed cannot be fooled
|
||||
/// by a filesystem whose timestamps are coarse.
|
||||
fn stamp_of(file: &FileConfig) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
file.lint_select.hash(&mut hasher);
|
||||
file.lint_ignore.hash(&mut hasher);
|
||||
file.lint_waivers.hash(&mut hasher);
|
||||
for entry in &file.lint_options {
|
||||
entry.rule.hash(&mut hasher);
|
||||
entry.key.hash(&mut hasher);
|
||||
entry.raw.hash(&mut hasher);
|
||||
entry.line.hash(&mut hasher);
|
||||
}
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Which config problems have already been said, so each is said **once**.
|
||||
///
|
||||
/// Once per (config file, message), not once per lint pass: the pass runs on
|
||||
/// every keystroke and every index rebuild, and a hundred copies of one line
|
||||
/// in the output channel is not a report, it is noise. The editor-settings
|
||||
/// path has said its own problems once since §34 — this is the same promise
|
||||
/// for the file a project checks in.
|
||||
///
|
||||
/// A config file whose lint content changed clears its own memo, so a user
|
||||
/// who edits `lucisv.toml` and gets it wrong again is told again. The memo is
|
||||
/// keyed by path, so it holds one small entry per config file a session ever
|
||||
/// linted through.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ProblemLog {
|
||||
said: HashMap<PathBuf, Said>,
|
||||
}
|
||||
|
||||
/// One config file's memo: the content it was taken under, and what was said.
|
||||
#[derive(Debug, Default)]
|
||||
struct Said {
|
||||
stamp: u64,
|
||||
messages: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl ProblemLog {
|
||||
/// The messages that have not been said yet for this config file, marked
|
||||
/// as said. An empty answer means the user has already been told.
|
||||
pub fn unsaid(&mut self, problems: &ConfigProblems) -> Vec<String> {
|
||||
let Some(source) = problems.source.clone() else { return Vec::new() };
|
||||
if problems.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let said = self.said.entry(source).or_default();
|
||||
if said.stamp != problems.stamp {
|
||||
said.stamp = problems.stamp;
|
||||
said.messages.clear();
|
||||
}
|
||||
problems
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|message| said.messages.insert((*message).clone()))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::{Document, Workspace};
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_linter::Severity;
|
||||
|
||||
fn config(text: &str) -> FileConfig {
|
||||
let mut file = lucisv_core::config::parse(text).expect("the config parses");
|
||||
file.source = Some(PathBuf::from("/rtl/lucisv.toml"));
|
||||
file
|
||||
}
|
||||
|
||||
fn names(settings: &ClientSettings, project: &ProjectLint, oracle: bool) -> Vec<&'static str> {
|
||||
super::super::enabled_rules(settings, project, oracle)
|
||||
.into_iter()
|
||||
.map(|rule| rule.name())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn editor(select: &[&str], ignore: &[&str]) -> ClientSettings {
|
||||
ClientSettings {
|
||||
lint_select: select.iter().map(|s| (*s).to_string()).collect(),
|
||||
lint_ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
|
||||
..ClientSettings::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn project(select: &[&str], ignore: &[&str]) -> ProjectLint {
|
||||
ProjectLint {
|
||||
select: select.iter().map(|s| (*s).to_string()).collect(),
|
||||
ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// §42.1's table: every combination of {toml select, editor select} ×
|
||||
/// {toml ignore, editor ignore}, against the ladder. The editor's list
|
||||
/// wins when it says anything, the project's is used when it does not,
|
||||
/// and the two keys are decided **independently** — the CLI's `pick`,
|
||||
/// applied twice.
|
||||
#[test]
|
||||
fn the_editor_outranks_the_project_key_by_key() {
|
||||
// Four rules stand in for the whole registry: two the project may
|
||||
// name and two the editor may, so a row's answer says which list was
|
||||
// consulted rather than which happened to be shorter.
|
||||
// (toml select, editor select, toml ignore, editor ignore, expected).
|
||||
type Row = (
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
);
|
||||
let rows: [Row; 8] = [
|
||||
// (toml select, editor select, toml ignore, editor ignore) => rules
|
||||
(&[], &[], &[], &[], &[]),
|
||||
(&["no-tabs"], &[], &[], &[], &["no-tabs"]),
|
||||
(&[], &["no-tabs"], &[], &[], &["no-tabs"]),
|
||||
(&["module-name-style"], &["no-tabs"], &[], &[], &["no-tabs"]),
|
||||
(&["no-tabs", "module-name-style"], &[], &["no-tabs"], &[], &["module-name-style"]),
|
||||
(&["no-tabs", "module-name-style"], &[], &[], &["no-tabs"], &["module-name-style"]),
|
||||
(
|
||||
&["no-tabs", "module-name-style"],
|
||||
&[],
|
||||
&["module-name-style"],
|
||||
&["no-tabs"],
|
||||
&["module-name-style"],
|
||||
),
|
||||
(
|
||||
&["module-name-style"],
|
||||
&["no-tabs", "module-name-style"],
|
||||
&["no-tabs"],
|
||||
&["module-name-style"],
|
||||
&["no-tabs"],
|
||||
),
|
||||
];
|
||||
for (toml_select, ed_select, toml_ignore, ed_ignore, want) in rows {
|
||||
let settings = editor(ed_select, ed_ignore);
|
||||
let from_file = project(toml_select, toml_ignore);
|
||||
let got = names(&settings, &from_file, false);
|
||||
if want.is_empty() {
|
||||
// The empty row is the base set, which is too long to spell.
|
||||
assert_eq!(
|
||||
got,
|
||||
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>(),
|
||||
"neither list said anything, so the base set stands"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
got, want,
|
||||
"{toml_select:?} {ed_select:?} {toml_ignore:?} {ed_ignore:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A severity word stands for its whole class in the toml's lists exactly
|
||||
/// as it does in the editor's, and as `--select style` does.
|
||||
#[test]
|
||||
fn a_severity_word_works_in_the_projects_lists_too() {
|
||||
let styled = names(&ClientSettings::default(), &project(&["style"], &[]), true);
|
||||
assert!(!styled.is_empty());
|
||||
assert!(styled
|
||||
.iter()
|
||||
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
|
||||
== Severity::Style));
|
||||
|
||||
let quiet = names(&ClientSettings::default(), &project(&[], &["style"]), true);
|
||||
assert!(!quiet.is_empty());
|
||||
assert!(quiet
|
||||
.iter()
|
||||
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
|
||||
!= Severity::Style));
|
||||
}
|
||||
|
||||
/// A rung 3 or 4 switch is the editor's alone, and still applies over a
|
||||
/// selection the project made.
|
||||
#[test]
|
||||
fn the_editor_only_rungs_still_apply_over_a_project_selection() {
|
||||
let mut settings = ClientSettings::default();
|
||||
settings.lint_severity.insert(Severity::Style, false);
|
||||
let from_file = project(&["no-tabs", "wire-reg-mixup"], &[]);
|
||||
assert_eq!(
|
||||
names(&settings, &from_file, false),
|
||||
vec!["wire-reg-mixup"],
|
||||
"the class switch removes the project's style rule"
|
||||
);
|
||||
|
||||
settings.lint_rules.insert("no-tabs".to_string(), true);
|
||||
assert_eq!(
|
||||
names(&settings, &from_file, false),
|
||||
vec!["no-tabs", "wire-reg-mixup"],
|
||||
"and the per-rule word puts it back"
|
||||
);
|
||||
}
|
||||
|
||||
/// A name the registry does not know is dropped and reported — the run
|
||||
/// `lucisv check` would have failed keeps going here with what was
|
||||
/// understood.
|
||||
#[test]
|
||||
fn an_unknown_name_in_the_projects_list_is_dropped_and_said() {
|
||||
let (from_file, problems) =
|
||||
ProjectLint::read(&config("[lint]\nselect = [\"no-tab\", \"no-tabs\"]\n"));
|
||||
assert_eq!(from_file.select, vec!["no-tabs"]);
|
||||
assert_eq!(problems, vec!["/rtl/lucisv.toml: [lint] select: unknown rule: no-tab"]);
|
||||
assert_eq!(names(&ClientSettings::default(), &from_file, false), vec!["no-tabs"]);
|
||||
|
||||
// Every name unknown leaves the list empty, which is the base set —
|
||||
// the safe direction: some rules rather than none.
|
||||
let (none, problems) = ProjectLint::read(&config("[lint]\nselect = [\"nope\"]\n"));
|
||||
assert!(none.select.is_empty());
|
||||
assert_eq!(problems.len(), 1);
|
||||
assert_eq!(
|
||||
names(&ClientSettings::default(), &none, false),
|
||||
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
/// §42.2: a `[lint.<rule>]` entry the registry refuses is reported once,
|
||||
/// however many lint passes run, and the buffer keeps being linted.
|
||||
#[test]
|
||||
fn a_rejected_option_is_said_once_and_the_lint_still_runs() {
|
||||
let dir = std::env::temp_dir()
|
||||
.join(format!("lucisv_lint_project_{}_rejected", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = \"wide\"\n")
|
||||
.expect("write config");
|
||||
let path = dir.join("m.sv");
|
||||
let text = "module m;\n\twire a;\nendmodule\n";
|
||||
std::fs::write(&path, text).expect("write source");
|
||||
|
||||
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let mut log = ProblemLog::default();
|
||||
|
||||
let mut said = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let doc: &Document = ws.document(&uri).expect("open");
|
||||
let run = super::super::LintRun::for_document(&ws, doc);
|
||||
// The lint still runs: the tab is still a finding.
|
||||
assert!(
|
||||
super::super::violations_in(doc, &run).iter().any(|v| v.rule == "no-tabs"),
|
||||
"the buffer is still linted with the entry dropped"
|
||||
);
|
||||
said.extend(log.unsaid(run.config_problems()));
|
||||
}
|
||||
assert_eq!(said.len(), 1, "said once across three passes: {said:#?}");
|
||||
let expected = format!("{}:2: rule `line-length` ", dir.join("lucisv.toml").display());
|
||||
assert!(said[0].starts_with(&expected), "the wording `lucisv check` prints: {}", said[0]);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An edited config gets a fresh hearing: the memo is keyed by the file's
|
||||
/// lint content, so the same mistake made again after a change is said
|
||||
/// again.
|
||||
#[test]
|
||||
fn an_edited_config_re_arms_the_report() {
|
||||
let first = config("[lint.line-length]\nlength = \"wide\"\n");
|
||||
let problems = ConfigProblems::new(&first, vec!["/rtl/lucisv.toml:2: bad".to_string()]);
|
||||
let mut log = ProblemLog::default();
|
||||
assert_eq!(log.unsaid(&problems).len(), 1);
|
||||
assert!(log.unsaid(&problems).is_empty(), "and not twice");
|
||||
|
||||
// Same message, different file content: the user has been editing.
|
||||
let edited = config("# a comment\n[lint.line-length]\nlength = \"wide\"\n");
|
||||
let again = ConfigProblems::new(&edited, vec!["/rtl/lucisv.toml:3: bad".to_string()]);
|
||||
assert_eq!(log.unsaid(&again).len(), 1, "a changed config is heard again");
|
||||
|
||||
// A buffer with no config file has nothing to report.
|
||||
let nowhere = ConfigProblems::new(&FileConfig::default(), vec!["never".to_string()]);
|
||||
assert!(log.unsaid(&nowhere).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! One lint pass's findings, kept for as long as they are still the answer.
|
||||
//!
|
||||
//! Take 5 **review** round §R1a (`docs/features/perf5r-lint-snapshot/README.md`,
|
||||
//! `docs/performance_take5_review.md` §1). A `textDocument/codeAction` on
|
||||
//! `pinmux_reg_top.sv` spends **21 of its 22 ms in `lint_with`**, and the first
|
||||
//! request after an edit runs that pass **twice** on one revision — once to
|
||||
//! publish diagnostics, once to discover quick fixes. This module is what lets
|
||||
//! the second one read the first one's answer.
|
||||
//!
|
||||
//! **The whole design is in [`Key`].** A snapshot is legitimate only while
|
||||
//! every input of `lint_with(ctx, rules, external)` is what it was, and the
|
||||
//! key is those inputs *by value* — no hash, no mtime, no generation number,
|
||||
//! so "could this offer a stale fix?" is a question about `PartialEq` and not
|
||||
//! about collision probability. What the key deliberately does **not** carry
|
||||
//! is the two things identity already settles:
|
||||
//!
|
||||
//! * the **buffer** — a [`Slot`] is a field on the `Document`, and
|
||||
//! `Workspace::set_document` builds a new `Document` for every flushed
|
||||
//! change, so a slot cannot outlive the text it was computed from (the
|
||||
//! argument `crate::fences` already rests on);
|
||||
//! * the **workspace index** the census oracle reads — every index mutation in
|
||||
//! `state/mod.rs` ends by calling `Document::refresh_overlay` on every open
|
||||
//! buffer, and that is where the slot is cleared.
|
||||
//!
|
||||
//! The invalidation table in the feature README has one row per input, the
|
||||
//! mechanism for each, and the test that flips it.
|
||||
//!
|
||||
//! **Bounded by construction:** one slot per open document, holding that
|
||||
//! document's own violations, dropped with the `Document` on `didClose`. There
|
||||
//! is no map, no eviction policy and no second unbounded analysis cache.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use vlog_linter::{RuleOptions, Violation};
|
||||
|
||||
/// Everything a lint result depends on that is **not** settled by the
|
||||
/// `Document`'s own identity.
|
||||
///
|
||||
/// Compared by value, field by field. Every field is an argument of the
|
||||
/// `lint_with` call it guards, which is what makes the list complete: see the
|
||||
/// feature README's table, which derives it from that call's signature.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Key {
|
||||
/// The enabled rules' names, in registry order — the whole of what the
|
||||
/// `lucisv.lint.*` ladder and the project's `[lint]` table decided.
|
||||
pub rules: Vec<&'static str>,
|
||||
/// The merged per-rule options: the buffer's `lucisv.toml` overlaid with
|
||||
/// the editor's `lucisv.lint.options`.
|
||||
pub options: RuleOptions,
|
||||
/// The width `line-length` holds this buffer to.
|
||||
pub line_length: usize,
|
||||
/// The width a `no-tabs` fix writes. It changes a fix's *text* and
|
||||
/// nothing else, but a fix's text is what a user applies.
|
||||
pub tab_width: usize,
|
||||
/// Whether the pass had a census to ask. The oracle's *answers* are
|
||||
/// covered by `refresh_overlay`; whether there is one at all is decided
|
||||
/// from the index's file count, which can move without any one file's
|
||||
/// facts moving.
|
||||
pub has_oracle: bool,
|
||||
/// Every external waiver file in force, path and **contents**, in the
|
||||
/// order they were read.
|
||||
///
|
||||
/// The contents, not a digest and not an mtime: a waiver file is not
|
||||
/// watched (`watch::SOURCE_GLOB` covers sources and the filelist alone),
|
||||
/// so the only thing that ever notices a rewritten one is this
|
||||
/// comparison. The text is already in hand — the pass read it to parse
|
||||
/// it — so keeping it costs a copy per open document and no I/O.
|
||||
pub waivers: Vec<(PathBuf, String)>,
|
||||
}
|
||||
|
||||
/// One document's lint snapshot: the key it was computed under, and what it
|
||||
/// found.
|
||||
struct Held {
|
||||
key: Key,
|
||||
violations: Arc<[Violation]>,
|
||||
}
|
||||
|
||||
/// The snapshot slot a `Document` carries.
|
||||
///
|
||||
/// A `Mutex` rather than a `RefCell` so a `Document` stays `Sync` exactly as
|
||||
/// its `OnceLock` fence memo leaves it; the lock is uncontended (one message
|
||||
/// loop) and is never held across the pass itself.
|
||||
#[derive(Default)]
|
||||
pub struct Slot(Mutex<Option<Held>>);
|
||||
|
||||
impl Slot {
|
||||
/// An empty slot — what every `Document` is built with.
|
||||
pub fn new() -> Slot {
|
||||
Slot(Mutex::new(None))
|
||||
}
|
||||
|
||||
/// Forget whatever is held.
|
||||
///
|
||||
/// Called from `Document::refresh_overlay`, which is the one place a
|
||||
/// `Document` is told the workspace index moved. Dropping here rather
|
||||
/// than keying on an index generation is deliberate: the four call sites
|
||||
/// that mutate the index all end in that loop, so there is no way for the
|
||||
/// index to move without this running, and no counter to keep in step.
|
||||
pub fn clear(&mut self) {
|
||||
if let Ok(mut held) = self.0.lock() {
|
||||
*held = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The violations for `key`, computing them when what is held is for
|
||||
/// anything else.
|
||||
///
|
||||
/// Returns `(violations, answered_from_the_snapshot)`. A poisoned lock —
|
||||
/// which this server has no way to produce, having one message loop and no
|
||||
/// panicking library code — degrades to computing every time rather than
|
||||
/// to an error a user would see.
|
||||
pub fn read_or(
|
||||
&self,
|
||||
key: &Key,
|
||||
compute: impl FnOnce() -> Vec<Violation>,
|
||||
) -> (Arc<[Violation]>, bool) {
|
||||
if let Ok(held) = self.0.lock() {
|
||||
if let Some(held) = held.as_ref().filter(|held| held.key == *key) {
|
||||
return (Arc::clone(&held.violations), true);
|
||||
}
|
||||
}
|
||||
// Computed with the lock released: `lint_with` is the expensive part
|
||||
// and it reads nothing this slot owns.
|
||||
let violations: Arc<[Violation]> = compute().into();
|
||||
if let Ok(mut held) = self.0.lock() {
|
||||
*held = Some(Held { key: key.clone(), violations: Arc::clone(&violations) });
|
||||
}
|
||||
(violations, false)
|
||||
}
|
||||
|
||||
/// Whether anything is held at all — for the tests that assert a slot was
|
||||
/// filled, or was not.
|
||||
#[cfg(test)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.lock().map_or(true, |held| held.is_none())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Slot {
|
||||
/// Says whether a snapshot is held and nothing about it: a `Document`'s
|
||||
/// `Debug` must not print a thousand violations.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let held = self.0.lock().map(|held| held.is_some()).unwrap_or(false);
|
||||
f.debug_tuple("Slot").field(&held).finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
fn key() -> Key {
|
||||
Key {
|
||||
rules: vec!["no-tabs"],
|
||||
options: RuleOptions::new(),
|
||||
line_length: 100,
|
||||
tab_width: 2,
|
||||
has_oracle: false,
|
||||
waivers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn violation(message: &str) -> Violation {
|
||||
Violation::new("no-tabs", message, TextRange::new(0, 1))
|
||||
}
|
||||
|
||||
/// The second ask for the same key does not compute, and answers with the
|
||||
/// same findings.
|
||||
#[test]
|
||||
fn a_matching_key_answers_without_computing() {
|
||||
let slot = Slot::new();
|
||||
let (first, hit) = slot.read_or(&key(), || vec![violation("one")]);
|
||||
assert!(!hit, "an empty slot cannot hit");
|
||||
let (again, hit) = slot.read_or(&key(), || panic!("must not recompute"));
|
||||
assert!(hit);
|
||||
assert_eq!(again.len(), 1);
|
||||
assert_eq!(again[0].message, first[0].message);
|
||||
}
|
||||
|
||||
/// Every field of the key is load-bearing: change any one and the pass
|
||||
/// runs again. This is the table's row set in miniature — the per-input
|
||||
/// server tests assert the same thing through the real doors.
|
||||
#[test]
|
||||
fn every_field_of_the_key_forces_a_recompute() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw("line-length", "length", "80").expect("a real option");
|
||||
let changes: Vec<(&str, Key)> = vec![
|
||||
("rules", Key { rules: vec!["no-tabs", "posix-eof"], ..key() }),
|
||||
("options", Key { options, ..key() }),
|
||||
("line_length", Key { line_length: 120, ..key() }),
|
||||
("tab_width", Key { tab_width: 4, ..key() }),
|
||||
("has_oracle", Key { has_oracle: true, ..key() }),
|
||||
(
|
||||
"waivers",
|
||||
Key {
|
||||
waivers: vec![(PathBuf::from("/w.waiver"), "waive --rule=no-tabs\n".into())],
|
||||
..key()
|
||||
},
|
||||
),
|
||||
];
|
||||
for (what, moved) in changes {
|
||||
let slot = Slot::new();
|
||||
slot.read_or(&key(), || vec![violation("old")]);
|
||||
let (found, hit) = slot.read_or(&moved, || vec![violation("new")]);
|
||||
assert!(!hit, "{what} did not invalidate the snapshot");
|
||||
assert_eq!(found[0].message, "new", "{what} answered stale");
|
||||
// ... and the new answer is what is held afterwards, so the stale
|
||||
// one cannot come back on the next request.
|
||||
let (again, hit) = slot.read_or(&moved, || panic!("must not recompute"));
|
||||
assert!(hit);
|
||||
assert_eq!(again[0].message, "new", "{what} left the old answer held");
|
||||
}
|
||||
}
|
||||
|
||||
/// A waiver file rewritten to the same length with different bytes is a
|
||||
/// different key: the contents are compared, not a size or a time.
|
||||
#[test]
|
||||
fn a_waiver_rewritten_in_place_is_a_different_key() {
|
||||
let one = |text: &str| Key {
|
||||
waivers: vec![(PathBuf::from("/w.waiver"), text.to_string())],
|
||||
..key()
|
||||
};
|
||||
let slot = Slot::new();
|
||||
slot.read_or(&one("waive --rule=no-tabs\n"), || vec![violation("old")]);
|
||||
let (found, hit) =
|
||||
slot.read_or(&one("waive --rule=posix-eof\n"), || vec![violation("new")]);
|
||||
assert!(!hit, "same length, different bytes");
|
||||
assert_eq!(found[0].message, "new");
|
||||
}
|
||||
|
||||
/// Clearing is what `refresh_overlay` does when the index moves.
|
||||
#[test]
|
||||
fn clearing_forces_the_next_pass_to_compute() {
|
||||
let mut slot = Slot::new();
|
||||
slot.read_or(&key(), || vec![violation("old")]);
|
||||
assert!(!slot.is_empty());
|
||||
slot.clear();
|
||||
assert!(slot.is_empty());
|
||||
let (found, hit) = slot.read_or(&key(), || vec![violation("new")]);
|
||||
assert!(!hit, "a cleared slot cannot hit");
|
||||
assert_eq!(found[0].message, "new");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
//! Where a lint-answering request's milliseconds went.
|
||||
//!
|
||||
//! Take 5 **review** round §R1b (`docs/performance_take5_review.md` §1,
|
||||
//! `docs/features/perf5r-lint-snapshot/README.md`). The review's own note is
|
||||
//! that the pinmux code-action menu costs **25 ms of which 23 is quickfix**,
|
||||
//! and that the first request after a one-character edit costs **136 ms** —
|
||||
//! but "config read plus lint" was as far as the previous lane could
|
||||
//! attribute it, and *config read plus lint* is two answers, not one. This
|
||||
//! module splits the request into the five stages a reader can act on:
|
||||
//!
|
||||
//! | stage | what it is |
|
||||
//! |---|---|
|
||||
//! | `config` | `Discovery::for_file`, `ProjectLint::read` and every waiver file read |
|
||||
//! | `build` | the rest of [`crate::lint::LintRun::for_document`] — the oracle, the rule ladder |
|
||||
//! | `lint` | `vlog_linter::lint_with`, and how many times it ran |
|
||||
//! | `fence` | `crate::fences::of` — computed, taken from the memo, or skipped |
|
||||
//! | `serialize` | turning violations into `CodeAction`s |
|
||||
//!
|
||||
//! and reports the **flush** — the debounced `Document` rebuild `answer_request`
|
||||
//! performs before any handler runs — as its own group, with the diagnostics
|
||||
//! pass that publishes inside it split the same five ways. That separation is
|
||||
//! the review's item 4: if the dirty-buffer stage dominates the 136 ms, a lint
|
||||
//! cache alone cannot fix it, and only a number can say.
|
||||
//!
|
||||
//! **Nothing here decides anything.** A trace is armed by
|
||||
//! [`crate::server`]'s request wrapper when `--verbose` asked for one, written
|
||||
//! as the request runs, logged once and dropped.
|
||||
//!
|
||||
//! Off is the shipped state and costs **one thread-local `Cell<bool>` read**
|
||||
//! per traced site — no clock read, no allocation, no line — which is the same
|
||||
//! bargain `Server::timer` makes for the rest of `docs/features/verbose-timing/`.
|
||||
//!
|
||||
//! Per thread, deliberately, for `vlog_parser::stats`' reason: a request is
|
||||
//! answered on one thread, so a thread-local accumulator is that request's
|
||||
//! number exactly, and `cargo test`'s parallel binaries cannot add to each
|
||||
//! other's.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// One stage of a lint-answering request.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Stage {
|
||||
/// Reading the project's configuration: the `lucisv.toml` discovery walk,
|
||||
/// its `[lint]` table, and the external waiver files.
|
||||
Config,
|
||||
/// The rest of the `LintRun`: the census oracle and the rule ladder.
|
||||
Build,
|
||||
/// `vlog_linter::lint_with` itself.
|
||||
Lint,
|
||||
/// The formatter's fenced-region answer.
|
||||
Fence,
|
||||
/// Turning violations into what goes on the wire.
|
||||
Serialize,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
/// The name this stage is counted under in the `timing:` line.
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Stage::Config => "config",
|
||||
Stage::Build => "build",
|
||||
Stage::Lint => "lint",
|
||||
Stage::Fence => "fence",
|
||||
Stage::Serialize => "serialize",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every stage, in the order a request passes through them — so a line
|
||||
/// always carries the same fields whether or not a stage ran.
|
||||
const ALL: [Stage; 5] =
|
||||
[Stage::Config, Stage::Build, Stage::Lint, Stage::Fence, Stage::Serialize];
|
||||
}
|
||||
|
||||
/// One stage of the debounced `Document` rebuild the flush performs, plus the
|
||||
/// diagnostics publish that follows it.
|
||||
///
|
||||
/// TODO §63.2: `flush{wall=…}` said the rebuild cost 100 ms and nothing about
|
||||
/// *which* of the six derivations that was, so the first thing this round does
|
||||
/// is name them. The six are [`crate::state::Document::new`]'s own steps in
|
||||
/// the order it runs them; `Publish` is what `flush_dirty` does with the
|
||||
/// rebuilt buffer, and the flush group's `config`/`build`/`lint`/`fence`
|
||||
/// stages are inside it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Rebuild {
|
||||
/// `tokenize` over the buffer's text.
|
||||
Lex,
|
||||
/// `parse_tolerant` over those tokens (or `parse_source_tolerant` when the
|
||||
/// buffer does not lex).
|
||||
Parse,
|
||||
/// `collect_defines` over the tokens.
|
||||
Defines,
|
||||
/// `analyze` over the tree.
|
||||
Analyze,
|
||||
/// `resolve_external` against the workspace index.
|
||||
External,
|
||||
/// `LineIndex::new` over the text.
|
||||
Lines,
|
||||
/// The diagnostics publish for the rebuilt buffer.
|
||||
Publish,
|
||||
}
|
||||
|
||||
impl Rebuild {
|
||||
/// The name this stage is counted under in the `timing:` line.
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Rebuild::Lex => "lex",
|
||||
Rebuild::Parse => "parse",
|
||||
Rebuild::Defines => "defines",
|
||||
Rebuild::Analyze => "analyze",
|
||||
Rebuild::External => "external",
|
||||
Rebuild::Lines => "lines",
|
||||
Rebuild::Publish => "publish",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every stage, in the order the flush passes through them.
|
||||
const ALL: [Rebuild; 7] = [
|
||||
Rebuild::Lex,
|
||||
Rebuild::Parse,
|
||||
Rebuild::Defines,
|
||||
Rebuild::Analyze,
|
||||
Rebuild::External,
|
||||
Rebuild::Lines,
|
||||
Rebuild::Publish,
|
||||
];
|
||||
}
|
||||
|
||||
/// The flush's inner stages: what rebuilding the dirty buffers cost, split.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Rebuilt {
|
||||
ms: [f64; Rebuild::ALL.len()],
|
||||
/// How many `Document`s were built from scratch.
|
||||
documents: usize,
|
||||
}
|
||||
|
||||
impl Rebuilt {
|
||||
/// The `const` form `thread_local!`'s initializer needs.
|
||||
const EMPTY: Rebuilt = Rebuilt { ms: [0.0; Rebuild::ALL.len()], documents: 0 };
|
||||
|
||||
fn add(&mut self, stage: Rebuild, took: Duration) {
|
||||
self.ms[stage as usize] += took.as_secs_f64() * 1_000.0;
|
||||
}
|
||||
|
||||
/// This group's fields, in the `key=value` shape `tools/perf` parses.
|
||||
fn fields(&self) -> String {
|
||||
let stages: Vec<String> = Rebuild::ALL
|
||||
.iter()
|
||||
.map(|stage| format!("{}={:.2}ms", stage.label(), self.ms[*stage as usize]))
|
||||
.collect();
|
||||
format!("{} documents={}", stages.join(" "), self.documents)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the fence filter did, when a pass reached it at all.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Fences {
|
||||
/// No finding carried a fix, so the filter would have been the identity
|
||||
/// and was not asked (take 5 §P1a).
|
||||
#[default]
|
||||
Skipped,
|
||||
/// `protected_regions` parsed the buffer for this `Document`.
|
||||
Computed,
|
||||
/// The `Document`'s memo answered (take 5 §P1b).
|
||||
Memo,
|
||||
}
|
||||
|
||||
impl Fences {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Fences::Skipped => "skipped",
|
||||
Fences::Computed => "computed",
|
||||
Fences::Memo => "memo",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a lint pass was answered from the snapshot (review round §R1a).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Reuse {
|
||||
/// No pass ran.
|
||||
#[default]
|
||||
None,
|
||||
/// The `Document` held no snapshot, or held one for other inputs.
|
||||
Miss,
|
||||
/// The snapshot matched and `lint_with` did not run.
|
||||
Hit,
|
||||
}
|
||||
|
||||
impl Reuse {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Reuse::None => "none",
|
||||
Reuse::Miss => "miss",
|
||||
Reuse::Hit => "hit",
|
||||
}
|
||||
}
|
||||
|
||||
/// A hit only survives while every pass hit: one recompute in a request
|
||||
/// is a miss for that request, which is what a reader wants to know.
|
||||
fn saw(self, other: Reuse) -> Reuse {
|
||||
match (self, other) {
|
||||
(Reuse::Miss, _) | (_, Reuse::Miss) => Reuse::Miss,
|
||||
(Reuse::Hit, _) | (_, Reuse::Hit) => Reuse::Hit,
|
||||
_ => Reuse::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One group of stages: the flush's, or the handler's own.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Group {
|
||||
ms: [f64; Stage::ALL.len()],
|
||||
/// How many times `lint_with` ran in this group.
|
||||
passes: u32,
|
||||
/// How many violations the last pass found.
|
||||
violations: usize,
|
||||
/// How many rules that pass ran.
|
||||
rules: usize,
|
||||
/// How many actions were serialized.
|
||||
actions: usize,
|
||||
/// How many waiver files were read from disk.
|
||||
waivers: usize,
|
||||
/// Whether a `lucisv.toml` was found and read.
|
||||
toml: bool,
|
||||
fences: Fences,
|
||||
reuse: Reuse,
|
||||
}
|
||||
|
||||
impl Group {
|
||||
/// The `const` form `thread_local!`'s initializer needs; `Default` is not
|
||||
/// callable there.
|
||||
const EMPTY: Group = Group {
|
||||
ms: [0.0; Stage::ALL.len()],
|
||||
passes: 0,
|
||||
violations: 0,
|
||||
rules: 0,
|
||||
actions: 0,
|
||||
waivers: 0,
|
||||
toml: false,
|
||||
fences: Fences::Skipped,
|
||||
reuse: Reuse::None,
|
||||
};
|
||||
|
||||
fn add(&mut self, stage: Stage, took: Duration) {
|
||||
self.ms[stage as usize] += took.as_secs_f64() * 1_000.0;
|
||||
}
|
||||
|
||||
/// This group's fields, in the `key=value` shape `tools/perf` parses.
|
||||
fn fields(&self) -> String {
|
||||
let stages: Vec<String> = Stage::ALL
|
||||
.iter()
|
||||
.map(|stage| format!("{}={:.2}ms", stage.label(), self.ms[*stage as usize]))
|
||||
.collect();
|
||||
format!(
|
||||
"{} passes={} rules={} violations={} actions={} waivers={} toml={} fences={} \
|
||||
snapshot={}",
|
||||
stages.join(" "),
|
||||
self.passes,
|
||||
self.rules,
|
||||
self.violations,
|
||||
self.actions,
|
||||
self.waivers,
|
||||
self.toml,
|
||||
self.fences.label(),
|
||||
self.reuse.label(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// One request's trace: what the flush cost, and what the handler cost.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Trace {
|
||||
/// The stages the debounced `Document` rebuild and its diagnostics
|
||||
/// publish passed through, closed by [`close_flush`].
|
||||
pub flush: Group,
|
||||
/// How long the whole flush took, publish included.
|
||||
pub flush_ms: f64,
|
||||
/// Buffers the flush rebuilt.
|
||||
pub flush_buffers: usize,
|
||||
/// Whole-file parses the flush performed (`vlog_parser::stats`).
|
||||
pub flush_parses: u64,
|
||||
/// What the flush's `Document` rebuild and publish cost, stage by stage.
|
||||
pub rebuild: Rebuilt,
|
||||
/// The handler's own stages.
|
||||
pub action: Group,
|
||||
}
|
||||
|
||||
impl Trace {
|
||||
/// Whether this request touched the lint path at all. A trace that did
|
||||
/// not is not worth a line.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.flush == Group::default()
|
||||
&& self.action == Group::default()
|
||||
&& self.flush_buffers == 0
|
||||
&& self.rebuild == Rebuilt::default()
|
||||
}
|
||||
|
||||
/// The whole trace as one `timing:`-style fragment.
|
||||
///
|
||||
/// The three groups are siblings, never nested: `tools/perf`'s group
|
||||
/// regex flattens `name{…}` one level and would not survive a brace
|
||||
/// inside a brace.
|
||||
pub fn line(&self) -> String {
|
||||
format!(
|
||||
"flush{{wall={:.2}ms buffers={} parses={} {}}} rebuild{{{}}} action{{{}}}",
|
||||
self.flush_ms,
|
||||
self.flush_buffers,
|
||||
self.flush_parses,
|
||||
self.flush.fields(),
|
||||
self.rebuild.fields(),
|
||||
self.action.fields(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// One branch is the whole of what verbose-off costs at a traced site.
|
||||
static ARMED: Cell<bool> = const { Cell::new(false) };
|
||||
static TRACE: RefCell<Trace> = const { RefCell::new(Trace {
|
||||
flush: Group::EMPTY,
|
||||
flush_ms: 0.0,
|
||||
flush_buffers: 0,
|
||||
flush_parses: 0,
|
||||
rebuild: Rebuilt::EMPTY,
|
||||
action: Group::EMPTY,
|
||||
}) };
|
||||
/// Which group the stages recorded right now belong to.
|
||||
static IN_FLUSH: Cell<bool> = const { Cell::new(true) };
|
||||
}
|
||||
|
||||
/// Start a fresh trace for one request. Called by the request wrapper when
|
||||
/// `--verbose` asked for timing, and by nothing else.
|
||||
pub fn arm() {
|
||||
ARMED.set(true);
|
||||
IN_FLUSH.set(true);
|
||||
TRACE.with_borrow_mut(|trace| *trace = Trace::default());
|
||||
}
|
||||
|
||||
/// Whether a trace is being written — the one branch a caller checks before
|
||||
/// reading a clock of its own.
|
||||
pub fn armed() -> bool {
|
||||
ARMED.get()
|
||||
}
|
||||
|
||||
/// Stop tracing and return what was written, or `None` when nothing armed it.
|
||||
pub fn disarm() -> Option<Trace> {
|
||||
if !ARMED.replace(false) {
|
||||
return None;
|
||||
}
|
||||
Some(TRACE.with_borrow(Clone::clone))
|
||||
}
|
||||
|
||||
/// Close the flush group: everything recorded from here on is the handler's.
|
||||
///
|
||||
/// `parses` is the `vlog_parser::stats::parses()` delta across the flush and
|
||||
/// `buffers` is how many dirty buffers it rebuilt, so the `Document` rebuild
|
||||
/// is readable beside the diagnostics pass that follows it.
|
||||
pub fn close_flush(took: Duration, buffers: usize, parses: u64) {
|
||||
if !ARMED.get() {
|
||||
return;
|
||||
}
|
||||
TRACE.with_borrow_mut(|trace| {
|
||||
trace.flush_ms = took.as_secs_f64() * 1_000.0;
|
||||
trace.flush_buffers = buffers;
|
||||
trace.flush_parses = parses;
|
||||
});
|
||||
IN_FLUSH.set(false);
|
||||
}
|
||||
|
||||
/// Run `work`, counting what it took against `stage`.
|
||||
///
|
||||
/// Untimed and unallocated when nothing armed a trace, which is every session
|
||||
/// but a `--verbose` one.
|
||||
pub fn stage<T>(stage: Stage, work: impl FnOnce() -> T) -> T {
|
||||
if !ARMED.get() {
|
||||
return work();
|
||||
}
|
||||
let started = Instant::now();
|
||||
let out = work();
|
||||
let took = started.elapsed();
|
||||
group(|held| held.add(stage, took));
|
||||
out
|
||||
}
|
||||
|
||||
/// Run `work`, counting what it took against one of the flush's inner stages.
|
||||
///
|
||||
/// Off costs the same one thread-local read [`stage`] costs. The flush group
|
||||
/// is not consulted: a rebuild belongs to the rebuild it is part of whichever
|
||||
/// half of the request it happens in, and outside a flush there is none.
|
||||
pub fn rebuild<T>(stage: Rebuild, work: impl FnOnce() -> T) -> T {
|
||||
if !ARMED.get() {
|
||||
return work();
|
||||
}
|
||||
let started = Instant::now();
|
||||
let out = work();
|
||||
let took = started.elapsed();
|
||||
TRACE.with_borrow_mut(|trace| trace.rebuild.add(stage, took));
|
||||
out
|
||||
}
|
||||
|
||||
/// Record that one `Document` was built from scratch.
|
||||
pub fn saw_document() {
|
||||
if !ARMED.get() {
|
||||
return;
|
||||
}
|
||||
TRACE.with_borrow_mut(|trace| trace.rebuild.documents += 1);
|
||||
}
|
||||
|
||||
/// Record what a lint pass ran and found.
|
||||
pub fn saw_lint(rules: usize, violations: usize, reuse: Reuse) {
|
||||
group(|held| {
|
||||
held.passes += 1;
|
||||
held.rules = rules;
|
||||
held.violations = violations;
|
||||
held.reuse = held.reuse.saw(reuse);
|
||||
});
|
||||
}
|
||||
|
||||
/// Record what the configuration read found: a `lucisv.toml`, and how many
|
||||
/// waiver files it and the editor's settings between them named.
|
||||
pub fn saw_config(toml: bool, waivers: usize) {
|
||||
group(|held| {
|
||||
held.toml |= toml;
|
||||
held.waivers += waivers;
|
||||
});
|
||||
}
|
||||
|
||||
/// Record what the fence filter did.
|
||||
pub fn saw_fences(fences: Fences) {
|
||||
group(|held| held.fences = fences);
|
||||
}
|
||||
|
||||
/// Record how many actions were put on the wire.
|
||||
pub fn saw_actions(actions: usize) {
|
||||
group(|held| held.actions += actions);
|
||||
}
|
||||
|
||||
/// Apply `write` to whichever group is being filled, or to nothing at all.
|
||||
fn group(write: impl FnOnce(&mut Group)) {
|
||||
if !ARMED.get() {
|
||||
return;
|
||||
}
|
||||
let flushing = IN_FLUSH.get();
|
||||
TRACE.with_borrow_mut(|trace| {
|
||||
write(if flushing { &mut trace.flush } else { &mut trace.action })
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Nothing is written when nothing armed a trace — the shipped state.
|
||||
#[test]
|
||||
fn an_unarmed_trace_records_nothing_and_returns_the_work() {
|
||||
assert_eq!(disarm(), None);
|
||||
assert_eq!(stage(Stage::Lint, || 7), 7);
|
||||
saw_lint(3, 4, Reuse::Miss);
|
||||
assert_eq!(disarm(), None, "still nothing to say");
|
||||
}
|
||||
|
||||
/// The two groups are kept apart, and `close_flush` is what separates
|
||||
/// them: a stage before it is the flush's, one after it the handler's.
|
||||
#[test]
|
||||
fn close_flush_divides_the_request_into_its_two_halves() {
|
||||
arm();
|
||||
saw_lint(9, 100, Reuse::Miss);
|
||||
close_flush(Duration::from_millis(110), 1, 1);
|
||||
saw_lint(9, 100, Reuse::Hit);
|
||||
saw_actions(2);
|
||||
saw_fences(Fences::Memo);
|
||||
let trace = disarm().expect("armed");
|
||||
assert_eq!(trace.flush.passes, 1);
|
||||
assert_eq!(trace.flush.violations, 100);
|
||||
assert_eq!(trace.flush.actions, 0, "the flush serializes nothing");
|
||||
assert_eq!(trace.flush_buffers, 1);
|
||||
assert_eq!(trace.flush_parses, 1);
|
||||
assert!((trace.flush_ms - 110.0).abs() < 5.0, "{}", trace.flush_ms);
|
||||
assert_eq!(trace.action.passes, 1);
|
||||
assert_eq!(trace.action.actions, 2);
|
||||
assert_eq!(trace.action.fences, Fences::Memo);
|
||||
assert_eq!(trace.action.reuse, Reuse::Hit);
|
||||
assert_eq!(disarm(), None, "disarming twice says nothing twice");
|
||||
}
|
||||
|
||||
/// One recompute in a request is a miss for that request: a reader asking
|
||||
/// "did this menu re-lint?" must not be told "hit" because the second
|
||||
/// pass reused what the first one had just computed.
|
||||
#[test]
|
||||
fn a_single_recompute_makes_the_whole_request_a_miss() {
|
||||
arm();
|
||||
close_flush(Duration::ZERO, 0, 0);
|
||||
saw_lint(9, 100, Reuse::Hit);
|
||||
saw_lint(9, 100, Reuse::Miss);
|
||||
assert_eq!(disarm().expect("armed").action.reuse, Reuse::Miss);
|
||||
}
|
||||
|
||||
/// Every stage is named in the line whether or not it ran, so a reader
|
||||
/// (and `tools/perf/phases_r1.py`) always parses the same fields.
|
||||
#[test]
|
||||
fn the_line_names_every_stage_in_both_groups() {
|
||||
arm();
|
||||
stage(Stage::Config, || {});
|
||||
close_flush(Duration::from_millis(1), 1, 1);
|
||||
stage(Stage::Lint, || {});
|
||||
let line = disarm().expect("armed").line();
|
||||
for stage in Stage::ALL {
|
||||
assert_eq!(line.matches(&format!("{}=", stage.label())).count(), 2, "{line}");
|
||||
}
|
||||
assert!(line.contains("buffers=1"), "{line}");
|
||||
assert!(line.contains("snapshot=none"), "{line}");
|
||||
assert!(!line.contains(" "), "no empty field: {line}");
|
||||
}
|
||||
|
||||
/// The flush's inner stages are their own sibling group, named whether or
|
||||
/// not they ran, and never nested inside `flush{…}` — `tools/perf`'s
|
||||
/// group regex flattens one level only (TODO §63.2).
|
||||
#[test]
|
||||
fn the_rebuild_group_names_every_stage_beside_the_other_two() {
|
||||
arm();
|
||||
rebuild(Rebuild::Lex, || {});
|
||||
saw_document();
|
||||
close_flush(Duration::from_millis(1), 1, 1);
|
||||
let line = disarm().expect("armed").line();
|
||||
let rebuilt = line.split("rebuild{").nth(1).expect("a rebuild group").split('}').next();
|
||||
let rebuilt = rebuilt.expect("a closed rebuild group");
|
||||
for stage in Rebuild::ALL {
|
||||
assert!(rebuilt.contains(&format!("{}=", stage.label())), "{line}");
|
||||
}
|
||||
assert!(rebuilt.contains("documents=1"), "{line}");
|
||||
assert!(!rebuilt.contains('{'), "no nested group: {line}");
|
||||
}
|
||||
|
||||
/// TODO §63.2 QA: the sibling-group contract, attacked directly against
|
||||
/// the parser it is a contract *with*.
|
||||
///
|
||||
/// `tools/perf/phases_p2.py`'s `GROUP` regex is `([a-z_]+)\{([^{}]*)\}` —
|
||||
/// a group's body may not contain another `{`. Sabotaging `line()` to
|
||||
/// nest `rebuild{…}` inside `flush{…}` (tried by hand while attacking
|
||||
/// this pin) does **not** fail the test above: splitting on `"rebuild{"`
|
||||
/// still finds a clean `rebuild` body, because the extra brace the
|
||||
/// nesting adds sits *outside* the slice that test inspects. Run through
|
||||
/// the actual regex, though, nesting is fatal: `[^{}]*` cannot cross the
|
||||
/// inner `{`, so the whole `flush{...}` match fails and `flush_wall`,
|
||||
/// `flush_buffers`, `flush_parses` and every `flush.fields()` entry
|
||||
/// silently vanish from every `tools/perf` row — confirmed with
|
||||
/// `GROUP.findall` in a scratch interpreter against the sabotaged line,
|
||||
/// which matched only `rebuild` and `action`, never `flush`. This test
|
||||
/// reads the line the way the regex does (each group's body must reach
|
||||
/// its own `}` before another `{` opens) so a future nesting regression
|
||||
/// fails here instead of only downstream in Python.
|
||||
#[test]
|
||||
fn the_three_top_level_groups_are_flat_never_nested() {
|
||||
arm();
|
||||
rebuild(Rebuild::Lex, || {});
|
||||
saw_document();
|
||||
close_flush(Duration::from_millis(1), 1, 1);
|
||||
let line = disarm().expect("armed").line();
|
||||
for name in ["flush", "rebuild", "action"] {
|
||||
let open =
|
||||
line.find(&format!("{name}{{")).unwrap_or_else(|| panic!("no {name}{{ in {line}"));
|
||||
let body = &line[open + name.len() + 1..];
|
||||
let close =
|
||||
body.find('}').unwrap_or_else(|| panic!("no closing brace for {name}: {line}"));
|
||||
let next_open = body.find('{');
|
||||
assert!(
|
||||
next_open.is_none_or(|o| o > close),
|
||||
"{name}{{...}} is not flat — a nested group vanishes from every \
|
||||
tools/perf row parsed by phases_p2.GROUP instead of failing loudly: {line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rebuild is recorded in either half of the request, and an unarmed
|
||||
/// one records nothing at all.
|
||||
#[test]
|
||||
fn a_rebuild_is_counted_whichever_half_of_the_request_runs_it() {
|
||||
assert_eq!(rebuild(Rebuild::Parse, || 4), 4);
|
||||
assert_eq!(disarm(), None);
|
||||
arm();
|
||||
rebuild(Rebuild::Parse, || {});
|
||||
close_flush(Duration::ZERO, 1, 1);
|
||||
rebuild(Rebuild::Parse, || {});
|
||||
saw_document();
|
||||
saw_document();
|
||||
let trace = disarm().expect("armed");
|
||||
assert_eq!(trace.rebuild.documents, 2);
|
||||
assert_eq!(trace.flush.passes, 0, "a rebuild is not a lint pass");
|
||||
assert_eq!(trace.action.passes, 0);
|
||||
}
|
||||
|
||||
/// A request that only rebuilt a buffer still has something to say: the
|
||||
/// trace must not be discarded as empty before the line is logged.
|
||||
///
|
||||
/// The rebuilt *count*, not a stage's milliseconds, is what says a
|
||||
/// rebuild happened — a stage whose work takes less than the clock's
|
||||
/// resolution adds 0.00 ms, which is why `Document::new` reports itself
|
||||
/// with [`saw_document`] rather than leaving the evidence to a duration.
|
||||
#[test]
|
||||
fn a_trace_holding_only_a_rebuild_is_not_empty() {
|
||||
arm();
|
||||
rebuild(Rebuild::Analyze, || {});
|
||||
saw_document();
|
||||
assert!(!disarm().expect("armed").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,18 @@
|
||||
//! buffer's own line index when there is one, and otherwise through
|
||||
//! `Workspace::file_view`, which reads a closed file at most once per
|
||||
//! generation of it rather than once per question about it.
|
||||
//!
|
||||
//! One span never needs that read at all: a **file-scope declaration**'s own
|
||||
//! name, whose client-side range the index recorded when the file was scanned
|
||||
//! ([`vlog_semantic::DeclPositions`]). [`definition_location`] is that path,
|
||||
//! and it is what `textDocument/definition` and `workspace/symbol` answer
|
||||
//! from — see `docs/features/lazy-code-action/README.md`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Location;
|
||||
use lsp_types::{Location, Position, Range};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Def, Utf16Range};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
@@ -27,6 +34,40 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location
|
||||
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
|
||||
}
|
||||
|
||||
/// Where an **indexed** declaration is written — its name's own range.
|
||||
///
|
||||
/// The index converted that range to client positions while it was scanning
|
||||
/// the file ([`vlog_semantic::DeclLines::positions`]), so pointing an editor
|
||||
/// at a module nobody has open is a map lookup rather than a file read: the
|
||||
/// same eight numbers, computed once at index time instead of once per
|
||||
/// question. Only **file-scope** declarations carry them; a member (a port, a
|
||||
/// parameter, a class field) records none and falls through to
|
||||
/// [`location`]'s read, which is the whole reason this is a separate function
|
||||
/// rather than a change inside that one.
|
||||
///
|
||||
/// **An open buffer keeps the read.** Its text may have moved since it was
|
||||
/// indexed, and every other answer about that buffer is computed against the
|
||||
/// text it holds now; answering this one from the index instead would make
|
||||
/// go-to-definition disagree with the document symbols beside it.
|
||||
pub fn definition_location(ws: &Workspace, path: &Path, def: &Def) -> Option<Location> {
|
||||
if ws.document_for_path(path).is_none() {
|
||||
if let Some(recorded) = def.lines.positions {
|
||||
return Some(Location { uri: path_to_uri(path)?, range: range(recorded.name) });
|
||||
}
|
||||
}
|
||||
location(ws, path, def.name_span)
|
||||
}
|
||||
|
||||
/// An index-recorded range as the protocol's own — the same four numbers,
|
||||
/// both already counted in UTF-16 code units by the file's own
|
||||
/// `LineIndex::utf16_position`, which is the converter `Positions` uses too.
|
||||
fn range(recorded: Utf16Range) -> Range {
|
||||
Range {
|
||||
start: Position { line: recorded.start.line, character: recorded.start.character },
|
||||
end: Position { line: recorded.end.line, character: recorded.end.character },
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
///
|
||||
@@ -49,3 +90,197 @@ pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
pub fn display_name(path: &Path) -> String {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
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_locate_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
/// Write a file as **bytes**, so a test can put a BOM or CRLF in one.
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text.as_bytes()).expect("write");
|
||||
path
|
||||
}
|
||||
|
||||
/// An indexed workspace over everything written so far.
|
||||
fn indexed(&self) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![self.path.clone()]);
|
||||
ws
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The one declaration of `name` in the index, and the file it is in.
|
||||
fn only_def<'w>(ws: &'w Workspace, name: &str) -> (&'w Def, &'w Path) {
|
||||
let index = ws.index();
|
||||
let [def] = index.units(name) else { panic!("exactly one `{name}`") };
|
||||
(def, index.path(def.file).expect("a path"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_scope_definition_is_located_without_reading_its_file() {
|
||||
let tree = Tree::new("no_read");
|
||||
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
|
||||
let ws = tree.indexed();
|
||||
let (def, path) = only_def(&ws, "sub");
|
||||
|
||||
let indexed = definition_location(&ws, path, def).expect("a location");
|
||||
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
|
||||
|
||||
// Only now, so the comparison cannot be what filled the cache.
|
||||
let read = location(&ws, path, def.name_span).expect("a location");
|
||||
assert_eq!(indexed, read);
|
||||
assert_eq!(ws.held_views().len(), 1, "the file-read path really does read one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom() {
|
||||
// Everything that has ever made a UTF-16 conversion disagree, in one
|
||||
// file: a BOM at offset 0, CRLF line endings, a two-byte character, a
|
||||
// three-byte one, and an astral character that is *two* UTF-16 code
|
||||
// units on its own.
|
||||
let tree = Tree::new("encodings");
|
||||
tree.write(
|
||||
"wide.sv",
|
||||
"\u{feff}// é ✓ 𝛼𝛽 — a comment\r\n\
|
||||
// 𝟘𝟙𝟚 more\r\n\
|
||||
module wide (\r\n input logic clk\r\n);\r\nendmodule\r\n",
|
||||
);
|
||||
let ws = tree.indexed();
|
||||
let (def, path) = only_def(&ws, "wide");
|
||||
|
||||
let indexed = definition_location(&ws, path, def).expect("a location");
|
||||
assert!(ws.held_views().is_empty(), "still no read");
|
||||
let read = location(&ws, path, def.name_span).expect("a location");
|
||||
assert_eq!(indexed, read, "the index-only range must be the file-read one");
|
||||
// And it really is the name, not the line: `module ` is seven UTF-16
|
||||
// units into line 2 (0-based), whatever the lines above it hold.
|
||||
assert_eq!(indexed.range.start.line, 2);
|
||||
assert_eq!(indexed.range.start.character, 7);
|
||||
assert_eq!(indexed.range.end.character, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_still_answers_from_the_buffer() {
|
||||
// The index saw the file on disk; the buffer has since gained a line
|
||||
// above the declaration, and has not been re-indexed. An indexed span
|
||||
// is stale either way — the byte offset is the disk file's — and what
|
||||
// this pins is that the *conversion* is unchanged by this round: the
|
||||
// buffer's own line index, exactly as before, so go-to-definition and
|
||||
// the document symbols beside it still agree with each other.
|
||||
let tree = Tree::new("open_buffer");
|
||||
let path = tree.write("sub.sv", "module sub;\nendmodule\n");
|
||||
let mut ws = tree.indexed();
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "// typed since\nmodule sub;\nendmodule\n".to_string());
|
||||
|
||||
let (def, path) = only_def(&ws, "sub");
|
||||
let located = definition_location(&ws, path, def).expect("a location");
|
||||
assert_eq!(
|
||||
located,
|
||||
location(&ws, path, def.name_span).expect("a location"),
|
||||
"an open buffer takes the file-read path, index positions or not"
|
||||
);
|
||||
assert_eq!(located.range.start.line, 0, "byte 7 of the buffer, not of the index's file");
|
||||
assert!(ws.held_views().is_empty(), "an open buffer is never viewed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_keeps_the_file_read_path() {
|
||||
// Members carry no `DeclPositions` — see `DeclLines` — so the fallback
|
||||
// is not decoration: it is the only answer for a port.
|
||||
let tree = Tree::new("member");
|
||||
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
|
||||
let ws = tree.indexed();
|
||||
let index = ws.index();
|
||||
let [port] = index.member("sub", "clk") else { panic!("one `clk`") };
|
||||
assert!(port.lines.positions.is_none(), "a member records no client positions");
|
||||
let path = index.path(port.file).expect("a path");
|
||||
assert_eq!(
|
||||
definition_location(&ws, path, port),
|
||||
location(&ws, path, port.name_span),
|
||||
"and the fallback answers exactly what it always did"
|
||||
);
|
||||
assert_eq!(ws.held_views().len(), 1, "which cost the read");
|
||||
}
|
||||
|
||||
/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server --bin lucisv-server locate::tests::defining -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"]
|
||||
fn defining_over_a_real_project() {
|
||||
// TODO §37.3's own number, beside the code it measures rather than in
|
||||
// `perf.rs` — the precedent `perf::mean`'s `pub(crate)` exists for.
|
||||
// Two columns over the same corpus and the same targets: converting an
|
||||
// indexed span by reading its file, and reading it off the index.
|
||||
// **Read-only** — the corpus is opened, never written.
|
||||
let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else {
|
||||
eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
ws.open_whole_workspace(vec![PathBuf::from(&root)]);
|
||||
let scan = started.elapsed();
|
||||
|
||||
// The targets: modules the corpus instantiates somewhere, whose single
|
||||
// declaration the index can name — what an F12 on an instantiation
|
||||
// lands on, and each in a different file.
|
||||
let names: Vec<String> =
|
||||
ws.index().instantiations().map(|(name, _)| name.to_string()).collect();
|
||||
let targets: Vec<(PathBuf, vlog_semantic::Def)> = names
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
let path = vlog_refactor::module_definition(ws.index(), name).ok()?;
|
||||
let [def] = ws.index().units(name) else { return None };
|
||||
def.lines.positions.is_some().then(|| (path.to_path_buf(), def.clone()))
|
||||
})
|
||||
.take(200)
|
||||
.collect();
|
||||
|
||||
let indexed = crate::perf::mean(5, || {
|
||||
for (path, def) in &targets {
|
||||
std::hint::black_box(definition_location(&ws, path, def));
|
||||
}
|
||||
});
|
||||
let read = crate::perf::mean(5, || {
|
||||
for (path, def) in &targets {
|
||||
std::hint::black_box(location(&ws, path, def.name_span));
|
||||
}
|
||||
});
|
||||
let each = targets.len().max(1) as u32;
|
||||
eprintln!(
|
||||
"definition over {} indexed files of {root} (scan {scan:?}), {} targets:\n \
|
||||
index-only {indexed:?}, file-read {read:?} — {:?} vs {:?} per definition",
|
||||
ws.index().files().len(),
|
||||
targets.len(),
|
||||
indexed / each,
|
||||
read / each,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,21 +13,28 @@ mod convert;
|
||||
mod design_hierarchy;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod extract;
|
||||
mod fences;
|
||||
mod file_ops;
|
||||
mod folding;
|
||||
mod format;
|
||||
mod hierarchy;
|
||||
mod hover;
|
||||
mod imports;
|
||||
mod includes;
|
||||
mod index_cache;
|
||||
mod inlay;
|
||||
mod inline;
|
||||
mod inline_module;
|
||||
mod instantiate;
|
||||
mod large;
|
||||
mod lens;
|
||||
mod linked;
|
||||
mod lint;
|
||||
mod lint_snapshot;
|
||||
mod lint_trace;
|
||||
mod locate;
|
||||
mod module_select;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
@@ -35,6 +42,9 @@ mod pairs;
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod rename_trace;
|
||||
mod scan_order;
|
||||
mod scan_trace;
|
||||
mod selection;
|
||||
mod server;
|
||||
mod settings;
|
||||
@@ -59,11 +69,12 @@ use lsp_types::{
|
||||
DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions,
|
||||
FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
|
||||
InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind,
|
||||
RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions,
|
||||
SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities,
|
||||
ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
|
||||
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability,
|
||||
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
RenameOptions, ResourceOperationKind, SaveOptions, SelectionRangeProviderCapability,
|
||||
SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
|
||||
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
|
||||
TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
|
||||
TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, WorkDoneProgressOptions,
|
||||
WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
};
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
@@ -126,6 +137,8 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
hierarchy_view,
|
||||
code_action_resolve: code_action_resolve_support(¶ms),
|
||||
create_files: create_files_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
@@ -259,10 +272,18 @@ fn capabilities() -> ServerCapabilities {
|
||||
CodeActionKind::QUICKFIX,
|
||||
CodeActionKind::new(code_action::FIX_ALL),
|
||||
CodeActionKind::new(ports::REFACTOR_PORTS),
|
||||
imports::kind(),
|
||||
extract::kind(),
|
||||
inline_module::kind(),
|
||||
]),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
// Every action is returned complete; there is nothing to resolve.
|
||||
resolve_provider: None,
|
||||
// The quick fixes are complete when they are offered; the port
|
||||
// refactorings are not, for a client that can ask
|
||||
// (`docs/features/lazy-code-action/README.md`). Advertised
|
||||
// unconditionally because the server can always answer a resolve
|
||||
// — including for an action that already carries its edit, which
|
||||
// it hands straight back.
|
||||
resolve_provider: Some(true),
|
||||
})),
|
||||
// The port refactorings. `lucisv.addPort` needs a declaration typed by
|
||||
// the user, which no code action can carry, and a Vim user has no
|
||||
@@ -391,10 +412,13 @@ fn capabilities() -> ServerCapabilities {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every command this server executes: the three port refactorings, the
|
||||
/// instantiation skeleton, and the jump the code lens hangs off.
|
||||
/// Every command this server executes: the port refactorings, organize
|
||||
/// imports, the instantiation skeleton, and the jump the code lens hangs off.
|
||||
fn commands() -> Vec<String> {
|
||||
let mut commands = ports::commands();
|
||||
commands.extend(imports::commands());
|
||||
commands.extend(extract::commands());
|
||||
commands.extend(inline_module::commands());
|
||||
commands.extend(instantiate::commands());
|
||||
commands.extend(lens::commands());
|
||||
commands
|
||||
@@ -499,6 +523,50 @@ fn snippet_support(params: &InitializeParams) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client can fetch a code action's `edit` after the fact —
|
||||
/// `textDocument.codeAction.resolveSupport.properties` listing `"edit"`.
|
||||
///
|
||||
/// The property list is the capability: a client that can resolve `title`
|
||||
/// alone cannot be offered an action without its edit, so nothing short of
|
||||
/// `"edit"` counts. A client that says nothing gets every action complete, as
|
||||
/// every client did before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
fn code_action_resolve_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.text_document
|
||||
.as_ref()
|
||||
.and_then(|text_document| text_document.code_action.as_ref())
|
||||
.and_then(|code_action| code_action.resolve_support.as_ref())
|
||||
.is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit"))
|
||||
}
|
||||
|
||||
/// Whether the client can apply a `WorkspaceEdit` that **creates a file** —
|
||||
/// `workspace.workspaceEdit.documentChanges` *and* a `resourceOperations`
|
||||
/// list containing `create`.
|
||||
///
|
||||
/// Both halves, because a creation is a resource operation and a resource
|
||||
/// operation can only be sent inside `documentChanges`: a client with one and
|
||||
/// not the other cannot apply the edit at all. A client that says nothing gets
|
||||
/// the extracted module written below the one it came from, in the file it
|
||||
/// came from, which needs no capability of any kind
|
||||
/// (`docs/features/extract-inline-module/README.md`).
|
||||
fn create_files_support(params: &InitializeParams) -> bool {
|
||||
let Some(edits) = params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.workspace_edit.as_ref())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let creates = edits
|
||||
.resource_operations
|
||||
.as_ref()
|
||||
.is_some_and(|kinds| kinds.contains(&ResourceOperationKind::Create));
|
||||
edits.document_changes.unwrap_or(false) && creates
|
||||
}
|
||||
|
||||
/// Whether the client applies a `workspace/applyEdit` request.
|
||||
///
|
||||
/// A client that did not say so gets a command's edit back as the request
|
||||
@@ -1148,6 +1216,91 @@ mod tests {
|
||||
assert!(kinds.contains(&CodeActionKind::QUICKFIX));
|
||||
assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL)));
|
||||
assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS)));
|
||||
assert_eq!(
|
||||
options.resolve_provider,
|
||||
Some(true),
|
||||
"the port refactorings are offered without their edits to a client that can ask"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_files_support_needs_both_halves_of_the_capability() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, ResourceOperationKind, WorkspaceClientCapabilities,
|
||||
WorkspaceEditClientCapabilities,
|
||||
};
|
||||
assert!(
|
||||
!create_files_support(&InitializeParams::default()),
|
||||
"silence means the module goes below the one it came from"
|
||||
);
|
||||
|
||||
let saying = |document_changes: Option<bool>, ops: Option<&[ResourceOperationKind]>| {
|
||||
InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities {
|
||||
workspace_edit: Some(WorkspaceEditClientCapabilities {
|
||||
document_changes,
|
||||
resource_operations: ops.map(<[_]>::to_vec),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let create = [ResourceOperationKind::Create];
|
||||
let rename = [ResourceOperationKind::Rename];
|
||||
assert!(create_files_support(&saying(Some(true), Some(&create))), "what VS Code sends");
|
||||
assert!(
|
||||
!create_files_support(&saying(Some(true), Some(&rename))),
|
||||
"a client that can rename but not create cannot apply the creation"
|
||||
);
|
||||
assert!(
|
||||
!create_files_support(&saying(Some(true), None)),
|
||||
"no resource operations at all is no creation"
|
||||
);
|
||||
assert!(
|
||||
!create_files_support(&saying(None, Some(&create))),
|
||||
"a resource operation can only be sent inside `documentChanges`"
|
||||
);
|
||||
assert!(!create_files_support(&saying(Some(false), Some(&create))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, CodeActionCapabilityResolveSupport, CodeActionClientCapabilities,
|
||||
TextDocumentClientCapabilities,
|
||||
};
|
||||
assert!(
|
||||
!code_action_resolve_support(&InitializeParams::default()),
|
||||
"silence means the whole edit up front"
|
||||
);
|
||||
|
||||
let saying = |properties: &[&str]| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
text_document: Some(TextDocumentClientCapabilities {
|
||||
code_action: Some(CodeActionClientCapabilities {
|
||||
resolve_support: Some(CodeActionCapabilityResolveSupport {
|
||||
properties: properties.iter().map(|p| p.to_string()).collect(),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(code_action_resolve_support(&saying(&["edit"])));
|
||||
assert!(code_action_resolve_support(&saying(&["documentation", "edit"])));
|
||||
assert!(
|
||||
!code_action_resolve_support(&saying(&["documentation"])),
|
||||
"resolving anything but the edit is no use to us"
|
||||
);
|
||||
assert!(!code_action_resolve_support(&saying(&[])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Which files can name a scope *inside* the module a refactoring rewrites.
|
||||
//!
|
||||
//! [`Workspace::module_sources`](crate::state::Workspace::module_sources)'s
|
||||
//! four rungs answer "who declares, instantiates or refers to these **names**".
|
||||
//! That is enough for the port refactorings and for extract, whose refusals
|
||||
//! are about the names themselves. It is not enough for inline-module, whose
|
||||
//! `no_hierarchy` refusal is about a *path through the design hierarchy*:
|
||||
//! `tb.sv` writing `u_wrapper.u_top.u_sub.s` names the instance `u_sub` that
|
||||
//! inlining dissolves, and `tb.sv` instantiates `wrapper` — not `top`, not
|
||||
//! `sub`. No rung asks for it, `no_hierarchy` only sees what it is handed, and
|
||||
//! the inline was **silently accepted**, dissolving a scope a testbench walks
|
||||
//! through. §53.2's QA reproduced exactly that; it is topology handshake 33.
|
||||
//!
|
||||
//! **The rung is the instance's own word census.** `no_hierarchy` refuses when
|
||||
//! some handed file's token stream holds an `Ident` spelling the instance with
|
||||
//! a `.` (or a `bind`) beside it. [`WorkspaceIndex::files_mentioning`] is the
|
||||
//! census of every file whose token stream writes a word down at all — read
|
||||
//! off `FileFacts::words`, which `vlog_semantic::words::harvest` fills from
|
||||
//! every `Ident` token *and* from the raw text of macro invocations,
|
||||
//! directives and attributes. So a file that could raise that refusal is
|
||||
//! always in this answer, and [`hierarchical_users`] hands inline exactly the
|
||||
//! files that could change its mind.
|
||||
//!
|
||||
//! That is a stronger claim than the transitive-instantiator walk the topology
|
||||
//! row asks for, and it is why this module does not do that walk. Climbing the
|
||||
//! instantiation edges upward from the host module finds the wrapper levels,
|
||||
//! but it misses `bind tb.u_wrapper.u_top.u_sub …` written in an SVA file that
|
||||
//! instantiates nothing in the chain, and `$root`-anchored and macro-built
|
||||
//! paths with it — all shapes `no_hierarchy` refuses over and all shapes the
|
||||
//! word census holds. It also selects files that instantiate up the chain and
|
||||
//! never spell the instance, which no refusal can turn on. The census is both
|
||||
//! the tighter and the more complete answer. Written out in the feature
|
||||
//! README's handshake note, with the failing `bind` fixture that settled it.
|
||||
//!
|
||||
//! The rung can only **add** files, so an edit stays the edit it was and a
|
||||
//! refusal it makes possible is one the whole-workspace engine also makes.
|
||||
//! Nothing here reads a file or parses anything: it is a walk over the records
|
||||
//! the index already holds, binary-searching each file's sorted word list.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::{FileId, WorkspaceIndex};
|
||||
|
||||
/// The extra reach one refactoring asks for.
|
||||
///
|
||||
/// A caller that needs none passes [`Reach::none`] — which is what
|
||||
/// `module_sources` itself does, so the port and extract paths are unchanged
|
||||
/// by this module in answer and in cost.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Reach<'a> {
|
||||
/// The scope names whose *inside* the refactoring dissolves: for
|
||||
/// inline-module, the instance it removes. Every file whose tokens write
|
||||
/// one of these words is wanted, because every file that could refuse
|
||||
/// over a hierarchical path through it does.
|
||||
pub scopes: &'a [String],
|
||||
}
|
||||
|
||||
impl Reach<'_> {
|
||||
/// No extra reach — the four rungs alone.
|
||||
pub fn none() -> Reach<'static> {
|
||||
Reach { scopes: &[] }
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file whose token stream writes one of `reach`'s scope names.
|
||||
///
|
||||
/// The caller unions this into the set its own rungs filled, so a path this
|
||||
/// rung is the first to ask for is still just a path.
|
||||
pub fn hierarchical_users(index: &WorkspaceIndex, reach: Reach<'_>) -> BTreeSet<PathBuf> {
|
||||
let mut out = BTreeSet::new();
|
||||
for scope in reach.scopes {
|
||||
out.extend(
|
||||
index
|
||||
.files_mentioning(scope)
|
||||
.filter_map(|file| index.path(file))
|
||||
.map(Path::to_path_buf),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The declaring file of every module instantiated in one of `files` — one
|
||||
/// hop down the instantiation edges the index already holds (`bind`
|
||||
/// directives included).
|
||||
///
|
||||
/// A rename's own rungs hand over every file declaring either name, so a
|
||||
/// module a `.*` instantiates is handed over exactly when it declares a port
|
||||
/// that needs a rewrite. When it declares neither name it is not, and the
|
||||
/// engine — which cannot tell "not handed over" from "not in the workspace" —
|
||||
/// refuses the rename as one it cannot check (TODO-MCP M3.5). This rung hands
|
||||
/// those modules over so the engine can see they bind nothing. It can only
|
||||
/// add files, so an edit stays the edit it was; nothing is read or parsed.
|
||||
pub fn instantiated_by(index: &WorkspaceIndex, files: &[&Path]) -> BTreeSet<PathBuf> {
|
||||
let ids: BTreeSet<FileId> = files.iter().filter_map(|path| index.file_id(path)).collect();
|
||||
let mut out = BTreeSet::new();
|
||||
for (module, edges) in index.instantiations() {
|
||||
if !edges.iter().any(|edge| ids.contains(&edge.file)) {
|
||||
continue;
|
||||
}
|
||||
let declared = index.units(module).iter().filter(|def| def.kind.is_instantiable());
|
||||
out.extend(declared.filter_map(|def| index.path(def.file)).map(Path::to_path_buf));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `tb` → `wrapper` → `top` → `sub`, the shape §53.2's QA reported: `tb`
|
||||
/// names `u_sub` through two levels it does not itself instantiate, and
|
||||
/// `sva.sv` names it through a `bind` while instantiating nothing at all.
|
||||
fn ladder() -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(vec![
|
||||
(PathBuf::from("/w/sub.sv"), "module sub; logic s; endmodule\n"),
|
||||
(PathBuf::from("/w/top.sv"), "module top; sub u_sub (); endmodule\n"),
|
||||
(PathBuf::from("/w/wrapper.sv"), "module wrapper; top u_top (); endmodule\n"),
|
||||
(
|
||||
PathBuf::from("/w/tb.sv"),
|
||||
"module tb; wrapper u_wrapper (); assign x = u_wrapper.u_top.u_sub.s; endmodule\n",
|
||||
),
|
||||
(
|
||||
PathBuf::from("/w/sva.sv"),
|
||||
"module chk (input logic a); endmodule\nbind tb.u_wrapper.u_top.u_sub chk u_chk (.a(1'b0));\n",
|
||||
),
|
||||
(PathBuf::from("/w/stranger.sv"), "module stranger; logic q; endmodule\n"),
|
||||
])
|
||||
}
|
||||
|
||||
fn names(paths: &BTreeSet<PathBuf>) -> Vec<String> {
|
||||
paths
|
||||
.iter()
|
||||
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_that_writes_the_instance_down_is_wanted() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let found = hierarchical_users(&index, Reach { scopes: &scopes });
|
||||
assert_eq!(
|
||||
names(&found),
|
||||
vec!["sva.sv".to_string(), "tb.sv".to_string(), "top.sv".to_string()],
|
||||
"the declaring file, the bench two levels up, and the bind that instantiates nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_never_writes_it_is_not() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_sub".to_string()];
|
||||
assert!(!names(&hierarchical_users(&index, Reach { scopes: &scopes }))
|
||||
.contains(&"stranger.sv".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_nothing_writes_wants_nothing() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_no_such_instance".to_string()];
|
||||
assert!(hierarchical_users(&index, Reach { scopes: &scopes }).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modules_a_file_instantiates_are_one_hop_down_and_no_further() {
|
||||
let index = ladder();
|
||||
let tb = Path::new("/w/tb.sv");
|
||||
let below = instantiated_by(&index, &[tb]);
|
||||
assert_eq!(names(&below), ["wrapper.sv"], "tb instantiates wrapper, and only wrapper");
|
||||
assert!(instantiated_by(&index, &[Path::new("/w/nowhere.sv")]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_reach_asked_for_is_no_work_done() {
|
||||
let index = ladder();
|
||||
assert!(hierarchical_users(&index, Reach::none()).is_empty());
|
||||
}
|
||||
}
|
||||
Loaded 100 of 469 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user