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 |
No files matched your search
+196
@@ -4,6 +4,202 @@ 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
|
||||
|
||||
Generated
+22
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.51.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.51.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.51.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.51.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.51.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -265,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.51.0"
|
||||
version = "0.56.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.51.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -278,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.51.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.51.0"
|
||||
version = "0.56.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
+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`.
|
||||
@@ -671,6 +671,11 @@ section only tracks the milestones.
|
||||
- [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP
|
||||
`prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves,
|
||||
cross-file, whole-edit-or-nothing verified by re-parse.
|
||||
**2026-09-23 (TODO-MCP M3.5):** a rename no longer cuts a `.name` or `.*`
|
||||
connection — the binding is written out explicitly (`.q(p)`, `.n(m)`) and
|
||||
warned about, the unreadable cases are refused, and the verifier prints
|
||||
every implicit binding before and after (`docs/features/refactor-rename/README.md`,
|
||||
"Implicit connections").
|
||||
- [x] **M3 `refactor-ports`** — add/remove/propagate module ports across
|
||||
the declaration and every instantiation (named/ordered/`.*`).
|
||||
**Amended 2026-08-28** (`docs/features/refactor-ports/README.md`): a
|
||||
@@ -4714,6 +4719,38 @@ in 0.49.0. Take 4's findings are in the loop-3 list above.
|
||||
already stat'd and could hand on), then `cache_open` 89 ms; warm settle
|
||||
~1.04–1.10 s against the plan's < 1 s, the rest being the store open
|
||||
the refused reuse would remove.
|
||||
- **review round §61.2 filed:** a `format::indent_width` form taking an
|
||||
already-read `FileConfig`, so the code-action path's run and the
|
||||
publish path do one `Discovery` walk, not two (+0.1 ms today).
|
||||
- **review round §61.3 filed:** a bounded local-record load of the index
|
||||
store for the open folder's head (measured ~26 ms vs the 89 ms whole
|
||||
open, but the 61 ms checksum verification is owed either way and it
|
||||
breaks `Load::canonical`) — its own experiment if the first answer
|
||||
needs the 89 ms; and a walk that can skip an already-walked subtree so
|
||||
the two-phase discovery stops walking the open folder twice (+2.5–5 %
|
||||
on the 1/10-buffer settle).
|
||||
- **review round §61.5 filed (QA, pre-existing):** a `bind` file's own
|
||||
occurrence of a renamed name (`aes_bind.sv` for a bound name or a
|
||||
two-level hierarchical tail) is neither edited nor warned about,
|
||||
identically before and after the reuse — the whole-scope engine's
|
||||
answer, so a missing warning at least (QA task `task_834abda3`); the
|
||||
scope reuse's collateral for the other refactorings (`_with` doors for
|
||||
extract/inline/imports/ports/references — the resolves and the extract
|
||||
edit are the candidates, the 805 ms refusal is after the build); the
|
||||
31 ms store decode the one-place tie costs.
|
||||
- **§63.1 QA (2026-09-12, pre-existing, `task_d8afe80f`):** cross-file
|
||||
`references` cannot see a hierarchical-surface-only declaration (a
|
||||
module's net, variable or instance), bind or not — `nav.rs`'s
|
||||
`leaves_this_file` and `indexed_def_in_file` (shared with hover) ask
|
||||
`WorkspaceIndex::member`, the connection surface; the fix is the
|
||||
hierarchical-surface lookup in both call sites plus a fixture sweep
|
||||
across definition/references/hover/documentHighlight.
|
||||
- **§63.2 filed (2026-09-12):** the rest of the first-after-edit flush —
|
||||
the token clone into `parse_tolerant` (3.9 ms; the parser mutates the
|
||||
stream it is given, and `Document::tokens` is read for comments by
|
||||
semantic tokens and the linter), `analyze` (9.4 ms), `resolve_external`
|
||||
(4.7 ms against the 3 975-file index), and ~6 ms dropping the previous
|
||||
revision's products on the request path (drop it after answering).
|
||||
Sections after §46 are planned when reached.
|
||||
|
||||
## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22
|
||||
@@ -5836,9 +5873,10 @@ document revision, computed only when a fix needs it
|
||||
— residues named, not hidden: the declaring file's parse (2.2–2.4 ms
|
||||
of the ports offer's 3.27) and the buffer's own share of the imports
|
||||
index (~0.8 ms), the second a `vlog_semantic` handshake request
|
||||
- [ ] lead ruling on a lint-result reuse item (new, from P1b's number:
|
||||
- [x] lead ruling on a lint-result reuse item (new, from P1b's number:
|
||||
24.0 ms, the whole of the pinmux row, for a client that sends no
|
||||
`only`) — a keyed cache in §59's shape, not this lane's to add
|
||||
— **closed by §61.2 (0.52.0): `lint_snapshot.rs`**
|
||||
- [x] QA (P1c): the every-offset parity suites re-attacked, the two
|
||||
counters sabotaged, the numbers re-taken on the same binary
|
||||
— 2026-09-07: ports side clean (three refusal fixtures old vs new
|
||||
@@ -6139,13 +6177,15 @@ semantic build/facts owners. Serialized after 60.1–60.3.
|
||||
true with no scan running), and the include graph and completion
|
||||
tables against a text-built pair on a tree with duplicate
|
||||
spellings and `+incdir+`s
|
||||
- [ ] the walk, filed by P4b3 for the next lane: `discovery` is 158 ms of
|
||||
- [x] the walk, filed by P4b3 for the next lane: `discovery` is 158 ms of
|
||||
scope walk plus one `fs::metadata` per file for the size cap, and
|
||||
it is the floor under every first useful answer. Two things to
|
||||
measure before building anything — the cap taking its size from the
|
||||
walk's own metadata (`lucisv_core::walk::collect_files` is not
|
||||
P4b3's file: a handshake request) and handing the first folder to
|
||||
`scan_step` before the walk has finished the workspace
|
||||
— **closed by §61.3 (0.52.0): two-phase discovery and the walk
|
||||
metadata hand-off (per-file `stat`s 3 979 → 0, cap 6.92 → 0.10 ms)**
|
||||
- [x] QA (P4a only, 2026-09-08: gates green, 4272/4272, no behaviour
|
||||
change verified by hunk review and by running both binaries —
|
||||
44/44 identical result_counts and identical scan file-counts;
|
||||
@@ -6166,7 +6206,736 @@ semantic build/facts owners. Serialized after 60.1–60.3.
|
||||
— 2026-09-08: nothing reopened it; the first-after-edit row after
|
||||
P1 is inside the frame, and no user command still blocks navigation
|
||||
for a whole scan on the startup path
|
||||
- [ ] `docs/perf/README.md` entry with the accepted numbers; topo
|
||||
- [x] `docs/perf/README.md` entry with the accepted numbers; topo
|
||||
edges/handshakes for every contract amended; the plan's status
|
||||
line updated; a release cut from the clean tree with its assets
|
||||
verified
|
||||
verified — done 2026-09-08: **0.51.0** (bc59336, v0.51.0), 8
|
||||
assets, the darwin-arm64 vsix at 0.51.0 with both binaries,
|
||||
`hierarchySections.js`, `extract.js`, no `*_test.js`.
|
||||
|
||||
## 61. Performance take 5 — the review round (owner request 2026-09-08)
|
||||
|
||||
`docs/performance_take5_review.md` (Codex, 2026-09-08, at 0.51.0) is the
|
||||
spec; its "Follow-up experiment queue" in `docs/perf/take5-tracking.md`
|
||||
(R1a–R4) is the ledger every lane fills; `docs/perf/take5-review-20260908/`
|
||||
is the baseline evidence (0.51.0 review cells are fixed). Same protocol as
|
||||
§60: serial lanes in the main tree, dev (Opus) → QA (Sonnet) → lead
|
||||
review → commit; a feature README per lane under
|
||||
`docs/features/perf5r-<lane>/`; every number by `tools/perf/` under
|
||||
`tools/guard.sh -m 8 -t 1800`, opentitan read-only, no build during a
|
||||
timed session, paired against the 0.51.0 review baseline cells;
|
||||
no `sleep` over 60 s, waits bounded and keyed on a PID or a file, never
|
||||
`pgrep -f`. Order chosen by cost-of-entry and what each measurement
|
||||
unlocks: the preflights first (cheap, large), then the action path, then
|
||||
the first answer, then the scan, then rename reuse if its measurement
|
||||
justifies it.
|
||||
|
||||
### 61.1 R3a + the refusal preflights (engine-owned)
|
||||
|
||||
Review §3 items 5–6. A `textDocument/rename` on a cursor with no symbol
|
||||
materializes the whole workspace (`server/rename.rs`: `rename_name_at`
|
||||
→ `None` → `ws.sources()`, 3 976 files) and the engine builds the scope
|
||||
(3 975 parses, 1.9 s) before `locate` refuses in 0.1 ms; the duplicate-
|
||||
module refusal and the "meaning would change" refusal take the same
|
||||
road; the extract at the `aes_wrap.sv` inline-site selection spends
|
||||
805 ms building a scope before its safety checks refuse. Files:
|
||||
`vlog_refactor/src/{rename/mod.rs,extract/mod.rs,lib.rs}`,
|
||||
`lucisv_server/src/{rename.rs,extract.rs}`, tests.
|
||||
- [x] engine-owned rename preflight over the request file alone (its
|
||||
parse + analysis; `prepare_rename_here` is the existing one-file
|
||||
shape — reuse it): `check_new_name`, then the cursor refusal, with
|
||||
today's error precedence (invalid new name → out-of-scope /
|
||||
unavailable file → no symbol here) and the exact sentences; the
|
||||
server calls it before selecting sources and materializes nothing
|
||||
when it refuses; a symbol found → today's path unchanged
|
||||
— `vlog_refactor::rename_preflight` (`rename/preflight.rs`), additive,
|
||||
**without** the `external`/`index` parameters the brief proposed: every
|
||||
refusal they could answer is one the staleness argument forbids taking,
|
||||
so they would have been unused. Takes rules 1, 4, 5, 6, 11a and — only
|
||||
for a non-file-scope declaration in the buffer — rule 2
|
||||
- [x] duplicate-declaration refusal moved ahead of materialization ONLY
|
||||
with the evidence the review asks for (the index is current and
|
||||
authoritative for that name — the workspace's `declared_twice`
|
||||
already gates the ports offer on it; state the argument or leave
|
||||
it on the slow road)
|
||||
— **left on the slow road, with the argument.** `state/mod.rs::set_document`
|
||||
reads the index and never writes it, so an unsaved edit that adds or
|
||||
removes a file-scope declaration is not in it; `rename` is the authority
|
||||
that re-derives the count. A wrong *offer* costs a lightbulb, a wrong
|
||||
*refusal* costs the work. `rstmgr_por` keeps its ~2.0 s, asserted by
|
||||
`a_name_declared_in_two_files_stays_on_the_slow_road`
|
||||
- [x] extract preflight: the selection's own checks that read only the
|
||||
request file's parse (the region, the item kinds, the refusal
|
||||
shapes `extract_site`/`Region::read` already know) run before
|
||||
`Scope::build`; exact refusal sentence preserved, no optimistic edit
|
||||
— **they already do, by two mechanisms**, which the new `extractrefuse`
|
||||
phase measures: `execute`'s `site_at` gate *is* `extract_site_in`, whose
|
||||
first two statements are the parse-diagnostic check and `Region::read`;
|
||||
and `plain_identifier`/occupied are `extract_module`'s own first
|
||||
statements, ahead of `Extraction::plan`. A preflight was written, wired,
|
||||
measured and **removed** as redundant
|
||||
- [x] measured: no-symbol rename ≤ 16 ms with zero closed-workspace
|
||||
parses; the `aes_wrap.sv` extract refusal with its parse count;
|
||||
the successful renames and the extract capture unchanged
|
||||
(fingerprints); R3a/R3c cells + experiment entries
|
||||
— no-symbol **2 012.3 → 0.34 ms**, `trace_parses` **3 975 → 0**,
|
||||
peak RSS 909 → 429 MiB, sentence identical. `aes_wrap.sv` extract
|
||||
refusal **761.1 → 767.8 ms (unchanged)**; its stage is
|
||||
`boundary::Crossing::read`, scope-dependent at depth — deferred to §61.5.
|
||||
All fingerprints identical (`b39defb21265…`, `fa7e31c78382…`,
|
||||
`090e92e7736e…`). R3a/R3c cells and both experiment records filed
|
||||
- [x] QA: refusal-precedence matrix old vs new (13 shapes: invalid name,
|
||||
keyword, unsaved/closed file, untitled, no symbol, comment, string,
|
||||
macro, duplicate module, existing name, same name, large-file
|
||||
buffer, cursor on a reference vs a declaration); parse counts;
|
||||
fingerprints; numbers re-taken
|
||||
— **PASS.** Rule table rebuilt independently from `renaming`/`Scope::
|
||||
locate`/`declaration` vs `rename_preflight`/`declared_here`, agrees
|
||||
with the dev's; oracle sabotaged twice (an invented refusal, a
|
||||
reworded sentence) and caught both; gates clean (fmt/clippy/4 322-test
|
||||
guarded run, matching a same-tree baseline + the 17 added tests
|
||||
exactly — the README's "4 328" was a slip, corrected); fresh guarded
|
||||
wire re-runs against the sha256-matched candidate binary over
|
||||
OpenTitan reproduce no-symbol 0/0 parses and ≤1 ms, the duplicate-
|
||||
module and common-port rows unchanged (3 975 parses, same sentence),
|
||||
the `aes_wrap.sv` extract refusal unchanged with its `Crossing::read`
|
||||
sentence, and the `aes.sv` capture fingerprint identical; all 12
|
||||
tracker R3a/R3c-x numbers and 5 fingerprints traced verbatim in
|
||||
`~/.cache/lucisv-perf/take5r-1/`. QA log in
|
||||
`docs/features/perf5r-preflight/README.md`
|
||||
|
||||
### 61.2 R1a + R1b — the code-action path on a large file
|
||||
|
||||
Review §1. `lint.rs::fixable` still runs `lint_with` on every request:
|
||||
23 of the 25 ms all-family menu on the pinmux comment; the first action
|
||||
after an edit is 136 ms. Files: `lucisv_server/src/{lint.rs,
|
||||
code_action.rs,fences.rs,server/dispatch.rs}` + a new small module for
|
||||
the snapshot; `state/` for one field at most; tests.
|
||||
- [x] R1b first: a `--verbose` stage trace for one `codeAction` on the
|
||||
pinmux comment — config/waiver load, dirty-buffer flush (the
|
||||
`Document` rebuild), lint, fence, serialization — for the first
|
||||
request, an unchanged repeat, the first after a one-character
|
||||
edit, and the definition queued behind each; harness rows
|
||||
— `lint_trace.rs`, one `timing: codeaction …` line per request that
|
||||
linted anything, two groups (`flush{…} action{…}`) divided by the
|
||||
flush; phases `actionprofile` and `ruleablation` in
|
||||
`tools/perf/phases_r1.py`. **The 23 ms is `lint_with`** (20.9 of 22.0;
|
||||
config I/O 0.04, run build 0.01, serialization 0.03, fence skipped) and
|
||||
**three semantic rules are the whole of it** — `unused-signal` +8.2,
|
||||
`multiply-driven` +7.5, `undriven-net` +7.4 ms over a 1.3 ms floor, the
|
||||
other 55 default rules ≤ +2.2 each. **The 136 ms is 78% the flush**:
|
||||
99.7 of 127.5 ms, of which 21.1 is the diagnostics pass, leaving
|
||||
~78.6 ms of `Document::new` on 1.3 MB; the handler then lints the same
|
||||
revision a **second** time for 20.2 ms. Deviation: the flush is one
|
||||
traced stage plus its parse count, not split into parse/analysis/overlay
|
||||
— those live in `state/mod.rs`, outside this lane's ownership, and
|
||||
flush-minus-diagnostics answers the question asked
|
||||
- [x] the dependency/invalidation table written BEFORE any cache:
|
||||
document content/revision, effective rules and options, tab width,
|
||||
external waiver contents, project/index inputs the workspace rules
|
||||
read (index generation); each row names the test that flips it
|
||||
— 14 rows in `docs/features/perf5r-lint-snapshot/README.md`, derived from
|
||||
the arguments of the `lint_with(ctx, rules, external)` call it guards, so
|
||||
the list is complete by construction. Three mechanisms only: **identity**
|
||||
(the buffer, `doc.large`, close/reopen — `set_document` builds a new
|
||||
`Document`), the **key by value** (rules, options, width, indent, waiver
|
||||
*contents*), and **one explicit drop** (`Document::refresh_overlay`, which
|
||||
every index mutation in `state/` already ends in). Row 12 is the one that
|
||||
decides the config question: the `lucisv.toml` and the waiver files are
|
||||
**not watched** (`watch::SOURCE_GLOB` is sources plus the filelist), so
|
||||
the per-request read is the only thing that ever notices them changing
|
||||
- [x] R1a: a lint-result snapshot keyed by that table, consumed by the
|
||||
diagnostics pass and the quick-fix discovery alike; recomputed on
|
||||
any mismatch; bounded (one per open document); the fence authority
|
||||
and execute-time validation untouched
|
||||
— `lint_snapshot.rs`: `Key` compared **by value, never hashed**, and
|
||||
`Slot`, one `Mutex<Option<…>>` field on the `Document`. One `found(doc,
|
||||
run)` in `lint.rs` that both doors call; the tab width moved onto the
|
||||
`LintRun` (read through `format::indent_width`, whose call the dispatcher
|
||||
no longer makes) so the two doors build the same context and share one
|
||||
slot. `fence.rs` and the shared-fence contract untouched; `vlog_linter`
|
||||
untouched
|
||||
- [x] measured: unchanged pinmux menu and queued definition ≤ 16 ms;
|
||||
first-after-edit improved and reported separately with its stage
|
||||
split; no stale diagnostic or fix under any invalidation; R1a/R1b
|
||||
cells + experiments
|
||||
— paired against trunk `51cbfd2`: **all families 22.61 → 0.98 ms
|
||||
(−95.6%)**, **quickfix only 24.51 → 0.11 (−99.5%)**, **queued definition
|
||||
22.39/22.38 → 0.78/0.76 (−96.5%)** — both gates met with two orders of
|
||||
magnitude of margin. **First-after-edit 125.65 → 106.89 ms (−14.9%)**,
|
||||
and its split names the remaining stage: ~84 ms `Document::new` plus the
|
||||
21.9 ms diagnostics pass, with the code-action lint at **0.00 ms**.
|
||||
Diagnostics publish +0.3%, idle RSS at 100 open buffers each holding a
|
||||
snapshot 574.0 → 574.6 MiB (+0.1%), take-3 `codeaction` cells within
|
||||
1.5%. Config-discovery memo **not taken**: the trace measures that I/O at
|
||||
0.04–0.16 ms and its failure mode would be a stale rule selection.
|
||||
R1a/R1b cells and both experiment records filed
|
||||
- [x] QA: every invalidation row forces a fresh result (change the
|
||||
buffer, the config, a waiver file, a dependency file the workspace
|
||||
rules read, close/reopen, a UTF-16 range); stale-fix attack; memory
|
||||
bound; numbers re-taken
|
||||
— PASS. All 14 rows attacked over real stdio JSON-RPC against the
|
||||
release binary on an independent fixture workspace (two standalone
|
||||
scripts, not the dev's own tests); three targeted sabotage cuts
|
||||
(waiver text, the `refresh_overlay` drop, `tab_width` in the key)
|
||||
each caught by exactly the predicted test and reverted clean; gates
|
||||
cross-checked against a from-scratch clone of `51cbfd2` with
|
||||
matching binary sha256es and a name-level test diff (+21/-0);
|
||||
100-buffer RSS and the stage trace reproduced independently within
|
||||
noise; 12 tracker numbers traced verbatim (some as documented
|
||||
medians) in `~/.cache/lucisv-perf/take5r-2/`; opentitan clean and
|
||||
zero guard kills throughout. QA log in
|
||||
`docs/features/perf5r-lint-snapshot/README.md`
|
||||
|
||||
### 61.3 R2a + R2b — the first useful answer
|
||||
|
||||
Review §2. Warm first answer 325 ms = 205 ms workspace discovery +
|
||||
92 ms store open before the open buffer's folder is even stepped.
|
||||
Files: `lucisv_core/src/walk.rs` (an additive handshake: hand on the
|
||||
metadata the walk already stat'd), `lucisv_server/src/{state/,
|
||||
scan_order.rs,server/startup.rs,server/index.rs,index_cache.rs}`, tests.
|
||||
- [x] R2a: measure the walk's stages (gitignore/config handling, the
|
||||
size-cap `metadata` per file, path sorting) and the store open;
|
||||
then the walk metadata hand-off (one `stat` per file, not two) —
|
||||
the handshake recorded in `lucisv_core`'s README and topo before
|
||||
the interface changes — **the split says the cap's second `stat` is
|
||||
6.9 ms of a 165 ms discovery, not the ~45 §P4b3 guessed, and the
|
||||
walk is 95 % of it; the hand-off (`collect_files_with`, additive)
|
||||
takes `stats` 3 979 → 0 and `cap` 6.92 → 0.10 ms, and the first
|
||||
answer does not move. Kept as a tidy-up; R2b is the lever.** The
|
||||
handshake went into the code's doc comments as the interface
|
||||
changed and into the feature README after, not before — recorded
|
||||
as a deviation; the topo edge is a request for the lead
|
||||
- [x] R2b: the raised-folder work begins before the remaining discovery
|
||||
finishes — one coherent scan (the folder walked, stepped and
|
||||
published first; the rest of the workspace discovered and stepped
|
||||
after; paths and facts deduplicated; configured scope, exclusions,
|
||||
filelists, size cap, unsaved-buffer precedence preserved; never two
|
||||
complete scans, never an answer from only the open file); if the
|
||||
store open remains the barrier, a measured design for bounded
|
||||
local-record loading before any format change — **shipped, bounded
|
||||
twice (rung 2 only, strict descendants of a root only,
|
||||
`HEAD_WALK_MAX` 512) and `collect_files_below` carries the root's
|
||||
`.gitignore` down so the two halves of one scan cannot disagree
|
||||
about which files exist. `OPENING_FILE_WAIT` (25 ms, inside the
|
||||
staging window) closes the didOpen-vs-configuration race that left
|
||||
2 sessions in 8 paying the old cost. The store open is 61 ms of
|
||||
checksum: the bounded local load was designed and measured (~26 ms,
|
||||
~50 ms first answer) and NOT shipped — it moves cost rather than
|
||||
removing it and changes `Load::canonical`, which the compaction
|
||||
skip and the byte-identical store rest on. Filed as its own
|
||||
experiment.**
|
||||
- [x] measured: first definition ≤ 200 ms warm and cold, equal to the
|
||||
settled target (not merely non-empty); warm quiet scan ≤ 1.0 s if
|
||||
reachable, reported honestly; RSS reduction kept; startup ordering
|
||||
cases (config before/after didOpen, late/no reply, unsaved buffer,
|
||||
multiple folders, root-level file, a dependency outside the first
|
||||
folder) pinned; R2a/R2b cells + experiments — **first definition
|
||||
265.9 → 77.9 ms cold (−70.7 %) and 301.3 → 115.1 warm (−61.8 %),
|
||||
result count 1 in 12 of 12; warm quiet settle 1 033.9 → 997.4 ms
|
||||
(≤ 1 s, first time, by less than the spread); idle RSS −8.6 % cold;
|
||||
store byte-identical (three sha256s over 28 stores); 24 of 24 scope
|
||||
cells; `mismatched_answers` 0 AND the new stricter
|
||||
`unsettled_answers` 0. Named costs: settled +2.5 % / +4.8 % at 1/10
|
||||
open buffers (the neighbourhood subtree walked twice), and the
|
||||
"equal to the settled target" gate is met on the measured cursor
|
||||
and all 54 probe requests but is NOT true by construction for a
|
||||
cross-folder cursor — pinned by a test and filed as a
|
||||
`server/dispatch.rs` handshake.** Feature README
|
||||
`docs/features/perf5r-first-answer/`; 4 343 → 4 360 tests
|
||||
- [x] QA: the ordering matrix; coherence (`mismatched_answers` 0 with the
|
||||
settled-equality check, not the non-empty one); persistence
|
||||
attacks re-run; numbers re-taken
|
||||
— PASS. Gates green (4 360 tests, +17/−0 vs `a1c77c0`, fmt/clippy
|
||||
clean); walk hand-off sabotage caught by exactly the predicted 12
|
||||
tests; `collect_files_below` attacked with 5 fixtures beyond the
|
||||
dev's own 4 (nested exclusion, intermediate `.gitignore`, symlink
|
||||
outside root — pinned, agrees with the plain walk, not a
|
||||
regression — missing folder, `gitignore:false`), all correct;
|
||||
`HEAD_WALK_MAX` fallback has **no shipped test** but independently
|
||||
verified correct via a constructed fixture (filed for the lead);
|
||||
ordering matrix (a–h) read and sampled across 17 wire tests, `f`
|
||||
pinned (`open_next` finishes the *whole* pending discovery before
|
||||
reordering, never a targeted walk); `unsettled_answers` confirmed
|
||||
to count empty mid-scan answers against a non-empty settled one;
|
||||
cross-folder `[]` exception reported, not failed; `index_cache.rs`
|
||||
diff confirmed empty; opentitan clean, zero guard kills. QA log in
|
||||
`docs/features/perf5r-first-answer/README.md`
|
||||
|
||||
### 61.4 R4 — publication cost under load
|
||||
|
||||
Review §4. Files: `tools/perf/` (a fixed-arrival-rate probe), then
|
||||
`lucisv_server/src/{server/index.rs,state/,candidates.rs,includes.rs}`.
|
||||
- [x] the probe: a definition every N ms of wall clock (not after the
|
||||
previous response), recording queue latency, publications, per-
|
||||
publication cost (index absorb / candidates / includes / overlays)
|
||||
and scan completion under the same offered load, 1 / 10 / many
|
||||
buffers — **`tools/perf/phases_r4.py`: `scanload` (warm),
|
||||
`scanloadcold`, `scanloadcross`, plus a quiet control in the same
|
||||
series. A fixed request *count* over a fixed window, because the
|
||||
first draft stopped sending when the server went quiet, which made
|
||||
the offered load a function of the server — `scanserve`'s own
|
||||
confound in a new place. The split at `eb54042`, warm, one open
|
||||
buffer, a definition every 100 ms: 34 publishes, `absorb` 2 433 ms
|
||||
(78 %), `candidates` 623 (20 %), `includes` 47, `overlay` 2.4
|
||||
(0.08 %) — 3 105 ms of publication in a 4 206 ms scan whose quiet
|
||||
form takes 1 005. Cold: 88 publishes, 7 973 of 10 675 against a
|
||||
2 766 ms quiet scan. `absorb` is the cost because it ends in a
|
||||
whole-index merge; the overlay refresh, which this item expected to
|
||||
matter, is 0.08 % at one buffer and 9.6 % at 101**
|
||||
- [x] then reduce duplicate publication work (incremental candidates and
|
||||
includes tables, or a bounded publish cadence) preserving the
|
||||
coherent-prefix contract; quiet-scan decode/merge only after an
|
||||
allocation profile shows duplication — **the cadence
|
||||
(`Scan::publish_is_due`, `PUBLISH_EVERY` 512): one merge per 512
|
||||
staged records instead of one per burst of requests, with the drain
|
||||
that has something *waiting* — the session's first useful answer —
|
||||
exempt. A quiet scan still publishes nothing. The candidates
|
||||
rebuild and the overlay refresh were **measured and not rebuilt**:
|
||||
the cadence takes both down with it, and the overlay is noise at
|
||||
every buffer count an editor has. `WorkspaceIndex::absorb`'s
|
||||
whole-index merge is named as a finding for a later lane —
|
||||
`update_facts` has a targeted merge beside it and `absorb` does
|
||||
not, but that is a `vlog_semantic` change this lane may not make**
|
||||
- [x] measured: same offered load, better queue latency AND completion;
|
||||
never fewer served requests reported as a speedup; R4 cells —
|
||||
**same offered load, requests answered equal in every cell:
|
||||
publication −78 to −88 %, the traced scan −48 to −65 %, the median
|
||||
request wait −98 to −99.5 % (warm 112.3 → 1.9 ms at one buffer,
|
||||
1 960 → 10.4 at 101; cold 137.7 → 1.5, and 4 706 → 2.1 at two).
|
||||
Across the sixteen loaded cells the tail improved in ten, was level
|
||||
in two and rose in four — three of them single-open-buffer cells,
|
||||
worst warm 168 → 422 ms, against cold 9 308 → 1 583 at 101 buffers.
|
||||
Quiet warm scan 1 005 → 985 ms (≤ 1 s kept), quiet cold 2 724 →
|
||||
2 694, first useful answer 78.2 → 80.8 cold / 115.1 → 115.8 warm,
|
||||
idle RSS −0.2 %, store size identical, 24 of 24 scope cells equal,
|
||||
`scanserve` cold median 122.2 → 45.6 with the same 13 requests
|
||||
served. `mismatched_answers` 0 and `unsettled_answers` 0
|
||||
everywhere — and on a new cross-folder cursor the reference is
|
||||
unsettled 12 of 270 with one buffer and 270 of 270 with eleven
|
||||
where the candidate is 0. Feature README
|
||||
`docs/features/perf5r-publication/`; 4 360 → 4 365 tests**
|
||||
- [x] the lead's §61.3 rulings, both on this drain path: **an empty
|
||||
navigation answer computed mid-startup-scan is not answered — the
|
||||
request is asked again at the next publish and at the latest when
|
||||
the scan ends, where `[]` is honest. Three methods
|
||||
(definition / typeDefinition / references), a hover untouched and
|
||||
pinned. The `HEAD_WALK_MAX` fixture QA asked for is in
|
||||
`server/tests/startup.rs` and was sabotage-checked**
|
||||
- [x] QA: coherence under load; the probe's arrival discipline verified;
|
||||
numbers re-taken — **PASS. Coherence sabotage-tested (a direct
|
||||
index/candidates-agreement test, failed when `publish_scan`'s
|
||||
candidates absorb is disabled). The "never re-ask" sabotage produces
|
||||
the lost-request failure this task guards against; the shipped rule
|
||||
does not. `HEAD_WALK_MAX` sabotage reproduces "515 files (the folder
|
||||
first)". `scanload`/`scanloadcross` re-run independently on the dev's
|
||||
own binaries: `mismatched_answers` 0 and `unsettled_answers` 0 for the
|
||||
candidate in every cell, matching the archived record. Quiet
|
||||
scan/RSS controls re-run within ±10% (widest +6.9%). Tail
|
||||
characterized: the CAND max attributed to cadence spacing, not
|
||||
deferral; a T=100 ms secondary bound estimated to give back most of
|
||||
this cell's publication win since the reference's own pre-cadence
|
||||
publish spacing (~123 ms) is already close to 100 ms. One
|
||||
non-blocking gap found and pinned by a new test: a `$/cancelRequest`
|
||||
against a request sitting in `Server::deferred`, arriving outside a
|
||||
batch that reunites it with a publish, is silently ineffective
|
||||
(exactly-one-response held; `cancel-request`'s README needs a dated
|
||||
amendment, filed as a handshake). QA log in
|
||||
`docs/features/perf5r-publication/README.md`**
|
||||
|
||||
### 61.5 R3b + R3c — rename scope reuse (conditional)
|
||||
|
||||
Review §3 items 1–4, after 61.1's measurement of the 229 ms scope stage
|
||||
(parse / analysis / index assembly / allocation split). Request-local
|
||||
reuse of open documents' analyses and closed files' cached facts, tied
|
||||
to the selected source bytes, unsaved-buffer precedence kept, cross-file
|
||||
resolution rebuilt for the candidate workspace, a memory budget stated;
|
||||
the 51 ms warning pass profiled and tightened without changing a
|
||||
sentence; the selection set stays the correctness reference (P2d).
|
||||
- [x] lead ruling from 61.1's split: go / defer — **go — 34.3 %.** The
|
||||
tail rename's 242.4 ms scope stage is `lead` 0.4 + `kept` 133.5 +
|
||||
**`other` 83.1** + `merge` 23.4, where `other` is the 103 container
|
||||
files analysed for their index record and never read again; 83.1 /
|
||||
242.4 = 34.3 %, against a 30 % condition. Agreed by every other
|
||||
multi-file row (25.0 / 33.0 / 35.8 / 36.0 %, and **87.8 %** on the
|
||||
duplicate-module refusal); 0 % on the two rows where every selected
|
||||
file spells the name, which is the case the reuse is not for. The
|
||||
split is now shipped in the engine's trace (`IndexTrace`,
|
||||
`WarnTrace`), and a trace-only build put the inside of one analysis
|
||||
at **lex 34 %, parse 32 %, analyse 20 %, read-off 13 %** — the
|
||||
review's "parser versus index" question answered as *parser*. The
|
||||
49.7 ms warning pass is **84 % the macro-argument scan**, which is
|
||||
one per-file lex already shared by all five scans (§P2d): no
|
||||
duplicated work left in it, and retaining tokens instead is refused
|
||||
on the `clk_i` row's 1.9 GiB peak
|
||||
- [x] if go: the reuse, ≥ 20 % wire-time on the large rename at bounded
|
||||
peak RSS, ordinary / common-port / collision / macro-bind /
|
||||
hierarchical-tail / fallback cases compared, verifier untouched —
|
||||
**shipped as an engine door (`vlog_refactor::KnownFacts`) with one
|
||||
server implementation: a caller may hand back the index record it
|
||||
holds for exactly the bytes it is handing over, and the engine skips
|
||||
that file's parse. The tie is `IndexCache`'s own store entry —
|
||||
record and FNV-1a written by one read and compared in one function —
|
||||
never the workspace index's record, which carries no hash. No
|
||||
persistent decoded-analysis cache; nothing retained past the
|
||||
request; unsaved-buffer precedence falls out of the content key.
|
||||
Paired against `07ef771` with the order alternated per phase: tail
|
||||
**380.2 → 314.0 ms (−17.4 %)**, parses **240 → 137** = `(K − 103) +
|
||||
E`; fallback `clk_i` −17.4 %, conflict −18.8 %, new-name-many-uses
|
||||
−18.5 %, duplicate-module refusal **2 053 → 695 ms (−66.1 %, 3 975
|
||||
→ 14 parses)**; `aes` −0.5 %, extract refusal −0.7 %, resolves
|
||||
within ±1.4 %; peak RSS lower or level everywhere. Parity: 36 rows
|
||||
equal on fingerprint/message/status/counts/titles and **1 750
|
||||
warning sentences compared line by line** by a new `renamewarn`
|
||||
phase — identical. `check/` no diff. **The ≥ 20 % gate is missed at
|
||||
−17.4 %** against the paired reference (−21.2 % against the review's
|
||||
own 398.3 baseline; the absolute ≤ 318 ms form met at 314.0), and
|
||||
the remaining stage is named: the reuse's own **31.1 ms of store
|
||||
decode**, the price of the one-place tie. Collateral for the other
|
||||
refactorings **not taken** — measured nil, and reaching them needs a
|
||||
`_with` entry point in five files this lane does not own. Feature
|
||||
README `docs/features/perf5r-scope-reuse/`; 4 366 → 4 374 tests**
|
||||
- [x] QA — **PASS** (2026-09-09). The tie verified as one comparison
|
||||
(`entry_for`) fed by one store entry, never the workspace index;
|
||||
stale-disk, unsaved-buffer, misfiled-record and identical-content
|
||||
cross-path attacks all forgiven correctly; two sabotage variants
|
||||
(hash check removed; workspace-index record substituted) both caught
|
||||
by existing tests. Index equality re-checked at the query level
|
||||
(`defines`, `member`, `references_to`, `members_of_chain`,
|
||||
`hierarchical_declarations`) over a macro-table + re-export fixture.
|
||||
`check/` no diff; `(K-reused)+E` formula sabotage-verified. 36-row and
|
||||
1 750-sentence parity, and the 34.3 % go arithmetic, re-derived from
|
||||
raw evidence, not just read. Three QA-chosen renames (wildcard
|
||||
import, bind-visible name, two-level hierarchical tail) run directly
|
||||
against the real opentitan tree: byte-identical outcomes across
|
||||
no-reuse/full-reuse/half-reuse. One out-of-scope observation flagged
|
||||
separately (a bind-file's own occurrence going unedited/unwarned,
|
||||
reproducible at HEAD, unrelated to the reuse door). Full log:
|
||||
`docs/features/perf5r-scope-reuse/README.md`'s QA log.
|
||||
|
||||
### 61.6 Closing
|
||||
|
||||
- [x] `docs/perf/README.md` entry; topo for every contract amended; the
|
||||
review's status line; release 0.52.0 with assets verified — entry,
|
||||
topo and status lines done 2026-09-09; **0.52.0** released
|
||||
(b12e0cc, v0.52.0): 8 assets, the darwin-arm64 vsix at 0.52.0 with
|
||||
both binaries, `hierarchySections.js`, `extract.js`, no `*_test.js`.
|
||||
|
||||
## 62. The 0.52.0 review (Codex, 2026-09-09) — F1/F2/F3 and the next lanes
|
||||
|
||||
`docs/performance_052_review.md` (findings F1–F3, next actions 3–5) and
|
||||
`docs/052_implementation_plan.md` (the other agent's plan; its Phase 1
|
||||
was implemented in the tree before the lead saw it) are the spec; the
|
||||
tracker's "Follow-up findings" and N1–N3 rows are the ledger; evidence in
|
||||
`docs/perf/review-052-20260909/`. Same protocol as §60/§61.
|
||||
|
||||
### 62.1 F1 — directory aliases in the split startup scan (correctness)
|
||||
|
||||
The neighbourhood walk and the rest walk had separate visited sets, so a
|
||||
directory reachable by two spellings (`a_alias -> z_real`) was indexed
|
||||
twice at startup: two definition targets, a false "declared in more than
|
||||
one file" rename refusal, healed only by a rescan. Fix (the other agent +
|
||||
the lead's finishing lane): one `DirectoryTracker` shared across both
|
||||
walks; a pre-check that falls back to the single canonical walk when an
|
||||
alias sorts before the open folder or an ancestor; the `HEAD_WALK_MAX`
|
||||
fallback discards the head instead of unioning it; an alias found only
|
||||
by the rest walk requests an ordinary rescan so path spellings converge;
|
||||
the open-buffer alias check stats only same-named files.
|
||||
- [x] tracker shared, pre-check, fallback, conflict → rescan; `stats` 0
|
||||
on opentitan again; discovery and the 100-buffer cell unchanged
|
||||
- [x] fixtures: alias before / after / multiple / ancestor / sibling
|
||||
(outside the chain) / cycle / ignore rules / unsaved buffer /
|
||||
genuine duplicate declarations (still refused) — startup, rescan
|
||||
and restart agree on index paths, definitions and prepareRename
|
||||
- [x] QA: the matrix re-attacked, stat counts, numbers re-taken
|
||||
|
||||
### 62.2 F2 + F3 — the load probe (harness)
|
||||
|
||||
- [x] F2: a warm `scanload` cell primes an empty store untimed; per-trial
|
||||
cache hits/misses in the row; a warm trial with 0 hits is an error
|
||||
- [x] F3: scan completion stamped from the scan's own end event, not the
|
||||
request window; responses partitioned by it; arrival stamps kept
|
||||
- [x] QA: a brand-new store, a window longer than the scan
|
||||
|
||||
### 62.3 N1–N3 — deferred to loop 3 unless the owner asks
|
||||
|
||||
N1 the dirty-buffer parse (114 ms first-after-edit), N2 the retained-
|
||||
analysis parse work and the 31 ms facts decode, N3 the whole-index merge
|
||||
per publication. Filed with the review's baselines; not started.
|
||||
|
||||
### 62.4 Closing
|
||||
|
||||
- [x] `docs/perf/README.md` note; topo (the walk tracker); release 0.53.0
|
||||
with assets verified — done 2026-09-09: **0.53.0** (b4a0668,
|
||||
v0.53.0), 8 assets, the darwin-arm64 vsix at 0.53.0 with both
|
||||
binaries, `hierarchySections.js`, `extract.js`, no `*_test.js`.
|
||||
|
||||
## 63. Loop 3, round 1 (planned 2026-09-11) — the `bind` rename gap, then N1
|
||||
|
||||
Two lanes, serial, in the main tree (§36's protocol: one dev (Opus), then
|
||||
one QA (Sonnet), then the lead's review; dev and QA both through
|
||||
`tools/guard.sh`; no `sleep` over 60 s; no `pgrep -f`). Ships as 0.54.0.
|
||||
|
||||
### 63.1 A `bind` file's own occurrence of a renamed name (QA `task_834abda3`)
|
||||
|
||||
Found by §61.5's QA on the real opentitan tree, reproducible at HEAD and
|
||||
unrelated to facts reuse. Renaming `entropy_masking_req` (a net declared in
|
||||
`hw/ip/aes/rtl/aes.sv`) edits `aes.sv` but leaves `hw/ip/aes/dv/aes_bind.sv`'s
|
||||
`.entropy_masking_req(entropy_masking_req)` — the expression half of a
|
||||
connection inside `bind aes aes_reseed_if u_aes_reseed_if (…)`, which the
|
||||
binder resolves in the bind target's scope (`Target::BindScope { target:
|
||||
"aes" }`, `vlog_semantic/src/resolve.rs`) — neither edited nor warned about.
|
||||
Renaming `seed_en` (declared in `aes_prng_clearing.sv`) leaves the same file's
|
||||
two-level tail `u_aes_core.u_aes_prng_clearing.seed_en` neither edited nor
|
||||
warned about, while §49's hierarchical tail from an ordinary instantiating
|
||||
file (`u_entropy_src_main_sm.state_q` in `entropy_src_core.sv`) is edited.
|
||||
The whole-scope engine is the refusal authority, so a silent miss is a
|
||||
wrong answer: after the rename the design no longer elaborates.
|
||||
|
||||
The contract to reach: an occurrence in a `bind` directive's connection is
|
||||
**edited** when the engine resolves it to the renamed declaration — a bare
|
||||
name in the bind target's scope, or a hierarchical path whose root is the
|
||||
bind target (the target module, a `: u_x` instance list, or a hierarchical
|
||||
target path) — through the same rungs an instantiating file's occurrences
|
||||
use; **warned about** (file:line, the sentence shape `rename/warnings.rs`
|
||||
already uses) when the name occurs in a `bind` connection the engine cannot
|
||||
resolve; never silent. Source selection (`rename_sources_traced`'s rungs,
|
||||
`module_select::hierarchical_users`, `files_mentioning`) must bring the
|
||||
`bind` file in — find out which rung drops it before adding one. Refusal
|
||||
parity with `rename_preflight` stays one-directional (the preflight may
|
||||
refuse only what the engine refuses); `check/after.rs`'s rebinding check
|
||||
runs over the edited `bind` file like any other.
|
||||
|
||||
Feature README: `docs/features/rename-bind-occurrences/README.md`. Files:
|
||||
`crates/vlog_refactor/src/{rename/,references.rs,scope.rs,check/}`,
|
||||
`crates/vlog_semantic/src/{resolve.rs,workspace/}` only if a resolver rung is
|
||||
missing (a Handshake entry in the README either way),
|
||||
`crates/lucisv_server/src/{rename.rs,rename_trace.rs,module_select.rs,state/}`
|
||||
for selection, `tools/perf/` only to add a fixture row. Nothing else.
|
||||
|
||||
- [x] the reproduction pinned first: engine-level fixtures in
|
||||
`vlog_refactor` (a `bind` file beside the declaring file) for the
|
||||
bare-name connection, the positional connection, the two-level tail,
|
||||
a `: u_x` instance-list target, a hierarchical target path, a `bind`
|
||||
inside a generate block (`if (…) begin : gen … end`), and one the
|
||||
engine must *not* resolve (a bind whose target module is not in the
|
||||
workspace) — each asserting today's silent miss, then flipped
|
||||
- [x] the fix: occurrences resolved through `Target::BindScope` and tails
|
||||
rooted at the bind target edited; unresolvable ones warned about;
|
||||
the rung that dropped `aes_bind.sv` named in the README
|
||||
- [x] parity: `renamewarn`'s 1 750 sentences and the 36-row `paired`
|
||||
fingerprints re-taken against 0.53.0 — every difference is a `bind`
|
||||
file's new edit or warning and is listed in the README, nothing else
|
||||
moves; the eight rename shapes' timings within noise (the tail rename
|
||||
≤ 330 ms median)
|
||||
- [x] the three QA renames (`WidthPRDSBox`, `entropy_masking_req`,
|
||||
`seed_en`) run against the real opentitan tree through
|
||||
`rename_traced_with` under all three reuse modes: identical answers,
|
||||
and `aes_bind.sv` now edited
|
||||
- [x] QA: fixtures re-attacked (a `bind` whose connection names a
|
||||
*different* declaration of the same name; the new name colliding in
|
||||
the bind target's scope — refused; an escaped-name target; a
|
||||
`defparam`-only bind file), parity re-derived, opentitan sweep
|
||||
|
||||
### 63.2 N1 — the first request after an edit (the 0.52.0 review, item 3)
|
||||
|
||||
The review's cell: `pinmux_reg_top.sv` (40 267 lines), one-character
|
||||
`didChange`, then the all-family `codeAction` menu — **113.6 ms**, against
|
||||
0.23 ms for the unchanged repeat. The lint snapshot cannot help a fresh
|
||||
revision; what remains is the debounced `Document::new` the request wrapper
|
||||
performs before any handler runs (`tokenize`, `parse_tolerant` over a clone
|
||||
of the token stream, `collect_defines`, `analyze`, `resolve_external`,
|
||||
`LineIndex::new`), the diagnostics publish that lints the new revision, and
|
||||
the menu's own stages. `crate::lint_trace` already splits the request into
|
||||
flush / config / build / lint / fence / serialize under `--verbose`; the
|
||||
flush's inner stages are not yet split.
|
||||
|
||||
Target: ≥ 15 % off the first-after-edit cell (stretch < 95 ms) with the
|
||||
AST, the diagnostics and the menu byte-identical; the unchanged-repeat cell
|
||||
and every other `offeredit`/`offerkinds` row within noise; peak RSS not up.
|
||||
Measure before building: split the flush in `lint_trace` (lex / parse /
|
||||
defines / analyze / external / lines / publish-lint), take the numbers on
|
||||
0.53.0, and go after the largest stage. Candidates, in the order the review
|
||||
named them: the token-stream clone into `parse_tolerant` (borrow or hand
|
||||
over, keeping `Document::tokens`), allocation in `tokenize`/`parse_tolerant`
|
||||
for a 40 k-line generated file, `analyze`'s tables, `resolve_external`
|
||||
against a 3 975-file index, a second lint of the same revision anywhere on
|
||||
the path (the snapshot must serve both the publish and the menu — verify it
|
||||
does). A change in `vlog_parser`'s public signatures is a Handshake in the
|
||||
README and a topo row. No stopwatch assertions in tests.
|
||||
|
||||
Feature README: `docs/features/perf-first-after-edit/README.md`. Files:
|
||||
`crates/lucisv_server/src/{lint_trace.rs,state/mod.rs,server/,diagnostics.rs,
|
||||
code_action.rs}`, `crates/vlog_parser/src/{lexer.rs,parser/,lib.rs}`,
|
||||
`crates/vlog_semantic/src/{analyze*,bind/}` only for a measured stage,
|
||||
`tools/perf/` for the flush split rows. Nothing else.
|
||||
|
||||
- [x] the flush split in `lint_trace` and a harness row per stage; the
|
||||
0.53.0 numbers in the README before any change — `Rebuild`'s seven
|
||||
stages (`lex parse defines analyze external lines publish`) plus
|
||||
`documents`, printed as a **third sibling group** `rebuild{…}` on
|
||||
the `timing: codeaction` line, which `phases_r1.actionprofile`
|
||||
picks up as `trace_rebuild_*` with no harness code change
|
||||
(`phases_p2.parse_trace` flattens one level). **The 100 ms flush on
|
||||
0.53.0: lex 29.1, parse 25.6, publish 22.2 (lint 22.0), analyze
|
||||
10.1, external 4.8, lines 0.6, defines 0.5, ~7 dropping the old
|
||||
revision.** Two of the review's candidates were answered by the
|
||||
split: `action` reads `snapshot=hit`/`lint=0.00ms` (no second lint
|
||||
of the revision) and `lint::context` already lends `doc.semantics`
|
||||
(no second analysis)
|
||||
- [x] the fix, one stage at a time, each with its before/after cell;
|
||||
parser snapshot and idempotency suites green; corpus and opentitan
|
||||
byte-identity gates — three changes, all in `vlog_parser`: the
|
||||
lexer's two phases **fused** (the intermediate `Vec<RawTok>` gone;
|
||||
`tokenize` 27.8 → 24.7 ms), **`Parser::skip`** for the 178
|
||||
`bump()` sites that threw the token away (`parse_tolerant` 17.5 →
|
||||
16.0 ms), and a **first-byte test in front of the 44-entry
|
||||
operator table** (24.7 → **11.6 ms**, the largest single win).
|
||||
Parity: token stream + parse diagnostics + whole AST + symbol
|
||||
table digested per file over **4 807 files** (corpus + opentitan),
|
||||
0 differ; `format --stdout` byte-identical over corpus (860) and
|
||||
over opentitan (one tree digest, identical stderr); diagnostics
|
||||
and the all-family + seven-family menus identical on the pinmux,
|
||||
aes and tb buffers before and after an edit, including a revision
|
||||
edited to *have* lint findings. 4 403 → **4 406 tests**
|
||||
- [x] `offeredit`, `offerkinds`, `flush`, `diagnostics` phases paired
|
||||
against 0.53.0 with the order alternated; RSS cell — the cell
|
||||
**110.95 / 107.54 → 88.31 / 88.36 ms, −19.2 %**: the ≥ 15 % gate
|
||||
met and the < 95 ms stretch met. The unchanged-repeat cell
|
||||
(0.27/0.32 → 0.22/0.19) and every `offeredit`/`offerkinds`/
|
||||
`flush`/`diagnostics` row are inside their own version's a/b
|
||||
spread. RSS **not up**: warm flat (≈428 MiB both), cold scan
|
||||
~25 MiB *lower* (506 → 480 MiB) — the `Vec<RawTok>` that is no
|
||||
longer built; index store byte-identical at 45 468 KiB. Feature
|
||||
README `docs/features/perf-first-after-edit/`; evidence and
|
||||
runners in `~/.cache/lucisv-perf/63-2/`
|
||||
- [x] QA: the trace's arithmetic re-derived, the parity attacked (a buffer
|
||||
that fails to lex; a `` `define`` edit that changes the macro table;
|
||||
an edit that moves a fence), the numbers re-taken
|
||||
|
||||
### 63.3 Closing
|
||||
|
||||
- [x] `docs/perf/README.md` entry; topo rows for every contract amended;
|
||||
release 0.54.0 with assets verified — done 2026-09-12: **0.54.0**
|
||||
(da32237, v0.54.0), 8 assets, the darwin-arm64 vsix at 0.54.0 with
|
||||
both binaries, `hierarchySections.js`, `extract.js`, no `*_test.js`.
|
||||
|
||||
## 64. Loop 3, round 2 (planned 2026-09-12) — cross-file references for hierarchical-surface-only declarations
|
||||
|
||||
One lane. The dev half runs in the owner's spawned session
|
||||
(`task_d8afe80f`, its own worktree); QA (Sonnet) and the lead's review run
|
||||
on that result in the main tree after it lands. Same rules as §63: guard
|
||||
every suite and sweep, no `sleep` over 60 s, no `pgrep -f`, opentitan
|
||||
read-only. Ships as 0.55.0.
|
||||
|
||||
### 64.1 `references` stops at the connection surface (QA §63.1, `task_d8afe80f`)
|
||||
|
||||
`crates/lucisv_server/src/nav.rs`: `leaves_this_file` (~148) and
|
||||
`indexed_def_in_file` (~235; `indexed_def_for_symbol` is shared with
|
||||
`hover.rs`) decide whether a declaration can be referenced from another file
|
||||
by `WorkspaceIndex::member(unit, name)` — the **connection** surface, ports
|
||||
and parameters. A module's net, variable or instance lives on the
|
||||
**hierarchical** surface only (`workspace/hierarchy.rs`, since 2026-09-05), so
|
||||
both functions treat such a declaration as unable to leave its file. Two
|
||||
symptoms, pinned by
|
||||
`nav.rs::a_binds_connection_expression_is_reachable_by_definition_not_yet_by_references`:
|
||||
`references` from the *declaration* of a hierarchically reached net falls to
|
||||
the single-file fallback and never sees a cross-file use (a `bind`
|
||||
connection or an ordinary `u_x.sig` tail alike); `references` from a *use*
|
||||
that does resolve cross-file cannot re-identify the open buffer's own
|
||||
in-file use of the same declaration, because `indexed_def_in_file` maps the
|
||||
live symbol back the same wrong way. Not `bind`-specific; reproduced with a
|
||||
plain `assign w = u_leaf.sig;`.
|
||||
|
||||
The contract to reach: a declaration's cross-file reachability is judged on
|
||||
the surface a use can actually reach it by — `member_in(unit, name,
|
||||
Surface::Hierarchical)` in both call sites (the connection answer is a prefix
|
||||
of the hierarchical one, so package/class/struct members and ports keep
|
||||
their answers byte-for-byte). `references_are_ambiguous` and the
|
||||
single-record rule (`defs.len() != 1`) keep their meaning over the wider
|
||||
answer — a name declared both as a port and as an internal net of the same
|
||||
unit is ambiguous, not silently the port. Hover and definition, which share
|
||||
`indexed_def_for_symbol`, must not change what they say for anything they
|
||||
already answered. No new index field, so no `FACTS_FORMAT` bump; if one
|
||||
turns out to be needed, say why in the README.
|
||||
|
||||
Feature README: `docs/features/references-hierarchical-surface/README.md`.
|
||||
Files: `crates/lucisv_server/src/{nav.rs,hover.rs}` and the server's wire
|
||||
tests (`server/tests/`), `crates/vlog_semantic/src/workspace/hierarchy.rs`
|
||||
only if `member_in` needs a case it lacks (a Handshake entry either way).
|
||||
Nothing else.
|
||||
|
||||
- [x] the fixture sweep first, asserting today's answers, then flipped:
|
||||
`definition`, `references` (from the declaration and from each use,
|
||||
`includeDeclaration` both ways), `hover`, `documentHighlight` over
|
||||
(a) a `bind` connection's bare name, (b) a `u_x.sig` tail from an
|
||||
instantiating file, (c) a two-level tail, (d) a port of the same
|
||||
unit (unchanged answers), (e) a package member (unchanged), (f) a
|
||||
name that is both a port and an internal net of one unit (ambiguous
|
||||
— the single-file fallback, as today), (g) an unsaved buffer
|
||||
(`untitled:`), (h) the open buffer's own in-file use seen from a
|
||||
cross-file use
|
||||
- [x] the fix in both call sites; the §63.1 QA test renamed to say what it
|
||||
now asserts
|
||||
- [x] on the real opentitan tree (read-only): `references` on
|
||||
`entropy_masking_req` from `aes.sv` lists `aes_bind.sv`; on
|
||||
`state_q` from `entropy_src_main_sm.sv` lists `entropy_src_core.sv`;
|
||||
the `nav`/`navqueue` harness rows within noise (the hierarchical
|
||||
lookup is one more map probe)
|
||||
- [x] QA: fixtures re-attacked (a generate-scoped net; a net shadowed by a
|
||||
port of the same name in a *different* unit; a class member — must
|
||||
stay on the connection answer), opentitan census, gates. Verdict:
|
||||
rework needed — three findings in the closed-declaring-file repair's
|
||||
handling of a stale-on-disk file (one new to this lane, two
|
||||
pre-existing and general); see the feature README's QA log.
|
||||
- [x] rework (dev, per the lead's ruling on QA findings 1–3): one fresh read
|
||||
per closed file per request, threaded to the rendering step
|
||||
(`file_view`'s cache is no longer on this path); a re-analysed closed
|
||||
file's declaration reported at its live span; every index-time
|
||||
closed-file span guarded with `hover::spells_exactly` (now `pub(crate)`)
|
||||
and dropped rather than misrendered. `qa_finding_1/2/3` flipped to the
|
||||
fixed answers and renamed, plus one attack on the guard itself. QA's
|
||||
+25 % on a local-net request in a 40 000-line file accepted as-is, for
|
||||
§64.2 to note in `docs/perf/README.md`.
|
||||
- [x] QA re-check (same worktree): findings 1–3 re-derived by hand and
|
||||
confirmed fixed (a use-only shift, a deleted declaring file, a UTF-8
|
||||
boundary, two independent closed files, an escaped port and an
|
||||
escaped hierarchical net all attacked and held). **Finding 4, new**:
|
||||
the `include_declaration` fallback's index-time span is rendered with
|
||||
**no guard** when the file is *open* (only the closed path calls
|
||||
`spells_exactly`) — reproduced with a renamed live buffer, a stale
|
||||
3-byte span lands on the first three characters of the live token
|
||||
`sig2`. Verdict: rework needed again; see the feature README's QA log
|
||||
for the fix suggestion. Gates green (4453 passed), opentitan
|
||||
re-confirmed byte-identical, size 423 lines.
|
||||
- [x] rework 2 (dev, finding 4): the `include_declaration` chain lifted into
|
||||
`nav::declaration_site`; an open buffer's index-time fallback span is
|
||||
emitted only if `hover::spells_exactly` holds against the live text,
|
||||
else the declaration is omitted (the closed path keeps its single guard
|
||||
in `closed_locations`). QA's finding-4 test flipped and renamed, plus a
|
||||
control (an unsaved edit above the declaration still reports the live
|
||||
line). Gates green through `tools/guard.sh`.
|
||||
- [x] QA final (escalated, same worktree): the finding-4 test re-derived
|
||||
by hand (a real unsaved rename; honest omission, tails unchanged) and
|
||||
the control shown to come from the live path; the declaration-site
|
||||
ladder attacked rung by rung — five `qa_final_*` tests (a failed live
|
||||
lookup with the name still in place → emitted; a suffix of a longer
|
||||
live name → dropped; off a UTF-8 boundary → dropped, no panic;
|
||||
`includeDeclaration: false` on the closed rungs; one observation, a
|
||||
different exact `sig` at the old bytes is reported, for the lead).
|
||||
`nav.rs` 433 production lines, no unwrap/expect/panic,
|
||||
`indexed_references` 71 lines (reported). Gates green (4459 passed),
|
||||
opentitan rows re-confirmed read-only, checkout status identical.
|
||||
Verdict: **pass**.
|
||||
|
||||
### 64.2 Closing
|
||||
|
||||
- [x] `docs/perf/README.md` note if any harness number moved; topo row
|
||||
(`lucisv_server ──▶ vlog_semantic`: nav asks the hierarchical
|
||||
surface) — done 2026-09-12 (the perf entry records the +25 % on a
|
||||
local-net `references` and the closed-file parse; the
|
||||
`references-nav ──▶ workspace-index` row amended)
|
||||
- [x] release 0.55.0 with assets verified — done 2026-09-17: **0.55.0**
|
||||
(23e2e4b, v0.55.0), CI green on the release commit, 8 assets, the
|
||||
darwin-arm64 vsix at 0.55.0 with both binaries,
|
||||
`hierarchySections.js`, `extract.js`, no `*_test.js`.
|
||||
+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;
|
||||
@@ -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;
|
||||
+393
-19
@@ -2,7 +2,7 @@
|
||||
//! `.gitignore` subset documented in
|
||||
//! `docs/features/parallel-files/README.md`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File extensions lucisv formats when walking a directory.
|
||||
@@ -48,27 +48,134 @@ pub fn collect_files(
|
||||
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(),
|
||||
visited: HashSet::new(),
|
||||
files,
|
||||
warn,
|
||||
};
|
||||
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
|
||||
@@ -76,24 +183,78 @@ pub fn collect_files(
|
||||
/// elsewhere it is the canonical path, which resolves symlinks the same way
|
||||
/// at the cost of a real path lookup.
|
||||
#[cfg(unix)]
|
||||
type DirId = (u64, u64);
|
||||
pub type DirId = (u64, u64);
|
||||
#[cfg(not(unix))]
|
||||
type DirId = PathBuf;
|
||||
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)]
|
||||
fn dir_id(path: &Path) -> Option<DirId> {
|
||||
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))]
|
||||
fn dir_id(path: &Path) -> Option<DirId> {
|
||||
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))
|
||||
@@ -109,8 +270,10 @@ struct Walk<'a> {
|
||||
gitignore: bool,
|
||||
ignores: Vec<Ignore>,
|
||||
rel: Vec<String>,
|
||||
visited: HashSet<DirId>,
|
||||
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),
|
||||
}
|
||||
|
||||
@@ -169,7 +332,10 @@ impl Walk<'_> {
|
||||
if meta.is_dir() {
|
||||
self.dir(&path);
|
||||
} else if meta.is_file() && is_source(&path) {
|
||||
self.files.push(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();
|
||||
@@ -192,7 +358,7 @@ impl Walk<'_> {
|
||||
///
|
||||
/// A directory whose identity cannot be read is not entered.
|
||||
fn enter(&mut self, dir: &Path) -> bool {
|
||||
dir_id(dir).is_some_and(|id| self.visited.insert(id))
|
||||
matches!(self.tracker.enter(dir), DirStatus::EnteredFirstTime)
|
||||
}
|
||||
|
||||
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
|
||||
@@ -680,6 +846,181 @@ mod tests {
|
||||
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.
|
||||
@@ -689,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
@@ -33,19 +33,36 @@ pub fn code_actions(
|
||||
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(run, 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
|
||||
}
|
||||
@@ -184,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(&LintRun::default(), &uri(), doc, whole, None, 2)
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, None)
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => action,
|
||||
@@ -268,7 +285,6 @@ mod tests {
|
||||
doc,
|
||||
line1,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2,
|
||||
);
|
||||
assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}");
|
||||
}
|
||||
@@ -341,14 +357,8 @@ mod tests {
|
||||
start: Position { line: fenced_line, character: 0 },
|
||||
end: Position { line: fenced_line, character: 0 },
|
||||
};
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&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 {
|
||||
@@ -356,15 +366,8 @@ mod tests {
|
||||
end: Position { line: 4, character: 0 },
|
||||
};
|
||||
assert_eq!(
|
||||
code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
at,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2
|
||||
)
|
||||
.len(),
|
||||
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]),)
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
@@ -409,19 +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(&LintRun::default(), &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(&LintRun::default(), &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(&LintRun::default(), &uri(), doc, whole, Some(&refactor), 2).is_empty()
|
||||
);
|
||||
assert!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -431,12 +429,11 @@ mod tests {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&LintRun::default().with_tab_width(4),
|
||||
&uri(),
|
||||
doc,
|
||||
whole,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
4,
|
||||
);
|
||||
let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") };
|
||||
assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n");
|
||||
@@ -467,18 +464,14 @@ mod tests {
|
||||
let ws = workspace(src);
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let (external, problems) = vlog_linter::ExternalWaivers::parse(
|
||||
std::path::Path::new("team.waiver"),
|
||||
"waive --rule=no-tabs\n",
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let waived = LintRun::default().with_external(external);
|
||||
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, 2).is_empty(),
|
||||
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, 2).is_empty(),
|
||||
!code_actions(&LintRun::default(), &uri(), doc, whole, None).is_empty(),
|
||||
"the same buffer without the waiver is fixable"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -137,6 +137,16 @@ pub fn execute(
|
||||
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))
|
||||
}
|
||||
@@ -381,4 +391,76 @@ endmodule
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -31,3 +31,10 @@ use crate::state::Document;
|
||||
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()
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -215,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
|
||||
@@ -226,8 +248,7 @@ impl IndexCache {
|
||||
/// gets here.
|
||||
pub fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
let looking = Instant::now();
|
||||
let found =
|
||||
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()));
|
||||
let found = self.entry_for(path, text);
|
||||
let mut work = self.work.get();
|
||||
work.lookup_ns += elapsed_ns(looking);
|
||||
let Some(entry) = found else {
|
||||
@@ -713,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
|
||||
|
||||
@@ -23,6 +23,7 @@ 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;
|
||||
@@ -35,6 +36,8 @@ 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};
|
||||
|
||||
@@ -53,10 +56,29 @@ 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.
|
||||
@@ -70,7 +92,9 @@ 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(),
|
||||
}
|
||||
}
|
||||
@@ -80,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.
|
||||
///
|
||||
@@ -90,25 +119,12 @@ 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 oracle = workspace.then_some(IndexMentions { index, own });
|
||||
// One discovery for the whole pass: the selection, the options, the
|
||||
// width and the waiver paths all read the same `FileConfig`, so
|
||||
// reading the project's rules costs no extra stat and no extra open.
|
||||
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
|
||||
let (from_file, bad_names) = ProjectLint::read(&file);
|
||||
messages.extend(bad_names);
|
||||
let rules = enabled_rules(ws.client_settings(), &from_file, workspace);
|
||||
let (mut external, bad_waivers) = external_waivers(&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.
|
||||
external.absorb(external_waivers(&editor_waivers(ws.client_settings(), ws.roots())).0);
|
||||
let problems = ConfigProblems::new(&file, messages);
|
||||
LintRun { rules, oracle, options, line_length, external, problems }
|
||||
// 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
|
||||
@@ -117,17 +133,53 @@ impl<'a> LintRun<'a> {
|
||||
&self.problems
|
||||
}
|
||||
|
||||
/// A run carrying these external waivers — for the tests that pin what a
|
||||
/// waiver keeps out of the code actions.
|
||||
/// 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_external(mut self, external: ExternalWaivers) -> Self {
|
||||
self.external = external;
|
||||
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,
|
||||
@@ -135,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
|
||||
@@ -237,18 +359,37 @@ fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
|
||||
/// 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 ExternalWaivers::read(path) {
|
||||
Ok((file, bad)) => {
|
||||
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(problem),
|
||||
Err(problem) => problems.push(format!("{}: {problem}", path.display())),
|
||||
}
|
||||
}
|
||||
(waivers, problems)
|
||||
(waivers, problems, texts)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings and
|
||||
@@ -419,16 +560,43 @@ fn context(doc: &Document) -> LintContext<'_> {
|
||||
/// 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) -> Vec<Violation> {
|
||||
lint_with(&run.context(doc), &run.rules, &run.external).0
|
||||
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
|
||||
@@ -437,14 +605,13 @@ 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(run: &LintRun, doc: &Document, tab_width: usize) -> Vec<Violation> {
|
||||
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 ctx = run.context(doc).with_tab_width(tab_width);
|
||||
let found = lint_with(&ctx, &run.rules, &run.external).0;
|
||||
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
|
||||
@@ -453,15 +620,24 @@ pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec<Violation
|
||||
// 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 !found.iter().any(|violation| violation.fix.is_some()) {
|
||||
return found;
|
||||
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 regions = crate::fences::of(doc);
|
||||
found.into_iter().filter(|violation| !fix_touches_fence(violation, regions)).collect()
|
||||
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
|
||||
@@ -645,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(&LintRun::default(), 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);
|
||||
@@ -665,7 +841,7 @@ mod tests {
|
||||
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
|
||||
"still reported"
|
||||
);
|
||||
assert!(fixable(&LintRun::default(), doc, 2).is_empty(), "and still not fixable");
|
||||
assert!(fixable(&LintRun::default(), doc).is_empty(), "and still not fixable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -913,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(&LintRun::default(), ws.document(&uri).expect("open"), 2).len(), 1);
|
||||
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -921,7 +1097,7 @@ 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(&LintRun::default(), 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));
|
||||
}
|
||||
@@ -958,6 +1134,79 @@ mod tests {
|
||||
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.
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ mod large;
|
||||
mod lens;
|
||||
mod linked;
|
||||
mod lint;
|
||||
mod lint_snapshot;
|
||||
mod lint_trace;
|
||||
mod locate;
|
||||
mod module_select;
|
||||
mod nav;
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
use vlog_semantic::{FileId, WorkspaceIndex};
|
||||
|
||||
/// The extra reach one refactoring asks for.
|
||||
///
|
||||
@@ -80,6 +80,30 @@ pub fn hierarchical_users(index: &WorkspaceIndex, reach: Reach<'_>) -> BTreeSet<
|
||||
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::*;
|
||||
@@ -138,6 +162,15 @@ mod tests {
|
||||
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();
|
||||
|
||||
+1756
-54
File diff suppressed because it is too large.
Load diff
@@ -17,6 +17,7 @@ use std::path::PathBuf;
|
||||
|
||||
use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit};
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::locate::display_name;
|
||||
@@ -65,6 +66,26 @@ pub fn rename_traced(
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
|
||||
// The engine's own first look at the request, over the buffer it is about
|
||||
// to be handed anyway. It refuses only what `vlog_refactor::rename` is
|
||||
// certain to refuse in the same words — so this is still one voice
|
||||
// deciding, just asked before the workspace is materialized for it. A
|
||||
// cursor on nothing used to read, parse and index all 3 976 files before
|
||||
// saying so (take 5 review §3 item 6); now it reads none.
|
||||
//
|
||||
// Sound because both selectors below hand the engine this very buffer, so
|
||||
// the out-of-scope refusal that outranks a cursor refusal cannot fire.
|
||||
//
|
||||
// A refusal here still writes a trace, because "where did the time go" is
|
||||
// a question about the fast refusals too — and the answer, nowhere, is
|
||||
// only believable if the line says `selected=0` and `parses=0` in the same
|
||||
// fields the slow road fills.
|
||||
if let Err(refusal) = vlog_refactor::rename_preflight(&doc.semantics, offset, new_name) {
|
||||
let (selection, engine) =
|
||||
(SelectionTrace::default(), vlog_refactor::RenameTrace::default());
|
||||
*trace = Some(format!("{} {} preflight=true", selection.line(), engine.line()));
|
||||
return Err(refusal);
|
||||
}
|
||||
// The name the cursor sits on, read off the buffer, is what the index is
|
||||
// asked for the fan-out. No refusal is taken here: `vlog_refactor::rename`
|
||||
// is the one voice that decides, and it decides over the files below. A
|
||||
@@ -80,7 +101,9 @@ pub fn rename_traced(
|
||||
}
|
||||
};
|
||||
let mut engine = vlog_refactor::RenameTrace::default();
|
||||
let outcome = vlog_refactor::rename_traced(&sources, &path, offset, new_name, &mut engine);
|
||||
let known = Known(ws);
|
||||
let outcome =
|
||||
vlog_refactor::rename_traced_with(&sources, &path, offset, new_name, &known, &mut engine);
|
||||
*trace = Some(format!("{} {}", selection.line(), engine.line()));
|
||||
let refactoring = outcome?;
|
||||
|
||||
@@ -116,6 +139,23 @@ pub fn rename_traced(
|
||||
Ok((WorkspaceEdit::new(changes), warnings))
|
||||
}
|
||||
|
||||
/// The workspace answering the engine's `KnownFacts` question, and nothing
|
||||
/// else: one call, to the one query that ties a record to the bytes it was
|
||||
/// read off ([`Workspace::known_facts`]).
|
||||
///
|
||||
/// A newtype rather than an `impl` on `Workspace` so that the promise this
|
||||
/// makes to `vlog_refactor` is written where a reader of the rename can see
|
||||
/// it, and so that no other handler can acquire it by accident — the facts a
|
||||
/// refactoring may reuse are the facts of the very texts it was handed, which
|
||||
/// is a property of *this* call site.
|
||||
struct Known<'a>(&'a Workspace);
|
||||
|
||||
impl vlog_refactor::KnownFacts for Known<'_> {
|
||||
fn facts_for(&self, path: &std::path::Path, text: &str) -> Option<FileFacts> {
|
||||
self.0.known_facts(path, text)
|
||||
}
|
||||
}
|
||||
|
||||
/// One sentence per file that writes the old name inside a macro invocation,
|
||||
/// a directive line or an attribute and was **not** among the files the engine
|
||||
/// was handed.
|
||||
@@ -213,6 +253,121 @@ mod tests {
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// A third file that spells nothing this rename is about, kept open so
|
||||
/// the open-buffer rung selects it: the "container" class in miniature —
|
||||
/// a file the engine must index and never analyses.
|
||||
const BYSTANDER: &str = "module bystander;\n logic unrelated;\nendmodule\n";
|
||||
|
||||
/// `sub.sv`, `top.sv` and `quiet.sv`, with the last two open and a
|
||||
/// persistent index store behind the workspace — so a rename is handed
|
||||
/// records keyed on the very bytes it reads.
|
||||
fn three_with_store(tree: &Tree, store: Option<&Tree>) -> (Workspace, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let quiet = tree.write("bystander.sv", BYSTANDER);
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_cache_path: store.map(|s| s.path.to_string_lossy().into_owned()),
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::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.set_document(path_to_uri(&quiet).expect("uri"), BYSTANDER.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// Every edit and every warning one rename produced, with the workspace's
|
||||
/// own scratch path taken out — the fingerprint the parity proof compares.
|
||||
fn print(result: &(WorkspaceEdit, Vec<String>), root: &Path) -> String {
|
||||
let (edit, warnings) = result;
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
for (uri, edits) in edit.changes.iter().flatten() {
|
||||
for one in edits {
|
||||
lines.push(format!(
|
||||
"{} {:?}..{:?} -> {}",
|
||||
uri.as_str(),
|
||||
one.range.start,
|
||||
one.range.end,
|
||||
one.new_text
|
||||
));
|
||||
}
|
||||
}
|
||||
lines.sort();
|
||||
lines.extend(warnings.iter().map(|w| format!("warn {w}")));
|
||||
lines.join("\n").replace(root.to_str().expect("utf-8"), "")
|
||||
}
|
||||
|
||||
/// **§R3b's server-side proof.** The same rename over the same files, once
|
||||
/// with a warm index store behind it — where the engine is handed every
|
||||
/// file's record and stops parsing the ones nothing analyses — and once
|
||||
/// with no store at all, where it parses them all: byte-identical edits,
|
||||
/// byte-identical warnings.
|
||||
///
|
||||
/// The reuse is asserted to have happened *and* to have removed a parse,
|
||||
/// so a store that silently stopped answering would fail this rather than
|
||||
/// pass it for the wrong reason.
|
||||
#[test]
|
||||
fn a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says() {
|
||||
let tree = Tree::new("reuse_store");
|
||||
let store = Tree::new("reuse_store_cache");
|
||||
let (warm, uri) = three_with_store(&tree, Some(&store));
|
||||
let mut line = None;
|
||||
let with_store = rename_traced(&warm, &uri, at(TOP, "clk"), "clk_x", &mut line)
|
||||
.expect("the rename succeeds");
|
||||
let trace = line.expect("a trace is always written");
|
||||
assert!(trace.contains("selected=3"), "all three files are selected: {trace}");
|
||||
assert!(trace.contains("reused_files=3"), "and every record came from the store: {trace}");
|
||||
assert!(trace.contains("other_files=1"), "bystander.sv is the unread one: {trace}");
|
||||
assert!(trace.contains("parses{index=2"), "so only the two analysed files: {trace}");
|
||||
|
||||
let bare = Tree::new("reuse_none");
|
||||
let (plain, plain_uri) = three_with_store(&bare, None);
|
||||
let mut plain_line = None;
|
||||
let no_store = rename_traced(&plain, &plain_uri, at(TOP, "clk"), "clk_x", &mut plain_line)
|
||||
.expect("the rename succeeds");
|
||||
let plain_trace = plain_line.expect("a trace is always written");
|
||||
assert!(plain_trace.contains("reused_files=0"), "premise: no store, no reuse");
|
||||
assert!(plain_trace.contains("parses{index=3"), "premise: all three parsed");
|
||||
|
||||
assert_eq!(
|
||||
print(&with_store, &tree.path),
|
||||
print(&no_store, &bare.path),
|
||||
"the reuse changed an edit or a warning"
|
||||
);
|
||||
}
|
||||
|
||||
/// **Unsaved-buffer precedence, for free.** A buffer whose text disagrees
|
||||
/// with the file on disk is not the bytes any record was written from, so
|
||||
/// the store answers nothing for it and it is parsed — and the rename acts
|
||||
/// on the buffer's text, which is the precedence it always had.
|
||||
///
|
||||
/// Nothing in the reuse arranges this: the key is the content, so unsaved
|
||||
/// text misses the same way changed text does.
|
||||
#[test]
|
||||
fn an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text() {
|
||||
let tree = Tree::new("reuse_unsaved");
|
||||
let store = Tree::new("reuse_unsaved_cache");
|
||||
let (mut ws, uri) = three_with_store(&tree, Some(&store));
|
||||
// A signal that exists only in the buffer. Its record cannot be in a
|
||||
// store keyed on what is on disk.
|
||||
let edited = "module top;\n logic only_here;\n sub u_sub (.clk(only_here));\nendmodule\n";
|
||||
ws.set_document(uri.clone(), edited.to_string());
|
||||
|
||||
let mut line = None;
|
||||
let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line)
|
||||
.expect("the buffer's own declaration renames");
|
||||
let trace = line.expect("a trace is always written");
|
||||
// Two untouched records: the open `bystander.sv`, and `sub.sv`, which
|
||||
// the buffer instantiates and the fan-out's instantiation step hands
|
||||
// over (M3.5) — both reused, and the edited buffer still parsed.
|
||||
assert!(trace.contains("reused_files=2"), "only the untouched files' records: {trace}");
|
||||
assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}");
|
||||
let edits = edit.changes.as_ref().expect("changes").values().flatten().count();
|
||||
assert_eq!(edits, 2, "the declaration and its one use, both in the buffer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_offers_the_identifier_and_its_placeholder() {
|
||||
let tree = Tree::new("prepare");
|
||||
@@ -1030,4 +1185,106 @@ mod tests {
|
||||
"and it is the engine's sentence, not the census's: {warning}"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The engine-owned preflight (take 5 review §3 item 6, TODO §61.1)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A cursor on nothing used to select every in-scope file, parse all of
|
||||
/// them and index them before the engine's 0.1 ms refusal. The preflight
|
||||
/// is only worth having if that is now literally no parses at all — not
|
||||
/// fewer, none — so the gate is asserted, not measured.
|
||||
#[test]
|
||||
fn a_rename_on_a_cursor_with_no_symbol_parses_nothing() {
|
||||
let tree = Tree::new("nosymbolparses");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let at_comment = TOP.len() as u32 - 1; // the newline after `endmodule`
|
||||
|
||||
let before = vlog_parser::stats::parses();
|
||||
let mut trace = None;
|
||||
let refusal =
|
||||
rename_traced(&ws, &uri, at_comment, "probe", &mut trace).expect_err("no symbol there");
|
||||
let parses = vlog_parser::stats::parses() - before;
|
||||
|
||||
assert_eq!(parses, 0, "the refusal parsed {parses} whole files");
|
||||
assert_eq!(refusal, "there is no symbol to rename at this position.");
|
||||
|
||||
// And the `--verbose` channel says so in its own fields, so the phase
|
||||
// that measures this row reads the parse count instead of trusting it.
|
||||
let trace = trace.expect("a refusal traces too");
|
||||
assert!(trace.contains("selected=0"), "{trace}");
|
||||
assert!(trace.contains("parses=0"), "{trace}");
|
||||
assert!(trace.contains("preflight=true"), "{trace}");
|
||||
}
|
||||
|
||||
/// …and it is the same sentence the whole workspace produced, taken from
|
||||
/// the engine over every in-scope file rather than from this module.
|
||||
#[test]
|
||||
fn the_preflights_refusal_is_the_whole_workspaces_refusal() {
|
||||
let tree = Tree::new("preflightparity");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let path = tree.path.join("top.sv");
|
||||
for (case, offset) in [
|
||||
("past the last item", TOP.len() as u32 - 1),
|
||||
("on the `module` keyword", at(TOP, "module")),
|
||||
("on a literal", at(TOP, "1'b0")),
|
||||
] {
|
||||
let fast = rename(&ws, &uri, offset, "probe").expect_err(case);
|
||||
let slow = vlog_refactor::rename(&ws.sources(), &path, offset, "probe")
|
||||
.expect_err("the whole workspace refuses too");
|
||||
assert_eq!(fast, slow, "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Precedence, in the two places the preflight could have disturbed it: an
|
||||
/// unusable buffer is refused by this module before the engine is asked
|
||||
/// anything, and an invalid new name outranks whatever the cursor is on.
|
||||
#[test]
|
||||
fn the_preflight_does_not_disturb_the_refusal_order() {
|
||||
let tree = Tree::new("preflightorder");
|
||||
let (ws, uri) = opened(&tree);
|
||||
|
||||
let untitled = Uri::from_str("untitled:Untitled-1").expect("uri");
|
||||
let mut with_untitled = Workspace::default();
|
||||
with_untitled.set_document(untitled.clone(), TOP.to_string());
|
||||
assert_eq!(
|
||||
rename(&with_untitled, &untitled, at(TOP, "u_sub"), "probe").expect_err("unsaved"),
|
||||
UNSAVED,
|
||||
"an untitled buffer is refused before the engine sees the cursor"
|
||||
);
|
||||
|
||||
// A cursor on nothing *and* a keyword for a new name: the name's
|
||||
// sentence, which is the one `renaming` reaches first.
|
||||
let refusal = rename(&ws, &uri, TOP.len() as u32 - 1, "module").expect_err("a keyword");
|
||||
assert_eq!(refusal, "`module` is a Verilog keyword.");
|
||||
}
|
||||
|
||||
/// The one buffer the preflight must never judge: on the large-file fast
|
||||
/// path every field but the text is the analysis of the *empty* file, so a
|
||||
/// preflight over it would refuse every cursor as symbolless. The
|
||||
/// large-buffer gate refuses the whole request first, and this pins that
|
||||
/// it still does.
|
||||
#[test]
|
||||
fn a_large_buffer_is_refused_before_the_preflight_could_see_it() {
|
||||
let tree = Tree::new("preflightlarge");
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
large_file_threshold: 1,
|
||||
..Default::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());
|
||||
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
assert!(doc.large, "premise: the buffer took the fast path");
|
||||
assert!(
|
||||
vlog_refactor::rename_preflight(&doc.semantics, at(TOP, "u_sub"), "probe").is_err(),
|
||||
"premise: the empty analysis would refuse a real cursor, which is why \
|
||||
`server/large_file.rs` must answer this method before we are reached"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -167,6 +167,46 @@ pub struct ScanTrace {
|
||||
/// 2026-09-08 that happens at the step that indexes each one, and is
|
||||
/// `read_ms` below (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
pub discovery_ms: f64,
|
||||
|
||||
// -- discovery, split (TODO §61.3) ----------------------------------
|
||||
//
|
||||
// Five disjoint parts of `discovery_ms` and one counter. They are a split
|
||||
// *of* that stage, not stages beside it, so nothing that adds the scan up
|
||||
// may add these as well
|
||||
// (`docs/features/perf5r-first-answer/README.md`).
|
||||
/// Reading each walk root's `lucisv.toml` for its `exclude` patterns —
|
||||
/// `Discovery::for_dir`, cached per instance, so a second root under the
|
||||
/// same config costs a map lookup.
|
||||
pub config_ms: f64,
|
||||
/// The directory walks themselves: `read_dir`, `.gitignore` parsing, the
|
||||
/// cycle guard, and the one `metadata` per entry the walk has always made.
|
||||
pub walk_ms: f64,
|
||||
/// How many roots were walked — one per scope directory, so a folder scope
|
||||
/// over three open buffers' folders is three.
|
||||
pub walk_dirs: usize,
|
||||
/// Reading a filelist, when rung 1 is the one in force.
|
||||
pub filelist_ms: f64,
|
||||
/// Sorting the walk's output into path order and dropping the paths two
|
||||
/// overlapping walks both found.
|
||||
pub sort_ms: f64,
|
||||
/// Applying `lucisv.index.maxFileSize` to every walked file.
|
||||
pub cap_ms: f64,
|
||||
/// `metadata` calls the cap made *itself* — the ones the walk's hand-off
|
||||
/// did not already answer. Zero for a walked scope since 2026-09-08;
|
||||
/// a filelist's entries are not walked and still cost one each.
|
||||
pub stats: usize,
|
||||
/// Taking every open buffer's text and its finished analysis, and letting
|
||||
/// it override the disk copy of its own path.
|
||||
pub buffers_ms: f64,
|
||||
/// Directories the remaining walk met under a spelling the root walk
|
||||
/// would have preferred — a directory alias outside the open folder's own
|
||||
/// chain ([`crate::state::Scan::wants_rescan`]). 0 in every ordinary
|
||||
/// session; 1 says this scan's paths are the head's spelling.
|
||||
pub conflict: usize,
|
||||
/// Whole rescans this scan asked for on its way out. One per `conflict`,
|
||||
/// and nothing else sets it.
|
||||
pub rescan_requested: usize,
|
||||
|
||||
/// Sorting into index order and putting the user's own neighbourhood at
|
||||
/// the front ([`crate::scan_order`]).
|
||||
pub order_ms: f64,
|
||||
@@ -365,7 +405,8 @@ impl ScanTrace {
|
||||
pub fn stage_line(&self) -> String {
|
||||
let c = &self.cache;
|
||||
format!(
|
||||
"scan {} stages ({}, {} files): discovery={:.2} order={:.2} cache_open={:.2} \
|
||||
"scan {} stages ({}, {} files): discovery={:.2} config={:.2} walk={:.2} \
|
||||
filelist={:.2} sort={:.2} cap={:.2} buffers={:.2} order={:.2} cache_open={:.2} \
|
||||
read={:.2} lookup={:.2} decode={:.2} parse={:.2} encode={:.2} store_write={:.2} \
|
||||
publish_absorb={:.2} publish_candidates={:.2} publish_includes={:.2} \
|
||||
publish_overlay={:.2} gone={:.2} absorb={:.2} compact={:.2} candidates={:.2} \
|
||||
@@ -374,6 +415,12 @@ impl ScanTrace {
|
||||
self.kind,
|
||||
self.read,
|
||||
self.discovery_ms,
|
||||
self.config_ms,
|
||||
self.walk_ms,
|
||||
self.filelist_ms,
|
||||
self.sort_ms,
|
||||
self.cap_ms,
|
||||
self.buffers_ms,
|
||||
self.order_ms,
|
||||
self.cache_open_ms,
|
||||
self.read_ms,
|
||||
@@ -402,13 +449,17 @@ impl ScanTrace {
|
||||
pub fn count_line(&self) -> String {
|
||||
let c = &self.cache;
|
||||
format!(
|
||||
"scan {} counts ({}): read={} read_kib={} skipped={} hits={} misses={} buffers={} \
|
||||
"scan {} counts ({}): read={} read_kib={} walk_dirs={} stats={} skipped={} \
|
||||
hits={} misses={} buffers={} \
|
||||
records={} repeats={} decoded_kib={} written_kib={} opens={} compactions={} \
|
||||
publishes={} published={} first_publish={:.2} overlays={}",
|
||||
publishes={} published={} first_publish={:.2} overlays={} \
|
||||
conflict={} rescan_requested={}",
|
||||
self.number,
|
||||
self.kind,
|
||||
self.read,
|
||||
kib(self.read_bytes),
|
||||
self.walk_dirs,
|
||||
self.stats,
|
||||
self.skipped,
|
||||
c.hits,
|
||||
c.misses,
|
||||
@@ -423,6 +474,8 @@ impl ScanTrace {
|
||||
self.published,
|
||||
self.first_publish_ms,
|
||||
self.overlays,
|
||||
self.conflict,
|
||||
self.rescan_requested,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ pub(super) fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
|
||||
/// The request id a `$/cancelRequest` names, or `None` for any other message.
|
||||
/// Both id forms the protocol allows are read; a cancel whose params do not
|
||||
/// parse is dropped, because there is no id to act on.
|
||||
fn cancelled_id(message: &Message) -> Option<RequestId> {
|
||||
pub(super) fn cancelled_id(message: &Message) -> Option<RequestId> {
|
||||
let Message::Notification(notification) = message else { return None };
|
||||
if notification.method != Cancel::METHOD {
|
||||
return None;
|
||||
|
||||
@@ -53,7 +53,7 @@ impl Server {
|
||||
let buffers = self.dirty.len();
|
||||
for (uri, text) in std::mem::take(&mut self.dirty) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.publish(&uri);
|
||||
crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri));
|
||||
}
|
||||
self.timed(started, |took| {
|
||||
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
|
||||
|
||||
@@ -45,10 +45,29 @@ use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{
|
||||
code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy,
|
||||
hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, nav, pairs, ports,
|
||||
rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
|
||||
hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, lint_trace, nav,
|
||||
pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
/// The requests whose empty answer may mean "this scan has not reached the
|
||||
/// file yet" rather than "there is nowhere to go".
|
||||
///
|
||||
/// All three answer with a **list of places** and with an empty list when they
|
||||
/// find none, so `[]` is exactly the shape that carries no information. Every
|
||||
/// other request is left alone: a hover's `null`, a completion's empty list and
|
||||
/// a code-action menu with no offers all mean what they say whatever the scan
|
||||
/// has reached, and deferring one would be withholding an answer rather than
|
||||
/// waiting for a better one. `textDocument/implementation` would belong here;
|
||||
/// this server does not answer it, so it is not written down as if it did.
|
||||
const NAVIGATION: [&str; 3] =
|
||||
[GotoDefinition::METHOD, GotoTypeDefinition::METHOD, References::METHOD];
|
||||
|
||||
/// Whether a response says **nowhere**: an answer, not a failure, and an empty
|
||||
/// list of places. See [`NAVIGATION`].
|
||||
pub(super) fn names_nowhere(response: &Response) -> bool {
|
||||
matches!(&response.response_result, Ok(Value::Array(found)) if found.is_empty())
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Answer one request, timing it when `--verbose` asked.
|
||||
///
|
||||
@@ -61,18 +80,92 @@ impl Server {
|
||||
pub(super) fn request(&mut self, request: Request) -> Response {
|
||||
let Some(started) = self.timer() else { return self.answer_request(request) };
|
||||
let method = request.method.clone();
|
||||
// One trace per request, armed here so the flush this request triggers
|
||||
// is inside it: the diagnostics pass that publishes during the flush is
|
||||
// the *other* consumer of a lint result, and the two are only readable
|
||||
// against each other when one line carries both (review round §R1b).
|
||||
lint_trace::arm();
|
||||
let response = self.answer_request(request);
|
||||
self.timing(format!("{method} answered in {}", ms(started)));
|
||||
// Silent for every request that never linted anything, which is all of
|
||||
// them but the code actions and the flushes that publish diagnostics.
|
||||
if let Some(trace) = lint_trace::disarm().filter(|trace| !trace.is_empty()) {
|
||||
self.timing(format!(
|
||||
"codeaction method={method} total={} {}",
|
||||
ms(started),
|
||||
trace.line()
|
||||
));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// A copy of `request` to ask again at the scan's next publish, when an
|
||||
/// empty answer to it right now would mean "not scanned yet" rather than
|
||||
/// "nowhere".
|
||||
///
|
||||
/// **The lead's ruling from §61.3, as a rule in the drain.** A held
|
||||
/// startup request is answered the moment the user's own folder is
|
||||
/// published, and a definition whose target lives in another folder was
|
||||
/// answered `[]` there — coherent, and wrong by the time the scan ended.
|
||||
/// Rather than teach the drain to work out whether the published prefix
|
||||
/// resolves *this* request's target, the answer is computed through the
|
||||
/// ordinary handler and, when it names nowhere and the index is still
|
||||
/// growing, put back ([`Server::deferred`]).
|
||||
///
|
||||
/// **Only while a scan is running**, so a settled server answers empty
|
||||
/// exactly as it always did — including the last try, after the scan ends.
|
||||
/// **Only the three navigation methods that answer with a list of places**
|
||||
/// ([`NAVIGATION`]): a hover, a completion, a code action or a rename is
|
||||
/// unaffected, and so is every request whose empty answer means something
|
||||
/// else. `textDocument/implementation` is not on the list because this
|
||||
/// server does not answer it.
|
||||
pub(super) fn ask_again_if_empty(&self, request: &Request) -> Option<Request> {
|
||||
if !self.scanning || !NAVIGATION.contains(&request.method.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some(Request::new(request.id.clone(), request.method.clone(), request.params.clone()))
|
||||
}
|
||||
|
||||
/// `--verbose`: that a navigation answer was set aside for the next
|
||||
/// publish rather than sent, and how many are waiting with it.
|
||||
pub(super) fn say_deferred(&self, request: &Request) {
|
||||
if !self.verbose {
|
||||
return;
|
||||
}
|
||||
self.timing(format!(
|
||||
"{} DEFERRED to the next publish (empty mid-scan, already deferred={})",
|
||||
request.method,
|
||||
self.deferred.len()
|
||||
));
|
||||
}
|
||||
|
||||
/// [`Server::flush_dirty`], with the dirty-buffer stage measured apart
|
||||
/// from the handler that follows it.
|
||||
///
|
||||
/// The review's item 4: *if the dirty-buffer stage dominates the 136 ms, a
|
||||
/// lint cache alone cannot fix it*. The flush rebuilds each dirty
|
||||
/// `Document` (parse and analysis, counted as whole-file parses) and then
|
||||
/// publishes its diagnostics, which lints; the handler lints again. One
|
||||
/// line carrying both is what makes the two comparable.
|
||||
fn flush_dirty_traced(&mut self) {
|
||||
if !lint_trace::armed() {
|
||||
return self.flush_dirty();
|
||||
}
|
||||
let buffers = self.dirty.len();
|
||||
let before = vlog_parser::stats::parses();
|
||||
let started = std::time::Instant::now();
|
||||
self.flush_dirty();
|
||||
let parses = vlog_parser::stats::parses().saturating_sub(before);
|
||||
lint_trace::close_flush(started.elapsed(), buffers, parses);
|
||||
}
|
||||
|
||||
fn answer_request(&mut self, request: Request) -> Response {
|
||||
// A request answers from a buffer's analysis, so any change the client
|
||||
// has already sent is in effect before it is answered — the order
|
||||
// contract the loop has always promised. Here is also where a typing
|
||||
// burst is coalesced: the changes before this request all become one
|
||||
// `set_document` in `flush_dirty`.
|
||||
self.flush_dirty();
|
||||
self.flush_dirty_traced();
|
||||
let id = request.id.clone();
|
||||
let method = request.method.clone();
|
||||
// The large-file fast path answers first, and for most methods it
|
||||
@@ -262,9 +355,9 @@ impl Server {
|
||||
if code_action::wants_fixes(only.as_deref()) {
|
||||
// A code-action request carries no `tabSize`, so the width a
|
||||
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
|
||||
// or from the built-in default.
|
||||
let tab_width =
|
||||
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
||||
// or from the built-in default — read by the run itself, off
|
||||
// the `FileConfig` it discovers anyway, so this path no longer
|
||||
// walks for a config file twice (review round §R1a).
|
||||
let run = lint::LintRun::for_document(&self.workspace, doc);
|
||||
actions.extend(code_action::code_actions(
|
||||
&run,
|
||||
@@ -272,7 +365,6 @@ impl Server {
|
||||
doc,
|
||||
p.range,
|
||||
only.as_deref(),
|
||||
tab_width,
|
||||
));
|
||||
}
|
||||
// The port refactorings answer for the cursor, not for a range:
|
||||
|
||||
@@ -221,9 +221,29 @@ impl Server {
|
||||
self.scanning = false;
|
||||
// A neighbourhood can only be owed by a scan, and there is none now.
|
||||
self.head_owed = false;
|
||||
self.answer_what_was_deferred();
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Answer whatever the empty-answer rule set aside, now that the index has
|
||||
/// stopped growing.
|
||||
///
|
||||
/// **The other half of that rule, and the reason it can never strand a
|
||||
/// request.** A navigation answer was deferred because `[]` might have
|
||||
/// meant "not scanned yet"; here it cannot mean that any more, so an empty
|
||||
/// answer is the honest one and goes out. The scan is over, so
|
||||
/// [`Server::ask_again_if_empty`] defers nothing this time round — and a
|
||||
/// request the order contract still holds, one behind something already
|
||||
/// `held`, is put back by `process_batch`'s own rule exactly as any other
|
||||
/// message would be.
|
||||
pub(super) fn answer_what_was_deferred(&mut self) {
|
||||
let deferred = std::mem::take(&mut self.deferred);
|
||||
if deferred.is_empty() || self.stopped {
|
||||
return;
|
||||
}
|
||||
self.stopped = !matches!(self.process_batch(deferred), Ok(false));
|
||||
}
|
||||
|
||||
/// One whole scan: the bar up, every file indexed with the client's
|
||||
/// messages answered between two of them, the bar down.
|
||||
///
|
||||
@@ -241,24 +261,54 @@ impl Server {
|
||||
let verbose = started.is_some();
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan = self.watching(bar.as_ref(), |ws, watch| ws.begin_scan(watch, verbose));
|
||||
let interleave = scan.total() > INTERLEAVE_ABOVE;
|
||||
// A scan that has walked the user's own folders and owes itself the
|
||||
// rest of the workspace **always** interleaves, whatever its work list
|
||||
// says today: the whole point of leading with that neighbourhood is
|
||||
// that the request waiting for it is answered the moment it is in
|
||||
// (`docs/features/perf5r-first-answer/README.md`).
|
||||
let interleave = scan.total() > INTERLEAVE_ABOVE || scan.discovery_pending();
|
||||
let total = scan.total();
|
||||
if started.is_some() {
|
||||
// Whether it interleaves is said here because it is decided here,
|
||||
// and because it is the answer to "why did my hover wait?" — a
|
||||
// scan that does not interleave answers nothing until it is done.
|
||||
let interleaving = if interleave { ", interleaved" } else { "" };
|
||||
self.timing(format!("scan started: {total} file{}{interleaving}", plural(total)));
|
||||
let staged = if scan.discovery_pending() { " (the folder first)" } else { "" };
|
||||
self.timing(format!(
|
||||
"scan started: {total} file{}{staged}{interleaving}",
|
||||
plural(total)
|
||||
));
|
||||
}
|
||||
while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch))
|
||||
{
|
||||
loop {
|
||||
// **No bar while the denominator can still grow.** The work list
|
||||
// is the neighbourhood so far, and a percentage against it would
|
||||
// fall to a twentieth of itself the moment the rest of the
|
||||
// workspace lands. The per-file log still runs — it names files,
|
||||
// not fractions — and the first percentage the client sees is the
|
||||
// first measured one (`docs/features/indexing-ux/README.md`).
|
||||
let showing = if scan.discovery_pending() { None } else { bar.as_ref() };
|
||||
let stepped =
|
||||
self.watching(showing, |workspace, watch| workspace.scan_step(&mut scan, watch));
|
||||
if !stepped {
|
||||
break;
|
||||
}
|
||||
if interleave && self.answer_what_is_waiting(&mut scan) {
|
||||
// Nothing after this may speak to a client that has gone, the
|
||||
// timing line included.
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
let total = scan.total();
|
||||
let (skipped, cached) = (scan.skipped(), scan.cached());
|
||||
// A split discovery whose two halves reached one directory by two
|
||||
// spellings: nothing was indexed twice, and every answer this scan
|
||||
// gives is the right one, but the paths are the head's and a plain
|
||||
// walk of the same tree spells them the other way
|
||||
// ([`Scan::wants_rescan`]). One ordinary rescan *is* that plain walk,
|
||||
// so it converges them — asked for with the same flag a save or a
|
||||
// settings change sets, and therefore run when this scan ends, with
|
||||
// every request held for the whole of it.
|
||||
self.rescan_wanted |= scan.wants_rescan();
|
||||
let warnings = self.workspace.finish_scan(scan);
|
||||
self.end_indexing(bar, skipped, cached);
|
||||
self.timed(started, |took| {
|
||||
@@ -313,13 +363,22 @@ impl Server {
|
||||
/// **This is the round's whole point, and its whole cost.** Polling costs
|
||||
/// one `try_recv` per file and finds nothing in a scan nobody is waiting
|
||||
/// on, so a quiet scan pays nothing at all; a scan somebody *is* waiting
|
||||
/// on pays one merge per burst to make the records it has taken since the
|
||||
/// last one answerable ([`Workspace::publish_scan`]). The messages then go
|
||||
/// on pays a merge to make the records it has taken since the last one
|
||||
/// answerable ([`Workspace::publish_scan`]). The messages then go
|
||||
/// through the same `process_batch` the loop uses, so a `didChange` queued
|
||||
/// ahead of a hover is applied before that hover is answered and a cancel
|
||||
/// beside its request still answers it `RequestCancelled` — the order
|
||||
/// contract is the loop's, unchanged, because it is the loop's code.
|
||||
///
|
||||
/// **A merge per burst was the cost; a merge per 512 files is what it is
|
||||
/// now.** [`Scan::publish_is_due`] is the cadence, and the one drain
|
||||
/// exempt from it is the one with something *waiting* — the startup's held
|
||||
/// requests, drained the moment the neighbourhood is in, which is the
|
||||
/// session's first useful answer and must not be a file later than it was
|
||||
/// (`docs/features/perf5r-first-answer/README.md`). Everything else reads
|
||||
/// a coherent prefix that is at most a cadence older, which is the trade
|
||||
/// `docs/features/perf5r-publication/README.md` measures.
|
||||
///
|
||||
/// An error here is a client that has gone: there is nobody to report it
|
||||
/// to and no reason to go on scanning, so it stops the scan the same way a
|
||||
/// `shutdown` does.
|
||||
@@ -329,9 +388,24 @@ impl Server {
|
||||
// would be `[]` (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
self.head_owed = !scan.neighbourhood_indexed();
|
||||
let mut batch = self.waiting_for_this_scan();
|
||||
let owed = !batch.is_empty();
|
||||
let mut arrived = Vec::new();
|
||||
while let Ok(message) = self.queue.try_recv() {
|
||||
batch.push(message);
|
||||
arrived.push(message);
|
||||
}
|
||||
// A quiet scan pays nothing at all, and that is a promise: the cadence
|
||||
// is asked only when there is something for a publish to be *for*.
|
||||
if !owed && arrived.is_empty() && self.deferred.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if owed || scan.publish_is_due() {
|
||||
self.workspace.publish_scan(scan);
|
||||
// A navigation answer this scan could not give yet is asked again
|
||||
// off the prefix that has just grown — behind whatever was already
|
||||
// waiting, ahead of everything newer ([`Server::deferred`]).
|
||||
batch.append(&mut self.deferred);
|
||||
}
|
||||
batch.append(&mut arrived);
|
||||
if batch.is_empty() {
|
||||
return false;
|
||||
}
|
||||
@@ -343,14 +417,13 @@ impl Server {
|
||||
// recomputed below once the new head segment is known.
|
||||
let opened = !opened_in(&batch).is_empty();
|
||||
self.head_owed |= opened;
|
||||
self.workspace.publish_scan(scan);
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
// The files the user has just opened, and the folders around them, are
|
||||
// what they are looking at, so they are indexed next rather than when
|
||||
// the alphabet reaches them — the open-first rule, for buffers opened
|
||||
// after the work list was taken.
|
||||
if opened {
|
||||
self.workspace.open_next(scan);
|
||||
self.watching(None, |workspace, watch| workspace.open_next(scan, watch));
|
||||
self.head_owed = !scan.neighbourhood_indexed();
|
||||
}
|
||||
self.stopped
|
||||
|
||||
@@ -46,7 +46,8 @@ use lsp_types::{SemanticToken, Uri};
|
||||
|
||||
use crate::state::Workspace;
|
||||
|
||||
use batch::{burst, cancelled_in, cancelled_response};
|
||||
use batch::{burst, cancelled_id, cancelled_in, cancelled_response};
|
||||
use dispatch::names_nowhere;
|
||||
|
||||
mod batch;
|
||||
mod client;
|
||||
@@ -227,6 +228,23 @@ pub struct Server {
|
||||
/// [`Server::must_wait`] — this is the order contract, not a queue of its
|
||||
/// own.
|
||||
held: Vec<Message>,
|
||||
/// Navigation requests a scan answered **empty** while it was still
|
||||
/// growing the index, to be asked again at its next publish.
|
||||
///
|
||||
/// **Not a second `held`, and deliberately not part of
|
||||
/// [`Server::must_wait`].** A held request is one the order contract says
|
||||
/// nothing newer may overtake; this is one whose answer was computed,
|
||||
/// found to name nowhere, and set aside because the reason it named
|
||||
/// nowhere may be that the file it wants has not been scanned yet
|
||||
/// (`docs/features/perf5r-publication/README.md`). Nothing else is owed
|
||||
/// anything by it — a hover, a completion or a code action behind one is
|
||||
/// answered exactly as before — and it is asked again at most once per
|
||||
/// publish, so the re-computation is bounded by the cadence and not by the
|
||||
/// scan's file count. A scan ending runs whatever is left through the
|
||||
/// dispatch one last time, with itself already over — so nothing is
|
||||
/// deferred that time round and an empty answer, which is now the honest
|
||||
/// one, goes out ([`Server::answer_what_was_deferred`]).
|
||||
deferred: Vec<Message>,
|
||||
/// `--verbose`: whether every operation says how long it took, in the
|
||||
/// client's log channel. Off is the shipped state and the whole of what it
|
||||
/// costs is the branch that reads this field — see
|
||||
@@ -393,7 +411,20 @@ impl Server {
|
||||
let response = if cancelled.remove(&request.id) {
|
||||
cancelled_response(request.id)
|
||||
} else {
|
||||
self.request(request)
|
||||
// A navigation request whose answer would be `[]` only
|
||||
// because the scan has not reached its target yet is
|
||||
// asked again at the next publish rather than answered
|
||||
// with nowhere ([`Server::deferred`]).
|
||||
let again = self.ask_again_if_empty(&request);
|
||||
let response = self.request(request);
|
||||
match again.filter(|_| names_nowhere(&response)) {
|
||||
Some(request) => {
|
||||
self.say_deferred(&request);
|
||||
self.deferred.push(Message::Request(request));
|
||||
continue;
|
||||
}
|
||||
None => response,
|
||||
}
|
||||
};
|
||||
self.connection.sender.send(Message::Response(response))?;
|
||||
}
|
||||
@@ -402,7 +433,14 @@ impl Server {
|
||||
// already been done above. Kept only so that a request behind
|
||||
// one that has to wait takes its cancel with it.
|
||||
Message::Notification(notification) if notification.method == Cancel::METHOD => {
|
||||
consumed_cancels.push(Message::Notification(notification));
|
||||
let cancel = Message::Notification(notification);
|
||||
// A request the empty-answer rule set aside is not in this
|
||||
// burst, so `cancelled_in` cannot see it — but it is still
|
||||
// a request the client is waiting on, and a cancel for it
|
||||
// is honoured where it lands: answered `RequestCancelled`
|
||||
// now, and never asked again (QA, perf5r-publication).
|
||||
self.cancel_deferred(&cancel)?;
|
||||
consumed_cancels.push(cancel);
|
||||
}
|
||||
Message::Notification(notification) => self.notification(notification),
|
||||
Message::Response(response) => self.response(response),
|
||||
@@ -411,6 +449,22 @@ impl Server {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]:
|
||||
/// take it out and answer it cancelled. A cancel naming anything else is
|
||||
/// left to the batch's own rule.
|
||||
fn cancel_deferred(&mut self, cancel: &Message) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
let Some(id) = cancelled_id(cancel) else { return Ok(()) };
|
||||
let found = self
|
||||
.deferred
|
||||
.iter()
|
||||
.position(|message| matches!(message, Message::Request(request) if request.id == id));
|
||||
if let Some(at) = found {
|
||||
self.deferred.remove(at);
|
||||
self.connection.sender.send(Message::Response(cancelled_response(id)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a request reaching the dispatch right now must wait instead of
|
||||
/// being answered.
|
||||
///
|
||||
|
||||
@@ -45,6 +45,26 @@ use crate::state::Workspace;
|
||||
/// nothing does not leave a workspace unindexed.
|
||||
pub(super) const CONFIGURATION_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// How long a startup waits, *after* the settings answer, for the editor to
|
||||
/// say which file it has open.
|
||||
///
|
||||
/// **Only when that name changes what the scan does.** A workspace-scoped scan
|
||||
/// with a buffer open walks that buffer's folder first, indexes it, and
|
||||
/// answers the request waiting for it in ~115 ms; without the name it walks
|
||||
/// all 3 976 files first and answers in ~290
|
||||
/// (`docs/features/perf5r-first-answer/README.md`). The two messages are
|
||||
/// written by the client at the same moment — the settings answer by whatever
|
||||
/// handles server-initiated requests, the `didOpen` by the editor — so which
|
||||
/// arrives first is a coin toss, and losing it costs 175 ms of the thing this
|
||||
/// round is about. This is that coin toss removed.
|
||||
///
|
||||
/// It is spent **only** by a session that is going to walk a whole workspace
|
||||
/// and has no buffer at all yet: a folder-scoped session has nothing to lead
|
||||
/// with, and a session whose buffer is already in hand stops waiting the
|
||||
/// moment it applies one. So the session that pays the full bound is the one
|
||||
/// with an empty editor, where nothing is waiting on the scan.
|
||||
pub(super) const OPENING_FILE_WAIT: Duration = Duration::from_millis(25);
|
||||
|
||||
/// Everything a session starts with that is not the connection or the roots.
|
||||
///
|
||||
/// One struct rather than six more parameters: `started` is the seam every
|
||||
@@ -147,6 +167,7 @@ impl Server {
|
||||
answering_a_rescan: false,
|
||||
stopped: false,
|
||||
held: Vec::new(),
|
||||
deferred: Vec::new(),
|
||||
verbose,
|
||||
born: Instant::now(),
|
||||
}
|
||||
@@ -233,10 +254,45 @@ impl Server {
|
||||
self.staging = true;
|
||||
self.request_configuration();
|
||||
self.await_configuration(wait);
|
||||
// Inside the staging window, because it is the same window: every
|
||||
// request is still held, and the scan has still not begun.
|
||||
if !wait.is_zero() && !self.stopped {
|
||||
self.await_opening_file(OPENING_FILE_WAIT);
|
||||
}
|
||||
self.staging = false;
|
||||
self.rescan_wanted = false;
|
||||
}
|
||||
|
||||
/// Wait a bounded moment for the editor's first `didOpen`, when knowing
|
||||
/// which folder the user is in is what decides the shape of the scan
|
||||
/// about to run ([`OPENING_FILE_WAIT`]).
|
||||
///
|
||||
/// Silent for every session that would not spend the knowledge: only a
|
||||
/// workspace-scoped scan leads with a folder, and only one with nothing
|
||||
/// open has a folder still to learn. The loop stops on the first buffer
|
||||
/// rather than draining the bound, so the ordinary session pays what the
|
||||
/// message took to arrive and nothing more.
|
||||
///
|
||||
/// **Not a scope decision.** Which files the scan indexes is settled by
|
||||
/// the settings that have just landed; this decides only which of them it
|
||||
/// indexes *first*, which `vlog_semantic::IndexBuilder` cannot see
|
||||
/// (`crate::scan_order`).
|
||||
fn await_opening_file(&mut self, wait: Duration) {
|
||||
if !self.workspace.leads_with_a_folder() {
|
||||
return;
|
||||
}
|
||||
let asked = Instant::now();
|
||||
while self.workspace.open_uris().is_empty() {
|
||||
let Some(left) = wait.checked_sub(asked.elapsed()) else { return };
|
||||
let Ok(message) = self.queue.recv_timeout(left) else { return };
|
||||
let batch = burst(&self.queue, message);
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
if self.stopped {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the client's messages until it answers the settings pull, the
|
||||
/// bound runs out, or it goes away.
|
||||
///
|
||||
|
||||
@@ -386,3 +386,35 @@ fn a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing() {
|
||||
// cancel did not intercept it.
|
||||
session.answer(server_id, Value::Null);
|
||||
}
|
||||
|
||||
/// A request the empty-answer rule set aside (`Server::deferred`,
|
||||
/// perf5r-publication) is not in any burst, so the burst's own cancel rule
|
||||
/// cannot see it. A cancel for it must still be honoured where it lands:
|
||||
/// answered `RequestCancelled` at once, taken out of the deferred set, and
|
||||
/// never asked again when the scan ends. Found by QA on §61.4; the request is
|
||||
/// planted directly because a real deferral lives only inside a running scan.
|
||||
#[test]
|
||||
fn a_cancel_for_a_deferred_request_answers_it_cancelled_and_forgets_it() {
|
||||
let (_tree, mut session, uri) = cancelling_session("cancel-deferred", ONE_MODULE);
|
||||
let parked = Request::new(
|
||||
RequestId::from(41),
|
||||
GotoDefinition::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": 7 }
|
||||
}),
|
||||
);
|
||||
session.server.deferred.push(Message::Request(parked));
|
||||
|
||||
session.server.process_batch(vec![cancel(serde_json::json!(41))]).expect("a burst");
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(41), Some(CANCELLED))]);
|
||||
assert!(session.server.deferred.is_empty(), "the cancelled request is not asked again");
|
||||
|
||||
// And the scan's end finds nothing left to answer: exactly one response.
|
||||
session.server.answer_what_was_deferred();
|
||||
assert!(outcomes(&session).is_empty(), "a cancelled request is answered once");
|
||||
|
||||
// A cancel naming a request that is *not* deferred changes nothing.
|
||||
session.server.process_batch(vec![cancel(serde_json::json!(42))]).expect("a burst");
|
||||
assert!(outcomes(&session).is_empty());
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! One test per row of the lint snapshot's invalidation table.
|
||||
//!
|
||||
//! Take 5 **review** round §R1a
|
||||
//! (`docs/features/perf5r-lint-snapshot/README.md`). A `Document` keeps the
|
||||
//! findings of one `lint_with` pass so that the diagnostics publish and
|
||||
//! quick-fix discovery do not run the same 21 ms twice on one revision. What
|
||||
//! makes that legitimate is that **every input which can change the answer
|
||||
//! either builds a new `Document`, or is in the key, or clears the slot** —
|
||||
//! and the README's table has one row per input.
|
||||
//!
|
||||
//! This file walks that table through the real doors: a `didChange`, a
|
||||
//! `didChangeConfiguration`, a `lucisv.toml` rewritten on disk, a waiver file
|
||||
//! rewritten in place, a watched file in **another** buffer, a close and
|
||||
//! reopen, a UTF-16 range, a large buffer — and one attack, a fix offered for
|
||||
//! a span the buffer no longer has.
|
||||
//!
|
||||
//! Reuse is observed by pointer, not by a stopwatch: two passes that share a
|
||||
//! snapshot answer with the same `Arc`, and one that recomputed cannot. A
|
||||
//! timing assertion on a lint pass would be a flake; `Arc::ptr_eq` is not.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vlog_linter::Violation;
|
||||
|
||||
use super::*;
|
||||
use crate::lint::{fixable, violations_in, LintRun};
|
||||
|
||||
/// A module with one tab in it: one `no-tabs` finding, carrying a Safe fix
|
||||
/// whose text is the indent width. Line 1 is the tab.
|
||||
const TABBED: &str = "module m;\n\twire a;\nendmodule\n";
|
||||
|
||||
/// A session over `tree` with `m.sv` open, its diagnostics already published.
|
||||
fn opened(tree: &Tree, text: &str) -> (Session, Uri) {
|
||||
let mut session = Session::wide(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
let _ = session.drain();
|
||||
(session, uri)
|
||||
}
|
||||
|
||||
/// The findings quick-fix discovery would offer for `uri` right now, taken
|
||||
/// through the same two calls the dispatcher makes.
|
||||
fn offered(session: &Session, uri: &Uri) -> Arc<[Violation]> {
|
||||
let doc = session.server.workspace.document(uri).expect("an open buffer");
|
||||
let run = LintRun::for_document(&session.server.workspace, doc);
|
||||
fixable(&run, doc)
|
||||
}
|
||||
|
||||
/// The rules that fired, by name, in the order they fired.
|
||||
fn rules(found: &[Violation]) -> Vec<&'static str> {
|
||||
found.iter().map(|violation| violation.rule).collect()
|
||||
}
|
||||
|
||||
/// The replacement text of the first fix, for the rows about fix bytes.
|
||||
fn fix_text(found: &[Violation]) -> String {
|
||||
let fix = found.first().and_then(|v| v.fix.as_ref()).expect("a fix");
|
||||
fix.edits.first().map(|(_, text)| text.clone()).expect("an edit")
|
||||
}
|
||||
|
||||
/// Push one `lucisv.lint.*` section and let the republish it triggers settle.
|
||||
fn push_lint_settings(session: &mut Session, lint: Value) {
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }),
|
||||
);
|
||||
let _ = session.drain();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the headline: one pass, two consumers
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The whole point of the round. A `didOpen` publishes diagnostics, which
|
||||
/// lints; the code action that follows reads **that** answer rather than
|
||||
/// running the rules again, and the two are the same object.
|
||||
#[test]
|
||||
fn the_diagnostics_publish_and_the_quick_fix_pass_share_one_lint() {
|
||||
let tree = Tree::new("lsshare");
|
||||
let (session, uri) = opened(&tree, TABBED);
|
||||
let doc = session.server.workspace.document(&uri).expect("open");
|
||||
assert!(
|
||||
!doc.lint.is_empty(),
|
||||
"the publish that answered the didOpen left its findings on the document"
|
||||
);
|
||||
let run = LintRun::for_document(&session.server.workspace, doc);
|
||||
let published = violations_in(doc, &run);
|
||||
let fixes = fixable(&run, doc);
|
||||
assert!(Arc::ptr_eq(&published, &fixes), "one pass answers both doors");
|
||||
assert_eq!(rules(&published), vec!["no-tabs"]);
|
||||
// ... and asking twice more does not compute twice more.
|
||||
assert!(Arc::ptr_eq(&fixes, &fixable(&run, doc)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 1 — the buffer's own text
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_edited_buffer_is_relinted() {
|
||||
let tree = Tree::new("lsedit");
|
||||
let (mut session, uri) = opened(&tree, TABBED);
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
|
||||
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": "module m;\n wire a;\nendmodule\n" }]),
|
||||
);
|
||||
assert!(
|
||||
offered(&session, &uri).is_empty(),
|
||||
"the tab is gone, so the finding and its fix are gone"
|
||||
);
|
||||
|
||||
change(&mut session, &uri, 3, serde_json::json!([{ "text": TABBED }]));
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "and back again");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 2 — the large-file fast path
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_large_buffer_lints_nothing_and_stores_nothing() {
|
||||
let tree = Tree::new("lslarge");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], true);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 16 } } } }),
|
||||
);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TABBED);
|
||||
let _ = session.drain();
|
||||
let doc = session.server.workspace.document(&uri).expect("open");
|
||||
assert!(doc.large, "premise: over the threshold");
|
||||
assert!(doc.lint.is_empty(), "a large buffer's publish lints nothing to keep");
|
||||
let menu = session.result(
|
||||
CodeActionRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": { "start": { "line": 1, "character": 1 },
|
||||
"end": { "line": 1, "character": 1 } },
|
||||
"context": { "diagnostics": [] },
|
||||
}),
|
||||
);
|
||||
assert_eq!(menu, serde_json::json!([]), "and offers nothing");
|
||||
let doc = session.server.workspace.document(&uri).expect("open");
|
||||
assert!(doc.lint.is_empty(), "the request left no snapshot behind either");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// rows 3 and 11 — the rule selection, pushed by the editor
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_pushed_rule_selection_is_relinted() {
|
||||
let tree = Tree::new("lsselect");
|
||||
let (mut session, uri) = opened(&tree, TABBED);
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
|
||||
|
||||
push_lint_settings(&mut session, serde_json::json!({ "ignore": ["no-tabs"] }));
|
||||
assert!(offered(&session, &uri).is_empty(), "the setting silenced the rule and its fix");
|
||||
|
||||
push_lint_settings(&mut session, serde_json::json!({ "ignore": [] }));
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "and un-silenced it");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// rows 4, 5, 8 and 12 — the `lucisv.toml`, rewritten under a running server
|
||||
// with no watcher event of any kind
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_rewritten_toml_is_relinted() {
|
||||
let tree = Tree::new("lstoml");
|
||||
tree.write("lucisv.toml", "[lint]\nignore = [\"no-tabs\"]\n");
|
||||
let (session, uri) = opened(&tree, TABBED);
|
||||
assert!(offered(&session, &uri).is_empty(), "premise: the project ignores the rule");
|
||||
|
||||
// Rewritten behind the server's back. `watch::SOURCE_GLOB` covers
|
||||
// `**/*.{v,vh,sv,svh}` and the filelist, so **no event is sent** — the
|
||||
// only thing that can notice is the per-request read and the key.
|
||||
tree.write("lucisv.toml", "[lint]\nignore = [\"posix-eof\"]\n");
|
||||
assert_eq!(
|
||||
rules(&offered(&session, &uri)),
|
||||
vec!["no-tabs"],
|
||||
"the next request read the new file"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 6 — the indent width, which is a fix's bytes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_tab_width_change_rewrites_the_fix() {
|
||||
let tree = Tree::new("lsindent");
|
||||
let (session, uri) = opened(&tree, TABBED);
|
||||
assert_eq!(fix_text(&offered(&session, &uri)), " ", "premise: the default indent");
|
||||
|
||||
tree.write("lucisv.toml", "indent = 4\n");
|
||||
assert_eq!(
|
||||
fix_text(&offered(&session, &uri)),
|
||||
" ",
|
||||
"the same finding, a different fix — and the snapshot must not hand back the old one"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 7 — an external waiver file, rewritten in place
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_rewritten_waiver_file_is_relinted() {
|
||||
let tree = Tree::new("lswaiver");
|
||||
tree.write("lucisv.toml", "[lint]\nwaivers = [\"team.waiver\"]\n");
|
||||
tree.write("team.waiver", "waive --rule=no-tabs\n");
|
||||
let (session, uri) = opened(&tree, TABBED);
|
||||
assert!(offered(&session, &uri).is_empty(), "premise: the waiver silences it");
|
||||
|
||||
// Rewritten to name a different rule. The two texts are different
|
||||
// lengths, so this row alone would pass on a length check too — the
|
||||
// same-length case is `lint_snapshot::tests`'
|
||||
// `a_waiver_rewritten_in_place_is_a_different_key`.
|
||||
tree.write("team.waiver", "waive --rule=posix-eof\n");
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "the waiver moved");
|
||||
|
||||
tree.write("team.waiver", "waive --rule=no-tabs\n");
|
||||
assert!(offered(&session, &uri).is_empty(), "and moved back");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// rows 9 and 10 — the workspace index the census oracle reads
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A change in **another** file, which is the row a document-revision key
|
||||
/// could not have covered: this buffer's bytes never move, and what the
|
||||
/// semantic rules say about it does.
|
||||
#[test]
|
||||
fn a_change_in_another_file_relints_this_one() {
|
||||
let tree = Tree::new("lsoracle");
|
||||
let dut = "module dut;\n logic dbg_probe;\nendmodule\n";
|
||||
tree.write("dut.sv", dut);
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
|
||||
);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&tree.path.join("dut.sv"), dut);
|
||||
let _ = session.drain();
|
||||
assert!(
|
||||
offered(&session, &uri).is_empty(),
|
||||
"premise: another file reads the signal, so it is not unused"
|
||||
);
|
||||
|
||||
// The other file stops mentioning it, and the watcher says so.
|
||||
tree.write("tb.sv", "module tb;\n dut d ();\nendmodule\n");
|
||||
session.watched(&[tree.path.join("tb.sv")]);
|
||||
let _ = session.drain();
|
||||
assert_eq!(
|
||||
rules(&offered(&session, &uri)),
|
||||
vec!["unused-signal"],
|
||||
"the index moved, so the snapshot had to go"
|
||||
);
|
||||
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
|
||||
);
|
||||
session.watched(&[tree.path.join("tb.sv")]);
|
||||
let _ = session.drain();
|
||||
assert!(offered(&session, &uri).is_empty(), "and back");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 13 — close and reopen
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_closed_and_reopened_buffer_is_relinted() {
|
||||
let tree = Tree::new("lsreopen");
|
||||
let (mut session, uri) = opened(&tree, TABBED);
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
let _ = session.drain();
|
||||
assert!(session.server.workspace.document(&uri).is_none(), "the snapshot went with it");
|
||||
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
assert!(offered(&session, &uri).is_empty(), "reopened with different text, relinted");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 14 — a fix's range, in UTF-16 units, off a reused snapshot
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The snapshot holds byte spans; the range on the wire is built per request
|
||||
/// from the buffer's text. A reused snapshot must therefore still produce
|
||||
/// UTF-16 columns, which is the one place a cached *position* would have gone
|
||||
/// wrong.
|
||||
#[test]
|
||||
fn a_snapshot_fix_keeps_its_utf16_range() {
|
||||
let tree = Tree::new("lsutf16");
|
||||
// The `é` is two bytes and one UTF-16 unit; `🎉` is four bytes and two.
|
||||
let text = "module m;\n // é 🎉\twire a;\nendmodule\n";
|
||||
let (mut session, uri) = opened(&tree, text);
|
||||
let ask = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": { "start": { "line": 1, "character": 9 },
|
||||
"end": { "line": 1, "character": 9 } },
|
||||
"context": { "diagnostics": [] },
|
||||
});
|
||||
// Twice: the first request may compute, the second is the reuse — and
|
||||
// both must name the same UTF-16 column.
|
||||
let first = session.result(CodeActionRequest::METHOD, ask.clone());
|
||||
let again = session.result(CodeActionRequest::METHOD, ask);
|
||||
assert_eq!(first, again, "the reused answer is the computed one");
|
||||
let edit = &first[0]["edit"]["changes"][uri.as_str()][0];
|
||||
assert_eq!(edit["range"]["start"]["character"], 9, "in UTF-16 units, not bytes");
|
||||
assert_eq!(edit["range"]["start"]["line"], 1);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the attack
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The failure the previous lane deferred this memo over: a **stale fix
|
||||
/// offer**. The buffer is edited so the bytes a previously offered fix named
|
||||
/// no longer exist; the next menu must not offer that fix, and must not offer
|
||||
/// an edit whose range runs past the end of the buffer.
|
||||
#[test]
|
||||
fn a_fix_is_never_offered_for_a_span_the_buffer_no_longer_has() {
|
||||
let tree = Tree::new("lsattack");
|
||||
// Two tabs, far apart, so the second fix's span is deep into the buffer.
|
||||
let long = format!("module m;\n\twire a;\n{}\twire z;\nendmodule\n", " // pad\n".repeat(40));
|
||||
let (mut session, uri) = opened(&tree, &long);
|
||||
let before = offered(&session, &uri);
|
||||
assert_eq!(before.len(), 2, "two tabs, two fixes: {:?}", rules(&before));
|
||||
let deepest = before.iter().map(|v| v.span.end).max().expect("a span");
|
||||
assert!(deepest as usize > 40, "premise: the fix is deep in the buffer");
|
||||
|
||||
// Now the buffer becomes three lines long. Every byte the second fix
|
||||
// named is gone.
|
||||
let after_text = "module m;\n wire a;\nendmodule\n";
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": after_text }]));
|
||||
let after = offered(&session, &uri);
|
||||
assert!(after.is_empty(), "no fix survives the text that justified it: {:?}", rules(&after));
|
||||
|
||||
// ... and through the wire, where a stale span would be a range past the
|
||||
// end of a three-line document.
|
||||
let menu = session.result(
|
||||
CodeActionRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": { "start": { "line": 0, "character": 0 },
|
||||
"end": { "line": 2, "character": 9 } },
|
||||
// The fix families alone: an extraction is offered for any whole
|
||||
// selection and is not what this row is about.
|
||||
"context": { "diagnostics": [], "only": ["quickfix", "source.fixAll.lucisv"] },
|
||||
}),
|
||||
);
|
||||
assert_eq!(menu, serde_json::json!([]), "and nothing is offered: {menu:#?}");
|
||||
assert_eq!(
|
||||
session.server.workspace.document(&uri).expect("open").text,
|
||||
after_text,
|
||||
"the buffer the answer describes is the buffer the client has"
|
||||
);
|
||||
}
|
||||
@@ -55,8 +55,11 @@ mod formatting;
|
||||
mod hierarchy_reach;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod lint_snapshot;
|
||||
mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod qa_rename_implicit;
|
||||
mod rename_implicit;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod scan_trace;
|
||||
@@ -98,6 +101,15 @@ impl Tree {
|
||||
}
|
||||
std::fs::write(&path, text).expect("write");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
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("parent");
|
||||
}
|
||||
std::os::unix::fs::symlink(target, &path).expect("symlink");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! QA M3.5 (2026-09-23): the LSP's rename against `.*`/`.name`, over the wire,
|
||||
//! on the engine tests' fixtures — the fan-out must hand the engine every
|
||||
//! file an implicit connection of the name lives in, open buffer or disk.
|
||||
|
||||
use super::*;
|
||||
|
||||
const LEAF: &str = "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n";
|
||||
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
const TOP2: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
|
||||
|
||||
/// Rename the name at (`line`, `character`) of `uri`.
|
||||
fn rename_at(session: &mut Session, uri: &Uri, line: u32, character: u32, new: &str) -> Response {
|
||||
session.request(
|
||||
Rename::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
"newName": new,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `text` with the LSP edits applied (ASCII fixtures: a character is a byte).
|
||||
fn applied(text: &str, edits: &[Value]) -> String {
|
||||
let starts: Vec<usize> =
|
||||
std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)).collect();
|
||||
let offset = |p: &Value| {
|
||||
let line = p["line"].as_u64().expect("line") as usize;
|
||||
starts[line] + p["character"].as_u64().expect("character") as usize
|
||||
};
|
||||
let mut spans: Vec<(usize, usize, String)> = edits
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let range = &e["range"];
|
||||
let text = e["newText"].as_str().expect("newText").to_string();
|
||||
(offset(&range["start"]), offset(&range["end"]), text)
|
||||
})
|
||||
.collect();
|
||||
spans.sort_by_key(|(start, end, _)| (*start, *end));
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0;
|
||||
for (start, end, new) in spans {
|
||||
out.push_str(&text[cursor..start]);
|
||||
out.push_str(&new);
|
||||
cursor = end;
|
||||
}
|
||||
out.push_str(&text[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// The edits for the file named `name` in a rename answer, or none — found
|
||||
/// by the URI's last segment, so a temp dir's symlinked spelling is moot.
|
||||
fn edits_for(answer: &Value, name: &str) -> Vec<Value> {
|
||||
let Some(changes) = answer["changes"].as_object() else { return Vec::new() };
|
||||
let suffix = format!("/{name}");
|
||||
let found = changes.iter().find(|(uri, _)| uri.ends_with(&suffix));
|
||||
found.and_then(|(_, edits)| edits.as_array().cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `d`'s column on line 0 of the three fixtures.
|
||||
fn d_column(text: &str) -> u32 {
|
||||
text.find("] d").expect("the port") as u32 + 2
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_lsp_port_rename_matches_the_engine_with_the_users_on_disk() {
|
||||
let tree = Tree::new("qa_rename_implicit_disk");
|
||||
tree.write("leaf.sv", LEAF);
|
||||
tree.write("top.sv", TOP);
|
||||
tree.write("top2.sv", TOP2);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("leaf.sv"), LEAF);
|
||||
|
||||
let answer =
|
||||
rename_at(&mut session, &uri, 0, d_column(LEAF), "din").response_result.expect("renames");
|
||||
assert_eq!(applied(TOP, &edits_for(&answer, "top.sv")), TOP.replace("(.*)", "(.*, .din(d))"));
|
||||
assert_eq!(applied(TOP2, &edits_for(&answer, "top2.sv")), TOP2.replace(".d,", ".din(d),"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_lsp_rename_reads_the_open_buffer_not_the_disk() {
|
||||
// On disk top.sv connects explicitly; the unsaved buffer uses `.*`.
|
||||
let tree = Tree::new("qa_rename_implicit_buffer");
|
||||
tree.write("leaf.sv", LEAF);
|
||||
let explicit = TOP.replace("(.*)", "(.clk(clk), .d(d), .q(q))");
|
||||
tree.write("top.sv", &explicit);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let top = session.open(&tree.path.join("top.sv"), TOP);
|
||||
let leaf = session.open(&tree.path.join("leaf.sv"), LEAF);
|
||||
|
||||
let answer =
|
||||
rename_at(&mut session, &leaf, 0, d_column(LEAF), "din").response_result.expect("renames");
|
||||
let top_edits = answer["changes"][top.as_str()].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(applied(TOP, &top_edits), TOP.replace("(.*)", "(.*, .din(d))"), "{answer:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_lsp_net_rename_reaches_a_bind_file_spelling_neither_name() {
|
||||
// binds.sv spells neither `d` nor `x`: only `leaf`'s instantiation sites
|
||||
// (leaf declares a port `d`) bring it into the fan-out.
|
||||
let tree = Tree::new("qa_rename_implicit_bind");
|
||||
let top =
|
||||
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
|
||||
let bind = "module binds;\n bind top leaf u_b (.*);\nendmodule\n";
|
||||
tree.write("leaf.sv", LEAF);
|
||||
tree.write("top.sv", top);
|
||||
tree.write("binds.sv", bind);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), top);
|
||||
|
||||
let answer =
|
||||
rename_at(&mut session, &uri, 0, d_column(top), "x").response_result.expect("renames");
|
||||
assert_eq!(
|
||||
applied(bind, &edits_for(&answer, "binds.sv")),
|
||||
bind.replace("(.*)", "(.*, .d(x))"),
|
||||
"{answer:#}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! A rename against `.*` connections, over the wire (TODO-MCP M3.5).
|
||||
//!
|
||||
//! The engine refuses a rename it cannot check against a `.*` whose module it
|
||||
//! cannot read, and the server hands the engine a *fan-out*, not the
|
||||
//! workspace. These pin the fan-out's instantiation step: every module a
|
||||
//! handed-over file instantiates is handed over too, so a `.*` into a module
|
||||
//! the workspace holds is read, not refused — and one into a module the
|
||||
//! workspace does not hold is still refused.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Rename the `d` at line 0, character `character` of `uri` to `x`.
|
||||
fn rename_d(session: &mut Session, uri: &Uri, character: u32) -> Response {
|
||||
session.request(
|
||||
Rename::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": character },
|
||||
"newName": "x",
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic q);\n quiet u_quiet (.*);\n leaf u_leaf (.*);\n assign q = d[0];\nendmodule\n";
|
||||
|
||||
/// Where the `d` of `input logic [7:0] d` sits on line 0.
|
||||
fn d_column() -> u32 {
|
||||
TOP.find("] d").expect("the port") as u32 + 2
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_rename_beside_a_wildcard_into_a_module_declaring_neither_name_succeeds() {
|
||||
let tree = Tree::new("rename_implicit_ok");
|
||||
// `quiet` declares neither `d` nor `x`, so no rung of the name's own
|
||||
// fan-out asks for it — only the instantiation step does.
|
||||
tree.write("quiet.sv", "module quiet (input logic clk);\nendmodule\n");
|
||||
tree.write("leaf.sv", "module leaf (input logic clk, input logic [7:0] d);\nendmodule\n");
|
||||
tree.write("top.sv", TOP);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
|
||||
let answer = rename_d(&mut session, &uri, d_column()).response_result.expect("renames");
|
||||
let edits = answer["changes"][uri.as_str()].as_array().expect("top.sv is edited").clone();
|
||||
let texts: Vec<&str> = edits.iter().filter_map(|e| e["newText"].as_str()).collect();
|
||||
assert!(texts.contains(&", .d(x)"), "the explicit connection: {answer:#}");
|
||||
assert_eq!(texts.iter().filter(|t| **t == "x").count(), 2, "the port and its use: {answer:#}");
|
||||
assert_eq!(edits.len(), 3, "and nothing for `u_quiet`: {answer:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_rename_beside_a_wildcard_into_a_module_outside_the_workspace_is_refused() {
|
||||
let tree = Tree::new("rename_implicit_refused");
|
||||
tree.write("leaf.sv", "module leaf (input logic clk, input logic [7:0] d);\nendmodule\n");
|
||||
tree.write("top.sv", TOP);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
|
||||
let error = rename_d(&mut session, &uri, d_column()).response_result.expect_err("refused");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
|
||||
assert!(
|
||||
error.message.contains(
|
||||
"`u_quiet` at top.sv:2 connects with `.*` to `quiet`, which lucisv cannot read"
|
||||
),
|
||||
"{}",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
@@ -286,3 +286,39 @@ fn a_startup_scan_with_no_files_opens_no_store_and_a_warm_rescan_rewrites_none()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_discovery_split_is_a_split_of_discovery_and_not_stages_beside_it() {
|
||||
// §61.3. `config`, `walk`, `filelist`, `sort`, `cap` and `buffers` are
|
||||
// disjoint parts of `discovery`, so they may never add up to more than it
|
||||
// — and anything that sums the scan (`the_stages_add_up_to_the_scan_they
|
||||
// _describe`) must not sum these as well, which is why they are absent
|
||||
// from that test's list. The slack is `collect_sources`'s own bookkeeping:
|
||||
// the `spoken_for` set, the `Vec` pushes, the `Scope` moves.
|
||||
let tree = trace_tree("tracediscovery", 30);
|
||||
let session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let lines = scan_lines(&session);
|
||||
let stages = line_of(&lines, "stages");
|
||||
let discovery = number(&stages, "discovery");
|
||||
let parts: f64 = ["config", "walk", "filelist", "sort", "cap", "buffers"]
|
||||
.iter()
|
||||
.map(|key| number(&stages, key))
|
||||
.sum();
|
||||
assert!(discovery > 0.0, "a walk of 30 files takes measurable time: {stages}");
|
||||
assert!(parts <= discovery * 1.02, "the parts cannot exceed the whole: {parts} of {discovery}");
|
||||
assert!(parts > 0.0, "and at least one of them was timed: {stages}");
|
||||
// Not asserted: that the parts account for *most* of discovery. On a
|
||||
// fixture this small the whole is well under a millisecond and the
|
||||
// bookkeeping slack — the `spoken_for` set, the `Vec` pushes — rivals the
|
||||
// walk, so a ratio bound is a stopwatch under the workspace suite's
|
||||
// parallel load (it tripped once at 50 % in the lead's gate run and
|
||||
// passed alone three times). On opentitan the walk is 95 % of discovery
|
||||
// (`docs/features/perf5r-first-answer/README.md`); that ratio is the
|
||||
// README's measurement, not this test's claim.
|
||||
assert_eq!(number(&stages, "filelist"), 0.0, "no filelist is in force: {stages}");
|
||||
// Nothing was walked twice: one root, and the cap read the walk's own
|
||||
// lengths rather than asking the filesystem again.
|
||||
let counts = line_of(&lines, "counts");
|
||||
assert_eq!(field(&counts, "walk_dirs"), "1", "one root, walked once: {counts}");
|
||||
assert_eq!(field(&counts, "stats"), "0", "the cap stats nothing the walk already read");
|
||||
}
|
||||
@@ -20,6 +20,8 @@ use std::time::Instant;
|
||||
use super::scan::{positions, symbol_request};
|
||||
use super::scan_trace::{field, is_trace_line, line_of, trace_tree};
|
||||
use super::*;
|
||||
use crate::server::startup::OPENING_FILE_WAIT;
|
||||
use crate::state::discover::HEAD_WALK_MAX;
|
||||
|
||||
/// A client that answers `workspace/configuration` and is told what a scan
|
||||
/// spent its time on.
|
||||
@@ -55,6 +57,16 @@ fn the_whole_workspace() -> Value {
|
||||
serde_json::json!({ "index": { "scope": "workspace", "logFiles": true } })
|
||||
}
|
||||
|
||||
/// [`the_whole_workspace`] with the folder scope's raise turned off, so the
|
||||
/// folder a split leads with is the open buffer's own directory — the
|
||||
/// settings `docs/performance_052_review.md` F1 reproduces with, and what
|
||||
/// every alias fixture below needs to reach the split at all.
|
||||
fn the_whole_workspace_flat() -> Value {
|
||||
serde_json::json!({
|
||||
"index": { "scope": "workspace", "scopeDepth": 0, "logFiles": true }
|
||||
})
|
||||
}
|
||||
|
||||
/// A `textDocument/didOpen` over the wire, as the client sends it.
|
||||
fn did_open(path: &Path, text: &str) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
@@ -527,3 +539,950 @@ fn an_answer_behind_a_held_request_is_not_stranded_for_the_whole_bound() {
|
||||
assert_eq!(positions(&said, 7).1, None, "a short scan answers nothing mid-way: {said:#?}");
|
||||
assert_eq!(session.server.held.len(), 1, "and the request is still owed an answer");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// §61.3 (R2b): the neighbourhood is walked, stepped and published before
|
||||
// the rest of the workspace is discovered at all.
|
||||
// `docs/features/perf5r-first-answer/README.md`
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The `scan started:` line, which says whether the scan led with a folder
|
||||
/// and how many files it had when it began.
|
||||
fn scan_started(messages: &[Message]) -> String {
|
||||
log_lines(messages)
|
||||
.into_iter()
|
||||
.find(|line| line.starts_with("timing: scan started"))
|
||||
.expect("a verbose scan says it started")
|
||||
}
|
||||
|
||||
/// A `textDocument/definition` on `path` at `line`:`character`.
|
||||
fn definition_at(id: i32, path: &Path, line: u32, character: u32) -> Message {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(id),
|
||||
GotoDefinition::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": path_to_uri(path).expect("uri") },
|
||||
"position": { "line": line, "character": character },
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// The result of the response to `id`, or `None` when it never came.
|
||||
fn result_of(messages: &[Message], id: i32) -> Option<Value> {
|
||||
messages.iter().find_map(|message| match message {
|
||||
Message::Response(response) if response.id == RequestId::from(id) => {
|
||||
response.response_result.clone().ok()
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_users_folder_is_walked_and_stepped_before_the_rest_of_the_workspace() {
|
||||
// **The whole of R2b.** Before it, a workspace-scoped session walked all
|
||||
// 3 976 opentitan files — 155 ms — before it could step the 124 in the
|
||||
// folder the user was looking at, and the request waiting for that folder
|
||||
// paid the whole walk. Now the folder is walked, stepped and published
|
||||
// first and the walk of the rest happens behind the answer.
|
||||
//
|
||||
// The claim is readable off two numbers on the wire: the scan *starts*
|
||||
// with the folder's file count and *finishes* over the whole workspace.
|
||||
let tree = a_block_and_a_crowd("splitfolderfirst", INTERLEAVE_ABOVE + 6);
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![
|
||||
configuration_answer(the_whole_workspace()),
|
||||
did_open(&opened, &text),
|
||||
definition_at(7, &opened, 1, 3),
|
||||
],
|
||||
);
|
||||
let said = session.drain();
|
||||
let started = scan_started(&said);
|
||||
assert!(
|
||||
started.contains("2 files (the folder first)"),
|
||||
"the scan begins with the block's two files, not the workspace's {}: {started}",
|
||||
INTERLEAVE_ABOVE + 8
|
||||
);
|
||||
|
||||
// One scan, and it lands over everything: the split bought the order,
|
||||
// never a smaller index.
|
||||
let lines = trace_lines(&said);
|
||||
assert_eq!(lines.len(), 3, "one scan, three trace lines: {lines:#?}");
|
||||
for line in &lines {
|
||||
assert!(line.starts_with("timing: scan 1 "), "no second scan ran: {line}");
|
||||
}
|
||||
assert_eq!(
|
||||
field(&line_of(&lines, "counts"), "read"),
|
||||
(INTERLEAVE_ABOVE + 8).to_string(),
|
||||
"and the work list ends as the whole workspace"
|
||||
);
|
||||
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 8);
|
||||
|
||||
// And the answer the folder bought is the right one, given inside the
|
||||
// scan.
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
let answered = answered.expect("the definition is answered at all");
|
||||
assert!(answered < ended.expect("the bar comes down"), "inside the scan: {said:#?}");
|
||||
let found = result_of(&said, 7).expect("a result");
|
||||
assert_eq!(
|
||||
found[0]["uri"],
|
||||
serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")),
|
||||
"the module in the folder next door: {found}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_split_head_obeys_a_gitignore_written_at_the_workspace_root() {
|
||||
// **The correctness the split could most easily have broken.** A walk
|
||||
// starting at `ip/aes` reads no `.gitignore` above itself, so the folder
|
||||
// half of the scan would have indexed files the rest of it excludes — two
|
||||
// answers to "which files exist" inside one scan. `collect_files_below`
|
||||
// carries the ancestor rules down, and this is the file that proves it.
|
||||
let tree = a_block_and_a_crowd("splitgitignore", 4);
|
||||
tree.write(".gitignore", "*_generated.sv\n");
|
||||
tree.write("ip/aes/rtl/aes_generated.sv", "module aes_generated;\nendmodule\n");
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text)],
|
||||
);
|
||||
let said = session.drain();
|
||||
assert!(scan_started(&said).contains("(the folder first)"), "{}", scan_started(&said));
|
||||
let indexed: Vec<String> = session
|
||||
.server
|
||||
.workspace
|
||||
.index()
|
||||
.files()
|
||||
.iter()
|
||||
.map(|path| path.display().to_string())
|
||||
.collect();
|
||||
assert!(
|
||||
!indexed.iter().any(|path| path.ends_with("aes_generated.sv")),
|
||||
"the root's rule reaches into the folder the head walked: {indexed:#?}"
|
||||
);
|
||||
// Six: two in the block, four in the crowd. The generated one is out.
|
||||
assert_eq!(indexed.len(), 6, "{indexed:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_from_the_workspace_root_is_no_neighbourhood_to_lead_with() {
|
||||
// The bound. A file opened from the root raises to the root, so "its
|
||||
// folder" is the whole workspace — leading with it would be leading with
|
||||
// everything, and waiting for it would be waiting out the entire scan
|
||||
// before answering anything. `splits_discovery` refuses, the scan is
|
||||
// ordered exactly as it was before this round, and
|
||||
// `scan_order::worth_waiting` decides the drain as it always did.
|
||||
let tree = a_block_and_a_crowd("splitrootlevel", INTERLEAVE_ABOVE + 6);
|
||||
tree.write("top.sv", "module top;\n aes dut ();\nendmodule\n");
|
||||
let opened = tree.path.join("top.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![
|
||||
configuration_answer(the_whole_workspace()),
|
||||
did_open(&opened, &text),
|
||||
definition_at(7, &opened, 1, 3),
|
||||
],
|
||||
);
|
||||
let said = session.drain();
|
||||
let started = scan_started(&said);
|
||||
assert!(
|
||||
!started.contains("the folder first"),
|
||||
"the root is not a folder to lead with: {started}"
|
||||
);
|
||||
// No deadlock: the request is still answered, and with the right place.
|
||||
// **It used to be answered `[]` inside the scan** — the drain reached it
|
||||
// before the alphabet reached `ip/aes/rtl`, and `[]` was what the prefix
|
||||
// said. Since §61.4 an empty *navigation* answer computed while the index
|
||||
// is still growing is not an answer at all: the request is asked again at
|
||||
// the scan's next publish and, in a workspace this small, at the scan's
|
||||
// end — which is later, and right (`perf5r-publication`).
|
||||
let found = result_of(&said, 7).expect("the definition is answered at all");
|
||||
assert_eq!(
|
||||
found[0]["uri"],
|
||||
serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")),
|
||||
"the module the buffer instantiates, not the empty prefix: {found}"
|
||||
);
|
||||
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_buffers_in_two_folders_put_both_folders_in_the_head() {
|
||||
// The multiple-folder case. The head is the union of what each buffer
|
||||
// raises to, so a definition into *either* block is answered off it —
|
||||
// and every file is still stepped exactly once, which is what the
|
||||
// finished index's file count says.
|
||||
let tree = a_block_and_a_crowd("splittwofolders", INTERLEAVE_ABOVE + 6);
|
||||
tree.write("ip/kmac/rtl/kmac.sv", "module kmac;\n localparam W = 2;\nendmodule\n");
|
||||
tree.write("ip/kmac/dv/tb/ktb.sv", "module ktb;\n kmac dut ();\nendmodule\n");
|
||||
let aes_tb = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let kmac_tb = tree.path.join("ip/kmac/dv/tb/ktb.sv");
|
||||
let aes_text = std::fs::read_to_string(&aes_tb).expect("read");
|
||||
let kmac_text = std::fs::read_to_string(&kmac_tb).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![
|
||||
configuration_answer(the_whole_workspace()),
|
||||
did_open(&aes_tb, &aes_text),
|
||||
did_open(&kmac_tb, &kmac_text),
|
||||
definition_at(7, &kmac_tb, 1, 3),
|
||||
],
|
||||
);
|
||||
let said = session.drain();
|
||||
let started = scan_started(&said);
|
||||
assert!(started.contains("4 files (the folder first)"), "both blocks lead: {started}");
|
||||
let found = result_of(&said, 7).expect("a result");
|
||||
assert_eq!(
|
||||
found[0]["uri"],
|
||||
serde_json::json!(path_to_uri(&tree.path.join("ip/kmac/rtl/kmac.sv")).expect("uri")),
|
||||
"the second buffer's own block is in the head too: {found}"
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.workspace.index().files().len(),
|
||||
INTERLEAVE_ABOVE + 10,
|
||||
"every file once, the head's included"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_buffer_leads_with_its_own_text_and_not_the_disk_copy() {
|
||||
// Unsaved-buffer precedence, at the head. The buffer names a module the
|
||||
// file on disk does not, and the definition sent behind it must resolve
|
||||
// — which it can only do if the head indexed the buffer's own text.
|
||||
let tree = a_block_and_a_crowd("splitunsaved", INTERLEAVE_ABOVE + 6);
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
// On disk the testbench instantiates nothing at all.
|
||||
tree.write("ip/aes/dv/tb/tb.sv", "module tb;\nendmodule\n");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![
|
||||
configuration_answer(the_whole_workspace()),
|
||||
did_open(&opened, "module tb;\n aes dut ();\nendmodule\n"),
|
||||
definition_at(7, &opened, 1, 3),
|
||||
],
|
||||
);
|
||||
let said = session.drain();
|
||||
assert!(scan_started(&said).contains("(the folder first)"), "{}", scan_started(&said));
|
||||
let found = result_of(&said, 7).expect("a result");
|
||||
assert_eq!(
|
||||
found[0]["uri"],
|
||||
serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")),
|
||||
"the head indexed the buffer, not the file under it: {found}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The cross-folder fixture: the buffer's folder is `ip/aes`, and what it
|
||||
/// instantiates lives in `ip/kmac` — so the head the split publishes first
|
||||
/// cannot answer the definition in it.
|
||||
fn a_block_that_instantiates_the_block_next_door(tag: &str) -> Tree {
|
||||
let tree = a_block_and_a_crowd(tag, INTERLEAVE_ABOVE + 6);
|
||||
tree.write("ip/kmac/rtl/kmac.sv", "module kmac;\nendmodule\n");
|
||||
tree.write("ip/aes/dv/tb/tb.sv", "module tb;\n kmac dut ();\nendmodule\n");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_outside_the_head_is_asked_again_rather_than_answered_nowhere() {
|
||||
// **§61.3's honest limit, closed by §61.4's rule.** A held request is
|
||||
// drained the moment the user's own folder is published, and a definition
|
||||
// whose target lives in *another* folder used to be answered `[]` there —
|
||||
// coherent, and wrong by the time the scan ended. The rule now says an
|
||||
// empty **navigation** answer computed while the index is still growing is
|
||||
// not an answer: the request is put back and asked again at the scan's
|
||||
// next publish, and at the latest when the scan ends
|
||||
// (`docs/features/perf5r-publication/README.md`).
|
||||
//
|
||||
// This fixture stages under `PUBLISH_EVERY` files, so there is exactly one
|
||||
// publish — the head's — and the request is answered where the second half
|
||||
// of the rule catches it: at the end of the scan, with the right location.
|
||||
let tree = a_block_that_instantiates_the_block_next_door("splitcrossfolder");
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![
|
||||
configuration_answer(the_whole_workspace()),
|
||||
did_open(&opened, &text),
|
||||
definition_at(7, &opened, 1, 3),
|
||||
],
|
||||
);
|
||||
let said = session.drain();
|
||||
let found = result_of(&said, 7).expect("a result, not a failure");
|
||||
assert_eq!(
|
||||
found[0]["uri"],
|
||||
serde_json::json!(path_to_uri(&tree.path.join("ip/kmac/rtl/kmac.sv")).expect("uri")),
|
||||
"the block next door, which is the settled answer: {found}"
|
||||
);
|
||||
|
||||
// Once, not twice: the deferral puts the request back, it does not answer
|
||||
// it and then answer it again.
|
||||
let answers = said
|
||||
.iter()
|
||||
.filter(|message| matches!(message, Message::Response(r) if r.id == RequestId::from(7)))
|
||||
.count();
|
||||
assert_eq!(answers, 1, "one response for one request: {said:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_navigation_answer_that_is_genuinely_empty_is_answered_when_the_scan_ends() {
|
||||
// **The rule defers; it never withholds.** A cursor on a name nothing in
|
||||
// the workspace declares is empty at every publish and empty at settle,
|
||||
// and the request is answered all the same — with `[]`, once the scan has
|
||||
// stopped being a reason to doubt it.
|
||||
let tree = a_block_and_a_crowd("crossfoldergenuinelyempty", INTERLEAVE_ABOVE + 6);
|
||||
tree.write("ip/aes/dv/tb/tb.sv", "module tb;\n nowhere dut ();\nendmodule\n");
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![
|
||||
configuration_answer(the_whole_workspace()),
|
||||
did_open(&opened, &text),
|
||||
definition_at(7, &opened, 1, 3),
|
||||
],
|
||||
);
|
||||
let said = session.drain();
|
||||
let found = result_of(&said, 7).expect("a result, not a failure");
|
||||
assert_eq!(
|
||||
found.as_array().map(Vec::len),
|
||||
Some(0),
|
||||
"nothing declares `nowhere`, and the answer says so: {found}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_type_definition_outside_the_head_is_asked_again_too() {
|
||||
// The rule is three methods wide and the definition test only walks one of
|
||||
// them. A `typeDefinition` on the instance name answers with the module it
|
||||
// instantiates, which lives in the block next door: empty off the head,
|
||||
// right once the scan has been all the way round.
|
||||
let tree = a_block_that_instantiates_the_block_next_door("splitcrossfoldertype");
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let ask = Message::Request(Request::new(
|
||||
RequestId::from(7),
|
||||
GotoTypeDefinition::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": path_to_uri(&opened).expect("uri") },
|
||||
"position": { "line": 1, "character": 7 },
|
||||
}),
|
||||
));
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text), ask],
|
||||
);
|
||||
let found = result_of(&session.drain(), 7).expect("a result, not a failure");
|
||||
assert_eq!(
|
||||
found[0]["uri"],
|
||||
serde_json::json!(path_to_uri(&tree.path.join("ip/kmac/rtl/kmac.sv")).expect("uri")),
|
||||
"the instance's module, from the block next door: {found}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hover_is_never_deferred_however_empty_it_is() {
|
||||
// **The rule is three methods wide, and this is the wall.** A hover
|
||||
// answers `null` for a name the index has not reached, and `null` is what
|
||||
// a hover means by "nothing to say" whatever the scan has done — so it is
|
||||
// answered where every mid-scan request is answered, inside the scan and
|
||||
// before the bar comes down. Deferring it would be withholding an answer
|
||||
// rather than waiting for a better one.
|
||||
let tree = a_block_that_instantiates_the_block_next_door("crossfolderhover");
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let hover = Message::Request(Request::new(
|
||||
RequestId::from(7),
|
||||
HoverRequest::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": path_to_uri(&opened).expect("uri") },
|
||||
"position": { "line": 1, "character": 3 },
|
||||
}),
|
||||
));
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text), hover],
|
||||
);
|
||||
let said = session.drain();
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
let answered = answered.expect("the hover is answered at all");
|
||||
assert!(
|
||||
answered < ended.expect("the bar comes down"),
|
||||
"inside the scan, at the head publish, like every other mid-scan request: {said:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_bigger_than_the_head_bound_is_scanned_exactly_as_it_always_was() {
|
||||
// **`HEAD_WALK_MAX`, pinned** — the bound QA found untested in §61.3. Past
|
||||
// 512 files the neighbourhood is not provably a minority of anything, so
|
||||
// the split is refused: the walk is finished there and then, the two lists
|
||||
// are merged in path order, and the scan is the one every scan before the
|
||||
// split was. The proof is in three parts — the scan does not say "the
|
||||
// folder first", every file is indexed once, and the index it lands is the
|
||||
// one a session with nothing open lands.
|
||||
let tree = a_block_and_a_crowd("headwalkmax", 4);
|
||||
for n in 0..=HEAD_WALK_MAX {
|
||||
tree.package(&format!("ip/aes/rtl/big{n:04}.sv"), &format!("big{n:04}"));
|
||||
}
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text)],
|
||||
);
|
||||
let started = scan_started(&session.drain());
|
||||
assert!(
|
||||
!started.contains("the folder first"),
|
||||
"a neighbourhood over the bound is walked with everything else: {started}"
|
||||
);
|
||||
|
||||
// Every file once: the whole tree is `crowd/` (4) + `ip/aes/rtl` (1 + the
|
||||
// padding) + `ip/aes/dv/tb` (1) + `ip/kmac` (none here).
|
||||
let files = session.server.workspace.index().files();
|
||||
let expected = 4 + 1 + (HEAD_WALK_MAX + 1) + 1;
|
||||
assert_eq!(files.len(), expected, "every file, and none of them twice");
|
||||
let mut sorted = files.to_vec();
|
||||
sorted.sort();
|
||||
sorted.dedup();
|
||||
assert_eq!(sorted.len(), files.len(), "no path is in the index twice");
|
||||
|
||||
// And the index is the one the bound's other side would have built.
|
||||
let quiet = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace())],
|
||||
);
|
||||
let _ = quiet.drain();
|
||||
assert_eq!(
|
||||
session.server.workspace.index().fingerprint(),
|
||||
quiet.server.workspace.index().fingerprint(),
|
||||
"the open buffer bought the order, never a different index"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_paints_no_percentage_until_the_denominator_is_final() {
|
||||
// `docs/features/indexing-ux/README.md`: the percentage only counts up,
|
||||
// and every one of them is measured. While the neighbourhood is being
|
||||
// stepped the denominator is the head — which is about to grow twentyfold
|
||||
// — so no report is sent at all, and the first one the client sees is
|
||||
// against the finished work list. The per-file log still names every
|
||||
// file, head included.
|
||||
let tree = a_block_and_a_crowd("splitbar", INTERLEAVE_ABOVE + 6);
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text)],
|
||||
);
|
||||
let said = session.drain();
|
||||
let percentages: Vec<u64> = said
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
n.params["value"]["percentage"].as_u64()
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!percentages.is_empty(), "the bar does report: {said:#?}");
|
||||
assert!(
|
||||
percentages.windows(2).all(|pair| pair[0] <= pair[1]),
|
||||
"a percentage never falls: {percentages:?}"
|
||||
);
|
||||
// The head is two files of `INTERLEAVE_ABOVE + 8`; a report against the
|
||||
// head alone would have opened at 50%.
|
||||
assert!(percentages[0] < 50, "the first report is measured, not invented: {percentages:?}");
|
||||
|
||||
// And the head's files are still named in the log.
|
||||
let logged: Vec<String> = log_lines(&said)
|
||||
.into_iter()
|
||||
.filter(|line| line.starts_with("indexing: ") || line.starts_with("analyzed: "))
|
||||
.collect();
|
||||
assert!(
|
||||
logged.iter().any(|line| line.ends_with("tb.sv")),
|
||||
"the buffer's own step is logged: {logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
logged.iter().any(|line| line.ends_with("aes.sv")),
|
||||
"and so is the folder's: {logged:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_opens_nothing_waits_only_the_opening_bound_and_scans() {
|
||||
// The cost side of `OPENING_FILE_WAIT`, and its bound. A workspace-scoped
|
||||
// session whose editor has no file open waits the whole of it — nothing
|
||||
// is waiting on the scan, which is why it is affordable — and then scans
|
||||
// the workspace exactly as it did before.
|
||||
assert_eq!(
|
||||
OPENING_FILE_WAIT,
|
||||
Duration::from_millis(25),
|
||||
"the shipped bound, which no test may quietly move"
|
||||
);
|
||||
let tree = trace_tree("splitnoopen", 9);
|
||||
let began = Instant::now();
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace())],
|
||||
);
|
||||
let took = began.elapsed();
|
||||
assert!(took < Duration::from_secs(1), "bounded, and by the small bound: {took:?}");
|
||||
let said = session.drain();
|
||||
let lines = trace_lines(&said);
|
||||
assert_eq!(lines.len(), 3, "one scan: {lines:#?}");
|
||||
assert_eq!(field(&line_of(&lines, "counts"), "read"), "9", "the whole workspace");
|
||||
assert!(!scan_started(&said).contains("the folder first"), "nothing to lead with");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_does_not_lead_with_a_folder_because_nothing_may_be_answered_inside_it() {
|
||||
// The other half of the bound. A whole rescan is one a message asked for,
|
||||
// and `must_wait`'s `answering_a_rescan` holds every request for the whole
|
||||
// of it — so leading with the user's folder buys no answer any sooner and
|
||||
// costs the neighbourhood one extra directory traversal. Only the startup
|
||||
// scan, which nothing is queued ahead of, takes the split.
|
||||
let tree = a_block_and_a_crowd("splitrescan", INTERLEAVE_ABOVE + 6);
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let mut session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text)],
|
||||
);
|
||||
assert!(scan_started(&session.drain()).contains("(the folder first)"), "premise");
|
||||
|
||||
// A changed `exclude` is a scope change, which is a whole rescan.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": {
|
||||
"index": { "scope": "workspace", "logFiles": true },
|
||||
"exclude": ["**/p000.sv"],
|
||||
} } }),
|
||||
);
|
||||
let said = session.drain();
|
||||
let started: Vec<String> = log_lines(&said)
|
||||
.into_iter()
|
||||
.filter(|line| line.starts_with("timing: scan started"))
|
||||
.collect();
|
||||
assert_eq!(started.len(), 1, "one rescan: {started:#?}");
|
||||
assert!(
|
||||
!started[0].contains("the folder first"),
|
||||
"a rescan takes the plain order: {started:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.workspace.index().files().len(),
|
||||
INTERLEAVE_ABOVE + 7,
|
||||
"and the exclusion took one file out"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Directory aliases across a split discovery (F1)
|
||||
// ----------------------------------------------------------------------
|
||||
//
|
||||
// A symlinked directory gives every file under it a second path, and a walk
|
||||
// reports each file under the **first spelling that reaches it**
|
||||
// (`docs/features/walk-cycles/README.md`). The startup scan walks the user's
|
||||
// own folder before it walks the workspace, so the two halves must share that
|
||||
// rule or one module lands in the index twice and cannot be renamed — the
|
||||
// regression `docs/performance_052_review.md` F1 found and every fixture here
|
||||
// pins.
|
||||
//
|
||||
// Each one makes the same three asks of the same tree — after the startup
|
||||
// scan, after a whole rescan, and of a fresh session — and they must agree.
|
||||
|
||||
/// The testbench every fixture opens: it names `child`, which is what the
|
||||
/// definition and the rename below are asked about.
|
||||
#[cfg(unix)]
|
||||
const TB: &str = "module tb;\n child u();\nendmodule\n";
|
||||
|
||||
/// A `child` module and the testbench that instantiates it, in `dir`.
|
||||
#[cfg(unix)]
|
||||
fn alias_pair(tree: &Tree, dir: &str) {
|
||||
tree.write(&format!("{dir}/child.sv"), "module child;\nendmodule\n");
|
||||
tree.write(&format!("{dir}/tb.sv"), TB);
|
||||
}
|
||||
|
||||
/// Where `child` is named in [`TB`] — the cursor every claim below is made at.
|
||||
#[cfg(unix)]
|
||||
fn at_child(uri: &Uri) -> Value {
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 1, "character": 3 },
|
||||
})
|
||||
}
|
||||
|
||||
/// What one session says about a fixture: which files the index holds, where
|
||||
/// the definition of `child` goes, whether that name may be renamed, and what
|
||||
/// the open buffer's diagnostics are.
|
||||
///
|
||||
/// The four together are the review's acceptance: a duplicate shows up as a
|
||||
/// second file, as a second target, and as a refusal to rename — and every
|
||||
/// answer the index feeds moves with it, which is what the diagnostics are
|
||||
/// here to catch.
|
||||
#[cfg(unix)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Says {
|
||||
files: Vec<String>,
|
||||
defs: Vec<Value>,
|
||||
renamable: bool,
|
||||
diagnostics: Vec<Value>,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn says(session: &mut Session, uri: &Uri) -> Says {
|
||||
let answer = session.result(GotoDefinition::METHOD, at_child(uri));
|
||||
let defs: Vec<Value> = serde_json::from_value(answer).expect("definition targets");
|
||||
let prepared = session.request(PrepareRenameRequest::METHOD, at_child(uri));
|
||||
let files =
|
||||
session.server.workspace.index().files().iter().map(|p| p.display().to_string()).collect();
|
||||
// The `resultId` is a generation counter and moves with every rebuild, so
|
||||
// what is compared is what the user sees: each diagnostic's sentence and
|
||||
// where it points.
|
||||
let report = document_pull(session, uri, None);
|
||||
let items = report["items"].as_array().cloned().expect("a full diagnostic report");
|
||||
let diagnostics = items
|
||||
.into_iter()
|
||||
.map(|item| serde_json::json!({ "message": item["message"], "range": item["range"] }))
|
||||
.collect();
|
||||
Says { files, defs, renamable: prepared.response_result.is_ok(), diagnostics }
|
||||
}
|
||||
|
||||
/// Index `tree` with `opened` open, then ask a whole rescan and a fresh
|
||||
/// session the same four questions. Reports what all three said.
|
||||
///
|
||||
/// The rescan trigger is the review's own: a watched-file notification naming
|
||||
/// more than one in-scope file is the whole rebuild rather than the one-file
|
||||
/// incremental path (`server/notification.rs`). No source byte changes, so a
|
||||
/// disagreement is the scan disagreeing with itself.
|
||||
#[cfg(unix)]
|
||||
fn startup_rescan_and_restart_agree(tree: &Tree, opened: &Path, text: &str) -> Says {
|
||||
let uri = path_to_uri(opened).expect("uri");
|
||||
let fresh = || {
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace_flat()), did_open(opened, text)],
|
||||
);
|
||||
session.drain();
|
||||
session
|
||||
};
|
||||
let mut session = fresh();
|
||||
let startup = says(&mut session, &uri);
|
||||
let changed: Vec<PathBuf> = startup.files.iter().map(PathBuf::from).collect();
|
||||
assert!(changed.len() > 1, "the whole-rebuild trigger names more than one file");
|
||||
session.watched(&changed);
|
||||
session.drain();
|
||||
let rescan = says(&mut session, &uri);
|
||||
let restart = says(&mut fresh(), &uri);
|
||||
assert_eq!(startup, rescan, "the startup scan and a whole rescan must agree");
|
||||
assert_eq!(startup, restart, "the startup scan and a fresh session must agree");
|
||||
startup
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_alias_sorting_before_its_target_is_indexed_once_under_the_root_walks_spelling() {
|
||||
// The review's own reproduction. A walk of the root reaches `a_alias`
|
||||
// first, so `a_alias/child.sv` is the canonical spelling and the head —
|
||||
// which would lead with `z_real` — must not be led with at all.
|
||||
let tree = Tree::new("aliasbefore");
|
||||
alias_pair(&tree, "z_real");
|
||||
tree.link("a_alias", "z_real");
|
||||
let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("z_real/tb.sv"), TB);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "a module declared once may be renamed");
|
||||
assert!(
|
||||
said.files.iter().any(|file| file.ends_with("a_alias/child.sv")),
|
||||
"the root walk's own spelling: {:#?}",
|
||||
said.files
|
||||
);
|
||||
assert!(said.diagnostics.is_empty(), "and nothing is wrong with it: {:#?}", said.diagnostics);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_alias_sorting_after_its_target_leaves_the_head_leading() {
|
||||
// Nothing precedes `a_real`, so this one keeps the split — and the
|
||||
// remaining walk must still recognise `z_alias` as the folder it has.
|
||||
let tree = Tree::new("aliasafter");
|
||||
alias_pair(&tree, "a_real");
|
||||
tree.link("z_alias", "a_real");
|
||||
let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("a_real/tb.sv"), TB);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "a module declared once may be renamed");
|
||||
assert!(
|
||||
said.files.iter().any(|file| file.ends_with("a_real/child.sv")),
|
||||
"the target's own spelling: {:#?}",
|
||||
said.files
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn several_aliases_of_one_directory_contribute_one_copy_between_them() {
|
||||
let tree = Tree::new("multialias");
|
||||
alias_pair(&tree, "real");
|
||||
tree.link("a1_alias", "real");
|
||||
tree.link("a2_alias", "real");
|
||||
tree.link("z_alias", "real");
|
||||
let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("real/tb.sv"), TB);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "three aliases are still one declaration");
|
||||
assert_eq!(said.files.len(), 2, "one child, one buffer: {:#?}", said.files);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_alias_of_an_ancestor_of_the_open_folder_falls_back_to_the_one_walk() {
|
||||
// The head would lead with `z_real/sub`, but the root walk reaches the
|
||||
// whole of `z_real` through `a_link` — so the folder's *ancestors* are
|
||||
// what the check has to look at, not the folder alone.
|
||||
let tree = Tree::new("aliasancestor");
|
||||
alias_pair(&tree, "z_real/sub");
|
||||
tree.link("a_link", "z_real");
|
||||
let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("z_real/sub/tb.sv"), TB);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "a module declared once may be renamed");
|
||||
assert!(
|
||||
said.files.iter().any(|file| file.ends_with("a_link/sub/child.sv")),
|
||||
"the root walk's own spelling: {:#?}",
|
||||
said.files
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_ancestor_cycle_inside_the_neighbourhood_ends_and_names_each_file_once() {
|
||||
// `sub/up -> ..` is a link out of the neighbourhood and back to the top,
|
||||
// so the head walk finds the root's own file under `sub/up/top.sv` while
|
||||
// a walk of the root spells it `top.sv`. One spelling reaches the index,
|
||||
// and the rescan the conflict asks for is what settles which.
|
||||
let tree = Tree::new("ancestorcycle");
|
||||
alias_pair(&tree, "sub");
|
||||
tree.write("top.sv", "module top;\nendmodule\n");
|
||||
tree.link("sub/up", "..");
|
||||
let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("sub/tb.sv"), TB);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "the cycle did not duplicate `child`");
|
||||
assert_eq!(said.files.len(), 3, "child, top and the buffer: {:#?}", said.files);
|
||||
assert!(
|
||||
said.files.iter().any(|file| file.ends_with("/top.sv") && !file.contains("/up/")),
|
||||
"the root's file under the root's own spelling: {:#?}",
|
||||
said.files
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_ignored_alias_is_excluded_by_both_halves_of_the_scan() {
|
||||
let tree = Tree::new("ignorealias");
|
||||
tree.write(".gitignore", "a_alias/\n");
|
||||
alias_pair(&tree, "z_real");
|
||||
tree.link("a_alias", "z_real");
|
||||
let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("z_real/tb.sv"), TB);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "a module declared once may be renamed");
|
||||
assert!(
|
||||
said.files.iter().all(|file| !file.contains("a_alias")),
|
||||
"the ignored alias is in nobody's scope: {:#?}",
|
||||
said.files
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_open_unsaved_buffer_is_not_indexed_again_under_an_alias() {
|
||||
// The buffer is `z_real/tb.sv` and the walk's own spelling of it is
|
||||
// `a_alias/tb.sv`: two paths, one file, and an index holding both would
|
||||
// hold `tb` twice while showing the user only one of them.
|
||||
let tree = Tree::new("unsavedalias");
|
||||
alias_pair(&tree, "z_real");
|
||||
tree.link("a_alias", "z_real");
|
||||
let unsaved = "module tb;\n child u();\n localparam UNSAVED = 1;\nendmodule\n";
|
||||
let opened = tree.path.join("z_real/tb.sv");
|
||||
let said = startup_rescan_and_restart_agree(&tree, &opened, unsaved);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "`child` is declared once");
|
||||
assert_eq!(said.files.len(), 2, "one child, one buffer: {:#?}", said.files);
|
||||
|
||||
// And the buffer's own name, which is the one the alias would have
|
||||
// duplicated: renamable, and the unsaved text is what was indexed.
|
||||
let uri = path_to_uri(&opened).expect("uri");
|
||||
let mut session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace_flat()), did_open(&opened, unsaved)],
|
||||
);
|
||||
let _ = session.drain();
|
||||
let at_tb = serde_json::json!({
|
||||
"textDocument": { "uri": &uri },
|
||||
"position": { "line": 0, "character": 8 },
|
||||
});
|
||||
let prepared = session.request(PrepareRenameRequest::METHOD, at_tb);
|
||||
assert!(prepared.response_result.is_ok(), "one `tb`: {:?}", prepared.response_result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_genuine_duplicate_declaration_is_still_ambiguous_at_startup_and_after_a_rescan() {
|
||||
// The other side of the fix, and the reason deduplicating by *name* was
|
||||
// never an option: two physical files really do declare `dup`, and a
|
||||
// rename that picked one of them would be a wrong edit.
|
||||
let tree = Tree::new("legitdup");
|
||||
tree.write("dir1/dup.sv", "module dup;\nendmodule\n");
|
||||
tree.write("dir2/dup.sv", "module dup;\nendmodule\n");
|
||||
let opened = tree.path.join("dir1/dup.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let uri = path_to_uri(&opened).expect("uri");
|
||||
let at_dup = serde_json::json!({
|
||||
"textDocument": { "uri": &uri },
|
||||
"position": { "line": 0, "character": 8 },
|
||||
});
|
||||
|
||||
let mut session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text)],
|
||||
);
|
||||
session.drain();
|
||||
let refused = session.request(PrepareRenameRequest::METHOD, at_dup.clone());
|
||||
let error = refused.response_result.expect_err("two declarations are ambiguous");
|
||||
assert!(error.message.contains("declared in more than one indexed file"), "{}", error.message);
|
||||
|
||||
session.watched(&[opened.clone(), tree.path.join("dir2/dup.sv")]);
|
||||
session.drain();
|
||||
let again = session.request(PrepareRenameRequest::METHOD, at_dup);
|
||||
let rescanned = again.response_result.expect_err("a rescan refuses it the same way");
|
||||
assert_eq!(rescanned.message, error.message, "the same sentence, word for word");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_alias_beside_the_open_folder_indexes_once_and_asks_for_one_rescan() {
|
||||
// The case no pre-check can see: `other/link` is nowhere on the open
|
||||
// folder's own chain, so the head leads with `z_real` and only the
|
||||
// remaining walk finds out that a walk of the root would have spelled
|
||||
// those files `other/link/…`. Nothing is indexed twice — and the scan
|
||||
// asks for the canonical walk once, which is where the spelling
|
||||
// converges.
|
||||
let tree = Tree::new("siblingalias");
|
||||
alias_pair(&tree, "z_real");
|
||||
tree.link("other/link", "../z_real");
|
||||
let opened = tree.path.join("z_real/tb.sv");
|
||||
let uri = path_to_uri(&opened).expect("uri");
|
||||
|
||||
let mut session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace_flat()), did_open(&opened, TB)],
|
||||
);
|
||||
let messages = session.drain();
|
||||
let traces = trace_lines(&messages);
|
||||
let counts: Vec<&String> = traces.iter().filter(|line| line.contains(" counts (")).collect();
|
||||
assert_eq!(counts.len(), 2, "the startup scan and the one rescan it asked for: {traces:#?}");
|
||||
assert_eq!(field(counts[0], "conflict"), "1", "{}", counts[0]);
|
||||
assert_eq!(field(counts[0], "rescan_requested"), "1", "{}", counts[0]);
|
||||
assert_eq!(field(counts[1], "conflict"), "0", "the rescan is one whole walk: {}", counts[1]);
|
||||
assert_eq!(
|
||||
field(counts[1], "rescan_requested"),
|
||||
"0",
|
||||
"and it cannot ask for another: {}",
|
||||
counts[1]
|
||||
);
|
||||
|
||||
// What the startup indexed, from the per-file log: the head's spelling,
|
||||
// one copy of `child`, and no `other/link` beside it.
|
||||
let indexed: Vec<String> =
|
||||
log_lines(&messages).into_iter().filter(|line| line.contains("child.sv")).collect();
|
||||
assert_eq!(indexed.len(), 2, "one `child` per scan, never two: {indexed:#?}");
|
||||
assert!(indexed[0].contains("z_real/child.sv"), "the startup's spelling: {}", indexed[0]);
|
||||
assert!(indexed[1].contains("other/link/child.sv"), "the rescan's: {}", indexed[1]);
|
||||
|
||||
// And what the rescan left: the spelling a plain walk of this tree gives,
|
||||
// which is what every later scan and every restart will produce.
|
||||
let said = says(&mut session, &uri);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "`child` is declared once");
|
||||
assert!(
|
||||
said.files.iter().any(|file| file.ends_with("other/link/child.sv")),
|
||||
"the canonical spelling won: {:#?}",
|
||||
said.files
|
||||
);
|
||||
let plain = startup_rescan_and_restart_agree(&tree, &opened, TB);
|
||||
assert_eq!(said, plain, "and it is stable under a rescan and a restart");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_same_named_file_symlink_outside_the_head_is_not_a_second_copy_of_the_buffer() {
|
||||
// QA's (f) on §62.1: the head walk asked `Aliased` about a same-named
|
||||
// file, the remaining walk did not, so a file symlink to the open buffer
|
||||
// living outside its folder was indexed a second time and `tb` was
|
||||
// falsely declared twice. Now both walks ask.
|
||||
let tree = Tree::new("filealias");
|
||||
alias_pair(&tree, "z_real");
|
||||
tree.link("alias_dir/tb.sv", "../z_real/tb.sv");
|
||||
let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("z_real/tb.sv"), TB);
|
||||
assert_eq!(
|
||||
said.files.iter().filter(|file| file.ends_with("tb.sv")).count(),
|
||||
1,
|
||||
"one `tb.sv`, the buffer's: {:#?}",
|
||||
said.files
|
||||
);
|
||||
assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs);
|
||||
assert!(said.renamable, "`tb` is declared once, whatever the disk spells");
|
||||
assert!(said.diagnostics.is_empty(), "{:#?}", said.diagnostics);
|
||||
}
|
||||
@@ -0,0 +1,794 @@
|
||||
//! Which files a scan will index, how they were found, and what the finding
|
||||
//! cost.
|
||||
//!
|
||||
//! The scope ladder ([`Workspace::source_files`]) and the overlay that lets an
|
||||
//! open buffer beat the disk ([`Workspace::collect_sources`]), lifted out of
|
||||
//! `state/mod.rs` on 2026-09-08 (TODO §61.3) when discovery grew a stage split
|
||||
//! and a second entry point. It answers one question — *which files exist as
|
||||
//! far as this server is concerned, and how big are they* — and every rung of
|
||||
//! the ladder is in this file.
|
||||
//!
|
||||
//! **The size a walked file reports is the walk's own.** `lucisv_core`'s walk
|
||||
//! calls `metadata` on every directory entry to answer "directory?", so the
|
||||
//! length is a field it already holds; asking the filesystem again, once per
|
||||
//! file, was 6.9 ms of a 165 ms discovery over 3 976 files — measured, not
|
||||
//! assumed, and smaller than it looks because the walk has just warmed every
|
||||
//! one of those inodes (`docs/features/perf5r-first-answer/README.md`). A path
|
||||
//! the walk did not stat — a filelist entry, an input named rather than walked
|
||||
//! — carries no length and is stat'd here, exactly as every path used to be.
|
||||
//!
|
||||
//! **And the walk is split in two when it pays to be.** A workspace-scoped
|
||||
//! session with a buffer open walks that buffer's own folders first, so the
|
||||
//! scan can index and publish them before it discovers the other 3 850 files
|
||||
//! ([`Workspace::first_scope`]). One scan, one work list, every file once.
|
||||
//!
|
||||
//! **"Every file once" is a claim about directory identity, not about paths.**
|
||||
//! A symlinked directory gives every file under it a second path, and a walk
|
||||
//! answers that by entering each directory identity once and reporting its
|
||||
//! files under the first spelling that reached it
|
||||
//! (`docs/features/walk-cycles/README.md`). Two walks with two visited sets do
|
||||
//! not have that rule *between* them, which is how the split came to index a
|
||||
//! module twice (`docs/performance_052_review.md` F1). So the two halves share
|
||||
//! one [`DirectoryTracker`]; the head is not led with at all when a walk of the
|
||||
//! root would reach the user's own folder by an earlier name
|
||||
//! ([`Workspace::has_preceding_alias`]); and where only the remaining walk can
|
||||
//! find that out, it says so and the scan asks for one canonical walk
|
||||
//! ([`Scan::wants_rescan`](super::Scan::wants_rescan)).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::walk::{
|
||||
collect_files_below_tracked, collect_files_tracked, dir_id, DirectoryTracker, EXTENSIONS,
|
||||
};
|
||||
|
||||
use crate::scan_trace::ScanTrace;
|
||||
|
||||
use super::scan::{Analyzed, HeldAnalyses, IndexEvent, PendingDiscovery, Sources};
|
||||
use super::Workspace;
|
||||
|
||||
/// One in-scope file, and the length whoever found it already knew.
|
||||
///
|
||||
/// `len` is `None` for a path nothing stat'd on the way here — a filelist
|
||||
/// entry, or an input named rather than walked. It is not "unknown size": it
|
||||
/// is "nobody has looked yet", and [`oversize`] is what looks.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Found {
|
||||
pub(super) path: PathBuf,
|
||||
pub(super) len: Option<u64>,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
/// A path nothing has stat'd.
|
||||
fn unmeasured(path: PathBuf) -> Found {
|
||||
Found { path, len: None }
|
||||
}
|
||||
|
||||
/// One path on its own, for a caller asking the cap about a single file
|
||||
/// rather than about a walk ([`Workspace::current_text`]).
|
||||
pub(super) fn of(path: &Path) -> Found {
|
||||
Found::unmeasured(path.to_path_buf())
|
||||
}
|
||||
}
|
||||
|
||||
/// What the scope ladder decided: the files to index, the directories an
|
||||
/// `` `include`` in them is looked for in, and what to tell the user.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Scope {
|
||||
pub(super) files: Vec<Found>,
|
||||
/// The filelist's `+incdir+`s, in filelist order. Empty for every rung
|
||||
/// but the filelist — nothing else names an include path.
|
||||
pub(super) incdirs: Vec<PathBuf>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The size of `found` when it is over `cap`, else `None` — the whole of the
|
||||
/// `lucisv.index.maxFileSize` test.
|
||||
///
|
||||
/// Metadata only: the point of the cap is that a 200 MB netlist is never read
|
||||
/// into memory, so knowing how big it is has to come first. A `cap` of 0 is
|
||||
/// the client asking for no cap, and a file whose metadata cannot be read is
|
||||
/// not skipped here — it simply fails the read later, as it always did.
|
||||
///
|
||||
/// `stats` counts the `metadata` calls this one really made, so a session can
|
||||
/// prove the walk's hand-off removed them rather than assert it.
|
||||
pub(super) fn oversize(found: &Found, cap: u64, stats: &mut usize) -> Option<u64> {
|
||||
if cap == 0 {
|
||||
return None;
|
||||
}
|
||||
let size = match found.len {
|
||||
Some(size) => size,
|
||||
None => {
|
||||
*stats += 1;
|
||||
fs::metadata(&found.path).ok()?.len()
|
||||
}
|
||||
};
|
||||
(size > cap).then_some(size)
|
||||
}
|
||||
|
||||
/// The open buffers' files by **identity**, so a walked path that is a second
|
||||
/// spelling of one of them can be recognised and left out.
|
||||
///
|
||||
/// A symlinked directory gives every file under it a second path. The walk
|
||||
/// reports each file under the first spelling that reaches it, which may not be
|
||||
/// the one the buffer was opened by — and an index holding `a_alias/tb.sv` from
|
||||
/// disk beside the open `z_real/tb.sv` holds one module twice and refuses to
|
||||
/// rename it (`docs/features/walk-cycles/README.md`).
|
||||
///
|
||||
/// **The name is the gate, and it is what keeps this free.** A directory alias
|
||||
/// cannot change a file's *name*, so a walked file whose name no open buffer
|
||||
/// shares cannot be one of them and is never stat'd: an ordinary workspace pays
|
||||
/// nothing at all, and one with same-named files pays one `metadata` per
|
||||
/// same-named candidate. A **file**-level symlink under a different name is out
|
||||
/// of scope — two names for one inode that no directory relates, which every
|
||||
/// other part of this server already treats as two files.
|
||||
struct Aliased {
|
||||
/// The names those buffers' files go by — the cheap half of the test.
|
||||
names: HashSet<std::ffi::OsString>,
|
||||
/// Their `(dev, ino)` identities, read once per open buffer rather than
|
||||
/// once per walked file.
|
||||
ids: HashSet<lucisv_core::walk::DirId>,
|
||||
}
|
||||
|
||||
impl Aliased {
|
||||
/// The identities of `paths`, with the names to gate on.
|
||||
fn of(paths: &HashSet<&Path>) -> Aliased {
|
||||
let names = paths.iter().filter_map(|p| p.file_name()).map(|n| n.to_os_string()).collect();
|
||||
let ids = paths.iter().filter_map(|p| dir_id(p)).collect();
|
||||
Aliased { names, ids }
|
||||
}
|
||||
|
||||
/// Whether `path` names a file an open buffer already speaks for, by a
|
||||
/// different spelling. `stats` counts the `metadata` calls it made.
|
||||
fn speaks_for(&self, path: &Path, stats: &mut usize) -> bool {
|
||||
if self.ids.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(name) = path.file_name() else { return false };
|
||||
if !self.names.contains(name) {
|
||||
return false;
|
||||
}
|
||||
*stats += 1;
|
||||
dir_id(path).is_some_and(|id| self.ids.contains(&id))
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
/// Resolve the scope: which files are in it, with open buffers overriding
|
||||
/// disk, and those buffers' own text.
|
||||
///
|
||||
/// **Metadata only, plus what is already in memory.** Nothing on disk is
|
||||
/// read here — a file's text is read by whoever indexes or rewrites it,
|
||||
/// one file at a time ([`Workspace::scan_step`], [`Workspace::sources`]).
|
||||
///
|
||||
/// This is where `lucisv.index.maxFileSize` applies, and it applies to the
|
||||
/// **walked** files only: an open buffer is folded in below whatever its
|
||||
/// size, because the user opened it deliberately and an editor that
|
||||
/// refused to understand the file on screen would be absurd. The check is
|
||||
/// the size the walk read, so an oversized file is still never read at all
|
||||
/// — which is the whole saving, and it is still counted and reported here
|
||||
/// so that a scan's skip count is known before its first step.
|
||||
///
|
||||
/// A refactoring reads this same list through `sources()`, so a file the
|
||||
/// cap keeps out of the index is also a file a workspace rename will not
|
||||
/// rewrite. That is the consistent answer: the cap says which files exist
|
||||
/// as far as this server is concerned.
|
||||
pub(super) fn collect_sources(
|
||||
&self,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
analyses: HeldAnalyses,
|
||||
trace: &mut ScanTrace,
|
||||
) -> Sources {
|
||||
let scope = self.source_files(trace);
|
||||
self.overlay_buffers(scope, watch, analyses, trace)
|
||||
}
|
||||
|
||||
/// [`Workspace::collect_sources`] over one already-resolved scope — the
|
||||
/// cap, then the open buffers over the top.
|
||||
///
|
||||
/// Split out because the two-phase startup resolves the scope twice (the
|
||||
/// user's own folders, then the rest of the workspace) and both halves owe
|
||||
/// the buffers the same precedence.
|
||||
pub(super) fn overlay_buffers(
|
||||
&self,
|
||||
scope: Scope,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
analyses: HeldAnalyses,
|
||||
trace: &mut ScanTrace,
|
||||
) -> Sources {
|
||||
let cap = self.client.max_file_size;
|
||||
// Every path an open buffer speaks for. Reading such a file from disk
|
||||
// is work thrown away — the buffer's text replaces it below, whatever
|
||||
// the disk says — so the read is skipped rather than undone. The cap is
|
||||
// still consulted first, so an oversized file still reports itself
|
||||
// skipped exactly as it did before the buffer put its own text back.
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
// …and every *other* spelling of those same files, which a directory
|
||||
// alias makes and a path comparison cannot see ([`Aliased`]).
|
||||
let aliased = Aliased::of(&spoken_for);
|
||||
let capping = trace.now();
|
||||
let mut stats = 0usize;
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
for found in scope.files {
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
watch(IndexEvent::Skipped { path: &found.path, size, cap });
|
||||
continue;
|
||||
}
|
||||
if spoken_for.contains(found.path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
if aliased.speaks_for(&found.path, &mut stats) {
|
||||
continue;
|
||||
}
|
||||
files.push(found.path);
|
||||
}
|
||||
ScanTrace::add(&mut trace.cap_ms, capping);
|
||||
trace.stats += stats;
|
||||
// Open buffers override what is on disk, and contribute themselves
|
||||
// when they are not on disk at all.
|
||||
//
|
||||
// Except a buffer on the large-file fast path, which overrides disk
|
||||
// with *nothing*: indexing it means parsing the hundred megabytes the
|
||||
// fast path exists not to parse. Removing the path rather than leaving
|
||||
// the disk copy in is the honest half of that — the alternative would
|
||||
// be an index describing a file the user is looking at by bytes it no
|
||||
// longer has. See `docs/features/large-file-mode/README.md` for the
|
||||
// interaction with `lucisv.index.maxFileSize`, whose "an open buffer is
|
||||
// never capped" rule this is the one exception to.
|
||||
let buffering = trace.now();
|
||||
let mut analyzed = Analyzed::default();
|
||||
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
|
||||
for doc in self.docs.values() {
|
||||
let Some(path) = doc.path.clone() else { continue };
|
||||
files.retain(|p| p != &path);
|
||||
if !doc.large {
|
||||
if analyses == HeldAnalyses::Wanted {
|
||||
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
|
||||
analyzed.words.insert(path.clone(), doc.words());
|
||||
}
|
||||
buffered.insert(path.clone(), doc.text.clone());
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
ScanTrace::add(&mut trace.buffers_ms, buffering);
|
||||
Sources { files, buffered, analyzed, incdirs: scope.incdirs, warnings: scope.warnings }
|
||||
}
|
||||
|
||||
/// The files the index covers, and what the user should be told about how
|
||||
/// they were chosen. The scope ladder, highest first:
|
||||
///
|
||||
/// 1. **A filelist** — `lucisv.filelist`, else a `filelist` key in the
|
||||
/// config governing a workspace root. It names *exactly* the files to
|
||||
/// index; the project said so, and guessing past it would defeat the
|
||||
/// point of having one. This is the "project file", and it is the one
|
||||
/// rung that is whole-project by definition.
|
||||
/// 2. **The workspace-folder walk**, on `lucisv.index.scope:
|
||||
/// "workspace"` — what every session did before 2026-08-27, now opt-in.
|
||||
/// 3. **The folder scope**, the default: each opened buffer's own
|
||||
/// directory raised `lucisv.index.scopeDepth` levels, walked. See
|
||||
/// `docs/features/index-scope/README.md` for what that costs, which is
|
||||
/// that a definition in another folder does not resolve until the
|
||||
/// scope reaches that folder.
|
||||
///
|
||||
/// A configured filelist that cannot be read falls back to rung 2 (or 3)
|
||||
/// with a warning. An editor that shows no symbols because of a typo in a
|
||||
/// path is worse than one that quietly indexes what it can and says so.
|
||||
///
|
||||
/// Only rung 1 can carry `+incdir+` directories: a walked workspace names
|
||||
/// none, so an `` `include`` there resolves against the including file's
|
||||
/// own directory alone (`docs/features/include-nav/README.md`).
|
||||
pub(super) fn source_files(&self, trace: &mut ScanTrace) -> Scope {
|
||||
// The walk's own warnings join the scope's, so an unreadable directory
|
||||
// reaches the output channel by the road a filelist's problems already
|
||||
// travel — said once per scan and never per keystroke.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let Some(path) = self.filelist_path() else {
|
||||
let files = self.default_files(&mut |w| warnings.push(w), trace);
|
||||
return Scope { files, warnings, ..Default::default() };
|
||||
};
|
||||
let reading = trace.now();
|
||||
let read = lucisv_core::filelist::read(&path);
|
||||
ScanTrace::add(&mut trace.filelist_ms, reading);
|
||||
match read {
|
||||
Ok(list) => Scope {
|
||||
files: list.files.into_iter().map(Found::unmeasured).collect(),
|
||||
incdirs: list.incdirs,
|
||||
warnings: list.warnings,
|
||||
},
|
||||
Err(problem) => {
|
||||
let files = self.default_files(&mut |w| warnings.push(w), trace);
|
||||
warnings.insert(0, format!("{problem} — indexing the workspace instead"));
|
||||
Scope { files, incdirs: Vec::new(), warnings }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The filelist governing this workspace, if any: the client's setting
|
||||
/// first (absolute, or relative to the first root), else the `filelist`
|
||||
/// key of the config governing a root, in root order.
|
||||
///
|
||||
/// Public because the file watchers must name it: a `.f` edited outside
|
||||
/// the editor changes the index's scope, and nothing else on disk would
|
||||
/// tell us (`docs/features/file-watching/README.md`).
|
||||
pub fn filelist_path(&self) -> Option<PathBuf> {
|
||||
if let Some(setting) = &self.client.filelist {
|
||||
let path = Path::new(setting);
|
||||
return Some(match self.roots.first() {
|
||||
Some(root) if path.is_relative() => root.join(path),
|
||||
_ => path.to_path_buf(),
|
||||
});
|
||||
}
|
||||
let mut discovery = Discovery::new(true);
|
||||
// A broken `lucisv.toml` names no filelist, exactly as it contributes no
|
||||
// excludes below: the user hears about it when they format.
|
||||
self.roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
|
||||
}
|
||||
|
||||
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
|
||||
/// asked for it, else the folder scope.
|
||||
fn default_files(&self, warn: &mut dyn FnMut(String), trace: &mut ScanTrace) -> Vec<Found> {
|
||||
if self.walks_the_workspace() {
|
||||
return self.walked_files(&self.roots, warn, trace);
|
||||
}
|
||||
self.folder_files(warn, trace)
|
||||
}
|
||||
|
||||
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
|
||||
/// filter the workspace walk applies.
|
||||
///
|
||||
/// One exception, kept exactly as it was from before this rung became the
|
||||
/// default: **a rootless session at depth 0 reads its directories flat**,
|
||||
/// one level, no `.gitignore`. That is the "a file opened on its own"
|
||||
/// case, where descending a tree the user never named would be a surprise
|
||||
/// — and the moment the user raises `scopeDepth` they have named one, so
|
||||
/// the walk is what they asked for.
|
||||
fn folder_files(&self, warn: &mut dyn FnMut(String), trace: &mut ScanTrace) -> Vec<Found> {
|
||||
let dirs = self.scope_dirs();
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(&dirs, trace);
|
||||
}
|
||||
self.walked_files(&dirs, warn, trace)
|
||||
}
|
||||
|
||||
/// Every source file under `dirs`, found by the CLI's own walk: the same
|
||||
/// extensions, the same `.gitignore` handling, and the `exclude` patterns
|
||||
/// of the config governing each directory. What `lucisv` skips, the index
|
||||
/// skips.
|
||||
///
|
||||
/// `dirs` is the workspace roots for rung 2 and the scope directories for
|
||||
/// rung 3. The one honest difference between the two: `.gitignore` files
|
||||
/// are read from the walk's own starting directory downwards, so a rule
|
||||
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
|
||||
/// starts below it. The `exclude` patterns are matched against whole
|
||||
/// paths and so behave identically either way.
|
||||
pub(super) fn walked_files(
|
||||
&self,
|
||||
dirs: &[PathBuf],
|
||||
warn: &mut dyn FnMut(String),
|
||||
trace: &mut ScanTrace,
|
||||
) -> Vec<Found> {
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
self.walked_files_tracked(dirs, &mut tracker, warn, trace)
|
||||
}
|
||||
|
||||
/// [`Workspace::walked_files`] over an existing [`DirectoryTracker`], so
|
||||
/// two walks of one scan enter each directory identity once between them.
|
||||
pub(super) fn walked_files_tracked(
|
||||
&self,
|
||||
dirs: &[PathBuf],
|
||||
tracker: &mut DirectoryTracker,
|
||||
warn: &mut dyn FnMut(String),
|
||||
trace: &mut ScanTrace,
|
||||
) -> Vec<Found> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut out: Vec<Found> = Vec::new();
|
||||
for root in dirs {
|
||||
// The walk names its inputs as strings; every directory here came
|
||||
// from a `file:` URI, which cannot carry a non-UTF-8 path.
|
||||
let Some(input) = root.to_str() else { continue };
|
||||
// A broken `lucisv.toml` must not stop the server from indexing: an
|
||||
// index that excludes nothing is a far better failure than a
|
||||
// server that comes up empty. The error is reported when the user
|
||||
// formats a file in this tree (`format::settings_for`).
|
||||
let configuring = trace.now();
|
||||
let mut exclude =
|
||||
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
|
||||
// The client's `lucisv.exclude` is *appended*, never substituted —
|
||||
// the CLI appends a config's excludes to `--exclude` the same way,
|
||||
// and a setting that silently dropped a checked-in exclude would
|
||||
// put vendored code back in the index for one user only.
|
||||
exclude.extend(self.client.exclude.iter().cloned());
|
||||
ScanTrace::add(&mut trace.config_ms, configuring);
|
||||
// `.gitignore` is always honoured: it is the CLI's default, and an
|
||||
// editor has no `--no-gitignore` to type. An unreadable directory
|
||||
// is skipped and said — the warning rides out on the scope's own
|
||||
// warnings, which `server/notification.rs` logs once per scan.
|
||||
let walking = trace.now();
|
||||
let _ = collect_files_tracked(
|
||||
input,
|
||||
&exclude,
|
||||
true,
|
||||
tracker,
|
||||
&mut |path, len| out.push(Found { path, len }),
|
||||
&mut |w| warn(w.to_string()),
|
||||
);
|
||||
ScanTrace::add(&mut trace.walk_ms, walking);
|
||||
trace.walk_dirs += 1;
|
||||
}
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
|
||||
/// The files the directories a widen added bring into scope, by the same
|
||||
/// rules [`Workspace::folder_files`] applies to the whole scope — including
|
||||
/// the rootless-at-depth-0 flat read.
|
||||
pub(super) fn widened_files(
|
||||
&self,
|
||||
added: &[PathBuf],
|
||||
warn: &mut dyn FnMut(String),
|
||||
trace: &mut ScanTrace,
|
||||
) -> Vec<Found> {
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(added, trace);
|
||||
}
|
||||
self.walked_files(added, warn, trace)
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest neighbourhood a startup will index before it finds out how big
|
||||
/// the workspace is.
|
||||
///
|
||||
/// The split's whole premise is that the user's own folder is a small part of
|
||||
/// the workspace, so stepping it first costs the rest of the scan nothing a
|
||||
/// user notices. Beyond this many files that premise is not proven — the
|
||||
/// count that would prove it is the walk this order exists to postpone — so
|
||||
/// the walk is finished first and the scan is ordered exactly as it was
|
||||
/// before, `scan_order::worth_waiting` and all.
|
||||
///
|
||||
/// 512 is a measured bound and not a round number: a warm step costs about
|
||||
/// 0.2 ms a file (124 files in 25 ms, `docs/features/perf5-p4/README.md`
|
||||
/// §P4b3), so a head of this size is ~100 ms of stepping and the whole first
|
||||
/// answer still fits inside the round's 200 ms gate.
|
||||
pub(crate) const HEAD_WALK_MAX: usize = 512;
|
||||
|
||||
impl Workspace {
|
||||
/// Whether this scan may walk the user's own folders first and the rest of
|
||||
/// the workspace afterwards.
|
||||
///
|
||||
/// Three conditions, and each of them names a case the split would
|
||||
/// otherwise make *worse*:
|
||||
///
|
||||
/// * **the workspace walk is the rung in force.** It is the only rung
|
||||
/// whose discovery is a walk of everything: a filelist names its files
|
||||
/// and reads in one go, and the folder rung's own scope *is* the
|
||||
/// neighbourhood, so splitting it would put the whole scan in the head.
|
||||
/// * **a buffer is open, in a folder below a workspace root.** With no
|
||||
/// buffer there is no neighbourhood to lead with; with one opened from
|
||||
/// the root itself, the folder it raises to *is* the workspace, which is
|
||||
/// the case `scan_order::worth_waiting` exists for and the case this
|
||||
/// returns `false` for so that rule still decides it.
|
||||
/// * **the walk finds a small enough neighbourhood** — checked by the
|
||||
/// caller once the folders are walked, against [`HEAD_WALK_MAX`].
|
||||
/// * **it is the session's first scan** — checked by the caller, which is
|
||||
/// the only one that knows the scan number.
|
||||
pub(super) fn splits_discovery(&self) -> bool {
|
||||
if !self.leads_with_a_folder() {
|
||||
return false;
|
||||
}
|
||||
let dirs = self.raised_dirs();
|
||||
!dirs.is_empty() && dirs.iter().all(|dir| self.below_a_root(dir))
|
||||
}
|
||||
|
||||
/// Whether a scan of this workspace would lead with the user's own folder
|
||||
/// if it knew one — the rung half of [`Workspace::splits_discovery`],
|
||||
/// asked on its own by the startup that waits a bounded moment to be told
|
||||
/// which folder that is (`server/startup.rs`).
|
||||
pub fn leads_with_a_folder(&self) -> bool {
|
||||
self.walks_the_workspace()
|
||||
}
|
||||
|
||||
/// Whether `dir` is a **strict** descendant of some workspace root.
|
||||
///
|
||||
/// A directory that *is* a root is the whole of that root's walk, so
|
||||
/// leading with it is leading with everything.
|
||||
fn below_a_root(&self, dir: &Path) -> bool {
|
||||
self.roots.iter().any(|root| dir.starts_with(root) && dir != root)
|
||||
}
|
||||
|
||||
/// What a whole scan starts from: its scope, and whatever of that scope is
|
||||
/// still to be walked.
|
||||
///
|
||||
/// `None` for the second half means what it has always meant — the scope
|
||||
/// was resolved entire before the first file was indexed, and the work
|
||||
/// list the caller gets is the whole of it. `Some` means the caller is
|
||||
/// holding the user's own folders and owes itself the rest of the
|
||||
/// workspace once it has published them ([`PendingDiscovery`]).
|
||||
pub(super) fn first_scope(
|
||||
&self,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
trace: &mut ScanTrace,
|
||||
) -> (Sources, Option<PendingDiscovery>) {
|
||||
// **The session's first scan only.** Every later whole rescan is one a
|
||||
// message asked for, and `must_wait`'s `answering_a_rescan` holds every
|
||||
// request for the whole of it — so leading with a folder buys no answer
|
||||
// any sooner and costs the neighbourhood one extra directory
|
||||
// traversal. The startup scan is the one nothing is queued ahead of,
|
||||
// and it is the one this order is for
|
||||
// (`docs/features/perf5r-first-answer/README.md`).
|
||||
if trace.number > 1 || !self.splits_discovery() {
|
||||
return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None);
|
||||
}
|
||||
// A directory alias that a root walk would reach *before* the folder
|
||||
// the head would lead with: leading with it would spell those files a
|
||||
// way no other scan of this workspace ever does
|
||||
// ([`Workspace::has_preceding_alias`]). The whole scope, walked once,
|
||||
// is the answer — a millisecond on a fixture and ~155 ms on
|
||||
// opentitan, and only for a session whose own folder is aliased.
|
||||
for dir in self.raised_dirs() {
|
||||
if let Some(root) = self.deepest_root(&dir) {
|
||||
if self.has_preceding_alias(&root, &dir) {
|
||||
return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
let head = self.neighbourhood_files(&mut tracker, &mut |w| warnings.push(w), trace);
|
||||
if head.len() > HEAD_WALK_MAX {
|
||||
// Too big to lead with unproven. The head is **discarded** and the
|
||||
// whole scope walked once, ordered the way every scan before this
|
||||
// one was: keeping it and walking the rest beside it would union
|
||||
// two walks that never agreed on a directory's spelling, which is
|
||||
// the very thing the tracker exists to prevent.
|
||||
return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None);
|
||||
}
|
||||
// Every path the neighbourhood walk named, before the cap has had a
|
||||
// say: what the remaining walk must not decide about a second time.
|
||||
let mut seen: HashSet<PathBuf> = head.iter().map(|found| found.path.clone()).collect();
|
||||
seen.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
let scope = Scope { files: head, incdirs: Vec::new(), warnings };
|
||||
let sources = self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace);
|
||||
(sources, Some(PendingDiscovery { roots: self.roots.clone(), seen, tracker }))
|
||||
}
|
||||
|
||||
/// Whether some directory between `root` and `dir` holds a **second
|
||||
/// spelling** of `dir` or of one of its ancestors that a walk of `root`
|
||||
/// would reach *first*.
|
||||
///
|
||||
/// The one case the split cannot lead with. A walk of the root reports
|
||||
/// each directory under the first path that reaches it, in name order, so
|
||||
/// with `a_alias -> z_real` the whole of `z_real` is spelled `a_alias/…`;
|
||||
/// a head walk starting at `z_real` would spell it `z_real/…` and the two
|
||||
/// halves of one scan would disagree with each other and with every later
|
||||
/// rescan. Asked before the head is walked, so the answer is a *fallback*
|
||||
/// to the single canonical walk and never a repair afterwards.
|
||||
///
|
||||
/// **It reads directories and stats symlinks only.** The chain from a
|
||||
/// buffer's folder to the root is a handful of directories (four on
|
||||
/// opentitan, ~150 entries between them); `read_dir` already carries each
|
||||
/// entry's kind, so an ordinary tree costs no `metadata` at all.
|
||||
fn has_preceding_alias(&self, root: &Path, dir: &Path) -> bool {
|
||||
let targets = identities_to(root, dir);
|
||||
!targets.is_empty()
|
||||
&& ancestors_to(root, dir).into_iter().any(|up| precedes_a_target(up, &targets))
|
||||
}
|
||||
|
||||
/// The user's own neighbourhood, walked: every source file under the
|
||||
/// folders the open buffers raise to, **as the walk of the workspace root
|
||||
/// would have found them**.
|
||||
///
|
||||
/// `collect_files_below` rather than `collect_files_with` is the whole of
|
||||
/// that "as": a walk starting at `hw/ip/aes` reads no `.gitignore` above
|
||||
/// itself, and the rung in force here is the *root's*, so the folder half
|
||||
/// of one scope must obey the same rules the other half does. Without it
|
||||
/// the head would index files the rest of the scan excludes, and the two
|
||||
/// halves of one scan would disagree about which files exist.
|
||||
fn neighbourhood_files(
|
||||
&self,
|
||||
tracker: &mut DirectoryTracker,
|
||||
warn: &mut dyn FnMut(String),
|
||||
trace: &mut ScanTrace,
|
||||
) -> Vec<Found> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut out: Vec<Found> = Vec::new();
|
||||
for dir in self.raised_dirs() {
|
||||
// The root this folder was raised inside: the deepest one that
|
||||
// contains it, which is the one `Workspace::raised` clamped to.
|
||||
let Some(root) = self.deepest_root(&dir) else { continue };
|
||||
let configuring = trace.now();
|
||||
let mut exclude =
|
||||
discovery.for_dir(&root).unwrap_or_default().exclude.unwrap_or_default();
|
||||
exclude.extend(self.client.exclude.iter().cloned());
|
||||
ScanTrace::add(&mut trace.config_ms, configuring);
|
||||
let walking = trace.now();
|
||||
let _ = collect_files_below_tracked(
|
||||
&root,
|
||||
&dir,
|
||||
&exclude,
|
||||
true,
|
||||
tracker,
|
||||
&mut |path, len| out.push(Found { path, len }),
|
||||
&mut |w| warn(w.to_string()),
|
||||
);
|
||||
ScanTrace::add(&mut trace.walk_ms, walking);
|
||||
trace.walk_dirs += 1;
|
||||
}
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
|
||||
/// The deepest workspace root containing `dir` — the one
|
||||
/// [`Workspace::raised`] clamped the raise to, and so the one whose walk
|
||||
/// this folder is part of.
|
||||
fn deepest_root(&self, dir: &Path) -> Option<PathBuf> {
|
||||
self.roots
|
||||
.iter()
|
||||
.filter(|root| dir.starts_with(root))
|
||||
.max_by_key(|root| root.components().count())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// The rest of the workspace: everything the roots hold that `seen` does
|
||||
/// not already name, capped and reported exactly as the neighbourhood was.
|
||||
///
|
||||
/// Returns the files to index, what the walk wants said, and how many the
|
||||
/// cap kept out. Open buffers are **not** folded in again — they were
|
||||
/// folded into the head, and a buffer's path is in `pending.seen`.
|
||||
///
|
||||
/// **It walks with the head's own directory identities.** The tracker is
|
||||
/// the one the neighbourhood filled, so a directory the head already
|
||||
/// entered is not entered again under an alias and no file is discovered
|
||||
/// twice. Where this walk reaches such a directory under a spelling the
|
||||
/// root walk would have *preferred*, the tracker says so
|
||||
/// ([`DirectoryTracker::has_conflict`]) and the caller asks for one
|
||||
/// ordinary rescan, which is that root walk.
|
||||
pub(super) fn rest_of_scope(
|
||||
&self,
|
||||
pending: &mut PendingDiscovery,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
trace: &mut ScanTrace,
|
||||
) -> (Vec<PathBuf>, Vec<String>, usize) {
|
||||
let (roots, seen) = (&pending.roots, &pending.seen);
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let walked = self.walked_files_tracked(
|
||||
roots,
|
||||
&mut pending.tracker,
|
||||
&mut |w| warnings.push(w),
|
||||
trace,
|
||||
);
|
||||
// The same gate the neighbourhood applied: a file an open buffer
|
||||
// already speaks for, reached here by **another** spelling (a
|
||||
// same-named file symlink outside the head), must not be indexed a
|
||||
// second time. The buffer's own spelling is not an alias — a buffer
|
||||
// opened mid-scan is discovered here for the first time and must land
|
||||
// in the work list — so the gate is asked only about other paths.
|
||||
// Found by QA on §62.1, twice: the head walk had the gate and this walk
|
||||
// did not; then the gate matched a mid-scan buffer against itself.
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let aliased = Aliased::of(&spoken_for);
|
||||
let cap = self.client.max_file_size;
|
||||
let capping = trace.now();
|
||||
let mut stats = 0usize;
|
||||
let mut skipped = 0usize;
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
for found in walked {
|
||||
// Already decided about by the neighbourhood: indexed, capped out,
|
||||
// or spoken for by an open buffer. Deciding again would step a
|
||||
// file twice or report one skip as two.
|
||||
let another_spelling = !spoken_for.contains(found.path.as_path());
|
||||
if seen.contains(&found.path)
|
||||
|| (another_spelling && aliased.speaks_for(&found.path, &mut stats))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
watch(IndexEvent::Skipped { path: &found.path, size, cap });
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
files.push(found.path);
|
||||
}
|
||||
ScanTrace::add(&mut trace.cap_ms, capping);
|
||||
trace.stats += stats;
|
||||
(files, warnings, skipped)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity of `dir` and of every directory between it and `root` — what
|
||||
/// a second spelling would have to name to matter ([`Workspace::has_preceding_alias`]).
|
||||
///
|
||||
/// `root` itself is not among them: a walk of the root enters it before it
|
||||
/// reads anything, so nothing it holds can precede it.
|
||||
fn identities_to(root: &Path, dir: &Path) -> Vec<(lucisv_core::walk::DirId, PathBuf)> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = dir;
|
||||
while at != root {
|
||||
if let Some(id) = dir_id(at) {
|
||||
out.push((id, at.to_path_buf()));
|
||||
}
|
||||
let Some(parent) = at.parent() else { break };
|
||||
at = parent;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The directories a walk of `root` reads on its way down to `dir`: its
|
||||
/// parent, that one's parent, and so on up to and including `root`.
|
||||
fn ancestors_to<'a>(root: &'a Path, dir: &'a Path) -> Vec<&'a Path> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = dir.parent();
|
||||
while let Some(parent) = at {
|
||||
out.push(parent);
|
||||
if parent == root {
|
||||
break;
|
||||
}
|
||||
at = parent.parent();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `dir` holds a symlink to one of `targets` under a name that sorts
|
||||
/// before the target's own path — the entry a root walk would follow first.
|
||||
fn precedes_a_target(dir: &Path, targets: &[(lucisv_core::walk::DirId, PathBuf)]) -> bool {
|
||||
let Ok(entries) = fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|entry| {
|
||||
// Only a symlink can be a second spelling of a directory, and the kind
|
||||
// is the one `read_dir` already read — so the stat below happens once
|
||||
// per link in the chain and never once per entry.
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_symlink()) {
|
||||
return false;
|
||||
}
|
||||
let path = entry.path();
|
||||
let Some(id) = dir_id(&path) else { return false };
|
||||
targets.iter().any(|(target, spelling)| id == *target && path < *spelling)
|
||||
})
|
||||
}
|
||||
|
||||
/// Path order, one entry per path — what the walk's callers have always done
|
||||
/// with the paths of several overlapping directory walks.
|
||||
///
|
||||
/// The first entry for a path wins, which matters only for the length beside
|
||||
/// it, and two walks that found the same file read the same `metadata` for it.
|
||||
pub(super) fn sort_found(found: &mut Vec<Found>) {
|
||||
found.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
found.dedup_by(|a, b| a.path == b.path);
|
||||
}
|
||||
|
||||
/// The source files sitting in each of `dirs`, one directory deep. No walk, no
|
||||
/// `.gitignore`: this is the rootless default, where descending a tree the
|
||||
/// user never named would be a surprise.
|
||||
fn sibling_files(dirs: &[PathBuf], trace: &mut ScanTrace) -> Vec<Found> {
|
||||
let walking = trace.now();
|
||||
let mut out: Vec<Found> = Vec::new();
|
||||
for dir in dirs {
|
||||
let Ok(entries) = fs::read_dir(dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
|
||||
if !EXTENSIONS.contains(&extension) {
|
||||
continue;
|
||||
}
|
||||
// One `metadata` — the same call `is_file()` was, with the length
|
||||
// it always had kept rather than thrown away. It follows symlinks,
|
||||
// exactly as `is_file()` did.
|
||||
let Ok(meta) = fs::metadata(&path) else { continue };
|
||||
if meta.is_file() {
|
||||
out.push(Found { path, len: Some(meta.len()) });
|
||||
}
|
||||
}
|
||||
}
|
||||
ScanTrace::add(&mut trace.walk_ms, walking);
|
||||
trace.walk_dirs += dirs.len();
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
@@ -20,9 +20,6 @@ use vlog_semantic::{
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::walk::{collect_files, EXTENSIONS};
|
||||
|
||||
use crate::candidates::Candidates;
|
||||
use crate::convert::Positions;
|
||||
use crate::includes::{self, IncludeGraph};
|
||||
@@ -31,11 +28,13 @@ use crate::module_select::{self, Reach};
|
||||
use crate::rename_trace::{self, Rung, SelectionTrace, Wanted};
|
||||
use crate::scan_order::{self, WorkList};
|
||||
|
||||
pub(crate) mod discover;
|
||||
mod scan;
|
||||
|
||||
use crate::scan_trace::{CacheWork, ScanTrace};
|
||||
use crate::settings::{ClientSettings, IndexScope};
|
||||
use crate::uri::uri_to_path;
|
||||
use discover::{oversize, Found};
|
||||
use scan::{Analyzed, HeldAnalyses, ScanKind, Sources};
|
||||
pub use scan::{IndexEvent, Scan};
|
||||
|
||||
@@ -105,6 +104,14 @@ pub struct Document {
|
||||
/// [`crate::fences::of`], which is the only thing that may touch it; it
|
||||
/// is bound to this revision because a change builds a new `Document`.
|
||||
pub fences: std::sync::OnceLock<Vec<vlog_formatter::fence::Region>>,
|
||||
/// This buffer's lint findings, kept while every input that produced them
|
||||
/// is unchanged — read by the diagnostics pass and by quick-fix discovery
|
||||
/// alike, so one revision is linted once rather than twice (review round
|
||||
/// §R1a, `crate::lint_snapshot`). Bound to this revision for the same
|
||||
/// structural reason `fences` is; the inputs that can move *without* a new
|
||||
/// `Document` are the snapshot's own key, and the index moving is
|
||||
/// [`Document::refresh_overlay`], which clears it.
|
||||
pub lint: crate::lint_snapshot::Slot,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
@@ -115,17 +122,19 @@ impl Document {
|
||||
// `tokenize` + `parse_tolerant`, so the tree is identical). A buffer
|
||||
// that does not lex keeps the old path, so its all-error tree and its
|
||||
// lex diagnostic are byte-for-byte what they always were.
|
||||
let (tokens, (tree, diagnostics)) = match tokenize(&text) {
|
||||
use crate::lint_trace::{rebuild, Rebuild};
|
||||
crate::lint_trace::saw_document();
|
||||
let (tokens, (tree, diagnostics)) = match rebuild(Rebuild::Lex, || tokenize(&text)) {
|
||||
Ok(tokens) => {
|
||||
let parsed = parse_tolerant(tokens.clone(), &text);
|
||||
let parsed = rebuild(Rebuild::Parse, || parse_tolerant(tokens.clone(), &text));
|
||||
(tokens, parsed)
|
||||
}
|
||||
Err(_) => (Vec::new(), parse_source_tolerant(&text)),
|
||||
Err(_) => (Vec::new(), rebuild(Rebuild::Parse, || parse_source_tolerant(&text))),
|
||||
};
|
||||
let defines = collect_defines(&tokens);
|
||||
let semantics = analyze(&tree, &text);
|
||||
let external = resolve_external(&semantics, index);
|
||||
let line_index = LineIndex::new(&text);
|
||||
let defines = rebuild(Rebuild::Defines, || collect_defines(&tokens));
|
||||
let semantics = rebuild(Rebuild::Analyze, || analyze(&tree, &text));
|
||||
let external = rebuild(Rebuild::External, || resolve_external(&semantics, index));
|
||||
let line_index = rebuild(Rebuild::Lines, || LineIndex::new(&text));
|
||||
let large = false;
|
||||
Document {
|
||||
path,
|
||||
@@ -139,6 +148,7 @@ impl Document {
|
||||
external,
|
||||
large,
|
||||
fences: std::sync::OnceLock::new(),
|
||||
lint: crate::lint_snapshot::Slot::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,6 +175,7 @@ impl Document {
|
||||
external: ExternalResolutions::default(),
|
||||
large: true,
|
||||
fences: std::sync::OnceLock::new(),
|
||||
lint: crate::lint_snapshot::Slot::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,6 +195,12 @@ impl Document {
|
||||
/// single-file analysis is unaffected by other files, by construction.
|
||||
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
|
||||
self.external = resolve_external(&self.semantics, index);
|
||||
// The index is what the census oracle answers from, so a lint result
|
||||
// taken under the old one is no longer this buffer's answer. This is
|
||||
// the whole of the snapshot's index invalidation: every mutation of
|
||||
// `Workspace::index` ends in the loop that calls this, so there is no
|
||||
// generation counter to keep in step (review round §R1a).
|
||||
self.lint.clear();
|
||||
}
|
||||
|
||||
/// What this buffer contributes to the workspace index, read off the
|
||||
@@ -273,33 +290,6 @@ pub fn mixed_buffer(blocks: usize) -> String {
|
||||
src
|
||||
}
|
||||
|
||||
/// What the scope ladder decided: the files to index, the directories an
|
||||
/// `` `include`` in them is looked for in, and what to tell the user.
|
||||
#[derive(Default)]
|
||||
struct Scope {
|
||||
files: Vec<PathBuf>,
|
||||
/// The filelist's `+incdir+`s, in filelist order. Empty for every rung
|
||||
/// but the filelist — nothing else names an include path.
|
||||
incdirs: Vec<PathBuf>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The size of `path` when it is over `cap`, else `None` — the whole of the
|
||||
/// `lucisv.index.maxFileSize` test.
|
||||
///
|
||||
/// Metadata only: the point of the cap is that a 200 MB netlist is never read
|
||||
/// into memory, so asking the filesystem how big it is has to come first. A
|
||||
/// `cap` of 0 is the client asking for no cap, and a file whose metadata
|
||||
/// cannot be read is not skipped here — it simply fails the read below, as it
|
||||
/// always did.
|
||||
fn oversize(path: &Path, cap: u64) -> Option<u64> {
|
||||
if cap == 0 {
|
||||
return None;
|
||||
}
|
||||
let size = fs::metadata(path).ok()?.len();
|
||||
(size > cap).then_some(size)
|
||||
}
|
||||
|
||||
/// How many bytes of buffer text a scan carries for its whole life — every
|
||||
/// other file's text lives from its own step to the end of that step.
|
||||
fn held_bytes(buffered: &HashMap<PathBuf, String>) -> usize {
|
||||
@@ -486,6 +476,22 @@ impl Workspace {
|
||||
&self.index
|
||||
}
|
||||
|
||||
/// The index record this workspace already holds for **exactly these
|
||||
/// bytes**, or nothing.
|
||||
///
|
||||
/// What `vlog_refactor::KnownFacts` asks a refactoring's caller. Exactly
|
||||
/// one thing in this server can promise it: the persistent index cache
|
||||
/// files each record under the FNV-1a of the bytes it was read off, so
|
||||
/// record and key are one store entry written by one read
|
||||
/// ([`crate::index_cache::IndexCache::facts_now`]). Not a modified time,
|
||||
/// not a size, and **not the workspace index's own record**, which carries
|
||||
/// no hash of the text it came from. An unsaved buffer misses for the same
|
||||
/// reason a changed file does, so precedence needs no rule here
|
||||
/// (`docs/features/perf5r-scope-reuse/README.md`).
|
||||
pub fn known_facts(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
self.cache.facts_now(path, text)
|
||||
}
|
||||
|
||||
/// The project-wide completion tables, as of the last index rebuild.
|
||||
pub fn candidates(&self) -> &Candidates {
|
||||
&self.candidates
|
||||
@@ -823,17 +829,18 @@ impl Workspace {
|
||||
self.views.borrow_mut().clear();
|
||||
let discovering = trace.now();
|
||||
let mut skipped = 0usize;
|
||||
let mut scope = {
|
||||
// The cap's skips are reported by `collect_sources` and counted
|
||||
// here, because the end message names them and the scan is what
|
||||
// owns that number now.
|
||||
let mut counting = |event: IndexEvent<'_>| {
|
||||
if matches!(event, IndexEvent::Skipped { .. }) {
|
||||
skipped += 1;
|
||||
}
|
||||
watch(event);
|
||||
};
|
||||
self.collect_sources(&mut counting, HeldAnalyses::Wanted)
|
||||
// The cap's skips are reported by `collect_sources` and counted here,
|
||||
// because the end message names them and the scan is what owns that
|
||||
// number now.
|
||||
let mut counting = |event: IndexEvent<'_>, skipped: &mut usize| {
|
||||
if matches!(event, IndexEvent::Skipped { .. }) {
|
||||
*skipped += 1;
|
||||
}
|
||||
watch(event);
|
||||
};
|
||||
let (mut scope, pending) = {
|
||||
let mut count = |event: IndexEvent<'_>| counting(event, &mut skipped);
|
||||
self.first_scope(&mut count, &mut trace)
|
||||
};
|
||||
ScanTrace::add(&mut trace.discovery_ms, discovering);
|
||||
let buffered = std::mem::take(&mut scope.buffered);
|
||||
@@ -842,7 +849,15 @@ impl Workspace {
|
||||
// The same list the index will be built from, with the user's own
|
||||
// neighbourhood moved to the front of it.
|
||||
let WorkList { files: work, head } = self.open_first(std::mem::take(&mut scope.files));
|
||||
let head = scan_order::worth_waiting(head, work.len());
|
||||
// A scan that has not walked the whole workspace yet cannot ask
|
||||
// whether its head is a minority of it — the count that would answer
|
||||
// is the walk it is postponing. `splits_discovery` is what bounds the
|
||||
// head instead, and it refuses exactly the case `worth_waiting`
|
||||
// refuses: a buffer whose folder is the workspace.
|
||||
let head = match pending.is_some() {
|
||||
true => head,
|
||||
false => scan_order::worth_waiting(head, work.len()),
|
||||
};
|
||||
let paths = work.clone();
|
||||
ScanTrace::add(&mut trace.order_ms, ordering);
|
||||
// Re-opened rather than held across rescans: the directory it belongs
|
||||
@@ -865,6 +880,7 @@ impl Workspace {
|
||||
incdirs: scope.incdirs,
|
||||
warnings: scope.warnings,
|
||||
at: 0,
|
||||
pending,
|
||||
staged: Vec::new(),
|
||||
staged_at: Vec::new(),
|
||||
words: HashMap::new(),
|
||||
@@ -874,6 +890,40 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the rest of the workspace, once the user's own neighbourhood has
|
||||
/// been indexed and published — the second half of a split discovery
|
||||
/// ([`PendingDiscovery`]). Reports whether there was anything to walk.
|
||||
///
|
||||
/// **Its own step, indexing nothing.** The step it shares a call with
|
||||
/// would otherwise report a file against a denominator that grew inside
|
||||
/// the same call, and a bar whose percentage falls is worse than one that
|
||||
/// waits (`docs/features/indexing-ux/README.md`). So this discovers, says
|
||||
/// "there is more", and lets the next step be an ordinary one.
|
||||
fn discover_the_rest(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
|
||||
let Some(mut pending) = scan.take_pending() else { return false };
|
||||
let discovering = scan.trace.now();
|
||||
let mut skipped = 0usize;
|
||||
let (files, warnings, walked_skips) = {
|
||||
let mut counting = |event: IndexEvent<'_>| {
|
||||
if matches!(event, IndexEvent::Skipped { .. }) {
|
||||
skipped += 1;
|
||||
}
|
||||
watch(event);
|
||||
};
|
||||
self.rest_of_scope(&mut pending, &mut counting, &mut scan.trace)
|
||||
};
|
||||
debug_assert_eq!(skipped, walked_skips, "the cap reports every skip it counts");
|
||||
ScanTrace::add(&mut scan.trace.discovery_ms, discovering);
|
||||
scan.land_discovery(files, warnings, walked_skips, pending.tracker.has_conflict());
|
||||
scan.trace.measure_work(
|
||||
scan.work.len(),
|
||||
held_bytes(&scan.buffered),
|
||||
scan.skipped,
|
||||
scan.trace.cache,
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
/// Open the store a whole rescan asked for, if this is the first thing to
|
||||
/// need it ([`StoreOpen`]).
|
||||
///
|
||||
@@ -943,14 +993,16 @@ impl Workspace {
|
||||
// `folder_files` follows — the whole scope is the union of these walks,
|
||||
// so the files this one finds beyond what is already indexed are
|
||||
// exactly the ones the widen owes.
|
||||
for path in self.widened_files(added, &mut |w| warnings.push(w)) {
|
||||
let mut stats = 0usize;
|
||||
for found in self.widened_files(added, &mut |w| warnings.push(w), &mut trace) {
|
||||
let path = found.path.clone();
|
||||
// Already indexed: by another scope directory this walk overlaps,
|
||||
// or by an earlier scan. Re-reading it is the cost this path
|
||||
// exists to avoid.
|
||||
if held.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
if let Some(size) = oversize(&path, cap) {
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
watch(IndexEvent::Skipped { path: &path, size, cap });
|
||||
skipped += 1;
|
||||
continue;
|
||||
@@ -1017,6 +1069,9 @@ impl Workspace {
|
||||
// buffer can widen — so the only warnings here are the walk's own.
|
||||
warnings,
|
||||
at: 0,
|
||||
// A widen names the directories it is about to walk, so there is
|
||||
// never anything left to discover.
|
||||
pending: None,
|
||||
staged: Vec::new(),
|
||||
staged_at: Vec::new(),
|
||||
words: HashMap::new(),
|
||||
@@ -1026,16 +1081,6 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
/// The files the directories a widen added bring into scope, by the same
|
||||
/// rules [`Workspace::folder_files`] applies to the whole scope — including
|
||||
/// the rootless-at-depth-0 flat read.
|
||||
fn widened_files(&self, added: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(added);
|
||||
}
|
||||
self.walked_files(added, warn)
|
||||
}
|
||||
|
||||
/// Index the next file of `scan`, reporting whether there was one.
|
||||
///
|
||||
/// One file is the whole step: **its text is read**, its record is taken —
|
||||
@@ -1059,7 +1104,7 @@ impl Workspace {
|
||||
pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
|
||||
let (done, total) = (scan.at, scan.work.len());
|
||||
if done == total {
|
||||
return false;
|
||||
return self.discover_the_rest(scan, watch);
|
||||
}
|
||||
scan.at += 1;
|
||||
// The first file of a scan is the first thing to ask the store
|
||||
@@ -1463,7 +1508,7 @@ impl Workspace {
|
||||
// exists to skip.
|
||||
return (!doc.large).then(|| doc.text.clone());
|
||||
}
|
||||
if oversize(path, self.client.max_file_size).is_some() {
|
||||
if oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_some() {
|
||||
return None;
|
||||
}
|
||||
fs::read_to_string(path).ok()
|
||||
@@ -1490,7 +1535,16 @@ impl Workspace {
|
||||
/// buffer is installed and the folder it raises to is known. What was
|
||||
/// already indexed is untouched; only the tail moves, and the finished
|
||||
/// index cannot tell ([`Scan::reorder`]).
|
||||
pub fn open_next(&self, scan: &mut Scan) {
|
||||
/// **The rest of the workspace is walked first when it has not been.** A
|
||||
/// split startup is leading with the folder the user *was* in; a `didOpen`
|
||||
/// says they are somewhere else now, and re-ordering a work list that does
|
||||
/// not yet contain the new folder would answer the request behind that
|
||||
/// `didOpen` off a prefix that cannot hold what it is asking about. The
|
||||
/// walk this order postpones is exactly what makes the new folder
|
||||
/// nameable, so it happens here
|
||||
/// (`docs/features/perf5r-first-answer/README.md`).
|
||||
pub fn open_next(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) {
|
||||
self.discover_the_rest(scan, watch);
|
||||
let ordered = self.open_first(scan.remaining());
|
||||
scan.reorder(ordered);
|
||||
}
|
||||
@@ -1528,7 +1582,7 @@ impl Workspace {
|
||||
/// did when `collect_sources` read them all.
|
||||
pub fn sources(&self) -> Vec<(PathBuf, String)> {
|
||||
let Sources { files, mut buffered, .. } =
|
||||
self.collect_sources(&mut |_| {}, HeldAnalyses::Unused);
|
||||
self.collect_sources(&mut |_| {}, HeldAnalyses::Unused, &mut ScanTrace::new(false));
|
||||
files
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
@@ -1702,7 +1756,13 @@ impl Workspace {
|
||||
}
|
||||
wanted.on(Rung::OpenBuffer);
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
let (paths, mut trace) = wanted.finish();
|
||||
let (mut paths, mut trace) = wanted.finish();
|
||||
// One hop down: the modules those files instantiate, so a `.*` into
|
||||
// one is read rather than refused (M3.5). In `selected`, under no rung.
|
||||
let handed: Vec<&Path> = paths.keys().map(PathBuf::as_path).collect();
|
||||
for below in module_select::instantiated_by(&self.index, &handed) {
|
||||
paths.entry(below).or_insert(Rung::Instantiation);
|
||||
}
|
||||
// §P2d's census: which rungs asked for files that write neither name
|
||||
// down, and therefore contribute to this request only by shaping how
|
||||
// the others resolve. One record lookup per selected file, no read.
|
||||
@@ -1850,78 +1910,6 @@ impl Workspace {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Resolve the scope: which files are in it, with open buffers overriding
|
||||
/// disk, and those buffers' own text.
|
||||
///
|
||||
/// **Metadata only, plus what is already in memory.** Nothing on disk is
|
||||
/// read here — a file's text is read by whoever indexes or rewrites it,
|
||||
/// one file at a time ([`Workspace::scan_step`], [`Workspace::sources`]).
|
||||
///
|
||||
/// This is where `lucisv.index.maxFileSize` applies, and it applies to the
|
||||
/// **walked** files only: an open buffer is folded in below whatever its
|
||||
/// size, because the user opened it deliberately and an editor that
|
||||
/// refused to understand the file on screen would be absurd. The check is
|
||||
/// a `metadata` call, so an oversized file is still never read at all —
|
||||
/// which is the whole saving, and it is still counted and reported here
|
||||
/// so that a scan's skip count is known before its first step.
|
||||
///
|
||||
/// A refactoring reads this same list through `sources()`, so a file the
|
||||
/// cap keeps out of the index is also a file a workspace rename will not
|
||||
/// rewrite. That is the consistent answer: the cap says which files exist
|
||||
/// as far as this server is concerned.
|
||||
fn collect_sources(
|
||||
&self,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
analyses: HeldAnalyses,
|
||||
) -> Sources {
|
||||
let scope = self.source_files();
|
||||
let cap = self.client.max_file_size;
|
||||
// Every path an open buffer speaks for. Reading such a file from disk
|
||||
// is work thrown away — the buffer's text replaces it below, whatever
|
||||
// the disk says — so the read is skipped rather than undone. The cap is
|
||||
// still consulted first, so an oversized file still reports itself
|
||||
// skipped exactly as it did before the buffer put its own text back.
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
for path in scope.files {
|
||||
if let Some(size) = oversize(&path, cap) {
|
||||
watch(IndexEvent::Skipped { path: &path, size, cap });
|
||||
continue;
|
||||
}
|
||||
if spoken_for.contains(path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
files.push(path);
|
||||
}
|
||||
// Open buffers override what is on disk, and contribute themselves
|
||||
// when they are not on disk at all.
|
||||
//
|
||||
// Except a buffer on the large-file fast path, which overrides disk
|
||||
// with *nothing*: indexing it means parsing the hundred megabytes the
|
||||
// fast path exists not to parse. Removing the path rather than leaving
|
||||
// the disk copy in is the honest half of that — the alternative would
|
||||
// be an index describing a file the user is looking at by bytes it no
|
||||
// longer has. See `docs/features/large-file-mode/README.md` for the
|
||||
// interaction with `lucisv.index.maxFileSize`, whose "an open buffer is
|
||||
// never capped" rule this is the one exception to.
|
||||
let mut analyzed = Analyzed::default();
|
||||
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
|
||||
for doc in self.docs.values() {
|
||||
let Some(path) = doc.path.clone() else { continue };
|
||||
files.retain(|p| p != &path);
|
||||
if !doc.large {
|
||||
if analyses == HeldAnalyses::Wanted {
|
||||
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
|
||||
analyzed.words.insert(path.clone(), doc.words());
|
||||
}
|
||||
buffered.insert(path.clone(), doc.text.clone());
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
Sources { files, buffered, analyzed, incdirs: scope.incdirs, warnings: scope.warnings }
|
||||
}
|
||||
|
||||
/// One **closed** file's text and line index, read at most once per file
|
||||
/// per generation of that file.
|
||||
///
|
||||
@@ -2004,155 +1992,6 @@ impl Workspace {
|
||||
None => fs::read_to_string(path).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The files the index covers, and what the user should be told about how
|
||||
/// they were chosen. The scope ladder, highest first:
|
||||
///
|
||||
/// 1. **A filelist** — `lucisv.filelist`, else a `filelist` key in the
|
||||
/// config governing a workspace root. It names *exactly* the files to
|
||||
/// index; the project said so, and guessing past it would defeat the
|
||||
/// point of having one. This is the "project file", and it is the one
|
||||
/// rung that is whole-project by definition.
|
||||
/// 2. **The workspace-folder walk**, on `lucisv.index.scope:
|
||||
/// "workspace"` — what every session did before 2026-08-27, now opt-in.
|
||||
/// 3. **The folder scope**, the default: each opened buffer's own
|
||||
/// directory raised `lucisv.index.scopeDepth` levels, walked. See
|
||||
/// `docs/features/index-scope/README.md` for what that costs, which is
|
||||
/// that a definition in another folder does not resolve until the
|
||||
/// scope reaches that folder.
|
||||
///
|
||||
/// A configured filelist that cannot be read falls back to rung 2 (or 3)
|
||||
/// with a warning. An editor that shows no symbols because of a typo in a
|
||||
/// path is worse than one that quietly indexes what it can and says so.
|
||||
///
|
||||
/// Only rung 1 can carry `+incdir+` directories: a walked workspace names
|
||||
/// none, so an `` `include`` there resolves against the including file's
|
||||
/// own directory alone (`docs/features/include-nav/README.md`).
|
||||
fn source_files(&self) -> Scope {
|
||||
// The walk's own warnings join the scope's, so an unreadable directory
|
||||
// reaches the output channel by the road a filelist's problems already
|
||||
// travel — said once per scan and never per keystroke.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let Some(path) = self.filelist_path() else {
|
||||
let files = self.default_files(&mut |w| warnings.push(w));
|
||||
return Scope { files, warnings, ..Default::default() };
|
||||
};
|
||||
match lucisv_core::filelist::read(&path) {
|
||||
Ok(list) => Scope { files: list.files, incdirs: list.incdirs, warnings: list.warnings },
|
||||
Err(problem) => {
|
||||
let files = self.default_files(&mut |w| warnings.push(w));
|
||||
warnings.insert(0, format!("{problem} — indexing the workspace instead"));
|
||||
Scope { files, incdirs: Vec::new(), warnings }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The filelist governing this workspace, if any: the client's setting
|
||||
/// first (absolute, or relative to the first root), else the `filelist`
|
||||
/// key of the config governing a root, in root order.
|
||||
///
|
||||
/// Public because the file watchers must name it: a `.f` edited outside
|
||||
/// the editor changes the index's scope, and nothing else on disk would
|
||||
/// tell us (`docs/features/file-watching/README.md`).
|
||||
pub fn filelist_path(&self) -> Option<PathBuf> {
|
||||
if let Some(setting) = &self.client.filelist {
|
||||
let path = Path::new(setting);
|
||||
return Some(match self.roots.first() {
|
||||
Some(root) if path.is_relative() => root.join(path),
|
||||
_ => path.to_path_buf(),
|
||||
});
|
||||
}
|
||||
let mut discovery = Discovery::new(true);
|
||||
// A broken `lucisv.toml` names no filelist, exactly as it contributes no
|
||||
// excludes below: the user hears about it when they format.
|
||||
self.roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
|
||||
}
|
||||
|
||||
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
|
||||
/// asked for it, else the folder scope.
|
||||
fn default_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
if self.walks_the_workspace() {
|
||||
return self.walked_files(&self.roots, warn);
|
||||
}
|
||||
self.folder_files(warn)
|
||||
}
|
||||
|
||||
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
|
||||
/// filter the workspace walk applies.
|
||||
///
|
||||
/// One exception, kept exactly as it was from before this rung became the
|
||||
/// default: **a rootless session at depth 0 reads its directories flat**,
|
||||
/// one level, no `.gitignore`. That is the "a file opened on its own"
|
||||
/// case, where descending a tree the user never named would be a surprise
|
||||
/// — and the moment the user raises `scopeDepth` they have named one, so
|
||||
/// the walk is what they asked for.
|
||||
fn folder_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
let dirs = self.scope_dirs();
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(&dirs);
|
||||
}
|
||||
self.walked_files(&dirs, warn)
|
||||
}
|
||||
|
||||
/// Every source file under `dirs`, found by the CLI's own walk: the same
|
||||
/// extensions, the same `.gitignore` handling, and the `exclude` patterns
|
||||
/// of the config governing each directory. What `lucisv` skips, the index
|
||||
/// skips.
|
||||
///
|
||||
/// `dirs` is the workspace roots for rung 2 and the scope directories for
|
||||
/// rung 3. The one honest difference between the two: `.gitignore` files
|
||||
/// are read from the walk's own starting directory downwards, so a rule
|
||||
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
|
||||
/// starts below it. The `exclude` patterns are matched against whole
|
||||
/// paths and so behave identically either way.
|
||||
fn walked_files(&self, dirs: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut out = Vec::new();
|
||||
for root in dirs {
|
||||
// The walk names its inputs as strings; every directory here came
|
||||
// from a `file:` URI, which cannot carry a non-UTF-8 path.
|
||||
let Some(input) = root.to_str() else { continue };
|
||||
// A broken `lucisv.toml` must not stop the server from indexing: an
|
||||
// index that excludes nothing is a far better failure than a
|
||||
// server that comes up empty. The error is reported when the user
|
||||
// formats a file in this tree (`format::settings_for`).
|
||||
let mut exclude =
|
||||
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
|
||||
// The client's `lucisv.exclude` is *appended*, never substituted —
|
||||
// the CLI appends a config's excludes to `--exclude` the same way,
|
||||
// and a setting that silently dropped a checked-in exclude would
|
||||
// put vendored code back in the index for one user only.
|
||||
exclude.extend(self.client.exclude.iter().cloned());
|
||||
// `.gitignore` is always honoured: it is the CLI's default, and an
|
||||
// editor has no `--no-gitignore` to type. An unreadable directory
|
||||
// is skipped and said — the warning rides out on the scope's own
|
||||
// warnings, which `server/notification.rs` logs once per scan.
|
||||
let _ = collect_files(input, &exclude, true, &mut out, &mut |w| warn(w.to_string()));
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The source files sitting in each of `dirs`, one directory deep. No walk, no
|
||||
/// `.gitignore`: this is the rootless default, where descending a tree the
|
||||
/// user never named would be a surprise.
|
||||
fn sibling_files(dirs: &[PathBuf]) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
let Ok(entries) = fs::read_dir(dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
|
||||
if path.is_file() && EXTENSIONS.contains(&extension) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2673,6 +2512,41 @@ mod tests {
|
||||
ws.finish_scan(scan)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_publication_cadence_holds_a_publish_until_enough_has_been_staged() {
|
||||
// **The whole of the cadence, at its exact boundary.** A publish is a
|
||||
// pass over the whole index, and before §61.4 the drain paid one per
|
||||
// burst of requests — 13 to 18 in one warm opentitan scan, 46 % of it
|
||||
// (`docs/features/perf5r-publication/README.md`). `publish_is_due`
|
||||
// spaces them by work done rather than by how often a client asks: no
|
||||
// publish is due until `PUBLISH_EVERY` records are staged, one is due
|
||||
// the moment the 512th lands, and publishing clears the debt.
|
||||
let tree = Tree::new("publishcadence");
|
||||
for n in 0..scan::PUBLISH_EVERY + 2 {
|
||||
tree.package(&format!("p{n:04}.sv"), &format!("p{n:04}"));
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
for taken in 1..scan::PUBLISH_EVERY {
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: file {taken} exists");
|
||||
assert!(!scan.publish_is_due(), "{taken} staged is not yet a publish");
|
||||
}
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: the 512th file exists");
|
||||
assert!(scan.publish_is_due(), "{} staged is", scan::PUBLISH_EVERY);
|
||||
ws.publish_scan(&mut scan);
|
||||
assert!(!scan.publish_is_due(), "and publishing clears the debt");
|
||||
|
||||
// The cadence is a latency decision and nothing else: what this scan
|
||||
// lands is what a one-shot scan over the same tree lands.
|
||||
while ws.scan_step(&mut scan, &mut |_| {}) {}
|
||||
ws.finish_scan(scan);
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(everything(&one_shot), everything(&ws));
|
||||
}
|
||||
|
||||
/// A tree of three files that declare each other's names and include each
|
||||
/// other, so a half-published index has something to get wrong.
|
||||
fn tangled(tag: &str) -> Tree {
|
||||
@@ -2791,7 +2665,7 @@ mod tests {
|
||||
let jumped = uri(&format!("file://{}", tree.path.join("c.sv").display()));
|
||||
let jumped_text = fs::read_to_string(tree.path.join("c.sv")).expect("the fixture");
|
||||
stepped.set_document(jumped, jumped_text);
|
||||
stepped.open_next(&mut scan);
|
||||
stepped.open_next(&mut scan, &mut |_| {});
|
||||
assert!(stepped.scan_step(&mut scan, &mut |_| {}));
|
||||
stepped.publish_scan(&mut scan);
|
||||
assert!(!stepped.index().units("c").is_empty(), "c.sv was indexed next, not last");
|
||||
@@ -2924,7 +2798,7 @@ mod tests {
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"]);
|
||||
assert_eq!(
|
||||
ws.walked_files(from_ref(&tree.path), &mut |_| {}).len(),
|
||||
ws.walked_files(from_ref(&tree.path), &mut |_| {}, &mut ScanTrace::new(false)).len(),
|
||||
2,
|
||||
"two files, once each"
|
||||
);
|
||||
@@ -4208,7 +4082,7 @@ mod tests {
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "the buffer's own file goes first");
|
||||
open(&mut ws, &tree, "ip/uart/rtl/uart.sv");
|
||||
ws.open_next(&mut scan);
|
||||
ws.open_next(&mut scan, &mut |_| {});
|
||||
// `uart.sv` is now the head of what is left, and at the shipped
|
||||
// `scopeDepth: 2` its own folder raises to `ip` — which brings
|
||||
// `ip/kmac` in with it. Four files of waiting, one behind the file
|
||||
@@ -5995,4 +5869,73 @@ mod tests {
|
||||
assert_eq!(ws.index().member("a_pkg", "EDITED").len(), 1, "the live edit is indexed");
|
||||
assert_eq!(ws.index().member("a_pkg", "K").len(), 0);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TODO §63.2 QA: the trace's arithmetic, attacked with the three
|
||||
// shapes TODO.md names — a buffer that fails to lex, a `define` edit
|
||||
// that changes the macro table, and (below, via the server-level
|
||||
// parity re-run) an edit that moves a fence.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A buffer that never lexes still reports a `Lex` stage (the failed
|
||||
/// attempt is real work and costs real time) and a `Parse` stage (the
|
||||
/// `parse_source_tolerant` fallback), and still counts as one document.
|
||||
/// `defines`/`analyze`/`external`/`lines` all still run over the empty
|
||||
/// token stream and empty-error tree exactly as the un-instrumented
|
||||
/// path always did — the wrapping must not skip a stage just because
|
||||
/// an earlier one errored.
|
||||
#[test]
|
||||
fn a_buffer_that_fails_to_lex_still_records_every_rebuild_stage() {
|
||||
crate::lint_trace::arm();
|
||||
// An unterminated string literal is an unambiguous lex error that
|
||||
// does not depend on lexer internals that could drift between
|
||||
// versions (`vlog_parser::tokenize` is documented all-or-nothing).
|
||||
let text = "module m;\n string s = \"unterminated\nendmodule\n".to_string();
|
||||
let doc = Document::new(None, text, &WorkspaceIndex::default());
|
||||
assert!(doc.tokens.is_empty(), "a lex failure leaves an empty token stream");
|
||||
assert!(!doc.diagnostics.is_empty(), "a lex failure is a diagnostic");
|
||||
let trace = crate::lint_trace::disarm().expect("armed");
|
||||
// Every stage's field is present on the line, whether or not it
|
||||
// took measurable time (`saw_document`, not a duration, is what
|
||||
// says a rebuild happened at all — see the flaky test this round
|
||||
// fixed in `lint_trace.rs`).
|
||||
let line = trace.line();
|
||||
assert!(line.contains("documents=1"), "{line}");
|
||||
for stage in ["lex=", "parse=", "defines=", "analyze=", "external=", "lines=", "publish="] {
|
||||
assert!(line.contains(stage), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `` `define `` edit changes the macro table `collect_defines`
|
||||
/// produces, and nothing about wrapping that call in `rebuild` changes
|
||||
/// which tokens it sees or what it returns: the new revision's table
|
||||
/// reflects only the new text, never a stale value from the revision
|
||||
/// before it (`Document::new` builds a fresh `DefineTable` every time,
|
||||
/// same as before this round).
|
||||
#[test]
|
||||
fn a_define_edit_changes_the_macro_table_the_rebuild_reports_on() {
|
||||
crate::lint_trace::arm();
|
||||
let before = Document::new(
|
||||
None,
|
||||
"`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] w;\nendmodule\n".to_string(),
|
||||
&WorkspaceIndex::default(),
|
||||
);
|
||||
assert_eq!(before.defines.latest("WIDTH").map(|d| d.body.trim()), Some("8"));
|
||||
assert!(before.defines.latest("DEPTH").is_none());
|
||||
|
||||
let after = Document::new(
|
||||
None,
|
||||
"`define DEPTH 16\nmodule m;\n wire [`DEPTH-1:0] w;\nendmodule\n".to_string(),
|
||||
&WorkspaceIndex::default(),
|
||||
);
|
||||
assert!(after.defines.latest("WIDTH").is_none(), "no macro survives across documents");
|
||||
assert_eq!(after.defines.latest("DEPTH").map(|d| d.body.trim()), Some("16"));
|
||||
|
||||
let trace = crate::lint_trace::disarm().expect("armed");
|
||||
let line = trace.line();
|
||||
assert!(
|
||||
line.contains("documents=2"),
|
||||
"two fresh Document::new calls, two rebuilds: {line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
//! `pub(super)` and visible exactly where they were before the move: inside
|
||||
//! `crate::state` and nowhere else.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -126,6 +126,11 @@ pub struct Scan {
|
||||
pub(super) warnings: Vec<String>,
|
||||
/// How many of `work` have been indexed.
|
||||
pub(super) at: usize,
|
||||
/// The rest of the workspace, still to be discovered — see
|
||||
/// [`PendingDiscovery`]. `None` for every scan that resolved its whole
|
||||
/// scope before it started, which is every scan but a workspace-scoped
|
||||
/// startup with a buffer already open.
|
||||
pub(super) pending: Option<PendingDiscovery>,
|
||||
/// The records taken since the last publish, and which files of `work`
|
||||
/// they came from. Staged rather than merged because a merge is a pass
|
||||
/// over the whole index — see [`vlog_semantic::WorkspaceIndex::absorb`].
|
||||
@@ -144,6 +149,50 @@ pub struct Scan {
|
||||
pub(super) trace: ScanTrace,
|
||||
}
|
||||
|
||||
/// The half of a scan's scope that has not been walked yet.
|
||||
///
|
||||
/// **One scan, discovered in two goes.** A workspace-scoped session with a
|
||||
/// buffer already open walks that buffer's own folders first, indexes them,
|
||||
/// publishes them and answers the request that has been waiting — and only
|
||||
/// then walks the remaining 3 800 directories, whose 155 ms used to sit in
|
||||
/// front of every one of those steps (`docs/features/perf5r-first-answer`).
|
||||
/// It is emphatically **not** two scans: one work list, one index, one
|
||||
/// `finish_scan`, one `gone` computed against the whole of it, and every file
|
||||
/// stepped exactly once — which is what `seen` is for.
|
||||
pub(super) struct PendingDiscovery {
|
||||
/// The directories still to walk: the workspace roots.
|
||||
pub(super) roots: Vec<PathBuf>,
|
||||
/// Every path the neighbourhood walk yielded — the ones it indexed, the
|
||||
/// ones the size cap kept out, and every open buffer's own path. The
|
||||
/// remaining walk covers the roots, so it finds all of these again; each
|
||||
/// one it names here has already been decided about, and deciding twice
|
||||
/// would step a file twice or report one skip as two.
|
||||
pub(super) seen: HashSet<PathBuf>,
|
||||
/// Every directory identity the neighbourhood walk entered, and the path
|
||||
/// it entered each one by.
|
||||
///
|
||||
/// **The two walks share it, and that is what makes them one walk.** An
|
||||
/// ordinary walk visits each directory identity once and reports its files
|
||||
/// under the first spelling that reached it
|
||||
/// (`docs/features/walk-cycles/README.md`); two walks with two sets would
|
||||
/// report a symlinked directory's files twice, under two spellings a path
|
||||
/// set cannot tell apart, and the index would hold every module in it
|
||||
/// twice. Sharing the tracker restores that contract across the split.
|
||||
pub(super) tracker: lucisv_core::walk::DirectoryTracker,
|
||||
}
|
||||
|
||||
/// How many records may be staged before another mid-scan publish is worth the
|
||||
/// whole-index merge it costs — see [`Scan::publish_is_due`].
|
||||
///
|
||||
/// **512 is a work bound, and it is deliberately the same number
|
||||
/// `HEAD_WALK_MAX` is.** Both answer "how much of this workspace may a user
|
||||
/// wait for before an answer stops being worth waiting for": 512 warm steps is
|
||||
/// ~100 ms of scanning on the corpus the round measured
|
||||
/// (`docs/features/perf5r-first-answer/README.md`), so a request landing
|
||||
/// between two publishes reads an index at most that far behind and the whole
|
||||
/// scan pays at most one merge per 512 files instead of one per burst.
|
||||
pub(crate) const PUBLISH_EVERY: usize = 512;
|
||||
|
||||
/// Which of the two shapes a [`Scan`] is.
|
||||
///
|
||||
/// One enum rather than two `finish` methods so a caller cannot pair the wrong
|
||||
@@ -195,6 +244,106 @@ impl Scan {
|
||||
self.at >= self.head
|
||||
}
|
||||
|
||||
/// Whether enough has been staged since the last publish for another one
|
||||
/// to be worth the merge it costs — the **publication cadence**.
|
||||
///
|
||||
/// **A publish is a pass over the whole index, and it used to be one per
|
||||
/// burst of requests.** `answer_what_is_waiting` published whenever
|
||||
/// anything at all was waiting, so a client asking ten times a second
|
||||
/// bought ten merges a second over a table that grows all the way to the
|
||||
/// end of the scan. Measured on opentitan under a definition every 100 ms
|
||||
/// (`docs/features/perf5r-publication/README.md`): 13 to 18 publishes in
|
||||
/// one warm scan, and `absorb` + `candidates` alone were 46 % of it.
|
||||
///
|
||||
/// The rule this asks is **how much new the next answer would see**, not
|
||||
/// how long ago the last publish was: a merge's cost is the index's size
|
||||
/// and its value is the records it makes answerable, so files staged is
|
||||
/// the currency both are in — and it is a count, so what a scan does is
|
||||
/// the same on a fast machine and a slow one, and a test may assert it.
|
||||
///
|
||||
/// It bounds staleness, never correctness: a request answered between two
|
||||
/// publishes reads a prefix at most [`PUBLISH_EVERY`] files older than the
|
||||
/// one it could have had, and every table in it still agrees with every
|
||||
/// other ([`Workspace::publish_scan`](super::Workspace::publish_scan)).
|
||||
/// The **first** publish of a scan is never deferred by it — that one is
|
||||
/// the session's first useful answer, and `server/index.rs` asks for it by
|
||||
/// a different door.
|
||||
pub fn publish_is_due(&self) -> bool {
|
||||
self.staged.len() >= PUBLISH_EVERY
|
||||
}
|
||||
|
||||
/// Whether this scan still owes itself the rest of its own scope — see
|
||||
/// [`PendingDiscovery`].
|
||||
///
|
||||
/// Two callers, and they want it for the same reason: `scan_once` must
|
||||
/// interleave a scan whose work list is short *so far*, and must not paint
|
||||
/// a percentage against a denominator that is going to grow
|
||||
/// (`docs/features/indexing-ux/README.md`).
|
||||
pub fn discovery_pending(&self) -> bool {
|
||||
self.pending.is_some()
|
||||
}
|
||||
|
||||
/// Take the remaining discovery, so the workspace can run it.
|
||||
pub(super) fn take_pending(&mut self) -> Option<PendingDiscovery> {
|
||||
self.pending.take()
|
||||
}
|
||||
|
||||
/// Whether this scan's answers are right but **spelled** differently from
|
||||
/// what a plain walk of the same tree would spell them, so one ordinary
|
||||
/// rescan is owed.
|
||||
///
|
||||
/// The case: a directory alias outside the open folder's ancestor chain —
|
||||
/// `other/link -> z_real`, with `other` sorting first. The head leads with
|
||||
/// `z_real`; the remaining walk meets `other/link`, recognises the
|
||||
/// directory the head already entered and skips it, so nothing is
|
||||
/// discovered twice and every answer this scan gives is one target and one
|
||||
/// file. But a walk of the root on its own — the next rescan, or a session
|
||||
/// that opens nothing — spells those same files `other/link/…`, and a
|
||||
/// startup that disagreed with every later scan about a path is the defect
|
||||
/// this whole tracker exists to close (`docs/performance_052_review.md`
|
||||
/// F1). So the scan asks for the canonical walk once it has landed, and
|
||||
/// the spelling converges there.
|
||||
///
|
||||
/// **Exactly one rescan can ever come of it.** Only a session's first scan
|
||||
/// splits its discovery ([`Workspace::first_scope`]), so the scan this
|
||||
/// asks for resolves its whole scope in one walk, has no
|
||||
/// [`PendingDiscovery`], and cannot ask again.
|
||||
///
|
||||
/// The answer is the trace's own counter, which is written whether or not
|
||||
/// anybody asked for a trace — like `publishes`, it is a fact about the
|
||||
/// scan rather than a stopwatch reading, so it lives where the scan's
|
||||
/// facts live and the `--verbose` count line says it out loud.
|
||||
pub fn wants_rescan(&self) -> bool {
|
||||
self.trace.rescan_requested > 0
|
||||
}
|
||||
|
||||
/// Fold the rest of the scope into this scan: its files onto the end of
|
||||
/// the work list, its paths into the set the include graph learns from,
|
||||
/// its warnings and its skips onto the scan's own — and whether the walk
|
||||
/// that found them disagreed with the head about a directory's spelling
|
||||
/// ([`Scan::wants_rescan`]).
|
||||
///
|
||||
/// Appended rather than re-ordered: the neighbourhood at the front has
|
||||
/// already been stepped, and `vlog_semantic::IndexBuilder` sorts by path
|
||||
/// inside `finish`, so what arrives here decides latency and nothing else
|
||||
/// ([`Scan::reorder`] makes the same argument).
|
||||
pub(super) fn land_discovery(
|
||||
&mut self,
|
||||
files: Vec<PathBuf>,
|
||||
warnings: Vec<String>,
|
||||
skipped: usize,
|
||||
conflict: bool,
|
||||
) {
|
||||
self.trace.conflict += usize::from(conflict);
|
||||
self.trace.rescan_requested += usize::from(conflict);
|
||||
self.paths.extend(files.iter().cloned());
|
||||
self.paths.sort();
|
||||
self.paths.dedup();
|
||||
self.work.extend(files);
|
||||
self.warnings.extend(warnings);
|
||||
self.skipped += skipped;
|
||||
}
|
||||
|
||||
/// The text of one file of this scan's work list, at the moment its step
|
||||
/// comes — `None` when it cannot be read.
|
||||
///
|
||||
|
||||
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user