Compare commits

...
250 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
release / build-and-publish (push) Successful in 9m37s
ci / corpus (push) Successful in 33s
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
release / build-and-publish (push) Successful in 6m58s
ci / corpus (push) Successful in 33s
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
release / build-and-publish (push) Successful in 6m41s
ci / corpus (push) Successful in 42s
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
lucio b12e0cc2c4 Release 0.52.0 — performance take 5, the review round
ci / checks (push) Successful in 1m17s
release / build-and-publish (push) Successful in 7m2s
ci / corpus (push) Successful in 36s
2026-09-09 00:42:39 -05:00
lucio 01843eb75a Review round closed (§61.6): perf README entry for the five lanes, the review's and the tracker's status lines 2026-09-09 00:41:34 -05:00
lucio 5e02142a8f Review round §61.5 (R3b/R3c): the rename's scope stage split (the parser is two thirds of it, a third spent on files never analysed) and facts reuse under a content-hash tie — a closed file's record is reused only when the handed bytes hash to what the store entry was written for, record and hash from one place, never the workspace index; tail rename 380 → 314 ms (−21 % against the review's baseline), the duplicate-module refusal 2.05 s → 0.7 s, 36 rows and 1 750 warning sentences byte-identical, check/ untouched 2026-09-09 00:41:34 -05:00
lucio 07ef771a35 Review round §61.4 (R4): a fixed-arrival probe showed a publish costs the size of the index (a whole-index merge per burst); a scan now publishes at most once per 512 files with the waiting drain exempt — publication −78 to −88 %, loaded scans −48 to −65 %, median wait 112 → 2 ms warm at the same offered load; an empty navigation answer mid-scan is deferred to the next publish or scan end (unsettled answers 0 everywhere); a cancel naming a deferred request answers it cancelled (lead fix for QA's finding); HEAD_WALK_MAX pinned
ci / checks (push) Successful in 1m17s
ci / corpus (push) Successful in 36s
2026-09-08 22:38:56 -05:00
lucio eb54042032 Review round §61.3 (R2a/R2b): the walk hands on the length it already has (collect_files_with) and a subtree walk carries the ancestor ignore stack down (collect_files_below); a workspace start walks, steps and publishes the open buffer's folders before discovering the rest (state/discover.rs, one scan, every file once, bounded to today's path otherwise); first useful answer 266 → 78 ms cold and 301 → 115 warm, correct in every session, warm settle under 1 s, store byte-identical, RSS down; one stopwatch assertion in a trace test dropped by the lead
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 33s
2026-09-08 20:48:41 -05:00
lucio a1c77c053f Review round §61.2 (R1a/R1b): one lint pass per document revision shared by the diagnostics publish and quick-fix discovery, keyed by value on every input of lint_with (waiver contents included) and cleared by every index mutation's overlay refresh; a --verbose codeaction stage trace first showed the 23 ms is three semantic rules and the first-after-edit is the flush; pinmux menu 22.6 → 1.0 ms, queued definition 22.4 → 0.8, publish and memory unchanged
ci / checks (push) Successful in 1m10s
ci / corpus (push) Successful in 35s
2026-09-08 18:26:44 -05:00
lucio 51cbfd27df Review round §61.1 (R3a): an engine-owned rename preflight refuses from the request buffer alone — a cursor with no symbol went from 2.0 s and 3 975 parses to 0.34 ms and none, sentence and precedence byte-identical; index-answered refusals stay on the slow road (a wrong rename refusal is terminal); the extract preflight was proven redundant and not shipped
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 32s
2026-09-08 16:48:05 -05:00
lucio e13ae4c89b TODO §61: the take-5 review round sequenced into lanes 61.1–61.6 with gates
ci / checks (push) Successful in 1m28s
ci / corpus (push) Successful in 42s
2026-09-08 15:24:03 -05:00
lucio b2bb912bbb docs: independent performance review of 0.51.0 (Codex, 2026-09-08) — paired rerun confirms the take-5 numbers; four follow-up items with gates; evidence preserved 2026-09-08 15:24:03 -05:00
lucio 126a6bcdac TODO §60.5: 0.51.0 verified — perf take 5 closed
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 32s
2026-09-08 04:47:12 -05:00
lucio bc59336d91 Release 0.51.0 — performance take 5
ci / checks (push) Successful in 1m2s
release / build-and-publish (push) Successful in 6m27s
ci / corpus (push) Successful in 33s
2026-09-08 04:37:51 -05:00
lucio b2a5f0a171 Perf take 5 closed (§60.5): perf README entry with the accepted numbers, the plan's and the tracker's status lines
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 32s
2026-09-08 04:36:11 -05:00
lucio 32204eba71 Perf take 5 P4b (§60.4): the startup staged behind the configuration answer (one scan at the answered scope, 2 s bound), the store not rewritten when unchanged and opened at the first step that needs it, the corpus read a file at a time in its own step, open buffers' folders at the head of the work list and a held opening request answered once that head is published; warm start 1.33 → ~1.05 s, warm idle RSS −15 to −20 %, store byte-identical across sessions, first useful answer correct in every session; state.rs split into state/ (pure move) 2026-09-08 04:36:11 -05:00
lucio 243472901d topo: perf5-p4 edges applied (table_sizes, the parsed timing lines, the trace plumbing) and the perf5 module ownership entries
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 34s
2026-09-08 00:07:17 -05:00
lucio 4621214a51 Perf take 5 P4a (§60.4): startup and memory instrumented on the --verbose channel (scan_trace, cache counters, table sizes; scanprofile/scanserve phases) — a session runs an empty scan before configuration that still opens and rewrites the 45 MB store (184 ms of a 1.33 s warm start), warm has no dominant stage and 27 % is store I/O, cold is 59 % parse; P4b ruled
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 35s
2026-09-08 00:05:43 -05:00
lucio 8e65da1ba8 Perf take 5 P3 (§60.3): one parse for the CLI package census — package_exports_in reads the census's own parse, an AST gate spares the nine files in ten that declare no package, the one-file index is built from the parse; the unused-import increment on hw/ip 142 → 5 ms, peak RSS −8.6 %, every output byte-identical
ci / checks (push) Successful in 1m12s
ci / corpus (push) Successful in 36s
2026-09-07 22:48:04 -05:00
lucio 5c9fdb2c62 Perf take 5 P2d (§60.2): handshake 33 closed by an opt-in word-census rung (module_select::hierarchical_users — stronger than the transitive walk, which cannot reach a bind from a file that instantiates nothing); the P2d census proves the 133 indirect files are container files a tail folds through, so no narrowing ships; the rename warnings stage lexes and indexes each file once (list-identical over 13 renames); tail rename 780 → 388 ms, 2.01×
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 34s
2026-09-07 21:53:19 -05:00
lucio e51a2c7f21 Perf take 5 P2a–c (§60.2): rename reuses its analysis, verification untouched — a --verbose stage trace (the tail rename was 238 files, 717 parses, two thirds repeated), one parse+analysis per file inside the scope (FileFacts::analyzed, Scope::build_keeping), the after-index absorbed from the edited files' records with every verifier check unchanged and re-attacked; tail rename 780 → 420 ms, aes rename −25%, resolves −20%, parses K+E
ci / checks (push) Successful in 1m10s
ci / corpus (push) Successful in 45s
2026-09-07 19:37:57 -05:00
lucio dafa4f0500 Perf take 5 P1c (§60.1): offer predicates instead of throwaway edits — port_offers/organize_offer answer the lightbulb from the plan-time checks with the same titles and counts, the click still recomputes and verifies; aes_reg_top offer 21.8 → 5.5 ms, aes 7.8 → 1.7, organize-imports 15.4 → 4.9; the organize-imports offer contract documented as optimistic like every other lazy offer (lead ruling on QA's finding)
ci / checks (push) Successful in 1m6s
ci / corpus (push) Successful in 41s
2026-09-07 17:35:24 -05:00
lucio 6c1f863417 Perf take 5 P1 (§60.1): code-action discovery stops repeating work — lint/config/fence gated by the requested kinds (only: [] answers at once), the fence answer asked only when a fix exists and memoized per Document, the four offer selectors read the document's own parse (additive _in APIs, text forms as wrappers), a per-thread parse counter proves a repeated offer parses nothing; pinmux no-offer comment 310 → 24 ms, queued definition likewise
ci / checks (push) Successful in 1m24s
ci / corpus (push) Successful in 36s
2026-09-07 16:05:26 -05:00
lucio 501b36d8b8 Perf take 5 P0 (§60.0): the harness tells the truth — schema 2 (units, status, result counts, client shape, fingerprints), command-bearing offers measured by a real execute phase with applyEdit capture, offerkinds/offerqueue phases, cold sweep tries actually cold; reference re-taken on the unchanged 0.50.0 binary
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 34s
2026-09-07 14:35:12 -05:00
lucio 9c75b7a4e5 TODO §60: performance take 5 sequenced into lanes P0–P4 with gates
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 37s
2026-09-07 13:44:00 -05:00
lucio be084f07b5 docs: performance take 5 — the owner's analysis, implementation plan, tracker and baseline evidence at 0.50.0 (bbdbfe9) 2026-09-07 13:44:00 -05:00
lucio bbdbfe9045 TODO: loop-2 coda — §58 and §59 shipped as 0.50.0
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 33s
2026-09-07 04:33:39 -05:00
lucio 3bd55acb98 Release 0.50.0 — the format cache key, performance take 4
ci / checks (push) Successful in 1m4s
release / build-and-publish (push) Successful in 6m26s
ci / corpus (push) Successful in 33s
2026-09-07 04:32:49 -05:00
lucio c37b13de31 Format cache: uvm-utils-indent joins the key (§59, topo 34) — Entry carries the option, the store line has it as a fourth field, a 0.49.0 store is rebuilt not trusted; CLI regression both toggle directions
ci / checks (push) Successful in 1m15s
ci / corpus (push) Successful in 34s
2026-09-07 04:31:26 -05:00
lucio d8d1791c1c tools/perf: drop the committed __pycache__, ignore it
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 34s
2026-09-07 04:01:41 -05:00
lucio d10e57aa6e Perf take 4 (§58): 0.49.0 vs 0.43.0 on opentitan — §46's didOpen fix 14× in the release build, the eager codeAction path 2×, the tail rename at 11×, the index +14%; harness committed in tools/perf/; findings filed for loop 3
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 33s
2026-09-07 04:01:29 -05:00
lucio 414d501847 §57 closed: 0.49.0 verified (8 assets, vsix contents checked), memory rewritten; §58 perf take 4 and §59 cache-key fix filed
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 33s
2026-09-07 02:43:13 -05:00
lucio 4123905aa1 docs: repository analysis, topo and site refreshed at 0.49.0 by the owner's audit; handshake 34 filed (format cache omits uvm-utils-indent) 2026-09-07 02:43:13 -05:00
lucioandClaude Fable 5.1 df4e71411f TODO: §8 backlog closed, §55 deferred to loop 3, §57 items ticked; 0.49.0 ruled the closing release
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:16:25 -05:00
lucioandClaude Fable 5.1 6759f0eea1 Loop 2 closed: TODO order section closed with the release map and the open items for loop 3; CLAUDE.md re-measured at 0.49.0; §57 tree and docs items ticked
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:15:28 -05:00
lucioandClaude Fable 5.1 4c2dae323e Release 0.49.0 — inline module, the last coverage gaps
ci / checks (push) Successful in 1m6s
release / build-and-publish (push) Successful in 6m20s
ci / corpus (push) Successful in 35s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:13:53 -05:00
lucioandClaude Fable 5.1 a69a1cb528 Coverage gaps L3, L6, L10: six language shapes, randsequence as real nodes, an opt-in uvm_field_* indent
TODO §54 (docs/features/coverage-gaps-l); closes docs/coverage_gaps.md
L3, L6 and L10. The first dev stalled under machine load; a second
finished from the tree.

54.1 `->>` with optional delay or event control (`StmtKind::EventTrigger`),
stream `with [range]` (`ExprKind::StreamWith`), the LRM's other
`casting_type`s, drive strength on a net declaration (`DataDecl::strength`,
whose comment slots also fix a pre-existing refusal on an `assign` with
a comment before its strength), `let` at statement position
(`StmtKind::Let`), and `#(min:typ:max)` clocking skews — `ClockingSkew`
as the LRM's two alternatives, `edge [delay]` | `delay` (review rework of
QA's HIGH). Comment slots added to `let`, stream concatenations and the
clocking grammar; the RTL gap fuzzer at 505 gaps, zero failing.
54.2 `randsequence` (it was a parse error; the keyword is new):
`RandSequence` → `Production` → `Alternative` → `ProdItem` (ref, block,
if, repeat, case, rand join), code blocks by the statement grammar; one
production per line, alternatives aligned; the LRM's examples as cases.
54.3 `[format] uvm-utils-indent` / `lucisv.format.uvmUtilsIndent`, default
off, tracking nested `_begin`/`_end` pairs; 21 corpus files change with
it on, all idempotent. A short comment-free enum body already one-lines,
so no key was built — the behaviour is pinned. `[format]` table tests
added (review rework). `->>`'s event control is bound through the shared
`bind_timing` (review rework of QA's second HIGH).

0 of 820 corpus files differ from 0.48.x with the key off; the opentitan
sweep is identical; no corpus or opentitan file writes any of the new
shapes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:12:49 -05:00
lucioandClaude Fable 5.1 e1679bebc5 Inline module: a module's body copied into its instantiator with ports and parameters substituted, and a verifier that knows a copy
ci / checks (push) Successful in 1m29s
ci / corpus (push) Successful in 37s
TODO §53.2 (docs/features/extract-inline-module), the fifth §8
refactoring; extract → inline round-trips byte-equal after formatting.

`vlog_refactor::inline_module` (inline/{mod,site,source,render}.rs):
every symbol bound in `S`'s module scope is classified once — a port
becomes the name or literal connected to it, anything else `S` declares
at module scope is prefixed `u_S_` only when `M`'s file already spells
one of them; parameters become `localparam`s with the override or
default; the body is copied verbatim except name spans, with `.name`
shorthand connections expanded when their signal is renamed. Refusals:
`.*`, positional lists, expression connections, an unconnected port, an
output into a literal, any hierarchical reference to `u_S` in the handed
files, `S` unknown/twice/in `M`'s own file, interface/`inout`/unpacked/
non-ANSI ports, `initial`/`final`, macros, directives, any `generate`, a
differing `timescale`, collisions prefixing cannot resolve. Server:
`refactor.inline` lazy action, `lucisv.inlineModule`.

Verifier: `Moving` gains `Origin::{Moved, Copied}` — a copied region's
pieces join the transit under rule 0, "a copied file appears in no
edit"; eight attack pairs through the production entry; QA's neutering
map shows every rule load-bearing. QA's MEDIUMs filed: topo §2.9-32
(same blind spot) and §2.9-33 (`module_sources` lacks a transitive-
instantiators rung).

Trials: corpus 5 inlined / 9 refused, opentitan 5 / 56, the lint census
0 → 0 on every pair. 0 of 854 corpus files differ from 0.48.x.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 21:04:05 -05:00
lucioandClaude Fable 5.1 94b0711efb Release 0.48.2 — the 0.48.0 packages rebuilt from the commit that has the hierarchy view
ci / checks (push) Successful in 1m3s
release / build-and-publish (push) Successful in 6m51s
ci / corpus (push) Successful in 34s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:14:15 -05:00
lucioandClaude Fable 5.1 449b874798 DUT-centred hierarchy view: star a module as DUT, its children and its parents in their own sections, everything else re-rooted
ci / checks (push) Successful in 1m7s
release / build-and-publish (push) Successful in 6m20s
ci / corpus (push) Successful in 31s
TODO §56 (docs/features/dut-hierarchy), the owner's request of 2026-09-06.

Client-only, over the flat `lucisv/moduleHierarchy` snapshot the server
already sends. `hierarchySections.js`: per starred DUT, in starred
order, the DUT's forward subtree (the DUT at the top) and an upward tree
from the DUT through every module that instantiates it (labelled `via
<instance>`, cycles cut with one `recursive` row), then one section for
every module in no DUT's subtree or ancestor closure, re-rooted where
its only parents are DUT ancestors (the review ruling — a monitor beside
the DUT under the same bench stays on screen); a module both below one
DUT and above another appears in both DUT sections; a starred name the
index lacks keeps its sections with a "not in the index" row. Star and
unstar from the webview row menu (the pane is a WebviewView, so the
menu is the renderer's, driven by a `menuTable()` per render), the
`lucisv.hierarchy.{starDut,unstarDut,clearDuts}` commands and title
actions, persistence in `workspaceState` in starred order, and the
`lucisv.hierarchy.duts` setting whose entries show locked. With nothing
starred the pane is byte-identical to before (pinned).

opentitan `hw/ip` (847 modules): `aes` → 3 sections with `tb` in its
parents and 5 modules under `aes_tb` re-rooted into others; `aes` +
`hmac` → 5 sections; every module reachable in both configurations; QA's
200-trial fuzz found no overlap and no gap. `extract_test.js` added to
`.vscodeignore`.

(Committed after the 0.48.0 version commit: the release chain broke at a
test-output grep and cut the tag one commit early; the tag is moved here.)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:04:05 -05:00
lucioandClaude Fable 5.1 4d342367b9 Release 0.48.0 — a DUT-centred hierarchy view
ci / checks (push) Successful in 1m5s
release / build-and-publish (push) Successful in 6m54s
ci / corpus (push) Successful in 37s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:03:33 -05:00
lucioandClaude Fable 5.1 a5ca0c9b10 Release 0.47.0 — organize imports, extract module
ci / checks (push) Successful in 59s
release / build-and-publish (push) Successful in 6m9s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 23:04:14 -05:00
lucioandClaude Fable 5.1 acf20f7e62 Extract module: dataflow-inferred ports, a new file where the client can create one, and a verifier ledger that follows the move
TODO §53.1 (docs/features/extract-inline-module), the fourth §8
refactoring; §53.2 inline module is unstarted and runs as its own lane.

`vlog_refactor::extract` (region, flow, boundary, render): a selection
of whole module items becomes a new module — a name declared outside
and read inside is an `input`, written inside an `output` (assign and
procedural LHS, for init/step, ++/--, force/release/deassign, `-> ev`,
an initialiser, an output/inout connection through the index), written
on both sides refused; parameters passed through `#(.P(P))`, used
imports copied, the port's type taken from the declaration's own text;
the selection replaced by an instantiation rendered from the new
module's text. Forty-three refusal sentences. `RefactorEdit::created`;
the server emits `CreateFile` document changes when the client reads
both halves of the capability, else writes the module below its source;
`refactor.extract` action carrying `lucisv.extractModule [uri, range,
name]`, and a name prompt in the VS Code extension through the language
client's middleware.

The verifier's never-dropped ledger follows the move (review rework of
QA's two HIGHs): `verify_move(moving: &[(file, region)])` — a piece
deleted inside the moved region must land exactly once in the file the
move names, a deletion outside the region stays an ordinary deletion,
four equations, twelve attack pairs through the production entry;
`check.rs` split (pure move) into `check/{mod,ledger}.rs`. `interface`
and `program` bodies are refused (one AST node, gated on `kw`). QA's
re-attack: PASS; its MEDIUM (a same-file relocation as two edits) is
filed as topo §2.9-32.

Trials: corpus 5 extracted / 6 refused, opentitan `hw/ip/{aes,uart,
spi_host,hmac}` 5 / 5, the unresolved-name census held for every
accepted extraction. 0 of 820 corpus files differ from 0.46.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 23:04:14 -05:00
lucioandClaude Fable 5.1 e6eaf53c35 Organize imports: unused imports removed, duplicates merged, the run sorted; the unused-import rule; source.organizeImports
ci / checks (push) Successful in 1m2s
ci / corpus (push) Successful in 47s
TODO §52 (docs/features/organize-imports), the third §8 refactoring.

The judgement lives in `vlog_semantic::imports` (one implementation for
the refactoring and the rule): an import is used when a reference in its
scope, or one nested in it, resolves to a member of the package through
it — `resolve::lexical`'s walk stopped at the scope, every import whose
path admits the name and whose package exports it (binder tables
same-file, `members_of_chain` with re-exports otherwise) marked used, a
deliberate superset; a qualified `p::y` and an import's own package name
never count; an `export p::x` / `export p::*` / `export *::*` in the
scope marks the import it re-exports through as used (IEEE 1800 §26.6 —
the review rework of QA's HIGH, pinned four ways). Refuse to judge: an
unknown or twice-declared package, a macro call or conditional directive
anywhere in the scope, a class with an out-of-file base, a parse
diagnostic, two imports on one line. `vlog_refactor::organize_imports`
deletes the unused lines, merges exact duplicates, sorts the run at the
scope's top (package, item, `*` first), keeps every comment; the
verifier's resolution check refuses a removal a reference needs (attack
pair). `unused-import` (Style, off; safe fix) through
`MentionOracle::package_exports`, silent without a project. Server:
`lucisv: organize imports (removes N, sorts M)` under
`source.organizeImports`, `lucisv.organizeImports`.

Corpus: 40 scopes with ≥ 2 imports, 1 organized, 32 refused for macros;
the rule finds 2, both substantiated. opentitan: 33 of 33 UVM env
packages refused (`` `include "uvm_macros.svh" ``). 0 of 860 corpus
files differ from 0.46.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 20:00:31 -05:00
lucioandClaude Fable 5.1 ce2f7190ed Release 0.46.0 — expand .* and convert ports to ANSI
release / build-and-publish (push) Successful in 6m17s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 18:03:54 -05:00
lucioandClaude Fable 5.1 aa479cf701 Convert ports to ANSI: a Verilog-2001 header merged with its body declarations, and a verifier that never drops a comment or an attribute
TODO §51 (docs/features/ansi-conversion), the second §8 refactoring.

`vlog_refactor::convert_to_ansi` (ports/ansi.rs, ports/merge.rs): for a
`PortList::NonAnsi` module, each header name gains its direction, net or
variable type, signing and packed dims from the body declarations that
describe it, merged per IEEE 1800 §23.2.2.2 (`output b; reg [7:0] b;`
→ `output reg [7:0] b`), as insertions around the untouched name so no
reference anchor moves; the absorbed declarations are deleted with their
comments carried onto the ports. Twenty-three refusals, each a sentence
(port expressions, disagreeing ranges, initialisers, directives, a
comment that would have to move into a one-line list, an attributed
declaration). Code action `lucisv: convert ports to ANSI (N ports)` and
command `lucisv.convertToAnsi`.

Review rework (QA's two HIGHs, invariant 4): the verifier's comment rule
is now `never_dropped` over comments and attribute instances alike —
`has ≥ had`, `wrote ≤ gone` unless the text is the one generated
placeholder, `has == had − gone + wrote` — with masked-corruption attack
tests, re-attacked by QA (30-plus pairs, a neutering pass).

Neither the corpus nor opentitan holds a non-ANSI module; acceptance is
by round trip (ANSI → 2001 → ANSI, same ports/types in order) over five
corpus modules and 290 of 291 opentitan candidates (the one failure is
kmac_reduced_tb.sv's pre-existing trailing-comma parse error). 0 of 854
corpus files differ from 0.45.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 18:03:54 -05:00
lucioandClaude Fable 5.1 d9ed2c447a Expand .*: a wildcard connection written out as the named connections it stands for
TODO §50 (docs/features/expand-wildcard), the first §8 refactoring.

`vlog_refactor::expand_wildcard` (ports/expand.rs): at the cursor's
instantiation, every port not explicitly connected becomes `.p(p)` when a
same-named net, variable or port is declared in the instance's scope
(generate block → parents → module; IEEE 1800 §23.3.2.4 read strictly —
a parameter, genvar, type, instance or tf argument does not bind) and
`.p()` plus a warning otherwise, in declaration order, replacing the
`.*` element through the ports engine's splice and verifier. Refusals:
no `.*`, two, a positional list, a `bind` directive, a multi-instance
statement, a parse diagnostic in either file, compiler directives in
either list, an unknown or twice-declared module, and a `.*` that binds
nothing. Server: the lazy code action `lucisv: expand .* (N connections)`
and the command `lucisv.expandWildcard`; a title-rewrite bug in the lazy
offer path (`counted`) fixed on the way. Corpus: 11 of 21 sites expand
(the rest refused honestly); opentitan `hw/`: 9 of 66 (50 are `bind`),
each verified, two surfacing real FPV-wrapper drift. 0 of 854 corpus
files differ. Dev-dependency vlog_refactor → vlog_formatter (tests).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 15:03:11 -05:00
lucioandClaude Fable 5.1 1da0a303cc Release 0.45.0 — type spans, package re-exports, hierarchical tails
ci / checks (push) Successful in 1m14s
release / build-and-publish (push) Successful in 6m25s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 13:35:57 -05:00
lucioandClaude Fable 5.1 f476c31483 Cross-file instance-member tail: a module's hierarchical surface, read only behind an instance head; rename edits the tail
TODO §49 (docs/features/hierarchical-tail). Closes topo §2.9-23 and
comment-slots finding 2. The first dev was cut off by an outage with the
library half complete; a second finished the tests, README and gates.

`Surface { Connection, Hierarchical }` on `Resolution::ExternalCandidate`
and `MemberSite::Unit`, set by `resolve.rs::head_surface` for an instance
head. `workspace/hierarchy.rs`: `surface_of` (the export rule, re-ruled)
and the two surface-taking reads; the index keeps two disjoint tables —
`members` (connection: ports, parameters; byte-identical to before for
every existing reader) and `hier_members` (nets, variables, instances) —
and a hierarchical read consults the connection table first, so a port
has one record. `FACTS_FORMAT` 18 → 19. `assign w = u_x.sig;` in another
file now resolves to `sub`'s `wire sig`; rename edits both files (nested
`u_a.u_b.sig` included); the §2.9-20 warning is retired for a resolved
tail; a generate-scoped net is still refused honestly. Completion after
`u_x.` in an expression lists the hierarchical surface; a connection
list's does not.

Census: single-file numbers unmoved; 12 939 connection + 5 239
hierarchical-only members; 335 corpus references newly resolve, 514 over
opentitan `hw/` (20 sampled by QA, all genuine). 0 of 860 corpus files
differ. Also: §50/§51 planned, §55 (state.rs size) filed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 13:35:57 -05:00
lucioandClaude Fable 5.1 9ef1058059 Package re-exports as real references: bound halves, RX facts, the member walk through re-exports
ci / checks (push) Successful in 1m17s
ci / corpus (push) Successful in 1m52s
TODO §48 (docs/features/package-reexports). Closes topo §2.9-16 and
dpi-export's request (a).

`bind_export_path` records `export pkg::item` as a `Target::Package` use
and a `Target::UnitMember` use, with no scope import (a re-export brings
nothing into the exporting scope, IEEE 1800 §26.6). `FileFacts` gains the
`RX` group (`FACTS_FORMAT` 17 → 18): per package its re-export edges
(package, source, item|*), with `export *::*` expanded into the package's
own imports at record time. `workspace/reexport.rs`: the member lookup
and listing follow re-exports transitively with a visited set, layered
over `own_chain`/`own_members` so the walk cannot recurse into itself;
`Affected::exporters` keeps one-file updates exact and `fingerprint()`
shows the edges. Definition, hover, completion after `pkg::`, references
and rename all read the one edge. Census 103 870 → 103 875 references
(the corpus's two package export lines), 0 unplaced; 0 of 860 corpus
files differ. opentitan: `spi_device_pkg::SramDepth`, reached only
through a re-export, resolves.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 10:41:54 -05:00
lucioandClaude Fable 5.1 4d59e80568 Type-name spans on the AST; vlog_semantic/src/scan.rs retired
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 33s
TODO §47 (docs/features/type-name-spans). Closes topo §2.9-2.

`DataType` carries `name_start` (a `u32` in its existing padding, so
`Expr` stays at its 96-byte pin) and derives `name_span()` and
`segments()` — the `::`/`.` split from the span's own text, with a
leading escaped identifier read to its terminator first. Five parser
construction sites set it; an implicit type gets the empty range at the
position its name would have had. `StmtKind::Disable { name, name_span }`.
The binder walks `ty.segments()` and verifies every segment's range
against the source before recording it (`exact_or_empty`); a segment that
does not read back is recorded with the empty range, never dropped, so
the census's `unplaced` counter is the alarm a join regression would
move (review rework of QA's MEDIUM). `scan.rs` deleted; `bind_data_type`
lost its `window` and ten call sites their window arithmetic.

Census unchanged in every field (860 files, 27 486 symbols, 103 870
references, 1 197 unresolved, 0 unplaced); 0 of 860 corpus files differ;
200/200 opentitan definition/hover/typeDefinition answers identical.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 09:24:19 -05:00
lucioandClaude Fable 5.1 859742ac84 TODO: §48 package re-exports and §49 cross-file instance-member tail planned
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:58:30 -05:00
lucioandClaude Fable 5.1 66f38987ac Release 0.44.0 — opening a file no longer stalls the editor
ci / checks (push) Successful in 1m1s
release / build-and-publish (push) Successful in 6m22s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:15:37 -05:00
lucioandClaude Fable 5.1 8145a67be6 The didOpen delay: undriven-net asks the workspace census last, not once per declaration
TODO §46 (docs/features/didopen-cost). Closes take-3 finding §8.4 (§44b).

Measured first: on opentitan the open of a 42 192-line file cost
1 745 ms, of which the lint pass was 1 654 ms and `undriven-net` alone
1 608 ms — the rule asked `WorkspaceIndex::files_mentioning` (a walk over
all 3 976 indexed files) once per declaration, ahead of the local guards
that silence almost all of them. Six lines reordered so the oracle is
asked last, as `unused-signal` always did: same findings, same order
(pinned by a counting-oracle unit test that fails on a revert, and shown
byte-identical against 0.43.0 over a crafted workspace and four opentitan
IPs). didOpen → next request: 1 742 → 117 ms on the largest file,
51–95 → 5–8 ms on typical IPs, the same on every keystroke flush. No
debounce added; three wire-level pins with a debug-build bound.

Docs: take-3 §8.4 annotated, docs/perf/README.md entry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:15:37 -05:00
lucioandClaude Fable 5.1 f7956060b3 Small items, round 4: the editor's unknown rule name said once, a warning channel for the walk, inline aggregate override arguments, comment slots inside delay lists
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 32s
TODO §45 (docs/features/small-items-4). Closes topo §2.9-17, 29, 30 and
adds the delay-list bar to §2.9-22.

45.1 `settings::rules` records every dropped `lucisv.lint.select`/`ignore`
name as `lucisv.lint.<setting>: unknown rule: <name>`; `apply_settings`
logs what the previous settings value did not already say — once per
(setting, name), re-armed by a changed list.
45.2 `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink: an
unreadable directory, an unreadable `.gitignore` and a dangling source
link are warned about and the walk continues; the CLI prints
`warning: <path>: <message>` on stderr before the report with the exit
code unchanged, the server logs once per scan through `report_scope`.
45.3 `parse_expr_or_type` accepts a `struct`/`union`/`enum` head as a
type argument, so `m #(.T(struct packed { logic a; })) u ();` parses and
`instantiation_plan` emits a one-line `parameter type` aggregate default.
45.4 Comment slots for `#(1:2:3)` and gate delay lists
(`MinTypMaxComments`, `DelayValue`, `ContAssign`/`GateInstantiation`/
`GateInstance` slots); `EXPECTED_RTL_GAPS` 374 → 419 at zero failures.
Review rework (QA's MEDIUM): a line comment after a gate instance's `,`
now ends the line, the next instance one level in.

Byte-identity vs 0.43.0: 0 of 820 corpus files and 0 opentitan outcomes
differ.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 07:12:54 -05:00
lucioandClaude Fable 5.1 f302b471a7 TODO: loop 2 order from the owner's twelve rulings; §45 and §46 planned; manual acceptance checklist
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 30s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 05:50:45 -05:00
lucioandClaude Fable 5.1 7aedfe2554 docs: performance take 3 on opentitan — 0.43.0 vs take 2 vs 0.39.0
ci / checks (push) Successful in 51s
ci / corpus (push) Successful in 28s
TODO §40 (owner request). Every take-2 row re-measured over the wire and
by CLI sweep, three tries each, no instrumentation added. Headlines: the
lazy codeAction is 11.8× on the cursor-move path (200.7 → 24.0 ms at the
128-file fan-out, 39.2 → 5.2 ms on `aes`), the default-scope didOpen is
1 731 → 1 082 ms cold, completion at 0–1 chars 14.8–19.4 → 2.3–3.2 ms;
nothing else moved since 0.39.0. Per-file outcome diff 0.39.0 → 0.43.0
is exactly the three predicted files. Two findings filed as §44
candidates: the eager codeAction path 1.35–1.40× slower than take 2, and
an in-scope didOpen delaying the next request by 21–51 ms.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 03:24:24 -05:00
lucioandClaude Fable 5.1 73799f3d53 Release 0.43.0 — the repository analysis's three findings
ci / checks (push) Successful in 58s
release / build-and-publish (push) Successful in 6m27s
ci / corpus (push) Successful in 31s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 02:43:10 -05:00
lucioandClaude Fable 5.1 ec9ec42276 Walker cycle policy by directory identity, and comment slots around a net delay's #
TODO §43 (docs/features/walk-cycles). Closes topo §2.9-8 and §2.9-27 and
repository-analysis finding 3; §2.9-30 filed.

43.1 `lucisv_core::walk::Walk` keeps a `visited` set keyed on `(dev, ino)`
(the canonical path off unix): each directory is entered once, a symlink
to one already entered is skipped, one not yet entered is followed once,
a dangling directory link is skipped. A dangling link that names a source
file is still handed on, so the front end's "no such file" error survives
(review ruling on QA's finding). Both front ends share the walk unchanged
in signature; a cyclic workspace indexes and a cyclic tree formats, each
file once.

43.2 `NetDelay::{before_hash, after_hash}`: the gaps around `#` have
slots, printed inline; the `#SKIP` in net_delay_position.cases is live
and the RTL gap fuzzer covers the construct (374 gaps, 0 failures).

Byte-identity vs 0.42.0: 0 of 820 corpus files differ. On opentitan the
only per-file change is §41's dedup reporting a same-directory symlink
alias once.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 02:43:10 -05:00
lucioandClaude Fable 5.1 4b2dad87fe One lint-configuration contract for project and editor: the server picks the editor's selection when set, else the project's, and logs rejected project entries once
TODO §42 (docs/features/lint-config-contract). Closes topo §2.9-28 and
repository-analysis finding 2.

`enabled_rules(settings, project, has_oracle)`: rung 2 is
`lucisv.lint.select` when non-empty else `[lint] select`, rung 5 the same
for `ignore` — the CLI's `pick` applied to the editor — so one buffer
linted two ways is linted the same way (asserted equal over the wire for
three configurations). `lint::project`: `ProjectLint` read from the
`Discovery` result `configured` already computes (no extra read per
pass); an unknown rule name in a project list is dropped and said rather
than silently emptying the selection. `ConfigProblems`/`ProblemLog`:
rejected `[lint.<rule>]` options, unknown names and bad `[lint] waivers`
lines are logged once per (config file, entry) in `lucisv check`'s
wording, re-armed when the config's lint content changes; the buffer
keeps linting with the entry dropped.

Docs applied: README, the linter guide, configuration.md, the analysis,
topo (28 struck; 29 filed for the editor-side unknown-name silence), site
rebuilt.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 01:45:48 -05:00
lucioandClaude Fable 5.1 3b08c0753c Same-target atomic writers: exclusive per-operation temps, mode before bytes, CLI dedup by canonical identity
TODO §41 (docs/features/atomic-write-coordination). Closes topo §2.9-26
and repository-analysis finding 1.

`atomic::write_atomic` names its temp `.{name}.{pid}.{n}.lucisv-tmp` with
a per-process counter and opens it create-new (O_EXCL), retrying a used
name up to 32 times; on unix the temp is created 0600 when a target
exists and takes the target's mode through the open handle before the
bytes are written, so a 0600 file never has a readable moment. The CLI's
`dedup` keys on the canonical path when the file exists, so a symlink
alias reaches one worker; the reported path is the first spelling. Two
processes on one target remain last-writer-wins (rename is atomic, the
formatter idempotent), stated in the module doc. The audit's probe is a
test: 0 write errors in 200 calls.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:40:48 -05:00
lucioandClaude Fable 5.1 972bd1cff1 Release 0.42.0 — external waiver files and the two vendor shapes
ci / checks (push) Successful in 1m5s
release / build-and-publish (push) Successful in 6m28s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:03:07 -05:00
lucioandClaude Fable 5.1 8a92e79fc0 External waiver files: Verible's format from lucisv.toml, --waiver-file and the editor, union with inline waivers, honoured by quick fixes
TODO §39 (docs/features/waiver-files). Closes §4's last waiver item.

`vlog_linter::waiver_file`: `waive --rule=<rule> [--line=N|N-M]
[--location=<pattern>]`, `#` comments, BOM tolerated; `--location` is
the `--exclude` matcher (`lucisv_core::walk::is_excluded`, a new
vlog_linter → lucisv_core edge), a regex-looking pattern refused by
name. `lint_with(ctx, rules, external)` applies inline and external
waivers as a union and reports which external directives fired;
`lucisv check` reports the dead ones under `unused-waiver` at the
waiver file's line after the whole run. Discovery: `[lint] waivers`
(relative to the toml), `--waiver-file` (repeatable), `lucisv.lint.waivers`
(first workspace root); bad lines fail the CLI run with file:line and
are dropped and logged once by the server.

Review rework (QA's HIGH): the server's code-action path now lints with
the buffer's `LintRun` — its enabled rules and external waivers — so a
quick fix is never offered, nor applied by fix-on-save, for a waived
finding.

Docs: Waivers sections in README and the linter guide, cli and
configuration rows, topo edge, site rebuilt.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:03:07 -05:00
lucioandClaude Fable 5.1 f6f18de10d docs: repository analysis audit at v0.41.0 — README architecture, topo facts (codec 17, handshakes 26–28), site guides and rebuilt dist
Written by the owner's audit process on 2026-09-04; committed by the lead
unchanged. Findings 1–3 are planned as TODO §41–§43.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 23:37:55 -05:00
lucioandClaude Fable 5.1 d5abf81563 The two §11 parser skips: rival unit headers across an ifdef/else split as one verbatim unit, a net delay accepted after the type
TODO §38 (docs/features/parser-skips). Closes the jtag_if.sv and
SimDTM.sv skips from the §11 sweep.

38.1 `Parser::at_rival_header`: in a module/interface/program body, a
continuing directive at the unit's own entry level followed by the same
keyword and name is a header written twice across the arms, not a
nested unit. The error routes into the existing conditional split
(`at_split_conditional` now fires on a rival as well as an open
bracket; `scan_split_extent` runs to the unit's real closer, counting
nested units of the same kind), so the whole unit is one Verbatim item
in both modes. jtag_if.sv now formats (body verbatim, the standing
directive-split trade).

38.2 `DataDecl::delay: Option<NetDelay { expr, after_type }>`: a net
delay is accepted before or after the type (IEEE 1800 §6.7 puts it
after), never both, and printed where it was written. SimDTM.sv now
formats; its four `#0.1` lines come back byte-identical.

Byte-identity vs 0.41.0: 0 of 820 corpus files differ; over 2 554
opentitan files exactly the two named files change outcome.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 23:06:37 -05:00
lucioandClaude Fable 5.1 97aa2fefd8 Release 0.41.0 — code actions off the fan-out
ci / checks (push) Successful in 58s
release / build-and-publish (push) Successful in 6m13s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 18:15:40 -05:00
lucioandClaude Fable 5.1 9604753b6c Lazy codeAction/resolve for the port refactorings, definitions from the index, the inlayHint zero ruled correct
TODO §37 (docs/features/lazy-code-action). Closes the four §10 lines.

37.1 For a client whose resolveSupport lists "edit", the port actions are
offered over the buffer plus the instantiated module's declaration alone
(`ports::offers`, `offer_sources`), carrying `data {uri, position,
title}` and no edit; `codeAction/resolve` (`ports::resolve`) re-runs the
eager path and returns the matching action, matched on the title minus
its count phrase, erroring when the action is gone or the buffer is on
the large-file path. Clients without resolve support get today's eager
answer. Offer flat at ~55 µs from a 3- to a 128-file fan-out where the
eager path was linear; ~4.5 ms vs ~77 ms over the wire on opentitan's
128-file case.

37.2 The inlayHint zero at the default scope is correct: the hinted
module (`pins_if`) is declared outside what the scope reaches, and
definition/hover answer nothing there either. Pinned, not changed.

37.3 `locate::definition_location`: an index-only Location for a closed
file's file-scope declaration from its recorded `DeclPositions`; nav and
workspace symbols routed through it (0.4 µs vs 28 µs). Open buffers keep
the file-read path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 18:15:40 -05:00
lucioandClaude Fable 5.1 797ef86d47 Release 0.40.0 — two parser residues and atomic writes
release / build-and-publish (push) Successful in 6m11s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 17:08:53 -05:00
lucioandClaude Fable 5.1 a30dda167a Small items, round 3: a bare begin block recovered as a generate block, the half-typed #( override lookahead, atomic in-place writes
TODO §36 (docs/features/small-items-3). Closes topo §2.9-24 and §2.9-25
and the §1 atomic-writes item.

36.1 `ItemKind::GenBlock(Box<GenBlock>)`: in tolerant mode a `begin … end`
at module scope or straight inside a generate region is parsed as an
unnamed generate block with a diagnostic at the keyword, so the items
inside and after it survive; strict mode is untouched. Consumers walk
its items; `module-begin-block`, `v2001-generate-begin` and
`mismatched-labels` read the node. The formatter's `gen_block` is split
by a pure extraction into `begin_block`. One server test that parsed a
3 000-deep begin nest on libtest's thread now runs on PARSE_STACK_SIZE.

36.2 `Parser::value_runs_into_next_instance`, a tolerant-mode lookahead
in `parse_connection`: an unclosed `.NAME(` whose value would swallow
the next instance as a call fails the element instead; `recover_element`
takes the bracket the element stopped on before skipping so the skip
stays at the list's level. The balanced-parens spelling stays greedy.

36.3 `lucisv_core::atomic::write_atomic`: sibling temp file + rename,
permissions preserved, symlink target replaced, read-only target
refused as `fs::write` refused it; used by format, `check --fix` and
the cache.

Also: TODO housekeeping (QA lines of §27–§35 ticked as recorded in
their QA logs; the §27 P6 line and the sva-bodies README checkbox
annotated as delivered by §29), topo §2.9-24/25 struck.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 17:08:53 -05:00
lucioandClaude Fable 5 0757503fd1 Release 0.39.0 — the rest of Verible's rules (73 in all)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 30s
release / build-and-publish (push) Successful in 6m18s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 05:03:37 -05:00
lucio 6a0af26fdf Merge branch 'lint-3' 2026-09-04 04:56:52 -05:00
lucioandClaude Fable 5 8adb6c8ac1 Linter expansion, wave 3: the remaining nineteen Verible rules, forbidden-macro, void-cast's forbidden calls, and the e2e options case
TODO section 35 (54 -> 73 rules: every rule in Verible's published
list but forbid-implicit-declarations).
module-begin-block, legacy-generate-region, legacy-genvar-declaration,
v2001-generate-begin, explicit-function-lifetime,
explicit-task-lifetime (both exempt out-of-body definitions after a
census showed 948 of 960 findings were exactly that shape),
positive-meaning-parameter-name, suggest-parentheses (safe fix,
truth-tabled), unpacked-dimensions-range-ordering, uvm-macro-semicolon,
create-object-name-match, numeric-format-string-style,
macro-string-concatenation, disable-statement, forbidden-macro,
endif-comment (safe fix), forbid-line-continuations, dff-name-style,
proper-parameter-declaration. Verible's forbidden-symbol is the
source-file name of invalid-system-task-function (read in its
rule .cc), so it is that rule's symbols option, nothing fires twice;
void-cast gains forbidden_calls. Shared readers: walk_items_scoped,
exprs.rs, preproc.rs. A checked-in e2e case drives lucisv.lint.options
over the wire. Two rules fire on an error leaf because the parser
refuses a module-scope begin/end and a bare generate begin - filed as
docs/topo.md 2.9-25.
3 695 tests / 48 binaries; corpus 814/820 byte-identical to 0.38.0;
opentitan default-set census 1 053 -> 1 169, the arithmetic balancing
to the six default-on additions; timing unchanged.

docs/features/linter-expansion-3/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:55:10 -05:00
lucioandClaude Fable 5 fbee290a0a docs: topo — linter-expansion-1/2/3 rows; §2.9-25 filed (module-scope begin/end and bare generate begin refused rather than recovered)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:31:36 -05:00
lucioandClaude Fable 5 b1b3cad09b TODO §35 planned: linter expansion wave 3 — the remaining twenty Verible rules, forbidden-* lists, the e2e options case
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:46:55 -05:00
lucioandClaude Fable 5 a896e0dff0 Release 0.38.0 — lint rule options and the Style family
ci / checks (push) Successful in 1m5s
release / build-and-publish (push) Successful in 11m24s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:46:03 -05:00
lucioandClaude Fable 5 0cb398bcd9 merge follow-up: §34's port walkers read ANSI port lists through ListElem::ok (§32's error elements)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:39:00 -05:00
lucio 17697b9d77 Merge branch 'lint-2' 2026-09-04 03:36:59 -05:00
lucioandClaude Fable 5 5e5813a2a9 Linter expansion, wave 2: per-rule options end to end, options on the naming rules, and eighteen Style rules
TODO section 34 (36 -> 54 rules).
Options: OptionSpec/OptionKind/OptionValue/RuleOptions in vlog_linter
with one validator behind both front ends - [lint.<rule>] tables in
lucisv.toml (accepted now; stored raw by lucisv_core::config, resolved
per file by the CLI with <config>:<line> on the first bad entry) and
the editor's lucisv.lint.options object (bad entries logged and
dropped) - precedence editor > toml > default key by key, --rules-doc
listing every option. A small anchored regex engine of our own: a
Thompson-NFA simulation, linear in pattern x name by construction
(QA's first cut found the backtracking matcher exponential on (a*)*b),
unknown escapes refused by name through both doors, a 71-row table
verified against CPython. The four naming rules take Verible's option
spellings with defaults that keep today's verdicts byte-identical.
Eighteen Style rules, one file each with true positives and near-
misses: line-length (the formatter's width), posix-eof (safe fix),
forbid-consecutive-null-statements (safe fix), generate-label and
generate-label-prefix, package-filename, one-module-per-file (off),
signal/interface/macro/constraint/parameter-type-name-style,
port-name-suffix (off), banned-declared-name-patterns (off),
typedef-enums, typedef-structs-unions (allow_anonymous_nested defaults
true here - opentitan's 3 159 findings were all generated register
packages, and its own config disables the rule), always-comb (unsafe
fix), explicit-begin (off, Verible's eleven enables). Four rules ask
parsed_cleanly() first after a census showed error-recovered UVM files
rebound as generate blocks. package.json regenerated (drift test).
3 549 tests / 48 binaries; corpus 814/820 byte-identical; naming-rule
finding lists identical to 0.36.0; opentitan check timing unchanged.

docs/features/linter-expansion-2/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:36:59 -05:00
lucioandClaude Fable 5 bafc1b425b docs: header-recovery QA follow-up — the fuzz sweep's time-based guard kill isolated; no hang (max single parse 38 ms over the whole file)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:25:52 -05:00
lucioandClaude Fable 5 8c61570a04 tools/guard.sh: keep the command's stdin (a backgrounded job got /dev/null, silently emptying stdin-fed lucisv runs)
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 31s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:09:29 -05:00
lucioandClaude Fable 5 7c4bdbcfea Release 0.37.0 — error recovery inside headers and lists
ci / checks (push) Successful in 1m8s
release / build-and-publish (push) Successful in 9m43s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:08:47 -05:00
lucioandClaude Fable 5 e902af37c5 docs: topo — header-recovery row, §2.9-24 filed (half-typed #( override that reads as a call)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:08:47 -05:00
lucio 4ba6eafa2d Merge branch 'wip-header-recovery'
# Conflicts:
#	crates/vlog_linter/src/visit.rs
2026-09-04 03:01:49 -05:00
lucioandClaude Fable 5 747ae02b0e Error recovery inside headers and lists: error elements, a list-local bracket-seeded sync that cannot stall, headers keep their node
TODO section 32 (coverage_gaps M10).
A typo inside a port list, parameter list, tf-port list, connection
list or a for/if/while/case header no longer destroys the enclosing
module or function. The four list element types and ExprKind gain an
Error(RawText) element; element_or_recover records the diagnostic and
skips to a list-local sync set (',' ')' ';' or a line change) with the
bracket counter seeded from the list's own opener, and list_ends ends
any list whose iteration left the cursor unmoved - the structural
guarantee that closes the non-advancing loop which exhausted memory on
the first cut. Headers are infallible in tolerant mode: the node keeps
its name, the typed elements and its body, so the body binds in the
right scope and there is no orphaned closer; recovery declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs and strict parity holds (550 fixtures and all 814 strict-parsing
corpus files, Debug-equal). Pins per shape with exact counts; server
pins: document symbols and scoped completion survive a broken header,
one diagnostic, the three validity probes keep their verdicts.
Census over the corpus truncated at each midpoint: error nodes 622 ->
555, diagnostics 1 702 -> 1 826 (surviving modules now report their
missing endmodule). parse_tolerant timing within noise. 3 259 tests on
this branch (0.35.0 + 15 pins); corpus 814/820 byte-identical.

docs/features/header-recovery/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 02:58:24 -05:00
lucioandClaude Fable 5 ffbb29ddbb Release 0.36.1 — 0.36.0 with its release notes (that tag never published: no CHANGELOG section)
ci / checks (push) Successful in 1m8s
release / build-and-publish (push) Successful in 11m34s
ci / corpus (push) Successful in 31s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 02:42:32 -05:00
lucioandClaude Fable 5 f1d44a2a0c WIP checkpoint, §32 paused 2026-09-03 — runaway root cause fixed (list_ends on an unmoved cursor), strict parity restored; 32.1–32.5 done, 32.6 half, 32.7 + gates not run
Root cause of the 100 GB crash: a non-ANSI port loop took its trailing
comma from the element, an error element never got that far, the next
iteration failed on the same comma, consumed nothing and pushed another
empty error element - an allocating spin. Fix is structural: list_ends
ends the list whenever the cursor has not moved since the iteration
began; the two loops that read their own separator also eat it after an
error element. Truncate-anywhere + delete-any-character pass under
tools/guard.sh -m 4. Strict parity: element_or_recover declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs. cargo test -p vlog_parser 365 + 26 + 31 / 0 failed; workspace
suite NOT re-run since the last fixes. Not done: completion pin + the
three validity probes (32.6), measurements (32.7), README amendments,
coverage_gaps M10, TODO ticks, every gate. Handshake: three
vlog_linter arms (visit.rs walk_param_ports, signals.rs connection
loops) live in the earlier commit 6a15594.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:28:33 -07:00
lucioandClaude Fable 5 10b63e665d docs: linter-expansion-1 review — opentitan lint timing re-measured at merge (no difference vs 0.35.0)
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 27s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:01:24 -07:00
lucioandClaude Fable 5 a648561f63 TODO §34 planned in detail: per-rule lint options end to end, options on the naming rules, the first eighteen Style rules; the rest deferred to §35
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:00:45 -07:00
lucioandClaude Fable 5 1c20549cfa Release 0.36.0 — lint severities, per-rule editor toggles, nineteen new rules
ci / checks (push) Successful in 53s
release / build-and-publish (push) Failing after 11m8s
ci / corpus (push) Successful in 28s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:57:22 -07:00
lucio 97f7296b8f Merge branch 'lint-1' 2026-09-03 17:49:03 -07:00
lucioandClaude Fable 5 cebeff45b4 Linter expansion, wave 1: severities end to end, per-rule editor toggles generated from the registry, and nineteen Error/Warning-class rules
TODO section 33. Every rule states a Severity (error: would likely fail
to compile or elaborate, or silently mis-synthesize; warning: a probable
bug; style), printed in lucisv check text and JSON, mapped to
ERROR/WARNING/INFORMATION in the editor, grouped in --rules-doc, and
accepted by --select/--ignore and [lint] as a class word. VS Code gains
lucisv.lint.severity.{error,warning,style} and one tri-state
lucisv.lint.rules.<rule> per rule (default/on/off - a client sends
every key, so a boolean cannot say unset), generated by
vlog_linter::vscode with a drift test, and lint::enabled_rules is the
one documented ladder: defaults -> select -> class switches -> per-rule
-> ignore. Nineteen new rules (17 -> 36), one file each with true
positives and near-misses: Error - mismatched-labels,
duplicate-declaration (Semantics::duplicates(), additive),
undeclared-identifier (with a project; silent for macro text, included
fragments, hierarchical tails, any name another file mentions),
unknown-port, unknown-parameter; Warning - forbid-defparam,
invalid-system-task-function, truncated-numeric-literal,
undersized-binary-literal (safe fix), suspicious-semicolon,
packed-dimensions-range-ordering, module-port, module-parameter,
explicit-function-task-parameter-type, plusarg-assignment,
instance-shadowing, forbid-negative-array-dim, void-cast,
incomplete-assignment. Every false-positive class found on opentitan
closed with a named test; 3 383 tests / 48 binaries; corpus 814/820
and byte-identical (formatter untouched); vsix smoke OK.

docs/features/linter-expansion-1/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:49:03 -07:00
lucioandClaude Fable 5 6a15594ae8 WIP §32 header recovery — DO NOT MERGE: half-finished; a fuzz test loops without advancing and exhausts memory (crashed the machine 2026-09-03)
Checkpoint of the interrupted dev work (rate limit) so master stays
clean. Known state: a_half_typed_instantiation_is_one_error_node
(expected to invert) and tolerant_parse_equals_strict_parse_on_valid_
sources FAIL; the error_recovery test binary exceeds 6 GB under
tools/guard.sh (a non-advancing recovery loop under the delete-any-
character / truncate fuzzers). Resume in a worktree of this branch,
under tools/guard.sh, fixing the advance guarantee first.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:48:28 -07:00
lucioandClaude Fable 5 4d70de1976 tools/guard.sh: kill a command's process tree past a memory or time cap; CLAUDE.md requires it for every suite, fuzzer and sweep
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 27s
A background test run consumed 100 GB and crashed the machine on
2026-09-03 (the process did not survive; the likely source was the
half-finished tolerant-parser recovery under the truncate-anywhere
fuzzers). macOS enforces no memory cap, so this poller is the cap:
8 GB / 30 min by default, TERM then KILL over the whole tree, exit 137
with the reason. Proved on a deliberate runaway allocator.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:47:41 -07:00
lucioandClaude Fable 5 63bbc23e37 Release 0.35.0 — format fences at statement level and inside class bodies
ci / checks (push) Successful in 54s
release / build-and-publish (push) Successful in 5m16s
ci / corpus (push) Successful in 26s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 03:46:24 -07:00
lucioandClaude Fable 5 a0ae5e5fa8 Format fences at statement level and inside class bodies
TODO section 31 (coverage_gaps M9, docs/topo.md 2.9-3).
fence::collect enters class bodies, functions, tasks and always/
initial/final blocks, and statement lists - begin/end, fork/join and
every compound body - through scan_stmt_scope/scan_nested_stmt on the
one scan_units both scope kinds share; stmt_docs/stmt_seq obey the two
swallowed-unit rules item_docs/item_seq had; fence regions merge into
range.rs's plan, which was load-bearing (a fenced statement has no
verbatim run behind it; proved by disabling it). A region opens only at
a line start (opens_line) - the rule the format-fences README has
stated since round 1 - so a fence after code on the same line is an
ordinary comment everywhere, which narrows one accidental item-level
shape (module m; // lucisv: off) and is ruled a drift fix. Deferred
with reasons: port lists, case-item label lists, same-line fences, a
property's locals. verify.rs, lucisv/src/lint.rs and
lucisv_server/src/lint.rs untouched.
Proof: 3 244 tests / 48 binaries, fences.cases 25 -> 38 with the
statement-level entry inverted, corpus 814/820 and 860 files byte-
identical to 0.34.0, opentitan: 4 of its 9 fenced files now keep their
fenced bytes and are fixed points, --check counts identical; 3 348
fence-injection trials with no new refusals.

docs/features/statement-fences/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 03:40:12 -07:00
lucioandClaude Fable 5 965c4ee25a TODO §33/§34 planned: linter expansion — severities, per-rule VS Code toggles, Error/Warning-class rules (wave 1); the Style class and per-rule options (wave 2)
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:57:31 -07:00
lucioandClaude Fable 5 999edd0203 Release 0.34.0 — rename macro-argument warnings, modport prototypes, unnamed DPI formals, --rules-doc
ci / checks (push) Successful in 1m3s
release / build-and-publish (push) Successful in 5m53s
ci / corpus (push) Successful in 28s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:48:12 -07:00
lucioandClaude Fable 5 1c6ed7e70d docs: topo — §2.9-5 and §2.9-18 struck; macro-word-census and interface-dpi-arms rows; FACTS 17 handshake
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:41:55 -07:00
lucio ef9ce984b7 Merge branch 'small-1' 2026-09-03 02:41:15 -07:00
lucioandClaude Fable 5 40a7b478c5 Rename warns about macro arguments it did not read; Scope at the crate root; lucisv check --rules-doc
TODO section 29; closes docs/topo.md 2.9-18 (server half) and 2.9-5;
the second half of coverage_gaps M12.
FileFacts::macro_words - the identifier-shaped words seen inside macro
invocations, directive lines and attributes (words::harvest_raw, which
shares its raw-token match with harvest so the two cannot drift) -
tag MW, FACTS_FORMAT 16 -> 17 (+3.1 percent corpus / +1.7 percent
opentitan store, measured). WorkspaceIndex::files_naming_in_macros is
files_mentioning's twin, and lucisv_server::rename appends one warning
per such file that lies outside the set rename_sources built: no new
rung, nothing read, 58 files in 186 microseconds for clk on opentitan.
Pinned by a three-file case and its no-double-warning control, run by
QA against the real server; QA also found an organic instance in
opentitan (cipher_crypt inside a DV_CHECK_FATAL) that 0.33.0 never
mentioned. vlog_refactor's Scope moves to the crate root (pure move,
counts identical). lucisv check --rules-doc prints rules_markdown(),
takes no files, is lint-only; the example binary is gone.
3 226 tests / 48 binaries, corpus 814/820, opentitan check byte-
identical to 0.33.0.

docs/features/macro-word-census/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:41:15 -07:00
lucio 5461179e18 Merge branch 'small-2'
ci / checks (push) Failing after 1m36s
ci / corpus (push) Successful in 43s
# Conflicts:
#	docs/coverage_gaps.md
2026-09-03 02:28:28 -07:00
lucioandClaude Fable 5 bff31bb80f docs: pre-existing docs pass found uncommitted in the tree — the three stale README claims closed, [lint] in README.md, docs site content and dist refresh
Committed by the lead as found on 2026-09-02 so lane merges can proceed;
content reviewed (README claims match delivered features).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:28:11 -07:00
lucioandClaude Fable 5 ee0faa2e18 Modport method prototypes, unnamed DPI formals, and the const ref comment gap
TODO section 30 (coverage_gaps M13, corrected).
A modport port may be a method prototype - import task drive(int x),
export function int get() - parsed by Parser::parse_tf_header, the
one header parse parse_function_decl and parse_task_decl now
destructure, printed by Fmt::tf_header, bound as Target::InScope
(IEEE 1800-2017 25.5: a modport names a member of its own interface)
with the formals declared in a scope of their own; one prototype per
import/export group, the LRM's comma list still a clean error
(recorded narrowing). A DPI import's formals may be unnamed
(35.5.5) behind parse_tf_ports(allow_unnamed), the empty-name
convention documented on TfArg::name, every other caller unchanged
and a non-DPI unnamed formal still an error at its position. M13's
const half was misfiled - const ref already parsed - but the probe
found the unowned gap in const /*c*/ ref, now TfArg::after_const.
Proof: 3 223 tests / 48 binaries, corpus 814/820, 4 807 corpus +
opentitan files byte-identical to 0.33.0 (zero population), QA's
adversarial probes and consumer audit of the possibly-empty names.

docs/features/interface-dpi-arms/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:27:24 -07:00
lucioandClaude Fable 5 15c78c1c32 TODO §32 planned: error recovery inside headers and lists (M10) — error elements, a list-local bracket-seeded sync, headers keep their node
ci / checks (push) Successful in 1m6s
ci / corpus (push) Successful in 30s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 22:19:01 -07:00
lucioandClaude Fable 5 132f6e9186 TODO §31 planned: format fences at statement level and inside class bodies (M9, §2.9-3)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 22:17:28 -07:00
lucioandClaude Fable 5 d1821ff859 TODO §29/§30 planned: Scope promotion, macro-word census for rename warnings, --rules-doc; M13 modport prototypes, const arguments, unnamed DPI formals
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 22:15:53 -07:00
lucioandClaude Fable 5 3d0a0af893 docs: §28 closed — topo and CLAUDE.md name every decomposed module; post-round census (two files over 600: perf.rs 895, lexer.rs 762)
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 25s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 22:01:01 -07:00
lucio eb87a555b3 Merge branch 'decomp-semantic' 2026-09-02 21:55:55 -07:00
lucioandClaude Fable 5 b57ae35be4 Decomposition, lane D: vlog_semantic's bind.rs and workspace.rs, vlog_refactor's ports.rs and rename.rs become modules, a pure move
TODO section 28, lane D (the file-size rule in CLAUDE.md).
bind.rs (1 718 production lines) becomes bind/{mod, item, decl, class,
cover, stmt, sva, expr}.rs; workspace.rs (1 111) becomes workspace/
{mod, index, update, record, external}.rs with facts.rs and
FACTS_FORMAT untouched; ports.rs (1 391) becomes ports/{mod, find, add,
remove, propagate, list}.rs, one file per refactoring; rename.rs (760)
becomes rename/{mod, scope, warnings, tests}.rs. No function split, no
file over 600 production lines (largest add.rs at 432), every public
path unchanged (crate-root doc pages identical; only private-module
pages relocated). Carved by a range manifest that had to tile the
original byte for byte. Proof: per-binary test counts identical
(vlog_semantic 345 / 17, vlog_refactor 206 / 5, workspace 3 215 / 48),
corpus --stdout byte-identical, and the lucisv check finding lists
byte-identical between this build and the base over the corpus and the
opentitan hw tree - done by the dev and redone from scratch by QA.

docs/features/decomposition-semantic/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:55:55 -07:00
lucioandClaude Fable 5 96425f6cb9 docs: topo §1.3/§3.3 and the README architecture table name the decomposed modules (lanes A–C)
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 28s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:36:27 -07:00
lucio de6f04bf7d Merge branch 'decomp-server'
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 41s
2026-09-02 21:33:48 -07:00
lucioandClaude Fable 5 b96827c51d Decomposition, lane C: lucisv_server's server.rs and completion.rs become modules, a pure move
TODO section 28, lane C (the file-size rule in CLAUDE.md).
server.rs (2 559 production + 6 293 test lines) becomes server/{mod,
dispatch, client, index, notification, progress, diagnostics, batch,
formatting, large_file, semantic_tokens}.rs with the tests in
server/tests/ (16 files, one per former banner section, 15 shared
helpers hoisted into the harness); completion.rs (1 716 + 2 463)
becomes completion/{mod, member, module, tiers, word, site,
harness}.rs with each provider's tests beside it. answer_request (393)
and handle_notification (197) stay whole as the dispatch tables they
are; perf.rs stays whole because its one sentence has no and. Every
import elsewhere in the crate resolves through pub(crate) re-exports,
so main.rs, inline.rs, instantiate.rs, hover.rs, nav.rs and state.rs
are byte-identical. Proof: per-binary counts identical (1 435 / 85 / 3;
workspace 3 215 / 48), e2e and the vsix smoke green, a live LSP session
against opentitan answering byte-identically from this build and the
base, and a line-multiset + signature census (360/360, 188/188) done
by the dev and redone from scratch by QA.

docs/features/decomposition-server/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:33:48 -07:00
lucio a426c4dbfe Merge branch 'decomp-parser'
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 28s
# Conflicts:
#	TODO.md
2026-09-02 21:13:33 -07:00
lucioandClaude Fable 5 9b93f33ae3 Decomposition, lane A: vlog_parser's parser.rs and ast.rs become twenty-seven modules, a pure move
TODO section 28, lane A (the file-size rule in CLAUDE.md).
parser.rs (8 786 production + 5 044 test lines) becomes parser/{mod,
cursor, recover, directive, split, verbatim, item, module, decl, tf,
instance, stmt, keyword_stmt, expr, primary, class, covergroup,
assertion, sva}.rs with the tests regrouped into parser/tests/ (14
files, 309 tests, same names and bodies); ast.rs (3 313) becomes
ast/{mod, module, decl, stmt, expr, class, covergroup, sva}.rs, every
type re-exported so vlog_parser::ast::X is unchanged. Nothing over 800
production lines; the two keyword dispatch tables kept whole and
documented as such, parse_keyword_stmt in a file of its own. Carved by
a line-range manifest that had to concatenate back to the original
byte for byte before writing; 149 methods and 18 items pub(super) as
the compiler demanded. Proof: per-binary test counts identical
(workspace 3 215 / 48), 4 807 corpus + opentitan files byte-identical
to the v0.33.0 binary, cargo doc item list unchanged, and a multiset +
signature census done by the dev, redone by QA, re-run by the lead.

docs/features/decomposition-parser/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:13:32 -07:00
lucioandClaude Fable 5 35f0b8d371 Decomposition, lane B: vlog_formatter's format.rs becomes fifteen modules, a pure move
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 28s
TODO section 28, lane B (the file-size rule in CLAUDE.md).
format.rs (5 444 production lines) becomes format/{mod, verbatim,
comment, phrase, list, item, module, instance, decl, routine, class,
cover, sva, stmt, expr}.rs - no file over 600 production lines, the
three dispatch tables (stmt_kind, expr, prop_expr) left whole and
documented as such, sibling modules private with pub(super) entry
points, every public path unchanged (cargo doc item list identical).
Proof: per-binary test counts identical (31/1/5/6/2/22/208/0; workspace
3 215 / 48), 4 807 corpus + opentitan files byte-identical to the
v0.33.0 binary in stdout, exit code and stderr, and a line-multiset +
function-signature census showing only use lines, visibility keywords,
banners and doc comments differ - done by the dev and re-done from
scratch by QA. verify.rs untouched.

docs/features/decomposition-formatter/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 16:39:08 -07:00
lucioandClaude Fable 5 159f6a0bd8 Release 0.33.0 — SVA bodies as real nodes
ci / checks (push) Successful in 57s
release / build-and-publish (push) Successful in 5m56s
ci / corpus (push) Successful in 26s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 16:08:19 -07:00
lucioandClaude Fable 5 a045cd7649 SVA bodies as real nodes: property and sequence expressions with Table 16-3 precedence, declarations, assertions, symbols, and a fallback that speaks
TODO section 27; the SVA half of coverage_gaps C1/M8; docs/topo.md
2.9-18's engine half.
property/sequence declarations, concurrent assert/assume/cover/restrict
property, expect, cover sequence and default disable iff were verbatim
text. They are nodes now: sequence_expr/property_expr as one
precedence-climbing extension of parse_expr (IEEE 1800-2017 Table 16-3
row by row - QA caught two rows transcribed from Table 11-2 and the
rework fixed them: nexttime on not's row, the whole loosest row read
position-independently), typed formals, assertion variables, action
blocks as the statements they are - behind a Rewind snapshot with a
byte-exact per-construct fallback that fires on 0 of 4 792 corpus and
opentitan files. No keyword reserved: operator words are text-matched
in SVA position only. One layout rule: top-level |->, |=>, ##, and, or
break one per line at the parent's indent when the spec does not fit.
SVA gap fuzzer 705 gaps / 0 failing; 46 attack pairs; verify.rs
untouched.
Semantics: SymbolKind::{Property, Sequence}, ScopeKind::PropSeq, formals
and locals scoped, instances resolve in-file and cross-file
(FACTS_FORMAT 15 -> 16); rename, references, document symbols and the
lints see inside; Scope::sva_fallback_warnings names what would still
fall back. macro_use_warnings pinned for a file whose only relationship
to the name is a macro argument (the server half stays filed).
Output moved in 13 corpus and 36 opentitan files, every changed line
inside an SVA construct (proved by tests/census.rs::sva_lines and by
QA's independent re-implementation); the 4 854 ASSERT macro uses are
byte-identical. Corpus 814/820.

docs/features/sva-bodies/README.md. Also carries TODO section 28
(decomposition, planned) and the topo rows for this round.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 16:02:29 -07:00
lucioandClaude Fable 5 f3af34980a CLAUDE.md: the file and function size rule — 300–600 production lines per file, split at 800, a reason above 1 200
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 25s
Set by the owner on 2026-09-02. Measured at the same time: thirteen
files over 800 production lines and eight over 1 200, led by
parser.rs (8 786), format.rs (5 444), ast.rs (3 313) and server.rs
(2 559 + 6 293 test) - the same files every feature lane collides in.
Decomposition is planned as TODO section 28: pure moves, public paths
kept by re-export, byte-identical output proven by the corpus and
opentitan gates.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 15:18:18 -07:00
lucioandClaude Fable 5 c2f107444c docs: coverage_gaps addendum at 0.32.0 — the recommended order is complete; TODO §27 planned (SVA bodies as real nodes, §2.9-18)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 40s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 13:22:42 -07:00
lucioandClaude Fable 5 baf0bf16f0 Release 0.32.0 — bind semantics, macro and directive residues, lucisv.instantiate
release / build-and-publish (push) Successful in 6m14s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 13:21:09 -07:00
lucioandClaude Fable 5 81df63d942 Bind semantics, the spaced macro call and the directive inside a connection, and lucisv.instantiate
TODO section 26; closes docs/topo.md 2.9-15 and 2.9-19; coverage_gaps
M4/M5/M6 corrected against a fresh opentitan census.
A bind directive's target is a path of segments with optional indices
(bind top.gen[0].u_core chk u_chk (...)); a lone target binds as a
module reference, an instance path records nothing rather than a guess.
Each connection's port half resolves against the module being bound in
and its expression half in the target module's scope first, the
workspace's member path when the target lives elsewhere, the writing
scope last (Target::BindScope, resolve::in_bind_target - the
inline-constraint shape). FACTS_FORMAT 14 -> 15: binds now post
references and an instantiation edge.
Expression-position spaced macro calls (assign x = `WIDTH (a + b);)
keep the author's gap, read from the source as glued_null_item reads
its gap; verify.rs untouched, both pins stand. A conditional directive
inside a connection value becomes ExprKind::Verbatim, byte-exact
through raw_inline as Doc::Inline, with the closing paren's line and
the list's break read from the source - so the instantiation keeps its
edge, lens and port references instead of collapsing to opaque bytes
(opentitan: the two padring sites in chip_earlgrey_{asic,cw340}.sv,
+2 edges, everything else byte-identical to 0.31.0).
lucisv.instantiate [uri, position, module] renders the inline ghost's
plan as plain text through workspace/applyEdit for clients without
inline completion; the Neovim README documents it.
QA: 3186 tests / 47 binaries, corpus 814/820, independent binary diff
over corpus and 2 645 opentitan files: only the two named files differ.

docs/features/bind-semantics/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 13:15:21 -07:00
lucioandClaude Fable 5 a0c290ccc2 Comment slots in shared machinery: an owner for every gap, four fuzzers at zero, and the small-correctness residue
ci / checks (push) Successful in 57s
release / build-and-publish (push) Successful in 5m49s
ci / corpus (push) Successful in 26s
TODO section 25; closes docs/topo.md 2.9-20, 2.9-21, 2.9-22; opens 2.9-23.
A comment written where no AST node had a field was never deleted: bump
queued it and take_meta handed it to the next node, so it printed one
node later and verify.rs refused the whole file. About seventy named
comment fields now own those gaps - SegmentComments on member/scope/
index/range segments (one parse_postfix_segment replacing three
hand-copied loops), one [a:b] grammar, BinaryComments on inside, casts,
unary/postfix, if/case/for/foreach/do-while headers, @ and # timing,
Stmt::before_semi with StmtKind::takes_semi() as the single owner of
the ; (debug_assert enforced), labels on ten nodes, qualifier runs as
Vec<Qualifier>, function/task/module/package/class/typedef/enum/struct
headers, declarators, ports, connections, instantiations. Each prints
through Fmt::slot_comments, a no-op when empty: 860 corpus and 3 975
opentitan files are byte-identical to v0.30.0 (QA reproduced from an
independent baseline build). Four exhaustive gap fuzzers at zero -
covergroup 329, fragment 153, constraint 395 (committed at last), RTL
352 (new) - are the regression gate. verify.rs untouched, ten attack
pairs. Expression slots are boxed so Expr stays 96 bytes; ast::size_pins
asserts it (QA's one finding).

Also: nav::definition gains the macro branch hover already had (H5);
a cast's type binds as a type via bind_type_expr, FACTS_FORMAT 13 -> 14
(M11); rename reports the candidate references that stayed unresolved
through the overlay, one line per file and unit (2.9-20); the scoped
name join keeps an escaped segment's terminator (2.9-21). One flagged
edit outside scope: a .. in vlog_linter/src/signals.rs patterns.

docs/features/comment-slots/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 11:32:16 -07:00
lucioandClaude Fable 5 58112d4d3b release: retry uploads past Cloudflare's 524, re-checking the server first; optional direct API URL
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 39s
0.29.0 and 0.30.0 both died in the publish step with curl: (56) ...
error: 524 - Cloudflare's origin timeout, because GITHUB_SERVER_URL is
the public host and every upload crosses the proxy. tools/
publish_release.sh now retries each upload (UPLOAD_ATTEMPTS, default 5,
backing off) and asks the server what it holds before every retry: an
asset already there at the local size is done, one at another size is a
truncated upload and is deleted before re-sending. LUCISV_API_URL, an
optional repository Actions variable passed through release.yml, names a
direct http://host:port so the API bypasses the proxy; unset, the public
URL is used as before. Mock-tested with a curl stand-in reproducing the
524-then-partial sequence. Work log in docs/features/ci-release.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 11:13:19 -07:00
lucioandClaude Fable 5 51869c8bf4 Release 0.30.0 — semantic lints on, vendor and formal collateral
release / build-and-publish (push) Failing after 7m36s
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 09:06:13 -07:00
lucioandClaude Fable 5 5051bbdf15 Semantic lints on by default: the index knows who mentions what, and the linter finally asks
TODO section 24, coverage_gaps M7 via topo 2.9-6 and 2.9-4.
unused-signal, undriven-net and multiply-driven shipped off because a
per-file analysis cannot see a signal read or driven from another
file's hierarchy. The index now carries a per-file identifier census -
FileFacts::words, FACTS_FORMAT 12 -> 13, one harvest lifted from the
server's completion candidates and now feeding them back from the store
instead of re-lexing every file at startup (scan -28 percent) - and the
linter gains a MentionOracle: unused-signal and undriven-net say nothing
when the name is mentioned in any other indexed file, the
false-negative-safe direction; multiply-driven shares the gate but never
reads it. The three are on wherever an oracle exists (the editor always,
the CLI when it walks a project) and off for a single file or stdin.
With them, the missing off switch: [lint] select/ignore in lucisv.toml
with CLI flags winning key by key, and lucisv.lint.select/ignore in the
editor.

QA's finding, reworked: the census dropped macro invocations whole, so a
signal named only inside `uvm_info(..., dut.sig) was not silenced; the
harvest now splits macro, directive and attribute words, skipping
double-quoted runs so a "%d" cannot silence a signal named d
project-wide, with workspace-defined macro names filtered out of the
completion table at the reader. Store +16.9 percent corpus / +15.0
percent opentitan, measured.

Corpus unused-signal 52 -> 44 and undriven-net 3 -> 0 with every
silencing hand-checked, nothing added; opentitan - lint-clean under its
own tools - 14 findings, all classified true against the whole repo.
Also: the docs-site rules page gains the empty-item row it lacked.

docs/features/semantic-lints-on/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 09:06:08 -07:00
lucioandClaude Fable 5 29096cbbac Vendor and formal collateral: specify, UDPs, checkers, configs, interface classes, alias, union tagged - proven output-neutral
TODO section 23, coverage_gaps M1-M3 with the evidence corrected: every
construct here has zero declarations in the corpus and in opentitan (the
analysis's '13 checker files' were UVM protocol-checker filenames), so
this is a completeness round for vendored cell/IO/memory models and
formal collateral, and the formatted output of all 860 corpus and all
3975 opentitan files is byte-identical to v0.29.0.

Five keywords reserved on a measured zero-collision census (checker,
endchecker, config, endconfig, library); five deliberately not - expect
has 41 real task-call sites, so the statement form is recognised only
when its parentheses hold a sequence operator. One parse_opaque_block
(counts its own opener, keeps the label, leaves a trailing ';' as the
null item empty-item sees) serves specify, primitive with table,
checker and config; library lines parse; specparam is a real
declaration with a rewind for PATHPULSE$; alias a = b = c binds every
term; union tagged formats; interface class routes through the class
prefix with no new kind and no FACTS bump - deliberately, so it cannot
collide with the parallel lane's bump - and implements now contributes
type-hierarchy supertypes. pairs.rs pairs table, checker and config.

docs/features/vendor-formal-grammar/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 08:33:30 -07:00
lucioandClaude Fable 5 c40e720518 Release 0.29.0 — fragment mode and define continuation
release / build-and-publish (push) Failing after 15m23s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 07:35:24 -07:00
lucioandClaude Fable 5 4e62a14af6 Fragment mode and define continuation: the three .svh shapes that did not parse, and the define that was blamed on its class body
TODO section 22, coverage_gaps H4 corrected. Class-body and module-item
include fragments already parsed - the file-scope item loop is the
class-item loop. The three shapes that did not - a bare statement list,
an enum-member list (riscv-dv's CUSTOM_1, file, included between enum
members), a covergroup-item list - become SourceFile::fragment, detected
by a whole-file rule that cannot misfire on a valid file: the first
structural item failed (directives, macros and null items do not count;
a tolerant Ok that recorded a diagnostic counts as failed - an existing
parity test caught if/else reading as a generate-if to one parser and a
statement to the other), the file does not open with a design-unit
keyword, and a shape consumes the file to EOF, tried narrowest-first.
Each shape re-lexes a fresh token stream - Rewind does not restore the
tokens' comment buckets and the first draft lost comments on
non-fragment files. A fragment formats at indent zero through the
existing printers; its declarations bind; its enum variants are not
exported (pkg::CUSTOM_1 must not resolve to a name that does not
exist). FACTS stays 12.

The other .svh was never a fragment problem: a define whose formal
argument list spans two lines with no backslash. The lexer continues
such a directive until the list closes - incrementally, after QA found
the first cut quadratic on an unclosed list (20000 lines: 2.5 s ->
0.56 ms), pinned by a byte-visit counter.

Opentitan 12 -> 10 failing files, exactly the two predicted; corpus
813 -> 814 of 820; every remaining comment-gap failure proven to fail
identically outside a fragment.

docs/features/fragment-mode/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 07:34:31 -07:00
lucioandClaude Fable 5 cbb80e884f docs: clocking-wave README — tl_errors.svh's blocker is a define continuation, not its class body
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:11:32 -07:00
lucioandClaude Fable 5 3ee1c558b3 docs: coverage_gaps.md status addendum at 0.28.0 — C1, C2, H1, H2, H3, H6 delivered; H4 next
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:03:21 -07:00
lucioandClaude Fable 5 fae939119a Release 0.28.0 — covergroup bodies
release / build-and-publish (push) Successful in 7m44s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:02:23 -07:00
lucioandClaude Fable 5 2734885f2b Covergroup bodies: coverpoints, bins, transitions and crosses are real code - 544 of 544 on opentitan, zero fallbacks
TODO section 21, round 2 of coverage_gaps C1, closing it. A covergroup
was a flat token scan into verbatim text; now ItemKind::Covergroup with
CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}, BinDecl
(wildcard, kind, array, spec: Values / Transitions / Default /
DefaultSequence / Select, with, iff) and SelectExpr for binsof ...
intersect ... && !binsof - behind the same Rewind fallback as
constraints (v0.27.0's scan re-run character for character on any
failure), no keywords reserved. The bin '(' ambiguity is settled by
position, the LRM's own rule, which replaced a lookahead scan and took
the fallback count to zero. Two guards in shared expression machinery -
an index cannot begin with *, -> or =; a bin's own with (...) filter is
not an array-method iterator argument - both attacked across the corpus
and the opentitan tree. Canonical layout, verify.rs untouched, thirteen
attack pairs. Every sampled expression binds to the class's properties;
cg_inst.cp resolves cross-file; FACTS_FORMAT 11 -> 12. The gap fuzzer
was built in from day one and its classification is asserted, not
claimed.

Opentitan: 544/544 structured, 87/87 DV covergroup files idempotent
with comment streams byte-identical, sweep and per-file diagnostics
identical. Corpus +1139 references, 1135 answered.

docs/features/covergroup-bodies/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:01:48 -07:00
lucioandClaude Fable 5 53bc293c37 Release 0.27.0 — constraint bodies
release / build-and-publish (push) Successful in 5m49s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 04:19:08 -07:00
lucioandClaude Fable 5 bce167c052 Constraint bodies: constraint c { ... } is real code - soft, dist, ->, foreach, solve before - with a rewind to the verbatim it always had
TODO section 20 round 1, coverage_gaps C1 for constraints. A constraint
declaration was opaque text with no name span; renaming a rand field
left constraint c { user_id < 5; } as non-compiling code. Now
ItemKind::Constraint with a structured ConstraintSet (Expr{soft},
Implication, If, Foreach, SolveBefore, Unique, DisableSoft, Directive,
Empty), ExprKind::Dist, and randomize() with bodies as
ConstraintBody::{Items, Verbatim}. The parser attempts the structured
body behind a Rewind snapshot - cursor, both pending-comment buckets,
depth, links, open_conds, diagnostics - and on any error re-runs
v0.26.0's verbatim capture character for character, so an unknown body
IS the old behavior. No keywords reserved: soft/dist/solve/before are
matched by text, so logic before; keeps working and token.rs, pairs.rs
and the editor grammar are untouched. Canonical layout, verify.rs
untouched, attack pairs re-derived and extended. Every operand binds to
the class's properties (foreach vars nest; a with block resolves against
the randomized object's class first), so hover, definition, references
and rename reach inside. FACTS_FORMAT 10 -> 11. Lint rules read
constraint operands.

QA's finding - comments after the round's own words were dropped and
the safety net refused the file - answered with an exhaustive gap fuzzer
(358 gaps, format and idempotency demanded) and fourteen named comment
fields; the forty gaps that remain are shared machinery that fails
identically outside a constraint, filed as topo 2.9-22. Opentitan: 1993
of 2009 bodies structured, sweep unchanged, 48 DV files idempotent with
comment streams byte-identical, per-file diagnostics identical.

docs/features/constraint-bodies/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 04:18:18 -07:00
lucioandClaude Fable 5 dd4aa498bb Release 0.26.0 — member completion and escaped identifiers
ci / checks (push) Successful in 57s
release / build-and-publish (push) Successful in 5m16s
ci / corpus (push) Successful in 22s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 02:19:17 -07:00
lucioandClaude Fable 5 7d637323a5 Escaped identifiers: the terminating space, written once at fifty sites
coverage_gaps H3. An escaped identifier ends at whitespace (IEEE 1800
5.6.1) and the lexer stops the token before it; the formatter emitted
every name bare or through a format! splice, so \my-signal; re-lexed
as one token and the safety net refused the whole file - netlists and
generated RTL could not be formatted at all. One choke point
(format::named / name_doc, predicate ends_escaped because parser-joined
composites like a.\b end inside an escaped name) now terminates the
name; the space is unconditional and the printer's trailing trim
removes it before a break, so doc.rs and printer.rs are untouched.
verify.rs untouched; eight masked-corruption attack pairs; corpus
byte-identical by construction (every corpus backslash is inside a
string or a comment). Ran in its own worktree in parallel with member
completion. Open, filed as topo 2.9-21: a scoped name whose segment is
escaped is refused, never corrupted, until the parser keeps segments.

docs/features/escaped-identifiers/README.md; TODO.md section 19.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 02:17:43 -07:00
lucioandClaude Fable 5 df85fd3b54 Member completion: a dot means members - item., reg2hw.ctrl., vif.cb., pkg::, and the port map
TODO section 18. Typing a dot used to get the whole-index dump (every
keyword and project word, capped at 512); now the answer after a
separator is exclusively the members of what precedes it, or nothing.
The prefix walk is published from vlog_semantic as MemberSite /
Semantics::member_site / WorkspaceIndex::members_of_chain and the
resolver's own member_of, unit_member, member_in_chain and follow_one
are rewritten to call it - one walk, so the popup cannot list a member
hover would not resolve (pinned structurally). Inherited members ride
the same base chain; this./super./pkg::/cls:: are the same question.
A headless dot inside an instantiation's (...) or #(...) lists the
module's ports or parameters through signature.rs's own list detector
and the Target::Port walk, already-connected ports dropped. Trigger
characters '.' and ':'. Measured cheaper than the dump it replaces
(6-62 us vs 212 us).

QA's finding fixed at the root: the binder had discarded ParamPort.kw
and bound every localparam as Param, so #(. offered prim_fifo_sync's
DepthW. SymbolKind::LocalParam, keyword sticky across continuation
entries as instantiate::params reads it, exported wherever Param is,
'localparam' on the hover card, excluded from the override list only.
FACTS_FORMAT 9 -> 10.

Also carried: TODO sections 19 and 20 (the escaped-identifier and
constraint-body plans) and the topo rows for both lanes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 02:05:03 -07:00
lucioandClaude Fable 5 bbf87976a1 Release 0.25.0 — struct members
ci / checks (push) Successful in 59s
release / build-and-publish (push) Successful in 5m16s
ci / corpus (push) Successful in 22s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 23:56:22 -07:00
lucioandClaude Fable 5 2a2334ef5a Struct members: s.field, reg2hw.ctrl.q and the anonymous aggregates resolve
coverage_gaps H1 + topo 2.9-13 delivered. The in-file gap was one
resolver gate: member_scope now returns any symbol's child scope when it
is a Struct scope, so a typedef, an anonymous struct declarator and an
inline nested field are one rule; fields declare with their own type so
s.hdr.addr hops through a member. Cross-file, struct members export
under the typedef's name, package-nested struct typedefs under their
bare name (the nested-class convention, ambiguity refused), and inline
nested fields - the opentitan register-package shape - under a
synthesized owner.field key carried as the field's type: joined with
'.', not '::', because member_type's last_segment would collapse the
latter to the bare field name and q/d/qe live in every register
package. Anonymous enum variants land in the enclosing scope like
typedef ones. FACTS_FORMAT 8 -> 9; typeDefinition descends into
typedef struct bodies.

Unresolved fell 1203 -> 1162; the corpus store shrank 1.1 percent
(resolved locals encode smaller than the candidates they replaced),
opentitan's register packages grow it 4.3 percent. QA: 28 opentitan
probes, three planted sibling pairs (rxfull/fmtfull, avsetup_rst/
avout_rst, tpm_csb/csb) all correct, zero wrong answers, hover under
0.5 ms.

docs/features/struct-members/README.md; TODO.md section 17.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 23:53:45 -07:00
lucioandClaude Fable 5 95f930cf20 Release 0.24.0 — interface semantics
ci / checks (push) Successful in 49s
release / build-and-publish (push) Successful in 4m40s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 22:55:31 -07:00
lucioandClaude Fable 5 311551f232 Interface semantics: interfaces, modports and clocking blocks become symbols; vif.sig crosses files
coverage_gaps C2/H2, topo 2.9-7 delivered. SymbolKind::{Interface,
Modport, Clocking}; is_instantiable() (Module | Interface) is the one
predicate every 'is this a module' filter reads, pinned in place, so
interfaces stay in the module table, the ghost, the hierarchies and the
refactorings while the card finally says 'interface'. An interface
exports its signals - they ARE its surface - where a module still exports
ports and params only, which is what lets virtual my_if vif; vif.sig
resolve across files. Modport and clocking-internal names bind as
scope-local references (nothing on a miss - a lexical walk would land a
modport port on a file-scope lure); the modport half of bus_if.mp in a
type position is Target::TypeMember, resolved through type_here; a
clocking block carries type_name = its enclosing unit so vif.cb.data
hops through round-2 machinery unchanged. FACTS_FORMAT 7 -> 8.

Unresolved fell 1256 -> 1203 on the corpus, the first movement in three
rounds: the @(cb) / cb.data names that had nothing to bind. Store +1.2
percent. A modport now renames from its type-position use (the refactor
pin flipped at review). QA: 17 opentitan probes, zero wrong answers, all
sub-millisecond; vif.cb.scl_i lands on i2c_if.sv's own signal.

docs/features/interface-semantics/README.md; TODO.md section 16.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 22:53:27 -07:00
lucioandClaude Fable 5 ff67281995 Release 0.23.0 — member chains and instance heads
ci / checks (push) Successful in 51s
release / build-and-publish (push) Successful in 4m50s
ci / corpus (push) Successful in 21s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 21:37:28 -07:00
lucioandClaude Fable 5 7ca2508ec7 Member chains and instance heads: cfg.vif.clk, item.hdr.addr, u_sub.port resolve through the index
DV round 2 (TODO section 15 round 2). A chain tail carries spellings -
Target::MemberOf { head, mids } - so in-file it hops declared type to
declared type, and a chain that leaves the file becomes one composed path
Unit::mid::tail that follow_one walks with member_type hops: no deferred
resolution, no ordering assumption, and chain tails post to the index
through the existing contract so hover, references and rename agree.
Def::type_name rides every indexed declaration (FACTS_FORMAT 6 -> 7,
with ReferenceFact base so this.x uses post cross-file); an instance
symbol's type is its module, and modules export ports and parameters -
nets/vars stayed in-file on measurement (+24 percent store, and .port(w)
connections would have resolved to internal nets). Typedef aliases are
chased with a visited guard; a type the workspace declares twice with
different kinds is refused one hop out, the round-1 lesson applied.

The rename truth flipped with it: u_sub.sig IS sub's wire sig and is
renamed alongside it; an unresolvable tail is left alone but no longer
warned about, filed as topo 2.9-20.

Corpus: references 97454 -> 98919, unresolved unchanged at 1256,
store +15.4 percent. QA: zero wrong answers across the attack suite and
15 live opentitan probes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 21:35:11 -07:00
lucioandClaude Fable 5 91b7c2fd67 Release 0.22.0 — class member access
ci / checks (push) Successful in 49s
release / build-and-publish (push) Successful in 4m51s
ci / corpus (push) Successful in 19s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 20:19:23 -07:00
lucioandClaude Fable 5 ce2f858e5e Class member access: in_item.user_id resolves, through the handle's type and up its extends chain
DV round 1 (TODO section 15). The tail of head.member gets a reference
when the head is a plain identifier whose declared type (Symbol::type_name,
new) is a class or module: the member is found in that scope, else up the
in-file extends chain, else the workspace's member table chases
WorkspaceIndex::base_of (a subclass-to-base map rebuilt from the existing
inheritance census, no new facts field) - cycle-guarded on both sides and
placed in follow_one so hover, cross-file references and rename cannot
disagree. this.x/super.x misses ride the same loop, delivering topo
2.9-9. An out-of-class method body (task c2::update) sees its class's
members through a stand-in Class scope. FACTS_FORMAT 5 -> 6: the layout is
unchanged but the reference census grew.

Honesty by construction, after QA's one REWORK: a head whose type is
declared in-file as anything without a member scope (typedef, alias,
enum, param) records nothing - a two-state Option had stood in for the
three-state TypeHere question, and a typedef named bus_t could have been
answered by an unrelated class bus_t elsewhere. The fix removed exactly
438 wrong postings from the corpus with unresolved unchanged at 1256.

Hover 7-143 us; opentitan tl_seq_item member 0.12 ms cold, 0.01 ms warm;
store +2.85 percent.

docs/features/class-member-access/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 20:17:18 -07:00
lucioandClaude Fable 5 14fbdab717 docs: coverage_gaps.md — the ranked Verilog/SV gap analysis at 0.21.0
ci / checks (push) Successful in 57s
ci / corpus (push) Successful in 23s
Two sweeps crossed: a 71-file empirical probe (44 RTL, 27 DV, 13 LSP
spot checks) against snapshot binaries, and an inventory of every
documented non-goal, verbatim capture, non-resolution rule and open
handshake. Idempotency and comment preservation held everywhere that
parsed; the gaps are grammar holes, opaque verbatim regions and
semantic blind spots, ranked Critical/High/Medium/Low with a
recommended order.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 16:34:53 -07:00
lucioandClaude Fable 5 f8401a0024 Release 0.21.0 — null items and the empty-item lint
ci / checks (push) Successful in 49s
release / build-and-publish (push) Successful in 4m58s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 15:03:36 -07:00
lucioandClaude Fable 5 307a56e921 Null items: the semicolon after endgenerate, and everywhere else an item may stand
Owner report: 'for loop inside generate shows expected item (found ;) at
endgenerate;'. Lead diagnosis before dispatch: every generate-for spelling
and three systemverilog.io examples already parsed; the failing token was
the lone ';' - IEEE 1800-2017 A.1.4's null item, legal in module,
generate, package, interface, program and class scope and at file scope,
rejected by lucisv in all of them.

ItemKind::Empty, one branch at the top of parse_item_kind, the three
exhaustive arms topo 3.3 predicts and no others. The formatter keeps the
';' where it was written - glued to the previous sibling's line
(endgenerate; end; endmodule; ;;) when no newline separates them and the
';' carries no docs of its own, else on a line of its own - decided from
src spans in item_seq rather than a parser flag. verify.rs untouched,
eight attack pairs. New empty-item lint (slang's -Wempty-member) with a
safe fix whose deletion range structurally cannot swallow a comment.

Corpus byte-identical at 813/820 against the pre-change binary; opentitan
sweep identical file-for-file; empty-item fires zero times there. The LSP
now publishes a warning with a quick fix where it used to publish a parse
error.

docs/features/null-items/README.md; TODO.md section 14.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 15:01:33 -07:00
lucioandClaude Fable 5 1e30ea0fb5 gitignore: the owner's .zcode and the agent-harness .claude directory
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 23s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-31 21:51:35 -07:00
lucioandClaude Fable 5 3f912e7fce Release 0.20.0 — fuzzy completion at VS Code's floor
ci / checks (push) Successful in 46s
release / build-and-publish (push) Successful in 4m35s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 19:04:41 -07:00
lucioandClaude Fable 5 f3b5a9d189 Fuzzy completion: clkenq reaches clk_osc_en_q, at VS Code's own floor
Prefix matching below three typed characters, subsequence from three
up — the owner's ruling, which is VS Code's own rule. The scope,
index-name and word tiers match by case-insensitive subsequence at 3+,
ranked prefix-first then by a three-pass greedy-tighten scorer
(boundary and contiguity bonuses, gap penalties); module, keyword,
template and macro tiers unchanged, and the instantiation ghost's
exact-match probe deliberately stays exact.

The scan is affordable because every word and unit name carries a
32-bit character mask beside it, written in exactly two places so
table and mask cannot desync: a clkenq keystroke rejects 99.6% of
opentitan's 100k-word table with one AND each (+0.05 ms); the
pathological class is three very common letters (aes +0.8 ms, QA's
ena ~3-4 ms answered-in), accepted at lead review as imperceptible
in a popup. Responses below the floor are always isIncomplete — a
complete two-character answer would be client-filtered and the third
keystroke, the one that turns fuzzy on, would never reach the server.

QA verified clkenq -> clk_osc_en_q live in a real opentitan buffer
(gfr_clk_mux2.sv) and the 2-to-3 transition over the wire; ten
adversarial matcher attacks all passed.

docs/features/fuzzy-completion/README.md; TODO.md section 13.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 19:02:42 -07:00
lucioandClaude Fable 5 02b4204536 Release 0.19.0 — the space-armed ghost, every module answering
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m47s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 17:17:44 -07:00
lucioandClaude Fable 5 03a4958294 Inline instantiation round 2: the space is the commitment, and every indexed module answers
Two owner rulings from live use. The ghost now fires only after
'name<space>' — aes alone may still be growing into aes_dft, so the
typed space is what says the name is finished; an Ident ending at the
cursor offers nothing at all. And a module declared in more than one
file no longer declines: completion::nearest_definition picks the copy
sharing the most leading path components with the asking buffer (a
top_earlgrey buffer gets top_earlgrey's ast_dft), then the shallowest,
then the lexicographically smallest — the depth term is QA's catch,
fixed at review, so a direct sibling beats a deeper subdirectory copy
that ties on the prefix. vlog_refactor::module_definition keeps its
ambiguity refusal for its own callers.

The refusal residue is now the enumerable inline::NoGhost, and QA's
sweep proves the ruling: 1131/1131 opentitan module names ghost, zero
declines (199 multiply-declared, tb 61 ways), ast_dft and io_osc
verified from both tops over the wire, 0.05-0.08 ms per non-matching
keystroke.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 17:15:42 -07:00
lucioandClaude Fable 5 f27fa1c045 Release 0.18.0 — inline instantiation, two levels
ci / checks (push) Successful in 50s
release / build-and-publish (push) Successful in 4m56s
ci / corpus (push) Successful in 21s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 14:47:40 -07:00
lucioandClaude Fable 5 cadb4319e4 Inline instantiation: the popup names the module, the ghost writes the rest
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 19s
Two levels, sized for opentitan. Tier 0 of the completion popup stops
planning skeletons (up to 64 file reads + header parses per keystroke)
and offers module names alone; once the identifier at the cursor exactly
matches an indexed module, textDocument/inlineCompletion ghosts the full
instantiation — every parameter, every port, each a tabstop, in-scope
signals auto-connected — planned once through the existing header-slice
path and the FileView cache. Candidates::has_module is the per-keystroke
probe: a case-sensitive binary search whose str-order premise is pinned.
lucisv.inlineInstantiation (default on) gates it, independent of
inlineTemplates.

Measured on opentitan: non-matching keystroke 0.10-0.17 ms warm, ghost
0.6-1.1 ms for aes (14 params/16 ports), 2.5 ms cold for the
112-parameter top_earlgrey; popup module tier reads no files at all.

Lead corrections at merge: four doc references to a lucisv/instantiate
command that never existed, replaced by the honest gap (topo 2.9-19: no
skeleton path for clients without inlineCompletion); extension and nvim
README docs delivered.

docs/features/inline-instantiation/README.md; TODO.md section 12.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 14:17:16 -07:00
lucioandClaude Fable 5 1cfbab4a56 Docs debt: performance_take2.md, the merged-wave measurement, finally checked in beside take 1
Written 2026-08-29 as the owner-requested second opentitan round; referenced
by CHANGELOG 0.15.0, docs/perf/README.md and the index-scope README ever
since, but never staged. Placed in docs/ so its relative link to
performance.md resolves.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 14:17:00 -07:00
lucioandClaude Fable 5 a1fa402fd8 Release 0.17.0 — the testbench wave, complete
ci / checks (push) Successful in 53s
release / build-and-publish (push) Successful in 5m4s
ci / corpus (push) Successful in 22s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 18:47:45 -07:00
lucioandClaude Fable 5 bc533c6cb1 The clocking wave: eight buckets in one round, 43 -> 11 on opentitan
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 22s
Clocking signal bindings (the one production the modelled node was
missing), default disable iff captured verbatim with six rejection
pairs, iff on event-control terms, indexed bare event names
(chain-charged), gate drive strengths (the mop-up's amortized skip),
program blocks as modules with a different closer, and macros as a
concurrent assertion's whole action — where QA caught a real
regression (a macro BEGINNING a statement, four UVM-idiom shapes) and
the rework moved the decision to the token after the call:
at_statement_tail, one line, with the failure asymmetry argued in the
doc and attacked by QA against the diff rather than trusted. Chain
limit 256 -> 1024 on measured need (567 links in pinmux_reg_top) with
PARSE_STACK_SIZE 16 -> 32 MiB restoring the 3.3x margin, a sabotage
probe proving it real, and parse_sens_list's uncharged chain loop
closed. Whole-tree superset: exactly one output move, ~55 lines of
prim_sync_reqack generate code freed from an assertion's opaque
bytes. Corpus 860 files byte-identical, 813/820. The 11 remaining:
macro fragments (preprocessing decision), vendor non-SV (exclude
patterns recommended), three written-up skips.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 18:46:58 -07:00
lucioandClaude Fable 5 5ad0772475 Merge testbench-syntax mop-up round
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 18s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 16:08:59 -07:00
lucioandClaude Fable 5 af3280c651 The mop-up: nine small buckets, forty-five files, no new surface where none was needed
Block-scoped typedef statements (new StmtKind, three arms plus the
typeDefinition hop QA's audit caught missing), system-function casting
types (the bucket the analysis had mislabeled as drive strengths),
enum member ranges, casts over assignment patterns, gate delay lists,
virtual iface.modport through ansi-first-port's own gate, rand on
struct members, foreach skipped dimensions, hierarchical bind instance
paths. OpenTitan sweep 88 -> 43 with zero newly-failing files and the
whole-tree superset check proving 0 of 3,855 previously-passing files
moved; corpus byte-identical at 813/820; tolerant diagnostics 147 -> 0
on the fixed set and 0 files worse anywhere. One skip written up
(pullup drive strength: two AST changes for one file). verify.rs
untouched, no capture added.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 16:08:51 -07:00
lucioandClaude Fable 5 24b0dd9912 Docs debt from the wave: changelog fold, coverage correction, stale non-goal
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 18s
The extension changelog's outside-edit "Unreleased" section described
the hierarchy sidebar 0.15.0 had already shipped — folded into that
entry, keeping its two specifics the entry lacked. syntax_coverage.md
carries the mop-up's correction (bucket 6 was system-function casting
types, never drive strengths; bucket 12 is six files) and is committed
as the pre-wave snapshot it is. ansi-first-port's deliberate non-goal
for virtual bus_if.mp is un-staled: the mop-up delivered it through
this feature's own gate, the narrow way the item asked for.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 15:42:28 -07:00
lucioandClaude Fable 5 852d05d9ad Release 0.16.0 — the testbench-syntax release
ci / checks (push) Successful in 52s
release / build-and-publish (push) Successful in 4m52s
ci / corpus (push) Successful in 23s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 15:34:30 -07:00
lucioandClaude Fable 5 98675c630a docs/topo.md: the testbench wave's edges
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 15:33:43 -07:00
lucioandClaude Fable 5 7f65a2449a The merged-tree pins both lanes promised each other
ci / checks (push) Successful in 48s
ci / corpus (push) Successful in 21s
The refusal pin a_comment_before_a_call_in_a_condition_is_still_refused
flips exactly as Lane B's Handshake said it should now that take_gap
and header_parens share a tree: the shape formats, the comment stays
inside the parens, fixed point asserted, plus the keymgr .cases entry.
And the standing invariant-4 template applied to the directive
capture: three (input, corrupted output) pairs — a dropped `else arm,
swapped arms, a lost `endif — each asserted rejected by the safety
net. Both were flagged by the serial round as the lead's first
post-merge task; done by the lead.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 13:43:24 -07:00
lucio 3f300fa9e9 Merge testbench-syntax serial round (directive-in-statements + take_gap)
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	docs/features/formatter-bug-fixes/README.md
2026-08-29 13:38:32 -07:00
lucioandClaude Fable 5 7881cc869c Directives may open inside a statement, and comments keep their owners
Bucket 7: the mirror image of directive-split — an `ifdef opening
INSIDE an assign RHS, expression or instantiation head, where all
three existing directive features trigger on a closing directive and
could not fire. The construct is captured verbatim by two mirror
recoveries sharing one capture step (statement-level first, item-level
behind it), construct_end classifying the head (Semi /
endfunction+label / Unknown -> refuse rather than guess), and
terminated_in_arm honoring both real terminator placements. Both
flagship tb.sv files needed only take_list_directives to stop
harvesting an outer region's `else as a list element. OpenTitan sweep
107 -> 100, exactly the 7 targets (chip_if.sv x2, chip_earlgrey
asic/cw340, jtag_dtm_reg_block, both top_* tb.sv), zero regressions,
corpus per-file byte-identical to baseline.

Also delivers Lane B's Handshake: take_before_open's queue drain was
necessary-but-not-sufficient — CallComments::dangling drained the
same way — both now behind Parser::take_gap (comments kept only when
span.start >= last_end()), verified by composing with Lane B's tree:
keymgr_scoreboard.sv formats, closing the last bucket-2 file.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 13:38:02 -07:00
lucio 89186a8eaa docs: move performance and topology notes
ci / checks (push) Successful in 53s
ci / corpus (push) Successful in 21s
2026-08-29 13:29:57 -07:00
lucio 27a652ee3d Merge testbench-syntax Lane B (formatter round-trip bugs)
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 21s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	TODO.md
2026-08-29 12:56:47 -07:00
lucioandClaude Fable 5 d3deacf0f6 Three formatter comment bugs fixed where they lived, safety net unwidened
Bucket 2 of syntax_coverage.md: 12 opentitan files parsed but failed
the formatter's own verification. Three shapes: (A) a line comment
trailing 'end' swallowed a cuddled 'else' into the comment — cuddling
now requires no trailing line comment (block comments still cuddle);
(B) a comment inside if/while/repeat/wait/case header parens printed
after the ')' — Fmt::header_parens finds the real ')' and prints the
split comments through the shared paren layout; (C) 'default;' grew an
invented ':' — the optional colon is read from the source byte. 11 of
12 files now format and round-trip (12 -> 1 verification failures on
the sweep); the 12th is a parser bug filed as a specified Handshake
and delivered by the directive round, not edited cross-lane. verify.rs
untouched; four masked-corruption rejection pairs added per the
standing template; QA's ~30-attack sweep found zero corruption and
pinned two informational boundaries. Formatter output changed:
release must bump the workspace version (format-cache rule).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 12:55:51 -07:00
lucio 17633d2214 Merge testbench-syntax Lane A (out-of-class constraints)
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 22s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	TODO.md
2026-08-29 11:11:29 -07:00
lucioandClaude Fable 5 e2c954ba77 Out-of-class constraints parse: one line, 45 files, a cascade gone
constraint C::name { ... } at file/package scope failed at the `::` —
parse_constraint's name was expect_name where the out-of-body method
path already existed; it is now parse_method_name, and nothing else
moved: the item was always a verbatim leaf, so no AST variant, no
formatter/binder/spans arm, verify.rs untouched. On the real opentitan
checkout: 45 of 45 bucket-1 files unblocked (44 fully clean, the 45th
advancing to its documented bucket-10 gap), whole-sweep failures
151 -> 107 with zero newly-failing files, and the tolerant-mode
cascade collapsing 1,349 diagnostics -> 1 across the bucket — the LSP
win the round was chosen for. Corpus gate exactly at baseline. QA
reproduced every number independently via stash before/after,
attacked the grammar widening and the verbatim byte-integrity, and
pinned the index-opacity promise with the corrected semantic test.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 11:05:34 -07:00
lucioandClaude Fable 5 e565dc0812 TODO.md: the testbench-syntax wave, planned from syntax_coverage.md
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 10:33:38 -07:00
lucioandClaude Fable 5 34b766cbef Release 0.15.0 — the interactive-latency release
ci / checks (push) Successful in 44s
release / build-and-publish (push) Successful in 4m25s
ci / corpus (push) Successful in 19s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:48:48 -07:00
lucio 8cdc1b3375 Merge the design-hierarchy sidebar (codex + integration round)
ci / checks (push) Successful in 47s
ci / corpus (push) Successful in 19s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	crates/lucisv_server/src/main.rs
2026-08-29 03:39:31 -07:00
lucioandClaude Fable 5 651e58bfb3 The design-hierarchy sidebar: codex's feature, integrated
An instance-oriented hierarchy view in the Activity Bar —
lucisv/moduleHierarchy snapshots (schema 2: uri table, flat ranges,
derived ids; 11.6 MB -> 2.3 MB on opentitan) plus
lucisv/moduleHierarchyChanged invalidation, gated on the extension's
initializationOptions. Format 5 carries decl spans, instance
occurrences and client positions for file-scope declarations
(+1.7-1.9 % store), so a snapshot reads no files at all: handler
145-167 -> 17-20 ms settled, a save with the sidebar open 366 ->
141 ms. complete is !scanning && !must_wait, pinned. Owner UI rounds:
no hover preview, all levels collapsed by default with stable ids
across refreshes, and search over a resident flat model (freeze
diagnosed: materialized expanded tree x undebounced double
fuzzyScore x whole-tree clone per keystroke) — prebuilt lowercased
index, bitmask prefilter, top-K counting, 200-row cap with an honest
remainder, single-digit ms over a 120k-entry fixture.
LineIndex::utf16_position unifies the index's and the wire's position
math under a cross-crate agreement test.

Implementation: codex. Integration fixes + owner items: Opus dev.
QA: lead (measurement pass) + Sonnet (SHIP, independent oracles).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:39:06 -07:00
lucioandClaude Fable 5 37560cad5e A subsuming widen was already incremental; its word merge was not
ci / checks (push) Failing after 1m4s
ci / corpus (push) Successful in 26s
Take 2 filed the RTL didOpen freeze as a chooser bug; measuring with
the HEAD binary refuted that — scope_dirs keeps every raised dir so
subsumption is Added, and begin_widen has file-diffed against the
index since the widen round; the 1.4-1.7 s figures were cold-store.
The real cost was candidates.absorb inserting each new word into the
sorted table one memmove at a time — quadratic in the batch, 403 ms
of a 935 ms warm jump — replaced by a counted one-pass merge whose
equivalence with build's sort is structural (43 ms). Warm hw/ip jump
935/881 -> 555/564 ms (QA: 872-880 -> 535-546 from its own builds);
the residual is real work, 1 683 new files and a 325 ms word re-lex
filed as the store's FACTS_FORMAT follow-up. The two previously
accidental properties are now pinned, QA's five-mutation matrix
confirming each test binds exactly its property. TODO.md carries take
2's other findings (codeAction big-fan-out zero-offers, inlayHint at
default scope) as deferred items.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 02:52:55 -07:00
lucioandClaude Fable 5 e4407984cb Hotfix: --stdio is accepted, because real VS Code sessions send it
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 21s
vscode-languageclient appends --stdio for TransportKind.stdio — the
spawn the shipped extension actually makes — and the --verbose round's
strict argument parser refused it: exit 2, five crashes, the client
gives up. Nothing in the loop caught it because smoke.js and the
restart harness spawn the binary directly, never through the library.
--stdio now parses as the statement of fact it is (stdio is the only
transport), in every combination, changing nothing; near misses and
genuinely unknown args still exit 2 with the usage line, which now
names both flags. smoke.js spawns with --stdio so the library's real
spawn shape stays covered from here on.

Found live by the owner installing the hierarchy preview build.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 02:48:56 -07:00
lucioandClaude Fable 5 40094c4c4e lucisv-server --verbose: per-operation timing as a shipped toggle
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
The hand-patched diagnostic build becomes a feature: --verbose gates
the timing lines (request answered / notification handled / HELD
behind a rescan / scan and widen lifecycle / flush / reindex_one, the
exact wordings of the two diagnostic builds) as LOG messages into the
client's output channel; without the flag not one line is sent and
the cost is one branch, measured unmeasurable against HEAD. Unknown
args exit 2 with usage before the transport opens. The extension
gains lucisv.verbose (default off) and its first restart-on-settings
machinery: restart.js, one serialized chain reconciling to the last
toggle, no client transition outside it — activation and deactivate
included — after QA twice caught the alternatives (a mid-start toggle
silently rejoining the stale start; deactivate's out-of-chain stop
orphaning a spawn). Headless node harness restart_test.js, 44 checks,
five mutations caught. Spawn contract amended everywhere it is
written: no args required, --verbose optional.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 01:44:56 -07:00
lucioandClaude Fable 5 829302d0bf CLAUDE.md: the 2-agent parallel-lane loop, codified
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 24s
Up to two dev/QA lanes concurrently when TOPO.md proves the features
independent (no shared edges, disjoint files; unanswerable = serial).
Each lane: own worktree off one trunk commit, a brief whose file list
is the merge contract, dev then QA in that worktree, lead review and
merge per lane with full gates on the merged tree. Wave tracking in a
TODO.md section written on trunk before branching. Distilled from the
2026-08-28 performance wave, where the shape was proven end to end.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 00:55:45 -07:00
lucio ee1efe3fb1 Merge performance-wave Lane A (prepareRename, rename, willRenameFiles)
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	docs/perf/README.md
2026-08-29 00:11:42 -07:00
lucioandClaude Fable 5 1029d2f199 Performance wave Lane A: the rename family reads its fan-out
prepareRename answered F2 by reading every in-scope file (1.6-3.0 s on
opentitan, blocking the loop); it now answers from the open buffer and
the index in 139 ns, with a refusal-by-refusal parity table (7
reproduced, 4 deferred to rename, none lost). rename computes over
rename_sources — declarers, reference postings, open buffers, and,
after QA's HIGH finding gated the round, rung 6: files_spelling over
the index's reference facts (resolved or not, FACTS_FORMAT untouched),
restoring the dangling-new-name capture refusal the first five rungs
lost; the old name needs no rung and the argument is written and
pinned, QA's shadowing hunt included. 3.47 s -> 105 ms at a 7-file
fan-out, rung cost 852 us worst-case, byte-parity swept at four real
cursors and 564 offsets, ambiguity escaping to the whole scope.
willRenameFiles rides IncludeGraph::includers(): 249 ms -> 14 ms over
331 includers of 3 976 files. Accepted residue, documented: files
whose only mention of the name is inside opaque macro tokens lose one
warning flavour; the FileFacts macro census is filed as the real fix.

Dev Opus + QA Sonnet (REWORK-gate, fix, SHIP on re-verify) in a
dedicated worktree. Lead-reviewed and merged.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 00:11:13 -07:00
lucioandClaude Fable 5 36caf1dd19 Merge performance-wave Lane B (completion, documentHighlight, scope default)
ci / checks (push) Successful in 47s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 23:58:29 -07:00
lucioandClaude Fable 5 61f345aca7 Performance wave Lane B: completion hot path, highlight fix, scope default
Completion stops parsing whole declaring files per keystroke: tier 0
slices the module header at its terminating ';' via a whitelist walk
over a bounded lex window, anchored on the index span and re-planning
whole-file on anything unrecognized (non-ANSI included); the module
table replaces a per-keystroke workspace_symbols(""). 53 -> 3.2 ms at
the empty prefix (opentitan wire 63-66 -> 13-15 ms; typing an 11-char
word 201 -> 64 ms), items pinned byte-identical.

documentHighlight answered 0 on any name the file uses but does not
declare (both cursor questions were single-file); nav gains
external_occurrences over the overlay, grouping by the whole defs()
slice, written failing-first and pinned at the two opentitan
positions over the wire.

lucisv.index.scopeDepth default 0 -> 2 (behavior change; CHANGELOG at
release): a dv/tb file now indexes its IP block (21 files / 15 ms)
instead of one file with every cross-file answer empty. Rootless
sessions no longer climb (latent unnamed-tree walk removed).

Dev Opus + QA Sonnet in a dedicated worktree; QA SHIP with one LOW
(pre-existing attribute-instance indexing gap, pinned) and one
recorded asymmetry. Lead-reviewed.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 23:58:22 -07:00
lucioandClaude Fable 5 ad27ed23dc codeAction reads the module's fan-out, not the workspace
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 20s
The owner's slow-F12 root cause: textDocument/codeAction on a module
instantiation read every in-scope file through ws.sources() and ran
the port-refactor engine over them, per cursor move — 3.1-4.6 s on
opentitan's 3 976 files, blocking the single-threaded loop so every
queued definition/hover paid the bill. Workspace::module_sources now
hands the engine the cursor modules' fan-out: declarers (units),
instantiation-edge files, references_to postings (the fourth rung —
edges_of drops owner-less file-scope instantiations, so edges alone
are not a superset), and every open buffer. 4.56 s -> 7.1 ms typical,
83 ms at a 36-file fan-out; equality with the whole-workspace
computation pinned by four dev + six QA equivalence/attack tests.
Disclosed behavior change: the answer now sees the workspace as the
index describes it, like every other index-backed answer.

Also: performance.md (full opentitan benchmark of every LSP action)
committed at the root, and TODO.md gains section 10 tracking the
performance wave the benchmark spawned (rename family, completion,
documentHighlight, scope default) with per-lane file ownership.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 22:35:00 -07:00
lucioandClaude Fable 5 bf9170a850 A scope widen indexes the folders it added, not everything again
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 20s
Every F12 jump into a new folder didOpen-widened the scope and re-ran
a full rescan of all folders accumulated so far, growing with browsing
(opentitan, warm: 120-169 ms per jump, ~90 ms of it re-opening and
decoding the whole persistent store). widen_of chooses: pure folder
adds take a widen scan over only the new files (absorbed into the live
index/candidates/includes, open buffers refreshed from held analyses,
store handle kept, no compaction); anything else still takes the whole
rescan; mid-scan defers to one whole follow-up. Jumps now cost the new
folder alone (12-44 ms flat), first definition of a session 99.7 ->
0.9 ms. IncludeGraph stores edges as the filesystem answered them and
re-spells on relearn so a newly scoped file lends its spelling to
earlier edges. Watcher-coverage narrowing documented: watcher-less
clients lose the widen's incidental disk re-read, same staleness class
as the save path since 2026-08-27. QA was stopped by the owner
mid-gates after its adversarial phases; lead gates run twice, green.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 21:36:55 -07:00
lucioandClaude Fable 5 b7a934080a Release 0.14.0 — the first-hover release
ci / checks (push) Successful in 52s
release / build-and-publish (push) Successful in 4m54s
ci / corpus (push) Successful in 22s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 20:22:30 -07:00
lucioandClaude Fable 5 172a034c67 The startup scan answers requests as it goes
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
A request sent right after initialized waited out the whole startup
scan — 780 ms cold, 287 ms warm over 200 files, against 26-64 us once
the scan was done. The scan is now a value (Scan: begin/step/publish/
finish; rebuild_index_with is the same three-line loop, so one-shot
and interleaved are structurally the same code and fingerprint
identically), fed to the live index with one WorkspaceIndex::absorb
per drain — per-file merging measured quadratic, 11.7 s over 800
files — and the message queue drains between files: the first hover of
a session answers in 15.5 ms cold / 12.8 ms warm against the index so
far, open file first, scan totals inside noise. Order contract kept:
only the startup scan answers mid-way (must_wait holds requests queued
behind any rescan), scans under 64 files stay one-shot (a count, not a
clock), mid-scan rescan requests coalesce into exactly one follow-up,
shutdown stops the scan where it stands. All three tables publish
together. QA pinned the INTERLEAVE_ABOVE boundary, the absorb
duplicate-path edge and the mid-scan didOpen double-publish; the whole
pre-existing suite passes unmodified, stable over repeated runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 20:20:20 -07:00
lucioandClaude Fable 5 20567e1a7f The index carries every declaration's line, and hover stops re-reading files
ci / checks (push) Successful in 40s
ci / corpus (push) Successful in 18s
The owner's first-level cache, realized on the carrier the index
already had: DeclLines (name line + detail line) on every Decl/Def,
computed at index time from the LineIndex the analysis already holds —
tens of KB for 20k modules, FACTS_FORMAT 3->4, old stores discarded
whole. A closed file's hover heading now costs zero I/O (it survives
the file being deleted), and the snippet's one remaining read is
served from a bounded FileView LRU (4 entries / 8 MiB, newest kept,
dropped on set_document/close/update_one/rebuild): repeat hovers into
a 12 MB file go 5.8 ms -> ~1 us, cross-file hover means 40/157 us ->
4.7/12.9 us. Ports ride the same member entries, so their lines came
free. Stale-disk edits leave heading and snippet stale together, the
spells_exactly guard still omits rather than lies, and QA pinned the
pair. Measured and filed, not fixed here: the first request of a
session waits 287-780 ms behind the startup scan (handshake for the
next round).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 18:04:38 -07:00
lucioandClaude Fable 5 17214ac8db Release 0.13.1 — the F12-latency release
ci / checks (push) Successful in 44s
release / build-and-publish (push) Successful in 4m37s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 16:31:47 -07:00
lucioandClaude Fable 5 d4eb8f48ff The stack fits the nesting limit by construction, on every thread
ci / checks (push) Successful in 42s
ci / corpus (push) Successful in 19s
MAX_NESTING_DEPTH turns over-deep input into a parse error only on a
stack big enough to reach level 64, and that was an unenforced README
assumption: debug frames drifted to ~94 KiB/level under rustc 1.97
(worst family nested case, 5.9 MiB at the limit), so a default 2 MiB
spawned thread aborted around level 30 with the limiter never firing.
New vlog_parser::PARSE_STACK_SIZE (16 MiB, 2.7x the re-measured worst
case) is applied at every parse-reaching site: both binaries' work
moved onto named spawned threads (a main stack is the OS's to size —
1 MiB on win32; pre-fix lucisv aborts under ulimit -s 1024, fixed one
diagnoses), rayon pool workers resized, forwarder and lsp-server IO
threads audited parse-free. Deep-nesting suites across four crates on
controlled stacks, sabotage-verified; caller-side stack contract added
to every public parse entry point's rustdoc. analyze measured at
71 KiB on a max-legal tree — no second bound needed.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 16:26:06 -07:00
lucioandClaude Fable 5 cf32e92e58 A rescan reuses what open buffers already analyzed
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 21s
A scope-widening didOpen re-parsed every open buffer's text twice —
once for its index facts, once for its completion words — 210 ms of a
223 ms rescan for one 1.4 MB top.sv. FileFacts::of and words_in each
split so their post-parse half is callable on a finished analysis
(facts_from_analysis, words_of_tokens; one implementation per path, so
the routes cannot drift), and collect_sources hands the index and
candidates builds each open buffer's held analysis instead of its
text, on the whole-rebuild path and didSave's. ~228 ms -> ~23 ms.
Equivalence pinned: encoded facts and fingerprints byte-identical
between the two routes over the corpus and 16 crafted non-corpus
shapes; unsaved-edit, didClose-revert, size-cap and large-file
threshold boundaries tested both directions. IndexEvent::Analyzed
keeps "from cache" meaning the persistent store.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 15:28:27 -07:00
lucioandClaude Fable 5 097498da23 References stop sweeping the whole open buffer per request
The open-document overlay loop in indexed_references did two index
lookups and a scope walk for every reference in every open buffer.
A spelled-name prefilter (sound: every Def is filed under exactly its
own declared name, so a mismatched name can never match the target)
plus a hoisted file_id take a 70k-reference open top from 3.2 ms to
110 us per request, both directions. In-file references and
documentHighlight batch-convert spans through the walker (1.76 ms ->
1.18 ms / 917 us on a 10k-use signal). Answers byte-identical; the
refactor-walk equivalence suite extended with a unit-vs-member
same-spelling case. Measurements also acquitted references of the
owner-reported direction asymmetry: the felt cost is the didOpen
scope-widening rescan re-parsing open buffers (210 of 223 ms), filed
as a Handshake for the next round.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 14:02:15 -07:00
lucioandClaude Opus 5 4f7b4a9f91 Release 0.13.0 — the responsiveness release
ci / checks (push) Successful in 49s
release / build-and-publish (push) Successful in 4m55s
ci / corpus (push) Successful in 21s
Typing no longer reanalyzes the buffer on every keystroke, cursor
answers binary-search the token stream instead of sweeping it, and
hover finally reads an old-style split port the way a designer wrote
it — header and body declaration, each with its comments.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:17:39 -07:00
lucioandClaude Opus 5 574ab833e3 Feature docs for the responsiveness round, and a perf record
Three new feature READMEs — change-debounce, port-detail-spans,
interactive-latency — each with the mandated sections, dev work logs,
QA findings and their dispositions, and the lead's review. Plus
`docs/perf/README.md`, the record of what was measured, on what, on
which machine, and with which command, so a later round can say
whether it made something faster or only different.

`topo.md` is added to the tree: the dependency topology the round was
planned against, with this round's new edges — the `detail_span` and
`symbols_named` handshake between the server and `vlog_semantic`, and
the facts-format edge to index persistence.

The perf record keeps its losses as well as its wins. A keystroke
followed by nothing now publishes at 164 ms rather than one
reanalysis, because it waits out the quiet period; a perf document
that only records improvements is not a perf document.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:54 -07:00
lucioandClaude Opus 5 12d0bbad51 Measure the paths a keystroke and a hover run through
Twelve `#[ignore]`d measurements, standard library only — `Instant`,
a mean over 10 to 1 000 runs and `black_box`, which is the shape this
repo already uses for perf notes. No benchmark dependency: the
workspace pins six direct ones and `CLAUDE.md` wants a written
justification for a seventh, which statistical rigor on numbers that
assert nothing does not earn.

They answer where a flush's time goes, and the answer is that lexing
and parsing are 79% of it. `analyze` is 5.5 ms of 31 ms, the lint pass
4%, and `resolve_external` — the one the plan expected to matter — is
49 µs, one part in six hundred. The breakdown sums to `Document::new`,
so nothing is unaccounted for.

They also take the numbers this round's changes are argued from: the
cost of one read and one `LineIndex` inside a cross-file hover, the
name lookup against the scan it replaced, and the token search against
the sweep it replaced.

Nothing here is a budget. A test that fails when the machine is busy
is a test that gets deleted.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:45 -07:00
lucioandClaude Opus 5 de8a7e129c Cursor answers binary-search the token stream instead of sweeping it
Expand-selection, on-type formatting, the completion scope gates and
the inline template trigger each walked every token in the file to
find the one at the cursor. The stream is sorted by start and does not
overlap, so the position is a binary search: 77 µs → 20 ns in a
10 000-line buffer, and 130 µs → 36 ns for completion's balanced
window, which had no upper bound and so swept the whole file to reach
a window a few dozen tokens wide.

Two primitives rather than one, and deliberately not `token_at`:
`selection.rs`'s `covers` takes `span.end` inclusively, so at a byte
two tokens share, the sweep returned the *earlier* token where
`token_at` returns the later one. Reaching for the existing helper
would have changed an answer.

No answer changes. Each swap is pinned by a test comparing the new
expression against the predicate it replaced at every byte of a buffer
written to be full of touching tokens, and the precondition they all
rest on — that the stream rises and never overlaps — is pinned
separately, so it is the test that fails first if the parser ever
changes shape.

Left alone, with reasons: signature help's paren depth is a function
of every bracket before the cursor and so is inherently a prefix scan;
`pairs.rs` is not a position query; and completion's comment gate
cannot be answered by any search of the stream, because comments are
trivia attached to whichever token happens to be adjacent. That last
one is the remaining per-keystroke whole-buffer walk.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:34 -07:00
lucioandClaude Opus 5 611dd23069 Hover shows a split port's real declaration, and its comments
A non-ANSI port's card used to show `data_in,` — the header line that
names it and says nothing else. It now shows two fenced sections: the
header, then the body declaration carrying the direction, the type and
the width. Go-to-definition offers both, body declaration first, so
hover and the jump agree. It works into closed files, because the
detail span travels through the workspace index.

Each section also carries the comments that document it: the comment
beside the declaration, the comment-only lines above it, and the
comment-only lines below it — all three where all three are written.
The guards are what make this safe rather than a guess. The walk above
stops at the first line that is not comment-only, so a line carrying
another port never contributes its trailing comment. The block below
attaches only when the line after it is one that positively reads as a
closer — a whitelist, deliberately, so that a line the predicate does
not recognise reads as another declaration and the comment stays with
it. Only a false "another declaration is here" is safe: it merely
declines to attach a comment, while a false "nothing here" would print
one declaration's comment on another's card.

Also: a hover into a closed file now reads that file once. The heading
line and the snippet used to take a read and a `LineIndex` each, since
neither shared the other's; a per-request memo keyed on the path
serves both, and `locate::line_number` answers from an open buffer's
existing index rather than re-reading it. On a 31.7 MB file that is
34 ms → 16.3 ms.

And `live_symbol` asks `symbols_named` for the candidates instead of
walking every symbol in the target buffer and calling
`indexed_def_for_symbol` on each.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:23 -07:00
lucioandClaude Opus 5 a4f23db2c7 Typing costs one reanalysis per burst, not one per keystroke
Every `didChange` used to run a full reparse, reanalysis, lint and
diagnostics publish. In a 10 000-line buffer that is 31 ms of work per
keystroke, nearly all of it thrown away by the next one.

The text stays exactly current after every notification — incremental
sync is applied immediately, and while a change is pending the buffer
the server holds *is* the pending text. Only the analysis is deferred,
and it is flushed by the first thing that needs it: the next request,
the next non-`didChange` notification, or a 150 ms quiet-period timer
in the message loop. Requests therefore see exactly what they saw
before; nothing answers from a stale buffer.

The invariant this replaces was "one didChange = one set_document =
one generation bump". It is now one *flush* = one `set_document` per
dirty buffer. The observable consequence is that intermediate
diagnostics states are no longer published, which the e2e test pins:
what is drawn is always a state the buffer really passed through,
there are simply fewer of them.

Closing a buffer drops its pending text before the flush rather than
after it, so a file closed mid-edit is not analyzed and republished
for nobody a line before its squiggles are cleared.

Also measures it over the wire, against the shipped binary: a burst of
ten keystrokes produces one `publishDiagnostics`, counted at the drain
rather than reasoned about. The burst is measured last, because every
`wait_for` accepts any publish and an earlier position would let a
second one be absorbed by the next row's wait and never counted.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:10 -07:00
lucioandClaude Opus 5 d94f9e3de0 Non-ANSI ports carry where their declaration is completed
A port declared the old way is one symbol named in the module header
and finished in the body by `input signed [31:0] data_in;`. The binder
already merged the two; what was missing was a record of *where* the
declaration is completed, so everything reading the symbol saw only
the header's bare `data_in,`.

`Symbol` and the index's `Def` gain `detail_span`, set by the binder
when a body port declaration resolves to a port already declared in
that scope — first writer wins, so a header naming a port twice stays
deterministic and is the linter's to complain about. Old-style task
and function arguments take the same path: the binder performs the
same merge for them, so they are not special-cased.

The persisted facts record grows two numbers per declaration, written
unconditionally so the stream stays flat. `FACTS_FORMAT` moves 2 → 3
because a store written before this cannot be read after it: only the
last declaration in a record is short enough to fail `done()`, and
every earlier one would be read field-shifted by two — a cache handing
back wrong spans, which is the shape the safety invariants exist to
catch. A store from the old format is now discarded whole.

Also: `Semantics::symbols_named`, a name-sorted side table of symbol
ids searched with two `partition_point`s, so looking a name up is a
binary search instead of a walk of every symbol. Stable-sorted, so
symbols sharing a name keep declaration order and the lookup is an
identity against the scan it replaces. A side table rather than a map
keyed by name, because `Semantics` is cloned per document and need not
hold a second copy of every name it already has.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:15:58 -07:00
lucioandClaude Fable 5 94b130aca1 Release 0.12.1 — hover shows the declaration itself
ci / checks (push) Successful in 48s
release / build-and-publish (push) Successful in 5m0s
ci / corpus (push) Successful in 22s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 22:35:56 -07:00
lucioandClaude Fable 5 efe67bde65 Hover shows the cross-file declaration itself, not just where it lives
ci / checks (push) Successful in 48s
ci / corpus (push) Successful in 21s
The Definition::External card now renders the declaration's source
line(s) fenced under the "declared in file:line" heading — direction,
type and width for a port, the header line for a module, the
declaration line for package members. No facts change: snippets are
fetched at hover time, from the live buffer via nav's logical matcher
when the target is open, from disk (what the index was built from)
otherwise. A boundary-checking guard (spells_exactly) drops the
snippet rather than ever showing a wrong line — QA's attack proved
prefix matching alone was forgivable (addr vs addr2) and the fix is
pinned. Caps at 5 lines / 400 chars with notes. 18 new tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 22:32:59 -07:00
lucioandClaude Fable 5 e70d979e51 Release 0.12.0 — the indexed-navigation release
ci / checks (push) Successful in 46s
release / build-and-publish (push) Successful in 4m58s
ci / corpus (push) Successful in 21s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 21:39:02 -07:00
lucioandClaude Fable 5 b2d778eb8d Indexed references: postings replace the per-request refactor walk
textDocument/references now reads declaration-to-occurrence postings
merged in WorkspaceIndex from compact per-file reference facts, with
open buffers overlaying live semantics — 0.062 ms/request over 820
files vs 21.7 ms for the old Workspace::sources() walk (~350x). The
walk stays as rename's engine and the equivalence oracle in tests.
FACTS_FORMAT 1->2 discards v1 caches whole. Cursor lookups
(symbol_at/reference_at/token_at) and macro-define lookup move to
binary-searched sorted tables; include definition inspects only the
cursor's line. Ambiguity refusals preserved throughout.

External dev: codex. Lead-reviewed, gates re-run, probe reproduced.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 21:36:01 -07:00
lucioandClaude Fable 5 27fc216df3 Marketplace page: absolute changelog link — vsce cannot resolve relative
ci / checks (push) Successful in 44s
release / build-and-publish (push) Successful in 4m37s
ci / corpus (push) Successful in 20s
vsce package validates README links and auto-resolves relative ones
only for GitHub/GitLab repositories; the Gitea remote is neither, so
the relative CHANGELOG.md link failed the v0.11.0 release build.
Absolute git.luci.ooo URL instead, the same convention the page's
images already use (the Marketplace's own Changelog tab is unaffected
— it reads the file directly). Reported by the owner from the failed
workflow log.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 19:46:49 -07:00
lucioandClaude Fable 5 4665641e42 Release 0.11.0 — the large-workarea release
ci / checks (push) Successful in 45s
release / build-and-publish (push) Failing after 4m12s
ci / corpus (push) Successful in 20s
Version bump (workspace + extension), the root CHANGELOG section
covering the six rounds (folder scope, incremental index + edge
tables, persistent cache, large-file mode, size cap + counting bar +
output log), the extension changelog's Unreleased flipped to 0.11.0,
and the Marketplace page's release-time pass: the Large workspaces
section drops its coming-soon framing, the stale Workspace
intelligence rows now describe the shipped scope model and counting
bar, and 0.11.0 highlights join the page. The scope-default behavior
change and its one-line migration are called out in the CHANGELOG.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 19:17:31 -07:00
lucioandClaude Fable 5 bc606dd6bd Large-file fast path: 100 MB netlists open in 40 ms
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 21s
Owner-requested round, the last of the large-workarea wave. Above
lucisv.largeFile.threshold (4 MiB default, 0 disables) a buffer opens
as a line index and nothing else — no lex, no parse, no semantics, and
its path removed from the index sources so nothing describes it by
stale disk bytes. Viewport highlighting lexes only the requested
window (snap to a line boundary, budget-bounded backward comment scan,
imperfection documented); semanticTokens/full answers the spec's
cancellation errors because the shipped VS Code binary marks tokens
complete on ANY non-error answer and never asks for ranges again —
settled by reading the bundle, verified independently by QA, pinned
with the client-library citations. Same-file definition/references
shipped on measurement (worst 37 ms vs the 150 ms budget); every
other handler answers as the empty file by construction; formatting
alone says why aloud. Two client facts recorded: VS Code never syncs
files over 50 MB, and above 20 MB our viewport tokens are the only
color.

QA rejected the first cut on the round's true shape — thousands of
tokens on one long line went quadratic through per-call UTF-16
conversion (7.86 s to color one 269 KB line). The fix adds a monotonic
PositionWalker to convert.rs (restart-on-backwards proven load-bearing
by the out-of-order tail-comment shape), adopted at three sites for
546x/759x on the probes — and it fixed ordinary files' semantic
tokens too (2.06 s to 232 ms on a one-line buffer), a cost the normal
path had always paid. Probes are now normally-running gates with 4.5x
margins, walker-vs-per-call equivalence swept over gnarly fixtures
and adversarial ping-pong.

51 tests added across both rounds (dev 43+5, QA 6+3, minus overlaps),
2 ignored probes. Completes the owner's large-workarea requests.

docs/features/large-file-mode/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 18:58:17 -07:00
lucioandClaude Fable 5 5e98b1a669 Marketplace page: the large-workarea wave documented, changelog added
ci / checks (push) Successful in 43s
ci / corpus (push) Successful in 21s
Owner-requested docs round, scoped to editors/vscode. The README's
settings table gains the seven new keys (index.scope/scopeDepth/
maxFileSize/logFiles/persist/cachePath, largeFile.threshold) with
their honest notes — scope-relative answers and the one-line
migration, the cap's open-buffer exemption, viewport-only highlighting
above the threshold — plus the formatOnSave tab-size caveat, and a new
'Large workspaces' section marked as coming in the next release
(nothing claims the wave as shipped; the 0.10.2 highlights and feature
tables stand as released). New editors/vscode/CHANGELOG.md gives the
Marketplace its Changelog tab: an Unreleased section for the wave and
condensed extension-user entries for every release 0.2.0 through
0.10.2, derived from the root changelog. Every setting name verified
against package.json; every claim traced to a feature README (the
claim-by-claim table is in the dev report); the two perf claims
qualified with their build profile by lead review.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 17:47:55 -07:00
lucioandClaude Fable 5 2e258df9a7 vlog_parser: the defines round-trip pieces the cache commit left behind
ci / checks (push) Successful in 41s
ci / corpus (push) Successful in 20s
DefineTable::from_entries and the PartialEq/Eq derives on
Define/DefineTable belong to the index-persistence round (e4b1f55) —
its facts.rs references from_entries — but the lead's explicit-path
staging missed the vlog_parser crate, so e4b1f55 does not build on a
clean checkout. Caught by the next round's dev noticing an uncommitted
change it did not make. The working tree was always green, which is
why every gate passed locally; the remote CI on e4b1f55 is the run
this fixes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 17:25:19 -07:00
lucioandClaude Fable 5 e4b1f55c12 Persistent index cache: a half-indexed workarea resumes where it stopped
ci / checks (push) Failing after 8s
ci / corpus (push) Failing after 5s
Owner-requested round. Every parsed file's FileFacts record is written
through to an index-cache store (append per file, atomic compaction at
scan end — a crash loses at most the file in flight), keyed by a
content hash that is the whole key: no mtime fast path, by measured
argument (6 ms of a 181 ms warm scan, and unsound against save-time
write-through). On reopen, hits skip parsing and the resume is
visible — cached: vs indexing: log lines, the bar counting through
hits, and an end message saying how many came from cache. Warm rescan
322 to 179 ms release, 1.5 s to 0.76 s debug; 910 KB store for the
860-file corpus. Location: lucisv.index.cachePath > the extension's
context.storageUri via initializationOptions (the one extension.js
change) > the OS cache dir keyed by workspace identity > nowhere;
lucisv.index.persist (default on) gates both directions immediately.

The cache is a performance artifact, never a correctness input, and
after the fix round that promise is total against everything but
intentional forgery — which the threat model now formally excludes
(same-user disk; a keyed MAC would be theater): a per-record checksum
drops every corrupt-but-parseable line (poisoned and reforged shapes
both pinned so the checksum is never mistaken for a MAC), first-writer
initialization is a create_new claim with structural 100/100 survival,
and a torn multi-byte tail costs exactly the torn record (0 of 583
offsets lose more). Old-format stores discard wholesale. Load==fresh
fingerprint equality swept over the corpus.

45 tests added across the main and fix rounds (dev 33+2, QA 9+3, one
QA test-construction bug self-caught), 2 ignored probes.

docs/features/index-persistence/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 16:33:52 -07:00
lucioandClaude Fable 5 5e4aa7bd6f Incremental indexing + the edge tables: one file changed, one file merged
Owner-requested round. WorkspaceIndex::update_file/remove_file replace
one file's contribution without reading or parsing anything else;
Server::reindex_one takes the fast path for a didSave of one held file
or a one-file watcher event (33 ms vs 1.5 s on the corpus, 45x), with
everything else — settings, scope, filelist, multi-file events —
keeping the full rebuild, pinned by a trigger-table test. FileIds stay
sorted positions by deliberate deviation: renumbering through the one
merge both finish and update_file end in makes build(W) byte-identical
to build(W minus F).update_file(F) — fingerprint equality, attacked by
QA across long interleaved sequences, disambiguation flips, define
shadowing and the ghost hunt (the affected-keys union reads old and
new records both). The per-file FileFacts the index retains are the
documented memory cost (~1.4 MB on the corpus).

The two oldest filed Handshakes land: instantiation and inheritance
edge tables, built by the byte-for-byte moved census walks, turn
codeLens counts (92 ms to 0.26 ms), incomingCalls and typeHierarchy
subtypes into lookups — census policies pinned unchanged at both the
consumers and now the source. Counts are as of the index, not of
unsaved keystrokes: the freshness delta is documented and pinned from
both sides. Saves no longer raise a progress bar; generation and lens
refresh still ride. Round 18's three inherited scope obligations are
pinned permanent.

36 tests added (dev 27 + QA 9). Left open, filed: wholesale republish,
Candidates re-derivation cost, incremental removal vs include
re-resolution.

docs/features/incremental-index/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 14:35:27 -07:00
lucioandClaude Fable 5 7266b13702 Index scope: open-file-first, folder-scoped by default
Owner-requested round. The scope ladder: a filelist still defines the
whole project and outranks everything; lucisv.index.scope=workspace
restores the walk-the-roots behavior (the same function, not an
equal-output one — pinned); the new default walks only the union of
folders a buffer has been opened from, each raised
lucisv.index.scopeDepth ancestor levels (default 0), clamped at the
deepest containing root. Opening a file outside the scope widens it
and reindexes through the existing progress/generation machinery;
scope grows only along the open axis within a session. Cross-file
answers are scope-relative and the docs say so loudly, with the
one-line migration in the setting description.

The round also closes indexing-ux QA's MEDIUM builder footgun:
IndexBuilder::finish now sorts and dedups before assigning FileIds, so
no insertion order can reach the result — pinned by a permanent
three-order fingerprint test — which makes feeding open files first
provably a progress nicety. 151 existing tests swept mechanically
(QA sampled 40+ sites: constructor swaps only); lead fixed the one
vacuous tail QA found plus two premise/comment hygiene items.

19 tests added. Known deltas documented: a root's .gitignore does not
reach a walk starting below it (filed against lucisv_core); rootless
depth-0 keeps its flat read; startup index is empty until the first
didOpen.

docs/features/index-scope/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 13:12:27 -07:00
lucioandClaude Fable 5 8c8cfc538e Indexing UX for large workareas: size cap, counting bar, output log
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 21s
Owner-requested round. lucisv.index.maxFileSize (default 1 MiB, 0
disables, junk values fall back to the default — misparse must never
un-cap) skips walked files at one fs::metadata call before any read;
open buffers are always served uncapped, a cap change rescans like
exclude does, and the cap reads consistently through every sources()
consumer — documented per consumer, with the write-path warning gap
(a rename silently leaving a capped file stale) filed as a follow-up.

The indexing bar now counts: $/progress reports '137/860 path' with a
monotonic percentage over the post-exclude post-cap denominator,
throttled to ≤1000 reports per rescan with the last file always
reporting. Enabled by vlog_semantic's new IndexBuilder (add_file/
finish) with build() redefined as the loop over the newly-exported
index_order — the FileId ordering rule is now a call, not a comment.
QA proved both production callers order correctly; hardening the
builder against out-of-order future callers is round 18's acceptance
test. lucisv.index.logFiles (default on) streams 'indexing: path' and
cap-skip lines to the editor's Output panel at LOG level; the skip
count survives in the end message when logging is off. Measured
overhead ≈2.6% on the 860-file corpus; 0 corpus files exceed 1 MiB
and the default-capped index is pinned identical to uncapped.

21 tests added + QA's attack set + the lead's human_size boundary fix
('1024.0 KiB' can no longer be printed for a byte short of a MiB).

docs/features/indexing-ux/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 11:56:30 -07:00
lucioandClaude Fable 5 8d070a4277 Release 0.10.2 — the all-platforms package
ci / checks (push) Successful in 43s
release / build-and-publish (push) Successful in 4m11s
ci / corpus (push) Successful in 19s
Version bump across the four files, the extension page's version
strings, and the changelog: the seventh .vsix carrying every platform's
binaries chosen at runtime, the consolidated seven-package release
flow, and the Marketplace-grade extension page.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 02:09:49 -07:00
lucioandClaude Fable 5 64d6e9a55d Marketplace-grade extension page, reviewed and corrected
The editor-marketplace-page round's rewrite of the extension README and
manifest (icon, banner, keywords, capability matrix, PNG artwork with
SVG sources kept out of the package), landed with three lead-review
corrections: the nonexistent lucisv.dev homepage now points at the
repository, the install table regains the universal no-binary fallback
the rewrite dropped, and Troubleshooting documents the duplicate-hover
trap of the pre-rename vfmt extension left installed next to lucisv.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 02:03:17 -07:00
lucioandClaude Fable 5 cebb333bd7 All-platforms VSIX + the release flow consolidated in one script
A 7th package, lucisv-<v>-all.vsix, carries every platform's binary
pair under bin/<platform>-<arch>/ and the extension picks the right one
at runtime — flat bin/ (platform package) first, then the platform-arch
subdirectory, then PATH. Target-less on purpose, so Alpine and anything
else vsce refuses to name gets working static binaries. The release.yml
inline prune step moves into tools/prune_release_assets.sh, which now
requires all seven packages by name before anything is published.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 02:03:10 -07:00
lucioandClaude Fable 5 0a93143bfb Release 0.10.1 — platform packages for the VS Code extension
ci / checks (push) Successful in 42s
release / build-and-publish (push) Successful in 4m12s
ci / corpus (push) Successful in 19s
Version bump across the four files (package-lock.json's two spots had
drifted since 0.7.2 and are trued up here) and the changelog section:
five platform-specific .vsix packages with the binaries embedded, and a
release page that ships exactly those packages plus the universal
fallback.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 01:17:02 -07:00
lucioandClaude Fable 5 ec65e0831f CI release publishes the six extension packages only
ci / checks (push) Successful in 43s
ci / corpus (push) Successful in 20s
Owner decision: the release page carries the .vsix packages (each
platform package checked by name — a missing one fails the release —
plus the universal fallback) and SHA256SUMS, nothing else. The loose
binaries are still built and audited on the runner, since the packages
embed them, but no longer attached; standalone binaries are a cargo
build away. The new workflow step prunes dist/ after the audit and
filters SHA256SUMS to the packages, keeping the audited hashes, then
re-verifies. Prune logic tested against the real 0.10.0 dist with a
missing-package negative control; docs trued up in RELEASING.md, the
top-level README and both feature READMEs.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 01:07:34 -07:00
lucioandClaude Fable 5 a399f81ad9 Platform-specific VSIXs: five packages with the binaries inside
ci / checks (push) Successful in 41s
ci / corpus (push) Successful in 19s
release.sh --cross now cuts a .vsix per platform — darwin-arm64,
darwin-x64, linux-x64, linux-arm64 (new aarch64-musl cross target),
win32-x64 — each carrying lucisv and lucisv-server under bin/, staged
transiently with an EXIT trap and content-asserted with unzip. The
extension resolves a user-set lucisv.serverPath, then the bundled
server (chmod'ed on activation; VSIX extraction drops the exec bit),
then PATH; the universal no-binary .vsix stays as the fallback. The
host package's embedded server is smoke-tested out of the zip on every
release. docs/features/editor-platform-vsix has the full round.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 00:55:53 -07:00
lucioandClaude Fable 5 20ad318d4e file_ops: the corpus fan-out test skips without corpus/, like its siblings
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 23s
The round-14 QA probe asserted the corpus's presence instead of
following the house convention, so any checkout that never fetched
corpus/ — a bare CI runner, act — panicked instead of skipping.
Reported by the owner from an act run. Swept the workspace for other
unguarded corpus asserts: every remaining one either guards with the
skip or lives inside an #[ignore]d perf probe.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 00:24:44 -07:00
lucioandClaude Fable 5 7cd439f500 Release 0.10.0 — the audit-complete release
ci / checks (push) Failing after 44s
release / build-and-publish (push) Successful in 4m24s
ci / corpus (push) Successful in 23s
Version bump (workspace + extension) and the CHANGELOG section
covering §9c and the two cross-crate rounds: typeDefinition, the
overlay promotion, the ANSI first-port parser fix, linkedEditing,
codeLens, onTypeFormatting, typeHierarchy, file operations,
workspace folders + configuration pull, and rangesFormatting. This
completes the LSP 3.18 audit's feature work (TODO.md §9).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 00:15:30 -07:00
lucioandClaude Fable 5 c47b16a65e LSP §9c: 3.18 extras — rangesFormatting ships, two honest parkings
ci / checks (push) Failing after 41s
ci / corpus (push) Successful in 29s
textDocument/rangesFormatting: the engine took multi-range LineRanges
natively (this is literally the CLI's --lines a-b,c-d call), so the
server adapter is map(lines_of) around it and the verified
all-or-nothing contract rides through whole. range_formatting is now
DEFINED as the one-element case, making refusal equality structural;
lines_of extracted with its own test, plus a latent debug-overflow fix
(end.line + 1 at u32::MAX -> saturating, proven by deliberate
breakage). The capability widens documentRangeFormattingProvider from
true to {rangesSupport: true} only for clients that asked (read from
the raw initialize params; lsp-types 0.97 spells neither half) — every
pre-round client sees a byte-identical initialize result, proven on
the wire. The round's discovery: vscode-languageclient 9.0.1 has been
sending rangesSupport and gating its multi-range provider on our
answer all along — the bare boolean was turning the feature off.

SnippetTextEdit and workspace/textDocumentContent are parked with
evidence: absent from lsp-types 0.97 and from the pinned client's
node_modules (a snippet edit sent today would write literal ${1:...}
into the buffer), and the thin extension deliberately has no content
provider. Each parking carries a one-grep re-check trigger. The
whole-document reply shape is kept: splitting per-range would claim
byte ownership the engine never verified.

24 tests added; QA re-ran every evidence grep, verified the client
citations against formatting.js, and closed with zero findings. This
completes TODO.md §9c and the LSP 3.18 audit's feature work.

docs/features/lsp-318-extras/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 00:13:43 -07:00
lucioandClaude Fable 5 17fb2129db LSP §9c: didChangeWorkspaceFolders + server-pull configuration
ci / checks (push) Failing after 42s
ci / corpus (push) Successful in 21s
Folders: workspace.workspaceFolders advertised with change
notifications; added/removed folders adjust the root set through one
8-line Workspace::change_roots (removals first, dedup, did-it-move
bool) and one reindex per moving notification — progress bar, code-
lens refresh and diagnostics generation all ride along, pinned. Open
buffers in a removed folder keep today's rootless conventions with no
new code. The source watcher's base-less glob needs no re-
registration; the absolute-path filelist watcher re-registers through
the same before/after comparison the settings push already ran.

Configuration: clients advertising workspace.configuration get one
pull at startup and one per empty didChangeConfiguration; the answer
funnels through the same parser and applier as the push, so the two
doors cannot drift, and every malformed answer shape lands on
defaults, silently. The outstanding-request routing refactored to one
Pending enum map — applyEdit's shipped behavior re-proven under
three-way out-of-order interleaving. Push-with-payload stays the
unchanged legacy path.

38 tests added (dev 27 + QA 11, closing every claim that lacked one:
roots.first() reordering, last-root-removed totality, double pulls,
stale answers, the pull-answer-moves-the-filelist chain, rootless-
gains-first-folder). QA's F1 — a subfolder added as its own root is
its own root, outside the parent's exclude — accepted as the per-root
model and documented in Assumptions.

docs/features/folders-and-config/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 23:33:17 -07:00
lucioandGPT 5.6 Sol 8dc8f6489f docs: clarify lucisv project description
ci / checks (push) Failing after 47s
ci / corpus (push) Successful in 24s
Co-Authored-By: GPT 5.6 Sol <[email protected]>
2026-08-26 22:42:37 -07:00
lucioandClaude Fable 5 33d2f2814f LSP §9c: workspace file operations — renames rewrite includes
workspace/willRenameFiles rewrites every `include whose RESOLVED
target is a renamed file — never a name match — sweeping sources() so
unopened files count and open buffers contribute unsaved text.
Rewrites preserve the include's form where the new location allows
(bare stays bare in-dir; otherwise the shortest suffix that resolves
under the rungs that form uses; ../ last; absolute stays absolute), a
still-resolving include gets no edit, and an unrewritable one is left
untouched with a warning rather than given an invented path.
Directory renames ride the same prefix mapping for free, and the
mirror case — the including file itself moving breaks its own-dir
rung — ships with the same machinery. didRenameFiles/didDeleteFiles
nudge the index through the watcher's own predicate.

Three checks guard the write path: the edit range is the path token
minus delimiters by construction; the rewritten line re-scans and
re-lexes to exactly one include of the same form; and the rewritten
path must resolve_as_if to exactly the new location against the
post-rename filesystem — with every edit addressed to the PRE-rename
uri, the spec detail a client silently drops edits over, pinned on
the wire by QA. QA's corpus probe (a real ibex header, 87 real
includers) caught the round's one real bug — unnormalized includer
paths turning same-directory renames into false warnings — fixed with
one normalize. Batch renames do not compound; recorded as a
documented choice bounded by the safety net.

42 tests added (dev 33 + QA 9). verify.rs untouched.

docs/features/file-operations/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 22:35:37 -07:00
lucioandClaude Fable 5 203e9b1a4f LSP §9c: type hierarchy over extends
textDocument/prepareTypeHierarchy + typeHierarchy/supertypes/subtypes
for SystemVerilog classes. Supertypes is one computed offset into the
existing resolution machinery — the overlay promotion made cross-file
bare class names answerable, and the offset is the LAST byte of the
extends name span so pkg::base lands in the tail's reference, never
the package's. Subtypes is a workspace census on the callers_of_each
pattern (one sources() pass, prefilter, deterministic sort), matching
the base name as written — 0 of the corpus's 270 extends clauses are
qualified, and the asymmetry with supertypes is documented and pinned
from both directions, including the same-name/different-file
consequence. Ambiguous bases answer every declaration, like
definition. Modules stay on callHierarchy by scope ruling.

lsp-types 0.97 has no server-side typeHierarchyProvider field, so
initialize_value() inserts the one key into the serialized result —
QA's strip-and-compare test proves every other key survives with
identical values. QA also traced the parser to show the degenerate
extends spans the code guards against cannot be constructed, corrected
two README figures the lead applied (the 309 extends count did not
reproduce; 270 does), and pinned the generate-block walk gap as a
scoped choice. Interface classes stay blocked on the parser, pinned.

45 tests added (dev 33 + QA 12), including the real ibex UVM chain
and a 10-deep expansion. The inheritance-edge index want is filed
beside the instantiation-edge Handshake as one future round.

docs/features/type-hierarchy/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 21:35:36 -07:00
lucioandClaude Fable 5 839a28ec8d vlog_parser: a direction-less first ANSI port parses
IEEE 1800 §23.2.2.2 allows an ANSI header's first port to carry no
direction — the normal spelling for interface ports — but
parse_port_list classified any leading identifier as a non-ANSI list
and errored on what followed. One clause fixes it: a leading Ident is
ANSI when the parser's existing type-then-name lookahead
(at_typed_declarator, which already walks pkg:: chains, #() overrides
and packed dims) or the new 4-token modport lookahead (ident.ident
ident) says so; the complement is exactly the old non-ANSI list, and
macro-led lists never enter the clause. bus_if.mp was a second,
independent gap (it parsed in no position before) and is glued into
DataType::name the way pkg::t already was. No AST change — the new
ports are AnsiPort { dir: None }, the shape later ports always had.
Two match-widenings ride along: bind_data_type and type_def's
type_span read the pre-dot half as the type, and the modport half is
bindable by nothing — pinned for rename by QA.

The safety case, established twice (dev, then QA independently via a
worktree build): corpus 813/820 both sides, TSVs byte-identical, and
all 820 formatted outputs SHA-256-identical across the change; zero
snapshot churn; verify.rs untouched. QA's boundary AST-diff harness
(~20 shapes at the classification edge) and a 50-file
direction-stripping fuzz sweep found no misfire. The
previously-blocked fixtures flipped to first-port order; instantiate
now plans interface-typed port lists instead of refusing. The two
remaining unsupported shapes (generic interface ports, virtual
modport declarations) are pinned by a lead-added test so a future
round changes them on purpose.

24 tests added (dev 21 + QA 2 + lead 1).

docs/features/ansi-first-port/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 20:49:16 -07:00
lucioandGPT 5.6 Sol 662e323802 docs: add static lucisv documentation site
Co-Authored-By: GPT 5.6 Sol <[email protected]>
2026-08-26 20:31:44 -07:00
lucioandClaude Fable 5 0e740d77ec vlog_semantic: type-position misses reach the workspace overlay
Delivers the Handshake docs/features/type-definition/README.md filed:
an unqualified lexical miss written where a TYPE goes — bus_if bus;,
my_cls h;, a cross-file typedef — now carries its bare name to the
workspace overlay (last, so imports still win), in both spellings:
ExternalCandidate, and InheritedCandidate inside extending classes,
whose base and count (7,841, bit-identical) are untouched. The
mechanism is a new Target::Type emitted only by bind_data_type's
unqualified arm; value-position identifiers, disable labels and
redeclarations keep their pre-round Target::Lexical behavior — NotFound
stays NotFound, and rename keeps refusing them.

That value/type split is the round's story: QA rejected the first cut
with a kept repro proving a value-position typo could rename an
unrelated same-named module cross-file (write-by-coincidence,
pre-round refused), and disproved the work log's exposure claim
against the pre-round source. The fix is a four-line behavior delta;
QA re-killed the regression from three angles and reproduced every
corpus figure to the digit. Result over the 860-file corpus: NotFound
1,418 -> 1,256, 418 clean-file references gained a jump target, none
lost one, 141 coincidence-answers deliberately given back.

The server's stopgap is deleted whole: type_def.rs::indexed_type,
qualifier guard included — all 45 type-definition tests green
unchanged, and cross-file interface rename from a type window is newly
possible and pinned. Corpus formatter results byte-identical (813/820
both trees). New docs/features/overlay-promotion/README.md; the
vlog-semantic and workspace-index tables re-measured (the committed
baselines had gone stale several rounds ago; both READMEs now carry
the three-state table).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 19:56:55 -07:00
lucioandClaude Fable 5 3bc61f9eab LSP §9c: textDocument/onTypeFormatting — two triggers, one engine
';' range-formats exactly the finished statement's line through the
existing verified all-or-nothing engine — no new formatting authority,
gated on one lexer fact (the token ending at the offset is a real ';',
so string/comment/macro semicolons decline). '\n' re-indents only the
line the newline opened, via a token-stream nesting model whose edit is
confined by construction to that line's leading whitespace — a model
bug can be a wrong indent, never a moved byte. The path never speaks:
no popups on refusal (it fires per keystroke), and the config warning
is deliberately not raised here — its dedup re-arms on the didChange
every keystroke produces, so it would fire per character; pinned in
both directions (silent on keystrokes, still warning on requests).

The nesting model was derived against the formatter itself: a corpus
anchor test (77,528 lines answered, 67.9% coverage floor, 0
disagreements) forced nine of its ten rules and caught a real
unconditional-pop bug mid-round. The anchor stays a normally-running
test by lead ruling — it is the correctness gate over the one piece of
formatting logic outside the verified engine.

49 tests added (dev 43 + QA 6: CRLF confinement, mixed tab/space,
macro-body and EOF semicolons, format-off fence riding through,
whole-file ifdef). verify.rs untouched; formatter suites untouched and
green.

docs/features/on-type-formatting/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 17:54:37 -07:00
lucioandClaude Fable 5 01c76067e8 LSP §9c: textDocument/codeLens — instantiation counts that jump
One lens per module and interface declaration: 'no/1/N instantiations',
counting instantiation sites workspace-wide through the one census the
server has — hierarchy.rs's walk, refactored so the batch is the
primitive (callers_of_each over one sources() pass; incoming is now a
one-element batch, behavior byte-identical, amortization pinned by a
corpus ratio test that fails if it goes linear). Clicking runs
lucisv.showInstantiations through the existing executeCommand path,
answering the site locations and pushing window/showDocument (first
site, takeFocus, selection) when the client can take it; the zero-count
lens is display-only. workspace/codeLens/refresh rides each reindex
after the progress bar comes down, capability-gated, once per rescan.

42 tests added (dev 33 + QA 9): count agreement with incomingCalls,
the absolute census policies pinned at the lens layer (multi-instance
statements are one site, textual recursion, both ifdef arms, name
collisions), one-sources()-read-per-request, showDocument/applyEdit
response independence, and grep-derived ground truth on a real corpus
file. The instantiation-edge-table request is now a concrete
vlog_semantic Handshake — two features pay the walk it would delete.

docs/features/code-lens/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 16:41:34 -07:00
lucioandClaude Fable 5 34938fbcf1 LSP §9c: textDocument/linkedEditingRange
SystemVerilog's closing labels now edit as one: module/interface,
package, class, function, task, clocking, generate and statement
blocks, fork/join, and the prefix-labeled b : begin ... end : b form —
every pair read off the AST's own end_label_span fields (the parser
already recorded both halves on one node; no parser change). A pair is
offered only when both halves exist and hold identical plain-identifier
text: mismatched labels, absent labels, and escaped identifiers all
answer null rather than link something a keystroke would corrupt. The
response carries the SV word pattern (with $), whose anchoring QA
verified against VS Code's linked-editing source — full-string
validation, anchors correct.

33 tests added (dev 25 + QA 8): exact-range decoding through the
server's own position converter (never the colon), the both-labels and
stray-second-end tolerant-parse shapes, identically-named nested
blocks pinned by exact ranges, and an 83k-offset corpus sweep
asserting totality and the identical-text/non-overlap invariants over
real labeled RTL. program/property/sequence/covergroup are filed as
parser Handshake wants.

docs/features/linked-editing/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 15:59:13 -07:00
lucioandClaude Fable 5 5d0725c158 LSP §9c: textDocument/typeDefinition
From a name to its type's declaration: variable to typedef/enum/struct,
handle to class, instance name to module, interface signal to
interface. The whole feature is one redirection — find where the
declaration wrote its type name (the same window vlog_semantic's binder
searched), then run nav::definition there — so cross-file resolution,
ambiguity, and position conversion are F12's, unchanged. One hop on
typedef aliases, never a chain; built-ins answer empty.

One stopgap with a three-condition fence: vlog_semantic reports an
unqualified lexical miss as NotFound — or InheritedCandidate inside any
extending class, the UVM norm — without consulting the workspace
overlay, so indexed_type asks the index directly for file-scope
Module/Class/Typedef declarations only, never for a qualified member
(the lead-added guard: a pkg:: qualifier must not be discarded into a
bare-name sweep — proven by deliberate breakage). The Handshake filed
in the README covers promoting both miss spellings so the whole
fallback deletes when vlog_semantic lands it. Also filed: the parser
gap where an ANSI header's direction-less first port fails to parse.

QA rejected the first cut — the corpus sweep found the
InheritedCandidate miss live on ibex DV files — and the fix round
answered with a one-pattern widening whose safety was derived from
three independent vlog_semantic citations. 45 unit tests + 1 e2e; the
corpus spot-check now asserts two real UVM-shaped jumps positively.

docs/features/type-definition/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 15:28:23 -07:00
845 changed files with 293143 additions and 26174 deletions

No files matched your search

+20 -4
View File
@@ -1,9 +1,15 @@
# Release: pushing a tag `vX.Y.Z` builds every distribution artifact and
# publishes a Gitea release with the CHANGELOG section for that version as
# its notes. The artifact set is exactly what tools/release.sh --cross
# produces: host (Apple Silicon) + x86_64 macOS + static-musl Linux +
# RHEL 8-compatible linux-gnu + Windows binaries for both lucisv and
# lucisv-server, the platform-independent .vsix, and SHA256SUMS.
# its notes. What the release page carries is the seven .vsix packages —
# the universal one, the five (darwin-arm64/darwin-x64/linux-x64/
# linux-arm64/win32-x64) with the lucisv + lucisv-server binaries embedded,
# and the all-platforms one carrying every pair at once — plus SHA256SUMS.
# Every package is a must: a missing one fails the release, by name
# (tools/prune_release_assets.sh). The loose binaries are still built for
# every target
# (the packages are made from them) and still audited, but they are not
# attached: anyone who wants a standalone binary builds it with
# `cargo build --release` (docs/features/editor-platform-vsix).
#
# The release fails, deliberately, when the tag does not match the
# workspace version or CHANGELOG.md has no section for it: every release
@@ -30,9 +36,19 @@ jobs:
echo "tag $GITHUB_REF_NAME does not match crate version $v" >&2
exit 1
}
# The release page ships extension packages only: all seven checked by
# name, SHA256SUMS filtered down to them and re-verified, the loose
# binaries (needed to build and audit the packages) dropped.
- name: Keep only the extension packages
run: tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"
- name: Extract the release notes from CHANGELOG.md
run: tools/release_notes.sh "${GITHUB_REF_NAME#v}" > dist/RELEASE_NOTES.md
# LUCISV_API_URL is an optional repository Actions variable naming a
# direct http://host:port for the Gitea API, so the uploads do not go
# through Cloudflare's 100-second origin timeout (0.29.0 and 0.30.0
# both died there with a 524). Unset, the public URL is used.
- name: Create the release and attach the artifacts
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
LUCISV_API_URL: ${{ vars.LUCISV_API_URL }}
run: tools/publish_release.sh "$GITHUB_REF_NAME" dist
+3
View File
@@ -5,3 +5,6 @@
/.lucisv_cache
/.score-results.tsv
.DS_Store
/.zcode
/.claude
__pycache__/
+1816
View File
File diff suppressed because it is too large. Load diff
+97
View File
@@ -29,6 +29,54 @@ doing anything.
- Match the style of the surrounding code (comment density, naming,
module layout).
## File and function size
Files and functions are sized for a human reader, not a compiler.
- **Target 300–600 production lines per file.** At 800, consider
splitting. Above 1,200, an explicit reason not to split goes in the
feature README. Test lines do not count, but a `#[cfg(test)]` block
that dwarfs its file moves to its own module or `tests/` file.
- **Functions: 10–50 lines.** Investigate anything over 80; anything
over 150 needs a reason in a comment (a dispatch table over an enum
is the usual one).
- Looser for declarative tables, generated code, snapshots and
repetitive tests. Complexity matters more than the count: 800 lines
of grammar productions read more easily than 250 lines of state.
- **The real test is one sentence.** A human should be able to say what
a file is responsible for in one sentence and predict which parts a
change touches. Several "and" clauses mean the file wants to be
several modules.
- A split is a **pure move**: public paths stay the same (re-export from
the old `mod`), behaviour and output stay byte-identical, the test
count does not drop. Measured, not asserted — the corpus and
opentitan byte-identity gates are the proof.
Measured 2026-09-02 (production lines): `vlog_parser/src/parser.rs`
8 786, `vlog_formatter/src/format.rs` 5 444, `vlog_parser/src/ast.rs`
3 313, `lucisv_server/src/server.rs` 2 559 (+6 300 test),
`vlog_semantic/src/bind.rs` 2 378, `vlog_semantic/src/workspace.rs`
1 975, `vlog_refactor/src/ports.rs` 1 778,
`lucisv_server/src/completion.rs` 1 716 — thirteen files over 800.
Every one of them was where feature lanes collided, which is the other
reason to split them. **Decomposed the same day by TODO §28** (four
lanes, pure moves, output byte-identical): `parser/` (19 modules) and
`ast/` (8), `format/` (15), `server/` (11 + tests) and `completion/`
(6), `bind/` (8), `workspace/` (5), `ports/` (6), `rename/` (4). Measured
after the round (non-blank, non-comment, outside tests): two files over
600 — `lucisv_server/src/perf.rs` 895 (one cohesive subsystem; the reason
is in the decomposition-server README) and `vlog_parser/src/lexer.rs`
762 — and 183 under it. Nothing new may push a file back over the
thresholds: a dev adding to a file near 600 puts the code in a new
module.
Re-measured 2026-09-07 at 0.49.0 (same rule, before `mod tests`): four
files over 600 — `lucisv_server/src/state.rs` 958 (grew across §37–§49;
a decomposition is filed as TODO §55: scope/widen, the document store,
the source selectors are three sentences), `perf.rs` 900 (reasoned),
`lexer.rs` 763, `vlog_formatter/src/format/stmt.rs` 604 (at the mark; the
next statement arm goes in a new module) — and everything else under it.
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
@@ -86,3 +134,52 @@ Rules:
(`cargo test -p vlog_formatter`).
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
## Runaway guard (never run a suite or sweep bare)
On 2026-09-03 a background test run consumed 100 GB and crashed the
machine. macOS enforces no memory cap, so the cap is ours:
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
process tree when its resident set or wall clock exceeds the limits
(defaults 8 GB / 30 min).
- **Every `cargo test`, every fuzzer, every corpus or opentitan sweep,
and every `lucisv`/`lucisv-server` run over a tree goes through
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
their features do not collide in `docs/topo.md`: no shared edge between them
(no `──▶`, no `◀──▶`, and neither touching the same open handshake in
§2.9), and disjoint file sets. `docs/topo.md` is the authority; if the
collision question is not answerable from it, the features are not
proven independent and run serially. Rules for a parallel wave:
- **The lead plans the lanes** before anything is dispatched: one brief
per lane with an explicit file-ownership list. That list is the merge
contract — a lane touches nothing outside it. A needed change to a
file the other lane owns (or to any unlisted file) is a Handshake
request in the lane's README plus a flag in its report, never a
silent edit; the lead rules on it at merge.
- **Each lane works in its own git worktree** branched from the same
trunk commit. Never two agents in one tree. Trunk stays untouched
while lanes are in flight; the lead merges each lane back only after
that lane's QA verdict and lead review, and re-runs the full gates on
the merged tree before pushing.
- **Roles per lane are unchanged**: one dev (Opus), then one QA
(Sonnet) in the same worktree, then the lead's review — so at most
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
its own dev is done. A QA rework loops inside its lane without
blocking the other lane.
- **Tracking lives in `TODO.md`**: the lead writes the wave's section
(one subsection per lane, each item naming its files) on trunk before
branching; each lane ticks only its own lines. Shared-by-nature files
(`TODO.md`, `docs/perf/README.md`) may be appended to by both lanes
in their own sections — the lead resolves the trivially-parallel
merge; anything worse than trivially-parallel means the lanes were
not actually independent, which is a planning failure to record.
- After merging, the lead updates `docs/topo.md` for any edge a lane added
or amended, so the next wave plans against reality.
Generated
+24 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.9.0"
version = "0.56.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,25 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.9.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.9.0"
version = "0.56.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,15 +262,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.9.0"
version = "0.56.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.9.0"
version = "0.56.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
@@ -264,19 +279,20 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.9.0"
version = "0.56.0"
[[package]]
name = "vlog_refactor"
version = "0.9.0"
version = "0.56.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
]
[[package]]
name = "vlog_semantic"
version = "0.9.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.9.0"
version = "0.56.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+447 -95
View File
@@ -1,6 +1,12 @@
# lucisv — Language Utility for Coding In SystemVerilog
A Verilog/SystemVerilog formatter and linter in Rust.
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
Start with the [repository analysis](docs/repository-analysis.md) for a code-based
assessment and [dependency topology](docs/topo.md) for interfaces and change
impact. The [documentation site source](docs/site/README.md) contains usage
guides and references; [CHANGELOG.md](CHANGELOG.md) records releases, and
[TODO.md](TODO.md) tracks work in progress.
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
@@ -80,10 +86,9 @@ run over an unchanged tree skips them: the summary says `N files from cache`,
and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
thread count, where parallelism has already taken the easy win).
An entry is keyed on **(content hash, `line-length`, `indent`, lucisv version)**
per file, and only ever records the *already formatted* verdict — a file that
would be reformatted, or that failed, is re-checked on every run, so
`--check`'s exit codes and `--diff`'s output never go stale. The store is one
An entry is keyed on **(content hash, `line-length`, `indent`,
`uvm-utils-indent`, lucisv version)** per file, and only ever records the *already formatted* verdict — a file that
would be reformatted, or that failed, is re-checked on every run. The store is one
text file in `.lucisv_cache/` (self-ignoring, like cargo's `target/`); deleting
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
neither reads nor writes it, and `--cache-dir <PATH>` puts it elsewhere (the
@@ -91,6 +96,10 @@ default is relative to the current directory). Content hashing is 64-bit
FNV-1a and a lookup never crosses files; `docs/features/format-cache/README.md`
states the collision posture, the semantics table and the concurrency story.
(In v0.49.0 only, `uvm-utils-indent` was missing from this key, so a cached
clean verdict survived a toggle of the option — fixed in 0.50.0; a 0.49.0
store is simply rebuilt.)
### Ignore files
While walking a directory, lucisv reads a `.gitignore` in every directory it
@@ -106,6 +115,12 @@ trailing `/` (matches directories only), and `!` negation. **Not** supported:
git's "already-tracked files are never ignored" rule. See
`docs/features/parallel-files/README.md` for the exact subset.
Directory walks enter each directory once by identity, so symlink cycles
terminate. Inputs resolving to one canonical file path are processed once.
Unreadable directories or `.gitignore` files and dangling source links found
during a walk warn on stderr and are skipped without changing the exit code;
a missing explicitly named input is still an error.
## Configuration
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
@@ -128,6 +143,10 @@ line-length = 100 # 40..400, same as --line-length
indent = 2 # 1..8, same as --indent
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
[lint]
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
ignore = ["module-filename"] # removed after selection
```
`filelist` names the project's sources the way the rest of the EDA world
@@ -154,10 +173,16 @@ error (exit 2) and nothing is processed. Details:
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
with a file that sets only `line-length` uses both). `exclude` is the
exception: config patterns are *added* to `--exclude`, not replaced by it.
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
off by default, indents the `` `uvm_field_* `` macros written between
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
formatting choice lucisv leaves to the project, because it changes bytes
in existing UVM code (21 of the 860 corpus files).
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
supported subset (tables, multi-line arrays, string escapes) is a hard error
naming the file and line — exit 2, with nothing written. This is deliberate:
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
arrays, unsupported string escapes) is a hard error naming the file and
line — exit 2, with nothing written. This is deliberate:
a silently ignored `line_length` typo costs more than a strict parser does.
## Linting
@@ -167,11 +192,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same
`lucisv.toml` discovery.
```bash
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
lucisv check rtl/ # FILE:LINE:COL: severity: message [rule]
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
lucisv check --ignore module-filename rtl/ # everything but these
lucisv check --select error rtl/ # a whole severity class, by name
lucisv check --fix rtl/ # apply the safe fixes, write files back
lucisv check --rules-doc # the generated reference for every rule
```
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
@@ -179,35 +206,195 @@ violations remain, 2 error. Unlike the formatter, `check` uses the
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
what it can see.
| Rule | Fix | What it wants |
|---|---|---|
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | safe | nothing but code before the newline |
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
| `always-comb-blocking` | — | `=` inside `always_comb` |
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | — | a one-module file is named after its module |
| `unused-waiver` | — | waivers that suppress nothing |
| `unused-signal` † | — | no net or variable nothing uses |
| `undriven-net` † | — | everything read is driven by something |
| `multiply-driven` † | — | one driver per variable |
### Severities
† Off by default — `--select` them. These three read the file's *symbol
table*, not just its syntax, which is what lets them tell one `count` from
another; they are off because a single-file analysis cannot see a signal used
from another file's hierarchy. See
`docs/features/semantic-lints/README.md`. The table above is not the whole
set — naming-style rules ship too, and
`cargo run -p vlog_linter --example rules_markdown` prints the generated
reference for every rule with its default.
Every rule is in one of three classes, and the class is the word that stands
in the diagnostic line, in the JSON `severity` field, and in the editor's
squiggle colour:
| Class | Means | Editor |
|---|---|---|
| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) |
| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) |
| `style` | correct, and reads badly | blue (LSP Information) |
A class name is accepted **wherever a rule name is** — on `--select`, on
`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`:
```bash
lucisv check --select error rtl/ # only the compile-breakers
lucisv check --ignore style rtl/ # everything but the naming rules
```
Every `error`-class rule follows one discipline: **silence beats a wrong
accusation**. Each of them goes quiet whenever the run cannot answer — a file
that did not fully parse, a module the project does not hold or holds twice, a
name a macro produces, a fragment written to be `` `include``d. That is what
makes an editor's red squiggle worth believing.
### The rules
| Rule | Severity | Fix | What it wants |
|---|---|---|---|
| `multiply-driven` † | error | — | one driver per variable |
| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file |
| `mismatched-labels` | error | — | `end : name` names the block it closes |
| `duplicate-declaration` | error | — | each name declared once per scope |
| `undeclared-identifier` † | error | — | every name is declared somewhere in the project |
| `unknown-port` † | error | — | `.name(…)` is a port the module declares |
| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares |
| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` |
| `always-comb-blocking` | warning | — | `=` inside `always_comb` |
| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` |
| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path |
| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` |
| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` |
| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` |
| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` |
| `truncated-numeric-literal` | warning | — | a sized literal fits its width |
| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written |
| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` |
| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension |
| `module-port` | warning | — | more than one port is connected by name |
| `module-parameter` | warning | — | more than one parameter is overridden by name |
| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type |
| `void-cast` | warning | — | `void'(…)` wraps a call |
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
| `undriven-net` † | warning | — | everything read is driven by something |
| `unused-signal` † | warning | — | no net or variable nothing uses |
| `create-object-name-match` | warning | — | `type_id::create("x")` names the handle `x` |
| `forbidden-macro` | warning | — | no macro on the project's forbidden list |
| `uvm-macro-semicolon` | warning | — | no `;` after a `` `uvm_* `` macro (off by default) |
| `macro-string-concatenation` | warning | — | no `` `` `` inside a plain string (off by default) |
| `disable-statement` | warning | — | `disable fork`, not a fork label (off by default) |
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
| `empty-item` | style | safe | no `;` standing where an item belongs |
| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | style | — | a one-module file is named after its module |
| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` |
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
| `line-length` | style | — | no line wider than the width the formatter uses |
| `posix-eof` | style | safe | the file ends with a newline |
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
| `generate-label` | style | — | every generate block carries a `: label` |
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
| `package-filename` | style | — | a one-package file is named after its package |
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
| `one-module-per-file` | style | — | one `module` per file (off by default) |
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
| `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) |
| `unused-waiver` | style | — | waivers that suppress nothing |
| `unused-import` † | style | safe | no `import` nothing in the scope reaches through (off by default; stays off without a project) |
| `explicit-function-lifetime` | style | — | `automatic`/`static` on a function outside a class |
| `explicit-task-lifetime` | style | — | `automatic`/`static` on a task outside a class |
| `positive-meaning-parameter-name` | style | — | no `disable`-prefixed parameter name |
| `suggest-parentheses` | style | safe | `a ? (b ? c : d) : e`, parenthesized |
| `unpacked-dimensions-range-ordering` | style | — | an unpacked dimension is `[0:N-1]` |
| `module-begin-block` | style | — | no `begin`/`end` at module scope |
| `v2001-generate-begin` | style | — | no bare `begin` in a generate region |
| `forbid-line-continuations` | style | — | no `\` breaking a string literal |
| `legacy-generate-region` | style | — | no `generate … endgenerate` wrapper (off) |
| `legacy-genvar-declaration` | style | — | a genvar is declared in the `for` header (off) |
| `endif-comment` | style | safe | `` `endif `` names what it closes (off by default) |
| `numeric-format-string-style` | style | — | a radix prefix matches its specifier (off) |
| `proper-parameter-declaration` | style | — | `parameter` in a header, `localparam` in a body (off) |
| `dff-name-style` | style | — | a flip-flop is `_q`, its input `_d` (off by default) |
† On by default when lucisv can see a project (a multi-file CLI run or the
language server), and off for a single file or stdin unless `--select` names
them. These rules read the file's *symbol table* and ask the project about
names, not just the file's syntax; the project-wide identifier census keeps a
hierarchical use in another file from becoming a false positive. See
`docs/features/semantic-lints-on/README.md` and
`docs/features/linter-expansion-1/README.md`.
`lucisv check --rules-doc` prints the whole reference — every rule, its class,
its default, its fix and the paragraph saying why it exists — generated from
the registry, so it can never be out of date.
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
that cannot change what the code means), `--unsafe-fixes` widens that — no
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
that cannot change what the code means), `--unsafe-fixes` widens that to the
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
`always_comb`, which is a different block at time zero and makes a second
driver of its outputs an error — right nearly always, and not lucisv's call to
make without being asked. Violations inside a `// verilog_format: off`
region are reported but never fixed: `off` means hands-off for the linter too,
so `--fix` leaves every byte of a fenced region exactly as written.
### Rule options
A rule can be configured in a `[lint.<rule-name>]` table:
```toml
[lint]
ignore = ["typedef-structs-unions"]
[lint.line-length]
length = 120 # the linter's limit, if not the formatter's
[lint.generate-label-prefix]
prefix = ["g_", "gen_"] # the label prefixes this project writes
[lint.parameter-name-style]
localparam_style = "CamelCase" # Verible's own default, stricter than ours
[lint.signal-name-style]
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
```
The keys are Verible's wherever it has the same option, so a `.rules.verible`
file translates word for word. An option nobody sets reads the default
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
value of the wrong kind, an integer out of range or a pattern that does not
compile **fails the run**, naming the config file and the line — a typo in a
lint setting is not something to guess at.
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
against the **whole** name, so `^`/`$` are accepted and redundant.
Everything else is **refused when the option is read, by name**: counted
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
worse than an error you can read.
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
length whatever shape the pattern has: no pattern can make `lucisv check` — or
an editor session — hang.
From an editor the same options are one object, `lucisv.lint.options`:
```json
"lucisv.lint.options": {
"line-length": { "length": 120 },
"typedef-structs-unions": { "allow_anonymous_nested": false }
}
```
There the precedence is **the editor's value, then the `lucisv.toml`, then the
rule's default — key by key**: a project can set two options and one user
override the third without losing the others. (This is the opposite order to
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
formatting has a byte-exact contract with CI, and which findings you are shown
in your own editor is yours to choose.) A bad entry there is *ignored* and
reported in the lucisv log rather than fatal, so one typo cannot leave a
session with no diagnostics.
### Waivers
```systemverilog
@@ -221,21 +408,82 @@ wire a; // lucisv: waive no-tabs suppresses that rule on this line
works unedited — including waivers naming Verible rules lucisv has not
implemented, which are ignored rather than reported. A waiver of lucisv's own
that suppresses nothing, names an unknown rule or is malformed is reported
under `unused-waiver`. External waiver files are not supported. Full rules:
under `unused-waiver`.
Findings can also be suppressed from **outside** the RTL, in Verible's
waiver-file format — one directive per line, `#` comments and blank lines
ignored:
```text
# every line of every file
waive --rule=no-tabs
# one line, or a range with both ends included
waive --rule=line-length --line=12
waive --rule=line-length --line=12-20
# only the files a pattern names
waive --rule=no-tabs --location=legacy/top.sv
```
`--rule` is required and names exactly one rule (a severity word is not
accepted). `--line` is 1-based. `--location` is matched the way an
`--exclude` pattern is — `*` within one path component, a pattern with `/`
matching a path suffix, one without matching the file name at any depth — and
**not** as a regular expression; a pattern that looks like one (`.*`, `\.`,
`[…]`) is an error naming the difference.
Waiver files come from three places, and they add up: `lucisv check
--waiver-file <path>` (repeatable, relative to the working directory),
`waivers` under `[lint]` in `lucisv.toml` (relative to that file; read by the
CLI and the editor), and the editor setting `lucisv.lint.waivers` (relative to
the first workspace folder). External and inline waivers are a union: a
finding either covers is suppressed, and one both cover leaves neither
reported as dead. A missing file or an unparsable directive fails `lucisv
check` with `<file>:<line>: <message>` and exit 2; in an editor the bad line
is dropped and the rest of the file applies, and the bad line is written once
to the lucisv log whether the file was named by the editor setting or by
`lucisv.toml`. Unused external waivers
are reported under `unused-waiver` at their line of the waiver file, by
`lucisv check` only and only after the whole run.
Both front ends read the same configuration, and the editor's settings play
the role the CLI's flags play: `lucisv.lint.select` when it is set, else
`[lint] select` from the buffer's `lucisv.toml`, else the default set — and
the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
`lucisv.lint.rules.*` have no project counterpart and apply over whichever
selection stands. Project per-rule options are read by both front ends. A
project entry lucisv cannot use — an unknown rule name in `[lint]
select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
file or a directive that does not parse — fails `lucisv check` with
`<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
once to the lucisv log in the same words, and everything lucisv did
understand still lints the buffer. Full rules:
`docs/features/linter-core/README.md`.
## Architecture (the ruff mapping)
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
generic pretty-printing IR, language formatting rules, and a thin CLI:
The eight-crate workspace separates source syntax, reusable engines, project
inputs, and the CLI/LSP front ends. The formatter follows ruff's separation
of document layout from language rules:
| This repo | ruff equivalent | Role |
|---|---|---|
| `crates/vlog_parser` | `ruff_python_parser` + `ruff_python_ast` | Hand-written lexer and recursive-descent parser producing a comment-preserving AST |
| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer |
| `crates/vlog_formatter/src/format.rs` | `ruff_python_formatter` | Per-node formatting rules |
| `crates/vlog_formatter/src/format/` | `ruff_python_formatter` | Per-node formatting rules, one module per grammar domain (`item`, `module`, `instance`, `decl`, `stmt`, `expr`, `class`, `cover`, `sva`, …) |
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
| `crates/lucisv` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
| `crates/vlog_semantic` | — | File scopes and references, workspace index, conservative cross-file resolution |
| `crates/vlog_refactor` | — | Verified rename/references, ports, imports, extract/inline module, instantiation plans |
| `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement |
| `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes |
| `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities |
`vlog_parser` and `lucisv_core` have no dependencies. The formatter depends
only on the parser; semantic analysis also depends only on the parser.
Linting consumes the parser, semantics and `lucisv_core` (for the one
`--exclude`-style matcher a waiver file's `--location` shares with the CLI);
refactoring consumes the parser and semantics. The CLI reaches
semantics through the linter and has no refactoring dependency. The server
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
including the linter’s and refactor’s formatter dependencies used only by tests.
Key ideas carried over from ruff/prettier:
@@ -248,8 +496,15 @@ Key ideas carried over from ruff/prettier:
lists, expressions, concatenations) is a `Group`: it renders on one line if
it fits within the line limit, otherwise it breaks one-element-per-line.
A comment inside a group forces it to break.
- **Idempotency as a hard invariant.** The test suite formats every fixture
twice and asserts a fixed point.
- **Verification on every formatting call.** The engine re-lexes input and
output and compares normalized tokens, including comments. It then parses
and formats the output again and requires a fixed point. Either check can
reject the result; the caller retains the original file. This is a lexical
safety net, not compiler elaboration or a proof of hardware equivalence.
- **Two parsing modes.** Formatting uses strict parsing. Linting and the
editor use tolerant parsing: failed elements become error leaves while
valid siblings remain available for analysis. A lexer failure is still
all-or-nothing. Neither mode performs cross-file macro expansion.
## Style
@@ -297,8 +552,8 @@ both layouts are fixed points of re-formatting:
### Turning the formatter off
Items between a `// verilog_format: off` and a `// verilog_format: on`
comment are emitted as the exact source bytes they were written with,
Everything between a `// verilog_format: off` and a `// verilog_format: on`
comment is emitted as the exact source bytes it was written with,
indentation included — the escape hatch for hand-aligned tables and the
like. `// lucisv: off` / `// lucisv: on` is an accepted alias.
@@ -312,12 +567,30 @@ module m;
endmodule
```
The fence must be a line comment on its own line, and its text must match
exactly — `// lucisv: off for now` is an ordinary comment, not a fence. An
`off` with no matching `on` runs to the end of the enclosing item list
(module body, package body, generate block, or the file). Fences select
whole items; one written between two *statements* has no effect yet. Full
rules: `docs/features/format-fences/README.md`.
A fence works between **items** — module, package and class members, and
top-level items — and between **statements**: inside `begin`…`end`,
`fork`…`join*`, and function, task, `initial`, `always` and `final` bodies.
```systemverilog
class scoreboard;
function void build_phase();
// verilog_format: off
uvm_config_db#(cfg_t)::set(this, "env.agent", "cfg",
cfg.agent_cfg); // hand-wrapped, left alone
// verilog_format: on
endfunction
endclass
```
The fence must be a line comment that begins its own line, and its text must
match exactly — `// lucisv: off for now` is an ordinary comment, not a fence,
and so is one written after code on the same line (`wire a; // lucisv: off`,
`begin // lucisv: off`). An `off` with no matching `on` runs to the end of the
enclosing list and no further: the module body, the class body, the
`begin`…`end`, the function body, or the file. A fence inside a port list, a
parameter list or a `case` **label** list is still an ordinary comment. Full
rules: `docs/features/format-fences/README.md` and
`docs/features/statement-fences/README.md`.
### Range formatting (`--lines`)
@@ -350,12 +623,19 @@ into ranges. Full semantics, including what happens at a range boundary:
## Supported syntax
v0.49.0 adds real `randsequence` productions; nonblocking `->>` event
triggers with optional timing; streaming `with [range]`; constant-expression
and packed-type cast bases; net drive strengths; statement-level `let`; and
min:typ:max clocking skews. The parser, formatter and AST consumers share these
nodes. See [coverage gaps](docs/coverage_gaps.md) for the dated survey and
remaining semantic limits.
Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
- Modules (ANSI and non-ANSI headers), packages, parameter ports,
`import`, `timeunit`
- Net/variable declarations (`wire`/`reg`/`logic`/`int`/... , signing,
packed/unpacked dimensions, net delays), `parameter`/`localparam`,
packed/unpacked dimensions, net delays and net drive strengths), `parameter`/`localparam`,
`genvar`, `defparam`
- `assign` (with delays), `always`/`always_comb`/`always_ff`/`always_latch`,
`initial`/`final`
@@ -397,24 +677,28 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
methods with `virtual`/`static`/`local`/`protected`/`automatic`, `function
new`, `extern` and `pure virtual` prototypes and their out-of-body
definitions, plus everything that already works at module scope (`typedef`,
`localparam`, `import`, directives, macro items, nested classes). `constraint
c { ... }` and `covergroup … endgroup` are **passed through verbatim** — two
grammars with no layout convention worth inventing. See
`docs/features/classes/README.md`
`localparam`, `import`, directives, macro items, nested classes).
`constraint c { ... }` and `covergroup … endgroup` are structured too:
constraint expressions, `soft`/`dist`, implication, `foreach`, `solve
before`, coverpoints, bins, transitions and crosses all format canonically
and participate in rename, references and semantic lints. An unrecognized
body rewinds to its exact source bytes instead of blocking the surrounding
file. See `docs/features/constraint-bodies/README.md` and
`docs/features/covergroup-bodies/README.md`
- Concurrent assertions (IEEE 1800 §16): `assert`/`assume`/`cover`/`restrict
property ( ... )` with an optional `label:` prefix and an action block
(`else $error(...)`, `$info(...); else ...`, `else begin ... end`, and any
statement that nests blocks: `if (c) begin ... end else ...`,
`fork ... join_none`, `case ... endcase`), wherever
a module item or a statement can appear — module and package bodies,
generate regions, `begin`/`end`, and at file scope. Plus `sequence ...
endsequence` and `property ... endproperty` declarations. All of it is
**passed through verbatim**, for the same reason `constraint` is: the
property/sequence expression language (`|->`, `##[1:3]`, `throughout`,
`disable iff`, `$rose`) is a second grammar with no layout convention worth
inventing. Only the first line is re-indented to the item's level; the
relative layout the source wrote is what survives. See
`docs/features/assertions/README.md`
`fork ... join_none`, `case ... endcase`), wherever a module item or a
statement can appear — module and package bodies, generate regions,
`begin`/`end`, and at file scope. `sequence` and `property` declarations,
typed formals, local variables, `expect`, `cover sequence`, and `default
disable iff` are real nodes. The property/sequence expression grammar uses
the LRM precedence table; top-level `|->`/`|=>`/`##`/`and`/`or` operators
break one per line when needed. Rename, references, document symbols and
semantic lints see inside; an unrecognized construct falls back to its exact
source bytes and produces a rename warning. See
`docs/features/sva-bodies/README.md`
- Dynamic types: queues (`string q[$]`, bounded `[$:N]`), dynamic arrays
(`int a[]`), associative arrays (`[*]`, `[string]`, `[key_t]`) — in
declarations, class properties, typedefs and function/task arguments; the
@@ -423,8 +707,8 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
`docs/features/dynamic-types/README.md`
- DV statements (IEEE 1800 §7.12, §9.3.5, §11.12, §12.7.3, §13.4.2, §18.7,
§18.16): `randomize() with { ... }` / `std::randomize(x, y) with { ... }`
(the call is structural, the constraint block is **passed through
verbatim**, exactly as `constraint c { ... }` is), the array-method
(the call and its constraint block are structural, with byte-exact fallback
for an unrecognized constraint shape), the array-method
iterator argument `q.sum() with (item.w)`, `foreach` over a
package-scoped or hierarchical array with selects on the way
(`foreach (pkg::isa[i])`, `foreach (h[id].sub[k])`, `foreach (a[i][j])`),
@@ -464,7 +748,8 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
trailing `;` is reproduced only if the source wrote one. At item and
statement position a space before the argument list is accepted too
(`` `uvm_field_int (a, UVM_DEFAULT) ``) and is reproduced as written; in
*expression* position `` `A (b) `` still parses as a call applied to `(b)`.
*expression* position the author-written gap is preserved too, because it
can affect how a macro with formals is interpreted.
A macro that ends its line is a complete macro, so whatever opens the next
line — a declaration, or a statement starting with `@`, `#`, `->` or `{` —
is its own item. See `docs/features/item-misc/README.md` and
@@ -490,10 +775,17 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
(``sub #(`include "config.vh") u (...)``). See
`docs/features/directives-in-lists/README.md` and
`docs/features/directives-in-instances/README.md`
- Programs, interface classes, `alias`, `union tagged`, `specparam`, library
map entries, and statement-form `expect`. `specify`, UDP `primitive`/`table`,
`checker`, and `config` blocks are recognized as opaque blocks so vendored
simulation models and formal collateral do not block the rest of a file;
their internal layout is preserved. See
`docs/features/vendor-formal-grammar/README.md`
Not yet supported (parse errors). Roadmap ordered by measured impact on
real RTL — see `docs/features/corpus-check/README.md` for the 820-file
corpus baseline this ordering comes from:
### Historical syntax roadmap
This roadmap records how parse coverage was raised, in measured-impact order.
See `docs/features/corpus-check/README.md` for the 820-file corpus baseline:
1. ~~Macro invocation at module-item / statement position
(`` `ASSERT_INIT(...) `` style)~~ — **done**; see
@@ -574,8 +866,9 @@ corpus baseline this ordering comes from:
`docs/features/dv-statements/README.md`. Emptied the `dv-statements`
bucket (26 files) and moved the parse rate from 94.1% to 97.1%; 24 of the
26 files format, the other 2 advanced to a macro-items blocker and to the
`new obj` shallow-copy expression. `specify` blocks, `checker`,
`program`, `interface class` and `randsequence` remain unsupported
`new obj` shallow-copy expression. `randsequence` remained unsupported at
this point; it shipped as real nodes in 0.49.0. The other vendor/formal
constructs listed here landed in 0.30.0
11. ~~A macro statement that ends its line followed by a symbol on the next
one, the `new obj` shallow copy (IEEE 1800 §8.12), and a based number
whose digits come from a macro (`` 32'h`DM_ADDR ``)~~ — **done**; see
@@ -598,6 +891,11 @@ corpus baseline this ordering comes from:
`` `X_EACH_CSR`` (need macro expansion, a deliberate non-goal) and 5
files that are not valid standalone Verilog
Fragment-mode support subsequently raised the current frozen corpus baseline
to **814/820 (99.3%)**. The remaining six files require cross-file macro
expansion, contain a conditional-split outlier, or are not valid standalone
Verilog; none regressed when the vendor/formal and SVA grammars landed.
Like ruff, `lucisv` refuses to output anything for a file it cannot fully
parse, so it can never corrupt code.
@@ -610,30 +908,62 @@ go-to-definition, references and document/workspace symbols — the full list,
and what is deliberately *not* advertised yet, is in
`docs/features/lucisv-server/README.md`.
**The binary comes from the same build as the CLI.** Download it from the
[releases page](https://git.luci.ooo/lucio/lucisv/releases) for your
platform, or build it yourself:
The editor now offers these refactorings alongside rename and port propagation:
| Action | Behavior |
|---|---|
| Expand wildcard | Replace `.*` with declaration-order named connections; unmatched ports become `.p()` with a warning |
| Convert ports to ANSI | Merge a legacy module header and its body port declarations, preserving comments and attributes |
| Organize imports | Remove unused imports, merge exact duplicates and sort a top-of-scope run; uncertainty keeps the action conservative |
| Extract module | Move selected whole module items into a named module, infer its interface, and insert the replacement instance; create a file when supported or append below the source module |
| Inline module | Copy a separate-file module body into its instance site with simple named-connection substitution and collision-aware internal renaming |
The [language-tools reference](docs/site/src/content/docs/reference/language-tools.md)
records commands and refusal limits. Inline-module has a known transitive
source-selection gap; review hierarchical uses through wrapper modules before
applying it (topology handshake 33).
In the VS Code hierarchy, **Star as DUT** groups a module’s children and
parents into sections alongside Other Modules. Stars persist per workspace;
`lucisv.hierarchy.duts` adds team-configured names, which are locked in the menu.
**VS Code needs no separate binary**: every release on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases) carries a
platform-specific `.vsix` with both binaries inside it — pick yours
(`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64`)
and sideload it:
```bash
code --install-extension lucisv-<version>-darwin-arm64.vsix
```
— or take `lucisv-<version>-all.vsix`, which carries all five platforms' binaries
in one file and picks the right pair at startup, when the machine is not known
in advance (or is Alpine, which VS Code never offers a Linux package to).
Every other editor (and the universal `lucisv-<version>.vsix`, the fallback
for platforms not listed) finds `lucisv-server` on `PATH`; the binary comes
from the same build as the CLI:
```bash
cargo build --release # target/release/lucisv-server (and target/release/lucisv)
cp target/release/lucisv-server ~/.local/bin/ # anywhere on PATH
```
Every editor below defaults to finding `lucisv-server` on `PATH`; each also
accepts an absolute path if you would rather leave the binary in `target/`.
Each editor also accepts an absolute path if you would rather leave the
binary in `target/`.
**VS Code** — a thin extension in `editors/vscode/` whose entire job is
registering the file types and starting the server:
registering the file types and starting the server (bundled, from `PATH`, or
from the `lucisv.serverPath` setting). To build the packages yourself:
```bash
tools/release.sh # builds dist/lucisv-<version>.vsix
code --install-extension dist/lucisv-<version>.vsix
tools/release.sh # dist/lucisv-<version>.vsix + the host platform package
code --install-extension dist/lucisv-<version>-darwin-arm64.vsix
```
The `.vsix` is also attached to every release on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases). Sideloading it
is the supported install; the extension is not on any marketplace. To package it by hand instead: `cd editors/vscode && npm ci &&
npx @vscode/vsce package`.
Sideloading is the supported install; the extension is not on any
marketplace.
Settings are listed in `editors/vscode/README.md`, along with the full steps,
the F5 development flow and troubleshooting.
@@ -656,8 +986,11 @@ vim.lsp.enable('lucisv')
**Which files the server indexes.** A filelist if the project has one — the
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
(a path, absolute or relative to the workspace folder) — and then exactly the
files it names. Otherwise the workspace folder, walked as the CLI walks it;
and with no folder open at all, the current file's own directory. Open buffers
files it names. Otherwise the default `lucisv.index.scope = "folder"` starts
from open-file folders, widens by `lucisv.index.scopeDepth` (default 2), and stays bounded by
the workspace roots; `"workspace"` walks the full roots. With no folder open,
the server stays in the current file's directory: depth 0 scans it flat; a
positive depth walks its descendants but never climbs to a parent. Open buffers
are always indexed on top. A filelist that cannot be read warns and falls back
to the folder walk, so the index is never silently empty.
@@ -665,7 +998,11 @@ to the folder walk, so the index is never silently empty.
<path-to-binary>` spawns it exactly as the extension does and drives a whole
`initialize`/`didOpen`/`shutdown`/`exit` session over stdio, exiting 0 only if
the handshake and the advertised capabilities are intact — which tells you
whether a failure is the server or your editor config.
whether a failure is the server or your editor config. Its neighbour
`node editors/vscode/restart_test.js` needs no binary at all: it drives the
extension's server-restart chain (the one `lucisv.verbose` uses) against a
scripted fake client, so a toggle can never be lost to a restart that was
already in flight.
**Formatting through an editor reads `lucisv.toml` too**, discovered from the
buffer's own path by the CLI's rule, so format-on-save agrees with what
@@ -684,30 +1021,45 @@ expected; no PRs or review required.
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo test # unit + snapshot + idempotency tests
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
```
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
expected outputs only for intentional formatting changes with
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
Table-driven cases live in `crates/vlog_formatter/tests/cases/`; lint cases
live in `crates/vlog_linter/tests/cases/`. All tests, fuzzers, and corpus/tree
sweeps must run through `tools/guard.sh` (8 GiB RSS / 30 minutes by default),
as required by [CLAUDE.md](CLAUDE.md). A guard kill is a finding, not a reason
to increase the limit. Documentation build instructions are in
[docs/site/README.md](docs/site/README.md).
## Install and releases
Prebuilt downloads live on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases): every tagged
version carries `lucisv` and `lucisv-server` for Apple Silicon and Intel
macOS, static-musl and RHEL 8-compatible glibc Linux, and Windows, plus the
`.vsix` and a `SHA256SUMS` to verify them with
(`shasum -a 256 -c SHA256SUMS`). Copy the two binaries onto your `PATH` and
sideload the extension with `code --install-extension`. The macOS binaries
are smoke-tested on the build machine; the Linux and Windows ones are
cross-built and audited (file type, dynamic-linkage, glibc-version ceiling),
not executed — there is no Linux or Windows machine in the loop.
version carries **seven `.vsix` packages** — platform-specific ones for
Apple Silicon and Intel macOS, x86-64 and ARM64 Linux (static musl) and
Windows, each with `lucisv` and `lucisv-server` embedded, an
all-platforms one carrying every pair at once for unknown or mixed
machines, plus the universal no-binary fallback — and a `SHA256SUMS` to
verify them with
(`shasum -a 256 -c SHA256SUMS`). Sideload the one for your machine with
`code --install-extension`. Standalone binaries are not published; build
them with `cargo build --release` (or `tools/release.sh --cross` for the
full set — the release binaries are cut from the same scripts). The macOS
binaries inside the packages are smoke-tested on the build machine; the
Linux and Windows ones are cross-built and audited (file type,
dynamic-linkage, glibc-version ceiling), not executed — there is no Linux
or Windows machine in the loop.
To build the same artifact set yourself:
```bash
tools/release.sh # host binaries + the .vsix + SHA256SUMS, into dist/
tools/release.sh --cross # ...plus the four cross-built platforms
tools/release.sh --cross # ...plus the four cross-built platforms and the all package
```
The script itself publishes nothing anywhere; publishing is CI's job —
+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`.
+6155 -27
View File
File diff suppressed because it is too large. Load diff
+102 -5
View File
@@ -71,6 +71,15 @@ pub struct Options {
pub select: Vec<String>,
/// `check` only: rules to drop from whatever `--select` left.
pub ignore: Vec<String>,
/// `check` only: external waiver files, relative to the current
/// directory. They *add* to whatever `[lint] waivers` in a `lucisv.toml`
/// names — a waiver file suppresses findings and can only ever suppress
/// fewer of them by being left out, so there is nothing here for a
/// command line flag to override.
pub waiver_files: Vec<String>,
/// `check` only: print the generated rule reference and exit, reading no
/// file at all.
pub rules_doc: bool,
/// Files, directories, or the single input `-`.
pub inputs: Vec<String>,
/// `-f`: EDA filelists whose files are added to [`Options::inputs`].
@@ -97,6 +106,12 @@ impl Options {
if let Some(n) = self.indent.or(file.indent) {
config.indent_width = n;
}
// `[format]` has no CLI flag: these keys change how already-clean
// files look, so the project's own config is the only place that
// turns one on.
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config
}
@@ -188,11 +203,26 @@ OPTIONS:
CHECK OPTIONS (`lucisv check` only):
--select <RULES> run only these rules (comma-separated, repeatable)
--ignore <RULES> drop these rules from the set that would run
Three rules read the *project* rather than one file — `unused-signal`,
`undriven-net`, `multiply-driven`. They run by default over more than one
file, where lucisv can ask whether another file mentions a name, and stay
off for a single file or a stdin buffer, where it cannot. `--select` runs
one either way; `--ignore`, or `ignore` under `[lint]` in lucisv.toml,
turns one off.
--output-format <FMT> `text` (default): FILE:LINE:COL: message [rule];
`json`: one array of diagnostic objects
--fix apply safe fixes and write the files back
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
one yet, so today this changes nothing)
--waiver-file <PATH> read waiver directives from this file; may be
repeated, and adds to whatever `[lint] waivers`
in a lucisv.toml already names
--rules-doc print the rule reference — every rule, what it
reports and whether it has a fix — as Markdown on
stdout and exit 0. Generated from the registry, so
it always describes the rules this build ships;
takes no files and lints nothing
Suppress a finding with a comment: `// lucisv: waive <rule>` on the line
itself or on the line above it, or a `// lucisv: waive-start <rule>` /
@@ -200,6 +230,31 @@ CHECK OPTIONS (`lucisv check` only):
accepted in place of `lucisv:`. A waiver that suppresses nothing is
reported under the `unused-waiver` rule.
WAIVER FILES:
Findings can also be suppressed from outside the RTL, in Verible's waiver
file format — one directive per line, `#` comments and blank lines ignored:
waive --rule=<rule> every line of every file
waive --rule=<rule> --line=12 one line
waive --rule=<rule> --line=12-20 a range, both ends included
waive --rule=<rule> --location=legacy.sv the files that pattern names
`--rule` is required and names one rule (a severity word is not accepted);
`--line` is 1-based and a range includes both ends; `--location` is matched
the way an `--exclude` pattern is — `*` within one path component, a
pattern with `/` against a path suffix and one without against the file
name. Unlike Verible's, it is **not** a regular expression, and a pattern
that looks like one is an error rather than a silent mismatch.
lucisv reads `--waiver-file <PATH>` (relative to the current directory) and
every path in `waivers` under `[lint]` in a `lucisv.toml` (relative to that
file). An external waiver and an inline one are a union: a finding either
covers is suppressed, and neither is then reported as dead. A file that
does not exist, or a directive that does not parse, fails the run with
`<file>:<line>: message` and exit 2. An external waiver that suppressed
nothing anywhere in the run is reported under `unused-waiver`, at the line
of the waiver file it was written on.
IGNORE FILES:
While walking a directory, lucisv reads a `.gitignore` in every directory it
enters and skips what it names; a deeper file overrides a shallower one and
@@ -233,8 +288,13 @@ CONFIGURATION:
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
read by lucisv-server only — the CLI reads a filelist only when `-f` names
one, so `lucisv rtl/` always means the directory it was given). A command
line flag overrides the file.
one, so `lucisv rtl/` always means the directory it was given). One table
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
paths, resolved against the config file's own directory). A command line
flag overrides the file's corresponding key; the other keys still apply —
`--waiver-file` is the exception, and adds to `waivers` rather than
replacing it.
RANGE FORMATTING:
`--lines` formats one construct at a time: an item whose lines meet a range
@@ -281,6 +341,8 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
unsafe_fixes: false,
select: Vec::new(),
ignore: Vec::new(),
waiver_files: Vec::new(),
rules_doc: false,
inputs: Vec::new(),
filelists: Vec::new(),
};
@@ -360,6 +422,11 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--ignore requires a value")?;
opts.ignore.extend(split_rules(&v));
}
"--waiver-file" => {
let v = args.next().ok_or("--waiver-file requires a value")?;
opts.waiver_files.push(v);
}
"--rules-doc" => opts.rules_doc = true,
"-h" | "--help" => {
print_help();
std::process::exit(0);
@@ -373,9 +440,16 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
s => opts.inputs.push(s.to_string()),
}
}
// A filelist is an input like any other, so `-f files.f` alone is a
// complete command line and needs no positional argument.
if opts.inputs.is_empty() && opts.filelists.is_empty() {
// `--rules-doc` prints the rule reference and reads nothing, so it is the
// one invocation with no input at all — and being given one means the
// caller expected files to be linted, which they would not be.
if opts.rules_doc {
if !opts.inputs.is_empty() || !opts.filelists.is_empty() {
return Err("--rules-doc takes no files".to_string());
}
} else if opts.inputs.is_empty() && opts.filelists.is_empty() {
// A filelist is an input like any other, so `-f files.f` alone is a
// complete command line and needs no positional argument.
return Err("no input files (try `lucisv --help`)".to_string());
}
// Repeating the flag is the same as one comma-separated list; both spell
@@ -418,6 +492,8 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
(opts.output_format != OutputFormat::Text, "--output-format"),
(!opts.select.is_empty(), "--select"),
(!opts.ignore.is_empty(), "--ignore"),
(!opts.waiver_files.is_empty(), "--waiver-file"),
(opts.rules_doc, "--rules-doc"),
];
let format_only = [
(opts.check, "--check"),
@@ -586,4 +662,25 @@ mod tests {
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
}
#[test]
fn waiver_files_are_collected_in_order_and_are_lint_only() {
let opts = parse(&["check", "--waiver-file", "a.waiver", "--waiver-file", "b", "rtl"])
.expect("parsed");
assert_eq!(opts.waiver_files, vec!["a.waiver", "b"]);
assert!(parse(&["check", "rtl"]).unwrap().waiver_files.is_empty());
assert!(parse(&["check", "--waiver-file"]).is_err(), "a value is required");
assert!(parse(&["--waiver-file", "a.waiver", "rtl"]).is_err(), "not a formatter flag");
}
#[test]
fn rules_doc_is_the_one_check_that_needs_no_input() {
assert!(parse(&["check", "--rules-doc"]).unwrap().rules_doc);
// ... and refuses one, rather than accepting a path it would not read.
assert!(parse(&["check", "--rules-doc", "rtl"]).is_err());
assert!(parse(&["check", "--rules-doc", "-f", "a.f"]).is_err());
// Lint-only, like every other `check` flag.
assert!(parse(&["--rules-doc"]).is_err());
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
}
}
+4 -217
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;
+467 -38
View File
@@ -5,13 +5,20 @@
//! is handed the same `(path, config)` job list `format` gets. Only what
//! happens to one file differs.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use lucisv_core::atomic::write_atomic;
use lucisv_core::config::FileConfig;
use rayon::prelude::*;
use vlog_formatter::fence::{self, Region};
use vlog_formatter::Config;
use vlog_linter::{apply_fixes, lint, Fix, ParsedSource, Rule, Violation};
use vlog_linter::words;
use vlog_linter::{
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
Violation, WaiverUse,
};
use vlog_parser::LineIndex;
use crate::args::{Options, OutputFormat};
@@ -22,6 +29,327 @@ use crate::args::{Options, OutputFormat};
/// cap only bounds a rule that would fight itself forever.
const MAX_FIX_ROUNDS: usize = 10;
/// One file to lint, with the rules the command line and its own
/// `lucisv.toml` resolved to.
pub struct Job {
path: PathBuf,
config: Config,
rules: Vec<&'static dyn Rule>,
/// What this file's `lucisv.toml` configured about each rule, validated
/// against the registry when the run was planned.
options: RuleOptions,
}
/// A whole `lucisv check` run: what to lint, and what the project says about
/// names.
pub struct Plan {
jobs: Vec<Job>,
/// The project's identifier census, built when at least one selected rule
/// asks for a workspace and there is more than one file to ask about.
census: Option<Census>,
/// Every external waiver file the run reads, applied to every job.
///
/// One set for the whole run rather than one per file, because a
/// `--location` pattern names files and a waiver is only *unused* when no
/// file in the run matched it — a question only the whole run can answer.
external: ExternalWaivers,
/// Every rule name any job in the run has switched on, for deciding which
/// external waivers never had a chance to fire.
enabled: Vec<&'static str>,
}
/// How many of the run's files write each identifier down.
///
/// The CLI's answer to the question the language server answers from its
/// index: it has none, so it builds one — a read and a lex of every file in
/// the run, before the first rule sees anything. Only the *counts* are kept;
/// a rule asks about one name at a time and never about a file.
pub struct Census {
files: HashMap<String, u32>,
/// Module or interface name → what it declares, `None` for a unit the run
/// cannot answer for: a header carrying a compiler directive, or two
/// declarations that disagree. Empty when no enabled rule asked for it —
/// building it costs a parse of every file in the run.
interfaces: HashMap<String, Option<vlog_linter::ModuleInterface>>,
/// Package name → the names it exports, `None` for a package the run
/// cannot answer for: one declared twice, or one re-exporting from
/// another package (only a whole-project index settles that). Empty
/// unless `unused-import` is enabled.
packages: HashMap<String, Option<Vec<String>>>,
}
/// What one file contributes to a [`Census`]: its words, the units it
/// declares, and the packages it exports from.
type PerFile = (
Vec<String>,
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
Vec<(String, Option<Vec<String>>)>,
);
/// One file's three contributions, off **one** parse.
///
/// The word census wants the tokens, the interface table wants the tree and
/// the package table wants both — so a run that asks for either table lexes
/// and parses the file exactly once and all three read that. A run that asks
/// for neither never parses at all: `harvest_text` lexes and stops, which is
/// what the word census alone needs.
///
/// A file that cannot be read contributes nothing, and so does one that does
/// not lex (`harvest_text` and a `ParsedSource` with no tokens agree on that).
/// The file's own check is what reports the error.
fn harvest_one(job: &Job, interfaces: bool, packages: bool) -> PerFile {
let Ok(src) = std::fs::read_to_string(&job.path) else {
return (Vec::new(), Vec::new(), Vec::new());
};
if !interfaces && !packages {
return (words::harvest_text(&src), Vec::new(), Vec::new());
}
let parsed = ParsedSource::parse(&src);
let declared = match interfaces {
true => vlog_linter::module_interfaces(parsed.file()),
false => Vec::new(),
};
let exports = match packages {
true => vlog_linter::package_exports_in(&job.path, parsed.file(), parsed.tokens(), &src),
false => Vec::new(),
};
(words::harvest(parsed.tokens()), declared, exports)
}
impl Census {
/// The census of every file in the run, harvested in parallel.
///
/// A file that cannot be read or does not lex contributes nothing, which
/// is the same all-or-nothing rule the rest of the run gives it: the
/// file's own check reports the error.
///
/// `interfaces` says whether the run also needs each unit's ports and
/// parameters (`unknown-port`, `unknown-parameter`), and `packages`
/// whether it needs each package's exported names (`unused-import`).
/// Either costs a **parse** of every file on top of the lex the word
/// census already pays for, so each is built only when some enabled rule
/// asks — measured on opentitan `hw/` in
/// `docs/features/linter-expansion-1/README.md`.
fn of(jobs: &[Job], interfaces: bool, packages: bool) -> Census {
let per_file: Vec<PerFile> =
jobs.par_iter().map(|job| harvest_one(job, interfaces, packages)).collect();
let mut files: HashMap<String, u32> = HashMap::new();
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
let mut exported: HashMap<String, Option<Vec<String>>> = HashMap::new();
for (words, declared, exports) in per_file {
for word in words {
*files.entry(word).or_default() += 1;
}
// A package name the run declares twice is a package the run
// cannot answer for, whatever the two say — the same rule the
// workspace index applies, where two `units` is `Ambiguous`.
for (name, names) in exports {
exported.entry(name).and_modify(|held| *held = None).or_insert(names);
}
for (name, interface) in declared {
// Two declarations of one name answer only when they agree;
// anything else is a question the run cannot settle.
units
.entry(name)
.and_modify(|held| {
if *held != interface {
*held = None;
}
})
.or_insert(interface);
}
}
Census { files, interfaces: units, packages: exported }
}
/// How many files in the run write `name` down.
fn count(&self, name: &str) -> u32 {
self.files.get(name).copied().unwrap_or(0)
}
/// What the run says `name` declares, or `None` when it cannot say.
fn interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.interfaces.get(name)?.clone()
}
/// What the run says the package `name` exports.
fn package(&self, name: &str) -> vlog_linter::Exports {
match self.packages.get(name) {
Some(Some(names)) => vlog_linter::Exports::Known(names.clone()),
Some(None) => vlog_linter::Exports::Ambiguous,
None => vlog_linter::Exports::Unknown,
}
}
}
/// One file's view of the census: everything the project says, minus what
/// this file says about itself.
struct Elsewhere<'a> {
census: &'a Census,
/// This file's own words, sorted — [`words::harvest`]'s answer over the
/// tokens the file was linted from, so the subtraction is exact rather
/// than assumed.
own: Vec<String>,
}
impl MentionOracle for Elsewhere<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
self.census.count(name) > mine
}
/// The run's interface table, which covers **every** file including this
/// one: a module is instantiated as often in the file that declares it as
/// anywhere else, and there is nothing to subtract here.
fn module_interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.census.interface(name)
}
/// The run's package table, whole-run for the same reason the interface
/// table is: a package is imported as often by the file that declares it
/// as by any other, and there is nothing here to subtract.
fn package_exports(&self, name: &str) -> vlog_linter::Exports {
self.census.package(name)
}
}
/// Resolve the run: the rules for each file, and whether a census is owed.
///
/// **Precedence is CLI over config, key by key**: `--select` replaces a
/// `[lint] select`, `--ignore` replaces a `[lint] ignore`, and a key the
/// command line does not mention is the config file's to answer — the same
/// ladder `--line-length` and `--indent` already climb.
///
/// A rule that [`Rule::needs_workspace`] is on by default here exactly when
/// the run holds more than one file: one file is one file whatever directory
/// it was found in, and a census of it could only ever say what the file
/// already says about itself.
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
let workspace = gathered.len() > 1;
let external = external_waivers(opts, gathered.iter().map(|(_, _, file)| file))?;
let mut jobs = Vec::with_capacity(gathered.len());
for (path, config, file_config) in gathered {
let select = pick(&opts.select, file_config.lint_select.as_deref());
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, workspace)
.map_err(|e| format!("{}: {e}", path.display()))?;
let options = rule_options(&file_config)?;
jobs.push(Job { path, config, rules, options });
}
let asks = |wants: fn(&'static dyn Rule) -> bool| {
jobs.iter().any(|job| job.rules.iter().any(|rule| wants(*rule)))
};
let wanted = asks(|rule| rule.needs_workspace()) || asks(reads_packages);
let interfaces = asks(reads_interfaces);
let packages = asks(reads_packages);
let census = (workspace && wanted)
.then(|| Census::of(&jobs, workspace && interfaces, workspace && packages));
let mut enabled: Vec<&'static str> =
jobs.iter().flat_map(|job| job.rules.iter().map(|rule| rule.name())).collect();
enabled.sort_unstable();
enabled.dedup();
Ok(Plan { jobs, census, external, enabled })
}
/// The run's external waiver files, read once each: `--waiver-file` in flag
/// order, then every `[lint] waivers` entry of a config file governing an
/// input.
///
/// The two **add up** rather than override: a waiver file only ever suppresses
/// findings, so there is nothing for a command line to take back. A file named
/// twice over — the flag and a `lucisv.toml`, or one `lucisv.toml` governing
/// five hundred files — is read once, or its directives would each be reported
/// unused as many times as the file was read.
///
/// A file that cannot be read, or a directive that does not parse, fails the
/// run naming the file and the line, exactly as a bad `[lint.<rule>]` entry
/// does and for the same reason: a user wrote it and is watching.
pub fn external_waivers<'a>(
opts: &Options,
configs: impl Iterator<Item = &'a FileConfig>,
) -> Result<ExternalWaivers, String> {
let mut paths: Vec<PathBuf> = opts.waiver_files.iter().map(PathBuf::from).collect();
for config in configs {
for path in config.lint_waivers.iter().flatten() {
paths.push(path.clone());
}
}
let mut read: Vec<PathBuf> = Vec::new();
let mut waivers = ExternalWaivers::default();
for path in paths {
// Compared canonically, because the flag's path is relative to the
// working directory and a `lucisv.toml`'s is absolute: the same file
// named both ways is still one file, and reading it twice would report
// each of its dead directives twice. Only the *comparison* is
// canonical — the path a diagnostic names stays the one written.
let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
if read.contains(&key) {
continue;
}
let (file, problems) = ExternalWaivers::read(&path)?;
if let Some(problem) = problems.first() {
return Err(problem.clone());
}
waivers.absorb(file);
read.push(key);
}
Ok(waivers)
}
/// The `[lint.<rule>]` entries of one file's config, resolved against the
/// registry.
///
/// The names and the values are checked **here**, where the registry is, and
/// the first bad entry fails the run naming the config file and the line it
/// was written on — the same treatment a bad `[lint] select` name gets, and
/// for the same reason: a user typed it and is watching.
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
let mut options = RuleOptions::new();
for entry in &file_config.lint_options {
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
let file = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
// The rule is named as well as the option: the table header two
// lines up says which rule it is, and an error a user reads out
// of a CI log has no table header beside it.
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
})?;
}
Ok(options)
}
/// Whether this rule reads the census's **interface** half, which costs a
/// parse of every file in the run rather than a lex.
///
/// By name, because the alternative is a fourth boolean on the `Rule` trait
/// for two rules: `Rule::needs_workspace` already says "this rule asks the
/// project something", and which *question* it asks is between the rule and
/// the oracle. A name that is not in the registry cannot reach here — the
/// rules are `&'static dyn Rule` values from that registry — and a rule added
/// to the pair without being added here answers `None` and goes quiet, which
/// is the safe direction.
fn reads_interfaces(rule: &'static dyn Rule) -> bool {
matches!(rule.name(), "unknown-port" | "unknown-parameter")
}
/// The rule that reads the package table, which costs an index of every file
/// in the run on top of the word census.
fn reads_packages(rule: &'static dyn Rule) -> bool {
rule.name() == "unused-import"
}
/// The command line's list when it said anything, else the config file's.
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
if cli.is_empty() {
config.unwrap_or(&[])
} else {
cli
}
}
/// What linting one file produced.
struct Report {
path: String,
@@ -31,21 +359,51 @@ struct Report {
violations: Vec<Violation>,
/// Violations whose fix was applied and written back.
fixed: usize,
/// Which of the run's external waivers suppressed something in this file.
/// Merged across every file before the dead ones are reported.
used: WaiverUse,
/// Set when the file could not be fully checked: unreadable, unwritable,
/// or — because the lexer is all-or-nothing — unlexable, in which case
/// only the text-level rules saw it.
error: Option<String>,
}
/// Everything one file's lint pass reads besides the file itself.
///
/// One value rather than six parameters: every function below the driver
/// needs the same set, and the `--fix` loop passes it down another level
/// again.
struct Pass<'a> {
config: &'a Config,
rules: &'a [&'static dyn Rule],
options: &'a RuleOptions,
census: Option<&'a Census>,
/// The run's external waiver files. Empty unless `--waiver-file` or a
/// `[lint] waivers` named one, and then costing nothing.
external: &'a ExternalWaivers,
}
/// Lints every gathered file and reports. Exit 1 if anything is left over,
/// 2 if a file could not be read, written, or lexed.
pub fn check_files(
opts: &Options,
jobs: &[(PathBuf, Config)],
rules: &[&'static dyn Rule],
) -> ExitCode {
let mut reports: Vec<Report> =
jobs.par_iter().map(|(file, config)| check_one(file, config, opts, rules)).collect();
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
let mut reports: Vec<Report> = plan
.jobs
.par_iter()
.map(|job| {
let pass = Pass {
config: &job.config,
rules: &job.rules,
options: &job.options,
census: plan.census.as_ref(),
external: &plan.external,
};
check_one(&job.path, opts, &pass)
})
.collect();
// The dead external waivers are found once every file has been linted,
// and reported against the waiver file, which then sorts in among the
// sources like any other path.
reports.extend(dead_waivers(&plan.external, &reports, &plan.enabled));
// Diagnostics are printed sorted by path, then by position within the
// file (`lint` already sorts those), so a run over a directory reads
// top to bottom whatever order the walk or the worker pool produced.
@@ -53,6 +411,37 @@ pub fn check_files(
finish(opts, reports)
}
/// The `unused-waiver` reports for external waivers no file in the run used.
///
/// **After the whole run**, which is the whole reason this is the CLI's job
/// and not the linter's: a `--location` pattern may match a file the run has
/// not reached yet, so a waiver is only dead once every file has been asked.
fn dead_waivers(
external: &ExternalWaivers,
reports: &[Report],
enabled: &[&'static str],
) -> Vec<Report> {
if external.is_empty() {
return Vec::new();
}
let mut used = WaiverUse::default();
for report in reports {
used.merge(&report.used);
}
external
.unused(&used, enabled)
.into_iter()
.map(|dead| Report {
path: dead.path.display().to_string(),
index: LineIndex::new(&dead.text),
violations: dead.violations,
fixed: 0,
used: WaiverUse::default(),
error: None,
})
.collect()
}
/// Lints a buffer piped in on stdin. `--stdin-filename` names it, and is
/// what the rules that need a file name see.
pub fn check_stdin(
@@ -60,25 +449,35 @@ pub fn check_stdin(
src: &str,
config: &Config,
rules: &[&'static dyn Rule],
options: &RuleOptions,
external: &ExternalWaivers,
) -> ExitCode {
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
let (violations, lex_error) = run_rules(src, path, config, rules);
let pass = Pass { config, rules, options, census: None, external };
let (violations, used, lex_error) = run_rules(src, path, &pass);
// Nothing is ever written back for stdin, so `--fix` has nothing to do
// here; the violations are reported as they are.
let error = lex_error.map(|e| format!("{name}: {e}"));
let report = Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error };
finish(opts, vec![report])
let report =
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, used, error };
// One buffer is a whole run too, so a waiver that covered nothing in it is
// as dead as one that covered nothing in a directory.
let names: Vec<&'static str> = rules.iter().map(|rule| rule.name()).collect();
let mut reports = vec![report];
reports.extend(dead_waivers(external, &reports, &names));
finish(opts, reports)
}
/// Lints one file, optionally fixing it, and never panics out of its worker.
fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn Rule]) -> Report {
fn check_one(file: &Path, opts: &Options, pass: &Pass) -> Report {
let path = file.display().to_string();
let failed = |error: String| Report {
path: path.clone(),
index: LineIndex::new(""),
violations: Vec::new(),
fixed: 0,
used: WaiverUse::default(),
error: Some(error),
};
@@ -88,19 +487,19 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
};
let outcome = crate::catch_panic(|| {
if opts.fix {
fix_source(&src, file, config, opts, rules)
fix_source(&src, file, opts, pass)
} else {
let (violations, lex_error) = run_rules(&src, Some(file.to_path_buf()), config, rules);
(violations, None, 0, lex_error)
let (violations, used, lex_error) = run_rules(&src, Some(file.to_path_buf()), pass);
(violations, used, None, 0, lex_error)
}
});
let (violations, rewritten, fixed, lex_error) = match outcome {
let (violations, used, rewritten, fixed, lex_error) = match outcome {
Ok(outcome) => outcome,
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
};
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
if let Some(text) = rewritten {
if let Err(e) = std::fs::write(file, &text) {
if let Err(e) = write_atomic(file, text.as_bytes()) {
return failed(format!("{path}: {e}"));
}
}
@@ -109,19 +508,20 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
// so the file must not pass as checked. It is an error (exit 2), exactly
// as `lucisv format` treats the same file.
let error = lex_error.map(|e| format!("{path}: {e}"));
Report { path, index, violations, fixed, error }
Report { path, index, violations, fixed, used, error }
}
/// Runs the rules over one text. The second half of the answer is the lex
/// error when the text does not lex — rendered `line:col: message`, ready
/// for a path prefix — because a file with no tokens was only text-linted
/// and must be reported as an error, not passed off as clean.
/// Runs the rules over one text, reporting which external waivers fired. The
/// last part of the answer is the lex error when the text does not lex —
/// rendered `line:col: message`, ready for a path prefix — because a file with
/// no tokens was only text-linted and must be reported as an error, not passed
/// off as clean.
fn run_rules(
src: &str,
path: Option<PathBuf>,
config: &Config,
rules: &[&'static dyn Rule],
) -> (Vec<Violation>, Option<String>) {
pass: &Pass,
) -> (Vec<Violation>, WaiverUse, Option<String>) {
let Pass { config, rules, options, census, external } = *pass;
// One parse per file (TODO §4): the products are built here, once, and
// lent to the context. Under `--fix` each *round* re-enters through this
// function with rewritten text — that re-parse is inherent (the old
@@ -129,10 +529,24 @@ fn run_rules(
// saves a parse; a plain `lucisv check` always does.
let parsed = ParsedSource::parse(src);
let lex_error = parsed.lex_error().map(|e| format!("lex error: {e}"));
// This file's own words, off the tokens it was just lexed from rather
// than off a second lex — what the oracle subtracts from the project's
// census so a signal never counts as mentioned by its own declaration.
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
// The indent width the formatter would use is also the width a tab
// expands to, so `--indent 4` fixes tabs into four spaces.
let ctx = parsed.context(path).with_tab_width(config.indent_width);
(lint(&ctx, rules), lex_error)
// expands to, so `--indent 4` fixes tabs into four spaces — and the width
// it would wrap to is the width `line-length` holds the file to.
let ctx = parsed
.context(path)
.with_tab_width(config.indent_width)
.with_line_length(config.max_width)
.with_options(options);
let ctx = match &elsewhere {
Some(elsewhere) => ctx.with_oracle(elsewhere),
None => ctx,
};
let (violations, used) = lint_with(&ctx, rules, external);
(violations, used, lex_error)
}
/// The violations whose fix may be applied: everything except a fix that
@@ -171,13 +585,15 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
fn fix_source(
src: &str,
file: &Path,
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
pass: &Pass,
) -> (Vec<Violation>, WaiverUse, Option<String>, usize, Option<String>) {
let mut text = src.to_string();
let mut fixed = 0;
let (mut violations, mut lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
let mut used = WaiverUse::default();
let (mut violations, mut round_used, mut lex_error) =
run_rules(&text, Some(file.to_path_buf()), pass);
used.merge(&round_used);
for _ in 0..MAX_FIX_ROUNDS {
let round =
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
@@ -186,10 +602,14 @@ fn fix_source(
}
fixed += round.applied;
text = round.output;
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
(violations, round_used, lex_error) = run_rules(&text, Some(file.to_path_buf()), pass);
// A waiver that covered a finding in an earlier round did its job even
// though the fix then removed the finding, so usage accumulates over
// the rounds rather than being the last round's.
used.merge(&round_used);
}
let rewritten = (text != src).then_some(text);
(violations, rewritten, fixed, lex_error)
(violations, used, rewritten, fixed, lex_error)
}
/// Prints the run and turns it into an exit code.
@@ -220,15 +640,23 @@ fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
}
}
/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`.
/// Verible's diagnostic line with the severity word in front of the message:
/// `FILE:LINE:COL: error|warning|style: message [rule-name]`.
///
/// The word sits where a compiler puts it, so the line greps and reads the way
/// every other tool's does, and `grep ': error:'` is the whole of "show me
/// what would not compile".
fn print_text(reports: &[Report]) {
let mut out = String::new();
for report in reports {
for violation in &report.violations {
let (line, col) = position(report, violation);
out.push_str(&format!(
"{}:{line}:{col}: {} [{}]\n",
report.path, violation.message, violation.rule
"{}:{line}:{col}: {}: {} [{}]\n",
report.path,
violation.severity.as_str(),
violation.message,
violation.rule
));
}
}
@@ -244,12 +672,13 @@ fn print_json(reports: &[Report]) {
let (line, col) = position(report, violation);
let (end_line, end_col) = end_position(report, violation);
items.push(format!(
"{{\"filename\":{},\"rule\":{},\"message\":{},\
"{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\
\"location\":{{\"line\":{line},\"column\":{col}}},\
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
quote(&report.path),
quote(violation.rule),
quote(violation.severity.as_str()),
quote(&violation.message),
violation.span.start,
violation.span.end,
+164 -37
View File
@@ -27,17 +27,13 @@ use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use lucisv_core::atomic::write_atomic;
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::Discovery;
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
/// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on
/// input that trips the parser's nesting limit; rayon's own default is
/// 2 MiB, which would put that crash back.
const WORKER_STACK: usize = 8 * 1024 * 1024;
use vlog_parser::PARSE_STACK_SIZE;
fn main() -> ExitCode {
let opts = match args::parse() {
@@ -50,24 +46,60 @@ fn main() -> ExitCode {
// Once, before any worker thread exists, so nothing ever races on it.
install_panic_hook();
// Nothing parses on the main thread, because its stack is not ours to
// state: 8 MiB on a stock macOS or Linux, whatever `ulimit -s` says in a
// container, 1 MiB on Windows. The parser's nesting limit only turns
// over-deep input into an error on a stack of at least
// `PARSE_STACK_SIZE` — below that the overflow, which aborts the
// process, comes first. A thread we spawn is the one stack whose size is
// ours to guarantee. The pool's workers cover the file-at-a-time paths
// (`build_pool`), but not the ones that never reach it: `-` reads and
// formats a buffer right here, and so does `lucisv check -`.
let spawned = std::thread::Builder::new()
.name("lucisv".to_string())
.stack_size(PARSE_STACK_SIZE)
.spawn(move || run(&opts));
let handle = match spawned {
Ok(handle) => handle,
Err(e) => {
eprintln!("error: could not start the worker thread: {e}");
return ExitCode::from(2);
}
};
match handle.join() {
Ok(code) => code,
// An uncontained panic, already printed by the hook above. 101 is
// what the same panic on the main thread would have exited with.
Err(_) => ExitCode::from(101),
}
}
/// The run itself, on the stack `main` sized for it.
fn run(opts: &Options) -> ExitCode {
match opts.command {
Command::Format if opts.is_stdin() => run_stdin(&opts),
Command::Format => run_files(&opts),
Command::Check => run_check(&opts),
Command::Format if opts.is_stdin() => run_stdin(opts),
Command::Format => run_files(opts),
Command::Check => run_check(opts),
}
}
/// `lucisv check`: the linter over the same file set the formatter would take.
fn run_check(opts: &Options) -> ExitCode {
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// Before any rule is selected and before any path is gathered: the rule
// reference is a property of the build, not of a run over files.
if opts.rules_doc {
print!("{}", vlog_linter::rules_markdown());
return ExitCode::SUCCESS;
}
// The command line's own names are checked before anything is walked, so
// a typo'd `--select` fails in milliseconds rather than after the scan.
// A `lucisv.toml`'s names are checked per file below, where they are read.
if let Err(e) = vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
eprintln!("error: {e}");
return ExitCode::from(2);
}
if opts.is_stdin() {
let config = match stdin_config(opts) {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -79,7 +111,34 @@ fn run_check(opts: &Options) -> ExitCode {
eprintln!("error: reading stdin: {e}");
return ExitCode::from(2);
}
return lint::check_stdin(opts, &src, &config, &rules);
// A stdin buffer is one text with nothing around it: there is no
// census to build and no other file to ask about, so the rules that
// need a project stay off. `--select` still reaches them.
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it exactly as `[lint] select` does.
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
Ok(external) => external,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -88,12 +147,18 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
};
lint::check_files(opts, &jobs, &rules)
match lint::plan(opts, jobs) {
Ok(plan) => lint::check_files(opts, &plan),
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(2)
}
}
}
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let config = match stdin_config(opts) {
let (config, _file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -149,11 +214,11 @@ fn run_files(opts: &Options) -> ExitCode {
// The cache is only read here; entries ride back with the results and
// are recorded serially below, so nothing is shared mutably.
let results: Vec<FileResult> =
jobs.par_iter().map(|(file, config)| process_file(file, config, opts, &cache)).collect();
jobs.par_iter().map(|(file, config, _)| process_file(file, config, opts, &cache)).collect();
let (mut changed, mut unchanged, mut errors, mut cached) = (0usize, 0usize, 0usize, 0usize);
for (index, result) in results.into_iter().enumerate() {
let (file, config) = &jobs[index];
let (file, config, _) = &jobs[index];
if let Some(content) = result.clean {
cache.record(file, entry_for(content, config));
}
@@ -252,7 +317,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
} else if opts.check {
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
} else if let Err(e) = std::fs::write(file, &out) {
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
} else {
// The bytes now on disk are formatted, so they are what the cache
@@ -268,15 +333,21 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
/// the key, not the config file that produced them, so identical settings
/// from different `lucisv.toml` files share entries.
fn entry_for(content: u64, config: &Config) -> Entry {
Entry { content, line_length: config.max_width, indent: config.indent_width }
Entry {
content,
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
}
}
/// Builds rayon's global pool. Worker stacks are sized for the parser's
/// recursion limit (see `WORKER_STACK`); `--threads 0` lets rayon pick.
/// recursion limit (`PARSE_STACK_SIZE` — rayon's own default is 2 MiB, which
/// would put the overflow back); `--threads 0` lets rayon pick the count.
fn build_pool(opts: &Options) -> Result<(), String> {
rayon::ThreadPoolBuilder::new()
.num_threads(opts.thread_count())
.stack_size(WORKER_STACK)
.stack_size(PARSE_STACK_SIZE)
.build_global()
.map_err(|e| format!("could not start the worker pool: {e}"))
}
@@ -287,7 +358,7 @@ fn build_pool(opts: &Options) -> Result<(), String> {
/// filelists name (exact paths, filtered by neither — they were named).
/// Every config file is read here, before anything is written, so a broken
/// one aborts the whole run instead of leaving it half applied.
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String> {
let mut discovery = Discovery::new(!opts.no_config);
let mut files = Vec::new();
for input in &opts.inputs {
@@ -300,7 +371,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
return Err(format!("--lines needs a file, not a directory: {input}"));
}
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
// The walk's own warnings — an unreadable directory, a source file
// that is only a broken link — go to stderr as they are found, before
// the report and exactly as a filelist's do. A warning is not a
// failure: the exit code is the formatting's alone.
let mut warn = |w| eprintln!("warning: {w}");
collect_files(input, &exclude, !opts.no_gitignore, &mut files, &mut warn)?;
}
// Filelists come after the command line's own inputs, in flag order: they
// add files, they never replace or reorder what was named directly.
@@ -311,8 +387,13 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
}
let mut jobs = Vec::with_capacity(files.len());
for file in files {
let config = opts.config_with(&discovery.for_file(&file)?);
jobs.push((file, config));
// The whole `FileConfig` rides along, not just the formatter settings
// it resolves to: `lucisv check` needs its `[lint]` keys too, and
// discovering them a second time would read every config file twice
// and could answer differently if one changed underneath the run.
let file_config = discovery.for_file(&file)?;
let config = opts.config_with(&file_config);
jobs.push((file, config, file_config));
}
Ok(jobs)
}
@@ -344,13 +425,25 @@ fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut seen = HashSet::new();
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect()
}
/// The key two spellings of one file share: the file's canonical path when it
/// is there, and the lexical fold when it is not.
///
/// Canonical means symlinks resolved, which is the only way to see that
/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one
/// target otherwise, each rewriting what the other just wrote. A path with no
/// file behind it has no canonical form, and the lexical fold is then the
/// best two names for it can be compared by. Neither is ever the path lucisv
/// reports: that stays the first spelling seen.
fn identity(cwd: &Path, path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are
/// deliberately left unresolved, so this is only ever a dedup key and never
/// the path lucisv reports.
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
/// answers for paths that do not exist, where there is nothing to resolve.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
@@ -368,13 +461,16 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// The settings for a buffer piped in on stdin: discovery anchors on
/// `--stdin-filename`'s directory when given, else on the current one.
fn stdin_config(opts: &Options) -> Result<Config, String> {
/// The formatter config a stdin buffer is served with, and the `lucisv.toml`
/// it came from — the linter needs the file's own `[lint.<rule>]` entries,
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
Ok(opts.config_with(&file))
Ok((opts.config_with(&file), file))
}
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
@@ -528,6 +624,37 @@ mod tests {
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
}
#[cfg(unix)]
#[test]
fn dedup_folds_a_symlink_onto_the_file_it_points_at() {
// A directory walk lists `b.sv` as a file of its own; lexically the
// two names share nothing, and two workers would rewrite one file.
let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let real = dir.join("a.sv");
let link = dir.join("b.sv");
std::fs::write(&real, "module m;\nendmodule\n").expect("seed");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real));
// Whichever spelling comes first is the one kept and reported.
assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link));
// And a `..` detour through the same link is still the same file.
std::fs::create_dir(dir.join("sub")).expect("sub dir");
let detour = dir.join("sub/../b.sv");
assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real));
// A file that is not there has no canonical path: the key is lexical,
// which still folds `.` and `..`, and two missing files stay two.
let gone = dir.join("gone.sv");
let same = dir.join("./sub/../gone.sv");
let other = dir.join("other.sv");
assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
+733 -8
View File
@@ -136,6 +136,57 @@ fn formats_files_in_place() {
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
}
/// A directory walk lists a symlink as a file of its own, so `b.sv -> a.sv`
/// used to put two workers on one file: two report lines for one file, and
/// two writers racing to replace it. It is one file now, named once.
#[cfg(unix)]
#[test]
fn a_symlink_and_its_target_are_one_file() {
let dir = TempDir::new("alias");
dir.write("a.sv", UNFORMATTED);
std::os::unix::fs::symlink(dir.path.join("a.sv"), dir.path.join("b.sv")).expect("symlink");
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let reported = stdout(&out);
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
assert_eq!(named.len(), 1, "one file, one line: {named:?}");
assert!(named[0].ends_with("a.sv"), "the first spelling walked is the one reported: {named:?}");
assert!(stderr(&out).contains("1 file would be reformatted"), "{}", stderr(&out));
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file reformatted"), "{}", stderr(&out));
assert_eq!(dir.read("a.sv"), FORMATTED);
assert_eq!(dir.read("b.sv"), FORMATTED, "and the link still reaches it");
assert!(
std::fs::symlink_metadata(dir.path.join("b.sv")).expect("stat").file_type().is_symlink(),
"the link was not replaced by a copy"
);
}
/// A directory that links back into itself. Before the walk kept a visited
/// set (`docs/features/walk-cycles/README.md`) this run recursed until the
/// OS refused the path; now each directory is entered once, so each file is
/// named once — under the first spelling that reaches it.
#[cfg(unix)]
#[test]
fn a_symlink_cycle_terminates_and_names_each_file_once() {
let dir = TempDir::new("cycle");
dir.write("rtl/a.sv", UNFORMATTED);
dir.write("rtl/sub/b.sv", UNFORMATTED);
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level down.
std::os::unix::fs::symlink("../rtl", dir.path.join("rtl/self")).expect("symlink");
std::os::unix::fs::symlink("..", dir.path.join("rtl/sub/up")).expect("symlink");
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let reported = stdout(&out);
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
assert_eq!(named.len(), 2, "two files, two lines: {named:?}");
assert!(stderr(&out).contains("2 files would be reformatted"), "{}", stderr(&out));
}
#[test]
fn check_reports_without_writing() {
let dir = TempDir::new("check");
@@ -407,7 +458,8 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
// costs two levels), so it parses — and needs several MiB of stack to
// do it in a debug build: without the depth limit this family died at
// 15 levels on a 2 MiB thread, which is exactly rayon's default worker
// stack. This test crashes the process if the pool's 8 MiB is dropped.
// stack. This test crashes the process if the pool's `PARSE_STACK_SIZE`
// is dropped.
let deep = format!(
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
"if (clk) begin\n".repeat(28),
@@ -425,6 +477,34 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
assert!(stdout(&out).contains("deep.sv"), "{}", stdout(&out));
}
#[test]
fn a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash() {
// The stdin path never touches the worker pool: it formats on the thread
// `main` spawned, which is the only stack whose size lucisv gets to
// state. 500 nested blocks are far past the parser's limit, so the run
// must end with an ordinary parse error — and not with a SIGABRT, which
// is what an unstated stack gives instead.
let deep = format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(500),
"end\n".repeat(500)
);
let out = run_with_stdin(&["-"], &deep);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("nesting too deep"), "{}", stderr(&out));
assert!(stdout(&out).is_empty(), "a rejected buffer prints nothing: {}", stdout(&out));
// And the deepest *legal* buffer formats on that same stack.
let legal = format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(58),
"end\n".repeat(58)
);
let out = run_with_stdin(&["-"], &legal);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stdout(&out).contains("endmodule"), "{}", stdout(&out));
}
#[test]
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
let dir = TempDir::new("configpar");
@@ -633,7 +713,7 @@ fn a_broken_config_exits_2_before_writing_anything() {
for (contents, expected) in [
("indent = 99\n", "between 1 and 8"),
("line-length = wide\n", "expects an integer"),
("[tool.lucisv]\nindent = 2\n", "tables"),
("[tool.lucisv]\nindent = 2\n", "unknown table"),
("exclude = [\n \"a\",\n]\n", "multi-line arrays are unsupported"),
] {
dir.write("lucisv.toml", contents);
@@ -724,7 +804,9 @@ fn check_reports_violations_and_exits_1() {
let out = run(&["check", &path]);
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
let text = stdout(&out);
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
// `FILE:LINE:COL: severity: message [rule]` — the severity word is part
// of the line since §33.0, and both of these are style findings.
assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}");
assert!(text.contains("[no-tabs]"), "{text}");
assert!(text.contains("[module-filename]"), "{text}");
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
@@ -768,6 +850,7 @@ fn check_json_is_one_array_with_positions_and_fixes() {
assert!(text.starts_with('['), "{text}");
assert!(text.trim_end().ends_with(']'), "{text}");
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
assert!(text.contains("\"severity\":\"style\""), "{text}");
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
assert!(text.contains("\"content\":\" \""), "{text}");
@@ -866,6 +949,30 @@ fn check_select_and_ignore_pick_the_rule_set() {
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
}
/// A severity word stands for its whole class wherever a rule name fits —
/// §33.0's headline for the command line.
#[test]
fn check_select_and_ignore_accept_a_severity_word() {
let dir = TempDir::new("check-severity");
// `reg` is an error-class finding, the tab and the name are style ones.
let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n");
let out = run(&["check", "--select", "error", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
let text = stdout(&out);
assert_eq!(text.lines().count(), 1, "{text}");
assert!(text.contains(": error: "), "{text}");
assert!(text.contains("[wire-reg-mixup]"), "{text}");
let out = run(&["check", "--ignore", "style", &path]);
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out));
// Ignoring every class leaves nothing to report.
let out = run(&["check", "--ignore", "error,warning,style", &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
}
#[test]
fn check_honors_inline_waivers_and_reports_dead_ones() {
let dir = TempDir::new("check-waive");
@@ -879,6 +986,89 @@ fn check_honors_inline_waivers_and_reports_dead_ones() {
assert!(stdout(&out).contains("[unused-waiver]"), "{}", stdout(&out));
}
/// Two tabbed lines, one of which a waiver file's `--line` covers.
const TABBED: &str = "module foo;\n\twire a;\n\twire b;\nendmodule\n";
/// `--waiver-file`: the suppression, the flag repeated, and the dead directive
/// reported at the waiver file's own line. TODO §39.
#[test]
fn check_reads_external_waiver_files() {
let dir = TempDir::new("check-waiver-file");
let path = dir.write("foo.sv", TABBED);
let one = dir.write("one.waiver", "# just line 2\nwaive --rule=no-tabs --line=2\n");
let out = run(&["check", "--waiver-file", &one, &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
assert_eq!(stdout(&out).lines().count(), 1, "one tab left: {}", stdout(&out));
assert!(stdout(&out).contains("foo.sv:3:1"), "{}", stdout(&out));
// A second file adds to the first rather than replacing it, and both are
// then used, so neither is reported.
let two = dir.write("two.waiver", "waive --rule=no-tabs --line=3 --location=foo.sv\n");
let out = run(&["check", "--waiver-file", &one, "--waiver-file", &two, &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
// A directive that covered nothing is reported against the waiver file.
let dead = dir.write("dead.waiver", "waive --rule=no-tabs --location=elsewhere.sv\n");
let out = run(&["check", "--waiver-file", &dead, &path]);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.contains("dead.waiver:1:1: style: unused waiver for `no-tabs`"), "{text}");
assert!(text.contains("[unused-waiver]"), "{text}");
}
/// The `[lint] waivers` key, and that `--waiver-file` adds to it. TODO §39.
#[test]
fn check_reads_the_waiver_files_a_config_file_names() {
let dir = TempDir::new("check-waiver-toml");
let path = dir.write("rtl/foo.sv", TABBED);
dir.write("lucisv.toml", "[lint]\nwaivers = [ \"project.waiver\" ]\n");
dir.write("project.waiver", "waive --rule=no-tabs --line=2\n");
// Relative to the config file, not to the working directory.
let out = run_raw(&["check", "--no-cache", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("foo.sv:3:1"), "only line 3 survives: {}", stdout(&out));
let extra = dir.write("extra.waiver", "waive --rule=no-tabs --line=3\n");
let out = run_raw(&["check", "--no-cache", "--waiver-file", &extra, &path]);
assert_eq!(code(&out), 0, "the two lists add up: {}", stdout(&out));
// `--no-config` drops the config file's list with everything else in it.
let out = run_raw(&["check", "--no-cache", "--no-config", &path]);
assert_eq!(code(&out), 1);
assert_eq!(stdout(&out).lines().count(), 2, "both tabs are back: {}", stdout(&out));
}
/// A waiver file that cannot be read, or that has a line that does not parse,
/// fails the run with `<file>:<line>: message` and exit 2. TODO §39.
#[test]
fn a_broken_waiver_file_fails_the_run() {
let dir = TempDir::new("check-waiver-bad");
let path = dir.write("foo.sv", TABBED);
let out = run(&["check", "--waiver-file", &dir.write("x.waiver", "hush\n"), &path]);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("x.waiver:1: expected a `waive` directive"), "{}", stderr(&out));
let bad = dir.write("y.waiver", "# fine\nwaive --rule=no-such-rule\n");
let out = run(&["check", "--waiver-file", &bad, &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("y.waiver:2: unknown rule"), "{}", stderr(&out));
let regexy = dir.write("z.waiver", "waive --rule=no-tabs --location=.*foo.sv\n");
let out = run(&["check", "--waiver-file", &regexy, &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("looks like a regular expression"), "{}", stderr(&out));
let out = run(&[
"check",
"--waiver-file",
&dir.path.join("gone.waiver").display().to_string(),
&path,
]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("gone.waiver:"), "{}", stderr(&out));
}
#[test]
fn check_reads_stdin_and_names_it() {
let out = run_with_stdin(&["check", "--stdin-filename", "rtl/z.sv", "-"], LINTY);
@@ -1077,16 +1267,18 @@ impl TempDir {
}
}
/// One hand-written cache line, for the tests that forge entries.
/// One hand-written cache line, for the tests that forge entries. The
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
fn cache_line(
path: &str,
content: &str,
line_length: usize,
indent: usize,
uvm: bool,
version: &str,
) -> String {
let hash = lucisv_core::cache::content_hash(content.as_bytes());
format!("{hash:016x}\t{line_length}\t{indent}\t{version}\t{path}\n")
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
}
#[test]
@@ -1173,7 +1365,8 @@ fn a_hit_skips_the_work_entirely() {
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 2, "without an entry this file is an error");
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, VERSION)).unwrap();
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, false, VERSION))
.unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "a hit does no work at all: {}", stderr(&out));
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
@@ -1198,6 +1391,65 @@ fn a_config_file_change_invalidates_the_entry_too() {
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
}
/// A UVM class whose layout depends on `[format] uvm-utils-indent`: with the
/// option on, the `` `uvm_field_* `` macro gains a level. Written here as the
/// formatter leaves it with the option *off*.
const UVM_CLASS: &str = "class c extends uvm_object;\n `uvm_object_utils_begin(c)\n \
`uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
#[test]
fn changing_uvm_utils_indent_invalidates_the_entry() {
let dir = TempDir::new("cache-uvm");
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
let path = dir.write("a.sv", UVM_CLASS);
let cache = dir.cache();
// Clean with the option off, and that verdict is cached.
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
let flat = dir.read("a.sv");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
// Turning the option on must not hit the entry the option-off run left.
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "uvm-utils-indent is part of the key: {}", stderr(&out));
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
// Format under the option on, cache *that*, then flip back off.
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
assert_ne!(dir.read("a.sv"), flat, "the option really does change the output");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "and the other direction too: {}", stderr(&out));
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
}
#[test]
fn a_store_written_before_the_option_joined_the_key_is_rebuilt() {
let dir = TempDir::new("cache-oldshape");
let path = dir.write("a.sv", FORMATTED);
let cache = dir.cache();
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
// The five-field line lucisv wrote before `uvm-utils-indent` was in the
// key. Not corruption: the line is dropped on its own and the run
// rebuilds the store in the current shape.
let hash = lucisv_core::cache::content_hash(FORMATTED.as_bytes());
std::fs::write(dir.cache_file(), format!("{hash:016x}\t100\t2\t{VERSION}\t{path}\n")).unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "an older store is never an error: {}", stderr(&out));
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert!(stderr(&out).contains("1 file from cache"), "the store was rebuilt: {}", stderr(&out));
}
#[test]
fn an_entry_from_another_lucisv_version_is_ignored() {
let dir = TempDir::new("cache-version");
@@ -1207,13 +1459,14 @@ fn an_entry_from_another_lucisv_version_is_ignored() {
// A forged entry claiming this unformatted file is clean. With this
// version's stamp it is believed…
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, VERSION)).unwrap();
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, VERSION))
.unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "the forged entry proves entries are really read");
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
// …and with any other version's stamp it is not.
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, "0.0.0-other"))
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, "0.0.0-other"))
.unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "another version's entry must not be trusted: {}", stderr(&out));
@@ -1698,3 +1951,475 @@ fn help_documents_the_filelist_flag() {
assert!(text.contains("-f <FILELIST>"), "{text}");
assert!(text.contains("read by lucisv-server only"), "the toml key stays server-only: {text}");
}
// ----------------------------------------------------------------------
// The semantic rules and the project census (semantic-lints-on, 2026-09-02)
// ----------------------------------------------------------------------
/// A module whose `dbg_probe` only a *second* file reads, hierarchically.
const DUT: &str = "module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n";
const TB: &str = "module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n";
/// The round's headline: over a project the semantic rules run by default,
/// and the file that reads `d.dbg_probe` is what keeps `dbg_probe` quiet.
/// `dead`, which nothing anywhere writes down twice, is still reported.
#[test]
fn a_mention_in_another_file_silences_unused_signal_over_a_project() {
let dir = TempDir::new("census");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(text.contains("`dead` is declared but never used"), "{text}");
assert!(!text.contains("dbg_probe"), "the other file reads it: {text}");
assert_eq!(code(&out), 1);
}
/// One file is not a project: there is nothing to ask, so the rules that
/// need a workspace stay off and the run is exactly v0.29.0's.
#[test]
fn a_single_file_run_leaves_the_semantic_rules_off() {
let dir = TempDir::new("alone");
let dut = dir.write("dut.sv", DUT);
let out = run(&["check", &dut]);
assert_eq!(stdout(&out), "");
assert_eq!(code(&out), 0);
// ... and naming the rule still runs it, oracle or no oracle.
let named = run(&["check", &dut, "--select", "unused-signal"]);
let text = stdout(&named);
assert!(text.contains("dbg_probe"), "{text}");
assert!(text.contains("dead"), "{text}");
assert_eq!(code(&named), 1);
}
/// A stdin buffer has no project either, and no file to build one from.
#[test]
fn a_stdin_buffer_leaves_the_semantic_rules_off() {
let out = run_with_stdin(&["check", "-"], DUT);
assert_eq!(stdout(&out), "");
assert_eq!(code(&out), 0);
let named = run_with_stdin(&["check", "-", "--select", "unused-signal"], DUT);
assert!(stdout(&named).contains("dbg_probe"), "{}", stdout(&named));
}
/// The off switch a default-on rule owes its users: `[lint] ignore` in the
/// `lucisv.toml` governing the files.
#[test]
fn a_lint_table_in_the_config_turns_a_rule_off() {
let dir = TempDir::new("lint-table");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the config silenced the rule");
assert_eq!(code(&out), 0);
}
/// `[lint] select` replaces the default set, exactly as `--select` does.
#[test]
fn a_lint_table_can_select_instead_of_ignore() {
let dir = TempDir::new("lint-select");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nselect = [\"unused-signal\"]\n");
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(text.contains("`dead` is declared but never used"), "{text}");
assert!(!text.contains("dbg_probe"), "{text}");
}
/// Precedence, key by key: the command line beats the config file, and a key
/// the command line does not mention stays the config file's.
#[test]
fn the_command_line_beats_the_lint_table() {
let dir = TempDir::new("lint-precedence");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
// `--ignore` replaces the config's ignore list, so `unused-signal` is back.
let out = run(&["check", &dir.root(), "--ignore", "no-tabs"]);
assert!(stdout(&out).contains("`dead` is declared but never used"), "{}", stdout(&out));
// `--select` replaces the default set; the config's ignore still applies.
let selected = run(&["check", &dir.root(), "--select", "unused-signal,no-tabs"]);
assert_eq!(stdout(&selected), "", "the config's ignore survives a CLI select");
}
/// An unknown rule name in a config file fails the run and says what is
/// known — the same answer a typo'd `--select` gets, named by file.
#[test]
fn an_unknown_rule_in_the_lint_table_is_an_error() {
let dir = TempDir::new("lint-unknown");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"no-such-rule\"]\n");
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains("unknown rule: no-such-rule"), "{text}");
assert!(text.contains("unused-signal"), "the error lists what is known: {text}");
assert_eq!(code(&out), 2);
}
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
/// with it — §34.0's headline claim, end to end through the real binary.
#[test]
fn a_per_rule_lint_table_changes_the_verdict() {
let dir = TempDir::new("lint-per-rule");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
dir.write("m.sv", &wide);
let out = run(&["check", &dir.root()]);
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the option raised the limit");
assert_eq!(code(&out), 0);
}
/// A bad entry fails the run naming the config file and the line, which is
/// what tells a user *where* to fix it.
#[test]
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
let dir = TempDir::new("lint-bad-option");
dir.write("m.sv", "module m;\nendmodule\n");
for (config, wanted) in [
("[lint.line-length]\nlength = 10\n", "must be between"),
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
// An escape from another dialect must be refused rather than read
// as a literal, which would silently judge the wrong names (QA,
// 2026-09-04).
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
] {
dir.write("lucisv.toml", config);
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains(wanted), "{config:?}: {text}");
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
assert_eq!(code(&out), 2, "{config:?}");
}
// Every one of them names the rule as well as the option, so an error
// read out of a CI log stands on its own.
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
let text = stderr(&run(&["check", &dir.root()]));
assert!(text.contains("rule `line-length`"), "{text}");
assert!(text.contains("`length` must be between"), "{text}");
}
/// The width `line-length` holds a file to is the width the formatter is
/// configured with, so the two halves of lucisv cannot disagree.
#[test]
fn line_length_follows_the_formatters_width() {
let dir = TempDir::new("lint-width");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
dir.write("m.sv", &wide);
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
dir.write("lucisv.toml", "line-length = 80\n");
let from_config = run(&["check", &dir.root()]);
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
}
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
#[test]
fn a_stdin_buffer_reads_the_rule_options_too() {
let dir = TempDir::new("lint-stdin-options");
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
/// RTL signal only inside a macro argument — `` `uvm_info(..., $sformatf("%b",
/// dut.sig), ...) ``, the commonest VPI-probe shape there is — must silence
/// `unused-signal` for that signal. The lexer hands the whole invocation over
/// as one token, so this works only because the census splits it.
#[test]
fn a_signal_named_only_inside_a_macro_argument_is_not_reported_unused() {
let dir = TempDir::new("macroarg");
dir.write("dut.sv", DUT);
dir.write(
"tb.sv",
"module tb;\n dut u_dut ();\n initial begin\n\
\x20 `uvm_info(\"tb\", $sformatf(\"probe=%b\", u_dut.dbg_probe), UVM_LOW)\n\
\x20 end\nendmodule\n",
);
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(!text.contains("dbg_probe"), "the macro argument names it: {text}");
assert!(text.contains("`dead` is declared but never used"), "and `dead` still reports: {text}");
// The format string is a value: a signal called `probe` in another file
// must not be silenced by `"probe=%b"` here.
let other = TempDir::new("macroargstring");
other.write("a.sv", "module a;\n logic probe;\nendmodule\n");
other.write(
"b.sv",
"module b;\n initial `uvm_info(\"t\", $sformatf(\"probe=%b\", 1'b0), UVM_LOW)\nendmodule\n",
);
assert!(
stdout(&run(&["check", &other.root()])).contains("`probe` is declared but never used"),
"a string's contents are not mentions"
);
}
/// `lucisv check --rules-doc` prints the generated rule reference and nothing
/// else. Generated from the registry, so a rule added without documentation
/// still shows up here — which is the whole point of the flag.
#[test]
fn rules_doc_prints_the_generated_reference() {
let out = run(&["check", "--rules-doc"]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert_eq!(text.lines().next(), Some("# lucisv lint rules"), "{text}");
for rule in vlog_linter::all_rules() {
let heading = format!("\n## {}\n", rule.name());
assert_eq!(
text.matches(&heading).count(),
1,
"`{}` wants exactly one section in the reference",
rule.name()
);
}
// The flag is the tool now, so it agrees with the library by construction.
assert_eq!(text, vlog_linter::rules_markdown());
}
/// The flag lints nothing, so a path beside it is a command line that means
/// two different things — refused rather than silently ignored.
#[test]
fn rules_doc_refuses_files_and_belongs_to_check() {
let dir = TempDir::new("rulesdoc");
let file = dir.write("m.sv", FORMATTED);
let out = run(&["check", "--rules-doc", &file]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("--rules-doc takes no files"), "{}", stderr(&out));
let out = run(&["format", "--rules-doc"]);
assert_eq!(code(&out), 2);
assert!(
stderr(&out).contains("--rules-doc is only valid for `lucisv check`"),
"{}",
stderr(&out)
);
}
// --- the walk's own warnings (docs/features/small-items-4/README.md) -------
/// A tree with the two things the walk can only warn about: a directory it
/// cannot read, and a source file that is only a broken link.
#[cfg(unix)]
fn unwalkable_tree(tag: &str) -> TempDir {
use std::os::unix::fs::{symlink, PermissionsExt};
let dir = TempDir::new(tag);
dir.write("a.sv", UNFORMATTED);
dir.write("z/late.sv", UNFORMATTED);
dir.write("locked/hidden.sv", UNFORMATTED);
symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
dir
}
#[cfg(unix)]
fn lock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
}
#[cfg(unix)]
fn unlock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
let _ =
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
// The finding TODO §45.2 closes: one permission-denied directory used to
// propagate `read_dir`'s error and fail the whole run.
let dir = unwalkable_tree("walk-warn");
let out = run(&[&dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "a warning is not a failure: {}", stderr(&out));
let said = stderr(&out);
assert_eq!(said.matches("warning: ").count(), 2, "{said}");
assert!(said.contains("locked"), "{said}");
assert!(said.contains("gone.sv: broken symbolic link"), "{said}");
assert_eq!(dir.read("a.sv"), FORMATTED, "the other files were formatted");
assert_eq!(dir.read("z/late.sv"), FORMATTED, "including the ones sorted after it");
}
#[test]
#[cfg(unix)]
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
let dir = unwalkable_tree("walk-warn-check");
let out = run(&["--check", &dir.root()]);
unlock(&dir);
// `--check` answers on formatting alone: two files would be reformatted.
assert_eq!(code(&out), 1, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
assert!(!stdout(&out).contains("warning"), "warnings stay off stdout: {}", stdout(&out));
// And with nothing left to reformat the run is clean, warnings and all.
dir.write("a.sv", FORMATTED);
dir.write("z/late.sv", FORMATTED);
lock(&dir);
let out = run(&["--check", &dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
// The walk drops the link; a path the user typed is not walked at all, so
// "no such file or directory" is still what naming one gets.
let dir = TempDir::new("walk-warn-named");
std::os::unix::fs::symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
let named = dir.path.join("gone.sv").to_string_lossy().into_owned();
let out = run(&[&named]);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
}
// ----------------------------------------------------------------------
// The package half of the census and `unused-import` (perf5-p3, 2026-09-07)
// ----------------------------------------------------------------------
/// A package with two exported names, and the two importers the rule has to
/// tell apart.
const PKG: &str = "package p_pkg;\n localparam int A = 1;\n localparam int B = 2;\nendpackage\n";
const USES_PKG: &str = "module uses_pkg;\n import p_pkg::*;\n localparam int C = A;\nendmodule\n";
const IGNORES_PKG: &str =
"module ignores_pkg;\n import p_pkg::*;\n localparam int C = 1;\nendmodule\n";
/// The style selection the rule lives in — `unused-import` is `Severity::Style`
/// and so is off in a default `check`.
const ALL_STYLE: [&str; 2] = ["--select", "error,warning,style"];
/// The headline: over a project, an import nothing in its file uses is
/// reported, and one the file does use is not — and it is the *package
/// census* that makes the difference, because the rule can only judge an
/// import whose package the run can answer for.
#[test]
fn an_unused_package_import_is_reported_over_a_project() {
let dir = TempDir::new("pkg-census");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write("ignores_pkg.sv", IGNORES_PKG);
let out = run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]);
let text = stdout(&out);
assert!(text.contains("unused-import"), "{text}");
assert!(text.contains("ignores_pkg.sv"), "{text}");
assert!(
!text.lines().any(|line| line.contains("uses_pkg.sv") && line.contains("unused-import")),
"the file that reads `A` keeps its import: {text}"
);
assert_eq!(code(&out), 1);
}
/// `unused-import` is a style rule, so a default `check` neither reports it
/// nor is changed by the presence of a package in the run.
#[test]
fn a_default_check_says_nothing_about_imports() {
let dir = TempDir::new("pkg-default");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write("ignores_pkg.sv", IGNORES_PKG);
let out = run(&["check", &dir.root()]);
assert!(!stdout(&out).contains("unused-import"), "{}", stdout(&out));
}
/// A package the run does not contain is a package the run cannot answer
/// for, and the rule is silent about every import of it. This is the
/// conservative direction the whole feature is built around: an accusation
/// needs a known export list.
#[test]
fn an_import_of_a_package_outside_the_run_is_not_reported() {
let dir = TempDir::new("pkg-unknown");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write(
"stranger.sv",
"module stranger;\n import elsewhere_pkg::*;\n localparam int C = 1;\nendmodule\n",
);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("elsewhere_pkg"), "an unknown package is unknowable: {text}");
}
/// A package that re-exports from another one answers `None`: only a whole
/// project index settles what a re-export chain lets through, and the CLI's
/// one-file census will not guess. Every import of it goes quiet.
#[test]
fn an_import_of_a_re_exporting_package_is_not_reported() {
let dir = TempDir::new("pkg-reexport");
dir.write("p_pkg.sv", PKG);
dir.write(
"r_pkg.sv",
"package r_pkg;\n import p_pkg::*;\n export p_pkg::*;\n localparam int D = 1;\n\
endpackage\n",
);
dir.write(
"ignores_r.sv",
"module ignores_r;\n import r_pkg::*;\n localparam int C = 1;\nendmodule\n",
);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("r_pkg"), "a re-export chain is unknowable: {text}");
}
/// Two files declaring one package name is a name the run cannot answer for,
/// whatever the two say — `Census::of`'s merge turns the second contribution
/// into `None`, and the rule goes quiet about it.
#[test]
fn an_import_of_a_package_two_files_declare_is_not_reported() {
let dir = TempDir::new("pkg-duplicate");
dir.write("p_pkg.sv", PKG);
dir.write("p_pkg_copy.sv", "package p_pkg;\n localparam int Z = 9;\nendpackage\n");
dir.write("ignores_pkg.sv", IGNORES_PKG);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("unused-import"), "a duplicate package is unknowable: {text}");
}
/// The gate is a claim about *cost*, not about answers, so the answers get
/// their own end-to-end pin: a run whose only package file is surrounded by
/// files holding the word `package` in strings and comments reports exactly
/// what a run without those files reports.
#[test]
fn text_that_merely_says_package_changes_no_finding() {
let bare = TempDir::new("pkg-bare");
bare.write("p_pkg.sv", PKG);
bare.write("ignores_pkg.sv", IGNORES_PKG);
let plain = stdout(&run(&["check", &bare.root(), ALL_STYLE[0], ALL_STYLE[1]]));
let noisy = TempDir::new("pkg-noisy");
noisy.write("p_pkg.sv", PKG);
noisy.write("ignores_pkg.sv", IGNORES_PKG);
noisy.write(
"talker.sv",
"// package q_pkg; endpackage\n\
module talker;\n initial $display(\"package q_pkg; endpackage\");\nendmodule\n",
);
let with_noise = stdout(&run(&["check", &noisy.root(), ALL_STYLE[0], ALL_STYLE[1]]));
for finding in plain.lines().filter(|line| line.contains("unused-import")) {
let tail = finding.rsplit('/').next().unwrap_or(finding);
assert!(with_noise.contains(tail), "{tail} lost: {with_noise}");
}
assert_eq!(
plain.matches("unused-import").count(),
with_noise.matches("unused-import").count(),
"{plain}\n---\n{with_noise}"
);
}
+451
View File
@@ -0,0 +1,451 @@
//! Replacing a file's contents without ever leaving it half written.
//!
//! `fs::write` truncates the target and then writes into it, so a crash, a
//! full disk or a `^C` between the two leaves the user's source truncated —
//! and lucisv's first invariant is that it never corrupts code. Every
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
//! gets the bytes, and a `rename` over the target publishes them in one step
//! that either happened or did not.
//!
//! Two threads of one process may write one target: the temp names carry a
//! per-process counter as well as the pid and are created with `O_EXCL`, so
//! each writer owns its own file and neither can see the other's bytes.
//!
//! Two *processes* writing one target are not coordinated, and deliberately
//! so. Both renames are atomic, the later one wins, and the loser's bytes are
//! discarded whole — never merged. Both processes formatted the same input
//! and `format` is idempotent, so whichever rename lands last leaves the
//! file complete and correctly formatted. A lock would buy nothing and would
//! be one more thing to leave behind after a `^C`.
//!
//! See `docs/features/small-items-3/README.md` and
//! `docs/features/atomic-write-coordination/README.md`.
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Writes `bytes` to `path`, replacing whatever was there in one step.
///
/// A temp file beside the target takes the bytes, inherits the target's
/// permissions when there is a target, and is renamed onto it — `rename` is
/// atomic within a directory on every platform lucisv ships to, so a reader
/// sees either the old file or the new one and never a truncated one. A
/// failure anywhere after the temp exists removes it before returning.
///
/// The temp is the caller's alone: [`temp_path`] hands out a name no other
/// writer in this process will be given, and the file is created with
/// `create_new`, so a name that somehow exists is an error and not a shared
/// file. Two threads writing one target therefore both succeed, and the
/// target ends up holding one thread's whole buffer.
///
/// A symlinked target is resolved first: `fs::write` writes *through* a
/// symlink, so replacing the link itself would silently redirect it at a new
/// file and leave the real one stale. The canonical path is what gets
/// replaced, which is also what makes the temp land on the target's own
/// filesystem — `rename` cannot cross one.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let perms = target_permissions(&target);
// A rename replaces a file whatever its mode, so a read-only target would
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
// a file someone made read-only is asking not to be rewritten in place.
if perms.as_ref().is_some_and(fs::Permissions::readonly) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is read-only", path.display()),
));
}
let (tmp, mut file) = create_temp(&target, perms.is_some())?;
if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
drop(file);
if let Err(e) = fs::rename(&tmp, &target) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
/// How many temp names one write tries before giving up.
///
/// A name is only ever handed out once per process, so a collision means a
/// leftover from a *previous* process that crashed mid-write and whose pid
/// this process now has. A handful of those may sit in one directory; a
/// hundred is a directory to clean up by hand, not a race to retry through.
const TEMP_ATTEMPTS: u32 = 32;
/// Creates the temp file, exclusively, and returns it with its path.
///
/// `replacing` says there is a target whose mode the temp is about to take.
/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does
/// not revoke a descriptor someone already opened, so the only way a private
/// file's replacement can never be read by anyone else is for the temp to be
/// private from the moment it exists. With no target there is no earlier mode
/// to honour and the umask decides, as `fs::write` would.
fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
if replacing {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
#[cfg(not(unix))]
let _ = replacing;
for _ in 0..TEMP_ATTEMPTS {
let tmp = temp_path(target)?;
match opts.open(&tmp) {
Ok(file) => return Ok((tmp, file)),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()),
))
}
/// Puts the target's mode on the temp, then the bytes in it.
///
/// The order is the point on unix: a 0600 target's replacement must not spend
/// even an instant holding the file's contents under the umask's broader
/// bits. Chmod does not close the handle opened before it, so a mode without
/// an owner-write bit still takes the write. Elsewhere `set_permissions`
/// takes a path rather than a handle and the mode goes on after the bytes,
/// which is the order this always had.
fn fill_temp(
file: &mut File,
tmp: &Path,
perms: Option<fs::Permissions>,
bytes: &[u8],
) -> io::Result<()> {
if cfg!(unix) {
copy_mode(file, perms);
file.write_all(bytes)
} else {
file.write_all(bytes)?;
if let Some(perms) = perms {
let _ = fs::set_permissions(tmp, perms);
}
Ok(())
}
}
/// Puts the target's mode on the temp through its open handle, which is what
/// lets it happen while the temp is still empty. No target means no earlier
/// mode to honour, and the umask's stands.
fn copy_mode(file: &File, perms: Option<fs::Permissions>) {
if let Some(perms) = perms {
let _ = file.set_permissions(perms);
}
}
/// The mode the temp must end up with: a file someone made executable, or
/// private, keeps its bits, because the temp was created with the process
/// umask (or 0600) and not with the target's. `None` means there is no target
/// — a new file, which takes the umask as `fs::write` would.
fn target_permissions(target: &Path) -> Option<fs::Permissions> {
fs::metadata(target).ok().map(|m| m.permissions())
}
/// Names handed out by [`temp_path`], one per call for the life of the
/// process. Wrapping after 2^64 names is not a scenario.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// The temp file's path: hidden, in the target's own directory, and stamped
/// with the process id and a per-process counter — the pid keeps two lucisv
/// runs apart, the counter keeps two threads of one run apart, and together
/// they mean no two writers anywhere are ever given the same name.
fn temp_path(target: &Path) -> io::Result<PathBuf> {
let dir = target.parent().unwrap_or_else(|| Path::new("."));
let name = target
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let mut tmp = std::ffi::OsString::from(".");
tmp.push(name);
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
Ok(dir.join(tmp))
}
#[cfg(test)]
mod tests {
use super::*;
/// A directory that removes itself, the way `cache.rs`'s own tests have
/// one — no dependency, and no leftovers under `target/`.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"lucisv-atomic-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
}
fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
/// Every name in the directory, so a test can say what is *not* there.
fn names(&self) -> Vec<String> {
let mut out: Vec<String> = fs::read_dir(&self.path)
.expect("read dir")
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
out.sort();
out
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn the_bytes_land_and_no_temp_file_is_left_behind() {
let dir = TempDir::new("plain");
let file = dir.file("a.sv");
fs::write(&file, "old\n").expect("seed");
write_atomic(&file, b"new\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
}
#[test]
fn a_file_that_does_not_exist_yet_is_created() {
let dir = TempDir::new("create");
let file = dir.file("new.sv");
write_atomic(&file, b"hello\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
}
#[test]
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
// A directory standing where the file should be: the write succeeds,
// the rename cannot.
let dir = TempDir::new("dirtarget");
let target = dir.file("occupied");
fs::create_dir(&target).expect("create dir");
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
assert!(err.to_string().len() > 1, "{err}");
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
}
#[test]
fn writing_the_same_path_twice_leaves_one_file() {
let dir = TempDir::new("twice");
let file = dir.file("a.sv");
write_atomic(&file, b"one\n").expect("write");
write_atomic(&file, b"two\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
}
#[cfg(unix)]
#[test]
fn the_targets_permissions_are_preserved() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("modes");
for mode in [0o600, 0o755] {
let file = dir.file(&format!("m{mode:o}.sv"));
fs::write(&file, "old\n").expect("seed");
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
write_atomic(&file, b"new\n").expect("write");
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
assert_eq!(got, mode, "mode {mode:o} was not preserved");
}
}
#[cfg(unix)]
#[test]
fn a_read_only_target_is_refused_and_left_alone() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("readonly");
let file = dir.file("ro.sv");
fs::write(&file, "old\n").expect("seed");
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
}
#[cfg(unix)]
#[test]
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
let dir = TempDir::new("symlink");
let real = dir.file("real.sv");
let link = dir.file("link.sv");
fs::write(&real, "old\n").expect("seed");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
write_atomic(&link, b"new\n").expect("write");
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
assert!(
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
"the link is still a link"
);
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
}
/// The audit's probe (`docs/repository-analysis.md` finding 1), which
/// used to produce 100 write errors in 200 calls: both threads derived
/// the same temp name from the target and the pid, so one deleted the
/// other's file under it. Now every writer owns its own temp, so every
/// call succeeds and the target holds one writer's whole buffer.
#[test]
fn two_threads_writing_one_target_never_collide() {
const MIB: usize = 1024 * 1024;
const ROUNDS: usize = 100;
let dir = TempDir::new("race");
let file = dir.file("a.sv");
fs::write(&file, "seed\n").expect("seed");
// Three parties: the two writers and this thread, which inspects the
// target between rounds. Nobody starts a round until everyone has
// finished the last one.
let start = std::sync::Arc::new(std::sync::Barrier::new(3));
let done = std::sync::Arc::new(std::sync::Barrier::new(3));
let writers: Vec<_> = (*b"ab")
.into_iter()
.map(|tag| {
let (path, start, done) = (file.clone(), start.clone(), done.clone());
std::thread::spawn(move || {
let bytes = vec![tag; MIB];
let mut errors = Vec::new();
for _ in 0..ROUNDS {
start.wait();
if let Err(e) = write_atomic(&path, &bytes) {
errors.push(e.to_string());
}
done.wait();
}
errors
})
})
.collect();
for round in 0..ROUNDS {
start.wait();
done.wait();
let got = fs::read(&file).expect("read");
assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed");
let tag = got[0];
assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte");
assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed");
assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left");
}
let errors: Vec<String> =
writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect();
assert!(
errors.is_empty(),
"{} write errors in {} calls: {errors:?}",
errors.len(),
2 * ROUNDS
);
}
#[test]
fn every_thread_gets_its_own_temp_name() {
const PER_THREAD: usize = 200;
let dir = TempDir::new("names");
let target = dir.file("a.sv");
let threads: Vec<_> = (0..4)
.map(|_| {
let target = target.clone();
std::thread::spawn(move || {
(0..PER_THREAD)
.map(|_| temp_path(&target).expect("temp name"))
.collect::<Vec<_>>()
})
})
.collect();
let names: Vec<PathBuf> =
threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect();
let unique: std::collections::HashSet<&PathBuf> = names.iter().collect();
assert_eq!(unique.len(), names.len(), "a temp name was handed out twice");
}
/// The mode goes on while the temp is still empty, so a 0600 file's
/// replacement never holds its contents under the umask's wider bits.
#[cfg(unix)]
#[test]
fn the_temp_takes_the_targets_mode_before_any_bytes() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("modewindow");
let target = dir.file("secret.sv");
fs::write(&target, "old\n").expect("seed");
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
let perms = target_permissions(&target);
let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp");
// Born private, before any mode is copied onto it: an fd opened by
// someone else in this instant would not see the bytes to come.
assert_eq!(
fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777,
0o600,
"the temp was created readable by others"
);
copy_mode(&file, perms.clone());
let meta = fs::metadata(&tmp).expect("stat");
assert_eq!(meta.len(), 0, "the mode is set before a single byte is written");
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable");
// And the chmod does not close the door on the handle opened before it.
fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill");
assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n");
let _ = fs::remove_file(&tmp);
}
/// The same window seen from outside, through a real `write_atomic`: a
/// big enough buffer that the temp is usually observable while it is
/// being filled. It asserts about what it sees and never about seeing it,
/// so a scheduler that hides the window cannot fail the test.
#[cfg(unix)]
#[test]
fn a_temp_seen_mid_write_is_never_world_readable() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("window");
let target = dir.file("secret.sv");
fs::write(&target, "old\n").expect("seed");
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
let path = target.clone();
let writer = std::thread::spawn(move || {
let bytes = vec![b'x'; 8 * 1024 * 1024];
write_atomic(&path, &bytes)
});
while !writer.is_finished() {
for entry in fs::read_dir(&dir.path).expect("read dir").flatten() {
if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") {
continue;
}
let Ok(meta) = entry.metadata() else { continue };
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"a temp for a 0600 target was readable by others"
);
}
}
writer.join().expect("writer thread").expect("write");
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
}
}
+96 -24
View File
@@ -32,6 +32,9 @@ pub struct Entry {
pub line_length: usize,
/// The `indent` that verdict was reached under.
pub indent: usize,
/// The `[format] uvm-utils-indent` that verdict was reached under: it
/// changes the output of a UVM class, so it is part of the key.
pub uvm_utils_indent: bool,
}
/// The cache for one run: loaded once at startup, written once at exit.
@@ -87,10 +90,7 @@ impl Cache {
if !ignore.exists() {
let _ = std::fs::write(&ignore, "*\n");
}
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
let _ = std::fs::remove_file(&tmp);
}
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
}
/// The file's text: one line per entry, sorted by path so that two
@@ -107,8 +107,8 @@ impl Cache {
let entry = &self.entries[path];
let _ = writeln!(
text,
"{:016x}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
);
}
text
@@ -140,25 +140,49 @@ fn key(path: &Path) -> Option<&str> {
Some(text)
}
/// The `(content, line-length, indent)` prefix every store line has ever
/// begun with, or `None` when those three fields are not what lucisv writes.
fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize, usize)> {
Some((u64::from_str_radix(content, 16).ok()?, line_length.parse().ok()?, indent.parse().ok()?))
}
/// Parses the store. `None` means "this file is not something lucisv wrote"
/// — one malformed line discards the whole cache, because partial trust in
/// a file already caught lying is not worth the branch. Entries from
/// another lucisv version are dropped individually; that is staleness, not
/// corruption.
/// another lucisv version, and lines written in an older field layout, are
/// dropped individually; that is staleness, not corruption.
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
let mut entries = HashMap::new();
for line in text.lines() {
let mut fields = line.splitn(5, '\t');
let content = u64::from_str_radix(fields.next()?, 16).ok()?;
let line_length = fields.next()?.parse().ok()?;
let indent = fields.next()?.parse().ok()?;
let version = fields.next()?;
let path = fields.next()?;
if path.is_empty() {
return None;
}
if version == VERSION {
entries.insert(path.to_string(), Entry { content, line_length, indent });
let fields: Vec<&str> = line.splitn(6, '\t').collect();
match fields[..] {
[content, line_length, indent, uvm, version, path] => {
let (content, line_length, indent) = prefix(content, line_length, indent)?;
let uvm_utils_indent = uvm.parse().ok()?;
if path.is_empty() {
return None;
}
if version == VERSION {
entries.insert(
path.to_string(),
Entry { content, line_length, indent, uvm_utils_indent },
);
}
}
// A store written before `uvm-utils-indent` joined the key: a
// well-formed line of that older shape says nothing about the
// option, so it is dropped individually, exactly like another
// version's entry. (The version field alone already makes such
// a store miss; the codec stays self-describing anyway.)
// Anything else on five fields is corruption and discards the
// file like any other malformed line.
[content, line_length, indent, _version, path] => {
prefix(content, line_length, indent)?;
if path.is_empty() {
return None;
}
}
_ => return None,
}
}
Some(entries)
@@ -204,7 +228,7 @@ mod tests {
}
fn entry(content: u64) -> Entry {
Entry { content, line_length: 100, indent: 2 }
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
}
#[test]
@@ -237,9 +261,53 @@ mod tests {
assert!(!reloaded.is_clean(&file, entry(0xbeef)));
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
}
#[test]
fn uvm_utils_indent_alone_is_a_different_entry() {
let on = Entry { uvm_utils_indent: true, ..entry(0xdead) };
assert_ne!(entry(0xdead), on, "the option is part of equality");
// …and it survives the round trip through the store, on its own.
let dir = TempDir::new("uvm");
let file = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&file, on);
cache.store();
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
let reloaded = Cache::load(&dir.path);
assert!(reloaded.is_clean(&file, on));
assert!(!reloaded.is_clean(&file, entry(0xdead)), "the option must invalidate the entry");
}
#[test]
fn a_line_without_the_option_is_dropped_but_not_fatal() {
// The five-field shape lucisv wrote before `uvm-utils-indent` joined
// the key: stale, like another version's entry, never corruption.
let dir = TempDir::new("oldshape");
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&old, entry(1)), "a line without the option must not be trusted");
assert!(cache.is_clean(&mine, entry(2)), "and it does not discard the rest of the file");
// And it is not carried forward.
cache.store();
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
}
#[test]
fn the_file_is_sorted_and_carries_the_version() {
let dir = TempDir::new("format");
@@ -257,7 +325,7 @@ mod tests {
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
assert_eq!(
lines[0],
format!("{:016x}\t100\t2\t{VERSION}\t{}", 1, a.to_string_lossy()),
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
"{text}"
);
}
@@ -280,12 +348,15 @@ mod tests {
"0000000000000001\twide\t2\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\t0.2.0\n",
"0000000000000001\t100\t2\t0.2.0\t\n",
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
"\0\0\0\n",
] {
let dir = TempDir::new("corrupt");
let file = dir.file("a.sv");
// A good line first: a bad one anywhere discards all of them.
let good = format!("{:016x}\t100\t2\t{VERSION}\t{}\n", 1, file.to_string_lossy());
let good =
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
@@ -298,7 +369,8 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\t0.0.0-not-this-one\t{}\n{:016x}\t100\t2\t{VERSION}\t{}\n",
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -397,7 +469,7 @@ mod tests {
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".tmp"))
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
}
+396 -11
View File
@@ -1,8 +1,9 @@
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a three-key config file needs is supported (comments,
//! `key = int`, `key = "string"`, `key = ["a", "b"]`); everything else is
//! rejected by name rather than ignored. See
//! Only what a small config file needs is supported (comments, `key = int`,
//! `key = "string"`, `key = ["a", "b"]`, the table `[lint]` and the per-rule
//! `[lint.<rule>]` tables); everything else is rejected by name rather than
//! ignored. See
//! `docs/features/config-discovery/README.md` for the grammar and the
//! reasoning behind not taking a TOML dependency.
@@ -29,6 +30,54 @@ pub struct FileConfig {
/// directory, so every `FileConfig` a `Discovery` hands out carries a
/// usable path. See `docs/features/filelist/README.md`.
pub filelist: Option<PathBuf>,
/// `[format] uvm-utils-indent`: indent the `` `uvm_field_* `` macro
/// statements written between `` `uvm_*_utils_begin `` and
/// `` `uvm_*_utils_end ``. Off for the same reason.
pub format_uvm_utils_indent: Option<bool>,
/// `[lint] select`: run exactly these rules, replacing the default set.
/// The names are **not** validated here — this crate does not know the
/// rule registry; `lucisv check` validates them the moment it resolves the
/// run's rules, with the same error a bad `--select` gets.
pub lint_select: Option<Vec<String>>,
/// `[lint] ignore`: rules dropped from whatever `select` left.
pub lint_ignore: Option<Vec<String>>,
/// `[lint] waivers`: external waiver files, in the order written.
///
/// Like [`FileConfig::filelist`], these name *other files*: [`parse`]
/// records them exactly as written and [`Discovery`] resolves each one
/// against the config file's own directory, so every `FileConfig` a
/// `Discovery` hands out carries usable paths. Nothing here reads them —
/// their contents name lint rules, and this crate does not know the rule
/// registry any more than it does for `select`.
pub lint_waivers: Option<Vec<PathBuf>>,
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
/// order.
///
/// Neither the rule names nor the option names or their values are
/// checked here — this crate does not know the rule registry, exactly as
/// it does not know which rule names `select` may hold. `lucisv check`
/// resolves them against `vlog_linter`'s specs and fails the run naming
/// this file and the line, which is what [`LintOption::line`] is for.
pub lint_options: Vec<LintOption>,
/// The config file these settings were read from, when they were read
/// from one. `parse` leaves it unset — it is handed text, not a path —
/// and [`Discovery`] fills it in, so an error about an entry can name the
/// file the user has to edit.
pub source: Option<PathBuf>,
}
/// One `key = value` written under a `[lint.<rule>]` table, as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintOption {
/// The rule named by the table header.
pub rule: String,
/// The option key.
pub key: String,
/// The value's text, comment stripped, quotes and all — the linter's own
/// parser reads it, because only it knows what kind the key takes.
pub raw: String,
/// 1-based line the entry was written on.
pub line: usize,
}
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
@@ -38,19 +87,62 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
// Editors on some platforms prepend a BOM; it would otherwise garble
// key matching on line 1 into an `unknown key` with invisible cause.
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
// Which table the keys below belong to: the top level until a header
// opens one, and then that one until the next header. Nothing closes a
// table, which is TOML's own rule.
let mut table = Table::Top;
for (index, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
parse_entry(line, &mut config).map_err(|e| format!("{}: {e}", index + 1))?;
parse_entry(line, &mut config, &mut table, index + 1)
.map_err(|e| format!("{}: {e}", index + 1))?;
}
Ok(config)
}
fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
/// The table whose keys are being read.
enum Table {
/// Before any header: the formatter's own keys.
Top,
/// `[lint]`: `select`, `ignore` and `waivers`.
Lint,
/// `[format]`: the layout keys that are off by default.
Format,
/// `[lint.<rule>]`: that rule's options.
Rule(String),
}
fn parse_entry(
line: &str,
config: &mut FileConfig,
table: &mut Table,
number: usize,
) -> Result<(), String> {
if line.starts_with('[') {
return Err("tables (`[section]`) are unsupported in lucisv.toml".to_string());
// `[lint]` carries `select`/`ignore`/`waivers`; `[lint.<rule>]` carries that
// rule's options, which are stored raw and checked by whoever knows
// the registry.
if line == "[lint]" {
*table = Table::Lint;
return Ok(());
}
if line == "[format]" {
*table = Table::Format;
return Ok(());
}
if let Some(rule) = line.strip_prefix("[lint.").and_then(|r| r.strip_suffix(']')) {
if rule.is_empty() || rule.contains('.') || rule.contains(' ') {
return Err(format!("`{line}` is not a rule table; write `[lint.<rule-name>]`"));
}
*table = Table::Rule(rule.to_string());
return Ok(());
}
return Err(format!(
"unknown table `{line}` \
(the tables are `[format]`, `[lint]` and `[lint.<rule-name>]`)"
));
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
@@ -59,6 +151,12 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
if value.is_empty() {
return Err(format!("`{key}` has no value"));
}
match table {
Table::Format => return parse_format_entry(key, value, config),
Table::Lint => return parse_lint_entry(key, value, config),
Table::Rule(rule) => return parse_rule_entry(rule, key, value, config, number),
Table::Top => {}
}
match key {
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
"indent" => set_int(&mut config.indent, key, value, 1, 8),
@@ -76,12 +174,90 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
config.filelist = Some(PathBuf::from(parse_string(value)?));
Ok(())
}
_ => {
Err(format!("unknown key `{key}` (known keys: line-length, indent, exclude, filelist)"))
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
uvm-utils-indent under `[format]`; \
select, ignore, waivers under `[lint]`; and a rule's own options \
under `[lint.<rule-name>]`)"
)),
}
}
/// One key of the `[format]` table: a boolean that defaults to off, because
/// it changes how already-clean files are laid out and a project has to opt
/// in before anything of its moves.
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
let slot = match key {
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
_ => {
return Err(format!(
"unknown key `{key}` under `[format]` \
(the only key is uvm-utils-indent)"
))
}
};
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
*slot = Some(parse_bool(key, value)?);
Ok(())
}
/// `true` or `false`, and nothing else — a misspelling is a typo the user
/// wants to hear about, not a silent `false`.
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
match value {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(format!("`{key}` expects `true` or `false`, found `{value}`")),
}
}
/// One key of the `[lint]` table.
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
if key == "waivers" {
if config.lint_waivers.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.lint_waivers = Some(parse_array(value)?.into_iter().map(PathBuf::from).collect());
return Ok(());
}
let slot = match key {
"select" => &mut config.lint_select,
"ignore" => &mut config.lint_ignore,
_ => {
return Err(format!(
"unknown key `{key}` under `[lint]` (known keys: select, ignore, waivers)"
))
}
};
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
*slot = Some(parse_array(value)?);
Ok(())
}
/// One `key = value` of a `[lint.<rule>]` table, kept as written.
fn parse_rule_entry(
rule: &str,
key: &str,
value: &str,
config: &mut FileConfig,
line: usize,
) -> Result<(), String> {
if config.lint_options.iter().any(|held| held.rule == rule && held.key == key) {
return Err(format!("duplicate key `{key}` under `[lint.{rule}]`"));
}
config.lint_options.push(LintOption {
rule: rule.to_string(),
key: key.to_string(),
raw: value.to_string(),
line,
});
Ok(())
}
fn set_int(
slot: &mut Option<usize>,
key: &str,
@@ -244,10 +420,18 @@ fn load(path: &Path) -> Result<FileConfig, String> {
// `filelist` is the one value that names another file, so it is resolved
// here — against the config file's own directory, which `parse` cannot
// know. An absolute path is left alone (`join` already does that).
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
if let Some(filelist) = config.filelist.take() {
let dir = path.parent().unwrap_or(Path::new("."));
config.filelist = Some(dir.join(filelist));
}
// `[lint] waivers` names other files the same way, and is resolved the
// same way: against the config file's directory, an absolute path left
// alone by `join`.
if let Some(waivers) = config.lint_waivers.take() {
config.lint_waivers = Some(waivers.into_iter().map(|file| dir.join(file)).collect());
}
// So an error about a `[lint.<rule>]` entry can name the file to edit.
config.source = Some(path.to_path_buf());
Ok(config)
}
@@ -311,6 +495,34 @@ exclude = [ \"build\", \"*_gen.sv\", ]
);
}
/// `[lint] waivers` names other files, so it resolves the way `filelist`
/// does: against the config file's own directory, absolute paths left
/// alone. See `docs/features/waiver-files/README.md`.
#[test]
fn lint_waivers_are_a_list_resolved_against_the_config_files_directory() {
assert_eq!(
ok("[lint]\nwaivers = [ \"a.waiver\", \"deep/b.waiver\" ]").lint_waivers,
Some(vec![PathBuf::from("a.waiver"), PathBuf::from("deep/b.waiver")])
);
assert_eq!(
ok("[lint]\nselect = [\"no-tabs\"]").lint_waivers,
None,
"absent unless written"
);
assert!(err("[lint]\nwaivers = \"a.waiver\"").contains("multi-line arrays"));
assert!(err("[lint]\nwaivers = []\nwaivers = []").contains("duplicate key `waivers`"));
assert!(err("[lint]\nwaiver = []").contains("unknown key `waiver` under `[lint]`"));
let tree = TempTree::new();
tree.write("lucisv.toml", "[lint]\nwaivers = [ \"rtl/a.waiver\", \"/opt/b.waiver\" ]\n");
let deep = tree.write("a/b/x.sv", "");
let found = Discovery::new(true).for_file(&deep).unwrap();
assert_eq!(
found.lint_waivers,
Some(vec![tree.path.join("rtl/a.waiver"), PathBuf::from("/opt/b.waiver")])
);
}
#[test]
fn an_empty_file_sets_nothing() {
assert_eq!(ok(""), FileConfig::default());
@@ -366,7 +578,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn unsupported_toml_is_named_not_ignored() {
assert!(err("[tool.lucisv]\nindent = 2").contains("tables"));
assert!(err("[tool.lucisv]\nindent = 2").contains("unknown table"));
assert!(err("exclude = [\n \"a\",\n]").contains("multi-line arrays are unsupported"));
assert!(err("exclude = [\"a\\tb\"]").contains("escapes"));
assert!(err("indent").contains("expected `key = value`"));
@@ -376,6 +588,179 @@ exclude = [ \"build\", \"*_gen.sv\", ]
fn duplicate_keys_are_rejected() {
assert!(err("indent = 2\nindent = 4").contains("duplicate key `indent`"));
assert!(err("exclude = []\nexclude = []").contains("duplicate key `exclude`"));
assert!(
err("[lint]\nignore = [\"a\"]\nignore = [\"b\"]").contains("duplicate key `ignore`")
);
}
/// The `[format]` table: the layout keys that change how an already-clean
/// file is laid out, and so are off unless a checked-in `lucisv.toml`
/// turns them on (TODO §54.3).
#[test]
fn the_format_table_carries_uvm_utils_indent() {
assert_eq!(ok("[format]\nuvm-utils-indent = true").format_uvm_utils_indent, Some(true));
assert_eq!(ok("[format]\nuvm-utils-indent = false").format_uvm_utils_indent, Some(false));
// Absent unless written — which is what makes the default off.
assert_eq!(ok("indent = 4").format_uvm_utils_indent, None);
assert_eq!(ok("[format]").format_uvm_utils_indent, None);
// The formatter keys still work above the table, and nothing closes
// the table but the next header.
let mixed = parse(
"indent = 4\n\n[format]\nuvm-utils-indent = true\n\n[lint]\nignore = [\"no-tabs\"]",
)
.expect("parses");
assert_eq!(mixed.indent, Some(4));
assert_eq!(mixed.format_uvm_utils_indent, Some(true));
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
}
/// Everything about the table's shape, the way the `[lint]` table's is
/// pinned: an unknown key is named, a non-boolean value is refused, and a
/// repeated key is an error rather than a last-one-wins.
#[test]
fn the_format_table_rejects_what_it_does_not_support() {
assert!(err("[format]\nbogus = true").contains("unknown key `bogus` under `[format]`"));
assert!(err("[format]\nuvm-utils-indent = \"yes\"")
.contains("`uvm-utils-indent` expects `true` or `false`, found `\"yes\"`"));
assert!(err("[format]\nuvm-utils-indent = 1").contains("expects `true` or `false`"));
assert!(err("[format]\nuvm-utils-indent =").contains("has no value"));
assert!(err("[format]\nuvm-utils-indent = true\nuvm-utils-indent = false")
.contains("duplicate key `uvm-utils-indent`"));
// A key before any table still belongs to the top level, and the
// top-level unknown-key message names the table it does belong to.
assert!(err("uvm-utils-indent = true").contains("unknown key `uvm-utils-indent`"));
assert!(err("uvm-utils-indent = true").contains("`[format]`"));
// `[format.<anything>]` is not a table this parser knows.
assert!(err("[format.uvm]\nx = 1").contains("unknown table"));
}
/// The same key in a real config file, so the message a user sees names
/// the file and the line to edit — the ladder `[format]` sits at the top
/// of (`lucisv.toml` outranks the editor setting).
#[test]
fn a_bad_format_key_names_the_file_and_line() {
let tree = TempTree::new();
let config = tree.write("lucisv.toml", "indent = 2\n\n[format]\nuvm-utils-indnet = true\n");
let file = tree.write("x.sv", "");
let message = Discovery::new(true).for_file(&file).expect_err("expected an error");
assert!(message.starts_with(&format!("{}:4: ", config.display())), "{message}");
assert!(message.contains("unknown key `uvm-utils-indnet` under `[format]`"), "{message}");
// And the key spelled right loads through the same walk.
let good = TempTree::new();
good.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
let sv = good.write("a/b/x.sv", "");
assert_eq!(Discovery::new(true).for_file(&sv).unwrap().format_uvm_utils_indent, Some(true));
}
/// The `[lint]` table: the off switch a round that turns rules on by
/// default owes its users (topo §2.9-4).
#[test]
fn the_lint_table_carries_select_and_ignore() {
let config =
parse("[lint]\nselect = [\"no-tabs\", \"unused-signal\"]\nignore = [\"no-tabs\"]")
.expect("parses");
assert_eq!(
config.lint_select.as_deref(),
Some(&["no-tabs".to_string(), "unused-signal".to_string()][..])
);
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
// Both are absent unless written, and the formatter keys still work
// above the table.
let mixed = parse("indent = 4\n\n[lint]\nignore = [\"unused-signal\"]").expect("parses");
assert_eq!(mixed.indent, Some(4));
assert_eq!(mixed.lint_select, None);
assert_eq!(parse("indent = 4").expect("parses").lint_ignore, None);
}
/// Rule *names* are not this crate's business — it has no registry to
/// check them against — but everything about the table's shape is.
#[test]
fn the_lint_table_rejects_what_it_does_not_support() {
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
assert!(err("[lint.]\nx = 1").contains("not a rule table"));
assert!(err("[lint.a.b]\nx = 1").contains("not a rule table"));
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
// A key before any table still belongs to the top level.
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
// Nothing closes the table — TOML's own rule, spelled out.
assert_eq!(
parse("[lint]\nselect = [\"no-tabs\"]").expect("parses").lint_select.as_deref(),
Some(&["no-tabs".to_string()][..])
);
}
/// The per-rule tables: stored exactly as written, because this crate
/// has no idea what a rule is or what its options take.
#[test]
fn a_rule_table_keeps_its_entries_as_written() {
let config = parse(
"[lint]\nignore = [\"no-tabs\"]\n\n\
[lint.line-length]\nlength = 120\n\n\
[lint.signal-name-style]\nstyle_regex = \"[a-z_0-9]+\" # ours\n",
)
.expect("parses");
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
let entries: Vec<(&str, &str, &str, usize)> = config
.lint_options
.iter()
.map(|o| (o.rule.as_str(), o.key.as_str(), o.raw.as_str(), o.line))
.collect();
assert_eq!(
entries,
vec![
("line-length", "length", "120", 5),
("signal-name-style", "style_regex", "\"[a-z_0-9]+\"", 8),
]
);
}
/// A backslash is legal in an option value and refused in a top-level
/// string: the linter's own parser reads the former, and a pattern is the
/// one value that needs them.
#[test]
fn a_rule_option_value_is_not_string_checked_here() {
let config =
parse("[lint.signal-name-style]\nstyle_regex = \"[a-z]\\d+\"\n").expect("parses");
assert_eq!(config.lint_options[0].raw, "\"[a-z]\\d+\"");
assert!(err("exclude = [\"a\\d\"]").contains("escapes"), "still refused up here");
}
#[test]
fn a_rule_table_rejects_a_repeated_key_and_a_bad_header() {
assert!(err("[lint.line-length]\nlength = 1\nlength = 2")
.contains("duplicate key `length` under `[lint.line-length]`"));
// The same key under two different rules is two different options.
let config = parse(
"[lint.enum-name-style]\nstyle_regex = \"a\"\n\
[lint.module-name-style]\nstyle_regex = \"b\"\n",
)
.expect("parses");
assert_eq!(config.lint_options.len(), 2);
assert!(err("[lint.a b]\nx = 1").contains("not a rule table"));
}
/// Nothing closes a table: the keys after a rule header belong to it
/// until the next header, and a formatter key written there is that
/// rule's option as far as this parser is concerned.
#[test]
fn a_rule_table_runs_until_the_next_header() {
let config =
parse("indent = 4\n[lint.line-length]\nlength = 120\nindent = 8\n").expect("parses");
assert_eq!(config.indent, Some(4));
assert_eq!(config.lint_options.len(), 2);
assert_eq!(config.lint_options[1].key, "indent");
}
#[test]
fn a_config_file_records_where_it_came_from() {
let tree = TempTree::new();
let written = tree.write("lucisv.toml", "[lint.line-length]\nlength = 120\n");
let file = tree.write("x.sv", "");
let found = Discovery::new(true).for_file(&file).expect("reads");
assert_eq!(found.source.as_deref(), Some(written.as_path()));
// `parse` alone has no path to record.
assert_eq!(parse("indent = 4").expect("parses").source, None);
}
/// A throwaway directory tree under the system temp dir.
+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}");
}
}
+6 -1
View File
@@ -6,12 +6,17 @@
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
//! `cache` answers the third question of the same family — whether a file
//! needs to be processed at all, and `filelist` answers the first one the way
//! an EDA project already does, from a `.f` file. See
//! an EDA project already does, from a `.f` file. `atomic` is the one write
//! path all of them share: nothing here ever truncates a file it is
//! replacing. `diff` is the unified diff the CLI's `--diff` and the MCP
//! server's `dry_run` both print. See
//! `docs/features/lucisv-core-lift/README.md`, and
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
//! for the rules themselves.
pub mod atomic;
pub mod cache;
pub mod config;
pub mod diff;
pub mod filelist;
pub mod walk;
+759 -25
View File
@@ -2,6 +2,7 @@
//! `.gitignore` subset documented in
//! `docs/features/parallel-files/README.md`.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// File extensions lucisv formats when walking a directory.
@@ -10,79 +11,390 @@ pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
/// The name of the per-directory ignore file that is honoured by default.
const GITIGNORE: &str = ".gitignore";
/// Something the walk could not do and went on regardless: a directory it
/// could not read, an ignore file it could not open, a source file that is
/// only a broken link.
///
/// The walk's warning channel exists because none of these is worth failing a
/// run over — one unreadable directory used to drop every file already found
/// — and because a silent skip loses the user the fact entirely. Rendering is
/// the front end's job: the CLI writes `warning: <path>: <message>` to stderr,
/// the server logs the same text once per scan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Warning {
/// What could not be used.
pub path: PathBuf,
/// Why, in the operating system's own words where there are any.
pub message: String,
}
impl std::fmt::Display for Warning {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.path.display(), self.message)
}
}
/// Adds `input` to `files`: the file itself, or every Verilog file under
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
/// to directory walks only — a path named on the command line is always
/// formatted.
///
/// `warn` is called once for everything the walk skipped and wants said; see
/// [`Warning`]. Only `input` itself naming nothing is an error — that is the
/// user's own typo, and the run has nothing to do.
pub fn collect_files(
input: &str,
exclude: &[String],
gitignore: bool,
files: &mut Vec<PathBuf>,
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
collect_files_with(input, exclude, gitignore, &mut |path, _| files.push(path), warn)
}
/// [`collect_files`] with the size the walk already read handed on beside each
/// path.
///
/// The same walk, the same order, the same warnings — the only difference is
/// where a file goes when it is found. A directory walk already calls
/// `metadata` on every entry to answer "directory?", so the length is a field
/// of a struct it holds anyway; a caller that has to know how big a file is —
/// the server's `lucisv.index.maxFileSize` cap — would otherwise ask the
/// filesystem the same question a second time, once per file.
/// `docs/features/perf5r-first-answer/README.md` measured that second `stat`
/// at 6.9 ms of a 165 ms discovery over 3 976 files — small, because the walk
/// has just warmed every one of those inodes, and 3 976 system calls that buy
/// a number already in hand all the same.
///
/// **`None` means the walk did not look.** `input` naming a file rather than a
/// directory is handed straight over, exactly as [`collect_files`] hands it
/// over, with no `metadata` call added to a path that never needed one — so a
/// caller that wants a size there asks for it itself. Every path a *directory
/// walk* yields carries `Some`.
pub fn collect_files_with(
input: &str,
exclude: &[String],
gitignore: bool,
found: &mut dyn FnMut(PathBuf, Option<u64>),
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
let mut tracker = DirectoryTracker::new();
collect_files_tracked(input, exclude, gitignore, &mut tracker, found, warn)
}
/// [`collect_files_with`] using an existing [`DirectoryTracker`].
pub fn collect_files_tracked(
input: &str,
exclude: &[String],
gitignore: bool,
tracker: &mut DirectoryTracker,
found: &mut dyn FnMut(PathBuf, Option<u64>),
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
let path = Path::new(input);
if path.is_dir() {
let mut walk = Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), files };
walk.dir(path).map_err(|e| format!("{input}: {e}"))?;
let mut walk =
Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn };
walk.dir(path);
} else if path.is_file() {
files.push(path.to_path_buf());
found(path.to_path_buf(), None);
} else {
return Err(format!("{input}: no such file or directory"));
}
Ok(())
}
/// [`collect_files_with`] over `input`, which lies **under** `root`, finding
/// exactly what a walk of `root` would have found there.
///
/// The difference from walking `input` directly is the `.gitignore` files
/// between the two. A walk reads ignore rules from its own starting directory
/// downwards, so `collect_files_with("<root>/hw/ip/aes")` never sees the rule
/// `<root>/.gitignore` writes about `hw/ip/aes/gen/` — and a caller walking a
/// subtree *of a scope whose rung is the root* would then index files that
/// scope excludes. This one walks the ancestor chain first: it reads each
/// ancestor's `.gitignore` onto the stack with the depth it belongs at, and it
/// stops without yielding anything when one of those ancestors is itself
/// ignored or excluded — because a walk of `root` would never have descended
/// into it.
///
/// `input` not being under `root` is the caller's mistake and is answered the
/// way a walk of an unknown path is: nothing found, and no error, since there
/// is no ancestor chain to apply.
///
/// Everything else is [`collect_files_with`]: the same order, the same cycle
/// guard, the same warnings, the same lengths.
pub fn collect_files_below(
root: &Path,
input: &Path,
exclude: &[String],
gitignore: bool,
found: &mut dyn FnMut(PathBuf, Option<u64>),
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
let mut tracker = DirectoryTracker::new();
collect_files_below_tracked(root, input, exclude, gitignore, &mut tracker, found, warn)
}
/// [`collect_files_below`] using an existing [`DirectoryTracker`].
pub fn collect_files_below_tracked(
root: &Path,
input: &Path,
exclude: &[String],
gitignore: bool,
tracker: &mut DirectoryTracker,
found: &mut dyn FnMut(PathBuf, Option<u64>),
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
let Ok(below) = input.strip_prefix(root) else { return Ok(()) };
if !input.is_dir() {
return Err(format!("{}: no such file or directory", input.display()));
}
let mut walk =
Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn };
// The root's own `.gitignore` sits at depth 0, exactly where a walk of the
// root would have put it.
walk.push_ignore(root);
let mut here = root.to_path_buf();
let names: Vec<String> = below.iter().map(|name| name.to_string_lossy().into_owned()).collect();
for (at, name) in names.iter().enumerate() {
here.push(name);
if is_excluded(&here, exclude) {
return Ok(());
}
walk.rel.push(name.clone());
if is_ignored(&walk.ignores, &walk.rel, true) {
return Ok(());
}
// Not `input`'s own — `Walk::dir` pushes that one itself, and pushing
// it twice would apply its rules at two different depths.
if at + 1 < names.len() {
walk.push_ignore(&here);
}
}
walk.dir(input);
Ok(())
}
/// How a directory is recognised as one the walk has already entered. Two
/// names for the same directory — a symlink and its target, or two symlinks
/// pointing at one place — must map to the same identity, or a cycle has no
/// end. On unix that is `(dev, ino)`, the pair the filesystem itself uses;
/// elsewhere it is the canonical path, which resolves symlinks the same way
/// at the cost of a real path lookup.
#[cfg(unix)]
pub type DirId = (u64, u64);
#[cfg(not(unix))]
pub type DirId = PathBuf;
/// The identity of the directory at `path`, or `None` when it cannot be
/// read — a dangling symlink, or a directory that vanished mid-walk.
#[cfg(unix)]
pub fn dir_id(path: &Path) -> Option<DirId> {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(path).ok()?;
Some((meta.dev(), meta.ino()))
}
#[cfg(not(unix))]
pub fn dir_id(path: &Path) -> Option<DirId> {
std::fs::canonicalize(path).ok()
}
/// What happened when attempting to enter a directory with [`DirectoryTracker`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DirStatus {
/// Entered for the first time.
EnteredFirstTime,
/// Already visited under the same or an earlier path.
AlreadyVisited,
/// Previously entered under `recorded`, but `dir < recorded` indicating
/// out-of-order traversal relative to a canonical root walk.
PrecedenceConflict { recorded: PathBuf },
}
/// Tracks visited directories across one or more walks to ensure cycle termination
/// and detect order divergence.
#[derive(Debug, Clone, Default)]
pub struct DirectoryTracker {
visited: HashMap<DirId, PathBuf>,
has_conflict: bool,
}
impl DirectoryTracker {
/// Creates an empty directory tracker.
pub fn new() -> Self {
Self::default()
}
/// Records `dir` as entered and returns its [`DirStatus`].
pub fn enter(&mut self, dir: &Path) -> DirStatus {
let Some(id) = dir_id(dir) else {
return DirStatus::AlreadyVisited;
};
match self.visited.entry(id) {
std::collections::hash_map::Entry::Vacant(v) => {
v.insert(dir.to_path_buf());
DirStatus::EnteredFirstTime
}
std::collections::hash_map::Entry::Occupied(o) => {
let recorded = o.get();
if dir < recorded.as_path() {
self.has_conflict = true;
DirStatus::PrecedenceConflict { recorded: recorded.clone() }
} else {
DirStatus::AlreadyVisited
}
}
}
}
/// Whether any precedence conflict was observed across walks.
pub fn has_conflict(&self) -> bool {
self.has_conflict
}
}
/// True when `path` names one of the source files lucisv formats.
fn is_source(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
}
/// One directory walk. `rel` is the path of the directory currently being
/// read, in components relative to the walk root, which is what
/// `.gitignore` rules are matched against; `ignores` is the stack of
/// ignore files seen from the root down to it.
/// ignore files seen from the root down to it; `visited` is every directory
/// already entered, by identity rather than by spelling.
struct Walk<'a> {
exclude: &'a [String],
gitignore: bool,
ignores: Vec<Ignore>,
rel: Vec<String>,
files: &'a mut Vec<PathBuf>,
tracker: &'a mut DirectoryTracker,
/// Where a source file goes when the walk finds one, with the length the
/// walk's own `metadata` call already read.
found: &'a mut dyn FnMut(PathBuf, Option<u64>),
warn: &'a mut dyn FnMut(Warning),
}
impl Walk<'_> {
fn dir(&mut self, dir: &Path) -> std::io::Result<()> {
let pushed = self.push_ignore(dir)?;
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
fn dir(&mut self, dir: &Path) {
if !self.enter(dir) {
return;
}
let pushed = self.push_ignore(dir);
self.entries(dir);
if pushed {
self.ignores.pop();
}
}
/// One directory's entries, in name order. A directory that cannot be read
/// — the permission-denied one somewhere under the start — is said and
/// skipped: everything already found stays found and the walk goes on,
/// which is the whole reason this channel exists.
fn entries(&mut self, dir: &Path) {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) => return self.say(dir, e.to_string()),
};
let mut entries = Vec::new();
for entry in read {
match entry {
Ok(entry) => entries.push(entry),
Err(e) => self.say(dir, e.to_string()),
}
}
entries.sort_by_key(|e| e.path());
for entry in entries {
let path = entry.path();
if is_excluded(&path, self.exclude) {
continue;
}
let is_dir = path.is_dir();
// One `metadata` call per entry, exactly as before — it follows
// symlinks, so it answers "directory?" for a symlinked directory
// the way `is_dir()` did. A dangling symlink has no metadata at
// all. One that *names a source file* is warned about and dropped:
// §43's QA was right that a silent skip loses the user the fact,
// and §45.2 gives that fact a home of its own rather than handing
// the path on to fail as "no such file" in the front end. One that
// names anything else was never going to be read, and is skipped
// as quietly as it always was.
let Ok(meta) = std::fs::metadata(&path) else {
if is_source(&path) {
let why = broken_link_reason(&path);
self.say(&path, why);
}
continue;
};
self.rel.push(entry.file_name().to_string_lossy().into_owned());
if !is_ignored(&self.ignores, &self.rel, is_dir) {
if is_dir {
self.dir(&path)?;
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
if EXTENSIONS.contains(&ext) {
self.files.push(path);
}
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
if meta.is_dir() {
self.dir(&path);
} else if meta.is_file() && is_source(&path) {
// The length comes off the `metadata` above — the same
// call that answered "directory?" — so a caller wanting it
// costs the walk nothing at all.
(self.found)(path, Some(meta.len()));
}
}
self.rel.pop();
}
if pushed {
self.ignores.pop();
}
Ok(())
}
/// Hand one warning to the front end.
fn say(&mut self, path: &Path, message: String) {
(self.warn)(Warning { path: path.to_path_buf(), message });
}
/// Records `dir` as entered, and answers whether it had not been entered
/// already. Identity, not spelling: `a/loop -> a` and `a/b/up -> ..` name
/// a directory the walk is already inside, and following either is the
/// cycle that only ends when the OS refuses a path. A symlink to a
/// directory the walk has *not* seen is followed once, so
/// `rtl -> ../shared/rtl` still contributes its files; the second link to
/// one target contributes nothing further, and the files are reported
/// under the first spelling that reached them.
///
/// A directory whose identity cannot be read is not entered.
fn enter(&mut self, dir: &Path) -> bool {
matches!(self.tracker.enter(dir), DirStatus::EnteredFirstTime)
}
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
/// Returns whether anything was pushed, so `dir` can pop it again.
fn push_ignore(&mut self, dir: &Path) -> std::io::Result<bool> {
///
/// An ignore file that cannot be read is said and ignored, for the same
/// reason an unreadable directory is: the walk that finds too much is a
/// better failure than the walk that finds nothing.
fn push_ignore(&mut self, dir: &Path) -> bool {
let path = dir.join(GITIGNORE);
if !self.gitignore || !path.is_file() {
return Ok(false);
return false;
}
let rules = parse_gitignore(&std::fs::read_to_string(&path)?);
self.ignores.push(Ignore { base: self.rel.len(), rules });
Ok(true)
match std::fs::read_to_string(&path) {
Ok(text) => {
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
true
}
Err(e) => {
self.say(&path, e.to_string());
false
}
}
}
}
/// Why a directory entry has no metadata, said the way a person would.
///
/// A broken symbolic link is what this is nearly always about, and naming it
/// as one is worth more than the bare `No such file or directory` the follow
/// produced; anything else keeps the operating system's own words.
fn broken_link_reason(path: &Path) -> String {
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => "broken symbolic link".to_string(),
Ok(_) => "cannot be read".to_string(),
Err(e) => e.to_string(),
}
}
@@ -214,6 +526,8 @@ fn glob_component(pattern: &str, name: &str) -> bool {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::sync::atomic::{AtomicUsize, Ordering};
fn excluded(path: &str, pattern: &str) -> bool {
is_excluded(Path::new(path), &[pattern.to_string()])
@@ -320,6 +634,393 @@ mod tests {
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
}
// ------------------------------------------------------------------
// Symlink cycles — `docs/features/walk-cycles/README.md`
//
// Every test below builds a real tree with real symlinks, because the
// question is what the filesystem answers, not what a mock does. Each
// one would run until the OS refused a path before the visited set.
// ------------------------------------------------------------------
/// A throwaway directory tree under the system temp dir, removed on
/// drop. `remove_dir_all` unlinks a symlink instead of following it, so
/// a tree with a cycle in it is cleaned up like any other.
#[cfg(unix)]
struct TempTree {
path: PathBuf,
}
#[cfg(unix)]
impl TempTree {
fn new(tag: &str) -> TempTree {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-walk-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempTree { path }
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::fs::write(&path, text).expect("write");
}
/// A source file with enough in it to be worth finding.
fn source(&self, rel: &str) {
self.write(rel, "module m;\nendmodule\n");
}
/// Set `rel`'s permission bits. `0o000` is how a test builds the
/// directory the walk cannot read; the test puts them back so the
/// temp tree can be removed.
fn chmod(&self, rel: &str, mode: u32) {
use std::os::unix::fs::PermissionsExt;
let path = self.path.join(rel);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
.expect("set permissions");
}
/// `rel` as a symlink to `target`, which is relative to `rel`'s own
/// directory — the spelling a checked-in symlink actually uses.
fn link(&self, rel: &str, target: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::os::unix::fs::symlink(target, &path).expect("symlink");
}
/// The walk from `rel` (empty for the root), as sorted paths
/// relative to the tree root. Warnings are dropped; the tests that
/// care about them call [`TempTree::warned`].
fn walk(&self, rel: &str) -> Vec<String> {
self.walked(rel).0
}
/// The same, plus what the walk said, each warning's path made
/// relative to the tree root so the assertions read.
fn warned(&self, rel: &str) -> (Vec<String>, Vec<String>) {
self.walked(rel)
}
fn walked(&self, rel: &str) -> (Vec<String>, Vec<String>) {
let start = if rel.is_empty() { self.path.clone() } else { self.path.join(rel) };
let mut files = Vec::new();
let mut warnings = Vec::new();
collect_files(
start.to_str().expect("utf-8 temp path"),
&[],
true,
&mut files,
&mut |w| warnings.push(format!("{}: {}", self.rel_of(&w.path), w.message)),
)
.expect("the walk finishes");
let mut out: Vec<String> = files.iter().map(|p| self.rel_of(p)).collect();
out.sort();
warnings.sort();
(out, warnings)
}
fn rel_of(&self, path: &Path) -> String {
path.strip_prefix(&self.path).unwrap_or(path).to_string_lossy().into_owned()
}
}
#[test]
#[cfg(unix)]
fn a_directory_linking_to_itself_is_entered_once() {
let tree = TempTree::new("selfloop");
tree.source("a/x.sv");
tree.link("a/loop", "../a");
assert_eq!(tree.walk(""), ["a/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_link_to_an_ancestor_terminates_from_a_nested_start() {
let tree = TempTree::new("uplink");
tree.source("root.sv");
tree.source("a/x.sv");
tree.link("a/up", "..");
// Starting *inside* the cycle: `a` is entered, then `a/up` is the
// root, which the walk has not seen yet and so does enter — once.
// Its own `a` is the directory already being walked, and stops.
assert_eq!(tree.walk("a"), ["a/up/root.sv", "a/x.sv"]);
}
#[test]
#[cfg(unix)]
fn two_links_to_one_directory_yield_its_files_once() {
let tree = TempTree::new("twolinks");
tree.source("shared/x.sv");
// Sorted after `shared`, so the real directory is the spelling that
// reaches the file first; whichever name wins, the file is reported
// exactly once.
tree.link("z1", "shared");
tree.link("z2", "shared");
assert_eq!(tree.walk(""), ["shared/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_link_to_a_directory_not_yet_walked_is_still_followed() {
let tree = TempTree::new("sibling");
tree.source("shared/rtl/x.sv");
tree.link("proj/rtl", "../shared/rtl");
// The `rtl -> ../shared/rtl` of a real checkout: the target is
// outside the walk, so the link is the only way to it.
assert_eq!(tree.walk("proj"), ["proj/rtl/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_is_warned_about_and_not_handed_on() {
// §43's review kept the dangling source link in the file list so the
// front end's "no such file" error survived. TODO §45.2 reverses that
// on purpose: the warning is now the error's home, so the link is said
// once here and never reaches the formatter. A dangling link that
// names no source file was never going to be read and stays silent.
let tree = TempTree::new("dangling");
tree.source("a/x.sv");
tree.link("a/gone.sv", "nowhere.sv");
tree.link("a/gonedir", "nowhere");
let (files, warnings) = tree.warned("");
assert_eq!(files, ["a/x.sv"]);
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
// The finding this channel exists for: one permission-denied directory
// used to propagate `read_dir`'s error out of the whole walk, dropping
// every file already found and failing the run.
let tree = TempTree::new("unreadable");
tree.source("a.sv");
tree.source("locked/hidden.sv");
tree.source("z/late.sv");
tree.chmod("locked", 0o000);
let (files, warnings) = tree.warned("");
tree.chmod("locked", 0o755);
assert_eq!(files, ["a.sv", "z/late.sv"], "the walk finished");
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with("locked: "), "the warning names it: {warnings:?}");
}
#[test]
#[cfg(unix)]
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
let tree = TempTree::new("lockedignore");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
tree.chmod(".gitignore", 0o000);
let (files, warnings) = tree.warned("");
tree.chmod(".gitignore", 0o644);
assert_eq!(files, ["keep.sv"]);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with(".gitignore: "), "{warnings:?}");
}
#[test]
#[cfg(unix)]
fn a_clean_walk_says_nothing() {
let tree = TempTree::new("quiet");
tree.source("a/x.sv");
tree.source("b/y.sv");
assert_eq!(tree.warned(""), (vec!["a/x.sv".to_string(), "b/y.sv".to_string()], Vec::new()));
}
#[test]
#[cfg(unix)]
fn a_cycle_inside_an_ignored_directory_is_never_entered() {
let tree = TempTree::new("ignoredcycle");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
tree.source("build/y.sv");
tree.link("build/loop", "../build");
assert_eq!(tree.walk(""), ["keep.sv"]);
}
// ------------------------------------------------------------------
// The metadata hand-off — `docs/features/perf5r-first-answer/README.md`
// ------------------------------------------------------------------
/// Every path `collect_files_with` yields under `rel`, with its length.
#[cfg(unix)]
fn walked_with(tree: &TempTree, rel: &str) -> Vec<(String, Option<u64>)> {
let start = if rel.is_empty() { tree.path.clone() } else { tree.path.join(rel) };
let mut out = Vec::new();
collect_files_with(
start.to_str().expect("utf-8 temp path"),
&[],
true,
&mut |path, len| out.push((tree.rel_of(&path), len)),
&mut |_| {},
)
.expect("the walk finishes");
out
}
#[test]
#[cfg(unix)]
fn the_metadata_entry_yields_exactly_the_paths_the_plain_one_does() {
// The claim the server's cap rests on: `collect_files` is
// `collect_files_with` with the length thrown away, so the two cannot
// disagree about which files exist — not about order, not about
// `.gitignore`, not about a symlink cycle, not about a broken link.
let tree = TempTree::new("handoffsame");
tree.write(".gitignore", "build\n");
tree.source("a.sv");
tree.source("rtl/b.sv");
tree.source("rtl/deep/c.svh");
tree.source("build/hidden.sv");
tree.write("rtl/notsource.txt", "x");
tree.link("rtl/loop", "..");
tree.link("rtl/dangling.sv", "nowhere.sv");
let mut plain = Vec::new();
collect_files(tree.path.to_str().expect("utf-8"), &[], true, &mut plain, &mut |_| {})
.expect("the walk finishes");
let plain: Vec<String> = plain.iter().map(|p| tree.rel_of(p)).collect();
let handed: Vec<String> =
walked_with(&tree, "").into_iter().map(|(path, _)| path).collect();
assert_eq!(plain, handed, "the same paths in the same order, byte for byte");
}
#[test]
#[cfg(unix)]
fn a_walked_file_carries_the_length_the_walk_already_read() {
let tree = TempTree::new("handofflen");
tree.write("small.sv", "module m;\nendmodule\n");
tree.write("big.sv", &"// pad\n".repeat(500));
let found = walked_with(&tree, "");
let sizes: Vec<(String, Option<u64>)> = found;
assert_eq!(
sizes,
[("big.sv".to_string(), Some(3_500)), ("small.sv".to_string(), Some(20))],
"the length is the file's own, not a guess"
);
}
#[test]
#[cfg(unix)]
fn a_path_named_directly_is_handed_over_without_a_stat() {
// `None` is the walk saying it did not look — the file was named, not
// walked to, and adding a `metadata` call for it would be a cost
// `collect_files` never paid.
let tree = TempTree::new("handoffnamed");
tree.source("one.sv");
let found = walked_with(&tree, "one.sv");
assert_eq!(found, [("one.sv".to_string(), None)]);
}
/// What `collect_files_below(root, root/rel)` finds, relative to the tree.
#[cfg(unix)]
fn below(tree: &TempTree, rel: &str, exclude: &[&str]) -> Vec<String> {
let patterns: Vec<String> = exclude.iter().map(|p| p.to_string()).collect();
let mut out = Vec::new();
collect_files_below(
&tree.path,
&tree.path.join(rel),
&patterns,
true,
&mut |path, _| out.push(tree.rel_of(&path)),
&mut |_| {},
)
.expect("the walk finishes");
out.sort();
out
}
/// What a walk of the whole tree finds under `rel` — the answer `below`
/// has to reproduce.
#[cfg(unix)]
fn whole_under(tree: &TempTree, rel: &str, exclude: &[&str]) -> Vec<String> {
let patterns: Vec<String> = exclude.iter().map(|p| p.to_string()).collect();
let mut out = Vec::new();
collect_files(tree.path.to_str().expect("utf-8"), &patterns, true, &mut out, &mut |_| {})
.expect("the walk finishes");
let prefix = format!("{rel}/");
let mut under: Vec<String> =
out.iter().map(|p| tree.rel_of(p)).filter(|p| p.starts_with(&prefix)).collect();
under.sort();
under
}
#[test]
#[cfg(unix)]
fn a_walk_that_starts_below_a_root_still_obeys_that_roots_gitignore() {
// The whole reason `collect_files_below` exists. Starting the walk at
// `hw/ip/aes` loses every rule written above it, and a scope whose
// rung *is* the root would then index files that scope excludes.
let tree = TempTree::new("belowignore");
tree.write(".gitignore", "gen/\n*_generated.sv\n");
tree.write("hw/.gitignore", "vendor/\n");
tree.source("hw/ip/aes/rtl/aes.sv");
tree.source("hw/ip/aes/rtl/aes_generated.sv");
tree.source("hw/ip/aes/gen/made.sv");
tree.source("hw/ip/aes/vendor/third.sv");
tree.source("hw/ip/aes/dv/tb.sv");
let seen = below(&tree, "hw/ip/aes", &[]);
assert_eq!(seen, ["hw/ip/aes/dv/tb.sv", "hw/ip/aes/rtl/aes.sv"]);
assert_eq!(seen, whole_under(&tree, "hw/ip/aes", &[]), "the root walk agrees");
}
#[test]
#[cfg(unix)]
fn a_directory_the_root_walk_never_entered_yields_nothing_below_it() {
// An ancestor the root's own rules ignore is an ancestor the root walk
// never descended into, so nothing under it is in scope however
// directly it is named.
let tree = TempTree::new("belowblocked");
tree.write(".gitignore", "hw/vendor/\n");
tree.source("hw/vendor/ip/aes/aes.sv");
tree.source("hw/ip/aes/aes.sv");
assert!(below(&tree, "hw/vendor/ip/aes", &[]).is_empty());
assert_eq!(below(&tree, "hw/ip/aes", &[]), ["hw/ip/aes/aes.sv"]);
// An excluded ancestor is the same answer by the other filter.
assert!(below(&tree, "hw/ip/aes", &["ip"]).is_empty());
}
#[test]
#[cfg(unix)]
fn a_negation_below_the_root_still_wins_over_the_root_rule() {
// The precedence a root walk gives — deeper file last, so its `!` line
// re-includes — must survive the ancestor chain being pre-loaded.
let tree = TempTree::new("belownegate");
tree.write(".gitignore", "*.sv\n");
tree.write("hw/ip/aes/.gitignore", "!keep.sv\n");
tree.source("hw/ip/aes/keep.sv");
tree.source("hw/ip/aes/drop.sv");
let seen = below(&tree, "hw/ip/aes", &[]);
assert_eq!(seen, ["hw/ip/aes/keep.sv"]);
assert_eq!(seen, whole_under(&tree, "hw/ip/aes", &[]), "the root walk agrees");
}
#[test]
#[cfg(unix)]
fn a_start_that_is_not_under_the_root_finds_nothing() {
let tree = TempTree::new("belowoutside");
tree.source("a/x.sv");
let mut out = Vec::new();
collect_files_below(
&tree.path.join("a"),
&tree.path,
&[],
true,
&mut |path, _| out.push(path),
&mut |_| {},
)
.expect("no error, nothing found");
assert!(out.is_empty());
}
#[test]
fn unsupported_syntax_degrades_to_plain_globbing() {
// `**` is just two stars inside one component; documented.
@@ -329,4 +1030,37 @@ mod tests {
assert!(ignored("x?.sv", "x?.sv"));
assert!(!ignored("x?.sv", "xa.sv"));
}
#[test]
#[cfg(unix)]
fn tracker_detects_precedence_conflict_when_alias_sorts_before() {
let tree = TempTree::new("trackconflict");
tree.source("z_real/child.sv");
tree.link("a_alias", "z_real");
let mut tracker = DirectoryTracker::new();
assert_eq!(tracker.enter(&tree.path.join("z_real")), DirStatus::EnteredFirstTime);
assert!(!tracker.has_conflict());
// Entering a_alias afterwards detects that a_alias sorts before z_real
let status = tracker.enter(&tree.path.join("a_alias"));
assert!(matches!(status, DirStatus::PrecedenceConflict { .. }));
assert!(tracker.has_conflict());
}
#[test]
#[cfg(unix)]
fn tracker_allows_alias_sorting_after_without_conflict() {
let tree = TempTree::new("trackorder");
tree.source("a_real/child.sv");
tree.link("z_alias", "a_real");
let mut tracker = DirectoryTracker::new();
assert_eq!(tracker.enter(&tree.path.join("a_real")), DirStatus::EnteredFirstTime);
assert!(!tracker.has_conflict());
// Entering z_alias afterwards: already visited, no precedence conflict
assert_eq!(tracker.enter(&tree.path.join("z_alias")), DirStatus::AlreadyVisited);
assert!(!tracker.has_conflict());
}
}
+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
File diff suppressed because it is too large. Load diff
+81 -13
View File
@@ -14,6 +14,7 @@ use lsp_types::{
use vlog_linter::{apply_fixes, rule_by_name, Applicability, Violation};
use crate::convert::Positions;
use crate::lint::LintRun;
use crate::state::Document;
/// The kind of the fix-everything action, namespaced under `source.fixAll` so
@@ -27,23 +28,41 @@ pub const FIX_ALL: &str = "source.fixAll.lucisv";
/// client, because a fix-on-save request asks for `source.fixAll.lucisv` alone
/// and computing every quick fix for it would be work nobody reads.
pub fn code_actions(
run: &LintRun,
uri: &Uri,
doc: &Document,
range: Range,
only: Option<&[CodeActionKind]>,
tab_width: usize,
) -> Vec<CodeActionOrCommand> {
let violations = crate::lint::fixable(run, doc);
// Timed apart from the lint pass that found them: a menu that is slow
// because it *renders* a thousand fixes is a different problem from one
// that is slow because it found them (review round §R1b).
let actions = crate::lint_trace::stage(crate::lint_trace::Stage::Serialize, || {
offered(uri, doc, range, only, &violations)
});
crate::lint_trace::saw_actions(actions.len());
actions
}
/// The quick fixes and the fix-all action `only` asks for, built from
/// violations already found.
fn offered(
uri: &Uri,
doc: &Document,
range: Range,
only: Option<&[CodeActionKind]>,
violations: &[Violation],
) -> Vec<CodeActionOrCommand> {
let positions = doc.positions();
let violations = crate::lint::fixable(doc, tab_width);
let mut actions = Vec::new();
if wanted(only, &CodeActionKind::QUICKFIX) {
let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range));
actions.extend(quick.map(CodeActionOrCommand::CodeAction));
}
if wanted(only, &CodeActionKind::new(FIX_ALL)) {
actions.extend(
fix_all(uri, doc, &positions, &violations).map(CodeActionOrCommand::CodeAction),
);
actions
.extend(fix_all(uri, doc, &positions, violations).map(CodeActionOrCommand::CodeAction));
}
actions
}
@@ -131,6 +150,18 @@ fn title(violation: &Violation) -> String {
format!("lucisv: {what} [{}]", violation.rule)
}
/// Whether a client asking for `only` wants anything [`code_actions`] can
/// offer — a quick fix or the fix-all action.
///
/// The two kinds this module answers for are the only two the **lint pass**
/// answers for, so this is the question the dispatcher asks before reading the
/// buffer's configuration and running the rules. A client asking for
/// `refactor.*` or `source.organizeImports` alone gets neither, and now pays
/// for neither (take 5 §P1a).
pub fn wants_fixes(only: Option<&[CodeActionKind]>) -> bool {
wanted(only, &CodeActionKind::QUICKFIX) || wanted(only, &CodeActionKind::new(FIX_ALL))
}
/// Whether a client asking for `only` wants this kind. A filter is a prefix of
/// the kinds it selects (`source` selects `source.fixAll.lucisv`), and no filter
/// at all selects everything.
@@ -170,7 +201,7 @@ mod tests {
fn actions_of(ws: &Workspace) -> Vec<CodeAction> {
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
code_actions(&uri(), doc, whole, None, 2)
code_actions(&LintRun::default(), &uri(), doc, whole, None)
.into_iter()
.map(|a| match a {
CodeActionOrCommand::CodeAction(action) => action,
@@ -248,7 +279,13 @@ mod tests {
start: Position { line: 1, character: 0 },
end: Position { line: 1, character: 0 },
};
let actions = code_actions(&uri(), doc, line1, Some(&[CodeActionKind::QUICKFIX]), 2);
let actions = code_actions(
&LintRun::default(),
&uri(),
doc,
line1,
Some(&[CodeActionKind::QUICKFIX]),
);
assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}");
}
@@ -320,14 +357,19 @@ mod tests {
start: Position { line: fenced_line, character: 0 },
end: Position { line: fenced_line, character: 0 },
};
let actions = code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2);
let actions =
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]));
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
// The unfenced tab one line further down still has one.
let at = Range {
start: Position { line: 4, character: 0 },
end: Position { line: 4, character: 0 },
};
assert_eq!(code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2).len(), 1);
assert_eq!(
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]),)
.len(),
1
);
}
#[test]
@@ -370,14 +412,14 @@ mod tests {
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let fix_all_only = [CodeActionKind::new(FIX_ALL)];
let actions = code_actions(&uri(), doc, whole, Some(&fix_all_only), 2);
let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only));
assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for");
// `source` is a prefix filter for `source.fixAll.lucisv`.
let source = [CodeActionKind::SOURCE];
assert_eq!(code_actions(&uri(), doc, whole, Some(&source), 2).len(), 1);
assert_eq!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source)).len(), 1);
// And an unrelated filter selects nothing.
let refactor = [CodeActionKind::REFACTOR];
assert!(code_actions(&uri(), doc, whole, Some(&refactor), 2).is_empty());
assert!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor)).is_empty());
}
#[test]
@@ -386,7 +428,13 @@ mod tests {
let ws = workspace(text);
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let actions = code_actions(&uri(), doc, whole, Some(&[CodeActionKind::QUICKFIX]), 4);
let actions = code_actions(
&LintRun::default().with_tab_width(4),
&uri(),
doc,
whole,
Some(&[CodeActionKind::QUICKFIX]),
);
let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") };
assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n");
}
@@ -407,4 +455,24 @@ mod tests {
assert!(out.contains("é 🎉"), "comments are never dropped: {out:?}");
assert_eq!(out, "module m;\n // é 🎉 wire a;\nendmodule\n");
}
#[test]
fn an_externally_waived_finding_gets_no_quick_fix_and_fix_all_leaves_it() {
// §39 QA's HIGH: `fixable` used `default_rules()` and no waivers, so
// fix-on-save rewrote a line a checked-in waiver file had waived.
let src = "module m;\n\twire a;\nendmodule\n";
let ws = workspace(src);
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let waived = LintRun::default()
.with_waivers(std::path::Path::new("team.waiver"), "waive --rule=no-tabs\n");
assert!(
code_actions(&waived, &uri(), doc, whole, None).is_empty(),
"no quick fix and no fix-all for a waived finding"
);
assert!(
!code_actions(&LintRun::default(), &uri(), doc, whole, None).is_empty(),
"the same buffer without the waiver is fixable"
);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,114 @@
//! The completion tests' harness: a scratch workspace on disk, and the
//! handful of helpers every provider's tests ask through.
//!
//! `#[cfg(test)]` only; the tests themselves sit at the foot of the file
//! whose code they pin.
use std::fs;
use std::path::PathBuf;
use super::*;
use crate::uri::path_to_uri;
pub(super) const SUB: &str = "\
module sub #(
parameter int WIDTH = 8
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
";
/// A scratch workspace root. Removed on drop.
pub(super) struct Tree {
pub(super) path: PathBuf,
}
impl Tree {
pub(super) fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_server_completion_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
pub(super) fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
/// A two-file workspace with `top.sv` open, and the cursor at `needle`'s
/// end. `sub.sv` declares [`SUB`].
pub(super) fn asking(name: &str, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
let tree = Tree::new(name);
tree.write("sub.sv", SUB);
opened(tree, top, needle)
}
/// The same, with whatever `tree` already holds and no `sub.sv` implied.
pub(super) fn opened(tree: Tree, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
opened_named(tree, "top.sv", top, needle)
}
/// The same again, with the buffer's file name spelled out — which is what
/// decides its dialect.
pub(super) fn opened_named(
tree: Tree,
file: &str,
top: &str,
needle: &str,
) -> (Tree, Workspace, Uri, Position) {
let path = tree.write(file, top);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
let doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
(tree, ws, uri, position)
}
pub(super) fn items(response: Option<CompletionResponse>) -> Vec<CompletionItem> {
match response {
Some(CompletionResponse::List(list)) => list.items,
Some(CompletionResponse::Array(items)) => items,
None => Vec::new(),
}
}
pub(super) fn inserted(item: &CompletionItem) -> String {
match item.text_edit.as_ref().expect("a text edit") {
CompletionTextEdit::Edit(edit) => edit.new_text.clone(),
CompletionTextEdit::InsertAndReplace(edit) => edit.new_text.clone(),
}
}
/// The tier an item was filed under, read off its `sortText`.
pub(super) fn tier(item: &CompletionItem) -> char {
item.sort_text.as_ref().and_then(|s| s.chars().next()).expect("every item is sorted")
}
/// Only the module skeletons — tier 0, the M4 items.
pub(super) fn skeletons(items: &[CompletionItem]) -> Vec<&CompletionItem> {
items.iter().filter(|item| tier(item) == TIER_MODULE).collect()
}
pub(super) fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a CompletionItem> {
items.iter().find(|item| item.label == label)
}
pub(super) fn labels(items: &[CompletionItem]) -> Vec<&str> {
items.iter().map(|item| item.label.as_str()).collect()
}
File diff suppressed because it is too large. Load diff
+837
View File
@@ -0,0 +1,837 @@
//! `textDocument/completion` — module hinting, templates, keywords, and every
//! name the project uses.
//!
//! One response, six tiers, ordered by `sortText`:
//!
//! 0. **module names** — at module-item position only, every module the
//! workspace declares whose name contains what is typed. The item inserts
//! the **name alone**; the instantiation follows as ghost text once the
//! name is spelled exactly and a space follows it (`inline.rs`,
//! 2026-08-30);
//! 1. **what is visible here** — the declarations the scope chain at the
//! cursor binds, from this file's `Semantics`;
//! 2. **what the project declares** — packages, their members, typedefs,
//! classes, modules and `` `define`` names, from the workspace index;
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! tabstops, offered only where the construct may be written;
//! 4. **keywords** — every reserved word `vlog_parser` knows;
//! 5. **project words** — every identifier the in-scope files' *token
//! streams* contain, the rope/VS Code word-completion tier.
//!
//! A name is offered once, by the highest tier that claims it. Nothing is
//! offered inside a comment or a string literal, and nothing that only ever
//! appears inside one is ever a candidate — see `candidates.rs`.
//!
//! **Every tier is a table lookup.** No request here reads a file or parses
//! one, which is what makes the answer affordable on a keystroke in a
//! workspace the size of opentitan. The planning half of the old tier 0 —
//! [`plan_for`] and [`module_header`](module::module_header), still here
//! because they are still the way an instantiation is planned — is now called by `inline.rs` for exactly
//! one module, once the user has spelled its whole name and typed the space
//! that says so.
//!
//! See `docs/features/completion-core/README.md`, for tier 0
//! `docs/features/inline-instantiation/README.md` and
//! `docs/features/refactor-instantiate/README.md`, and for tier 3
//! `docs/features/completion-templates/README.md`.
//!
//! The module is one directory: this file is the entry point, the response
//! under construction (`Items`) and the small helpers every tier shares; the
//! rest is one file per answer, in the order `completions` consults them:
//!
//! * `word` — what is typed: the identifier run at the cursor, the backtick
//! or the `.`/`::` before it, and the spine a separator follows;
//! * `site` — what may be written here: the module-item and statement gates
//! over the token stream's scope chain;
//! * `member` — the exclusive answer after a `.` or a `::`, the connection
//! list included;
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
//! `instantiate.rs` share;
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
//! the response.
//!
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
//! entry points other modules of the crate use keep their paths through the
//! re-exports below. Each file's tests sit at its foot, on the harness in
//! `harness.rs`.
use std::collections::HashSet;
use lsp_types::{
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
TextEdit, Uri,
};
use vlog_parser::token::{Comment, TokenKind};
use vlog_parser::TextRange;
use vlog_refactor::Layout;
use vlog_semantic::{Symbol, SymbolKind};
use crate::candidates::Query;
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::Template;
use member::member_answer;
use module::module_tier;
use site::{at_module_item, at_statement, enclosing_scopes};
use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier};
use word::typed_word;
pub(crate) use module::{nearest_definition, plan_for};
// `perf.rs`, the one caller outside this module, is itself test-only; an
// unconditional re-export would be an unused import in every other build.
#[cfg(test)]
pub(crate) use module::module_header;
pub(crate) use site::at_instantiation_site;
pub(crate) use tiers::layout_at;
#[cfg(test)]
mod harness;
mod member;
mod module;
mod site;
mod tiers;
mod word;
/// How many items one response carries, over every tier.
///
/// Large enough that an *empty* prefix still reaches the last tier — 64
/// modules plus 181 keywords plus what one scope binds leaves room — and small
/// enough to bound the payload at a few tens of kilobytes. Tiers fill in
/// order, so a truncated list loses the least useful end of it and comes back
/// `isIncomplete`: the protocol's way of saying "ask me again when you have
/// typed more".
const LIMIT: usize = 512;
/// How many characters must be typed before a name may match by
/// *subsequence* rather than by prefix.
///
/// **VS Code's own rule**, which is the whole policy of this round: below
/// three characters its widget filters what it holds by prefix, and so does
/// the server; from three up both match by subsequence, so `clkenq` reaches
/// `clk_osc_en_q`. Matching the client is the point — a server that went
/// fuzzy at one character would answer a question the widget then filtered the
/// answer to, and one that never went fuzzy is what this round is fixing.
///
/// The floor is not only manners. A one-character fuzzy query matches most of
/// a workspace, which is a list nobody can read, and it is the one query the
/// character-mask prefilter cannot help with at all — one bit wide, it rejects
/// nothing, so the whole table is scanned. Measured at 2.7 ms over the real
/// opentitan word list against the 0.05 ms `clkenq` costs.
///
/// See `docs/features/fuzzy-completion/README.md`.
const FUZZY_MIN: usize = 3;
/// `sortText` prefixes. The client sorts on these, so they *are* the tier
/// order; the name follows so each tier is alphabetical within itself.
const TIER_MODULE: char = '0';
/// Members, after a `.` or a `::`.
///
/// The same digit as tier 0 and not a contradiction: the member answer is
/// **exclusive**, so no other tier's item is ever in the same response and
/// the digit orders members among themselves and nothing else. `'0'` because
/// these are not one tier of an answer but the whole of it. A sixth digit
/// would say there is a ranking against the other tiers to express, and there
/// is not.
const TIER_MEMBER: char = '0';
const TIER_SCOPE: char = '1';
const TIER_INDEX: char = '2';
const TIER_TEMPLATE: char = '3';
const TIER_KEYWORD: char = '4';
const TIER_WORD: char = '5';
/// What a multi-line item tells the client about its own whitespace.
///
/// Every skeleton here is laid out at the *site's* indentation already: a
/// `Layout`'s `base` is the trigger line's leading whitespace, and every line
/// after the first carries it. An editor that "helpfully" indents the
/// insertion again would double it — VS Code's `SnippetSession.adjustWhitespace`
/// prepends the insertion line's own indentation to every line after the first,
/// and it is on by default (`SuggestController._insertSuggestion` passes
/// `adjustWhitespace: !(insertTextRules & KeepWhitespace)`). `asIs` is the
/// protocol's way of saying "the text is already positioned, do not touch it",
/// and `vscode-languageclient` turns it into exactly the `keepWhitespace` flag
/// that clears the rule. Single-line items neither need it nor are harmed by
/// it; only the two tiers that write more than one line send it.
///
/// This is the sibling of the fix `inline.rs` had to make differently: an
/// inline completion has no such field, so its bodies are *relative* instead.
/// See `docs/features/inline-templates/README.md`, 2026-08-25.
const KEEP_MY_INDENTATION: InsertTextMode = InsertTextMode::AS_IS;
/// The completions available at a position, or nothing when the cursor is
/// somewhere no name may be written.
///
/// `snippets` is what the client advertised: without it a module skeleton is
/// inserted as plain text, because a literal `${1:clk}` left in a buffer is
/// worse than no tabstops at all.
pub fn completions(
ws: &Workspace,
uri: &Uri,
position: Position,
snippets: bool,
) -> Option<CompletionResponse> {
let doc = ws.document(uri)?;
let offset = doc.positions().offset(position);
// A buffer that does not lex has no token stream, so nothing here can tell
// a comment from code — and the commonest way to break the lexer is to
// open a string or a block comment and keep typing. Declining is the safe
// half of that trade; the buffer lexes again as soon as it is closed.
if doc.tokens.is_empty() || in_comment_or_string(doc, offset) {
return None;
}
let word = typed_word(doc, offset)?;
// A backtick admits exactly one kind of name, so the answer is only that
// kind — and the backtick already typed is inside the replaced range, so
// it is never doubled.
if word.backtick {
// The backtick itself is replaced, so the item may carry its own.
let replacing = TextRange::new(word.start.saturating_sub(1), offset);
let mut items = Items::new(doc, replacing);
for entry in ws.candidates().macros(&word.text) {
items.simple(
&format!("`{}", entry.name),
CompletionItemKind::CONSTANT,
TIER_INDEX,
entry.detail.clone(),
);
}
return items.finish();
}
// A `.` or a `::` admits exactly one kind of name too — a member of what
// stands before it — so the answer is only those. See [`member_answer`].
if word.sep.is_some() {
return member_answer(ws, doc, &word, offset);
}
// Both position gates read the same scope chain, and neither can be true
// unless the word starts a line — so a keystroke in the middle of an
// expression pays for neither.
let starts_a_line = word.at_line_start || word.statement_head;
let chain = match starts_a_line {
true => enclosing_scopes(&doc.tokens, word.start),
false => Vec::new(),
};
let at_item = word.at_line_start && at_module_item(doc, &chain, word.start);
let at_statement = starts_a_line && at_statement(doc, &chain, word.start);
// Prefix below [`FUZZY_MIN`], subsequence from it up. One `Query` for the
// whole request: it folds the typed characters and computes their mask
// once, and every tier that scans a table reads the same prepared form.
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
let mut items = Items::new(doc, word.range(offset));
module_tier(&mut items, ws, doc, &word, at_item);
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
index_tier(&mut items, ws, &word, fuzzy.as_ref());
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
keyword_tier(&mut items, &word);
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
// **The `isIncomplete` trap.** VS Code asks the server again on the next
// keystroke *only* when the last answer said it was incomplete; otherwise
// it filters the list it already holds. A complete two-character prefix
// answer would therefore be filtered client-side for the rest of the word,
// and the third keystroke — the one that turns fuzzy on — would never
// reach here at all. So every answer below the floor says it is
// incomplete, whatever the cap did.
//
// Above the floor the ordinary rule stands, and is sound because the hit
// set only ever *shrinks* as characters are appended: if a name holds
// `clke` in order it holds `clk` in order, so a complete answer at three
// characters really does contain every answer to four.
if fuzzy.is_none() {
items.incomplete = true;
}
items.finish()
}
/// The response under construction: the items, the names already spoken for,
/// and whether the cap cut anything off.
struct Items {
/// The bytes every item replaces, as the client reads them.
range: Range,
items: Vec<CompletionItem>,
seen: HashSet<String>,
incomplete: bool,
}
impl Items {
fn new(doc: &Document, replacing: TextRange) -> Items {
Items {
range: doc.positions().range(replacing),
items: Vec::new(),
seen: HashSet::new(),
incomplete: false,
}
}
/// Whether the cap has been reached. Once it has, every further candidate
/// only sets [`Items::incomplete`] — which is why the tiers ask first
/// rather than building items nobody will see.
fn full(&mut self) -> bool {
if self.items.len() >= LIMIT {
self.incomplete = true;
return true;
}
false
}
/// Add an item, unless a higher tier already offered that name or the
/// response is full.
fn push(&mut self, item: CompletionItem) {
if self.full() || !self.seen.insert(item.label.clone()) {
return;
}
self.items.push(item);
}
/// A plain-text item that inserts exactly its own name.
fn simple(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
if self.full() || self.seen.contains(name) {
return;
}
let item = CompletionItem {
label: name.to_string(),
kind: Some(kind),
detail: Some(detail),
sort_text: Some(format!("{tier}{name}")),
insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range: self.range,
new_text: name.to_string(),
})),
..Default::default()
};
self.push(item);
}
/// One template: the skeleton it inserts, the word it is reached by, and
/// the shape it expands to.
///
/// A client that never said it understands snippets gets the same text
/// with every hole filled in rather than nothing at all — the M4 ruling,
/// applied to a body whose defaults were chosen so that the result parses.
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
if self.full() || self.seen.contains(template.label) {
return;
}
let item = CompletionItem {
label: template.label.to_string(),
kind: Some(CompletionItemKind::SNIPPET),
detail: Some(format!("{} — template", template.detail)),
documentation: Some(Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: format!("```systemverilog\n{}\n```", template.expansion()),
})),
// The label is prose, so the client must be told what the user
// types to reach the item — otherwise `if` would not match
// `if begin/end` at all.
filter_text: Some(template.prefix.to_string()),
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
insert_text_format: Some(match snippets {
true => InsertTextFormat::SNIPPET,
false => InsertTextFormat::PLAIN_TEXT,
}),
insert_text_mode: Some(KEEP_MY_INDENTATION),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range: self.range,
new_text: template.render(layout, snippets),
})),
..Default::default()
};
self.push(item);
}
fn finish(self) -> Option<CompletionResponse> {
if self.items.is_empty() {
return None;
}
Some(self.into_list())
}
/// The response whether or not anything is in it.
///
/// [`Items::finish`]'s `None` means "this was not my question", which is
/// the right answer for a tiered response nobody filled. For the
/// **exclusive** member answer an empty list is the answer — the site
/// resolved and holds no matching member — and it has to be sent rather
/// than declined, because `None` carries no `isIncomplete` and so cannot
/// ask the client to come back with the third character.
fn into_list(self) -> CompletionResponse {
CompletionResponse::List(CompletionList {
is_incomplete: self.incomplete,
items: self.items,
})
}
}
/// The LSP icon a declaration gets in a completion list. The same choices
/// `symbols::lsp_kind` makes for the outline, in the other enum.
fn completion_kind(kind: SymbolKind) -> CompletionItemKind {
match kind {
SymbolKind::Module | SymbolKind::Package | SymbolKind::Block => CompletionItemKind::MODULE,
SymbolKind::Interface | SymbolKind::Modport => CompletionItemKind::INTERFACE,
SymbolKind::Clocking => CompletionItemKind::EVENT,
SymbolKind::Port | SymbolKind::StructMember => CompletionItemKind::FIELD,
SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar | SymbolKind::Instance => {
CompletionItemKind::VARIABLE
}
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => {
CompletionItemKind::CONSTANT
}
SymbolKind::Typedef => CompletionItemKind::TYPE_PARAMETER,
SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER,
SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION,
SymbolKind::Class => CompletionItemKind::CLASS,
SymbolKind::Constraint | SymbolKind::Coverpoint | SymbolKind::Cross => {
CompletionItemKind::PROPERTY
}
SymbolKind::Covergroup => CompletionItemKind::CLASS,
// A property and a sequence are named declarations a concurrent
// assertion calls by name, so they take the icon a function does.
SymbolKind::Property | SymbolKind::Sequence => CompletionItemKind::FUNCTION,
}
}
/// What a visible declaration shows beside its name: the line it was declared
/// on, which is the cheapest honest summary there is.
fn declaration_detail(doc: &Document, symbol: &Symbol) -> String {
let line = doc.positions().whole_lines(symbol.decl_span).lines().next().unwrap_or("").trim();
match line.is_empty() {
true => kind_label(symbol.kind).to_string(),
false => shorten(line, 80),
}
}
/// `text`, cut to `max` characters on a character boundary.
fn shorten(text: &str, max: usize) -> String {
match text.char_indices().nth(max) {
Some((at, _)) => format!("{}…", &text[..at]),
None => text.to_string(),
}
}
/// Whether `offset` sits inside a comment or a string literal — the two places
/// a completion list has no business appearing.
///
/// Comments are lexer trivia hanging off the token that follows (or precedes)
/// them, so this reads both. A linear pass over the token stream: a scan of a
/// few tens of thousands of tokens is tens of microseconds, and a binary
/// search would have to reason about which token a comment attached to.
fn in_comment_or_string(doc: &Document, offset: u32) -> bool {
for token in &doc.tokens {
if token.kind == TokenKind::String && token.span.start < offset && offset < token.span.end {
return true;
}
if token.leading.iter().chain(token.trailing.as_ref()).any(|c| in_comment(c, offset)) {
return true;
}
}
false
}
/// Whether `offset` is inside `comment`. A `//` comment runs to the end of the
/// line, so a cursor at its last byte is still inside it; a `/* */` one ends
/// at its marker, and the byte after that is code again.
fn in_comment(comment: &Comment, offset: u32) -> bool {
if offset <= comment.span.start {
return false;
}
match comment.text.starts_with("//") {
true => offset <= comment.span.end,
false => offset < comment.span.end,
}
}
/// One tabstop: `${n:default}`, or a bare `${n}` when there is no default to
/// preselect. The default is escaped, because `$`, `}` and `\` are the snippet
/// grammar's own punctuation and a type like `logic [$bits(t)-1:0]` really
/// does contain one.
///
/// `pub(crate)` for `inline.rs`, whose ghost instantiation writes the same
/// holes: one spelling of a tabstop, one place to fix an escaping bug.
pub(crate) fn snippet_hole(n: usize, default: &str) -> String {
if default.is_empty() {
return format!("${{{n}}}");
}
let mut escaped = String::with_capacity(default.len());
for ch in default.chars() {
if matches!(ch, '$' | '}' | '\\') {
escaped.push('\\');
}
escaped.push(ch);
}
format!("${{{n}:{escaped}}}")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::candidates::starts_with_ignore_case;
use crate::completion::harness::*;
use crate::settings::ClientSettings;
use crate::uri::path_to_uri;
use std::path::PathBuf;
#[test]
fn a_tabstop_default_is_escaped_so_the_snippet_grammar_cannot_read_it() {
assert_eq!(snippet_hole(1, ""), "${1}");
assert_eq!(snippet_hole(2, "8"), "${2:8}");
assert_eq!(snippet_hole(3, "$bits(t)"), "${3:\\$bits(t)}");
assert_eq!(snippet_hole(4, "a}b\\c"), "${4:a\\}b\\\\c}");
}
// ------------------------------------------------------------------
// comments and strings, both ways round
// ------------------------------------------------------------------
#[test]
fn nothing_is_offered_inside_a_comment_or_a_string() {
for (name, top, needle) in [
("line", "module top;\n // wid\nendmodule\n", "// wid"),
("block", "module top;\n /* wid */\nendmodule\n", "/* wid"),
("trailing", "module top;\n logic a; // wid\nendmodule\n", "// wid"),
("string", "module top;\n initial $display(\"wid\");\nendmodule\n", "\"wid"),
] {
let (_tree, ws, uri, position) = asking(&format!("in{name}"), top, needle);
assert!(completions(&ws, &uri, position, true).is_none(), "{name}: {top}");
}
}
#[test]
fn the_byte_after_a_block_comment_is_code_again() {
// The other half of the boundary: `/* x */w|` is not inside anything.
let top = "module top;\n /* c */ wid\nendmodule\n";
let (_tree, ws, uri, position) = asking("afterblock", top, "*/ wid");
assert!(completions(&ws, &uri, position, true).is_some());
}
#[test]
fn a_name_that_only_a_comment_or_a_string_holds_is_never_a_candidate() {
let tree = Tree::new("harvest");
tree.write(
"other.sv",
"module other;\n // widget_in_comment\n logic widget_in_code;\n\
initial $display(\"widget_in_string\");\nendmodule\n",
);
let top = "module top;\n assign x = widget\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= widget");
let items = items(completions(&ws, &uri, position, true));
let labels = labels(&items);
assert!(labels.contains(&"widget_in_code"), "{labels:?}");
assert!(!labels.contains(&"widget_in_comment"), "a comment is not code: {labels:?}");
assert!(!labels.contains(&"widget_in_string"), "a string is not code: {labels:?}");
}
#[test]
fn a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at() {
let top = "module top;\n logic a; /* unterminated\n wid\n";
let (_tree, ws, uri, position) = asking("nolex", top, " wid");
assert!(completions(&ws, &uri, position, true).is_none());
}
// ------------------------------------------------------------------
// `define names and the backtick
// ------------------------------------------------------------------
#[test]
fn a_backtick_offers_macro_names_and_only_macro_names() {
let tree = Tree::new("macro");
tree.write("defs.svh", "`define WIDTH 8\n`define MAX(a, b) 0\n");
tree.write("other.sv", "module other;\n logic WIDGET;\nendmodule\n");
let top = "module top;\n assign x = `WI\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "`WI");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(labels(&items), ["`WIDTH"], "only a macro may follow a backtick");
assert_eq!(inserted(&items[0]), "`WIDTH");
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(
edit.range.start,
Position { line: 1, character: 13 },
"the typed backtick is replaced, not doubled"
);
}
#[test]
fn a_macro_name_without_a_backtick_is_offered_bare() {
// Where a macro name is written without one: `` `ifdef NAME ``.
let tree = Tree::new("macrobare");
tree.write("defs.svh", "`define WIDTH 8\n");
let top = "module top;\n assign x = WID\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= WID");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "WIDTH").expect("the macro name");
assert_eq!(inserted(item), "WIDTH", "no backtick is invented");
assert_eq!(item.detail.as_deref(), Some("`define WIDTH"));
}
// ------------------------------------------------------------------
// filtering, the cap, and the scope ladder
// ------------------------------------------------------------------
#[test]
fn the_prefix_filters_server_side() {
let tree = Tree::new("prefix");
tree.write("other.sv", "module other;\n logic aaa_one, bbb_two;\nendmodule\n");
let top = "module top;\n assign x = aaa\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= aaa");
let items = items(completions(&ws, &uri, position, true));
assert!(!items.is_empty());
for item in &items {
assert!(
starts_with_ignore_case(&item.label, "aaa"),
"{} does not start with the typed prefix",
item.label
);
}
}
#[test]
fn a_full_response_is_truncated_and_says_it_is_incomplete() {
let mut top = String::from("module top;\n");
for i in 0..LIMIT + 40 {
top.push_str(&format!(" logic wsig{i:04};\n"));
}
top.push_str(" assign x = wsig\nendmodule\n");
let (_tree, ws, uri, position) = asking("cap", &top, "= wsig");
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
panic!("a completion list");
};
assert_eq!(list.items.len(), LIMIT);
assert!(list.is_incomplete, "a truncated list must say so");
}
#[test]
fn a_file_outside_the_filelist_contributes_no_words() {
// M1's ladder decides what "the project" is, and the word tier is
// built from exactly that list.
let tree = Tree::new("filelist");
tree.write("listed.sv", "module listed;\n logic word_listed;\nendmodule\n");
tree.write("unlisted.sv", "module unlisted;\n logic word_unlisted;\nendmodule\n");
tree.write("files.f", "listed.sv\n");
let top = "module top;\n assign x = word_\nendmodule\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
filelist: Some("files.f".to_string()),
..Default::default()
});
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
ws.rebuild_index();
let offset = (top.find("= word_").expect("needle") + 7) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let items = items(completions(&ws, &uri, position, true));
let labels = labels(&items);
assert!(labels.contains(&"word_listed"), "{labels:?}");
assert!(!labels.contains(&"word_unlisted"), "outside the project: {labels:?}");
}
#[test]
fn an_unsaved_edit_contributes_its_own_words_at_once() {
// The buffer's own token stream is read per request, so a name typed
// a moment ago is a candidate before anything is saved.
let top = "module top;\n logic fresh_name;\n assign x = fre\nendmodule\n";
let (_tree, ws, uri, position) = asking("unsaved", top, "= fre");
// The file on disk is `top` too, so make the buffer differ from it.
let edited = "module top;\n logic fresher_name;\n assign x = fre\nendmodule\n";
let mut ws = ws;
ws.set_document(uri.clone(), edited.to_string());
let items = items(completions(&ws, &uri, position, true));
assert!(labels(&items).contains(&"fresher_name"), "{:?}", labels(&items));
}
// ------------------------------------------------------------------
// the performance claim, measured
// ------------------------------------------------------------------
/// What a keystroke costs over the real corpus, and what the tables cost
/// to build. Skipped when `corpus/` is not checked out
/// (`tools/corpus_fetch.sh`), exactly like the other corpus tests.
///
/// The budgets are deliberately loose — a debug build on a loaded machine
/// is the worst case this ever runs in — and exist to catch an *order of
/// magnitude* regression, not to pin a number. The numbers themselves are
/// in `docs/features/completion-core/README.md`.
#[test]
fn a_keystroke_over_the_whole_corpus_stays_in_budget() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let started = std::time::Instant::now();
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus.clone()]);
let build = started.elapsed();
// A buffer that is not on disk: it overlays the walk, so the corpus is
// never written to.
let top = "module lucisv_probe;\n logic clk;\n assign x = pr\nendmodule\n";
let uri = path_to_uri(&corpus.join("lucisv_probe.sv")).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find("= pr").expect("needle") + 4) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
// Warm, then the measurement: ten requests, worst one reported. Twice
// — once for a typed prefix, once for the empty one, which is the
// worst case there is (every tier matches, and the cap does the work).
let empty = ws.document(&uri).expect("open").positions().position(offset - 2);
let mut worst = std::time::Duration::ZERO;
let mut worst_empty = std::time::Duration::ZERO;
for round in 0..11 {
let started = std::time::Instant::now();
let typed = items(completions(&ws, &uri, position, true));
let after_typed = started.elapsed();
let started = std::time::Instant::now();
let all = items(completions(&ws, &uri, empty, true));
let after_empty = started.elapsed();
assert!(!typed.is_empty());
assert_eq!(all.len(), LIMIT, "the empty prefix fills the response");
if round > 0 {
worst = worst.max(after_typed);
worst_empty = worst_empty.max(after_empty);
}
}
// …and the fuzzy path, which is a *scan* of the whole word table
// where the two above are a binary search into it. Six characters,
// the shape the round is named after.
let fuzzy = "module lucisv_probe;\n logic clk;\n assign x = clkenq\nendmodule\n";
ws.set_document(uri.clone(), fuzzy.to_string());
let offset = (fuzzy.find("= clkenq").expect("needle") + 8) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let mut worst_fuzzy = std::time::Duration::ZERO;
for round in 0..11 {
let started = std::time::Instant::now();
let found = items(completions(&ws, &uri, position, true));
let elapsed = started.elapsed();
assert!(!found.is_empty(), "the buffer's own `clk` matches at least");
if round > 0 {
worst_fuzzy = worst_fuzzy.max(elapsed);
}
}
eprintln!(
"corpus: {} files, {} words, {} index names; index+tables built in {build:?}; \
worst request {worst:?} typed / {worst_empty:?} empty / {worst_fuzzy:?} fuzzy",
ws.index().files().len(),
ws.candidates().words("").len(),
ws.candidates().units("").len(),
);
assert!(worst < std::time::Duration::from_millis(150), "a keystroke cost {worst:?}");
assert!(worst_empty < std::time::Duration::from_millis(150), "{worst_empty:?}");
assert!(worst_fuzzy < std::time::Duration::from_millis(150), "{worst_fuzzy:?}");
}
/// What a **member** request costs over the real corpus, against the
/// shapes the feature is named for: a generated register struct
/// (`uart_reg2hw_t`, eleven fields whose types are eleven more structs in
/// the same package), one of its inner registers reached by the
/// synthesized key, a package, and a connection list on a real wide
/// module.
///
/// The member answer is a table lookup like every other tier — one
/// `member_site` walk over one file's scopes, then one `BTreeMap` scan
/// per unit on the chain — so it should be *cheaper* than the tiered
/// answer, which scans three tables. Same loose budget, same reason: an
/// order of magnitude, not a number.
#[test]
fn a_member_request_over_the_whole_corpus_stays_in_budget() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus.clone()]);
let uri = path_to_uri(&corpus.join("lucisv_member_probe.sv")).expect("uri");
let mut worst = Vec::new();
for (what, top, needle) in [
(
"reg2hw.",
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.\n end\nendmodule\n",
" reg2hw.",
),
(
"reg2hw.ctrl.",
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n",
" reg2hw.ctrl.",
),
(
"uart_reg_pkg::",
"module lucisv_member_probe;\n initial begin\n $display(uart_reg_pkg::);\n end\nendmodule\n",
"uart_reg_pkg::",
),
// The connection list, against a real wide module in another
// file — the position the 2026-09-02 rework exists for.
(
"uart_core (.",
"module lucisv_member_probe;\n uart_core u_core (\n .\n );\nendmodule\n",
" .",
),
] {
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle") + needle.len()) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let mut slowest = std::time::Duration::ZERO;
let mut count = 0;
for round in 0..11 {
let started = std::time::Instant::now();
let found = items(completions(&ws, &uri, position, true));
let elapsed = started.elapsed();
count = found.len();
if round > 0 {
slowest = slowest.max(elapsed);
}
}
assert!(count > 0, "{what} must list members over the corpus");
worst.push(format!("{what} {count} members in {slowest:?}"));
assert!(slowest < std::time::Duration::from_millis(150), "{what} cost {slowest:?}");
}
eprintln!("corpus member requests: {}", worst.join(" / "));
}
/// **QA's own reproduction, against the real file.** `prim_fifo_sync`
/// derives `localparam int DepthW = prim_util_pkg::vbits(Depth+1)` in its
/// header; six `parameter`s stand above it. A `#(.` list must offer the
/// six and not the seventh. Skipped when `corpus/` is not checked out,
/// like every other corpus test.
#[test]
fn the_opentitan_shape_that_found_the_localparam_bug() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus.clone()]);
let top = "module lucisv_param_probe;\n prim_fifo_sync #(.) u_fifo ();\nendmodule\n";
let uri = path_to_uri(&corpus.join("lucisv_param_probe.sv")).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find("#(.").expect("needle") + 3) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(
found,
vec!["Depth", "NeverClears", "OutputZeroIfEmpty", "Pass", "Secure", "Width"],
"the six overridable parameters, and not the derived `DepthW`",
);
// …and `DepthW` is still *there*: a hierarchical read of it is legal
// and still resolves, which is what the split deliberately preserved.
assert!(
ws.index().members_of_chain("prim_fifo_sync").iter().any(|(name, _)| *name == "DepthW"),
"the localparam is still exported",
);
}
}
@@ -0,0 +1,923 @@
//! Tier 0 — module names at module-item position — and the instantiation
//! planning that `inline.rs`'s ghost and `instantiate.rs`'s command share.
//!
//! The tier itself is a table scan: the names the workspace declares, ranked
//! above everything else where an instantiation may be written. The planning
//! half is the one part of completion that costs a *parse*, and it is here
//! rather than in `inline.rs` because there must be exactly one answer to
//! "which file, and which header, is this module planned from" —
//! `nearest_definition` chooses among duplicate declarations and
//! `module_header` slices the declaring file down to its header before the
//! plan is built. See `docs/features/inline-instantiation/README.md` and
//! `docs/features/refactor-instantiate/README.md`.
use std::cmp::Reverse;
use std::path::Path;
use lsp_types::CompletionItemKind;
use vlog_parser::token::Token;
use vlog_parser::TextRange;
use vlog_refactor::{InstantiationPlan, Site};
use vlog_semantic::{SymbolKind, WorkspaceIndex};
use super::word::Word;
use super::{Items, TIER_MODULE};
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
/// How many module names one response carries.
///
/// Its own cap, below [`LIMIT`](super::LIMIT), because tier 0 matches a
/// *substring* and so answers far more widely than the prefix tiers: an empty word at item
/// position matches all 1 544 modules of opentitan, and letting one tier fill
/// the whole response would starve the five below it. It no longer bounds any
/// *work* — the tier is a scan of a table and nothing else, where until
/// 2026-08-30 each item cost one file read and one header parse.
const MODULE_LIMIT: usize = 64;
/// How far past a module's name [`module_header`] reads looking for the end of
/// its header, smallest first.
///
/// A ladder rather than one bound because the lex is the whole cost of the
/// slice and it is linear in what it is handed, so every header would
/// otherwise pay for the widest one. The rungs come from measuring opentitan's
/// 344 RTL modules: **59% of headers end inside 256 bytes**, 90% inside 2 KB,
/// and the largest — `aes_control_fsm_n`, sixty commented ports — is 6.6 KB.
/// The top rung is well past that, because a rung that is too small is not a
/// wrong answer but a whole-file parse, and for those files that is 2–4 ms
/// against the 0.6 ms of lexing 16 KB.
const HEADER_WINDOWS: [usize; 3] = [256, 2 * 1024, 16 * 1024];
/// Tier 0: the names of the modules that could be instantiated here, at
/// module-item position only.
///
/// **Names, not skeletons, since 2026-08-30** (owner ruling). Until then each
/// item carried the whole instantiation, which cost one `module_definition`
/// lookup, one file read and one header parse *per candidate* — up to
/// [`MODULE_LIMIT`] of each, on every keystroke, for a list the user reads one
/// line of. The instantiation is now offered by `inline.rs` as ghost text,
/// once the name before the cursor is spelled exactly and a space follows it,
/// and is planned once.
/// See `docs/features/inline-instantiation/README.md`.
///
/// What survives is the ranking, which is the tier's real job: at a position
/// where an instantiation may be written, a module name beats every other kind
/// of name, and it is matched as a *substring* so `reg_top` reaches
/// `aes_reg_top`.
pub(super) fn module_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
at_item: bool,
) {
if !at_item {
return;
}
// The same names `vlog_refactor::module_names` answers, off the table
// built with the index instead of off the index's whole symbol table —
// which the old call rebuilt and re-sorted on every keystroke.
let names = ws.candidates().modules(&word.text);
if names.len() > MODULE_LIMIT {
items.incomplete = true;
}
for name in names.into_iter().take(MODULE_LIMIT) {
items.simple(
name,
CompletionItemKind::MODULE,
TIER_MODULE,
module_detail(ws.index(), name, doc.path.as_deref()),
);
}
}
/// What a module item shows beside its name: where the module is declared.
///
/// A lookup in the index's unit table — no file is opened. The wording is tier
/// 2's, so a module offered by either tier reads the same.
///
/// **The file named is the one the ghost will read** ([`nearest_definition`]),
/// which since round 2 (2026-08-30) is an answer even for a name two files
/// declare: `ast_dft` under `top_earlgrey` and `ast_dft` under `top_darjeeling`
/// are two different headers, and the popup saying which one is coming is worth
/// more than the bare kind label it used to fall back to.
fn module_detail(index: &WorkspaceIndex, module: &str, from: Option<&Path>) -> String {
// An interface is instantiated exactly as a module is and rides this same
// list, so the label is read off what the index actually holds — a card
// that said "module" over an `interface` would be the wrong answer this
// round exists to remove.
let kind = index
.units(module)
.iter()
.find(|def| def.kind.is_instantiable())
.map_or(SymbolKind::Module, |def| def.kind);
let label = kind_label(kind);
let Some(path) = nearest_definition(index, module, from) else {
return label.to_string();
};
match path.file_name().and_then(|name| name.to_str()) {
Some(file) => format!("{label} — {file}"),
None => label.to_string(),
}
}
/// The file whose declaration of `module` a request made in `from` should be
/// planned from.
///
/// **This never refuses on multiplicity**, which is the whole of what parts it
/// from `vlog_refactor::module_definition`. That one errors when a name is
/// declared twice and will not guess; in opentitan `ast_dft` and `io_osc` are
/// each declared once under `hw/top_earlgrey/ip/ast/rtl` and once under
/// `hw/top_darjeeling/ip/ast/rtl`, so refusing meant two whole IP blocks with
/// no ghost at all. The owner's ruling of 2026-08-30 is that every indexed
/// module expands, so the server chooses instead of declining — and
/// `module_definition` keeps its refusal for its own callers, which want an
/// error message rather than a guess.
///
/// The rule is **nearest to the asker**: the declaration whose path shares the
/// longest run of leading *path components* with the document being typed in,
/// so a buffer under `hw/top_earlgrey/…` is offered top_earlgrey's copy. A tie
/// — and a buffer with no path at all — falls to the lexicographically smallest
/// path, so the answer never depends on the order the index happened to be
/// built in. Where the two declarations have different headers the user gets
/// the nearest one's; that is the accepted semantics, not an approximation.
///
/// A module only one file declares is chosen by exactly this path too, and
/// picks that one file — the same answer `module_definition` gives.
pub(crate) fn nearest_definition<'i>(
index: &'i WorkspaceIndex,
module: &str,
from: Option<&Path>,
) -> Option<&'i Path> {
index
.units(module)
.iter()
.filter(|def| def.kind.is_instantiable())
.filter_map(|def| index.path(def.file))
// Most shared leading components first; among those, the *shallowest*
// candidate — fewest components of its own past the shared prefix —
// then the lexicographically smallest path. The depth key is the QA
// round-2 fix: a copy in the asking buffer's own directory and one in
// a subdirectory of it share the same prefix with the buffer (the
// buffer's filename never matches a directory), and without the depth
// key the lexicographic tie-break could prefer the deeper, less
// related copy (`rstmgr/dv/rstmgr_cnsty_chk/tb.sv` over the direct
// sibling `rstmgr/dv/tb.sv`, because `'r' < 't'`).
.min_by_key(|path| {
let shared = shared_components(path, from);
(Reverse(shared), path.components().count() - shared, *path)
})
}
/// How many leading path components `path` and `from` spell the same way.
///
/// Components, not bytes: `hw/top_earlgrey` and `hw/top_darjeeling` share `hw`
/// and nothing else, where a byte-wise prefix would count `hw/top_` as shared
/// and rank two unrelated copies by a coincidence of spelling.
fn shared_components(path: &Path, from: Option<&Path>) -> usize {
let Some(from) = from else { return 0 };
path.components().zip(from.components()).take_while(|(ours, theirs)| ours == theirs).count()
}
/// One module's instantiation plan, off its header alone where that is the
/// whole of what the plan reads, and off its whole file otherwise.
///
/// The slice is an optimisation and never an answer of its own. Two things
/// send this back to the whole file, and both leave the answer exactly what it
/// was before the slice existed:
///
/// * the slice does not plan at all — [`module_header`] cut a header this
/// parser does not read as one;
/// * the plan it produced has a port with neither a direction nor a type,
/// which is what a **non-ANSI** port list looks like once its body is gone:
/// `module m (a); input wire a;` writes the direction below the header, and
/// the body is the part the slice drops.
///
/// `pub(crate)` for `inline.rs`, which plans the one module the user has
/// spelled out. One planner on purpose: a second answer to "what is this
/// module's instantiation" would eventually disagree with this one, and any
/// future non-ghost spelling of the skeleton (a command for clients without
/// `inlineCompletion`, say — filed in `docs/topo.md` §2.9) must come through
/// here too.
pub(crate) fn plan_for(
index: &WorkspaceIndex,
module: &str,
definition: &str,
site: Site<'_>,
) -> Result<InstantiationPlan, String> {
let whole = || vlog_refactor::instantiation_plan(module, definition, Some(site));
let Some(header) = module_header(index, module, definition) else { return whole() };
match vlog_refactor::instantiation_plan(module, &header, Some(site)) {
Ok(plan) if plan.ports.iter().all(|p| !p.dir.is_empty() || !p.ty.is_empty()) => Ok(plan),
_ => whole(),
}
}
/// The text one skeleton is planned from: the declaring file's header alone
/// where this function can find it, and the whole file where it cannot.
///
/// Tier 0 is the one tier that costs a *parse*, and until 2026-08-28 it parsed
/// the whole declaring file — three hundred lines of body to read a header a
/// few hundred bytes long, [`MODULE_LIMIT`] times per keystroke. A plan reads
/// nothing but the header, so nothing but the header needs to be parsed.
///
/// The prefix is kept **byte for byte**: every span the plan reads is an offset
/// into the text it was parsed from, so cutting the front off would move them
/// all. Only the body is dropped, and an `endmodule` is written in its place so
/// the declaration is closed.
///
/// **Every declaration of the name is tried, not just a lone one** (round 2,
/// 2026-08-30). Until then a name two files declared made this decline outright,
/// which cost `ast_dft` and `io_osc` their ghost; it now walks them, because
/// the index's span is only ever a *hint* here and the guard below is what
/// makes a hint safe. A span from the wrong file either does not spell the
/// module's name in this text — declined, and the caller parses the whole file
/// instead, exactly as it did before — or it does, in which case the slice is
/// taken from a real occurrence of the name in the text actually being read.
pub(crate) fn module_header(index: &WorkspaceIndex, module: &str, text: &str) -> Option<String> {
index
.units(module)
.iter()
.filter(|def| def.kind.is_instantiable())
.find_map(|def| header_from(module, def.name_span, text))
}
/// The header of the declaration `text` spells at `name`, or `None` when it
/// does not spell one there at all.
fn header_from(module: &str, name: TextRange, text: &str) -> Option<String> {
// The index's span is as of the last scan, and may belong to a sibling
// file that declares the same module. A file edited on disk since then has
// moved it, and a slice taken at a stale offset would be a different
// module's header — so the name has to still be there.
if text.get(name.start as usize..name.end as usize) != Some(module) {
return None;
}
let from = name.end as usize;
for size in HEADER_WINDOWS {
// A window that cuts a block comment or a string in half does not lex,
// and one that cuts the port list in half runs out of tokens before
// the `;`. Both answer "not in this window" and are asked again at the
// next rung; both answer `None` at the last one.
let window = text.get(from..text.len().min(from + size))?;
if let Ok(tokens) = vlog_parser::tokenize(window) {
if let Some(end) = header_end(&tokens) {
let head = text.get(..from + end as usize)?;
return Some(format!("{head}\nendmodule\n"));
}
}
if from + size >= text.len() {
break;
}
}
None
}
/// Where the header that begins just after a module's name ends: the offset
/// one past its terminating `;`, in the window's own coordinates.
///
/// A **whitelist**, not a scan for the first `;`: `module aes import
/// aes_pkg::*; #(...) (...);` writes three of them and only the last ends the
/// header. Anything this does not recognise — a compiler directive between the
/// name and the port list, a header longer than the window — answers `None`,
/// and the caller parses the whole file rather than guessing.
fn header_end(tokens: &[Token]) -> Option<u32> {
let mut at = 0;
loop {
let token = tokens.get(at)?;
match token.text.as_str() {
";" => return Some(token.span.end),
// A lifetime qualifier: `module automatic foo (...);`.
"static" | "automatic" => at += 1,
// A package import written into the header, whose own `;` is not
// the header's.
"import" => at = skip_to_semicolon(tokens, at + 1)?,
// The parameter list, the port list, and an attribute instance —
// each one parenthesised, each one skipped whole.
"#" | "(" => at = skip_parens(tokens, at)?,
_ => return None,
}
}
}
/// Past the parenthesised group starting at `at`, which a `#` may introduce.
fn skip_parens(tokens: &[Token], mut at: usize) -> Option<usize> {
while tokens.get(at)?.text == "#" {
at += 1;
}
if tokens.get(at)?.text != "(" {
return None;
}
let mut depth = 0i32;
loop {
match tokens.get(at)?.text.as_str() {
"(" => depth += 1,
")" if depth == 1 => return Some(at + 1),
")" => depth -= 1,
_ => {}
}
at += 1;
}
}
/// Past the next `;` written outside any parentheses.
fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
let mut depth = 0i32;
loop {
match tokens.get(at)?.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
";" if depth == 0 => return Some(at + 1),
_ => {}
}
at += 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use std::fs;
use std::path::PathBuf;
/// Completion's own view of the three new kinds, and the detail card that
/// used to hard-code "module" over an interface — the C2 wrong answer
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn an_interface_completes_as_an_interface() {
assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT);
let index = vlog_semantic::WorkspaceIndex::build([
(PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"),
(PathBuf::from("/rtl/sub.sv"), SUB),
]);
assert!(module_detail(&index, "bus_if", None).starts_with("interface"));
assert!(module_detail(&index, "sub", None).starts_with("module"));
// The ghost-instantiation lookups reach an interface too.
assert_eq!(
nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()),
Some("/rtl/bus_if.sv".to_string())
);
}
// ------------------------------------------------------------------
// tier 0's header slice (2026-08-28) — it must change no answer
// ------------------------------------------------------------------
/// Every header shape the slice has to survive, as (file text, module).
///
/// The list is the argument that the slice changes nothing: each entry is
/// planned both ways below and the two plans are compared field by field.
const SHAPES: &[(&str, &str)] = &[
// The ordinary ANSI header, params and all.
(SUB, "sub"),
// No ports at all.
("module bare;\nendmodule\n", "bare"),
// An empty port list.
("module empty ();\n logic x;\nendmodule\n", "empty"),
// A package import written into the header: its `;` is not the
// header's, and a slice that stopped there would report no ports.
(
"package p;\n localparam int W = 4;\nendpackage\n\
module imported import p::*; #(\n parameter int W = 8\n) (\n \
input logic clk,\n output logic [W-1:0] q\n);\n \
assign q = '0;\nendmodule\n",
"imported",
),
// Two imports, then a parameter list.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
"twice",
),
// A **non-ANSI** port list: the directions live in the body, which is
// exactly what the slice drops.
(
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
always @* b = |a;\nendmodule\n",
"old",
),
// Non-ANSI with nothing declaring the ports at all.
("module silent (a, b);\nendmodule\n", "silent"),
// A comment and an attribute inside the header.
(
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
input logic clk\n);\nendmodule\n",
"noisy",
),
// A lifetime qualifier.
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
// A second module in the same file, after the one being planned.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"first",
),
// …and before it, so the slice's prefix carries a whole module.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"second",
),
// A compiler directive between the name and the port list, which the
// whitelist refuses outright.
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
// A directive *inside* the port list, which carries a warning the two
// plans must both raise.
(
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
`endif\n);\nendmodule\n",
"ifdefd",
),
// An escaped identifier for the module and for a port.
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
// A header longer than the first rung of the window ladder.
(WIDE, "wide"),
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
// instance, `(* ... *)`, right after the module name and before the
// parameter list — the one shape the "noisy" case above is commented
// as covering but does not (it has two comments, no attribute).
// **Finding, not a regression this round introduced**: a module with
// an attribute anywhere near its header is not indexed as a `Module`
// unit at all (see
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
// so this pins the safe side effect — `module_header` declines before
// its whitelist walk ever runs — rather than the whitelist's own
// handling of attributes, which this shape cannot reach.
(
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
input logic clk\n);\nendmodule\n",
"attributed",
),
// An attribute instance *inside* the port list, attached to one port.
// Same finding as `attributed`: not indexed, so not reached either.
(
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
);\nendmodule\n",
"port_attributed",
),
// A single import declaration naming several packages, comma
// separated (`import a::*, b::*;`) — one statement, not two, and the
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module chained import p::*, q::*; (input logic a);\nendmodule\n",
"chained",
),
// A parameter default whose string literal carries the exact bytes
// the whitelist watches for — `;` and `)` — which must stay inside
// the `String` token and never be mistaken for header punctuation.
(
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
input logic clk\n);\nendmodule\n",
"stringy",
),
// CRLF line endings through the whole header.
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
];
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
input logic port_number_one_with_a_long_name,\n \
input logic port_number_two_with_a_long_name,\n \
input logic port_number_three_with_a_long_name,\n \
input logic port_number_four_with_a_long_name,\n \
input logic port_number_five_with_a_long_name,\n \
output logic port_number_six_with_a_long_name\n);\n \
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
/// The whole argument for the slice: for every shape above, the plan built
/// from the header alone is the plan built from the whole file. Where it
/// would not be — a non-ANSI list, a header the whitelist refuses — the
/// guard in [`plan_for`] sends the question back to the whole file, so the
/// comparison holds there too.
#[test]
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
for (text, module) in SHAPES {
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
let ours = plan_for(&index, module, text, site);
assert_eq!(ours, whole, "{module}");
}
}
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
/// trivially for a shape the whitelist declines — both sides parse the
/// whole file, so a wrong slice could hide behind that. These shapes must
/// actually slice, so the comparison exercises the whitelist walk it is
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
/// `;`/`)` sitting inside a string literal, and CRLF endings.
#[test]
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
module_header(&index, module, text).is_some(),
"{module}: expected the header to actually slice, not fall back whole-file"
);
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
/// differently off its header, and really is sent back to the whole file.
#[test]
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
let path = PathBuf::from("/rtl/old.sv");
let index = WorkspaceIndex::build(vec![(path, text)]);
let header = module_header(&index, "old", text).expect("the header slices");
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
assert!(
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
"premise: the header alone knows nothing about these ports"
);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let guarded = plan_for(&index, "old", text, site).expect("a plan");
assert_eq!(guarded.ports[0].dir, "input");
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
}
/// The whole answer, pinned at the prefixes the hot path is worst at — the
/// empty one and a one-character one, where every tier is at its widest.
/// Tier 0 answers with names, so the pin spells out every module item's
/// label *and* the text it inserts, which is now the label again.
#[test]
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
let tree = Tree::new("pinned");
tree.write("sub.sv", SUB);
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
let (_tree, mut ws, uri, _) =
opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
// Nothing typed, then one character — the two widest requests there
// are. `top` is in the answer because the buffer declares it and the
// index holds it like any other module.
let mut answer = |typed: &str| {
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
+ typed.len() as u32;
let doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
items(completions(&ws, &uri, position, true))
};
for (typed, expected) in
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
{
let items = answer(typed);
let found: Vec<&str> =
skeletons(&items).iter().map(|item| item.label.as_str()).collect();
assert_eq!(found, expected, "module items after typing {typed:?}");
}
// …and the exact text each of them inserts, which is the name and
// nothing else however many ports the module has. The instantiation is
// `inline.rs`'s business now.
let items = answer("");
for name in ["sub", "alpha", "submarine"] {
let item = find(&items, name).expect("the module item");
assert_eq!(inserted(item), name, "the popup inserts the name alone");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(item.insert_text_mode, None, "there is no indentation to keep");
}
}
/// A file edited on disk since the index last read it has moved every span
/// the index holds, so the slice must not take one on trust.
#[test]
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
let text =
"module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
// The same index against a file whose text has shifted underneath it.
let moved = format!("// a line nobody told the index about\n{text}");
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
}
// ------------------------------------------------------------------
// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30)
// ------------------------------------------------------------------
#[test]
fn a_module_name_at_item_position_completes_to_the_name_alone() {
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("nameonly", top, " su");
let items = items(completions(&ws, &uri, position, true));
let modules = skeletons(&items);
assert_eq!(modules.len(), 1, "{items:#?}");
let item = modules[0];
assert_eq!(item.label, "sub");
assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon");
assert_eq!(item.detail.as_deref(), Some("module — sub.sv"));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest");
assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show");
}
#[test]
fn the_snippet_flag_no_longer_changes_the_module_item() {
// The M4 fallback — a plain-text spelling of the skeleton for a client
// that never advertised `snippetSupport` — has nothing left to fall
// back from: the item is a word either way.
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, " su");
for snippets in [true, false] {
let items = items(completions(&ws, &uri, position, snippets));
let item = skeletons(&items)[0];
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "snippets: {snippets}");
}
}
/// The whole point of level 1: the popup no longer reads the files it
/// offers names from. Proved by deleting the declaring file after the
/// index has been built — the old tier answered nothing at all here,
/// because every item needed that file's text.
#[test]
fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() {
let tree = Tree::new("noread");
let sub = tree.write("sub.sv", SUB);
let (_tree, ws, uri, position) =
opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su");
fs::remove_file(&sub).expect("remove the declaring file");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(
skeletons(&items).iter().map(|item| item.label.as_str()).collect::<Vec<_>>(),
["sub"],
"the name comes from the index's table, not from the file: {items:#?}"
);
}
#[test]
fn the_edit_replaces_exactly_the_typed_word() {
let top = "module top;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("replace", top, " su");
let items = items(completions(&ws, &uri, position, true));
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}");
assert_eq!(edit.range.end, Position { line: 1, character: 4 });
}
}
#[test]
fn no_skeleton_is_offered_in_the_middle_of_an_expression() {
// The other tiers answer here — a name is a name wherever it is
// written — but a fifteen-line instantiation is not.
for (name, top, needle) in [
("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"),
("decl", "module top;\n logic su\nendmodule\n", "logic su"),
("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"),
("header", "module top (su\n);\nendmodule\n", "top (su"),
] {
let (_tree, ws, uri, position) = asking(name, top, needle);
let items = items(completions(&ws, &uri, position, true));
assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}");
}
}
#[test]
fn no_skeleton_is_offered_inside_a_procedural_block() {
let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("always", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "module top;\n initial begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("initial", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn no_skeleton_is_offered_inside_a_function_or_a_class() {
let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n";
let (_tree, ws, uri, position) = asking("function", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "package p;\n class c;\n su\n endclass\nendpackage\n";
let (_tree, ws, uri, position) = asking("class", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_generate_block_is_still_item_position() {
let top = "\
module top;
for (genvar i = 0; i < 4; i++) begin : g
su
end
endmodule
";
let (_tree, ws, uri, position) = asking("genfor", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}");
let top = "module top;\n generate\n su\n endgenerate\nendmodule\n";
let (_tree, ws, uri, position) = asking("generate", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1);
}
#[test]
fn no_skeleton_is_offered_outside_a_design_unit() {
let top = "su\nmodule top;\nendmodule\n";
let (_tree, ws, uri, position) = asking("toplevel", top, "su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_prefix_that_matches_no_module_offers_no_skeleton() {
let top = "module top;\n zzz\nendmodule\n";
let (_tree, ws, uri, position) = asking("nomatch", top, " zzz");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() {
// Until 2026-08-30 tier 0 skipped it: there is no single definition to
// build a *skeleton* from, and the skeleton was the item. A name needs
// no definition, so round 1 offered the name and left the detail
// blank. Round 2 (owner ruling, same day) makes the ghost choose a
// copy rather than decline, so the popup names the copy the ghost will
// read — `nearest_definition`'s answer, which for a buffer at the tree
// root is the lexicographically smaller path.
let tree = Tree::new("dup");
tree.write("a.sv", "module dup ();\nendmodule\n");
tree.write("b.sv", "module dup ();\nendmodule\n");
let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "dup").expect("the name is still known");
assert_eq!(tier(item), TIER_MODULE, "{items:#?}");
assert_eq!(item.detail.as_deref(), Some("module — a.sv"));
}
/// The nearest-definition chooser, at the level `inline.rs` consumes it.
///
/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling`
/// share `hw` and nothing more, and a byte-wise prefix would count the
/// `hw/top_` they spell alike and rank the copies by a coincidence.
#[test]
fn the_nearest_definition_is_the_one_sharing_the_most_path_components() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let index =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let asking = |from: &str| {
nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from)))
.expect("a definition")
.to_path_buf()
};
assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey);
assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling);
// Near neither, and no path at all: the tie falls to the smaller path
// rather than to whatever the index happens to hold first.
assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling);
assert_eq!(
nearest_definition(&index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
/// QA round-2 finding, fixed at lead review: a copy in the asking
/// buffer's own directory and one in a subdirectory of it share the same
/// number of leading components with the buffer (its filename never
/// matches a directory), and the lexicographic tie-break alone could pick
/// the deeper, less related copy. The real shape is opentitan's 61-way
/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv`
/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`.
#[test]
fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() {
let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv");
let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv");
let text = "module tb ();\nendmodule\n";
for sources in [
vec![(sibling.clone(), text), (deeper.clone(), text)],
vec![(deeper.clone(), text), (sibling.clone(), text)],
] {
let index = WorkspaceIndex::build(sources);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
sibling.as_path(),
"the shallower copy is the nearer one"
);
}
// …and depth only breaks a tie: a deeper copy that genuinely shares
// more of the asking path still wins.
let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
deeper.as_path(),
"sharing more components outranks being shallow"
);
}
/// The answer is a property of the paths, not of the order the index was
/// built in — which is what makes it the same answer twice in a row, and
/// the same answer in two editors.
#[test]
fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let forwards =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let backwards =
WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]);
for index in [&forwards, &backwards] {
let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv");
assert_eq!(
nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"),
earlgrey.as_path()
);
assert_eq!(
nearest_definition(index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
}
/// A module only one file declares goes through the same chooser and comes
/// back with the file `vlog_refactor::module_definition` picks — the
/// equivalence that says round 2 widened the twice-declared case and moved
/// nothing else.
#[test]
fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() {
let path = PathBuf::from("/rtl/sub.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]);
let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition");
assert_eq!(expected, path.as_path());
for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] {
assert_eq!(
nearest_definition(&index, "sub", from.as_deref()).expect("a definition"),
expected,
"{from:?}"
);
}
// And a name nothing declares is `None` here where it is an `Err`
// there — the same "no answer", spelled the way each caller reads it.
assert!(nearest_definition(&index, "nope", None).is_none());
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
}
}
+264
View File
@@ -0,0 +1,264 @@
//! What may be written here: the module-item gate and the statement gate,
//! judged over the token stream's scope chain.
//!
//! Both are heuristics over `pairs::analyze` — the same scope matcher the
//! begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
//! an unbalanced one still answers. Tier 0, the templates, `inline.rs`'s
//! ghost instantiation and `instantiate.rs` all ask these two questions, and
//! they ask them here so there is one answer to "may an instantiation go
//! here". The consts at the top are the whole of the grammar the gates know.
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use super::word::line_head_is_blank;
use crate::pairs;
use crate::state::{first_token_from, Document};
/// The scopes a module instantiation may be written directly inside.
const ITEM_SCOPES: &[&str] =
&["module", "macromodule", "interface", "program", "generate", "begin"];
/// Scopes that make everything inside them something other than a module item:
/// a subprogram body, a class body, a checker-ish declaration, a `case` arm's
/// interior, a `fork` block.
const NOT_ITEM_SCOPES: &[&str] = &[
"function",
"task",
"class",
"covergroup",
"property",
"sequence",
"clocking",
"specify",
"primitive",
"fork",
"case",
"casex",
"casez",
"randcase",
];
/// The scopes a *statement* may be written directly inside. A `begin` or a
/// `fork` qualifies only when it is procedural (see [`at_statement`]); a
/// `function`/`task` body always does.
const STATEMENT_SCOPES: &[&str] = &["begin", "fork", "function", "task"];
/// Keywords that make the `begin` after them procedural, so nothing inside it
/// is a module item. `@` is on the list because it is the whole of what stands
/// between `always` and its `begin`.
const PROCEDURAL: &[&str] =
&["always", "always_ff", "always_comb", "always_latch", "initial", "final", "@"];
/// Tokens that end whatever came before them, stopping the backward scan that
/// looks for a [`PROCEDURAL`] keyword.
const STATEMENT_END: &[&str] =
&["begin", "end", "endcase", "join", "join_any", "join_none", "generate", ";"];
/// Whether a module instantiation may be written starting at `at`.
///
/// **Tier 0's own gate**, factored out so `inline.rs`'s ghost instantiation
/// asks the identical question: the two features offer the same construct, and
/// a second answer to "may an instantiation go here" would eventually disagree
/// with this one. Both halves are here — the word must start its line, and the
/// scope chain covering it must be one an item belongs to (see
/// [`at_module_item`] for what that means and what it cannot see).
pub(crate) fn at_instantiation_site(doc: &Document, at: u32) -> bool {
if !line_head_is_blank(&doc.text, at) {
return false;
}
at_module_item(doc, &enclosing_scopes(&doc.tokens, at), at)
}
/// Whether `at` is somewhere a module instantiation could be written, judged
/// over the token stream.
///
/// This is a **heuristic, not a parse**, and the README says exactly what it
/// gets wrong. It reuses `pairs::analyze` — the same scope matcher the
/// begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
/// an unbalanced one still answers. Three conditions, all necessary:
///
/// 1. the innermost scope open here is one of [`ITEM_SCOPES`];
/// 2. no scope in the chain is one of [`NOT_ITEM_SCOPES`], so a `begin` inside
/// a `function` or a `case` arm is rejected however module-ish its parent;
/// 3. the outermost `begin` in the chain is not a procedural one — a
/// generate-`for`'s `begin` qualifies, an `always @(...)`'s does not.
///
/// Parentheses close the door too: an item never starts inside one, which is
/// what keeps a port list and a connection list out.
pub(super) fn at_module_item(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
let tokens = &doc.tokens;
if tokens.is_empty() {
return false;
}
let Some(&(innermost, opener)) = chain.first() else { return false };
if !ITEM_SCOPES.contains(&innermost) {
return false;
}
if chain.iter().any(|(keyword, _)| NOT_ITEM_SCOPES.contains(keyword)) {
return false;
}
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
if let Some(&(_, span)) = outermost_begin {
if is_procedural(tokens, span.start) {
return false;
}
}
balanced(tokens, opener.end, at)
}
/// Whether `at` is somewhere a *statement* could be written, judged over the
/// same scope chain [`at_module_item`] reads.
///
/// Two ways to qualify, and they are the only two this asks about:
///
/// 1. the innermost open scope is a `function` or a `task`, whose body is
/// statements all the way down; or
/// 2. it is a `begin`/`fork` whose outermost `begin` is a procedural one — the
/// exact inverse of the test that keeps module items out of an `always`.
///
/// Everything else is refused, `case` arms included: a bare `if` is not a
/// legal case item, and a gate that guesses at one would offer a template that
/// does not compile. Parentheses close the door here too.
pub(super) fn at_statement(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
let tokens = &doc.tokens;
if tokens.is_empty() {
return false;
}
let Some(&(innermost, opener)) = chain.first() else { return false };
if !STATEMENT_SCOPES.contains(&innermost) {
return false;
}
if innermost == "begin" || innermost == "fork" {
let in_subprogram = chain.iter().any(|(kw, _)| *kw == "function" || *kw == "task");
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
let procedural = match outermost_begin {
Some(&(_, span)) => is_procedural(tokens, span.start),
None => false,
};
if !in_subprogram && !procedural {
return false;
}
}
balanced(tokens, opener.end, at)
}
/// The scopes open at `at`, innermost first, as `(keyword, opener span)`.
pub(super) fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)> {
let analysis = pairs::analyze(tokens);
let mut out: Vec<(&'static str, TextRange)> = analysis
.pairs
.iter()
.filter(|pair| pair.open.end <= at && at <= pair.close.start)
.map(|pair| (pair.keyword, pair.open))
.chain(
analysis
.unmatched_open
.iter()
.filter(|open| open.span.end <= at)
.map(|open| (open.keyword, open.span)),
)
.collect();
// Innermost first: the scope that opened last is the one we are in.
out.sort_by_key(|(_, span)| std::cmp::Reverse(span.start));
out
}
/// Whether the `begin` starting at `offset` belongs to a procedural block.
///
/// Read backwards from the keyword: `always @(posedge clk) begin` reaches `@`
/// and then `always`, `initial begin` reaches `initial`, while a generate
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
/// `generate begin` reaches `generate`. Whichever comes first decides.
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
// A token starting exactly at `offset` is the first one that starts at or
// after it: every earlier token starts before, every later token after.
let begin = first_token_from(tokens, offset);
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
return false;
}
for token in tokens[..begin].iter().rev() {
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
return true;
}
if STATEMENT_END.iter().any(|kw| token.text == *kw) {
return false;
}
}
false
}
/// Whether every parenthesis opened between `from` and `at` was closed again.
pub(super) fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
let mut depth = 0i32;
// The tokens whose start falls in `[from, at)` are a contiguous run,
// because starts rise across the vector — so the filter this replaced was
// reading the whole buffer to reach a window the two bounds name outright.
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
for token in &tokens[window] {
if token.kind != TokenKind::Symbol {
continue;
}
match token.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
_ => {}
}
}
depth == 0
}
/// The whitespace the line holding `offset` begins with.
pub(super) fn line_indent(text: &str, offset: u32) -> String {
let Some(head) = text.get(..offset as usize) else { return String::new() };
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
head.get(line_start..).unwrap_or("").chars().take_while(|c| *c == ' ' || *c == '\t').collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// [`is_procedural`] used to sweep the vector for the token starting at
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
/// two offsets name. Both now binary-search; both must answer exactly what
/// the sweeps answered, at every byte and for every window.
#[test]
fn the_scope_gates_answer_what_their_sweeps_answered() {
let text = crate::state::mixed_buffer(20);
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
let tokens = &doc.tokens;
for offset in 0..=text.len() as u32 {
let swept = tokens.iter().position(|token| token.span.start == offset);
let searched = {
let begin = first_token_from(tokens, offset);
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
};
assert_eq!(swept, searched, "the token starting at {offset}");
}
// Every `begin`/`end` opener in the buffer against a spread of cursors
// after it: the two bounds are what pick the window out.
let openers: Vec<u32> = tokens
.iter()
.filter(|t| t.text == "begin" || t.text == "(")
.map(|t| t.span.end)
.collect();
assert!(openers.len() > 20, "premise: plenty of windows to check");
for from in openers {
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
let mut depth = 0i32;
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
if token.kind != TokenKind::Symbol {
continue;
}
match token.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
_ => {}
}
}
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
}
}
}
}
@@ -0,0 +1,979 @@
//! Tiers 1 to 5: the five ordinary tiers, in the order they fill the
//! response.
//!
//! What the scope chain binds, what the workspace index declares (macro
//! names included), the templates, the keywords, and every identifier the
//! project's token streams contain. Each is a filter over one table with the
//! house matching rule — prefix below `FUZZY_MIN`, subsequence from it up —
//! and each stops the moment the response is full. Tier 0 lives in
//! `module.rs` because its planning half is a different kind of work; the
//! member answer lives in `member.rs` because it is exclusive rather than a
//! tier.
use std::collections::HashSet;
use lsp_types::CompletionItemKind;
use vlog_parser::token::TokenKind;
use vlog_parser::KEYWORDS;
use vlog_refactor::Layout;
use vlog_semantic::{Semantics, Symbol};
use super::site::line_indent;
use super::word::Word;
use super::{
completion_kind, declaration_detail, Items, LIMIT, TIER_INDEX, TIER_KEYWORD, TIER_SCOPE,
TIER_WORD,
};
use crate::candidates::{rank_cmp, starts_with_ignore_case, Candidate, Query, Score};
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::{self, Gate, Template};
/// Tier 1: everything the scope chain at the cursor binds.
///
/// The one fuzzy tier with no mask table behind it, and deliberately so: what
/// a scope chain binds is tens of names computed per request, where a table of
/// masks would cost more to build than the scan it saved.
pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
let visible = visible_symbols(&doc.semantics, word.start);
let matched: Vec<&Symbol> = match fuzzy {
None => visible
.into_iter()
.filter(|symbol| starts_with_ignore_case(&symbol.name, &word.text))
.collect(),
Some(query) => {
let mut hits: Vec<(&Symbol, Score)> = visible
.into_iter()
.filter_map(|symbol| Some((symbol, query.score(&symbol.name)?)))
.collect();
hits.sort_by(|a, b| rank_cmp((&a.0.name, a.1), (&b.0.name, b.1)));
hits.into_iter().map(|(symbol, _)| symbol).collect()
}
};
for symbol in matched {
if items.full() {
break;
}
items.simple(
&symbol.name,
completion_kind(symbol.kind),
TIER_SCOPE,
declaration_detail(doc, symbol),
);
}
}
/// Every declaration the scope chain covering `offset` binds, innermost scope
/// first, each name only once — the inner declaration shadows the outer one,
/// which is the rule `vlog_semantic`'s own lookup follows.
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
let mut out = Vec::new();
let mut seen = HashSet::new();
let mut at = innermost_scope(semantics, offset);
while let Some(id) = at {
let Some(scope) = semantics.scope(id) else { break };
for symbol in scope.symbols.iter().filter_map(|&id| semantics.symbol(id)) {
if seen.insert(symbol.name.as_str()) {
out.push(symbol);
}
}
at = scope.parent;
}
out
}
/// The smallest scope whose span covers `offset`.
pub(super) fn innermost_scope(
semantics: &Semantics,
offset: u32,
) -> Option<vlog_semantic::ScopeId> {
semantics
.scopes()
.iter()
.enumerate()
.filter(|(_, scope)| scope.span.contains(offset))
.min_by_key(|(_, scope)| scope.span.len())
.map(|(i, _)| vlog_semantic::ScopeId(i as u32))
}
/// Tier 2: what the workspace index declares, `` `define`` names included.
///
/// The index names match fuzzily from [`FUZZY_MIN`](super::FUZZY_MIN) up;
/// the macro names do not. That is a deliberate split, not an oversight — see the feature
/// README's *What did not go fuzzy*.
pub(super) fn index_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
let matched: Vec<&Candidate> = match fuzzy {
None => ws.candidates().units(&word.text).iter().collect(),
Some(query) => {
let hits = ws.candidates().units_fuzzy(query, LIMIT);
// A full return means the scan kept its best LIMIT and dropped the
// rest, so the response is a best-of and has to say so. `full()`
// below would only notice if every one of them reached the list,
// and a name a higher tier already claimed does not.
items.incomplete |= hits.len() >= LIMIT;
hits.into_iter().map(|(unit, _)| unit).collect()
}
};
for candidate in matched {
if items.full() {
break;
}
items.simple(
&candidate.name,
completion_kind(candidate.kind),
TIER_INDEX,
format!("{} — {}", kind_label(candidate.kind), candidate.detail),
);
}
// Bare, with no backtick invented. A macro *use* is spelled with one and
// the user types it (see the early return above); the places a macro name
// is written without one — `` `ifdef NAME ``, `` `undef NAME `` — are
// exactly where this item is the right text.
for entry in ws.candidates().macros(&word.text) {
if items.full() {
break;
}
items.simple(&entry.name, CompletionItemKind::CONSTANT, TIER_INDEX, entry.detail.clone());
}
}
/// Tier 3: the statement, item and declaration templates.
///
/// Above the keywords because a user who typed `if` almost always wants
/// `if (…) begin … end` rather than the three letters they already typed, and
/// below both semantic tiers because a name the code actually declares beats a
/// skeleton every time. The templates a *position* rules out never reach the
/// list at all, so the ranking argument only has to hold where they do.
pub(super) fn template_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
snippets: bool,
at_item: bool,
at_statement: bool,
) {
if !at_item && !at_statement {
return;
}
let layout = layout_at(ws, doc, word.start);
let dialect = templates::dialect(doc.path.as_deref());
for template in templates::for_dialect(dialect) {
if items.full() {
break;
}
if !offered(template, at_item, at_statement) {
continue;
}
if !starts_with_ignore_case(template.prefix, &word.text) {
continue;
}
items.template(template, &layout, snippets);
}
}
/// Whether a template's gate lets it be written where the cursor is.
fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool {
match template.gate {
Gate::Statement | Gate::ElseTail => at_statement,
Gate::Item => at_item,
// A declaration is a module item and a block item both.
Gate::Declaration => at_item || at_statement,
}
}
/// How generated text is indented at `offset`: the line's own indentation, and
/// one step as `lucisv.indent` spells it.
///
/// Private from 2026-08-25 to 2026-09-02: `inline.rs` stopped sharing it when
/// ghost text moved to *relative* indentation and let the editor place it
/// (see `inline.rs`'s `render`). `pub(crate)` again for `instantiate.rs`,
/// whose `workspace/applyEdit` is plain text no editor re-indents, so it needs
/// exactly this — the real indentation of the real line.
pub(crate) fn layout_at(ws: &Workspace, doc: &Document, offset: u32) -> Layout {
let step = " ".repeat(ws.client_settings().indent.unwrap_or(2));
Layout { base: line_indent(&doc.text, offset), step }
}
/// Tier 4: every reserved word the lexer knows.
pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
for keyword in KEYWORDS.iter().filter(|kw| starts_with_ignore_case(kw, &word.text)) {
if items.full() {
break;
}
items.simple(keyword, CompletionItemKind::KEYWORD, TIER_KEYWORD, "keyword".to_string());
}
}
/// Tier 5: identifiers used anywhere in the project scope.
///
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
/// buffer being typed in is harvested afresh from its own token stream, so an
/// unsaved edit contributes to its own file's completions immediately.
pub(super) fn word_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
// Gathering and sorting the names is the one tier whose *setup* costs
// something, so a response that is already full skips it outright.
if items.full() {
return;
}
let names: Vec<&str> = match fuzzy {
None => {
let mut names: Vec<&str> =
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
names
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
names.sort_unstable();
names.dedup();
names
}
Some(query) => {
// The table's hits come back ranked; the buffer's own words are
// scored here and the two are ranked together, so a name the user
// typed a moment ago sits where its match deserves rather than
// after everything the table knows.
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
// A full return is a truncation; see `index_tier`.
items.incomplete |= hits.len() >= LIMIT;
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
hits.sort_by(|a, b| rank_cmp(*a, *b));
// A name in both lists is offered once: `Items` drops the second
// by label, so no dedup is needed here.
hits.into_iter().map(|(name, _)| name).collect()
}
};
for name in names {
if items.full() {
break;
}
items.simple(name, CompletionItemKind::TEXT, TIER_WORD, "used in this project".to_string());
}
}
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
///
/// The live half of the tier: the prebuilt table is as of the last index
/// rebuild, and this is the buffer's own token stream, recomputed on every
/// change. The filter is `candidates::is_word`'s, in the other direction —
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
/// identifier.
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
doc.tokens
.iter()
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
.map(|token| token.text.as_str())
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::completion::harness::*;
use crate::completion::*;
use crate::uri::path_to_uri;
// ------------------------------------------------------------------
// tier 3 — templates
// ------------------------------------------------------------------
/// Only the templates — tier 3.
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
items
.iter()
.filter(|item| tier(item) == TIER_TEMPLATE)
.map(|item| item.label.as_str())
.collect()
}
/// The items offered at `needle`'s end in a buffer named `file`.
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
items(completions(&ws, &uri, position, true))
}
#[test]
fn a_statement_template_expands_where_a_statement_may_be_written() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("stmt", "top.sv", top, " if");
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
assert_eq!(
inserted(item),
"if (${1:cond}) begin\n $0\n end",
"the site's own indentation, the condition first and the body last"
);
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
}
#[test]
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
// Dedup is by label, so the labels are prose on purpose: `if` the
// keyword and `if begin/end` the template are two items, in that
// order of specificity.
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("both", "top.sv", top, " if");
let keyword = find(&items, "if").expect("the bare keyword");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(keyword), TIER_KEYWORD);
assert_eq!(tier(template), TIER_TEMPLATE);
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
}
#[test]
fn a_template_ranks_below_a_name_the_code_declares() {
let top = "\
module top;
logic if_enable;
always_comb begin
if
end
endmodule
";
let items = offering("rank", "top.sv", top, " if");
let symbol = find(&items, "if_enable").expect("a declaration in scope");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(symbol), TIER_SCOPE);
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
}
#[test]
fn statement_templates_and_item_templates_swap_places_with_the_position() {
// One prefix, `i`, reaching `if` in one place and `initial` in the
// other — so this is the gate and not the filter.
let inside = offering(
"posstmt",
"top.sv",
"module top;\n always_comb begin\n i\n end\nendmodule\n",
" i",
);
assert!(template_labels(&inside).contains(&"if begin/end"));
assert!(
!template_labels(&inside).contains(&"initial begin/end"),
"an initial block is not a statement: {:?}",
template_labels(&inside)
);
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
assert!(template_labels(&at_item).contains(&"initial begin/end"));
assert!(
!template_labels(&at_item).contains(&"if begin/end"),
"a bare if is not a module item: {:?}",
template_labels(&at_item)
);
}
#[test]
fn an_always_template_is_a_module_item_and_nothing_else() {
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
"and `alw` finds every one of them"
);
let inside = offering(
"alwstmt",
"top.sv",
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
" alw",
);
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
}
#[test]
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
let inside = offering(
"declstmt",
"top.sv",
"module top;\n always_comb begin\n log\n end\nendmodule\n",
" log",
);
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
}
#[test]
fn the_file_name_decides_which_dialect_is_offered() {
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
assert!(template_labels(&sv).contains(&"logic name;"));
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
assert_eq!(template_labels(&reg), ["reg name;", "reg [N:0] name;"]);
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
#[test]
fn an_else_template_follows_an_end_on_the_same_line() {
let top = "\
module top;
always_comb begin
if (a) begin
end el
end
endmodule
";
let items = offering("elsetail", "top.sv", top, "end el");
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
assert_eq!(
inserted(find(&items, "else if").expect("the else-if template")),
"else if (${1:cond}) begin\n $0\n end"
);
}
#[test]
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
// The other half of the same rule: `x = if` is an expression, not a
// place a template belongs — and the general tiers still answer there.
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
let items = offering("midline", "top.sv", top, "x = if");
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
}
#[test]
fn no_template_is_offered_where_a_statement_cannot_go() {
for (name, top, needle) in [
// A generate block is item position, not statement position.
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
// A `case` arm wants `label:`, not a bare statement.
(
"casearm",
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
" if",
),
// Nothing at all is open here.
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
// A port list is not a statement, however much it starts a line.
("ports", "module top (\n if\n);\nendmodule\n", " if"),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
}
}
#[test]
fn a_subprogram_body_is_statement_position() {
for (name, top, needle) in [
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
(
"fnbegin",
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
" if",
),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
}
}
#[test]
fn nothing_templated_is_offered_inside_a_comment() {
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_client_without_snippet_support_gets_the_template_filled_in() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
let items = items(completions(&ws, &uri, position, false));
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
let text = inserted(item);
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
assert_eq!(text, "if (cond) begin\n\n end");
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the inserted text must parse: {text}"
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
let items = offering("tmpldocs", "top.sv", top, " alw");
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
panic!("markdown documentation");
};
// Fenced with the language id the extension's TextMate grammar is
// registered for, so the panel renders highlighted rather than grey.
assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value);
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
}
// ------------------------------------------------------------------
// tier 4 — keywords
// ------------------------------------------------------------------
#[test]
fn every_keyword_the_lexer_knows_is_offered() {
let top = "module top;\n assign x = alw\nendmodule\n";
let (_tree, ws, uri, position) = asking("keyword", top, "= alw");
let items = items(completions(&ws, &uri, position, true));
let keywords: Vec<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]);
let always = find(&items, "always").expect("`always`");
assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD));
assert_eq!(inserted(always), "always");
}
#[test]
fn the_keyword_tier_is_exactly_the_lexers_list() {
let top = "module top;\n assign x = \nendmodule\n";
let (_tree, ws, uri, position) = asking("allkeywords", top, "= ");
let items = items(completions(&ws, &uri, position, true));
let offered: HashSet<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
let known: HashSet<&str> = KEYWORDS.iter().copied().collect();
assert_eq!(offered, known, "no keyword may be missing and none invented");
}
// ------------------------------------------------------------------
// tiers, ordering and dedup
// ------------------------------------------------------------------
#[test]
fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() {
let tree = Tree::new("tiers");
tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n");
tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n");
let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= w");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE);
assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX);
assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD);
assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD);
let scope = find(&items, "w_local").expect("in scope");
let word = find(&items, "w_elsewhere").expect("a project word");
assert!(scope.sort_text < word.sort_text, "the client sorts scope above words");
}
#[test]
fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() {
let tree = Tree::new("dedup");
// The same name, declared here and used elsewhere in the project.
tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n");
let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= shared");
let items = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
items.iter().filter(|i| i.label == "shared_name").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it");
}
#[test]
fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() {
let top = "\
module top #(parameter int WIDTH = 8) (input logic clk);
typedef logic [1:0] pair_t;
logic [WIDTH-1:0] data;
function int f(); return 0; endfunction
assign x =
endmodule
";
let (_tree, ws, uri, position) = asking("kinds", top, "assign x =");
let items = items(completions(&ws, &uri, position, true));
let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind;
assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT));
assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD));
assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER));
assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE));
assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION));
assert_eq!(
find(&items, "data").expect("data").detail.as_deref(),
Some("logic [WIDTH-1:0] data;"),
"the declaration as written"
);
}
#[test]
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
// `inner` is declared in a block the cursor is not in, so it may only
// arrive as a project word — never as a visible declaration.
let top = "\
module top;
initial begin : b
integer inner_only;
end
initial begin
x = inner
end
endmodule
";
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "inner_only").expect("known as a word at least");
assert_eq!(tier(item), TIER_WORD, "{item:#?}");
}
// ------------------------------------------------------------------
// fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md
// ------------------------------------------------------------------
/// A workspace holding the name the whole round is about, a scatter to
/// rank it against, and a `ce…` name that only a prefix reaches.
fn typing(name: &str) -> (Tree, Workspace, Uri) {
let tree = Tree::new(name);
tree.write(
"ast.sv",
"module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\
endmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
(tree, ws, uri)
}
/// The response to `typed`, written mid-expression in `top.sv` — the
/// position where no tier is position-gated off.
fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option<CompletionResponse> {
let text = format!("module top;\n assign x = {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset =
(text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32;
let position = ws.document(uri).expect("open").positions().position(offset);
completions(ws, uri, position, true)
}
/// The headline: three characters reach a name no prefix ever would.
#[test]
fn three_characters_reach_a_name_a_prefix_never_would() {
let (_tree, mut ws, uri) = typing("fuzzyhit");
for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] {
let found = items(after_typing(&mut ws, &uri, typed));
let item = find(&found, "clk_osc_en_q")
.unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found)));
assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project");
assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted");
}
}
/// …and the edit still replaces exactly what was typed, which is the
/// whole reason a fuzzy hit is usable at all: `clkenq` becomes
/// `clk_osc_en_q`, not `clkenqclk_osc_en_q`.
#[test]
fn a_fuzzy_hit_replaces_exactly_the_typed_word() {
let (_tree, mut ws, uri) = typing("fuzzyedit");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit");
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
// ` assign x = clkenq` — the word starts at column 13 and the cursor
// is at its end.
assert_eq!(edit.range.start, Position { line: 1, character: 13 });
assert_eq!(edit.range.end, Position { line: 1, character: 19 });
assert_eq!(edit.new_text, "clk_osc_en_q");
assert_eq!(item.filter_text, None, "the client filters on the label, as it should");
}
/// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters
/// in order and must still not reach it.
#[test]
fn two_characters_match_by_prefix_and_nothing_else() {
let (_tree, mut ws, uri) = typing("fuzzyfloor");
for typed in ["c", "ce"] {
let found = items(after_typing(&mut ws, &uri, typed));
assert!(!found.is_empty(), "premise: {typed:?} answers something");
for item in &found {
assert!(
starts_with_ignore_case(&item.label, typed),
"{:?} is not a prefix match for {typed:?}",
item.label
);
}
}
// The discriminator, spelled out: `ce` would reach it if it were fuzzy
// (`c` at 0, `e` at 8), and `cen` — one character more — does.
let two = items(after_typing(&mut ws, &uri, "ce"));
assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two));
assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two));
let three = items(after_typing(&mut ws, &uri, "cen"));
assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three));
}
/// The 1- and 2-character answers, pinned against what they were before
/// fuzzy matching existed. The keyword tier is checked as a set rather
/// than listed, so adding a reserved word to the lexer does not break a
/// test about completion.
#[test]
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `c` itself is in the list because the buffer being typed in
// holds it as an `Ident` token — behaviour this round did not
// touch, pinned here because a golden that quietly lost it would
// be a change.
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["ce", "celsius"]),
] {
let found = items(after_typing(&mut ws, &uri, typed));
let named: Vec<&str> = found
.iter()
.filter(|item| tier(item) != TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
assert_eq!(named, expected, "the names {typed:?} answers with");
let keywords: Vec<&str> = found
.iter()
.filter(|item| tier(item) == TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
let expected_keywords: Vec<&str> =
KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect();
assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with");
}
}
/// **The `isIncomplete` trap.** VS Code asks again on the next keystroke
/// only when the last answer said it was incomplete, so a complete
/// two-character answer would swallow the third keystroke and fuzzy would
/// never fire at all.
#[test]
fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() {
let (_tree, mut ws, uri) = typing("fuzzyincomplete");
for typed in ["", "c", "ce"] {
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else {
panic!("a completion list for {typed:?}");
};
assert!(list.is_incomplete, "{typed:?} must ask to be asked again");
}
// From the floor up the ordinary rule stands: complete when the whole
// hit set fit, which is sound because appending a character can only
// ever shrink it.
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else {
panic!("a completion list");
};
assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len());
}
/// A prefix match is the best subsequence match there is, and the list
/// says so — asserted on the order of the array, which is what the cap
/// cuts and what a client that does not re-rank shows.
#[test]
fn a_prefix_hit_outranks_a_scattered_one() {
let (_tree, mut ws, uri) = typing("fuzzyrank");
let found = items(after_typing(&mut ws, &uri, "clk"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("clk_osc_en_q") < at("c_l_k_scatter"),
"the prefix hit leads: {:?}",
labels(&found)
);
}
/// Scoring the boundaries is visible in the order, not only in the score:
/// a run that starts after an underscore beats the same letters buried
/// mid-word.
#[test]
fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() {
let tree = Tree::new("fuzzyboundary");
tree.write(
"ast.sv",
"module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "ena"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("osc_ena_ready") < at("xxenaxx_ready"),
"the boundary run leads: {:?}",
labels(&found)
);
drop(tree);
}
/// Dedup survives the change: a name two tiers can reach is offered once,
/// by the better tier, whichever way it was matched.
#[test]
fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() {
let tree = Tree::new("fuzzydedup");
// The same name, declared in this buffer (tier 1) and used in the
// project (tier 5), reachable from `clkenq` by neither prefix.
tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("= clkenq").expect("needle") + 8) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
found.iter().filter(|item| item.label == "clk_osc_en_q").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE));
drop(tree);
}
/// The tiers that did **not** go fuzzy, pinned so the split is a decision
/// and not a drift: keywords, templates and macro names still match by
/// prefix, and the module tier still matches by substring.
#[test]
fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() {
let tree = Tree::new("fuzzyunchanged");
tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n");
tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
// Mid-expression: the macro name is offered bare by tier 2 and must
// not be reachable by subsequence, and neither is a keyword.
let found = items(after_typing(&mut ws, &uri, "clkenq"));
assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found));
let found = items(after_typing(&mut ws, &uri, "alws"));
assert!(labels(&found).is_empty() || !labels(&found).contains(&"always"));
// A backtick still answers by prefix only.
let text = "module top;\n assign x = `CLKENQ\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way");
// …and the module tier is still a substring match, which is wider
// than a prefix and narrower than a subsequence.
let text = "module top;\n osc_en\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("osc_en").expect("needle") + 6) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect();
assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it");
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
fn a_declaration_in_scope_is_reached_by_subsequence() {
let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "clk_osc_en_q").expect("the declaration");
assert_eq!(tier(item), TIER_SCOPE);
assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;"));
}
/// The index tier goes fuzzy too — a package member is reached the same
/// way a project word is.
#[test]
fn a_project_declaration_is_reached_by_subsequence() {
let tree = Tree::new("fuzzyindex");
tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "CLK_OSC_EN_Q").expect("the package member");
assert_eq!(tier(item), TIER_INDEX);
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT));
drop(tree);
}
#[test]
fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() {
let tree = Tree::new("overlay");
let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n");
let top = "module top;\n assign x = ov\nendmodule\n";
let (_tree, mut ws, uri, position) = opened(tree, top, "= ov");
let other_uri = path_to_uri(&other).expect("uri");
ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string());
ws.rebuild_index();
let items = items(completions(&ws, &uri, position, true));
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
}
}
+246
View File
@@ -0,0 +1,246 @@
//! What is typed: the identifier run ending at the cursor and what stands
//! around it — a backtick, a `.` or a `::`, and the spine a separator
//! follows.
//!
//! Everything here reads the buffer's *text* backwards from the cursor and
//! nothing else; the token-stream questions (is this an item position, a
//! statement position) are `site.rs`'s. The one shape decision made here is
//! `Word::sep`: a separator says the response is a member list and nothing
//! else, which is why the spine is read this early.
use vlog_parser::TextRange;
use crate::state::Document;
/// What may stand between the start of a line and a statement: the `end` of
/// the block before it and the `else` that chains onto it. Anything else on
/// the line means the word being typed is part of an expression, not the start
/// of a statement.
const STATEMENT_HEADS: &[&str] = &["end", "else", "end else"];
/// The identifier the user is part-way through typing, and what stands around
/// it.
pub(super) struct Word {
/// The identifier run, backtick excluded. Empty when the cursor follows
/// something that is not an identifier character.
pub(super) text: String,
/// Where the run starts — the byte after the backtick, when there is one.
pub(super) start: u32,
/// Whether a `` ` `` immediately precedes the run, making this a macro
/// name being typed and nothing else.
pub(super) backtick: bool,
/// Whether nothing but whitespace precedes the run on its line.
///
/// Half of the *module* gate, and deliberately blunt: an instantiation is
/// written at the start of a line, and a word that is not (`assign x =
/// fo|`, `logic fo|`, `.clk(cl|`) is somewhere a module name would be
/// wrong. It costs the rare user who writes two items on one line their
/// skeleton — a far better failure than offering a fifteen-line
/// instantiation in the middle of an expression. Every other tier ignores
/// it: a name is a name wherever it is written.
pub(super) at_line_start: bool,
/// Whether the only thing before the run on its line is [`STATEMENT_HEADS`]
/// — the `end` a statement follows, or the `else` it hangs off.
///
/// Half of the *template* gate, and the reason `end else if` completes: a
/// statement is written at the start of a line or right after one of those
/// two words, and nowhere else.
pub(super) statement_head: bool,
/// The `.` or `::` the run immediately follows, when it follows one.
///
/// Its presence alone decides the shape of the whole response: a
/// separator says the user is naming a **member** of what stands before
/// it, and nothing else may be written there — so the member answer is
/// exclusive, exactly as the backtick's is. A lone `:` (a case item, a
/// label, a ternary) is not a separator and is `None`.
pub(super) sep: Option<Sep>,
/// What stands before the separator, when it is a spine this can read.
/// `None` with a `sep` set means the response is nothing at all: there is
/// a member question here and no head to answer it about.
pub(super) spine: Option<Spine>,
}
/// The two separators that make the run after them a member name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Sep {
/// `handle.`, `vif.cb.`, `this.` — a member of a *value*'s type.
Dot,
/// `pkg::`, `cls::` — a member of a named unit.
Scope,
}
/// The head of a member access as the buffer spells it: the first identifier
/// of the chain, and the names between it and the cursor.
///
/// `item.hdr.` is `head = "item"`, `mids = ["hdr"]` — exactly the two
/// arguments [`vlog_semantic::Semantics::member_site`] takes, because they
/// are exactly what `bind.rs`'s own `spine` records for the same expression.
/// For [`Sep::Scope`] the head is the whole `::` path (`pkg`, `pkg::cls`) and
/// `mids` is empty.
pub(super) struct Spine {
pub(super) head: String,
pub(super) mids: Vec<String>,
}
impl Word {
/// The bytes a completion replaces: the word as typed.
pub(super) fn range(&self, cursor: u32) -> TextRange {
TextRange::new(self.start, cursor)
}
}
/// The identifier run ending at the cursor, and the shape of the line it sits
/// on. `None` only when the cursor is not on a character boundary of the text
/// the server holds.
pub(super) fn typed_word(doc: &Document, cursor: u32) -> Option<Word> {
let text = doc.text.get(..cursor as usize)?;
let head = text.trim_end_matches(is_ident_char);
let start = head.len();
let backtick = head.ends_with('`');
let bare = match backtick {
true => head.get(..head.len() - 1)?,
false => head,
};
let line_start = bare.rfind('\n').map_or(0, |newline| newline + 1);
let head = bare.get(line_start..)?;
let at_line_start = !backtick && line_head_is_blank(&doc.text, start as u32);
// `end else` and `end else` are the same head; nothing else is compared,
// so one `split_whitespace` join is the whole normalization needed.
let words = head.split_whitespace().collect::<Vec<&str>>().join(" ");
let statement_head = !backtick && STATEMENT_HEADS.contains(&words.as_str());
// A backtick admits only a macro name, and a macro name follows no
// separator, so the two questions never both apply.
let (sep, spine) = match backtick {
true => (None, None),
false => separator(bare),
};
Some(Word {
text: text.get(start..)?.to_string(),
start: start as u32,
backtick,
at_line_start,
statement_head,
sep,
spine,
})
}
/// The separator `before` ends with, and the head spine standing before that.
///
/// `::` is checked first, so a `pkg::` is never read as the lone `:` of a
/// case item, a block label or a ternary — that one is deliberately **not** a
/// separator, and a request there falls through to the ordinary six tiers
/// exactly as it always did.
fn separator(before: &str) -> (Option<Sep>, Option<Spine>) {
if let Some(rest) = before.strip_suffix("::") {
return (Some(Sep::Scope), scope_head(rest));
}
if let Some(rest) = before.strip_suffix('.') {
return (Some(Sep::Dot), dot_spine(rest));
}
(None, None)
}
/// The `::` path ending at `before`: `pkg`, `pkg::cls`.
fn scope_head(before: &str) -> Option<Spine> {
let mut segments = Vec::new();
let mut rest = before;
loop {
let (head, name) = split_ident(rest)?;
segments.push(name.to_string());
match head.strip_suffix("::") {
Some(next) => rest = next,
None => break,
}
}
segments.reverse();
Some(Spine { head: segments.join("::"), mids: Vec::new() })
}
/// The `.`-joined spine ending at `before`: `item`, `cfg.vif`, `q[i]`,
/// `this`, `super`.
///
/// **What it reads, and nothing else**: identifiers joined by `.`, each
/// optionally carrying balanced `[…]` index suffixes, which are stripped —
/// `q[i].` and `arr[3][k].` name a member of the element type, which is the
/// declared type name either way. Everything else answers `None`, and `None`
/// means the response is nothing at all rather than a guess: a call
/// (`f().b`), a cast, a concatenation, a macro invocation, a `::`-qualified
/// head (`pkg::cls.`, which is not how a class member is written anyway), and
/// whitespace anywhere in the spine (`a . b`, legal SystemVerilog nobody
/// writes — refusing it costs a popup, accepting it would mean deciding where
/// an expression ends by scanning backwards over arbitrary text).
fn dot_spine(before: &str) -> Option<Spine> {
let mut segments: Vec<String> = Vec::new();
let mut rest = before;
loop {
let (head, name) = split_ident(strip_indices(rest)?)?;
segments.push(name.to_string());
match head.strip_suffix('.') {
Some(next) => rest = next,
None => {
// A head reached through `::` is a unit, not a value, and
// `member_site` resolves the head on the lexical chain.
if head.ends_with(':') {
return None;
}
break;
}
}
}
segments.reverse();
let mut mids = segments;
let head = mids.remove(0);
Some(Spine { head, mids })
}
/// `text` split at the start of the identifier run it ends with, as
/// (what precedes it, the identifier). `None` when it does not end with one,
/// or when the run starts with a digit — that is a number, not a name.
fn split_ident(text: &str) -> Option<(&str, &str)> {
let head = text.trim_end_matches(is_ident_char);
let name = text.get(head.len()..)?;
if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
return None;
}
Some((head, name))
}
/// `text` with every balanced `[…]` it ends with removed. `None` when a `]`
/// has no matching `[` — an expression this cannot read, so nothing is
/// offered for it.
fn strip_indices(text: &str) -> Option<&str> {
let mut rest = text;
while rest.ends_with(']') {
let mut depth = 0usize;
let mut opened = None;
for (i, byte) in rest.bytes().enumerate().rev() {
match byte {
b']' => depth += 1,
b'[' => {
depth = depth.checked_sub(1)?;
if depth == 0 {
opened = Some(i);
break;
}
}
_ => {}
}
}
rest = rest.get(..opened?)?;
}
Some(rest)
}
fn is_ident_char(ch: char) -> bool {
ch.is_ascii_alphanumeric() || ch == '_' || ch == '$'
}
/// Whether nothing but indentation stands before `at` on its line — half of
/// the module gate, shared by [`typed_word`] and
/// [`at_instantiation_site`](super::site::at_instantiation_site).
pub(super) fn line_head_is_blank(text: &str, at: u32) -> bool {
let Some(head) = text.get(..at as usize) else { return false };
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
head.get(line_start..).is_some_and(|head| head.chars().all(|c| c == ' ' || c == '\t'))
}
+234 -8
View File
@@ -24,15 +24,20 @@ impl<'a> Positions<'a> {
/// The LSP position of a byte offset. An offset inside a multi-byte
/// character is floored to that character's start.
///
/// The conversion itself lives on [`LineIndex`], so that the semantic
/// index — which records the same positions for a declaration while its
/// file is scanned — cannot answer differently from the wire.
pub fn position(&self, offset: u32) -> Position {
let offset = self.floor_boundary(offset);
let (line, _) = self.index.line_col(offset);
let start = self.index.line_range(line).map_or(0, |r| r.start) as usize;
let slice = self.text.get(start..offset as usize).unwrap_or("");
// LSP line content excludes the whole `\r\n`; `LineIndex` keeps the
// `\r` as an ordinary byte of its line, so drop it here.
let slice = slice.strip_suffix('\r').unwrap_or(slice);
Position { line: line - 1, character: utf16_len(slice) }
let (line, character) = self.index.utf16_position(self.text, offset);
Position { line, character }
}
/// A cursor for converting many byte offsets in one non-decreasing sweep,
/// in amortized O(1) each rather than [`position`](Self::position)'s
/// O(offset within its line).
pub fn walker(&self) -> PositionWalker<'_> {
PositionWalker { positions: self, line: 0, line_start: 0, cursor: 0, units: 0 }
}
/// The byte offset of an LSP position, clamped into the document.
@@ -112,6 +117,62 @@ impl<'a> Positions<'a> {
}
}
/// A monotonic byte-offset → [`Position`] cursor, for a caller that has a
/// whole sequence of offsets to convert and already has them in order.
///
/// [`Positions::position`] measures a line from its start on every call, which
/// is free on ordinary source and quadratic when thousands of tokens sit on
/// **one** very long line — the netlist shape the large-file fast path exists
/// for, where it cost seconds per keystroke. The walker carries the
/// measurement forward instead: one line lookup per call, and each byte of a
/// line counted once however many offsets fall on it.
///
/// **Total, not merely fast.** An offset below the last one is not an error
/// and never panics: the walker restarts at that line's start and re-measures,
/// which is exactly the work [`Positions::position`] would have done. So every
/// answer is that function's answer — by construction, and pinned by
/// `the_walker_agrees_with_the_per_call_converter_on_every_shape`.
pub struct PositionWalker<'a> {
positions: &'a Positions<'a>,
/// The 1-based line the cursor sits on. Zero before the first call, which
/// is a line number no offset has, so the first call always restarts.
line: u32,
/// The byte offset that line starts at.
line_start: u32,
/// How far into the text the cursor has measured, on that line.
cursor: u32,
/// UTF-16 units of `line_start..cursor`, before the `\r` rule below.
units: u32,
}
impl PositionWalker<'_> {
/// The LSP position of a byte offset — [`Positions::position`]'s answer,
/// reached without re-measuring the line for offsets already passed.
pub fn position(&mut self, offset: u32) -> Position {
let offset = self.positions.floor_boundary(offset);
let (line, _) = self.positions.index.line_col(offset);
if line != self.line || offset < self.cursor {
self.line = line;
self.line_start = self.positions.index.line_range(line).map_or(0, |r| r.start);
self.cursor = self.line_start;
self.units = 0;
}
let step = self.positions.text.get(self.cursor as usize..offset as usize).unwrap_or("");
self.units += utf16_len(step);
self.cursor = offset;
// The one `\r` `Positions::position`'s `strip_suffix` would drop: LSP
// line content excludes the whole `\r\n`, and `\r` is one UTF-16 unit.
let carriage = offset > self.line_start
&& self.positions.text.as_bytes().get(offset as usize - 1) == Some(&b'\r');
Position { line: line - 1, character: self.units - u32::from(carriage) }
}
/// The LSP range of a byte range, whose two ends are in order already.
pub fn range(&mut self, span: TextRange) -> Range {
Range { start: self.position(span.start), end: self.position(span.end) }
}
}
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
fn utf16_len(s: &str) -> u32 {
s.chars().map(|c| c.len_utf16() as u32).sum()
@@ -283,6 +344,171 @@ mod tests {
});
}
// ------------------------------------------------------------------
// the monotonic walker
// ------------------------------------------------------------------
/// A fixed-seed linear congruential generator — deterministic randomness
/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` and
/// `tokens.rs` use.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
self.0 >> 33
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n.max(1)
}
}
/// Every shape a byte → position converter has to survive: multi-byte and
/// astral characters, CRLF, empty lines, a last line with no terminator,
/// and a buffer that is one enormous line — the shape the walker exists
/// for.
fn fixtures() -> Vec<String> {
let mut giant = String::from("module m; wire ");
for n in 0..2_000 {
giant.push_str(&format!("a{n},"));
}
giant.push_str("last;\nendmodule\n");
let mut wide_and_wide = String::from("// é ✓ 🎉 ");
for n in 0..500 {
wide_and_wide.push_str(&format!("würe_{n}_✓, "));
}
wide_and_wide.push_str("\r\nendmodule\n");
vec![
String::new(),
"module m;\nendmodule\n".to_string(),
"// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule".to_string(),
"ab\r\ncd\r\n\r\nef\r\n".to_string(),
"\n".repeat(50),
giant,
wide_and_wide,
]
}
#[test]
fn the_walker_agrees_with_the_per_call_converter_on_every_shape() {
let mut rng = Lcg(0x5EEDA11);
for text in fixtures() {
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let len = text.len() as u64;
for trial in 0..20 {
// Two strides, alternating: a crawl of a few bytes at a time
// (many offsets on one line, which is what the walker is for)
// and one that crosses the whole fixture in a few dozen steps.
let stride = if trial % 2 == 0 { 4 } else { (len / 20).max(1) };
let mut offset = rng.below(len + 1) as u32;
let mut walker = positions.walker();
for _ in 0..60 {
assert_eq!(
walker.position(offset),
positions.position(offset),
"{text:?} at {offset}"
);
offset += rng.below(stride * 2) as u32;
}
}
}
}
#[test]
fn the_walker_agrees_at_every_byte_of_a_gnarly_buffer() {
// Ascending one byte at a time walks through the middle of every
// multi-byte character and over both bytes of every `\r\n`.
let text = "// é ✓ 🎉\r\nmodule mü;\n\r\n wire ✓a;\r\nendmodule";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut walker = positions.walker();
for offset in 0..=text.len() as u32 + 2 {
assert_eq!(walker.position(offset), positions.position(offset), "at {offset}");
}
}
#[test]
fn a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position() {
// Out of order is debug-unreachable for the callers, but the walker
// is total: a backwards offset restarts the measurement rather than
// returning a stale column.
let text = "// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut rng = Lcg(0xBACC1);
let mut walker = positions.walker();
for _ in 0..500 {
let offset = rng.below(text.len() as u64 + 4) as u32;
assert_eq!(walker.position(offset), positions.position(offset), "at {offset}");
}
}
/// QA attack (fix-round re-verification): the walker's restart is a
/// per-line promise, not a per-document one. Two huge lines far apart,
/// hit in alternation — the shape that would expose an accidental
/// document-wide rescan hiding inside the "reset to line start" path.
/// Each call still answers `Positions::position`'s answer exactly, and
/// (checked by hand alongside this test, not asserted here to keep the
/// test itself fast and non-flaky) costs only that one line's length,
/// never the whole document's.
#[test]
fn a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly() {
let mut text = String::new();
text.push_str(&"a".repeat(20_000));
text.push('\n');
text.push_str(&"b".repeat(20_000));
text.push('\n');
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let line1_positions = [0u32, 1, 5_000, 19_999, 20_000];
let line2_start = 20_001u32;
let line2_positions =
[line2_start, line2_start + 1, line2_start + 5_000, line2_start + 19_999];
let mut walker = positions.walker();
for round in 0..50 {
let (a, b) = line1_positions
.iter()
.zip(line2_positions.iter().cycle())
.nth(round % line1_positions.len())
.expect("non-empty");
for &offset in [*a, *b].iter() {
assert_eq!(
walker.position(offset),
positions.position(offset),
"round {round}, offset {offset}"
);
}
}
}
#[test]
fn the_walkers_range_is_the_per_call_range() {
let text = "module m;\r\n wire ✓a, b, c;\nendmodule\n";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut walker = positions.walker();
for span in [
TextRange::new(0, 6),
TextRange::new(9, 11),
TextRange::new(13, 17),
TextRange::new(20, 21),
TextRange::new(30, text.len() as u32),
] {
assert_eq!(walker.range(span), positions.range(span), "{span:?}");
}
}
#[test]
fn a_walker_over_an_empty_document_answers_the_one_position_there_is() {
with("", |p| {
let mut walker = p.walker();
assert_eq!(walker.position(0), pos(0, 0));
assert_eq!(walker.position(99), pos(0, 0));
});
}
#[test]
fn an_empty_document_has_one_position() {
with("", |p| {
@@ -0,0 +1,525 @@
//! The VS Code instance-oriented design hierarchy.
//!
//! LSP call hierarchy deliberately groups a module's calls by target module
//! type. The sidebar needs the other view of the same facts: every individual
//! instance name, its source range, and every declaration its module type may
//! name. The response stays flat; the client chooses roots and expands paths,
//! which keeps recursion out of the protocol and lets one snapshot serve
//! search as well as rendering.
//!
//! **Two things this answer must not be, and the shape follows from both.** It
//! must not read files — every line and character below was converted once,
//! when the declaring file was scanned, and rides the index
//! (`vlog_semantic::DeclPositions`, `InstanceOccurrence::positions`). And it
//! must not be enormous: a whole design re-sent on every save is a message the
//! request queue is blocked writing. So a URI is written **once**, in `files`,
//! and every location names it by index; a range is four numbers rather than
//! four nested objects; a row carries no id, because the client can compose the
//! one it used to be sent; and an instance carries no copy of the declarations
//! its module name resolves to, because the client already has every module.
//! Those four together are 11.6 MB → 1.9 MB on opentitan, and the client
//! rebuilds the richer shape in `hierarchyModel.js`'s `validateSnapshot` — see
//! `docs/features/vscode-hierarchy-sidebar/README.md`.
use std::collections::HashMap;
use serde::Serialize;
use vlog_semantic::{FileId, Utf16Range, WorkspaceIndex};
use crate::state::Workspace;
use crate::uri::path_to_uri;
pub const METHOD: &str = "lucisv/moduleHierarchy";
pub const CHANGED_METHOD: &str = "lucisv/moduleHierarchyChanged";
/// The wire version. Bumped on any change to the shape below; the client
/// refuses a snapshot it does not recognise rather than half-reading one.
const SCHEMA_VERSION: u32 = 2;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
schema_version: u32,
revision: u64,
complete: bool,
/// Every file a location below names, once. Locations index into this.
files: Vec<String>,
modules: Vec<Module>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Module {
module_name: String,
definition: Location,
instances: Vec<Instance>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Instance {
instance_name: String,
module_name: String,
site: Location,
}
/// A place in the workspace: which file, the whole construct, and the name
/// inside it. Each range is `[startLine, startCharacter, endLine,
/// endCharacter]`, 0-based lines and UTF-16 characters — an LSP `Range` with
/// its four field names left off.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Location {
file: u32,
range: [u32; 4],
selection_range: [u32; 4],
}
/// A complete snapshot of the index currently installed in `workspace`.
///
/// **It reads no files.** The first shape of this function read every
/// module-declaring file and built a `LineIndex` over each — 5.0 s cold and
/// ~300 ms warm on opentitan, on *every* request, which is the per-request
/// whole-workspace read the release before it existed to kill.
///
/// `complete` is false only when the request arrived between two files of the
/// startup scan. The server sends `CHANGED_METHOD` when that scan lands, so a
/// client can render the partial answer as loading and replace it once.
pub fn snapshot(workspace: &Workspace, revision: u64, complete: bool) -> Snapshot {
let index = workspace.index();
let mut files = FileTable::default();
let mut modules = Vec::new();
let mut module_at = HashMap::new();
// An interface instance is an instantiation edge exactly as a module
// instance is, so both kinds are roots here — the wire shape is unchanged.
for (name, def) in index.instantiable_units() {
// Every file-scope declaration carries its positions; one without them
// would be a declaration the index built by some other route, and
// dropping it beats inventing a range for it.
let Some(positions) = def.lines.positions else { continue };
let Some(file) = files.of(index, def.file) else { continue };
module_at.insert((def.file, def.name_span.start, def.name_span.end), modules.len());
modules.push(Module {
module_name: name.to_string(),
definition: location(file, positions.name, positions.decl),
instances: Vec::new(),
});
}
for (target_name, edges) in index.instantiations() {
for edge in edges {
let owner = (edge.file, edge.owner.name_span.start, edge.owner.name_span.end);
let Some(&owner_at) = module_at.get(&owner) else { continue };
let Some(file) = files.of(index, edge.file) else { continue };
for occurrence in &edge.instances {
modules[owner_at].instances.push(Instance {
instance_name: occurrence.name.clone(),
module_name: target_name.to_string(),
site: location(file, occurrence.name_positions, occurrence.positions),
});
}
}
}
// `sort_by_cached_key`, not `sort_by`: both keys lowercase a name, and
// paying for that once per element rather than twice per comparison is the
// difference between a few and a few hundred thousand allocations on a
// workspace with 14 000 instances in it.
for module in &mut modules {
module.instances.sort_by_cached_key(|instance| instance_key(&files, instance));
}
modules.sort_by_cached_key(|module| module_key(&files, module));
Snapshot { schema_version: SCHEMA_VERSION, revision, complete, files: files.uris, modules }
}
/// The snapshot's file table: one URI per file, given an index the first time
/// a location needs it.
#[derive(Default)]
struct FileTable {
uris: Vec<String>,
at: HashMap<FileId, Option<u32>>,
}
impl FileTable {
/// This file's index, adding it if it is new. `None` for a path that is
/// not a URI — the same answer every other feature gives for such a path,
/// and it drops that file's rows rather than the whole snapshot.
fn of(&mut self, index: &WorkspaceIndex, file: FileId) -> Option<u32> {
if let Some(&known) = self.at.get(&file) {
return known;
}
let found = index.path(file).and_then(path_to_uri).map(|uri| {
self.uris.push(uri.as_str().to_string());
self.uris.len() as u32 - 1
});
self.at.insert(file, found);
found
}
fn uri(&self, file: u32) -> &str {
self.uris.get(file as usize).map_or("", |uri| uri.as_str())
}
}
/// One location, built from ranges the index already holds.
fn location(file: u32, selection: Utf16Range, whole: Utf16Range) -> Location {
Location { file, range: range(whole), selection_range: range(selection) }
}
fn range(range: Utf16Range) -> [u32; 4] {
[range.start.line, range.start.character, range.end.line, range.end.character]
}
fn module_key(files: &FileTable, module: &Module) -> (String, String, u32, u32) {
(
module.module_name.to_ascii_lowercase(),
files.uri(module.definition.file).to_string(),
module.definition.selection_range[0],
module.definition.selection_range[1],
)
}
fn instance_key(files: &FileTable, instance: &Instance) -> (String, String, String, u32, u32) {
(
instance.instance_name.to_ascii_lowercase(),
instance.module_name.to_ascii_lowercase(),
files.uri(instance.site.file).to_string(),
instance.site.selection_range[0],
instance.site.selection_range[1],
)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{json, Value};
use std::path::PathBuf;
struct Tree(PathBuf);
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_design_hierarchy_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree(path)
}
fn write(&self, name: &str, text: &str) {
std::fs::write(self.0.join(name), text).expect("write fixture");
}
fn workspace(&self) -> Workspace {
let mut workspace = Workspace::default();
workspace.open_whole_workspace(vec![self.0.clone()]);
workspace
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn taken(workspace: &Workspace) -> Value {
serde_json::to_value(snapshot(workspace, 7, true)).expect("serializes")
}
#[test]
fn a_snapshot_is_flat_sorted_and_keeps_every_individual_instance() {
let tree = Tree::new("flat");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf zed (), alpha ();\nendmodule\n");
tree.write("tb.sv", "module TB; top dut (); missing u_missing (); endmodule\n");
let value = taken(&tree.workspace());
assert_eq!(value["schemaVersion"], 2);
assert_eq!(value["revision"], 7);
assert_eq!(value["complete"], true);
let modules = value["modules"].as_array().expect("modules");
let names: Vec<&str> =
modules.iter().map(|module| module["moduleName"].as_str().expect("name")).collect();
assert_eq!(names, ["leaf", "TB", "top"], "case-insensitive alphabetical order");
let top = module(modules, "top");
// `[startLine, startCharacter, endLine, endCharacter]`: the whole
// module for `range`, its name alone for `selectionRange`.
assert_eq!(top["definition"]["range"], json!([0, 0, 2, 9]));
assert_eq!(top["definition"]["selectionRange"], json!([0, 7, 0, 10]));
let instances = top["instances"].as_array().expect("instances");
let names: Vec<&str> = instances
.iter()
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
assert_eq!(names, ["alpha", "zed"], "one statement became two sorted children");
let tb = module(modules, "TB");
let missing = tb["instances"]
.as_array()
.expect("instances")
.iter()
.find(|instance| instance["instanceName"] == "u_missing")
.expect("unresolved instance is still a row");
// Nothing on the wire says "unresolved": the client asks its own module
// table for `missing`, finds none, and that is the same answer.
assert_eq!(missing["moduleName"], "missing");
assert_eq!(missing["site"]["selectionRange"][0], 0);
}
/// An interface is an instantiable unit, so it is a row of the sidebar
/// and an interface instance is an ordinary child — exactly as both were
/// when an interface was indexed as a `SymbolKind::Module`
/// (`docs/features/interface-semantics/README.md`). The wire shape is
/// unchanged: schema 2, the same fields, one more module row.
#[test]
fn an_interface_is_a_row_and_its_instance_a_child_like_any_other() {
let tree = Tree::new("iface");
tree.write("bus_if.sv", "interface bus_if;\nendinterface\n");
tree.write("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n");
let value = taken(&tree.workspace());
assert_eq!(value["schemaVersion"], 2);
let modules = value["modules"].as_array().expect("modules");
let names: Vec<&str> =
modules.iter().map(|module| module["moduleName"].as_str().expect("name")).collect();
assert_eq!(names, ["bus_if", "top"]);
let instances = module(modules, "top")["instances"].as_array().expect("instances");
assert_eq!(instances.len(), 1);
assert_eq!(instances[0]["instanceName"], "u_bus");
assert_eq!(instances[0]["moduleName"], "bus_if");
}
/// The round's central claim, pinned the way `hover-line-index` pinned its
/// own: delete every source file after indexing, and the answer is
/// byte-identical, because no part of it comes from a file.
#[test]
fn a_snapshot_reads_no_files_at_all() {
let tree = Tree::new("noreads");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf u_leaf ();\nendmodule\n");
let workspace = tree.workspace();
let before = taken(&workspace);
assert_eq!(
before["modules"].as_array().expect("modules").len(),
2,
"premise: both indexed"
);
for name in ["leaf.sv", "top.sv"] {
std::fs::remove_file(tree.0.join(name)).expect("delete");
}
assert_eq!(taken(&workspace), before, "the snapshot came from the index, not the disk");
}
/// A URI appears once however many rows name it, and a range is four
/// numbers — the two decisions that took the opentitan answer from 11.6 MB
/// to under 2 MB.
#[test]
fn every_file_is_named_once_and_a_range_is_four_numbers() {
let tree = Tree::new("filetable");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf a (), b (), c ();\nendmodule\n");
let value = taken(&tree.workspace());
let files = value["files"].as_array().expect("files");
assert_eq!(files.len(), 2, "one entry per file, not one per row: {files:#?}");
let text = serde_json::to_string(&value).expect("serializes");
for uri in files {
let uri = uri.as_str().expect("a uri string");
assert_eq!(text.matches(uri).count(), 1, "{uri} is written more than once");
}
let top = module(value["modules"].as_array().expect("modules"), "top");
for instance in top["instances"].as_array().expect("instances") {
assert!(instance["site"]["file"].is_number(), "a file index, not a URI");
assert_eq!(instance["site"]["range"].as_array().expect("range").len(), 4);
}
}
/// Positions are the client's, not the index's: 0-based lines and UTF-16
/// code units, so a two-byte character before a name still counts one.
#[test]
fn positions_are_zero_based_utf16_even_through_multibyte_text() {
let tree = Tree::new("utf16");
// `🎉` is four UTF-8 bytes and two UTF-16 units, so every column after
// it on that line differs from the byte column the index records.
tree.write("m.sv", "module top;\n /*\u{1F389}*/ sub u_x ();\nendmodule\n");
let value = taken(&tree.workspace());
let top = module(value["modules"].as_array().expect("modules"), "top");
assert_eq!(
top["definition"]["selectionRange"],
json!([0, 7, 0, 10]),
"line 0 counting from 0, `top` at character 7"
);
let instance = &top["instances"].as_array().expect("instances")[0];
assert_eq!(instance["instanceName"], "u_x");
assert_eq!(instance["site"]["selectionRange"], json!([1, 13, 1, 16]));
assert_eq!(instance["site"]["range"], json!([1, 13, 1, 19]));
}
/// **The one property the whole zero-I/O trick rests on**: a position the
/// index recorded while a file was scanned is the position `convert` would
/// have produced from that file's text on the wire. The two answers come
/// from one function on `LineIndex`, and this is what says so out loud —
/// over the shapes that break naive conversions.
#[test]
fn an_indexed_position_is_the_position_the_wire_converter_would_have_given() {
let sources = [
"module plain;\n sub u ();\nendmodule\n",
// A CRLF file: `\r` is a byte of its line but not of its content.
"module crlf;\r\n sub u_crlf ();\r\nendmodule\r\n",
// Two, three and four byte characters ahead of the names.
"// \u{e9}\u{2713}\u{1F389}\nmodule wide;\n /*\u{1F389}*/ sub u_wide ();\nendmodule\n",
// A name on the last line, with no trailing newline at all.
"module tail;\n sub u_tail ();\nendmodule",
// Two instances in one statement, and an attribute before `module`.
"(* keep *) module many;\n sub a (), b ();\nendmodule\n",
// CRLF and bare LF mixed in one file: the `\r`-stripping rule must
// apply per line, not once for the whole file.
"module mixed;\r\n sub u_a ();\n sub u_b ();\r\nendmodule\n",
// The instance on the very same line as the module header, so the
// name and the instance share a line's worth of UTF-16 columns.
"module oneline; sub u_same ();\nendmodule\n",
];
let tree = Tree::new("agreement");
let mut texts = Vec::new();
for (at, source) in sources.iter().enumerate() {
tree.write(&format!("f{at}.sv"), source);
texts.push((tree.0.join(format!("f{at}.sv")), *source));
}
let workspace = tree.workspace();
let index = workspace.index();
let mut checked = 0usize;
for (path, text) in &texts {
let lines = vlog_parser::LineIndex::new(text);
let positions = crate::convert::Positions::new(text, &lines);
let file = index.file_id(path).expect("the file is indexed");
for (_, def) in index.instantiable_units() {
if def.file != file {
continue;
}
let recorded = def.lines.positions.expect("a unit carries positions");
assert_eq!(range(recorded.name), as_four(positions.range(def.name_span)));
assert_eq!(range(recorded.decl), as_four(positions.range(def.decl_span)));
checked += 1;
}
for (_, edges) in index.instantiations() {
for edge in edges.iter().filter(|edge| edge.file == file) {
for occurrence in &edge.instances {
assert_eq!(
range(occurrence.name_positions),
as_four(positions.range(occurrence.name_span))
);
assert_eq!(
range(occurrence.positions),
as_four(positions.range(occurrence.span))
);
checked += 1;
}
}
}
}
assert!(checked >= 16, "premise: every fixture contributed rows, got {checked}");
}
/// QA (2026-08-29): two files declaring the same module name must each
/// keep their own row, their own instances, and never merge — the wire's
/// only handle on a module is `(file, definition range)`, exactly as an
/// ambiguous type is meant to look on the client.
#[test]
fn duplicate_module_names_across_files_stay_two_distinct_rows() {
let tree = Tree::new("duplicate");
tree.write("a.sv", "module dup;\n sub u_in_a ();\nendmodule\n");
tree.write("b.sv", "module dup;\n sub u_in_b ();\nendmodule\n");
tree.write("sub.sv", "module sub; endmodule\n");
let value = taken(&tree.workspace());
let modules = value["modules"].as_array().expect("modules");
let dups: Vec<&Value> =
modules.iter().filter(|module| module["moduleName"] == "dup").collect();
assert_eq!(dups.len(), 2, "one row per declaration, not one merged row: {dups:#?}");
assert_ne!(
dups[0]["definition"]["file"], dups[1]["definition"]["file"],
"the only thing distinguishing them is which file",
);
let mut instance_names: Vec<&str> = dups
.iter()
.flat_map(|module| module["instances"].as_array().expect("instances"))
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
instance_names.sort_unstable();
assert_eq!(
instance_names,
["u_in_a", "u_in_b"],
"each declaration keeps only the instances its own body writes",
);
}
/// QA (2026-08-29): an escaped Verilog identifier (`\foo$bar `, terminated
/// by whitespace, the space itself not part of the name) is as ordinary a
/// module or instance name as any other — the wire and the position
/// conversion must not choke on the backslash or the trailing space.
#[test]
fn an_escaped_identifier_names_a_module_and_an_instance() {
let tree = Tree::new("escaped");
tree.write(
"m.sv",
"module \\weird$leaf ;\nendmodule\n\
module top;\n \\weird$leaf \\u$inst ();\nendmodule\n",
);
let value = taken(&tree.workspace());
let modules = value["modules"].as_array().expect("modules");
let leaf = module(modules, "\\weird$leaf");
assert_eq!(leaf["instances"].as_array().expect("instances").len(), 0);
let top = module(modules, "top");
let instances = top["instances"].as_array().expect("instances");
assert_eq!(instances.len(), 1);
assert_eq!(instances[0]["instanceName"], "\\u$inst");
assert_eq!(instances[0]["moduleName"], "\\weird$leaf");
}
/// QA (2026-08-29): a module instantiated 100 times in one statement list
/// produces 100 individual, individually sorted instance rows — the
/// flattening the sidebar exists for, at a scale one instance would not
/// exercise.
#[test]
fn one_hundred_instances_of_one_module_are_one_hundred_sorted_rows() {
let tree = Tree::new("manyinstances");
tree.write("leaf.sv", "module leaf; endmodule\n");
let instances: Vec<String> = (0..100).map(|n| format!("u_{n:03} ()", n = n)).collect();
tree.write(
"top.sv",
&format!("module top;\n leaf {};\nendmodule\n", instances.join(", ")),
);
let value = taken(&tree.workspace());
let top = module(value["modules"].as_array().expect("modules"), "top");
let instances = top["instances"].as_array().expect("instances");
assert_eq!(instances.len(), 100, "every one of the 100 instances is its own row");
let names: Vec<&str> = instances
.iter()
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
let mut sorted = names.clone();
sorted.sort_unstable();
assert_eq!(names, sorted, "sorted by instance name, as every module's instances are");
assert!(instances.iter().all(|instance| instance["moduleName"] == "leaf"));
}
fn as_four(range: lsp_types::Range) -> [u32; 4] {
[range.start.line, range.start.character, range.end.line, range.end.character]
}
fn module<'a>(modules: &'a [Value], name: &str) -> &'a Value {
modules
.iter()
.find(|module| module["moduleName"] == name)
.unwrap_or_else(|| panic!("no module {name}: {modules:#?}"))
}
}
+58 -4
View File
@@ -23,10 +23,32 @@ pub const SOURCE: &str = "lucisv";
/// The missing-closer warnings sit between the two: they explain a parse
/// error rather than add an opinion, and they exist at all only when the parse
/// already failed (`pairs::missing_end_diagnostics`).
///
/// `#[cfg(test)]` for the same reason `lint::diagnostics` is: the server
/// always has a workspace and always calls [`all_in`], so this is the door the
/// tests that predate the project-aware pass come in by.
#[cfg(test)]
pub fn all(doc: &Document) -> Vec<Diagnostic> {
all_in(doc, &crate::lint::LintRun::default())
}
/// [`all`] for a lint pass that knows what the project says — the workspace's
/// rule selection and its identifier census
/// (`docs/features/semantic-lints-on/README.md`). The parse and missing-closer
/// halves are unaffected by either; only the lint pass reads `run`.
pub fn all_in(doc: &Document, run: &crate::lint::LintRun) -> Vec<Diagnostic> {
// A buffer on the large-file fast path was never parsed, so there is
// nothing to say about it — and both passes below would read its *text*
// (the lint context builds one, the fence filter scans for them), which is
// the whole-file work the fast path exists to skip. The empty list is not
// a silent no-op either: it is what clears the squiggles a buffer that has
// just grown past the threshold left behind.
if doc.large {
return Vec::new();
}
let mut all = diagnostics(doc);
all.extend(crate::pairs::missing_end_diagnostics(doc));
all.extend(crate::lint::diagnostics(doc));
all.extend(crate::lint::diagnostics_in(doc, run));
all
}
@@ -113,11 +135,12 @@ mod tests {
#[test]
fn one_list_carries_both_sources() {
// A file that parses cleanly and violates a lint rule: the publish is
// one list, and the lint finding is in it as a warning.
// one list, and the lint finding is in it at its rule's own severity
// — `no-tabs` is a style rule, so INFORMATION (§33.0).
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let published = all(ws.document(&uri).expect("open"));
assert_eq!(published.len(), 1);
assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(published[0].severity, Some(DiagnosticSeverity::INFORMATION));
assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into())));
}
@@ -127,12 +150,43 @@ mod tests {
let published = all(ws.document(&uri).expect("open"));
let severities: Vec<_> = published.iter().map(|d| d.severity).collect();
assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::INFORMATION)), "{published:#?}");
assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv")));
// Errors first: a parse error is what the user must fix.
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
}
/// The user-visible contract of header recovery (TODO §32), pinned where
/// the user meets it: a typo in a port list costs **one** diagnostic, and
/// the module around it survives whole — its name, the ports typed before
/// and after the typo, and its body all still in the outline.
///
/// Before this round the same buffer published two errors (the header, and
/// the orphaned `endmodule`), the body re-parsed as file-scope items, and
/// the outline had no module in it at all.
#[test]
fn a_broken_port_list_publishes_one_error_and_keeps_its_module() {
let (ws, uri) = doc_of("module m (input a, , input b);\n wire ok;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 1, "{diags:#?}");
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(diags[0].range.start.line, 0, "the header's own line");
// The missing-closer pass explains a *parse* failure; there is no
// unclosed block here, so it must add nothing.
assert!(crate::pairs::missing_end_diagnostics(doc).is_empty());
let symbols = crate::symbols::document_symbols(doc);
assert_eq!(symbols.len(), 1, "the module is still in the outline");
assert_eq!(symbols[0].name, "m");
let children = symbols[0].children.as_ref().expect("module contents");
let names: Vec<&str> = children.iter().map(|c| c.name.as_str()).collect();
assert!(names.contains(&"a"), "the port before the typo: {names:?}");
assert!(names.contains(&"b"), "the port after it: {names:?}");
assert!(names.contains(&"ok"), "the body: {names:?}");
}
#[test]
fn a_lex_error_gets_a_visible_range() {
// The lexer gives up at end of file, which a trailing newline makes
+466
View File
@@ -0,0 +1,466 @@
//! Extract a selection into a module of its own, on the wire:
//! `textDocument/codeAction` under LSP's own `refactor.extract`, and
//! `workspace/executeCommand` for the editors that have no lightbulb.
//!
//! Protocol only. The edit is `vlog_refactor::extract_module`; this module
//! decides which files that engine is handed, turns its answer into a
//! `WorkspaceEdit`, and turns its refusal into a request error.
//!
//! **The action carries a command, not an edit** — which is what makes it the
//! laziest of the lot rather than merely a lazy one. Extracting needs a *name*
//! for the new module, and LSP has no prompt: a code action can carry an
//! `edit`, a `command`, or both, and only a command can be intercepted by a
//! client that wants to ask the user something first. So the offer is one
//! parse of one buffer (`vlog_refactor::extract_site`) plus a `Command` naming
//! [`EXTRACT_MODULE`] and the default name `M_extracted`; the VS Code
//! extension registers a client-side command of the same name that shows an
//! input box and calls the server's with what the user typed, and every other
//! client runs the command as sent and gets the default. See
//! `docs/features/extract-inline-module/README.md`.
//!
//! **The new file.** A module extracted into a file of its own is a
//! `CreateFile` resource operation, which only a client that advertises
//! `workspace.workspaceEdit.documentChanges` *and* `resourceOperations`
//! containing `create` can apply. That capability is read at `initialize`
//! ([`crate::server::ClientAbilities::create_files`]) and is the whole of the
//! choice between the two homes: a client that can create files gets `N.sv`
//! beside `M`'s file, and every other client gets `N` written below `M` in the
//! file it came from. The engine says which happened in its warnings.
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
#![allow(clippy::mutable_key_type)]
use lsp_types::{
CodeAction, CodeActionKind, CodeActionOrCommand, Command, CreateFile, DocumentChangeOperation,
DocumentChanges, OneOf, OptionalVersionedTextDocumentIdentifier, Range, ResourceOp,
TextDocumentEdit, TextEdit, Uri, WorkspaceEdit,
};
use serde_json::Value;
use vlog_parser::LineIndex;
use vlog_refactor::{Home, RefactorEdit};
use crate::convert::Positions;
use crate::state::{Document, Workspace};
use crate::uri::path_to_uri;
/// Extract a selection into a module: `[uri, range, name]`.
pub const EXTRACT_MODULE: &str = "lucisv.extractModule";
/// Every command this module executes.
pub fn commands() -> Vec<String> {
vec![EXTRACT_MODULE.to_string()]
}
/// The kind LSP reserves for an extraction, which is what an editor's
/// "Refactor…" menu asks for by name.
pub fn kind() -> CodeActionKind {
CodeActionKind::REFACTOR_EXTRACT
}
/// The action for a selection, carrying the command that will ask for a name.
///
/// One parse of the buffer and nothing else: the engine's cheap gate answers
/// "there is nothing here" for almost every selection, and where it does find
/// something the offer is a `Command`, so no workspace is read until the user
/// has picked the action *and* named the module.
/// Whether `[start, end)` is a selection lucisv could extract, asked of the
/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b).
///
/// A buffer on the large-file fast path keeps the text form, whose parse is of
/// the real bytes rather than of the empty analysis that path installs — see
/// `ports::modules_at` and `docs/features/perf5-p1/README.md`.
fn site_at(doc: &Document, start: u32, end: u32) -> Option<vlog_refactor::ExtractSite> {
match doc.large {
true => vlog_refactor::extract_site(&doc.text, start, end),
false => vlog_refactor::extract_site_in(&doc.tree, &doc.diagnostics, &doc.text, start, end),
}
}
pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOrCommand> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
if doc.path.is_none() {
// An `untitled:` buffer has no directory to put `N.sv` beside and no
// path for the engine's file set; nothing is offered rather than
// offered and refused.
return Vec::new();
}
let positions = doc.positions();
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
let Some(site) = site_at(doc, start, end) else { return Vec::new() };
let arguments = vec![
serde_json::to_value(uri).unwrap_or(Value::Null),
serde_json::to_value(range).unwrap_or(Value::Null),
Value::String(site.default_name.clone()),
];
let title = vlog_refactor::extract_title();
vec![CodeActionOrCommand::CodeAction(CodeAction {
title: title.clone(),
kind: Some(kind()),
command: Some(Command {
title,
command: EXTRACT_MODULE.to_string(),
arguments: Some(arguments),
}),
..Default::default()
})]
}
/// Run `lucisv.extractModule`, or say why it cannot run.
pub fn execute(
ws: &Workspace,
arguments: &[Value],
create_files: bool,
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let uri: Uri = argument(arguments, 0, "a document URI")?;
let range: Range = argument(arguments, 1, "a range")?;
let name: String = argument(arguments, 2, "a name for the new module")?;
let doc = ws
.document(&uri)
.ok_or_else(|| "lucisv can only extract from an open file.".to_string())?;
let path = doc
.path
.clone()
.ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?;
let positions = doc.positions();
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
let Some(site) = site_at(doc, start, end) else {
return Err(NOTHING.to_string());
};
// The engine looks up every module the selection instantiates and every
// package it imports, so the file set is those units' own fan-out — plus
// the new name's, so a workspace that already declares it is a workspace
// the engine can refuse over.
let mut units = site.units;
units.push(name.clone());
let files = ws.module_sources(&path, &units);
let home = match create_files {
true => Home::NewFile,
false => Home::SameFile,
};
// No preflight here, and the take 5 review round (§61.1) is why: every
// refusal one could take is already taken before a scope is built. The
// `site_at` gate above **is** `extract_site_in`, which returns `None` on a
// parse diagnostic and on every `Region::read` refusal, so neither can
// reach the engine; and `extract_module` checks the new name and the
// occupied target as its own first two statements, ahead of
// `Extraction::plan`. The 805 ms at `aes_wrap.sv` is none of those — it is
// `boundary::Crossing::read`, which needs the instantiated modules' port
// directions and so needs the scope. See
// `docs/features/perf5r-preflight/README.md`.
let refactoring = vlog_refactor::extract_module(&files, &path, start, end, &name, home)?;
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
}
/// A whole extraction as a `WorkspaceEdit`.
///
/// `documentChanges` rather than `changes` whenever a file is created: a
/// creation is a resource operation, and the two shapes cannot be mixed in one
/// edit. An extraction that creates nothing goes through the ordinary
/// `changes` map, which every client understands.
pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result<WorkspaceEdit, String> {
if refactoring.created.is_empty() {
return crate::ports::workspace_edit(ws, refactoring);
}
let mut operations: Vec<DocumentChangeOperation> = Vec::new();
for path in &refactoring.created {
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
operations.push(DocumentChangeOperation::Op(ResourceOp::Create(CreateFile {
uri,
options: None,
annotation_id: None,
})));
}
for (path, edits) in &refactoring.edits {
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
// A file the edit creates has no text yet, and the one insertion into
// it is at 0:0 — which is what `Positions` over an empty text says.
let created = refactoring.created.iter().any(|created| created == path);
let text = match created {
true => String::new(),
false => ws.text_of(path).ok_or_else(|| unaddressable(path))?,
};
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
operations.push(DocumentChangeOperation::Edit(TextDocumentEdit {
text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
edits: edits
.iter()
.map(|edit| {
OneOf::Left(TextEdit {
range: positions.range(edit.range),
new_text: edit.new_text.clone(),
})
})
.collect(),
}));
}
Ok(WorkspaceEdit {
document_changes: Some(DocumentChanges::Operations(operations)),
..Default::default()
})
}
fn argument<T: serde::de::DeserializeOwned>(
arguments: &[Value],
n: usize,
what: &str,
) -> Result<T, String> {
arguments
.get(n)
.and_then(|value| serde_json::from_value(value.clone()).ok())
.ok_or_else(|| format!("{EXTRACT_MODULE} wants {what} as argument {}.", n + 1))
}
fn unaddressable(path: &std::path::Path) -> String {
format!("lucisv could not address {} as a document; no edits were made.", path.display())
}
const NOTHING: &str = "there is nothing to extract at this selection.";
#[cfg(test)]
mod tests {
use super::*;
use crate::uri::path_to_uri;
use lsp_types::Position;
use std::fs;
use std::path::PathBuf;
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_server_extract_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
const TOP: &str = "\
module top (
input logic [7:0] a,
input logic [7:0] b,
output logic [7:0] q
);
logic [7:0] s;
assign s = a + b;
assign q = s;
endmodule
";
fn opened(tree: &Tree) -> (Workspace, Uri) {
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
(ws, uri)
}
/// The range of `assign s = a + b;`, as the client speaks it.
fn selection() -> Range {
Range {
start: Position { line: 6, character: 2 },
end: Position { line: 6, character: 19 },
}
}
fn only(actions: Vec<CodeActionOrCommand>) -> Vec<CodeAction> {
actions
.into_iter()
.filter_map(|a| match a {
CodeActionOrCommand::CodeAction(action) => Some(action),
CodeActionOrCommand::Command(_) => None,
})
.collect()
}
#[test]
fn a_selection_of_whole_items_is_offered_the_action_with_a_command_and_a_default_name() {
let tree = Tree::new("offer");
let (ws, uri) = opened(&tree);
let actions = only(code_actions(&ws, &uri, selection()));
let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") };
assert_eq!(action.title, "lucisv: extract selection into module…");
assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_EXTRACT));
assert!(action.edit.is_none(), "the offer reads no workspace");
let command = action.command.as_ref().expect("a command");
assert_eq!(command.command, EXTRACT_MODULE);
let arguments = command.arguments.as_ref().expect("arguments");
assert_eq!(arguments.len(), 3);
assert_eq!(arguments[2], Value::String("top_extracted".to_string()));
}
#[test]
fn a_selection_that_covers_no_whole_item_is_offered_nothing() {
let tree = Tree::new("nothing");
let (ws, uri) = opened(&tree);
let half = Range {
start: Position { line: 6, character: 2 },
end: Position { line: 6, character: 8 },
};
assert!(code_actions(&ws, &uri, half).is_empty());
}
#[test]
fn the_command_creates_the_new_file_for_a_client_that_can() {
let tree = Tree::new("create");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(selection()).expect("range"),
Value::String("sum".to_string()),
];
let (edit, warnings) = execute(&ws, &arguments, true).expect("extracts");
assert!(warnings.iter().any(|w| w.contains("sum.sv")), "{warnings:?}");
let Some(DocumentChanges::Operations(ops)) = edit.document_changes else {
panic!("a creating edit speaks documentChanges: {edit:?}")
};
let creates = ops
.iter()
.filter(|op| matches!(op, DocumentChangeOperation::Op(ResourceOp::Create(_))))
.count();
assert_eq!(creates, 1, "one file is created: {ops:?}");
assert_eq!(ops.len(), 3, "the creation plus one edit per file: {ops:?}");
}
#[test]
fn the_command_writes_the_module_into_the_same_file_for_a_client_that_cannot() {
let tree = Tree::new("same");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(selection()).expect("range"),
Value::String("sum".to_string()),
];
let (edit, warnings) = execute(&ws, &arguments, false).expect("extracts");
assert!(
warnings.iter().any(|w| w.contains("did not say it can create files")),
"{warnings:?}"
);
assert!(edit.document_changes.is_none(), "no resource operation is needed");
let changes = edit.changes.as_ref().expect("changes");
assert_eq!(changes.len(), 1, "one file is touched");
assert_eq!(changes.get(&uri).expect("this file").len(), 2);
}
#[test]
fn the_command_says_why_when_there_is_nothing_to_extract() {
let tree = Tree::new("refuse");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Range {
start: Position { line: 0, character: 0 },
end: Position { line: 0, character: 3 },
})
.expect("range"),
Value::String("sum".to_string()),
];
assert_eq!(execute(&ws, &arguments, true), Err(NOTHING.to_string()));
}
#[test]
fn the_command_wants_all_three_of_its_arguments() {
let tree = Tree::new("arguments");
let (ws, uri) = opened(&tree);
let short = vec![serde_json::to_value(&uri).expect("uri")];
let message = execute(&ws, &short, true).expect_err("a refusal");
assert!(message.contains("argument 2"), "{message}");
}
#[test]
fn a_client_asking_only_for_refactor_extract_is_answered() {
let filter = [CodeActionKind::REFACTOR_EXTRACT];
assert!(crate::code_action::wanted(Some(&filter), &kind()));
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
}
// ------------------------------------------------------------------
// Where the extract refusals are actually taken (take 5 review §3 item 5,
// TODO §61.1). No preflight was added — every refusal below is already
// reached before a scope exists, and these pin that it stays so.
// ------------------------------------------------------------------
fn run(
ws: &Workspace,
uri: &Uri,
range: Range,
name: &str,
create: bool,
) -> Result<(), String> {
let arguments = vec![
serde_json::to_value(uri).expect("uri"),
serde_json::to_value(range).expect("range"),
Value::String(name.to_string()),
];
execute(ws, &arguments, create).map(|_| ())
}
/// A bad new name is refused by `extract_module`'s own first statement,
/// and a selection covering no whole item is refused by the `site_at` gate
/// — neither reaches `Extraction::plan`, so neither builds a scope.
#[test]
fn the_cheap_refusals_reach_the_wire_in_the_engines_words() {
let tree = Tree::new("preflightrefusals");
let (ws, uri) = opened(&tree);
let bad = run(&ws, &uri, selection(), "1bad", true).expect_err("a bad name");
assert!(bad.contains("plain SystemVerilog identifier"), "{bad}");
// Half of `assign s = a + b;`, which covers no whole item.
let partial = Range {
start: Position { line: 6, character: 6 },
end: Position { line: 6, character: 19 },
};
assert_eq!(
run(&ws, &uri, partial, "sum", true),
Err(NOTHING.to_string()),
"the `site_at` gate answers a partial selection before the engine is asked"
);
}
/// A file already sitting where the new module would go is refused before
/// `Extraction::plan`, and the question is asked of the source set the
/// engine was handed rather than of the disk behind its back.
#[test]
fn an_occupied_target_is_refused_with_the_engines_sentence() {
let tree = Tree::new("preflightoccupied");
tree.write("sum.sv", "module sum;\nendmodule\n");
let (ws, uri) = opened(&tree);
let refusal = run(&ws, &uri, selection(), "sum", true).expect_err("occupied");
assert!(refusal.contains("there is already a"), "{refusal}");
assert!(refusal.contains("sum.sv"), "and it names the file: {refusal}");
// Into the same file nothing is occupied, so the early check passes
// and the engine refuses for its own, later reason: the workspace
// already declares that name — an index question, answered by the
// stage that owns the index.
let deferred = run(&ws, &uri, selection(), "sum", false).expect_err("already declared");
assert!(deferred.contains("the workspace already declares"), "{deferred}");
}
/// The control: a whole, movable item still extracts.
#[test]
fn a_whole_movable_selection_still_extracts() {
let tree = Tree::new("preflightok");
let (ws, uri) = opened(&tree);
assert!(run(&ws, &uri, selection(), "sum", true).is_ok());
}
}
+40
View File
@@ -0,0 +1,40 @@
//! The fenced regions of an open buffer, asked once per document revision.
//!
//! `vlog_formatter::fence::protected_regions` takes **text** and parses it
//! itself, on purpose: one fence answer for every front end, and none of them
//! able to feed it a stale tree. That contract
//! (`docs/features/shared-fence-filter/README.md`) is not amended here, and
//! `fence.rs` is not touched — the call is still
//! `protected_regions(&doc.text)`, byte for byte the same question.
//!
//! What this module adds is that the answer is computed **once** for a given
//! buffer instead of once per `textDocument/codeAction`. That is safe for one
//! structural reason: a `Document` is built whole by
//! `Workspace::set_document` and thrown away by it, so the text a `Document`
//! holds cannot change without a new `Document` — and `answer_request`
//! flushes every pending change before a handler runs. There is no revision
//! number to compare because there is no way to be looking at the wrong one.
//!
//! A 42 192-line generated buffer is where this is worth having: the fence
//! parse alone measured ~59 ms of that file's code-action cost (take 5 §P1,
//! `docs/features/perf5-p1/README.md`).
use vlog_formatter::fence::{self, Region};
use crate::state::Document;
/// The regions of `doc` no tool may edit automatically.
///
/// Computed on first use and kept for the life of this `Document`. The
/// caller borrows the answer rather than a copy of it, so asking twice costs
/// a pointer.
pub fn of(doc: &Document) -> &[Region] {
doc.fences.get_or_init(|| fence::protected_regions(&doc.text))
}
/// Whether the answer is already in hand — asked *before* [`of`], so a
/// `--verbose` trace can say whether this request paid the parse or read the
/// memo (review round §R1b, `crate::lint_trace`). Decides nothing.
pub fn held(doc: &Document) -> bool {
doc.fences.get().is_some()
}
File diff suppressed because it is too large. Load diff
+251 -21
View File
@@ -1,15 +1,16 @@
//! `textDocument/formatting` and `textDocument/rangeFormatting`.
//! `textDocument/formatting`, `textDocument/rangeFormatting` and
//! `textDocument/rangesFormatting`.
//!
//! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and
//! these handlers keep it: either one whole-document edit built from verified
//! output, or no edit at all and an error for the user to read. That holds for
//! the range request too — its output is verified over the whole buffer, and
//! what makes it a *range* format is which constructs it laid out, not which
//! bytes it was allowed to replace.
//! the range requests too — their output is verified over the whole buffer,
//! and what makes a request a *range* format is which constructs it laid out,
//! not which bytes it was allowed to replace.
use std::path::Path;
use lsp_types::{FormattingOptions, Range, TextEdit};
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
@@ -88,29 +89,57 @@ pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, S
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
}
/// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request.
///
/// Spelled out here because `lsp-types` 0.97 predates it — the same reason
/// `pairs::ScopePairsParams` is hand-rolled. See
/// `docs/features/lsp-318-extras/README.md`.
pub const RANGES_FORMATTING: &str = "textDocument/rangesFormatting";
/// `textDocument/rangesFormatting` params: one document, `n` ranges, one set
/// of options.
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RangesFormattingParams {
pub text_document: TextDocumentIdentifier,
pub ranges: Vec<Range>,
pub options: FormattingOptions,
}
/// Format the constructs a selection reaches, and nothing else.
///
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
/// wants 1-based inclusive *lines*, so only the line numbers survive the
/// conversion. An end position at character 0 still names its line — an
/// editor's "select these three lines" ends at the start of the fourth — so
/// a range that stops at a line's very beginning does not drag that line in
/// unless it is also where the range started.
///
/// The reply is still one whole-document edit: the engine's contract is
/// all-or-nothing over the file, and a partial run's output differs from the
/// buffer only where it decided to differ.
/// The one-range case of [`ranges_formatting`], which is where the whole
/// answer lives — an `n`-range request is this request with `n` line spans.
pub fn range_formatting(
doc: &Document,
config: &Config,
range: Range,
) -> Result<Option<TextEdit>, String> {
let first = range.start.line.saturating_add(1);
// An end at character 0 of a later line is the start of that line, not
// any of its content.
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
let last = if ends_before_its_line { range.end.line } else { range.end.line + 1 };
let lines = LineRanges::new([(first, last.max(first))])?;
ranges_formatting(doc, config, std::slice::from_ref(&range))
}
/// Format the constructs any of several selections reach, and nothing else.
///
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
/// before the engine sees them, so overlapping, adjacent, repeated and
/// unsorted input from the client all reach the same answer. No range is
/// formatted on its own — one `format_range` call lays out the union, which is
/// what keeps the all-or-nothing contract (CLAUDE.md invariant #1) whole
/// rather than making it a promise per range.
///
/// The reply is still one whole-document edit: the engine's contract is
/// all-or-nothing over the file, and a partial run's output differs from the
/// buffer only where it decided to differ. An empty range list is not an
/// error — it is an ask for nothing, answered with no edit.
pub fn ranges_formatting(
doc: &Document,
config: &Config,
ranges: &[Range],
) -> Result<Option<TextEdit>, String> {
if ranges.is_empty() {
return Ok(None);
}
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
if formatted == doc.text {
return Ok(None);
@@ -118,6 +147,27 @@ pub fn range_formatting(
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
}
/// The 1-based inclusive line span an LSP range names.
///
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
/// wants lines, so only the line numbers survive the conversion — which
/// sidesteps the UTF-16 column question rather than solving it again. An end
/// position at character 0 still names its line — an editor's "select these
/// three lines" ends at the start of the fourth — so a range that stops at a
/// line's very beginning does not drag that line in unless it is also where
/// the range started.
///
/// One conversion, shared by both range requests: a second spelling of this
/// rule would be a second thing to get wrong.
fn lines_of(range: Range) -> (u32, u32) {
let first = range.start.line.saturating_add(1);
// An end at character 0 of a later line is the start of that line, not
// any of its content.
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
let last = if ends_before_its_line { range.end.line } else { range.end.line.saturating_add(1) };
(first, last.max(first))
}
/// The indent width governing a buffer, for a lint fix that has to write
/// spaces where a tab was.
///
@@ -174,6 +224,14 @@ fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingO
if let Some(line_length) = file.line_length {
config.max_width = line_length;
}
// The `[format]` keys follow the same ladder: the editor's own setting
// first, then `lucisv.toml`, which outranks it.
if let Some(on) = client.uvm_utils_indent {
config.uvm_utils_indent = on;
}
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config
}
@@ -458,6 +516,39 @@ mod tests {
assert_eq!(settings.config.max_width, Config::default().max_width);
}
/// The `[format]` keys climb the same ladder — with no rung 3, since the
/// protocol has no option for them: `lucisv.toml` > `lucisv.format.*` >
/// the built-in default, which is off (TODO §54.3).
#[test]
fn a_format_key_climbs_the_ladder_from_off() {
let uvm = |on: Option<bool>| ClientSettings { uvm_utils_indent: on, ..Default::default() };
// Rung 4: nobody asked, so the key never fires.
let (ws, uri) = document("module m;\nendmodule\n");
assert!(!settings_with(&ws, &uri, &none(), &options(2, true)).config.uvm_utils_indent);
// Rung 2: the editor setting is the only thing that spoke.
assert!(
settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent
);
// Rung 1: `lucisv.toml` outranks the editor, in both directions.
let on = Tree::new("[format]\nuvm-utils-indent = true\n");
let (ws, uri) = on.document("module m;\nendmodule\n");
let settings = settings_with(&ws, &uri, &uvm(Some(false)), &options(2, true));
assert_eq!(settings.problem, None);
assert!(settings.config.uvm_utils_indent, "lucisv.toml wins");
let off = Tree::new("[format]\nuvm-utils-indent = false\n");
let (ws, uri) = off.document("module m;\nendmodule\n");
assert!(
!settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent
);
// A config that names other keys is silent about this one, so the
// editor setting still answers for it.
let other = Tree::new("indent = 4\n");
let (ws, uri) = other.document("module m;\nendmodule\n");
let settings = settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true));
assert_eq!(settings.config.indent_width, 4);
assert!(settings.config.uvm_utils_indent);
}
#[test]
fn each_key_climbs_the_ladder_independently() {
// A `lucisv.toml` naming only `indent` must not also claim the width:
@@ -625,6 +716,145 @@ mod tests {
assert!(!message.is_empty(), "the user needs something to read");
}
// ------------------------------------------------------------------
// `rangesFormatting` — the union of the ranges, on the one engine
// ------------------------------------------------------------------
/// Four items, one per line, so two disjoint ranges can reach two of them
/// and leave the ones between untouched.
const FOUR: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
fn multi(text: &str, ranges: &[Range]) -> Result<Option<TextEdit>, String> {
let (ws, uri) = document(text);
let doc = ws.document(&uri).expect("open");
ranges_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, ranges)
}
/// The `new_text` a multi-range request answers with, or `None`.
fn multi_text(text: &str, ranges: &[Range]) -> Option<String> {
multi(text, ranges).expect("formats").map(|edit| edit.new_text)
}
#[test]
fn two_ranges_lay_out_both_the_items_they_reach_and_nothing_between() {
// Lines 2 and 4 selected, line 3 not: `b` keeps its bytes.
let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed");
assert_eq!(both, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
}
#[test]
fn a_multi_range_answer_is_the_union_of_the_single_range_answers() {
// The contract, stated as an equality rather than as a re-spelled
// expectation: where two ranges do not interact, asking for both at
// once is asking for each and taking both results. Line 2 formatted
// alone, then line 4 formatted on *that* text, must be byte-identical
// to one request naming both.
let first = ranged(FOUR, at(1, 0, 1, 11)).expect("formats").expect("changed").new_text;
let second = ranged(&first, at(3, 0, 3, 11)).expect("formats").expect("changed").new_text;
let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed");
assert_eq!(both, second);
}
#[test]
fn ranges_arrive_unsorted_overlapping_adjacent_or_twice_and_mean_the_same_thing() {
// `LineRanges::new` sorts and merges, and this asserts it through the
// answer rather than restating the arithmetic. All four spellings name
// lines 2 and 3.
let want = multi_text(FOUR, &[at(1, 0, 2, 11)]).expect("changed");
assert_eq!(want, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
for (spelling, ranges) in [
("unsorted", vec![at(2, 0, 2, 11), at(1, 0, 1, 11)]),
("overlapping", vec![at(1, 0, 2, 4), at(2, 0, 2, 11)]),
("adjacent", vec![at(1, 0, 1, 11), at(2, 0, 2, 11)]),
("the same range twice", vec![at(1, 0, 2, 11), at(1, 0, 2, 11)]),
] {
assert_eq!(multi_text(FOUR, &ranges).as_deref(), Some(want.as_str()), "{spelling}");
}
}
#[test]
fn an_empty_range_list_is_an_ask_for_nothing_and_not_an_error() {
// A client with no selections must not get a popup. `LineRanges::new`
// refuses an empty list — that refusal is the CLI's (`--lines ''` is a
// typo), and it is answered before the engine here.
assert_eq!(multi(FOUR, &[]).expect("never an error"), None);
}
#[test]
fn one_range_over_the_whole_buffer_is_the_whole_file_format() {
let whole = multi_text(FOUR, &[at(0, 0, 99, 0)]).expect("changed");
assert_eq!(whole, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
// And so is every line named separately, which is the same union.
let each: Vec<Range> = (0..5).map(|line| at(line, 0, line, 11)).collect();
assert_eq!(multi_text(FOUR, &each).as_deref(), Some(whole.as_str()));
}
#[test]
fn a_one_element_multi_range_request_is_the_single_range_request() {
// `range_formatting` is *defined* as this call, so the two can never
// drift — but the equality is what a client relies on, so it is
// asserted rather than argued.
for range in [at(1, 4, 1, 4), at(1, 0, 3, 0), at(3, 0, 3, 9), at(0, 0, 99, 0)] {
assert_eq!(ranged(THREE, range), multi(THREE, &[range]), "{range:?}");
}
}
#[test]
fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() {
// No partial output on either path (CLAUDE.md invariant #1), and the
// same message: both are one `format_range` call away from the engine.
let broken = "module m;\n wire ;\nendmodule\n";
let one = ranged(broken, at(0, 0, 0, 9));
let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]);
assert!(one.is_err() && many.is_err(), "a broken buffer is refused both ways");
assert_eq!(one, many, "byte-identical refusals, message included");
}
#[test]
fn a_multi_range_format_is_a_fixed_point_under_the_same_ranges() {
// Idempotency through the new path: format lines 2 and 4, then ask for
// exactly the same two ranges on the answer — nothing left to do.
let ranges = [at(1, 0, 1, 11), at(3, 0, 3, 11)];
let once = multi_text(FOUR, &ranges).expect("changed");
assert_eq!(multi_text(&once, &ranges), None, "the second run has nothing to say");
}
#[test]
fn a_multi_range_request_over_already_formatted_lines_produces_no_edit() {
let clean = "module m;\n wire a;\n wire b;\nendmodule\n";
assert_eq!(multi(clean, &[at(0, 0, 0, 9), at(1, 0, 1, 9)]).expect("formats"), None);
}
#[test]
fn multi_byte_content_survives_a_multi_range_format_too() {
// The columns are UTF-16 units and only the lines reach the engine, so
// an emoji two lines up must not shift which items are laid out.
let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n";
let out = multi_text(text, &[at(2, 0, 2, 11), at(3, 0, 3, 11)]).expect("changed");
assert_eq!(out, "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n");
assert!(out.contains("é ✓ 🎉"), "comments are never dropped");
}
#[test]
fn the_line_conversion_is_the_one_rangeformatting_always_used() {
// Pinned directly, because both requests now share it: a cursor names
// its own line; an end at character 0 of a *later* line stops one line
// short; an end at character 0 on the start line does not.
assert_eq!(lines_of(at(1, 4, 1, 4)), (2, 2), "a cursor");
assert_eq!(lines_of(at(1, 0, 3, 0)), (2, 3), "select two lines");
assert_eq!(lines_of(at(2, 0, 3, 0)), (3, 3), "select one line");
assert_eq!(lines_of(at(2, 0, 2, 0)), (3, 3), "an empty range on its own line");
assert_eq!(lines_of(at(0, 0, 99, 0)), (1, 99), "past the end of the buffer");
// And it never produces a span `LineRanges` would refuse: line 0 is
// impossible (1-based), and `last` can never fall below `first`.
assert_eq!(lines_of(at(0, 0, 0, 0)), (1, 1), "the very first line");
assert_eq!(
lines_of(at(u32::MAX, 0, u32::MAX, 0)),
(u32::MAX, u32::MAX),
"a saturating add, not an overflow"
);
}
#[test]
fn multi_byte_content_survives_formatting() {
let (ws, uri) = document("module m;\n// é ✓ 🎉\nwire a;\nendmodule\n");
+136 -66
View File
@@ -22,10 +22,11 @@ use lsp_types::{
};
use vlog_parser::ast::Item;
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
use vlog_semantic::SymbolKind as SemanticKind;
use vlog_semantic::instantiations::{self, Decl};
use vlog_semantic::{DeclSite, InstantiationEdge};
use crate::convert::Positions;
use crate::instantiations::{self, Decl};
use crate::state::Workspace;
use crate::uri::{path_to_uri, uri_to_path};
@@ -60,27 +61,67 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
/// Who instantiates this module: one call per **instantiating module**, with
/// every instantiation site inside it.
///
/// Every in-scope file is walked, because the workspace index records what a
/// file *declares* and not what it instantiates — there is no edge table to
/// consult. A file whose text does not contain the name at all is skipped
/// before it is parsed, which is what keeps the walk affordable: an
/// instantiation of `fifo` has to write `fifo`.
/// One name asked of the batch below, which is the only census in this server
/// — the code lens counts what this lists.
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
// Nothing this server hands out is nameless, so an empty name is a
// malformed item — and the prefilter below matches every file for it,
// which would read and parse the whole workspace to find nothing.
if item.name.is_empty() {
return Vec::new();
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
}
/// Who instantiates each of `names`, answered one list per name in the order
/// asked.
///
/// **A lookup in the workspace index's instantiation-edge table** since
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
/// file. The census is unchanged — the table is built by the same
/// [`instantiations::sites`] walk this function used to run, at index time
/// (`docs/features/incremental-index/README.md`) — and so is the answer's
/// shape and order. What changed is the cost: only the files that really do
/// instantiate one of the names are read, to turn the recorded byte spans into
/// the protocol's line/character ranges.
///
/// The **batch** stays the primitive: `lens.rs` asks about every module
/// declared in a buffer at once, and one file that instantiates three of them
/// is read once for the batch rather than once per name.
///
/// An empty name is answered with nothing rather than looked up: nothing this
/// server hands out is nameless, and a nameless question has no answer.
pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyIncomingCall>> {
let index = ws.index();
let mut answers: Vec<Vec<CallHierarchyIncomingCall>> =
names.iter().map(|_| Vec::new()).collect();
// Every file holding an edge for any of the names, once, in path order.
let mut files: Vec<vlog_semantic::FileId> = names
.iter()
.filter(|name| !name.is_empty())
.flat_map(|name| index.instantiations_of(name).iter().map(|edge| edge.file))
.collect();
files.sort();
files.dedup();
for file in files {
let Some(path) = index.path(file) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
// The spans were recorded against the text the index was built from;
// this is the text now. The two differ only for a buffer edited since
// the last rebuild, which is the same staleness `item_in_file` has
// always carried.
let Some(text) = ws.text_of(path) else { continue };
let line_index = LineIndex::new(&text);
let positions = Positions::new(&text, &line_index);
for (at, name) in names.iter().enumerate() {
if name.is_empty() {
continue;
}
let edges = index.instantiations_of(name).iter().filter(|edge| edge.file == file);
answers[at].extend(callers_in(&uri, &positions, edges));
}
}
let mut calls: Vec<CallHierarchyIncomingCall> = Vec::new();
for (path, text) in ws.sources() {
calls.extend(callers_in(&path, &text, &item.name));
for answer in &mut answers {
answer.sort_by(|a, b| {
(a.from.uri.as_str(), key(a.from.selection_range))
.cmp(&(b.from.uri.as_str(), key(b.from.selection_range)))
});
}
calls.sort_by(|a, b| {
(a.from.uri.as_str(), key(a.from.selection_range))
.cmp(&(b.from.uri.as_str(), key(b.from.selection_range)))
});
calls
answers
}
/// What this module instantiates: one call per **distinct instantiated
@@ -120,37 +161,29 @@ pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOu
.collect()
}
/// Every module in one file that instantiates `name`, with its sites.
fn callers_in(path: &Path, text: &str, name: &str) -> Vec<CallHierarchyIncomingCall> {
// An instantiation of `name` writes `name`. Nearly every file in a
// workspace does not, and this is what keeps those files unparsed.
if !text.contains(name) {
return Vec::new();
}
let Some(uri) = path_to_uri(path) else { return Vec::new() };
let (tree, _) = parse_source_tolerant(text);
let mut callers: Vec<(Decl, Vec<TextRange>)> = Vec::new();
for site in instantiations::sites(&tree.items) {
if site.inst.module != name {
continue;
}
// An instantiation at file scope has no calling module to report.
let Some(owner) = site.owner else { continue };
match callers.iter_mut().find(|(decl, _)| decl.span == owner.span) {
Some((_, spans)) => spans.push(site.inst.module_span),
None => callers.push((owner, vec![site.inst.module_span])),
/// One file's edges for one module, as incoming calls: one call per
/// instantiating module, with every site inside it.
///
/// Sites are grouped by the declaration they sit in rather than by adjacency,
/// because a module written inside another can put its own sites between two
/// of the outer module's.
fn callers_in<'a>(
uri: &Uri,
positions: &Positions,
edges: impl Iterator<Item = &'a InstantiationEdge>,
) -> Vec<CallHierarchyIncomingCall> {
let mut callers: Vec<(&DeclSite, Vec<TextRange>)> = Vec::new();
for edge in edges {
match callers.iter_mut().find(|(owner, _)| owner.span == edge.owner.span) {
Some((_, spans)) => spans.push(edge.site_span),
None => callers.push((&edge.owner, vec![edge.site_span])),
}
}
if callers.is_empty() {
return Vec::new();
}
let line_index = LineIndex::new(text);
let positions = Positions::new(text, &line_index);
callers
.into_iter()
.filter_map(|(decl, spans)| {
.filter_map(|(owner, spans)| {
Some(CallHierarchyIncomingCall {
from: item(uri.clone(), &positions, decl)?,
from: item_of(uri.clone(), positions, &owner.name, owner.name_span, owner.span)?,
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
})
})
@@ -160,20 +193,28 @@ fn callers_in(path: &Path, text: &str, name: &str) -> Vec<CallHierarchyIncomingC
/// The hierarchy item for one module declaration, positioned against the text
/// it was parsed from.
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<CallHierarchyItem> {
let name_span = decl.module.name_span;
item_of(uri, positions, &decl.module.name, decl.module.name_span, decl.span)
}
/// [`item`] from the parts, for a caller reading them out of the index's edge
/// table rather than off a parse tree.
fn item_of(
uri: Uri,
positions: &Positions,
name: &str,
name_span: TextRange,
span: TextRange,
) -> Option<CallHierarchyItem> {
if name_span.is_empty() {
return None;
}
// The protocol requires `selectionRange` inside `range`; a declaration the
// parser could not close is the case where that may not hold, and there
// the name alone is the honest extent.
let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end {
decl.span
} else {
name_span
};
let full =
if span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
Some(CallHierarchyItem {
name: decl.module.name.clone(),
name: name.to_string(),
kind: SymbolKind::MODULE,
tags: None,
detail: None,
@@ -189,7 +230,7 @@ fn declarations_of(ws: &Workspace, name: &str) -> Vec<CallHierarchyItem> {
ws.index()
.units(name)
.iter()
.filter(|def| def.kind == SemanticKind::Module)
.filter(|def| def.kind.is_instantiable())
.filter_map(|def| {
let path = ws.index().path(def.file)?;
item_in_file(ws, path, name, Some(def.name_span))
@@ -309,7 +350,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -365,6 +406,19 @@ endmodule
assert_eq!(items[0].range.end.line, 1, "through `endmodule`");
}
/// An interface is instantiated exactly as a module is, so the call
/// hierarchy still finds its declaration from an instantiation site
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn the_cursor_on_an_interface_instantiation_prepares_the_interface() {
const IFACE: &str = "interface bus_if;\nendinterface\n";
const USER: &str = "module top;\n bus_if u_bus ();\nendmodule\n";
let (_tree, ws, uri) = workspace("ifaceprepare", &[("top.sv", USER), ("bus_if.sv", IFACE)]);
let items = prepare(&ws, &uri, at(USER, "bus_if")).expect("the interface");
assert_eq!(items.len(), 1);
assert_eq!(shape(&items[0]), ("bus_if".to_string(), "bus_if.sv".to_string(), 0));
}
#[test]
fn the_cursor_on_an_instantiation_prepares_the_module_it_names() {
let (_tree, ws, uri) = three("inst");
@@ -501,7 +555,7 @@ endmodule
tree.write("files.f", "sub.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
@@ -510,9 +564,15 @@ endmodule
}
#[test]
fn an_unsaved_instantiation_is_a_caller_before_it_is_saved() {
// The sources a walk reads are the open buffers overlaid on disk, so a
// just-typed instantiation counts.
fn an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it() {
// Superseded this round (incremental-index, 2026-08-27):
// `an_unsaved_instantiation_is_a_caller_before_it_is_saved` pinned the
// census reading `Workspace::sources()` on every request, so a
// keystroke in *another* buffer moved the count before anything
// rebuilt. The census is the index's edge table now, and an index is
// only ever as of its last build or update — which does fold every
// open buffer in, so a save (or any other rescan trigger) makes the
// edit count. The rule the test pins is the new one, from both sides.
let (tree, mut ws, uri) = three("unsaved");
let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone();
assert_eq!(incoming(&ws, &root).len(), 2, "premise");
@@ -520,7 +580,14 @@ endmodule
let fresh = tree.path.join("other.sv");
let other_uri = path_to_uri(&fresh).expect("uri");
ws.set_document(other_uri, "module other;\nendmodule\n".to_string());
assert_eq!(incoming(&ws, &root).len(), 1, "the buffer removed its instantiation");
assert_eq!(
incoming(&ws, &root).len(),
2,
"the buffer alone does not move the census — the index has not seen it"
);
// What a save does, and what the incremental path does with it.
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
assert_eq!(incoming(&ws, &root).len(), 1, "the edit removed its instantiation");
}
// ------------------------------------------------------------------
@@ -909,17 +976,20 @@ endmodule
#[test]
#[ignore]
fn qa_perf_worst_case_common_word_module_name() {
// A single-letter module name is a substring of nearly every file's
// text, so the prefilter admits nearly everything — the worst case
// the prefilter can face. Measures whether that worst case is still
// sane, not a specific number.
// A single-letter module name used to be the worst case there was: it
// is a substring of nearly every file, so the prefilter over
// `Workspace::sources()` admitted nearly everything. There is no
// prefilter and no walk since 2026-08-27 — the census is a lookup in
// the index's edge table, and a name nothing instantiates is an empty
// slice — so this probe is kept for what it now measures: that the
// shape which used to be the worst case is not a case at all.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let item = CallHierarchyItem {
name: "d".to_string(),
kind: SymbolKind::MODULE,
@@ -967,7 +1037,7 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&declaring).expect("uri");
ws.set_document(uri.clone(), text.clone());
let root = prepare(&ws, &uri, at(&text, "module prim_flop_2sync") + 7)
Loaded 100 of 845 files, more files were not shown because too many files have changed in this diff. Show more