Compare commits

...
177 Commits
Author SHA1 Message Date
lucioandClaude Opus 5.5 58520e586e Release 0.60.0: rename and references through generate block labels; rename warnings scoped to the renamed declaration
ci / checks (push) Successful in 1m37s
ci / corpus (push) Successful in 36s
release / build-and-publish (push) Successful in 8m2s
Version bump; the notes are in CHANGELOG.md (## 0.60.0) and
editors/vscode/CHANGELOG.md. TODO §65.1 plus the independent review's
H-1/H-2 and M-1/M-2 fixes. Gates on the tree: fmt and clippy -D warnings
clean, workspace lib/bins/tests 80 suites 5 078 passed 0 failed, node tests
6/6; doc-tests and the corpus gate run in CI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-08 01:14:59 -07:00
lucioandClaude Opus 5.5 a062f62581 Docs for §65.1 match the code (review M-3)
ci / checks (push) Successful in 1m42s
ci / corpus (push) Successful in 33s
generate-label-rename README: "What changed" covers reworks 1-5 and the
review fixes; the stale "engine and verifier unchanged in code" claim is
replaced (what a rename rewrites is unchanged; the verifier gained no
normalization, only path-qualified file names). Status lists reworks 2-5,
P1/P2, §65.6 and the review; work log entries for M-2 and M-3, including
that QA's P1/P2 were fixed in the tree with no log entry. refactor-rename
README: dated correction. topo row 40: second half answered by row 43.
CHANGELOG: the two scoping bullets merged into one that matches rework 5
plus the H-1/H-2 fix. qa_warning_scope.rs P1/P2 test comments and the
rename module doc updated (comments only; that suite: 24 passed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 02:06:47 -07:00
lucioandClaude Opus 5.5 6d1957076a Refactor messages: count shared file names once per set, not once per file named (review M-2)
Scope::name_of scanned every source on each call, and the define and
macro-argument warning scans named every file of the set before looking for
a site — two quadratic passes. scope::BaseNames counts base names once (kept
on Scope and on the port offers' Files; name_among folded into it).

OpenTitan engine probe, whole hw, entropy_src_main_sm.state_q: 2.95 s ->
2.23 s (defines 326 -> 7 ms, macro arguments 394 -> 77 ms), the same 47
warnings. Workspace: 80 suites, 5 078 passed, 0 failed, 51 ignored; clippy
-D warnings clean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 02:05:33 -07:00
lucioandClaude Opus 5.5 38244e6aaf Rename: an include-related file's use that the rename edits is not said to be left unchanged (review M-1)
ci / checks (push) Successful in 1m51s
ci / corpus (push) Successful in 47s
fragment_use_warnings ignored the rename's edits, so renaming module `m`
while `all.sv` includes `m.sv` and `n.sv` rewrote `n.sv`'s instantiation and
still warned "n.sv:2: `m` is used in a file that includes `m.sv` … and was
left unchanged". Tokens covered by an edit in that file are skipped.

Test: rename_warning_scope.rs (fails with the skip disabled). Workspace:
80 suites, 5 077 passed, 0 failed, 51 ignored (first run cut by the guard at
1 800 s launching a fresh test binary — the §65.3 stall; re-run green).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:37:01 -07:00
lucioandClaude Opus 5.5 eadee02c37 Independent review of the §65.1 working tree (oct_review.md): 2 high (fixed), 3 medium, 13 low findings
ci / checks (push) Successful in 1m43s
ci / corpus (push) Successful in 52s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:41 -07:00
lucioandClaude Opus 5.5 e8e22c2364 Rename warnings: a macro argument the macro carries to the declaration is said wherever it is written (review H-1/H-2)
The home-set scoping dropped a bare macro argument outside the home set
whatever the macro did with it, and never saw a `bind` produced by a macro —
silent missed renames, regressions against 0.59.0 (`CONN(state_q)` building
`.state_q(state_q)` broke the instantiation without a word). New
rename/carry.rs decides per macro and formal position whether an argument is
carried: after a `.` (past blanks and pastes), into a carried position of
another macro, or by a macro that expands to a `bind` into the unit (every
position; its body is news and a file invoking it is home). An undefined
macro's arguments, one past the formals and a macro cycle are doubt and said.

Tests: tests/rename_macro_carry.rs (8), carry.rs unit tests (4). Workspace
lib/bins/tests: 80 suites, 5 076 passed, 0 failed, 51 ignored (guard exit 0).
OpenTitan engine probe against carrying disabled: state_q 47 = 47,
StIdle 0 = 0, cnt_q 13 = 13 warnings, timing unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:41 -07:00
lucioandClaude Opus 5.5 7794d3938b TODO §65.1: rename and references through a generate block label; rename warnings and mentions scoped to the renamed declaration
A path segment naming a block (bare, indexed, nested, cross-file) is now a
reference to its label: vlog_semantic declares a `for` block's label in the
enclosing scope, makes `generate … endgenerate` no scope, gives a block a
member scope, walks an index in a path, and files blocks on a module's
hierarchical surface under `module.label` (FACTS_FORMAT 21). The LSP, CLI
and MCP rename/references get it through the engine; lucisv-mcp's `block`
refusal is lifted. No verifier normalization (attacks in
check/qa_block_paths.rs, qa_block_attacks.rs).

Reworks after QA: unresolved path segments warned in every file of the set;
sibling-arm members warned; a label beside a net is a duplicate-declaration;
function-local block keys never collide; file names path-qualified when base
names collide; rename warnings and lucisv-mcp mentions scoped to the
declaration's home set (rename/home.rs, scoped.rs), falling back to unscoped
on any doubt. TODO §65.4 and §65.6 filed.

docs/features/generate-label-rename. Workspace lib/bins/tests: 79 suites,
5 064 passed, 0 failed, 51 ignored (guard exit 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:23 -07:00
lucioandClaude Fable 5.1 b9ee399ac6 TODO §65: stabilization round 1 — generate-label rename/references, LSP references fan-out to the pd_main tops, the doc-test stall
ci / checks (push) Successful in 1m39s
ci / corpus (push) Successful in 35s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-30 01:44:39 -07:00
lucioandClaude Fable 5.1 5316c0b127 Release 0.59.0: MCP read-only mode (--read-only, five tools, 1 797 bytes) and the hierarchy instance cap
ci / checks (push) Successful in 1m27s
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 7m16s
Version bump; the notes are in CHANGELOG.md (## 0.59.0) and
editors/vscode/CHANGELOG.md. Gates: fmt and clippy -D warnings clean,
72 suites + 6 doc suites (4937 passed, 0 failed), corpus 814/820,
node tests 6/6.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 02:12:33 -07:00
lucioandClaude Fable 5.1 74c56318c0 MCP: hierarchy caps at 300 instances (100 with peek), peek lines no longer count; census round 5 (read-only, same-day base control) written up; 0.59.0 notes dated
ci / checks (push) Successful in 2m11s
ci / corpus (push) Successful in 45s
Round 5 found `hierarchy up` + `peek` cut to 20 of 77 instantiations by
the 300-line cap. Same-day base controls put read-only mode at parity
with file tools (a +8 %, d −8 %) and show the base arm itself moved
22–29 % in six days.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 01:38:54 -07:00
lucioandClaude Fable 5.1 b757e82161 MCP M8: read-only mode — lucisv-mcp --read-only lists five read tools (1 797 bytes), never writes inside a root; full mode unchanged
ci / checks (push) Successful in 1m50s
ci / corpus (push) Successful in 52s
The mode filters the registry; an edit tool name answers unknown-tool.
Extension setting lucisv.mcp.mode (full | read-only; any other value is
read-only and logged), label and copy-config key lucisv-ro, both smokes
in the release script. Tests: tests/read_only.rs, QA lane tests/qa_m8.rs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 01:10:10 -07:00
lucioandClaude Fable 5.1 e992cca577 MCP plan §11 + lane M8: read-only mode (--read-only: five tools, ≤1 800 bytes, never writes inside a root; full mode unchanged)
ci / checks (push) Successful in 1m32s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 00:40:34 -07:00
lucioandClaude Fable 5.1 03c566a08b Release 0.58.0: the lean MCP catalogue (nine tools, 3 440 bytes, trusted writes) and census round 4
ci / checks (push) Failing after 1m41s
ci / corpus (push) Successful in 38s
release / build-and-publish (push) Successful in 10m37s
Version bump; the notes are in CHANGELOG.md (## 0.58.0) and
editors/vscode/CHANGELOG.md. Gates: check/fmt/clippy clean, 4922 tests
passed 0 failed (75 suites), corpus 814/820 (baseline).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-24 03:00:54 -07:00
lucioandClaude Fable 5.1 9242594457 mcp_analysis.md: census round 4 on the lean catalogue (6/6 correct; a −1 %, d parity, b/c +9…+10 %); 0.58.0 notes dated
ci / checks (push) Successful in 2m36s
ci / corpus (push) Successful in 49s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-24 02:03:14 -07:00
lucioandClaude Fable 5.1 bfa8e98eb5 MCP M7: the lean catalogue — nine tools, 3 440 model-visible bytes, no dry_run/paging, short answers
ci / checks (push) Successful in 1m43s
ci / corpus (push) Successful in 36s
hierarchy (file:line per instance, peek), find (every declaration by
name, refs + unresolved mentions), outline, read, check, rename, port,
edit_item, format. Name lookup reaches every declaration the symbol
tables hold (tools/declared.rs); rename of a generate-block label is
refused (engine gap filed as topo §2.9 MCP-14). Text-only results,
engine sentences made root-relative. Tests ported or deleted per the
README; QA lane in tests/qa_m7.rs. Docs, smoke gate, release notes
(0.58.0 unreleased) updated.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-24 01:40:53 -07:00
lucioandClaude Fable 5.1 edad66947f MCP plan §10 + lane M7: the lean catalogue (nine tools, ≤3 500 model-visible bytes, no dry_run/paging, short answers)
ci / checks (push) Successful in 1m25s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 23:55:04 -07:00
lucioandClaude Fable 5.1 77b3a2370b TODO-MCP: tick the release and round-3b boxes; 0.57.0 verified (8 assets, three binaries)
ci / checks (push) Successful in 1m32s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 23:36:15 -07:00
lucioandClaude Fable 5.1 522ae70db9 Release 0.57.0: the MCP block (lucisv-mcp), packaging, cache reuse, three census rounds
ci / checks (push) Successful in 1m38s
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 7m12s
Version bump only; the notes are in CHANGELOG.md (## 0.57.0) and
editors/vscode/CHANGELOG.md. Gates: check/fmt/clippy clean,
4953 tests passed 0 failed, corpus 814/820 (baseline).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 23:25:56 -07:00
lucioandClaude Fable 5.1 aba39e5535 mcp_analysis.md: round 3b re-measure on the final binary (task d −10 %, task a's opt-in lesson); raw run log updated
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 23:01:04 -07:00
lucioandClaude Fable 5.1 2954ae8a84 MCP feedback-3: the instantiation template and hierarchy overrides are opt-in; census round 3 and the verdict written; 0.57.0 notes drafted
ci / checks (push) Successful in 1m28s
ci / corpus (push) Successful in 32s
Round 3 of the census (mcp_analysis.md): with feedback-1/2 the whole-design question is one call and 15 % cheaper than plain file tools (47/47 in 9 calls); the small edits stay 4–19 % dearer; the cross-file rename is complete every time; a 71-instance hierarchy question costs a third of the tool calls but the same tokens because every unit_interface answer carried a 30-line template. Verdict: helpful, not a toy — no wrong answer in 20 runs, one-call whole-design answers, completeness on cross-file edits, verified writes — with a fixed catalogue tax and verbose answers as the cost. Feedback-3 (crates/lucisv_mcp/src/tools/{interface,hierarchy}.rs): `unit_interface` renders the template only with `template: true` (−40 % bytes), `hierarchy` renders `#(…)` only with `overrides: true` (−55…66 %), `ports (N):`/`parameters (N):` headers; QA proved the opt-in output byte-identical to the previous binary over every fixture and the opentitan clone. Docs: the Agents guide's tool table regenerated from the binary and the site rebuilt; CHANGELOG 0.57.0 section and the extension notes drafted for the closing release; TODO-MCP's M6 items closed; docs/mcp/census-runs.txt holds the raw run log. Gates through tools/guard.sh: fmt, clippy, workspace 4 953 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 22:53:18 -07:00
lucioandClaude Fable 5.1 c2e42b8840 MCP feedback-2: the count line leads every paged answer, default limit 500, in path-glob filter on the listing tools, post-edit check hint; census round 2 written up
ci / checks (push) Successful in 1m39s
ci / corpus (push) Successful in 33s
Census round 2 (mcp_analysis.md): with feedback-1 the rename task became complete (the unresolved-mentions list surfaced the DV string path) at a token cost inside the base arm's run-to-run variance; the port task was unchanged; the census task regressed — the agent chose `hierarchy up` (right) but paged the 77-row answer with a small limit and never read the trailing "… and N more". Fixes: every paged text answer opens with `N <noun> (showing a–b)` (JSON gains `shown`), DEFAULT_LIMIT 500; `list_units`, `search_symbols`, `references`, `hierarchy`, `diagnostics` and `defines` take `in`, a root-relative path glob (`*` within a component, `**` across, `?`; a bare directory means everything below it) applied before paging — `hierarchy up prim_fifo_sync` with `in: "ip/**/rtl/*.sv"` answers the census's 47 in one call; the six design-wide edits end with `check: diagnostics on <files>`. Catalogue 17 993 B, instructions 896 chars. QA (Opus): 14 qa_f2 tests, four notes. Gates through tools/guard.sh: fmt, clippy, workspace 4 943 passed (+1 lead test).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 21:50:34 -07:00
lucioandClaude Fable 5.1 4671b91704 MCP feedback-1: unresolved mentions on references and the edit tools, a smaller catalogue, hierarchy/references routing, add_port after, temp sweep; census round 1 written up
ci / checks (push) Successful in 1m30s
ci / corpus (push) Successful in 32s
Census round 1 (mcp_analysis.md, Sonnet arms on the opentitan clone): the mcp arm used more tokens than plain file tools on all three tasks (+18/+25/+20 %) and was incomplete on the rename — the `rename` tool renamed what the engine sees and warned about the macro argument, but nothing listed the old name still spelled as text (a DV force path built as the string ".state_q"), which the base arm's broad search found. Fixes (crates/lucisv_mcp/src/tools/{mentions,place,place/slot,place/verify}.rs + descriptions): `references`, `rename`, `remove_port` and `add_port` end with every whole-word spelling of the name in strings, comments, macro text, define bodies and macro-rooted paths that no engine answer accounted for, ranked edited-files-first, capped at 50, computed on the texts as written; `hierarchy` leads with "who instantiates a module", `references` routes a module name there, `instructions` say so; `tools/list` 30.2 kB → 18.0 kB with every argument still documented; `add_port` takes `after` — the engine appends, the placer moves the header element and each instance's connection to after the anchor in the neighbours' layout, refuses any list holding an unreadable element (an `(* attr *)` port the parser keeps as text would otherwise make the next port inherit the new type — QA's blocking find), and a checker compares every port's declaration text and pairs each comment with its anchoring name against the engine's result; stale `index-cache-mcp.*.tmp` files older than 10 min swept before a write. QA (Opus, two rounds): 23 qa_f1 tests. Gates through tools/guard.sh: fmt, clippy, workspace 4 918 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 20:44:06 -07:00
lucioandClaude Fable 5.1 0f4830afa5 MCP M6: read-only reuse of the editor's index cache, an own store, the forced-delete ruling, first instructions; the block's closing docs
ci / checks (push) Successful in 1m25s
ci / corpus (push) Successful in 31s
crates/lucisv_mcp/src/cache.rs: at startup `--index-cache DIR/index-cache` (the language server's store) is read READ-ONLY — header CACHE_FORMAT/FACTS_FORMAT/version must match this build or the store is ignored with one stderr line; each record line's checksum verified, decoded, keyed by (record path, content hash) and used only for a discovered file whose bytes hash to it, through IndexBuilder::add_facts instead of a parse; the server never writes that file. Its own `index-cache-mcp` is written once at exit, atomically, in the same codec (a test pins the restated framing against index_cache.rs's source). opentitan: cold 1.9 s → warm 0.8 s (walk 210 ms + merge 204 ms are the floor). delete_item with force may remove an item holding `define/`undef, warning which macros went (M4's ruling); INSTRUCTIONS names the read tools, the edit tools, dry_run and diagnostics. Closing docs: docs/topo.md gains the lucisv_mcp node and its six edges, the mcp-packaging spawn/packaging rows, the read-only cache row and §2.9 rows 35–42 (MCP-5/6/7/8/10/11/12/13 and the parser leniency the M3.5 verifier exposed); repository-analysis map row and nine-crate count; README architecture row; CLAUDE.md measurement for the new crate.

QA (Opus; interrupted by the owner moving the machine, verdict pass so far): swapped/stale/foreign/deleted/off-by-one-header/CRLF stores skipped, the editor's store byte-identical through a session, SIGKILL mid-write harmless, a 231 MB store linear, fingerprint parity over the whole checkout; two low items open — the README threat model reworded, and an orphaned `.tmp` after a kill between write and rename to be swept in the census round. Gates: fmt, clippy clean; lucisv_mcp 318 passed; the dev's workspace run 4 858 passed on the same code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 17:14:43 -07:00
lucioandClaude Fable 5.1 d4ec571958 MCP M5: lucisv-mcp ships in every platform vsix; the extension registers it with VS Code's agent mode; Agents guide
tools/release.sh builds -p lucisv_mcp for the host and every cross triple, stages lucisv-mcp[.exe] beside the two binaries (three per platform package, fifteen in the all-platforms one; the universal package still carries none), smoke-tests it (editors/vscode/mcp_smoke.js: initialize, tools/list ≥ 26, project_overview) loose and unzipped from the host and all-platforms packages; tools/audit_artifacts.sh audits the third name and rejects any other; prune_release_assets.sh unchanged (seven vsix names). editors/vscode/mcp.js: the three-rung binary ladder (lucisv.mcp.path → bundled → PATH), one McpStdioServerDefinition per workspace folder — the constructor is POSITIONAL (label, command, args, env, version) with cwd set afterwards; the plan's object form was wrong and is corrected — with `--root <folder> --index-cache <storage>`, refreshed on folder and setting changes, guarded so VS Code < 1.101 registers nothing but the command; a missing binary refused at resolve time with one output-channel line; the `lucisv.mcp.copyConfig` command puts the Claude Code / Cursor / VS Code snippet on the clipboard. package.json: contributes.mcpServerDefinitionProviders, lucisv.mcp.enabled/path, the command; engine stays ^1.82.0 (vsce 4 accepts). ci.yml runs node --test over the extension's unit tests. Docs: docs/site guides/agents.md with the tool table generated from the binary (site rebuilt), README paragraph, RELEASING.md, extension README/CHANGELOG (Unreleased), manual-acceptance rows 18–25 for the live-VS Code checks.

QA (Opus): API signature confirmed against VS Code 1.138's vscode.d.ts; 8 mutation checks caught by mcp_test.js; release.sh run end to end, vsix contents listed (three binaries, mcp.js, no test files), SHA256SUMS verified, the embedded binary smoke-tested, the vsix installed into an isolated profile. Gates: node --test 6/6, fmt clean.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 15:59:07 -07:00
lucioandClaude Fable 5.1 23ec44455c MCP M4: structural edits — replace_item, insert_item, delete_item with the block's own verifier
crates/lucisv_mcp/src/tools/item.rs + item/{verify,lexical,span,refs,macros,star}.rs: the general token saver — an agent sends one item's text, never the file. Every edit is a byte-range splice of exactly the slice read_item shows (kind classes: module/interface/program/package/class/declaration/port declaration/always/initial/final/instance/function/task/generate/…), through apply::run (dry_run, freshness, atomic write). The verifier: 1a the text lexes on its own; 1b every token and comment outside the region is byte-identical, shifted, nothing straddles the region's end and no comment inside attaches to a token outside; 2 every item outside the region keeps its depth, kind class and span (a text opening a block or closing the enclosing module is refused); 3 the region holds what the tool promised, each item a kind its container may hold; 4 no new duplicate declaration; 5 ifdef/endif balance in the old and new bytes; 6 define entries inside the region unchanged unless the item is a directive; 7 fence markers unchanged. Normalisation: one trailing newline when the old slice ended a line, the file's line endings; a text that brings comments widens the replaced span over the item's own leading/trailing comments so repeats are `unchanged`; own comments stop at the first blank-line gap; a same-line comment goes with the item. delete_item refuses while a declared name is used — the whole-set engine, the file's own tables, macro-call arguments and define bodies (possible use), and `.*` instantiations in the item's scope whose module declares the port (bound) or cannot be resolved (possible) — unless force, listing the first sites.

QA (Opus, two rounds across an app restart): 45 qa_m4 tests + 23 dev attacks; four masked corruptions fixed (open comment swallowing a fence, macro and .* uses invisible to delete, banner comments deleted). Timings release: 40 000-line file replace 159 ms, insert 284 ms, delete 263 ms. Handshakes MCP-11 (batched find_references), MCP-12 (generate-loop hierarchical use missed by the engine), MCP-13 (lint gap on a directionless header port). Gates through tools/guard.sh: fmt, clippy, workspace 4 846 passed.

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 03:58:55 -07:00
lucioandClaude Fable 5.1 ef867db004 TODO §64.2: 0.55.0 verified — loop 3 round 2 closed
ci / checks (push) Successful in 1m23s
ci / corpus (push) Successful in 35s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-17 14:49:13 -07:00
lucioandClaude Fable 5.1 23e2e4bca5 Release 0.55.0 — loop 3 round 2: references reach a module's internals across files; a stale index omits, never mislocates
ci / checks (push) Successful in 1m11s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 9m37s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-17 14:36:35 -07:00
lucioandClaude Fable 5.1 a2a22adad8 Cross-file references reach a module's nets, variables and instances (§64.1, QA task_d8afe80f of §63.1): nav.rs's two index questions (leaves_this_file, indexed_def_in_file, the latter shared with hover's live_symbol) asked WorkspaceIndex::member — the connection surface, ports and parameters — so a declaration only a hierarchical path can name (a bind connection's expression half, a u_x.sig tail) was judged unable to leave its file and references fell to the single-file answer, while a rename already edited both files; from a use that did resolve cross-file, the declaring buffer's own uses could not re-identify themselves. Both now ask member_in(…, Surface::Hierarchical); the connection answer comes first and whole from that read, so every port/parameter/package/class/struct answer is byte-identical (nav harness controls and a 948-declaration opentitan census). A hierarchical-only member has no Local postings by the §49 ruling, so nav::declaring_file_uses parses exactly the closed declaring file once per request (0.4–1.5 ms on state_q into a shut entropy_src_main_sm.sv), hierarchical_only asking the index's own table rather than restating surface_of. Three QA rounds (Sonnet, Sonnet, then Fable per the escalation rule): the closed-file path read a cached FileView and rendered against a fresh text_of (a stale offset on a wrong line) — now one fresh read per closed file threaded to the rendering step; every index-time span about a closed file, and the open-buffer declaration fallback (nav::declaration_site), guarded by hover::spells_exactly (pub(crate), shared not copied): a stale index may omit a location, never mislocate one. Accepted: +25 % on a local-net references in a 40 267-line buffer (1.22 → 1.54 ms), the guard is textual (a different exact token at a deleted declaration's old bytes). opentitan: entropy_masking_req from aes.sv now lists aes_bind.sv; state_q lists entropy_src_core.sv; checkout untouched. Tests 4422 → 4459 (11 dev + 1 hover + 1 e2e wire test; 19 QA attacks incl. escaped identifiers, UTF-8 boundaries, a deleted declaring file, oracle equivalence with vlog_refactor::find_references); fmt, clippy, workspace suite green through tools/guard.sh. Feature README docs/features/references-hierarchical-surface; references-nav, hierarchical-tail and hover-declarations READMEs, record.rs's postings comment and the topo row amended; perf entry in docs/perf/README.md. Release 0.55.0 left to the owner.
ci / checks (push) Successful in 1m14s
ci / corpus (push) Successful in 36s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 14:50:16 -07:00
lucioandClaude Fable 5.1 9d1eb1671e TODO §64: loop 3 round 2 — cross-file references for hierarchical-surface-only declarations
ci / checks (push) Successful in 1m11s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 13:01:38 -07:00
lucioandClaude Fable 5.1 5d70cb89cc TODO §63.3: 0.54.0 verified — loop 3 round 1 closed
ci / checks (push) Successful in 1m11s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-12 03:23:09 -07:00
lucioandClaude Fable 5.1 da32237a0e Release 0.54.0 — loop 3 round 1: rename edits bind files; first request after an edit −19 %
ci / checks (push) Successful in 1m9s
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
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m26s
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
ci / corpus (push) Successful in 35s
release / build-and-publish (push) Successful in 6m20s
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
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 6m51s
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
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 6m20s
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
ci / corpus (push) Successful in 37s
release / build-and-publish (push) Successful in 6m54s
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
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m25s
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
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m22s
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
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 6m27s
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
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m28s
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
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m13s
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
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 9m43s
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
ci / corpus (push) Successful in 28s
release / build-and-publish (push) Failing after 11m8s
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
ci / corpus (push) Successful in 26s
release / build-and-publish (push) Successful in 5m16s
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
ci / corpus (push) Successful in 28s
release / build-and-publish (push) Successful in 5m53s
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
ci / corpus (push) Successful in 26s
release / build-and-publish (push) Successful in 5m56s
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 / corpus (push) Successful in 29s
ci / checks (push) Successful in 1m1s
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
826 changed files with 223740 additions and 37673 deletions

No files matched your search

+7 -3
View File
@@ -1,7 +1,7 @@
# CI: the three checks CLAUDE.md requires before any work is finished,
# plus the corpus gate, enforced on every push. Runs on the self-hosted
# mac-arm64 runner in host mode (no containers), so the toolchain is the
# same one releases are built with.
# plus the extension's JavaScript tests and the corpus gate, enforced on
# every push. Runs on the self-hosted mac-arm64 runner in host mode (no
# containers), so the toolchain is the same one releases are built with.
name: ci
on:
push:
@@ -19,6 +19,10 @@ jobs:
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: cargo test --workspace
# The VS Code extension's headless checks (a stubbed `vscode`, no npm
# dependencies): node >= 18 for `--test`; the runner has node 22.
- name: extension tests
run: node --test editors/vscode/*_test.js
# The 99.1% headline, enforced: score the 820-file corpus and fail on any
# regression below scripts/corpus-baseline (verification errors and
+7 -2
View File
@@ -2,8 +2,8 @@
# publishes a Gitea release with the CHANGELOG section for that version as
# 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.
# linux-arm64/win32-x64) with the lucisv + lucisv-server + lucisv-mcp binaries embedded,
# and the all-platforms one carrying every platform's three binaries 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
@@ -43,7 +43,12 @@ jobs:
run: tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"
- name: Extract the release notes from CHANGELOG.md
run: tools/release_notes.sh "${GITHUB_REF_NAME#v}" > dist/RELEASE_NOTES.md
# LUCISV_API_URL is an optional repository Actions variable naming a
# direct http://host:port for the Gitea API, so the uploads do not go
# through Cloudflare's 100-second origin timeout (0.29.0 and 0.30.0
# both died there with a 524). Unset, the public URL is used.
- name: Create the release and attach the artifacts
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
LUCISV_API_URL: ${{ vars.LUCISV_API_URL }}
run: tools/publish_release.sh "$GITHUB_REF_NAME" dist
+1
View File
@@ -7,3 +7,4 @@
.DS_Store
/.zcode
/.claude
__pycache__/
+1240
View File
File diff suppressed because it is too large. Load diff
+69
View File
@@ -29,6 +29,61 @@ 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.
Re-measured 2026-09-23 for the MCP block (`crates/lucisv_mcp`, nine crates
now): largest files `tools/read.rs` 405, `tools/item.rs` 379, `tools/item/verify.rs`
363, `tools/nav.rs` 340, `tools/diagnostics.rs` 330, `tools/interface.rs` 322,
`tools/hierarchy.rs` 316 — everything under 600; the M3.5 engine lane left
`vlog_refactor/src/rename/connections.rs` at 477 and `check/mod.rs` at 426,
and `lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55).
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
@@ -87,6 +142,20 @@ Rules:
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
## Runaway guard (never run a suite or sweep bare)
On 2026-09-03 a background test run consumed 100 GB and crashed the
machine. macOS enforces no memory cap, so the cap is ours:
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
process tree when its resident set or wall clock exceeds the limits
(defaults 8 GB / 30 min).
- **Every `cargo test`, every fuzzer, every corpus or opentitan sweep,
and every `lucisv`/`lucisv-server` run over a tree goes through
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
Generated
+24 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.26.0"
version = "0.60.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,25 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.26.0"
version = "0.60.0"
[[package]]
name = "lucisv_mcp"
version = "0.60.0"
dependencies = [
"lucisv_core",
"serde",
"serde_json",
"vlog_formatter",
"vlog_linter",
"vlog_parser",
"vlog_refactor",
"vlog_semantic",
]
[[package]]
name = "lucisv_server"
version = "0.26.0"
version = "0.60.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,15 +262,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.26.0"
version = "0.60.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.26.0"
version = "0.60.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
@@ -264,19 +279,20 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.26.0"
version = "0.60.0"
[[package]]
name = "vlog_refactor"
version = "0.26.0"
version = "0.60.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
]
[[package]]
name = "vlog_semantic"
version = "0.26.0"
version = "0.60.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.26.0"
version = "0.60.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+418 -73
View File
@@ -2,6 +2,12 @@
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
Start with the [repository analysis](docs/repository-analysis.md) for a code-based
assessment and [dependency topology](docs/topo.md) for interfaces and change
impact. The [documentation site source](docs/site/README.md) contains usage
guides and references; [CHANGELOG.md](CHANGELOG.md) records releases, and
[TODO.md](TODO.md) tracks work in progress.
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
layout conventions and lint ergonomics borrowed from
@@ -80,10 +86,9 @@ run over an unchanged tree skips them: the summary says `N files from cache`,
and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
thread count, where parallelism has already taken the easy win).
An entry is keyed on **(content hash, `line-length`, `indent`, lucisv version)**
per file, and only ever records the *already formatted* verdict — a file that
would be reformatted, or that failed, is re-checked on every run, so
`--check`'s exit codes and `--diff`'s output never go stale. The store is one
An entry is keyed on **(content hash, `line-length`, `indent`,
`uvm-utils-indent`, lucisv version)** per file, and only ever records the *already formatted* verdict — a file that
would be reformatted, or that failed, is re-checked on every run. The store is one
text file in `.lucisv_cache/` (self-ignoring, like cargo's `target/`); deleting
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
neither reads nor writes it, and `--cache-dir <PATH>` puts it elsewhere (the
@@ -91,6 +96,10 @@ default is relative to the current directory). Content hashing is 64-bit
FNV-1a and a lookup never crosses files; `docs/features/format-cache/README.md`
states the collision posture, the semantics table and the concurrency story.
(In v0.49.0 only, `uvm-utils-indent` was missing from this key, so a cached
clean verdict survived a toggle of the option — fixed in 0.50.0; a 0.49.0
store is simply rebuilt.)
### Ignore files
While walking a directory, lucisv reads a `.gitignore` in every directory it
@@ -106,6 +115,12 @@ trailing `/` (matches directories only), and `!` negation. **Not** supported:
git's "already-tracked files are never ignored" rule. See
`docs/features/parallel-files/README.md` for the exact subset.
Directory walks enter each directory once by identity, so symlink cycles
terminate. Inputs resolving to one canonical file path are processed once.
Unreadable directories or `.gitignore` files and dangling source links found
during a walk warn on stderr and are skipped without changing the exit code;
a missing explicitly named input is still an error.
## Configuration
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
@@ -128,6 +143,10 @@ line-length = 100 # 40..400, same as --line-length
indent = 2 # 1..8, same as --indent
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
[lint]
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
ignore = ["module-filename"] # removed after selection
```
`filelist` names the project's sources the way the rest of the EDA world
@@ -154,10 +173,16 @@ error (exit 2) and nothing is processed. Details:
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
with a file that sets only `line-length` uses both). `exclude` is the
exception: config patterns are *added* to `--exclude`, not replaced by it.
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
off by default, indents the `` `uvm_field_* `` macros written between
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
formatting choice lucisv leaves to the project, because it changes bytes
in existing UVM code (21 of the 860 corpus files).
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
supported subset (tables, multi-line arrays, string escapes) is a hard error
naming the file and line — exit 2, with nothing written. This is deliberate:
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
arrays, unsupported string escapes) is a hard error naming the file and
line — exit 2, with nothing written. This is deliberate:
a silently ignored `line_length` typo costs more than a strict parser does.
## Linting
@@ -167,11 +192,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same
`lucisv.toml` discovery.
```bash
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
lucisv check rtl/ # FILE:LINE:COL: severity: message [rule]
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
lucisv check --ignore module-filename rtl/ # everything but these
lucisv check --select error rtl/ # a whole severity class, by name
lucisv check --fix rtl/ # apply the safe fixes, write files back
lucisv check --rules-doc # the generated reference for every rule
```
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
@@ -179,35 +206,195 @@ violations remain, 2 error. Unlike the formatter, `check` uses the
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
what it can see.
| Rule | Fix | What it wants |
|---|---|---|
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | safe | nothing but code before the newline |
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
| `always-comb-blocking` | — | `=` inside `always_comb` |
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | — | a one-module file is named after its module |
| `unused-waiver` | — | waivers that suppress nothing |
| `unused-signal` † | — | no net or variable nothing uses |
| `undriven-net` † | — | everything read is driven by something |
| `multiply-driven` † | — | one driver per variable |
### Severities
† Off by default — `--select` them. These three read the file's *symbol
table*, not just its syntax, which is what lets them tell one `count` from
another; they are off because a single-file analysis cannot see a signal used
from another file's hierarchy. See
`docs/features/semantic-lints/README.md`. The table above is not the whole
set — naming-style rules ship too, and
`cargo run -p vlog_linter --example rules_markdown` prints the generated
reference for every rule with its default.
Every rule is in one of three classes, and the class is the word that stands
in the diagnostic line, in the JSON `severity` field, and in the editor's
squiggle colour:
| Class | Means | Editor |
|---|---|---|
| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) |
| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) |
| `style` | correct, and reads badly | blue (LSP Information) |
A class name is accepted **wherever a rule name is** — on `--select`, on
`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`:
```bash
lucisv check --select error rtl/ # only the compile-breakers
lucisv check --ignore style rtl/ # everything but the naming rules
```
Every `error`-class rule follows one discipline: **silence beats a wrong
accusation**. Each of them goes quiet whenever the run cannot answer — a file
that did not fully parse, a module the project does not hold or holds twice, a
name a macro produces, a fragment written to be `` `include``d. That is what
makes an editor's red squiggle worth believing.
### The rules
| Rule | Severity | Fix | What it wants |
|---|---|---|---|
| `multiply-driven` † | error | — | one driver per variable |
| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file |
| `mismatched-labels` | error | — | `end : name` names the block it closes |
| `duplicate-declaration` | error | — | each name declared once per scope |
| `undeclared-identifier` † | error | — | every name is declared somewhere in the project |
| `unknown-port` † | error | — | `.name(…)` is a port the module declares |
| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares |
| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` |
| `always-comb-blocking` | warning | — | `=` inside `always_comb` |
| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` |
| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path |
| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` |
| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` |
| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` |
| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` |
| `truncated-numeric-literal` | warning | — | a sized literal fits its width |
| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written |
| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` |
| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension |
| `module-port` | warning | — | more than one port is connected by name |
| `module-parameter` | warning | — | more than one parameter is overridden by name |
| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type |
| `void-cast` | warning | — | `void'(…)` wraps a call |
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
| `undriven-net` † | warning | — | everything read is driven by something |
| `unused-signal` † | warning | — | no net or variable nothing uses |
| `create-object-name-match` | warning | — | `type_id::create("x")` names the handle `x` |
| `forbidden-macro` | warning | — | no macro on the project's forbidden list |
| `uvm-macro-semicolon` | warning | — | no `;` after a `` `uvm_* `` macro (off by default) |
| `macro-string-concatenation` | warning | — | no `` `` `` inside a plain string (off by default) |
| `disable-statement` | warning | — | `disable fork`, not a fork label (off by default) |
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
| `empty-item` | style | safe | no `;` standing where an item belongs |
| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | style | — | a one-module file is named after its module |
| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` |
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
| `line-length` | style | — | no line wider than the width the formatter uses |
| `posix-eof` | style | safe | the file ends with a newline |
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
| `generate-label` | style | — | every generate block carries a `: label` |
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
| `package-filename` | style | — | a one-package file is named after its package |
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
| `one-module-per-file` | style | — | one `module` per file (off by default) |
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
| `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) |
| `unused-waiver` | style | — | waivers that suppress nothing |
| `unused-import` † | style | safe | no `import` nothing in the scope reaches through (off by default; stays off without a project) |
| `explicit-function-lifetime` | style | — | `automatic`/`static` on a function outside a class |
| `explicit-task-lifetime` | style | — | `automatic`/`static` on a task outside a class |
| `positive-meaning-parameter-name` | style | — | no `disable`-prefixed parameter name |
| `suggest-parentheses` | style | safe | `a ? (b ? c : d) : e`, parenthesized |
| `unpacked-dimensions-range-ordering` | style | — | an unpacked dimension is `[0:N-1]` |
| `module-begin-block` | style | — | no `begin`/`end` at module scope |
| `v2001-generate-begin` | style | — | no bare `begin` in a generate region |
| `forbid-line-continuations` | style | — | no `\` breaking a string literal |
| `legacy-generate-region` | style | — | no `generate … endgenerate` wrapper (off) |
| `legacy-genvar-declaration` | style | — | a genvar is declared in the `for` header (off) |
| `endif-comment` | style | safe | `` `endif `` names what it closes (off by default) |
| `numeric-format-string-style` | style | — | a radix prefix matches its specifier (off) |
| `proper-parameter-declaration` | style | — | `parameter` in a header, `localparam` in a body (off) |
| `dff-name-style` | style | — | a flip-flop is `_q`, its input `_d` (off by default) |
† On by default when lucisv can see a project (a multi-file CLI run or the
language server), and off for a single file or stdin unless `--select` names
them. These rules read the file's *symbol table* and ask the project about
names, not just the file's syntax; the project-wide identifier census keeps a
hierarchical use in another file from becoming a false positive. See
`docs/features/semantic-lints-on/README.md` and
`docs/features/linter-expansion-1/README.md`.
`lucisv check --rules-doc` prints the whole reference — every rule, its class,
its default, its fix and the paragraph saying why it exists — generated from
the registry, so it can never be out of date.
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
that cannot change what the code means), `--unsafe-fixes` widens that — no
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
that cannot change what the code means), `--unsafe-fixes` widens that to the
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
`always_comb`, which is a different block at time zero and makes a second
driver of its outputs an error — right nearly always, and not lucisv's call to
make without being asked. Violations inside a `// verilog_format: off`
region are reported but never fixed: `off` means hands-off for the linter too,
so `--fix` leaves every byte of a fenced region exactly as written.
### Rule options
A rule can be configured in a `[lint.<rule-name>]` table:
```toml
[lint]
ignore = ["typedef-structs-unions"]
[lint.line-length]
length = 120 # the linter's limit, if not the formatter's
[lint.generate-label-prefix]
prefix = ["g_", "gen_"] # the label prefixes this project writes
[lint.parameter-name-style]
localparam_style = "CamelCase" # Verible's own default, stricter than ours
[lint.signal-name-style]
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
```
The keys are Verible's wherever it has the same option, so a `.rules.verible`
file translates word for word. An option nobody sets reads the default
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
value of the wrong kind, an integer out of range or a pattern that does not
compile **fails the run**, naming the config file and the line — a typo in a
lint setting is not something to guess at.
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
against the **whole** name, so `^`/`$` are accepted and redundant.
Everything else is **refused when the option is read, by name**: counted
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
worse than an error you can read.
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
length whatever shape the pattern has: no pattern can make `lucisv check` — or
an editor session — hang.
From an editor the same options are one object, `lucisv.lint.options`:
```json
"lucisv.lint.options": {
"line-length": { "length": 120 },
"typedef-structs-unions": { "allow_anonymous_nested": false }
}
```
There the precedence is **the editor's value, then the `lucisv.toml`, then the
rule's default — key by key**: a project can set two options and one user
override the third without losing the others. (This is the opposite order to
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
formatting has a byte-exact contract with CI, and which findings you are shown
in your own editor is yours to choose.) A bad entry there is *ignored* and
reported in the lucisv log rather than fatal, so one typo cannot leave a
session with no diagnostics.
### Waivers
```systemverilog
@@ -221,21 +408,84 @@ 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 nine-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 |
| `crates/lucisv_mcp` | — | Model Context Protocol server for coding agents: project understanding and verified, token-saving edits over stdio (`docs/mcp/PLAN.md`) |
`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, and so does the MCP server (never the LSP
crate). 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 +498,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 +554,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 +569,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 +625,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 +679,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 +709,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 +750,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 +777,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 +868,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 +893,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,9 +910,28 @@ go-to-definition, references and document/workspace symbols — the full list,
and what is deliberately *not* advertised yet, is in
`docs/features/lucisv-server/README.md`.
The editor now offers these refactorings alongside rename and port propagation:
| Action | Behavior |
|---|---|
| Expand wildcard | Replace `.*` with declaration-order named connections; unmatched ports become `.p()` with a warning |
| Convert ports to ANSI | Merge a legacy module header and its body port declarations, preserving comments and attributes |
| Organize imports | Remove unused imports, merge exact duplicates and sort a top-of-scope run; uncertainty keeps the action conservative |
| Extract module | Move selected whole module items into a named module, infer its interface, and insert the replacement instance; create a file when supported or append below the source module |
| Inline module | Copy a separate-file module body into its instance site with simple named-connection substitution and collision-aware internal renaming |
The [language-tools reference](docs/site/src/content/docs/reference/language-tools.md)
records commands and refusal limits. Inline-module has a known transitive
source-selection gap; review hierarchical uses through wrapper modules before
applying it (topology handshake 33).
In the VS Code hierarchy, **Star as DUT** groups a module’s children and
parents into sections alongside Other Modules. Stars persist per workspace;
`lucisv.hierarchy.duts` adds team-configured names, which are locked in the menu.
**VS Code needs no separate binary**: every release on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases) carries a
platform-specific `.vsix` with both binaries inside it — pick yours
platform-specific `.vsix` with the binaries inside it — pick yours
(`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64`)
and sideload it:
@@ -666,11 +985,28 @@ vim.lsp.enable('lucisv')
`nvim-lspconfig`, Vim 9 (`vim-lsp`) and coc.nvim equivalents:
`editors/nvim/README.md`.
**Agents (MCP).** `lucisv-mcp` is lucisv as a Model Context Protocol server
for coding agents: project overview, unit interfaces, outlines, one item's
source, definition/references/hierarchy, diagnostics, and verified edits
(format, lint fixes, rename, the port refactorings, single-item
replace/insert/delete), each with `dry_run`. The platform `.vsix` packages
carry it as a third binary and, on VS Code 1.101+, register it with agent
mode — one server per workspace folder, under **MCP: List Servers**
(`lucisv.mcp.enabled`, `lucisv.mcp.path`). For Claude Code or Cursor, run
**lucisv: Copy MCP server config** in VS Code, or by hand:
`cargo build --release -p lucisv_mcp`, then
`claude mcp add lucisv -- lucisv-mcp --root .`. The tool list, the config
snippets and the safety rules are in the
[Agents (MCP) guide](docs/site/src/content/docs/guides/agents.md).
**Which files the server indexes.** A filelist if the project has one — the
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
(a path, absolute or relative to the workspace folder) — and then exactly the
files it names. Otherwise the workspace folder, walked as the CLI walks it;
and with no folder open at all, the current file's own directory. Open buffers
files it names. Otherwise the default `lucisv.index.scope = "folder"` starts
from open-file folders, widens by `lucisv.index.scopeDepth` (default 2), and stays bounded by
the workspace roots; `"workspace"` walks the full roots. With no folder open,
the server stays in the current file's directory: depth 0 scans it flat; a
positive depth walks its descendants but never climbs to a parent. Open buffers
are always indexed on top. A filelist that cannot be read warns and falls back
to the folder walk, so the index is never silently empty.
@@ -701,11 +1037,20 @@ expected; no PRs or review required.
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo test # unit + snapshot + idempotency tests
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
```
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
expected outputs only for intentional formatting changes with
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
Table-driven cases live in `crates/vlog_formatter/tests/cases/`; lint cases
live in `crates/vlog_linter/tests/cases/`. All tests, fuzzers, and corpus/tree
sweeps must run through `tools/guard.sh` (8 GiB RSS / 30 minutes by default),
as required by [CLAUDE.md](CLAUDE.md). A guard kill is a finding, not a reason
to increase the limit. Documentation build instructions are in
[docs/site/README.md](docs/site/README.md).
## Install and releases
+500
View File
@@ -0,0 +1,500 @@
# 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.
- [x] `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`
- [x] `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
- [x] 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)
- [x] 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`)
- [x] 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)`.
- [x] `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/*`
- [x] `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
- [x] `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
- [x] 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
- [x] CI: `node --test editors/vscode/*_test.js` in `ci.yml`
- [x] 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
- [x] 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.
- [x] `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)
— done 2026-09-23 (dev): `src/cache.rs`, `tests/cache.rs`; the M4
rule-6 ruling (`force` on `delete_item`) and the first `instructions`
revision delivered in the same lane (`docs/features/mcp-cache-and-census`)
- [x] 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`
— done 2026-09-23 (dev): cold 1.87 s, warm 0.83–0.85 s from either
store, sweep 5.6–6.1 ms, `rename` dry run 2.23–2.28 s
- [x] the token census (PLAN §8): four tasks over three rounds, 20 runs
(Sonnet arms, one Opus pair), base vs mcp on a clean opentitan clone,
graded against lead-computed ground truths — written up in
`mcp_analysis.md` (repo root; the owner's name for it) with the raw
run log in `docs/mcp/census-runs.txt`. Verdict: no wrong answer in
20 runs; −15 % tokens on the whole-design question, +4…+19 % on small
edits, completeness won on the rename
- [x] `instructions` and tool descriptions revised from what the census
transcripts showed (feedback-1/2/3); no `prompts/*` — the census
showed no repeated multi-tool sequence worth one
- [x] `docs/topo.md`: the `lucisv_mcp` node and six edges, the §2.8 rows,
MCP-1 delivered in M3, §2.9 rows 35–42 for the engine findings —
done 2026-09-23 with the M6 commit
- [x] `CHANGELOG.md` section (0.57.0), `README.md` architecture table row
(nine crates), `docs/repository-analysis.md` map row, CLAUDE.md
measurement line — done with the M6 commit and the closing release
- [x] release **0.56.0** (or the next minor free at the time): tag, CI
— done: 0.56.0 (72ff5df, M1–M3.5) and the closing **0.57.0**
(522ae70, tag v0.57.0, 2026-09-23): CI green, 8 assets, the
darwin-arm64 vsix holds bin/{lucisv,lucisv-server,lucisv-mcp} +
mcp.js, the bundled server answers `initialize` as 0.57.0
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
- [x] 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
— done 2026-09-23 (Opus; interrupted by the owner moving the
machine, verdict pass-so-far with no blocking finding, recorded in
the README's QA log; the lead reviewed and committed; the temp-file
sweep QA asked for landed in feedback-1 and the census exercised the
warm-start path across 20 runs)
## Feedback rounds (the token census → the server)
### Round 1 → lane feedback-1 (`docs/features/mcp-feedback-1`)
- [x] unresolved mentions (`src/tools/mentions.rs`): every whole-word
spelling of the name in strings, comments, macro text, `define bodies
and macro-rooted paths that no engine answer accounted for, capped at
50; `references` ends with the section, `rename`/`remove_port`/
`add_port` warn with it; `unresolved_mentions` in the JSON; opentitan
cost recorded — done 2026-09-23 (dev)
- [x] descriptions and `instructions`: `hierarchy` leads with "who
instantiates a module", `references` points a module name at
`hierarchy up`; every description trimmed; `tools/list` 30 221 B →
17 981 B (≤ 18 kB, pinned by a wire test) — done 2026-09-23 (dev)
- [x] `add_port` `after`: the port placed after a named one in its line's
layout, each named connection after `.after(…)`; verified against the
engine's appending edit (`src/tools/place.rs`) — done 2026-09-23 (dev)
- [x] stale `index-cache-mcp.*.tmp` swept before the own store is written;
M6 QA's ignored test un-ignored — done 2026-09-23 (dev)
- [x] wire tests: mentions on `references` and `rename`, `after` byte-exact
on an `aes_core`-shaped fixture, catalogue size, sweep — done
2026-09-23 (dev)
- [x] QA: attack the mentions scanner (false positives and misses) and the
`after` verifier; verdict
### Round 2 → lane feedback-2 (`docs/features/mcp-feedback-2`)
- [x] paging header: every paged answer opens `N <noun>` or
`N <noun> (showing a–b)`; `shown` in the JSON; `DEFAULT_LIMIT` 500;
`hierarchy up` from one root counts instantiations (`render.rs`,
the seven paging tools) — done 2026-09-23 (dev)
- [x] `in` path glob (`*`, `**`, `?`, root-relative, before paging) on
`list_units`, `search_symbols`, `references`, `hierarchy`,
`diagnostics`, `defines`; ``0 <noun> (none match `in`)``
(`read.rs::path_match`) — done 2026-09-23 (dev)
- [x] post-edit line `check: diagnostics on …` (`check after writing:` on a
dry run) on `rename`, `add_port`, `remove_port`, `expand_wildcard`,
`extract_module`, `inline_module` (`edit.rs::with_check`) — done
2026-09-23 (dev)
- [x] `INSTRUCTIONS` names `in` (896 characters); catalogue 17 993 B
(≤ 18 000) — done 2026-09-23 (dev)
- [x] wire tests (header cut and whole per tool, `in` per tool with `**`,
`?`, no-match and an escaped name, the check line); fixture
`tests/fixtures/paths/` — done 2026-09-23 (dev)
- [x] QA: attack the path matcher, the "none match" rule and the
`hierarchy` counting; verdict — PASS 2026-09-23 (QA,
`tests/qa_f2.rs`, 14 tests; four low notes in the QA log)
### Round 3 → lane feedback-3 (`docs/features/mcp-feedback-3`)
- [x] `unit_interface`: the instantiation template opt-in (`template`,
default false; text and JSON); `parameters (N):` / `ports (N):`
headers — done 2026-09-23 (dev)
- [x] `hierarchy`: the `#( … )` overrides on the text line opt-in
(`overrides`, default false); the JSON keeps them — done 2026-09-23
(dev)
- [x] `INSTRUCTIONS` names `overrides: true` (896 characters; `template:
true` did not fit); catalogue 17 943 B (≤ 18 000; `dry_run`'s
description trimmed in `edit.rs`, flagged) — done 2026-09-23 (dev)
- [x] wire tests for both defaults and both opt-ins; old pins moved to the
opt-in; measured on the eval clone (`unit_interface prim_fifo_sync`
596 B vs 999 B; `hierarchy up … in ip/**/rtl/*.sv` 22 163 B vs
64 783 B) — done 2026-09-23 (dev)
- [x] QA: attack both flags (defaults, `false`, wrong types, packages,
recursive/noted lines, JSON equality); verdict — PASS 2026-09-23 (QA;
`tests/qa_f3.rs`, 7 tests; differential vs the c2e42b8 binary)
- [x] re-measure census task d (and a, which now needs `overrides: true`)
— done 2026-09-23 as round 3b (d 96k, −10 % vs base; a 111k, the
opt-in was not discovered), written up in `mcp_analysis.md` (aba39e5)
## M7. The lean catalogue (0.58; PLAN §10 — owner's steer 2026-09-23)
Nine tools, the model-visible catalogue under 3 500 bytes, instructions
under 400, short answers, no dry_run/paging, edits told to be trusted.
Feature README `docs/features/mcp-lean-catalogue`. One dev (Opus), one QA
(Opus), on trunk.
- [x] registry: `TOOLS` holds exactly `hierarchy, find, outline, read,
check, rename, port, edit_item, format` in that order; `title` and
`structuredContent` removed from the wire (`Answer` is text only);
`Param.description` gone; `wire.rs` pins the names, the order, the
byte budgets (≤ 3 500 model-visible, ≤ 400 instructions) and that no
schema names `dry_run`, `limit`, `offset`, `in`, `template`,
`overrides`, `force`
- [x] `hierarchy`: no root → counts line + top modules; down = instance
tree with instantiation `file:line`; `up`; `peek`; cap 300;
unknown-root refusal with near matches; opentitan instance set
identical to the old tool (test against `tests/opentitan.rs` truth)
- [x] `find`: declarations + `refs` uses grouped one file per line +
`unresolved:`; macros found; near-match refusal
- [x] `outline` (`file` xor `unit`), `read` (design-wide lookup, ambiguity
refusal), `check` (`ok` when clean; old `diagnostics` line set
preserved on the fixtures)
- [x] `rename` (name-based, `file` disambiguates), `port` (add xor remove),
`edit_item` (four ops, the M4 verifier unchanged, `attacks.rs` green
unchanged), `format` (path or glob, `fix`)
- [x] instructions ≤ 400 bytes per PLAN §10.3; resources render through
the new renderers
- [x] tests: the old suites that exercise dropped tools are ported to the
surviving tool or deleted with a line in the README saying which;
every kept invariant (verifier attacks, all-or-nothing writes, roots,
freshness, cache read-only) keeps its test
- [x] docs: feature README; `docs/site/.../guides/agents.md` table
regenerated by `mcp_smoke.js --tool-table` (+ the promises paragraph:
no dry_run); extension README/CHANGELOG; `CHANGELOG.md` 0.58.0 notes
(unreleased); `docs/topo.md` §2.8 rows; PLAN §4.3/§4.5 marked
superseded by §10
- [x] QA: attack the byte budget (a description that grows), the caps, the
ambiguity refusals, `peek` on a multi-line instantiation with
comments, `port add` after a non-existent port, `edit_item delete`
of a used item, `format` with a glob that matches nothing; differential
`hierarchy`/`check` against the 0.57.0 binary on the fixtures and the
eval clone
- [x] census round 4 (lead): tasks a–d on the lean binary (`bin/lucisv-mcp-r5`),
base arm reused from round 3; written up in `mcp_analysis.md` — done
2026-09-24 (9242594): 6/6 correct incl. one Opus run; a −1 %, d parity
over two runs, b +10 %, c +9 % vs the base re-run
- [x] release 0.58.0 when round 4 meets PLAN §10.5 — tagged 2026-09-24
(a −1 %, d parity, b +10 %, c +9 % vs the base re-run; 6/6 correct);
gates: 4 922 tests / 0 failed, corpus 814/820
## M8. Read-only mode (0.59; PLAN §11 — owner's request 2026-09-29)
`lucisv-mcp --read-only`: five tools, ≤ 1 800 model-visible bytes,
instructions ≤ 300, never writes inside a root; full mode unchanged.
Feature README `docs/features/mcp-read-only`. One dev (Opus), one QA
(Opus), on trunk.
- [x] server: `--read-only` parsed, in the usage line; the registry
filtered by mode (`tools/list`, `tools/call`); read-only
instructions; the unknown-tool message for the four edit tools
- [x] tests (`tests/wire.rs` or a new `tests/read_only.rs`): names and
order, both budgets, full mode unchanged byte for byte, every
full-catalogue tool name called in read-only mode leaves the tree
untouched (sizes, mtimes, names)
- [x] extension: `lucisv.mcp.mode` setting, label, args, change event,
copy-config (`lucisv-ro` key, `--read-only`), node tests;
`mcp_smoke.js --read-only`; `tools/release.sh` runs both smokes
- [x] docs: feature README; Agents guide (a "Read-only mode" section, the
table's `writes` column already tells the five); extension
README/CHANGELOG; `CHANGELOG.md` 0.59.0 (unreleased);
`docs/topo.md` §2.8; `tools/RELEASING.md`; manual-acceptance rows
- [x] QA: attack the no-write promise (every edit tool name, resources,
malformed calls, a call racing a mode it does not have), the budgets,
full-mode identity against the 0.58.0 binary, the extension tests
- [x] census round 5 (lead): tasks a and d on `--read-only` — done
2026-09-29 (74c5631): 7 runs, all correct; with same-day base controls
a +8 %, d −8 % (parity); found and fixed the `peek` cap defect
(`hierarchy` caps at 300 instances, 100 with `peek`)
- [x] release 0.59.0 — tagged 2026-09-29; gates: clippy -D warnings, fmt,
72 suites + 6 doc suites (4 937 passed, 0 failed), corpus 814/820,
node tests 6/6. The first suite run stalled 25 min in the vlog_linter
doc-test and was cut by the guard; the doc-tests passed in under a
minute as their own gate
## 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`.
+4864 -32
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,
+127 -26
View File
@@ -27,8 +27,9 @@ use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use lucisv_core::atomic::write_atomic;
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::Discovery;
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
@@ -84,15 +85,21 @@ fn run(opts: &Options) -> ExitCode {
/// `lucisv check`: the linter over the same file set the formatter would take.
fn run_check(opts: &Options) -> ExitCode {
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// Before any rule is selected and before any path is gathered: the rule
// reference is a property of the build, not of a run over files.
if opts.rules_doc {
print!("{}", vlog_linter::rules_markdown());
return ExitCode::SUCCESS;
}
// The command line's own names are checked before anything is walked, so
// a typo'd `--select` fails in milliseconds rather than after the scan.
// A `lucisv.toml`'s names are checked per file below, where they are read.
if let Err(e) = vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
eprintln!("error: {e}");
return ExitCode::from(2);
}
if opts.is_stdin() {
let config = match stdin_config(opts) {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -104,7 +111,34 @@ fn run_check(opts: &Options) -> ExitCode {
eprintln!("error: reading stdin: {e}");
return ExitCode::from(2);
}
return lint::check_stdin(opts, &src, &config, &rules);
// A stdin buffer is one text with nothing around it: there is no
// census to build and no other file to ask about, so the rules that
// need a project stay off. `--select` still reaches them.
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it exactly as `[lint] select` does.
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
Ok(external) => external,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -113,12 +147,18 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
};
lint::check_files(opts, &jobs, &rules)
match lint::plan(opts, jobs) {
Ok(plan) => lint::check_files(opts, &plan),
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(2)
}
}
}
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let config = match stdin_config(opts) {
let (config, _file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -174,11 +214,11 @@ fn run_files(opts: &Options) -> ExitCode {
// The cache is only read here; entries ride back with the results and
// are recorded serially below, so nothing is shared mutably.
let results: Vec<FileResult> =
jobs.par_iter().map(|(file, config)| process_file(file, config, opts, &cache)).collect();
jobs.par_iter().map(|(file, config, _)| process_file(file, config, opts, &cache)).collect();
let (mut changed, mut unchanged, mut errors, mut cached) = (0usize, 0usize, 0usize, 0usize);
for (index, result) in results.into_iter().enumerate() {
let (file, config) = &jobs[index];
let (file, config, _) = &jobs[index];
if let Some(content) = result.clean {
cache.record(file, entry_for(content, config));
}
@@ -277,7 +317,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
} else if opts.check {
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
} else if let Err(e) = std::fs::write(file, &out) {
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
} else {
// The bytes now on disk are formatted, so they are what the cache
@@ -293,7 +333,12 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
/// the key, not the config file that produced them, so identical settings
/// from different `lucisv.toml` files share entries.
fn entry_for(content: u64, config: &Config) -> Entry {
Entry { content, line_length: config.max_width, indent: config.indent_width }
Entry {
content,
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
}
}
/// Builds rayon's global pool. Worker stacks are sized for the parser's
@@ -313,7 +358,7 @@ fn build_pool(opts: &Options) -> Result<(), String> {
/// filelists name (exact paths, filtered by neither — they were named).
/// Every config file is read here, before anything is written, so a broken
/// one aborts the whole run instead of leaving it half applied.
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String> {
let mut discovery = Discovery::new(!opts.no_config);
let mut files = Vec::new();
for input in &opts.inputs {
@@ -326,7 +371,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
return Err(format!("--lines needs a file, not a directory: {input}"));
}
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
// The walk's own warnings — an unreadable directory, a source file
// that is only a broken link — go to stderr as they are found, before
// the report and exactly as a filelist's do. A warning is not a
// failure: the exit code is the formatting's alone.
let mut warn = |w| eprintln!("warning: {w}");
collect_files(input, &exclude, !opts.no_gitignore, &mut files, &mut warn)?;
}
// Filelists come after the command line's own inputs, in flag order: they
// add files, they never replace or reorder what was named directly.
@@ -337,8 +387,13 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
}
let mut jobs = Vec::with_capacity(files.len());
for file in files {
let config = opts.config_with(&discovery.for_file(&file)?);
jobs.push((file, config));
// The whole `FileConfig` rides along, not just the formatter settings
// it resolves to: `lucisv check` needs its `[lint]` keys too, and
// discovering them a second time would read every config file twice
// and could answer differently if one changed underneath the run.
let file_config = discovery.for_file(&file)?;
let config = opts.config_with(&file_config);
jobs.push((file, config, file_config));
}
Ok(jobs)
}
@@ -370,13 +425,25 @@ fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut seen = HashSet::new();
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect()
}
/// The key two spellings of one file share: the file's canonical path when it
/// is there, and the lexical fold when it is not.
///
/// Canonical means symlinks resolved, which is the only way to see that
/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one
/// target otherwise, each rewriting what the other just wrote. A path with no
/// file behind it has no canonical form, and the lexical fold is then the
/// best two names for it can be compared by. Neither is ever the path lucisv
/// reports: that stays the first spelling seen.
fn identity(cwd: &Path, path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are
/// deliberately left unresolved, so this is only ever a dedup key and never
/// the path lucisv reports.
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
/// answers for paths that do not exist, where there is nothing to resolve.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
@@ -394,13 +461,16 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// The settings for a buffer piped in on stdin: discovery anchors on
/// `--stdin-filename`'s directory when given, else on the current one.
fn stdin_config(opts: &Options) -> Result<Config, String> {
/// The formatter config a stdin buffer is served with, and the `lucisv.toml`
/// it came from — the linter needs the file's own `[lint.<rule>]` entries,
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
Ok(opts.config_with(&file))
Ok((opts.config_with(&file), file))
}
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
@@ -554,6 +624,37 @@ mod tests {
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
}
#[cfg(unix)]
#[test]
fn dedup_folds_a_symlink_onto_the_file_it_points_at() {
// A directory walk lists `b.sv` as a file of its own; lexically the
// two names share nothing, and two workers would rewrite one file.
let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let real = dir.join("a.sv");
let link = dir.join("b.sv");
std::fs::write(&real, "module m;\nendmodule\n").expect("seed");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real));
// Whichever spelling comes first is the one kept and reported.
assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link));
// And a `..` detour through the same link is still the same file.
std::fs::create_dir(dir.join("sub")).expect("sub dir");
let detour = dir.join("sub/../b.sv");
assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real));
// A file that is not there has no canonical path: the key is lexical,
// which still folds `.` and `..`, and two missing files stay two.
let gone = dir.join("gone.sv");
let same = dir.join("./sub/../gone.sv");
let other = dir.join("other.sv");
assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
+703 -7
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");
@@ -662,7 +713,7 @@ fn a_broken_config_exits_2_before_writing_anything() {
for (contents, expected) in [
("indent = 99\n", "between 1 and 8"),
("line-length = wide\n", "expects an integer"),
("[tool.lucisv]\nindent = 2\n", "tables"),
("[tool.lucisv]\nindent = 2\n", "unknown table"),
("exclude = [\n \"a\",\n]\n", "multi-line arrays are unsupported"),
] {
dir.write("lucisv.toml", contents);
@@ -753,7 +804,9 @@ fn check_reports_violations_and_exits_1() {
let out = run(&["check", &path]);
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
let text = stdout(&out);
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
// `FILE:LINE:COL: severity: message [rule]` — the severity word is part
// of the line since §33.0, and both of these are style findings.
assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}");
assert!(text.contains("[no-tabs]"), "{text}");
assert!(text.contains("[module-filename]"), "{text}");
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
@@ -797,6 +850,7 @@ fn check_json_is_one_array_with_positions_and_fixes() {
assert!(text.starts_with('['), "{text}");
assert!(text.trim_end().ends_with(']'), "{text}");
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
assert!(text.contains("\"severity\":\"style\""), "{text}");
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
assert!(text.contains("\"content\":\" \""), "{text}");
@@ -895,6 +949,30 @@ fn check_select_and_ignore_pick_the_rule_set() {
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
}
/// A severity word stands for its whole class wherever a rule name fits —
/// §33.0's headline for the command line.
#[test]
fn check_select_and_ignore_accept_a_severity_word() {
let dir = TempDir::new("check-severity");
// `reg` is an error-class finding, the tab and the name are style ones.
let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n");
let out = run(&["check", "--select", "error", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
let text = stdout(&out);
assert_eq!(text.lines().count(), 1, "{text}");
assert!(text.contains(": error: "), "{text}");
assert!(text.contains("[wire-reg-mixup]"), "{text}");
let out = run(&["check", "--ignore", "style", &path]);
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out));
// Ignoring every class leaves nothing to report.
let out = run(&["check", "--ignore", "error,warning,style", &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
}
#[test]
fn check_honors_inline_waivers_and_reports_dead_ones() {
let dir = TempDir::new("check-waive");
@@ -908,6 +986,89 @@ fn check_honors_inline_waivers_and_reports_dead_ones() {
assert!(stdout(&out).contains("[unused-waiver]"), "{}", stdout(&out));
}
/// Two tabbed lines, one of which a waiver file's `--line` covers.
const TABBED: &str = "module foo;\n\twire a;\n\twire b;\nendmodule\n";
/// `--waiver-file`: the suppression, the flag repeated, and the dead directive
/// reported at the waiver file's own line. TODO §39.
#[test]
fn check_reads_external_waiver_files() {
let dir = TempDir::new("check-waiver-file");
let path = dir.write("foo.sv", TABBED);
let one = dir.write("one.waiver", "# just line 2\nwaive --rule=no-tabs --line=2\n");
let out = run(&["check", "--waiver-file", &one, &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
assert_eq!(stdout(&out).lines().count(), 1, "one tab left: {}", stdout(&out));
assert!(stdout(&out).contains("foo.sv:3:1"), "{}", stdout(&out));
// A second file adds to the first rather than replacing it, and both are
// then used, so neither is reported.
let two = dir.write("two.waiver", "waive --rule=no-tabs --line=3 --location=foo.sv\n");
let out = run(&["check", "--waiver-file", &one, "--waiver-file", &two, &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
// A directive that covered nothing is reported against the waiver file.
let dead = dir.write("dead.waiver", "waive --rule=no-tabs --location=elsewhere.sv\n");
let out = run(&["check", "--waiver-file", &dead, &path]);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.contains("dead.waiver:1:1: style: unused waiver for `no-tabs`"), "{text}");
assert!(text.contains("[unused-waiver]"), "{text}");
}
/// The `[lint] waivers` key, and that `--waiver-file` adds to it. TODO §39.
#[test]
fn check_reads_the_waiver_files_a_config_file_names() {
let dir = TempDir::new("check-waiver-toml");
let path = dir.write("rtl/foo.sv", TABBED);
dir.write("lucisv.toml", "[lint]\nwaivers = [ \"project.waiver\" ]\n");
dir.write("project.waiver", "waive --rule=no-tabs --line=2\n");
// Relative to the config file, not to the working directory.
let out = run_raw(&["check", "--no-cache", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("foo.sv:3:1"), "only line 3 survives: {}", stdout(&out));
let extra = dir.write("extra.waiver", "waive --rule=no-tabs --line=3\n");
let out = run_raw(&["check", "--no-cache", "--waiver-file", &extra, &path]);
assert_eq!(code(&out), 0, "the two lists add up: {}", stdout(&out));
// `--no-config` drops the config file's list with everything else in it.
let out = run_raw(&["check", "--no-cache", "--no-config", &path]);
assert_eq!(code(&out), 1);
assert_eq!(stdout(&out).lines().count(), 2, "both tabs are back: {}", stdout(&out));
}
/// A waiver file that cannot be read, or that has a line that does not parse,
/// fails the run with `<file>:<line>: message` and exit 2. TODO §39.
#[test]
fn a_broken_waiver_file_fails_the_run() {
let dir = TempDir::new("check-waiver-bad");
let path = dir.write("foo.sv", TABBED);
let out = run(&["check", "--waiver-file", &dir.write("x.waiver", "hush\n"), &path]);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("x.waiver:1: expected a `waive` directive"), "{}", stderr(&out));
let bad = dir.write("y.waiver", "# fine\nwaive --rule=no-such-rule\n");
let out = run(&["check", "--waiver-file", &bad, &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("y.waiver:2: unknown rule"), "{}", stderr(&out));
let regexy = dir.write("z.waiver", "waive --rule=no-tabs --location=.*foo.sv\n");
let out = run(&["check", "--waiver-file", &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);
@@ -1106,16 +1267,18 @@ impl TempDir {
}
}
/// One hand-written cache line, for the tests that forge entries.
/// One hand-written cache line, for the tests that forge entries. The
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
fn cache_line(
path: &str,
content: &str,
line_length: usize,
indent: usize,
uvm: bool,
version: &str,
) -> String {
let hash = lucisv_core::cache::content_hash(content.as_bytes());
format!("{hash:016x}\t{line_length}\t{indent}\t{version}\t{path}\n")
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
}
#[test]
@@ -1202,7 +1365,8 @@ fn a_hit_skips_the_work_entirely() {
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 2, "without an entry this file is an error");
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, VERSION)).unwrap();
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, false, VERSION))
.unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "a hit does no work at all: {}", stderr(&out));
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
@@ -1227,6 +1391,65 @@ fn a_config_file_change_invalidates_the_entry_too() {
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
}
/// A UVM class whose layout depends on `[format] uvm-utils-indent`: with the
/// option on, the `` `uvm_field_* `` macro gains a level. Written here as the
/// formatter leaves it with the option *off*.
const UVM_CLASS: &str = "class c extends uvm_object;\n `uvm_object_utils_begin(c)\n \
`uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
#[test]
fn changing_uvm_utils_indent_invalidates_the_entry() {
let dir = TempDir::new("cache-uvm");
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
let path = dir.write("a.sv", UVM_CLASS);
let cache = dir.cache();
// Clean with the option off, and that verdict is cached.
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
let flat = dir.read("a.sv");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
// Turning the option on must not hit the entry the option-off run left.
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "uvm-utils-indent is part of the key: {}", stderr(&out));
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
// Format under the option on, cache *that*, then flip back off.
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
assert_ne!(dir.read("a.sv"), flat, "the option really does change the output");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "and the other direction too: {}", stderr(&out));
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
}
#[test]
fn a_store_written_before_the_option_joined_the_key_is_rebuilt() {
let dir = TempDir::new("cache-oldshape");
let path = dir.write("a.sv", FORMATTED);
let cache = dir.cache();
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
// The five-field line lucisv wrote before `uvm-utils-indent` was in the
// key. Not corruption: the line is dropped on its own and the run
// rebuilds the store in the current shape.
let hash = lucisv_core::cache::content_hash(FORMATTED.as_bytes());
std::fs::write(dir.cache_file(), format!("{hash:016x}\t100\t2\t{VERSION}\t{path}\n")).unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "an older store is never an error: {}", stderr(&out));
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert!(stderr(&out).contains("1 file from cache"), "the store was rebuilt: {}", stderr(&out));
}
#[test]
fn an_entry_from_another_lucisv_version_is_ignored() {
let dir = TempDir::new("cache-version");
@@ -1236,13 +1459,14 @@ fn an_entry_from_another_lucisv_version_is_ignored() {
// A forged entry claiming this unformatted file is clean. With this
// version's stamp it is believed…
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, VERSION)).unwrap();
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, VERSION))
.unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "the forged entry proves entries are really read");
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
// …and with any other version's stamp it is not.
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, "0.0.0-other"))
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, "0.0.0-other"))
.unwrap();
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "another version's entry must not be trusted: {}", stderr(&out));
@@ -1727,3 +1951,475 @@ fn help_documents_the_filelist_flag() {
assert!(text.contains("-f <FILELIST>"), "{text}");
assert!(text.contains("read by lucisv-server only"), "the toml key stays server-only: {text}");
}
// ----------------------------------------------------------------------
// The semantic rules and the project census (semantic-lints-on, 2026-09-02)
// ----------------------------------------------------------------------
/// A module whose `dbg_probe` only a *second* file reads, hierarchically.
const DUT: &str = "module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n";
const TB: &str = "module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n";
/// The round's headline: over a project the semantic rules run by default,
/// and the file that reads `d.dbg_probe` is what keeps `dbg_probe` quiet.
/// `dead`, which nothing anywhere writes down twice, is still reported.
#[test]
fn a_mention_in_another_file_silences_unused_signal_over_a_project() {
let dir = TempDir::new("census");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(text.contains("`dead` is declared but never used"), "{text}");
assert!(!text.contains("dbg_probe"), "the other file reads it: {text}");
assert_eq!(code(&out), 1);
}
/// One file is not a project: there is nothing to ask, so the rules that
/// need a workspace stay off and the run is exactly v0.29.0's.
#[test]
fn a_single_file_run_leaves_the_semantic_rules_off() {
let dir = TempDir::new("alone");
let dut = dir.write("dut.sv", DUT);
let out = run(&["check", &dut]);
assert_eq!(stdout(&out), "");
assert_eq!(code(&out), 0);
// ... and naming the rule still runs it, oracle or no oracle.
let named = run(&["check", &dut, "--select", "unused-signal"]);
let text = stdout(&named);
assert!(text.contains("dbg_probe"), "{text}");
assert!(text.contains("dead"), "{text}");
assert_eq!(code(&named), 1);
}
/// A stdin buffer has no project either, and no file to build one from.
#[test]
fn a_stdin_buffer_leaves_the_semantic_rules_off() {
let out = run_with_stdin(&["check", "-"], DUT);
assert_eq!(stdout(&out), "");
assert_eq!(code(&out), 0);
let named = run_with_stdin(&["check", "-", "--select", "unused-signal"], DUT);
assert!(stdout(&named).contains("dbg_probe"), "{}", stdout(&named));
}
/// The off switch a default-on rule owes its users: `[lint] ignore` in the
/// `lucisv.toml` governing the files.
#[test]
fn a_lint_table_in_the_config_turns_a_rule_off() {
let dir = TempDir::new("lint-table");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the config silenced the rule");
assert_eq!(code(&out), 0);
}
/// `[lint] select` replaces the default set, exactly as `--select` does.
#[test]
fn a_lint_table_can_select_instead_of_ignore() {
let dir = TempDir::new("lint-select");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nselect = [\"unused-signal\"]\n");
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(text.contains("`dead` is declared but never used"), "{text}");
assert!(!text.contains("dbg_probe"), "{text}");
}
/// Precedence, key by key: the command line beats the config file, and a key
/// the command line does not mention stays the config file's.
#[test]
fn the_command_line_beats_the_lint_table() {
let dir = TempDir::new("lint-precedence");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
// `--ignore` replaces the config's ignore list, so `unused-signal` is back.
let out = run(&["check", &dir.root(), "--ignore", "no-tabs"]);
assert!(stdout(&out).contains("`dead` is declared but never used"), "{}", stdout(&out));
// `--select` replaces the default set; the config's ignore still applies.
let selected = run(&["check", &dir.root(), "--select", "unused-signal,no-tabs"]);
assert_eq!(stdout(&selected), "", "the config's ignore survives a CLI select");
}
/// An unknown rule name in a config file fails the run and says what is
/// known — the same answer a typo'd `--select` gets, named by file.
#[test]
fn an_unknown_rule_in_the_lint_table_is_an_error() {
let dir = TempDir::new("lint-unknown");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"no-such-rule\"]\n");
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains("unknown rule: no-such-rule"), "{text}");
assert!(text.contains("unused-signal"), "the error lists what is known: {text}");
assert_eq!(code(&out), 2);
}
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
/// with it — §34.0's headline claim, end to end through the real binary.
#[test]
fn a_per_rule_lint_table_changes_the_verdict() {
let dir = TempDir::new("lint-per-rule");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
dir.write("m.sv", &wide);
let out = run(&["check", &dir.root()]);
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the option raised the limit");
assert_eq!(code(&out), 0);
}
/// A bad entry fails the run naming the config file and the line, which is
/// what tells a user *where* to fix it.
#[test]
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
let dir = TempDir::new("lint-bad-option");
dir.write("m.sv", "module m;\nendmodule\n");
for (config, wanted) in [
("[lint.line-length]\nlength = 10\n", "must be between"),
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
// An escape from another dialect must be refused rather than read
// as a literal, which would silently judge the wrong names (QA,
// 2026-09-04).
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
] {
dir.write("lucisv.toml", config);
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains(wanted), "{config:?}: {text}");
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
assert_eq!(code(&out), 2, "{config:?}");
}
// Every one of them names the rule as well as the option, so an error
// read out of a CI log stands on its own.
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
let text = stderr(&run(&["check", &dir.root()]));
assert!(text.contains("rule `line-length`"), "{text}");
assert!(text.contains("`length` must be between"), "{text}");
}
/// The width `line-length` holds a file to is the width the formatter is
/// configured with, so the two halves of lucisv cannot disagree.
#[test]
fn line_length_follows_the_formatters_width() {
let dir = TempDir::new("lint-width");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
dir.write("m.sv", &wide);
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
dir.write("lucisv.toml", "line-length = 80\n");
let from_config = run(&["check", &dir.root()]);
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
}
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
#[test]
fn a_stdin_buffer_reads_the_rule_options_too() {
let dir = TempDir::new("lint-stdin-options");
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
/// RTL signal only inside a macro argument — `` `uvm_info(..., $sformatf("%b",
/// dut.sig), ...) ``, the commonest VPI-probe shape there is — must silence
/// `unused-signal` for that signal. The lexer hands the whole invocation over
/// as one token, so this works only because the census splits it.
#[test]
fn a_signal_named_only_inside_a_macro_argument_is_not_reported_unused() {
let dir = TempDir::new("macroarg");
dir.write("dut.sv", DUT);
dir.write(
"tb.sv",
"module tb;\n dut u_dut ();\n initial begin\n\
\x20 `uvm_info(\"tb\", $sformatf(\"probe=%b\", u_dut.dbg_probe), UVM_LOW)\n\
\x20 end\nendmodule\n",
);
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(!text.contains("dbg_probe"), "the macro argument names it: {text}");
assert!(text.contains("`dead` is declared but never used"), "and `dead` still reports: {text}");
// The format string is a value: a signal called `probe` in another file
// must not be silenced by `"probe=%b"` here.
let other = TempDir::new("macroargstring");
other.write("a.sv", "module a;\n logic probe;\nendmodule\n");
other.write(
"b.sv",
"module b;\n initial `uvm_info(\"t\", $sformatf(\"probe=%b\", 1'b0), UVM_LOW)\nendmodule\n",
);
assert!(
stdout(&run(&["check", &other.root()])).contains("`probe` is declared but never used"),
"a string's contents are not mentions"
);
}
/// `lucisv check --rules-doc` prints the generated rule reference and nothing
/// else. Generated from the registry, so a rule added without documentation
/// still shows up here — which is the whole point of the flag.
#[test]
fn rules_doc_prints_the_generated_reference() {
let out = run(&["check", "--rules-doc"]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert_eq!(text.lines().next(), Some("# lucisv lint rules"), "{text}");
for rule in vlog_linter::all_rules() {
let heading = format!("\n## {}\n", rule.name());
assert_eq!(
text.matches(&heading).count(),
1,
"`{}` wants exactly one section in the reference",
rule.name()
);
}
// The flag is the tool now, so it agrees with the library by construction.
assert_eq!(text, vlog_linter::rules_markdown());
}
/// The flag lints nothing, so a path beside it is a command line that means
/// two different things — refused rather than silently ignored.
#[test]
fn rules_doc_refuses_files_and_belongs_to_check() {
let dir = TempDir::new("rulesdoc");
let file = dir.write("m.sv", FORMATTED);
let out = run(&["check", "--rules-doc", &file]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("--rules-doc takes no files"), "{}", stderr(&out));
let out = run(&["format", "--rules-doc"]);
assert_eq!(code(&out), 2);
assert!(
stderr(&out).contains("--rules-doc is only valid for `lucisv check`"),
"{}",
stderr(&out)
);
}
// --- the walk's own warnings (docs/features/small-items-4/README.md) -------
/// A tree with the two things the walk can only warn about: a directory it
/// cannot read, and a source file that is only a broken link.
#[cfg(unix)]
fn unwalkable_tree(tag: &str) -> TempDir {
use std::os::unix::fs::{symlink, PermissionsExt};
let dir = TempDir::new(tag);
dir.write("a.sv", UNFORMATTED);
dir.write("z/late.sv", UNFORMATTED);
dir.write("locked/hidden.sv", UNFORMATTED);
symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
dir
}
#[cfg(unix)]
fn lock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
}
#[cfg(unix)]
fn unlock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
let _ =
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
// The finding TODO §45.2 closes: one permission-denied directory used to
// propagate `read_dir`'s error and fail the whole run.
let dir = unwalkable_tree("walk-warn");
let out = run(&[&dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "a warning is not a failure: {}", stderr(&out));
let said = stderr(&out);
assert_eq!(said.matches("warning: ").count(), 2, "{said}");
assert!(said.contains("locked"), "{said}");
assert!(said.contains("gone.sv: broken symbolic link"), "{said}");
assert_eq!(dir.read("a.sv"), FORMATTED, "the other files were formatted");
assert_eq!(dir.read("z/late.sv"), FORMATTED, "including the ones sorted after it");
}
#[test]
#[cfg(unix)]
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
let dir = unwalkable_tree("walk-warn-check");
let out = run(&["--check", &dir.root()]);
unlock(&dir);
// `--check` answers on formatting alone: two files would be reformatted.
assert_eq!(code(&out), 1, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
assert!(!stdout(&out).contains("warning"), "warnings stay off stdout: {}", stdout(&out));
// And with nothing left to reformat the run is clean, warnings and all.
dir.write("a.sv", FORMATTED);
dir.write("z/late.sv", FORMATTED);
lock(&dir);
let out = run(&["--check", &dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
// The walk drops the link; a path the user typed is not walked at all, so
// "no such file or directory" is still what naming one gets.
let dir = TempDir::new("walk-warn-named");
std::os::unix::fs::symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
let named = dir.path.join("gone.sv").to_string_lossy().into_owned();
let out = run(&[&named]);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
}
// ----------------------------------------------------------------------
// The package half of the census and `unused-import` (perf5-p3, 2026-09-07)
// ----------------------------------------------------------------------
/// A package with two exported names, and the two importers the rule has to
/// tell apart.
const PKG: &str = "package p_pkg;\n localparam int A = 1;\n localparam int B = 2;\nendpackage\n";
const USES_PKG: &str = "module uses_pkg;\n import p_pkg::*;\n localparam int C = A;\nendmodule\n";
const IGNORES_PKG: &str =
"module ignores_pkg;\n import p_pkg::*;\n localparam int C = 1;\nendmodule\n";
/// The style selection the rule lives in — `unused-import` is `Severity::Style`
/// and so is off in a default `check`.
const ALL_STYLE: [&str; 2] = ["--select", "error,warning,style"];
/// The headline: over a project, an import nothing in its file uses is
/// reported, and one the file does use is not — and it is the *package
/// census* that makes the difference, because the rule can only judge an
/// import whose package the run can answer for.
#[test]
fn an_unused_package_import_is_reported_over_a_project() {
let dir = TempDir::new("pkg-census");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write("ignores_pkg.sv", IGNORES_PKG);
let out = run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]);
let text = stdout(&out);
assert!(text.contains("unused-import"), "{text}");
assert!(text.contains("ignores_pkg.sv"), "{text}");
assert!(
!text.lines().any(|line| line.contains("uses_pkg.sv") && line.contains("unused-import")),
"the file that reads `A` keeps its import: {text}"
);
assert_eq!(code(&out), 1);
}
/// `unused-import` is a style rule, so a default `check` neither reports it
/// nor is changed by the presence of a package in the run.
#[test]
fn a_default_check_says_nothing_about_imports() {
let dir = TempDir::new("pkg-default");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write("ignores_pkg.sv", IGNORES_PKG);
let out = run(&["check", &dir.root()]);
assert!(!stdout(&out).contains("unused-import"), "{}", stdout(&out));
}
/// A package the run does not contain is a package the run cannot answer
/// for, and the rule is silent about every import of it. This is the
/// conservative direction the whole feature is built around: an accusation
/// needs a known export list.
#[test]
fn an_import_of_a_package_outside_the_run_is_not_reported() {
let dir = TempDir::new("pkg-unknown");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write(
"stranger.sv",
"module stranger;\n import elsewhere_pkg::*;\n localparam int C = 1;\nendmodule\n",
);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("elsewhere_pkg"), "an unknown package is unknowable: {text}");
}
/// A package that re-exports from another one answers `None`: only a whole
/// project index settles what a re-export chain lets through, and the CLI's
/// one-file census will not guess. Every import of it goes quiet.
#[test]
fn an_import_of_a_re_exporting_package_is_not_reported() {
let dir = TempDir::new("pkg-reexport");
dir.write("p_pkg.sv", PKG);
dir.write(
"r_pkg.sv",
"package r_pkg;\n import p_pkg::*;\n export p_pkg::*;\n localparam int D = 1;\n\
endpackage\n",
);
dir.write(
"ignores_r.sv",
"module ignores_r;\n import r_pkg::*;\n localparam int C = 1;\nendmodule\n",
);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("r_pkg"), "a re-export chain is unknowable: {text}");
}
/// Two files declaring one package name is a name the run cannot answer for,
/// whatever the two say — `Census::of`'s merge turns the second contribution
/// into `None`, and the rule goes quiet about it.
#[test]
fn an_import_of_a_package_two_files_declare_is_not_reported() {
let dir = TempDir::new("pkg-duplicate");
dir.write("p_pkg.sv", PKG);
dir.write("p_pkg_copy.sv", "package p_pkg;\n localparam int Z = 9;\nendpackage\n");
dir.write("ignores_pkg.sv", IGNORES_PKG);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("unused-import"), "a duplicate package is unknowable: {text}");
}
/// The gate is a claim about *cost*, not about answers, so the answers get
/// their own end-to-end pin: a run whose only package file is surrounded by
/// files holding the word `package` in strings and comments reports exactly
/// what a run without those files reports.
#[test]
fn text_that_merely_says_package_changes_no_finding() {
let bare = TempDir::new("pkg-bare");
bare.write("p_pkg.sv", PKG);
bare.write("ignores_pkg.sv", IGNORES_PKG);
let plain = stdout(&run(&["check", &bare.root(), ALL_STYLE[0], ALL_STYLE[1]]));
let noisy = TempDir::new("pkg-noisy");
noisy.write("p_pkg.sv", PKG);
noisy.write("ignores_pkg.sv", IGNORES_PKG);
noisy.write(
"talker.sv",
"// package q_pkg; endpackage\n\
module talker;\n initial $display(\"package q_pkg; endpackage\");\nendmodule\n",
);
let with_noise = stdout(&run(&["check", &noisy.root(), ALL_STYLE[0], ALL_STYLE[1]]));
for finding in plain.lines().filter(|line| line.contains("unused-import")) {
let tail = finding.rsplit('/').next().unwrap_or(finding);
assert!(with_noise.contains(tail), "{tail} lost: {with_noise}");
}
assert_eq!(
plain.matches("unused-import").count(),
with_noise.matches("unused-import").count(),
"{plain}\n---\n{with_noise}"
);
}
+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 }
+340
View File
@@ -0,0 +1,340 @@
//! 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 which files were written. There
//! is no dry run (PLAN §10): an edit is a file write the agent is told to
//! trust, so the verification happens here, before it. 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 vlog_refactor::{RefactorEdit, TextEdit};
use crate::project::Project;
/// 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>,
/// The engine's sentences about what it deliberately left alone.
pub warnings: Vec<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)
}
/// What a plan came to on disk: the root-relative files rewritten and
/// created, and those whose new text equals the old.
#[derive(Debug, Default)]
pub struct Written {
pub changed: Vec<String>,
pub created: Vec<String>,
pub unchanged: Vec<String>,
}
/// Check every target, then write every changed file, or nothing.
pub fn run(project: &Project, plan: &Plan) -> Result<Written, 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));
commit(&moved, |path| project.relative(path))?;
let mut written = Written::default();
for change in &plan.changes {
let file = project.relative(&change.path);
match (change.created, change.before == change.after) {
(true, _) => written.created.push(file),
(false, false) => written.changed.push(file),
(false, true) => written.unchanged.push(file),
}
}
written.changed.sort();
written.created.sort();
written.unchanged.sort();
Ok(written)
}
/// 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(())
}
#[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).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();
}
}
+223
View File
@@ -0,0 +1,223 @@
//! The index caches a startup reads instead of parsing (PLAN §6): the
//! language server's `index-cache`, **read only, never written**, and this
//! server's own `index-cache-mcp` beside it, in the same codec, written once
//! when the session ends.
//!
//! The codec is `lucisv_server::index_cache`'s, restated here because its
//! constants are private to that crate (Handshake MCP-14 in
//! `docs/features/mcp-cache-and-census/README.md`; a test pins the restated
//! header and line formats against that file's source text). A store is a
//! header line `lucisv-index-cache\t<CACHE_FORMAT>\t<FACTS_FORMAT>\t<version>`
//! and one record per line, `<content hash:016x>\t<encoded facts>\t<fnv of
//! the facts:016x>`. A record is used only for a file whose bytes hash to its
//! content hash, so it can only ever stand in for the parse of exactly those
//! bytes; a store from another build, a torn line or a line whose checksum
//! fails costs a parse and nothing else.
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use lucisv_core::cache::content_hash;
use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT};
/// The language server's store in the cache directory. Read, never written.
pub const EDITOR_STORE: &str = "index-cache";
/// This server's own store in the same directory.
pub const OWN_STORE: &str = "index-cache-mcp";
/// `lucisv_server::index_cache::CACHE_FORMAT`: the framing's version.
const CACHE_FORMAT: u32 = 2;
/// lucisv's version: another release may parse the same bytes into other
/// facts, so its store is not read.
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Which store a record came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
/// The language server's `index-cache`.
Editor,
/// This server's `index-cache-mcp`.
Own,
}
/// The records of both stores, still encoded, keyed by the path they
/// describe and the hash of the bytes they were read from.
#[derive(Default)]
pub struct Records {
held: HashMap<(PathBuf, u64), (Source, String)>,
}
/// How a startup used the stores.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Reuse {
/// Files whose record came from the language server's store.
pub editor: usize,
/// Files whose record came from this server's own store.
pub own: usize,
}
impl Reuse {
/// One more file taken from `source`.
pub fn count(&mut self, source: Source) {
match source {
Source::Editor => self.editor += 1,
Source::Own => self.own += 1,
}
}
}
impl Records {
/// Both stores in `dir`. A missing directory or store is a cold start,
/// silently (the editor may not have made the directory yet); a store
/// from another build is ignored whole, with one line on stderr.
pub fn load(dir: &Path) -> Records {
let mut records = Records::default();
// Own first, so a record both stores hold is credited to the editor.
records.read(&dir.join(OWN_STORE), Source::Own);
records.read(&dir.join(EDITOR_STORE), Source::Editor);
records
}
/// Read one store into the map.
fn read(&mut self, store: &Path, source: Source) {
let Ok(bytes) = fs::read(store) else { return };
let mut lines = store_lines(&bytes).into_iter();
match lines.next() {
None => return,
Some(first) if first == header().as_bytes() => {}
Some(_) => {
eprintln!(
"lucisv-mcp: ignoring the index cache {}: not written by lucisv {VERSION}",
store.display()
);
return;
}
}
for line in lines {
if let Some((path, content, facts)) = std::str::from_utf8(line).ok().and_then(parse) {
self.held.insert((path, content), (source, facts.to_string()));
}
}
}
/// The facts of `path` when its bytes hash to `content`, and where they
/// came from. A record that no longer decodes is a miss.
pub fn take(&mut self, path: &Path, content: u64) -> Option<(FileFacts, Source)> {
let (source, encoded) = self.held.remove(&(path.to_path_buf(), content))?;
let facts = FileFacts::decode(&encoded)?;
(facts.path() == path).then_some((facts, source))
}
}
/// Write this server's own store in `dir`: the header, then one record per
/// `(content hash, facts)`, in the order given. Atomic — a temporary file
/// renamed over the store — so a reader sees the old store or the new one.
/// Never touches [`EDITOR_STORE`].
pub fn write_own(dir: &Path, records: &[(u64, &FileFacts)]) -> io::Result<usize> {
fs::create_dir_all(dir)?;
// Self-ignoring, as the language server marks the directory: a cache
// path inside the project is a plausible thing to pass.
let ignore = dir.join(".gitignore");
if !ignore.exists() {
let _ = fs::write(&ignore, "*\n");
}
sweep_stale_temps(dir);
let mut text = header();
text.push('\n');
let mut written = 0;
for (content, facts) in records {
// A path that cannot be written on a line (not UTF-8, a tab) is
// simply not cached.
if let Some(encoded) = facts.encode() {
text.push_str(&line(*content, &encoded));
text.push('\n');
written += 1;
}
}
let tmp = dir.join(format!("{OWN_STORE}.{}.tmp", std::process::id()));
let written_through =
fs::write(&tmp, text).and_then(|()| fs::rename(&tmp, dir.join(OWN_STORE)));
if let Err(problem) = written_through {
let _ = fs::remove_file(&tmp);
return Err(problem);
}
Ok(written)
}
/// How old a temporary store file must be before a writer counts it as a
/// dead writer's: a live writer renames its own within a second or two.
const STALE_TEMP: Duration = Duration::from_secs(600);
/// Remove the `index-cache-mcp.<pid>.tmp` files in `dir` older than
/// [`STALE_TEMP`] — left by a writer killed between its write and its
/// rename (M6 QA finding 2). A younger one may be a concurrent writer's,
/// and is left alone; anything else in the directory is never touched.
fn sweep_stale_temps(dir: &Path) {
let Ok(entries) = fs::read_dir(dir) else { return };
let now = SystemTime::now();
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
let ours = name
.strip_prefix(OWN_STORE)
.and_then(|rest| rest.strip_prefix('.'))
.and_then(|rest| rest.strip_suffix(".tmp"))
.is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit()));
let modified = entry.metadata().and_then(|meta| meta.modified());
let stale =
modified.is_ok_and(|at| now.duration_since(at).is_ok_and(|age| age > STALE_TEMP));
if ours && stale && entry.file_type().is_ok_and(|kind| kind.is_file()) {
let _ = fs::remove_file(entry.path());
}
}
}
/// The first line of a store this build reads and writes.
fn header() -> String {
format!("lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t{VERSION}")
}
/// One record: the content hash, the encoded facts, their checksum.
fn line(content: u64, facts: &str) -> String {
format!("{content:016x}\t{facts}\t{:016x}", content_hash(facts.as_bytes()))
}
/// One record read back: its path, content hash and still-encoded facts.
/// `None` for anything but a whole record whose facts match their checksum —
/// which includes a torn last line.
fn parse(line: &str) -> Option<(PathBuf, u64, &str)> {
let (hash, rest) = line.split_once('\t')?;
let content = hex16(hash)?;
// No encoded field holds a raw tab, so the facts run to the last one.
let (facts, checksum) = rest.rsplit_once('\t')?;
if hex16(checksum)? != content_hash(facts.as_bytes()) {
return None;
}
Some((record_path(facts)?, content, facts))
}
/// A 16-digit hexadecimal field, exactly as wide as [`line`] writes it.
fn hex16(field: &str) -> Option<u64> {
if field.len() != 16 {
return None;
}
u64::from_str_radix(field, 16).ok()
}
/// The store's lines as bytes (a torn multi-byte character costs its own
/// line only), `\r` stripped as `str::lines` would.
fn store_lines(bytes: &[u8]) -> Vec<&[u8]> {
let body = bytes.strip_suffix(b"\n").unwrap_or(bytes);
if body.is_empty() {
return Vec::new();
}
body.split(|byte| *byte == b'\n').map(|line| line.strip_suffix(b"\r").unwrap_or(line)).collect()
}
#[cfg(test)]
mod tests;
+143
View File
@@ -0,0 +1,143 @@
//! The caches against the rebuild oracle: an index started from records is
//! the index a cold build over the same files makes
//! (`WorkspaceIndex::fingerprint`), and every record that is not exactly
//! right is a parse, not an answer.
use std::fs;
use std::path::{Path, PathBuf};
use super::*;
use crate::project::Project;
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("lucisv-mcp-cache-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("src")).unwrap();
fs::create_dir_all(dir.join("cache")).unwrap();
fs::canonicalize(dir).unwrap()
}
/// Three files that reach each other: a package, a module importing it, a
/// module instantiating that one through `.*`, and a macro.
fn design(dir: &Path) {
let src = dir.join("src");
fs::write(src.join("p.sv"), "package p; parameter int W = 4; endpackage\n").unwrap();
let leaf = "`define ONE 1'b1\nmodule leaf import p::*; (input logic [W-1:0] d);\nendmodule\n";
fs::write(src.join("leaf.sv"), leaf).unwrap();
let top = "module top(input logic [3:0] d);\n leaf u_leaf(.*);\nendmodule\n";
fs::write(src.join("top.sv"), top).unwrap();
}
fn cold(dir: &Path) -> String {
Project::open(vec![dir.join("src")], None).index().fingerprint()
}
fn warm(dir: &Path) -> Project {
Project::open_cached(vec![dir.join("src")], None, Some(dir.join("cache")))
}
/// A store in the language server's format, one record per file as its
/// parse finds it.
fn editor_store(dir: &Path) -> String {
let mut text = format!("{}\n", header());
let mut paths: Vec<PathBuf> =
fs::read_dir(dir.join("src")).unwrap().map(|e| e.unwrap().path()).collect();
paths.sort();
for path in paths {
let bytes = fs::read(&path).unwrap();
let facts = FileFacts::of(path.clone(), std::str::from_utf8(&bytes).unwrap());
text.push_str(&line(content_hash(&bytes), &facts.encode().unwrap()));
text.push('\n');
}
text
}
#[test]
fn the_codec_is_the_language_servers_own() {
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../lucisv_server/src/index_cache.rs");
let source = fs::read_to_string(source).unwrap();
for pinned in [
format!("const FILE: &str = \"{EDITOR_STORE}\";"),
format!("const CACHE_FORMAT: u32 = {CACHE_FORMAT};"),
"const VERSION: &str = env!(\"CARGO_PKG_VERSION\");".to_string(),
"format!(\"lucisv-index-cache\\t{CACHE_FORMAT}\\t{FACTS_FORMAT}\\t{VERSION}\")".to_string(),
"format!(\"{content:016x}\\t{facts}\\t{:016x}\", content_hash(facts.as_bytes()))"
.to_string(),
] {
assert!(source.contains(&pinned), "index_cache.rs no longer says {pinned}");
}
assert_eq!(header(), format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}"));
}
#[test]
fn a_warm_start_from_the_editors_store_is_the_cold_index() {
let dir = scratch("editor");
design(&dir);
fs::write(dir.join("cache").join(EDITOR_STORE), editor_store(&dir)).unwrap();
let project = warm(&dir);
assert_eq!(project.reuse(), Some(Reuse { editor: 3, own: 0 }));
assert_eq!(project.index().fingerprint(), cold(&dir));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_warm_start_from_its_own_store_is_the_cold_index_and_a_changed_file_is_parsed() {
let dir = scratch("own");
design(&dir);
let first = warm(&dir);
assert_eq!(first.reuse(), Some(Reuse::default()));
let (store, written) = first.save_cache().unwrap().unwrap();
assert_eq!((store, written), (dir.join("cache").join(OWN_STORE), 3));
assert!(!dir.join("cache").join(EDITOR_STORE).exists(), "the editor's store is never written");
let second = warm(&dir);
assert_eq!(second.reuse(), Some(Reuse { editor: 0, own: 3 }));
assert_eq!(second.index().fingerprint(), cold(&dir));
fs::write(dir.join("src/top.sv"), "module top2; leaf u_leaf(.d(4'b0)); endmodule\n").unwrap();
let third = warm(&dir);
assert_eq!(third.reuse(), Some(Reuse { editor: 0, own: 2 }));
assert_eq!(third.index().fingerprint(), cold(&dir));
assert_eq!(third.index().units("top2").len(), 1);
assert!(third.index().units("top").is_empty());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_torn_a_forged_and_a_foreign_record_are_each_a_parse() {
let dir = scratch("damaged");
design(&dir);
let good = editor_store(&dir);
let lines: Vec<&str> = good.lines().collect();
// Record 1 (leaf.sv): its hash still the file's, a macro renamed in its
// facts, its checksum left as it was.
assert!(lines[1].contains("/leaf.sv\t") && lines[1].contains("ONE"));
let forged = lines[1].replacen("ONE", "TWO", 1);
// Record 3 (top.sv): torn inside its facts, no newline.
let torn = &lines[3][..lines[3].len() / 2];
let store = format!("{}\n{forged}\n{}\n{torn}", lines[0], lines[2]);
fs::write(dir.join("cache").join(EDITOR_STORE), &store).unwrap();
let project = warm(&dir);
assert_eq!(project.reuse(), Some(Reuse { editor: 1, own: 0 }), "only p.sv is whole");
assert_eq!(project.index().fingerprint(), cold(&dir));
let foreign = good.replacen(VERSION, "0.0.0", 1);
fs::write(dir.join("cache").join(EDITOR_STORE), &foreign).unwrap();
assert_eq!(warm(&dir).reuse(), Some(Reuse::default()), "another version's store is not read");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_record_filed_under_another_path_or_hash_is_not_taken() {
let mut records = Records::default();
let facts = FileFacts::of(PathBuf::from("/a.sv"), "module a; endmodule\n");
let encoded = facts.encode().unwrap();
let record = line(7, &encoded);
let parsed = parse(&record).unwrap();
assert_eq!((parsed.0.as_path(), parsed.1), (Path::new("/a.sv"), 7));
records.held.insert((parsed.0, parsed.1), (Source::Editor, parsed.2.to_string()));
assert!(records.take(Path::new("/a.sv"), 8).is_none(), "another hash");
assert!(records.take(Path::new("/b.sv"), 7).is_none(), "another path");
assert!(records.take(Path::new("/a.sv"), 7).is_some());
assert!(parse("0000000000000007\tx").is_none(), "no checksum");
assert!(parse("7\tx\t0000000000000000").is_none(), "a hash of the wrong width");
}
+144
View File
@@ -0,0 +1,144 @@
//! `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 cache;
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] [--read-only] [--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`: the language server's index cache directory,
/// read at startup; this server's own store is written there on exit.
pub index_cache: Option<PathBuf>,
/// `--read-only`: the five read tools only (PLAN §11).
pub mode: tools::Mode,
/// `--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")?),
"--read-only" => options.mode = tools::Mode::ReadOnly,
"--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",
"--read-only",
"--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_eq!(options.mode, tools::Mode::ReadOnly);
assert!(options.verbose);
assert_eq!(parse(&["--verbose"]).unwrap().mode, tools::Mode::Full);
}
#[test]
fn the_usage_line_names_every_flag() {
for flag in ["--root", "--filelist", "--index-cache", "--read-only", "--verbose"] {
assert!(USAGE.contains(flag), "{flag}");
}
}
#[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());
}
}
+142
View File
@@ -0,0 +1,142 @@
//! 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, Semantics};
/// 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 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());
}
#[test]
fn tokens_and_defines_are_kept() {
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!(analysis.tokens.iter().any(|t| t.text == "module"));
}
#[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 (unreadable filelists, links leaving a root).
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();
}
}
+361
View File
@@ -0,0 +1,361 @@
//! 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 vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
use crate::cache::{self, Records, Reuse};
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>,
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,
/// `--index-cache DIR`: where the stores are read from and ours written.
cache_dir: Option<PathBuf>,
/// How many files the startup took from a store instead of parsing.
reuse: Reuse,
}
/// 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 {
/// [`Project::open_cached`] without a cache directory — the tests' open.
#[cfg(test)]
pub fn open(roots: Vec<PathBuf>, filelist: Option<PathBuf>) -> Project {
Project::open_cached(roots, filelist, None)
}
/// Discover the files under `roots` (already canonical) and index them,
/// taking from the index caches in `cache_dir` the facts of every file
/// whose exact bytes a record was read from (PLAN §6) and parsing the
/// rest — on the stack-sized thread.
pub fn open_cached(
roots: Vec<PathBuf>,
filelist: Option<PathBuf>,
cache_dir: Option<PathBuf>,
) -> Project {
let started = Instant::now();
let walk = discover(&roots, filelist.as_deref());
let mut records = cache_dir.as_deref().map(Records::load).unwrap_or_default();
let loaded = load(&walk.files, &mut records);
// The merge is part of the build: finished before the clock is read.
let index = loaded.builder.finish();
let now = Instant::now();
Project {
roots,
filelist_arg: filelist,
files: loaded.files,
index,
analyses: Analyses::default(),
walk,
walked_at: now,
updated_at: now,
build: now - started,
unreadable: loaded.unreadable,
walked_in_call: true,
cache_dir,
reuse: loaded.reuse,
}
}
/// Write the project's own index cache (`--index-cache DIR/index-cache-mcp`):
/// one record per indexed file, the facts the index holds under the hash
/// of the bytes they were read from. `Ok(None)` without a cache directory.
pub fn save_cache(&self) -> std::io::Result<Option<(PathBuf, usize)>> {
let Some(dir) = self.cache_dir.as_deref() else { return Ok(None) };
let records: Vec<(u64, &FileFacts)> = self
.files
.iter()
.filter_map(|(path, stamp)| Some((stamp.hash, self.index.facts_for(path)?)))
.collect();
let written = cache::write_own(dir, &records)?;
Ok(Some((dir.join(cache::OWN_STORE), written)))
}
/// How many files the startup took from the index caches, when a cache
/// directory was given.
pub fn reuse(&self) -> Option<Reuse> {
self.cache_dir.as_ref().map(|_| self.reuse)
}
/// 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)
}
/// 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)
}
}
/// What reading the discovered files at startup produced.
struct Loaded {
builder: IndexBuilder,
files: BTreeMap<PathBuf, Stamp>,
unreadable: Vec<(PathBuf, String)>,
reuse: Reuse,
}
/// Read and stamp every file; add its facts from a store record when one was
/// read off exactly these bytes, else parse it.
fn load(paths: &[PathBuf], records: &mut Records) -> Loaded {
let mut loaded = Loaded {
builder: IndexBuilder::new(),
files: BTreeMap::new(),
unreadable: Vec::new(),
reuse: Reuse::default(),
};
for path in paths {
let (text, stamp) = match read_source(path) {
Ok(read) => read,
Err(problem) => {
loaded.unreadable.push((path.clone(), problem.to_string()));
continue;
}
};
match records.take(path, stamp.hash) {
Some((facts, source)) => {
loaded.reuse.count(source);
loaded.builder.add_facts(facts);
}
None => loaded.builder.add_file(path.clone(), &text),
}
loaded.files.insert(path.clone(), stamp);
}
loaded
}
/// [`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();
}
+207
View File
@@ -0,0 +1,207 @@
//! The rendering rules every tool's text answer follows (PLAN §10.2): the
//! token budget is the product.
//!
//! - one line per fact, root-relative paths, `file:line`; a line range is
//! `first–last`;
//! - no headers, no blank lines, no trailing hints;
//! - a fixed cap per tool, and one `… and N more` line when it cuts;
//! - counts only where they are the answer.
use vlog_semantic::SymbolKind;
/// 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 an item selector 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(" ")
}
/// `n` of a noun whose plural adds `s`: `1 file`, `3 files`.
pub fn count(n: usize, noun: &str) -> String {
if n == 1 {
format!("1 {noun}")
} else {
format!("{n} {noun}s")
}
}
/// `lines` cut at `cap`, ending with one `… and N more` line when cut.
pub fn capped(mut lines: Vec<String>, cap: usize) -> Vec<String> {
if lines.len() > cap {
let rest = lines.len() - cap;
lines.truncate(cap);
lines.push(more(rest));
}
lines
}
/// The line that says how many entries a cut list left out.
pub fn more(rest: usize) -> String {
format!("… and {rest} more")
}
/// Sites grouped one file per line, `file:12,40,41`: files in the order
/// each first appears, each line once, in the order given.
pub fn by_file(sites: &[(String, u32)]) -> Vec<String> {
let mut grouped: Vec<(&str, Vec<u32>)> = Vec::new();
for (file, line) in sites {
match grouped.iter_mut().find(|(held, _)| held == file) {
Some((_, lines)) if lines.contains(line) => {}
Some((_, lines)) => lines.push(*line),
None => grouped.push((file, vec![*line])),
}
}
grouped
.into_iter()
.map(|(file, lines)| {
let lines: Vec<String> = lines.iter().map(u32::to_string).collect();
format!("{file}:{}", lines.join(","))
})
.collect()
}
/// One `warning: …` line per sentence an engine or the write path said.
pub fn warnings(out: &mut Vec<String>, warnings: &[String]) {
out.extend(warnings.iter().map(|warning| format!("warning: {}", one_line(warning))));
}
#[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");
assert_eq!(one_line("a\n b\t c "), "a b c");
assert_eq!((count(1, "file"), count(0, "site")), ("1 file".into(), "0 sites".into()));
}
#[test]
fn a_cut_list_ends_with_one_more_line() {
let all: Vec<String> = (0..5).map(|n| n.to_string()).collect();
assert_eq!(capped(all.clone(), 3), ["0", "1", "2", "… and 2 more"]);
assert_eq!(capped(all.clone(), 5), all);
}
#[test]
fn sites_are_grouped_one_file_per_line() {
let sites = [("b.sv", 3), ("a.sv", 1), ("b.sv", 9), ("b.sv", 3)];
let sites: Vec<(String, u32)> = sites.iter().map(|(f, l)| (f.to_string(), *l)).collect();
assert_eq!(by_file(&sites), ["b.sv:3,9", "a.sv:1"]);
}
}
+178
View File
@@ -0,0 +1,178 @@
//! The `lucisv://` resources: the project overview, the lint rule
//! reference, one unit's outline and one file's outline — the same answers
//! `hierarchy` and `outline` 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": "File and module counts and the top-level modules, as hierarchy without a root answers.",
"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 outline",
"description": "A unit's file:line, parameters and ports (modports, package members), as outline unit answers.",
"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 `hierarchy` without a
/// root 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, "hierarchy", None)?),
(Resource::Unit(name), Some(project)) => {
// A URI has no argument to pick among declarations.
let text = run(project, "outline", Some(("unit", name))).map_err(|why| {
why.replace("outline one `file` instead", "read one file's outline resource")
})?;
("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> {
// A resource runs read tools only, so it answers the same in either mode.
let tool =
tools::find(tool, tools::Mode::ReadOnly).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}");
}
}
}
+423
View File
@@ -0,0 +1,423 @@
//! 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::{self, Mode};
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` (PLAN §10.3, ≤ 400 bytes).
const INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
/// What the agent is told in `--read-only` mode (PLAN §11.1, ≤ 300 bytes).
const INSTRUCTIONS_READ_ONLY: &str = "lucisv-mcp reads the SystemVerilog on disk (save first); it never edits. Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check for issues. Paths root-relative, lines 1-based.";
/// The instructions for `mode`.
fn instructions(mode: Mode) -> &'static str {
match mode {
Mode::Full => INSTRUCTIONS,
Mode::ReadOnly => INSTRUCTIONS_READ_ONLY,
}
}
/// 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 => {
server.finish();
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(self.options.mode)),
"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(self.options.mode),
})
}
/// `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, self.options.mode) else {
return Err(fault(INVALID_PARAMS, unknown_tool(&name, self.options.mode)));
};
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 client closed stdin: write the project's own index cache, when
/// there is a project and a cache directory. A failure is one line on
/// stderr; the session ends either way.
fn finish(&self) {
let Some(project) = &self.project else { return };
match project.save_cache() {
Ok(Some((store, written))) if self.options.verbose => {
eprintln!("lucisv-mcp: wrote {written} records to {}", store.display());
}
Ok(_) => {}
Err(problem) => eprintln!("lucisv-mcp: cannot write the index cache: {problem}"),
}
}
/// 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_cached(
options.roots.clone(),
options.filelist.clone(),
options.index_cache.clone(),
);
let (build, _) = project.timing();
let reused = match project.reuse() {
Some(reuse) => {
format!(" ({} from the editor's cache, {} from its own)", reuse.editor, reuse.own)
}
None => String::new(),
};
let (files, ms) = (project.files().count(), build.as_millis());
eprintln!("lucisv-mcp: indexed {files} files in {ms} ms{reused}");
project
}
/// The `-32602` message for a tool `mode` does not offer. In read-only mode
/// it says why, so an agent does not retry an edit the server cannot make.
fn unknown_tool(name: &str, mode: Mode) -> String {
match mode {
Mode::Full => format!("unknown tool: {name}"),
Mode::ReadOnly => format!("unknown tool: {name} (the server runs --read-only)"),
}
}
/// 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 }],
"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_instructions_stay_under_400_bytes() {
assert!(INSTRUCTIONS.len() <= 400, "{}", INSTRUCTIONS.len());
assert!(INSTRUCTIONS_READ_ONLY.len() <= 300, "{}", INSTRUCTIONS_READ_ONLY.len());
}
#[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"));
}
}
+96
View File
@@ -0,0 +1,96 @@
//! The declarations the files' own symbol tables hold — every one the
//! semantic model knows and `outline` lists: typedefs, enum values,
//! functions, tasks, genvars, generate blocks and what they declare,
//! procedural locals, beside the ports, nets and variables the index also
//! records. The index's word census narrows the files read: a file that
//! declares a name writes it. One table for `find` (an exact name) and for
//! its near matches (a part of a name), so both see the same set.
use std::path::PathBuf;
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::span::TextRange;
use super::read_item::child_items;
use crate::project::{Analysis, Project};
use crate::render;
/// Which names the table is asked for.
pub enum Wanted<'a> {
/// Exactly this name.
Exact(&'a str),
/// Every name containing this part, any case (already lower-cased).
Containing(String),
}
impl Wanted<'_> {
fn accepts(&self, name: &str) -> bool {
match self {
Wanted::Exact(wanted) => name == *wanted,
Wanted::Containing(part) => name.to_ascii_lowercase().contains(part.as_str()),
}
}
/// Whether a file's sorted word census holds a wanted name.
fn in_census(&self, words: &[String]) -> bool {
match self {
Wanted::Exact(wanted) => words.binary_search_by(|w| w.as_str().cmp(wanted)).is_ok(),
Wanted::Containing(_) => words.iter().any(|word| self.accepts(word)),
}
}
}
/// One declaration read off a file's own symbol table.
pub struct Local {
pub path: PathBuf,
pub name: String,
pub kind: &'static str,
/// The byte offset of the name itself.
pub offset: u32,
/// The line shown: the completing declaration's for a non-ANSI port.
pub line: u32,
/// The module, interface, package or class the declaration is inside.
pub unit: Option<String>,
}
/// Every declaration whose name `wanted` accepts, in every indexed file
/// whose words hold such a name, read from disk now.
pub fn declared(project: &Project, wanted: &Wanted) -> Vec<Local> {
let mut out = Vec::new();
for (path, _) in project.files() {
let census = project.index().facts_for(path).map(|facts| facts.words());
if !census.is_some_and(|words| wanted.in_census(words)) {
continue;
}
let Ok(text) = std::fs::read_to_string(path) else { continue };
let analysis = Analysis::of(text);
for symbol in analysis.semantics.symbols().iter().filter(|s| wanted.accepts(&s.name)) {
let shown = symbol.detail_span.unwrap_or(symbol.name_span);
let offset = symbol.name_span.start;
out.push(Local {
path: path.clone(),
name: symbol.name.clone(),
kind: render::kind(symbol.kind),
offset,
line: analysis.lines.line_col(shown.start).0,
unit: unit_at(&analysis.tree.items, symbol.name_span).map(str::to_string),
});
}
}
out
}
/// The innermost module, interface, package or class whose item holds
/// `span`, other than one `span` names.
fn unit_at(items: &[Item], span: TextRange) -> Option<&str> {
let item =
items.iter().find(|item| item.span.start <= span.start && span.end <= item.span.end)?;
let own = match &item.kind {
ItemKind::Module(module) => Some((module.name.as_str(), module.name_span)),
ItemKind::Package { name, name_span, .. } => Some((name.as_str(), *name_span)),
ItemKind::Class(class) => Some((class.name.as_str(), class.name_span)),
_ => None,
};
let inner = child_items(&item.kind).into_iter().find_map(|items| unit_at(items, span));
inner.or(own.filter(|(_, name_span)| *name_span != span).map(|(name, _)| name))
}
+325
View File
@@ -0,0 +1,325 @@
//! `check`: what `lucisv check` would say about one file or the whole
//! design — the tolerant parse's errors, then the lint findings — one line
//! each, `file:line:col severity message [rule]`, errors first.
//!
//! 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 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 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;
/// The most findings an answer lists before `… and N more`.
const CAP: usize = 200;
pub const CHECK: Tool = Tool {
name: "check",
description: "Parse errors and lint findings of `file` or the whole design, one per line (file:line:col severity message [rule]), errors first; `ok` when clean.",
params: &[Param { name: "file", ty: Ty::Str, required: false }],
rewalk: false,
handler: check,
};
/// One finding: where, how bad, what, and which rule.
struct Finding {
file: String,
rule: String,
severity: &'static str,
message: String,
start: (u32, u32),
}
/// 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 check(project: &mut Project, args: &Args) -> Result<Answer, String> {
let mut runs = Runs::new();
let mut findings = 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);
file_findings(project, &mut runs, &path, &analysis, &oracle)?
}
None => project_findings(project, &mut runs)?,
};
if findings.is_empty() {
return Ok(Answer::lines(vec!["ok".to_string()]));
}
// Errors first, then warnings, then the rest; each file's order within.
findings.sort_by_key(|finding| severity_rank(finding.severity));
let lines = findings.iter().map(Finding::render).collect();
Ok(Answer::lines(render::capped(lines, CAP)))
}
fn severity_rank(severity: &str) -> u8 {
match severity {
"error" => 0,
"warning" => 1,
_ => 2,
}
}
impl Finding {
/// `file:line:col severity message [rule]`.
fn render(&self) -> String {
let (line, col) = self.start;
let message = render::one_line(&self.message);
format!("{}:{line}:{col} {} {message} [{}]", self.file, self.severity, self.rule)
}
}
/// Every indexed file's findings, and the external waivers nothing used.
fn project_findings(project: &Project, runs: &mut Runs) -> Result<Vec<Finding>, String> {
let census = Census::of(project.index());
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
let mut findings = Vec::new();
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, runs, path, &analysis, &oracle)?);
}
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
Ok(findings)
}
/// The runs met so far in one call, one per governing config file — shared
/// with `format`'s `fix`, so a fix runs under exactly the rules a finding
/// came from.
pub(super) struct Runs {
discovery: Discovery,
held: BTreeMap<Option<PathBuf>, Rc<Run>>,
}
impl Runs {
/// No run built yet.
pub(super) fn new() -> Runs {
Runs { discovery: Discovery::new(true), held: BTreeMap::new() }
}
/// 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 = 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),
})
.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 {
Finding {
file: file.to_string(),
rule: violation.rule.to_string(),
severity: violation.severity.as_str(),
message: violation.message.clone(),
start: lines.line_col(violation.span.start),
}
}
/// 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)
}
}
+223
View File
@@ -0,0 +1,223 @@
//! `rename`, and what every design-wide edit shares: the whole-set read the
//! engines are handed, and the step from a verified `RefactorEdit` to a
//! written plan with the name's unresolved mentions listed.
//!
//! Each engine gets **every indexed file**, read from disk at call time
//! (`source::WholeSet`, M2's ruling: 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
//! on a `warning:` line (QA finding 2 of M3).
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_refactor::{RefactorEdit, TextEdit};
use super::mentions::{self, Focus};
use super::names::{self, Declaration};
use super::read_item::split_line;
use super::source::WholeSet;
use super::{Answer, Args, Param, Tool, Ty};
use crate::apply::{self, Plan};
use crate::project::Project;
use crate::render;
pub const RENAME: Tool = Tool {
name: "rename",
description: "Rename declaration `name` (or unit.name) to `new_name` with every resolved use (.name/.* written out); `file` and name@LINE pick among declarations. Lists unresolved mentions.",
params: &[
Param { name: "name", ty: Ty::Str, required: true },
Param { name: "new_name", ty: Ty::Str, required: true },
Param { name: "file", ty: Ty::Str, required: false },
],
rewalk: true,
handler: rename,
};
fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
let new_name = args.str("new_name").unwrap_or_default().trim();
let declaration = one_declaration(project, args)?;
let (name, path) = (declaration.name, declaration.path);
if name == new_name {
return Ok(Answer::lines(vec!["renamed 0 sites in 0 files".to_string()]));
}
let set = whole_set(project, Some(&path), std::slice::from_ref(&name))?;
let edit = vlog_refactor::rename(&set.files, &path, declaration.offset, new_name)
.map_err(|why| set.rooted(&why))?;
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
// A member of a module is named bare only where it is declared or used;
// the module (or interface, program) itself is named anywhere.
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
let member = unit.is_some() && !unit_itself;
let told = Told { name: &name, home: &path, unit: unit.as_deref(), member };
let done = write_telling(project, edit, &set, &told)?;
let (sites, files) = (render::count(sites, "site"), render::count(done.files, "file"));
let mut lines = vec![format!("renamed {sites} in {files}")];
lines.extend(done.tail);
Ok(Answer::lines(lines))
}
/// The declaration a rename means: `name` (or `name@LINE`), in `file` when
/// given — exactly one, else a refusal listing them.
struct Picked {
name: String,
path: PathBuf,
offset: u32,
/// The declaration's kind word (`module`, `var`, …).
kind: &'static str,
}
fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String> {
let given = args.str("name").unwrap_or_default().trim().trim_start_matches('`');
let (name, line) = split_line(given)?;
let file = match args.str("file") {
Some(file) => Some(project.resolve(file)?),
None => None,
};
let found = names::declarations_walking(project, name);
if found.is_empty() {
return Err(names::no_declaration(project, name));
}
let wanted = |d: &&Declaration| {
file.as_ref().is_none_or(|file| d.path == *file) && line.is_none_or(|line| d.line == line)
};
let picked: Vec<&Declaration> = found.iter().filter(wanted).collect();
match picked.as_slice() {
[] => Err(format!(
"`{given}` is not declared there; its declarations: {}.",
sites(&found.iter().collect::<Vec<_>>())
)),
[one] if one.is_macro() => {
Err(format!("`{name}` is a macro; lucisv does not rename macros."))
}
[one] => {
let name = names::qualified(name).1.to_string();
Ok(Picked { name, path: one.path.clone(), offset: one.offset, kind: one.kind })
}
many => Err(names::ambiguous(name, many, "pass `file`, and `name@LINE` within one file")),
}
}
fn sites(found: &[&Declaration]) -> String {
found.iter().map(|d| format!("{}:{}", d.file, d.line)).collect::<Vec<_>>().join(", ")
}
/// 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)
}
/// The name an edit changes, for the unresolved-mentions block: the name,
/// the file declaring it, and the unit around it when known.
pub(super) struct Told<'a> {
pub name: &'a str,
pub home: &'a Path,
pub unit: Option<&'a str>,
/// Whether the name is a member of a module or interface: its bare
/// mentions outside its home set (`vlog_refactor::home_set`) are not
/// listed.
pub member: bool,
}
/// What a written edit says after its first line: how many files it wrote,
/// and the warning and `unresolved:` lines.
pub(super) struct Done {
pub files: usize,
pub tail: Vec<String>,
}
/// Write a verified edit over the set's texts, then list the unresolved
/// mentions of `told.name` the edit left alone — found in the texts as the
/// edit writes them, so each `file:line` is right after the write (QA
/// finding 4 of feedback-1).
pub(super) fn write_telling(
project: &Project,
edit: RefactorEdit,
set: &WholeSet,
told: &Told,
) -> Result<Done, String> {
let accounted: Vec<(PathBuf, Vec<TextRange>)> =
edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect();
let plan = Plan::from_refactor(edit, &set.files)?;
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(w)).collect();
let named = path_warned(&warnings);
let written = set.files.iter().map(|(path, text)| {
let change = plan.changes.iter().find(|change| &change.path == path);
(path.as_path(), change.map_or(text.as_str(), |change| change.after.as_str()))
});
// The member's home set (the declaring file, what it includes and what
// includes it, and the edited files): where a bare mention can mean it.
let edited: Vec<PathBuf> = plan.changes.iter().map(|change| change.path.clone()).collect();
// `None` — list every mention — for a non-member, and for a member whose
// home set is not known (an include the engine cannot resolve).
let local = match told.member {
true => vlog_refactor::home_set(&set.files, told.home, &edited),
false => None,
};
let focus = Focus {
name: told.name,
home: told.home,
unit: told.unit,
accounted: &accounted,
named: &named,
local: local.as_deref(),
};
let mentions = mentions::find(project, written, &focus);
let done = apply::run(project, &plan)?;
let mut tail = Vec::new();
render::warnings(&mut tail, &warnings);
tail.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
tail.extend(mentions.block());
Ok(Done { files: done.changed.len() + done.created.len(), tail })
}
/// The `(file, line)` pairs the engine's unresolved-path warnings name
/// (`rtl/a.sv:3,7: a hierarchical path through …`), so the `unresolved:`
/// block does not list them a second time.
fn path_warned(warnings: &[String]) -> Vec<(String, u32)> {
let mut out = Vec::new();
for warning in warnings {
let Some((head, _)) = warning.split_once(": a hierarchical path through `") else {
continue;
};
let Some((file, lines)) = head.rsplit_once(':') else { continue };
out.extend(
lines
.split(',')
.filter_map(|line| line.parse().ok())
.map(|line| (file.to_string(), line)),
);
}
out
}
/// Where each of one file's edits lands in the text as written: its start
/// shifted by what the edits before it added or removed, its length the
/// new text's.
fn written_ranges(edits: &[TextEdit]) -> Vec<TextRange> {
let mut sorted: Vec<&TextEdit> = edits.iter().collect();
sorted.sort_by_key(|edit| (edit.range.start, edit.range.end));
let mut shift: i64 = 0;
let mut out = Vec::new();
for edit in sorted {
let start = (i64::from(edit.range.start) + shift).max(0) as u32;
out.push(TextRange::new(start, start + edit.new_text.len() as u32));
shift += edit.new_text.len() as i64 - i64::from(edit.range.len());
}
out
}
+199
View File
@@ -0,0 +1,199 @@
//! `find`: where a name is declared and, on `refs`, where each declaration
//! is used — the question an agent otherwise answers by grepping and
//! reading. Declarations come from the index (`names.rs`); uses from
//! `vlog_refactor::find_references` over every indexed file read from disk
//! now (`source::WholeSet`, M2's ruling: a use can resolve through a file
//! that never spells the name); then the name's unresolved mentions —
//! strings, comments, macro text — that no engine resolved.
use std::path::PathBuf;
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
use super::mentions::{self, Focus};
use super::names::{self, Declaration};
use super::source::WholeSet;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render;
/// The most lines an answer holds before `… and N more`.
const CAP: usize = 300;
/// The most declarations whose uses one call lists: each is a whole-set
/// engine run (≈ 2 s on opentitan), and a name declared more often than
/// this is a question `read` or `outline` answers better.
const REFS_CAP: usize = 5;
pub const FIND: Tool = Tool {
name: "find",
description: "Every declaration of `name` or unit.name (kind name file:line; macros too); `refs: true` adds each one's uses as file:line and the unresolved mentions (strings, comments, macro text).",
params: &[
Param { name: "name", ty: Ty::Str, required: true },
Param { name: "refs", ty: Ty::Bool, required: false },
],
rewalk: false,
handler: find,
};
fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
let name = args.str("name").unwrap_or("").trim().trim_start_matches('`');
if name.is_empty() {
return Err("`name` is empty.".into());
}
let found = names::declarations_walking(project, name);
if found.is_empty() {
return Err(names::no_declaration(project, name));
}
let name = names::qualified(name).1;
if !args.flag("refs") {
let lines = found.iter().map(|declaration| declaration.render(name)).collect();
return Ok(Answer::lines(render::capped(lines, CAP)));
}
// The uses must be searched in every file, so one written since the last
// walk is walked into first.
project.ensure_walked_for_miss();
Ok(Answer::lines(render::capped(with_uses(project, name, &found), CAP)))
}
/// Each declaration's line followed by its uses, then the unresolved
/// mentions of the name no engine accounted for.
fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String> {
let set = WholeSet::read(project, None);
let mut lines = Vec::new();
let mut accounted: Vec<(PathBuf, Vec<TextRange>)> = Vec::new();
let mut searched = 0;
for declaration in found {
lines.push(declaration.render(name));
if declaration.is_macro() || searched == REFS_CAP {
continue;
}
searched += 1;
let hits = vlog_refactor::find_references(
&set.files,
&declaration.path,
declaration.offset,
false,
);
match hits {
Ok(hits) => {
lines
.extend(uses(project, &set, &hits).into_iter().map(|line| format!(" {line}")));
account(&mut accounted, hits);
}
Err(why) => {
let why = engine_refusal(&set.rooted(&why));
lines.push(format!(" uses not listed: {why}"));
}
}
}
let followed = found.iter().filter(|declaration| !declaration.is_macro()).count();
if followed > REFS_CAP {
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
}
let home = &found[0].path;
let local = member_files(&set, found, &accounted);
let focus = Focus {
name,
home,
unit: None,
accounted: &accounted,
named: &[],
local: local.as_deref(),
};
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
lines.extend(mentions::find(project, files, &focus).block());
lines.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
lines
}
/// The files a bare mention of a **module member** can mean it in — each
/// declaration's home set (`vlog_refactor::home_set`) with every file the
/// engine found a use in — or `None` when
/// any declaration is not a member (a unit, a package member, a macro), whose
/// every mention is listed (§65.1, lead's inspection: a `state_q` found in forty
/// modules is not news about this one).
fn member_files(
set: &WholeSet,
found: &[Declaration],
accounted: &[(PathBuf, Vec<TextRange>)],
) -> Option<Vec<PathBuf>> {
if found.iter().any(Declaration::is_macro) {
return None;
}
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
let mut local: Vec<PathBuf> = Vec::new();
for declaration in found {
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)?;
local.extend(vlog_refactor::home_set(&set.files, &declaration.path, &hit_files)?);
}
Some(local)
}
/// The engine's hits, one file per line: `file:12,40`.
fn uses(project: &Project, set: &WholeSet, hits: &[(PathBuf, TextRange)]) -> Vec<String> {
let mut sites: Vec<(String, u32)> = Vec::new();
let mut current: Option<(&PathBuf, LineIndex)> = None;
for (path, span) in hits {
if current.as_ref().is_none_or(|(held, _)| *held != path) {
let text = set.files.iter().find(|(held, _)| held == path).map_or("", |(_, t)| t);
current = Some((path, LineIndex::new(text)));
}
if let Some((_, lines)) = &current {
sites.push((project.relative(path), lines.line_col(span.start).0));
}
}
render::by_file(&sites)
}
/// The hits recorded per file, so the mentions pass skips them.
fn account(accounted: &mut Vec<(PathBuf, Vec<TextRange>)>, hits: Vec<(PathBuf, TextRange)>) {
for (path, span) in hits {
match accounted.iter_mut().find(|(held, _)| *held == path) {
Some((_, spans)) => spans.push(span),
None => accounted.push((path, vec![span])),
}
}
}
/// The engine's refusal, said as ours: `find_references` shares the
/// rename's resolution, so its sentences speak of renaming; these do not.
fn engine_refusal(sentence: &str) -> 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 = render::one_line(sentence);
for (from, to) in REWORDED {
out = out.replace(from, to);
}
out
}
#[cfg(test)]
mod tests {
use super::engine_refusal;
#[test]
fn engine_refusals_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);
assert!(!said.contains("rename"), "{said}");
}
}
}
+197
View File
@@ -0,0 +1,197 @@
//! `format`: the CLI's `lucisv format` over a path or a glob, and with
//! `fix` the CLI's `lucisv check --fix` first — each file through the one
//! write path (`apply.rs`).
//!
//! Formatting is `format_source` under the `lucisv.toml` governing each file;
//! the formatter's own safety net decides, and a file it refuses is named
//! and left alone while the rest are written (PLAN §10.1). `fix` runs the
//! lint pass `check` 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::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_source, Config};
use vlog_linter::{apply_fixes, Fix, Violation};
use super::diagnostics::{violations, Mentions, Runs};
use super::glob::path_match;
use super::{Answer, Args, Param, Tool, Ty};
use crate::apply::{self, Change, Plan};
use crate::project::{Analysis, Project};
use crate::render;
/// 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;
pub const FORMAT: Tool = Tool {
name: "format",
description: "Format `files` (a path, directory or glob like `rtl/**/*.sv`) as lucisv format; `fix: true` applies safe lint fixes first. A file the formatter refuses is named and left alone.",
params: &[
Param { name: "files", ty: Ty::Str, required: true },
Param { name: "fix", ty: Ty::Bool, required: false },
],
rewalk: false,
handler: format,
};
fn format(project: &mut Project, args: &Args) -> Result<Answer, String> {
let paths = matching_files(project, args.str("files").unwrap_or_default().trim())?;
let fix = args.flag("fix");
let mut discovery = Discovery::new(true);
let mut runs = Runs::new();
let mut plan = Plan::default();
let mut refused: Vec<String> = Vec::new();
for path in paths {
let before = read(project, &path)?;
match fixed_and_formatted(project, &mut discovery, &mut runs, &path, &before, fix) {
Ok(after) => plan.changes.push(Change { path, before, after, created: false }),
Err(why) => refused.push(format!("not formatted: {} ({why})", project.relative(&path))),
}
}
if plan.changes.is_empty() {
return Err(refused.join("; "));
}
let written = apply::run(project, &plan)?;
let formatted = written.changed.len() + written.unchanged.len();
let unchanged = written.unchanged.len();
let formatted = render::count(formatted, "file");
let mut lines = vec![format!("formatted {formatted} ({unchanged} unchanged)")];
lines.extend(refused);
Ok(Answer::lines(render::capped(lines, 200)))
}
/// The files `files` names: one path, every indexed file below a
/// directory, or every indexed file a glob matches — refused when none.
fn matching_files(project: &mut Project, files: &str) -> Result<Vec<PathBuf>, String> {
if files.is_empty() {
return Err("`files` is empty.".into());
}
let wildcard = files.contains(['*', '?']);
if !wildcard {
if let Ok(path) = project.resolve(files) {
return Ok(vec![path]);
}
}
let select = |project: &Project| -> Vec<PathBuf> {
let kept = |path: &&PathBuf| path_match(files, &project.relative(path));
project.files().map(|(path, _)| path).filter(kept).cloned().collect()
};
let mut found = select(project);
if found.is_empty() && project.ensure_walked_for_miss() {
found = select(project);
}
if found.is_empty() {
return Err(match wildcard {
true => format!("no indexed file matches `{files}`; nothing written."),
false => project.resolve(files).err().unwrap_or_default(),
});
}
Ok(found)
}
/// 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)))
}
/// One file's new text: its safe lint fixes (on `fix`), then formatted.
fn fixed_and_formatted(
project: &Project,
discovery: &mut Discovery,
runs: &mut Runs,
path: &Path,
before: &str,
fix: bool,
) -> Result<String, String> {
let text = match fix {
true => fix_file(project, runs, path, before)?,
false => before.to_string(),
};
let config = formatter_config(&discovery.for_file(path)?);
formatted(&text, &config)
}
/// 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) -> Result<String, String> {
let run = catch_unwind(AssertUnwindSafe(|| format_source(text, config)));
match run {
Ok(Ok(out)) => Ok(out),
Ok(Err(e)) => Err(e.to_string()),
Err(_) => Err("the formatter panicked".into()),
}
}
/// 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<String, 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 mut remaining = violations(&run, path, &first, &oracle);
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!(
"its fixes would leave {errors_after} parse errors where it had {errors_before}"
));
}
Ok(text)
}
/// 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))
}
+102
View File
@@ -0,0 +1,102 @@
//! Path globs, as `format`'s `files` takes them: `*` and `?` within one
//! path component, `**` for any run of components, and a bare directory
//! for everything below it — the `.gitignore` / `rg -g` reading.
/// 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 == '*')
}
/// Whether a root-relative `path` matches a path glob: `*` and `?` within
/// one component ([`glob_match`]), `**` as a whole component for any run of
/// components (none included). A trailing `/` means everything below.
pub fn path_match(pattern: &str, path: &str) -> bool {
let pattern = pattern.strip_prefix("./").unwrap_or(pattern);
// A bare directory (`ip/aes`, no wildcard) means everything below it, as
// it does for `.gitignore` and `rg -g` (feedback-2 QA note 2).
let literal = !pattern.contains(['*', '?']);
if literal && path.strip_prefix(pattern).is_some_and(|rest| rest.starts_with('/')) {
return true;
}
let mut parts: Vec<&str> = pattern.split('/').collect();
if parts.last() == Some(&"") && parts.len() > 1 {
parts.pop();
parts.push("**");
}
// `**/**` means what `**` means; collapsing keeps the search linear-ish.
parts.dedup_by(|a, b| *a == "**" && *b == "**");
let components: Vec<&str> = path.split('/').collect();
components_match(&parts, &components)
}
fn components_match(pattern: &[&str], path: &[&str]) -> bool {
match pattern.split_first() {
None => path.is_empty(),
Some((&"**", rest)) => (0..=path.len()).any(|skip| components_match(rest, &path[skip..])),
Some((first, rest)) => path
.split_first()
.is_some_and(|(part, below)| glob_match(first, part) && components_match(rest, below)),
}
}
#[cfg(test)]
mod tests {
use super::{glob_match, path_match};
#[test]
fn a_bare_directory_glob_means_everything_below_it() {
assert!(super::path_match("ip/aes", "ip/aes/rtl/aes.sv"));
assert!(super::path_match("ip/aes/", "ip/aes/rtl/aes.sv"));
assert!(!super::path_match("ip/aes", "ip/aes_x/rtl/aes.sv"));
assert!(!super::path_match("ip/aes", "ip/ae"));
assert!(super::path_match("ip/aes/rtl/aes.sv", "ip/aes/rtl/aes.sv"));
assert!(!super::path_match("ip/a?s", "ip/aes/rtl/aes.sv"), "a wildcard keeps glob rules");
}
#[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"));
}
#[test]
fn path_globs_keep_star_in_one_component_and_let_double_star_span_many() {
assert!(path_match("ip/**/rtl/*.sv", "ip/aes/rtl/aes.sv"));
assert!(path_match("ip/**/rtl/*.sv", "ip/aes/sub/rtl/aes.sv"));
assert!(path_match("ip/**/rtl/*.sv", "ip/rtl/x.sv"));
assert!(!path_match("ip/**/rtl/*.sv", "ip/aes/dv/aes.sv"));
assert!(!path_match("ip/*/*.sv", "ip/aes/rtl/aes.sv"));
assert!(!path_match("*.sv", "ip/aes.sv"));
assert!(path_match("**/*.sv", "ip/aes.sv") && path_match("**/*.sv", "top.sv"));
assert!(path_match("ip/ae?/**", "ip/aes/rtl/aes.sv"));
assert!(!path_match("ip/ae?/**", "ip/aesx/rtl/aes.sv"));
assert!(path_match("ip/", "ip/aes/rtl/aes.sv") && path_match("./ip/**", "ip/a.sv"));
assert!(path_match("**/**/**/rtl/**", "a/b/rtl/c/d.sv"));
assert!(!path_match("ip/**", "hw/ip/aes.sv"));
}
}
+371
View File
@@ -0,0 +1,371 @@
//! `hierarchy`: the project's shape. Without a `root`, the counts and the
//! top modules; with one, the instance tree down from it or every
//! instantiation of it up to `depth` levels — read off the index's
//! instantiation edges, textual rather than elaborated, exactly the census
//! the editor's hierarchy view and call hierarchy draw from. Every instance
//! line points at its **instantiation site**, and `peek` shows the
//! statement written there.
//!
//! 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 vlog_parser::span::TextRange;
use vlog_semantic::{
Def, FileId, InstanceOccurrence, InstantiationEdge, SymbolKind, WorkspaceIndex,
};
use super::names;
use super::source::Texts;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render;
/// The deepest a walk may go, whatever `depth` asks.
const MAX_DEPTH: i64 = 20;
/// The most nodes one walk collects before it stops.
const NODE_CAP: usize = 50_000;
/// The most lines the overview holds, and the most nodes (tree lines, the
/// root's included) a tree answer without `peek` shows, before
/// `… and N more`.
const CAP: usize = 300;
/// The most nodes a tree answer with `peek` shows. A node's `peek` lines
/// never count — the cap is on instances — but each costs up to 13 lines,
/// so the answer stays short (PLAN §10.1).
const PEEK_CAP: usize = 100;
/// The most source lines `peek` shows of one statement before `…`.
const PEEK_LINES: usize = 12;
pub const HIERARCHY: Tool = Tool {
name: "hierarchy",
description: "The instance tree of `root` to `depth` (1-20, default 1), each at its instantiation file:line; `up`: its instantiations; `peek`: each statement's source. No `root`: file/module counts and the top modules.",
params: &[
Param { name: "root", ty: Ty::Str, required: false },
Param { name: "up", ty: Ty::Bool, required: false },
Param { name: "depth", ty: Ty::Range { min: 1, max: MAX_DEPTH }, required: false },
Param { name: "peek", ty: Ty::Bool, required: false },
],
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 last instance ends.
end: u32,
}
impl Child {
/// One instance of an edge to `module`.
fn of(module: &str, edge: &InstantiationEdge, occurrence: &InstanceOccurrence) -> Child {
let end = edge.instances.last().map_or(occurrence.span.end, |last| last.span.end);
Child {
instance: occurrence.name.clone(),
module: module.to_string(),
file: edge.file,
site: edge.site_span,
name: occurrence.name_span,
end,
}
}
}
/// One line of a tree. A root line (down only) has no instance.
struct Node {
depth: usize,
/// Down: the instance; up: the instance of the module on the line above.
instance: Option<Child>,
/// Down: the instantiated module; up: the instantiating one; root: itself.
module: String,
root: Option<Def>,
note: Option<&'static str>,
declared: usize,
}
fn hierarchy(project: &mut Project, args: &Args) -> Result<Answer, String> {
let Some(root) = args.str("root").map(str::trim).filter(|root| !root.is_empty()) else {
// Files written since the last walk are counted.
project.ensure_walked_for_miss();
return Ok(Answer::lines(overview(project)));
};
if modules_named(project.index(), root).is_empty() {
project.ensure_walked_for_miss();
}
let index = project.index();
let declared = modules_named(index, root);
if declared.is_empty() {
let similar = names::similar_units(index, root, 10);
return Err(match similar.is_empty() {
true => format!("no module or interface named `{root}`."),
false => {
format!("no module or interface named `{root}`; similar: {}.", similar.join(", "))
}
});
}
let (up, depth) = (args.flag("up"), args.count("depth", 1));
let mut walk = Walk::new(index, depth, !up);
if up {
walk.path = vec![root.to_string()];
walk.up(root, 1);
} else {
for def in declared {
walk.root(root, def);
}
}
if up && walk.nodes.is_empty() {
return Ok(Answer::lines(vec![format!("nothing instantiates {root}")]));
}
Ok(Answer::lines(render_nodes(project, &walk.nodes, up, args.flag("peek"))))
}
/// `N files, M modules, K top`, then each top module as `name file:line`.
fn overview(project: &Project) -> Vec<String> {
let index = project.index();
let modules = index.units_of(SymbolKind::Module).count();
let tops = top_modules(index);
let files = project.files().count();
let (files, modules) = (render::count(files, "file"), render::count(modules, "module"));
let mut lines = vec![format!("{files}, {modules}, {} top", tops.len())];
for (name, def) in &tops {
let path = index.path(def.file).unwrap_or(Path::new(""));
lines.push(format!("{name} {}:{}", project.relative(path), def.lines.name));
}
render::capped(lines, CAP)
}
/// 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()
}
/// 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>,
}
impl<'a> Walk<'a> {
/// A walk over the 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: &str, def: Def) {
if self.full() {
return;
}
self.path = vec![name.to_string()];
let line = Node {
depth: 0,
instance: None,
module: name.to_string(),
root: Some(def.clone()),
note: None,
declared: 1,
};
self.nodes.push(line);
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"),
0 => Some("not indexed"),
1 => None,
_ => Some("declared"),
};
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,
declared: declared.len(),
});
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);
self.nodes.push(Node {
depth,
instance: Some(Child::of(module, edge, occurrence)),
module: parent.clone(),
root: None,
note: recursive.then_some("recursive"),
declared: 1,
});
if !recursive && depth < self.max_depth {
self.path.push(parent.clone());
self.up(&parent, depth + 1);
self.path.pop();
}
}
}
}
}
/// The nodes as lines, two spaces per level (`up` starts at no indent),
/// each followed by its statement on `peek`; at most [`CAP`] nodes
/// ([`PEEK_CAP`] with `peek`), then `… and N more` counting the nodes not
/// shown.
fn render_nodes(project: &Project, nodes: &[Node], up: bool, peek: bool) -> Vec<String> {
let mut texts = Texts::default();
let mut lines: Vec<String> = Vec::new();
let cap = if peek { PEEK_CAP } else { CAP };
for (at, node) in nodes.iter().enumerate() {
if at == cap {
lines.push(render::more(nodes.len() - at));
return lines;
}
let level = if up { node.depth - 1 } else { node.depth };
let indent = " ".repeat(level);
lines.push(format!("{indent}{}", node_line(project, &mut texts, node, up)));
if let (true, Some(child)) = (peek, &node.instance) {
let source = statement(project, &mut texts, child);
// A blank line of the statement stays blank: no indent of ours.
let shown = |line: String| match line.is_empty() {
true => line,
false => format!("{indent} {line}"),
};
lines.extend(source.into_iter().map(shown));
}
}
lines
}
/// One node: `instance: module file:line` down, `parent.instance file:line`
/// up, `module file:line` for a root — the instance's line is where it is
/// instantiated, the root's where it is declared.
fn node_line(project: &Project, texts: &mut Texts, node: &Node, up: bool) -> String {
let index = project.index();
let mut out = match (&node.instance, &node.root) {
(Some(child), _) => {
let path = index.path(child.file).unwrap_or(Path::new(""));
let line = texts.get(path).map_or(0, |(_, lines)| lines.line_col(child.name.start).0);
let at = format!("{}:{line}", project.relative(path));
match up {
false => format!("{}: {} {at}", child.instance, child.module),
true => format!("{}.{} {at}", node.module, child.instance),
}
}
(None, Some(def)) => {
let path = index.path(def.file).unwrap_or(Path::new(""));
format!("{} {}:{}", node.module, project.relative(path), def.lines.name)
}
(None, None) => node.module.clone(),
};
match node.note {
Some("declared") => out.push_str(&format!(" (declared {} times)", node.declared)),
Some(note) => out.push_str(&format!(" ({note})")),
None => {}
}
out
}
/// The instantiation statement around `child`, as written: from the start
/// of the line naming the module to the end of the line holding its `;`,
/// its common indentation removed, cut at [`PEEK_LINES`] lines. Nothing
/// when the file no longer spells the module there.
fn statement(project: &Project, texts: &mut Texts, child: &Child) -> Vec<String> {
let index = project.index();
let Some((text, _)) = index.path(child.file).and_then(|path| texts.get(path)) else {
return Vec::new();
};
if text.get(child.site.as_range()) != Some(child.module.as_str()) {
return Vec::new();
}
let site = child.site.start as usize;
let end = (child.end as usize).min(text.len());
let start = text[..site].rfind('\n').map_or(0, |at| at + 1);
let semi = text[end..].find(';').map_or(end, |at| end + at + 1);
let stop = text[semi..].find('\n').map_or(text.len(), |at| semi + at);
let written: Vec<&str> = text[start..stop].lines().map(str::trim_end).collect();
let margin = written
.iter()
.filter(|line| !line.trim().is_empty())
.map(|line| line.len() - line.trim_start().len())
.min()
.unwrap_or(0);
let mut out: Vec<String> = written
.iter()
.take(PEEK_LINES)
.map(|line| line.get(margin..).unwrap_or("").to_string())
.collect();
if written.len() > PEEK_LINES {
out.push("…".to_string());
}
out
}
+230
View File
@@ -0,0 +1,230 @@
//! `outline unit:` — what a unit offers the code that uses it: a module's
//! or interface's parameters and ports in declaration order (plus an
//! interface's modports), a package's or class's members — without the
//! agent reading the file that declares it.
use std::path::PathBuf;
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::span::TextRange;
use vlog_refactor::{instantiation_plan, InstantiationPlan};
use vlog_semantic::{Def, ScopeId, Semantics, Symbol, SymbolKind};
use super::read_item::child_items;
use crate::project::{Analysis, Project};
use crate::render;
/// A unit found in the index: where it is, and what it is.
struct Found {
path: PathBuf,
def: Def,
}
/// The unit's `file:line`, then its interface, one fact per line.
pub fn unit_outline(project: &mut Project, name: &str) -> Result<Vec<String>, String> {
let mut found = candidates(project, name);
if found.is_empty() && project.ensure_walked_for_miss() {
found = candidates(project, name);
}
let found = pick(project, found, name)?;
let analysis = project.analysis(&found.path)?;
let head = format!("{}:{}", project.relative(&found.path), 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),
_ => Ok(members(project, &analysis, &found, short, head)),
}
}
/// Every indexed unit declaration of `name` (`pkg::cls` for a class).
fn candidates(project: &Project, name: &str) -> Vec<Found> {
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));
defs.into_iter()
.filter_map(|def| Some(Found { path: index.path(def.file)?.to_path_buf(), def }))
.collect()
}
/// 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) -> Result<Found, String> {
match found.len() {
0 => {
let similar = super::names::similar_units(project.index(), name, 10);
let near = match similar.is_empty() {
true => String::new(),
false => format!("; similar: {}", similar.join(", ")),
};
Err(format!("no module, interface, package or class named `{name}`{near}."))
}
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 ({}); outline one `file` instead.",
sites.len(),
sites.join(", ")
))
}
}
}
/// A module's or interface's parameters, ports and modports.
fn instantiable(
analysis: &Analysis,
found: &Found,
name: &str,
head: String,
) -> Result<Vec<String>, String> {
let plan = instantiation_plan(name, &analysis.text, None)?;
let scope = unit_symbol(&analysis.semantics, found, name).and_then(|s| s.child_scope);
let mut lines = vec![head];
lines.extend(plan.params.iter().map(|p| match p.default.trim() {
"" => format!("param {}", p.name),
default => format!("param {} = {}", p.name, render::one_line(default)),
}));
lines.extend(port_lines(&plan, analysis, scope));
if let (SymbolKind::Interface, Some(scope)) = (found.def.kind, scope) {
lines.extend(modports_of(analysis, scope));
}
render::warnings(&mut lines, &plan.warnings);
Ok(lines)
}
/// An interface's modports, each as its declaration reads on one line,
/// led by the keyword.
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)))
.map(|written| match written.starts_with("modport") {
true => written,
false => format!("modport {written}"),
})
.collect()
}
/// 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),
)
}
/// Each port as `dir type [range] name [unpacked]`, the empty parts left
/// out.
fn port_lines(
plan: &InstantiationPlan,
analysis: &Analysis,
scope: Option<ScopeId>,
) -> Vec<String> {
plan.ports
.iter()
.map(|port| {
let unpacked =
scope.map_or(String::new(), |scope| unpacked(analysis, scope, &port.name));
let parts = [port.dir.as_str(), port.ty.trim(), port.name.as_str(), unpacked.as_str()];
let parts: Vec<&str> = parts.into_iter().filter(|part| !part.is_empty()).collect();
render::one_line(&parts.join(" "))
})
.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, as `kind name
/// LINE`, 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,
head: String,
) -> Vec<String> {
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 mut lines = vec![head];
if let Some(base) = class_base(&analysis.tree.items, found.def.name_span) {
lines.push(format!("extends {base}"));
}
lines.extend(rows.iter().map(|(line, kind, member)| format!("{kind} {member} {line}")));
lines
}
/// 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))
}
+375
View File
@@ -0,0 +1,375 @@
//! `edit_item` — the structural edits under one name (`replace`,
//! `insert_before`, `insert_after`, `delete`), the general token saver: an
//! agent sends one item's text, never the file.
//!
//! Each op finds its place with the slicer `read` uses
//! ([`read_item::select`]), so the bytes it replaces are exactly the bytes
//! `read` showed; builds a [`Splice`]; hands it to [`verify::check`] (the
//! rules are there); and writes through `apply::run`, the one write path
//! (freshness, atomic write). Contract and rules:
//! `docs/features/mcp-structural-edits/README.md`; the lean surface:
//! `docs/features/mcp-lean-catalogue/README.md`.
mod lexical;
mod macros;
mod refs;
mod span;
mod star;
mod verify;
use std::path::PathBuf;
use std::rc::Rc;
use vlog_formatter::fence;
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::span::TextRange;
use super::read_item::{child_items, select};
use super::{Answer, Args, Param, Tool, Ty};
use crate::apply::{self, Change, Plan};
use crate::project::{Analysis, Project};
use crate::render;
use span::{
alone_before, blank_line_at, blank_line_before, line_start, own_lines, past_doubled_blank,
replace_region, SHARED_LINE,
};
use verify::{Expect, Splice};
pub const EDIT_ITEM: Tool = Tool {
name: "edit_item",
description: "One item of `file` (selector as read): `op` replace it by `text` (same kind and names), insert `text` before/after it (item `end`/`end@UNIT`: a unit's end), or delete it if unused.",
params: &[
Param { name: "file", ty: Ty::Str, required: true },
Param {
name: "op",
ty: Ty::Enum(&["replace", "insert_before", "insert_after", "delete"]),
required: true,
},
Param { name: "item", ty: Ty::Str, required: true },
Param { name: "text", ty: Ty::Str, required: false },
],
rewalk: true,
handler: edit_item,
};
fn edit_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
let op = args.str("op").unwrap_or_default();
let text = args.str("text");
match (op, text) {
("delete", None) => delete_item(project, args),
("delete", Some(_)) => Err("`delete` takes no `text`; nothing written.".into()),
(_, None) => Err(format!("`{op}` needs `text`; nothing written.")),
("replace", Some(text)) => replace_item(project, args, text),
(_, Some(text)) => insert_item(project, args, text, op == "insert_before"),
}
}
/// The file a call names: its path, its root-relative name and analysis.
/// A file that does not lex is refused here: no span in it can be trusted.
fn open(project: &mut Project, args: &Args) -> Result<(PathBuf, String, Rc<Analysis>), String> {
let path = project.resolve(args.str("file").unwrap_or(""))?;
let file = project.relative(&path);
let analysis = project.analysis(&path)?;
if analysis.tokens.is_empty() {
return Err(format!(
"`{file}` does not lex (an unterminated string or comment?); fix that first; nothing written."
));
}
Ok((path, file, analysis))
}
/// One item node and where it sits: its sibling list and its index there.
struct Located<'a> {
item: &'a Item,
siblings: &'a [Item],
index: usize,
}
/// The item node `selector` names. A declaration that is part of a larger
/// item (an ANSI port, a function argument) is refused: these tools edit
/// whole items.
fn target<'a>(analysis: &'a Analysis, selector: &str, file: &str) -> Result<Located<'a>, String> {
let (_, span) =
select(analysis, selector).map_err(|why| format!("{why} in `{file}`; nothing written."))?;
locate(&analysis.tree.items, span).ok_or_else(|| {
format!(
"`{selector}` is part of a larger item (a port in a module header, an argument, a generate branch), not an item of its own; edit the enclosing item (`port` for ports); nothing written."
)
})
}
/// The item whose span is exactly `span`, searched through nested scopes.
fn locate(items: &[Item], span: TextRange) -> Option<Located<'_>> {
for (index, item) in items.iter().enumerate() {
if item.span == span {
return Some(Located { item, siblings: items, index });
}
if item.span.start <= span.start && span.end <= item.span.end {
return child_items(&item.kind).into_iter().find_map(|list| locate(list, span));
}
}
None
}
/// A refusal from the verifier, said for this file.
fn refused(file: &str) -> impl Fn(String) -> String + '_ {
move |why| format!("{why} (in `{file}`); nothing written.")
}
/// Whether any byte of `start..end` (an insertion when empty) is fenced.
fn fenced(text: &str, start: u32, end: u32) -> bool {
let regions = fence::protected_regions(text);
fence::is_protected(&regions, start as usize, end as usize)
}
const FENCED: &str = "lies inside a `// lucisv: off` fence, which no lucisv tool edits";
fn replace_item(project: &mut Project, args: &Args, text: &str) -> Result<Answer, String> {
let (path, file, analysis) = open(project, args)?;
let selector = args.str("item").unwrap_or("").trim();
let located = target(&analysis, selector, &file)?;
let span = located.item.span;
let text = normalise(text, &analysis.text, false)?;
let (start, end) = replace_region(&analysis.text, located.item, &text);
let class = verify::class_of(&located.item.kind);
// The item as it already is: a no-op, not a refusal (even in a fence).
if text == analysis.slice(start, end) {
let (first, last) = analysis.line_span(span.start, span.end);
let names = verify::owned_names(&analysis, span);
return Ok(said("unchanged", class, &names, &file, (first, last), Vec::new()));
}
if fenced(&analysis.text, start, end) {
return Err(format!("`{selector}` {FENCED}; nothing written."));
}
let splice = Splice { start, old_end: end, text };
let outcome = verify::check(&analysis, &splice, Expect::One(class)).map_err(refused(&file))?;
let new_span = outcome.items.first().map_or(span, |(_, span)| *span);
let was = verify::owned_names(&analysis, span);
let now = verify::owned_names(&outcome.analysis, new_span);
name_rule(&was, &now)?;
let lines = outcome.analysis.line_span(new_span.start, new_span.end);
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
Ok(said("replaced", class, &now, &file, lines, Vec::new()))
}
/// The text declares the names the item did: a replacement that renames
/// would leave every reference behind (`rename` renames with references).
fn name_rule(was: &[String], now: &[String]) -> Result<(), String> {
if was == now {
return Ok(());
}
Err(format!(
"the text declares {} where the item declared {}; `rename` renames a declaration with its references; nothing written.",
listed(now),
listed(was)
))
}
fn insert_item(
project: &mut Project,
args: &Args,
text: &str,
before: bool,
) -> Result<Answer, String> {
let (path, file, analysis) = open(project, args)?;
let anchor = args.str("item").unwrap_or("").trim();
let text = normalise(text, &analysis.text, true)?;
let spot = match anchor.strip_prefix("end") {
Some(rest) if rest.is_empty() || rest.starts_with('@') => {
end_spot(&analysis, rest.trim_start_matches('@'), &file)?
}
_ => anchor_spot(&analysis, anchor, before, &file)?,
};
let block = spot.block(&analysis.text, &text);
let splice = Splice { start: spot.at, old_end: spot.at, text: block };
// The verifier first, so a text that cannot stand anywhere is refused
// as such; then the place.
let outcome = verify::check(&analysis, &splice, Expect::Some).map_err(refused(&file))?;
if fenced(&analysis.text, spot.at, spot.at) {
return Err(format!("the insertion point {FENCED}; nothing written."));
}
let (first, last) = match (outcome.items.first(), outcome.items.last()) {
(Some((_, first)), Some((_, last))) => (*first, *last),
_ => return Err(format!("the text holds no item (in `{file}`); nothing written.")),
};
let lines = outcome.analysis.line_span(first.start, last.end);
let classes: Vec<&str> = outcome.items.iter().map(|(class, _)| *class).collect();
let names: Vec<String> = outcome
.items
.iter()
.flat_map(|(_, span)| verify::owned_names(&outcome.analysis, *span))
.collect();
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
Ok(said("inserted", &classes.join(", "), &names, &file, lines, Vec::new()))
}
fn delete_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
let (path, file, analysis) = open(project, args)?;
let selector = args.str("item").unwrap_or("").trim();
let located = target(&analysis, selector, &file)?;
let (start, end) = own_lines(&analysis.text, located.item)
.map_err(|why| format!("`{selector}` {why}; nothing written."))?;
let end = past_doubled_blank(&analysis.text, start, end);
if fenced(&analysis.text, start, end) || fence_comment(located.item) {
return Err(format!("`{selector}` {FENCED}; nothing written."));
}
let removed = TextRange::new(start, end);
let place = refs::Place { item: located.item.span, removed, scope: located.siblings };
let warnings = refs::check(project, &path, &analysis, &place)?;
let class = verify::class_of(&located.item.kind);
let splice = Splice { start, old_end: end, text: String::new() };
let outcome = verify::check(&analysis, &splice, Expect::Nothing).map_err(refused(&file))?;
let names = verify::owned_names(&analysis, located.item.span);
let lines = analysis.line_span(start, end);
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
Ok(said("deleted", class, &names, &file, lines, warnings))
}
/// `replaced function f file:12–20`, then any warning lines.
fn said(
verb: &str,
class: &str,
names: &[String],
file: &str,
(first, last): (u32, u32),
warnings: Vec<String>,
) -> Answer {
let named = if names.is_empty() { String::new() } else { format!(" {}", names.join(", ")) };
let mut lines = vec![format!("{verb} {class}{named} {file}:{}", render::lines(first, last))];
render::warnings(&mut lines, &warnings);
Answer::lines(lines)
}
/// Whether the item's own leading comments hold a fence line: deleting one
/// would move a fence's edge.
fn fence_comment(item: &Item) -> bool {
item.meta.leading.iter().any(|comment| fence::fence_of(&comment.text).is_some())
}
/// The one-file plan: the analysed text before, the verified text after.
fn plan(path: PathBuf, analysis: &Analysis, after: String, warnings: Vec<String>) -> Plan {
let change = Change { path, before: analysis.text.clone(), after, created: false };
Plan { changes: vec![change], warnings }
}
/// `` `a`, `b` `` for a list of names; `nothing` when empty.
fn listed(names: &[String]) -> String {
if names.is_empty() {
return "nothing".to_string();
}
names.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>().join(", ")
}
/// `text` made ready to splice: surrounding blank space dropped (for an
/// insertion, the first line's indentation is kept), line endings made the
/// file's. Empty text is refused: deleting is `op: delete`'s.
fn normalise(text: &str, file_text: &str, keep_indent: bool) -> Result<String, String> {
let trimmed = text.trim_end_matches(|c: char| c.is_ascii_whitespace());
let trimmed = if keep_indent {
let first_code = trimmed.find(|c: char| !c.is_ascii_whitespace()).unwrap_or(0);
&trimmed[line_start(trimmed, first_code as u32) as usize..]
} else {
trimmed.trim_start_matches(|c: char| c.is_ascii_whitespace())
};
if trimmed.is_empty() {
return Err("`text` is empty; `op: delete` removes an item; nothing written.".into());
}
let lf = trimmed.replace("\r\n", "\n");
Ok(if line_ending(file_text) == "\r\n" { lf.replace('\n', "\r\n") } else { lf })
}
/// The file's line ending, judged by its first line.
fn line_ending(text: &str) -> &'static str {
match text.find('\n') {
Some(at) if text[..at].ends_with('\r') => "\r\n",
_ => "\n",
}
}
/// Where an insertion lands: a line start, and whether an item neighbours
/// it above and below (the blank-line policy).
struct Spot {
at: u32,
above: bool,
below: bool,
}
impl Spot {
/// `text` framed for this spot: a line break when the file's last line
/// has none, a blank line on each side that has a neighbouring item
/// unless one is already there, and the text's own line ending.
fn block(&self, file_text: &str, text: &str) -> String {
let nl = line_ending(file_text);
let mut block = String::new();
if self.at as usize == file_text.len()
&& !file_text.is_empty()
&& !file_text.ends_with('\n')
{
block.push_str(nl);
}
if self.above && !blank_line_before(file_text, self.at) {
block.push_str(nl);
}
block.push_str(text);
block.push_str(nl);
if self.below && !blank_line_at(file_text, self.at) {
block.push_str(nl);
}
block
}
}
/// Before the anchor item (and its leading comments) or after it (and its
/// trailing comment).
fn anchor_spot(
analysis: &Analysis,
selector: &str,
before: bool,
file: &str,
) -> Result<Spot, String> {
let located = target(analysis, selector, file)?;
let (first, last) = own_lines(&analysis.text, located.item)
.map_err(|why| format!("`{selector}` {why}; nothing written."))?;
Ok(if before {
Spot { at: first, above: located.index > 0, below: true }
} else {
let below = located.index + 1 < located.siblings.len();
Spot { at: last, above: true, below }
})
}
/// The line of a unit's end keyword: `unit` is empty for the file's last
/// unit, else a selector naming a module, interface, program, package or
/// class.
fn end_spot(analysis: &Analysis, unit: &str, file: &str) -> Result<Spot, String> {
let is_unit = |item: &Item| {
matches!(item.kind, ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_))
};
let item = if unit.is_empty() {
let last = analysis.tree.items.iter().rev().find(|item| is_unit(item));
last.ok_or_else(|| {
format!("`{file}` declares no module, package or class; nothing written.")
})?
} else {
let located = target(analysis, unit, file)?;
if !is_unit(located.item) {
return Err(format!("`{unit}` is not a module, package or class; nothing written."));
}
located.item
};
let keyword = analysis
.tokens
.iter()
.filter(|t| item.span.start <= t.span.start && t.span.end <= item.span.end)
.rfind(|t| END_WORDS.contains(&t.text.as_str()))
.ok_or_else(|| format!("the unit has no end keyword in `{file}`; nothing written."))?;
if !alone_before(&analysis.text, keyword.span.start) {
return Err(format!("`{}` {SHARED_LINE}; nothing written.", keyword.text));
}
let children = child_items(&item.kind);
let above = children.iter().any(|list| !list.is_empty());
Ok(Spot { at: line_start(&analysis.text, keyword.span.start), above, below: false })
}
/// The keywords that close a unit `end` may name.
const END_WORDS: &[&str] = &["endmodule", "endinterface", "endprogram", "endpackage", "endclass"];
+175
View File
@@ -0,0 +1,175 @@
//! The verifier's lexical rules — what a splice may do to the token stream
//! and its comments, before any parse is asked:
//!
//! - **1a.** `text` lexes on its own. A text ending in an open `/*`, string
//! or macro call lexes inside the file only by running into the code after
//! it — a `*/` further down closes it and the fence between is swallowed.
//! - **1b.** Outside the region nothing lexes differently: every token and
//! every comment before the region, and every one after it (shifted by
//! the length change), is the old file's — same kind, text and span. No
//! token or comment starts inside the region and ends past it, and no
//! comment the new bytes write is attached (`Token.leading`/`trailing`)
//! to a token outside them: a comment the text leaves on a line of its
//! own at its end would lead the next item, not this one.
//! - **7.** The region holds the same `lucisv: off`/`on` fence markers
//! before and after: a text neither opens nor closes a fence.
use vlog_formatter::fence;
use vlog_parser::token::{Comment, Token, TokenKind};
use crate::project::Analysis;
/// A splice's region in both files: `start..old_end` in the old one,
/// `start..new_end` in the new one.
#[derive(Clone, Copy)]
pub struct Region {
pub start: u32,
pub old_end: u32,
pub new_end: u32,
}
/// One lexical element of a file: a token or a comment.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Element<'a> {
kind: Option<TokenKind>,
text: &'a str,
start: u32,
end: u32,
}
impl Element<'_> {
fn describe(&self, analysis: &Analysis) -> String {
let line = analysis.lines.line_col(self.start).0;
let text: String = self.text.chars().take(24).collect();
let what = if self.kind.is_some() { "token" } else { "comment" };
format!("the {what} `{text}` at line {line}")
}
}
fn comment(c: &Comment) -> Element<'_> {
Element { kind: None, text: &c.text, start: c.span.start, end: c.span.end }
}
/// Every token and comment of a stream, in source order.
fn elements(tokens: &[Token]) -> Vec<Element<'_>> {
let mut out = Vec::with_capacity(tokens.len() + tokens.len() / 4);
for token in tokens {
out.extend(token.leading.iter().map(comment));
let (start, end) = (token.span.start, token.span.end);
out.push(Element { kind: Some(token.kind), text: &token.text, start, end });
out.extend(token.trailing.iter().map(comment));
}
out
}
/// The elements before `start` and after `end` (shifted by `shift`); an
/// element that starts inside and ends past `end` is returned as `Err`.
fn sides<'a>(
all: &[Element<'a>],
start: u32,
end: u32,
shift: i64,
) -> Result<(Vec<Element<'a>>, Vec<Element<'a>>), Element<'a>> {
let moved = |at: u32| u32::try_from(i64::from(at) + shift).unwrap_or(u32::MAX);
let (mut before, mut after) = (Vec::new(), Vec::new());
for element in all {
if element.start < start {
before.push(*element);
} else if element.start >= end {
after.push(Element {
start: moved(element.start),
end: moved(element.end),
..*element
});
} else if element.end > end {
return Err(*element);
}
}
Ok((before, after))
}
/// Rule 1a: `text` lexes on its own.
pub fn lexes_alone(text: &str) -> Result<(), String> {
vlog_parser::tokenize(text).map(|_| ()).map_err(|e| {
format!(
"the text does not lex on its own (rule 1a: {}); a comment, string or macro call it leaves open would run into the code after it",
e.message
)
})
}
/// Rule 1b: the tokens and comments outside `start..old_end` (old) and
/// `start..new_end` (new) are the same, shifted; nothing straddles the new
/// region's end; no comment inside it is attached to a token outside it.
pub fn same_outside(old: &Analysis, new: &Analysis, region: Region) -> Result<(), String> {
let Region { start, old_end, new_end } = region;
let shift = i64::from(new_end) - i64::from(old_end);
let (was, now) = (elements(&old.tokens), elements(&new.tokens));
let changed = |element: &Element| {
format!("the edit would change how the code outside the item lexes (rule 1b: {} would not survive as it is)", element.describe(old))
};
let (was_before, was_after) = sides(&was, start, old_end, shift).map_err(|e| changed(&e))?;
let (now_before, now_after) = sides(&now, start, new_end, 0).map_err(|element| {
format!(
"{} would run past the text's end into the code after it (rule 1b)",
element.describe(new)
)
})?;
for (was, now) in [(&was_before, &now_before), (&was_after, &now_after)] {
if was != now {
let at = was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len());
let element = was.get(at).or(was.last()).or(now.get(at));
return Err(element.map_or_else(
|| {
"the edit would change how the code outside the item lexes (rule 1b)"
.to_string()
},
changed,
));
}
}
attached_inside(new, start, new_end)
}
/// Rule 1b's last clause: a comment the new bytes hold belongs to a token
/// they hold.
fn attached_inside(new: &Analysis, start: u32, end: u32) -> Result<(), String> {
let inside = |at: u32| start <= at && at < end;
for token in new.tokens.iter().filter(|token| !inside(token.span.start)) {
let stray = token.leading.iter().chain(&token.trailing).find(|c| inside(c.span.start));
if let Some(comment) = stray {
let line = new.lines.line_col(comment.span.start).0;
return Err(format!(
"the comment at line {line} of the text would belong to the code after it, not to the item (rule 1b); put the comment before the item or on its last line"
));
}
}
Ok(())
}
/// Rule 7: the fence markers inside the region are the same before and
/// after.
pub fn same_fences(old: &Analysis, new: &Analysis, region: Region) -> Result<(), String> {
let Region { start, old_end, new_end } = region;
let (was, now) = (markers(&old.tokens, start, old_end), markers(&new.tokens, start, new_end));
if was == now {
return Ok(());
}
let (verb, longer, shorter) =
if now.len() >= was.len() { ("add", &now, &was) } else { ("remove", &was, &now) };
let at = longer.iter().zip(shorter.iter()).position(|(a, b)| a != b).unwrap_or(shorter.len());
let marker = longer.get(at).copied().unwrap_or("// lucisv: off");
Err(format!(
"the edit would {verb} the fence marker `{marker}` (rule 7); `lucisv: off`/`on` fences are written by hand, not through these tools"
))
}
/// The fence-marker comments starting in `start..end`, in order.
fn markers(tokens: &[Token], start: u32, end: u32) -> Vec<&str> {
elements(tokens)
.into_iter()
.filter(|e| e.kind.is_none() && start <= e.start && e.start < end)
.filter(|e| fence::fence_of(e.text).is_some())
.map(|e| e.text.trim())
.collect()
}
+108
View File
@@ -0,0 +1,108 @@
//! `op: delete`'s macro rule: a name spelled inside a macro call's
//! arguments (`` `ASSERT_KNOWN(k, sig) ``) or a `` `define`` body is a use
//! no lucisv engine resolves — the lexer keeps a macro call as one token and
//! a `` `define`` as one directive. Each such spelling the engine and the
//! file's own tables did not account for is a *possible* use.
use vlog_parser::defines::{collect_defines, DefineKind};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use crate::tools::source::word_in;
/// Where `name` is spelled inside a macro call's arguments or a
/// `` `define`` body in `tokens`, outside `skip`: the byte offset of each
/// spelling (a `` `define``'s own start for a body).
pub fn macro_spellings(tokens: &[Token], name: &str, skip: TextRange) -> Vec<u32> {
let outside = |span: TextRange| span.end <= skip.start || span.start >= skip.end;
let mut out = Vec::new();
for token in tokens.iter().filter(|token| outside(token.span)) {
match token.kind {
TokenKind::Ident if token.text.starts_with('`') => {
call_arguments(&token.text, token.span.start, name, &mut out);
}
TokenKind::Directive if defines_with_body_spelling(token, name) => {
out.push(token.span.start);
}
_ => {}
}
}
out
}
/// The spellings of `name` in one macro call's arguments (`text` starts at
/// byte `at`), nested calls included. Arguments that do not lex are
/// searched as bytes.
fn call_arguments(text: &str, at: u32, name: &str, out: &mut Vec<u32>) {
let Some(open) = text.find('(') else {
return;
};
let args = &text[open..];
let base = at + open as u32;
match tokenize(args) {
Ok(tokens) => {
for token in tokens.iter().filter(|t| t.kind == TokenKind::Ident) {
let start = base + token.span.start;
if token.text == name {
out.push(start);
} else if token.text.starts_with('`') {
call_arguments(&token.text, start, name, out);
}
}
}
Err(_) => out.extend(word_in(args, name).map(|offset| base + offset as u32)),
}
}
/// Whether a `` `define`` directive's body spells `name` as an identifier
/// that is not one of its own formal arguments.
fn defines_with_body_spelling(token: &Token, name: &str) -> bool {
let table = collect_defines(std::slice::from_ref(token));
table.entries().iter().any(|define| {
let formal = define
.params
.iter()
.flatten()
.any(|param| param.split('=').next().is_some_and(|formal| formal.trim() == name));
define.kind == DefineKind::Define && !formal && body_spells(&define.body, name)
})
}
/// Whether a macro body spells `name` as an identifier, nested calls
/// included (searched as bytes when the body does not lex on its own —
/// token pasting, escaped quotes).
fn body_spells(body: &str, name: &str) -> bool {
let Ok(tokens) = tokenize(body) else {
return word_in(body, name).is_some();
};
let mut found = Vec::new();
for token in tokens.iter().filter(|t| t.kind == TokenKind::Ident) {
if token.text == name {
return true;
}
if token.text.starts_with('`') {
call_arguments(&token.text, 0, name, &mut found);
}
}
!found.is_empty()
}
#[cfg(test)]
mod tests {
use super::*;
fn spellings(src: &str, name: &str) -> Vec<u32> {
let tokens = tokenize(src).unwrap();
macro_spellings(&tokens, name, TextRange::new(0, 0))
}
#[test]
fn a_name_in_a_macro_call_or_a_define_body_is_found() {
let src = "`define B(x) x + sig\nassign o = `ID(`W(sig));\n";
assert_eq!(spellings(src, "sig"), [0, src.find("sig)").unwrap() as u32]);
assert!(spellings(src, "x").is_empty(), "a formal argument is not a use");
assert!(spellings("assign o = `ID(a) + sig;\n", "sig").is_empty());
assert!(spellings("`define S \"sig\"\n", "sig").is_empty(), "a string is not a use");
}
}
+262
View File
@@ -0,0 +1,262 @@
//! `edit_item op: delete`'s reference rule: an item is not deleted while a
//! name it owns (`verify::owned`) is still used anywhere in the project.
//!
//! Uses are `vlog_refactor::find_references` over the whole indexed set,
//! read from disk now (`WholeSet`, M2's ruling) — the census `references`
//! answers with — plus what that engine cannot see:
//!
//! - a `.*` in the item's scope that binds the name ([`star`]) — it binds
//! without spelling it, so this runs for every name;
//! - a spelling inside a macro call's arguments or a `` `define`` body
//! ([`macros`]), a *possible* use;
//! - in the item's own file, a use the file's tables resolve to the
//! declaration or to nothing ([`local_uses`]).
//!
//! Apart from `.*`, a name no file spells outside the removed lines has no
//! use to find, so the rest runs only for names some other text spells (a
//! whole-word byte search): an identifier, escaped or not, is always
//! written out where it is used.
use std::path::{Path, PathBuf};
use vlog_parser::ast::Item;
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
use vlog_semantic::Symbol;
use super::macros::macro_spellings;
use super::star::star_uses;
use super::verify;
use crate::project::{Analysis, Project};
use crate::tools::source::{word_in, WholeSet};
/// How many surviving uses a refusal lists.
const SHOWN: usize = 5;
/// The uses and doubts found, the first few spelled out.
#[derive(Default)]
struct Census {
shown: Vec<String>,
total: usize,
}
impl Census {
fn add(&mut self, line: impl FnOnce() -> String) {
if self.shown.len() < SHOWN {
self.shown.push(line());
}
self.total += 1;
}
fn render(&self) -> String {
let more = self.total - self.shown.len();
let tail = if more > 0 { format!("; and {more} more") } else { String::new() };
format!("{}{tail}", self.shown.join("; "))
}
}
/// Where a deletion sits: the item's span, the bytes the deletion takes
/// (its comments included), and the item list it is taken from.
pub struct Place<'a> {
pub item: TextRange,
pub removed: TextRange,
pub scope: &'a [Item],
}
/// The warnings a deletion carries, or the refusal.
pub fn check(
project: &Project,
path: &Path,
analysis: &Analysis,
place: &Place,
) -> Result<Vec<String>, String> {
let symbols = verify::owned(analysis, place.item);
if symbols.is_empty() {
return Ok(Vec::new());
}
let set = WholeSet::read(project, Some(path));
let own = set.files.iter().find(|(held, _)| held == path).map(|(_, text)| text.as_str());
if own != Some(analysis.text.as_str()) {
let file = project.relative(path);
return Err(format!("`{file}` changed on disk while it was read; nothing written."));
}
let names: Vec<String> = symbols.iter().map(|symbol| symbol.name.clone()).collect();
let mut census = Census::default();
if let Some((skipped, why, name)) = set.mentioning(&names) {
let file = project.relative(skipped);
census.add(|| format!("{file} (skipped: {why}) may reference `{name}`"));
}
let scan = Scan { project, set: &set, path, analysis, place };
for symbol in symbols {
scan.uses_of(symbol, &mut census);
}
if census.total > 0 {
return Err(format!("still referenced: {}; nothing written.", census.render()));
}
Ok(set.warning(project).into_iter().collect())
}
/// What one deletion's reference scan reads.
struct Scan<'a> {
project: &'a Project,
set: &'a WholeSet,
path: &'a Path,
analysis: &'a Analysis,
place: &'a Place<'a>,
}
/// The spans some rule already counted (or knows to be another name's), per
/// file: a macro spelling at one of them is not counted twice.
type Accounted = Vec<(PathBuf, TextRange)>;
impl Scan<'_> {
/// Count the uses of one owned declaration that the deletion would leave.
fn uses_of(&self, symbol: &Symbol, census: &mut Census) {
let (name, removed) = (&symbol.name, self.place.removed);
if !within(symbol.name_span, removed) {
let line = self.analysis.lines.line_col(symbol.name_span.start).0;
census.add(|| {
format!("`{name}` is also declared on line {line}, which the deletion would leave incomplete")
});
return;
}
self.stars(name, census);
if !mentioned(self.set, self.path, removed, name) {
return;
}
let accounted = self.references(symbol, census);
self.macros(name, &accounted, census);
}
/// The engine's and the file's own uses, counted; what they account for.
fn references(&self, symbol: &Symbol, census: &mut Census) -> Accounted {
let (name, removed) = (&symbol.name, self.place.removed);
let mut uses = local_uses(self.analysis, symbol, removed);
let mut accounted: Accounted = self
.analysis
.semantics
.references()
.iter()
.filter(|use_| use_.name == *name)
.map(|use_| (self.path.to_path_buf(), use_.name_span))
.collect();
let found = vlog_refactor::find_references(
&self.set.files,
self.path,
symbol.name_span.start,
false,
);
match found {
Ok(hits) => {
for (file, span) in hits {
if file != self.path {
census.add(|| site(self.project, self.set, &file, span, name));
} else if !within(span, removed) && !uses.contains(&span) {
uses.push(span);
}
accounted.push((file, span));
}
}
Err(why) => census.add(|| {
format!("the uses of `{name}` cannot all be listed ({})", why.trim_end_matches('.'))
}),
}
uses.sort_by_key(|span| span.start);
for span in uses {
census.add(|| site(self.project, self.set, self.path, span, name));
}
accounted
}
/// Rule `.*`: the implicit connections in the item's scope that bind
/// (or may bind) `name`.
fn stars(&self, name: &str, census: &mut Census) {
let index = self.project.index();
for star in star_uses(index, self.place.scope, self.place.removed, name) {
let at = position(self.project, self.set, self.path, star.at);
census.add(|| match star.certain {
true => format!("bound by `.*` at {at} `{name}` (module `{}`)", star.module),
false => format!(
"possible use (`.*`) at {at} `{name}` (module `{}` does not resolve to one declaration)",
star.module
),
});
}
}
/// Rule macros: every spelling of `name` inside a macro call or a
/// `` `define`` body, in any file of the set, that nothing accounted for.
fn macros(&self, name: &str, accounted: &Accounted, census: &mut Census) {
for (file, text) in &self.set.files {
if word_in(text, name).is_none() {
continue;
}
let (own, lexed);
let tokens = if file == self.path {
own = &self.analysis.tokens;
own
} else if let Ok(tokens) = vlog_parser::tokenize(text) {
lexed = tokens;
&lexed
} else {
let at = self.project.relative(file);
census.add(|| format!("possible use in {at} (it does not lex) `{name}`"));
continue;
};
let skip = if file == self.path { self.place.removed } else { TextRange::new(0, 0) };
let lines = LineIndex::new(text);
for offset in macro_spellings(tokens, name, skip) {
if !accounted.iter().any(|(held, span)| held == file && span.start == offset) {
let at =
format!("{}:{}", self.project.relative(file), lines.line_col(offset).0);
census.add(|| format!("possible use (macro) at {at} `{name}`"));
}
}
}
}
}
fn within(inner: TextRange, outer: TextRange) -> bool {
outer.start <= inner.start && inner.end <= outer.end
}
/// The uses of `symbol` the file's own tables hold outside the removed
/// bytes: resolved to it, or to nothing at all. The second kind is what the
/// cross-file engine does not follow (a hierarchical path into a generate
/// loop, `gen_l[0].z`); counting it may refuse a deletion that was safe,
/// never allow one that was not.
fn local_uses(analysis: &Analysis, symbol: &Symbol, removed: TextRange) -> Vec<TextRange> {
let semantics = &analysis.semantics;
let id = semantics.symbol_at(symbol.name_span.start);
semantics
.references()
.iter()
.filter(|use_| use_.name == symbol.name && !within(use_.name_span, removed))
.filter(|use_| use_.resolved().is_none() || use_.resolved() == id)
.map(|use_| use_.name_span)
.collect()
}
/// Whether any text of the set, the removed bytes aside, spells `name`.
fn mentioned(set: &WholeSet, path: &Path, removed: TextRange, name: &str) -> bool {
set.files.iter().any(|(held, text)| {
if held != path {
return word_in(text, name).is_some();
}
let head = text.get(..removed.start as usize).unwrap_or("");
let tail = text.get(removed.end as usize..).unwrap_or("");
word_in(head, name).is_some() || word_in(tail, name).is_some()
})
}
/// `file:line:col `name`` for one use.
fn site(project: &Project, set: &WholeSet, file: &Path, span: TextRange, name: &str) -> String {
format!("{} `{name}`", position(project, set, file, span))
}
/// `file:line:col` of a span's start.
fn position(project: &Project, set: &WholeSet, file: &Path, span: TextRange) -> String {
let text = set.files.iter().find(|(held, _)| held == file).map_or("", |(_, t)| t.as_str());
let (line, col) = LineIndex::new(text).line_col(span.start);
format!("{}:{line}:{col}", project.relative(file))
}
+157
View File
@@ -0,0 +1,157 @@
//! Which bytes an item owns: the lines `edit_item`'s inserts and deletes
//! work on, and the span its `replace` replaces when its text brings comments.
//!
//! Two rules, stated once here and in the README:
//!
//! - **Own comments.** An item's leading comments (`Meta::leading`) are its
//! own back to the first gap holding a blank line: a banner a blank line
//! separates from the item belongs to what follows it, not to this item.
//! - **Own lines.** An item owns its lines unless another item's *code*
//! sits on its first or last line; a comment on the same line goes with
//! the item (`/* lead */ logic a;` owns its line).
use vlog_parser::ast::Item;
use vlog_parser::tokenize;
/// Why an item that does not own its lines is refused by insert and delete.
pub const SHARED_LINE: &str = "shares a line with other code; edit_item inserts and deletes work on items on lines of their own (run `format` first)";
/// The start of the item's own leading comments (the item's own start when
/// it has none): walking back over `Meta::leading`, up to the first gap
/// that holds a blank line.
pub fn own_comments_start(text: &str, item: &Item) -> u32 {
let mut first = item.span.start;
for comment in item.meta.leading.iter().rev() {
let gap = text.get(comment.span.end as usize..first as usize).unwrap_or("x");
if !gap.trim().is_empty() || gap.matches('\n').count() > 1 {
break;
}
first = comment.span.start;
}
first
}
/// The lines an item owns: from the line of its first own leading comment
/// to the end of its own last line (its trailing comment included). An item
/// whose first or last line holds other code owns no lines.
pub fn own_lines(text: &str, item: &Item) -> Result<(u32, u32), String> {
let first = own_comments_start(text, item);
if !alone_before(text, first) {
return Err(SHARED_LINE.to_string());
}
let trailing = item.meta.trailing.as_ref().map_or(0, |comment| comment.span.end);
let last = alone_after(text, item.span.end.max(trailing)).ok_or(SHARED_LINE)?;
Ok((line_start(text, first), last))
}
/// The bytes `op: replace` replaces with `text`: the item's span, widened
/// back over its own leading comments when `text` begins with a comment,
/// and forward over its trailing comment when `text` ends with one on its
/// last line — so the same call twice finds its own text and is
/// `unchanged`. A text that does not lex is left to the verifier.
pub fn replace_region(file_text: &str, item: &Item, text: &str) -> (u32, u32) {
let (mut start, mut end) = (item.span.start, item.span.end);
let Ok(tokens) = tokenize(text) else {
return (start, end);
};
let Some((eof, code)) = tokens.split_last() else {
return (start, end);
};
let leads = code.first().is_some_and(|token| !token.leading.is_empty());
let trails =
eof.leading.is_empty() && code.last().is_some_and(|token| token.trailing.is_some());
if leads {
start = own_comments_start(file_text, item);
}
if let Some(comment) = item.meta.trailing.as_ref().filter(|_| trails) {
end = end.max(comment.span.end);
}
(start, end)
}
/// `end`, moved past a blank line when the removal `start..end` would leave
/// two blank lines in a row.
pub fn past_doubled_blank(text: &str, start: u32, end: u32) -> u32 {
if blank_line_before(text, start) && blank_line_at(text, end) {
return alone_after(text, end).unwrap_or(end);
}
end
}
/// The first byte of the line holding `at`.
pub fn line_start(text: &str, at: u32) -> u32 {
text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |nl| nl as u32 + 1)
}
/// Whether only spaces and tabs stand between `at` and its line's start.
pub fn alone_before(text: &str, at: u32) -> bool {
let head = text.get(line_start(text, at) as usize..at as usize).unwrap_or("x");
head.bytes().all(|b| b == b' ' || b == b'\t')
}
/// The end of the line holding `at`, past its line ending (or the file's
/// end), when only blank space follows `at` on it.
fn alone_after(text: &str, at: u32) -> Option<u32> {
let rest = text.get(at as usize..)?;
let (line, next) = match rest.find('\n') {
Some(nl) => (&rest[..nl], at + nl as u32 + 1),
None => (rest, text.len() as u32),
};
line.trim().is_empty().then_some(next)
}
/// Whether the line starting at `at` is blank (and exists).
pub fn blank_line_at(text: &str, at: u32) -> bool {
(at as usize) < text.len() && alone_after(text, at).is_some()
}
/// Whether the line ending just before `at` (a line start) is blank.
pub fn blank_line_before(text: &str, at: u32) -> bool {
at > 0 && blank_line_at(text, line_start(text, at - 1))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::project::Analysis;
/// The first item of the first module of `src`.
fn first_item(analysis: &Analysis) -> &Item {
match &analysis.tree.items[0].kind {
vlog_parser::ast::ItemKind::Module(module) => &module.items[0],
_ => panic!("not a module"),
}
}
#[test]
fn a_blank_line_ends_an_items_own_comments() {
let src = "module m;\n // banner\n\n // own\n logic a;\nendmodule\n";
let analysis = Analysis::of(src.to_string());
let item = first_item(&analysis);
let (start, end) = own_lines(src, item).unwrap();
assert_eq!(&src[start as usize..end as usize], " // own\n logic a;\n");
}
#[test]
fn a_comment_before_the_item_on_its_line_goes_with_it() {
let src = "module m;\n /* lead */ logic a;\nendmodule\n";
let analysis = Analysis::of(src.to_string());
let (start, end) = own_lines(src, first_item(&analysis)).unwrap();
assert_eq!(&src[start as usize..end as usize], " /* lead */ logic a;\n");
let shared = "module m; /* c */ logic a;\nendmodule\n";
let analysis = Analysis::of(shared.to_string());
assert!(own_lines(shared, first_item(&analysis)).is_err());
}
#[test]
fn a_text_with_comments_widens_the_replaced_span_over_the_items_own() {
let src = "module m;\n // doc\n logic a; // t\nendmodule\n";
let analysis = Analysis::of(src.to_string());
let item = first_item(&analysis);
let slice = |(s, e): (u32, u32)| &src[s as usize..e as usize];
assert_eq!(slice(replace_region(src, item, "logic b;")), "logic a;");
assert_eq!(slice(replace_region(src, item, "// x\nlogic b;")), "// doc\n logic a;");
assert_eq!(slice(replace_region(src, item, "logic b; // y")), "logic a; // t");
assert_eq!(slice(replace_region(src, item, "logic b;\n// own line")), "logic a;");
}
}
+96
View File
@@ -0,0 +1,96 @@
//! `op: delete`'s implicit-connection rule: a `.*` binds a signal without
//! spelling it, so `find_references` (which returns only spans that spell
//! the name) never lists it. For each deleted name, every `.*`
//! instantiation in the item's own scope — its sibling items and the
//! generate blocks among them, the removed bytes aside — counts as a use
//! when its module (one declaration in the project index) has a port of
//! that name, and as a *possible* use when its module does not resolve to
//! exactly one declaration.
use vlog_parser::ast::{Connections, Instantiation, Item, ItemKind};
use vlog_parser::span::TextRange;
use vlog_semantic::{SymbolKind, WorkspaceIndex};
use crate::tools::read_item::child_items;
/// One `.*` a deleted name meets: where the `.*` is written, and whether
/// the binding is certain (the module has the port) or only possible.
pub struct StarUse {
pub at: TextRange,
pub module: String,
pub certain: bool,
}
/// The `.*` connections in `scope` that bind (or may bind) `name`.
pub fn star_uses(
index: &WorkspaceIndex,
scope: &[Item],
removed: TextRange,
name: &str,
) -> Vec<StarUse> {
let mut stars = Vec::new();
collect(scope, removed, &mut stars);
stars
.into_iter()
.filter_map(|(instantiation, at)| {
let module = instantiation.module.clone();
match binds(index, &module, name) {
Some(false) => None,
Some(true) => Some(StarUse { at, module, certain: true }),
None => Some(StarUse { at, module, certain: false }),
}
})
.collect()
}
/// Every instantiation with a `.*` in `items` and the generate constructs
/// among them, outside `removed`, with the `.*`'s span.
fn collect<'a>(
items: &'a [Item],
removed: TextRange,
out: &mut Vec<(&'a Instantiation, TextRange)>,
) {
for item in items {
let inside = removed.start <= item.span.start && item.span.end <= removed.end;
if inside {
continue;
}
match &item.kind {
ItemKind::Instantiation(instantiation) => {
out.extend(wildcard(instantiation).map(|at| (instantiation, at)));
}
ItemKind::GenerateRegion { .. }
| ItemKind::GenIf(_)
| ItemKind::GenFor(_)
| ItemKind::GenCase(_)
| ItemKind::GenBlock(_) => {
for children in child_items(&item.kind) {
collect(children, removed, out);
}
}
_ => {}
}
}
}
/// The span of the first `.*` among an instantiation's connections.
fn wildcard(instantiation: &Instantiation) -> Option<TextRange> {
instantiation.instances.iter().find_map(|instance| match &instance.conns {
Connections::Named(conns) => {
conns.iter().filter_map(|conn| conn.ok()).find(|conn| conn.name == "*").map(|c| c.span)
}
Connections::Ordered(_) => None,
})
}
/// Whether `module` has a port `name`: `None` when the module does not
/// resolve to exactly one indexed module or interface.
fn binds(index: &WorkspaceIndex, module: &str, name: &str) -> Option<bool> {
let instantiable =
|kind: SymbolKind| matches!(kind, SymbolKind::Module | SymbolKind::Interface);
let declarations = index.units(module).iter().filter(|def| instantiable(def.kind)).count();
if declarations != 1 {
return None;
}
Some(index.member(module, name).iter().any(|def| def.kind == SymbolKind::Port))
}
+575
View File
@@ -0,0 +1,575 @@
//! The verifier the three structural edits share — the one new piece of
//! logic in the MCP block, so it is guilty until proven innocent: every rule
//! here has an attack in `tests/attacks.rs`.
//!
//! An edit is a [`Splice`]: the bytes `start..old_end` of the file become
//! `text`. The splice itself cannot touch a byte outside that range (it is a
//! string replacement), so what is verified is what the new bytes do to the
//! **lexing and the parse**:
//!
//! 1. the new file lexes, and parses strictly when the old one did (else its
//! tolerant error count does not grow); (1a) `text` lexes on its own;
//! (1b) every token and comment outside the region is the old file's,
//! shifted, and the text's comments attach to the text's tokens — both
//! in [`lexical`];
//! 2. every item outside the region — before it, after it, and the ones
//! enclosing it — is the same item as before: same depth, same kind
//! class, same start (items after the region shifted by the splice's
//! length change), same end. A text that leaves a block open, or closes
//! the enclosing module, moves some item's end and is refused;
//! 3. the items inside the region are what the tool expects ([`Expect`]),
//! one level below the enclosing items, and each is a kind the enclosing
//! scope may hold;
//! 4. no name is declared twice in one scope that was not already;
//! 5. the region's `` `ifdef``/`` `endif`` directives balance, in the old
//! bytes and in the new;
//! 6. the `` `define``/`` `undef`` entries inside the region are the same
//! before and after — except inside a directive or macro item at the
//! region's level, where editing the definition is the point (a deletion
//! is held to it too: the lean catalogue has no `force`, PLAN §10.1);
//! 7. the region holds the same fence markers before and after
//! ([`lexical`]).
//!
//! What is deliberately **not** verified: whether the new text makes sense —
//! its types, widths, the names it reads. `check` answers that.
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::defines::DefineKind;
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::Symbol;
use super::lexical::{self, Region};
use crate::project::Analysis;
use crate::tools::read_item::child_items;
/// Replace the bytes `start..old_end` of a file with `text`.
pub struct Splice {
pub start: u32,
pub old_end: u32,
pub text: String,
}
/// What the region must hold after the splice.
pub enum Expect {
/// Exactly one item, of this kind class (`op: replace`).
One(&'static str),
/// One item or more (`insert_before`, `insert_after`).
Some,
/// Nothing (`edit_item op: delete`).
Nothing,
}
/// A splice that passed: the new file, its analysis, and the items the
/// region now holds at its own level (kind class and span).
pub struct Outcome {
pub text: String,
pub analysis: Analysis,
pub items: Vec<(&'static str, TextRange)>,
}
/// Check `splice` against `old` (see the module comment); the refusal is one
/// sentence naming the rule broken.
pub fn check(old: &Analysis, splice: &Splice, expect: Expect) -> Result<Outcome, String> {
let text = spliced(&old.text, splice)?;
let analysis = Analysis::of(text.clone());
let new_end = splice.start + splice.text.len() as u32;
let region = Region { start: splice.start, old_end: splice.old_end, new_end };
parses_as_well(old, &analysis, &splice.text)?;
lexical::same_outside(old, &analysis, region)?;
let shift = i64::from(new_end) - i64::from(splice.old_end);
let before = split(old, &outline(&old.tree.items), splice.start, splice.old_end, shift)?;
let after = split(&analysis, &outline(&analysis.tree.items), splice.start, new_end, 0)?;
same_surroundings(old, &before, &after)?;
let level = after.enclosing.len();
let items: Vec<(&'static str, TextRange)> = after
.inside
.iter()
.filter(|node| node.depth == level)
.map(|node| (node.class, TextRange::new(node.start, node.end)))
.collect();
expected(&items, &expect)?;
let container = after.enclosing.last().map_or("file", |node| node.class);
if let Some((class, _)) = items.iter().find(|(class, _)| !fits(container, class)) {
return Err(format!("a {class} cannot stand in a {container}'s scope"));
}
same_macros(old, &analysis, region, (&before, &after))?;
no_new_duplicates(old, &analysis)?;
balanced(&old.tokens, splice.start, splice.old_end, "the old item")?;
balanced(&analysis.tokens, splice.start, new_end, "the new text")?;
lexical::same_fences(old, &analysis, region)?;
Ok(Outcome { text, analysis, items })
}
/// The old text with the splice applied; a range off a character boundary
/// is refused, never adjusted.
fn spliced(old: &str, splice: &Splice) -> Result<String, String> {
let (start, end) = (splice.start as usize, splice.old_end as usize);
match (old.get(..start), old.get(end..)) {
(Some(head), Some(tail)) if start <= end => Ok(format!("{head}{}{tail}", splice.text)),
_ => Err(format!("bytes {start}..{end} do not fall on character boundaries")),
}
}
/// Rule 1: the new file lexes, and so does `text` alone (1a); it parses
/// strictly when the old one did, and otherwise has no more tolerant parse
/// errors than the old one.
fn parses_as_well(old: &Analysis, new: &Analysis, text: &str) -> Result<(), String> {
if new.tokens.is_empty() {
return Err("the file would no longer lex (an unterminated string or comment?)".into());
}
lexical::lexes_alone(text)?;
if vlog_parser::parse_source(&old.text).is_ok() {
return vlog_parser::parse_source(&new.text)
.map(|_| ())
.map_err(|e| format!("the file would no longer parse ({e})"));
}
let (was, would) = (old.diagnostics.len(), new.diagnostics.len());
if would > was {
return Err(format!("the file already had {was} parse error(s) and would have {would}"));
}
Ok(())
}
/// One item of a file, flattened: how deep it sits, its kind class and span.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Node {
depth: usize,
class: &'static str,
start: u32,
end: u32,
}
/// Every item of a tree, depth first, in source order.
fn outline(items: &[Item]) -> Vec<Node> {
let mut out = Vec::new();
flatten(items, 0, &mut out);
out
}
fn flatten(items: &[Item], depth: usize, out: &mut Vec<Node>) {
for item in items {
let span = item.span;
out.push(Node { depth, class: class_of(&item.kind), start: span.start, end: span.end });
for children in child_items(&item.kind) {
flatten(children, depth + 1, out);
}
}
}
/// A file's items relative to a region, in the new file's coordinates.
struct Split {
/// Items wholly before or wholly after the region (the latter shifted).
outside: Vec<Node>,
/// Items containing the region (their ends shifted).
enclosing: Vec<Node>,
/// Items wholly inside it.
inside: Vec<Node>,
}
/// Sort `nodes` around `start..end`, shifting what follows by `shift`. An
/// item that begins on one side of a region boundary and ends on the other
/// is the text opening or closing something it should not: refused.
fn split(
analysis: &Analysis,
nodes: &[Node],
start: u32,
end: u32,
shift: i64,
) -> Result<Split, String> {
let moved = |at: u32| u32::try_from(i64::from(at) + shift).unwrap_or(u32::MAX);
let mut out = Split { outside: Vec::new(), enclosing: Vec::new(), inside: Vec::new() };
for node in nodes {
if end > start && start <= node.start && node.end <= end {
out.inside.push(*node);
} else if node.end <= start {
out.outside.push(*node);
} else if node.start >= end {
out.outside.push(Node { start: moved(node.start), end: moved(node.end), ..*node });
} else if node.start < start && node.end >= end {
out.enclosing.push(Node { end: moved(node.end), ..*node });
} else {
let line = analysis.lines.line_col(node.start).0;
return Err(format!(
"the {} at line {line} would begin on one side of the edit and end on the other; the text must open and close everything it starts",
node.class
));
}
}
Ok(out)
}
/// Rule 2: the items around the region are the items that were there.
fn same_surroundings(old: &Analysis, before: &Split, after: &Split) -> Result<(), String> {
let describe = |node: Option<&Node>| match node {
Some(node) => {
format!("the {} at line {}", node.class, old.lines.line_col(node.start).0)
}
None => "the end of the file".to_string(),
};
for (was, now, place) in [
(&before.enclosing, &after.enclosing, "around"),
(&before.outside, &after.outside, "outside"),
] {
if was == now {
continue;
}
let at = was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len());
return Err(format!(
"the edit would change how the file parses {place} the item ({} would not survive as it is); the text must be complete items that open and close within themselves",
describe(was.get(at).or(was.last()))
));
}
Ok(())
}
/// Rule 3: the region holds what the tool promised.
fn expected(items: &[(&'static str, TextRange)], expect: &Expect) -> Result<(), String> {
match (expect, items) {
(Expect::One(class), [(found, _)]) if found == class => Ok(()),
(Expect::One(class), [(found, _)]) => Err(format!(
"the text is a {found} where a {class} was; `replace` keeps an item's kind (`delete`, then an insert, to change it)"
)),
(Expect::One(_), many) => Err(format!(
"the text holds {} items where one was; `replace` replaces one item with one (an insert adds more)",
many.len()
)),
(Expect::Some, []) => Err("the text holds no item".into()),
(Expect::Nothing, [_, ..]) => {
Err("the deletion would leave an item behind".into())
}
_ => Ok(()),
}
}
/// The kind class of an item: the unit of "the same kind" for
/// `op: replace`, and what [`fits`] asks about. The table is the README's.
pub fn class_of(kind: &ItemKind) -> &'static str {
match kind {
ItemKind::Module(module) => match module.kw.as_str() {
"interface" => "interface",
"program" => "program",
_ => "module",
},
ItemKind::Package { .. } => "package",
ItemKind::Class(_) => "class",
ItemKind::DataDecl(_)
| ItemKind::ParamDecl(_)
| ItemKind::Typedef(_)
| ItemKind::Let(_) => "declaration",
ItemKind::PortDecl(_) => "port declaration",
ItemKind::Genvar(_) => "genvar",
ItemKind::ContAssign(_) => "assign",
ItemKind::Alias(_) => "alias",
ItemKind::Always { .. } => "always",
ItemKind::Initial(_) => "initial",
ItemKind::Final(_) => "final",
ItemKind::Instantiation(_) | ItemKind::GateInstantiation(_) => "instance",
ItemKind::Function(_) => "function",
ItemKind::Task(_) => "task",
ItemKind::GenerateRegion { .. }
| ItemKind::GenIf(_)
| ItemKind::GenFor(_)
| ItemKind::GenCase(_)
| ItemKind::GenBlock(_) => "generate",
ItemKind::Import(_) => "import",
ItemKind::Export(_) => "export",
ItemKind::Modport(_) => "modport",
ItemKind::Clocking(_) => "clocking",
ItemKind::Constraint(_) => "constraint",
ItemKind::Covergroup(_) => "covergroup",
ItemKind::PropSeqDecl(_) => "property",
ItemKind::Assertion(_) | ItemKind::DefaultDisable(_) => "assertion",
ItemKind::Verbatim(raw) => verbatim_class(&raw.text),
ItemKind::Bind(_) => "bind",
ItemKind::Defparam(_) => "defparam",
ItemKind::Timeunit(_) => "timeunit",
ItemKind::ElabTask(_) => "elaboration task",
ItemKind::MacroItem(_) => "macro",
ItemKind::Directive(_) => "directive",
ItemKind::Empty => "empty item",
ItemKind::Error(_) => "unparsed text",
}
}
/// A verbatim item's class, read off its first words: the parser keeps a
/// concurrent assertion, and a constraint or covergroup its grammar did not
/// fit, as text — the same construct the parsed kinds classify.
fn verbatim_class(text: &str) -> &'static str {
let words: Vec<&str> = text
.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.filter(|word| !word.is_empty())
.take(3)
.collect();
let has = |set: &[&str]| words.iter().any(|word| set.contains(word));
if has(&["assert", "assume", "cover", "restrict", "expect"]) {
"assertion"
} else if has(&["covergroup"]) {
"covergroup"
} else if has(&["constraint"]) {
"constraint"
} else if has(&["property", "sequence"]) {
"property"
} else {
"verbatim"
}
}
/// Kinds only a module-like body (module, interface, program, generate) holds.
const BODY_ONLY: &[&str] = &[
"always",
"initial",
"final",
"assign",
"alias",
"instance",
"generate",
"port declaration",
"modport",
"clocking",
"assertion",
"defparam",
"genvar",
"elaboration task",
];
/// Whether an item of `class` may stand directly in a `container` (a kind
/// class, or `file` for the compilation unit) — IEEE 1800 A.1: a file or a
/// package holds no processes, instances or port declarations; a package
/// or a class holds no design units; a package stands only in a file.
fn fits(container: &str, class: &str) -> bool {
let unit = matches!(class, "module" | "interface" | "program" | "package");
match container {
"file" => !BODY_ONLY.contains(&class),
"package" => !BODY_ONLY.contains(&class) && !unit,
"class" => !BODY_ONLY.contains(&class) && !unit && class != "bind",
_ => class != "package",
}
}
/// Rule 6: the macro definitions whose directives lie in the region are the
/// same before and after, those inside a directive or macro item at the
/// region's level aside — a text may not define or undefine a macro that
/// code outside it reads, except by editing the `` `define`` item itself.
fn same_macros(
old: &Analysis,
new: &Analysis,
region: Region,
(before, after): (&Split, &Split),
) -> Result<(), String> {
let was = definitions(old, region.start, region.old_end, before);
let now = definitions(new, region.start, region.new_end, after);
if was == now {
return Ok(());
}
let at =
was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len().min(now.len()));
let name = now.get(at).or(was.get(at)).map_or("", |define| define.1.as_str());
Err(format!(
"the text changes a macro definition (`{name}`) nested in an item (rule 6); edit the `define item itself"
))
}
/// A define entry as compared: kind, name, parameters, body.
type Definition = (DefineKind, String, Option<Vec<String>>, String);
/// The `` `define``/`` `undef`` entries starting in `start..end`, except those
/// inside a directive or macro item at the split's own level.
fn definitions(analysis: &Analysis, start: u32, end: u32, split: &Split) -> Vec<Definition> {
let level = split.enclosing.len();
let exempt: Vec<&Node> = split
.inside
.iter()
.filter(|node| node.depth == level && matches!(node.class, "directive" | "macro"))
.collect();
let in_exempt = |at: u32| exempt.iter().any(|node| node.start <= at && at < node.end);
analysis
.defines
.entries()
.iter()
.filter(|d| start <= d.span.start && d.span.start < end && !in_exempt(d.span.start))
.map(|d| (d.kind, d.name.clone(), d.params.clone(), d.body.clone()))
.collect()
}
/// Rule 4: every name the new file declares twice in one scope, it already
/// declared twice (counted per name).
fn no_new_duplicates(old: &Analysis, new: &Analysis) -> Result<(), String> {
let names = |analysis: &Analysis| {
let mut names: Vec<String> =
analysis.semantics.duplicates().iter().map(|d| d.name.clone()).collect();
names.sort();
names
};
let (was, now) = (names(old), names(new));
let count = |list: &[String], name: &str| list.iter().filter(|n| *n == name).count();
match now.iter().find(|name| count(&now, name) > count(&was, name)) {
Some(name) => Err(format!("`{name}` would be declared twice in one scope")),
None => Ok(()),
}
}
/// Rule 5: the conditional-compilation directives starting inside
/// `start..end` open and close within it.
fn balanced(tokens: &[Token], start: u32, end: u32, what: &str) -> Result<(), String> {
let mut depth = 0usize;
let inside = tokens
.iter()
.filter(|t| t.kind == TokenKind::Directive && start <= t.span.start && t.span.start < end);
for token in inside {
let word = token.text.split_whitespace().next().unwrap_or("");
match word {
"`ifdef" | "`ifndef" => depth += 1,
"`elsif" | "`else" if depth == 0 => return Err(unbalanced(what, word)),
"`endif" => depth = depth.checked_sub(1).ok_or_else(|| unbalanced(what, word))?,
_ => {}
}
}
if depth > 0 {
return Err(unbalanced(what, "`ifdef"));
}
Ok(())
}
fn unbalanced(what: &str, word: &str) -> String {
format!("{what} holds a `{}` whose other half is outside it", word.trim_start_matches('`'))
}
/// The declarations an item owns: those it writes (by name, or — for a
/// non-ANSI port's body declaration — by its detail) where its neighbours
/// can name them. Names bound in a scope a construct inside the item opens
/// (a module's signals, a function's arguments, an unnamed `begin`'s
/// locals) are the item's business; the header scope a generate loop opens
/// for its genvar and label, which spans exactly the item, is see-through.
pub fn owned(analysis: &Analysis, span: TextRange) -> Vec<&Symbol> {
let within = |inner: TextRange| span.start <= inner.start && inner.end <= span.end;
analysis
.semantics
.symbols()
.iter()
.filter(|symbol| within(symbol.name_span) || symbol.detail_span.is_some_and(within))
.filter(|symbol| seen_from_outside(analysis, symbol, span))
.collect()
}
/// Whether every scope between `symbol` and the first scope outside `span`
/// is one the item opened around itself (unnamed, spanning exactly it).
fn seen_from_outside(analysis: &Analysis, symbol: &Symbol, span: TextRange) -> bool {
let semantics = &analysis.semantics;
let mut at = Some(symbol.scope);
while let Some(id) = at {
// The file scope may span exactly the item when the file is that
// item and nothing else; it is never the item's own.
let Some(scope) = semantics.scope(id).filter(|_| id != semantics.file_scope()) else {
return true;
};
let inside = span.start <= scope.span.start && scope.span.end <= span.end;
if !inside {
return true;
}
if scope.owner.is_some() || scope.span != span {
return false;
}
at = scope.parent;
}
true
}
/// The names [`owned`] finds, sorted.
pub fn owned_names(analysis: &Analysis, span: TextRange) -> Vec<String> {
let mut names: Vec<String> =
owned(analysis, span).into_iter().map(|symbol| symbol.name.clone()).collect();
names.sort();
names
}
#[cfg(test)]
mod tests {
use super::*;
const SRC: &str = "module m (input logic d);\n logic a;\n always_comb a = d;\nendmodule\n";
fn run(start: u32, old_end: u32, text: &str, expect: Expect) -> Result<Outcome, String> {
let old = Analysis::of(SRC.to_string());
check(&old, &Splice { start, old_end, text: text.into() }, expect)
}
fn span_of(needle: &str) -> (u32, u32) {
let at = SRC.find(needle).unwrap() as u32;
(at, at + needle.len() as u32)
}
#[test]
fn a_same_kind_item_passes_and_reports_its_span() {
let (start, end) = span_of("logic a;");
let outcome = run(start, end, "logic [3:0] a;", Expect::One("declaration")).unwrap();
assert_eq!(outcome.items.len(), 1);
assert_eq!(outcome.items[0].1, TextRange::new(start, start + 14));
assert!(outcome.text.contains(" logic [3:0] a;\n always_comb"));
}
#[test]
fn each_rule_refuses_with_its_own_sentence() {
let (start, end) = span_of("logic a;");
let open = run(start, end, "always_comb begin a = d;", Expect::One("declaration"));
assert!(open.err().unwrap().contains("no longer parse"));
let closes = run(start, end, "logic a;\nendmodule\nmodule z;", Expect::One("declaration"));
assert!(closes.err().unwrap().contains("open and close"));
let two = run(start, end, "logic a; logic b;", Expect::One("declaration"));
assert!(two.err().unwrap().contains("holds 2 items"));
let kind = run(start, end, "initial a = 0;", Expect::One("declaration"));
assert!(kind.err().unwrap().contains("initial where a declaration was"));
let twice = run(start, end, "logic d;", Expect::One("declaration"));
assert!(twice.err().unwrap().contains("`d` would be declared twice"));
let half = run(start, end, "`ifdef X\nlogic a;", Expect::Some);
assert!(half.err().unwrap().contains("`ifdef"), "half");
let split = run(start + 1, end, "x", Expect::Some);
assert!(split.is_err());
}
#[test]
fn a_file_scope_insert_must_be_a_kind_the_file_may_hold() {
let at = SRC.len() as u32;
let always = run(at, at, "always_comb x = 1;\n", Expect::Some);
assert!(always.err().unwrap().contains("always cannot stand in a file's scope"));
assert!(run(at, at, "module z; endmodule\n", Expect::Some).is_ok());
}
#[test]
fn verbatim_items_are_classed_by_their_words() {
assert_eq!(verbatim_class("a1: assert property (p);"), "assertion");
assert_eq!(verbatim_class("covergroup cg @(e); endgroup"), "covergroup");
assert_eq!(verbatim_class("static constraint c { x; }"), "constraint");
assert_eq!(verbatim_class("sequence s; a; endsequence"), "property");
assert_eq!(verbatim_class("?"), "verbatim");
assert!(fits("module", "always") && !fits("package", "module") && !fits("class", "bind"));
}
#[test]
fn owned_names_are_the_ones_bound_around_the_item() {
let analysis = Analysis::of(SRC.to_string());
let whole = TextRange::new(0, SRC.len() as u32 - 1);
assert_eq!(owned_names(&analysis, whole), ["m"]);
let (start, end) = span_of("logic a;");
assert_eq!(owned_names(&analysis, TextRange::new(start, end)), ["a"]);
let (start, end) = span_of("always_comb a = d;");
assert!(owned_names(&analysis, TextRange::new(start, end)).is_empty());
}
#[test]
fn a_generate_loop_owns_its_label_and_an_unnamed_begin_keeps_its_locals() {
let src = "module g;\n for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end\n always begin\n int k;\n end\nendmodule\n";
let analysis = Analysis::of(src.to_string());
let span = |needle: &str, len: usize| {
let at = src.find(needle).unwrap() as u32;
TextRange::new(at, at + len as u32)
};
let lp = span(
"for (genvar",
"for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end".len(),
);
assert_eq!(owned_names(&analysis, lp), ["gen_l", "i"]);
let always = span("always begin", "always begin\n int k;\n end".len());
assert!(owned_names(&analysis, always).is_empty());
}
}
+347
View File
@@ -0,0 +1,347 @@
//! Unresolved mentions: every whole-word spelling of a name that no engine
//! answer accounted for and that sits where no lucisv engine looks — inside
//! a string literal, a comment, a macro call's text, a `` `define`` body, or
//! a hierarchical path rooted at a macro (`` `X_HIER.u_core.name``).
//!
//! These are the spellings a rename leaves behind without a word: a DV
//! force path built as the string `".state_q"`, a probe through a macro
//! path, a comment naming the signal. lucisv cannot tell whether any of them
//! means *this* declaration — a word is a word — so they are listed, never
//! edited, and the agent decides (feedback round 1, `mcp_analysis.md`).
//!
//! The pass reads nothing new: the engines were handed every indexed file's
//! text already (`source::WholeSet`), so each text is byte-searched for the
//! name, and only a text that spells it is lexed. The index's word censuses
//! (`files_mentioning`, `files_naming_in_macros`) cannot narrow it further:
//! comments and strings are not in them.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{tokenize, LineIndex};
use super::source::word_in;
use crate::project::Project;
use crate::render;
/// The most mentions an answer lists; the rest are counted.
pub const CAP: usize = 50;
/// One unresolved spelling: the file and line that hold it.
pub struct Mention {
pub file: String,
pub line: u32,
}
/// The mentions an answer lists (at most [`CAP`]) and how many there are.
#[derive(Default)]
pub struct Mentions {
pub listed: Vec<Mention>,
pub total: usize,
}
/// What the search is about: the name, where it is declared (the listing
/// starts nearest to it), and the spans the engine already accounted for.
pub struct Focus<'a> {
pub name: &'a str,
/// The declaration's file.
pub home: &'a Path,
/// The unit declaring the name, when known: a line naming it (an
/// instance `u_<unit>` on a macro path) is listed early.
pub unit: Option<&'a str>,
/// Per file, the spans an engine returned (hits) or rewrote (edits).
pub accounted: &'a [(PathBuf, Vec<TextRange>)],
/// `(file, line)` pairs an engine warning already names — a `rename`'s
/// unresolved-path warning — which are not repeated as mentions.
pub named: &'a [(String, u32)],
/// For a member of a module or interface (a net, a port, a block, …):
/// the files where a bare spelling can mean it — its home set: the
/// declaring file, what it includes and what includes it, and the files
/// the edit wrote or the engine found uses in. Elsewhere only a
/// spelling right after a `.` (`".state_q"`, `` `HIER.u.state_q``) is
/// listed. `None` for a name any file may spell bare (a unit, a package
/// member): every mention is listed.
pub local: Option<&'a [PathBuf]>,
}
impl Mentions {
/// Whether there is nothing to say.
pub fn is_empty(&self) -> bool {
self.total == 0
}
/// The `unresolved:` block an answer ends with — the label, then the
/// mentions one file per line (`file:12,40`), then the cut — or nothing.
pub fn block(&self) -> Vec<String> {
if self.is_empty() {
return Vec::new();
}
let sites: Vec<(String, u32)> =
self.listed.iter().map(|m| (m.file.clone(), m.line)).collect();
let mut out = vec!["unresolved:".to_string()];
out.extend(render::by_file(&sites).into_iter().map(|line| format!(" {line}")));
let rest = self.total - self.listed.len();
if rest > 0 {
out.push(format!(" {}", render::more(rest)));
}
out
}
}
/// The unresolved mentions of `focus.name` across `files`, nearest first.
pub fn find<'t>(
project: &Project,
files: impl Iterator<Item = (&'t Path, &'t str)>,
focus: &Focus,
) -> Mentions {
let mut found: Vec<(u8, usize, Mention)> = Vec::new();
for (path, text) in files {
if !text.contains(focus.name) {
continue;
}
let accounted = focus.accounted.iter().find(|(held, _)| held.as_path() == path);
let spans = accounted.map_or(&[][..], |(_, spans)| spans.as_slice());
let lines = LineIndex::new(text);
let mut last_line = 0;
let foreign = focus.local.is_some_and(|local| !local.iter().any(|p| p == path));
for (at, _) in spellings(text, focus.name) {
if foreign
&& !text.as_bytes().get((at as usize).wrapping_sub(1)).is_some_and(|&b| b == b'.')
{
continue;
}
let end = at + focus.name.len() as u32;
if spans.iter().any(|span| span.start <= at && end <= span.end) {
continue;
}
let line = lines.line_col(at).0;
if line == last_line {
continue;
}
last_line = line;
let source = lines
.line_range(line)
.and_then(|range| text.get(range.start as usize..range.end as usize))
.unwrap_or("");
let rank = rank(accounted.is_some(), focus.unit, source);
let mention = Mention { file: project.relative(path), line };
if focus.named.iter().any(|(file, at)| *file == mention.file && *at == line) {
continue;
}
found.push((rank, shared_components(path, focus.home), mention));
}
}
// Files the engine touched, then lines naming the declaring unit, then
// nearest to the declaration's directory; file and line order within.
found.sort_by(|a, b| (b.0, b.1, &a.2.file, a.2.line).cmp(&(a.0, a.1, &b.2.file, b.2.line)));
let total = found.len();
let listed = found.into_iter().take(CAP).map(|(_, _, mention)| mention).collect();
Mentions { listed, total }
}
/// How early a mention is listed: 2 in a file the engine touched, 1 on a
/// line that spells the declaring unit's name (`u_<unit>` included), 0
/// otherwise.
fn rank(touched: bool, unit: Option<&str>, line: &str) -> u8 {
if touched {
2
} else if unit.is_some_and(|unit| !unit.is_empty() && line.contains(unit)) {
1
} else {
0
}
}
/// How many leading path components two paths share.
fn shared_components(a: &Path, b: &Path) -> usize {
a.components().zip(b.components()).take_while(|(x, y)| x == y).count()
}
/// Every whole-word spelling of `name` in `text` that lies in a comment, a
/// string, a macro call, a `` `define`` body, or ends a macro-rooted path,
/// as `(byte offset, kind)` in source order. A file that does not lex has
/// every spelling listed (`text`): nothing in it was resolved.
fn spellings(text: &str, name: &str) -> Vec<(u32, &'static str)> {
let Ok(tokens) = tokenize(text) else {
return words(text, 0, name).into_iter().map(|at| (at, "text")).collect();
};
let mut out = Vec::new();
for (i, token) in tokens.iter().enumerate() {
for comment in token.leading.iter().chain(token.trailing.as_ref()) {
let at = comment.span.start;
out.extend(words(&comment.text, at, name).into_iter().map(|at| (at, "comment")));
}
let (at, source) = (token.span.start, token.text.as_str());
match token.kind {
TokenKind::String => {
out.extend(words(source, at, name).into_iter().map(|at| (at, "string")))
}
TokenKind::Ident if token.is_macro() => {
let after = macro_name_end(source);
let found = words(&source[after..], at + after as u32, name);
out.extend(found.into_iter().map(|at| (at, "macro")));
}
TokenKind::Directive => {
let Some((formals, body)) = define_parts(source) else { continue };
// A formal argument of that name shadows it in the body.
if word_in(&source[formals..body], name).is_some() {
continue;
}
let found = words(&source[body..], at + body as u32, name);
out.extend(found.into_iter().map(|at| (at, "define")));
}
TokenKind::Ident if token.text == name && macro_rooted(&tokens, i) => {
out.push((at, "path"));
}
_ => {}
}
}
out.sort_by_key(|(at, _)| *at);
out
}
/// Every whole-word occurrence of `name` in `text`, as offsets from `base`.
fn words(text: &str, base: u32, name: &str) -> Vec<u32> {
let mut out = Vec::new();
let mut from = 0;
while let Some(found) = text.get(from..).and_then(|rest| word_in(rest, name)) {
out.push(base + (from + found) as u32);
from += found + name.len();
}
out
}
/// Where a macro use's own name ends (`` `NAME`` then its arguments).
fn macro_name_end(text: &str) -> usize {
1 + ident_len(text.get(1..).unwrap_or(""))
}
/// The length of the identifier `text` starts with.
fn ident_len(text: &str) -> usize {
let glued = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$';
text.find(|c: char| !glued(c)).unwrap_or(text.len())
}
/// A `` `define`` directive's formal argument list and body: where the list
/// starts (past the macro's name) and where the body starts (past the list).
/// `None` for any other directive.
fn define_parts(text: &str) -> Option<(usize, usize)> {
let rest = text.strip_prefix("`define")?;
let name_at = text.len() - rest.trim_start().len();
let formals = name_at + ident_len(&text[name_at..]);
if !text[formals..].starts_with('(') {
return Some((formals, formals));
}
let mut depth = 0usize;
for (offset, c) in text[formals..].char_indices() {
match c {
'(' => depth += 1,
')' if depth == 1 => return Some((formals, formals + offset + 1)),
')' => depth = depth.saturating_sub(1),
_ => {}
}
}
Some((formals, text.len()))
}
/// Whether the identifier at `i` ends a dotted path whose head is a macro
/// (`` `HIER.u_a[0].name``, `` `HIER(1).name``) — a path no engine follows.
fn macro_rooted(tokens: &[Token], i: usize) -> bool {
let symbol = |at: usize, text: &str| {
tokens.get(at).is_some_and(|t| t.kind == TokenKind::Symbol && t.text == text)
};
let mut at = i;
loop {
if at < 2 || !symbol(at - 1, ".") {
return false;
}
let mut head = at - 2;
// Skip the selects of the segment before the dot: `u_a[0][1]`.
while symbol(head, "]") {
let mut depth = 0usize;
loop {
if symbol(head, "]") {
depth += 1;
} else if symbol(head, "[") {
depth -= 1;
if depth == 0 {
break;
}
}
let Some(before) = head.checked_sub(1) else { return false };
head = before;
}
let Some(before) = head.checked_sub(1) else { return false };
head = before;
}
match tokens.get(head) {
Some(token) if token.is_macro() => return true,
Some(token) if token.kind == TokenKind::Ident => at = head,
_ => return false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(src: &str, name: &str) -> Vec<(u32, &'static str)> {
spellings(src, name)
}
fn lines_of(src: &str, name: &str) -> Vec<(u32, &'static str)> {
let lines = LineIndex::new(src);
spellings(src, name).into_iter().map(|(at, kind)| (lines.line_col(at).0, kind)).collect()
}
#[test]
fn strings_comments_macro_text_and_macro_paths_are_found() {
let src = "module m;\n\
// state_q holds the state\n\
logic state_q;\n\
initial $display(\"%m.state_q\");\n\
`ASSERT(A, state_q == 0)\n\
`define PROBE(x) x.state_q\n\
assign o = `HIER.u_fsm[0].state_q;\n\
assign p = `SPI(1).u.state_q;\n\
assign q = u_fsm.state_q;\n\
endmodule /* state_q */\n";
assert_eq!(
lines_of(src, "state_q"),
[
(2, "comment"),
(4, "string"),
(5, "macro"),
(6, "define"),
(7, "path"),
(8, "path"),
(10, "comment"),
]
);
}
#[test]
fn a_word_inside_another_and_a_formal_argument_are_not_mentions() {
assert!(kinds("// state_qq and xstate_q\n", "state_q").is_empty());
assert!(kinds("`define F(state_q) state_q + 1\n", "state_q").is_empty());
assert!(kinds("`define G(a) a\n", "a").is_empty());
assert!(kinds("`state_q\n", "state_q").is_empty(), "a macro's own name");
assert_eq!(kinds("`ifdef state_q\n`endif\n", "state_q"), []);
}
#[test]
fn a_file_that_does_not_lex_lists_every_spelling() {
assert_eq!(kinds("x = \"state_q\n state_q", "state_q").len(), 2);
}
#[test]
fn ranking_prefers_touched_files_then_the_unit_then_nearness() {
assert_eq!(rank(true, None, ""), 2);
assert_eq!(rank(false, Some("main_sm"), "`HIER.u_main_sm.state_q"), 1);
assert_eq!(rank(false, Some("main_sm"), "`HIER.u_ack_sm.state_q"), 0);
let (a, b) = (Path::new("/hw/ip/es/rtl/a.sv"), Path::new("/hw/ip/es/dv/b.sv"));
assert_eq!(shared_components(a, b), 4);
}
}
+315
View File
@@ -0,0 +1,315 @@
//! 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 declared;
mod diagnostics;
mod edit;
mod find;
mod format;
mod glob;
mod hierarchy;
mod interface;
mod item;
mod mentions;
mod names;
mod outline;
mod place;
mod port;
mod read;
mod read_item;
mod source;
use serde_json::{json, Map, Value};
use crate::project::Project;
/// What a tool hands back: the text the agent reads. A result is its text;
/// there is no structured twin (PLAN §10.1).
pub struct Answer {
pub text: String,
}
impl Answer {
/// An answer of these lines, each ended by a newline.
pub fn lines(lines: Vec<String>) -> Answer {
let mut text = String::new();
for line in lines {
text.push_str(&line);
text.push('\n');
}
Answer { text }
}
}
/// 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,
/// One of a fixed set of strings.
Enum(&'static [&'static str]),
/// `true` or `false`.
Bool,
/// An integer inside `min..=max` — checked here; the schema says only
/// `integer`, the tool's description names the range.
Range { min: i64, max: i64 },
}
/// One argument a tool takes. It has no description of its own: the tool's
/// one description names its arguments (PLAN §10.1).
pub struct Param {
pub name: &'static str,
pub ty: Ty,
pub required: bool,
}
/// One tool, as `tools/list` shows it and `tools/call` runs it.
pub struct Tool {
pub name: &'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 part of the whole set an edit needs.
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. `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)] = &[
(hierarchy::HIERARCHY, Read),
(find::FIND, Read),
(outline::OUTLINE, Read),
(read::READ, Read),
(diagnostics::CHECK, Read),
(edit::RENAME, Edit { idempotent: false }),
(port::PORT, Edit { idempotent: false }),
(item::EDIT_ITEM, Edit { idempotent: false }),
(format::FORMAT, Edit { idempotent: true }),
];
/// Which part of the registry the server offers (PLAN §11).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mode {
/// Every tool, the edits included.
#[default]
Full,
/// `--read-only`: the read tools alone; an edit tool is unknown.
ReadOnly,
}
impl Mode {
/// Whether a tool of this effect exists in this mode.
fn offers(self, effect: Effect) -> bool {
matches!((self, effect), (Mode::Full, _) | (Mode::ReadOnly, Read))
}
}
/// The tools `mode` offers, in `tools/list` order.
fn offered(mode: Mode) -> impl Iterator<Item = (&'static Tool, Effect)> {
TOOLS
.iter()
.filter(move |(_, effect)| mode.offers(*effect))
.map(|(tool, effect)| (tool, *effect))
}
/// The tool called `name`, when `mode` offers it.
pub fn find(name: &str, mode: Mode) -> Option<&'static Tool> {
offered(mode).map(|(tool, _)| tool).find(|tool| tool.name == name)
}
/// The `tools/list` result: every tool `mode` offers, no pagination.
pub fn list(mode: Mode) -> Value {
let tools: Vec<Value> = offered(mode).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, all or nothing.
let (read_only, idempotent) = match effect {
Read => (true, true),
Edit { idempotent } => (false, idempotent),
};
json!({
"name": tool.name,
"description": tool.description,
"inputSchema": schema(tool.params),
// Hosts read these; the model never sees them (PLAN §10.1).
"annotations": {
"readOnlyHint": read_only,
"destructiveHint": false,
"idempotentHint": idempotent,
"openWorldHint": false,
},
})
}
/// A JSON Schema object for an argument list: closed, with its required
/// set, and `type` alone per property (an `enum` where one applies).
fn schema(params: &[Param]) -> Value {
let mut properties = Map::new();
for param in params {
let property = match param.ty {
Ty::Str => json!({ "type": "string" }),
Ty::Enum(values) => json!({ "type": "string", "enum": values }),
Ty::Bool => json!({ "type": "boolean" }),
Ty::Range { .. } => json!({ "type": "integer" }),
};
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)
}
/// A boolean argument; `false` when absent.
pub fn flag(&self, name: &str) -> bool {
self.0.get(name).and_then(Value::as_bool).unwrap_or(false)
}
/// A non-negative integer argument, or `default`.
pub fn count(&self, name: &str, default: usize) -> usize {
let given = self.0.get(name).and_then(Value::as_i64);
given.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::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::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_bare_and_every_name_is_unique() {
for (tool, _) in TOOLS {
let schema = schema(tool.params);
assert_eq!(schema["additionalProperties"], false, "{}", tool.name);
assert!(schema["required"].is_array(), "{}", tool.name);
for (name, property) in schema["properties"].as_object().unwrap() {
let keys: Vec<&String> = property.as_object().unwrap().keys().collect();
assert!(keys.iter().all(|k| *k == "type" || *k == "enum"), "{name}: {keys:?}");
}
assert!(!tool.description.is_empty() && tool.description.len() < 300, "{}", 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 read_only_mode_offers_the_read_tools_alone_in_order() {
let names = |mode| -> Vec<&str> { offered(mode).map(|(tool, _)| tool.name).collect() };
assert_eq!(names(Mode::ReadOnly), ["hierarchy", "find", "outline", "read", "check"]);
assert_eq!(names(Mode::Full).len(), TOOLS.len());
for edit in ["rename", "port", "edit_item", "format"] {
assert!(find(edit, Mode::ReadOnly).is_none(), "{edit}");
assert!(find(edit, Mode::Full).is_some(), "{edit}");
}
}
#[test]
fn validation_names_the_offending_argument() {
let find = |name| find(name, Mode::Full);
let tool = find("check").unwrap();
let unknown = validate(tool, args(json!({"fil": "x"}))).err().unwrap();
assert!(unknown.contains("`fil`") && unknown.contains("file"), "{unknown}");
let wrong = validate(tool, args(json!({"file": 3}))).err().unwrap();
assert!(wrong.contains("`file`") && wrong.contains("a string"), "{wrong}");
let missing = validate(find("read").unwrap(), Map::new()).err().unwrap();
assert!(missing.contains("`item`"), "{missing}");
assert!(validate(tool, args(json!({"file": null}))).is_ok());
let edit = find("edit_item").unwrap();
let op = json!({"file": "a.sv", "op": "move", "item": "x"});
let op = validate(edit, args(op)).err().unwrap();
assert!(op.contains("`op`") && op.contains("replace"), "{op}");
let hierarchy = find("hierarchy").unwrap();
let flag = validate(hierarchy, args(json!({"up": "yes"}))).err().unwrap();
assert!(flag.contains("true or false"), "{flag}");
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"], json!({"type": "integer"}));
}
}
+234
View File
@@ -0,0 +1,234 @@
//! Names looked up — the by-name half every lean tool shares: every
//! declaration of a name (the index's units, exported members and module
//! internals, every declaration the files' own symbol tables hold, and the
//! `` `define``s), each read off the bytes on disk, and the near matches a
//! refusal lists when there is none — from the same table — so the next
//! call is right.
use std::collections::{BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_semantic::{Def, DefinitionKey, FileId, Surface, SymbolKind, WorkspaceIndex};
use super::declared::{declared, Local, Wanted};
use super::source::{checked_site, Texts};
use crate::project::Project;
use crate::render;
/// One declaration of a name, where it is written.
pub struct Declaration {
pub path: PathBuf,
/// The byte offset of the name itself.
pub offset: u32,
/// The kind word (`macro` for a `` `define``).
pub kind: &'static str,
pub file: String,
pub line: u32,
}
impl Declaration {
/// `kind name file:line`, as `find` lists it.
pub fn render(&self, name: &str) -> String {
format!("{} {name} {}:{}", self.kind, self.file, self.line)
}
/// Whether this is a `` `define`` (no engine follows its uses).
pub fn is_macro(&self) -> bool {
self.kind == "macro"
}
}
/// A name as written, split into the unit it is qualified by (`unit.name`,
/// `pkg::name`) and the name itself; an escaped identifier is never split.
pub fn qualified(name: &str) -> (Option<&str>, &str) {
if name.starts_with('\\') {
return (None, name);
}
let split = name.rsplit_once("::").or_else(|| name.rsplit_once('.'));
match split {
Some((unit, member)) if !unit.is_empty() && !member.is_empty() => (Some(unit), member),
_ => (None, name),
}
}
/// Every declaration of `name` — its declarations first, then its
/// `` `define``s — each whose file still spells the name there, in file
/// and line order within each group. `unit.name` (or `pkg::name`) is the
/// member of that unit only.
pub fn declarations(project: &Project, name: &str) -> Vec<Declaration> {
let index = project.index();
let (unit, name) = qualified(name);
let mut texts = Texts::default();
let mut out: Vec<Declaration> = Vec::new();
let defs = match unit {
Some(unit) => index.member_in(unit, name, Surface::Hierarchical).to_vec(),
None => defs_named(index, name),
};
for def in defs {
let Some(path) = index.path(def.file) else { continue };
let shown = def.detail_span.unwrap_or(def.name_span);
let kind = unit_kind(project, path, &def);
let site = checked_site(project, &mut texts, path, def.name_span, shown, name);
if let Some(site) = site {
let offset = def.name_span.start;
let (file, line) = (site.file, site.line);
out.push(Declaration { path: path.to_path_buf(), offset, kind, file, line });
}
}
let locals = declared(project, &Wanted::Exact(name));
let in_unit = |local: &&Local| unit.is_none_or(|unit| local.unit.as_deref() == Some(unit));
for local in locals.iter().filter(in_unit) {
let known = out.iter().any(|d| d.path == local.path && d.offset == local.offset);
if !known {
out.push(Declaration {
path: local.path.clone(),
offset: local.offset,
kind: local.kind,
file: project.relative(&local.path),
line: local.line,
});
}
}
out.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
out.dedup_by(|a, b| (&a.file, a.line, a.offset) == (&b.file, b.line, b.offset));
if unit.is_some() {
return out;
}
let mut macros = macro_declarations(project, &mut texts, name);
macros.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
out.extend(macros);
out
}
/// Every indexed non-macro declaration of `name`, each once.
fn defs_named(index: &WorkspaceIndex, name: &str) -> Vec<Def> {
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 = HashSet::new();
defs.retain(|def| seen.insert(DefinitionKey::of(def)));
defs
}
/// Every indexed `` `define`` of `name` whose file still spells it there.
fn macro_declarations(project: &Project, texts: &mut Texts, name: &str) -> Vec<Declaration> {
let index = project.index();
let defined = index.find_define(name).into_iter().filter(|(_, d)| d.kind == DefineKind::Define);
defined
.filter_map(|(file, define)| {
let path = index.path(file)?;
let span = define.name_span;
let site = checked_site(project, texts, path, span, span, name)?;
let (file, line) = (site.file, site.line);
Some(Declaration {
path: path.to_path_buf(),
offset: span.start,
kind: "macro",
file,
line,
})
})
.collect()
}
/// A declaration's kind word, telling a `program` from the module it is
/// modelled as.
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"))
}
/// Every declaration of `name`, walking the roots once first when the index
/// holds none (a file written since the last walk).
pub fn declarations_walking(project: &mut Project, name: &str) -> Vec<Declaration> {
let found = declarations(project, name);
if found.is_empty() && project.ensure_walked_for_miss() {
return declarations(project, name);
}
found
}
/// The refusal for a name nothing declares: the near matches, when any.
pub fn no_declaration(project: &Project, name: &str) -> String {
let similar = similar(project, qualified(name).1, 20);
match similar.is_empty() {
true => format!("no declaration named `{name}`."),
false => format!("no declaration named `{name}`; similar: {}.", similar.join(", ")),
}
}
/// Up to `cap` declared names (and macros) that contain `name`, any case —
/// the declarations [`declarations`] would list, read from the same table.
pub fn similar(project: &Project, name: &str, cap: usize) -> Vec<String> {
let index = project.index();
let mut names: BTreeSet<String> =
index.workspace_symbols(name).iter().map(|hit| hit.name.to_string()).collect();
let part = Wanted::Containing(name.to_ascii_lowercase());
names.extend(declared(project, &part).into_iter().map(|local| local.name));
for at in 0..index.files().len() {
let Some(table) = index.defines(FileId(at as u32)) else { continue };
let found = table.entries().iter().filter(|d| contains_any_case(&d.name, name));
names.extend(found.map(|define| define.name.clone()));
}
names.into_iter().filter(|found| found != name).take(cap).collect()
}
/// Up to `cap` module or interface names that contain `name`, any case.
pub fn similar_units(index: &WorkspaceIndex, name: &str, cap: usize) -> Vec<String> {
let mut names: Vec<String> = index
.instantiable_units()
.map(|(unit, _)| unit)
.filter(|unit| contains_any_case(unit, name))
.map(str::to_string)
.collect();
names.dedup();
names.truncate(cap);
names
}
fn contains_any_case(text: &str, part: &str) -> bool {
text.to_ascii_lowercase().contains(&part.to_ascii_lowercase())
}
/// The refusal for a name declared more than once: every site, and what
/// picks one.
pub fn ambiguous(name: &str, found: &[&Declaration], pick: &str) -> String {
let sites: Vec<String> = found.iter().map(|d| format!("{}:{}", d.file, d.line)).collect();
format!("`{name}` is declared {} times ({}); {pick}.", sites.len(), sites.join(", "))
}
#[cfg(test)]
mod tests {
use super::qualified;
#[test]
fn a_unit_qualifies_a_name_and_an_escaped_name_is_whole() {
assert_eq!(qualified("core.state_q"), (Some("core"), "state_q"));
assert_eq!(qualified("pkg::W"), (Some("pkg"), "W"));
assert_eq!(qualified("a::b::c"), (Some("a::b"), "c"));
assert_eq!(qualified("state_q"), (None, "state_q"));
assert_eq!(qualified("\\a.b "), (None, "\\a.b "));
assert_eq!(qualified(".x"), (None, ".x"));
}
}
+61
View File
@@ -0,0 +1,61 @@
//! `outline`: a file's declarations as a tree with line ranges (its parse
//! errors first), or — for `unit` — what a unit offers the code that uses
//! it (`interface.rs`), so an agent reads the shape before the source.
use vlog_semantic::DocumentSymbol;
use super::interface;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render;
/// The most lines an answer holds before `… and N more`.
pub const CAP: usize = 300;
pub const OUTLINE: Tool = Tool {
name: "outline",
description: "Exactly one of: `file`, its declarations as a tree with line ranges, parse errors first; `unit`, its file:line, parameters and ports in order (modports, package members).",
params: &[
Param { name: "file", ty: Ty::Str, required: false },
Param { name: "unit", ty: Ty::Str, required: false },
],
rewalk: false,
handler: outline,
};
fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
let lines = match (args.str("file"), args.str("unit")) {
(Some(file), None) => file_outline(project, file)?,
(None, Some(unit)) => interface::unit_outline(project, unit.trim())?,
_ => return Err("give exactly one of `file` and `unit`.".into()),
};
Ok(Answer::lines(render::capped(lines, CAP)))
}
/// `error LINE: message` per parse error, then `kind name first–last`,
/// two spaces per level.
pub fn file_outline(project: &mut Project, file: &str) -> Result<Vec<String>, String> {
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let mut lines: Vec<String> = analysis
.diagnostics
.iter()
.map(|error| format!("error {}: {}", error.line, render::one_line(&error.message)))
.collect();
tree(&analysis, &analysis.semantics.document_symbols(), 0, &mut lines);
Ok(lines)
}
/// The outline tree in pre-order.
fn tree(analysis: &Analysis, nodes: &[DocumentSymbol], level: usize, out: &mut Vec<String>) {
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);
let (kind, name) = (render::kind(symbol.kind), &symbol.name);
let indent = " ".repeat(level);
out.push(format!("{indent}{kind} {name} {}", render::lines(first, last)));
tree(analysis, &node.children, level + 1, out);
}
}
+448
View File
@@ -0,0 +1,448 @@
//! `port`'s `after`: the new port placed right after a named one, in the
//! layout of the line it follows, and each named connection placed right
//! after the instance's `.after(…)`.
//!
//! The engine (`vlog_refactor::add_port`) only appends. So it runs first,
//! unchanged, and its verified edit is the reference: this module moves the
//! header's new element, and each instance's new connection, to the slot
//! after the anchor's separator ([`slot`]) — and then checks that the
//! result is the engine's result with elements moved and nothing else
//! ([`verify`]).
//!
//! What it refuses (the engine's refusals come first): a non-ANSI or empty
//! port list; a port list, or the connection list of an instance it would
//! place into, holding an element the parser could not read (it cannot see
//! what that element inherits or binds — QA finding 5); an `after` that is
//! not a port; a next port that would inherit from the new one; an anchor
//! inside an `` `ifdef`` arm; and a positional instantiation unless `after`
//! is the last port. An instance whose connection cannot be placed (no
//! `.after(…)`, an `` `ifdef`` around it) keeps the engine's appended
//! connection and is said under `warnings`.
mod slot;
mod verify;
use std::path::{Path, PathBuf};
use vlog_parser::ast::{AnsiPort, Connections, Instance, Item, ItemKind, ListDirective};
use vlog_parser::ast::{ListElem, Module, PortList, RawText};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_refactor::{RefactorEdit, TextEdit};
use super::read_item::child_items;
use crate::render::one_line;
use slot::{aligned_connection, aligned_port, slot};
/// What is being placed: the module, where it is written, the anchor port,
/// the new port's name and declaration, and how a file is named in a
/// sentence (root-relative, as every answer names it).
pub struct Spec<'a> {
pub module: &'a str,
pub file: &'a Path,
pub after: &'a str,
pub port: &'a str,
pub declaration: &'a str,
pub show: &'a dyn Fn(&Path) -> String,
}
/// The engine's appending `edit`, re-placed after `spec.after` and
/// verified against it; the warnings name each instance left appended.
pub fn after(
files: &[(PathBuf, String)],
edit: &RefactorEdit,
spec: &Spec,
) -> Result<RefactorEdit, String> {
let home = text_of(files, spec.file)?;
let (tree, _) = parse_source_tolerant(home);
let module = find_module(&tree.items, spec.module)
.ok_or_else(|| format!("lucisv can no longer find `{}`.", spec.module))?;
let (header, region, last_port) = header(home, module, spec)?;
let mut placed = RefactorEdit { warnings: edit.warnings.clone(), ..RefactorEdit::default() };
for (path, edits) in &edit.edits {
let mut kept: Vec<TextEdit> = edits.clone();
if path == spec.file {
kept.retain(|edit| !region.contains(edit.range.start));
kept.extend(header.iter().cloned());
}
let text = text_of(files, path)?;
let tokens = lexed(text, spec, path)?;
let (tree, _) = parse_source_tolerant(text);
let mut instances = Vec::new();
collect_instances(&tree.items, spec.module, &mut instances);
for instance in instances {
let inside = |edit: &TextEdit| {
instance.span.start <= edit.range.start && edit.range.start <= instance.span.end
};
let appended: Vec<TextEdit> = kept.iter().filter(|e| inside(e)).cloned().collect();
if appended.is_empty() || positional(instance, last_port, spec, path)? {
continue;
}
let at = || format!("`{}` in {}", instance.name, (spec.show)(path));
if let Some(raw) = unreadable_connection(instance) {
return Err(unreadable(&at(), raw));
}
match connection(text, &tokens, instance, &appended, spec) {
Ok(edits) => {
kept.retain(|edit| !inside(edit));
kept.extend(edits);
}
Err(why) => placed.warnings.push(format!(
"{}: the connection of `{}` was appended at the end ({why}).",
at(),
spec.port
)),
}
}
kept.sort_by_key(|edit| (edit.range.start, edit.range.end));
placed.edits.push((path.clone(), kept));
}
verify::verify(files, edit, &placed, spec)?;
Ok(placed)
}
fn text_of<'f>(files: &'f [(PathBuf, String)], path: &Path) -> Result<&'f str, String> {
files
.iter()
.find(|(held, _)| held == path)
.map(|(_, text)| text.as_str())
.ok_or_else(|| format!("the edit names `{}`, which was not read", path.display()))
}
fn lexed(text: &str, spec: &Spec, path: &Path) -> Result<Vec<Token>, String> {
tokenize(text).map_err(|_| format!("{} does not lex.", (spec.show)(path)))
}
/// The module called `name`, looked for in modules and packages.
fn find_module<'t>(items: &'t [Item], name: &str) -> Option<&'t Module> {
items.iter().find_map(|item| match &item.kind {
ItemKind::Module(module) if module.name == name => Some(module),
ItemKind::Module(module) => find_module(&module.items, name),
ItemKind::Package { items, .. } => find_module(items, name),
_ => None,
})
}
/// Every instance of `module` in `items`, generate blocks and `bind`s
/// included.
fn collect_instances<'t>(items: &'t [Item], module: &str, out: &mut Vec<&'t Instance>) {
for item in items {
match &item.kind {
ItemKind::Instantiation(inst) if inst.module == module => out.extend(&inst.instances),
ItemKind::Bind(bind) if bind.inst.module == module => out.extend(&bind.inst.instances),
kind => child_items(kind).into_iter().for_each(|c| collect_instances(c, module, out)),
}
}
}
/// Whether `next`, written right after the new port (directed `new_dir`,
/// placed after an anchor directed `anchor_dir`), would take something
/// from it that it took from the anchor before: with neither direction nor
/// type it inherits both; with a type but no direction, the direction —
/// harmless only when the two directions are the same. A modport port
/// (`bus_if.mp bus`) has no direction to inherit (QA finding 3); an
/// unreadable element cannot be judged.
fn inherits(next: &ListElem<AnsiPort>, new_dir: Option<&str>, anchor_dir: Option<&str>) -> bool {
let ListElem::Ok(next) = next else { return true };
if next.dir.is_some() {
return false;
}
if next.ty.is_implicit() && next.net.is_none() {
return true;
}
let modport = next.ty.name.contains('.');
!modport && (new_dir.is_none() || new_dir != anchor_dir)
}
/// The header edit placing the new port after the anchor, the port list's
/// bytes (where the engine's appended element lands), and whether the
/// anchor is the last port.
fn header(
text: &str,
module: &Module,
spec: &Spec,
) -> Result<(Vec<TextEdit>, TextRange, bool), String> {
let PortList::Ansi(ports) = &module.ports else {
return Err(format!(
"`after` places a port in an ANSI port list, and `{}` has none; omit `after`.",
spec.module
));
};
// `index` counts every element, readable or not, as
// `ListDirective::before` does (QA finding 5b).
let found = ports.iter().enumerate().find_map(|(index, element)| {
element.ok().filter(|port| port.name == spec.after).map(|port| (index, port))
});
let Some((index, anchor)) = found else {
return Err(no_such_port(ports, spec));
};
if !balanced_before(&module.port_directives, index) {
return Err(format!(
"`{}` sits inside an `ifdef arm of the port list, so a port placed after it would exist in one configuration only; place it by hand.",
spec.after
));
}
if let Some(raw) = ports.iter().find_map(error_of) {
return Err(unreadable(&format!("`{}`'s port list", spec.module), raw));
}
let (new_dir, anchor_dir) = (new_direction(spec.declaration), anchor.dir.as_deref());
let inheriting = |next: &&ListElem<AnsiPort>| inherits(next, new_dir.as_deref(), anchor_dir);
if let Some(next) = ports.get(index + 1).filter(inheriting) {
let name = next.ok().map_or("", |port| port.name.as_str());
return Err(format!(
"`{name}` takes its direction (or type) from the port before it, so a port placed after `{}` would change it; name another `after`.",
spec.after
));
}
let tokens = lexed(text, spec, spec.file)?;
let at = slot(text, &tokens, anchor.span)
.map_err(|why| format!("after `{}`, {why}.", spec.after))?;
let element = match &at.line {
Some(line) => aligned_port(text, line, anchor, spec.declaration),
None => one_line(spec.declaration),
};
let region = list_region(&tokens, ports)?;
Ok((at.edits(&element), region, index + 1 == ports.len()))
}
/// The refusal for an `after` no readable port is named.
fn no_such_port(ports: &[ListElem<AnsiPort>], spec: &Spec) -> String {
let names: Vec<&str> = ports.iter().filter_map(ListElem::ok).map(|p| p.name.as_str()).collect();
let more = if names.len() > 12 { ", …" } else { "" };
let shown = names.iter().take(12).copied().collect::<Vec<_>>().join(", ");
format!("`{}` has no port `{}` (its ports: {shown}{more}).", spec.module, spec.after)
}
/// The direction keyword a declaration starts with.
fn new_direction(declaration: &str) -> Option<String> {
let tokens = tokenize(declaration).ok()?;
tokens.first().filter(|t| t.kind == TokenKind::Keyword).map(|t| t.text.clone())
}
/// The refusal for an element the parser could not read.
fn unreadable(list: &str, raw: &RawText) -> String {
format!(
"{list} holds `{}`, which lucisv cannot read, so it cannot tell what a port placed beside it would change; nothing written — omit `after` or place the port by hand.",
crate::tools::source::capped(&raw.text, 80)
)
}
/// The first element of an instance's connection list the parser could not
/// read.
fn unreadable_connection(instance: &Instance) -> Option<&RawText> {
match &instance.conns {
Connections::Named(conns) => conns.iter().find_map(error_of),
Connections::Ordered(conns) => conns.iter().find_map(error_of),
}
}
fn error_of<T>(element: &ListElem<T>) -> Option<&RawText> {
match element {
ListElem::Error(raw) => Some(raw),
ListElem::Ok(_) => None,
}
}
/// Whether the `` `ifdef``s written before element `index + 1` of a list
/// are all closed again — an element inserted there is unconditional.
/// `index` counts every element of the list, as `ListDirective::before`
/// does.
fn balanced_before(directives: &[ListDirective], index: usize) -> bool {
let mut depth = 0i32;
for directive in directives.iter().filter(|d| d.before <= index) {
match directive.raw.text.split_whitespace().next().unwrap_or_default() {
"`ifdef" | "`ifndef" => depth += 1,
"`endif" => depth -= 1,
_ => {}
}
}
depth == 0
}
/// The bytes from the first port to the port list's `)`.
fn list_region(tokens: &[Token], ports: &[ListElem<AnsiPort>]) -> Result<TextRange, String> {
let span = |element: &ListElem<AnsiPort>| match element {
ListElem::Ok(port) => port.span,
ListElem::Error(raw) => raw.span,
};
let (Some(first), Some(last)) = (ports.first().map(span), ports.last().map(span)) else {
return Err("lucisv cannot find this module's port list.".to_string());
};
let close = tokens
.iter()
.find(|t| t.span.start >= last.end && t.kind == TokenKind::Symbol && t.text == ")")
.ok_or_else(|| "lucisv cannot find where this module's port list ends.".to_string())?;
Ok(TextRange::new(first.start, close.span.end))
}
/// Whether an instance connects by position — its appended connection
/// stays where the engine put it, which is right only when the new port is
/// last; anywhere else it is refused.
fn positional(
instance: &Instance,
last_port: bool,
spec: &Spec,
path: &Path,
) -> Result<bool, String> {
match &instance.conns {
Connections::Ordered(_) if last_port => Ok(true),
Connections::Ordered(_) => Err(format!(
"`{}` in {} connects `{}` by position, so a port placed after `{}` would shift every later connection; give it named connections first, or omit `after`.",
instance.name,
(spec.show)(path),
spec.module,
spec.after
)),
Connections::Named(_) => Ok(false),
}
}
/// The edit placing one instance's new connection after `.after(…)`, its
/// expression taken from the engine's appended one.
fn connection(
text: &str,
tokens: &[Token],
instance: &Instance,
appended: &[TextEdit],
spec: &Spec,
) -> Result<Vec<TextEdit>, String> {
let Connections::Named(conns) = &instance.conns else {
return Err("a positional list".to_string());
};
let found = conns.iter().enumerate().find_map(|(index, conn)| {
conn.ok().filter(|conn| conn.name == spec.after).map(|conn| (index, conn))
});
let Some((index, anchor)) = found else {
return Err(format!("it does not connect `.{}`", spec.after));
};
if !balanced_before(&instance.conn_directives, index) {
return Err(format!("`.{}` sits inside an `ifdef arm", spec.after));
}
let written: String = appended.iter().map(|edit| edit.new_text.as_str()).collect();
let expr = appended_expr(&written, spec.port)
.ok_or_else(|| "lucisv could not read the appended connection".to_string())?;
let at = slot(text, tokens, anchor.span)?;
let element = match &at.line {
Some(line) => aligned_connection(text, line, anchor, spec.port, &expr),
None => format!(".{}({expr})", spec.port),
};
Ok(at.edits(&element))
}
/// The expression inside the engine's appended `.port(expr)`.
fn appended_expr(written: &str, port: &str) -> Option<String> {
let open = written.find(&format!(".{port}("))? + port.len() + 2;
let mut depth = 1usize;
for (offset, c) in written[open..].char_indices() {
match c {
'(' => depth += 1,
')' if depth == 1 => return Some(written[open..open + offset].trim().to_string()),
')' => depth -= 1,
_ => {}
}
}
None
}
/// The port a declaration's tokens name: the last identifier outside
/// brackets before any `=` default.
pub fn port_name(tokens: &[Token]) -> Option<&Token> {
let mut depth = 0usize;
let mut name = None;
for token in tokens {
match (token.kind, token.text.as_str()) {
(TokenKind::Symbol, "[" | "(" | "{") => depth += 1,
(TokenKind::Symbol, "]" | ")" | "}") => depth = depth.saturating_sub(1),
(TokenKind::Symbol, "=") if depth == 0 => break,
(TokenKind::Ident, _) if depth == 0 && !token.is_macro() => name = Some(token),
_ => {}
}
}
name
}
#[cfg(test)]
mod tests {
use super::*;
use crate::apply::Plan;
const TOP: &str = "module top(input logic a, output logic y);\n m u_m (\n .a (a), // in\n .y (y)\n );\nendmodule\n";
fn design(header: &str) -> Vec<(PathBuf, String)> {
let m = format!("module m (\n{header}\n);\nendmodule\n");
vec![(PathBuf::from("/d/m.sv"), m), (PathBuf::from("/d/top.sv"), TOP.to_string())]
}
fn show(path: &Path) -> String {
path.file_name().map_or(String::new(), |name| name.to_string_lossy().into_owned())
}
fn spec<'a>(after: &'a str) -> Spec<'a> {
let (file, declaration) = (Path::new("/d/m.sv"), "input logic en");
Spec { module: "m", file, after, port: "en", declaration, show: &show }
}
fn engine(files: &[(PathBuf, String)]) -> RefactorEdit {
vlog_refactor::add_port(files, vlog_refactor::ModuleRef::Name("m"), "input logic en")
.unwrap()
}
fn texts(files: &[(PathBuf, String)], edit: &RefactorEdit) -> Vec<String> {
let plan = Plan::from_refactor(edit.clone(), files).unwrap();
plan.changes.into_iter().map(|change| change.after).collect()
}
fn refusal(files: &[(PathBuf, String)], after_port: &str) -> String {
after(files, &engine(files), &spec(after_port)).err().unwrap_or_default()
}
#[test]
fn a_placed_port_and_connection_follow_their_anchors() {
let files = design(" input logic a, // first\n output logic y");
let placed = after(&files, &engine(&files), &spec("a")).unwrap();
let [m, top] = texts(&files, &placed).try_into().unwrap();
let header = " input logic a, // first\n input logic en,\n output logic y\n";
assert_eq!(m, format!("module m (\n{header});\nendmodule\n"));
// `top` has no `en`: the engine's placeholder, placed.
let placed = " .a (a), // in\n .en (/* TODO: connect */),\n .y (y)\n";
assert!(top.contains(placed), "{top}");
}
#[test]
fn what_a_placement_cannot_see_or_would_change_is_refused() {
let inherit = refusal(&design(" input logic [7:0] a, b,\n output logic y"), "a");
assert!(inherit.contains("`b` takes its direction"), "{inherit}");
let typed = refusal(&design(" output logic a, logic [3:0] b,\n output logic y"), "a");
assert!(typed.contains("`b` takes its direction"), "{typed}");
let arm = refusal(&design("`ifdef X\n input logic a,\n`endif\n output logic y"), "a");
assert!(arm.contains("inside an `ifdef arm"), "{arm}");
let hidden =
refusal(&design(" input logic [7:0] a,\n (* keep *) b,\n output logic y"), "a");
assert!(hidden.contains("`m`'s port list holds `(* keep *) b`"), "{hidden}");
let mut files = design(" input logic a,\n output logic y");
files[1].1 =
"module top(input logic a, en, output logic y);\n m u_m (a, y);\nendmodule\n".into();
let edit = engine(&files);
let refused = after(&files, &edit, &spec("a")).unwrap_err();
assert!(refused.contains("`u_m` in top.sv connects `m` by position"), "{refused}");
assert!(after(&files, &edit, &spec("y")).is_ok(), "last is fine");
}
#[test]
fn a_modport_or_a_same_directed_typed_port_after_the_anchor_is_placed() {
let files = design(" input logic a,\n bus_if.mp bus,\n output logic y");
assert!(after(&files, &engine(&files), &spec("a")).is_ok());
let files = design(" input logic a, logic [3:0] b,\n output logic y");
assert!(after(&files, &engine(&files), &spec("a")).is_ok());
}
#[test]
fn the_engines_appended_expression_is_read_back() {
assert_eq!(appended_expr(",\n .dbg_i(dbg_i)", "dbg_i").as_deref(), Some("dbg_i"));
let todo = appended_expr(", .d(/* TODO: connect */)", "d");
assert_eq!(todo.as_deref(), Some("/* TODO: connect */"));
assert_eq!(appended_expr(".d(f(a))", "d").as_deref(), Some("f(a)"));
assert_eq!(appended_expr(".e(x)", "d"), None);
}
}
+306
View File
@@ -0,0 +1,306 @@
//! Where a new list element goes after its anchor, and how it is written.
//!
//! The element always goes **after the separator that follows the anchor**
//! — past the anchor's `,` (and any comment on that comma's line), or, for
//! a last anchor, after a `,` added at the anchor's end and past the
//! comments on its line — never at the anchor's end, where it would take
//! over a comment written between the anchor and its comma (QA finding 1).
//! A new line copies the anchor's indentation and line ending, and, when
//! the anchor stands alone on its line, its column layout.
use vlog_parser::ast::{AnsiPort, Connection};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use vlog_refactor::TextEdit;
use crate::render::one_line;
/// The line an anchor starts on: where it starts, its indentation, and
/// whether the anchor is the first thing on it.
pub struct AnchorLine {
start: usize,
indent: String,
alone: bool,
}
/// Where the new element is written: a `,` at `comma_at` when the anchor
/// was last, then `prefix element suffix` at `at`. `line` is the anchor's
/// line when the element gets a line of its own in the anchor's layout.
pub struct Slot {
comma_at: Option<u32>,
at: u32,
prefix: String,
suffix: &'static str,
pub line: Option<AnchorLine>,
}
impl Slot {
/// The insertions writing `element` here.
pub fn edits(&self, element: &str) -> Vec<TextEdit> {
let at = |offset: u32| TextRange::new(offset, offset);
let mut edits: Vec<TextEdit> = self
.comma_at
.map(|comma| TextEdit { range: at(comma), new_text: ",".to_string() })
.into_iter()
.collect();
let new_text = format!("{}{element}{}", self.prefix, self.suffix);
edits.push(TextEdit { range: at(self.at), new_text });
edits
}
}
/// The slot after the element spanning `anchor`, read off the file's
/// tokens: the anchor must be followed by its list's `,` or `)`.
pub fn slot(text: &str, tokens: &[Token], anchor: TextRange) -> Result<Slot, String> {
let index = tokens.iter().position(|t| t.span.start >= anchor.end);
let next = index.and_then(|i| tokens.get(i)).filter(|t| t.kind == TokenKind::Symbol);
let line = anchor_line(text, anchor.start as usize);
match next.map(|t| t.text.as_str()) {
Some(",") => {
let comma = next.map_or(anchor.end, |t| t.span.end);
let following = index.and_then(|i| tokens.get(i + 1));
let Some(following) = following.filter(|t| starts_line(text, t.span.start as usize))
else {
// The next element shares the comma's line: `a, en, b`.
let suffix = ",";
return Ok(Slot {
comma_at: None,
at: comma,
prefix: " ".into(),
suffix,
line: None,
});
};
let (at, newline) = line_end(text, comma as usize, tokens);
let indent = match line.alone {
true => line.indent.clone(),
false => indentation(text, following.span.start as usize),
};
let prefix = format!("{newline}{indent}");
let line = line.alone.then_some(line);
Ok(Slot { comma_at: None, at, prefix, suffix: ",", line })
}
Some(")") => {
let close = next.map_or(anchor.end, |t| t.span.start);
let between = &text[anchor.end as usize..close as usize];
if starts_line(text, close as usize) {
let (at, newline) = line_end(text, anchor.end as usize, tokens);
let prefix = format!("{newline}{}", line.indent);
let line = line.alone.then_some(line);
return Ok(Slot { comma_at: Some(anchor.end), at, prefix, suffix: "", line });
}
if between.trim().is_empty() {
let prefix = ", ".to_string();
return Ok(Slot { comma_at: None, at: anchor.end, prefix, suffix: "", line: None });
}
// A comment between the last anchor and `)`: it stays the anchor's.
let prefix = " ".to_string();
Ok(Slot { comma_at: Some(anchor.end), at: close, prefix, suffix: "", line: None })
}
_ => Err("lucisv cannot find the `,` or `)` after it".to_string()),
}
}
fn anchor_line(text: &str, from: usize) -> AnchorLine {
let start = text[..from].rfind('\n').map_or(0, |at| at + 1);
let before = &text[start..from];
let alone = before.chars().all(|c| c == ' ' || c == '\t');
AnchorLine { start, indent: indentation(text, from), alone }
}
/// The blanks a line starts with, the line holding `offset`.
fn indentation(text: &str, offset: usize) -> String {
let start = text[..offset].rfind('\n').map_or(0, |at| at + 1);
text[start..].chars().take_while(|c| *c == ' ' || *c == '\t').collect()
}
/// Whether only blanks precede `offset` on its line.
fn starts_line(text: &str, offset: usize) -> bool {
let start = text[..offset].rfind('\n').map_or(0, |at| at + 1);
text[start..offset].chars().all(|c| c == ' ' || c == '\t')
}
/// The end of the line `from` is on — past any comment that closes on a
/// later line — before its line ending, and that line ending.
fn line_end(text: &str, from: usize, tokens: &[Token]) -> (u32, &'static str) {
let comments: Vec<TextRange> = tokens
.iter()
.flat_map(|t| t.leading.iter().chain(t.trailing.as_ref()))
.map(|comment| comment.span)
.collect();
let mut at = from;
loop {
let newline = text[at..].find('\n').map_or(text.len(), |found| at + found);
match comments.iter().find(|c| (c.start as usize) < newline && newline < c.end as usize) {
Some(comment) => at = comment.end as usize,
None => {
return match text[..newline].strip_suffix('\r') {
Some(_) => ((newline - 1) as u32, "\r\n"),
None => (newline as u32, "\n"),
}
}
}
}
}
/// Character columns on the anchor's line.
fn column(text: &str, line: &AnchorLine, offset: usize) -> usize {
text[line.start..offset].chars().count()
}
/// `out` (which follows the line's indentation) padded so its end reaches
/// `col`; one space when it is already past or there is no column.
fn pad_to(out: &mut String, line: &AnchorLine, col: Option<usize>) {
let width = line.indent.chars().count() + out.chars().count();
match col {
Some(col) if width < col => out.push_str(&" ".repeat(col - width)),
_ => out.push(' '),
}
}
/// The declaration in the anchor's layout (without the indentation):
/// direction, type and name each at the anchor's column when the text
/// before it fits, else one space apart.
pub fn aligned_port(text: &str, line: &AnchorLine, anchor: &AnsiPort, declaration: &str) -> String {
let declaration = declaration.trim();
let (Some(parts), Some(dir)) = (split_declaration(declaration), anchor.dir.as_deref()) else {
return one_line(declaration);
};
let dir_end = anchor.span.start as usize + dir.len();
if text.get(anchor.span.start as usize..dir_end) != Some(dir) {
return one_line(declaration);
}
let type_at = dir_end + (text[dir_end..].len() - text[dir_end..].trim_start().len());
let name_at = anchor.name_span.start as usize;
let type_col = (type_at < name_at).then(|| column(text, line, type_at));
let mut out = parts.dir.to_string();
if !parts.ty.is_empty() {
pad_to(&mut out, line, type_col);
out.push_str(&one_line(parts.ty));
}
pad_to(&mut out, line, Some(column(text, line, name_at)));
out.push_str(&one_line(parts.rest));
out
}
/// The connection `.port(expr)` in the anchor's layout: the `(` and the `)`
/// at the anchor's columns when they fit, the anchor's blanks inside them.
pub fn aligned_connection(
text: &str,
line: &AnchorLine,
anchor: &Connection,
port: &str,
expr: &str,
) -> String {
let plain = format!(".{port}({expr})");
let Some(value) = anchor.expr.as_ref().filter(|_| anchor.after_dot.is_empty()) else {
return plain;
};
let name_end = anchor.name_span.end as usize;
let open = name_end + (text[name_end..].len() - text[name_end..].trim_start().len());
let close = (anchor.span.end as usize).saturating_sub(1);
let (start, end) = (value.span.start as usize, value.span.end as usize);
let blank = |from: usize, to: usize| {
text.get(from..to).filter(|gap| gap.chars().all(|c| c == ' ' || c == '\t'))
};
let (Some(before_open), Some(inside), Some(_)) =
(blank(name_end, open), blank(open + 1, start), blank(end, close))
else {
return plain;
};
if text.get(open..open + 1) != Some("(") || text.get(close..close + 1) != Some(")") {
return plain;
}
let mut out = format!(".{port}");
// An anchor that glues its `(` to the name is followed; else aligned.
if !before_open.is_empty() {
pad_to(&mut out, line, Some(column(text, line, open)));
}
out.push('(');
out.push_str(inside);
out.push_str(expr);
let width = line.indent.chars().count() + out.chars().count();
let close_col = column(text, line, close);
match width < close_col {
true => out.push_str(&" ".repeat(close_col - width)),
false => out.push_str(inside),
}
out.push(')');
out
}
/// A declaration split where a layout puts its columns: the direction, the
/// type between it and the name, and the name with what follows it.
struct Parts<'a> {
dir: &'a str,
ty: &'a str,
rest: &'a str,
}
fn split_declaration(declaration: &str) -> Option<Parts<'_>> {
let tokens = tokenize(declaration).ok()?;
let dir = tokens.first().filter(|t| t.kind == TokenKind::Keyword)?;
let name = super::port_name(&tokens)?;
let (dir_end, name_start) = (dir.span.end as usize, name.span.start as usize);
Some(Parts {
dir: &declaration[..dir_end],
ty: declaration[dir_end..name_start].trim(),
rest: declaration[name_start..].trim(),
})
}
#[cfg(test)]
mod tests {
use super::*;
/// `text` with `element` written in the slot after `anchor`.
fn placed(text: &str, anchor: &str, element: &str) -> String {
let tokens = tokenize(text).unwrap();
let start = text.find(anchor).unwrap() as u32;
let span = TextRange::new(start, start + anchor.len() as u32);
let slot = slot(text, &tokens, span).unwrap();
let mut out = text.to_string();
for edit in slot.edits(element).iter().rev() {
out.insert_str(edit.range.start as usize, &edit.new_text);
}
out
}
#[test]
fn the_element_goes_after_the_separator_and_its_comments() {
let e = "input e";
assert_eq!(
placed("(\n input a,\n input b\n);", "input a", e),
"(\n input a,\n input e,\n input b\n);"
);
assert_eq!(
placed("(\n input a /* about a */,\n input b\n);", "input a", e),
"(\n input a /* about a */,\n input e,\n input b\n);"
);
assert_eq!(
placed("(\n input b // about b\n , input c);", "input b", e),
"(\n input b // about b\n , input e, input c);"
);
assert_eq!(placed("(input a, input b);", "input a", e), "(input a, input e, input b);");
assert_eq!(
placed("(\n input y /* last */\n);", "input y", e),
"(\n input y, /* last */\n input e\n);"
);
assert_eq!(placed("(input y /* c */);", "input y", e), "(input y, /* c */ input e);");
assert_eq!(placed("(input y);", "input y", e), "(input y, input e);");
assert_eq!(
placed("(\r\n input a, /* x\r\n y */\r\n input b\r\n);", "input a", e),
"(\r\n input a, /* x\r\n y */\r\n input e,\r\n input b\r\n);"
);
}
#[test]
fn a_declaration_splits_at_its_name() {
let parts = split_declaration("input logic [W-1:0] cfg [2] = 0").unwrap();
assert_eq!((parts.dir, parts.ty, parts.rest), ("input", "logic [W-1:0]", "cfg [2] = 0"));
let parts = split_declaration("output pkg::t_e st").unwrap();
assert_eq!((parts.ty, parts.rest), ("pkg::t_e", "st"));
assert_eq!(split_declaration("input dbg_i").unwrap().ty, "");
}
}
+310
View File
@@ -0,0 +1,310 @@
//! The check a placement must pass before anything is written: the placed
//! edit is the engine's verified edit with elements **moved and nothing
//! else**. Per file, against the engine's result:
//!
//! 1. the same tokens (kind and text), as a multiset;
//! 2. every comment attached to the same identifier — the one before it for
//! a comment on its token's line, the one after it for a comment on
//! lines of its own — so a comment cannot slide onto the new element
//! (QA finding 1);
//! 3. no more parse diagnostics;
//! 4. the module's port list, **every** element counted (an element the
//! parser could not read included, by its text): the engine's order with
//! the new port moved to right after the anchor; each port's declaration
//! the engine's, blanks collapsed (QA finding 5); and the port after the
//! new one does not inherit from it;
//! 5. every instance's connections the same: named ones as a set of
//! `.name(expr)` with blanks squeezed, positional ones in order.
//!
//! Guilty until proven innocent: each rule has an attack in this module's
//! tests.
use std::path::PathBuf;
use vlog_parser::ast::{Connections, Instance, Item, ListElem, PortList};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_refactor::RefactorEdit;
use super::{collect_instances, find_module, inherits, Spec};
use crate::apply::Plan;
use crate::render::one_line;
/// Check `placed` against `engine` (see the module comment); the refusal
/// names the file and the rule broken.
pub fn verify(
files: &[(PathBuf, String)],
engine: &RefactorEdit,
placed: &RefactorEdit,
spec: &Spec,
) -> Result<(), String> {
let expected = Plan::from_refactor(engine.clone(), files)?;
let got = Plan::from_refactor(placed.clone(), files)?;
let refuse = |why: String| {
format!(
"placing `{}` after `{}` failed a check ({why}); nothing written.",
spec.port, spec.after
)
};
if expected.changes.len() != got.changes.len() {
return Err(refuse("a different set of files".into()));
}
for (want, have) in expected.changes.iter().zip(&got.changes) {
let shown = (spec.show)(&have.path);
if want.path != have.path {
return Err(refuse(format!("{shown} is not the engine's file")));
}
let lexed = lexed(&have.after);
if lexed.is_none() || lexed != self::lexed(&want.after) {
return Err(refuse(format!("{shown} lexes to other tokens or comments")));
}
let (want_tree, want_errors) = parse_source_tolerant(&want.after);
let (have_tree, have_errors) = parse_source_tolerant(&have.after);
if have_errors.len() > want_errors.len() {
return Err(refuse(format!("{shown} parses worse")));
}
if have.path == spec.file {
let want = (want.after.as_str(), want_tree.items.as_slice());
let have = (have.after.as_str(), have_tree.items.as_slice());
ports_in_order(have, want, spec).map_err(&refuse)?;
}
let mut wanted = Vec::new();
let mut had = Vec::new();
collect_instances(&want_tree.items, spec.module, &mut wanted);
collect_instances(&have_tree.items, spec.module, &mut had);
let signature = |text: &str, instances: &[&Instance]| -> Vec<Vec<String>> {
instances.iter().map(|instance| connections(text, instance)).collect()
};
if signature(&want.after, &wanted) != signature(&have.after, &had) {
return Err(refuse(format!("{shown}'s connections differ")));
}
}
Ok(())
}
/// Every token's kind and text, and every comment with the identifier it is
/// attached to, sorted: equal for two texts that hold the same tokens in
/// any order, with each comment still beside the same name.
fn lexed(text: &str) -> Option<Vec<String>> {
let tokens = tokenize(text).ok()?;
let ident = |token: &vlog_parser::token::Token| token.kind == TokenKind::Ident;
let mut out: Vec<String> = Vec::new();
let mut last_ident = "";
for (i, token) in tokens.iter().enumerate() {
out.push(format!("{:?} {}", token.kind, token.text));
if !token.leading.is_empty() {
let next = tokens[i..].iter().find(|t| ident(t)).map_or("", |t| t.text.as_str());
out.extend(token.leading.iter().map(|c| format!("comment before {next}: {}", c.text)));
}
if ident(token) {
last_ident = &token.text;
}
if let Some(comment) = &token.trailing {
out.push(format!("comment after {last_ident}: {}", comment.text));
}
}
out.sort();
Some(out)
}
/// A port list's elements as the check compares them: each readable port
/// as `name: declaration` (blanks collapsed), each unreadable one by text.
fn port_elements(text: &str, items: &[Item], spec: &Spec) -> Option<Vec<(String, String)>> {
let module = find_module(items, spec.module)?;
let PortList::Ansi(ports) = &module.ports else { return None };
let written = |span: TextRange| one_line(text.get(span.as_range()).unwrap_or(""));
let elements = ports.iter().map(|element| match element {
ListElem::Ok(port) => (port.name.clone(), written(port.span)),
ListElem::Error(raw) => (String::new(), one_line(&raw.text)),
});
Some(elements.collect())
}
/// The module's ports in the placed text are the engine's, each declared
/// as the engine left it, with the new one moved to right after the anchor;
/// the port after it does not inherit from it.
fn ports_in_order(
(have_text, have): (&str, &[Item]),
(want_text, want): (&str, &[Item]),
spec: &Spec,
) -> Result<(), String> {
let (Some(have_ports), Some(mut want_ports)) =
(port_elements(have_text, have, spec), port_elements(want_text, want, spec))
else {
return Err(format!("`{}` has no ANSI port list", spec.module));
};
let new = want_ports.iter().position(|(name, _)| name == spec.port);
let Some(new) = new.map(|at| want_ports.remove(at)) else {
return Err("the engine's result has no new port".to_string());
};
let at = want_ports.iter().position(|(name, _)| name == spec.after).map_or(0, |at| at + 1);
want_ports.insert(at, new);
if have_ports != want_ports {
let names: Vec<String> =
have_ports.iter().map(|(name, written)| format!("{name}: {written}")).collect();
return Err(format!("the ports are {}", names.join("; ")));
}
let module = find_module(have, spec.module).ok_or("the module is gone")?;
let PortList::Ansi(ports) = &module.ports else { return Err("no port list".into()) };
let dir = |at: usize| ports.get(at).and_then(ListElem::ok).and_then(|p| p.dir.as_deref());
let anchor_dir = at.checked_sub(1).and_then(dir);
if ports.get(at + 1).is_some_and(|next| inherits(next, dir(at), anchor_dir)) {
return Err("the port after the new one would inherit from it".to_string());
}
Ok(())
}
/// One instance's connections, blanks squeezed: sorted for a named list
/// (order does not bind) and in order for a positional one; an unreadable
/// element by its text.
fn connections(text: &str, instance: &Instance) -> Vec<String> {
let squeeze = |span: TextRange| -> String {
text.get(span.as_range()).unwrap_or("").split_whitespace().collect()
};
match &instance.conns {
Connections::Named(conns) => {
let mut out: Vec<String> = conns
.iter()
.map(|conn| match conn {
ListElem::Ok(conn) => squeeze(conn.span),
ListElem::Error(raw) => squeeze(raw.span),
})
.collect();
out.sort();
out
}
Connections::Ordered(conns) => conns
.iter()
.map(|conn| match conn {
ListElem::Ok(conn) => squeeze(conn.span),
ListElem::Error(raw) => squeeze(raw.span),
})
.collect(),
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use vlog_refactor::TextEdit;
use super::super::after;
use super::*;
const TOP: &str = "module top(input logic a, output logic y);\n m u_m (\n .a (a), // in\n .y (y)\n );\nendmodule\n";
fn design(header: &str) -> Vec<(PathBuf, String)> {
let m = format!("module m (\n{header}\n);\nendmodule\n");
vec![(PathBuf::from("/d/m.sv"), m), (PathBuf::from("/d/top.sv"), TOP.to_string())]
}
fn show(path: &Path) -> String {
path.display().to_string()
}
fn spec<'a>(after: &'a str, declaration: &'a str) -> Spec<'a> {
let file = Path::new("/d/m.sv");
Spec { module: "m", file, after, port: "en", declaration, show: &show }
}
fn engine(files: &[(PathBuf, String)], declaration: &str) -> RefactorEdit {
vlog_refactor::add_port(files, vlog_refactor::ModuleRef::Name("m"), declaration).unwrap()
}
/// `edit` with the module file's edits replaced by `header`.
fn with_header(edit: &RefactorEdit, header: Vec<TextEdit>) -> RefactorEdit {
let mut bad = edit.clone();
bad.edits[0].1 = header;
bad
}
fn insert(at: usize, text: &str) -> TextEdit {
TextEdit { range: TextRange::new(at as u32, at as u32), new_text: text.to_string() }
}
/// Masked-corruption attacks: a placed edit that is not the engine's
/// with elements moved is refused, whatever it looks like.
#[test]
fn a_placement_that_is_not_a_move_is_refused() {
let files = design(" input logic a, // first\n output logic y");
let decl = "input logic en";
let edit = engine(&files, decl);
let good = after(&files, &edit, &spec("a", decl)).unwrap();
assert!(verify(&files, &edit, &good, &spec("a", decl)).is_ok());
let m = &files[0].1;
let first = m.find("// first").unwrap();
// The anchor line's comment taken by the new line.
let stolen = with_header(&good, vec![insert(first, "\n input logic en, ")]);
assert!(verify(&files, &edit, &stolen, &spec("a", decl)).is_err());
// A wider type on the new port.
let wide = m.find("\n output").unwrap();
let wider = with_header(&good, vec![insert(wide, "\n input logic [1:0] en,")]);
assert!(verify(&files, &edit, &wider, &spec("a", decl)).is_err());
// A connection to another signal.
let mut rewired = good.clone();
let conn = rewired.edits[1].1.iter_mut().find(|e| e.new_text.contains(".en")).unwrap();
conn.new_text = conn.new_text.replace("TODO: connect */", "*/ a");
assert!(verify(&files, &edit, &rewired, &spec("a", decl)).is_err());
// The engine's own append, where `after` asked for `a`.
let last = verify(&files, &edit, &edit, &spec("a", decl)).unwrap_err();
assert!(last.contains("the ports are"), "{last}");
}
/// QA finding 5's pair: the type swapped between the anchor and the new
/// port — the same tokens, names in order, parse and connections.
#[test]
fn a_type_swapped_between_the_anchor_and_the_new_port_is_refused() {
let files = design(" input logic [7:0] a,\n output logic y");
let decl = "input logic en";
let edit = engine(&files, decl);
let m = &files[0].1;
let dims = m.find("[7:0] ").unwrap();
let comma = m.find("a,").unwrap() + 2;
let swapped = with_header(
&edit,
vec![
TextEdit {
range: TextRange::new(dims as u32, dims as u32 + 6),
new_text: String::new(),
},
insert(comma, "\n input logic [7:0] en,"),
],
);
let said = verify(&files, &edit, &swapped, &spec("a", decl)).unwrap_err();
assert!(said.contains("the ports are"), "{said}");
}
/// QA finding 1's shapes: a comment glued to the anchor's comma, and a
/// leading-comma list, each with the new element placed at the anchor's
/// end — the comment then documents the new port.
#[test]
fn a_comment_moved_onto_the_new_element_is_refused() {
for header in [
" input logic a /* about a */,\n output logic y",
" input logic a // about a\n , output logic y",
] {
let files = design(header);
let decl = "input logic en";
let edit = engine(&files, decl);
let end = files[0].1.find("logic a").unwrap() + "logic a".len();
let glued = with_header(&edit, vec![insert(end, ", input logic en")]);
let said = verify(&files, &edit, &glued, &spec("a", decl)).unwrap_err();
assert!(said.contains("comments"), "{header}: {said}");
// The slot after the separator keeps it.
let placed = after(&files, &edit, &spec("a", decl)).unwrap();
assert!(verify(&files, &edit, &placed, &spec("a", decl)).is_ok(), "{header}");
}
}
#[test]
fn comments_pair_with_the_name_they_are_written_beside() {
let pairs = lexed("a /* x */, b // y\n// z\nc").unwrap();
let comments: Vec<&String> = pairs.iter().filter(|p| p.starts_with("comment")).collect();
assert_eq!(
comments,
["comment after a: /* x */", "comment after b: // y", "comment before c: // z"]
);
}
}
+146
View File
@@ -0,0 +1,146 @@
//! `port`: add a port to a module and connect it by name in every
//! instantiation, or remove one and its connection everywhere — the
//! design-wide edit a file write cannot do safely. `add` is
//! `vlog_refactor::add_port`, placed after `after` by `place.rs`; `remove`
//! is `vlog_refactor::remove_port`, refused by the engine while the body
//! uses the port. Both write through the one write path and list the port
//! name's unresolved mentions.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use vlog_refactor::{module_definition, ModuleRef};
use vlog_semantic::SymbolKind;
use super::edit::{whole_set, write_telling, Told};
use super::place;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render;
pub const PORT: Tool = Tool {
name: "port",
description: "On `module`, `add` an ANSI port declaration (after port `after`, else last) connected in every instantiation, or `remove` a port and its connections (refused while used).",
params: &[
Param { name: "module", ty: Ty::Str, required: true },
Param { name: "add", ty: Ty::Str, required: false },
Param { name: "after", ty: Ty::Str, required: false },
Param { name: "remove", ty: Ty::Str, required: false },
],
rewalk: true,
handler: port,
};
fn port(project: &mut Project, args: &Args) -> Result<Answer, String> {
let module = args.str("module").unwrap_or_default().trim();
let file = declaring_file(project, module)?;
match (args.str("add"), args.str("remove"), args.str("after")) {
(Some(add), None, after) => add_port(project, module, &file, add, after),
(None, Some(remove), None) => remove_port(project, module, &file, remove.trim()),
(None, Some(_), Some(_)) => Err("`after` goes with `add`, not `remove`.".into()),
_ => Err("give exactly one of `add` and `remove`.".into()),
}
}
/// The one file declaring module `module`, walking once for a module
/// written since the last walk.
fn declaring_file(project: &mut Project, module: &str) -> Result<PathBuf, String> {
let found = module_definition(project.index(), module).map(Path::to_path_buf);
match found {
Err(_) if project.ensure_walked_for_miss() => {
module_definition(project.index(), module).map(Path::to_path_buf)
}
found => found,
}
}
fn add_port(
project: &mut Project,
module: &str,
file: &Path,
declaration: &str,
after: Option<&str>,
) -> Result<Answer, String> {
let set = whole_set(project, None, &[module.to_string()])?;
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(module), declaration)
.map_err(|why| set.rooted(&why))?;
let tokens = vlog_parser::tokenize(declaration).unwrap_or_default();
let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default();
let show = &|path: &Path| project.relative(path);
let edit = match after.map(str::trim) {
Some(after) => {
let spec = place::Spec { module, file, after, port: &port, declaration, show };
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(&why))?
}
None => edit,
};
let told = Told { name: &port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("added port {port} in module {module}: {}", census(count, files));
Ok(Answer::lines(std::iter::once(head).chain(done.tail).collect()))
}
fn remove_port(
project: &mut Project,
module: &str,
file: &Path,
port: &str,
) -> Result<Answer, String> {
let offset = port_offset(project, module, file, port)?;
let set = whole_set(project, Some(file), &[port.to_string(), module.to_string()])?;
let edit =
vlog_refactor::remove_port(&set.files, file, offset).map_err(|why| set.rooted(&why))?;
let told = Told { name: port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("removed port {port} in module {module}: {}", census(count, files));
Ok(Answer::lines(std::iter::once(head).chain(done.tail).collect()))
}
/// Where port `port` of `module` is named in the module's file: its header
/// entry (an ANSI port, or a non-ANSI header name).
fn port_offset(
project: &mut Project,
module: &str,
file: &Path,
port: &str,
) -> Result<u32, String> {
let analysis = project.analysis(file)?;
let semantics = &analysis.semantics;
let unit = semantics
.symbols_named(module)
.filter_map(|id| semantics.symbol(id))
.find(|symbol| symbol.kind.is_instantiable())
.and_then(|symbol| symbol.child_scope);
let found = semantics
.symbols_named(port)
.filter_map(|id| semantics.symbol(id))
.find(|symbol| symbol.kind == SymbolKind::Port && Some(symbol.scope) == unit);
match found {
Some(symbol) => Ok(symbol.name_span.start),
None => {
let ports: Vec<&str> = semantics
.symbols()
.iter()
.filter(|symbol| symbol.kind == SymbolKind::Port && Some(symbol.scope) == unit)
.map(|symbol| symbol.name.as_str())
.collect();
Err(format!("`{module}` has no port `{port}` (its ports: {}).", ports.join(", ")))
}
}
}
/// `N instantiations in K files`.
fn census(count: usize, files: usize) -> String {
format!("{} in {}", render::count(count, "instantiation"), render::count(files, "file"))
}
/// How many instances of `module` the index holds, and in how many files —
/// the instantiations a port edit connects or disconnects.
fn instantiations(project: &Project, module: &str) -> (usize, usize) {
let edges = project.index().instantiations_of(module);
let count = edges.iter().map(|edge| edge.instances.len()).sum();
let files: BTreeSet<_> = edges.iter().map(|edge| edge.file).collect();
(count, files.len())
}
+80
View File
@@ -0,0 +1,80 @@
//! `read`: one item's exact source — a slice, never the file — preceded by
//! `file:first–last`. In a named `file` the item is sliced as
//! `read_item::select` slices it; without one the name is looked up
//! design-wide and must be declared exactly once.
use std::path::PathBuf;
use super::names;
use super::read_item::{declared_lines, select, split_kind, split_line, BY_LINE};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render;
pub const READ: Tool = Tool {
name: "read",
description: "One item's exact source after its file:first–last line. `item`: name, kind:name, name@LINE, or always@LINE; `file` is needed for always@LINE or a name declared in several files.",
params: &[
Param { name: "item", ty: Ty::Str, required: true },
Param { name: "file", ty: Ty::Str, required: false },
],
rewalk: false,
handler: read,
};
fn read(project: &mut Project, args: &Args) -> Result<Answer, String> {
let selector = args.str("item").unwrap_or("").trim();
if selector.is_empty() {
return Err("`item` is empty.".into());
}
let path = match args.str("file") {
Some(file) => project.resolve(file)?,
None => locate(project, selector)?,
};
let file = project.relative(&path);
let analysis = project.analysis(&path)?;
let (_, span) = select(&analysis, selector).map_err(|why| format!("{why} in `{file}`."))?;
let (first, last) = analysis.line_span(span.start, span.end);
let mut text =
format!("{file}:{}\n{}", render::lines(first, last), analysis.slice(span.start, span.end));
if !text.ends_with('\n') {
text.push('\n');
}
Ok(Answer { text })
}
/// The one file declaring what `selector` names, design-wide; a refusal
/// listing every site when there are several, or the near matches when
/// there are none.
fn locate(project: &mut Project, selector: &str) -> Result<PathBuf, String> {
let (head, line) = split_line(selector)?;
if line.is_some() && BY_LINE.contains(&head) {
return Err(format!("`{selector}` names a block by its line; give its `file`."));
}
let (_, name) = split_kind(head);
let mut files: Vec<PathBuf> = Vec::new();
for declaration in names::declarations_walking(project, name) {
if !declaration.is_macro() && !files.contains(&declaration.path) {
files.push(declaration.path);
}
}
let mut sites: Vec<(PathBuf, String)> = Vec::new();
for path in files {
let analysis = project.analysis(&path)?;
let file = project.relative(&path);
let lines = declared_lines(&analysis, selector);
sites.extend(lines.into_iter().map(|line| (path.clone(), format!("{file}:{line}"))));
}
match sites.as_slice() {
[] => Err(names::no_declaration(project, name)),
[(path, _)] => Ok(path.clone()),
many => {
let listed: Vec<&str> = many.iter().map(|(_, site)| site.as_str()).collect();
Err(format!(
"`{selector}` is declared {} times ({}); give `file`, and `name@LINE` within one file.",
listed.len(),
listed.join(", ")
))
}
}
}
+319
View File
@@ -0,0 +1,319 @@
//! The item slicer `read` and `edit_item` share: one item's exact span in
//! a 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 structural edits 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 vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind};
use vlog_parser::span::TextRange;
use vlog_semantic::Symbol;
use crate::project::Analysis;
use crate::render;
/// The keywords that name an unlabelled item by the line it covers.
pub const BY_LINE: &[&str] = &["always", "initial", "final", "assign"];
/// 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).
pub 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`).
pub 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 lines of every declaration a by-name `selector` matches in this
/// file — none for a malformed or by-line selector.
pub fn declared_lines(analysis: &Analysis, selector: &str) -> Vec<u32> {
let Ok((head, line)) = split_line(selector) else { return Vec::new() };
let (kind, name) = split_kind(head);
let mut found = matching(analysis, name, kind, line);
if found.is_empty() && line.is_some() && name.starts_with('\\') {
found = matching(analysis, split_kind(selector).1, kind, None);
}
found.iter().map(|symbol| analysis.lines.line_col(symbol.name_span.start).0).collect()
}
/// Every declaration of `name` matching the optional kind word and line.
fn matching<'a>(
analysis: &'a Analysis,
name: &str,
kind: Option<&str>,
line: Option<u32>,
) -> Vec<&'a Symbol> {
let semantics = &analysis.semantics;
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()
}
/// 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 matches = matching(analysis, name, kind, line);
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}");
}
}
+273
View File
@@ -0,0 +1,273 @@
//! Declaration sites read back off the disk: `find` and the by-name tools
//! answer with `file: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. Also the whole set a cross-file engine is
//! handed, and the small text helpers the answers share.
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
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))
}
}
/// One place a declaration (or a use) is written.
pub struct Site {
pub file: String,
pub line: u32,
}
/// 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,
) -> Option<Site> {
let (text, lines) = texts.get(path)?;
if text.get(name_span.as_range()) != Some(name) {
return None;
}
Some(Site { file: project.relative(path), line: lines.line_col(shown.start).0 })
}
/// `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}…")
}
/// 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)>,
/// How an engine sentence names each file of the set, and the
/// root-relative spelling it becomes — built once per set by
/// [`WholeSet::read`] ([`WholeSet::rooted`]).
names: Vec<(String, 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(), names: Vec::new() };
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.names = names_of(project, &set.files);
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()))
})
}
/// An engine sentence with every file of the set written root-relative.
/// The engines name a file by its base name when that is unique in the
/// set they were handed (`p1.sv:2` → `rtl/p1.sv:2`) and by the path they
/// were given otherwise (`/abs/…/top_a/pwrmgr_if.sv:80` →
/// `top_a/…/pwrmgr_if.sv:80`, generate-label-rename R1). One pass over
/// the set's spellings per sentence; the table itself is built once.
pub fn rooted(&self, sentence: &str) -> String {
let mut out = sentence.to_string();
for (spelled, shown) in &self.names {
if out.contains(spelled.as_str()) {
out = replace_file_name(&out, spelled, shown);
}
}
out
}
/// 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(", ")))
}
}
/// Every file's engine spelling and its root-relative one: the full path for
/// a base name several files share, else the base name (skipped when it is
/// already the relative path). Full paths first, so a bare base name never
/// rewrites the tail of one.
fn names_of(project: &Project, files: &[(PathBuf, String)]) -> Vec<(String, String)> {
let mut count: HashMap<&std::ffi::OsStr, usize> = HashMap::new();
for (path, _) in files {
if let Some(base) = path.file_name() {
*count.entry(base).or_default() += 1;
}
}
let (mut full, mut bare) = (Vec::new(), Vec::new());
for (path, _) in files {
let Some(base) = path.file_name() else { continue };
let shown = project.relative(path);
match count.get(base) {
Some(1) => {
if let Some(base) = base.to_str().filter(|base| *base != shown) {
bare.push((base.to_string(), shown));
}
}
_ => full.push((path.display().to_string(), shown)),
}
}
full.extend(bare);
full
}
/// `text` with every occurrence of the file name `base` that stands alone —
/// not the tail of a longer path or name — replaced by `path`.
fn replace_file_name(text: &str, base: &str, path: &str) -> String {
let glued_before = |c: char| is_ident_char(c) || matches!(c, '/' | '\\' | '.' | '-');
let glued_after = |c: char| is_ident_char(c) || matches!(c, '/' | '-');
let mut out = String::with_capacity(text.len());
let mut from = 0;
while let Some(found) = text[from..].find(base) {
let (start, end) = (from + found, from + found + base.len());
let before = text[..start].chars().next_back();
let after = text[end..].chars().next();
let alone = !before.is_some_and(glued_before) && !after.is_some_and(glued_after);
out.push_str(&text[from..start]);
out.push_str(if alone { path } else { base });
from = end;
}
out.push_str(&text[from..]);
out
}
/// 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_bare_file_name_is_replaced_only_where_it_stands_alone() {
let said = "at `u_s` (p1.sv:2), in p1.sv, not rtl/p1.sv, xp1.sv or p1.svh";
assert_eq!(
replace_file_name(said, "p1.sv", "rtl/p1.sv"),
"at `u_s` (rtl/p1.sv:2), in rtl/p1.sv, not rtl/p1.sv, xp1.sv or p1.svh"
);
assert_eq!(replace_file_name("p1.sv:6", "p1.sv", "a/p1.sv"), "a/p1.sv:6");
}
#[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 a_capped_text_is_one_line_cut_with_an_ellipsis() {
assert_eq!(capped("x y", 2), "x …");
assert_eq!(capped("x y", 3), "x y");
}
}
+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");
}
}
+786
View File
@@ -0,0 +1,786 @@
//! The dev's attack suite on the structural edits' verifier (lane M4) —
//! CLAUDE.md invariant 4 applied to the MCP block's own safety net: every
//! case is an edit the verifier could plausibly let through, asserted
//! **refused with the tree byte-identical** (every file hashed before and
//! after). A few controls sit beside them: the nearest edit that must pass,
//! so a refusal is known to come from the rule and not from a broken setup.
//!
//! The cases were written against `replace_item`, `insert_item` and
//! `delete_item`; the lean catalogue folds the three into `edit_item`
//! (PLAN §10.1), so [`lean`] maps each call and the cases stay as written.
//! What the lean surface removed (`dry_run`, `rename`, `force`) is gone from
//! the cases too: a refusal is checked once, and a forced deletion is now a
//! refusal like any other.
use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap;
use std::fs;
use std::hash::{Hash, Hasher};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::time::{Duration, Instant};
use serde_json::{json, Value};
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch tree: the `item` fixture plus the files a case adds.
struct Tree(PathBuf);
impl Tree {
fn with(files: &[(&str, &str)]) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir()
.join(format!("lucisv-mcp-attacks-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/item");
copy_tree(&fixture, &dir);
for (name, text) in files {
fs::write(dir.join(name), text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
/// Every file, root-relative, with the hash of its bytes.
fn hashes(&self) -> BTreeMap<String, u64> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, u64>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
continue;
}
let mut hasher = DefaultHasher::new();
fs::read(&path).unwrap().hash(&mut hasher);
let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
out.insert(name, hasher.finish());
}
}
let mut out = BTreeMap::new();
walk(&self.0, &self.0, &mut out);
out
}
fn read(&self, file: &str) -> String {
fs::read_to_string(self.0.join(file)).unwrap()
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// One running server, initialised.
struct Session {
child: Child,
stdin: ChildStdin,
lines: Receiver<String>,
next_id: i64,
}
impl Session {
fn over(tree: &Tree) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", tree.0.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdout = child.stdout.take().unwrap();
let (send, lines) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if send.send(line).is_err() {
break;
}
}
});
let stdin = child.stdin.take().unwrap();
let mut session = Session { child, stdin, lines, next_id: 0 };
session.request("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}));
session.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
session
}
fn send(&mut self, message: &Value) {
writeln!(self.stdin, "{message}").unwrap();
self.stdin.flush().unwrap();
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let id = self.next_id;
self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
let reply: Value = serde_json::from_str(&line).unwrap();
assert_eq!(reply["id"], id);
reply
}
/// A tool call: whether it was refused, and its text.
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String) {
let (tool, arguments) = lean(tool, arguments);
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
let result = &reply["result"];
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
(result["isError"] == true, text)
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// An M4 call as `edit_item` takes it: `replace_item`'s `item`,
/// `insert_item`'s `anchor` and `position`, `delete_item`'s `item`, each
/// under its `op`.
fn lean(tool: &str, mut args: Value) -> (&'static str, Value) {
let op = match tool {
"replace_item" => "replace",
"delete_item" => "delete",
"insert_item" => {
let before = args["position"] == "before";
let object = args.as_object_mut().unwrap();
object.remove("position");
let anchor = object.remove("anchor").unwrap();
object.insert("item".into(), anchor);
if before {
"insert_before"
} else {
"insert_after"
}
}
other => panic!("not a structural edit: {other}"),
};
args["op"] = Value::from(op);
("edit_item", args)
}
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
/// every file of the tree byte-identical.
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) {
let before = tree.hashes();
let (error, text) = server.call(tool, args.clone());
assert!(error, "{tool} {args}: not refused: {text}");
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
assert!(text.ends_with("nothing written.") || text.contains("nothing written"), "{text}");
assert_eq!(before, tree.hashes(), "{tool} {args}: a refusal wrote");
}
/// Run `tool` and assert it wrote (the control beside an attack).
fn accepted(server: &mut Session, tool: &str, args: Value) -> String {
let (error, text) = server.call(tool, args.clone());
assert!(!error, "{tool} {args}: refused: {text}");
text
}
fn core(item: &str, text: &str) -> Value {
json!({"file": "rtl/core.sv", "item": item, "text": text})
}
#[test]
fn a_text_that_opens_a_block_it_does_not_close_is_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let open = "always_ff @(posedge clk) begin\n r <= d;";
refused(&tree, &mut server, "replace_item", core("always@12", open), "no longer parse");
let unclosed_function = "function automatic int f(int a);\n return a;";
let args = json!({"file": "rtl/core.sv", "anchor": "r", "text": unclosed_function});
refused(&tree, &mut server, "insert_item", args, "no longer parse");
}
#[test]
fn a_text_that_closes_the_enclosing_module_is_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
// Still a valid file: `r` ends `core` and the rest becomes `sneaky`.
let closes = "logic [7:0] r;\nendmodule\nmodule sneaky;";
refused(&tree, &mut server, "replace_item", core("r", closes), "open and close");
let end = json!({"file": "rtl/wrap.sv", "anchor": "end", "text": "endmodule\nmodule sneaky;"});
refused(&tree, &mut server, "insert_item", end, "open and close");
}
#[test]
fn a_text_that_redeclares_a_port_is_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
// The duplicate rule fires before the name rule: a port is never
// redeclared.
refused(
&tree,
&mut server,
"replace_item",
core("p", "logic d;"),
"`d` would be declared twice",
);
let insert = json!({"file": "rtl/core.sv", "anchor": "p", "text": "logic [3:0] clk;"});
refused(&tree, &mut server, "insert_item", insert, "`clk` would be declared twice");
}
#[test]
fn two_items_where_one_was_and_an_empty_text_are_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let two = "logic p;\n logic p2;";
refused(&tree, &mut server, "replace_item", core("p", two), "holds 2 items where one was");
let empty_item = "logic p;;";
refused(&tree, &mut server, "replace_item", core("p", empty_item), "holds 2 items");
for empty in ["", " \n\t\r\n"] {
refused(&tree, &mut server, "replace_item", core("p", empty), "`op: delete` removes");
let args = json!({"file": "rtl/core.sv", "anchor": "end", "text": empty});
refused(&tree, &mut server, "insert_item", args, "`text` is empty");
}
}
const UTF8: &str =
"module u;\n logic a;// \u{fc}\u{20ac} note\n /*\u{e9}*/logic b;/*\u{df}*/\nendmodule\n";
#[test]
fn a_multibyte_neighbour_stays_byte_identical_and_a_non_ascii_name_is_refused() {
let tree = Tree::with(&[("rtl/u.sv", UTF8)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/u.sv", "item": "b", "text": "logic b\u{e9};"});
refused(&tree, &mut server, "replace_item", args, "the file would no longer");
let after = json!({"file": "rtl/u.sv", "anchor": "a", "text": "logic \u{e9};"});
refused(&tree, &mut server, "insert_item", after, "would no longer");
// The control: the comments hugging `b` on both sides, multibyte, stay.
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/u.sv", "item": "b", "text": "logic [1:0] b;"}),
);
assert_eq!(tree.read("rtl/u.sv"), UTF8.replace("logic b;", "logic [1:0] b;"));
// A multibyte comment inside the new text is the agent's to write.
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/u.sv", "item": "b", "text": "logic b; // \u{e9}"}),
);
}
#[test]
fn nothing_inside_a_format_fence_is_edited() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let fence = "`// lucisv: off` fence";
refused(&tree, &mut server, "replace_item", core("keep_me", "logic keep_me;"), fence);
refused(
&tree,
&mut server,
"delete_item",
json!({"file": "rtl/core.sv", "item": "keep_me"}),
fence,
);
for position in ["before", "after"] {
let args = json!({"file": "rtl/core.sv", "anchor": "keep_me", "position": position, "text": "logic z;"});
refused(&tree, &mut server, "insert_item", args, fence);
}
// Deleting the fenced region's owner, or an item whose leading comment
// is the `on` fence, would move a fence.
refused(
&tree,
&mut server,
"delete_item",
json!({"file": "rtl/core.sv", "item": "core"}),
fence,
);
refused(
&tree,
&mut server,
"delete_item",
json!({"file": "rtl/core.sv", "item": "always@22"}),
fence,
);
}
#[test]
fn a_file_or_a_text_with_an_unterminated_string_is_refused() {
let broken = "module s;\n initial $display(\"oops);\n logic a;\nendmodule\n";
let tree = Tree::with(&[("rtl/s.sv", broken)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/s.sv", "item": "a", "text": "logic [1:0] a;"});
refused(&tree, &mut server, "replace_item", args, "does not lex");
let end = json!({"file": "rtl/s.sv", "anchor": "end", "text": "logic b;"});
refused(&tree, &mut server, "insert_item", end, "does not lex");
refused(&tree, &mut server, "replace_item", core("p", "logic p = \"x;"), "no longer lex");
}
#[test]
fn an_insert_after_endmodule_must_be_something_a_file_may_hold() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
// Both parse: the parser accepts module items at file scope.
for text in ["always_comb q = r;", "assign q = 8'h0;", "core u_again (.*);"] {
let args =
json!({"file": "rtl/wrap.sv", "anchor": "wrap", "position": "after", "text": text});
refused(&tree, &mut server, "insert_item", args, "cannot stand in a file's scope");
}
let in_package =
json!({"file": "rtl/item_pkg.sv", "anchor": "end", "text": "initial $display(1);"});
refused(&tree, &mut server, "insert_item", in_package, "cannot stand in a package's scope");
// The control: a module after a module.
let module =
json!({"file": "rtl/wrap.sv", "anchor": "wrap", "text": "module extra;\nendmodule"});
accepted(&mut server, "insert_item", module);
assert!(tree.read("rtl/wrap.sv").ends_with("endmodule\n\nmodule extra;\nendmodule\n"));
}
#[test]
fn a_valid_item_of_another_kind_is_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let function = "function automatic int f(int a);\n return a;\n endfunction";
refused(
&tree,
&mut server,
"replace_item",
core("always@12", function),
"a function where a always was",
);
let initial = "initial r = '0;";
refused(
&tree,
&mut server,
"replace_item",
core("always@12", initial),
"initial where a always",
);
refused(
&tree,
&mut server,
"replace_item",
core("p", "assign q = 8'h1;"),
"assign where a declaration",
);
// The control: `always_ff` may become `always_comb` — one class.
accepted(&mut server, "replace_item", core("always@22", "always @* p = ^r;"));
}
const ESCAPED: &str = "module e;\n logic \\a+b ;\n assign \\a+b = 1'b0;\nendmodule\n";
#[test]
fn an_escaped_name_is_matched_exactly() {
let tree = Tree::with(&[("rtl/e.sv", ESCAPED)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/e.sv", "item": "\\a+b", "text": "logic \\a+c ;"});
refused(
&tree,
&mut server,
"replace_item",
args,
"declares `\\a+c` where the item declared `\\a+b`",
);
let delete = json!({"file": "rtl/e.sv", "item": "\\a+b"});
refused(&tree, &mut server, "delete_item", delete, "rtl/e.sv:3:10 `\\a+b`");
let args = json!({"file": "rtl/e.sv", "item": "\\a+b", "text": "logic [1:0] \\a+b ;"});
accepted(&mut server, "replace_item", args);
assert_eq!(tree.read("rtl/e.sv"), ESCAPED.replace("logic \\a+b", "logic [1:0] \\a+b"));
}
#[test]
fn half_an_ifdef_is_refused_in_either_direction() {
let guarded = "module g;\n`ifdef FAST\n logic a;\n`endif\n logic b;\nendmodule\n";
let tree = Tree::with(&[("rtl/g.sv", guarded)]);
let mut server = Session::over(&tree);
let open = "`ifdef FAST\n logic [7:0] r;";
refused(&tree, &mut server, "replace_item", core("r", open), "holds 2 items");
// One item — a module — carrying half a guard inside it.
let inside = "module tick (\n input logic clk\n);\n`ifdef X\nendmodule";
let args = json!({"file": "rtl/tick.sv", "item": "tick", "text": inside});
refused(&tree, &mut server, "replace_item", args, "`ifdef` whose other half");
let close = json!({"file": "rtl/core.sv", "anchor": "r", "text": "`endif\nlogic z;"});
refused(&tree, &mut server, "insert_item", close, "`endif` whose other half");
let orphan =
json!({"file": "rtl/g.sv", "anchor": "b", "position": "before", "text": "`else\nlogic c;"});
refused(&tree, &mut server, "insert_item", orphan, "`else` whose other half");
// The controls: a balanced guard inserts; an item inside one replaces.
let whole =
json!({"file": "rtl/g.sv", "anchor": "b", "text": "`ifdef SLOW\n logic c;\n`endif"});
accepted(&mut server, "insert_item", whole);
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/g.sv", "item": "a", "text": "logic [1:0] a;"}),
);
}
#[test]
fn an_insert_or_delete_on_a_shared_line_is_refused() {
let shared = "module n; logic q; logic w; endmodule\n";
let tree = Tree::with(&[("rtl/n.sv", shared)]);
let mut server = Session::over(&tree);
let delete = json!({"file": "rtl/n.sv", "item": "q"});
refused(&tree, &mut server, "delete_item", delete, "shares a line");
let insert = json!({"file": "rtl/n.sv", "anchor": "w", "text": "logic e;"});
refused(&tree, &mut server, "insert_item", insert, "shares a line");
let end = json!({"file": "rtl/n.sv", "anchor": "end", "text": "logic e;"});
refused(&tree, &mut server, "insert_item", end, "shares a line");
// `replace_item` needs no line of its own: the span is the span.
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/n.sv", "item": "q", "text": "logic [1:0] q;"}),
);
assert_eq!(tree.read("rtl/n.sv"), "module n; logic [1:0] q; logic w; endmodule\n");
}
#[test]
fn a_port_in_a_header_is_not_an_item_and_a_non_ansi_body_port_keeps_its_header() {
let non_ansi =
"module k (a, b);\n input [3:0] a;\n output b;\n assign b = 1'b0;\nendmodule\n";
let tree = Tree::with(&[("rtl/k.sv", non_ansi)]);
let mut server = Session::over(&tree);
refused(
&tree,
&mut server,
"replace_item",
core("d", "input logic [3:0] d"),
"part of a larger item",
);
refused(
&tree,
&mut server,
"delete_item",
json!({"file": "rtl/core.sv", "item": "clk"}),
"part of a larger item",
);
let body = json!({"file": "rtl/k.sv", "item": "a"});
refused(&tree, &mut server, "delete_item", body, "`a` is also declared on line 1");
let widen = json!({"file": "rtl/k.sv", "item": "a", "text": "input [7:0] a;"});
accepted(&mut server, "replace_item", widen);
}
/// A module of `lines` lines: `logic sN;` declarations with one always
/// block in the middle.
fn big_module(lines: usize) -> String {
let mut text = String::from("module big (input logic clk);\n");
for n in 0..lines - 3 {
if n == lines / 2 {
text.push_str(" always_ff @(posedge clk) s0 <= ~s0;\n");
} else {
text.push_str(&format!(" logic s{n};\n"));
}
}
text.push_str("endmodule\n");
text
}
#[test]
fn a_forty_thousand_line_file_is_verified_in_bounded_time() {
let big = big_module(40_000);
let tree = Tree::with(&[("rtl/big.sv", &big)]);
let mut server = Session::over(&tree);
let line = big.lines().position(|l| l.contains("always_ff")).unwrap() + 1;
let item = format!("always@{line}");
let timed = |server: &mut Session, tool: &str, args: Value| {
let started = Instant::now();
let answer = server.call(tool, args);
(answer, started.elapsed().as_millis())
};
let before = tree.hashes();
let open =
json!({"file": "rtl/big.sv", "item": item, "text": "always_ff @(posedge clk) begin"});
let ((error, text), refused_ms) = timed(&mut server, "replace_item", open);
assert!(error && text.contains("no longer parse"), "{text}");
assert_eq!(before, tree.hashes());
let good =
json!({"file": "rtl/big.sv", "item": item, "text": "always_ff @(posedge clk) s0 <= s0;"});
let ((error, text), replaced_ms) = timed(&mut server, "replace_item", good);
assert!(!error, "{text}");
let insert = json!({"file": "rtl/big.sv", "anchor": "end", "text": "logic tail;"});
let ((error, text), inserted_ms) = timed(&mut server, "insert_item", insert);
assert!(!error, "{text}");
let delete = json!({"file": "rtl/big.sv", "item": "s7"});
let ((error, text), deleted_ms) = timed(&mut server, "delete_item", delete);
assert!(!error, "{text}");
println!(
"40 000 lines: refused replace {refused_ms} ms, replace {replaced_ms} ms, insert {inserted_ms} ms, delete {deleted_ms} ms"
);
}
const LOOP: &str = "module h;\n for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end\n assign gen_l[0].z = 1'b0;\nendmodule\n";
#[test]
fn a_generate_loop_owns_its_label() {
let tree = Tree::with(&[("rtl/h.sv", LOOP)]);
let mut server = Session::over(&tree);
let relabel = "for (genvar i = 0; i < 2; i++) begin : gen_m\n logic z;\n end";
let args = json!({"file": "rtl/h.sv", "item": "gen_l", "text": relabel});
refused(
&tree,
&mut server,
"replace_item",
args,
"declares `gen_m`, `i` where the item declared `gen_l`, `i`",
);
let delete = json!({"file": "rtl/h.sv", "item": "gen_l"});
refused(&tree, &mut server, "delete_item", delete, "rtl/h.sv:5:10 `gen_l`");
// The control: a wider body under the same label.
let wider = "for (genvar i = 0; i < 2; i++) begin : gen_l\n logic [1:0] z;\n end";
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/h.sv", "item": "gen_l", "text": wider}),
);
}
// ---- the rework's attacks (QA findings 1–8, 2026-09-23) --------------------
const FENCE_BELOW: &str = "module f;
logic a;
logic b; // b's own
// lucisv: off
/* hand aligned */
logic keep_me;
// lucisv: on
logic z;
endmodule
";
/// Rule 1a/1b (finding 1): a text may not reach past its own end — an open
/// comment a later `*/` closes, or a comment left on a line of its own that
/// would lead the next item.
#[test]
fn a_text_reaching_past_its_end_is_refused_by_the_lexical_rules() {
let tree = Tree::with(&[("rtl/f.sv", FENCE_BELOW)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a; /* note"});
refused(&tree, &mut server, "replace_item", args, "rule 1a");
let args = json!({"file": "rtl/f.sv", "anchor": "a", "text": "logic y; /* note"});
refused(&tree, &mut server, "insert_item", args, "rule 1a");
let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a;\n // about b"});
refused(&tree, &mut server, "replace_item", args, "rule 1b");
// The control: a comment on the item's own line stays the item's.
let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a; /* note */"});
accepted(&mut server, "replace_item", args);
assert_eq!(tree.read("rtl/f.sv"), FENCE_BELOW.replace("logic a;", "logic a; /* note */"));
}
const DOCUMENTED: &str = "module d;
// Section banner
// old doc of a
logic a; // old trailing
logic b;
endmodule
";
/// Finding 2: a text carrying the item's comments replaces the item's own
/// comments with it, so the same call twice is `unchanged`; a banner a blank
/// line separates from the item is not the item's.
#[test]
fn a_text_with_comments_replaces_the_items_own_and_repeats_unchanged() {
let tree = Tree::with(&[("rtl/d.sv", DOCUMENTED)]);
let mut server = Session::over(&tree);
let text = "// new doc of a\n logic [1:0] a; // new trailing";
let args = json!({"file": "rtl/d.sv", "item": "a", "text": text});
accepted(&mut server, "replace_item", args.clone());
let once = tree.read("rtl/d.sv");
let expected = DOCUMENTED.replace(
"// old doc of a\n logic a; // old trailing",
"// new doc of a\n logic [1:0] a; // new trailing",
);
assert_eq!(once, expected);
let again = accepted(&mut server, "replace_item", args);
assert!(again.starts_with("unchanged"), "{again}");
assert_eq!(tree.read("rtl/d.sv"), once);
// Without comments in the text, the item's comments stay where they are.
let args = json!({"file": "rtl/d.sv", "item": "a", "text": "logic a;"});
accepted(&mut server, "replace_item", args);
assert_eq!(tree.read("rtl/d.sv"), once.replace("logic [1:0] a;", "logic a;"));
}
const MACROS: &str = "`define ID(x) x
`define CHECK(s) initial assert (!$isunknown(s));
module mc (output logic o);
logic in_arg;
logic in_nested;
logic in_other_body;
logic free;
assign o = `ID(in_arg);
`CHECK(`ID(in_nested))
// free is only named in this comment
initial $display(\"free\");
endmodule
";
const MACRO_HEADER: &str = "`define READ_OTHER in_other_body\n";
/// Finding 3: a spelling inside a macro call (nested too) or another file's
/// `` `define`` body is a possible use; a comment or a string is not.
#[test]
fn a_name_spelled_inside_a_macro_is_a_possible_use() {
let tree = Tree::with(&[("rtl/mc.sv", MACROS), ("rtl/defs.svh", MACRO_HEADER)]);
let mut server = Session::over(&tree);
for (name, line) in [("in_arg", "rtl/mc.sv:8"), ("in_nested", "rtl/mc.sv:9")] {
let args = json!({"file": "rtl/mc.sv", "item": name});
refused(
&tree,
&mut server,
"delete_item",
args,
&format!("possible use (macro) at {line} `{name}`"),
);
}
let args = json!({"file": "rtl/mc.sv", "item": "in_other_body"});
refused(
&tree,
&mut server,
"delete_item",
args,
"possible use (macro) at rtl/defs.svh:1 `in_other_body`",
);
// The control: a name spelled only in a comment and a string goes.
accepted(&mut server, "delete_item", json!({"file": "rtl/mc.sv", "item": "free"}));
}
const BANNERS: &str = "// File banner
module fb;
// Registers
// the a flop
logic a;
logic b;
endmodule
";
/// Finding 4: a comment a blank line separates from the item is not the
/// item's — not a section banner, not the file banner above a module.
#[test]
fn a_delete_leaves_the_comments_a_blank_line_separates_from_the_item() {
let tree = Tree::with(&[("rtl/fb.sv", BANNERS)]);
let mut server = Session::over(&tree);
accepted(&mut server, "delete_item", json!({"file": "rtl/fb.sv", "item": "a"}));
assert_eq!(tree.read("rtl/fb.sv"), BANNERS.replace(" // the a flop\n logic a;\n", ""));
accepted(&mut server, "delete_item", json!({"file": "rtl/fb.sv", "item": "fb"}));
assert_eq!(tree.read("rtl/fb.sv"), "// File banner\n\n");
}
/// Finding 5: a comment before the item on its line goes with the item; only
/// another item's code on the line makes it shared.
#[test]
fn a_same_line_comment_goes_with_its_item_and_code_still_shares_the_line() {
let src = "module sl;\n /* lead */ logic a;\n logic x; /* c */ logic y;\nendmodule\n";
let tree = Tree::with(&[("rtl/sl.sv", src)]);
let mut server = Session::over(&tree);
let delete = json!({"file": "rtl/sl.sv", "item": "y"});
refused(&tree, &mut server, "delete_item", delete, "shares a line");
accepted(&mut server, "delete_item", json!({"file": "rtl/sl.sv", "item": "a"}));
assert_eq!(tree.read("rtl/sl.sv"), "module sl;\n logic x; /* c */ logic y;\nendmodule\n");
}
const DEFINES: &str = "`define W 1'b1
module dm (output logic o, output logic p);
always_comb begin
p = 1'b0;
end
assign o = `W;
endmodule
";
/// Rule 6 (finding 6): a `` `define``/`` `undef`` nested in an item changes
/// code outside it — refused by replace, insert and delete; a directive item
/// of its own is the control.
#[test]
fn a_macro_definition_nested_in_an_item_is_refused() {
let tree = Tree::with(&[("rtl/dm.sv", DEFINES)]);
let mut server = Session::over(&tree);
let nested = "always_comb begin\n`undef W\n p = 1'b0;\n end";
let args = json!({"file": "rtl/dm.sv", "item": "always@3", "text": nested});
refused(&tree, &mut server, "replace_item", args, "changes a macro definition (`W`)");
let insert = json!({"file": "rtl/dm.sv", "anchor": "always@3", "text": "initial begin\n`define W 1'b0\n end"});
refused(&tree, &mut server, "insert_item", insert, "(rule 6)");
let with_define = DEFINES.replace(" p = 1'b0;\n", "`define Q 1\n p = 1'b0;\n");
let tree = Tree::with(&[("rtl/dm.sv", &with_define)]);
let mut server = Session::over(&tree);
let delete = json!({"file": "rtl/dm.sv", "item": "always@3"});
refused(&tree, &mut server, "delete_item", delete, "(`Q`)");
// The control: a directive item of its own may be inserted.
let args = json!({"file": "rtl/dm.sv", "anchor": "always@3", "text": "`define R 2"});
accepted(&mut server, "insert_item", args);
}
/// Rule 7 (finding 7): a text neither opens nor closes a fence.
#[test]
fn a_text_may_not_carry_a_fence_marker() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let text = "// lucisv: off\n logic lo;";
let args = json!({"file": "rtl/core.sv", "anchor": "p", "text": text});
refused(&tree, &mut server, "insert_item", args, "fence marker `// lucisv: off`");
let text = "always_comb begin\n // lucisv: on\n p = ^r;\n end";
refused(&tree, &mut server, "replace_item", core("always@22", text), "(rule 7)");
// The control: an ordinary comment in the same place.
let text = "always_comb begin\n // lucisv: parity\n p = ^r;\n end";
accepted(&mut server, "replace_item", core("always@22", text));
}
const STARS: &str = "module sw;
logic clk;
logic rst_ni;
logic [7:0] d;
logic [7:0] q;
logic unrelated;
if (1) begin : g
core u_core (.*);
end
endmodule
module other;
logic d;
ghost u_ghost (.*);
endmodule
";
/// Finding 8: a `.*` binds without spelling the name — a port of the
/// instantiated module is a use (generate blocks included); a module the
/// index cannot resolve makes every name a possible use in that scope.
#[test]
fn a_signal_bound_by_a_dot_star_is_still_referenced() {
let tree = Tree::with(&[("rtl/sw.sv", STARS)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/sw.sv", "item": "d@4"});
refused(
&tree,
&mut server,
"delete_item",
args,
"bound by `.*` at rtl/sw.sv:8:18 `d` (module `core`)",
);
let args = json!({"file": "rtl/sw.sv", "item": "d@12"});
refused(
&tree,
&mut server,
"delete_item",
args,
"possible use (`.*`) at rtl/sw.sv:13:18 `d` (module `ghost`",
);
// The controls: a signal the module has no port for; a module's own `.*`
// does not reach another module's names.
accepted(&mut server, "delete_item", json!({"file": "rtl/sw.sv", "item": "unrelated"}));
let clk = json!({"file": "rtl/sw.sv", "item": "clk"});
refused(&tree, &mut server, "delete_item", clk, "bound by `.*` at rtl/sw.sv:7:18 `clk`");
}
+257
View File
@@ -0,0 +1,257 @@
//! The index caches over the wire (TODO-MCP M6, PLAN §6): the language
//! server's `index-cache` is read and never written — its bytes are hashed
//! before and after a whole session that indexes, answers and edits — every
//! record that is not exactly right is skipped, a missing or unwritable
//! cache directory costs a cold start and nothing else, and the server's own
//! `index-cache-mcp` is written on exit and read on the next start.
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use lucisv_core::cache::content_hash;
use serde_json::{json, Value};
use vlog_semantic::{FileFacts, FACTS_FORMAT};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// The design fixture's file count.
const FILES: usize = 7;
/// A fresh copy of `tests/fixtures/design` under `<dir>/src`, and `<dir>/cache`
/// for the stores; removed on drop.
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Scratch {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-cache-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/design");
copy_tree(&source, &dir.join("src"));
Scratch(fs::canonicalize(dir).unwrap())
}
fn src(&self) -> PathBuf {
self.0.join("src")
}
fn cache(&self) -> PathBuf {
self.0.join("cache")
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// Every file under `dir`, sorted.
fn files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
out.extend(files(&path));
} else {
out.push(path);
}
}
out.sort();
out
}
/// The language server's header for this build.
fn header(version: &str) -> String {
format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{version}")
}
/// One record in the language server's format.
fn record(path: &Path) -> String {
let bytes = fs::read(path).unwrap();
let facts = FileFacts::of(path.to_path_buf(), std::str::from_utf8(&bytes).unwrap());
let encoded = facts.encode().unwrap();
let checksum = content_hash(encoded.as_bytes());
format!("{:016x}\t{encoded}\t{checksum:016x}", content_hash(&bytes))
}
/// A store the way the language server writes one, over every source file.
fn editor_store(scratch: &Scratch, version: &str) -> Vec<String> {
let mut lines = vec![header(version)];
lines.extend(files(&scratch.src()).iter().map(|path| record(path)));
lines
}
/// One server over the scratch design with `--index-cache`.
struct Session {
child: Child,
next_id: i64,
stdout: std::io::BufReader<std::process::ChildStdout>,
}
impl Session {
fn start(scratch: &Scratch) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.arg("--root")
.arg(scratch.src())
.arg("--index-cache")
.arg(scratch.cache())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
let mut session = Session { child, next_id: 0, stdout };
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
session
}
fn request(&mut self, method: &str, params: Value) -> Value {
use std::io::BufRead;
self.next_id += 1;
let line =
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
let stdin = self.child.stdin.as_mut().unwrap();
writeln!(stdin, "{line}").unwrap();
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: its text.
fn text(&mut self, tool: &str, arguments: Value) -> String {
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
assert_eq!(reply["result"]["isError"], false, "{tool}: {reply}");
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
}
/// Close stdin, as a host does, and return everything said on stderr.
fn end(mut self) -> String {
drop(self.child.stdin.take());
let status = self.child.wait().unwrap();
assert!(status.success(), "{status}");
let mut stderr = String::new();
self.child.stderr.take().unwrap().read_to_string(&mut stderr).unwrap();
stderr
}
}
/// A session that indexes, answers, edits and ends; its stderr.
fn whole_session(scratch: &Scratch) -> String {
let mut session = Session::start(scratch);
assert!(session.text("hierarchy", json!({})).starts_with("7 files, "));
assert!(session.text("outline", json!({"unit": "leaf"})).starts_with("rtl/leaf.sv:1\n"));
session.text("format", json!({"files": "rtl/top.sv"}));
// One more call, so the index has absorbed whatever the edit wrote.
session.text("outline", json!({"file": "rtl/top.sv"}));
let stderr = session.end();
assert!(stderr.contains(&format!("lucisv-mcp: indexed {FILES} files in ")), "{stderr}");
stderr
}
/// The startup line's tail: `ms (E from the editor's cache, O from its own)`
/// after `indexed 7 files in`.
fn reused(editor: usize, own: usize) -> String {
format!(" ms ({editor} from the editor's cache, {own} from its own)\n")
}
fn hash_file(path: &Path) -> u64 {
content_hash(&fs::read(path).unwrap())
}
#[test]
fn the_editors_store_is_read_skipping_bad_records_and_never_written() {
let scratch = Scratch::new();
let mut lines = editor_store(&scratch, env!("CARGO_PKG_VERSION"));
// A record whose hash matches its file but whose facts no longer match
// their checksum: an instance renamed inside it.
let at = lines.iter().position(|line| line.contains("/rtl/top.sv\t")).unwrap();
let forged = lines[at].replacen("\tu_leaf\t", "\tu_lesf\t", 1);
assert_ne!(forged, lines[at], "the forgery changed the facts");
lines[at] = forged;
// A torn last record, no newline.
let last = lines.len() - 1;
lines[last] = lines[last][..lines[last].len() / 2].to_string();
fs::create_dir_all(scratch.cache()).unwrap();
let store = scratch.cache().join("index-cache");
fs::write(&store, lines.join("\n")).unwrap();
let before = (hash_file(&store), fs::metadata(&store).unwrap().modified().unwrap());
let stderr = whole_session(&scratch);
assert!(stderr.contains(&reused(FILES - 2, 0)), "{stderr}");
let after = (hash_file(&store), fs::metadata(&store).unwrap().modified().unwrap());
assert_eq!(before, after, "the language server's store is byte-identical, untouched");
let own = fs::read_to_string(scratch.cache().join("index-cache-mcp")).unwrap();
assert!(own.starts_with(&format!("{}\n", header(env!("CARGO_PKG_VERSION")))));
assert_eq!(own.lines().count(), 1 + FILES);
}
#[test]
fn a_store_from_another_version_is_ignored_whole_with_one_line() {
let scratch = Scratch::new();
fs::create_dir_all(scratch.cache()).unwrap();
let store = scratch.cache().join("index-cache");
fs::write(&store, editor_store(&scratch, "0.0.0").join("\n") + "\n").unwrap();
let before = hash_file(&store);
let stderr = whole_session(&scratch);
assert_eq!(stderr.matches("ignoring the index cache").count(), 1, "{stderr}");
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(hash_file(&store), before);
}
#[test]
fn a_missing_directory_starts_cold_and_its_own_store_serves_the_next_start() {
let scratch = Scratch::new();
let stderr = whole_session(&scratch);
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert!(!stderr.contains("ignoring") && !stderr.contains("cannot"), "{stderr}");
assert!(!scratch.cache().join("index-cache").exists(), "the editor's store is not made");
assert!(scratch.cache().join("index-cache-mcp").exists());
let stderr = whole_session(&scratch);
assert!(stderr.contains(&reused(0, FILES)), "{stderr}");
// A file changed since its record: its hash misses, it is parsed, and
// the answer is the new text's.
let leaf = scratch.src().join("rtl/leaf.sv");
let text = fs::read_to_string(&leaf).unwrap().replace("module leaf", "module leaf2");
fs::write(&leaf, text).unwrap();
let mut session = Session::start(&scratch);
let units = session.text("find", json!({"name": "leaf2"}));
assert!(units.contains("module leaf2"), "{units}");
let stderr = session.end();
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
}
#[cfg(unix)]
#[test]
fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
fs::create_dir_all(scratch.cache()).unwrap();
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o555)).unwrap();
let stderr = whole_session(&scratch);
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o755)).unwrap();
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert!(fs::read_dir(scratch.cache()).unwrap().next().is_none(), "nothing was written");
}
@@ -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
@@ -0,0 +1,7 @@
`define CORE_HIER tb.u_core
`define SM_STATE `CORE_HIER.u_main_sm.state_q
interface probe_if;
string path = {"tb.u_core.u_main_sm", ".state_q"};
logic seen;
assign seen = `CORE_HIER.u_main_sm.state_q;
endinterface
+12
View File
@@ -0,0 +1,12 @@
module cipher #(
parameter bit Masking = 1
) (
input logic clk_i,
input logic rst_ni,
// Data
input logic [31:0] data_i,
output logic valid_o
);
assign valid_o = data_i[0] & rst_ni;
endmodule
+11
View File
@@ -0,0 +1,11 @@
module core (
input logic clk_i,
output logic busy_o,
output logic probe_o
);
main_sm u_main_sm (
.clk_i (clk_i),
.busy_o (busy_o)
);
assign probe_o = u_main_sm.state_q;
endmodule
@@ -0,0 +1,8 @@
module other_sm (
input logic clk_i,
output logic busy_o
);
logic state_q;
always_ff @(posedge clk_i) state_q <= ~state_q;
assign busy_o = state_q;
endmodule
+11
View File
@@ -0,0 +1,11 @@
// The main state machine; state_q is its register.
`define FLOP(d, q) always_ff @(posedge clk_i) q <= d;
module main_sm (
input logic clk_i,
output logic busy_o
);
logic state_d, state_q;
`FLOP(state_d, state_q)
assign state_d = ~state_q;
assign busy_o = state_q;
endmodule
+17
View File
@@ -0,0 +1,17 @@
module wrap (
input logic clk_i,
input logic rst_ni,
input logic dbg_i,
input logic [31:0] data_i,
output logic valid_o
);
cipher #(
.Masking ( 1 )
) u_cipher (
.clk_i ( clk_i ),
.rst_ni ( rst_ni ),
.data_i ( data_i ), // payload
.valid_o ( valid_o )
);
endmodule
+23
View File
@@ -0,0 +1,23 @@
module core (
input logic clk,
input logic rst_ni,
input logic [7:0] d,
output logic [7:0] q
);
logic [7:0] r; // the register
// Parity of r.
logic p;
// Register the input.
always_ff @(posedge clk or negedge rst_ni)
if (!rst_ni) r <= '0;
else r <= d;
assign q = r;
// lucisv: off
logic keep_me;
// lucisv: on
always_comb p = item_pkg::parity(r);
endmodule
+13
View File
@@ -0,0 +1,13 @@
package item_pkg;
parameter int WIDTH = 8;
// Parity of a word.
function automatic logic parity(logic [WIDTH-1:0] w);
return ^w;
endfunction
// Nobody calls this one.
function automatic logic spare(logic a);
return a;
endfunction
endpackage
+4
View File
@@ -0,0 +1,4 @@
module tick (
input logic clk
);
endmodule
+9
View File
@@ -0,0 +1,9 @@
module wrap (
input logic clk,
input logic rst_ni,
input logic [7:0] d,
output logic [7:0] q
);
core u_core (.*);
tick u_tick (.clk);
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))
Loaded 100 of 826 files, more files were not shown because too many files have changed in this diff. Show more