Compare commits

...
21 Commits
Author SHA1 Message Date
lucioandClaude Fable 5.1 72ff5df1cc Release 0.56.0 — rename keeps implicit connections bound; lucisv-mcp preview
release / build-and-publish (push) Successful in 6m49s
Version bump (workspace Cargo.toml, Cargo.lock, editors/vscode/package.json) and the 0.56.0 notes in CHANGELOG.md, editors/vscode/CHANGELOG.md and the extension README. Ships M3.5 (rename writes out `.name`/`.*` bindings, verified by a binding print; the LSP hands the engine one more hop) and the MCP block's M1–M3 as a `cargo build --release -p lucisv_mcp` preview — not yet in the .vsix (TODO-MCP M5). Gates through tools/guard.sh: fmt, clippy -D warnings, workspace 4 762 passed, corpus 814/820 (baseline 814).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 12:18:45 -07:00
lucioandClaude Fable 5.1 4edada583f Rename keeps implicit connections bound (TODO-MCP M3.5): .name and .* rewritten explicitly, verified by a binding print; the LSP hands the engine one more hop
vlog_refactor: a rename used to cut a `.name` shorthand or a `.*` wildcard binding — port d → din of leaf left `leaf u (.*)` binding nothing and turned `.d` into `.din` against a parent with no net din; renaming the parent's net cut both — and verified clean, because the semantic layer records the port half of `.name` and nothing of `.*` (M3 QA finding 1; the LSP shared it). rename/{connections,sites,layout}.rs: an AST walk over every named connection list finds the implicit bindings and looks each name up the way the language does (nearest declaration outward; a bind's target module; a bare instance name resolved through the instantiation table with the bind's enclosing module's own instances winning, §23.11); `.p` becomes `.q(p)`, a `.*` that bound the name gains `.q(p)` / `.n(m)` appended in the list's own layout (comma before a trailing // comment, CRLF kept); every rewrite listed in warnings; refused by name: a `.*` into a module lucisv cannot read or finds declared twice, a list split by ifdefs or holding unparsed text, a hierarchical bind target, a `.*` that would start binding the new name, a package variable an import might hand to a `.*`. check/implicit.rs: the verifier learns the shape — a file with insertions passes only if every replacement is the old name becoming the new and every insertion is one of four connection templates at the exact slot the rewrite writes (a shorthand's name end; between a `.*` list's last element and its `)`), the comma and its `.X(Y)` only as a pair in one list, no slot at all in a list holding an error element — and every implicit binding (port half and net half) is printed before and after and must match. lucisv_server: rename_sources_traced hands the engine one more hop — the declaring files of every module a handed-over file instantiates (module_select::instantiated_by, index edges only) — so a `.*` into a module declaring neither name is read, not refused. lucisv_mcp: the rename tool's known-limit sentence replaced; the M3 QA finding-1 test un-ignored.

Three QA rounds (Opus) attacked the widened verifier and found, in order, position-blind insertions, a lone trailing comma, and a slot after an error element — each fixed (the last by the lead) and pinned by 40+ qa_* tests incl. masked-corruption pairs; opentitan copies: prim_count err_o/clr_i, aes_core clk_i, entropy_src clk_i, prim_packer_fifo wready_o rename cleanly with their .* cov binds written out; prim_fifo_sync clr_i refused over the FPV binds that really target fifo instances. Accepted gap: a bind onto an instance that exists only inside a generate block of the enclosing module. Filed to vlog_parser: trailing `,` / `{d,, d}` / `type(x)'(y)` in a connection list parse without a diagnostic. Gates through tools/guard.sh: fmt, clippy, workspace 4 762 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 11:41:46 -07:00
lucioandClaude Fable 5.1 14b72f2862 MCP M3: the edit tools — format, fix_lint, rename, the port/import/module refactorings, instantiate — through one all-or-nothing write path; diff printer lifted to lucisv_core (MCP-1)
crates/lucisv_mcp/src/apply.rs is the one write path every edit tool uses: every file's new text is computed first (edits applied last-first; overlap, past-the-end and split-character edits refused), every target must lie inside a root (a created file's directory too, symlinked dirs resolved), every file is re-read and compared byte for byte with the text the plan was computed against before the first write — one mismatch refuses the whole edit — then write_atomic in path order, a failure part-way reported as "written N of M". dry_run returns the unified diff. Tools (tools/{format,edit,refactor}.rs): format (per-file lucisv.toml config, lines ranges, the safety net's refusal names the file, a formatter panic is caught), fix_lint (the diagnostics lint pass, safe fixes only, never inside a lucisv: off fence, refuses a result with more parse errors), rename, expand_wildcard, convert_ports, organize_imports, inline_module, propagate_ports, remove_port, add_port, extract_module (new file or same file), instantiate (text only; instance name validated). Every whole-set tool hands the engine every indexed file read at call time and re-walks the roots first (a file written in the last 5 s is in the set); a file the index skips (over 1 MiB, non-UTF-8) that spells a changed name as a whole word refuses the edit, otherwise it is named once under warnings; references carries the same warning. Annotations from an Effect table (read / edit, idempotent where a second call writes nothing).

MCP-1 delivered as a pure move: crates/lucisv/src/diff.rs::unified → lucisv_core::diff::unified, the CLI re-exports it; --diff output byte-identical (QA compared the 82bbba0 binary over the aes copy); lucisv_core still dependency-free.

QA (Opus, two rounds + two lead fixes): 38 qa_m3 tests; the write path held under a 50 ms writer race (no torn file in 650 calls), chmod 444, symlinked escapes, a concurrent lucisv --check; format/fix_lint byte-identical to the CLI on CRLF, nested configs, fences and all 124 aes files. Open and OUT of this lane: vlog_refactor::rename leaves .* and .name shorthand connections broken when a port or its bound net is renamed — a pre-existing engine corruption the LSP shares, fixed next in lane M3.5 (TODO-MCP.md); the rename tool says so until then. Engine findings filed: MCP-8 (false remove_port refusal on a same-file instantiation), MCP-10 (extract_module writes LF into a CRLF file). Gates through tools/guard.sh: fmt, clippy, workspace 4 664 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 07:24:28 -07:00
lucioandClaude Fable 5.1 82bbba04be MCP M2: definition, references, hierarchy, diagnostics, defines and the lucisv:// resources
Five navigation tools on the M1 transport (crates/lucisv_mcp/src/tools/{nav,select,hierarchy,diagnostics,defines,source}.rs, src/resources.rs): one selector for definition/references (file+line+col in 1-based bytes, file+line+name with the name chosen by token — never by text, so comments, strings and macro arguments cannot stand in — file+name refused when its uses resolve to different declarations, or a bare name with an optional unit); definition walks the server's ladder (include beside the file, macro, local table, workspace overlay computed per call) and lists every site with its byte-checked source line; references hands vlog_refactor::find_references the WHOLE indexed set — the plan's word-census narrowing was the lead's and QA proved it drops uses that resolve through a file never spelling the name (a two-level tail, a class-handle chain), so it is gone and MCP-7 asks vlog_refactor for a KnownFacts variant (≈2 s per call on opentitan's 3 944 files, recorded); hierarchy is the index's instantiation census down (default every top module) or up, depth 1..=20 in the schema, recursion and node caps, overrides sliced per statement; diagnostics is what `lucisv check .` reports — parse errors first, then lint under each file's lucisv.toml [lint] select/ignore/options/waivers through an index-backed MentionOracle, unused waivers in the whole-project form, the CLI's JSON field names; defines lists one file's, one macro's or the project's table. Resources: lucisv://overview, lucisv://rules, lucisv://unit/{name}, lucisv://file/{path}/outline. M1 QA finding 11 (a bare escaped name ending in @digits) fixed in read_item.

QA (Opus, two rounds): 43 qa_m2 tests; four wrong answers (the narrowing, a macro-argument occurrence answered as the macro, per-instance overrides in one statement, file+name guessing among declarations) and seven smaller findings fixed under the lead's rulings. opentitan census as an #[ignore] test (LUCISV_OPENTITAN): entropy_masking_req lists aes_bind.sv, state_q lists entropy_src_core.sv, top_earlgrey → u_aes : aes, parity with the LSP at every symbol — plus three real aes instantiations in the *_pd_main.sv tops the LSP omits (MCP-6, to file in TODO.md). Checkout untouched. Gates through tools/guard.sh: fmt, clippy, workspace 4 610 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 05:46:19 -07:00
lucioandClaude Fable 5.1 7a0c8e51f9 MCP block: plan, TODO-MCP.md, and M1 — lucisv-mcp transport and the six read tools
docs/mcp/PLAN.md and TODO-MCP.md (2026-09-23): lucisv gets a Model Context Protocol server for coding agents as a separate block — a new crate composing the six library crates, never lucisv_server or the CLI, interacting with them only through lucisv.toml/filelist discovery, atomic on-disk edits the LSP's watcher already sees, and (M6) a read-only warm start from the LSP's index cache; shipped as a third binary in every platform vsix (M5). Six lanes, dev → QA → lead on trunk, both Opus 5.5 by the owner's ruling; no release until the block is done.

M1: crates/lucisv_mcp (binary lucisv-mcp), no new dependency — newline-delimited JSON-RPC over stdio with the pinned serde_json, one synchronous loop on a PARSE_STACK_SIZE thread, legacy-era handshake (2025-11-25 echoed or offered, 2025-06-18 accepted; the 2026-07-28 era filed as MCP-4). Project: roots, Discovery, filelist-or-walk with the 1 MiB cap, IndexBuilder, per-call freshness sweep (size/mtime/ctime/inode + git's racy-clean rule, absorb in one merge, re-walk on a miss/every 5 s/on overview) so no answer is older than the disk when the call arrived; walked files outside every root dropped with a warning; paths refused outside the roots. Tools project_overview, list_units, unit_interface (params, ports with packed/unpacked ranges, instantiation template, modports, class/package members read off the declaration itself), outline, read_item (name, kind:name, name@LINE, always@LINE…), search_symbols — closed schemas, read-only annotations, compact renderings (PLAN §4.5), structuredContent beside the text. Invalid tool arguments are tool errors (SEP-1303), columns are 1-based bytes everywhere.

QA (Opus, two rounds): 51 qa_m1 tests; the one wrong answer (a class's extends/members read by bare name) and nine smaller findings fixed under the lead's rulings; finding 11 (a bare escaped name ending in @digits) carried to M2. opentitan hw/: 3 944 files indexed in 1.6 s release, later calls 5–11 ms, a miss walk 145 ms; checkout untouched. Gates through tools/guard.sh: fmt, clippy, workspace 4 548 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 03:58:55 -07:00
lucioandClaude Fable 5.1 ef867db004 TODO §64.2: 0.55.0 verified — loop 3 round 2 closed
ci / checks (push) Successful in 1m23s
ci / corpus (push) Successful in 35s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-17 14:49:13 -07:00
lucioandClaude Fable 5.1 23e2e4bca5 Release 0.55.0 — loop 3 round 2: references reach a module's internals across files; a stale index omits, never mislocates
ci / checks (push) Successful in 1m11s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 9m37s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-17 14:36:35 -07:00
lucioandClaude Fable 5.1 a2a22adad8 Cross-file references reach a module's nets, variables and instances (§64.1, QA task_d8afe80f of §63.1): nav.rs's two index questions (leaves_this_file, indexed_def_in_file, the latter shared with hover's live_symbol) asked WorkspaceIndex::member — the connection surface, ports and parameters — so a declaration only a hierarchical path can name (a bind connection's expression half, a u_x.sig tail) was judged unable to leave its file and references fell to the single-file answer, while a rename already edited both files; from a use that did resolve cross-file, the declaring buffer's own uses could not re-identify themselves. Both now ask member_in(…, Surface::Hierarchical); the connection answer comes first and whole from that read, so every port/parameter/package/class/struct answer is byte-identical (nav harness controls and a 948-declaration opentitan census). A hierarchical-only member has no Local postings by the §49 ruling, so nav::declaring_file_uses parses exactly the closed declaring file once per request (0.4–1.5 ms on state_q into a shut entropy_src_main_sm.sv), hierarchical_only asking the index's own table rather than restating surface_of. Three QA rounds (Sonnet, Sonnet, then Fable per the escalation rule): the closed-file path read a cached FileView and rendered against a fresh text_of (a stale offset on a wrong line) — now one fresh read per closed file threaded to the rendering step; every index-time span about a closed file, and the open-buffer declaration fallback (nav::declaration_site), guarded by hover::spells_exactly (pub(crate), shared not copied): a stale index may omit a location, never mislocate one. Accepted: +25 % on a local-net references in a 40 267-line buffer (1.22 → 1.54 ms), the guard is textual (a different exact token at a deleted declaration's old bytes). opentitan: entropy_masking_req from aes.sv now lists aes_bind.sv; state_q lists entropy_src_core.sv; checkout untouched. Tests 4422 → 4459 (11 dev + 1 hover + 1 e2e wire test; 19 QA attacks incl. escaped identifiers, UTF-8 boundaries, a deleted declaring file, oracle equivalence with vlog_refactor::find_references); fmt, clippy, workspace suite green through tools/guard.sh. Feature README docs/features/references-hierarchical-surface; references-nav, hierarchical-tail and hover-declarations READMEs, record.rs's postings comment and the topo row amended; perf entry in docs/perf/README.md. Release 0.55.0 left to the owner.
ci / checks (push) Successful in 1m14s
ci / corpus (push) Successful in 36s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 14:50:16 -07:00
lucioandClaude Fable 5.1 9d1eb1671e TODO §64: loop 3 round 2 — cross-file references for hierarchical-surface-only declarations
ci / checks (push) Successful in 1m11s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 13:01:38 -07:00
lucioandClaude Fable 5.1 5d70cb89cc TODO §63.3: 0.54.0 verified — loop 3 round 1 closed
ci / checks (push) Successful in 1m11s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 03:23:09 -07:00
lucioandClaude Fable 5.1 da32237a0e Release 0.54.0 — loop 3 round 1: rename edits bind files; first request after an edit −19 %
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m58s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 03:13:40 -07:00
lucioandClaude Fable 5.1 c82978c3db First request after an edit −19 % (§63.2, N1 of the 0.52.0 review): the flush split on the timing line (rebuild{lex parse defines analyze external lines publish documents}) named lex 29 + parse 26 of a 100 ms flush and no second lint or analysis; the lexer's two phases fused (the intermediate Vec<RawTok> gone), Parser::skip for the 178 bump() sites that discarded the token, a first-byte test in front of the operator table (tokenize 27.8 → 11.6 ms). Pinmux first menu after didChange 109 → 88 ms paired; every other row within noise; RSS not up. Token stream, diagnostics, AST and symbols digested over 4 807 files: 0 differ (re-derived by QA against a rebuilt 1b8723c); five gap fuzzers at their pins; corpus and opentitan byte-identical. Lead: an orphan trailing comment leads the next token instead of vanishing (unreachable, kept as a rule). QA: 16 attack tests, the flat-groups guard the harness relies on.
ci / checks (push) Successful in 1m16s
ci / corpus (push) Successful in 34s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 03:11:59 -07:00
lucioandClaude Fable 5.1 1b8723ca1f Rename edits and warns about a bind file's own occurrences (§63.1): a bind connection's bare name is a reference on the target's hierarchical surface under target::name (the resolver asked the connection surface — ports and parameters — so an internal net resolved to nothing and, with no name on the path, was never warned about); a hierarchical path in a bind connection is rooted at the bind target (Target::BindMember, walking descend/member_at shared with member_of); a multi-segment target is spelled tb::u_aes for follow_one; FACTS_FORMAT 19 → 20 (a 0.53.0 store rebuilds once); selection was never the gap. Parity: every difference against 0.53.0 is a bind file's new edit or warning (1 758 − 8 = 1 750 sentences held), tail rename 326 ms. 16 engine fixtures (QA's six attacks included), a preflight-parity fixture, a wire-level definition/references test; QA filed the pre-existing nav.rs references gap for loop 3.
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 34s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 01:05:14 -07:00
lucioandClaude Fable 5.1 2675131f8c TODO §63: loop 3 round 1 — the bind rename gap (63.1), N1 first-after-edit (63.2)
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-11 23:08:51 -07:00
lucioandClaude Fable 5.1 409acae087 TODO: correct the §61.3 closing note (the metadata hand-off shipped)
ci / checks (push) Successful in 1m6s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-11 23:04:02 -07:00
lucioandClaude Fable 5.1 f5edac9197 TODO: tick the two loop-3 lines §61.2/§61.3 already closed
ci / checks (push) Successful in 1m8s
ci / corpus (push) Successful in 31s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-11 23:03:48 -07:00
lucio 7df86fe979 TODO §62.4: 0.53.0 verified — the 0.52.0 review closed
ci / checks (push) Successful in 1m14s
ci / corpus (push) Successful in 39s
2026-09-09 17:50:49 -05:00
lucio b4a0668b24 Release 0.53.0 — the 0.52.0 review's alias fix
ci / checks (push) Successful in 1m13s
ci / corpus (push) Successful in 42s
release / build-and-publish (push) Successful in 6m41s
2026-09-09 17:40:29 -05:00
lucio 41945912a3 0.52.0 review fixes (§62): F1 — one directory-identity tracker shared by the split scan's two walks, a pre-check that takes the single canonical walk when an alias sorts before the open folder, a conflict found by the remaining walk turned into one ordinary rescan, the open-buffer alias gate on both walks and only on same-named files (stats 0 on opentitan again), nine alias fixtures agreeing across startup, rescan and restart; F2/F3 — the load probe primes a warm store untimed and stamps scan completion from the scan's own end event
ci / checks (push) Successful in 1m19s
ci / corpus (push) Successful in 46s
2026-09-09 17:39:23 -05:00
lucio faf890d9f0 docs: independent review of 0.52.0 (Codex, 2026-09-09) — F1 a symlink-aliased directory indexed twice by the split startup scan, F2/F3 load-probe defects; the implementation plan and the evidence 2026-09-09 17:39:23 -05:00
lucio 3ceba21bb2 TODO §61.6: 0.52.0 verified — the review round closed
ci / checks (push) Successful in 1m8s
ci / corpus (push) Successful in 32s
2026-09-09 00:52:01 -05:00
174 changed files with 33574 additions and 694 deletions

No files matched your search

+154
View File
@@ -4,6 +4,160 @@ 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
Generated
+22 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.52.0"
version = "0.56.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,25 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.52.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.52.0"
version = "0.56.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.52.0"
version = "0.56.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.52.0"
version = "0.56.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -265,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.52.0"
version = "0.56.0"
[[package]]
name = "vlog_refactor"
version = "0.52.0"
version = "0.56.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -278,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.52.0"
version = "0.56.0"
dependencies = [
"vlog_parser",
]
+2 -1
View File
@@ -9,10 +9,11 @@ members = [
"crates/lucisv_core",
"crates/lucisv",
"crates/lucisv_server",
"crates/lucisv_mcp",
]
[workspace.package]
version = "0.52.0"
version = "0.56.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+331
View File
@@ -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`.
+345 -3
View File
@@ -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
@@ -4733,6 +4738,19 @@ in 0.49.0. Take 4's findings are in the loop-3 list above.
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
@@ -5855,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
@@ -6158,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;
@@ -6596,4 +6617,325 @@ sentence; the selection set stays the correctness reference (P2d).
- [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; release below
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
View File
@@ -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;
+221
View File
@@ -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}");
}
}
+3 -1
View File
@@ -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;
+125 -25
View File
@@ -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.
@@ -77,18 +77,24 @@ pub fn collect_files_with(
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(),
found,
warn,
};
let mut walk =
Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn };
walk.dir(path);
} else if path.is_file() {
found(path.to_path_buf(), None);
@@ -125,20 +131,27 @@ pub fn collect_files_below(
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(),
visited: HashSet::new(),
found,
warn,
};
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);
@@ -170,24 +183,78 @@ pub fn collect_files_below(
/// 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))
@@ -203,7 +270,7 @@ struct Walk<'a> {
gitignore: bool,
ignores: Vec<Ignore>,
rel: Vec<String>,
visited: HashSet<DirId>,
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>),
@@ -291,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.
@@ -963,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());
}
}
+23
View File
@@ -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 }
+415
View File
@@ -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();
}
}
+130
View File
@@ -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());
}
}
+168
View File
@@ -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());
}
}
+284
View File
@@ -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();
}
}
+321
View File
@@ -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;
+109
View File
@@ -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();
}
+246
View File
@@ -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");
}
}
+180
View File
@@ -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}");
}
}
}
+370
View File
@@ -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"));
}
}
+210
View File
@@ -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('…'));
}
}
+388
View File
@@ -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)
}
}
+283
View File
@@ -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)
}
+267
View File
@@ -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, &regions)))
.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")
}
+408
View File
@@ -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);
}
}
+372
View File
@@ -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))
}
+283
View File
@@ -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);
}
}
+416
View File
@@ -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}");
}
}
}
+474
View File
@@ -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"));
}
}
+340
View File
@@ -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}");
}
}
+291
View File
@@ -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) }
}
+212
View File
@@ -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)
}
+289
View File
@@ -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;");
}
}
+95
View File
@@ -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
+3
View File
@@ -0,0 +1,3 @@
module broken (input logic a);
assign b = ;
endmodule
+5
View File
@@ -0,0 +1,5 @@
interface bus_if;
logic req, gnt;
modport master (output req, input gnt);
modport slave (input req, output gnt);
endinterface
+16
View File
@@ -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
+16
View File
@@ -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
+4
View File
@@ -0,0 +1,4 @@
module messy(input logic a,output logic b);
assign b=a;
// keep this comment
endmodule
+7
View File
@@ -0,0 +1,7 @@
module cell (
input logic clk,
input logic en,
output logic o
);
assign o = en;
endmodule
+4
View File
@@ -0,0 +1,4 @@
package edit_pkg;
parameter int WIDTH = 8;
typedef logic [WIDTH-1:0] word_t;
endpackage
+9
View File
@@ -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
+9
View File
@@ -0,0 +1,9 @@
module inl (
input logic x,
output logic z
);
inv u_inv (
.i(x),
.o(z)
);
endmodule
+6
View File
@@ -0,0 +1,6 @@
module inv (
input logic i,
output logic o
);
assign o = ~i;
endmodule
+7
View File
@@ -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
+11
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
module old (a, b, y);
input a;
input b;
output y;
assign y = a & b;
endmodule
+7
View File
@@ -0,0 +1,7 @@
module partial (
input logic clk,
input logic en,
output logic o
);
cell u_c (.clk(clk));
endmodule
+7
View File
@@ -0,0 +1,7 @@
module spare (
input logic clk,
input logic unused_i,
output logic o
);
assign o = clk;
endmodule
+10
View File
@@ -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
+15
View File
@@ -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
+7
View File
@@ -0,0 +1,7 @@
module wild (
input logic clk,
input logic en,
output logic o
);
cell u_cell (.*);
endmodule
+2
View File
@@ -0,0 +1,2 @@
# The chain file is waived for line length.
waive --rule=line-length --location=rtl/chain.sv
+7
View File
@@ -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
+5
View File
@@ -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
+2
View File
@@ -0,0 +1,2 @@
module checker_m (input logic [3:0] state_q);
endmodule
+14
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
bind core checker_m u_chk (.state_q(state_q));
+2
View File
@@ -0,0 +1,2 @@
`define NAV_W 4
`define ADD(a, b = 1) ((a) + (b))
+6
View File
@@ -0,0 +1,6 @@
module dual (a, y);
input a;
output y;
wire y;
assign y = a;
endmodule
+9
View File
@@ -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
+6
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
class env;
sb s;
function void run();
s.count = 0;
endfunction
endclass
+6
View File
@@ -0,0 +1,6 @@
class sb;
int count;
function void add();
count++;
endfunction
endclass
+161
View File
@@ -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
+40 -1
View File
@@ -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
+209 -2
View File
@@ -72,6 +72,86 @@ impl Stage {
[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 {
@@ -200,6 +280,8 @@ pub struct Trace {
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,
}
@@ -208,17 +290,25 @@ 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.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={} {}}} action{{{}}}",
"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(),
)
}
@@ -232,6 +322,7 @@ thread_local! {
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.
@@ -292,6 +383,30 @@ pub fn stage<T>(stage: Stage, work: impl FnOnce() -> T) -> T {
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| {
@@ -397,4 +512,96 @@ mod tests {
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());
}
}
+34 -1
View File
@@ -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();
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -359,7 +359,10 @@ mod tests {
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");
assert!(trace.contains("reused_files=1"), "only the untouched buffer's record: {trace}");
// 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");
+12 -1
View File
@@ -198,6 +198,14 @@ pub struct ScanTrace {
/// 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`]).
@@ -444,7 +452,8 @@ impl ScanTrace {
"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,
@@ -465,6 +474,8 @@ impl ScanTrace {
self.published,
self.first_publish_ms,
self.overlays,
self.conflict,
self.rescan_requested,
)
}
@@ -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))
+9
View File
@@ -300,6 +300,15 @@ impl Server {
}
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| {
@@ -58,6 +58,8 @@ 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;
@@ -99,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
);
}
@@ -57,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(
@@ -1109,3 +1119,370 @@ fn a_rescan_does_not_lead_with_a_folder_because_nothing_may_be_answered_inside_i
"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);
}
+215 -35
View File
@@ -21,13 +21,28 @@
//! 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, collect_files_with, EXTENSIONS};
use lucisv_core::walk::{
collect_files_below_tracked, collect_files_tracked, dir_id, DirectoryTracker, EXTENSIONS,
};
use crate::scan_trace::ScanTrace;
@@ -93,6 +108,53 @@ pub(super) fn oversize(found: &Found, cap: u64, stats: &mut usize) -> Option<u64
(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.
@@ -144,6 +206,9 @@ impl Workspace {
// 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();
@@ -155,6 +220,9 @@ impl Workspace {
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);
@@ -301,6 +369,19 @@ impl Workspace {
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();
@@ -326,10 +407,11 @@ impl Workspace {
// 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_with(
let _ = collect_files_tracked(
input,
&exclude,
true,
tracker,
&mut |path, len| out.push(Found { path, len }),
&mut |w| warn(w.to_string()),
);
@@ -441,25 +523,59 @@ impl Workspace {
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 head = self.neighbourhood_files(&mut |w| warnings.push(w), trace);
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()));
if head.len() > HEAD_WALK_MAX {
// Too big to lead with unproven. Finish the walk now and hand back
// the whole scope, ordered the way every scan before this one was.
let (mut files, rest_warnings, _) = self.walked_rest(&seen, trace);
warnings.extend(rest_warnings);
files.extend(head);
sort_found(&mut files);
let scope = Scope { files, incdirs: Vec::new(), warnings };
return (self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace), None);
}
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 }))
(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
@@ -474,6 +590,7 @@ impl Workspace {
/// 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> {
@@ -489,11 +606,12 @@ impl Workspace {
exclude.extend(self.client.exclude.iter().cloned());
ScanTrace::add(&mut trace.config_ms, configuring);
let walking = trace.now();
let _ = collect_files_below(
let _ = collect_files_below_tracked(
&root,
&dir,
&exclude,
true,
tracker,
&mut |path, len| out.push(Found { path, len }),
&mut |w| warn(w.to_string()),
);
@@ -517,36 +635,45 @@ impl Workspace {
.cloned()
}
/// The roots walked, less what `seen` already names — the walk half of
/// [`Workspace::rest_of_scope`], with no cap and no reporting.
fn walked_rest(
&self,
seen: &HashSet<PathBuf>,
trace: &mut ScanTrace,
) -> (Vec<Found>, Vec<String>, usize) {
let mut warnings: Vec<String> = Vec::new();
let walked = self.walked_files(&self.roots, &mut |w| warnings.push(w), trace);
let kept: Vec<Found> =
walked.into_iter().filter(|found| !seen.contains(&found.path)).collect();
let count = kept.len();
(kept, warnings, count)
}
/// 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 `seen`.
/// 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,
roots: &[PathBuf],
seen: &HashSet<PathBuf>,
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(roots, &mut |w| warnings.push(w), trace);
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;
@@ -556,7 +683,10 @@ impl Workspace {
// 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.
if seen.contains(&found.path) {
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) {
@@ -572,6 +702,56 @@ impl Workspace {
}
}
/// 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.
///
+88 -11
View File
@@ -122,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,
@@ -898,7 +900,7 @@ impl Workspace {
/// 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(pending) = scan.take_pending() else { return false };
let Some(mut pending) = scan.take_pending() else { return false };
let discovering = scan.trace.now();
let mut skipped = 0usize;
let (files, warnings, walked_skips) = {
@@ -908,11 +910,11 @@ impl Workspace {
}
watch(event);
};
self.rest_of_scope(&pending.roots, &pending.seen, &mut counting, &mut scan.trace)
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);
scan.land_discovery(files, warnings, walked_skips, pending.tracker.has_conflict());
scan.trace.measure_work(
scan.work.len(),
held_bytes(&scan.buffered),
@@ -1754,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.
@@ -5861,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}"
);
}
}
+46 -1
View File
@@ -168,6 +168,17 @@ pub(super) struct PendingDiscovery {
/// 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
@@ -277,9 +288,40 @@ impl Scan {
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.
/// 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
@@ -290,7 +332,10 @@ impl Scan {
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();
+110
View File
@@ -8631,3 +8631,113 @@ fn organize_imports_is_offered_under_its_own_kind_and_runs_as_a_command() {
let _ = std::fs::remove_dir_all(&dir);
}
/// TODO §64.1 over the wire. `leaf` declares an internal net; `top.sv` names it
/// through a hierarchical tail and `leaf.sv` uses it itself. Before §64.1
/// `textDocument/references` answered `leaf.sv`'s two lines from the
/// declaration and never the tail, while `textDocument/rename` at the same
/// position edited both files — lucisv could change a reference it could not
/// list. Asserted here from both ends, with `leaf.sv` the only open buffer, so
/// the tail comes out of the persisted postings and `leaf.sv`'s own use out of
/// the live one; then from `top.sv` with `leaf.sv` closed, where that file's
/// own use is served by one re-analysis of it.
#[test]
fn a_hierarchical_nets_references_and_rename_agree_over_the_wire() {
let dir = temp_dir("hierrefs");
let leaf = dir.join("leaf.sv");
let leaf_text = "\
module leaf (input logic clk_i);
logic sig;
assign sig = clk_i;
endmodule
";
std::fs::write(&leaf, leaf_text).expect("write");
let top = dir.join("top.sv");
let top_text = "\
module top;
leaf u_leaf (.clk_i(1'b0));
wire w;
assign w = u_leaf.sig;
endmodule
";
std::fs::write(&top, top_text).expect("write");
let root = format!("file://{}", dir.display());
let leaf_uri = format!("file://{}", leaf.display());
let top_uri = format!("file://{}", top.display());
// `sig` is declared at line 1 column 8 of `leaf.sv`, used at line 2
// column 9 there, and named at line 3 column 20 of `top.sv`.
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{leaf_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(leaf_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{leaf_uri}"}},"position":{{"line":1,"character":8}},"context":{{"includeDeclaration":true}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{leaf_uri}"}},"position":{{"line":1,"character":8}},"newName":"renamed"}}}}"#
)),
// Now from the other side, with `leaf.sv` shut.
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didClose","params":{{"textDocument":{{"uri":"{leaf_uri}"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(top_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":3,"character":20}},"context":{{"includeDeclaration":true}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let response = |id: u32| -> &serde_json::Value {
messages
.iter()
.find(|m| m["id"] == id)
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"))
};
// Every place naming the net, as `(file, line)`.
let places = |id: u32| -> Vec<(String, i64)> {
let mut out: Vec<(String, i64)> = response(id)["result"]
.as_array()
.expect("a list")
.iter()
.map(|location| {
let uri = location["uri"].as_str().expect("a uri");
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
(name, location["range"]["start"]["line"].as_i64().expect("a line"))
})
.collect();
out.sort();
out
};
let everywhere =
vec![("leaf.sv".to_string(), 1), ("leaf.sv".to_string(), 2), ("top.sv".to_string(), 3)];
assert_eq!(places(2), everywhere, "from the declaration");
assert_eq!(places(4), everywhere, "from the tail, with `leaf.sv` closed");
// And the rename that was already editing both files edits exactly those
// places — the asymmetry §64.1 was filed for, closed from both sides.
let changes = &response(3)["result"]["changes"];
let own = changes[&leaf_uri].as_array().expect("edits for the declaring file");
assert_eq!(own.len(), 2, "{own:#?}");
let elsewhere = changes[&top_uri].as_array().expect("edits for the naming file");
assert_eq!(elsewhere.len(), 1, "{elsewhere:#?}");
assert_eq!(elsewhere[0]["range"]["start"]["line"], 3);
assert_eq!(elsewhere[0]["range"]["start"]["character"], 20);
assert!(elsewhere.iter().all(|e| e["newText"] == "renamed"), "{elsewhere:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
+280 -62
View File
@@ -403,8 +403,14 @@ impl<'a> RawLexer<'a> {
});
}
// Operators, longest match first.
// Operators, longest match first. The first-byte test is not a second
// way of matching — `starts_with` still decides — it is what keeps a
// `;` from being compared against all 42 spellings: one byte compare
// rejects every operator that cannot start here (TODO §63.2).
for op in OPERATORS {
if op.as_bytes()[0] != c {
continue;
}
if self.starts_with(op) {
for _ in 0..op.len() {
self.bump();
@@ -918,80 +924,111 @@ fn is_line_directive(word: &str) -> bool {
)
}
/// What the attachment phase carries from one raw token to the next.
#[derive(Default)]
struct Attaching {
/// Comments waiting for the real token they lead.
pending: Vec<Comment>,
/// Whether a blank line was seen since the last pending comment.
pending_blank: bool,
}
/// Tokenize source text, attaching comments and blank-line info to tokens.
///
/// The two phases are **fused**: each raw token is attached as it is lexed,
/// rather than collected into a `Vec<RawTok>` the attachment loop then walks.
/// Attachment only ever reads the raw token in hand and the token last pushed,
/// so the fusion is a pure reordering — it drops a second whole-file vector
/// (a 40 267-line file's worth of it is ~22 MB of allocation, growth copying
/// and teardown), which is why the first request after an edit pays less for
/// the same tokens (TODO §63.2).
pub fn tokenize(source: &str) -> Result<Vec<Token>, LexError> {
let mut raw_lexer = RawLexer::new(source.as_bytes());
let mut raws: Vec<RawTok> = Vec::new();
let mut tokens: Vec<Token> = Vec::with_capacity(estimated_tokens(source.len()));
let mut state = Attaching::default();
loop {
let tok = raw_lexer.next_raw()?;
let is_eof = tok.kind == RawKind::Real(TokenKind::Eof);
raws.push(tok);
let raw = raw_lexer.next_raw()?;
let is_eof = raw.kind == RawKind::Real(TokenKind::Eof);
attach(raw, &mut tokens, &mut state);
if is_eof {
break;
}
}
Ok(tokens)
}
// Attachment phase.
let mut tokens: Vec<Token> = Vec::new();
let mut pending: Vec<Comment> = Vec::new();
let mut pending_blank = false;
/// How many tokens a source of `bytes` bytes is guessed to hold.
///
/// Only to spare the growing vector its early doublings; a wrong guess costs
/// nothing but the growth it would have paid anyway. Six bytes a token is the
/// measured average over the corpus and over opentitan's generated register
/// files alike, and the guess is capped so a pathological file (one enormous
/// string literal) cannot reserve more than it could ever need.
fn estimated_tokens(bytes: usize) -> usize {
(bytes / 6).min(1 << 20)
}
for raw in raws {
match raw.kind {
RawKind::LineComment | RawKind::BlockComment => {
let same_line_as_prev =
raw.newlines_before == 0 && !tokens.is_empty() && pending.is_empty();
let comment = Comment {
text: raw.text,
blank_before: raw.newlines_before > 1 || pending_blank,
line: raw.line,
col: raw.col,
span: raw.span,
};
if same_line_as_prev {
// Trailing comment for the previous real token.
let prev = tokens.last_mut().unwrap();
match &mut prev.trailing {
Some(existing) => {
// Two comments on one line become one node, so its
// span has to cover both — the merge normalizes
// the gap between them to a single space, which is
// why a merged comment is the one comment whose
// text can differ from `source[span]`.
existing.text.push(' ');
existing.text.push_str(&comment.text);
existing.span = TextRange::new(existing.span.start, comment.span.end);
}
None => prev.trailing = Some(comment),
}
} else {
pending.push(comment);
pending_blank = false;
}
}
RawKind::Real(kind) => {
let blank_before = if pending.is_empty() {
raw.newlines_before > 1
} else {
// Comments already carry their own blank flags; the token
// is blank-separated only if there was a blank line
// between the last comment and the token itself.
raw.newlines_before > 1
};
tokens.push(Token {
kind,
text: raw.text,
line: raw.line,
col: raw.col,
span: raw.span,
leading: std::mem::take(&mut pending),
trailing: None,
blank_before,
});
/// Fold one raw token into the token stream: a comment onto its neighbour,
/// a real token onto the end with whatever comments were waiting for it.
fn attach(raw: RawTok, tokens: &mut Vec<Token>, state: &mut Attaching) {
match raw.kind {
RawKind::LineComment | RawKind::BlockComment => {
let same_line_as_prev =
raw.newlines_before == 0 && !tokens.is_empty() && state.pending.is_empty();
let comment = Comment {
text: raw.text,
blank_before: raw.newlines_before > 1 || state.pending_blank,
line: raw.line,
col: raw.col,
span: raw.span,
};
// A comment that finds no token to trail — unreachable while
// `same_line_as_prev` requires one, kept as a rule rather than a
// hope — leads the next token instead of vanishing (invariant 3).
let orphan =
if same_line_as_prev { attach_trailing(tokens, comment) } else { Some(comment) };
if let Some(comment) = orphan {
state.pending.push(comment);
state.pending_blank = false;
}
}
RawKind::Real(kind) => {
// Comments already carry their own blank flags; the token is
// blank-separated only if there was a blank line between the last
// comment and the token itself — which is the same test either
// way, so `pending` does not enter into it.
let blank_before = raw.newlines_before > 1;
tokens.push(Token {
kind,
text: raw.text,
line: raw.line,
col: raw.col,
span: raw.span,
leading: std::mem::take(&mut state.pending),
trailing: None,
blank_before,
});
}
}
Ok(tokens)
}
/// Hang a comment off the token before it, merging with one already there.
/// Handed back untouched when there is no token before it.
fn attach_trailing(tokens: &mut [Token], comment: Comment) -> Option<Comment> {
let Some(prev) = tokens.last_mut() else { return Some(comment) };
match &mut prev.trailing {
Some(existing) => {
// Two comments on one line become one node, so its span has to
// cover both — the merge normalizes the gap between them to a
// single space, which is why a merged comment is the one comment
// whose text can differ from `source[span]`.
existing.text.push(' ');
existing.text.push_str(&comment.text);
existing.span = TextRange::new(existing.span.start, comment.span.end);
}
None => prev.trailing = Some(comment),
}
None
}
#[cfg(test)]
@@ -1510,4 +1547,185 @@ mod tests {
assert!(texts.contains(&"!=="));
assert!(texts.contains(&"<="));
}
// ------------------------------------------------------------------
// TODO §63.2 QA: the fused attach phase, attacked
//
// These cover the shapes the two-phase code (a `Vec<RawTok>` fully
// built, then walked) could tell apart from the fused one-pass code
// (each raw token attached as it is produced) if the fusion were not a
// pure reordering: a comment with no token before it at all, comments
// that never see a "previous token" until much later, EOF immediately
// after a trailing comment, and so on. Every one of these was also
// cross-checked, file for file, against `tokenize` built from 1b8723c
// (the pre-fusion tree) with a throwaway digest tool in the QA
// scratchpad — token-for-token identical, hash and manual `Debug`
// inspection alike; the assertions below pin that result durably.
// ------------------------------------------------------------------
#[test]
fn a_comment_as_the_very_first_thing_in_the_file_is_the_first_token_s_leading() {
let toks = tokenize("// only thing before the module\nmodule m;\nendmodule").unwrap();
assert_eq!(toks[0].leading.len(), 1);
assert_eq!(toks[0].leading[0].text, "// only thing before the module");
assert!(!toks[0].leading[0].blank_before);
}
#[test]
fn two_comments_on_the_first_line_before_any_token_both_lead_it() {
// Two *separate* comments here means two lines, each its own line
// comment (a line comment always runs to end of line, so "two
// comments on one line" before any token is only possible with
// block comments — covered by `two_block_comments_on_one_line_merge`
// below).
let toks = tokenize("// one\n// two\nmodule m;\nendmodule").unwrap();
assert_eq!(toks[0].leading.len(), 2);
assert_eq!(toks[0].leading[0].text, "// one");
assert_eq!(toks[0].leading[1].text, "// two");
assert!(!toks[0].leading[1].blank_before);
}
#[test]
fn a_trailing_comment_after_the_last_real_token_reaches_eof() {
let toks = tokenize("module m;\nendmodule // trailing at eof\n").unwrap();
let end = toks.iter().find(|t| t.is_kw("endmodule")).unwrap();
let trailing = end.trailing.as_ref().expect("trailing comment on endmodule");
assert_eq!(trailing.text, "// trailing at eof");
assert_eq!(toks.last().unwrap().kind, TokenKind::Eof);
}
#[test]
fn two_block_comments_on_one_line_merge_into_one_trailing_comment() {
let toks = tokenize("wire w; /* one */ /* two */\nendmodule").unwrap();
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
let trailing = semi.trailing.as_ref().expect("merged trailing comment");
assert_eq!(trailing.text, "/* one */ /* two */");
}
#[test]
fn a_blank_line_between_a_comment_and_its_token_marks_both() {
let toks = tokenize("// lead\n\nmodule m;\nendmodule").unwrap();
assert_eq!(toks[0].leading.len(), 1);
// The comment itself is not blank-separated from what came before it
// (nothing did); the blank line sits between the comment and the
// token, so the *token* carries the flag.
assert!(!toks[0].leading[0].blank_before);
assert!(toks[0].blank_before);
}
#[test]
fn crlf_line_endings_lex_like_lf_with_the_same_comment_attachment() {
let toks = tokenize("module m; // c\r\nendmodule\r\n").unwrap();
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
assert_eq!(semi.trailing.as_ref().unwrap().text, "// c");
let end = toks.iter().find(|t| t.is_kw("endmodule")).unwrap();
assert_eq!(end.line, 2);
}
#[test]
fn a_block_comment_spanning_lines_still_leads_a_same_line_token() {
let toks = tokenize("/* block\n spanning\n lines */ module m;\nendmodule").unwrap();
assert_eq!(toks[0].leading.len(), 1);
assert!(toks[0].leading[0].text.starts_with("/* block"));
assert!(toks[0].leading[0].text.ends_with("lines */"));
// The module keyword itself sits on the block comment's last line.
assert_eq!(toks[0].line, 3);
}
#[test]
fn a_comment_between_a_macro_invocation_and_its_arguments_trails_the_macro() {
let toks = tokenize("module m;\n`MYMACRO /*c*/ (a, b);\nendmodule").unwrap();
let mac = toks.iter().find(|t| t.text == "`MYMACRO").unwrap();
assert_eq!(mac.trailing.as_ref().unwrap().text, "/*c*/");
// The macro call's parenthesized arguments are unaffected — still
// ordinary tokens right after, comment or not.
let open_paren_idx = toks.iter().position(|t| t.is_sym("(")).unwrap();
assert_eq!(toks[open_paren_idx + 1].text, "a");
}
#[test]
fn a_file_that_is_only_comments_attaches_them_all_to_the_synthetic_eof() {
let toks = tokenize("// only a comment, nothing else\n").unwrap();
assert_eq!(toks.len(), 1);
assert_eq!(toks[0].kind, TokenKind::Eof);
assert_eq!(toks[0].leading.len(), 1);
assert_eq!(toks[0].leading[0].text, "// only a comment, nothing else");
}
#[test]
fn an_empty_file_lexes_to_a_lone_eof_with_no_comments() {
let toks = tokenize("").unwrap();
assert_eq!(toks.len(), 1);
assert_eq!(toks[0].kind, TokenKind::Eof);
assert!(toks[0].leading.is_empty());
}
// ------------------------------------------------------------------
// TODO §63.2 QA: the operator table's first-byte test
// ------------------------------------------------------------------
#[test]
fn every_operator_s_first_byte_is_a_single_ascii_byte() {
// `op.as_bytes()[0] != c` compares one byte of `c: u8` against the
// table entry's first *byte*. If any entry's first character were
// multi-byte UTF-8, its first byte alone would not identify it and
// the guard could reject a spelling it should have let through. Every
// entry here is pure ASCII punctuation, so the byte comparison is the
// whole character.
for op in OPERATORS {
let first = op.chars().next().expect("no empty operator spellings");
assert!(first.is_ascii(), "{op:?} does not start with an ASCII byte");
assert_eq!(
op.as_bytes()[0],
first as u8,
"{op:?}'s first byte does not match its first char"
);
}
}
#[test]
fn the_operator_table_has_no_duplicate_or_empty_entries() {
// A duplicate wastes a comparison; an empty entry would make
// `op.as_bytes()[0]` panic before ever reaching `starts_with`.
for op in OPERATORS {
assert!(!op.is_empty());
}
let mut sorted = OPERATORS.to_vec();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), OPERATORS.len(), "OPERATORS has a duplicate entry");
}
#[test]
fn every_operator_followed_by_every_other_operator_still_lexes_without_a_gap() {
// The first-byte test must not change *which* entry `starts_with`
// picks — only how many entries are tried before it does. Lexing
// every `op1 op2` concatenation (no space) and requiring the token
// stream to account for every byte with no lex error is the
// regression gate: a wrong short-circuit would either misplace the
// split point or leave a byte unconsumed. Cross-checked pair for
// pair against `tokenize` built from 1b8723c (pre-first-byte-test)
// in the QA scratchpad: 1 764 pairs, 0 differ.
for &op1 in OPERATORS {
for &op2 in OPERATORS {
let src = format!("{op1}{op2} ;");
let toks = tokenize(&src)
.unwrap_or_else(|e| panic!("lexing {op1:?} followed by {op2:?} failed: {e}"));
// Everything up to the space must be Symbol tokens whose
// texts concatenate back to exactly op1 followed by op2,
// with no gap and no overlap.
let mut consumed = String::new();
let mut i = 0;
while toks[i].kind == TokenKind::Symbol && toks[i].text != ";" {
consumed.push_str(&toks[i].text);
i += 1;
}
assert_eq!(
consumed,
format!("{op1}{op2}"),
"{op1:?} followed by {op2:?} did not round-trip"
);
}
}
}
}
+17 -17
View File
@@ -53,11 +53,11 @@ impl<'a> Parser<'a> {
let start = self.here();
let col = self.cur().col;
if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") {
self.bump();
self.bump();
self.skip();
self.skip();
}
// `assert` / `assume` / `cover` / `restrict`.
self.bump();
self.skip();
self.expect_kw("property")?;
self.expect_sym("(")?;
self.skip_balanced("(", ")")?;
@@ -132,22 +132,22 @@ impl<'a> Parser<'a> {
at_stmt_start = false;
let t = self.cur();
if t.is_sym("(") {
self.bump();
self.skip();
self.skip_balanced("(", ")")?;
} else if t.is_sym("[") {
self.bump();
self.skip();
self.skip_balanced("[", "]")?;
} else if t.is_sym("{") {
self.bump();
self.skip();
self.skip_balanced("{", "}")?;
} else if (t.is_kw("disable") || t.is_kw("wait")) && self.nth(1).is_kw("fork") {
// `disable fork` / `wait fork` name the enclosing block; they
// do not open one.
self.bump();
self.bump();
self.skip();
self.skip();
} else if BLOCK_OPENERS.iter().any(|k| t.is_kw(k)) {
depth += 1;
self.bump();
self.skip();
} else if BLOCK_CLOSERS.iter().any(|k| t.is_kw(k)) {
if depth == 0 {
// A closer with nothing open: the action statement is
@@ -156,7 +156,7 @@ impl<'a> Parser<'a> {
return self.error("expected `;`");
}
depth -= 1;
self.bump();
self.skip();
if depth == 0 {
self.parse_label()?;
if !self.eat_kw("else") {
@@ -167,7 +167,7 @@ impl<'a> Parser<'a> {
} else if depth == 0 && self.eat_sym(";") {
return Ok(());
} else {
self.bump();
self.skip();
}
}
}
@@ -199,9 +199,9 @@ impl<'a> Parser<'a> {
let start = self.here();
let col = self.cur().col;
let end_kw = if self.cur().is_kw("sequence") { "endsequence" } else { "endproperty" };
self.bump();
self.skip();
while !self.at_eof() && !self.cur().is_kw(end_kw) {
self.bump();
self.skip();
}
self.expect_closer(end_kw)?;
self.parse_label()?;
@@ -220,7 +220,7 @@ impl<'a> Parser<'a> {
fn parse_default_disable(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.bump(); // default
self.skip(); // default
self.expect_kw("disable")?;
self.expect_kw("iff")?;
self.skip_to_semi()?;
@@ -252,7 +252,7 @@ impl<'a> Parser<'a> {
fn parse_prop_seq_decl_inner(&mut self) -> PResult<PropSeqDecl> {
let kw = self.cur().text.clone();
let end_kw = if kw == "sequence" { "endsequence" } else { "endproperty" };
self.bump();
self.skip();
let before_name = self.take_gap();
let name = self.expect_name()?;
let before_args = self.take_before_open("(");
@@ -407,7 +407,7 @@ impl<'a> Parser<'a> {
let mut action = ActionBlock::default();
if self.cur().is_sym(";") {
action.before = self.take_gap();
self.bump();
self.skip();
return Ok(action);
}
if !self.cur().is_kw("else") {
@@ -415,7 +415,7 @@ impl<'a> Parser<'a> {
}
if self.cur().is_kw("else") {
action.before_else = self.take_gap();
self.bump();
self.skip();
action.after_else = self.take_gap();
action.fail = Some(Box::new(self.parse_stmt()?));
}
+12 -12
View File
@@ -94,7 +94,7 @@ impl<'a> Parser<'a> {
let mut after_hash = Vec::new();
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
self.skip();
after_hash = self.take_gap();
self.expect_sym("(")?;
let mark = self.diags_mark();
@@ -305,7 +305,7 @@ impl<'a> Parser<'a> {
return self.parse_constraint_foreach();
}
if self.cur().is_kw("unique") && self.nth(1).is_sym("{") {
self.bump();
self.skip();
let comments = self.take_gap();
let items = self.parse_constraint_expr_set()?;
return Ok(ConstraintItemKind::Unique { items, comments });
@@ -314,9 +314,9 @@ impl<'a> Parser<'a> {
// `soft` is matched by text, for the reason `parse_constraint_expr`
// gives.
if self.cur().is_kw("disable") && word_at(self.nth(1), "soft") {
self.bump();
self.skip();
let before = self.take_gap();
self.bump();
self.skip();
let after = self.take_gap();
let expr = self.parse_expr()?;
return Ok(ConstraintItemKind::DisableSoft {
@@ -341,7 +341,7 @@ impl<'a> Parser<'a> {
let soft = self.at_soft_constraint();
let mut after_soft = Vec::new();
if soft {
self.bump();
self.skip();
after_soft = self.take_gap();
}
let mark = self.pending_trailing.len();
@@ -374,7 +374,7 @@ impl<'a> Parser<'a> {
}
if !soft && self.cur().is_sym("->") {
let before = self.take_around(mark);
self.bump();
self.skip();
let after = self.take_around(mark);
let set = self.parse_constraint_set()?;
return Ok(ConstraintItemKind::Implication {
@@ -403,7 +403,7 @@ impl<'a> Parser<'a> {
let mut els = None;
if self.cur().is_kw("else") {
else_comments = self.take_dangling();
self.bump();
self.skip();
// The gap after `else` is this item's when the set it introduces
// opens with a token of its own — a `{`, or the `if` of a chain.
// A set written on the next line leaves it to that item's own
@@ -458,13 +458,13 @@ impl<'a> Parser<'a> {
}
fn parse_solve_before(&mut self) -> PResult<ConstraintItemKind> {
self.bump(); // solve
self.skip(); // solve
let solve = self.parse_solve_operands()?;
if !word_at(self.cur(), "before") {
return self.error("expected `before`");
}
let before_comments = self.take_gap();
self.bump();
self.skip();
let before = self.parse_solve_operands()?;
Ok(ConstraintItemKind::SolveBefore { solve, before_comments, before })
}
@@ -526,7 +526,7 @@ impl<'a> Parser<'a> {
expr: Expr,
before: Vec<Comment>,
) -> PResult<Expr> {
self.bump(); // dist
self.skip(); // dist
let after = self.take_gap();
self.expect_sym("{")?;
let mut weights: Vec<DistItem> = Vec::new();
@@ -539,8 +539,8 @@ impl<'a> Parser<'a> {
let mut op_comments = BinaryComments::default();
if let Some(spelling) = self.dist_weight_op() {
op_comments.before = self.take_gap();
self.bump();
self.bump();
self.skip();
self.skip();
op_comments.after = self.take_gap();
op = Some(spelling.to_string());
weight = Some(self.parse_ternary()?);
+22 -22
View File
@@ -56,7 +56,7 @@ impl<'a> Parser<'a> {
self.take_member_prefix();
self.expect_kw("covergroup")?;
while !self.at_eof() && !self.cur().is_kw("endgroup") {
self.bump();
self.skip();
}
self.expect_closer("endgroup")?;
self.parse_label()?;
@@ -139,7 +139,7 @@ impl<'a> Parser<'a> {
fn parse_coverage_event(&mut self) -> PResult<Option<CoverageEvent>> {
if self.cur().is_kw("with") {
let before_with = self.take_gap();
self.bump();
self.skip();
let after_with = self.take_gap();
self.expect_kw("function")?;
let after_function = self.take_gap();
@@ -147,7 +147,7 @@ impl<'a> Parser<'a> {
return self.error("expected `sample`");
}
let name = Name { text: self.cur().text.clone(), span: self.cur().span };
self.bump();
self.skip();
let before_args = self.take_before_open("(");
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports(false)?.args;
@@ -163,7 +163,7 @@ impl<'a> Parser<'a> {
}
if self.cur().is_sym("@") {
let before = self.take_gap();
self.bump();
self.skip();
let sens = self.parse_sens_list()?;
return Ok(Some(CoverageEvent::Clocking { before, sens }));
}
@@ -206,9 +206,9 @@ impl<'a> Parser<'a> {
&& (word_at(self.nth(2), "coverpoint") || word_at(self.nth(2), "cross"))
{
let name = Name { text: self.cur().text.clone(), span: self.cur().span };
self.bump();
self.skip();
let before = self.take_gap();
self.bump(); // :
self.skip(); // :
let after = self.take_gap();
Some(CoverLabel { name, comments: Box::new(BinaryComments { before, after }) })
} else {
@@ -224,7 +224,7 @@ impl<'a> Parser<'a> {
}
fn parse_coverpoint(&mut self, label: Option<CoverLabel>) -> PResult<CoverpointDecl> {
self.bump(); // coverpoint
self.skip(); // coverpoint
let after_kw = self.take_gap();
let expr = self.parse_expr()?;
let iff = self.parse_cover_iff()?;
@@ -234,7 +234,7 @@ impl<'a> Parser<'a> {
}
fn parse_cross(&mut self, label: Option<CoverLabel>) -> PResult<CrossDecl> {
self.bump(); // cross
self.skip(); // cross
let after_kw = self.take_gap();
let mut items: Vec<ExprItem> = Vec::new();
loop {
@@ -265,7 +265,7 @@ impl<'a> Parser<'a> {
return Ok(None);
}
let before_kw = self.take_gap();
self.bump();
self.skip();
let after_kw = self.take_gap();
self.expect_sym("(")?;
let after_open = self.take_gap();
@@ -356,13 +356,13 @@ impl<'a> Parser<'a> {
let wildcard = word_at(self.cur(), "wildcard") && bin_kind_at(self.nth(1)).is_some();
let mut after_wildcard = Vec::new();
if wildcard {
self.bump();
self.skip();
after_wildcard = self.take_gap();
}
let Some(kind) = bin_kind_at(self.cur()) else {
return self.error("expected `bins`, `ignore_bins` or `illegal_bins`");
};
self.bump();
self.skip();
let before_name = self.take_gap();
let name = self.expect_name()?;
let array = self.parse_bin_array()?;
@@ -392,7 +392,7 @@ impl<'a> Parser<'a> {
return Ok(None);
}
let before = self.take_gap();
self.bump();
self.skip();
let inner_before = self.take_gap();
let size = if self.cur().is_sym("]") { None } else { Some(self.parse_expr()?) };
let inner_after = self.gap_before("]");
@@ -412,12 +412,12 @@ impl<'a> Parser<'a> {
/// `bins b = (1'b1[*5]);` wrong.
fn parse_bin_spec(&mut self, in_cross: bool) -> PResult<BinSpec> {
if self.cur().is_kw("default") {
self.bump();
self.skip();
// `sequence` really is a lexer keyword (a `sequence ... endsequence`
// declaration), so this one is not matched by text.
if self.cur().is_kw("sequence") {
let comments = self.take_gap();
self.bump();
self.skip();
return Ok(BinSpec::DefaultSequence { comments });
}
return Ok(BinSpec::Default);
@@ -446,7 +446,7 @@ impl<'a> Parser<'a> {
break;
}
let before = self.take_gap();
self.bump();
self.skip();
let after = self.take_gap();
arrow = BinaryComments { before, after };
}
@@ -494,7 +494,7 @@ impl<'a> Parser<'a> {
return Ok(None);
}
let before = self.take_gap();
self.bump(); // [
self.skip(); // [
let after_open = self.take_gap();
let op = self.bump().text;
let inner_before = self.take_gap();
@@ -503,7 +503,7 @@ impl<'a> Parser<'a> {
let mut hi = None;
if self.cur().is_sym(":") {
colon.before = self.take_gap();
self.bump();
self.skip();
colon.after = self.take_gap();
hi = Some(self.parse_expr()?);
}
@@ -541,13 +541,13 @@ impl<'a> Parser<'a> {
fn parse_select_primary(&mut self) -> PResult<SelectExpr> {
if self.cur().is_sym("!") {
self.bump();
self.skip();
let comments = self.take_gap();
let expr = self.parse_select_primary()?;
return Ok(SelectExpr::Not { comments, expr: Box::new(expr) });
}
if self.cur().is_sym("(") {
self.bump();
self.skip();
let before = self.take_gap();
let expr = self.parse_select_expr()?;
let after = self.gap_before(")");
@@ -577,7 +577,7 @@ impl<'a> Parser<'a> {
}
fn parse_binsof(&mut self) -> PResult<BinsofSel> {
self.bump(); // binsof
self.skip(); // binsof
let after_kw = self.take_gap();
self.expect_sym("(")?;
let after_open = self.take_gap();
@@ -589,7 +589,7 @@ impl<'a> Parser<'a> {
let mut intersect = None;
if word_at(self.cur(), "intersect") {
before_intersect = self.take_gap();
self.bump();
self.skip();
after_intersect = self.take_gap();
intersect = Some(self.parse_constraint_expr_set()?);
}
@@ -610,7 +610,7 @@ impl<'a> Parser<'a> {
return Ok(None);
}
let before_kw = self.take_gap();
self.bump();
self.skip();
let after_kw = self.take_gap();
self.expect_sym("(")?;
let after_open = self.take_gap();
+27 -2
View File
@@ -63,6 +63,31 @@ impl<'a> Parser<'a> {
t
}
/// Consume the current token without building a copy of it.
///
/// Exactly [`Parser::bump`] for the caller that throws the token away —
/// the same comment plumbing, the same cursor step, the same `self.tokens`
/// left untouched — minus the clone. `bump` copies the token's `text`
/// (a `String`, so an allocation) and its comment buckets for a value most
/// callers drop on the next line; on a 40 267-line generated file that is
/// one allocate-and-free per token consumed (TODO §63.2).
pub(super) fn skip(&mut self) {
let token = &self.tokens[self.pos];
// Cloned rather than moved out, because `bump` moved them out of its
// *copy*: the stream keeps its comments either way, which is what the
// rewind of a speculative parse relies on.
let (mut leading, trailing) = (token.leading.clone(), token.trailing.clone());
if self.pos + 1 < self.tokens.len() {
self.pos += 1;
}
if !leading.is_empty() {
self.pending_leading.append(&mut leading);
}
if let Some(trailing) = trailing {
self.pending_trailing.push(trailing);
}
}
/// Open one level of nesting, refusing to recurse past
/// [`MAX_NESTING_DEPTH`]. Callers that succeed must pair this with
/// [`Parser::leave`] on every path out, including the error paths.
@@ -199,7 +224,7 @@ impl<'a> Parser<'a> {
pub(super) fn eat_sym(&mut self, sym: &str) -> bool {
if self.cur().is_sym(sym) {
self.bump();
self.skip();
true
} else {
false
@@ -208,7 +233,7 @@ impl<'a> Parser<'a> {
pub(super) fn eat_kw(&mut self, kw: &str) -> bool {
if self.cur().is_kw(kw) {
self.bump();
self.skip();
true
} else {
false
+7 -7
View File
@@ -39,7 +39,7 @@ impl<'a> Parser<'a> {
// this function with the `virtual` already taken into
// `DataDecl::qualifiers`, so this only fires for the other positions.)
if self.cur().is_kw("virtual") {
self.bump();
self.skip();
ty.virt =
Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare });
// `virtual spi_if.tb sif` — a modport-qualified virtual interface
@@ -97,12 +97,12 @@ impl<'a> Parser<'a> {
// comment inside the brackets could attach.
let mut comments =
SegmentComments { before_open: self.take_gap(), ..Default::default() };
self.bump();
self.skip();
comments.after_open = self.take_gap();
let kind = if self.cur().is_sym("]") {
// `[]` — a dynamic array.
comments.before_close = std::mem::take(&mut comments.after_open);
self.bump();
self.skip();
dims.push(Dim {
kind: DimKind::Dynamic,
comments: Box::new(comments),
@@ -111,7 +111,7 @@ impl<'a> Parser<'a> {
continue;
} else if self.cur().is_sym("*") && self.nth(1).is_sym("]") {
// `[*]` — a wildcard-keyed associative array.
self.bump();
self.skip();
DimKind::Wildcard
} else {
let a = self.parse_expr()?;
@@ -303,7 +303,7 @@ impl<'a> Parser<'a> {
// `wire /* c */ #5 w;`. Taken only here — when the read does not
// happen the gap belongs to whatever comes next.
let before_hash = self.take_gap();
self.bump();
self.skip();
let after_hash = self.take_gap();
Ok(Some(NetDelay { before_hash, after_hash, expr: self.parse_delay_value()?, after_type }))
}
@@ -392,7 +392,7 @@ impl<'a> Parser<'a> {
let mut eq_comments = BinaryComments::default();
let value = if self.cur().is_sym("=") {
eq_comments.before = self.take_gap();
self.bump();
self.skip();
eq_comments.after = self.take_gap();
Some(self.parse_expr()?)
} else {
@@ -436,7 +436,7 @@ impl<'a> Parser<'a> {
// grammar of their own and are still a clean parse error.
let tagged = word_at(self.cur(), "tagged");
if tagged {
self.bump();
self.skip();
header_comments.after_tagged = self.take_gap();
}
let packed = self.eat_kw("packed");
+2 -2
View File
@@ -347,8 +347,8 @@ impl<'a> Parser<'a> {
let raw = if self.at_spaced_macro_call() {
let start = self.here();
let col = self.cur().col;
self.bump(); // `NAME
self.bump(); // (
self.skip(); // `NAME
self.skip(); // (
self.skip_balanced("(", ")")?;
// Verbatim, space included: the argument text is preprocessor
// input lucisv does not model, and closing the gap would make the
+8 -8
View File
@@ -64,7 +64,7 @@ impl<'a> Parser<'a> {
// Each of the four gaps inside a `? :` can hold comments; kept
// apart so none of them drifts across the `?` or the `:`.
let before_question = self.take_around(mark);
self.bump();
self.skip();
let after_question = self.take_around(mark);
let then = self.parse_expr()?;
let before_colon = self.take_around(mark);
@@ -144,7 +144,7 @@ impl<'a> Parser<'a> {
// The word is an operator like any other, and keeps the
// comments written on either side of it the same way.
let before = self.take_around(mark);
self.bump();
self.skip();
let after = self.take_around(mark);
let comments = Box::new(BinaryComments { before, after });
// `x inside `MACRO` — the macro expands to the `{...}` set,
@@ -324,7 +324,7 @@ impl<'a> Parser<'a> {
let base = Box::new(base);
if self.cur().is_sym(".") || self.cur().is_sym("::") {
let scoped = self.cur().is_sym("::");
self.bump();
self.skip();
comments.after_open = self.take_gap();
let name = self.expect_ident()?;
let comments = Box::new(comments);
@@ -415,7 +415,7 @@ impl<'a> Parser<'a> {
before_open: self.take_before_open("("),
..CallComments::default()
};
self.bump();
self.skip();
let mut args = Vec::new();
if !self.cur().is_sym(")") {
let arg_start = self.here();
@@ -462,14 +462,14 @@ impl<'a> Parser<'a> {
},
);
} else if self.nth(1).is_sym("[") {
self.bump(); // with
self.skip(); // with
let range = self.parse_stream_range(comments)?;
expr = self.expr_at(
start,
ExprKind::StreamWith { base: Box::new(expr), range: Box::new(range) },
);
} else {
self.bump(); // with
self.skip(); // with
comments.after_kw = self.take_before_open("(");
// `( expression )` — an ordinary parenthesized primary,
// which is what IEEE 1800 §7.12 spells here.
@@ -511,9 +511,9 @@ impl<'a> Parser<'a> {
},
);
} else {
self.bump(); // '
self.skip(); // '
comments.after_tick = self.take_gap();
self.bump(); // (
self.skip(); // (
comments.after_open = self.take_gap();
let inner = self.parse_expr()?;
comments.before_close = self.gap_before(")");
+11 -11
View File
@@ -24,7 +24,7 @@ impl<'a> Parser<'a> {
let mut after_hash = Vec::new();
let mut after_delay = Vec::new();
let delay = if self.cur().is_sym("#") {
self.bump();
self.skip();
after_hash = self.take_gap();
let delay = self.parse_delay_value()?;
// The gap between the delay and the first left-hand side is the
@@ -82,7 +82,7 @@ impl<'a> Parser<'a> {
}
let mut comments =
Box::new(DriveStrengthComments { before_open: self.take_gap(), ..Default::default() });
self.bump(); // (
self.skip(); // (
comments.after_open = self.take_gap();
let first = self.bump().text;
// The gap after the first strength ends either at the `,` or at the
@@ -121,7 +121,7 @@ impl<'a> Parser<'a> {
// What is written just inside the `(` belongs to the first value; the
// gap before each `,` and the gap after it belong to the values either
// side of it.
self.bump();
self.skip();
let mut leading = self.take_gap();
let mut out: Vec<DelayValue> = Vec::new();
loop {
@@ -242,7 +242,7 @@ impl<'a> Parser<'a> {
/// `bind <target> [: <inst>, ...] <module> [#(...)] <name> (...);`
pub(super) fn parse_bind(&mut self) -> PResult<BindDirective> {
self.bump(); // `bind`
self.skip(); // `bind`
// The target is a bare string, so a comment written before it has no
// node to attach to: harvest it here, where source order is still
// known, rather than letting it drift onto the instance below.
@@ -250,7 +250,7 @@ impl<'a> Parser<'a> {
let start = self.here();
let mut target = vec![self.parse_path_segment()?];
while self.cur().is_sym(".") {
self.bump();
self.skip();
target.push(self.parse_path_segment()?);
}
let target_span = self.span_from(start);
@@ -278,7 +278,7 @@ impl<'a> Parser<'a> {
let start = self.here();
let mut text = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
self.skip();
let segment = self.expect_ident()?;
Self::push_path_segment(&mut text, &segment);
}
@@ -301,7 +301,7 @@ impl<'a> Parser<'a> {
let module_start = self.here();
let mut module = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
self.skip();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut module, &segment);
}
@@ -312,7 +312,7 @@ impl<'a> Parser<'a> {
let mut after_hash = Vec::new();
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
self.skip();
after_hash = self.take_gap();
self.expect_sym("(")?;
let mut list = Vec::new();
@@ -571,7 +571,7 @@ impl<'a> Parser<'a> {
// `.name(/* unused */)`: the comments were written inside
// these parens and are printed back inside them.
let inside = self.take_around(mark);
self.bump();
self.skip();
Some(self.expr_at(paren_start, ExprKind::Empty(inside)))
} else {
after_open = self.take_gap();
@@ -684,7 +684,7 @@ impl<'a> Parser<'a> {
let start = self.here();
let col = self.cur().col;
while self.pos < end_pos && !self.at_eof() {
self.bump();
self.skip();
}
let raw = self.verbatim_since(start, col);
self.expr_at(start, ExprKind::Verbatim(raw))
@@ -699,7 +699,7 @@ impl<'a> Parser<'a> {
let before_hash = self.take_before_open("#");
let mut after_hash = Vec::new();
let delay = if self.cur().is_sym("#") {
self.bump();
self.skip();
after_hash = self.take_gap();
self.parse_delay_values()?
} else {
+11 -11
View File
@@ -155,7 +155,7 @@ impl<'a> Parser<'a> {
// `TokenKind` match below because punctuation is matched by text
// everywhere in this file. See `ItemKind::Empty`.
if self.cur().is_sym(";") {
self.bump();
self.skip();
return Ok(ItemKind::Empty);
}
let t = self.cur();
@@ -209,7 +209,7 @@ impl<'a> Parser<'a> {
"modport" => self.parse_modport().map(ItemKind::Modport),
"clocking" => self.parse_clocking(false).map(ItemKind::Clocking),
"default" if self.nth(1).is_kw("clocking") => {
self.bump();
self.skip();
self.parse_clocking(true).map(ItemKind::Clocking)
}
"default" if self.nth(1).is_kw("disable") => self.parse_default_disable_item(),
@@ -243,7 +243,7 @@ impl<'a> Parser<'a> {
Ok(ItemKind::PortDecl(d))
}
"genvar" => {
self.bump();
self.skip();
let mut names = vec![self.expect_name()?];
while self.eat_sym(",") {
names.push(self.expect_name()?);
@@ -258,15 +258,15 @@ impl<'a> Parser<'a> {
Ok(ItemKind::Always { kw, stmt })
}
"initial" => {
self.bump();
self.skip();
Ok(ItemKind::Initial(self.parse_stmt()?))
}
"final" => {
self.bump();
self.skip();
Ok(ItemKind::Final(self.parse_stmt()?))
}
"generate" => {
self.bump();
self.skip();
let mut items = Vec::new();
while !self.at_body_end("endgenerate") {
items.push(self.item_or_recover()?);
@@ -339,7 +339,7 @@ impl<'a> Parser<'a> {
}
}
"defparam" => {
self.bump();
self.skip();
let mut pairs = Vec::new();
loop {
let lhs = self.parse_expr()?;
@@ -492,7 +492,7 @@ impl<'a> Parser<'a> {
loop {
let star = self.cur().span;
let pkg = if allow_star_pkg && self.cur().is_sym("*") {
self.bump();
self.skip();
Name { text: "*".to_string(), span: star }
} else {
self.expect_name()?
@@ -578,7 +578,7 @@ impl<'a> Parser<'a> {
}
let span = self.cur().span;
let name = Name { text: self.bump().text, span };
self.bump();
self.skip();
Some(name)
}
@@ -603,7 +603,7 @@ impl<'a> Parser<'a> {
let then = self.parse_gen_block()?;
let els = if self.cur().is_kw("else") {
let meta = self.take_meta();
self.bump();
self.skip();
if self.cur().is_kw("if") {
Some(Box::new(GenElse::If(meta, Box::new(self.parse_gen_if()?))))
} else {
@@ -688,7 +688,7 @@ impl<'a> Parser<'a> {
// The gap between whatever came before and the `begin` belongs to
// the block — nothing else was written where it could attach.
let before_kw = self.take_gap();
self.bump();
self.skip();
let before_colon = self.gap_before(":");
let mut after_colon = Vec::new();
let label_name = if self.eat_sym(":") {
+18 -18
View File
@@ -22,7 +22,7 @@ impl<'a> Parser<'a> {
let kw = self.cur().text.clone();
match kw.as_str() {
"begin" => {
self.bump();
self.skip();
let (label_comments, label_name) = self.parse_label_with()?;
let (label, label_span) = split_label(label_name);
let mut stmts = Vec::new();
@@ -45,7 +45,7 @@ impl<'a> Parser<'a> {
})
}
"fork" => {
self.bump();
self.skip();
let (label_comments, label_name) = self.parse_label_with()?;
let (label, label_span) = split_label(label_name);
let mut stmts = Vec::new();
@@ -88,7 +88,7 @@ impl<'a> Parser<'a> {
"case" | "casex" | "casez" => self.parse_case_stmt(None),
"for" => self.parse_for_stmt(),
"while" => {
self.bump();
self.skip();
self.expect_sym("(")?;
let cond = self.cond_or_recover()?;
let recovered = cond.is_error();
@@ -96,7 +96,7 @@ impl<'a> Parser<'a> {
Ok(StmtKind::While { cond, body: Box::new(self.body_after_recovery(recovered)?) })
}
"do" => {
self.bump();
self.skip();
let body = Box::new(self.parse_stmt()?);
self.expect_kw("while")?;
let mut comments =
@@ -110,7 +110,7 @@ impl<'a> Parser<'a> {
Ok(StmtKind::DoWhile { body, cond, comments: Box::new(comments) })
}
"repeat" => {
self.bump();
self.skip();
self.expect_sym("(")?;
let count = self.cond_or_recover()?;
let recovered = count.is_error();
@@ -118,11 +118,11 @@ impl<'a> Parser<'a> {
Ok(StmtKind::Repeat { count, body: Box::new(self.body_after_recovery(recovered)?) })
}
"forever" => {
self.bump();
self.skip();
Ok(StmtKind::Forever { body: Box::new(self.parse_stmt()?) })
}
"foreach" => {
self.bump();
self.skip();
let mut comments =
HeaderComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
@@ -141,41 +141,41 @@ impl<'a> Parser<'a> {
})
}
"randcase" => {
self.bump();
self.skip();
let (items, dangling) = self.parse_case_body()?;
Ok(StmtKind::RandCase { items, dangling })
}
"return" => {
self.bump();
self.skip();
let after_kw = self.take_gap();
let expr = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
self.expect_stmt_semi()?;
Ok(StmtKind::Return { after_kw, expr })
}
"break" => {
self.bump();
self.skip();
self.expect_stmt_semi()?;
Ok(StmtKind::Break)
}
"continue" => {
self.bump();
self.skip();
self.expect_stmt_semi()?;
Ok(StmtKind::Continue)
}
"disable" => {
self.bump();
self.skip();
// `disable fork;` kills every process the enclosing `fork`
// started; `fork` is a keyword, not a block name.
if self.cur().is_kw("fork") {
let name_span = self.cur().span;
self.bump();
self.skip();
self.expect_stmt_semi()?;
return Ok(StmtKind::Disable { name: "fork".to_string(), name_span });
}
let start = self.here();
let mut name = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
self.skip();
name.push('.');
name.push_str(&self.expect_ident()?);
}
@@ -184,11 +184,11 @@ impl<'a> Parser<'a> {
Ok(StmtKind::Disable { name, name_span })
}
"wait" => {
self.bump();
self.skip();
// `wait fork;` waits for the enclosing `fork`'s children
// (IEEE 1800 §9.6.1); `fork` is a keyword, not a condition.
if self.cur().is_kw("fork") {
self.bump();
self.skip();
self.expect_stmt_semi()?;
return Ok(StmtKind::WaitFork);
}
@@ -217,7 +217,7 @@ impl<'a> Parser<'a> {
Ok(StmtKind::Assert { kw, cond, then, els })
}
"force" => {
self.bump();
self.skip();
let lhs = self.parse_unary()?;
self.expect_sym("=")?;
let rhs = self.parse_expr()?;
@@ -290,7 +290,7 @@ impl<'a> Parser<'a> {
/// is parsed as usual. The init entries read before the failure are kept
/// — they are what declares the loop variable the body uses.
fn parse_for_stmt(&mut self) -> PResult<StmtKind> {
self.bump();
self.skip();
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
+2 -2
View File
@@ -431,7 +431,7 @@ impl<'a> Parser<'a> {
let mut scope: Vec<ScopeSeg> = Vec::new();
while self.cur().is_sym("::") {
let before_sep = self.take_gap();
self.bump();
self.skip();
let after_sep = self.take_gap();
let next = self.expect_name()?;
scope.push(ScopeSeg { name, before_sep, after_sep });
@@ -474,7 +474,7 @@ impl<'a> Parser<'a> {
let start = self.here();
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
self.skip();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
+5 -5
View File
@@ -327,7 +327,7 @@ impl<'a> Parser<'a> {
return Ok(None);
}
let before_dir = self.take_gap();
self.bump();
self.skip();
let after_dir = self.take_gap();
Ok(Some(ClockingDefault { before_dir, after_dir, skew: self.parse_clocking_skew()? }))
}
@@ -387,7 +387,7 @@ impl<'a> Parser<'a> {
if !self.cur().is_sym("#") {
return Ok(out);
}
self.bump();
self.skip();
out.after_hash = self.take_gap();
self.expect_sym("(")?;
let mark = self.diags_mark();
@@ -438,7 +438,7 @@ impl<'a> Parser<'a> {
return Ok((Box::default(), None));
}
let before = self.take_gap();
self.bump();
self.skip();
let after = self.take_gap();
let value = parse(self)?;
Ok((Box::new(BinaryComments { before, after }), Some(value)))
@@ -507,7 +507,7 @@ impl<'a> Parser<'a> {
if !self.cur().is_sym("(") {
return Ok((PortList::None, Vec::new(), Vec::new()));
}
self.bump();
self.skip();
let mark = self.diags_mark();
// Directives before the first port. Harvested here rather than in the
// loop below because both the ANSI/non-ANSI decision and the
@@ -517,7 +517,7 @@ impl<'a> Parser<'a> {
if self.cur().is_sym(")") {
// `module m (/* c */);` — the comments stay between the parens.
let dangling = self.take_dangling();
self.bump();
self.skip();
return Ok((PortList::Empty, dangling, directives));
}
let ansi = {
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more