Compare commits

...
8 Commits
Author SHA1 Message Date
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
115 changed files with 15185 additions and 560 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
+2 -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
+51
View File
@@ -4,6 +4,57 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.57.0 — 2026-09-23
### The MCP block complete: structural edits, the server in the extension, cache reuse, and three census rounds
- **`lucisv-mcp` ships inside every platform package** and VS Code's
agent mode finds it with no configuration: the extension registers one
server per workspace folder through `mcpServerDefinitionProviders`
(VS Code 1.101+; older VS Code keeps working without it), passes it the
folder as root and the extension's storage as the index-cache directory,
and the command **lucisv: Copy MCP server config** puts the snippet for
Claude Code, Cursor or a `.vscode/mcp.json` on the clipboard. Settings
`lucisv.mcp.enabled` and `lucisv.mcp.path`. The Agents guide on the
docs site lists every tool. (`docs/features/mcp-packaging`.)
- **Structural edits — the token saver.** `replace_item`, `insert_item`
and `delete_item` take one item's text, never the file: a module, an
`always` block, a function, a declaration, selected the way `read_item`
slices it. The block's own verifier refuses anything that changes a byte
outside the item's lines, opens a block it does not close, closes the
enclosing module, changes an item's kind, declares a name twice, splits
an `ifdef`, alters a macro definition or a fence marker, or leaves a
comment or string running into the code after it; `delete_item` refuses
while a declared name is still used — by the engine, by a macro argument
or `define` body, or through a `.*` binding — unless `force` is passed.
45 QA attack tests. (`docs/features/mcp-structural-edits`.)
- **Warm start from the editor's index.** With `--index-cache DIR` the
server reads the language server's store read-only (never writes it),
skips the parse of every file whose bytes it already describes, and
keeps its own store beside it: opentitan startup 1.9 s → 0.8 s.
(`docs/features/mcp-cache-and-census`.)
- **What three census rounds changed** (`mcp_analysis.md`: four tasks,
20 sub-agent runs on opentitan, with and without the server): every
`references`, `rename`, `add_port` and `remove_port` answer now ends
with the *unresolved mentions* of the name — strings, comments, macro
text and macro-rooted paths no engine resolves — so a DV force path
built as a string is no longer missed; every paged answer opens with
`N things (showing a–b)` and the default limit is 500; the listing tools
take an `in` path glob (`ip/**/rtl/*.sv`), which turns "who
instantiates X under ip/, RTL only" into one call; `add_port` takes
`after` to place the port where the file's style wants it; the tool
catalogue is 40 % smaller; the instantiation template and hierarchy
overrides are opt-in. Verdict: no wrong answer in 20 runs, 15 % fewer
tokens on the whole-design question, small edits 4–19 % dearer, the
cross-file rename complete where plain search had missed a site.
- **Filed for the engines, not fixed here:** the parser's silence on a
trailing `,` in a connection list, `{d,, d}` and `type(x)'(y)` in a
connection; a false `remove_port` refusal on a same-file instantiation;
`extract_module` writing LF into a CRLF file; a lint gap on a
directionless header port; the LSP's `references` omitting three real
`aes` instantiations in the `*_pd_main.sv` tops (`docs/topo.md` §2.9
rows 35–42).
## 0.56.0 — 2026-09-23
### Rename keeps implicit connections bound; the MCP server, as a preview
+7
View File
@@ -77,6 +77,13 @@ 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]`
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.56.0"
version = "0.57.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.56.0"
version = "0.57.0"
[[package]]
name = "lucisv_mcp"
version = "0.56.0"
version = "0.57.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.56.0"
version = "0.57.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.56.0"
version = "0.57.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.56.0"
version = "0.57.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.56.0"
version = "0.57.0"
[[package]]
name = "vlog_refactor"
version = "0.56.0"
version = "0.57.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.56.0"
version = "0.57.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.56.0"
version = "0.57.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+19 -3
View File
@@ -460,7 +460,7 @@ understand still lints the buffer. Full rules:
## Architecture (the ruff mapping)
The eight-crate workspace separates source syntax, reusable engines, project
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:
@@ -475,6 +475,7 @@ of document layout from language rules:
| `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.
@@ -482,7 +483,8 @@ Linting consumes the parser, semantics and `lucisv_core` (for the one
`--exclude`-style matcher a waiver file's `--location` shares with the CLI);
refactoring consumes the parser and semantics. The CLI reaches
semantics through the linter and has no refactoring dependency. The server
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
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:
@@ -929,7 +931,7 @@ parents into sections alongside Other Modules. Stars persist per workspace;
**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:
@@ -983,6 +985,20 @@ 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
+109 -31
View File
@@ -186,25 +186,25 @@ lane: the LSP's rename inherits the fix.
`tests/wire.rs` and `tests/attacks.rs` (new), fixtures, the
`mcp-structural-edits` README. Depends on M3 merged.
- [ ] `replace_item`, `insert_item`, `delete_item` with the PLAN §4.3
- [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`
- [ ] `tests/attacks.rs`, written by the dev, every case asserted
- [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
- [ ] README `mcp-structural-edits`: the contract as a table, the attack
- [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)
- [ ] gates; sizes (`item.rs` is expected to be the largest file in the
- [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`)
- [ ] QA: re-attack with at least eight new cases (a `text` that is two
- [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
@@ -224,13 +224,13 @@ mcp_test.js,mcp_smoke.js,.vscodeignore,README.md,CHANGELOG.md}`,
trunk; touches no Rust. `extension.js` changes are limited to requiring
`mcp.js` and calling its `activate(context)`.
- [ ] `release.sh`: stage `lucisv-mcp[.exe]` into `bin/` (platform) and
- [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/*`
- [ ] `mcp.js`: the three-rung binary ladder reusing `bundledBinary`;
- [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`),
@@ -241,20 +241,20 @@ trunk; touches no Rust. `extension.js` changes are limited to requiring
binary; `mcp_test.js` with a stubbed `vscode` (the `hierarchyView_test`
pattern) covering the ladder, the guard on an old VS Code (no `lm`),
and the three snippets
- [ ] `package.json`: `contributes.mcpServerDefinitionProviders`, the two
- [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
- [ ] docs: the site guide page (install via vsix → nothing to do; Claude
- [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
- [ ] CI: `node --test editors/vscode/*_test.js` in `ci.yml`
- [ ] README `mcp-packaging`; work log; `node --test` green; a local
- [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
- [ ] QA: install the vsix into a clean VS Code profile: the server listed
- [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
@@ -273,38 +273,43 @@ MCP section), `docs/topo.md` (§1.1 node + §2.8 rows for `lucisv_mcp`, an
`mcp-cache-and-census` README, `TODO-MCP.md` (this file's closing entries).
Depends on M4 and M5 merged.
- [ ] `cache.rs`: the read-only reader of the LSP's `index-cache` (header
- [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)
- [ ] startup timing on opentitan cold / warm-from-LSP-store /
— 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`
- [ ] the token census (PLAN §8): the three tasks, each run twice (file
tools only / with lucisv-mcp) by the same agent model, tokens in and
out from the transcripts, written up in `docs/mcp/census.md` with the
transcripts' task ids; if a task saved nothing, say so — the number
is the deliverable, not its sign
- [ ] `instructions` and tool descriptions revised from what the census
transcripts show the agent misunderstood; `prompts/*` added only if
the census shows a repeated multi-tool sequence worth one prompt
- [ ] `docs/topo.md`: the `lucisv_mcp` node (`──▶` the six libraries; `-.spawn
contract.->` from `editors/vscode`; `-.builds/packages.->` from
`tools/`), the §2.8 rows, the Handshake MCP-1 status (delivered or
still open), and MCP-3 filed in §2.9 if M2's hierarchy walk and the
server's snapshot drifted
- [ ] `CHANGELOG.md` section, `README.md` architecture table row (nine
crates), `docs/repository-analysis.md` map row, CLAUDE.md measurement
line refreshed with the new crate's sizes
— 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
- [ ] release **0.56.0** (or the next minor free at the time): tag, CI
green, 8 assets, the darwin-arm64 vsix unzipped and checked for three
binaries, the MCP smoke in the release log; the install line and the
`claude mcp add` line given to the owner
- [ ] QA: the read-only promise on the LSP store attacked (a store with a
- [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
@@ -312,6 +317,79 @@ Depends on M4 and M5 merged.
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)
- [ ] re-measure census task d (and a, which now needs `overrides: true`)
## Open questions for the owner (answer before the lane that needs it)
+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");
}
+3 -1
View File
@@ -8,6 +8,7 @@
//! `docs/features/mcp-transport/README.md`.
mod apply;
mod cache;
mod project;
mod render;
mod resources;
@@ -31,7 +32,8 @@ pub struct Options {
pub roots: Vec<PathBuf>,
/// `--filelist FILE`: overrides the configured `filelist`.
pub filelist: Option<PathBuf>,
/// `--index-cache DIR`: accepted and stored; read from M6 on.
/// `--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>,
/// `--verbose`: per-call timing lines on stderr.
pub verbose: bool,
+86 -19
View File
@@ -13,6 +13,8 @@ use std::time::{Duration, Instant};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
use crate::cache::{self, Records, Reuse};
pub use analysis::Analysis;
pub use files::Stamp;
@@ -54,6 +56,10 @@ pub struct Project {
/// 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
@@ -77,9 +83,21 @@ pub fn canonical_roots(roots: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
}
impl Project {
/// Discover the files under `roots` (already canonical) and index them.
/// Parses every file, so it runs on the stack-sized thread.
/// [`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 mut discovery = Discovery::new(true);
let (config, config_problem) = match roots.first().map(|r| discovery.for_dir(r)) {
@@ -88,38 +106,50 @@ impl Project {
None => (FileConfig::default(), None),
};
let walk = discover(&roots, filelist.as_deref());
let mut builder = IndexBuilder::new();
let mut files = BTreeMap::new();
let mut unreadable = Vec::new();
for path in &walk.files {
match read_source(path) {
Ok((text, stamp)) => {
builder.add_file(path.clone(), &text);
files.insert(path.clone(), stamp);
}
Err(problem) => {
unreadable.push((path.clone(), problem.to_string()));
}
}
}
let 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,
config,
config_problem,
files,
index: builder.finish(),
files: loaded.files,
index,
analyses: Analyses::default(),
walk,
walked_at: now,
updated_at: now,
build: now - started,
unreadable,
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
@@ -307,6 +337,43 @@ impl Project {
}
}
/// 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);
+88 -3
View File
@@ -5,15 +5,28 @@
//! about it, never once per line;
//! - lines and columns are 1-based, a position is `line:col`, a range is
//! `first-last`;
//! - lists are capped, the cap is said with `… and N more` and the caller can
//! page with `offset`;
//! - lists are capped and open with their total — `N units`, or
//! `N units (showing a–b)` when cut; a cut list also ends `… and N more`,
//! and the caller can page with `offset`;
//! - no prose and no markdown headings: a label is a bare word and a colon,
//! a table only where the columns are fixed.
use serde_json::{json, Value};
use vlog_semantic::SymbolKind;
/// How many entries a list answer holds unless the caller says otherwise.
pub const DEFAULT_LIMIT: usize = 200;
pub const DEFAULT_LIMIT: usize = 500;
/// What a list answer counts, singular then plural.
#[derive(Clone, Copy)]
pub struct Noun(pub &'static str, pub &'static str);
impl Noun {
/// `n` of this noun: `1 unit`, `3 units`.
fn count(self, n: usize) -> String {
format!("{n} {}", if n == 1 { self.0 } else { self.1 })
}
}
/// A declaration kind as one lower-case word — the keyword that declares it
/// where there is one.
@@ -106,6 +119,58 @@ pub fn page<T>(items: &[T], offset: usize, limit: usize) -> (&[T], usize) {
(&items[start..end], items.len() - end)
}
/// One page of a list: the entries shown, where they start, and how many
/// the whole list holds.
pub struct Page<'a, T> {
pub shown: &'a [T],
pub offset: usize,
pub total: usize,
}
impl<'a, T> Page<'a, T> {
/// The window `offset..offset + limit` of `items`.
pub fn of(items: &'a [T], offset: usize, limit: usize) -> Page<'a, T> {
let (shown, _) = page(items, offset, limit);
Page { shown, offset: offset.min(items.len()), total: items.len() }
}
/// How many entries follow the page.
pub fn rest(&self) -> usize {
self.total - self.offset - self.shown.len()
}
/// The line a list answer opens with: the total first, so an agent that
/// stops reading when the list looks done still knows it was cut.
pub fn header(&self, noun: Noun) -> String {
let total = noun.count(self.total);
if self.shown.len() == self.total {
return format!("{total}\n");
}
match self.span() {
Some((first, last)) if first == last => format!("{total} (showing {first})\n"),
Some((first, last)) => format!("{total} (showing {first}–{last})\n"),
None => format!("{total} (showing none: `offset` is past the end)\n"),
}
}
/// The shown entries' 1-based positions, `[first, last]`; `[0, 0]` for
/// an empty page.
pub fn shown_json(&self) -> Value {
let (first, last) = self.span().unwrap_or((0, 0));
json!([first, last])
}
fn span(&self) -> Option<(usize, usize)> {
let first = self.offset + 1;
(!self.shown.is_empty()).then(|| (first, self.offset + self.shown.len()))
}
}
/// The whole text of a list the `in` path glob emptied.
pub fn none_match(noun: Noun) -> String {
format!("0 {} (none match `in`)\n", noun.1)
}
/// The line that says a list was cut, or nothing when it was not.
pub fn more(out: &mut String, rest: usize) {
if rest > 0 {
@@ -224,6 +289,26 @@ mod tests {
assert_eq!(out, "… and 2 more\n");
}
#[test]
fn a_page_opens_with_its_total_and_the_window_it_shows() {
const UNITS: Noun = Noun("unit", "units");
let items: Vec<usize> = (0..77).collect();
let cut = Page::of(&items, 0, 50);
assert_eq!(cut.header(UNITS), "77 units (showing 1–50)\n");
assert_eq!((cut.rest(), cut.shown_json()), (27, json!([1, 50])));
let last = Page::of(&items, 50, 50);
assert_eq!(last.header(UNITS), "77 units (showing 51–77)\n");
assert_eq!(last.rest(), 0);
assert_eq!(Page::of(&items, 76, 5).header(UNITS), "77 units (showing 77)\n");
let whole = Page::of(&items[..1], 0, 50);
assert_eq!(whole.header(UNITS), "1 unit\n");
let past = Page::of(&items, 90, 5);
assert_eq!(past.header(UNITS), "77 units (showing none: `offset` is past the end)\n");
assert_eq!((past.rest(), past.shown_json()), (0, json!([0, 0])));
assert_eq!(Page::of(&items[..0], 0, 5).header(UNITS), "0 units\n");
assert_eq!(none_match(UNITS), "0 units (none match `in`)\n");
}
#[test]
fn a_file_is_named_once_per_group() {
let entries = vec![
+32 -4
View File
@@ -36,7 +36,7 @@ const NOT_INITIALIZED: i64 = -32002;
const RESOURCE_NOT_FOUND: i64 = -32002;
/// What the agent is told once, at `initialize`.
const INSTRUCTIONS: &str = "lucisv-mcp answers questions about the Verilog/SystemVerilog design under its roots, read from the files on disk (never from unsaved editor buffers). Prefer unit_interface for a module's parameters and ports, outline for what a file declares, and read_item for one module, function or always block over reading whole files; list_units and search_symbols find where things are declared. Paths in answers are relative to the root; lines and columns are 1-based.";
const INSTRUCTIONS: &str = "lucisv-mcp reads and edits the SystemVerilog design under its roots, from disk, never unsaved buffers. Read less: unit_interface gives a module's ports, outline a file's declarations, read_item one item; list_units, search_symbols, definition, references and hierarchy find the rest; `in` filters by path glob. Who instantiates module X: hierarchy direction up (overrides: true adds #(…)), not references. Every edit is verified, all-or-nothing, straight to disk, and names files for diagnostics; dry_run: true shows the diff first. One item: replace_item, insert_item, delete_item. Design-wide: rename, add_port, remove_port and other refactorings; format, fix_lint. rename, references and the port edits list the name's unresolved mentions (strings, comments, macro text) to check. A position: file + line (+ col or name). Paths are relative to a root; lines are 1-based, columns 1-based bytes.";
/// A JSON-RPC error object.
#[derive(Debug, Serialize)]
@@ -136,7 +136,10 @@ pub fn serve(options: Options) -> Result<(), String> {
let mut server = Server { options, version: None, project: None };
loop {
let reply = match transport.read_line().map_err(|e| format!("reading stdin: {e}"))? {
Line::Eof => return Ok(()),
Line::Eof => {
server.finish();
return Ok(());
}
Line::NotUtf8 => {
Some(response(&Value::Null, Err(fault(PARSE_ERROR, "the line is not UTF-8"))))
}
@@ -267,6 +270,20 @@ impl Server {
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 {
@@ -285,9 +302,20 @@ impl Server {
/// Discover and index the project, saying on stderr how long it took.
fn open_project(options: &Options) -> Project {
let project = Project::open(options.roots.clone(), options.filelist.clone());
let project = Project::open_cached(
options.roots.clone(),
options.filelist.clone(),
options.index_cache.clone(),
);
let (build, _) = project.timing();
eprintln!("lucisv-mcp: indexed {} files in {} ms", project.files().count(), build.as_millis());
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
}
+55 -32
View File
@@ -9,10 +9,13 @@ use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use vlog_parser::defines::{Define, DefineKind};
use super::read::{only_in, IN};
use super::source::{self, Texts};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render::{self, DEFAULT_LIMIT};
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
const DEFINES_NOUN: Noun = Noun("define", "defines");
/// A body longer than this many characters is cut, with `…`.
const BODY_CAP: usize = 200;
@@ -20,31 +23,23 @@ const BODY_CAP: usize = 200;
pub const DEFINES: Tool = Tool {
name: "defines",
title: "Macro definitions",
description: "The `define table: name, parameters, body (on one line) and file:line — of one `file`, of one macro `name` across the project (every definition; which one a use sees depends on include order, so none is picked), or of the whole project. Prefer it over grepping for `define.",
description:
"The `define table (name, parameters, body, file:line) of a `file`, a macro `name`, or all.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "Only this file's table (its `undef`s included), relative to a root or absolute inside one.",
},
Param {
name: "name",
ty: Ty::Str,
required: false,
description: "Only this macro, written with or without the backtick.",
},
Param { name: "file", ty: Ty::Str, required: false, description: "Only this file." },
Param { name: "name", ty: Ty::Str, required: false, description: "Only this macro." },
IN,
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most entries to return (default 200).",
description: "Default 500.",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Entries to skip, for paging past `… and N more` (default 0).",
description: "Entries to skip.",
},
],
rewalk: false,
@@ -60,29 +55,56 @@ struct Row {
fn defines(project: &mut Project, args: &Args) -> Result<Answer, String> {
let name = args.str("name").map(|name| name.trim_start_matches('`')).filter(|n| !n.is_empty());
let (rows, rest, total) = match args.str("file") {
let (rows, listing) = match args.str("file") {
Some(file) => in_file(project, file, name, args)?,
None => {
let mut all = indexed(project, name);
let select = |project: &Project| {
only_in(args, indexed(project, name), |(path, _)| project.relative(path))
};
let (mut all, mut emptied) = select(project);
if all.is_empty() && name.is_some() && project.ensure_walked_for_miss() {
all = indexed(project, name);
(all, emptied) = select(project);
}
let (shown, rest) =
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
(rows_of(project, shown), rest, all.len())
let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
(rows_of(project, page.shown), Listing::of(&page, emptied))
}
};
let entries: Vec<(String, String)> = rows
.iter()
.map(|row| (row.file.clone(), format!("{} {}", row.line, spelled(&row.define))))
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
if total == 0 {
text = "no defines\n".to_string();
let mut text = listing.header.clone();
text.push_str(&render::grouped(&entries));
render::more(&mut text, listing.rest);
if listing.total == 0 {
text =
if listing.emptied { render::none_match(DEFINES_NOUN) } else { "no defines\n".into() };
}
let listed: Vec<Value> = rows.iter().map(row_json).collect();
Ok(Answer { text, structured: json!({ "defines": listed, "total": total }) })
let structured = json!({ "defines": listed, "total": listing.total, "shown": listing.shown });
Ok(Answer { text, structured })
}
/// What an answer says about the page it shows, taken off a [`Page`] of
/// either form's list.
struct Listing {
header: String,
rest: usize,
total: usize,
shown: Value,
emptied: bool,
}
impl Listing {
fn of<T>(page: &Page<T>, emptied: bool) -> Listing {
Listing {
header: page.header(DEFINES_NOUN),
rest: page.rest(),
total: page.total,
shown: page.shown_json(),
emptied,
}
}
}
/// One file's table as it is on disk now, filtered by `name`.
@@ -91,7 +113,7 @@ fn in_file(
file: &str,
name: Option<&str>,
args: &Args,
) -> Result<(Vec<Row>, usize, usize), String> {
) -> Result<(Vec<Row>, Listing), String> {
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let shown_file = project.relative(&path);
@@ -101,9 +123,10 @@ fn in_file(
.iter()
.filter(|define| name.is_none_or(|name| define.name == name))
.collect();
let (shown, rest) =
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let rows = shown
let (all, emptied) = only_in(args, all, |_| shown_file.clone());
let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let rows = page
.shown
.iter()
.map(|define| Row {
file: shown_file.clone(),
@@ -111,7 +134,7 @@ fn in_file(
define: (*define).clone(),
})
.collect();
Ok((rows, rest, all.len()))
Ok((rows, Listing::of(&page, emptied)))
}
/// Every indexed definition (of `name`, when given), in file order.
+56 -32
View File
@@ -24,44 +24,47 @@ use vlog_linter::{
use vlog_parser::LineIndex;
use vlog_semantic::{FileId, PackageExports, SymbolKind, WorkspaceIndex};
use super::read::{in_glob, only_in, path_match, IN};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render::{self, DEFAULT_LIMIT};
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
pub const DIAGNOSTICS: Tool = Tool {
name: "diagnostics",
title: "Diagnostics",
description: "Parse errors and lint findings for one `file`, or for every indexed file, grouped by file as `line:col severity message [rule]` — what `lucisv check` over the whole tree reports (cross-file rules on), under the project's lucisv.toml [lint] settings and waivers. Filter with `rules` (like --select) and `severity`. The whole-project form lints every file and returns the first `limit` findings with the total.",
description:
"Parse errors and lint findings (`line:col severity message [rule]`) of `file` or all.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "One file, relative to a root or absolute inside one (default: every indexed file).",
description: "One file (default: all).",
},
Param {
name: "rules",
ty: Ty::Str,
required: false,
description: "Comma-separated rule names or severities to run instead of the configured set, like `--select`.",
description: "Rules or severities to run.",
},
Param {
name: "severity",
ty: Ty::Enum(&["error", "warning", "style"]),
required: false,
description: "Only findings of this severity (parse errors are `error`).",
description: "Only this severity.",
},
IN,
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most findings to return (default 200).",
description: "Default 500.",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Findings to skip, for paging past `… and N more` (default 0).",
description: "Findings to skip.",
},
],
rewalk: false,
@@ -96,33 +99,48 @@ fn diagnostics(project: &mut Project, args: &Args) -> Result<Answer, String> {
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
});
let mut runs = Runs::new(selected);
let mut findings = Vec::new();
match args.str("file") {
let (mut findings, no_file) = match args.str("file") {
Some(file) => {
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let own = project.index().file_id(&path);
let oracle = Mentions::of_file(project.index(), own);
findings = file_findings(project, &mut runs, &path, &analysis, &oracle)?;
(file_findings(project, &mut runs, &path, &analysis, &oracle)?, false)
}
None => {
let census = Census::of(project.index());
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
for path in paths {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let analysis = Analysis::of(text);
let own = project.index().file_id(&path);
let oracle = Mentions { index: project.index(), census: Some(&census), own };
findings.extend(file_findings(project, &mut runs, &path, &analysis, &oracle)?);
}
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
}
}
None => project_findings(project, &mut runs, in_glob(args))?,
};
if let Some(severity) = args.str("severity") {
findings.retain(|finding| finding.severity == severity);
}
Ok(render_findings(&findings, args))
let (findings, emptied) = only_in(args, findings, |finding| finding.file.clone());
Ok(render_findings(&findings, no_file || emptied, args))
}
/// Every indexed file's findings — only the files the `in` glob keeps, when
/// one is given — and whether the glob kept no file at all.
fn project_findings(
project: &Project,
runs: &mut Runs,
glob: Option<&str>,
) -> Result<(Vec<Finding>, bool), String> {
let census = Census::of(project.index());
let all: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
let kept = |path: &PathBuf| glob.is_none_or(|glob| path_match(glob, &project.relative(path)));
let paths: Vec<PathBuf> = all.iter().filter(|path| kept(path)).cloned().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: a filtered run
// does not say so.
if glob.is_none() {
findings.extend(runs.unused_waivers(project));
}
Ok((findings, paths.is_empty() && !all.is_empty()))
}
/// The runs met so far in one call, one per governing config file — shared
@@ -281,10 +299,13 @@ fn lint_finding(file: &str, lines: &LineIndex, violation: &Violation) -> Finding
}
}
const FINDINGS: Noun = Noun("finding", "findings");
/// Findings grouped by file, paged; the JSON is the CLI's array shape.
fn render_findings(findings: &[Finding], args: &Args) -> Answer {
let (shown, rest) =
render::page(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
/// `emptied` when the `in` glob removed everything there was.
fn render_findings(findings: &[Finding], emptied: bool, args: &Args) -> Answer {
let page = Page::of(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let shown = page.shown;
let entries: Vec<(String, String)> = shown
.iter()
.map(|f| {
@@ -293,10 +314,11 @@ fn render_findings(findings: &[Finding], args: &Args) -> Answer {
(f.file.clone(), line)
})
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
let mut text = page.header(FINDINGS);
text.push_str(&render::grouped(&entries));
render::more(&mut text, page.rest());
if findings.is_empty() {
text = "no findings\n".to_string();
text = if emptied { render::none_match(FINDINGS) } else { "no findings\n".to_string() };
}
let listed: Vec<Value> = shown
.iter()
@@ -310,7 +332,9 @@ fn render_findings(findings: &[Finding], args: &Args) -> Answer {
})
})
.collect();
Answer { text, structured: json!({ "diagnostics": listed, "total": findings.len() }) }
let total = findings.len();
let structured = json!({ "diagnostics": listed, "total": total, "shown": page.shown_json() });
Answer { text, structured }
}
/// How many files write each word, and the first of them — the whole-project
+171 -51
View File
@@ -15,8 +15,10 @@
use std::path::{Path, PathBuf};
use vlog_refactor::RefactorEdit;
use vlog_parser::span::TextRange;
use vlog_refactor::{RefactorEdit, TextEdit};
use super::mentions::{self, Focus};
use super::select::{target, Target};
use super::source::WholeSet;
use super::{nav, Answer, Args, Param, Tool, Ty};
@@ -24,37 +26,16 @@ use crate::apply::{self, Plan};
use crate::project::{Analysis, Project};
/// `dry_run`, which every edit tool takes.
pub(super) const DRY_RUN: Param = Param {
name: "dry_run",
ty: Ty::Bool,
required: false,
description: "Return the unified diff and write nothing (default false).",
};
pub(super) const DRY_RUN: Param =
Param { name: "dry_run", ty: Ty::Bool, required: false, description: "Diff only." };
const FILE: Param = Param {
name: "file",
ty: Ty::Str,
required: true,
description: "The file holding the position, relative to a root or absolute inside one.",
};
const LINE: Param = Param {
name: "line",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based line in `file`; alone it means the line's first non-blank character.",
};
const COL: Param = Param {
name: "col",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based column in bytes on `line`.",
};
const NAME: Param = Param {
name: "name",
ty: Ty::Str,
required: false,
description: "The name written at the position: with `line`, its occurrence on that line; without, its occurrence in `file`.",
};
const FILE: Param = Param { name: "file", ty: Ty::Str, required: true, description: "The file." };
const LINE: Param =
Param { name: "line", ty: Ty::Int { min: 1 }, required: false, description: "Line." };
const COL: Param =
Param { name: "col", ty: Ty::Int { min: 1 }, required: false, description: "Byte column." };
const NAME: Param =
Param { name: "name", ty: Ty::Str, required: false, description: "The name on `line`." };
/// The position arguments of the six cursor refactorings, then `dry_run`.
const AT: &[Param] = &[FILE, LINE, COL, NAME, DRY_RUN];
@@ -69,7 +50,7 @@ type Stake = fn(&Analysis, u32) -> Vec<String>;
pub const EXPAND_WILDCARD: Tool = Tool {
name: "expand_wildcard",
title: "Expand .* connections",
description: "Replace one instantiation's `.*` with the named connections it binds, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a `bind` instance, a positional list, and a port list whose binding depends on `ifdef`s, with the reason. `dry_run` returns the diff.",
description: "Replace one instance's `.*` with the named connections it binds.",
params: AT,
rewalk: true,
handler: expand_wildcard,
@@ -78,7 +59,7 @@ pub const EXPAND_WILDCARD: Tool = Tool {
pub const CONVERT_PORTS: Tool = Tool {
name: "convert_ports",
title: "Convert ports to ANSI",
description: "Rewrite a module's non-ANSI header (`module m(a, b); input a; …`) as an ANSI port list, verified before anything is written. Point at the module: `file`+`line` (+`col`, or the module `name`). Refuses a header it cannot convert exactly, with the reason. `dry_run` returns the diff.",
description: "Rewrite a module's non-ANSI header as an ANSI port list.",
params: AT,
rewalk: true,
handler: convert_ports,
@@ -87,7 +68,7 @@ pub const CONVERT_PORTS: Tool = Tool {
pub const ORGANIZE_IMPORTS: Tool = Tool {
name: "organize_imports",
title: "Organize imports",
description: "Remove the unused `import` items of the scope at a position and sort the rest, verified before anything is written. Point into the scope with `file`+`line`. Refuses where it cannot judge (a macro or `include` in the scope, an unknown package), with the reason. `dry_run` returns the diff.",
description: "Remove unused `import`s in the scope at a position; sort the rest.",
params: AT,
rewalk: true,
handler: organize_imports,
@@ -95,8 +76,8 @@ pub const ORGANIZE_IMPORTS: Tool = Tool {
pub const INLINE_MODULE: Tool = Tool {
name: "inline_module",
title: "Inline a module instance",
description: "Replace one instantiation with the body of the module it instantiates, its connections substituted, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses what it cannot substitute exactly, with the reason. `dry_run` returns the diff.",
title: "Inline an instance",
description: "Replace one instance with its module's body, connections substituted.",
params: AT,
rewalk: true,
handler: inline_module,
@@ -105,7 +86,7 @@ pub const INLINE_MODULE: Tool = Tool {
pub const PROPAGATE_PORTS: Tool = Tool {
name: "propagate_ports",
title: "Connect missing ports",
description: "Add a named connection for every port one instantiation leaves unconnected, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a positional or `.*` list, and an instance that already connects every port. `dry_run` returns the diff.",
description: "Connect by name every port one instance leaves unconnected.",
params: AT,
rewalk: true,
handler: propagate_ports,
@@ -114,7 +95,8 @@ pub const PROPAGATE_PORTS: Tool = Tool {
pub const REMOVE_PORT: Tool = Tool {
name: "remove_port",
title: "Remove a port",
description: "Delete one module port and its connection from every instantiation in the project, verified before anything is written. Point at the port: `file`+`line` (+`col`, or the port `name`). Refuses a port the body still uses, a positional instantiation, and a deletion that would drop a comment. `dry_run` returns the diff.",
description:
"Delete a port and its connection in every instantiation; refused while the body uses it.",
params: AT,
rewalk: true,
handler: remove_port,
@@ -122,24 +104,24 @@ pub const REMOVE_PORT: Tool = Tool {
pub const RENAME: Tool = Tool {
name: "rename",
title: "Rename a symbol",
description: "Rename one declaration and every reference to it across the project, verified before anything is written. Select as for `definition`: `file`+`line`+`col`, `file`+`line`+`name`, `file`+`name`, or `name` (+`unit`). Refuses an invalid or clashing name and a use it cannot account for; a name already `new_name` is `unchanged`. A `.*` or `.name` connection that bound the renamed name is written out explicitly (listed in `warnings`).",
title: "Rename",
description: "Rename a declaration and its uses; select as `definition`. Writes out `.*`/`.name` bindings, lists unresolved mentions.",
params: &[
Param { required: false, ..FILE },
Param {
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
description: "Line.",
..LINE
},
COL,
Param {
description: "The name to rename: alone, looked up across the project; with `file`, its occurrence there; with `file` and `line`, its occurrence on that line.",
description: "Name; alone, looked up project-wide.",
..NAME
},
Param {
name: "unit",
ty: Ty::Str,
required: false,
description: "With a bare `name`: the module, interface, package or class declaring it.",
description: "Unit declaring a bare `name`.",
},
Param {
name: "new_name",
@@ -154,7 +136,7 @@ pub const RENAME: Tool = Tool {
};
fn expand_wildcard(project: &mut Project, args: &Args) -> Result<Answer, String> {
at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated)
with_check(at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated), args)
}
fn convert_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
@@ -167,7 +149,7 @@ fn organize_imports(project: &mut Project, args: &Args) -> Result<Answer, String
}
fn inline_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
at_cursor(project, args, vlog_refactor::inline_module, instantiated)
with_check(at_cursor(project, args, vlog_refactor::inline_module, instantiated), args)
}
fn propagate_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
@@ -175,12 +157,25 @@ fn propagate_ports(project: &mut Project, args: &Args) -> Result<Answer, String>
}
fn remove_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
let port_and_module = |analysis: &Analysis, offset: u32| {
let mut names = name_at(analysis, offset);
names.extend(instantiated(analysis, offset));
names
with_check(remove_port_at(project, args), args)
}
fn remove_port_at(project: &mut Project, args: &Args) -> Result<Answer, String> {
let (path, offset) = cursor(project, args)?;
let analysis = project.analysis(&path)?;
let port = name_at(&analysis, offset);
let mut names = port.clone();
names.extend(instantiated(&analysis, offset));
let unit = enclosing(&analysis, offset);
let set = whole_set(project, Some(&path), &names)?;
let edit = vlog_refactor::remove_port(&set.files, &path, offset)?;
let Some(port) = port.first() else { return finish(project, edit, &set, args) };
let told = Told {
name: port,
lead: format!("the removed port `{port}` is still spelled"),
home: &path,
};
at_cursor(project, args, vlog_refactor::remove_port, port_and_module)
finish_telling(project, edit, &set, args, told, unit.first().map(String::as_str))
}
/// The declared name at a position.
@@ -266,7 +261,94 @@ pub(super) fn finish(
apply::run(project, plan, args.flag("dry_run", false))
}
/// The name an edit changes, for the unresolved-mentions warning: the name,
/// how the warning begins, and the file declaring it.
pub(super) struct Told<'a> {
pub name: &'a str,
pub lead: String,
pub home: &'a Path,
}
/// [`finish`], and the unresolved mentions of `told.name` the edit left
/// alone named under `warnings:` (and as `unresolved_mentions`) — found in
/// the texts as the edit writes them, so each `file:line` is right after
/// the write (QA finding 4).
pub(super) fn finish_telling(
project: &Project,
edit: RefactorEdit,
set: &WholeSet,
args: &Args,
told: Told,
unit: Option<&str>,
) -> Result<Answer, String> {
let accounted: Vec<(PathBuf, Vec<TextRange>)> =
edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect();
let mut plan = Plan::from_refactor(edit, &set.files)?;
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()))
});
let focus = Focus { name: told.name, home: told.home, unit, accounted: &accounted };
let mentions = mentions::find(project, written, &focus);
plan.warnings.extend(set.warning(project));
if !mentions.is_empty() {
plan.warnings.push(mentions.warning(&told.lead));
}
let mut answer = apply::run(project, plan, args.flag("dry_run", false))?;
answer.structured["unresolved_mentions"] = mentions.json();
Ok(answer)
}
/// How many changed files the check line names; the rest are counted.
const CHECK_CAP: usize = 5;
/// An edit's answer, ending with the line that names the files to run
/// `diagnostics` on — the agents ran it anyway; saying which saves a
/// decision (feedback round 2). Nothing is added when nothing changed.
pub(super) fn with_check(answer: Result<Answer, String>, args: &Args) -> Result<Answer, String> {
let mut answer = answer?;
let mut files: Vec<&str> = ["changed", "created"]
.iter()
.filter_map(|key| answer.structured[*key].as_array())
.flatten()
.filter_map(|entry| entry["file"].as_str())
.collect();
if files.is_empty() {
return Ok(answer);
}
files.sort_unstable();
let when = if args.flag("dry_run", false) { "check after writing" } else { "check" };
let mut line =
format!("{when}: diagnostics on {}", files[..files.len().min(CHECK_CAP)].join(", "));
if files.len() > CHECK_CAP {
line.push_str(&format!(" and {} more", files.len() - CHECK_CAP));
}
answer.text.push_str(&line);
answer.text.push('\n');
Ok(answer)
}
/// 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
}
fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
with_check(rename_at(project, args), args)
}
fn rename_at(project: &mut Project, args: &Args) -> Result<Answer, String> {
let new_name = args.str("new_name").unwrap_or_default();
let (path, offset) = match target(project, args)? {
Target::At { path, offset, .. } => (path, offset),
@@ -279,5 +361,43 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
}
let set = whole_set(project, Some(&path), &names)?;
let edit = vlog_refactor::rename(&set.files, &path, offset, new_name)?;
finish(project, edit, &set, args)
let Some(old) = names.first() else { return finish(project, edit, &set, args) };
let unit = enclosing(&*project.analysis(&path)?, offset);
let told =
Told { name: old, lead: format!("the old name `{old}` is still spelled"), home: &path };
finish_telling(project, edit, &set, args, told, unit.first().map(String::as_str))
}
#[cfg(test)]
mod tests {
use serde_json::{json, Value};
use super::super::Args;
use super::{with_check, Answer};
fn answer(changed: &[&str], created: &[&str]) -> Result<Answer, String> {
let entries = |files: &[&str]| -> Vec<Value> {
files.iter().map(|file| json!({ "file": file })).collect()
};
let structured = json!({ "changed": entries(changed), "created": entries(created) });
Ok(Answer { text: "files: …\n".into(), structured })
}
fn args(dry_run: bool) -> Args {
Args(json!({ "dry_run": dry_run }).as_object().cloned().unwrap_or_default())
}
#[test]
fn the_check_line_names_five_files_in_path_order_and_counts_the_rest() {
let changed = ["f.sv", "b.sv", "e.sv", "a.sv", "d.sv", "g.sv"];
let said = with_check(answer(&changed, &["c.sv"]), &args(false)).unwrap();
assert!(said
.text
.ends_with("\ncheck: diagnostics on a.sv, b.sv, c.sv, d.sv, e.sv and 2 more\n"));
let dry = with_check(answer(&["a.sv"], &[]), &args(true)).unwrap();
assert!(dry.text.ends_with("\ncheck after writing: diagnostics on a.sv\n"));
let nothing = with_check(answer(&[], &[]), &args(false)).unwrap();
assert_eq!(nothing.text, "files: …\n");
assert!(with_check(Err("no".into()), &args(false)).is_err());
}
}
+7 -16
View File
@@ -28,23 +28,14 @@ use crate::project::{Analysis, Project};
/// CLI's reason: two overlapping fixes land in successive rounds.
const MAX_FIX_ROUNDS: usize = 10;
const FILE: Param = Param {
name: "file",
ty: Ty::Str,
required: false,
description: "One file, relative to a root or absolute inside one.",
};
const FILES: Param = Param {
name: "files",
ty: Ty::Str,
required: false,
description: "Several files, comma-separated, instead of `file`.",
};
const FILE: Param = Param { name: "file", ty: Ty::Str, required: false, description: "The file." };
const FILES: Param =
Param { name: "files", ty: Ty::Str, required: false, description: "Comma-separated files." };
pub const FORMAT: Tool = Tool {
name: "format",
title: "Format files",
description: "Format `file` (or the comma-separated `files`) as `lucisv format` does, under each file's lucisv.toml; `lines` (`12-40,55`, one file only) formats just the constructs meeting those lines. The formatter verifies its own output: a file it will not format safely refuses the whole call, naming it. An already formatted file is `unchanged`. `dry_run` returns the diff.",
description: "Format `file`/`files` as `lucisv format`; `lines` limits it.",
params: &[
FILE,
FILES,
@@ -52,7 +43,7 @@ pub const FORMAT: Tool = Tool {
name: "lines",
ty: Ty::Str,
required: false,
description: "1-based line ranges such as `12-40,55`; only with a single file.",
description: "Line ranges such as `12-40,55` (one file only).",
},
DRY_RUN,
],
@@ -63,7 +54,7 @@ pub const FORMAT: Tool = Tool {
pub const FIX_LINT: Tool = Tool {
name: "fix_lint",
title: "Apply safe lint fixes",
description: "Apply the safe automatic fixes of the lint findings in `file` (or the comma-separated `files`), as `lucisv check --fix` does: the project's [lint] config and waivers, never inside a `// lucisv: off` fence, never an unsafe fix. Reports which rules were fixed and how many findings remain (`diagnostics` lists them). `rules` narrows the run like --select. `dry_run` returns the diff.",
description: "Apply the safe lint fixes to `file`/`files`; says what remains.",
params: &[
FILE,
FILES,
@@ -71,7 +62,7 @@ pub const FIX_LINT: Tool = Tool {
name: "rules",
ty: Ty::Str,
required: false,
description: "Comma-separated rule names or severities to fix instead of the configured set.",
description: "Rules or severities to fix.",
},
DRY_RUN,
],
+93 -30
View File
@@ -8,6 +8,9 @@
//! 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.
//!
//! Each instance's `#(...)` overrides are always in the JSON; the text line
//! shows them only on `overrides: true`, since a census rarely reads them.
use std::collections::HashMap;
use std::path::Path;
@@ -18,15 +21,17 @@ use vlog_semantic::{
Def, FileId, InstanceOccurrence, InstantiationEdge, SymbolKind, WorkspaceIndex,
};
use super::read::{in_glob, path_match};
use super::source::{self, Texts};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render::{self, DEFAULT_LIMIT};
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
/// The deepest a walk may go, whatever `depth` asks.
const MAX_DEPTH: usize = 20;
/// The longest overrides text a line shows; the JSON carries all of it.
/// The longest overrides text a line shows (on `overrides: true`); the JSON
/// carries all of it.
const OVERRIDES_CAP: usize = 200;
/// The most nodes one walk collects before it stops.
@@ -35,37 +40,49 @@ const NODE_CAP: usize = 50_000;
pub const HIERARCHY: Tool = Tool {
name: "hierarchy",
title: "Instance hierarchy",
description: "The instance tree as indented `instance : module #(overrides)` lines, down from `root` (default: every top-level module), or with `direction: up` every `parent.instance` that instantiates `root`, with file:line. Textual, not elaborated: `generate` and `ifdef` branches all appear. Prefer it over reading files to find who instantiates what.",
description: "Who instantiates a module (`up`, with file:line) or what it instantiates (`down`, default). Textual.",
params: &[
Param {
name: "root",
ty: Ty::Str,
required: false,
description: "The module to start from; required for `up` (default for `down`: every module nothing instantiates).",
description: "The module; required for `up`.",
},
Param {
name: "direction",
ty: Ty::Enum(&["down", "up"]),
required: false,
description: "`down` lists what `root` instantiates (default); `up` lists what instantiates it.",
description: "Default `down`.",
},
Param {
name: "depth",
ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 },
required: false,
description: "Levels to walk (default 3, at most 20).",
description: "Default 3.",
},
Param {
name: "in",
ty: Ty::Str,
required: false,
description: "Path glob on the instantiating file (`up`) or the module's (`down`), e.g. `ip/**/rtl/*.sv`.",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most lines to return (default 200).",
description: "Default 500.",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Lines to skip, for paging past `… and N more` (default 0).",
description: "Lines to skip.",
},
Param {
name: "overrides",
ty: Ty::Bool,
required: false,
description: "Add each `#(…)` to the text lines.",
},
],
rewalk: false,
@@ -114,10 +131,12 @@ struct Node {
note: Option<String>,
}
/// A walk in progress: the edges by owner, what it collected, and the path
/// of modules above the current node.
/// A walk in progress: the edges by owner, the `in` glob, what it
/// collected, and the path of modules above the current node.
struct Walk<'a> {
project: &'a Project,
index: &'a WorkspaceIndex,
glob: Option<&'a str>,
below: HashMap<(FileId, u32), Vec<Child>>,
max_depth: usize,
nodes: Vec<Node>,
@@ -140,17 +159,27 @@ fn hierarchy(project: &mut Project, args: &Args) -> Result<Answer, String> {
}
let max_depth = args.count("depth", 3);
let index = project.index();
let mut walk = Walk::new(index, max_depth, !up);
let mut walk = Walk::new(project, in_glob(args), max_depth, !up);
let roots: Vec<(String, Def)> = match root {
Some(root) => {
modules_named(index, root).into_iter().map(|d| (root.to_string(), d)).collect()
}
None => top_modules(index),
None => top_modules(index).into_iter().filter(|(_, def)| walk.keeps(def.file)).collect(),
};
let single_up = up && roots.len() == 1;
for (name, def) in roots {
walk.root(name, def, up);
}
Ok(render(project, walk.nodes, up, args))
let emptied = walk.glob.is_some()
&& match root {
Some(root) if single_up => {
walk.nodes.len() == 1 && !index.instantiations_of(root).is_empty()
}
None => walk.nodes.is_empty() && !top_modules(index).is_empty(),
Some(_) => false,
};
let shape = Shape { up, single_up, emptied };
Ok(render(project, walk.nodes, shape, args))
}
/// Every instantiable declaration of `name`.
@@ -169,8 +198,10 @@ fn top_modules(index: &WorkspaceIndex) -> Vec<(String, Def)> {
}
impl<'a> Walk<'a> {
/// A walk over `index`; the owner table is built only for `down`.
fn new(index: &'a WorkspaceIndex, max_depth: usize, down: bool) -> Walk<'a> {
/// A walk over `project`'s index; the owner table is built only for
/// `down`.
fn new(project: &'a Project, glob: Option<&'a str>, max_depth: usize, down: bool) -> Walk<'a> {
let index = project.index();
let mut below: HashMap<(FileId, u32), Vec<Child>> = HashMap::new();
for (module, edges) in index.instantiations().filter(|_| down) {
for edge in edges {
@@ -183,7 +214,14 @@ impl<'a> Walk<'a> {
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() }
Walk { project, index, glob, below, max_depth, nodes: Vec::new(), path: Vec::new() }
}
/// Whether the `in` glob (if any) keeps an entry in `file`.
fn keeps(&self, file: FileId) -> bool {
let Some(glob) = self.glob else { return true };
let path = self.index.path(file);
path.is_some_and(|path| path_match(glob, &self.project.relative(path)))
}
fn full(&self) -> bool {
@@ -220,6 +258,10 @@ impl<'a> Walk<'a> {
return;
}
let declared = modules_named(self.index, &child.module);
// `in` asks for the module's own file; one not indexed has none.
if self.glob.is_some() && !declared.iter().any(|def| self.keeps(def.file)) {
continue;
}
let recursive = self.path.contains(&child.module);
let note = match declared.len() {
_ if recursive => Some("recursive".to_string()),
@@ -248,6 +290,9 @@ impl<'a> Walk<'a> {
fn up(&mut self, module: &str, depth: usize) {
let index = self.index;
for edge in index.instantiations_of(module) {
if !self.keeps(edge.file) {
continue;
}
for occurrence in &edge.instances {
if self.full() {
return;
@@ -273,31 +318,47 @@ impl<'a> Walk<'a> {
}
}
const NODES: Noun = Noun("node", "nodes");
const INSTANTIATIONS: Noun = Noun("instantiation", "instantiations");
/// How an answer is counted: `up` from one root counts the instantiations
/// under its root line, which every page repeats; any other walk counts
/// every line. `emptied` when the `in` glob removed every entry there was.
struct Shape {
up: bool,
single_up: bool,
emptied: bool,
}
/// The collected nodes, paged, as indented lines and as a flat JSON list.
fn render(project: &Project, nodes: Vec<Node>, up: bool, args: &Args) -> Answer {
let (shown, rest) =
render::page(&nodes, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
fn render(project: &Project, nodes: Vec<Node>, shape: Shape, args: &Args) -> Answer {
let (lead, counted, noun) = match nodes.split_first() {
Some((root, rest)) if shape.single_up => (Some(root), rest, INSTANTIATIONS),
_ => (None, nodes.as_slice(), NODES),
};
let page = Page::of(counted, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let mut text = if shape.emptied { render::none_match(noun) } else { page.header(noun) };
let show_overrides = args.flag("overrides", false);
let mut texts = Texts::default();
let mut text = String::new();
let mut listed: Vec<Value> = Vec::new();
for node in shown {
for node in lead.into_iter().chain(page.shown) {
let line = Line::of(project, &mut texts, node);
text.push_str(&" ".repeat(node.depth));
text.push_str(&line.text(node, up));
text.push_str(&line.text(node, shape.up, show_overrides));
text.push('\n');
listed.push(line.json(node, up));
listed.push(line.json(node, shape.up));
}
render::more(&mut text, rest);
render::more(&mut text, page.rest());
if nodes.len() >= NODE_CAP {
text.push_str(&format!("tree cut at {NODE_CAP} nodes; lower `depth` or pick a `root`\n"));
}
if nodes.is_empty() {
if nodes.is_empty() && !shape.emptied {
text = "no modules\n".to_string();
}
let direction = if up { "up" } else { "down" };
let direction = if shape.up { "up" } else { "down" };
let structured = json!({
"direction": direction, "nodes": listed, "total": nodes.len(),
"cut": nodes.len() >= NODE_CAP,
"direction": direction, "nodes": listed, "total": counted.len(),
"shown": page.shown_json(), "cut": nodes.len() >= NODE_CAP,
});
Answer { text, structured }
}
@@ -328,13 +389,15 @@ impl Line {
Line { file, line, overrides: overrides(text, child) }
}
fn text(&self, node: &Node, up: bool) -> String {
/// The line as the text answer shows it; the overrides only when
/// `show_overrides`.
fn text(&self, node: &Node, up: bool, show_overrides: bool) -> String {
let mut out = match (&node.instance, up) {
(None, _) => format!("{} {}:{}", node.module, self.file, self.line),
(Some(child), false) => format!("{} : {}", child.instance, child.module),
(Some(child), true) => format!("{}.{}", node.module, child.instance),
};
if let Some(overrides) = &self.overrides {
if let Some(overrides) = self.overrides.as_ref().filter(|_| show_overrides) {
out.push(' ');
out.push_str(&source::capped(overrides, OVERRIDES_CAP));
}
+34 -20
View File
@@ -1,7 +1,7 @@
//! `unit_interface`: what a unit offers the code that uses it — a module's
//! or interface's parameters, ports and instantiation template (plus an
//! interface's modports), a package's or class's exported members — without
//! the agent reading the file that declares it.
//! or interface's parameters and ports (plus an interface's modports, and
//! the instantiation template on request), a package's or class's exported
//! members — without the agent reading the file that declares it.
use std::path::PathBuf;
@@ -19,19 +19,25 @@ use crate::render;
pub const UNIT_INTERFACE: Tool = Tool {
name: "unit_interface",
title: "Unit interface",
description: "The interface of one unit by name: a module's or interface's parameters with defaults, ports in declaration order (direction, type, range) and a ready-to-paste instantiation; an interface's modports; a package's or class's members. Prefer it over reading the declaring file. Refuses a name declared in several files unless `file` picks one.",
description: "A unit's parameters, ports (direction, type, range), modports or members; `template: true` adds an instantiation.",
params: &[
Param {
name: "name",
ty: Ty::Str,
required: true,
description: "The unit's name; a class inside a package may be written `pkg::cls`.",
description: "The unit (`pkg::cls` for a class).",
},
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "The declaring file, when the name is declared more than once.",
description: "Its file, if declared twice.",
},
Param {
name: "template",
ty: Ty::Bool,
required: false,
description: "Add the instantiation.",
},
],
rewalk: false,
@@ -58,7 +64,8 @@ fn unit_interface(project: &mut Project, args: &Args) -> Result<Answer, String>
let short = name.rsplit("::").next().unwrap_or(name);
match found.def.kind {
SymbolKind::Module | SymbolKind::Interface => {
instantiable(&analysis, &found, short, head, &file).map(|mut answer| {
let template = args.flag("template", false);
instantiable(&analysis, &found, short, head, &file, template).map(|mut answer| {
answer.structured["kind"] = Value::from(kind);
answer
})
@@ -117,13 +124,15 @@ fn pick(
}
}
/// A module's or interface's parameters, ports, modports and template.
/// A module's or interface's parameters, ports and modports, and its
/// template when `with_template` asks for it.
fn instantiable(
analysis: &Analysis,
found: &Found,
name: &str,
head: String,
file: &str,
with_template: bool,
) -> Result<Answer, String> {
let plan = instantiation_plan(name, &analysis.text, None)?;
let scope = unit_symbol(&analysis.semantics, found, name).and_then(|s| s.child_scope);
@@ -132,9 +141,9 @@ fn instantiable(
(SymbolKind::Interface, Some(scope)) => modports_of(analysis, scope),
_ => Vec::new(),
};
let template = plan.render(&Layout::default());
let text = interface_text(head, &plan, &ports, &modports, &template);
let structured = json!({
let template = with_template.then(|| plan.render(&Layout::default()));
let text = interface_text(head, &plan, &ports, &modports, template.as_deref());
let mut structured = json!({
"name": name,
"kind": render::kind(found.def.kind),
"file": file,
@@ -142,9 +151,11 @@ fn instantiable(
"parameters": plan.params.iter().map(|p| json!({ "name": p.name, "default": p.default })).collect::<Vec<_>>(),
"ports": ports.iter().map(PortRow::to_json).collect::<Vec<_>>(),
"modports": modports,
"template": template,
"warnings": plan.warnings,
});
if let Some(template) = template {
structured["template"] = Value::from(template);
}
Ok(Answer { text, structured })
}
@@ -159,22 +170,23 @@ fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec<String> {
.collect()
}
/// The text answer: the head line, then each non-empty section.
/// The text answer: the head line, then each non-empty section; the
/// template last, when asked for.
fn interface_text(
mut text: String,
plan: &InstantiationPlan,
ports: &[PortRow],
modports: &[String],
template: &str,
template: Option<&str>,
) -> String {
if !plan.params.is_empty() {
text.push_str("parameters:\n");
text.push_str(&format!("parameters ({}):\n", plan.params.len()));
let rows: Vec<Vec<String>> =
plan.params.iter().map(|p| vec![p.name.clone(), default_cell(&p.default)]).collect();
text.push_str(&render::table(&rows));
}
if !ports.is_empty() {
text.push_str("ports:\n");
text.push_str(&format!("ports ({}):\n", ports.len()));
let rows: Vec<Vec<String>> = ports
.iter()
.map(|p| vec![p.dir.clone(), p.written_type(), p.name_with_unpacked()])
@@ -190,10 +202,12 @@ fn interface_text(
for warning in &plan.warnings {
text.push_str(&format!("warning: {warning}\n"));
}
text.push_str("template:\n");
text.push_str(template);
if !template.ends_with('\n') {
text.push('\n');
if let Some(template) = template {
text.push_str("template:\n");
text.push_str(template);
if !template.ends_with('\n') {
text.push('\n');
}
}
text
}
+455
View File
@@ -0,0 +1,455 @@
//! The structural edits — `replace_item`, `insert_item`, `delete_item` — the
//! general token saver: an agent sends one item's text, never the file.
//!
//! Each tool finds its place with `read_item`'s own slicer
//! ([`read_item::select`]), so the bytes it replaces are exactly the bytes
//! `read_item` showed; builds a [`Splice`]; hands it to [`verify::check`]
//! (the rules are there); and writes through `apply::run`, the one write
//! path (dry run, freshness, atomic write). Contract and rules:
//! `docs/features/mcp-structural-edits/README.md`.
mod lexical;
mod macros;
mod refs;
mod span;
mod star;
mod verify;
use std::path::PathBuf;
use std::rc::Rc;
use serde_json::json;
use vlog_formatter::fence;
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::span::TextRange;
use super::edit::DRY_RUN;
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};
const FILE: Param = Param { name: "file", ty: Ty::Str, required: true, description: "The file." };
const ITEM: Param =
Param { name: "item", ty: Ty::Str, required: true, description: "`read_item`'s selector." };
const TEXT: Param =
Param { name: "text", ty: Ty::Str, required: true, description: "The source text." };
pub const REPLACE_ITEM: Tool = Tool {
name: "replace_item",
title: "Replace one item",
description: "Replace one item with `text`: one item, same kind and names (unless `rename`; references untouched). Comments around `text` replace the item's own.",
params: &[
FILE,
ITEM,
TEXT,
Param {
name: "rename",
ty: Ty::Bool,
required: false,
description: "Allow other declared names.",
},
DRY_RUN,
],
rewalk: false,
handler: replace_item,
};
pub const INSERT_ITEM: Tool = Tool {
name: "insert_item",
title: "Insert items",
description: "Insert items `text` before or after item `anchor`, or at `end` (`end@NAME`) of the last unit (unit NAME).",
params: &[
FILE,
Param {
name: "anchor",
ty: Ty::Str,
required: true,
description: "An item selector, `end`, or `end@NAME`.",
},
Param {
name: "position",
ty: Ty::Enum(&["before", "after"]),
required: false,
description: "`before` or `after` (default).",
},
TEXT,
DRY_RUN,
],
rewalk: false,
handler: insert_item,
};
pub const DELETE_ITEM: Tool = Tool {
name: "delete_item",
title: "Delete one item",
description: "Delete one item and its leading comments; refused while its names are used (sites listed) or it holds a `define, unless `force`.",
params: &[
FILE,
ITEM,
Param {
name: "force",
ty: Ty::Bool,
required: false,
description: "Delete anyway.",
},
DRY_RUN,
],
rewalk: true,
handler: delete_item,
};
/// 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 (`add_port`/`remove_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) -> 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(args.str("text").unwrap_or(""), &analysis.text, false)?;
let dry_run = args.flag("dry_run", false);
let (start, end) = replace_region(&analysis.text, located.item, &text);
// The item as it already is: a no-op, not a refusal (even in a fence).
if text == analysis.slice(start, end) {
return apply::run(project, Plan::default(), dry_run);
}
if fenced(&analysis.text, start, end) {
return Err(format!("`{selector}` {FENCED}; nothing written."));
}
let class = verify::class_of(&located.item.kind);
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);
let warnings = name_rule(&was, &now, args.flag("rename", false))?;
let lines = outcome.analysis.line_span(new_span.start, new_span.end);
let note = format!("replaced {class}{}", named(&now));
finish(project, (path, &analysis, outcome.text), note, lines, warnings, dry_run)
}
/// The text declares the names the item did, unless `rename` allows others
/// — and then the answer warns that no reference followed.
fn name_rule(was: &[String], now: &[String], rename: bool) -> Result<Vec<String>, String> {
if was == now {
return Ok(Vec::new());
}
if !rename {
return Err(format!(
"the text declares {} where the item declared {}; pass `rename: true` to allow it (references are not updated; `rename` does that); nothing written.",
listed(now),
listed(was)
));
}
Ok(vec![format!(
"{} replaced by {}: references are NOT updated (the `rename` tool renames with references)",
listed(was),
listed(now)
)])
}
fn insert_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
let (path, file, analysis) = open(project, args)?;
let anchor = args.str("anchor").unwrap_or("").trim();
let before = args.str("position") == Some("before");
let text = normalise(args.str("text").unwrap_or(""), &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();
let note = format!("inserted {}{}", classes.join(", "), named(&names));
let dry_run = args.flag("dry_run", false);
finish(project, (path, &analysis, outcome.text), note, lines, Vec::new(), dry_run)
}
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 force = args.flag("force", false);
let place = refs::Place { item: located.item.span, removed, scope: located.siblings };
let mut warnings = refs::check(project, &path, &analysis, &place, force)?;
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 { force }).map_err(refused(&file))?;
warnings.extend(dropped_macros_warning(&outcome.dropped_macros));
let names = verify::owned_names(&analysis, located.item.span);
let lines = analysis.line_span(start, end);
let note =
format!("deleted {class}{} (old lines {})", named(&names), render::lines(lines.0, lines.1));
let dry_run = args.flag("dry_run", false);
let plan = plan(path, &analysis, outcome.text, note, warnings);
apply::run(project, plan, dry_run)
}
/// What a forced deletion says about the macro definitions it removed
/// (the M4 review's ruling on rule 6): nothing when it removed none.
fn dropped_macros_warning(names: &[String]) -> Option<String> {
(!names.is_empty()).then(|| {
format!(
"deleted macro definitions: {} — code after the item that used them will change meaning",
names.join(", ")
)
})
}
/// 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,
note: String,
warnings: Vec<String>,
) -> Plan {
let change = Change { path, before: analysis.text.clone(), after, created: false };
Plan { changes: vec![change], note: Some(note), warnings, ..Plan::default() }
}
/// Write (or diff) a replace or insert, its note carrying the new item's
/// lines and the hint; the lines are in `structuredContent.item` too.
fn finish(
project: &Project,
(path, analysis, after): (PathBuf, &Analysis, String),
note: String,
(first, last): (u32, u32),
warnings: Vec<String>,
dry_run: bool,
) -> Result<Answer, String> {
let lines = render::lines(first, last);
let note = format!(
"{note} (lines {lines})\nhint: run `format` with `lines: \"{lines}\"` to reflow; `diagnostics` to check"
);
let mut answer = apply::run(project, plan(path, analysis, after, note, warnings), dry_run)?;
answer.structured["item"] = json!({ "lines": [first, last] });
Ok(answer)
}
/// `` `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(", ")
}
/// ` `a`, `b`` after a kind word, or nothing.
fn named(names: &[String]) -> String {
if names.is_empty() {
String::new()
} else {
format!(" {}", listed(names))
}
}
/// `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 `delete_item`'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; `delete_item` 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 @@
//! `delete_item`'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");
}
}
+272
View File
@@ -0,0 +1,272 @@
//! `delete_item`'s reference rule: an item is not deleted while a name it
//! owns (`verify::owned`) is still used anywhere in the project, unless the
//! agent says `force`.
//!
//! 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,
force: bool,
) -> 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);
}
let mut warnings: Vec<String> = set.warning(project).into_iter().collect();
if census.total == 0 {
return Ok(warnings);
}
if !force {
return Err(format!(
"still referenced: {}; nothing written (`force: true` deletes anyway).",
census.render()
));
}
warnings.push(format!("deleted with references left: {}", census.render()));
Ok(warnings)
}
/// 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 — `force` is the way past.
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 `insert_item` and `delete_item` work
//! on, and the span `replace_item` 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; insert_item and delete_item 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 `replace_item` 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 @@
//! `delete_item`'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))
}
+605
View File
@@ -0,0 +1,605 @@
//! 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, and for a
//! forced deletion, which removes them and names them
//! ([`Outcome::dropped_macros`]);
//! 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. `diagnostics` 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 (`replace_item`).
One(&'static str),
/// One item or more (`insert_item`).
Some,
/// Nothing (`delete_item`); `force` lets rule 6 pass over the macro
/// definitions the deleted item held (they are named instead).
Nothing { force: bool },
}
/// 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)>,
/// The macro definitions a forced deletion removed, as the warning
/// names them (`W`, `X (undef)`); empty for every other edit.
pub dropped_macros: Vec<String>,
}
/// 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"));
}
let dropped_macros = match same_macros(old, &analysis, region, (&before, &after)) {
Ok(()) => Vec::new(),
Err(_) if matches!(expect, Expect::Nothing { force: true }) => {
dropped(old, region, &before)
}
Err(why) if matches!(expect, Expect::Nothing { .. }) => {
return Err(format!("{why}, or pass `force: true` to delete it anyway"))
}
Err(why) => return Err(why),
};
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, dropped_macros })
}
/// 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_item keeps an item's kind (delete_item, then insert_item, to change it)"
)),
(Expect::One(_), many) => Err(format!(
"the text holds {} items where one was; replace_item replaces one item with one (insert_item 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
/// `replace_item`, 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"
))
}
/// The macro definitions a deletion of the region removes, each name once,
/// in source order: `W` for a `` `define``, `X (undef)` for an `` `undef``.
fn dropped(old: &Analysis, region: Region, before: &Split) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
for (kind, name, _, _) in definitions(old, region.start, region.old_end, before) {
let shown = match kind {
DefineKind::Undef => format!("{name} (undef)"),
_ => name,
};
if !names.contains(&shown) {
names.push(shown);
}
}
names
}
/// 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());
}
}
+352
View File
@@ -0,0 +1,352 @@
//! 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 serde_json::{json, Value};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{tokenize, LineIndex};
use super::source::{capped, word_in};
use crate::project::Project;
/// The most mentions an answer lists; the rest are counted.
pub const CAP: usize = 50;
/// The longest line text a mention shows.
const LINE_CAP: usize = 160;
/// One unresolved spelling: where, what kind of text holds it, and the line.
pub struct Mention {
pub file: String,
pub line: u32,
pub kind: &'static str,
pub text: String,
}
/// 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>)],
}
impl Mentions {
/// Whether there is nothing to say.
pub fn is_empty(&self) -> bool {
self.total == 0
}
/// One indented line per mention, `file:line kind: text`, then the cap.
pub fn lines(&self, indent: &str) -> String {
let mut out = String::new();
for mention in &self.listed {
let (file, line, kind) = (&mention.file, mention.line, mention.kind);
out.push_str(&format!("{indent}{file}:{line} {kind}: {}\n", mention.text));
}
let rest = self.total - self.listed.len();
if rest > 0 {
out.push_str(&format!("{indent}… and {rest} more\n"));
}
out
}
/// The `unresolved_mentions` JSON: the listed ones.
pub fn json(&self) -> Value {
let listed: Vec<Value> = self
.listed
.iter()
.map(|m| json!({ "file": m.file, "line": m.line, "text": m.text, "kind": m.kind }))
.collect();
Value::from(listed)
}
/// The sentence an edit tool puts under `warnings:` — `lead` is how it
/// begins (`the old name `x` is still spelled`) — the list below it.
pub fn warning(&self, lead: &str) -> String {
let places = if self.total == 1 { "1 place" } else { "these places" };
let mut text = format!(
"{lead} as text at {places} lucisv does not resolve (strings, comments, macro text; {} in all); check whether these are references:\n",
self.total
);
text.push_str(self.lines(" ").trim_end());
text
}
}
/// 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;
for (at, kind) in spellings(text, focus.name) {
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 file = project.relative(path);
let mention = Mention { file, line, kind, text: capped(source, LINE_CAP) };
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);
}
}
+8 -1
View File
@@ -9,7 +9,10 @@ mod edit;
mod format;
mod hierarchy;
mod interface;
mod item;
mod mentions;
mod nav;
mod place;
mod read;
mod read_item;
mod refactor;
@@ -102,6 +105,9 @@ const TOOLS: &[(Tool, Effect)] = &[
(edit::REMOVE_PORT, Edit { idempotent: false }),
(refactor::ADD_PORT, Edit { idempotent: false }),
(refactor::EXTRACT_MODULE, Edit { idempotent: false }),
(item::REPLACE_ITEM, Edit { idempotent: true }),
(item::INSERT_ITEM, Edit { idempotent: false }),
(item::DELETE_ITEM, Edit { idempotent: true }),
(refactor::INSTANTIATE, Read),
];
@@ -129,8 +135,9 @@ fn describe(tool: &Tool, effect: Effect) -> Value {
"title": tool.title,
"description": tool.description,
"inputSchema": schema(tool.params),
// The display name is `title` above; `annotations.title` would
// repeat it in a catalogue every session reads.
"annotations": {
"title": tool.title,
"readOnlyHint": read_only,
"destructiveHint": false,
"idempotentHint": idempotent,
+77 -38
View File
@@ -15,51 +15,41 @@
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex};
use super::mentions::{self, Focus, Mentions};
use super::read::{in_glob, only_in, path_match, IN};
use super::select::{macro_name, target, Target};
use super::source::{self, checked_site, Site, Texts, WholeSet};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render::{self, DEFAULT_LIMIT};
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
/// The selector's arguments, shared by both tools.
const FILE: Param = Param {
name: "file",
ty: Ty::Str,
required: false,
description: "The file holding the position, relative to a root or absolute inside one.",
};
const LINE: Param = Param {
name: "line",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
};
const COL: Param = Param {
name: "col",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based column in bytes on `line`.",
};
const FILE: Param = Param { name: "file", ty: Ty::Str, required: false, description: "The file." };
const LINE: Param =
Param { name: "line", ty: Ty::Int { min: 1 }, required: false, description: "Line." };
const COL: Param =
Param { name: "col", ty: Ty::Int { min: 1 }, required: false, description: "Byte column." };
const NAME: Param = Param {
name: "name",
ty: Ty::Str,
required: false,
description: "The name: alone, looked up across the project (`` `NAME`` for a macro); with `file`, its first occurrence there; with `file` and `line`, its occurrence on that line.",
description: "Name; alone, looked up project-wide (`` `X`` is a macro).",
};
const UNIT: Param = Param {
name: "unit",
ty: Ty::Str,
required: false,
description: "With a bare `name`: the module, interface, package or class declaring it.",
description: "Unit declaring a bare `name`.",
};
pub const DEFINITION: Tool = Tool {
name: "definition",
title: "Go to definition",
description: "Where a name is declared: every declaration site as file:line:col, its kind and the declaration's own source line (a name declared in several places lists them all, never a guess). Select by position (`file`, `line`, `col`), by `file`+`line`+`name`, or by `name` (and `unit`) across the project; also answers a macro use and an `include` line. Prefer it over grepping for the declaration.",
title: "Definition",
description: "Where a name or macro is declared: file:line:col, kind, line. Select by position, `file`+`name`, or `name`.",
params: &[FILE, LINE, COL, NAME, UNIT],
rewalk: false,
handler: definition,
@@ -68,7 +58,7 @@ pub const DEFINITION: Tool = Tool {
pub const REFERENCES: Tool = Tool {
name: "references",
title: "Find references",
description: "Every use of one declaration across the project, grouped by file as line:col and the line's text — the same occurrences a rename would edit. Select as for `definition`; a bare `name` must name one declaration. Refuses a name lucisv cannot resolve to one declaration, with the reason.",
description: "Uses of one declaration, then its unresolved mentions (strings, comments, macro text). Select as `definition`. Module instances: `hierarchy` up.",
params: &[
FILE,
LINE,
@@ -79,19 +69,20 @@ pub const REFERENCES: Tool = Tool {
name: "include_declaration",
ty: Ty::Bool,
required: false,
description: "List the declaration itself too (default true).",
description: "Default true.",
},
IN,
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most hits to return (default 200).",
description: "Default 500.",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Hits to skip, for paging past `… and N more` (default 0).",
description: "Hits to skip.",
},
],
rewalk: true,
@@ -294,6 +285,7 @@ fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
let found = vlog_refactor::find_references(&set.files, &path, offset, include)
.map_err(engine_refusal)?;
let partial = set.warning(project);
let mentions = unresolved(project, &set, &analysis, (&path, offset), &found, args);
let mut texts = Texts::default();
for (held, text) in set.files {
texts.hold(held, text);
@@ -305,7 +297,13 @@ fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
Some(Site::at(project.relative(file), text, lines, *span, "use"))
})
.collect();
let mut answer = render_hits(&hits, args);
let (hits, emptied) = only_in(args, hits, |hit| hit.file.clone());
let mut answer = render_hits(&hits, emptied, args);
if !mentions.is_empty() {
answer.text.push_str(MENTIONS_LABEL);
answer.text.push_str(&mentions.lines(" "));
}
answer.structured["unresolved_mentions"] = mentions.json();
// A file the index skipped was not searched: the census is partial.
if let Some(partial) = partial {
answer.text.push_str(&format!("warning: {partial}\n"));
@@ -314,6 +312,41 @@ fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
Ok(answer)
}
/// The section `references` ends with when the name is also spelled where
/// no engine looks.
const MENTIONS_LABEL: &str =
"unresolved mentions (strings, comments, macro text — not resolved by lucisv):\n";
/// The declaration's unresolved mentions across the set, the engine's hits
/// accounted for — on the first page only; later pages repeat nothing.
fn unresolved(
project: &Project,
set: &WholeSet,
analysis: &Analysis,
(path, offset): (&Path, u32),
found: &[(PathBuf, TextRange)],
args: &Args,
) -> Mentions {
let name = vlog_refactor::rename_name_at(&analysis.semantics, offset);
let (Some(name), 0) = (name, args.count("offset", 0)) else {
return Mentions::default();
};
let mut accounted: Vec<(PathBuf, Vec<TextRange>)> = Vec::new();
for (file, span) in found {
match accounted.iter_mut().find(|(held, _)| held == file) {
Some((_, spans)) => spans.push(*span),
None => accounted.push((file.clone(), vec![*span])),
}
}
let unit = vlog_refactor::enclosing_module(&analysis.text, offset);
let focus = Focus { name: &name, home: path, unit: unit.as_deref(), accounted: &accounted };
// `in` keeps the mentions it keeps the hits of.
let kept =
|path: &Path| in_glob(args).is_none_or(|glob| path_match(glob, &project.relative(path)));
let files = set.files.iter().filter(|(path, _)| kept(path));
mentions::find(project, files.map(|(path, text)| (path.as_path(), text.as_str())), &focus)
}
/// The one declaration a bare `name` selects for `references` (and `rename`).
pub(super) fn declaration_position(
project: &mut Project,
@@ -376,24 +409,30 @@ fn engine_refusal(sentence: String) -> String {
format!("lucisv cannot follow this position: {out}")
}
/// Hits grouped by file, `line:col text`, paged.
fn render_hits(hits: &[Site], args: &Args) -> Answer {
let (shown, rest) =
render::page(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let entries: Vec<(String, String)> = shown
const HITS: Noun = Noun("hit", "hits");
/// Hits grouped by file, `line:col text`, paged; `emptied` when the `in`
/// glob removed every hit there was.
fn render_hits(hits: &[Site], emptied: bool, args: &Args) -> Answer {
let page = Page::of(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let entries: Vec<(String, String)> = page
.shown
.iter()
.map(|hit| (hit.file.clone(), format!("{}:{} {}", hit.line, hit.col, hit.text)))
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
let mut text = page.header(HITS);
text.push_str(&render::grouped(&entries));
render::more(&mut text, page.rest());
if hits.is_empty() {
text = "no references\n".to_string();
text = if emptied { render::none_match(HITS) } else { "no references\n".to_string() };
}
let listed: Vec<Value> = shown
let listed: Vec<Value> = page
.shown
.iter()
.map(|hit| json!({ "file": hit.file, "line": hit.line, "col": hit.col, "text": hit.text }))
.collect();
Answer { text, structured: json!({ "hits": listed, "total": hits.len() }) }
let structured = json!({ "hits": listed, "total": hits.len(), "shown": page.shown_json() });
Answer { text, structured }
}
#[cfg(test)]
+448
View File
@@ -0,0 +1,448 @@
//! `add_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"]
);
}
}
+147 -49
View File
@@ -9,25 +9,36 @@ use vlog_semantic::{Def, DocumentSymbol, SymbolKind, WorkspaceIndex};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render::{self, DEFAULT_LIMIT};
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
const LIMIT: Param = Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most entries to return (default 200).",
};
const LIMIT: Param =
Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, description: "Default 500." };
const OFFSET: Param = Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Entries to skip, for paging past `… and N more` (default 0).",
description: "Entries to skip.",
};
/// `in`, the path filter every whole-project listing takes.
pub(super) const IN: Param = Param {
name: "in",
ty: Ty::Str,
required: false,
description: "Path glob the file must match, e.g. `ip/**/rtl/*.sv`.",
};
/// How many top-level modules the overview names; the rest are counted.
const TOPS_CAP: usize = 200;
const UNITS: Noun = Noun("unit", "units");
const ENTRIES: Noun = Noun("entry", "entries");
const SYMBOLS: Noun = Noun("symbol", "symbols");
pub const PROJECT_OVERVIEW: Tool = Tool {
name: "project_overview",
title: "Project overview",
description: "Summarise the Verilog/SystemVerilog project under the roots: file count, units by kind, top-level modules (nothing instantiates them) and the largest files. Call it first to orient yourself instead of listing directories.",
description: "Files, units by kind, top modules, largest files. Call it first.",
params: &[],
rewalk: true,
handler: project_overview,
@@ -35,21 +46,22 @@ pub const PROJECT_OVERVIEW: Tool = Tool {
pub const LIST_UNITS: Tool = Tool {
name: "list_units",
title: "List design units",
description: "List the modules, interfaces, packages, classes and programs declared in the project with their file:line, optionally filtered by kind and a name glob (`*`, `?`). Prefer it over grepping for `module` to find where a unit lives.",
title: "List units",
description: "Units (modules, interfaces, packages, classes, programs) with file:line.",
params: &[
Param {
name: "kind",
ty: Ty::Enum(&["module", "interface", "package", "class", "program"]),
required: false,
description: "Only units of this kind.",
description: "Only this kind.",
},
Param {
name: "glob",
ty: Ty::Str,
required: false,
description: "Only names matching this pattern; `*` is any run, `?` one character.",
description: "Name pattern with `*` and `?`.",
},
IN,
LIMIT,
OFFSET,
],
@@ -60,19 +72,14 @@ pub const LIST_UNITS: Tool = Tool {
pub const OUTLINE: Tool = Tool {
name: "outline",
title: "File outline",
description: "The declarations in one file as a tree with 1-based line ranges (units, ports, parameters, signals, functions, instances, blocks), plus its parse errors. Prefer it over reading a file to see what it contains; then use read_item for the part you need.",
description: "A file's declarations as a tree with line ranges, and its parse errors.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: true,
description: "The file, relative to a root or absolute inside one.",
},
Param { name: "file", ty: Ty::Str, required: true, description: "The file." },
Param {
name: "depth",
ty: Ty::Int { min: 1 },
required: false,
description: "Levels to show; 1 is the file's units only (default: all).",
description: "Levels (1: units only; default all).",
},
LIMIT,
OFFSET,
@@ -84,14 +91,15 @@ pub const OUTLINE: Tool = Tool {
pub const SEARCH_SYMBOLS: Tool = Tool {
name: "search_symbols",
title: "Search symbols",
description: "Find declarations whose name contains `query` (case-insensitive) across the project: units, and the ports, parameters and package/class members other files can name. Answers file and line per hit; a module's internal signals are not included (use outline for those).",
description: "Declarations whose name contains `query` (any case), members included.",
params: &[
Param {
name: "query",
ty: Ty::Str,
required: true,
description: "Substring of the name to find; empty matches everything.",
description: "Name substring; empty matches all.",
},
IN,
LIMIT,
OFFSET,
],
@@ -188,29 +196,87 @@ pub fn glob_match(pattern: &str, name: &str) -> bool {
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)),
}
}
/// The call's `in` path glob; an empty one filters nothing.
pub(super) fn in_glob(args: &Args) -> Option<&str> {
args.str("in").filter(|glob| !glob.is_empty())
}
/// The entries whose root-relative file the call's `in` glob keeps (all of
/// them without one — `file` is then never asked), and whether the glob
/// removed every entry there was.
pub(super) fn only_in<T>(
args: &Args,
items: Vec<T>,
file: impl Fn(&T) -> String,
) -> (Vec<T>, bool) {
let Some(glob) = in_glob(args) else { return (items, false) };
let had = !items.is_empty();
let kept: Vec<T> = items.into_iter().filter(|item| path_match(glob, &file(item))).collect();
let emptied = had && kept.is_empty();
(kept, emptied)
}
fn list_units(project: &mut Project, args: &Args) -> Result<Answer, String> {
let mut all = matching_units(project, args);
let select =
|project: &Project| only_in(args, matching_units(project, args), |u| u.file.clone());
let (mut all, mut emptied) = select(project);
// A glob names something the agent expects to exist — often a file it
// has just written — so a miss walks once before it is believed.
if all.is_empty() && args.str("glob").is_some() && project.ensure_walked_for_miss() {
all = matching_units(project, args);
let named = args.str("glob").is_some() || in_glob(args).is_some();
if all.is_empty() && named && project.ensure_walked_for_miss() {
(all, emptied) = select(project);
}
let (shown, rest) =
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let entries: Vec<(String, String)> = shown
let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let entries: Vec<(String, String)> = page
.shown
.iter()
.map(|u| (u.file.clone(), format!("{} {} {}", u.kind, u.name, u.line)))
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
let mut text = page.header(UNITS);
text.push_str(&render::grouped(&entries));
render::more(&mut text, page.rest());
if all.is_empty() {
text = "no units match\n".to_string();
text = if emptied { render::none_match(UNITS) } else { "no units match\n".to_string() };
}
let structured: Vec<Value> = shown
let structured: Vec<Value> = page
.shown
.iter()
.map(|u| json!({ "name": u.name, "kind": u.kind, "file": u.file, "line": u.line }))
.collect();
Ok(Answer { text, structured: json!({ "units": structured, "total": all.len() }) })
let structured = json!({ "units": structured, "total": all.len(), "shown": page.shown_json() });
Ok(Answer { text, structured })
}
/// The units `list_units`'s `kind` and `glob` select.
@@ -252,7 +318,7 @@ impl Overview {
.map(|&kind| (kind, all.iter().filter(|u| u.kind == kind).count()))
.collect();
let tops = top_modules(project.index());
let (shown, more_tops) = render::page(&tops, 0, DEFAULT_LIMIT);
let (shown, more_tops) = render::page(&tops, 0, TOPS_CAP);
let (config, config_problem) = project.config();
let discovery = project.discovery();
let (build, age) = project.timing();
@@ -357,10 +423,11 @@ fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
let depth = args.count("depth", usize::MAX);
let mut rows: Vec<(usize, String, &'static str, u32, u32)> = Vec::new();
flatten(&analysis, &analysis.semantics.document_symbols(), 0, depth, &mut rows);
let (shown, rest) =
render::page(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let page = Page::of(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let shown = page.shown;
let file = project.relative(&path);
let mut text = format!("{file}\n");
let mut text = page.header(ENTRIES);
text.push_str(&format!("{file}\n"));
let errors = &analysis.diagnostics;
if let Some(first) = errors.first() {
text.push_str(&format!(
@@ -375,7 +442,7 @@ fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
let indent = " ".repeat(level + 1);
text.push_str(&format!("{indent}{kind} {name} {}\n", render::lines(*first, *last)));
}
render::more(&mut text, rest);
render::more(&mut text, page.rest());
let symbols: Vec<Value> = shown
.iter()
.map(|(level, name, kind, first, last)| {
@@ -388,6 +455,7 @@ fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
.collect();
let structured = json!({
"file": file, "parse_errors": parse_errors, "symbols": symbols, "total": rows.len(),
"shown": page.shown_json(),
});
Ok(Answer { text, structured })
}
@@ -420,17 +488,18 @@ fn search_symbols(project: &mut Project, args: &Args) -> Result<Answer, String>
project.ensure_walked_for_miss();
}
let index = project.index();
let hits = index.workspace_symbols(query);
let (shown, rest) =
render::page(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let file_of = |file| project.relative(index.path(file).unwrap_or(Path::new("")));
let (hits, emptied) =
only_in(args, index.workspace_symbols(query), |hit| file_of(hit.def.file));
let page = Page::of(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let mut entries = Vec::new();
let mut structured = Vec::new();
for hit in shown {
for hit in page.shown {
let file = file_of(hit.def.file);
let name = match hit.container {
Some(unit) => format!("{unit}{}{}", separator(index, unit), hit.name),
None => hit.name.to_string(),
};
let file = project.relative(index.path(hit.def.file).unwrap_or(Path::new("")));
// A line and no column: the index records a client (UTF-16) column
// for units only, and every column this server prints is a byte one.
let line = hit.def.lines.name;
@@ -439,12 +508,15 @@ fn search_symbols(project: &mut Project, args: &Args) -> Result<Answer, String>
"name": name, "kind": render::kind(hit.def.kind), "file": file, "line": line,
}));
}
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
let mut text = page.header(SYMBOLS);
text.push_str(&render::grouped(&entries));
render::more(&mut text, page.rest());
if hits.is_empty() {
text = "no symbols match\n".to_string();
text = if emptied { render::none_match(SYMBOLS) } else { "no symbols match\n".into() };
}
Ok(Answer { text, structured: json!({ "symbols": structured, "total": hits.len() }) })
let total = hits.len();
let structured = json!({ "symbols": structured, "total": total, "shown": page.shown_json() });
Ok(Answer { text, structured })
}
/// How a member is spelled after its unit: `unit.x` for a module or
@@ -459,7 +531,17 @@ fn separator(index: &WorkspaceIndex, unit: &str) -> &'static str {
#[cfg(test)]
mod tests {
use super::glob_match;
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() {
@@ -471,4 +553,20 @@ mod tests {
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"));
}
}
+3 -3
View File
@@ -20,19 +20,19 @@ use crate::render;
pub const READ_ITEM: Tool = Tool {
name: "read_item",
title: "Read one item",
description: "The exact source text and 1-based line range of one item in a file: `name`, `kind:name` (e.g. `function:crc`), `name@LINE` when a name is declared twice, or `always@LINE` / `initial@LINE` / `final@LINE` / `assign@LINE` for the unlabelled block or assignment covering that line (`@LINE` is the last `@` followed only by digits, so `\\a@b@1` is `\\a@b` on line 1). Prefer it over reading the whole file; outline shows what there is.",
description: "One item's exact source and lines. Selector: `name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: true,
description: "The file, relative to a root or absolute inside one.",
description: "The file.",
},
Param {
name: "item",
ty: Ty::Str,
required: true,
description: "`name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).",
description: "The selector.",
},
],
rewalk: false,
+57 -29
View File
@@ -7,38 +7,41 @@ use std::path::{Path, PathBuf};
use vlog_refactor::{instantiation_plan, module_definition, Home, Layout, ModuleRef};
use super::edit::{enclosing, finish, whole_set, DRY_RUN};
use super::edit::{enclosing, finish, finish_telling, whole_set, with_check, Told, DRY_RUN};
use super::place;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
pub const ADD_PORT: Tool = Tool {
name: "add_port",
title: "Add a port",
description: "Add one ANSI port to a module and a connection for it to every instantiation in the project, verified before anything is written. Name the module by `module`, or by `file`+`line` inside its declaration; `declaration` is the port as written in the header (`input logic [7:0] cfg`). Refuses a port that exists, an ordered instantiation of a different length, and a list split by `ifdef`s. `dry_run` returns the diff.",
description:
"Add an ANSI port to a module, connected in every instantiation; `after` positions it.",
params: &[
Param {
name: "module",
ty: Ty::Str,
required: false,
description: "The module's name (declared once in the project).",
},
Param { name: "module", ty: Ty::Str, required: false, description: "The module." },
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "Instead of `module`: the file declaring it, with `line`.",
description: "Instead of `module`: its file, with `line`.",
},
Param {
name: "line",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based line inside the module's declaration in `file`.",
description: "A line inside the module.",
},
Param {
name: "declaration",
ty: Ty::Str,
required: true,
description: "One directed ANSI port declaration, e.g. `input logic [7:0] cfg`.",
description: "As written, e.g. `input logic [7:0] cfg`.",
},
Param {
name: "after",
ty: Ty::Str,
required: false,
description: "Port to place it after (default last).",
},
DRY_RUN,
],
@@ -48,38 +51,38 @@ pub const ADD_PORT: Tool = Tool {
pub const EXTRACT_MODULE: Tool = Tool {
name: "extract_module",
title: "Extract lines into a module",
description: "Move the whole items on lines `start_line`..`end_line` of a module into a new module `new_name`, whose ports come from the dataflow across the selection, and instantiate it in their place; verified before anything is written. `home: new_file` (default) creates `new_name.sv` beside the file (refused if it exists); `same_file` writes it below the module. Refuses a partial item and names it cannot carry. `dry_run` returns the diff.",
title: "Extract a module",
description: "Move whole items in lines `start_line`..`end_line` to a new module instantiated in their place.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: true,
description: "The file holding the module, relative to a root or absolute inside one.",
description: "The file.",
},
Param {
name: "start_line",
ty: Ty::Int { min: 1 },
required: true,
description: "First line of the selection (1-based).",
description: "First line.",
},
Param {
name: "end_line",
ty: Ty::Int { min: 1 },
required: true,
description: "Last line of the selection (1-based, included).",
description: "Last line (included).",
},
Param {
name: "new_name",
ty: Ty::Str,
required: true,
description: "The new module's name; nothing in the project may declare it yet.",
description: "An unused name.",
},
Param {
name: "home",
ty: Ty::Enum(&["new_file", "same_file"]),
required: false,
description: "Where the new module goes: `new_file` (default) or `same_file`.",
description: "Default `new_file` (`new_name.sv`).",
},
DRY_RUN,
],
@@ -90,37 +93,38 @@ pub const EXTRACT_MODULE: Tool = Tool {
pub const INSTANTIATE: Tool = Tool {
name: "instantiate",
title: "Instantiation template",
description: "The text of an instantiation of module `name` for the agent to place — parameters with their defaults, the instance name, and each port connected to a same-named signal (`named`) or as `.*` (`wildcard`). Writes nothing. Refuses a module that is not indexed or is declared twice (pass `file` to pick one).",
description:
"Instantiation text for module `name`: parameters, instance name, named or `.*` ports.",
params: &[
Param {
name: "name",
ty: Ty::Str,
required: true,
description: "The module (or interface) to instantiate.",
description: "The module or interface.",
},
Param {
name: "style",
ty: Ty::Enum(&["named", "wildcard"]),
required: false,
description: "`named` connections (default) or `.*`.",
description: "`named` (default) or `wildcard` (`.*`).",
},
Param {
name: "with_params",
ty: Ty::Bool,
required: false,
description: "Write the `#( … )` parameter overrides (default true).",
description: "Write `#(...)` overrides (default true).",
},
Param {
name: "instance",
ty: Ty::Str,
required: false,
description: "The instance name (default `u_<name>`).",
description: "Instance name (default `u_<name>`).",
},
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "The file declaring the module, when more than one does.",
description: "Its file, if declared twice.",
},
],
rewalk: false,
@@ -128,12 +132,17 @@ pub const INSTANTIATE: Tool = Tool {
};
fn add_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
with_check(add_port_to(project, args), args)
}
fn add_port_to(project: &mut Project, args: &Args) -> Result<Answer, String> {
let declaration = args.str("declaration").unwrap_or_default();
match (args.str("module"), args.str("file"), args.int("line")) {
let (module, file, set, edit) = match (args.str("module"), args.str("file"), args.int("line")) {
(Some(name), None, None) => {
let set = whole_set(project, None, &[name.to_string()])?;
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(name), declaration)?;
finish(project, edit, &set, args)
let file = module_definition(project.index(), name).map(Path::to_path_buf)?;
(name.to_string(), file, set, edit)
}
(None, Some(file), Some(line)) => {
let path = project.resolve(file)?;
@@ -142,10 +151,25 @@ fn add_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
let set = whole_set(project, Some(&path), &names)?;
let module = ModuleRef::At { file: &path, offset };
let edit = vlog_refactor::add_port(&set.files, module, declaration)?;
finish(project, edit, &set, args)
let name = names.into_iter().next().unwrap_or_default();
(name, path, set, edit)
}
_ => Err("name the module by `module`, or by `file` and `line`, not both.".into()),
}
_ => return Err("name the module by `module`, or by `file` and `line`, not both.".into()),
};
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 args.str("after") {
Some(after) => {
let spec =
place::Spec { module: &module, file: &file, after, port: &port, declaration, show };
place::after(&set.files, &edit, &spec)?
}
None => edit,
};
let lead = format!("the new port's name `{port}` is already spelled");
let told = Told { name: &port, lead, home: &file };
finish_telling(project, edit, &set, args, told, Some(&module))
}
/// The byte offset where 1-based `line` of `path` starts; `end` asks for
@@ -166,6 +190,10 @@ fn line_start(project: &mut Project, path: &Path, line: i64) -> Result<u32, Stri
}
fn extract_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
with_check(extract_lines(project, args), args)
}
fn extract_lines(project: &mut Project, args: &Args) -> Result<Answer, String> {
let file = args.str("file").unwrap_or_default();
let path = project.resolve(file)?;
let (first, last) = (args.int("start_line").unwrap_or(1), args.int("end_line").unwrap_or(1));
+764
View File
@@ -0,0 +1,764 @@
//! 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.
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 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();
}
}
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
/// every file of the tree byte-identical — also under `dry_run`.
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) {
let before = tree.hashes();
for dry_run in [true, false] {
let mut arguments = args.clone();
arguments["dry_run"] = Value::from(dry_run);
let (error, text) = server.call(tool, arguments);
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_even_with_rename() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
// The duplicate rule fires before the name rule, so `rename` changes
// nothing: a port is never redeclared.
refused(
&tree,
&mut server,
"replace_item",
core("p", "logic d;"),
"`d` would be declared twice",
);
let mut renamed = core("p", "logic d;");
renamed["rename"] = Value::from(true);
refused(&tree, &mut server, "replace_item", renamed, "`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), "`delete_item` 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", "force": true}),
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`",
);
let forced = json!({"file": "rtl/mc.sv", "item": "in_arg", "force": true});
let answer = accepted(&mut server, "delete_item", forced);
assert!(answer.contains("deleted with references left: possible use (macro)"), "{answer}");
// 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 forced = json!({"file": "rtl/sw.sv", "item": "clk", "force": true});
let answer = accepted(&mut server, "delete_item", forced);
assert!(answer.contains("bound by `.*` at rtl/sw.sv:7:18 `clk`"), "{answer}");
}
+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("project_overview", json!({})).contains("files: 7 indexed"));
assert!(session.text("unit_interface", json!({"name": "leaf"})).contains("module leaf"));
session.text("format", json!({"file": "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("list_units", json!({}));
assert!(units.contains("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,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
@@ -0,0 +1,5 @@
`define AES_TB 1
module aes_tb;
logic clk_i;
aes_core u_dut (.clk_i(clk_i), .q_o());
endmodule
@@ -0,0 +1,8 @@
`define AES_W 8
module aes_core (
input logic clk_i,
output logic [`AES_W - 1:0] q_o
);
logic \esc*name ;
assign q_o = '0;
endmodule
@@ -0,0 +1,3 @@
package aes_pkg;
parameter int \esc*w = 4;
endpackage
@@ -0,0 +1,2 @@
module uart_fifo;
endmodule
@@ -0,0 +1,8 @@
module uart (
input logic clk_i,
input logic spare_i
);
logic idle_x;
aes_core u_aes (.clk_i(clk_i), .q_o());
uart_fifo u_fifo ();
endmodule
+2
View File
@@ -0,0 +1,2 @@
[lint]
select = ["unused-signal"]
+7
View File
@@ -0,0 +1,7 @@
module chip (
input logic clk_i,
input logic spare_i
);
uart u_uart (.*);
aes_core u_aes2 (.clk_i(clk_i), .q_o());
endmodule
+114 -14
View File
@@ -7,10 +7,10 @@
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
//! lucisv_mcp --test opentitan -- --ignored --nocapture`.
use std::io::{BufRead, BufReader, Write};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::time::Instant;
use std::time::{Duration, Instant};
use serde_json::{json, Value};
@@ -24,33 +24,55 @@ fn checkout() -> PathBuf {
/// One server over the checkout.
struct Session {
child: Child,
stdin: ChildStdin,
stdin: Option<ChildStdin>,
stdout: BufReader<ChildStdout>,
next_id: i64,
}
impl Session {
fn over(root: &Path) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", root.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdin = child.stdin.take().unwrap();
Session::spawn(root, None)
}
/// A server with `--index-cache cache` when given; its stderr is kept
/// for [`Session::end`] only then (the one line it writes is small).
fn spawn(root: &Path, cache: Option<&Path>) -> Session {
let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"));
command.args(["--root", root.to_str().unwrap()]);
if let Some(cache) = cache {
command.arg("--index-cache").arg(cache);
}
let stderr = if cache.is_some() { Stdio::piped() } else { Stdio::null() };
let mut child =
command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(stderr).spawn().unwrap();
let stdin = child.stdin.take();
let stdout = BufReader::new(child.stdout.take().unwrap());
let mut session = Session { child, stdin, stdout, next_id: 0 };
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
session
}
/// Close stdin as a host does; the time the server took to exit (its
/// own store is written then) and what it said on stderr.
fn end(mut self) -> (Duration, String) {
let started = Instant::now();
drop(self.stdin.take());
self.child.wait().unwrap();
let took = started.elapsed();
let mut stderr = String::new();
if let Some(mut pipe) = self.child.stderr.take() {
pipe.read_to_string(&mut stderr).unwrap();
}
(took, stderr)
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let line =
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
writeln!(self.stdin, "{line}").unwrap();
self.stdin.flush().unwrap();
let stdin = self.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()
@@ -144,7 +166,8 @@ fn opentitan_navigation_matches_the_language_server() {
let clock = s.hits(json!({"file": tb, "line": 46, "name": "clk_i"}));
assert_covers(&clock, &["hw/ip/aes/rtl/aes.sv:42:53", "hw/ip/aes/rtl/aes.sv:197:31"]);
let top = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2, "limit": 500}));
let top = json!({"root": "top_earlgrey", "depth": 2, "limit": 500, "overrides": true});
let top = s.text("hierarchy", top);
assert!(top.contains("\n u_aes : aes #("), "{top}");
let fifo = s.text("definition", json!({"name": "prim_fifo_sync"}));
@@ -159,3 +182,80 @@ fn opentitan_navigation_matches_the_language_server() {
drop(s);
assert_eq!(status(&root), before, "the checkout was only read");
}
/// The median of some wall times, in milliseconds.
fn median_ms(mut times: Vec<Duration>) -> f64 {
times.sort();
times[times.len() / 2].as_secs_f64() * 1000.0
}
/// One startup over the checkout with the stores in `cache`: the first
/// call's wall time, the exit's, and the server's `indexed …` line.
fn startup(root: &Path, cache: &Path, label: &str) -> Session {
let mut s = Session::spawn(root, Some(cache));
let started = Instant::now();
s.text("project_overview", json!({}));
println!("startup: {label}: first call {} ms", started.elapsed().as_millis());
s
}
/// Close a session, printing its exit time and startup line.
fn finish(s: Session, label: &str) {
let (exit, stderr) = s.end();
let line = stderr.lines().find(|l| l.contains("indexed")).unwrap_or("").to_string();
println!("startup: {label}: {line}; exit (own store written) {} ms", exit.as_millis());
}
/// TODO-MCP M6: startup cold, warm from the editor's store and warm from
/// this server's own; the per-call stat sweep; the whole-set `rename`. The
/// stores live in a scratch directory outside the checkout; the editor's is
/// the own store renamed — the same codec, byte for byte (`src/cache.rs`,
/// pinned against the language server's source by its unit test).
#[test]
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN)"]
fn opentitan_startup_cold_and_warm_and_the_stat_sweep() {
let root = checkout();
let before = status(&root);
let cache = std::env::temp_dir().join(format!("lucisv-mcp-ot-cache-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&cache);
finish(startup(&root, &cache, "cold, no store"), "cold, no store");
let mut s = startup(&root, &cache, "warm, own store");
// The stat sweep: a call whose answer is cached after its first run, so
// what is left is the sweep over every file; `tools/list` is the floor.
let outline = json!({"file": "hw/ip/prim/rtl/prim_fifo_sync.sv"});
s.text("outline", outline.clone());
let mut swept = Vec::new();
let mut floor = Vec::new();
for _ in 0..21 {
let started = Instant::now();
s.request("tools/list", json!({}));
floor.push(started.elapsed());
let started = Instant::now();
s.text("outline", outline.clone());
swept.push(started.elapsed());
}
println!(
"sweep: outline median {:.2} ms, tools/list median {:.2} ms",
median_ms(swept),
median_ms(floor)
);
let rename = json!({"file": "hw/ip/aes/rtl/aes_cipher_core.sv", "line": 123, "name": "op_i", "new_name": "cipher_op_i", "dry_run": true});
for pass in ["first", "second"] {
let started = Instant::now();
let text = s.text("rename", rename.clone());
assert!(text.contains("(dry run: nothing written)"), "{text}");
println!("rename: op_i dry run, {pass} call {} ms", started.elapsed().as_millis());
}
finish(s, "warm, own store");
let own = cache.join("index-cache-mcp");
std::fs::rename(&own, cache.join("index-cache")).unwrap();
let editor = std::fs::read(cache.join("index-cache")).unwrap();
let s = startup(&root, &cache, "warm, editor's store");
finish(s, "warm, editor's store");
assert_eq!(std::fs::read(cache.join("index-cache")).unwrap(), editor, "read, never written");
println!("store: {} bytes", editor.len());
let _ = std::fs::remove_dir_all(&cache);
assert_eq!(status(&root), before, "the checkout was only read");
}
+786
View File
@@ -0,0 +1,786 @@
//! QA attacks on lane feedback-1 (unresolved mentions, `add_port`'s `after`
//! and its move-checker, the trimmed catalogue, the temp-store sweep),
//! 2026-09-23.
//!
//! Every test spawns the real binary over a scratch tree, as a host would.
//! Placements are asserted byte for byte; refusals with every file of the
//! tree byte-identical, under `dry_run` and for real.
//!
//! A test that pins a QA finding asserts the *correct* behaviour and is
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
//! numbered as in the QA log of `docs/features/mcp-feedback-1/README.md`.
use std::collections::BTreeMap;
use std::fs;
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;
use serde_json::{json, Value};
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch tree holding the files a case writes; removed on drop.
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-qa-f1-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
for (name, text) in files {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
/// Every file, root-relative, with its bytes.
fn snapshot(&self) -> BTreeMap<String, Vec<u8>> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
out.insert(name, fs::read(&path).unwrap());
}
}
}
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);
}
}
/// One running server, initialised.
struct Session {
child: Child,
stdin: Option<ChildStdin>,
lines: Receiver<String>,
next_id: i64,
/// The `initialize` reply.
init: Value,
}
impl Session {
fn over(tree: &Tree) -> Session {
Session::spawn(&["--root", tree.0.to_str().unwrap()])
}
fn spawn(args: &[&str]) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(args)
.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: Some(stdin), lines, next_id: 0, init: Value::Null };
session.init = 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) {
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{message}").unwrap();
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, its text, its structured content.
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) {
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, result["structuredContent"].clone())
}
/// Close stdin and wait for the server to exit on its own.
fn end(mut self) {
self.stdin.take();
let _ = self.child.wait();
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// A tree and a server over it.
fn served(files: &[(&str, &str)]) -> (Tree, Session) {
let tree = Tree::with(files);
let server = Session::over(&tree);
(tree, server)
}
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
/// every file of the tree byte-identical — under `dry_run` and for real.
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) -> String {
let before = tree.snapshot();
let mut said = String::new();
for dry_run in [true, false] {
let mut arguments = args.clone();
arguments["dry_run"] = Value::from(dry_run);
let (error, text, _) = server.call(tool, arguments);
assert!(error, "{tool} {args}: not refused: {text}");
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
assert!(before == tree.snapshot(), "{tool} {args}: a refusal wrote");
said = text;
}
said
}
/// Run `tool` for real and assert it wrote; its text and structured answer.
fn written(server: &mut Session, tool: &str, args: Value) -> (String, Value) {
let (error, text, structured) = server.call(tool, args.clone());
assert!(!error, "{tool} {args}: refused: {text}");
(text, structured)
}
// ---------------------------------------------------------------------------
// 1. `add_port` `after`: placements, byte for byte.
// ---------------------------------------------------------------------------
const M_HEADER: &str = "module m (\n input logic a, // anchor comment\n input logic b,\n output logic y /* last */\n);\n assign y = a & b;\nendmodule\n";
const M_TOP: &str = "module top (input logic a, b, en, output logic y);\n m u_m (\n .a (a), // in\n .b (b),\n .y (y)\n );\n m u_n (.a(a), .b(b), .y()), u_o (.a(a), .b(b), .y());\n generate if (1) begin : g_one\n m u_g (\n .a ( a ),\n .b ( b ),\n .y ( )\n );\n end endgenerate\nendmodule\n";
#[test]
fn qa_after_keeps_the_anchor_lines_comment_and_places_every_instance_shape() {
let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args.clone());
// The anchor's own comment stays on the anchor's line; the new line
// follows it in the anchor's columns.
assert_eq!(
tree.read("rtl/m.sv"),
M_HEADER.replace("comment\n", "comment\n input logic en,\n")
);
// One-per-line (aligned), two instances in one statement (inline, each
// placed), an instance in a generate block (aligned to its own anchor).
let want = M_TOP
.replace(" .a (a), // in\n", " .a (a), // in\n .en (en),\n")
.replace(
".a(a), .b(b), .y()), u_o (.a(a), .b(b)",
".a(a), .en(en), .b(b), .y()), u_o (.a(a), .en(en), .b(b)",
)
.replace(" .a ( a ),\n", " .a ( a ),\n .en ( en ),\n");
assert_eq!(tree.read("rtl/top.sv"), want);
// The same call again: the port exists, the engine refuses, nothing moves.
refused(&tree, &mut server, "add_port", args, "already has a port named `en`");
}
#[test]
fn qa_after_the_last_port_puts_the_comma_before_its_trailing_comment() {
let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "y"});
written(&mut server, "add_port", args);
let header = " output logic y, /* last */\n input logic en\n);\n";
assert_eq!(
tree.read("rtl/m.sv"),
M_HEADER.replace(" output logic y /* last */\n);\n", header)
);
let top = tree.read("rtl/top.sv");
assert!(top.contains(" .y (y),\n .en (en)\n );\n"), "{top}");
assert!(top.contains(".y(), .en(en)), u_o (.a(a), .b(b), .y(), .en(en));"), "{top}");
}
#[test]
fn qa_after_keeps_crlf_and_tabs_and_places_an_instance_in_the_modules_own_file() {
let m = "module m (\r\n\tinput logic a,\t// tabbed\r\n\toutput logic y\r\n);\r\nendmodule\r\nmodule top2 (input logic a, en, output logic y);\r\n m u_s (\r\n .a (a),\r\n .y (y)\r\n );\r\nendmodule\r\n";
let (tree, mut server) = served(&[("rtl/m.sv", m)]);
let args =
json!({"file": "rtl/m.sv", "line": 2, "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args);
let want = m
.replace("// tabbed\r\n", "// tabbed\r\n\tinput logic en,\r\n")
.replace(" .a (a),\r\n", " .a (a),\r\n .en (en),\r\n");
assert_eq!(tree.read("rtl/m.sv"), want);
}
#[test]
fn qa_positional_instances_append_after_the_last_port_and_refuse_elsewhere() {
let top = "module top (input logic a, b, en, output logic y);\n m u_p (a, b, y);\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "b"});
refused(&tree, &mut server, "add_port", args, "connects `m` by position");
let args = json!({"module": "m", "declaration": "input logic en", "after": "y"});
written(&mut server, "add_port", args);
assert_eq!(tree.read("rtl/top.sv"), top.replace("(a, b, y)", "(a, b, y, en)"));
}
#[test]
fn qa_after_a_parameter_an_unknown_name_or_an_ifdef_arm_is_refused() {
let m = "module m #(parameter int W = 1) (\n input logic a,\n`ifdef X\n input logic b,\n`endif\n output logic y\n);\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m)]);
let decl = "input logic en";
let args = json!({"module": "m", "declaration": decl, "after": "W"});
refused(&tree, &mut server, "add_port", args, "`m` has no port `W` (its ports: a, b, y)");
let args = json!({"module": "m", "declaration": decl, "after": "b"});
refused(&tree, &mut server, "add_port", args, "inside an `ifdef arm");
// Just before the arm, and just after it: placed outside it.
let args = json!({"module": "m", "declaration": decl, "after": "a", "dry_run": true});
let text = written(&mut server, "add_port", args).0;
assert!(text.contains(" input logic a,\n+ input logic en,\n `ifdef X\n"), "{text}");
let args = json!({"module": "m", "declaration": decl, "after": "y"});
written(&mut server, "add_port", args);
let want = m.replace(" output logic y\n", " output logic y,\n input logic en\n");
assert_eq!(tree.read("rtl/m.sv"), want);
}
#[test]
fn qa_a_connection_anchor_in_an_ifdef_arm_keeps_the_engines_append_and_says_so() {
let m = "module m (\n input logic a,\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, en, output logic y);\n m u_i (\n`ifdef X\n .a (a),\n`endif\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let (text, structured) = written(&mut server, "add_port", args);
assert!(text.contains("`u_i` in "), "{text}");
assert!(
text.contains(
"the connection of `en` was appended at the end (`.a` sits inside an `ifdef arm)"
),
"{text}"
);
assert_eq!(structured["warnings"].as_array().unwrap().len(), 1, "{structured}");
assert_eq!(tree.read("rtl/top.sv"), top.replace(" .y (y)\n", " .y (y),\n .en(en)\n"));
assert!(tree.read("rtl/m.sv").contains(" input logic a,\n input logic en,\n"));
}
/// Apply a unified diff (as `apply::run` renders it) to `before`.
fn patch(before: &str, diff: &str) -> String {
let old: Vec<&str> = before.split_inclusive('\n').collect();
let mut out = String::new();
let mut at = 0usize;
for line in diff.split_inclusive('\n') {
if line.starts_with("---") || line.starts_with("+++") || line.starts_with('\\') {
continue;
}
if let Some(header) = line.strip_prefix("@@ -") {
let start: usize = header.split([',', ' ']).next().unwrap().parse().unwrap();
while at + 1 < start {
out.push_str(old[at]);
at += 1;
}
} else if let Some(added) = line.strip_prefix('+') {
out.push_str(added);
} else if line.starts_with('-') {
at += 1;
} else {
out.push_str(old[at]);
at += 1;
}
}
old[at..].iter().for_each(|rest| out.push_str(rest));
out
}
#[test]
fn qa_the_dry_run_diff_is_exactly_what_the_real_run_writes() {
for after in ["a", "b", "y"] {
let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]);
let args = json!({"module": "m", "declaration": "input logic [3:0] en", "after": after});
let mut dry = args.clone();
dry["dry_run"] = Value::from(true);
let (_, preview) = written(&mut server, "add_port", dry);
let diffs: BTreeMap<String, String> = preview["changed"]
.as_array()
.unwrap()
.iter()
.map(|c| (c["file"].as_str().unwrap().into(), c["diff"].as_str().unwrap().into()))
.collect();
let before = tree.snapshot();
written(&mut server, "add_port", args);
for (file, diff) in &diffs {
let old = String::from_utf8(before[file].clone()).unwrap();
assert_eq!(patch(&old, diff), tree.read(file), "after {after}: {file}\n{diff}");
}
assert_eq!(diffs.len(), 2);
}
}
// ---------------------------------------------------------------------------
// Findings on `after` (QA log, findings 1–4).
// ---------------------------------------------------------------------------
/// Finding 1: an anchor whose comment sits between it and its comma (or on
/// the anchor's line before a leading-comma next element) is placed inline
/// at the anchor's end, so the new port lands *between* the anchor and its
/// comment: `a, input logic en /* about a */,`. The comment now documents
/// the new port. `place::verify` compares comment texts as a sorted
/// multiset, so it forgives the move. Correct: the comment stays right
/// after its anchor (insert before the comma token, after the trivia).
#[test]
fn qa_a_comment_between_the_anchor_and_its_comma_stays_with_the_anchor() {
let m = "module m (\n input logic a /* about a */,\n input logic b // about b\n , input logic c,\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, b, c, en, output logic y);\n m u_m (\n .a (a) /* conn a */,\n .b (b),\n .c (c),\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args =
json!({"module": "m", "declaration": "input logic en", "after": "a", "dry_run": true});
let (text, _) = written(&mut server, "add_port", args);
assert!(!text.contains("en /* about a */"), "the anchor's comment moved to `en`:\n{text}");
assert!(!text.contains(".en(en) /* conn a */"), "the connection's comment moved:\n{text}");
let args =
json!({"module": "m", "declaration": "input logic en", "after": "b", "dry_run": true});
let (text, _) = written(&mut server, "add_port", args);
assert!(!text.contains("en // about b"), "the anchor's comment moved to `en`:\n{text}");
drop(tree);
}
/// Finding 2: the warnings and refusals `place.rs` writes name the file by
/// its absolute path (`path.display()`, place.rs:84 and :221); every other
/// answer names files relative to a root.
#[test]
fn qa_place_names_files_relative_to_the_root() {
let m = "module m (\n input logic a,\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, en, output logic y);\n m u_i (\n`ifdef X\n .a (a),\n`endif\n .y (y)\n );\n m u_p (a, y);\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let root = tree.0.to_str().unwrap().to_string();
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let said = refused(&tree, &mut server, "add_port", args, "by position");
assert!(!said.contains(&root) && said.contains("rtl/top.sv"), "{said}");
fs::write(tree.0.join("rtl/top.sv"), top.replace(" m u_p (a, y);\n", "")).unwrap();
let args =
json!({"module": "m", "declaration": "input logic en", "after": "a", "dry_run": true});
let (text, _) = written(&mut server, "add_port", args);
assert!(!text.contains(&root) && text.contains("rtl/top.sv"), "{text}");
}
/// Finding 3: a next port that is an interface port (`bus_if.mp bus`) has
/// no direction, but does not inherit one either; `after` the port before
/// it is refused as if it did (place.rs:155).
#[test]
fn qa_a_modport_port_after_the_anchor_does_not_refuse() {
let n = "interface bus_if; logic v; modport mp(input v); endinterface\nmodule n (\n input logic clk,\n bus_if.mp bus,\n output logic y\n);\nendmodule\n";
let (_tree, mut server) = served(&[("rtl/n.sv", n)]);
let args =
json!({"module": "n", "declaration": "input logic en", "after": "clk", "dry_run": true});
let (error, text, _) = server.call("add_port", args);
assert!(!error, "{text}");
}
/// Finding 4: the edit tools list mentions with the line numbers of the
/// text *before* the edit; after a real write that adds or removes lines
/// (`add_port`, `remove_port`, a rename writing out `.*`), a mention below
/// the edit in an edited file names the wrong line.
#[test]
fn qa_mention_lines_name_the_file_as_written() {
let m = "module m (\n input logic a,\n input logic b,\n output logic y\n);\n // en gates y\n assign y = a & b;\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let (_, structured) = written(&mut server, "add_port", args);
let mention = &structured["unresolved_mentions"][0];
let line = mention["line"].as_u64().unwrap() as usize;
let on_disk = tree.read("rtl/m.sv");
assert_eq!(on_disk.lines().nth(line - 1).map(str::trim), mention["text"].as_str(), "{on_disk}");
}
/// Finding 5 (BLOCKING), a: a port list holding an element the parser
/// could not read (`(* keep *) b` — legal SV: an attribute on a port that
/// inherits `a`'s direction and type) hides that element from `place.rs`,
/// which reads the list through `ListElem::ok`. The port placed after `a`
/// lands before `b`, so `b` now inherits `input logic` — its width drops
/// from 8 to 1 — and `place::verify` (which also sees only the well-formed
/// ports, the same token multiset and the same error count) writes it.
/// Correct: refused, nothing written.
#[test]
fn qa_a_port_hidden_by_a_parse_error_does_not_change_its_inherited_type() {
let m = "module m (\n input logic [7:0] a,\n (* keep *) b,\n output logic y\n);\n assign y = ^b;\nendmodule\n";
let top = "module top (input logic [7:0] a, b, input logic en, output logic y);\n m u_m (\n .a (a),\n .b (b),\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let before = tree.snapshot();
let (error, text, _) = server.call("add_port", args);
assert!(error, "written: {text}\n{}", tree.read("rtl/m.sv"));
assert!(before == tree.snapshot());
}
/// Finding 5 (BLOCKING), b: `balanced_before` is handed the anchor's index
/// among the *well-formed* ports, but `ListDirective::before` counts every
/// element. One unreadable element before the anchor shifts the count, so
/// an anchor inside an `` `ifdef`` arm passes as outside it: the new port
/// is written inside the arm (it exists only when `X` is defined) while
/// every connection is unconditional — and the engine's own warning, still
/// in the answer, says the port was added "outside every conditional arm".
/// place.rs:161 (header) and :244 (connections) share the bug.
#[test]
fn qa_an_unreadable_element_does_not_let_an_anchor_in_an_ifdef_arm_through() {
let m = "module m (\n input logic a,\n (* keep *) input logic d,\n`ifdef X\n input logic b,\n`endif\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, b, d, en, output logic y);\n m u_m (\n .a (a),\n .d (d),\n`ifdef X\n .b (b),\n`endif\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "b"});
refused(&tree, &mut server, "add_port", args, "inside an `ifdef arm");
}
// ---------------------------------------------------------------------------
// Re-check of the rework (2026-09-23): the new rules, attacked.
// ---------------------------------------------------------------------------
const PLAIN_M: &str = "module m (\n input logic a,\n output logic y\n);\nendmodule\nmodule o (input logic p, q);\nendmodule\n";
/// An unreadable connection (`..q (p)`) in an instance nothing is placed
/// into — another module's, and a `.*` instance of `m` the engine leaves
/// alone — does not refuse; in an instance the port is placed into, it does,
/// named root-relative, with nothing written.
#[test]
fn qa_r_only_an_affected_instances_unreadable_connection_refuses() {
let top = "module top (input logic a, en, p, output logic y);\n o u_o (\n .p (p),\n ..q (p)\n );\n m u_w (.*, ..z (p));\n m u_m (\n .a (a),\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", PLAIN_M), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args.clone());
assert_eq!(
tree.read("rtl/top.sv"),
top.replace(" .a (a),\n", " .a (a),\n .en (en),\n")
);
assert!(tree.read("rtl/m.sv").contains(" input logic a,\n input logic en,\n"));
let affected = top.replace(" .y (y)\n", " .y (y),\n ..z (p)\n");
let (tree, mut server) = served(&[("rtl/m.sv", PLAIN_M), ("rtl/top.sv", &affected)]);
let said = refused(&tree, &mut server, "add_port", args, "`u_m` in rtl/top.sv holds `..z (p)`");
assert!(said.contains("nothing written"), "{said}");
}
/// The last anchor under an own-line comment, with an own-line comment
/// closing the list: the comma goes on the anchor, the new element right
/// below it, both comments stay where they were — header and connections.
#[test]
fn qa_r_own_line_comments_around_the_last_anchor_stay_put() {
let m = "module m (\n input logic a,\n // the result\n output logic y\n // end of ports\n);\nendmodule\n";
let top = "module top (input logic a, en, output logic y);\n m u_m (\n .a (a),\n // the result\n .y (y)\n // end\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "y"});
written(&mut server, "add_port", args);
let header = " output logic y,\n input logic en\n // end of ports\n";
assert_eq!(tree.read("rtl/m.sv"), m.replace(" output logic y\n // end of ports\n", header));
let conns = " .y (y),\n .en (en)\n // end\n";
assert_eq!(tree.read("rtl/top.sv"), top.replace(" .y (y)\n // end\n", conns));
}
/// A `//` comment after the separator on the anchor's line (with a block
/// comment before the separator too) stays on the anchor's line; a last
/// anchor with a comment before `)` on the same line keeps it; a
/// leading-comma list gets the element after the separator.
#[test]
fn qa_r_comments_on_the_anchors_line_stay_on_it() {
let m = "module m (\n input logic a /* c1 */, // c2\n input logic b // about b\n , output logic y\n);\nendmodule\nmodule n (input logic a, output logic y /* c */);\nendmodule\n";
let top = "module top (input logic a, b, en, output logic y);\n m u_m (\n .a (a), // in a\n .b (b),\n .y (y)\n );\n n u_n (.a(a), .y(y) /* k */);\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args);
let want = m.replace("// c2\n", "// c2\n input logic en,\n");
assert_eq!(tree.read("rtl/m.sv"), want);
let want_top = top.replace("// in a\n", "// in a\n .en (en),\n");
assert_eq!(tree.read("rtl/top.sv"), want_top);
let args = json!({"module": "m", "declaration": "input logic f", "after": "b"});
written(&mut server, "add_port", args);
let header = " input logic b // about b\n , input logic f, output logic y\n";
assert_eq!(
tree.read("rtl/m.sv"),
want.replace(" input logic b // about b\n , output logic y\n", header)
);
let args = json!({"module": "n", "declaration": "input logic en", "after": "y"});
written(&mut server, "add_port", args);
let m_now = tree.read("rtl/m.sv");
assert!(
m_now.contains("module n (input logic a, output logic y, /* c */ input logic en);"),
"{m_now}"
);
let top_now = tree.read("rtl/top.sv");
assert!(top_now.contains(" n u_n (.a(a), .y(y), /* k */ .en(en));"), "{top_now}");
}
/// A typed port without a direction after the anchor inherits the anchor's
/// direction: a new port of the same direction keeps it (placed, byte for
/// byte); of another direction would turn it (refused, nothing written).
#[test]
fn qa_r_a_typed_undirected_next_port_is_placed_only_under_the_same_direction() {
let m = "module m (\n input logic a,\n logic [3:0] b,\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, en, input logic [3:0] b, output logic y);\n m u_m (\n .a (a),\n .b (b),\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "output logic en", "after": "a"});
refused(&tree, &mut server, "add_port", args, "`b` takes its direction");
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args);
assert_eq!(
tree.read("rtl/m.sv"),
m.replace(" input logic a,\n", " input logic a,\n input logic en,\n")
);
assert_eq!(
tree.read("rtl/top.sv"),
top.replace(" .a (a),\n", " .a (a),\n .en (en),\n")
);
}
/// A rename that writes out a `.*` binding adds a line above the mentions;
/// the written answer names the lines of the file as written.
#[test]
fn qa_r_mention_lines_after_a_rename_writing_out_a_star_binding() {
let m = "module m (\n input logic a,\n output logic y\n);\n assign y = a;\nendmodule\n";
let top = "module top (input logic a, output logic y);\n m u_m (\n .*\n );\n // a feeds u_m\n initial $display(\"a\");\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"file": "rtl/m.sv", "line": 2, "name": "a", "new_name": "a_i"});
let (text, structured) = written(&mut server, "rename", args);
assert!(text.contains("added `.a_i(a)`"), "{text}");
let on_disk = tree.read("rtl/top.sv");
assert!(on_disk.contains(" .*,\n .a_i(a)\n"), "{on_disk}");
let listed = structured["unresolved_mentions"].as_array().unwrap();
assert_eq!(listed.len(), 2, "{structured}");
for mention in listed {
let line = mention["line"].as_u64().unwrap() as usize;
let shown = on_disk.lines().nth(line - 1).map(str::trim);
assert_eq!(shown, mention["text"].as_str(), "{on_disk}");
}
}
/// Finding 6 (low, for the lead to rule): the rework computes mentions on
/// the texts as they *would be* written under `dry_run` too, so a dry run's
/// `file:line` names a line of a file that is not on disk — the comment at
/// top.sv:5 is listed as top.sv:6, which on disk is the `$display`.
#[test]
#[ignore = "QA finding 6"]
fn qa_r_dry_run_mention_lines_name_the_file_on_disk() {
let m = "module m (\n input logic a,\n output logic y\n);\n assign y = a;\nendmodule\n";
let top = "module top (input logic a, output logic y);\n m u_m (\n .*\n );\n // a feeds u_m\n initial $display(\"a\");\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args =
json!({"file": "rtl/m.sv", "line": 2, "name": "a", "new_name": "a_i", "dry_run": true});
let (_, structured) = written(&mut server, "rename", args);
let on_disk = tree.read("rtl/top.sv");
for mention in structured["unresolved_mentions"].as_array().unwrap() {
let line = mention["line"].as_u64().unwrap() as usize;
let shown = on_disk.lines().nth(line - 1).map(str::trim);
assert_eq!(shown, mention["text"].as_str(), "{on_disk}");
}
}
// ---------------------------------------------------------------------------
// 2. Unresolved mentions.
// ---------------------------------------------------------------------------
const SM: &str = "module main_sm (\n input logic clk_i,\n output logic busy_o\n);\n logic state_q, state_q_d;\n // see tb.u_main_sm.state_q for the probe\n // state_q_d is not it, nor xstate_q\n `uvm_info(\"SM\", $sformatf(\"state_q=%0d\", state_q_d), UVM_LOW)\n `define F(state_q) state_q + 1\n `define G(x) x.state_q\n assign busy_o = state_q;\n initial $display(\"%m.state_q\");\n // \\state_q escaped\nendmodule\n";
const DV: &str = "module dv_x;\n logic a, b;\n assign a = `HIER.u_a[2].state_q;\n assign b = `HIER.u_a[2].state_q_d;\n assign b = `HIER.u_a[state_q].x;\nendmodule\n";
const CRLF: &str =
"module c;\r\n // one\r\n // state_q two\r\n string s = \"state_q\";\r\nendmodule\r\n";
/// Each listed mention as `file:line kind`.
fn sites(structured: &Value) -> Vec<String> {
let listed = structured["unresolved_mentions"].as_array().unwrap();
listed
.iter()
.map(|m| {
format!("{}:{} {}", m["file"].as_str().unwrap(), m["line"], m["kind"].as_str().unwrap())
})
.collect()
}
#[test]
fn qa_mentions_find_every_kind_and_only_whole_words() {
let files = [("rtl/sm.sv", SM), ("rtl/sub/crlf.sv", CRLF), ("dv/x.sv", DV)];
let (_tree, mut server) = served(&files);
let (text, structured) =
written(&mut server, "references", json!({"name": "state_q", "unit": "main_sm"}));
assert_eq!(
sites(&structured),
[
// The file of the hits first: a hierarchical path in a comment,
// a string inside a macro's arguments, a `define body (not the
// `define whose formal is the name), a string, an escaped
// spelling in a comment.
"rtl/sm.sv:6 comment",
"rtl/sm.sv:8 macro",
"rtl/sm.sv:10 define",
"rtl/sm.sv:12 string",
"rtl/sm.sv:13 comment",
// Then nearest the declaration; CRLF lines counted right.
"rtl/sub/crlf.sv:3 comment",
"rtl/sub/crlf.sv:4 string",
// A macro-rooted path through an index; `state_q_d` and a
// name used as an index are not the path's last name.
"dv/x.sv:3 path",
],
"{text}"
);
assert!(text.contains(" rtl/sub/crlf.sv:4 string: string s = \"state_q\";\n"), "{text}");
assert!(!text.contains('\r'), "no carriage return in a mention's text");
// The JSON shape: exactly these four keys, a number for the line.
for mention in structured["unresolved_mentions"].as_array().unwrap() {
let keys: Vec<&String> = mention.as_object().unwrap().keys().collect();
assert_eq!(keys, ["file", "kind", "line", "text"]);
assert!(mention["line"].is_u64());
}
// A later page repeats nothing.
let args = json!({"name": "state_q", "unit": "main_sm", "offset": 1});
let (text, structured) = written(&mut server, "references", args);
assert!(!text.contains("unresolved mentions"), "{text}");
assert_eq!(structured["unresolved_mentions"], json!([]));
}
#[test]
fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
let far: String = (0..60).map(|i| format!("// state_q far {i}\n")).collect::<String>()
+ "module far; endmodule\n";
let files = [("rtl/sm.sv", SM), ("zz/far.sv", far.as_str())];
let (tree, mut server) = served(&files);
let args = json!({"name": "state_q", "unit": "main_sm", "new_name": "st_q", "dry_run": true});
let (text, structured) = written(&mut server, "rename", args);
let listed = sites(&structured);
assert_eq!(listed.len(), 50);
assert_eq!(listed[0], "rtl/sm.sv:6 comment", "the edited file first");
assert_eq!(listed[5], "zz/far.sv:1 comment");
assert_eq!(listed[49], "zz/far.sv:45 comment");
assert!(text.contains("(strings, comments, macro text; 65 in all)"), "{text}");
assert!(text.contains("\n … and 15 more"), "{text}");
// The renamed spellings are not mentions; the edit left the rest alone.
assert!(!listed
.iter()
.any(|site| site.starts_with("rtl/sm.sv:5 ") || site.starts_with("rtl/sm.sv:11 ")));
written(
&mut server,
"rename",
json!({"name": "state_q", "unit": "main_sm", "new_name": "st_q"}),
);
let sm = tree.read("rtl/sm.sv");
assert_eq!(
sm,
SM.replace("logic state_q,", "logic st_q,").replace("busy_o = state_q;", "busy_o = st_q;")
);
}
// ---------------------------------------------------------------------------
// 3. The catalogue and the instructions.
// ---------------------------------------------------------------------------
#[test]
fn qa_the_catalogue_is_small_fully_described_and_spec_shaped() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let reply = server.request("tools/list", json!({}));
let size = reply["result"].to_string().len();
assert!(size <= 18_000, "tools/list is {size} bytes");
let tools = reply["result"]["tools"].as_array().unwrap();
assert_eq!(tools.len(), 26);
for tool in tools {
let name = tool["name"].as_str().unwrap();
assert!(tool["title"].as_str().is_some_and(|t| !t.is_empty()), "{name} keeps its title");
assert!(tool["description"].as_str().is_some_and(|d| !d.is_empty()), "{name}");
let annotations = tool["annotations"].as_object().unwrap();
assert!(!annotations.contains_key("title"), "{name}: annotations.title is gone");
for hint in ["readOnlyHint", "destructiveHint", "idempotentHint"] {
assert!(annotations[hint].is_boolean(), "{name}.{hint}");
}
let schema = &tool["inputSchema"];
assert_eq!(schema["type"], "object", "{name}");
for (param, property) in schema["properties"].as_object().unwrap() {
let described = property["description"].as_str().is_some_and(|d| d.len() > 2);
assert!(described, "{name}.{param} lost its description");
}
}
let add_port = tools.iter().find(|t| t["name"] == "add_port").unwrap();
assert_eq!(add_port["inputSchema"]["properties"]["after"]["type"], "string");
let required = add_port["inputSchema"]["required"].as_array().unwrap();
assert!(!required.contains(&json!("after")));
// The instructions: short, and every tool they name exists.
let instructions = server.init["result"]["instructions"].as_str().unwrap();
assert!(instructions.chars().count() <= 900, "{}", instructions.chars().count());
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
for word in words.filter(|w| w.contains('_') && *w != "dry_run") {
assert!(names.contains(&word), "the instructions name `{word}`, which is not a tool");
}
for word in
["outline", "definition", "references", "hierarchy", "rename", "format", "diagnostics"]
{
assert!(names.contains(&word) && instructions.contains(word), "{word}");
}
}
// ---------------------------------------------------------------------------
// 4. The temp-store sweep.
// ---------------------------------------------------------------------------
#[test]
fn qa_the_sweep_takes_only_old_files_of_the_exact_temp_name() {
let tree = Tree::with(&[("rtl/a.sv", "module a; endmodule\n")]);
let cache = tree.0.join("cache");
fs::create_dir_all(&cache).unwrap();
let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
let old = |path: &Path| {
fs::File::open(path).unwrap().set_modified(hour_ago).unwrap();
};
let stale = cache.join("index-cache-mcp.1.tmp");
let spared_names = [
"index-cache-mcp..tmp",
"index-cache-mcp.12a.tmp",
"index-cache-mcp.12.tmp.bak",
"index-cache.12.tmp",
"xindex-cache-mcp.12.tmp",
];
for name in std::iter::once("index-cache-mcp.1.tmp").chain(spared_names) {
fs::write(cache.join(name), "torn").unwrap();
old(&cache.join(name));
}
// An old directory of the exact name is not a file: left alone.
let dir = cache.join("index-cache-mcp.77.tmp");
fs::create_dir_all(dir.join("inside")).unwrap();
old(&dir);
let mut server = Session::spawn(&[
"--root",
tree.0.to_str().unwrap(),
"--index-cache",
cache.to_str().unwrap(),
]);
server.call("list_units", json!({}));
server.end();
assert!(cache.join("index-cache-mcp").is_file(), "the own store is still written");
assert!(!stale.exists(), "an hour-old `<store>.<pid>.tmp` is swept");
for name in spared_names {
assert!(cache.join(name).exists(), "{name} is not ours to sweep");
}
assert!(dir.join("inside").is_dir(), "a directory is never swept");
}
+750
View File
@@ -0,0 +1,750 @@
//! QA attacks on lane feedback-2 (the count line on every paged answer, the
//! `in` path glob, the post-edit check line), 2026-09-23.
//!
//! Every test spawns the real binary over a scratch tree, as a host would.
//! The count line is checked by one rule applied to every paged tool over a
//! grid of windows: its total is the JSON `total`, its window the JSON
//! `shown`, the JSON list holds exactly the window, and the old
//! `… and N more` tail says `total − b`.
//!
//! A test that pins a QA finding asserts the *correct* behaviour and is
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
//! numbered as in the QA log of `docs/features/mcp-feedback-2/README.md`.
use std::collections::BTreeMap;
use std::fs;
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;
use serde_json::{json, Value};
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch tree holding the files a case writes; removed on drop.
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-qa-f2-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
for (name, text) in files {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
/// Every file, root-relative, with its bytes.
fn snapshot(&self) -> BTreeMap<String, Vec<u8>> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
out.insert(name, fs::read(&path).unwrap());
}
}
}
let mut out = BTreeMap::new();
walk(&self.0, &self.0, &mut out);
out
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One running server, initialised.
struct Session {
child: Child,
stdin: Option<ChildStdin>,
lines: Receiver<String>,
next_id: i64,
/// The `initialize` reply.
init: Value,
}
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: Some(stdin), lines, next_id: 0, init: Value::Null };
session.init = 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) {
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{message}").unwrap();
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, its text, its structured content.
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) {
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, result["structuredContent"].clone())
}
/// A call that must answer; its text and structured content.
fn ok(&mut self, tool: &str, arguments: Value) -> (String, Value) {
let (error, text, structured) = self.call(tool, arguments.clone());
assert!(!error, "{tool} {arguments}: refused: {text}");
(text, structured)
}
fn text(&mut self, tool: &str, arguments: Value) -> String {
self.ok(tool, arguments).0
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
// ---------------------------------------------------------------------------
// The tree: three depths under `ip/`, a `hw/ip/` decoy for anchoring, a
// `lib/` the RTL instantiates, an escaped name holding `*`, a comment
// mention outside `ip/`, a no-tabs finding and an unused external waiver.
// ---------------------------------------------------------------------------
const TREE: &[(&str, &str)] = &[
(
"lucisv.toml",
"[lint]\nselect = [\"unused-signal\", \"no-tabs\", \"unused-waiver\"]\nwaivers = [\"w.waiver\"]\n",
),
("w.waiver", "waive --rule=no-tabs --location=nothing.sv\n"),
(
"ip/x.sv",
"`define IPX 1\nmodule ipx (input logic clk_i);\n logic dead_a;\n leaf u_a (.clk_i(clk_i));\nendmodule\n",
),
(
"ip/aes/rtl/aes.sv",
"`define AES_A 1\n`define AES_B 2\nmodule aes (input logic clk_i);\n logic dead_b;\n leaf u_b (.clk_i(clk_i));\n mid u_m (.clk_i(clk_i));\nendmodule\n",
),
(
"ip/aes/rtl/sub/deep.sv",
"module deep (input logic clk_i);\n logic dead_c;\n leaf u_c (.clk_i(clk_i));\nendmodule\n",
),
(
"ip/aes/dv/tb.sv",
"module tb;\n logic clk_i; // clk_i drives leaf\n aes u_dut (.clk_i(clk_i));\n leaf u_d (.clk_i(clk_i));\nendmodule\n",
),
("hw/ip/y.sv", "module hwy (input logic clk_i);\n\tleaf u_e (.clk_i(clk_i));\nendmodule\n"),
("lib/leaf.sv", "module leaf (input logic clk_i);\nendmodule\n"),
(
"lib/mid.sv",
"module mid (input logic clk_i);\n leaf u_f (.clk_i(clk_i));\n deep u_g (.clk_i(clk_i));\nendmodule\n",
),
("doc/notes.sv", "// leaf is the unit under test\nmodule notes; endmodule\n"),
("esc/e.sv", "module \\esc*mod (input logic a);\nendmodule\n"),
];
fn served() -> (Tree, Session) {
let tree = Tree::with(TREE);
let server = Session::over(&tree);
(tree, server)
}
// ---------------------------------------------------------------------------
// 1. The count line, one rule for every paged tool.
// ---------------------------------------------------------------------------
/// What an answer's first line says: its total and its window (`None` for
/// a whole list, `Some(None)` past the end, `Some(Some((a, b)))` cut).
struct Header {
total: usize,
window: Option<Option<(usize, usize)>>,
}
/// Parse the count line, checking its noun agrees with the number.
fn header(text: &str) -> Header {
let first = text.lines().next().unwrap_or_default();
let (count, rest) = first.split_once(' ').unwrap_or_else(|| panic!("no count line: {text}"));
let total: usize = count.parse().unwrap_or_else(|_| panic!("no count line: {text}"));
let (noun, window) = match rest.split_once(" (") {
Some((noun, window)) => (noun, Some(window.trim_end_matches(')'))),
None => (rest, None),
};
assert_eq!(noun.ends_with('s'), total != 1, "singular only for one: {first}");
let window = match window {
None => None,
Some("none match `in`") => {
assert_eq!(total, 0, "{first}");
None
}
Some("showing none: `offset` is past the end") => Some(None),
Some(showing) => {
let span = showing.strip_prefix("showing ").unwrap_or_else(|| panic!("{first}"));
let (a, b) = span.split_once('–').unwrap_or((span, span));
let (a, b): (usize, usize) = (a.parse().unwrap(), b.parse().unwrap());
assert!(1 <= a && a <= b && b <= total, "{first}");
assert!(a < b || !span.contains('–'), "one entry is `showing a`: {first}");
assert!(a > 1 || b < total, "a whole list says no window: {first}");
Some(Some((a, b)))
}
};
Header { total, window }
}
/// Check one answer against the rule: the count line's total is `total`,
/// its window is `shown`, the JSON `key` list holds the window (plus `lead`
/// lines that are not counted) and the tail counts what follows.
fn agrees(label: &str, text: &str, structured: &Value, key: &str, lead: usize) {
let listed = structured[key].as_array().map_or(0, Vec::len);
let total = structured["total"].as_u64().unwrap() as usize;
let tail = text.lines().find(|line| line.starts_with("… and "));
if text.starts_with("no ") {
// An empty list keeps its old one-line answer.
assert_eq!((total, structured["shown"].clone()), (0, json!([0, 0])), "{label}");
return;
}
let said = header(text);
assert_eq!(said.total, total, "{label}: the count line is the JSON total\n{text}");
let (a, b) = match said.window {
None if total == 0 => (0, 0),
None => (1, total),
Some(None) => (0, 0),
Some(Some(span)) => span,
};
assert_eq!(structured["shown"], json!([a, b]), "{label}: `shown` is the window\n{text}");
let in_window = if a == 0 { 0 } else { b - a + 1 };
assert_eq!(listed, in_window + lead, "{label}: the JSON lists the window\n{text}");
match b < total && a > 0 {
true => assert_eq!(tail, Some(format!("… and {} more", total - b).as_str()), "{label}"),
false => assert_eq!(tail, None, "{label}: nothing follows\n{text}"),
}
}
/// Every window worth trying on a list of `n`.
fn windows(n: usize) -> Vec<Value> {
let mut out = vec![json!({})];
for (offset, limit) in
[(0, 1), (1, 1), (0, 2), (1, 2), (n - 1, 1), (n - 1, 5), (n, 1), (n + 3, 2), (1, n)]
{
out.push(json!({"offset": offset, "limit": limit}));
}
out.push(json!({"offset": 1}));
out
}
/// The paged tools, each with arguments that give a list of several, the
/// JSON key of its list, and the lines it prints that the count leaves out.
fn paged_calls() -> Vec<(&'static str, Value, &'static str, usize)> {
vec![
("list_units", json!({}), "units", 0),
("list_units", json!({"in": "ip/**"}), "units", 0),
("search_symbols", json!({"query": "clk"}), "symbols", 0),
("search_symbols", json!({"query": "clk", "in": "**/ip/**"}), "symbols", 0),
("outline", json!({"file": "ip/aes/rtl/aes.sv"}), "symbols", 0),
("references", json!({"name": "leaf"}), "hits", 0),
("references", json!({"name": "leaf", "in": "ip/**"}), "hits", 0),
("diagnostics", json!({}), "diagnostics", 0),
("diagnostics", json!({"in": "ip/**"}), "diagnostics", 0),
("defines", json!({}), "defines", 0),
("defines", json!({"in": "ip/aes/**"}), "defines", 0),
("defines", json!({"file": "ip/aes/rtl/aes.sv"}), "defines", 0),
("hierarchy", json!({"root": "leaf", "direction": "up"}), "nodes", 1),
("hierarchy", json!({"root": "leaf", "direction": "up", "depth": 1}), "nodes", 1),
("hierarchy", json!({"root": "leaf", "direction": "up", "in": "ip/**"}), "nodes", 1),
("hierarchy", json!({}), "nodes", 0),
("hierarchy", json!({"in": "ip/**"}), "nodes", 0),
("hierarchy", json!({"root": "tb", "depth": 5}), "nodes", 0),
]
}
fn merged(base: &Value, window: &Value) -> Value {
let mut out = base.clone();
for (key, value) in window.as_object().unwrap() {
out[key] = value.clone();
}
out
}
#[test]
fn qa_every_paged_tool_agrees_with_its_json_over_every_window() {
let (_tree, mut server) = served();
for (tool, base, key, lead) in paged_calls() {
let (_, whole) = server.ok(tool, base.clone());
let n = whole["total"].as_u64().unwrap() as usize;
assert!(n >= 2, "{tool} {base}: the grid wants a list of several, got {n}");
for window in windows(n) {
let arguments = merged(&base, &window);
let (text, structured) = server.ok(tool, arguments.clone());
agrees(&format!("{tool} {arguments}"), &text, &structured, key, lead);
}
}
}
#[test]
fn qa_the_count_line_pins_whole_cut_single_and_past_the_end() {
let (_tree, mut server) = served();
let units = server.text("list_units", json!({}));
assert!(units.starts_with("9 units\ndoc/notes.sv\n"), "{units}");
let one = server.text("list_units", json!({"limit": 1}));
assert_eq!(one, "9 units (showing 1)\ndoc/notes.sv\n module notes 2\n… and 8 more\n");
let last = server.text("list_units", json!({"offset": 8, "limit": 3}));
assert_eq!(last, "9 units (showing 9)\nlib/mid.sv\n module mid 1\n");
let past = server.text("list_units", json!({"offset": 9}));
assert_eq!(past, "9 units (showing none: `offset` is past the end)\n");
let single = server.text("list_units", json!({"glob": "leaf"}));
assert_eq!(single, "1 unit\nlib/leaf.sv\n module leaf 1\n");
assert_eq!(server.text("list_units", json!({"glob": "zz*"})), "no units match\n");
let outline = server.text("outline", json!({"file": "lib/leaf.sv"}));
assert_eq!(outline, "2 entries\nlib/leaf.sv\n module leaf 1-2\n port clk_i 1\n");
let one = server.text("outline", json!({"file": "lib/leaf.sv", "depth": 1}));
assert_eq!(one, "1 entry\nlib/leaf.sv\n module leaf 1-2\n");
let past = server.text("outline", json!({"file": "lib/leaf.sv", "offset": 7}));
assert_eq!(past, "2 entries (showing none: `offset` is past the end)\nlib/leaf.sv\n");
let hit = server.text("references", json!({"name": "notes"}));
assert_eq!(hit, "1 hit\ndoc/notes.sv\n 2:8 module notes; endmodule\n");
let cut = server.text("references", json!({"name": "leaf", "limit": 2, "offset": 5}));
assert!(cut.starts_with("7 hits (showing 6–7)\nlib/leaf.sv\n"), "{cut}");
assert!(!cut.contains("… and"), "{cut}");
let finding = server.text("diagnostics", json!({"file": "hw/ip/y.sv"}));
assert_eq!(
finding,
"1 finding\nhw/ip/y.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n"
);
let define = server.text("defines", json!({"name": "IPX"}));
assert_eq!(define, "1 define\nip/x.sv\n 1 `define IPX 1\n");
let symbol = server.text("search_symbols", json!({"query": "leaf"}));
assert_eq!(symbol, "1 symbol\nlib/leaf.sv\n module leaf 1\n");
}
// ---------------------------------------------------------------------------
// 2. `hierarchy`: `up` from one root counts instantiations, the root line
// on every page; any other walk counts nodes.
// ---------------------------------------------------------------------------
const LEAF_UP: &str = "leaf lib/leaf.sv:1\n";
#[test]
fn qa_hierarchy_up_repeats_its_root_line_on_every_page_and_counts_only_instantiations() {
let (_tree, mut server) = served();
let (whole, structured) = server.ok("hierarchy", json!({"root": "leaf", "direction": "up"}));
// Deeper lines are instantiations of the ancestors and are counted.
assert_eq!(structured["total"], 11);
assert_eq!(whole.lines().count(), 1 + 1 + 11, "{whole}");
assert_eq!(structured["nodes"][0]["module"], "leaf", "{structured}");
for offset in 0..13 {
let args = json!({"root": "leaf", "direction": "up", "limit": 2, "offset": offset});
let (text, _) = server.ok("hierarchy", args);
let (_, body) = text.split_once('\n').unwrap();
assert!(body.starts_with(LEAF_UP), "offset {offset}: {text}");
assert_eq!(body.matches(LEAF_UP).count(), 1, "offset {offset}: {text}");
}
let page = server.text(
"hierarchy",
json!({"root": "leaf", "direction": "up", "depth": 1, "limit": 2, "offset": 2}),
);
assert_eq!(
page,
"6 instantiations (showing 3–4)\nleaf lib/leaf.sv:1\n aes.u_b ip/aes/rtl/aes.sv:5\n deep.u_c ip/aes/rtl/sub/deep.sv:3\n… and 2 more\n"
);
let past = server.text("hierarchy", json!({"root": "leaf", "direction": "up", "offset": 40}));
assert_eq!(
past,
format!("11 instantiations (showing none: `offset` is past the end)\n{LEAF_UP}")
);
let top = server.text("hierarchy", json!({"root": "tb", "direction": "up"}));
assert_eq!(top, "0 instantiations\ntb ip/aes/dv/tb.sv:1\n");
let one = server.text("hierarchy", json!({"root": "aes", "direction": "up"}));
assert_eq!(one, "1 instantiation\naes ip/aes/rtl/aes.sv:3\n tb.u_dut ip/aes/dv/tb.sv:3\n");
}
#[test]
fn qa_hierarchy_up_from_a_root_declared_twice_counts_every_line_as_nodes() {
let tree = Tree::with(&[
("a/d1.sv", "module dup; endmodule\n"),
("b/d2.sv", "module dup; endmodule\n"),
("a/user.sv", "module user; dup u1 (); dup u2 (); endmodule\n"),
]);
let mut server = Session::over(&tree);
let (text, structured) = server.ok("hierarchy", json!({"root": "dup", "direction": "up"}));
assert_eq!(
text,
"6 nodes\ndup a/d1.sv:1\n user.u1 a/user.sv:1\n user.u2 a/user.sv:1\ndup b/d2.sv:1\n user.u1 a/user.sv:1\n user.u2 a/user.sv:1\n"
);
assert_eq!(
(structured["total"].clone(), structured["shown"].clone()),
(json!(6), json!([1, 6]))
);
let cut = server.text("hierarchy", json!({"root": "dup", "direction": "up", "limit": 2}));
assert!(
cut.starts_with("6 nodes (showing 1–2)\ndup a/d1.sv:1\n")
&& cut.ends_with("… and 4 more\n")
);
}
#[test]
fn qa_hierarchy_down_from_several_tops_counts_nodes() {
let (_tree, mut server) = served();
let (tops, structured) = server.ok("hierarchy", json!({"depth": 1}));
assert_eq!(
tops,
"9 nodes\n\\esc*mod esc/e.sv:1\nhwy hw/ip/y.sv:1\n u_e : leaf\nipx ip/x.sv:2\n u_a : leaf\nnotes doc/notes.sv:2\ntb ip/aes/dv/tb.sv:1\n u_dut : aes\n u_d : leaf\n"
);
assert_eq!(structured["total"], 9);
let cut = server.text("hierarchy", json!({"depth": 1, "offset": 3, "limit": 3}));
assert_eq!(
cut,
"9 nodes (showing 4–6)\nipx ip/x.sv:2\n u_a : leaf\nnotes doc/notes.sv:2\n… and 3 more\n"
);
}
// ---------------------------------------------------------------------------
// 3. `in`: the path matcher through the tools.
// ---------------------------------------------------------------------------
/// The unit names `list_units` gives under `in`, or the whole text when the
/// answer is not a list.
fn units_in(server: &mut Session, glob: &str) -> Vec<String> {
let (text, structured) = server.ok("list_units", json!({"in": glob}));
if structured["total"] == 0 {
return vec![text];
}
let units = structured["units"].as_array().unwrap();
units.iter().map(|u| u["name"].as_str().unwrap().to_string()).collect()
}
#[test]
fn qa_in_star_stays_in_one_component_and_double_star_spans_zero_or_more() {
let (_tree, mut server) = served();
let none = || vec!["0 units (none match `in`)\n".to_string()];
// `*` never crosses a `/`: `sub/deep.sv` is not in `rtl/*.sv`.
assert_eq!(units_in(&mut server, "ip/aes/rtl/*.sv"), ["aes"]);
assert_eq!(units_in(&mut server, "ip/aes/rtl/**"), ["aes", "deep"]);
assert_eq!(units_in(&mut server, "ip/aes/rtl/**/*.sv"), ["aes", "deep"]);
// `**` spans zero components too.
assert_eq!(units_in(&mut server, "ip/**/x.sv"), ["ipx"]);
assert_eq!(units_in(&mut server, "**/x.sv"), ["ipx"]);
assert_eq!(units_in(&mut server, "ip/**/rtl/**/deep.sv"), ["deep"]);
// Anchored at the root: `ip/**` is not `hw/ip/**`.
assert_eq!(units_in(&mut server, "ip/**"), ["tb", "aes", "deep", "ipx"]);
assert_eq!(units_in(&mut server, "**/ip/**"), ["hwy", "tb", "aes", "deep", "ipx"]);
assert_eq!(units_in(&mut server, "hw/ip/*.sv"), ["hwy"]);
assert_eq!(units_in(&mut server, "*/ip/*"), ["hwy"]);
// `?` is one character of one component.
assert_eq!(units_in(&mut server, "ip/ae?/*/*.sv"), ["tb", "aes"]);
assert_eq!(units_in(&mut server, "ip/a?/**"), none());
assert_eq!(units_in(&mut server, "l?b/m?d.sv"), ["mid"]);
assert_eq!(units_in(&mut server, "ip?x.sv"), none(), "`?` never matches a `/`");
// A leading `./`, a trailing `/`, `**/**`.
assert_eq!(units_in(&mut server, "./lib/*"), ["leaf", "mid"]);
assert_eq!(units_in(&mut server, "lib/"), ["leaf", "mid"]);
assert_eq!(units_in(&mut server, "**/**/lib/**/**"), ["leaf", "mid"]);
// A whole-path glob is not a substring search.
assert_eq!(units_in(&mut server, "aes"), none());
assert_eq!(units_in(&mut server, "*.sv"), none());
}
#[test]
fn qa_in_matches_paths_never_names_even_escaped_ones_holding_a_star() {
let (_tree, mut server) = served();
let none = vec!["0 units (none match `in`)\n".to_string()];
// The unit is named `\esc*mod `; the glob sees only `esc/e.sv`.
assert_eq!(units_in(&mut server, "\\esc*mod "), none);
assert_eq!(units_in(&mut server, "esc*"), none);
assert_eq!(units_in(&mut server, "esc*/*"), ["\\esc*mod"]);
let named = server.text("list_units", json!({"glob": "\\esc*mod", "in": "esc/e.sv"}));
assert_eq!(named, "1 unit\nesc/e.sv\n module \\esc*mod 1\n");
let symbols = server.text("search_symbols", json!({"query": "esc*", "in": "esc/*"}));
assert!(symbols.starts_with("1 symbol\nesc/e.sv\n"), "{symbols}");
}
#[test]
fn qa_in_says_none_match_only_when_it_removed_something() {
let (_tree, mut server) = served();
// Empty before the glob: the old answer, per tool.
let empty = [
("list_units", json!({"glob": "zz", "in": "nowhere/**"}), "no units match\n"),
("search_symbols", json!({"query": "zz", "in": "nowhere/**"}), "no symbols match\n"),
("defines", json!({"name": "ZZ", "in": "nowhere/**"}), "no defines\n"),
("defines", json!({"file": "lib/mid.sv", "in": "nowhere/**"}), "no defines\n"),
("diagnostics", json!({"file": "lib/mid.sv", "in": "nowhere/**"}), "no findings\n"),
];
for (tool, args, said) in empty {
assert_eq!(server.text(tool, args.clone()), said, "{tool} {args}");
}
let refs = server.text("references", json!({"name": "clk_i", "unit": "leaf", "in": "zz/**"}));
assert_eq!(refs, "0 hits (none match `in`)\n");
// Emptied by the glob: said so, per tool.
let emptied = [
("list_units", json!({"in": "nowhere/**"}), "0 units (none match `in`)\n"),
("search_symbols", json!({"query": "clk", "in": "doc/*"}), "0 symbols (none match `in`)\n"),
("defines", json!({"in": "lib/**"}), "0 defines (none match `in`)\n"),
("defines", json!({"file": "ip/x.sv", "in": "lib/**"}), "0 defines (none match `in`)\n"),
("diagnostics", json!({"in": "nowhere/**"}), "0 findings (none match `in`)\n"),
(
"diagnostics",
json!({"file": "ip/x.sv", "in": "lib/*"}),
"0 findings (none match `in`)\n",
),
("hierarchy", json!({"in": "lib/**"}), "0 nodes (none match `in`)\n"),
];
for (tool, args, said) in emptied {
let (text, structured) = server.ok(tool, args.clone());
assert_eq!(text, said, "{tool} {args}");
assert_eq!(
(structured["total"].clone(), structured["shown"].clone()),
(json!(0), json!([0, 0]))
);
}
// Matched files with nothing to say are clean, not "none match".
assert_eq!(server.text("diagnostics", json!({"in": "lib/**"})), "no findings\n");
// `in` and a window together: the total is the filtered count.
let (text, structured) =
server.ok("references", json!({"name": "leaf", "in": "ip/**", "offset": 1, "limit": 2}));
assert!(text.starts_with("4 hits (showing 2–3)\n"), "{text}");
assert!(text.contains("… and 1 more\n"), "{text}");
assert_eq!(structured["total"], 4);
let past = server.text("list_units", json!({"in": "lib/*", "offset": 2}));
assert_eq!(past, "2 units (showing none: `offset` is past the end)\n");
}
#[test]
fn qa_in_on_references_keeps_only_the_mentions_in_matching_files() {
let (_tree, mut server) = served();
let (all, structured) = server.ok("references", json!({"name": "leaf"}));
assert!(all.contains("doc/notes.sv:1 comment") && all.contains("ip/aes/dv/tb.sv:2 comment"));
assert_eq!(structured["unresolved_mentions"].as_array().unwrap().len(), 2);
let (rtl, structured) = server.ok("references", json!({"name": "leaf", "in": "ip/**"}));
assert!(!rtl.contains("doc/notes.sv"), "a mention outside the glob: {rtl}");
assert!(rtl.contains("ip/aes/dv/tb.sv:2 comment"), "{rtl}");
assert_eq!(structured["unresolved_mentions"].as_array().unwrap().len(), 1);
let lib = server.text("references", json!({"name": "leaf", "in": "lib/**"}));
assert_eq!(
lib,
"2 hits\nlib/leaf.sv\n 1:8 module leaf (input logic clk_i);\nlib/mid.sv\n 2:3 leaf u_f (.clk_i(clk_i));\n"
);
// Hits emptied, a mention kept: both said.
let doc = server.text("references", json!({"name": "leaf", "in": "doc/*"}));
assert!(doc.starts_with("0 hits (none match `in`)\nunresolved mentions"), "{doc}");
assert!(doc.ends_with(" doc/notes.sv:1 comment: // leaf is the unit under test\n"), "{doc}");
}
#[test]
fn qa_in_on_hierarchy_down_drops_a_whole_subtree_and_up_does_not_climb_through_a_drop() {
let (_tree, mut server) = served();
// `mid` lives in `lib/`; its child `deep` lives in `ip/` but is under a
// dropped node, so it must not appear.
let aes = server.text("hierarchy", json!({"root": "aes", "depth": 5, "in": "ip/**"}));
assert_eq!(aes, "1 node\naes ip/aes/rtl/aes.sv:3\n");
let tb = server.text("hierarchy", json!({"root": "tb", "depth": 5, "in": "**/rtl/**"}));
assert_eq!(tb, "2 nodes\ntb ip/aes/dv/tb.sv:1\n u_dut : aes\n");
let tb = server.text("hierarchy", json!({"root": "tb", "depth": 5, "in": "lib/*"}));
assert_eq!(tb, "2 nodes\ntb ip/aes/dv/tb.sv:1\n u_d : leaf\n");
// No root: tops by their own file, children by theirs.
let dv = server.text("hierarchy", json!({"in": "ip/aes/dv/*", "depth": 5}));
assert_eq!(dv, "1 node\ntb ip/aes/dv/tb.sv:1\n");
// Up: `mid.u_g` (lib/) is dropped, so `aes.u_m` above it is not reached
// through it; `deep.u_c` (ip/) is kept.
let up = server.text("hierarchy", json!({"root": "deep", "direction": "up", "in": "ip/**"}));
assert_eq!(up, "0 instantiations (none match `in`)\ndeep ip/aes/rtl/sub/deep.sv:1\n");
let up = server.text("hierarchy", json!({"root": "leaf", "direction": "up", "in": "ip/**"}));
assert_eq!(
up,
"5 instantiations\nleaf lib/leaf.sv:1\n tb.u_d ip/aes/dv/tb.sv:4\n aes.u_b ip/aes/rtl/aes.sv:5\n tb.u_dut ip/aes/dv/tb.sv:3\n deep.u_c ip/aes/rtl/sub/deep.sv:3\n ipx.u_a ip/x.sv:4\n"
);
}
#[test]
fn qa_in_on_whole_project_diagnostics_lints_matching_files_and_reports_no_unused_waiver() {
let (_tree, mut server) = served();
let all = server.text("diagnostics", json!({}));
assert!(all.starts_with("5 findings\n"), "{all}");
assert!(all.contains("w.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n"));
let (ip, structured) = server.ok("diagnostics", json!({"in": "ip/**"}));
assert_eq!(
ip,
"3 findings\nip/aes/rtl/aes.sv\n 4:9 warning `dead_b` is declared but never used [unused-signal]\nip/aes/rtl/sub/deep.sv\n 2:9 warning `dead_c` is declared but never used [unused-signal]\nip/x.sv\n 3:9 warning `dead_a` is declared but never used [unused-signal]\n"
);
assert_eq!(structured["total"], 3);
for glob in ["**/*.sv", "hw/**", "*.waiver", "w.waiver"] {
let text = server.text("diagnostics", json!({"in": glob}));
assert!(!text.contains("unused-waiver"), "{glob}: {text}");
}
// `in` + severity + a window.
let args = json!({"in": "**/ip/**", "severity": "warning", "offset": 2, "limit": 5});
let (text, structured) = server.ok("diagnostics", args);
assert!(text.starts_with("3 findings (showing 3)\nip/x.sv\n"), "{text}");
assert_eq!(structured["shown"], json!([3, 3]));
}
// ---------------------------------------------------------------------------
// 4. The check line on the six design-wide edits.
// ---------------------------------------------------------------------------
/// The last line of an answer.
fn last_line(text: &str) -> &str {
text.trim_end_matches('\n').rsplit('\n').next().unwrap_or_default()
}
#[test]
fn qa_each_edit_ends_with_its_check_line_dry_and_real_and_nothing_else_does() {
let (tree, mut server) = served();
let cases = [
("rename", json!({"name": "mid", "new_name": "mid2"}), "ip/aes/rtl/aes.sv, lib/mid.sv"),
(
"add_port",
json!({"module": "deep", "declaration": "input logic en"}),
"ip/aes/rtl/sub/deep.sv, lib/mid.sv",
),
("expand_wildcard", json!({"file": "ip/wild.sv", "line": 2}), "ip/wild.sv"),
(
"remove_port",
json!({"file": "lib/solo.sv", "line": 1, "name": "k"}),
"ip/wild.sv, lib/solo.sv",
),
("inline_module", json!({"file": "ip/wild.sv", "line": 2, "name": "u_l"}), "ip/wild.sv"),
(
"extract_module",
json!({"file": "ip/x.sv", "start_line": 4, "end_line": 4, "new_name": "slot"}),
"ip/slot.sv, ip/x.sv",
),
];
fs::write(
tree.0.join("lib/solo.sv"),
"module solo (input logic a, input logic k);\nendmodule\n",
)
.unwrap();
fs::write(
tree.0.join("ip/wild.sv"),
"module wild (input logic a, input logic k);\n solo u_l (.*);\nendmodule\n",
)
.unwrap();
for (tool, args, files) in cases {
let before = tree.snapshot();
let mut dry = args.clone();
dry["dry_run"] = json!(true);
let (text, structured) = server.ok(tool, dry);
assert_eq!(
last_line(&text),
format!("check after writing: diagnostics on {files}"),
"{tool}"
);
assert_eq!(text.matches("diagnostics on").count(), 1, "{tool}: {text}");
assert!(structured.get("check").is_none(), "{tool}: the JSON is unchanged");
assert!(before == tree.snapshot(), "{tool}: a dry run wrote");
let (text, _) = server.ok(tool, args.clone());
assert_eq!(last_line(&text), format!("check: diagnostics on {files}"), "{tool}: {text}");
// Once more: `unchanged` or a refusal, never a check line.
let (_, again, _) = server.call(tool, args.clone());
assert!(!again.contains("diagnostics on"), "{tool} again: {again}");
}
let unchanged = server.text("rename", json!({"name": "leaf", "new_name": "leaf"}));
assert_eq!(unchanged, "unchanged\n");
// The edits outside the brief carry no line.
let args = json!({"file": "lib/leaf.sv", "line": 1, "dry_run": true});
let (_, ports, _) = server.call("convert_ports", args);
assert!(!ports.contains("diagnostics on"), "{ports}");
}
#[test]
fn qa_the_check_line_names_five_files_in_path_order_and_counts_the_rest() {
let mut files: Vec<(String, String)> =
vec![("z/leaf.sv".into(), "module leaf (input logic a);\nendmodule\n".into())];
for (i, dir) in ["q", "B", "a", "a/b", "m", "a.x", "c"].iter().enumerate() {
let text = format!("module u{i} (input logic a);\n leaf u_l (.a(a));\nendmodule\n");
files.push((format!("{dir}/u{i}.sv"), text));
}
let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect();
let tree = Tree::with(&borrowed);
let mut server = Session::over(&tree);
let args = json!({"name": "leaf", "new_name": "leaf_r", "dry_run": true});
let text = server.text("rename", args);
// Byte order: `B` < `a.x` < `a/` (`.` < `/`) < `c` …; 8 files, 5 named.
assert_eq!(
last_line(&text),
"check after writing: diagnostics on B/u1.sv, a.x/u5.sv, a/b/u3.sv, a/u2.sv, c/u6.sv and 3 more"
);
let text = server.text("rename", json!({"name": "leaf", "new_name": "leaf_r"}));
assert!(text.ends_with("c/u6.sv and 3 more\n"), "{text}");
}
// ---------------------------------------------------------------------------
// 5. The catalogue and the instructions.
// ---------------------------------------------------------------------------
#[test]
fn qa_catalogue_and_instructions_stay_in_budget_and_name_real_tools() {
let (_tree, mut server) = served();
let instructions = server.init["result"]["instructions"].as_str().unwrap().to_string();
assert!(instructions.chars().count() <= 900, "{} chars", instructions.chars().count());
let reply = server.request("tools/list", json!({}));
assert!(reply["result"].to_string().len() <= 18_000);
let tools = reply["result"]["tools"].as_array().unwrap();
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
for word in words.filter(|w| w.contains('_') && *w != "dry_run") {
assert!(names.contains(&word), "`{word}` in the instructions is no tool");
}
for bare in
["outline", "definition", "references", "hierarchy", "format", "rename", "diagnostics"]
{
assert!(instructions.contains(bare) && names.contains(&bare), "{bare}");
}
for tool in tools {
for (name, property) in tool["inputSchema"]["properties"].as_object().unwrap() {
let described = property["description"].as_str().is_some_and(|d| !d.is_empty());
assert!(described, "{}.{name} is documented", tool["name"]);
}
let takes_in = tool["inputSchema"]["properties"].get("in").is_some();
let lists =
["list_units", "search_symbols", "references", "hierarchy", "diagnostics", "defines"];
assert_eq!(takes_in, lists.contains(&tool["name"].as_str().unwrap()), "{}", tool["name"]);
let limit = &tool["inputSchema"]["properties"]["limit"]["description"];
assert!(limit.is_null() || limit.as_str().unwrap().contains("500"), "{}", tool["name"]);
}
}
+430
View File
@@ -0,0 +1,430 @@
//! QA attacks on lane feedback-3 (`unit_interface`'s `template` and
//! `hierarchy`'s `overrides` made opt-in, counted section headers),
//! 2026-09-23.
//!
//! Every test spawns the real binary over a scratch tree, as a host would.
//! The `OLD_*` literals are what the c2e42b8 binary (the tree before this
//! lane, built from `git archive HEAD`) answered for the same calls, so
//! "the opt-in is byte-identical to the old default" is pinned against the
//! old binary's own bytes, not against a re-derivation.
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::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;
use serde_json::{json, Value};
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch tree holding the files a case writes; removed on drop.
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-qa-f3-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
for (name, text) in files {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One running server, initialised.
struct Session {
child: Child,
stdin: Option<ChildStdin>,
lines: Receiver<String>,
next_id: i64,
/// The `initialize` reply.
init: Value,
}
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: Some(stdin), lines, next_id: 0, init: Value::Null };
session.init = 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) {
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{message}").unwrap();
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, its text, its structured content.
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) {
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, result["structuredContent"].clone())
}
/// A call that must answer; its text and structured content.
fn ok(&mut self, tool: &str, arguments: Value) -> (String, Value) {
let (error, text, structured) = self.call(tool, arguments.clone());
assert!(!error, "{tool} {arguments}: refused: {text}");
(text, structured)
}
/// A call that must be refused; its text.
fn refused(&mut self, tool: &str, arguments: Value) -> String {
let (error, text, _) = self.call(tool, arguments.clone());
assert!(error, "{tool} {arguments}: answered: {text}");
text
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
// ---------------------------------------------------------------------------
// The tree: an interface with modports, a module with `ifdef'd lists (so
// it has warnings), an empty module, a parameter-only module, a module of
// multi-declarator and unpacked ports, a program, and instances whose
// overrides are long (over the 200-byte cap), absent, and commented.
// ---------------------------------------------------------------------------
fn long_overrides() -> String {
format!(".A({}), .B({})", "1".repeat(96), "2".repeat(118))
}
fn tree() -> Tree {
let user2 = format!(
"module user2 (input logic clk);\n leaf2 #({}) u_long (.clk(clk));\n leaf2 u_plain (.clk(clk));\n leaf2 #(.A(1) /* #( in a comment */) u_c (.clk(clk));\nendmodule\n",
long_overrides()
);
let leaf2 =
"module leaf2 #(parameter int A = 1, parameter int B = 2) (input logic clk);\nendmodule\n";
Tree::with(&[
(
"bus.sv",
"interface bus #(parameter int W = 8) (input logic clk);\n logic [W-1:0] data;\n logic valid;\n modport mst (output data, valid);\n modport slv (input data, valid);\nendinterface\n",
),
(
"dirs.sv",
"module dirs #(parameter int W = 1\n`ifdef X\n , parameter int V = 3\n`endif\n) (input logic a\n`ifdef X\n , output logic b\n`endif\n);\nendmodule\n",
),
("nothing.sv", "module nothing;\nendmodule\n"),
("onlyp.sv", "module onlyp #(parameter int W = 1, parameter int D = 2);\nendmodule\n"),
("np.sv", "module np (input logic a, b, output logic [3:0] y [2]);\nendmodule\n"),
("prog.sv", "program prog (input logic clk);\nendprogram\n"),
("pkg.sv", "package pkg;\n parameter int P = 1;\n typedef logic [3:0] nib_t;\nendpackage\n"),
("leaf2.sv", leaf2),
("user2.sv", user2.as_str()),
])
}
// ---------------------------------------------------------------------------
// 1. `unit_interface`: the template, opt-in and byte-identical.
// ---------------------------------------------------------------------------
/// What c2e42b8 answered for `unit_interface` (no flag existed then).
const OLD_UNITS: &[(&str, &str)] = &[
(
"bus",
"interface bus bus.sv:1\nparameters:\n W = 8\nports:\n input logic clk\nmodports:\n mst (output data, valid)\n slv (input data, valid)\ntemplate:\nbus #(\n .W(8)\n) u_bus (\n .clk(clk)\n);\n",
),
(
"dirs",
"module dirs dirs.sv:1\nparameters:\n W = 1\n V = 3\nports:\n input logic a\n output logic b\nwarning: `dirs`'s port list carries compiler directives, so what it declares depends on the configuration; the skeleton names every entry written, from every `ifdef arm.\nwarning: `dirs`'s parameter list carries compiler directives, so what it declares depends on the configuration; the skeleton names every entry written, from every `ifdef arm.\ntemplate:\ndirs #(\n .W(1),\n .V(3)\n) u_dirs (\n .a(a),\n .b(b)\n);\n",
),
("nothing", "module nothing nothing.sv:1\ntemplate:\nnothing u_nothing ();\n"),
(
"np",
"module np np.sv:1\nports:\n input logic a\n input logic b\n output logic [3:0] y [2]\ntemplate:\nnp u_np (\n .a(a),\n .b(b),\n .y(y)\n);\n",
),
];
/// The old text with this lane's counted headers: the only change the
/// opt-in answer may carry.
fn counted(old: &str, parameters: usize, ports: usize) -> String {
old.replace("\nparameters:\n", &format!("\nparameters ({parameters}):\n"))
.replace("\nports:\n", &format!("\nports ({ports}):\n"))
}
#[test]
fn qa_template_true_is_the_old_answer_byte_for_byte_and_the_default_stops_before_it() {
let tree = tree();
let mut s = Session::over(&tree);
for (name, old) in OLD_UNITS {
let (with, full) = s.ok("unit_interface", json!({"name": name, "template": true}));
let parameters = full["parameters"].as_array().unwrap().len();
let ports = full["ports"].as_array().unwrap().len();
let expected = counted(old, parameters, ports);
assert_eq!(with, expected, "{name}");
let old_template = &old[old.find("template:\n").unwrap() + "template:\n".len()..];
assert_eq!(format!("{}\n", full["template"].as_str().unwrap()), old_template, "{name}");
let (plain, bare) = s.ok("unit_interface", json!({"name": name}));
assert_eq!(plain, expected[..expected.find("template:\n").unwrap()], "{name}");
assert!(!plain.contains("template"), "{name}: {plain}");
let object = bare.as_object().unwrap();
assert!(!object.contains_key("template"), "{name}: no key, not null: {bare}");
let mut stripped = full.clone();
stripped.as_object_mut().unwrap().remove("template");
assert_eq!(stripped, bare, "{name}: the JSON differs only by `template`");
}
}
#[test]
fn qa_a_program_is_instantiable_and_a_package_ignores_the_flag() {
let tree = tree();
let mut s = Session::over(&tree);
let (plain, bare) = s.ok("unit_interface", json!({"name": "prog"}));
assert_eq!(plain, "program prog prog.sv:1\nports (1):\n input logic clk\n");
assert!(bare.get("template").is_none());
let (with, _) = s.ok("unit_interface", json!({"name": "prog", "template": true}));
assert!(with.ends_with("template:\nprog u_prog (\n .clk(clk)\n);\n"), "{with}");
let package = s.ok("unit_interface", json!({"name": "pkg"}));
let flagged = s.ok("unit_interface", json!({"name": "pkg", "template": true}));
assert_eq!(package, flagged);
assert!(package.0.contains("members:\n"), "{}", package.0);
}
// ---------------------------------------------------------------------------
// 2. The counted headers.
// ---------------------------------------------------------------------------
/// The rows under `header` in `text`: the indented lines that follow it.
fn rows_under(text: &str, header: &str) -> Option<usize> {
let start = text.find(&format!("\n{header}"))? + 1;
let body = &text[start..];
Some(body.lines().skip(1).take_while(|line| line.starts_with(" ")).count())
}
/// The count a header like `ports (12):` carries.
fn header_count(text: &str, section: &str) -> Option<usize> {
let at = text.find(&format!("\n{section} ("))? + section.len() + 3;
text[at..].split(')').next()?.parse().ok()
}
#[test]
fn qa_every_header_count_equals_its_rows_and_the_json_and_an_empty_section_has_no_header() {
let tree = tree();
let mut s = Session::over(&tree);
let expected: &[(&str, usize, usize)] =
&[("bus", 1, 1), ("dirs", 2, 2), ("nothing", 0, 0), ("onlyp", 2, 0), ("np", 0, 3)];
for (name, parameters, ports) in expected {
let (text, json) = s.ok("unit_interface", json!({"name": name}));
for (section, want, key) in
[("parameters", parameters, "parameters"), ("ports", ports, "ports")]
{
assert_eq!(json[key].as_array().unwrap().len(), *want, "{name}.{key}");
if *want == 0 {
// An empty section is left out, as before the lane: no `(0)`.
assert!(!text.contains(&format!("{section} (")), "{name}: {text}");
assert!(!text.contains(&format!("{section}:")), "{name}: {text}");
} else {
assert_eq!(header_count(&text, section), Some(*want), "{name}: {text}");
let header = format!("{section} ({want}):\n");
assert_eq!(rows_under(&text, &header), Some(*want), "{name}: {text}");
}
}
}
// The modports header keeps no count; its rows are still all there.
let (bus, json) = s.ok("unit_interface", json!({"name": "bus"}));
assert!(bus.contains("\nmodports:\n"), "{bus}");
assert_eq!(rows_under(&bus, "modports:\n"), Some(2));
assert_eq!(json["modports"].as_array().unwrap().len(), 2);
// A parameter-only module's answer ends at its last parameter.
let (onlyp, _) = s.ok("unit_interface", json!({"name": "onlyp"}));
assert_eq!(onlyp, "module onlyp onlyp.sv:1\nparameters (2):\n W = 1\n D = 2\n");
}
// ---------------------------------------------------------------------------
// 3. `hierarchy`: the overrides, opt-in on the text, always in the JSON.
// ---------------------------------------------------------------------------
/// What c2e42b8 answered: overrides on every text line, capped at 200.
fn old_up() -> String {
let capped: String = format!("#({}", long_overrides()).chars().take(200).collect();
format!(
"3 instantiations\nleaf2 leaf2.sv:1\n user2.u_long {capped}… user2.sv:2\n user2.u_plain user2.sv:3\n user2.u_c #(.A(1) ) user2.sv:4\n"
)
}
fn old_down() -> String {
let capped: String = format!("#({}", long_overrides()).chars().take(200).collect();
format!(
"4 nodes\nuser2 user2.sv:1\n u_long : leaf2 {capped}…\n u_plain : leaf2\n u_c : leaf2 #(.A(1) )\n"
)
}
#[test]
fn qa_overrides_true_is_the_old_text_and_the_default_drops_only_the_segment() {
let tree = tree();
let mut s = Session::over(&tree);
let cases = [
(json!({"root": "leaf2", "direction": "up"}), old_up()),
(json!({"root": "user2"}), old_down()),
];
for (args, old) in cases {
let mut asked = args.clone();
asked["overrides"] = json!(true);
let (with, with_json) = s.ok("hierarchy", asked);
assert_eq!(with, old, "{args}");
let (plain, plain_json) = s.ok("hierarchy", args.clone());
assert_eq!(plain_json, with_json, "{args}: the JSON ignores the flag");
assert!(!plain.contains("#("), "{args}: {plain}");
assert!(!plain.contains('…'), "{args}: {plain}");
// Line for line, the default is the old line minus ` #(…)`, the
// segment being the node's JSON `overrides` as the old line capped it.
let nodes = with_json["nodes"].as_array().unwrap();
assert_eq!(plain.lines().count(), nodes.len() + 1, "{args}: count line + nodes");
for ((short, long), node) in plain.lines().zip(with.lines()).skip(1).zip(nodes) {
let expected = match node["overrides"].as_str() {
None => long.to_string(),
Some(full) if full.chars().count() > 200 => {
let capped: String = full.chars().take(200).collect();
long.replacen(&format!(" {capped}…"), "", 1)
}
Some(full) => long.replacen(&format!(" {full}"), "", 1),
};
assert_eq!(short, expected, "{long}");
}
// Every node carries `overrides`, uncapped in full where the site has one.
for node in with_json["nodes"].as_array().unwrap() {
assert!(node.as_object().unwrap().contains_key("overrides"), "{node}");
}
let full = format!("#({})", long_overrides());
assert!(with_json["nodes"].as_array().unwrap().iter().any(|n| n["overrides"] == full));
}
}
#[test]
fn qa_overrides_hold_under_paging_the_in_glob_and_depth() {
let tree = tree();
let mut s = Session::over(&tree);
let windows = [
json!({"root": "leaf2", "direction": "up", "limit": 1, "offset": 1}),
json!({"root": "leaf2", "direction": "up", "in": "user2.sv"}),
json!({"root": "leaf2", "direction": "up", "depth": 1}),
json!({}),
];
for args in windows {
let (plain, plain_json) = s.ok("hierarchy", args.clone());
let mut asked = args.clone();
asked["overrides"] = json!(true);
let (with, with_json) = s.ok("hierarchy", asked);
assert_eq!(plain_json, with_json, "{args}");
assert!(!plain.contains("#("), "{args}: {plain}");
assert_eq!(plain.lines().next(), with.lines().next(), "{args}: the count line");
assert_eq!(plain.lines().count(), with.lines().count(), "{args}");
}
let (page, _) = s.ok(
"hierarchy",
json!({"root": "leaf2", "direction": "up", "limit": 1, "offset": 1, "overrides": true}),
);
assert!(page.contains(" user2.u_plain user2.sv:3\n"), "{page}");
}
// ---------------------------------------------------------------------------
// 4. The arguments and the catalogue.
// ---------------------------------------------------------------------------
#[test]
fn qa_a_non_boolean_flag_is_refused_naming_the_field_and_null_means_the_default() {
let tree = tree();
let mut s = Session::over(&tree);
for bad in [json!("true"), json!(1), json!([true]), json!({})] {
let why = s.refused("unit_interface", json!({"name": "np", "template": bad}));
assert!(why.contains("`template`") && why.contains("true or false"), "{why}");
let why = s.refused("hierarchy", json!({"root": "user2", "overrides": bad}));
assert!(why.contains("`overrides`") && why.contains("true or false"), "{why}");
}
// `null` is taken as absent, as for every other flag.
let plain = s.ok("unit_interface", json!({"name": "np"}));
assert_eq!(s.ok("unit_interface", json!({"name": "np", "template": null})), plain);
let plain = s.ok("hierarchy", json!({"root": "user2"}));
assert_eq!(s.ok("hierarchy", json!({"root": "user2", "overrides": null})), plain);
// The flag belongs to its own tool only.
let why = s.refused("hierarchy", json!({"root": "user2", "template": true}));
assert!(why.contains("`template`"), "{why}");
let why = s.refused("unit_interface", json!({"name": "np", "overrides": true}));
assert!(why.contains("`overrides`"), "{why}");
}
#[test]
fn qa_the_catalogue_offers_both_flags_as_optional_booleans_and_stays_small() {
let tree = tree();
let mut s = Session::over(&tree);
let reply = s.request("tools/list", json!({}));
let size = reply["result"].to_string().len();
assert!(size <= 18_000, "tools/list is {size} bytes");
let tools = reply["result"]["tools"].as_array().unwrap();
for (tool, flag) in [("unit_interface", "template"), ("hierarchy", "overrides")] {
let entry = tools.iter().find(|t| t["name"] == tool).unwrap();
let schema = &entry["inputSchema"];
assert_eq!(schema["properties"][flag]["type"], "boolean", "{tool}.{flag}");
let required = schema["required"].as_array().cloned().unwrap_or_default();
assert!(!required.contains(&json!(flag)), "{tool}.{flag} is optional");
}
let unit = tools.iter().find(|t| t["name"] == "unit_interface").unwrap();
assert!(unit["description"].as_str().unwrap().contains("`template: true`"));
let hierarchy = tools.iter().find(|t| t["name"] == "hierarchy").unwrap();
assert!(!hierarchy["description"].as_str().unwrap().contains("#("), "no longer promised");
let instructions = s.init["result"]["instructions"].as_str().unwrap();
assert!(instructions.chars().count() <= 900, "{}", instructions.chars().count());
assert!(instructions.contains("overrides: true"), "{instructions}");
assert!(!instructions.contains("(instances, overrides)"), "{instructions}");
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
for word in words.filter(|w| w.contains('_') && *w != "dry_run") {
assert!(names.contains(&word), "the instructions name `{word}`, which is not a tool");
}
}
+37 -24
View File
@@ -276,8 +276,8 @@ fn qa_everything_but_initialize_and_ping_waits_for_the_handshake() {
assert!(s.pings());
s.initialize();
// M2 added five tools (defines, definition, references, hierarchy,
// diagnostics) to M1's six; M3 added twelve edit tools.
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 23);
// diagnostics) to M1's six; M3 added twelve edit tools; M4 three more.
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 26);
}
#[test]
@@ -430,7 +430,8 @@ fn qa_an_escaped_identifier_unit_is_listed_described_and_instantiable() {
)]);
let mut s = Session::ready(&scratch);
assert!(s.text("list_units", json!({})).contains("module \\my-mod 1"));
let answer = s.text("unit_interface", json!({"name": "\\my-mod"}));
// feedback-3: the template is opt-in.
let answer = s.text("unit_interface", json!({"name": "\\my-mod", "template": true}));
assert!(answer.starts_with("module \\my-mod esc.sv:1\n"), "{answer}");
// The template must still be legal: an escaped name ends at whitespace.
assert!(answer.contains("\\my-mod \\u_my-mod ("), "{answer}");
@@ -462,7 +463,7 @@ fn qa_a_typed_parameter_keeps_its_default_and_a_localparam_is_not_offered() {
"module tp #(parameter type T = logic [3:0], parameter int unsigned N = 4,\n localparam int L = 2) (input T a);\nendmodule\n",
)]);
let mut s = Session::ready(&scratch);
let result = s.call("unit_interface", json!({"name": "tp"}));
let result = s.call("unit_interface", json!({"name": "tp", "template": true}));
let params = &result["structuredContent"]["parameters"];
assert_eq!(
params,
@@ -477,14 +478,17 @@ fn qa_crlf_files_keep_their_line_numbers_and_read_item_returns_the_exact_bytes()
let scratch = Scratch::with(&[("crlf.sv", text)]);
let mut s = Session::ready(&scratch);
let outline = s.text("outline", json!({"file": "crlf.sv"}));
assert_eq!(outline, "crlf.sv\n module crlf 2-9\n port clk 3\n port q 4\n var x 6\n");
assert_eq!(
outline,
"4 entries\ncrlf.sv\n module crlf 2-9\n port clk 3\n port q 4\n var x 6\n"
);
let result = s.call("read_item", json!({"file": "crlf.sv", "item": "always@8"}));
assert_eq!(result["structuredContent"]["lines"], json!([7, 8]));
assert_eq!(result["structuredContent"]["text"], "always_ff @(posedge clk)\r\n q <= x;");
let module = s.call("read_item", json!({"file": "crlf.sv", "item": "crlf"}));
let start = text.find("module").unwrap();
assert_eq!(module["structuredContent"]["text"], &text[start..text.len() - 2]);
assert_eq!(s.text("list_units", json!({})), "crlf.sv\n module crlf 2\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\ncrlf.sv\n module crlf 2\n");
}
#[test]
@@ -495,7 +499,10 @@ fn qa_multibyte_text_before_an_item_keeps_lines_right() {
)]);
let mut s = Session::ready(&scratch);
let outline = s.text("outline", json!({"file": "utf.sv"}));
assert_eq!(outline, "utf.sv\n module utf 2-4\n port a 2\n var z 2\n var w 3\n");
assert_eq!(
outline,
"4 entries\nutf.sv\n module utf 2-4\n port a 2\n var z 2\n var w 3\n"
);
let w = s.call("read_item", json!({"file": "utf.sv", "item": "w"}));
assert_eq!(w["structuredContent"]["text"], "logic w;");
assert_eq!(w["structuredContent"]["lines"], json!([3, 3]));
@@ -647,7 +654,7 @@ fn qa_an_escaped_name_holding_at_or_colon_is_selectable_by_itself() {
fn qa_rename_then_recreate_in_the_same_mtime_second_is_seen() {
let scratch = Scratch::with(&[("a.sv", "module alpha; endmodule\n")]);
let mut s = Session::ready(&scratch);
assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n");
let old = mtime(&scratch.path("a.sv"));
fs::rename(scratch.path("a.sv"), scratch.path("b.sv")).unwrap();
scratch.write("a.sv", b"module gamma; endmodule\n");
@@ -670,7 +677,7 @@ fn qa_a_same_size_rewrite_with_the_same_mtime_is_caught_by_the_racy_rule() {
let old = mtime(&scratch.path("a.sv"));
scratch.write("a.sv", b"module delta; endmodule\n");
set_mtime(&scratch.path("a.sv"), old);
assert_eq!(s.text("list_units", json!({})), "a.sv\n module delta 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module delta 1\n");
let answer = s.text("unit_interface", json!({"name": "delta"}));
assert!(answer.starts_with("module delta a.sv:1"), "{answer}");
}
@@ -688,7 +695,7 @@ fn qa_a_same_size_rewrite_that_restores_an_old_mtime_is_seen() {
s.text("list_units", json!({}));
scratch.write("c.sv", b"module chxrlie; endmodule\n");
set_mtime(&scratch.path("c.sv"), long_ago);
assert_eq!(s.text("list_units", json!({})), "c.sv\n module chxrlie 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chxrlie 1\n");
}
#[test]
@@ -700,7 +707,10 @@ fn qa_a_new_file_in_a_new_subdirectory_appears_at_the_next_walk() {
// project_overview always walks; every later call sees the file.
let overview = s.call("project_overview", json!({}));
assert_eq!(overview["structuredContent"]["files"], 2);
assert_eq!(s.text("list_units", json!({"glob": "newbie"})), "n1/n2/n.sv\n module newbie 1\n");
assert_eq!(
s.text("list_units", json!({"glob": "newbie"})),
"1 unit\nn1/n2/n.sv\n module newbie 1\n"
);
assert!(s.text("unit_interface", json!({"name": "newbie"})).contains("input k"));
}
@@ -729,7 +739,7 @@ fn qa_a_file_growing_past_one_mib_drops_out_of_the_index() {
big.extend(std::iter::repeat_n(b'x', 1024 * 1024));
big.push(b'\n');
scratch.write("a.sv", &big);
assert_eq!(s.text("list_units", json!({})), "c.sv\n module charlie 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module charlie 1\n");
let overview = s.call("project_overview", json!({}));
assert_eq!(overview["structuredContent"]["skipped_large"], 1);
assert_eq!(overview["structuredContent"]["files"], 1);
@@ -745,7 +755,7 @@ fn qa_a_gitignore_added_after_startup_drops_its_files_at_the_next_walk() {
assert!(s.text("list_units", json!({})).contains("generated"));
scratch.write(".gitignore", b"gen/\n");
s.text("project_overview", json!({}));
assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n");
}
#[test]
@@ -792,7 +802,7 @@ fn qa_the_walk_does_not_index_files_outside_the_roots_through_symlinks() {
let scratch = Scratch::with(SMALL);
std::os::unix::fs::symlink(outside.path("secret.sv"), scratch.path("link.sv")).unwrap();
let mut s = Session::ready(&scratch);
assert_eq!(s.text("list_units", json!({})), "x.sv\n module x 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\nx.sv\n module x 1\n");
s.refusal("unit_interface", json!({"name": "secret_mod"}));
}
@@ -808,11 +818,11 @@ fn qa_nested_roots_index_each_file_once() {
s.initialize();
assert_eq!(
s.text("list_units", json!({})),
"a.sv\n module alpha 1\nsub/b.sv\n module beta 1\n"
"2 units\na.sv\n module alpha 1\nsub/b.sv\n module beta 1\n"
);
assert_eq!(s.call("project_overview", json!({}))["structuredContent"]["files"], 2);
// The inner root still resolves its own relative paths.
assert!(s.text("outline", json!({"file": "b.sv"})).starts_with("sub/b.sv\n"));
assert!(s.text("outline", json!({"file": "b.sv"})).starts_with("1 entry\nsub/b.sv\n"));
}
#[test]
@@ -820,7 +830,7 @@ fn qa_a_relative_root_is_resolved_against_the_working_directory() {
let scratch = Scratch::with(&[("rtl/sub/b.sv", "module beta; endmodule\n")]);
let mut s = Session::spawn_in(&["--root", "rtl/sub"], Some(&scratch.0));
s.initialize();
assert_eq!(s.text("list_units", json!({})), "b.sv\n module beta 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\nb.sv\n module beta 1\n");
let roots = s.call("project_overview", json!({}))["structuredContent"]["roots"].clone();
assert_eq!(roots, json!([scratch.path("rtl/sub")]));
}
@@ -889,7 +899,7 @@ fn qa_rework_a_symlinked_directory_leaving_the_root_is_dropped_warned_and_a_loop
std::os::unix::fs::symlink("rtl/in.sv", scratch.path("alias.sv")).unwrap();
std::os::unix::fs::symlink(&scratch.0, outside.path("back")).unwrap();
let mut s = Session::ready(&scratch);
assert_eq!(s.text("list_units", json!({})), "rtl/in.sv\n module inner_mod 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\nrtl/in.sv\n module inner_mod 1\n");
let overview = s.call("project_overview", json!({}))["structuredContent"].clone();
assert_eq!(overview["files"], 1);
let warnings = overview["warnings"].as_array().unwrap();
@@ -962,11 +972,14 @@ fn qa_rework_every_by_name_tool_finds_a_file_written_just_now() {
scratch.write("m1.sv", b"module fresh1 (input k1); endmodule\n");
assert!(s.text("unit_interface", json!({"name": "fresh1"})).contains("input k1"));
scratch.write("m2.sv", b"module fresh2 (input k2); endmodule\n");
assert_eq!(s.text("list_units", json!({"glob": "fresh2"})), "m2.sv\n module fresh2 1\n");
assert_eq!(
s.text("list_units", json!({"glob": "fresh2"})),
"1 unit\nm2.sv\n module fresh2 1\n"
);
scratch.write("n/m/m3.sv", b"module fresh3 (input k3); endmodule\n");
assert_eq!(
s.text("search_symbols", json!({"query": "fresh3"})),
"n/m/m3.sv\n module fresh3 1\n"
"1 symbol\nn/m/m3.sv\n module fresh3 1\n"
);
// A package member and a class in a new file, by `pkg::cls`.
scratch.write("p.sv", b"package fp; class fc; int f; endclass endpackage\n");
@@ -986,7 +999,7 @@ fn qa_rework_a_legitimate_miss_does_not_make_later_hits_walk() {
assert_eq!(s.text("search_symbols", json!({"query": "zzqq"})), "no symbols match\n");
}
scratch.write("late.sv", b"module late; endmodule\n");
assert_eq!(s.text("list_units", json!({})), "x.sv\n module x 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\nx.sv\n module x 1\n");
assert!(s.text("outline", json!({"file": "late.sv"})).contains("module late 1"));
s.text("project_overview", json!({}));
assert!(s.text("list_units", json!({})).contains("late.sv"));
@@ -1019,7 +1032,7 @@ fn qa_rework_a_file_that_stops_being_utf8_is_warned_and_leaves_the_index() {
let mut s = Session::ready(&scratch);
assert!(s.text("list_units", json!({})).contains("beta"));
scratch.write("b.sv", b"module beta; // \xe9\xff\nendmodule\n");
assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n");
let overview = s.call("project_overview", json!({}))["structuredContent"].clone();
assert_eq!(overview["warnings"], json!(["b.sv: not UTF-8 text"]));
assert_eq!(overview["files"], 1);
@@ -1041,10 +1054,10 @@ fn qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen() {
s.text("list_units", json!({}));
fs::rename(scratch.path("stash/c.txt"), scratch.path("c.sv")).unwrap();
assert_eq!(mtime(&scratch.path("c.sv")), long_ago);
assert_eq!(s.text("list_units", json!({})), "c.sv\n module chxrlie 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chxrlie 1\n");
// cp -p of a same-size file with the same old mtime: ctime moves.
fs::write(scratch.path("stash/d.txt"), "module chyrlie; endmodule\n").unwrap();
fs::copy(scratch.path("stash/d.txt"), scratch.path("c.sv")).unwrap();
set_mtime(&scratch.path("c.sv"), long_ago);
assert_eq!(s.text("list_units", json!({})), "c.sv\n module chyrlie 1\n");
assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chyrlie 1\n");
}
+30 -22
View File
@@ -342,7 +342,7 @@ fn qa_byte_columns_hold_after_multibyte_text_and_in_crlf_files() {
}
assert_eq!(s.sites(json!({"file": "crlf.sv", "line": 3, "name": "cc"})), ["crlf.sv:2:9 var"]);
let crlf = s.text("references", json!({"file": "crlf.sv", "line": 3, "col": 10}));
assert_eq!(crlf, "crlf.sv\n 2:9 logic cc;\n 3:10 assign cc = a;\n");
assert_eq!(crlf, "2 hits\ncrlf.sv\n 2:9 logic cc;\n 3:10 assign cc = a;\n");
assert!(s.pings());
}
@@ -482,12 +482,13 @@ const HIER: &[(&str, &str)] = &[
fn qa_hierarchy_terminates_on_self_and_mutual_recursion() {
let scratch = Scratch::with(HIER);
let mut s = Session::ready(&scratch);
let selfm = s.text("hierarchy", json!({"root": "selfm", "depth": 20}));
assert_eq!(selfm, "selfm self.sv:1\n u_s : selfm #(.N(N-1)) (recursive)\n");
// feedback-3: the overrides are on the text line only on request.
let selfm = s.text("hierarchy", json!({"root": "selfm", "depth": 20, "overrides": true}));
assert_eq!(selfm, "2 nodes\nselfm self.sv:1\n u_s : selfm #(.N(N-1)) (recursive)\n");
let mutual = s.text("hierarchy", json!({"root": "ma", "depth": 20}));
assert_eq!(mutual, "ma mutual.sv:1\n u_b : mb\n u_a : ma (recursive)\n");
assert_eq!(mutual, "3 nodes\nma mutual.sv:1\n u_b : mb\n u_a : ma (recursive)\n");
let up = s.text("hierarchy", json!({"root": "ma", "direction": "up", "depth": 20}));
assert_eq!(up, "ma mutual.sv:1\n mb.u_a mutual.sv:2\n ma.u_b mutual.sv:1 (recursive)\n mtop.u mutual.sv:3\n");
assert_eq!(up, "3 instantiations\nma mutual.sv:1\n mb.u_a mutual.sv:2\n ma.u_b mutual.sv:1 (recursive)\n mtop.u mutual.sv:3\n");
}
#[test]
@@ -495,7 +496,8 @@ fn qa_hierarchy_depth_is_capped_and_bad_arguments_are_schema_refusals() {
let scratch = Scratch::with(&[("chain.sv", &chain(30))]);
let mut s = Session::ready(&scratch);
let deep = s.text("hierarchy", json!({"root": "c0", "depth": 20}));
assert_eq!(deep.lines().count(), 21, "{deep}");
// The count line, the root, twenty levels.
assert_eq!(deep.lines().count(), 22, "{deep}");
assert!(deep.ends_with("u19 : c20\n") && !deep.contains("c21"), "{deep}");
for depth in [json!(0), json!(-1), json!(2.5), json!("3")] {
let refused = s.refusal("hierarchy", json!({"root": "c0", "depth": depth}));
@@ -527,7 +529,7 @@ fn qa_hierarchy_marks_not_modules_duplicates_and_two_parents() {
assert!(refused.contains(&format!("`{root}`")), "{refused}");
}
let dupe = s.text("hierarchy", json!({"root": "usedupe"}));
assert_eq!(dupe, "usedupe usedupe.sv:1\n u_d : dupe (declared 2 times)\n");
assert_eq!(dupe, "2 nodes\nusedupe usedupe.sv:1\n u_d : dupe (declared 2 times)\n");
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"}));
assert!(up.contains(" p1.u_l1 p1.sv:1\n p1.u_l2 p1.sv:1\n p2.u_l p2.sv:1\n"), "{up}");
}
@@ -551,7 +553,7 @@ fn qa_finding_4_every_instance_of_one_statement_shows_only_the_overrides() {
let result = s.call("hierarchy", json!({"root": "ov"}));
assert_eq!(result["structuredContent"]["nodes"][3]["instance"], "u_b");
assert_eq!(result["structuredContent"]["nodes"][3]["overrides"], "#(.W(2))");
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"}));
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up", "overrides": true}));
assert!(up.contains(" ov.u_b #(.W(2)) ov.sv:4\n"), "{up}");
}
@@ -593,14 +595,14 @@ fn qa_diagnostics_follow_each_files_own_config_directory() {
// Root config: select 3, ignore no-tabs, length 45, a/waived.sv waived.
assert_eq!(
s.text("diagnostics", json!({"file": "a/m.sv"})),
"a/m.sv\n 2:46 style line is 50 characters; the limit is 45 [line-length]\n"
"1 finding\na/m.sv\n 2:46 style line is 50 characters; the limit is 45 [line-length]\n"
);
assert_eq!(s.text("diagnostics", json!({"file": "a/waived.sv"})), "no findings\n");
// b/lucisv.toml: its own select (no-tabs back) and its own line-length
// 60, which the 59-character line 2 is inside (45 would flag it).
assert_eq!(
s.text("diagnostics", json!({"file": "b/n.sv"})),
"b/n.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n"
"1 finding\nb/n.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n"
);
// `rules` replaces select; the config's ignore still applies.
assert_eq!(
@@ -696,7 +698,7 @@ fn qa_defines_list_every_definition_and_never_pick_one() {
("d.sv", "module d; localparam int P = `TWICE; endmodule\n"),
]);
let mut s = Session::ready(&scratch);
let twice = "a.svh\n 1 `define TWICE 1\nb.svh\n 1 `define TWICE 2\n";
let twice = "2 defines\na.svh\n 1 `define TWICE 1\nb.svh\n 1 `define TWICE 2\n";
assert_eq!(s.text("defines", json!({"name": "TWICE"})), twice);
assert_eq!(s.text("defines", json!({"name": "`TWICE"})), twice);
assert_eq!(
@@ -711,7 +713,7 @@ fn qa_defines_list_every_definition_and_never_pick_one() {
assert_eq!(s.text("defines", json!({"name": "NOPE"})), "no defines\n");
assert_eq!(
s.text("defines", json!({"file": "b.svh", "name": "TWICE"})),
"b.svh\n 1 `define TWICE 2\n 2 `undef TWICE\n"
"2 defines\nb.svh\n 1 `define TWICE 2\n 2 `undef TWICE\n"
);
assert_eq!(s.text("defines", json!({"file": "a.svh", "name": "NOPE"})), "no defines\n");
let missing = s.refusal("defines", json!({"file": "nope.sv"}));
@@ -745,7 +747,9 @@ fn qa_resources_refuse_what_they_cannot_name_and_decode_escapes() {
] {
let reply = read(&mut s, uri);
let text = reply["result"]["contents"][0]["text"].as_str().unwrap_or("");
assert!(text.starts_with(starts), "{uri}: {reply}");
// The outline's count line, then the file.
let (_, file) = text.split_once('\n').unwrap_or_default();
assert!(file.starts_with(starts), "{uri}: {reply}");
}
for uri in [
"lucisv://unit/dup",
@@ -791,16 +795,19 @@ fn qa_references_and_hierarchy_follow_edits_and_deletions() {
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3", "top.sv:4:3"]);
assert_eq!(
s.text("hierarchy", json!({"root": "top"})),
"top top.sv:1\n u1 : leaf\n u2 : leaf\n"
"3 nodes\ntop top.sv:1\n u1 : leaf\n u2 : leaf\n"
);
fs::remove_file(scratch.path("top.sv")).unwrap();
assert!(s.refusal("hierarchy", json!({"root": "top"})).contains("`top`"));
assert_eq!(s.text("hierarchy", json!({"root": "leaf", "direction": "up"})), "leaf leaf.sv:1\n");
assert_eq!(
s.text("hierarchy", json!({"root": "leaf", "direction": "up"})),
"0 instantiations\nleaf leaf.sv:1\n"
);
scratch.write("other.sv", "module other; leaf u9 (.a()); endmodule\n");
fs::remove_file(scratch.path("leaf.sv")).unwrap();
assert_eq!(
s.text("hierarchy", json!({"root": "other"})),
"other other.sv:1\n u9 : leaf (not indexed)\n"
"2 nodes\nother other.sv:1\n u9 : leaf (not indexed)\n"
);
assert!(s.refusal("definition", json!({"name": "leaf"})).contains("`leaf`"));
}
@@ -899,10 +906,10 @@ fn qa_recheck_overrides_split_across_lines_and_comments_between_instances() {
]);
let mut s = Session::ready(&scratch);
assert_eq!(
s.text("hierarchy", json!({"root": "ov"})),
"ov ov.sv:1\n u_a : leaf #(.W(2))\n u_b : leaf #(.W(2))\n u_c : leaf #(.W(2))\n u_d : leaf\n u_e : leaf\n u_f : leaf\n u_g : leaf #( .W(3) )\n u_h : leaf #( .W(3) )\n u_i : leaf #( .W(3) )\n u_j : leaf #(.W(4))\n u_k : leaf #(.W(5))\n u_l : leaf\n u_m : leaf\n"
s.text("hierarchy", json!({"root": "ov", "overrides": true})),
"14 nodes\nov ov.sv:1\n u_a : leaf #(.W(2))\n u_b : leaf #(.W(2))\n u_c : leaf #(.W(2))\n u_d : leaf\n u_e : leaf\n u_f : leaf\n u_g : leaf #( .W(3) )\n u_h : leaf #( .W(3) )\n u_i : leaf #( .W(3) )\n u_j : leaf #(.W(4))\n u_k : leaf #(.W(5))\n u_l : leaf\n u_m : leaf\n"
);
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"}));
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up", "overrides": true}));
assert!(up.contains(" ov.u_i #( .W(3) ) ov.sv:9\n ov.u_j #(.W(4)) ov.sv:10\n"), "{up}");
}
@@ -920,7 +927,8 @@ fn qa_recheck_depth_twenty_is_the_schema_maximum() {
.clone();
let depth = &hierarchy["inputSchema"]["properties"]["depth"];
assert_eq!((depth["minimum"].clone(), depth["maximum"].clone()), (json!(1), json!(20)));
assert_eq!(s.text("hierarchy", json!({"root": "c0", "depth": 20})).lines().count(), 21);
// The count line, the root, twenty levels.
assert_eq!(s.text("hierarchy", json!({"root": "c0", "depth": 20})).lines().count(), 22);
let refused = s.refusal("hierarchy", json!({"root": "c0", "depth": 21}));
assert!(refused.contains("from 1 to 20"), "{refused}");
}
@@ -1038,7 +1046,7 @@ fn qa_recheck_unused_waivers_match_lucisv_check_of_the_tree() {
let mut s = Session::ready(&scratch);
assert_eq!(
s.text("diagnostics", json!({})),
"w.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n"
"1 finding\nw.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n"
);
assert_eq!(s.text("diagnostics", json!({"rules": "no-tabs"})), "no findings\n");
assert_eq!(s.text("diagnostics", json!({"file": "m.sv"})), "no findings\n");
@@ -1055,7 +1063,7 @@ fn qa_recheck_one_files_diagnostics_are_its_lines_of_lucisv_check_dot() {
let mut s = Session::ready(&scratch);
assert_eq!(
s.text("diagnostics", json!({"file": "top.sv"})),
"top.sv\n 2:12 error `leaf` declares no port `b` [unknown-port]\n"
"1 finding\ntop.sv\n 2:12 error `leaf` declares no port `b` [unknown-port]\n"
);
assert_eq!(s.text("diagnostics", json!({"file": "leaf.sv"})), "no findings\n");
}
File diff suppressed because it is too large. Load diff
+710
View File
@@ -0,0 +1,710 @@
//! QA attacks on lane M6 (the index caches and the rule-6 ruling),
//! 2026-09-23.
//!
//! Every test spawns the real binary over a scratch copy of the `design`
//! fixture with `--index-cache` pointing at a scratch directory, as a host
//! would. The wrong-record hunt comes first: a record may only ever stand in
//! for the parse of exactly the bytes it was read from, so every store below
//! that is not exactly right must cost a parse — never an answer — and the
//! language server's store must be left byte-identical.
//!
//! A test that pins a QA finding asserts the *correct* behaviour and is
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
//! numbered as in the QA log of `docs/features/mcp-cache-and-census/README.md`.
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdout, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime};
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;
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// A fresh copy of `tests/fixtures/design` under `<dir>/src`, and `<dir>/cache`
/// (not created) 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-qa-m6-{}-{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 file(&self, rel: &str) -> PathBuf {
self.src().join(rel)
}
fn cache(&self) -> PathBuf {
self.0.join("cache")
}
fn editor_store(&self) -> PathBuf {
self.cache().join("index-cache")
}
fn own_store(&self) -> PathBuf {
self.cache().join("index-cache-mcp")
}
/// Write the language server's store from `lines`, one per line, with a
/// final newline.
fn write_editor_store(&self, lines: &[String]) {
fs::create_dir_all(self.cache()).unwrap();
fs::write(self.editor_store(), lines.join("\n") + "\n").unwrap();
}
}
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
}
fn header() -> String {
format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}")
}
/// The encoded facts `path` would have if its bytes were `text`.
fn facts_of(path: &Path, text: &str) -> String {
FileFacts::of(path.to_path_buf(), text).encode().unwrap()
}
/// One record line with a *valid* checksum: `content` as the hash field,
/// `facts` as the record — whatever they describe.
fn line(content: u64, facts: &str) -> String {
format!("{content:016x}\t{facts}\t{:016x}", content_hash(facts.as_bytes()))
}
/// The honest record of `path` as it is on disk.
fn record(path: &Path) -> String {
let bytes = fs::read(path).unwrap();
line(content_hash(&bytes), &facts_of(path, std::str::from_utf8(&bytes).unwrap()))
}
/// The honest store over every source file.
fn honest_store(scratch: &Scratch) -> Vec<String> {
let mut lines = vec![header()];
lines.extend(files(&scratch.src()).iter().map(|path| record(path)));
lines
}
/// One server over the scratch design.
struct Session {
child: Child,
next_id: i64,
stdout: BufReader<ChildStdout>,
}
impl Session {
/// With `--index-cache cache` when given.
fn start(scratch: &Scratch, cache: Option<&Path>) -> Session {
let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"));
command.arg("--root").arg(scratch.src());
if let Some(cache) = cache {
command.arg("--index-cache").arg(cache);
}
let mut child = command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());
let mut session = Session { child, next_id: 0, stdout };
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
session
}
/// The usual shape: `--index-cache <scratch>/cache`.
fn cached(scratch: &Scratch) -> Session {
Session::start(scratch, Some(&scratch.cache()))
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let line =
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
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's whole result (success or refusal).
fn call(&mut self, tool: &str, arguments: Value) -> Value {
self.request("tools/call", json!({"name": tool, "arguments": arguments}))["result"].clone()
}
/// A tool call that must succeed: its text.
fn text(&mut self, tool: &str, arguments: Value) -> String {
let result = self.call(tool, arguments);
assert_eq!(result["isError"], false, "{tool}: {result}");
result["content"][0]["text"].as_str().unwrap().to_string()
}
/// Close stdin, as a host does; 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
}
}
/// The startup line's tail for `E` editor and `O` own hits.
fn reused(editor: usize, own: usize) -> String {
format!(" ms ({editor} from the editor's cache, {own} from its own)\n")
}
/// A session that asks what the tests below check the index with; its
/// answers and stderr.
fn probe(scratch: &Scratch, cache: Option<&Path>) -> (Vec<String>, String) {
let mut session = Session::start(scratch, cache);
let answers = [
("list_units", json!({})),
("unit_interface", json!({"name": "leaf"})),
("unit_interface", json!({"name": "top"})),
("outline", json!({"file": "rtl/top.sv"})),
("outline", json!({"file": "rtl/leaf.sv"})),
("search_symbols", json!({"query": "word"})),
("references", json!({"name": "leaf"})),
("hierarchy", json!({"root": "top"})),
("defines", json!({})),
]
.into_iter()
.map(|(tool, args)| session.text(tool, args))
.collect();
(answers, session.end())
}
fn hash_file(path: &Path) -> u64 {
content_hash(&fs::read(path).unwrap())
}
/// Everything the store's owner could notice changed: bytes, mtime, mode.
#[cfg(unix)]
fn fingerprint(path: &Path) -> (u64, SystemTime, u32) {
use std::os::unix::fs::PermissionsExt;
let meta = fs::metadata(path).unwrap();
(hash_file(path), meta.modified().unwrap(), meta.permissions().mode())
}
/// Temporary files left in `dir`.
fn temp_files(dir: &Path) -> Vec<String> {
fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.filter(|name| name.ends_with(".tmp"))
.collect()
}
// ---------------------------------------------------------------------------
// 1. The wrong-record hunt.
// ---------------------------------------------------------------------------
/// Two records' facts swapped, each checksum recomputed so every line is
/// valid: the record under `leaf.sv`'s hash now describes `top.sv` and the
/// other way round. The store is keyed by the path *inside* the facts, so
/// each lands under (other path, this hash) and matches no file: both are
/// parsed, and the answers are the cold ones.
#[test]
fn qa_swapped_records_with_valid_checksums_are_never_served() {
let scratch = Scratch::new();
let (cold, _) = probe(&scratch, None);
let (leaf, top) = (scratch.file("rtl/leaf.sv"), scratch.file("rtl/top.sv"));
let text = |path: &Path| fs::read_to_string(path).unwrap();
let mut lines = vec![header()];
for path in files(&scratch.src()) {
if path != leaf && path != top {
lines.push(record(&path));
}
}
lines.push(line(hash_file(&leaf), &facts_of(&top, &text(&top))));
lines.push(line(hash_file(&top), &facts_of(&leaf, &text(&leaf))));
scratch.write_editor_store(&lines);
let (warm, stderr) = probe(&scratch, Some(&scratch.cache()));
assert!(stderr.contains(&reused(FILES - 2, 0)), "{stderr}");
assert_eq!(warm, cold, "the answers are a cold start's");
}
/// Records for a file that no longer exists and for one outside every root
/// (it exists, beside the root): neither module is indexed, and neither
/// record survives into the store this server writes.
#[test]
fn qa_records_for_gone_files_or_outside_the_roots_are_not_indexed_nor_kept() {
let scratch = Scratch::new();
let outside = scratch.0.join("outside.sv");
fs::write(&outside, "module outside_root; endmodule\n").unwrap();
let ghost = scratch.file("rtl/ghost.sv");
let ghost_text = "module ghost_unit; endmodule\n";
let mut lines = honest_store(&scratch);
lines.push(record(&outside));
lines.push(line(content_hash(ghost_text.as_bytes()), &facts_of(&ghost, ghost_text)));
scratch.write_editor_store(&lines);
let mut session = Session::cached(&scratch);
let units = session.text("list_units", json!({}));
assert!(!units.contains("outside_root") && !units.contains("ghost_unit"), "{units}");
let stderr = session.end();
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
let own = fs::read_to_string(scratch.own_store()).unwrap();
assert_eq!(own.lines().count(), 1 + FILES, "one record per indexed file");
assert!(!own.contains("outside.sv") && !own.contains("ghost.sv"), "{own}");
}
/// The language server appends: one path may have a record for an older
/// version of the file and one for the current. Keyed by (path, hash), both
/// are held, and the one whose hash is the file's bytes is served — here the
/// *older* one, after the file was put back. Two records for one (path, hash)
/// with different facts: the later line wins, as in the language server
/// (`IndexCache::open`); with the honest record last, the answer is right.
#[test]
fn qa_several_records_for_one_path_serve_only_the_bytes_on_disk() {
let scratch = Scratch::new();
let leaf = scratch.file("rtl/leaf.sv");
let original = fs::read_to_string(&leaf).unwrap();
let edited = original.replace("module leaf", "module leaf_v2");
let mut lines = honest_store(&scratch);
// A record for the edited version (not on disk), then a checksum-valid
// record under the current hash describing the edited text, then the
// honest one again: the last line for (leaf.sv, hash) wins.
lines.push(line(content_hash(edited.as_bytes()), &facts_of(&leaf, &edited)));
lines.push(line(content_hash(original.as_bytes()), &facts_of(&leaf, &edited)));
lines.push(record(&leaf));
scratch.write_editor_store(&lines);
let mut session = Session::cached(&scratch);
let units = session.text("list_units", json!({}));
assert!(units.contains("leaf") && !units.contains("leaf_v2"), "{units}");
session.end();
// Now the edited version is on disk: its own record serves it.
fs::write(&leaf, &edited).unwrap();
fs::remove_file(scratch.own_store()).unwrap();
let mut session = Session::cached(&scratch);
let units = session.text("list_units", json!({}));
assert!(units.contains("leaf_v2"), "{units}");
let stderr = session.end();
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
}
/// A store whose lines end `\r\n` (an editor or a checkout rewrote it): the
/// `\r` is stripped the way `str::lines` and the language server strip it,
/// the checksums still hold over the facts, and the answers are cold's.
#[test]
fn qa_a_crlf_store_is_read_as_the_language_server_reads_it() {
let scratch = Scratch::new();
let (cold, _) = probe(&scratch, None);
fs::create_dir_all(scratch.cache()).unwrap();
fs::write(scratch.editor_store(), honest_store(&scratch).join("\r\n") + "\r\n").unwrap();
let before = hash_file(&scratch.editor_store());
let (warm, stderr) = probe(&scratch, Some(&scratch.cache()));
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
assert_eq!(warm, cold);
assert_eq!(hash_file(&scratch.editor_store()), before);
}
/// Headers one step away from this build's: each store is ignored whole with
/// exactly one stderr line, the index is cold, the file byte-identical.
#[test]
fn qa_header_near_misses_are_ignored_whole_and_left_byte_identical() {
let (major_minor, patch) = VERSION.rsplit_once('.').unwrap();
let next_patch = format!("{major_minor}.{}", patch.parse::<u32>().unwrap() + 1);
let headers = [
format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{next_patch}"),
format!("lucisv-index-cache\t2\t{}\t{VERSION}", FACTS_FORMAT + 1),
format!("lucisv-index-cache\t2\t{}\t{VERSION}", FACTS_FORMAT - 1),
format!("lucisv-index-cache\t1\t{FACTS_FORMAT}\t{VERSION}"),
format!("lucisv-index-cache\t3\t{FACTS_FORMAT}\t{VERSION}"),
format!("{} ", header()),
format!("\u{feff}{}", header()),
format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}\textra"),
];
for first in headers {
let scratch = Scratch::new();
let mut lines = honest_store(&scratch);
lines[0] = first.clone();
scratch.write_editor_store(&lines);
let before = hash_file(&scratch.editor_store());
let mut session = Session::cached(&scratch);
assert!(session.text("list_units", json!({})).contains("leaf"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, 0)), "{first:?}: {stderr}");
assert_eq!(stderr.matches("ignoring the index cache").count(), 1, "{first:?}: {stderr}");
assert_eq!(hash_file(&scratch.editor_store()), before, "{first:?}");
}
}
// ---------------------------------------------------------------------------
// 2. The read-only promise and the own store's writes.
// ---------------------------------------------------------------------------
/// An empty store and a header-only store are silent cold starts; so is a
/// directory where the editor's store would be.
#[test]
fn qa_empty_stores_and_a_directory_named_index_cache_are_silent_cold_starts() {
for shape in ["empty", "header only", "directory"] {
let scratch = Scratch::new();
fs::create_dir_all(scratch.cache()).unwrap();
match shape {
"empty" => fs::write(scratch.editor_store(), "").unwrap(),
"header only" => fs::write(scratch.editor_store(), header() + "\n").unwrap(),
_ => fs::create_dir(scratch.editor_store()).unwrap(),
}
let mut session = Session::cached(&scratch);
assert!(session.text("list_units", json!({})).contains("leaf"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, 0)), "{shape}: {stderr}");
assert_eq!(stderr.lines().count(), 1, "{shape}: only the startup line: {stderr}");
assert!(scratch.own_store().is_file(), "{shape}");
}
}
/// A directory where this server's own store goes: the read is a silent
/// miss, the write fails with one stderr line, no temporary file is left,
/// and the answers were right.
#[test]
fn qa_a_directory_named_index_cache_mcp_costs_one_line_and_leaves_no_temp() {
let scratch = Scratch::new();
fs::create_dir_all(scratch.own_store()).unwrap();
let mut session = Session::cached(&scratch);
assert!(session.text("unit_interface", json!({"name": "leaf"})).contains("module leaf"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert!(scratch.own_store().is_dir(), "the directory is left alone");
assert!(temp_files(&scratch.cache()).is_empty(), "{:?}", temp_files(&scratch.cache()));
}
/// `--index-cache` naming a file, not a directory: the stores cannot be read
/// under it (a silent miss), the write fails with one line, and the file is
/// byte-identical.
#[test]
fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
let scratch = Scratch::new();
let file = scratch.0.join("not-a-dir");
fs::write(&file, "keep me\n").unwrap();
let mut session = Session::start(&scratch, Some(&file));
assert!(session.text("list_units", json!({})).contains("leaf"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert_eq!(fs::read_to_string(&file).unwrap(), "keep me\n");
}
/// A cache directory with no permissions at all (mode 000, holding a whole
/// honest editor store): nothing can be read, so the start is cold; the
/// answers are right; the exit says it could not write, once; the store in
/// it is untouched.
#[cfg(unix)]
#[test]
fn qa_a_cache_directory_without_permission_is_a_cold_start_that_answers() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
let (cold, _) = probe(&scratch, None);
scratch.write_editor_store(&honest_store(&scratch));
let before = hash_file(&scratch.editor_store());
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o000)).unwrap();
let (answers, stderr) = probe(&scratch, Some(&scratch.cache()));
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(answers, cold);
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert_eq!(hash_file(&scratch.editor_store()), before);
assert!(!scratch.own_store().exists());
}
/// The editor's store read-only on disk (0444) and in the shape a live
/// language server leaves between compactions — out of path order, a
/// duplicate line, a torn line in the middle, a checksum-failing line: a
/// session that indexes, answers, formats a file and ends leaves its bytes,
/// mtime and mode exactly as they were (nothing "tidies" it), and the good
/// records were all used.
#[cfg(unix)]
#[test]
fn qa_the_editors_store_is_never_tidied_whatever_its_shape() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
let mut lines = honest_store(&scratch);
lines[1..].reverse();
lines.push(lines[1].clone());
let torn = lines[2][..lines[2].len() / 3].to_string();
lines.insert(2, torn);
let bad = lines[3].replacen("\t", "\tX", 2);
lines.insert(3, bad);
scratch.write_editor_store(&lines);
fs::set_permissions(scratch.editor_store(), fs::Permissions::from_mode(0o444)).unwrap();
let before = fingerprint(&scratch.editor_store());
let mut session = Session::cached(&scratch);
assert!(session.text("project_overview", json!({})).contains("files: 7 indexed"));
session.text("format", json!({"file": "rtl/top.sv"}));
session.text("outline", json!({"file": "rtl/top.sv"}));
let stderr = session.end();
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
assert_eq!(fingerprint(&scratch.editor_store()), before, "bytes, mtime and mode unchanged");
assert!(scratch.own_store().is_file());
fs::set_permissions(scratch.editor_store(), fs::Permissions::from_mode(0o644)).unwrap();
}
/// A session killed (SIGKILL) after it answered — the host crashed, it never
/// saw EOF — writes nothing: the previous own store is byte-identical and
/// no temporary file is left, even though the file it would describe changed.
#[test]
fn qa_a_killed_session_leaves_the_previous_own_store_intact() {
let scratch = Scratch::new();
let session = Session::cached(&scratch);
drop(session.end()); // no call: no project, nothing written
assert!(!scratch.own_store().exists(), "a session that never answered writes no store");
let mut session = Session::cached(&scratch);
session.text("list_units", json!({}));
session.end();
let first = fs::read(scratch.own_store()).unwrap();
let leaf = scratch.file("rtl/leaf.sv");
let text = fs::read_to_string(&leaf).unwrap().replace("module leaf", "module leaf_k");
fs::write(&leaf, text).unwrap();
let mut session = Session::cached(&scratch);
assert!(session.text("list_units", json!({})).contains("leaf_k"));
session.child.kill().unwrap();
session.child.wait().unwrap();
assert_eq!(fs::read(scratch.own_store()).unwrap(), first, "the previous store, whole");
assert!(temp_files(&scratch.cache()).is_empty(), "{:?}", temp_files(&scratch.cache()));
// And the next start is right about the changed file (its hash misses).
let mut session = Session::cached(&scratch);
assert!(session.text("list_units", json!({})).contains("leaf_k"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
}
/// QA finding 2: a write killed between the temp file and the rename leaves
/// `index-cache-mcp.<pid>.tmp` (reproduced on opentitan: 9.4 MB of a 46 MB
/// store) and nothing ever removes it — each crash adds one. The language
/// server has the same leak, filed by its own QA (2026-08-27,
/// `index_cache.rs` `an_orphaned_compaction_tmp_file_is_never_swept_up`).
/// Correct behaviour: the next write sweeps a stale temp file of its own
/// store's name (an old mtime, so a concurrent writer's live one is spared).
#[test]
fn qa_an_orphaned_temp_file_is_swept_by_the_next_write() {
let scratch = Scratch::new();
fs::create_dir_all(scratch.cache()).unwrap();
let orphan = scratch.cache().join("index-cache-mcp.999999.tmp");
fs::write(&orphan, "lucisv-index-cache\t2\ttorn").unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
fs::File::options().write(true).open(&orphan).unwrap().set_modified(old).unwrap();
let mut session = Session::cached(&scratch);
session.text("list_units", json!({}));
session.end();
assert!(scratch.own_store().is_file());
assert!(!orphan.exists(), "an hour-old temp file of our store is a dead writer's");
}
// ---------------------------------------------------------------------------
// 3. Parity and freshness.
// ---------------------------------------------------------------------------
/// Warm from the editor's store, warm from its own, and cold: the same
/// answers to every read tool the probe asks.
#[test]
fn qa_warm_answers_equal_cold_answers_from_either_store() {
let scratch = Scratch::new();
let (cold, _) = probe(&scratch, None);
scratch.write_editor_store(&honest_store(&scratch));
let (from_editor, stderr) = probe(&scratch, Some(&scratch.cache()));
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
assert_eq!(from_editor, cold);
fs::remove_file(scratch.editor_store()).unwrap();
let (from_own, stderr) = probe(&scratch, Some(&scratch.cache()));
assert!(stderr.contains(&reused(0, FILES)), "{stderr}");
assert_eq!(from_own, cold);
}
/// Since the store was written: a same-size edit (only the hash can tell)
/// is re-parsed and answered new, and a new file is indexed.
#[test]
fn qa_a_same_size_edit_and_a_new_file_since_the_store_are_seen() {
let scratch = Scratch::new();
scratch.write_editor_store(&honest_store(&scratch));
let leaf = scratch.file("rtl/leaf.sv");
let before = fs::read_to_string(&leaf).unwrap();
let after = before.replace("held", "hold");
assert_eq!(before.len(), after.len(), "premise: the size does not change");
fs::write(&leaf, after).unwrap();
fs::write(scratch.file("rtl/extra.sv"), "module extra_unit; endmodule\n").unwrap();
let mut session = Session::cached(&scratch);
let outline = session.text("outline", json!({"file": "rtl/leaf.sv"}));
assert!(outline.contains("hold") && !outline.contains("held"), "{outline}");
assert!(session.text("list_units", json!({})).contains("extra_unit"));
let stderr = session.end();
assert!(stderr.contains(&reused(FILES - 1, 0)), "{stderr}");
assert!(stderr.contains(&format!("indexed {} files", FILES + 1)), "{stderr}");
}
// ---------------------------------------------------------------------------
// 4. Rule 6: the forced delete.
// ---------------------------------------------------------------------------
const HOLDER: &str = "module keep_before;
endmodule
module holder;
`define LOCAL 3
`define LOCAL 4
always_comb begin
`undef GONE
end
endmodule
module user_after (output logic [3:0] o);
assign o = `LOCAL;
endmodule
";
/// A module holding a `define that code after it reads: refused without
/// `force` (tree byte-identical, the refusal says how to override); forced,
/// the warning names each macro once in source order, and every byte outside
/// the module's lines is the byte that was there.
#[test]
fn qa_a_forced_delete_of_a_define_holder_leaves_the_code_after_it_unchanged() {
let scratch = Scratch::new();
let file = scratch.file("rtl/holder.sv");
fs::write(&file, HOLDER).unwrap();
let mut session = Session::start(&scratch, None);
let args = json!({"file": "rtl/holder.sv", "item": "holder"});
let refused = session.call("delete_item", args.clone());
assert_eq!(refused["isError"], true, "{refused}");
let said = refused["content"][0]["text"].as_str().unwrap();
assert!(said.contains("rule 6") && said.contains("force: true"), "{said}");
assert_eq!(fs::read_to_string(&file).unwrap(), HOLDER, "a refusal writes nothing");
let mut forced = args;
forced["force"] = Value::from(true);
let applied = session.text("delete_item", forced);
assert!(applied.contains("deleted macro definitions: LOCAL, GONE (undef) — "), "{applied}");
let start = HOLDER.find("module holder;").unwrap();
let end = HOLDER.find("module user_after").unwrap();
let now = fs::read_to_string(&file).unwrap();
assert!(now.starts_with(&HOLDER[..start]), "{now}");
assert!(now.ends_with(&HOLDER[end - 1..]), "the code after the item, byte for byte: {now}");
assert!(!now.contains("`define"), "{now}");
session.end();
}
/// `force` on a deletion whose item holds no macro: no macro warning, and a
/// `define item at the file's own level is still not a delete target.
#[test]
fn qa_force_says_nothing_about_macros_it_did_not_remove() {
let scratch = Scratch::new();
fs::write(scratch.file("rtl/holder.sv"), HOLDER).unwrap();
let mut session = Session::start(&scratch, None);
let args = json!({"file": "rtl/holder.sv", "item": "keep_before", "force": true});
let applied = session.text("delete_item", args);
assert!(!applied.contains("macro"), "{applied}");
session.end();
}
// ---------------------------------------------------------------------------
// 5. The instructions.
// ---------------------------------------------------------------------------
/// ≤ 900 characters; names the read tools, the edit tools, `dry_run`,
/// `diagnostics`, the disk, root-relative paths and byte columns; and every
/// snake_case or tool-like word in it is a tool `tools/list` has.
#[test]
fn qa_the_instructions_are_short_and_name_only_real_tools() {
let scratch = Scratch::new();
let mut session = Session::start(&scratch, None);
let init = session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
let text = init["result"]["instructions"].as_str().unwrap().to_string();
let listed = session.request("tools/list", json!({}));
let tools: Vec<String> = listed["result"]["tools"]
.as_array()
.unwrap()
.iter()
.map(|tool| tool["name"].as_str().unwrap().to_string())
.collect();
session.end();
assert!(text.chars().count() <= 900, "{} characters", text.chars().count());
for named in [
"unit_interface",
"outline",
"read_item",
"list_units",
"search_symbols",
"definition",
"references",
"hierarchy",
"replace_item",
"insert_item",
"delete_item",
"rename",
"add_port",
"remove_port",
"format",
"fix_lint",
"diagnostics",
] {
assert!(text.contains(named), "the instructions name {named}");
assert!(tools.iter().any(|tool| tool == named), "{named} is a real tool");
}
for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) {
if word.contains('_') && word != "dry_run" {
assert!(tools.iter().any(|tool| tool == word), "`{word}` is not a tool");
}
}
for phrase in ["dry_run", "disk", "relative to a root", "1-based bytes", "never unsaved"] {
assert!(text.contains(phrase), "{phrase}: {text}");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,387 @@
# mcp-cache-and-census
Lane **M6** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §6 and §8):
the index cache reuse, the startup and per-call timings, the M4 review's
rule-6 ruling, the first revision of the `initialize` instructions — and,
the lead's half, the token census and the closing release.
## Goal
A coding agent's first question to `lucisv-mcp` pays for the index build:
1.9 s on opentitan, every session. The language server has already parsed
the same files and persisted one `FileFacts` record per file, keyed by the
file's content hash (`lucisv_server::index_cache`). This lane lets MCP
start from those records — read only, never written — and from a store of
its own in the same codec, so a warm start skips the parse of every file
whose bytes a record was read from. A record can only ever stand in for the
parse of exactly the bytes it was read from, so the cache is a performance
input and never a correctness one: a torn, damaged, foreign or stale record
costs a parse and nothing else.
## Assumptions
- **Where.** Only `--index-cache DIR` turns the caches on (the extension
passes VS Code's `storagePath`, the directory the language server writes
`index-cache` in). No OS-cache-dir fallback: without the flag MCP starts
cold, as before. The directory may not exist yet (M5 QA F4: VS Code
creates `storagePath` lazily) — that is a silent cold start.
- **Read.** At startup `cache::Records::load` reads `DIR/index-cache-mcp`
and then `DIR/index-cache` (so a record both hold is credited to the
editor). A store is used only when its first line is exactly this build's
header `lucisv-index-cache\t2\t<FACTS_FORMAT>\t<version>`; any other first
line ignores the store whole with **one stderr line**; a missing or empty
file is silent. Each record line is `hash\tfacts\tchecksum`; a line whose
hash or checksum is not 16 hex digits, whose checksum is not the FNV-1a of
the facts field, or which is not UTF-8 is skipped — that covers a torn
last line (a writer killed mid-append) and a record edited after it was
written. Records are keyed by `(record_path, content hash)`.
- **Use.** For each discovered file, MCP reads and hashes the bytes (it
must anyway: the stamp and the freshness sweep need the hash). When
`(canonical path, hash)` has a record that `FileFacts::decode`s to the
same path, `IndexBuilder::add_facts` takes it instead of `add_file`. A
record under another path (the language server's paths are whatever the
editor handed it; MCP's are canonical) is a miss, not a translation.
- **Write — only our own store.** On EOF (the host closes stdin) the
server writes `DIR/index-cache-mcp`: the same header, then one record per
indexed file — the facts the index holds, under the hash in the file's
stamp (both come from the same read, so they describe the same bytes),
in path order. Atomic: a `index-cache-mcp.<pid>.tmp` renamed over the
store; a failure removes the temp file and is **one stderr line**
(`cannot write the index cache: …`); the session ends either way. The
directory is created if missing, and gets a `.gitignore` of `*` when it
has none (the language server does the same). **`DIR/index-cache` is
never opened for writing**: `cache.rs` has no code path that names it
except `fs::read`, and `tests/cache.rs` hashes it before and after whole
sessions.
- **Not written:** a session that never answered a tool call (no project
was built), or a session killed rather than closed. Two MCP servers on one
directory each rename their own complete store over the file: last writer
wins, both stores are whole.
- **The stderr line** is `lucisv-mcp: indexed N files in M ms (E from the
editor's cache, O from its own)` when `--index-cache` is given, and the
old line without the parenthesis otherwise. `M` now includes the index
merge (`IndexBuilder::finish`), which the M1 line left out — the number
went up by the merge's ~200 ms on opentitan; the build did not change.
- **The codec is restated, not shared.** `index_cache.rs`'s `FILE`,
`CACHE_FORMAT`, header and line formats are private to `lucisv_server`
(a binary crate MCP must not depend on — PLAN §4.1). `cache.rs` restates
them; `cache::tests::the_codec_is_the_language_servers_own` reads
`crates/lucisv_server/src/index_cache.rs` at test time and fails if any of
the five pinned source lines changes (Handshake MCP-14).
- **Rule 6, the M4 ruling.** `delete_item` with `force: true` may remove an
item that holds `` `define``/`` `undef`` entries (a module with a
`` `define`` in its body, an `always` with one nested): the deletion
passes rule 6 and the answer carries the warning `deleted macro
definitions: Q, W (undef) — code after the item that used them will
change meaning` (each name once, in source order, `(undef)` for an
`` `undef``). Without `force` the refusal stands and now ends `, or pass
`force: true` to delete it anyway`. `replace_item` and `insert_item` take
no `force` and are unchanged. The verifier change is local:
`Expect::Nothing { force }`, and `Outcome::dropped_macros`.
- **The instructions** (`rpc.rs`, 787 characters, pinned ≤ 900 by a wire
test) name the read tools to prefer over reading files, that edits are
verified, all-or-nothing, on disk with `dry_run`, the item tools vs the
design-wide ones, `diagnostics` to check, and the path/column units. The
lead revises them after the census.
## Handshakes
Consumed (unchanged, read only): `vlog_semantic::{FileFacts::{encode,
decode, path}, record_path, FACTS_FORMAT, IndexBuilder::{add_facts,
add_file, finish}, WorkspaceIndex::{facts_for, fingerprint}}`;
`lucisv_core::cache::content_hash`; the byte format of
`lucisv_server::index_cache` (below).
Promised: `Project::open_cached(roots, filelist, cache_dir)` (the old
`Project::open` is now the tests' uncached shorthand), `Project::save_cache`,
`Project::reuse`. `rpc.rs` calls them in `open_project` and on EOF.
Filed:
- **MCP-14 → `lucisv_server` (informational + one request).** MCP reads
the server's `index-cache` read-only (`fs::read`, never a write handle)
and writes `index-cache-mcp` beside it in the same codec. Nothing in the
server changes. *Request (not blocking):* the codec constants (`FILE`,
`CACHE_FORMAT`, `header()`, `line()`/`parse_entry`) are private to a
binary crate, so MCP restates them and pins the restatement against the
source text; lifting the codec (not the store) into `vlog_semantic` or
`lucisv_core` as a pure move would let both sides share one definition
and retire the pin. Until then, **a change to the store's framing must
bump `CACHE_FORMAT` and update `crates/lucisv_mcp/src/cache.rs`** — the
pin test fails otherwise.
- **MCP-7 → `vlog_refactor`: status unchanged (open).** `rename` still
hands the engine the whole set: 2.23–2.28 s per dry run on opentitan
(below), the cost MCP-7's `KnownFacts` variant (or passing the index's
facts to `rename_traced_with`, which already takes `&dyn KnownFacts`)
would remove. That is an M3 tools change, not this lane's.
- **Out-of-ownership edit, flagged for the lead:** `tests/qa_m4.rs`
`qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always`
pinned "a forced delete of a module holding a `define is refused" — the
exact behaviour the M4 review ruled to change. The loop over
`force ∈ {false, true}` became the unforced refusal plus a forced dry run
that must succeed and name `LOCAL` (8 lines, comment says why). Without
it `cargo test -p lucisv_mcp` is red.
- **For the lead (docs outside this lane):** the M1 README's Assumption
"`--index-cache DIR` is accepted and stored, and unused until M6" is now
stale; `docs/mcp/PLAN.md` §6 matches what was built.
## Status / TODO
- [x] `cache.rs`: read-only reader of the editor's store (header, per-line
checksum, `record_path`, `decode`), keyed by path + content hash
- [x] warm start: `add_facts` on a hit, parse on a miss; hit counts on the
stderr startup line
- [x] own store `index-cache-mcp`: same codec, written atomically on EOF,
read on start; a write failure is one stderr line
- [x] F4: a missing directory is a silent cold start
- [x] unit tests (`src/cache/tests.rs`): the codec pin; warm from the
editor's store = cold fingerprint; own store round trip = cold
fingerprint; a changed file misses; torn / damaged / foreign records
each a parse; a record under another path or hash not taken
- [x] wire tests (`tests/cache.rs`): the editor's store byte-identical
(hash + mtime) after a session that indexes, answers and edits, with
a damaged and a torn record skipped; another version's store ignored
with one line; missing directory → cold, own store written, next
start warm from it, a changed file re-parsed and answered new; an
unwritable directory (0555) → answers, one stderr line, nothing
written
- [x] opentitan timings (`tests/opentitan.rs`, ignored): cold / warm from
own store / warm from the editor's store, exit write, stat sweep,
whole-set `rename`
- [x] rule-6 ruling: `force` relaxes rule 6 on `delete_item` with the
warning; wire test + attack test
- [x] `INSTRUCTIONS` first revision (≤ 900 characters, wire-tested)
- [x] `docs/perf/README.md` MCP entry
- [ ] token census, instruction revision after it, topo, CHANGELOG,
release — the lead's
## Timings
Release build (`cargo test --release -p lucisv_mcp --test opentitan --
--ignored --nocapture opentitan_startup`), macOS arm64, the whole opentitan
checkout (3 944 indexed files, 3 over 1 MiB skipped), two runs; the
checkout's `git status --porcelain` identical before and after. The stores
live in a scratch directory outside the checkout; the "editor's store" is
the own store renamed to `index-cache` — the same bytes the language server
would write (46.3 MB), which is what the codec pin guarantees.
| what | wall |
|---|---|
| cold start, no store (first `project_overview`) | 1 854–1 887 ms (build 1 800–1 880 ms) |
| warm from its own store | 837–847 ms (build 821–840 ms, 3 944 hits) |
| warm from the editor's store | 821–832 ms (build 814–824 ms, 3 944 hits) |
| exit, writing `index-cache-mcp` (46.3 MB) | 251–272 ms |
| per-call freshness sweep (`outline` of a cached file, median of 21) | 5.6–6.1 ms |
| — the transport floor (`tools/list`, median of 21) | 0.38 ms |
| `rename` `op_i` → `cipher_op_i` at `hw/ip/aes/rtl/aes_cipher_core.sv:123`, `dry_run`, whole set | 2 227–2 276 ms (first and second call alike) |
Where a warm build's ~820 ms goes (one instrumented run, not committed):
walk 210 ms, reading the store 87 ms, reading + hashing + decoding 3 944
files 318 ms (1 387 ms when each is parsed instead), the index merge
204 ms. The walk and the merge are the floor a cache cannot remove.
## Token census (lead)
## Work log
**2026-09-23 (dev, Opus).** Built as briefed, in the owned files plus the
two flagged edits (`rpc.rs` wiring beyond `INSTRUCTIONS`; `tests/qa_m4.rs`).
- `cache.rs` (118 production lines): `Records::load/take`, `write_own`,
the restated header/line codec, `store_lines` reading bytes a line at a
time exactly as the language server does (a torn multi-byte character
costs one line). `Reuse` counts hits by source.
- `project/mod.rs`: `open_cached` + a `load` helper (read, stamp, take a
record or parse); `save_cache` builds `(stamp.hash, index.facts_for)`
per file; `reuse()`. **Deviation:** the build clock now stops after
`finish()` — the old code read the clock before the merge ran inside the
struct literal, so every "indexed in M ms" since M1 left out ~200 ms on
opentitan. `Project::open` became `#[cfg(test)]` (its only callers are
tests; clippy's dead-code lint otherwise).
- `rpc.rs`: `open_project` calls `open_cached` and prints the counts;
`Line::Eof` calls `Server::finish`, which saves (verbose: a line with the
record count; failure: one line always). **Deviation:** the brief listed
`rpc.rs` for `INSTRUCTIONS` only, but the startup line and the EOF write
live there; the change is those two call sites.
- `verify.rs`/`item.rs`: the rule-6 ruling (above); `delete_item`'s
description and `force` parameter say so.
- Unit tests live in `src/cache/tests.rs` (the fingerprint oracle needs
`Project`, which a `tests/` file cannot reach in a binary crate).
- The own store is rewritten on every exit even when unchanged (~260 ms on
opentitan, after the last answer): simple, and a store the host kills us
during is still the previous whole store.
- Tests: `lucisv_mcp` 290 → 302 passing (+5 unit, +4 `tests/cache.rs`,
+3 wire), ignored 2 → 3 (the opentitan timing test); workspace 4 846 →
4 858.
**2026-09-23 (dev, feedback-1).** QA finding 2 fixed: `write_own` first removes `index-cache-mcp.<pid>.tmp` files older than 10 minutes (a younger one may be a live writer's); `qa_an_orphaned_temp_file_is_swept_by_the_next_write` un-ignored. `INSTRUCTIONS` revised (896 characters) — `docs/features/mcp-feedback-1`.
## QA log
**2026-09-23 (QA, Opus) — QA — interrupted** (the session was cut off before the workspace gate finished; everything below was run and is recorded as measured).
**The cache half of the M6 QA line. Verdict so far: pass;
no wrong record served, the editor's store never written. Two non-blocking
findings (one doc, one inherited leak). The census spot-check waits for the
census.** Tests in `crates/lucisv_mcp/tests/qa_m6.rs` (16 pass, 1 ignored =
finding 2), each spawning the real binary over a scratch copy of the
`design` fixture.
*Wrong-record hunt (blocking class — nothing found).*
- **Swapped records, checksums recomputed** (`leaf.sv`'s hash carrying
`top.sv`'s facts and the reverse): not served. The key is `(record_path
of the facts, hash)` and `take` compares the decoded path again, so each
lands under (other path, this hash) and matches no file — 5/7 hits, the
probe's nine answers equal a cold start's. Also run on a copy of opentitan
`hw/ip/{aes,prim}` with a real language-server store (`prim_fifo_sync` ↔
`prim_fifo_async`): 391/393 hits, both interfaces right.
- **Inherited, documented limit (not a finding against the code):** a
record *relabelled* — `prim_fifo_async`'s facts with `prim_fifo_sync.sv`'s
path, under `prim_fifo_sync.sv`'s real hash, checksum recomputed — is
served (393/393 hits; `unit_interface prim_fifo_sync` answers "not
indexed") and is then re-laundered into `index-cache-mcp` with a fresh
checksum. The language server does exactly the same: `index_cache.rs`'s
module doc states the same-user/same-disk threat model (FNV-1a is not a
MAC; whoever can write the store can write the sources). Accidental
damage cannot produce this shape. See finding 1 for the doc.
- Records for a deleted file and for a file outside every root (it exists
beside the root): neither module listed, neither record written back
(own store = header + 7). Two records for one path under two hashes
(the append log's normal shape): the one whose hash is the bytes on disk is
served, older or newer; two for one `(path, hash)`: the later line wins, as
in `IndexCache::open` (tested with a checksum-valid wrong record first and
the honest one last).
- CRLF store: `\r` stripped exactly as the language server strips it, 7/7
hits, answers = cold. Header near-misses — version patch + 1,
`FACTS_FORMAT` ± 1, `CACHE_FORMAT` 1 and 3, a trailing space, a BOM, a
fifth field: each ignored whole with exactly one stderr line, store
byte-identical. Empty store, header-only store, a directory named
`index-cache`: silent cold starts (stderr = the startup line only).
- A 231 MB store (opentitan's 46 MB store + 4 copies under `/ghostN` paths,
checksums valid), release build, 3 944 files: build 892 / 937 / 1 026 /
1 203 ms at 46 / 92 / 138 / 231 MB — linear (~1.7 ms/MB); peak RSS 407 →
750 MB (the store bytes plus every record's string are held until the
load ends); the store byte-identical after each run.
*Read-only promise and the own store's writes.*
- The editor's store at mode 0444, in a live server's between-compactions
shape (reversed path order, a duplicate line, a torn line mid-file, a
checksum-failing line), through a session that indexes, answers, runs
`format` (writes a file) and ends: bytes, mtime and mode identical, 7/7
hits. On the real `aes`+`prim` LSP store: `shasum` identical after a warm
session. Code: `cache.rs` names `EDITOR_STORE` only in `Records::load`
→ `fs::read`; `write_own` writes only `index-cache-mcp`, its temp file and
`.gitignore` (when missing — as the language server does).
- Killed sessions (SIGKILL): after an answer and before EOF (fixture, with
a changed file that would have changed the store): the previous own store
byte-identical, no temp file, the next start re-parses the changed file.
On opentitan, killed at 20–350 ms after EOF (11 delays): own store
intact, no temp. Killed the instant `index-cache-mcp.<pid>.tmp` appeared:
store intact, **a 9.4 MB temp file left behind for good** → finding 2.
- `--index-cache` naming a regular file: answers right, one `cannot write
the index cache` line, the file untouched. A directory named
`index-cache-mcp`: silent read miss, one line at exit, no temp left. Cache
directory mode 000 holding an honest store: cold start, the nine probe
answers equal cold's, one line at exit, store untouched. (A startup that
cannot *read* a store is silent — only the exit's write failure speaks.
Acceptable for a performance input; noted, not filed.)
*Parity.*
- The nine-answer probe (`list_units`, two `unit_interface`, two `outline`,
`search_symbols`, `references`, `hierarchy`, `defines`) is identical cold,
warm from the editor's store and warm from the own store.
- A **real language-server store** (release `lucisv-server` driven over
stdio on a copy of `hw/ip/{aes,prim}`, `index.scope = workspace`,
`storagePath` = scratch; 393 records, 2.69 MB): MCP warm start 393/393
editor hits, and — the stronger check — a **cold** MCP session's
`index-cache-mcp` over the same tree is **byte-identical** to the
server's `index-cache`: same header, same facts, same order.
- `WorkspaceIndex::fingerprint` (throwaway unit test in a scratch copy of
the crate, not committed): warm-from-LSP-store = cold on `aes`+`prim`
(393 files); warm-from-own-store = cold on the **whole opentitan
checkout** (3 944 files, fingerprint 37.2 MB); the checkout's `git status
--porcelain` identical before and after every run.
- Same-size edit (`held` → `hold`) since the store: re-parsed, the outline
shows `hold`; a new file since the store: indexed; 6/7 hits.
*Rule 6 (the M4 ruling).* A module holding `` `define LOCAL`` twice and a
nested `` `undef GONE``, read by the module after it: without `force`
refused (names rule 6 and `force: true`), file byte-identical; forced: the
warning reads `deleted macro definitions: LOCAL, GONE (undef) — …` (each
name once, source order), every byte before and after the item's lines is
the original's. `force` on an item with no macro says nothing about
macros. The `tests/qa_m4.rs` diff is exactly the ruling's assertion swap
(the `force ∈ {false, true}` refusal loop → unforced refusal + forced dry
run naming `LOCAL`), nothing else. The code: `Expect::Nothing { force }`;
for a deletion `same_macros` can only fail when the region held a
definition, which is exactly what `dropped` lists — `force` cannot excuse
anything else.
*Instructions.* 787 characters (≤ 900). Names `unit_interface`, `outline`,
`read_item`, `list_units`, `search_symbols`, `definition`, `references`,
`hierarchy`, the three item tools, `rename`, `add_port`, `remove_port`,
`format`, `fix_lint`, `diagnostics` — every one in `tools/list`, and no
snake_case word that is not a tool (`dry_run` aside); says disk-only,
root-relative paths, 1-based byte columns.
*Sizes.* Production lines: `cache.rs` 118, `project/mod.rs` 289, `rpc.rs`
265, `tools/item.rs` 389, `tools/item/verify.rs` 388 — all under 600.
*Timings (release, whole opentitan, this machine, `tests/opentitan.rs`).*
Cold 1 769 ms build (first call 1 776 ms); warm own 833 ms; warm editor's
807 ms; exit write 243–260 ms; sweep median 4.9–5.0 ms (floor 0.35 ms);
`rename` dry run 2 152–2 172 ms. Consistent with the dev's table.
*Findings.*
1. **(low, doc)** `docs/features/mcp-cache-and-census/README.md` Goal:
"a torn, damaged, foreign or stale record costs a parse and nothing else"
overclaims — a forgery that recomputes the FNV-1a checksum is served
(reproduction above; the language server has the same property by
design). Fix: say "a torn, damaged, foreign or stale record", and add the
threat-model sentence the server's `index_cache.rs` module doc carries
(same user, same disk; the checksum catches damage, not intent) to
Assumptions → Read. No code change.
2. **(minor, inherited)** `crates/lucisv_mcp/src/cache.rs:140-146`
(`write_own`): a process killed between `fs::write(tmp)` and the rename
leaves `index-cache-mcp.<pid>.tmp` (9.4 MB on opentitan) that no later
session removes — one per crash, each up to the store's size. Harmless
to correctness (only the exact store names are read). Same leak as the
language server's, filed by its QA 2026-08-27
(`an_orphaned_compaction_tmp_file_is_never_swept_up`). Pinned by
`qa_an_orphaned_temp_file_is_swept_by_the_next_write` (ignored). Fix:
before writing, remove `index-cache-mcp.*.tmp` files in `dir` older than
a few minutes (a concurrent writer's live temp file is seconds old).
*Gates* (through `tools/guard.sh`, one at a time): `cargo fmt --all --
--check` clean; `cargo clippy --workspace --all-targets` clean (no
warnings); `cargo test -p lucisv_mcp` 318 passed, 0 failed, 4 ignored
(302 + 16 QA; ignored: 2 opentitan, M3 finding, M6 finding 2); the
opentitan tests (release, `--ignored`) 2 passed, checkout unchanged;
`cargo test --workspace` **NOT completed** — cut off after ~16 minutes, mid-run (reached `vlog_refactor`, `corpus`, `inline` test binaries; every result line captured before the cut-off was `ok`, no failure seen).
*Not yet checked:* the full `cargo test --workspace` count (needs ≥ 4 858 + 16 = 4 874 passing); the census transcripts spot-check (the census has not been run — the lead's half); a whole-opentitan store written by the *language server itself* (only `aes`+`prim` was; whole opentitan was checked with MCP's own store). The M6 QA box in `TODO-MCP.md` is left unticked.
## Review
**Lead, 2026-09-23 (M6, committed at the owner's move).** The reader keys a
record on the file's content hash and the record's own path, never writes
the editor's store, and a warm start on opentitan halves the startup (1.9 s
→ 0.8 s; the walk and the merge are the floor). QA (interrupted by the move,
verdict pass so far): swapped, stale, foreign-path, deleted-file, off-by-one
header and CRLF stores all skipped; the editor's store byte-identical through
a session; SIGKILL mid-write leaves the previous own store intact; a
231 MB store loads linearly; fingerprint parity with a cold build over the
whole checkout. Two low items: the README's threat model now says
"damaged", not "forged" — a record with a recomputed checksum is used,
exactly as the language server uses it, because whoever can write the store
can write the sources; and an orphaned `index-cache-mcp.<pid>.tmp` after a
kill between write and rename is not swept (QA's ignored test
`qa_an_orphaned_temp_file_is_swept_by_the_next_write`) — to be fixed in the
first census round. The forced-delete ruling (rule 6) and the first
`INSTRUCTIONS` revision landed here; the census revises the instructions
again. The full workspace suite was still running when the machine moved;
the dev's run on the same code passed 4 858 and QA's crate suite 318.
+2
View File
@@ -397,6 +397,8 @@ as skipped (finding 7, un-ignored). Cost of the walk on opentitan `hw/`:
≈140 ms per edit call, against the 1.6–2.6 s the whole-set read already
costs. Gates re-run by the lead through `tools/guard.sh`.
**2026-09-23 (dev, feedback-1).** `rename`, `remove_port` and `add_port` add one `warnings:` entry listing the name's unresolved textual mentions, and `unresolved_mentions` to their JSON (handshake change); `add_port` takes `after` (placement re-done on the MCP side, verified against the engine's appending edit, `src/tools/place.rs`); `remove_port` no longer goes through `at_cursor` — `docs/features/mcp-feedback-1`.
## QA log
**2026-09-23 (QA, M3). Verdict: FAIL — two blocking findings (1 in
+433
View File
@@ -0,0 +1,433 @@
# mcp-feedback-1
Lane **feedback-1** of the MCP block: the changes the first token-census
round asked for (`mcp_analysis.md`, Round 1 → "Changes for round 2").
Tracked in `TODO-MCP.md` → "Feedback rounds".
## Goal
Round 1 showed that `lucisv-mcp`'s answers were correct but not complete
enough, and not discoverable enough, to beat plain file tools: a rename left
a DV force-path string and a macro-rooted probe behind without a word, the
census agent asked `references` for "who instantiates X" instead of
`hierarchy up`, `add_port` could not place a port where the task wanted it,
and the tool catalogue cost every session ~7 500 tokens before any work.
This lane makes the answers say what the engines could not see (unresolved
mentions), points the agent at the right tool (descriptions and
instructions), makes a positioned port insertion one verified call
(`add_port`'s `after`), cuts the catalogue by 40 %, and sweeps the orphaned
temporary store M6 QA found.
## Assumptions
- **What a mention is.** A whole-word spelling of the name (not glued to an
identifier character on either side, `source::word_in`) that lies in: a
comment (every token's `leading`/`trailing` trivia), a `String` token, a
macro call's text after the macro's own name (every word — arguments,
strings and comments inside them alike), a `` `define`` body after the
macro name and formal list (a define whose formals spell the name is
skipped: the formal shadows it), or an identifier ending a dotted path
whose head is a macro token (`` `X_HIER.u_a[0].name``, `` `SPI(1).u.name``).
A file that does not lex lists every spelling as `text`. Plain
identifiers elsewhere are never mentions: they belong to some declaration
the engines resolve (another module's own `state_q` is not noise here).
`` `ifdef name`` and attributes are not searched.
- **Accounted for.** A spelling inside a span the engine returned —
`references`' hits, or any edit range of the rename/`remove_port`/
`add_port` edit — is not a mention. The engines' own macro warnings
(rename's "appears in the arguments of…") still appear; the mentions list
repeats those sites, deliberately: it is the one complete list.
- **Why not `macro_spellings`.** `item/macros.rs::macro_spellings` answers
"is this identifier used here", so it skips strings inside macro text
(`` `define P ".state_q"``) — exactly the round-1 miss. The mentions
scanner word-searches the raw macro/define text instead.
- **Order and cap.** Listed nearest first: files the engine touched, then
lines spelling the declaring unit's name (catches `u_<unit>` on a macro
path), then by how many leading path components the file shares with the
declaration's file; file and line within. One mention per line. At most 50
(`mentions::CAP`), then `… and N more`; lines capped at 160 characters.
On opentitan `state_q` (entropy_src main_sm) the three round-1 sites are
lines 1, 2 and 4 of 415.
- **Cost.** No new reads: the engines already hold every indexed file's text
(`WholeSet`). Each text is `str::contains`-filtered; only a text spelling
the name is lexed. The index word censuses (`files_mentioning`,
`files_naming_in_macros`) cannot narrow further — comments and strings are
not in them — so they are not used. Measured on the eval clone
(`~/.cache/lucisv-eval/ot/hw`, 3 944 files, release builds, same session
warm, two runs each), r1 binary → this lane:
| call | r1 | feedback-1 | mentions |
|---|---|---|---|
| `references` `state_q` (entropy_src_main_sm.sv:42) | 1.98 s | 2.04–2.09 s | 415 (50 listed) |
| `references` `clk_i` (aes_core.sv:30) | 2.37–2.39 s | 2.60–2.69 s | 50 listed |
| `rename` `state_q` dry run | 2.17–2.24 s | 2.34–2.39 s | 415 (50 listed) |
i.e. +0.06–0.3 s on a 2–2.7 s whole-set call.
- **`references` paging.** The section is on the first page only
(`offset` 0); later pages repeat nothing.
- **Descriptions.** `tools/list` measured as the compact JSON of the
`result` object: **30 221 B before, 17 981 B after** (−40.5 %). Tool
descriptions 9 095 → ~2 700 B, argument descriptions 7 621 → ~2 500 B,
`annotations.title` dropped (it repeated `title`). Every argument keeps a
description. The position rules left the descriptions for `INSTRUCTIONS`
(896 characters, under qa_m6's 900 cap).
- **Temp sweep.** Before writing its store, `cache::write_own` removes
`index-cache-mcp.<digits>.tmp` files older than 10 minutes
(`STALE_TEMP`); a younger one may be a live concurrent writer's, and no
other file is touched.
### `add_port` `after` — exactly what happens
`vlog_refactor::add_port` only appends (header and connections), so it runs
first, unchanged; its verified edit is the reference. `tools/place.rs` then:
1. **Header** (MCP side). The module's ANSI port named `after` is the
anchor; its index counts **every** element of the list, as
`ListDirective::before` does. Refused, in this order: a non-ANSI/empty
list; an unknown `after` (the ports are named); an anchor inside an
`` `ifdef`` arm; a list holding an element the parser could not read
(`(* keep *) b` — its text is named; lucisv cannot see what it
inherits); a next port that would inherit from the new one — no
direction and no type (inherits both), or a type but no direction when
the new port's direction differs from the anchor's (a modport port,
`bus_if.mp bus`, has no direction to inherit and is placed after). The
engine's header edits (those inside the port list's parens) are dropped
and the new element goes into the **slot after the anchor's separator**
(`place/slot.rs`), never at the anchor's end:
- anchor followed by `,` and the next element starting a later line:
a new line at the end of the comma's line (past a comment on it, and
past a block comment that closes on a later line), `element,`;
- `,` with the next element on the same line (`a, b`, a leading-comma
list ` , input c`): ` element,` right after the comma;
- a last anchor with `)` starting a later line: `,` at the anchor's end,
a new line at the end of the anchor's line (past its comments);
- a last anchor with `)` on its line: `, element` at the anchor's end,
or — a comment between — `,` at the anchor's end and ` element`
before the `)`.
A new line takes the anchor's line ending (CRLF kept); when the anchor
is alone on its line, its indentation and column layout (direction,
type, name at the anchor's columns when they fit), else the next
element's indentation and the declaration on one line.
2. **Connections.** For each instance of the module that the engine gave a
connection edit: a positional list is refused unless `after` is the last
port (then the engine's appended connection stands); a list holding an
unreadable element is refused (its text named); a named list whose
`.after(…)` sits outside any `` `ifdef`` arm (full-list index) gets the
engine's expression (read back from its appended `.port(expr)`,
`/* TODO: connect */` included) in the same slot after `.after(…)`'s
separator, aligned (`(` and `)` at the anchor's columns when they fit)
or inline. Otherwise the engine's appended connection stands and a
warning names the instance (root-relative) and why.
3. **Verification** (`place/verify.rs`, the refusal names the failed
check): the placed edit applied must, file by file, be the engine's
result with elements moved: the same sorted multiset of tokens (kind +
text); every comment attached to the same identifier — the nearest one
before it for a comment on its token's line (a `,` is never an anchor),
the nearest one after it for a comment on lines of its own; no more
parse diagnostics; the module's port list with **every** element
(unreadable ones by text) in the engine's order with the new port moved
after `after`, each port's declaration text (blanks collapsed) the
engine's, and the port after the new one not inheriting from it; every
instance's connections the same (named: sorted `name(expr)` with blanks
squeezed; positional: in order; unreadable elements by text). Then the
one write path, `apply::run`.
## Handshakes
- **Consumed:** `vlog_parser::{tokenize, parse_source_tolerant, LineIndex}`,
AST port/instance types; `vlog_refactor::{add_port, remove_port, rename,
find_references, rename_name_at, enclosing_module, module_definition,
RefactorEdit, TextEdit}`; `apply::Plan::from_refactor` (applies and
checks edits, used as-is by `place::verify`).
- **Promised (answer shapes):** `references` text gains the section
`unresolved mentions (strings, comments, macro text — not resolved by
lucisv):` with ` file:line kind: text` lines; `rename`, `remove_port`
and `add_port` gain one `warnings:` entry — "`<lead>` as text at these
places lucisv does not resolve (strings, comments, macro text; N in all);
check whether these are references:" with the same lines indented four.
All four add `"unresolved_mentions": [{file, line, text, kind}]` to their
JSON (empty when none); `kind` ∈ `comment`, `string`, `macro`, `define`,
`path`, `text`. `add_port` takes `after`. `tools/list` no longer carries
`annotations.title`.
- **Flag for the lead (ownership):** `src/tools/place.rs` is a new file not
in the lane's list — `refactor.rs` would have gone from 291 to ~770 lines
with it. It is only used by `refactor.rs`. The rework split it into
`place.rs` (driver and refusals), `place/slot.rs` (where and how an
element is written) and `place/verify.rs` (the move-checker), all new.
- **Mentions after an edit** (QA finding 4): `finish_telling` runs the
mentions pass on the texts as written (the plan's new text for an edited
file, the read text otherwise), with the edit's ranges shifted into the
written text, so `file:line` names the file as it is after the write —
and, for a dry run, the diff's new side.
## Status / TODO
- [x] `src/tools/mentions.rs` — the scanner, ranking, rendering
- [x] `references` section + JSON; `rename`/`remove_port`/`add_port`
warning + JSON (`edit::finish_telling`)
- [x] descriptions and `INSTRUCTIONS` (hierarchy/references wording; ≤ 18 kB)
- [x] `add_port` `after` (`src/tools/place.rs`), with attack tests on its
verifier
- [x] stale temp-store sweep; `qa_an_orphaned_temp_file_is_swept_by_the_next_write`
un-ignored
- [x] wire tests (mentions on `references`/`rename`, `after` byte-exact on an
`aes_core`-shaped fixture, last-port and unknown-anchor, catalogue
size, sweep)
- [x] opentitan cost measured (above)
## Work log
**2026-09-23 (dev, Opus).**
- `mentions.rs` (212 production lines): `find` over the `WholeSet` texts,
`spellings` per file (comments, strings, macro text, define bodies,
macro-rooted paths), ranking, `Mentions::{lines, json, warning}`.
- `nav.rs`: `references` computes mentions before handing texts to
`Texts`; the section follows the hits; `unresolved_mentions` in JSON.
- `edit.rs`: `finish_telling` (accounted = the edit's ranges); `rename`
and `remove_port` (no longer through `at_cursor`) use it.
- `refactor.rs`: `add_port` takes `after`, resolves the module's file
(`module_definition` or the given file), runs `place::after`, and
finishes through `finish_telling` with the new port's name.
- `place.rs` (479 production lines): see "exactly what happens" above.
Decision: re-placing the engine's verified edit and verifying the moved
result against it, rather than asking for an engine change — no
Handshake on `vlog_refactor` needed.
- Descriptions: all 26 rewritten; `mod.rs` drops `annotations.title`.
30 221 → 17 981 B.
- `cache.rs`: `sweep_stale_temps` before each own-store write.
- Tests: unit tests in `mentions.rs` (4) and `place.rs` (6, three of them
attacks/refusals on the verifier); 7 wire tests; fixture
`tests/fixtures/feedback/`.
**2026-09-23 (dev, Opus) — rework on the QA verdict and the lead's
rulings.** All six `qa_f1` tests un-ignored; none contradicted a ruling
(5b's expects the `ifdef` refusal for an anchor inside an arm next to an
unreadable element, so the arm is checked before the unreadable-element
refusal — both refuse).
- **5 (blocking)**: `place.rs` `header` refuses a port list with an
unreadable element (named), after the `ifdef` check; `after` refuses an
affected instance whose connection list holds one; `balanced_before` is
handed full-list indices on both sides; `verify` compares the whole port
list, unreadable elements by text, each port as `name: declaration`
(blanks collapsed) against the engine's — the type-swap pair is a unit
test (`place/verify.rs`), refused.
- **1 (major)**: insertion moved to the slot after the separator
(`place/slot.rs`, unit-tested on `a /* about a */,`, a leading-comma list,
a last port with a block comment, a block comment spanning the comma's
line, CRLF); `verify` pairs each comment with its identifier (attacks: a
comment glued to the anchor's comma, a leading-comma list, the anchor
line's comment taken by the new line). Deviation from the ruling's
letter, for the reason: the ruling pairs every comment with its
*preceding* token; for a comment on lines of its own that would forbid
the placement round 1 asked for (`rst_ni,` ⏎ blank ⏎ `// Data` ⏎
`data_i` — the new port goes right after `rst_ni`, so `// Data`'s
preceding name changes although it still sits above `data_i`). Such a
comment is paired with the identifier after it instead; a same-line
comment with the one before it (never a `,`). Both catch QA's attacks.
- **2**: every file `place.rs` names goes through `Spec::show`
(`project.relative`).
- **3**: `inherits`: no direction and no type → inherits both (refused);
a type but no direction → inherits the direction, refused only when the
new port's direction differs from the anchor's; a modport type
(`x.y`) → never. Stricter than the ruling's "both absent" in one case
(`output logic a, logic [3:0] b` with a new `input`: `b` would turn
input), unit-tested.
- **4**: `edit.rs::finish_telling` scans the written texts;
`mentions::find` now takes `(path, text)` pairs; `written_ranges` shifts
the edit ranges.
## QA log
**2026-09-23 (QA, Opus) — verdict: REWORK (1 blocking, 1 major, 3 low).**
Attacks in `crates/lucisv_mcp/tests/qa_f1.rs` (real binary over scratch
trees; placements byte-exact, refusals with the tree byte-identical under
`dry_run` and for real): 11 pass, 6 `#[ignore = "QA finding N"]` pin the
findings below (each fails today, run with `--ignored`).
Verified, holds:
- `after` byte-exact on: an anchor with a `//` comment on its line (stays
there), the last port with a trailing `/* */` (comma before the comment,
the new line has none), tab indentation, CRLF (kept on the new line),
one-per-line aligned connections, two instances in one statement, an
instance in a generate block, an instance in the module's own file
(`file`+`line` selector), a positional instance with `after` = last
(appended) and elsewhere (refused, nothing written), an anchor just
before and just after an `` `ifdef`` arm (placed outside), an anchor in
an arm (refused), a parameter as `after` (refused, ports listed), a
connection anchor in an arm (engine's append kept, warning names the
instance), `.*` instances (the engine's warning; nothing placed), the
same call twice (engine refuses, nothing written). `dry_run`'s diff,
applied to the old text, is byte-for-byte what the real run writes (for
`after` = first, middle, last).
- Mentions: a hierarchical path in a comment, a string inside a macro's
arguments, a `` `define`` body listed and a `` `define`` with the name
as formal not, a macro-rooted path through `[2]`, an escaped `\name` in
a comment, `state_q_d`/`xstate_q`/a path ending in `state_q_d`/the name
as an index not listed; CRLF line numbers right and no `\r` in the
text; JSON keys exactly `file, kind, line, text`; `offset` > 0 has no
section and `[]`; the cap (60 far mentions + the edited file's: 50
listed, edited file first, "65 in all", "… and 15 more"); a renamed
file's hits excluded and its other mentions kept. opentitan (eval clone,
release, through the shim): `references clk_i` at aes_core.sv:30 —
r1 4.00 s / 4.00 s, feedback-1 4.21 s / 4.22 s (+0.21 s, within the
recorded +0.06–0.3 s); 801 mentions, 50 listed; the clone left clean.
- Catalogue: `tools/list` 17 981 B (≤ 18 000), 26 tools, every argument
described, no argument lost against HEAD (only `after` added; checked
per file by `git show HEAD:`), `title` kept at tool level and absent
from `annotations`, the three hints booleans; `instructions` 896 chars,
every `snake_case` word it names is a tool (bar `dry_run`).
- Sweep: an hour-old `index-cache-mcp.1.tmp` goes; `..tmp`, `.12a.tmp`,
`.12.tmp.bak`, `index-cache.12.tmp`, `xindex-cache-mcp.12.tmp` (all an
hour old) and an old *directory* `index-cache-mcp.77.tmp` stay; the own
store is still written (plus the dev's young-file test).
Findings:
1. **Major — a comment re-attached to the new port, forgiven by the
checker.** An anchor whose comment sits between it and its comma
(`input logic a /* about a */,`), or on its line before a leading-comma
next element (`input logic b // about b` ⏎ `, input logic c`), is not
"alone on its line", so `inline` inserts at the anchor's *end*
(place.rs:173, :256): `input logic a, input logic en /* about a */,` and
`.a (a), .en(en) /* conn a */,` — the comment now documents `en`.
`verify` compares comment texts as a sorted multiset (place.rs:529–540),
so the move passes. Repro:
`qa_a_comment_between_the_anchor_and_its_comma_stays_with_the_anchor`.
Fix: insert `, element` at the start of the token after the anchor when
it is `,` or `)` (past the trivia), else at the anchor's end; and in
`verify`, compare each comment paired with its preceding non-`,` token.
2. **Low — absolute paths.** The warnings and refusals `place.rs` writes
use `path.display()` (place.rs:84, :221):
`` `u_n` in /private/var/…/rtl/top.sv: the connection … ``; every other
answer is root-relative. Repro: `qa_place_names_files_relative_to_the_root`.
3. **Low — false refusal.** A modport port after the anchor
(`bus_if.mp bus`) has no direction and inherits none, but place.rs:155
refuses "takes its direction and type from the port before it". Repro:
`qa_a_modport_port_after_the_anchor_does_not_refuse`. (A bare
`bus_if bus` is ambiguous with a type; refusing that one is right.)
4. **Low — stale mention lines after a write.** `finish_telling`
(edit.rs, the `mentions::find` over `set.files`) lists mentions with the
*pre-edit* line numbers; after a real `add_port` (lines added),
`remove_port` (removed) or a `rename` that writes out `.*` bindings, a
mention below the edit in an edited file names the wrong line
(`rtl/m.sv:6 comment: // en gates y` — line 6 is now `);`). Repro:
`qa_mention_lines_name_the_file_as_written`. Fix: shift each mention by
the net newlines the file's edits insert before its offset, when not a
dry run.
5. **BLOCKING — an unreadable port-list element defeats the placer and the
checker (masked corruption, written to disk).** `place.rs` reads the
header through `ListElem::ok` (`ansi_ports`, place.rs:128–133) and so
does `verify` (`ports_in_order`, place.rs:542–564). An element the
parser could not read — `(* keep *) b`, legal SV, an attribute on a
port — is invisible to both:
- a) `input logic [7:0] a,` ⏎ `(* keep *) b,` with `after: "a"`:
the new `input logic en` lands between them, so `b` now inherits
`input logic` — **8 bits become 1** — and it is written (same tokens,
same parse-error count, same well-formed port order). Repro:
`qa_a_port_hidden_by_a_parse_error_does_not_change_its_inherited_type`.
- b) `balanced_before` gets the anchor's index among the *well-formed*
elements, but `ListDirective::before` counts all of them
(place.rs:161; the connection side has the same shape at :241–244).
With `(* keep *) input logic d` before an `` `ifdef X`` arm, `after: "b"`
(inside the arm) passes: the port is written **inside the arm** while
the connection is unconditional, and the engine's warning in the same
answer says it was added "outside every conditional arm". Repro:
`qa_an_unreadable_element_does_not_let_an_anchor_in_an_ifdef_arm_through`.
Fix: refuse `after` when the port list (or the anchor instance's
connection list) holds any `ListElem::Error`, or index the raw list
everywhere (the anchor's raw index for `balanced_before`, the raw next
element must be `Ok` with a direction). `verify` should re-derive the
same on the placed tree with raw indices, and compare each port's
declaration text (blanks squeezed) by name with the engine's: today a
crafted `input logic [7:0] a, input logic en` →
`input logic a, input logic [7:0] en` (a type swapped between the
anchor and the new port) has the same tokens, names in order, parse and
connections, and `verify` would accept it. These attack pairs belong in
`place.rs`'s unit tests next to `verify_refuses_a_placement_that_is_not_a_move`
(`verify` is private; QA cannot reach it from `tests/`).
Observations (no test; for the lead):
- Layout: a multi-line anchor (`input logic` ⏎ `[7:0] e,`) measures its
name column across the newline (place.rs:339), so the new line's name is
pushed far right. Cosmetic.
- Ranking ignores kind: 60 comments in one file push that file's
macro-rooted path — the round-1 miss class — past the cap. Ranking
`path`/`string`/`define`/`macro` above `comment` within a rank would keep
the valuable ones listed.
- Out of lane (engine / parser, pre-existing): `vlog_refactor::add_port`
appends a connection *inside* an `` `else`` arm when the list's tail is
conditional (`.y ()` ⏎ `` `endif``); the parser reads `(* attr *)` on an
ANSI port as an error element (`after: "d"` answers "no port `d`"); the
unified diff re-lists unchanged lines as `-`/`+` near a file end without
a final newline.
Gates (all through `tools/guard.sh`):
- `cargo fmt --all -- --check` — exit 0, no output.
- `cargo clippy --all-targets` — ``Finished `dev` profile [unoptimized + debuginfo] target(s) in 6.96s``, no warnings.
- `cargo test -p lucisv_mcp` — 347 passed, 0 failed, 9 ignored (qa_f1: `test result: ok. 11 passed; 0 failed; 6 ignored`).
- `cargo test --workspace` — 4 903 passed, 0 failed, 56 ignored (4 892 + 11).
**2026-09-23 (QA, Opus) — re-check of the rework: PASS** (findings 1–5
closed; one new low, finding 6, left for the lead).
Re-derived by hand over stdio (the eval shim `mcp_call.sh` on the debug
binary, scratch trees): 5a `(* keep *) b` after an 8-bit `a` — refused,
"`m`'s port list holds `(* keep *) b`…; nothing written", both files
byte-identical (md5); 5b anchor `b` inside the arm behind an unreadable
`d` — refused "inside an `ifdef arm", and `after: "a"` in the same list
refused by the unreadable-element rule; 5c the type swap cannot be built
through the tool (the placer writes the declaration verbatim), so
confirmed as the unit test
`place::verify::tests::a_type_swapped_between_the_anchor_and_the_new_port_is_refused`
(passes); 1 `a /* about a */,` → the new line below it, the comment on
`a`'s line; `.a (a) /* conn a */,` likewise; `b // about b` ⏎
`, input logic c` → `, input logic en, input logic c`. The six pinned
tests (findings 1–5) pass un-ignored and unchanged.
New attacks (`qa_r_*` in `tests/qa_f1.rs`, all byte-exact or tree
byte-identical): an unreadable connection (`..q (p)`) in another module's
instance and in an untouched `.*` instance of `m` — placed, not refused;
in the instance placed into — refused, named `rtl/top.sv`; own-line
comments above the last anchor and closing the list — both stay, header
and connections; `a /* c1 */, // c2` — the new line goes below, both
comments on `a`'s line; a last anchor with `/* c */` before `)` on its
line — `y, /* c */ input logic en)`; a leading-comma list; a typed
undirected `logic [3:0] b` after the anchor — placed under `input`,
refused under `output` (nothing written); a rename writing out a `.*`
binding (one line added above the mentions) — each listed line is the
line on disk after the write (off-by-none).
6. **Low — dry-run mention lines name a file that is not on disk.** The
rework computes mentions on the texts as they would be written, under
`dry_run` too: in the `.*` rename above, the dry run lists
`rtl/top.sv:6 comment: // a feeds u_m`, and line 6 on disk is the
`$display` (the comment is at 5 until the edit is written). The text is
shown beside the line, so an agent can recover; but a dry run's diff
and lines otherwise describe the file on disk. Repro:
`qa_r_dry_run_mention_lines_name_the_file_on_disk` (ignored). Either use
the pre-edit lines under `dry_run`, or say "lines as written" in the
warning — the lead's call.
Gates (all through `tools/guard.sh`, one at a time):
- `cargo fmt --all -- --check` — exit 0, no output.
- `cargo clippy --all-targets` — ``Finished `dev` profile [unoptimized + debuginfo] target(s) in 3.21s``, no warnings.
- `cargo test -p lucisv_mcp` — 362 passed, 0 failed, 4 ignored (unit: `test result: ok. 73 passed`; qa_f1: `test result: ok. 22 passed; 0 failed; 1 ignored`).
- `cargo test --workspace` — 4 918 passed, 0 failed, 51 ignored (4 913 + 5 new).
## Review
**Lead, 2026-09-24 (feedback-1).** The first census round's lesson was
discoverability and completeness of what the server *says*, not the
correctness of what it answers, and this lane changes exactly that: an
"unresolved mentions" section on `references` and the edit tools (the DV
string path round 1 missed is now line 4 of the list on opentitan), a
catalogue 40 % smaller, `hierarchy`/`references` descriptions that route
"who instantiates X" to the right tool, and a positioned `add_port`. The
last is the one piece of new text-moving logic, and QA's first round found
the classic hole — an unreadable port element the placer could not see, so
the next port inherited the new one's type — fixed by refusing any list
with an unreadable element, full-list positions, and a checker that
compares every port's declaration text and pairs each comment with its
anchoring name. Ruling on QA's finding 6: under `dry_run` the mention line
numbers describe the file as it would be written; the line text beside
each number is the recovery, and the wording stays. Committed; the round-2
binary is frozen from this commit.
+312
View File
@@ -0,0 +1,312 @@
# mcp-feedback-2
Lane **feedback-2** of the MCP block: the changes the second token-census
round asked for (`mcp_analysis.md`, Round 2 → "Changes for round 3").
Tracked in `TODO-MCP.md` → "Feedback rounds".
## Goal
Round 2's task a regressed: the agent reached for `hierarchy up`, paged the
77-row answer with a small `limit`, never read the trailing `… and 28 more`
line and reported 35 of 47 instantiations as complete. Every census task
also spent turns dropping `dv/`, `fpv/` and template rows by hand. This lane
puts the total first on every paged answer (`77 instantiations (showing
1–50)`), raises the default page to 500, gives the listing tools a path
glob `in` applied to root-relative paths before paging, and ends the
design-wide edits with the one line that names the files to run
`diagnostics` on.
## Assumptions
- **The header.** Every paged text answer opens with `N <noun>` when the
list is whole and `N <noun> (showing a–b)` when it is cut — `(showing a)`
for a one-entry window, ``(showing none: `offset` is past the end)`` past
the end; singular for 1 (`1 unit`). The trailing `… and N more` stays.
Nouns: `units` (`list_units`), `entries` (`outline`), `symbols`
(`search_symbols`), `hits` (`references`), `findings` (`diagnostics`),
`defines` (`defines`, `` `undef`` rows of the file form included),
`instantiations` (`hierarchy up` with one root line), `nodes` (every
other `hierarchy` walk). An **empty** list keeps its old one-line answer
(`no units match`, `no references`, `no findings`, `no defines`, `no
modules`), except `hierarchy up` from one root, which always has its root
line and now says `0 instantiations`. `project_overview` is not a paged
tool: its `top:` line keeps its own cap of 200 (`read.rs::TOPS_CAP`), so
the overview did not grow with `DEFAULT_LIMIT`.
- **`hierarchy up` from one root.** The window counts the instantiation
lines only; the root line heads every page, `offset`/`limit` skip and
cap instantiation lines, and the JSON's `total`/`shown` count them too
(`nodes` still starts with the root). Lines deeper than 1 are
instantiations of the ancestors and are counted. A root declared twice
(two root lines) is counted as `nodes`, all lines paged, as before.
- **JSON.** Every paged answer's `structuredContent` gains `"shown": [a, b]`
(1-based, inclusive; `[0, 0]` for an empty window) next to `total`, which
is the count after `in`.
- **`in`.** A glob over the root-relative path (`Project::relative`,
`/`-separated): `*` and `?` within one component (the existing
`glob_match`), `**` as a whole component for any run of components, none
included; `**/**` collapses to `**`; a leading `./` is dropped; a trailing
`/` means everything below. Anchored at the root: `ip/**` does not match
`hw/ip/x.sv` (write `**/ip/**`). `**` inside a component (`a**b`) is two
`*`s. An empty `in` filters nothing. The glob only ever sees paths —
names, escaped ones included (`\esc*w `), are never matched against it.
A file outside every root is shown absolute, and matches only a glob
starting with `/` or with `**`. A bare directory (`ip/aes`, no wildcard)
means everything below it, as for `.gitignore` (lead, after QA note 2).
- **What `in` filters, per tool.** `list_units`, `search_symbols`: the
declaring file. `references`: each hit's file, and the unresolved
mentions are searched only in matching files (the engine still runs over
the whole set — a use can resolve through any file). `defines`: the
defining file (both forms). `diagnostics`: the whole-project form lints
only matching files; the file form keeps its findings only when the file
matches; a filtered whole-project run does not report unused external
waivers (only a complete run knows a waiver matched nothing).
`hierarchy`: `up` keeps an instance when the file holding it matches
(the walk does not climb through a dropped instance); `down` keeps a
child when any declaration of its module lies in a matching file (a
module that is not indexed has no file and is dropped; a dropped child's
subtree is not walked); with no `root`, top modules are kept by their
own file. An explicit `root` line is always shown.
- **"none match".** ``0 <noun> (none match `in`)`` is said only when the
glob removed every entry there was; a list that was empty before the
glob keeps its old empty answer (`no symbols match`), and so does a
whole-project `diagnostics` whose matching files are clean (`no
findings`); ``0 findings (none match `in`)`` means no file matched.
`hierarchy`: `up` from one root when the module has instantiations and
none is kept (root line still shown); no-root `down` when no top module
is kept.
- **The check line.** `rename`, `add_port`, `remove_port`,
`expand_wildcard`, `extract_module` and `inline_module` end their text
with `check: diagnostics on <files>` (`check after writing: …` for a dry
run): the changed and created files, root-relative, in path order, the
first 5 then `and N more`. An `unchanged` answer and a refusal get none.
The line is appended after `apply::run` (below the diff on a dry run);
the JSON is unchanged. `convert_ports`, `organize_imports`,
`propagate_ports`, the item tools, `format` and `fix_lint` do not carry
it (not in the brief).
- **Catalogue.** `tools/list` measured as the test measures it
(`result.to_string().len()`): 17 981 B at 4671b91; with the `in`
arguments and the brief's wording it was 18 696 B; after the trims below
it is **17 993 B** (≤ 18 000, pinned by `the_tool_catalogue_stays_under_18_kb`
and `qa_the_catalogue_is_small_fully_described_and_spec_shaped`). The
generic `in` description is "Path glob the file must match, e.g.
`ip/**/rtl/*.sv`." — the brief's longer wording did not fit five times;
`hierarchy`'s says which file per direction. Trimmed, in this lane's
files only: every `limit` description to "Default 500."; `include_
declaration` to "Default true."; `direction`/`depth`/`home` to their
defaults; the descriptions of `project_overview`, `list_units`,
`search_symbols`, `definition`, `references`, `hierarchy` (it still
starts "Who instantiates a module (`up`"; "all branches" dropped),
`diagnostics`, `defines`, `rename`, `organize_imports`, `propagate_ports`,
`remove_port`, `add_port`, `extract_module`, `instantiate`; titles
`List units`, `Definition`, `Rename`, `Inline an instance`, `Extract a
module`; `defines.name` lost "(backtick optional)" (still accepted).
- **`INSTRUCTIONS`** (896 characters): "; `in` filters by path glob" after
the finder tools; the edit sentence now says each edit "names files for
diagnostics" and the separate "Run diagnostics after an edit." is gone;
"Verilog/SystemVerilog" → "SystemVerilog", "from the files on disk
(never unsaved editor buffers)" → "from disk, never unsaved buffers" to
stay under 900.
## Handshakes
- **Consumed:** unchanged — `Project::{relative, index, files}`,
`WorkspaceIndex`, `apply::run`'s `structuredContent`
(`changed`/`created` arrays of `{file}`), which the check line reads.
- **Promised (answer shapes, changed):** the first line of every paged text
answer is the count line above; `structuredContent.shown` on every paged
answer; `hierarchy up` from one root pages and counts instantiation lines
(the root line repeated per page); six tools take `in`; six edit answers
end with the check line. The MCP resources (`lucisv://file/…/outline`)
run `outline` and so start with its count line too (`resources.rs`
untouched).
- **Flag for the lead (docs outside the lane):** `docs/mcp/PLAN.md` and
`docs/features/mcp-navigation/README.md` still say "default 200"; the
Agents guide, if it quotes answers, shows them without the count line.
## Status / TODO
- [x] `render.rs`: `Page` (window, `header`, `shown_json`, `rest`),
`Noun`, `none_match`; `DEFAULT_LIMIT` 500
- [x] header + `shown` on `list_units`, `outline`, `search_symbols`,
`references`, `hierarchy`, `diagnostics`, `defines`
- [x] `in`: `read.rs::{path_match, in_glob, only_in, IN}`; wired into the
six tools
- [x] check line: `edit.rs::with_check` on the six edits
- [x] `INSTRUCTIONS` clause; catalogue ≤ 18 000 B
- [x] tests: unit (header, path glob, check cap), wire (8), existing
first-line pins updated
- [x] QA — PASS 2026-09-23 (see QA log)
## Work log
**2026-09-23 (dev, Opus).**
- `render.rs`: `Page::of` wraps the old `page`; `header` puts the total
first; `none_match`. `page` and `more` stay (the overview's `top:` and
warnings lines use them).
- `read.rs`: `IN`, `in_glob`, `path_match`/`components_match` (split on
`/`, `**` recursion, `glob_match` per component), `only_in` (filter +
"emptied"); `list_units` filters before the walk-on-miss check, so a
glob or an `in` that misses walks once; `search_symbols` computes a hit's
relative path only when `in` is given; `outline` header; `TOPS_CAP`.
- `nav.rs`: `references` filters hits with `only_in` and passes only
matching files to `mentions::find`.
- `hierarchy.rs`: `Walk` holds the project and the glob; `keeps(file)`;
`down` skips a child whose module has no matching declaration, `up`
skips an edge in a non-matching file, no-root tops are filtered; `Shape`
(`up`, `single_up`, `emptied`) drives `render`, which pages the counted
slice and prints the lead root line on every page.
- `diagnostics.rs`: `project_findings` (the whole-project form, filtering
paths before linting, no unused-waiver report under `in`); file-form
findings go through `only_in`.
- `defines.rs`: both forms filter with `only_in`; a small `Listing` carries
the page facts out of either form.
- `edit.rs`/`refactor.rs`: `with_check` wraps `rename`, `remove_port`,
`expand_wildcard`, `inline_module`, `add_port`, `extract_module` (the
bodies moved to `rename_at`, `remove_port_at`, `add_port_to`,
`extract_lines`).
- Fixture `tests/fixtures/paths/` (ip/aes/{rtl,dv}, ip/uart/rtl/sub, top,
an escaped `\esc*w ` parameter and `\esc*name ` net, a `lucisv.toml`
selecting `unused-signal`).
- Existing assertions updated (the brief's allowance: they pinned the old
first line of a paged answer, or a line count that now includes it):
qa_m1 — the `list_units`/`outline`/`search_symbols` literals gain
`1 unit\n` etc. (16 tests), one outline `starts_with`; qa_m2 — `defines`,
`diagnostics`, `hierarchy` literals, two `lines().count()` 21 → 22, the
escaped-path resource loop reads past the count line; wire — the
`defines`, `diagnostics`, `hierarchy`, `references`, `outline`,
`search_symbols` literals and the outline resource check.
- Measured on the opentitan checkout (debug build, read-only):
`hierarchy up prim_fifo_sync depth 1` → `77 instantiations`, the same
with `in: "hw/ip/**/rtl/*.sv"` → `47 instantiations` (round 2's 47);
`list_units in hw/ip/aes/**` → 129 units in 32 ms.
- Gates (all through `tools/guard.sh`, one at a time): `cargo fmt --all
-- --check` exit 0; `cargo clippy --workspace --all-targets` `Finished`,
no warnings; `cargo test -p lucisv_mcp` 373 passed, 0 failed, 4 ignored
(unit 76, wire 55); `cargo test --workspace` exit 0, **4 929 passed, 0
failed, 51 ignored** (4 918 before: +8 wire, +3 unit); the ignored
`opentitan` tests (`LUCISV_OPENTITAN` default path, `--ignored`) 2
passed, the checkout only read. No guard kill.
## QA log
**2026-09-23 (QA, Opus) — verdict: PASS.** No correctness finding; four
low-severity notes for the lead (none blocks round 3). New file
`crates/lucisv_mcp/tests/qa_f2.rs` (14 tests, all passing, none ignored);
no source touched.
- **Count line, one rule over every paged tool.**
`qa_every_paged_tool_agrees_with_its_json_over_every_window` runs 18
base calls (`list_units`, `search_symbols`, `outline`, `references`,
`diagnostics`, `defines` both forms, `hierarchy` up/down/no-root, with
and without `in`) × 11 windows each (`limit` 1, 2, n; `offset` 0, 1,
n−1, n, n+3; default) and checks: the first line's number is the JSON
`total`; its window is the JSON `shown` (`[1, n]` whole, `[0, 0]` past
the end or empty); the JSON list holds exactly the window (+1 root line
for `hierarchy up` from one root); `… and N more` equals `total − b` and
is absent when nothing follows; singular only for 1; `(showing a)` only
for a one-entry window; no window on a whole list. All hold. Literal
pins for whole / cut / `(showing a)` / past the end (outline keeps its
file line past the end) / `1 unit`, `1 entry`, `1 hit`, `1 finding`,
`1 define`, `1 symbol`, `1 instantiation`.
- **`hierarchy` counting.** `up` from one root: the root line heads every
page (13 offsets, `limit` 2) exactly once, past the end included;
`total` counts the depth-2/3 lines too (11 = 13 lines − count − root);
a root with no instantiations `0 instantiations` + root line; a root
declared twice falls back to `nodes` with every line paged; no-root
`down` from five tops counts nodes (`9 nodes (showing 4–6)`).
- **`in`.** `*` stays in one component (`ip/aes/rtl/*.sv` does not reach
`rtl/sub/deep.sv`, `rtl/**` does); `**` spans zero components
(`ip/**/x.sv` ↔ `ip/x.sv`, `**/x.sv`); anchored (`ip/**` excludes
`hw/ip/y.sv`, `**/ip/**` and `*/ip/*` reach it); `?` is one character
and never `/`; `./`, trailing `/`, `**/**`; a whole-path glob is no
substring search (`aes`, `*.sv` at depth). A `*` in a directory name
and a space in one match literally. Names are never matched: the unit
`\esc*mod ` is not found by `in: "\esc*mod "` or `esc*`, only by its
path. "None match" only when the glob removed something — the old empty
answers stay for `list_units`, `search_symbols`, both `defines` forms,
file-form `diagnostics`; whole-project `diagnostics` over clean matched
files says `no findings`. `in` + `offset` + `limit`: total is the
filtered count. `references`: a mention outside the glob is dropped
(JSON `unresolved_mentions` too); hits emptied with a mention kept says
both. `hierarchy down`: a dropped child's subtree is not walked
(`tb` with `in: "lib/*"` shows `u_d : leaf` but not `lib/mid.sv` under
the dropped `aes`); `up` does not climb through a dropped instance.
Whole-project `diagnostics` with `in` never reports the unused waiver
(`**/*.sv`, `hw/**`, `*.waiver`, `w.waiver`), without `in` it does.
- **Check line.** All six edits, dry run (`check after writing:`, after
the diff, tree byte-identical, JSON without a new key) and real
(`check:`); repeated → `unchanged`/refusal with no line; `convert_ports`
carries none; 8 files → five in byte order (`B/` < `a.x/` < `a/b/` <
`a/` < `c/`) `and 3 more`, dry and real.
- **Changed assertions** (`qa_m1.rs` 16 literals + 1 `starts_with`,
`qa_m2.rs`, `wire.rs`): every hunk read — each only prepends the count
line or adds 1 to a line count (21 → 22 with the count line). Two
resource checks are marginally looser: `wire.rs:758` went from
`starts_with("rtl/top.sv\n…")` to `contains("entries\nrtl/top.sv\n…")`,
and the `qa_m2.rs:749` loop skips the first line unchecked; both still
pin the file line and the first entry. Not a weakening worth a finding.
- **Budgets.** Catalogue 17 993 B (≤ 18 000); `INSTRUCTIONS` 896 chars
(≤ 900); every tool name in it exists; every argument described; `in`
on exactly the six tools; every `limit` says 500. Production lines after
the lane: `read.rs` 454, `hierarchy.rs` 357, `nav.rs` 370,
`diagnostics.rs` 348, `edit.rs` 288, `render.rs` 172 — all under 600.
- **opentitan** (eval clone `~/.cache/lucisv-eval/ot/hw`, `--root …/hw` as
round 3 runs it, release binary, read-only, `git status` clean after):
`hierarchy up prim_fifo_sync depth 1` → `77 instantiations`; with
`in: "ip/**/rtl/*.sv"` → `47 instantiations` (round 2's 47); `limit 50`
→ `77 instantiations (showing 1–50)`, `offset 50` → `(showing 51–77)`.
`references clk_i` (aes_core.sv:30) 2.60 / 2.69 s, 24 hits — the same
as feedback-1's recorded 2.60–2.69 s; with `in: "ip/aes/**"` 2.42 /
2.44 s. `search_symbols ""` with `in` 0.11 s (95 237 → 2 671), a
pathological `**/*/**/*/…/zzz` glob 0.22 s. The ignored `opentitan`
tests (`--ignored`, default checkout, read-only) 2 passed.
- **Gates** (all through `tools/guard.sh`, one at a time): `cargo fmt
--all -- --check` exit 0; `cargo clippy --workspace --all-targets`
`Finished`, 0 warnings; `cargo test -p lucisv_mcp` 387 passed, 0
failed, 4 ignored (qa_f2 14); `cargo test --workspace` exit 0, **4 943
passed, 0 failed, 51 ignored** (4 929 + 14). No guard kill.
Notes for the lead (low; no ignored test — each is a wording or design
call, not a spec violation):
1. **Doc inaccuracy** (Assumptions, "`in`"): "A file outside every root …
matches only a glob starting with `/`" — a leading `**` matches it too
(`**` spans the empty first component of `/abs/…`). Repro: a
`--filelist` naming `/…/ext/outer.sv`, `list_units {"in": "**/*.sv"}`
lists it. Behaviour is reasonable; reword to "a glob starting with `/`
or `**`".
2. **A bare directory matches nothing**: `in: "ip/aes"` or
`"ip/uart/rtl"` → ``0 units (none match `in`)``; only `ip/aes/` or
`ip/aes/**` work. The answer lets an agent recover, at the cost of a
turn; gitignore/`rg -g` treat a pattern naming a directory as its
subtree. Either do that (a glob that matches a proper directory prefix
of the path keeps it) or say "a directory needs `/**`" — the
catalogue has 7 bytes left, so `INSTRUCTIONS` (4 chars left) cannot
carry it either without a trim.
3. **`diagnostics` `in: "**"`** keeps every file yet suppresses the
unused-waiver report; `paths.len() == all.len()` would be the exact
"complete run" test (`diagnostics.rs::project_findings`). As briefed,
kept.
4. **`hierarchy down` with an explicit `root`** whose glob drops every
child says `1 node` with no "none match" signal (as specified — the
root line is always shown), while `up` says
``0 instantiations (none match `in`)``. The work-log example
`in: "hw/ip/**/rtl/*.sv"` → 47 is right for a server rooted at the
checkout top; round 3 roots at `hw`, where that glob answers
``0 instantiations (none match `in`)`` and the one to quote is
`ip/**/rtl/*.sv` (verified 47 above).
## Review
**Lead, 2026-09-24 (feedback-2).** Round 2's regression on the census task
was a rendering fault, not an engine one: a 77-row answer paged with a small
limit and a count at the bottom the agent never read. The count line now
leads every paged answer, the default limit is 500, and the `in` path glob
returns exactly the rows a "under `ip/`, RTL only" question asks for — on
opentitan, `hierarchy up prim_fifo_sync` with `in: "ip/**/rtl/*.sv"` answers
47 instantiations in one call, the round-1 ground truth. QA passed it with
14 tests and four notes; the lead took note 2 (a bare directory glob means
everything below it, as `.gitignore` reads it) and the README's outside-root
sentence, and left notes 3 and 4 as documented behaviour. Committed; the
round-3 binary is frozen from this commit.
+298
View File
@@ -0,0 +1,298 @@
# mcp-feedback-3
Lane **feedback-3** of the MCP block, the last census lane: the changes the
third token-census round asked for (`mcp_analysis.md`, Round 3 →
Observations and "Still to do"). Tracked in `TODO-MCP.md` → "Feedback
rounds".
## Goal
Round 3's task d (the `entropy_src` instance tree with 20 port counts) came
out at +4 % tokens with a third of the tool calls. Most of the server's
overhead there was twenty `unit_interface` answers, each carrying a
30-line instantiation template the task never used. `hierarchy` lines had
the same problem: every line carried the instance's `#( … )` overrides,
which a census rarely reads. This lane makes both **opt-in**:
`unit_interface` gains `template` and `hierarchy` gains `overrides`, both
default false. The JSON of `hierarchy` keeps `overrides` on every node,
because it costs little there. `unit_interface`'s section headers now carry
their counts (`parameters (6):`, `ports (12):`), so a port count can be
read without counting lines.
## Assumptions
- **`unit_interface` without `template`** (or with `template: false`):
the text is the head line, `parameters (N):` (if any), `ports (N):` (if
any), `modports:` (if any), then the `warning:` lines. There is no
`template:` section. The JSON has no `template` key at all (not `null`).
**With `template: true`** the text ends with `template:` and the
rendered plan, and the JSON has `template` as before. Otherwise the
JSON is identical key for key (pinned by a wire test). The plan is
still built either way: ports and parameters come from it. Only the
`render` step is skipped.
- **Packages and classes** take the `template` flag and ignore it: they
have no template. The member answer is unchanged, and its `members:`
header gets no count, because the brief named only ports and
parameters.
- **`modports:`** keeps its header without a count, for the same reason.
- **`hierarchy` without `overrides`**: each line is exactly the old line
without the ` #( … )` segment: `instance : module` (`down`),
`parent.instance file:line` (`up`), and root lines as before. A note
(`(recursive)`, `(not indexed)`, `(declared N times)`) still ends the
line. **With `overrides: true`** the line is byte-identical to the old
default, capped at `OVERRIDES_CAP` (200) as before. The JSON is the same
with or without the flag: `overrides` is on every node (`null` where the
site has none).
- The brief wrote the `up` line as "`instance : module file:line`". The
line has been `parent.instance file:line` since M2, and the brief also
says "exactly as today minus the overrides". I kept today's shape.
- **Census task a** asks for "both params on every row", so it now needs
`overrides: true`. The `hierarchy` parameter description and
`INSTRUCTIONS` both say so. A re-run of task a should be read with this
in mind.
## Handshakes
- **Consumed:** unchanged: `instantiation_plan` and `InstantiationPlan::render`
(`vlog_refactor`), `Args::flag` (`tools/mod.rs`).
- **Promised, changed (answer shapes):**
- `unit_interface`'s default text no longer ends with `template:`, and
its default JSON has no `template` key. Its headers read
`parameters (N):` / `ports (N):`. A new optional boolean argument,
`template`.
- `hierarchy`'s default text lines drop the `#( … )` segment. There is a
new optional boolean argument, `overrides`. The JSON is unchanged.
- The resources (`lucisv://…`) do not call either tool; nothing else in
the crate consumes these texts.
- **Out-of-ownership edit (flagged for the lead's ruling):**
`crates/lucisv_mcp/src/tools/edit.rs:30`. The shared `DRY_RUN`
parameter description changed from "Return the diff only." to "Diff
only.". The two new parameters took `tools/list` to 18 273 B. Trimming
every description in this lane's files as far as it would go, without
losing meaning, got it to 18 074 B, still over the 18 000 B pinned by
`the_tool_catalogue_stays_under_18_kb` and
`qa_the_catalogue_is_small_fully_described_and_spec_shaped`. `dry_run`
appears 14 times, so this one edit saves 154 B. The catalogue is now
**17 943 B**. The brief allowed "trim a description if needed" and did
not say whose. To revert: restore the string and trim ~75 B elsewhere.
- **Request (not done, outside ownership):** the Agents guide
`docs/site/src/content/docs/guides/agents.md:102` still promises "a
ready-to-paste instantiation" by default. Line 109 still shows
`instance : module #(overrides)` lines. Both need "on `template: true`" /
"on `overrides: true`". `docs/mcp/PLAN.md:146,263` describe the
original design and can stay as history.
## Status / TODO
- [x] `unit_interface`: `template` (Bool, default false); text and JSON
without the template by default; `parameters (N):` / `ports (N):`;
description names `template: true`
- [x] `hierarchy`: `overrides` (Bool, default false) on the text line;
JSON unchanged; description updated
- [x] `INSTRUCTIONS`: the hierarchy clause names `overrides: true` (896
characters, unchanged length). `template: true` does not fit (940
with both); the `unit_interface` description carries it
- [x] wire tests: both defaults and both opt-ins, text and JSON; existing
pins moved to the opt-in (listed in the work log); catalogue
≤ 18 000 B
- [x] measured on the eval clone (below)
- [x] QA — PASS 2026-09-23 (see QA log)
## Work log
**2026-09-23 (dev, Opus).**
- `src/tools/interface.rs`: `UNIT_INTERFACE` gains the `template` param
(l.36–41). The description is "A unit's parameters, ports (direction,
type, range), modports or members; `template: true` adds an
instantiation." The brief's "paste-ready" wording was trimmed for the
catalogue budget. The handler reads `args.flag("template", false)`
(l.67). `instantiable` takes `with_template` and renders the plan only
then (l.144). `template` is added to the JSON only when present
(l.156–157). `interface_text` takes `Option<&str>` and writes the counted
headers (l.183, l.189) and the template section only on request
(l.205). The module doc says the template is on request.
- `src/tools/hierarchy.rs`: `HIERARCHY` gains the `overrides` param
(l.81–86, "Add each `#(…)` to the text lines.").
The description no longer lists overrides: "Who instantiates a module
(`up`, with file:line) or what it instantiates (`down`, default).
Textual." `render` reads the flag (l.341) and passes it to `Line::text`,
which shows the overrides only then (l.394–400). The JSON's
`Line::json` is untouched. Trimmed for the budget: `depth` → "Default
3." (the schema's `maximum: 20` says the rest), `in` → "Path glob on
the instantiating file (`up`) or the module's (`down`), e.g.
`ip/**/rtl/*.sv`.".
- `src/rpc.rs` `INSTRUCTIONS`: "Who instantiates module X (instances,
overrides): hierarchy with direction up, not references." → "Who
instantiates module X: hierarchy direction up (overrides: true adds
#(…)), not references." (896 → 896 characters). The old clause promised
overrides in the default answer, which is no longer true. Adding
`template: true` as well measured 940 characters, so it was left out.
- `src/tools/mod.rs`: no change needed (`Ty::Bool` and `Args::flag`
already existed).
- `src/tools/edit.rs:30`: `DRY_RUN` description "Diff only." (see
Handshakes: an out-of-ownership edit, flagged).
- Tests (`tests/wire.rs`):
- New: `unit_interface_template_is_opt_in`. It checks that the default
text ends at the last port, the JSON has no `template` key, and
`template: false` equals the default. With `template: true` the
template section comes after the ports and the JSON equals the default
plus `template`. It also covers an interface's template after its
modports, the refusal of `"template": "yes"`, and a package ignoring
the flag.
- New: `hierarchy_overrides_are_opt_in_on_the_text_and_always_in_the_json`.
It checks that `up` with `overrides: true` is byte-identical to the old
default, the JSON is equal with and without the flag, `false` equals
the default, and `down` and a recursive line work with the flag. It
also covers the refusal of `"overrides": 1`.
- Existing assertions changed (they pinned the old default output):
- `wire.rs`:
- `unit_interface_answers_ports_parameters_modports_and_members`: the
header prefix now reads `parameters (2):` … `ports (4):`, and the
template assertion now asserts that `template:` is absent.
- `hierarchy_walks_down_and_up_and_terminates_on_recursion`: the
three literals (tops, `tree`, `core` up) lose their overrides. The
JSON node assertion still has `"overrides": "#( .W (8) )"`.
- `qa_m1.rs`:
- `qa_an_escaped_identifier_unit_is_listed_described_and_instantiable`
now passes `template: true`.
- `qa_a_typed_parameter_keeps_its_default_and_a_localparam_is_not_offered`
now passes `template: true` (it reads `structuredContent.template`).
- `qa_m2.rs`:
- `qa_hierarchy_terminates_on_self_and_mutual_recursion`: the `selfm`
call now passes `overrides: true`.
- `qa_finding_4_every_instance_of_one_statement_shows_only_the_overrides`:
the text `up` call now passes `overrides: true`.
- `qa_recheck_overrides_split_across_lines_and_comments_between_instances`:
both calls now pass `overrides: true`.
- `opentitan.rs` (ignored without the checkout): the `top_earlgrey`
call that asserts `u_aes : aes #(` now passes `overrides: true`.
- **Measured** on the eval clone, read-only (`target/release/lucisv-mcp
--root ~/.cache/lucisv-eval/ot/hw`, no `--index-cache`, so nothing is
written; `git status --porcelain` in the clone was empty before and
after). Bytes of `content[0].text` and of the compact
`structuredContent`:
| call | text B (lines) | JSON B |
|---|---|---|
| `unit_interface prim_fifo_sync` | **596** (21) | 1 284 |
| … `template: true` | 999 (43) | 1 710 |
| `hierarchy up prim_fifo_sync in ip/**/rtl/*.sv` (default depth 3) | **22 163** (349) | 102 939 |
| … `overrides: true` | 64 783 (349) | 102 939 |
| same, `depth: 1` (task a's 47 rows) | **3 238** (49) | — |
| … `overrides: true` | 7 230 (49) | — |
So `unit_interface` is −40 % by default (403 B saved per call; round 3's
task d made 20 such calls; the saving grows with the port count), and the
`hierarchy up` text is −66 % at depth 3 and −55 % at depth 1. The JSON
of `hierarchy` does not change. `tools/list` is 17 943 B, down from
18 273 B with the two new parameters before the trims. Catalogue at
c2e42b8: 17 993 B, per mcp-feedback-2.
- Gates (through `tools/guard.sh`, one at a time): `cargo fmt --all`
clean; `cargo clippy --all-targets` `Finished`, no warnings; `cargo
test -p lucisv_mcp` 390 passed, 0 failed, 4 ignored (wire 55 → 57);
`cargo test --workspace` **4 946 passed, 0 failed, 51 ignored**.
- Production lines (non-blank, non-comment, before `mod tests`):
`interface.rs` 334, `hierarchy.rs` 364, `mod.rs` 181, `rpc.rs` 265,
`edit.rs` 288.
## QA log
**2026-09-23 (QA) — verdict: PASS, no findings against the lane.**
Read `CLAUDE.md`, this README, `git diff` of `src/tools/{interface,hierarchy,edit}.rs`,
`src/rpc.rs` and `tests/{wire,qa_m1,qa_m2,opentitan}.rs`.
- **Baseline binary, not a re-derivation.** HEAD (c2e42b8) was exported
with `git archive HEAD` into the scratchpad (no worktree, repo untouched)
and built there (`--target-dir` in the scratchpad), so "`template: true`
/ `overrides: true` equals the old default" was checked against the old
binary's own bytes. `vlog_parser`, `vlog_refactor`, `vlog_formatter` and
`vlog_semantic` have no diff since v0.56.0, so the template renderer is
the 0.56.0 one; the 0.56.0 vsix `lucisv-mcp` agreed on every
`unit_interface` too (its `hierarchy` predates feedback-2's count line,
so only HEAD's is a valid hierarchy baseline).
- **Differential, all six fixture trees** (`tests/fixtures/*`, every unit
from `list_units`; every module `down` and `up` at depth 20): 50/50
`unit_interface` — `template: true` text = old text with only
`parameters:`/`ports:` → `(N)`; JSON = old JSON key for key; default
text = that text cut at `template:\n`; default JSON = old minus the
`template` key (absent, not `null`); counts = rows = JSON array lengths;
packages/classes identical with and without the flag. 78/78
`hierarchy` — `overrides: true` text byte-identical to the old text
(refusals too), JSON identical across old/flag/default, no default line
holds `#(`, every node has an `overrides` key.
- **Same differential on the eval clone** (`~/.cache/lucisv-eval/ot/hw`,
read-only, no `--index-cache`; `git status --porcelain` empty before and
after): 12 units (`prim_fifo_sync`, `aes`, `entropy_src`,
`top_earlgrey`, `uart`, `tl_if`, …, two declared-twice refusals
identical) and 5 hierarchy calls (`top_earlgrey` depth 2,
`prim_fifo_sync` up with `in`/depth 1, `aes` up, `entropy_src` depth 3):
all equal. Default text (characters) is 17–45 % smaller for
`unit_interface` (`tl_if` least, few ports) and 48–83 % for `hierarchy`.
- **`tests/qa_f3.rs`** (new, 7 tests, all pass), pinned against literals
the c2e42b8 binary produced on the same tree:
1. `template: true` byte-identical for an interface with modports, a
module with `ifdef`'d lists (warnings, then the template), an empty
module, multi-declarator/unpacked ports; JSON `template` = the old
section; default ends before `template:` with no `template` key.
2. a `program` is instantiable (template on request); a package's answer
is identical with `template: true`.
3. counts: `parameters (N):`/`ports (N):` = indented rows = JSON length
for 5 shapes. **Zero parameters or zero ports: the header is absent,
not `(0)`** — the pre-lane rule (an empty section is left out), and
sensible: the JSON still has `[]`, and a `(0)` header would cost
tokens to say nothing. `modports:` keeps no count; rows complete.
4. `hierarchy` `up` and `down` over an instance whose overrides exceed
the 200-char cap, one without, one with a comment inside `#(…)`:
`overrides: true` = old text (cap and `…` kept); default = each old
line minus exactly ` <capped overrides>` of that node; JSON equal
with/without flag, full uncapped overrides present.
5. default vs `overrides: true` under `limit`/`offset`, `in`, `depth: 1`
and the no-root listing: same count line, same line count, same JSON,
no `#(` in the default.
6. `"true"`, `1`, `[true]`, `{}` refused for both flags naming the field
and "true or false"; `null` is taken as the default (as for every
`Ty::Bool` flag — `Args::flag` uses `as_bool`); each flag is refused
on the other tool as an unknown argument.
7. catalogue ≤ 18 000 B (measured **17 943 B**, 57 B headroom), both
flags `boolean` and not required; `unit_interface`'s description
names `` `template: true` ``, `hierarchy`'s no longer promises `#(`;
`INSTRUCTIONS` **896 chars**, says `overrides: true`, dropped
"(instances, overrides)", names only existing tools.
- **Changed existing assertions** — every hunk read: `wire.rs` (header
prefix gains the counts and `ports (4):`, the template assertion becomes
its absence; three `hierarchy` literals lose exactly their `#(…)`
segments, the JSON node assertion is unchanged), `qa_m1.rs` (2 calls add
`template: true`), `qa_m2.rs` (4 calls add `overrides: true`, literals
unchanged), `opentitan.rs` (1 call adds `overrides: true`). Each is a
flag addition or a literal minus the overrides/template; nothing
weakened. `opentitan_navigation_matches_the_language_server` run
(`--ignored`, read-only over /Users/guoliangchen/repo/opentitan): ok,
83 s; checkout status unchanged.
- **Out-of-ownership `edit.rs:30`** (`DRY_RUN` → "Diff only."): no test or
consumer depends on the old string; meaning survives next to
`dry_run: true shows the diff first` in `INSTRUCTIONS`. Left for the
lead's ruling as flagged.
- **Size/style:** production lines `interface.rs` 334, `hierarchy.rs` 364,
`edit.rs` 288, `rpc.rs` 265; the changed functions (`instantiable`,
`interface_text`, `render`, `Line::text`) are all under 50 lines. No
`unwrap`/`expect` added to library code.
- **Gates** (through `tools/guard.sh`, one at a time): `cargo fmt --all
--check` clean; `cargo clippy --all-targets` `Finished`, no warnings;
`cargo test -p lucisv_mcp` **397 passed, 0 failed, 4 ignored** (390 +
7); `cargo test --workspace` **4 953 passed, 0 failed, 51 ignored**
(4 946 + 7).
- **Not done here (lead's list):** the Agents guide request in
Handshakes; the census re-measure of tasks a/d.
## Review
**Lead, 2026-09-23 (feedback-3).** The last census lesson was answer
weight: twenty `unit_interface` answers each carrying a template the task
never used. Both the template and the hierarchy overrides are now opt-in,
the ports and parameters headers carry their counts, and QA proved the
opt-in text byte-identical to the old output over every fixture and the
opentitan clone. The `dry_run` wording trim in `edit.rs` is accepted. The
Agents guide's tool table was regenerated from the binary by the lead.
Committed; the release binary is this one.
+5 -1
View File
@@ -142,7 +142,7 @@ instead of calling tools.
language server's `pairs::missing_end_diagnostics`, not a library API,
and the tolerant tree's diagnostics alone do not carry them. The
whole-project form lints every indexed file (1.9 s on opentitan, 2 100
findings) and returns the first `limit` (default 200) with the total.
findings) and returns the first `limit` (default 500 since feedback-2) with the total.
**Unused external waivers**: the whole-project form, being a complete
run, reports each `[lint] waivers` directive that suppressed nothing as an
`unused-waiver` finding against the waiver file (`ExternalWaivers::unused`
@@ -433,6 +433,10 @@ passed, `opentitan` 1 ignored, `qa_m1` 51 passed, `qa_m2` 32 passed,
`wire` 19 passed; `cargo test --workspace` exit 0 in 254 s, **4 599
passed, 0 failed, 47 ignored**.
**2026-09-23 (dev, feedback-1).** `references` now ends with an `unresolved mentions` section and carries `unresolved_mentions` in its JSON (handshake change: a new trailing section and a new JSON key; hits unchanged); `references`/`definition`/`hierarchy` descriptions trimmed, `hierarchy` leads with "who instantiates a module" — `docs/features/mcp-feedback-1`.
**2026-09-23 (dev, feedback-3).** `hierarchy`'s text lines show the `#( … )` overrides only on `overrides: true` (handshake change: the default line drops them; the JSON keeps `overrides` on every node) — `docs/features/mcp-feedback-3`.
## QA log
**2026-09-23 (QA, M2). Verdict: rework needed** — four blocking findings
+339
View File
@@ -0,0 +1,339 @@
# mcp-packaging
## Goal
Ship `lucisv-mcp` (the Model Context Protocol server of `docs/mcp/PLAN.md`)
the way `lucisv-server` ships: as a third binary in every platform `.vsix` and
in the all-platforms one, smoke-tested out of the package by
`tools/release.sh`; registered by the VS Code extension with agent mode (one
stdio server per workspace folder) on a VS Code that has the MCP API; and
reachable from hosts that do not read VS Code's registry (Claude Code, Cursor)
through a copy-config command and a docs page. TODO-MCP **M5**, PLAN §5.
## Assumptions
- **Engine stays `^1.82.0`.** `npx @vscode/vsce package` (vsce 4.0.0,
2026-09-23) packages `contributes.mcpServerDefinitionProviders` under
`^1.82.0` with no warning beyond the pre-existing "bundle your extension"
one, so no bump. The registration is guarded at runtime: `vscode.lm`,
`vscode.lm.registerMcpServerDefinitionProvider` and
`vscode.McpStdioServerDefinition` must all exist (VS Code 1.101+); on an
older VS Code nothing is registered, one line goes to the lucisv output
channel, and the rest of the extension is unaffected.
- **`McpStdioServerDefinition`'s constructor is positional**, not an object:
`(label, command, args?, env?, version?)`, with `cwd` a plain property.
Verified against the installed VS Code 1.138's `vscode.d.ts` and its
extension-host implementation (`constructor(t,e,n,o={},i,s){this.label=t;
this.command=e;this.args=n;this.env=o;this.version=i;…}`). PLAN §2.3 and the
VS Code extension guide's sample show an object argument — that would make
the object the label and leave `command` undefined. `mcp.js` uses the
positional form and assigns `cwd` afterwards.
- **Activation.** `activationEvents` is unchanged: VS Code derives
`onMcpCollection:lucisv.mcp` from the contribution point itself (seen in the
1.138 workbench: `activationEventsGenerator` yields it for every provider
id), so agent mode can activate the extension without a Verilog file open.
Activation starts the language server too — `mcp.activate` is called at the
end of `extension.js`'s `activate`, after the server start.
- **Where the binary is found** — the server's three-rung ladder: an explicit
`lucisv.mcp.path` (read with `inspect()`; blank and the manifest default
count as unset — the `userServerPath` rule), else `bin/lucisv-mcp` or
`bin/<platform>-<arch>/lucisv-mcp` in the package (`extension.js`'s own
`bundledBinary`, handed to `mcp.activate` — so there is one implementation
of the two layouts and the chmod), else `lucisv-mcp` on `PATH`.
- **What the extension passes**: `--root <folder fsPath>` and, when VS Code
gives one, `--index-cache <storageUri, else globalStorageUri, fsPath>` — the
same directory the language server receives as `storagePath`. `cwd` is the
folder's URI, `env` is `{}`, `version` is `package.json`'s. Not passed:
`lucisv.index.cachePath` (the LSP's override of that directory) and
`lucisv.filelist` (MCP reads the project's `lucisv.toml` `filelist` itself).
M6, which reads the store, may want the former.
- **What VS Code shows**: one `lucisv (<folder name>)` server per workspace
folder under **MCP: List Servers**; trust is VS Code's own per-server
prompt. A folder added/removed or any `lucisv.mcp.*` change fires
`onDidChangeMcpServerDefinitions`, so the list follows without a reload.
- **`lucisv.mcp.enabled: false` is live.** The provider stays registered and
returns no definitions while the setting is off (one output-channel line at
activation says so); turning it back on needs no reload. The brief said
"register nothing" — returning nothing has the same visible effect and
avoids the reload.
- **A missing binary is not started.** `resolveMcpServerDefinition` checks the
command exists (as given when it has a directory part, else on `PATH`);
when not, it logs one line to the lucisv output channel and returns
`undefined`, which the API defines as "do not start". This is the universal
package on a machine without `lucisv-mcp`.
- **Hosts that need the copied config**: Claude Code (`.mcp.json`,
`mcpServers`), Cursor (`.cursor/mcp.json`, `mcpServers`) — neither reads VS
Code's provider registry — and VS Code itself when configured by hand
(`.vscode/mcp.json`, `servers` with `type: "stdio"`). The snippet names the
resolved binary and one `--root` per workspace folder; when that binary is
the bundled one, the message warns that its path changes on update.
- **The loose binaries stay unpublished**, as for the other two
(`tools/prune_release_assets.sh`, unchanged: it keys on the seven `.vsix`
names).
- **CI runs the extension's JavaScript tests** with `node --test
editors/vscode/*_test.js`. The runner is this Mac in host mode, node 22
(`--test` needs ≥ 18). The tests stub `vscode` and need no `npm ci`.
## Handshakes
- **`editors/vscode ─▶ lucisv_mcp` (spawn contract).** Binary name
`lucisv-mcp` (`lucisv-mcp.exe` on Windows); arguments `--root DIR` and
optionally `--index-cache DIR`, nothing else; stdio newline-delimited
JSON-RPC; cwd the folder. Pinned by `mcp_test.js` (exact args) and
`mcp_smoke.js` (spawns the real binary with the same shape). A rename of
either flag in `crates/lucisv_mcp/src/main.rs` breaks both.
- **`tools/ ─▶ lucisv_mcp` (packaging).** `release.sh` builds `-p
lucisv_mcp` for the host and every cross triple and expects
`target/[<triple>/]release/lucisv-mcp[.exe]`; `mcp_smoke.js` expects
`serverInfo.name == "lucisv-mcp"`, ≥ 26 tools and a non-error
`project_overview` whose text names the top module. Lowering the tool count
means lowering `MIN_TOOLS` in `mcp_smoke.js`.
- **Promised to users**: the settings `lucisv.mcp.enabled` / `lucisv.mcp.path`,
the command `lucisv.mcp.copyConfig`, the provider id `lucisv.mcp`.
- **Request to the lead (outside this lane's files)**:
`.gitea/workflows/release.yml`'s header comment still says the platform
packages embed "the lucisv + lucisv-server binaries"; it wants "lucisv,
lucisv-server and lucisv-mcp". `docs/mcp/PLAN.md` §2.3/§5.2 show the object
form of the `McpStdioServerDefinition` constructor, which is wrong (see
Assumptions). `docs/topo.md` edges are M6's.
## Status / TODO
- [x] `release.sh`: `-p lucisv_mcp` in the host and cross builds; loose
`dist/lucisv-mcp-<version>-<triple>[.exe]`; staged as `bin/lucisv-mcp`
and `bin/<target>/lucisv-mcp`; `expect_vsix_bins` three per platform,
fifteen for `all`; universal still asserts no `bin/`;
`smoke_embedded_mcp` for the host platform package and (with `--cross`)
the `all` package; host `mcp_smoke.js` run; checksummed
- [x] `audit_artifacts.sh`: every binary must be one of the three names; the
same per-triple audits apply to `lucisv-mcp`
- [x] `prune_release_assets.sh`: read, unchanged
- [x] `mcp.js`, `mcp_test.js`, `mcp_smoke.js`; `extension.js` +2 lines
- [x] `package.json`: provider, two settings, command + palette; engine kept
- [x] `.vscodeignore`: `mcp_test.js`, `mcp_smoke.js` excluded
- [x] CI step `node --test editors/vscode/*_test.js`
- [x] docs: site guide `guides/agents.md` + sidebar, `README.md` paragraph,
`tools/RELEASING.md`, extension README + CHANGELOG (Unreleased)
- [x] local `tools/release.sh` (host) green; darwin-arm64 vsix unzipped
- [ ] QA (TODO-MCP M5 last box)
## Work log
### 2026-09-23 (dev)
- **VS Code API check.** Read the installed VS Code 1.138's `vscode.d.ts` and
minified extension host: the stdio definition's constructor is positional;
the plan's object form would have produced a server with an object label
and no command. The contribution point generates `onMcpCollection:<id>`
activation implicitly.
- **`mcp.js`** (≈ 180 lines with comments): ladder, provider with
`provideMcpServerDefinitions` / `resolveMcpServerDefinition` /
`onDidChangeMcpServerDefinitions`, copy-config command (registered on every
VS Code, including those without the MCP API). `bundledBinary` and the
output channel are passed in from `extension.js`, whose change is two lines
(the `require`, and the call after `restarter.start()`).
- **`mcp_test.js`**: 7 groups — the ladder (explicit / blank / bundled /
PATH), one definition per folder with exact args/cwd/version and both
storage fallbacks, change events (folders, `lucisv.mcp`, not others),
`enabled: false` (no definitions, one log line, re-enabled live), the old
VS Code guard in three forms (no `lm`, `lm` without the function, no
definition class; no throw with no channel), missing-binary refusal, and
the three snippets' exact JSON plus the dismissed pick.
- **`mcp_smoke.js`**: temp project of two files, the extension's spawn shape,
all four messages written then stdin closed; checks serverInfo, tool count,
overview text, stdout purity and exit status 0. Fails cleanly (exit 1) on
a missing binary and on the wrong binary (`lucisv-server` refuses
`--root`). `--tool-table` prints the Markdown table checked into the guide.
- **`release.sh`** host run under `tools/guard.sh -t 1800`: exit 0; both
smokes passed on the loose binaries and on the ones unzipped from
`lucisv-0.56.0-darwin-arm64.vsix`; `shasum -c` OK for all five artifacts.
`unzip -Z1 … 'extension/bin/*'` → `lucisv`, `lucisv-mcp`, `lucisv-server`;
`extension/mcp.js` present; no `mcp_test.js` / `mcp_smoke.js`. The universal
vsix has `extension/mcp.js` and no `bin/`.
- **Size**: `lucisv-0.56.0-darwin-arm64.vsix` = 6 784 784 bytes; the
`lucisv-mcp` entry is 4 532 816 bytes, 1 922 890 deflated, `mcp.js` 2 686
deflated — **+1.93 MB** per platform package (≈ +9.6 MB for `all`, by the
same ratio across five targets; not measured, needs `--cross`).
- **Cross check** (not in the brief, cheap insurance): built `-p lucisv_mcp`
for `x86_64-unknown-linux-gnu`, `x86_64-pc-windows-gnu` and
`x86_64-unknown-linux-musl` with the script's recipes; `audit_artifacts.sh`
passed all three (glibc ceiling `GLIBC_2.28`); a stray name
(`lucisv-lsp-…`) is rejected.
- **vsce**: engine `^1.82.0` accepted (see Assumptions); no bump.
- `node --test editors/vscode/*_test.js`: 6 files, all pass. The docs site
builds (`astro build` to a scratch dir) with the new page.
- No Rust touched.
## QA log
### 2026-09-23 (QA) — verdict: **pass** (headless); live-VS Code steps filed as manual-acceptance rows 18–25
Everything below ran on master 23ec444 + the lane's uncommitted tree; scratch
work under the session scratchpad, nothing committed, no Rust touched.
1. **API claim — confirmed.** VS Code **1.138.0** (`code --version`;
`/Applications/Visual Studio Code.app/Contents/Resources/app/out/vscode-dts/vscode.d.ts`):
`vscode.d.ts:20467` `constructor(label: string, command: string, args?: string[], env?: Record<string, string | number | null>, version?: string);`
and `vscode.d.ts:20434` `cwd?: Uri;` (a plain, non-readonly property;
`label` is the only readonly one). The extension host
(`out/vs/workbench/api/node/extensionHostProcess.js`) implements it as
`constructor(t,e,n,o={},i,s){this.label=t;this.command=e;this.args=n;this.env=o;this.version=i;this.metadata=s}`.
`resolveMcpServerDefinition` may return `undefined` = "do not start"
(`vscode.d.ts:20538`). Contribution point schema in
`workbench.desktop.main.js`: `extensionPoint:"mcpServerDefinitionProviders"`,
items `{id, label, when}` (`additionalProperties:false`), and
`activationEventsGenerator` yields `onMcpCollection:<id>` — the
Assumptions' implicit-activation claim holds. `package.json` uses exactly
`id`/`label`; `PROVIDER_ID` in `mcp.js` equals it.
2. **`mcp.js`** — read line by line; `node --test editors/vscode/*_test.js`:
6 files, 6 pass, 0 fail (node v22.13.1). Ladder order, blank = unset,
one definition per folder with args exactly `--root <fsPath>
--index-cache <storage>`, change events, `enabled:false`, the three
old-VS Code shapes, the snippets — all asserted. **Mutation check** (8
mutants of a scratch `mcp.js`: bundled-before-explicit, untrimmed blank,
`--index-cache` renamed, `cwd` dropped, fire on every config change,
`type:"stdio"` dropped, `enabled` ignored, `lm` guard dropped): all 8
killed by `mcp_test.js` under `node --test`. **Own scratch checks**
(`qa_mcp_test.js`, not checked in), all pass, with
`unhandledRejection`/`uncaughtException` hooks asserting nothing escaped:
zero folders (`workspaceFolders` both `undefined` and `[]`): no
definitions, no log line, each snippet `JSON.parse`s with `args: []`;
folder `/work/my proj` and bundled path `/ext dir/bin/lucisv-mcp`: label
`lucisv (my proj)`, args keep the space inside one element, `cwd.fsPath`
right, all three snippets `JSON.parse` and round-trip the path, only the
VS Code one has `"type":"stdio"`, and a real existing binary under a
directory with a space resolves; `lucisv.mcp.path` →
`/definitely/not/here/lucisv-mcp`: the setting wins over bundled, resolve
returns `undefined` without throwing, one output-channel line (and no
throw with no channel at all); no `vscode.lm`: copy-config still yields
valid VS Code JSON naming bare `lucisv-mcp`.
3. **`extension.js`**: `git diff` is exactly +2 lines (the `require` and
`mcp.activate(context, { bundledBinary, outputChannel: client.outputChannel })`
after `restarter.start()`; no early return in `activate` before it).
`restart_test.js` passes (44 checks); `tools/guard.sh -- cargo build
--release -p lucisv_server -p lucisv_mcp` then `node
editors/vscode/smoke.js target/release/lucisv-server`: OK (55 messages).
4. **Packaging**: `tools/guard.sh -t 1800 -- tools/release.sh` → exit 0
(both smokes on the loose binaries and on the ones unzipped from the
darwin-arm64 vsix; `bin/ contents ok` for both packages; vsce 4.0.0
printed only the pre-existing "bundle your extension" warning — engine
`^1.82.0` accepted). `shasum -a 256 -c SHA256SUMS`: 5 × OK.
`unzip -Z1 dist/lucisv-0.56.0-darwin-arm64.vsix | sort` minus 315
`extension/node_modules/` entries: `[Content_Types].xml`,
`extension.vsixmanifest`, `extension/LICENSE.txt`,
`extension/bin/lucisv`, `extension/bin/lucisv-mcp`,
`extension/bin/lucisv-server`, `extension/changelog.md`,
`extension/extension.js`, `extension/extract.js`,
`extension/hierarchyModel.js`, `extension/hierarchySections.js`,
`extension/hierarchyView.js`, `extension/images/{architecture.png,feature-map.png,hierarchy.svg,icon.png}`,
`extension/mcp.js`, `extension/media/{hierarchy.css,hierarchy.js}`,
`extension/package.json`, `extension/readme.md`, `extension/restart.js`,
`extension/snippets/{systemverilog,verilog}.json`,
`extension/syntaxes/systemverilog.tmLanguage.json` — no `*_test.js`, no
`smoke.js`/`mcp_smoke.js`. Universal `lucisv-0.56.0.vsix`: 0
`extension/bin/` entries, `extension/mcp.js` present. Unzipped by hand
to scratch: `mcp_smoke.js` against the embedded `lucisv-mcp` → OK
(0.56.0, 26 tools); it is byte-identical (`cmp`) to the loose binary.
Negative smokes exit 1: missing path (ENOENT), `lucisv-server` and
`lucisv` (both refuse `--root`). **Clean-profile install**: `code
--user-data-dir <scratch> --extensions-dir <scratch> --install-extension
dist/lucisv-0.56.0-darwin-arm64.vsix` → installed,
`[email protected]`, `bin/` holds the three executables (755).
`tools/prune_release_assets.sh`: not in `git diff`/`git status`; its
seven suffixes (`""`, darwin-arm64, darwin-x64, linux-x64, linux-arm64,
win32-x64, all) match `vsce_target_for` + the universal + `-all` in
`release.sh` (read, cross not run). `--cross` artifact arithmetic in
`RELEASING.md` (6 triples × 3 = eighteen loose binaries, fifteen `bin/`
entries in `all`) matches the script. `audit_artifacts.sh` on a scratch
copy of dist: clean → exit 0 (3 audited, incl. `lucisv-mcp-…`); a stray
`lucisv-foo-0.56.0-aarch64-apple-darwin` → `FAIL: … not lucisv,
lucisv-server or lucisv-mcp`, exit 1; a Mach-O renamed
`lucisv-mcp-0.56.0-x86_64-unknown-linux-musl` → `not an x86-64 ELF`,
exit 1 (the per-triple audit really applies to the third name).
5. **CI**: `yaml.safe_load` parses `ci.yml`; job `checks` steps in order
`cargo fmt`, `cargo clippy`, `cargo test`, `extension tests` (after the
cargo steps). Local node v22.13.1 (≥ 18); the runner's node version is
the dev's statement, not checked from here.
6. **Docs**: `node editors/vscode/mcp_smoke.js --tool-table
target/release/lucisv-mcp` regenerated; `diff` against the guide's table
→ identical (26 rows). Every one of the 14 write tools has `dry_run` in
its input schema (the guide's "on any edit tool" holds); `lucisv-mcp
--bogus` → usage line, exit 2; default root `.` (`canonical_roots`) — the
Standalone paragraph is accurate. Links: the guide has one, absolute; the
extension README's only non-`https://` links are in-page anchors
(`#agents-mcp`, new; `#large-workspaces`, pre-existing), which vsce
accepts (it packaged). Site: `tools/guard.sh -t 600 -- npx astro build
--outDir <scratch>` → 14 pages, `guides/agents/` built, sidebar entry on
every page, the `` `define `` row renders as text, `\a@b@1` intact. (Built
to scratch because `docs/site/dist/` is **tracked** — see lead items.)
`README.md` paragraph and `RELEASING.md` agree with `release.sh`
(three binaries, both smokes, host + `all` re-smoke, the artifact
table, "nine crates" = 9 `version.workspace` crates).
7. **PLAN §2.3/§5.2**: found already corrected in the working tree (not
this lane's edit) to the positional form with `cwd` set afterwards;
`release.yml`'s header now names `lucisv-mcp`.
Extra, headless proxies for the QA checklist's live-VS Code clauses: the
Claude Code snippet built by `configSnippet` with the *installed* extension's
`bin/lucisv-mcp` and a root containing a space, spawned exactly as
`command`/`args` from an unrelated cwd (`os.tmpdir()`): status 0,
`serverInfo.name` `lucisv-mcp`, `project_overview` non-error with the right
root. `lucisv-mcp --index-cache /nonexistent/dir/x` starts and answers
(exit 0) — VS Code creates `storageUri` lazily, so the directory the
extension passes may not exist yet.
**Findings** (none blocking; no fix made):
- F1 (docs, minor) `tools/RELEASING.md:240` — "~13 MB rather than ~3 MB (both
before `lucisv-mcp` joined them; the darwin-arm64 package measured 6.8 MB
with it, +1.9 MB)": 3 + 1.9 ≠ 6.8. The pre-MCP darwin-arm64 package was
already ≈ 4.9 MB (6 785 772 − 1 922 890 deflated), so "~3 MB" was stale
before this lane; the new parenthesis makes the inconsistency visible.
Same stale "about 13 MB against 3 MB" at `editors/vscode/README.md:55`
(pre-existing, untouched by the lane).
- F2 (docs, drift risk) `editors/vscode/README.md:196` hard-codes "its 26
tools"; `MIN_TOOLS` in `mcp_smoke.js` only guards the floor, so a 27th
tool leaves this stale silently. Suggest "its tools" or regenerate with the
guide's table.
- F3 (hardening, optional) `mcp.js:157` — `registerMcpServerDefinitionProvider`
is not wrapped: if it ever throws (e.g. a future VS Code rejecting the
provider), `activate` in `extension.js:293` throws *after* the language
server has started, and VS Code reports the whole extension's activation
as failed. A try/catch logging one line would keep the MCP part
strictly additive. Not reproducible today (the id is declared).
- F4 (for M6) the `--index-cache` directory may not exist when VS Code spawns
the server (see above); the M6 reader must treat a missing directory as
"cold start", not an error.
**Lead items (outside this lane's files):** `docs/site/dist/` is tracked
and was not rebuilt, so the committed site build lacks `guides/agents/` until
someone regenerates it; `.gitea/workflows/release.yml:6` still says "every
pair at once" one line below the corrected binary list; PLAN §5.2 now shows
`undefined` for `env` where `mcp.js` passes `{}` (equivalent — the host
defaults `env` to `{}` — noted only so the two read alike).
**Not done here (owner, live VS Code):** MCP: List Servers, trust, an agent-mode
`project_overview`, `enabled:false` live, multi-root, universal-without-PATH
degradation as VS Code shows it, the copied snippet in a real Claude Code
session — `docs/manual-acceptance.md` rows 18–25. The stubbed unit tests and
the headless proxies above cover the logic behind each; only VS Code's own UI
reaction (e.g. whether it adds a toast when `resolve` returns `undefined`) is
unverified.
## Review
**Lead, 2026-09-23 (M5).** The lane is scripts, JavaScript and docs, and it
did the one thing the plan got wrong right: VS Code's
`McpStdioServerDefinition` is a positional constructor (confirmed by the dev
and by QA against 1.138's `vscode.d.ts`), so the plan's object form is
corrected in `docs/mcp/PLAN.md` §2.3/§5.2. Rulings kept from the dev's
deviations: `lucisv.mcp.enabled: false` leaves the provider registered and
returning no servers (no reload to turn it back on); a missing binary is
refused at `resolveMcpServerDefinition` with one output-channel line, which
is what the universal package needs. Engine stays `^1.82.0` — vsce 4 accepts
the contribution point and the registration is guarded at runtime. QA's F1/F2
(stale size and tool-count prose) fixed by the lead; F3 (a try/catch around
the registration) and F4 (`--index-cache` may not exist yet — M6's reader
must tolerate it) noted for M6. The tracked docs site rebuilt so the Agents
page ships. Rows 18–25 of `docs/manual-acceptance.md` are the owner's in a
live VS Code. Committed as M5.
+7 -1
View File
@@ -78,11 +78,15 @@ rendering; no language knowledge lives in the MCP crate.
| paths root-relative | `Project::relative`: relative to the first root holding the file, `/`-separated; absolute only for a file outside every root (a filelist entry) |
| a file named once per group | `render::grouped` — the file on its own line, its entries indented two spaces under it (`list_units`, `search_symbols`); single-file answers name the file once at the top (`outline`, `read_item`, `unit_interface`'s head line) |
| 1-based positions | lines always; `line:col` (byte column) where a column is given — today only `outline`'s parse errors; ranges `first-last`, a one-line range one number |
| capped lists | `limit` (default 200) and `offset` on every list tool; a cut list ends `… and N more`; `structuredContent` carries `total` so the agent can page |
| capped lists | `limit` (default 500) and `offset` on every list tool; the answer opens with its total — `N units`, or `N units (showing a–b)` when cut — and a cut list also ends `… and N more`; `structuredContent` carries `total` and `shown` so the agent can page |
| no prose, no headings | labels are a bare word and a colon (`parameters:`, `ports:`, `modports:`, `template:`, `members:`); `none`/`no units match` for empty answers |
| tables only for fixed columns | `render::table` — ports (direction, type-with-range, name), parameters (name, default), members, largest files; a column empty in every row takes no space |
| a declaration as its own line | modports are shown as their declaration collapsed to one line; parameter defaults likewise |
Amended 2026-09-23 (lane feedback-2, `docs/features/mcp-feedback-2`): the
count line first, the default page 500, `shown` in the JSON; `list_units`
and `search_symbols` take the `in` path glob.
## Handshakes
Consumed: see `docs/features/mcp-transport/README.md` (one table for the
@@ -186,6 +190,8 @@ findings, as applied to the read tools (the transport half is in
is what makes both it and the lead's `\a@b@1` work.
- **6 — no action** (a library limit; QA's note stands).
**2026-09-23 (dev, feedback-3).** `unit_interface`'s instantiation template is opt-in (`template: true`); without it the text ends after ports/modports/warnings and the JSON has no `template` key; the headers read `parameters (N):` / `ports (N):` (handshake change: answer shape and a new argument) — `docs/features/mcp-feedback-3`.
## QA log
**2026-09-23 (QA, M1 — the six read tools).** Verdict: **rework needed**
@@ -0,0 +1,809 @@
# mcp-structural-edits
Lane **M4** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §4.3).
## Goal
The general token saver: an agent that wants to change one `always` block,
one function or one declaration sends **only that item's new text**, never
the file — `replace_item`, `insert_item`, `delete_item`. Each finds its
place with `read_item`'s own slicer, so the bytes it edits are exactly the
bytes `read_item` showed; each verifies the result before anything is
written (CLAUDE.md invariant 1: verified output or nothing); each writes
through M3's one write path (`apply::run`: `dry_run` diff, write-freshness,
atomic write). The verifier is the one new piece of logic in the MCP block,
so it ships with its attack suite (`tests/attacks.rs`) — invariant 4.
## Assumptions
### The contract
| tool | arguments | does | refused when |
|---|---|---|---|
| `replace_item` | `file`, `item` (`read_item`'s selector), `text`, `rename?` (false), `dry_run?` | the bytes of exactly the span `read_item::select` returns become `text` (normalised, below) — widened over the item's own comments when the text brings comments of its own (below); nothing outside that span changes | `text` empty; the item is part of a larger item (an ANSI port, an argument); the span is fenced; any verifier rule (below) with `Expect::One(old class)`; the text declares other names than the item did and `rename` is false |
| `insert_item` | `file`, `anchor` (a selector, `end`, or `end@UNIT`), `position?` (`before`/`after`, default `after`, ignored for `end`), `text`, `dry_run?` | `text` becomes new items before the anchor (above its own leading comments) or after it (below its trailing comment), or the last items of a unit (`end`: the file's last module/interface/program/package/class; `end@UNIT`: that one) | `text` empty; the anchor (or the unit's end keyword) shares a line with other code; the insertion point is fenced; any verifier rule with `Expect::Some` |
| `delete_item` | `file`, `item`, `force?` (false), `dry_run?` | removes the item's lines, its own leading comments (`Meta::leading` back to the first blank line, below), its trailing comment, and the blank line the removal would leave doubled | the item shares a line; the removed bytes are fenced or its leading comments hold a fence line; a name it owns is still referenced — or possibly referenced, through a macro or a `.*` (below) — and `force` is false; any verifier rule with `Expect::Nothing` |
Annotations: `replace_item` and `delete_item` are `idempotentHint: true`
(the same `replace_item` twice answers `unchanged`; a second `delete_item`
is refused "no declaration matches" — it writes nothing); `insert_item` is
`false` (the same insertion twice is refused only when it would declare a
name twice; otherwise it inserts again). `delete_item` walks the roots
first (`rewalk: true`, whole-set rule); the other two touch one file.
The answer is `apply.rs`'s summary — `files: 1 changed, 0 created`, the
`path +a -b` line — then the note: `replaced always (lines 12-14)` /
`inserted declaration `s` (lines 24)` / `deleted function `spare` (old
lines 9-12)`, and for replace and insert one hint line: ``hint: run `format`
with `lines: "12-14"` to reflow; `diagnostics` to check``.
`structuredContent.item.lines` carries the new item's line range. Nothing
is formatted implicitly (PLAN open question 3: the agent's choice).
### The verifier (`src/tools/item/verify.rs`)
Every edit is a `Splice` (`start..old_end` becomes `text`), so no byte
outside the region can change — the wire tests compare the prefix and
suffix bytes anyway. What is checked is what the new bytes do to the parse:
1. **Lex and parse.** The new file lexes. When the old file parses
strictly (`vlog_parser::parse_source`), the new one must; when it did
not, the tolerant diagnostic count must not grow. A file that does not
lex at all is refused up front (no span in it can be trusted).
- **1a.** The spliced `text` lexes **on its own**
(`vlog_parser::tokenize(text)`): a text ending in an open `/*`, string
or macro call lexes inside the file only by running into the code
after it — a later `*/` closes it and swallows what lies between (QA
finding 1: a fence comment).
- **1b.** The token stream **outside the region** is the old one: every
token and every comment (the `Token.leading`/`trailing` trivia,
flattened in source order) before the region, and every one after it
shifted by the length change, has the same kind, text and span as in
the old file; nothing starts inside the region and ends past it; and
no comment inside the new bytes is attached to a token outside them (a
comment the text leaves on a line of its own at its end would lead the
next item). Rules 1a/1b live in `src/tools/item/lexical.rs`; the
refusal names the rule (`rule 1a`, `rule 1b`). Order: whole-file lex,
1a, strict parse, 1b, then rules 2–7.
2. **Surroundings.** Every item of the tree (depth first, all levels) is
classified against the region: before it, after it (shifted by the
length change), enclosing it (end shifted), or inside it. The before,
after and enclosing lists — depth, kind class, start, end — must be
identical in the old and new trees. An item that begins on one side of
a region boundary and ends on the other is refused by name ("the text
must open and close everything it starts"). This is what catches a text
that closes the enclosing module (still a valid file, `sneaky` module
and all), a stray attribute that glues onto the next item, and a block
left open that error recovery would otherwise absorb.
3. **Content.** The items inside the region at the enclosing level:
exactly one of the old kind class (replace), at least one (insert),
none (delete). Each must be a kind its container may hold (below).
4. **Duplicates.** No name is declared twice in one scope more times than
before (`Semantics::duplicates`, counted per name). This catches a port
re-declared in the body — even with `rename: true` — and a repeated
insert.
5. **Conditionals.** The `` `ifdef``/`` `ifndef``/`` `elsif``/`` `else``/
`` `endif`` directive tokens starting inside the region balance, in the
old bytes and in the new (the parser keeps directives as raw items, so
half a guard parses).
6. **Macro definitions** (QA finding 6). The file's define table entries
(`Analysis.defines`) whose directive starts inside the region — kind,
name, parameters, body — are the same before and after, except those
inside a **directive or macro item at the region's own level** (kind
class `directive`/`macro`): replacing, inserting or deleting such an
item is editing the definition, which is the point. So a
`` `define``/`` `undef`` nested in an `always`, a function, or a module
the text replaces whole cannot be added, changed or removed by these tools ("the text
changes a macro definition (`W`) nested in an item (rule 6); edit the
`define item itself"), and a top-level `` `define`` item can be inserted.
Applied to all three tools (the ruling names replace and insert; a
delete removing a nested `` `define`` changes the code after it the
same way).
7. **Fence markers** (QA finding 7). The `lucisv: off`/`on` marker
comments (`fence::fence_of`, trailing ones included) starting inside the
region are the same before and after: a text neither opens nor closes a
fence ("the edit would add the fence marker `// lucisv: off` (rule 7)").
### Kind classes
| class | `ItemKind` |
|---|---|
| module / interface / program | `Module` by keyword (`macromodule` is module) |
| package, class | `Package`, `Class` |
| declaration | `DataDecl`, `ParamDecl`, `Typedef`, `Let` |
| port declaration | `PortDecl` (non-ANSI body) |
| genvar | `Genvar` |
| assign, alias | `ContAssign`, `Alias` |
| always | `Always` (every `always*` keyword — one class) |
| initial, final | `Initial`, `Final` |
| instance | `Instantiation`, `GateInstantiation` |
| function, task | `Function`, `Task` |
| generate | `GenerateRegion`, `GenIf`, `GenFor`, `GenCase`, `GenBlock` |
| import, export, modport, clocking, bind, defparam, timeunit | one each |
| constraint, covergroup, property | `Constraint`, `Covergroup`, `PropSeqDecl` |
| assertion | `Assertion`, `DefaultDisable` |
| (verbatim) | a `Verbatim` item is classed by its first words: assert/assume/cover/restrict/expect → assertion; covergroup; constraint; property/sequence → property; else `verbatim` |
| elaboration task, macro, directive, empty item, unparsed text | `ElabTask`, `MacroItem`, `Directive`, `Empty`, `Error` |
**Container rule** (IEEE 1800 A.1): in a file or a package, none of
always/initial/final/assign/alias/instance/generate/port declaration/
modport/clocking/assertion/defparam/genvar/elaboration task; in a package
or a class, no module/interface/program/package either; in a class, no
bind; a package only in a file. The parser accepts `always_comb` after
`endmodule`, so this rule — not the parse — is what refuses it.
### Normalisation and blank lines
- **`text`**: trailing spaces, tabs and line endings are dropped, because
the line ending after the old item is outside the span and stays: the
new item ends at a line end exactly when the old one did — one newline,
never two. For `replace_item` leading blank space is dropped too (the
indentation before the span stays); for `insert_item` leading blank lines
are dropped and the first line's indentation is kept as written (no
re-indentation — `format` does that). Line endings become the file's
(judged by its first line): an LF text in a CRLF file is written CRLF.
An empty text is refused, never taken as a deletion.
- **Comments the text brings** (QA finding 2, lead ruling). When `text`
begins with a comment (its first token, lexed alone, has leading
trivia), the replaced span is widened back over the old item's **own**
leading comments (the own-comments rule below); when `text` ends with a
trailing comment on its last line (its last token has a trailing comment
and nothing follows), the span is widened forward over the old item's
trailing comment. The text's comments then *replace* the item's, and the
same call again finds its own text: `unchanged`. A text without comments
leaves the item's comments where they are. `read_item` is not changed
(it still shows the code span). A comment the text leaves on a line of
its own after its last token is refused by rule 1b. Implemented in
`span::replace_region`.
- A `text` equal to the replaced span's bytes after normalisation is
`unchanged` (also for a fenced item: nothing is written either way).
- **Blank lines (insert)**: a blank line separates the new items from a
neighbouring item on each side, unless that side's line is already blank.
No blank line is added between them and the enclosing unit's header (no
item above) or end keyword (`end`, or `after` the last item). A file
whose last line has no line ending gets one first.
- **Blank lines (delete)**: the removal takes whole lines; when the line
above and the line below the removed lines are both blank, the one below
goes too.
### Own comments and own lines (`src/tools/item/span.rs`)
- **Own comments** (QA finding 4). An item's leading comments
(`Meta::leading`) are its own walking back from the item up to the first
gap that holds a blank line: a section banner, or the file banner above a
module, separated by a blank line, belongs to what follows it and stays
when the item is deleted (it then leads the next item).
- **Own lines** (QA finding 5). 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 and can be
an anchor or deleted; `logic x; /* c */ logic a;` still shares). The
first line is judged from the first own comment; the last line runs to
the end of the trailing comment (which may continue onto later lines).
### Names and references
- **Owned names** (`verify::owned`): the symbols whose name — or, for a
non-ANSI body port declaration, whose detail — lies in the item, bound in
a scope a construct inside the item opens (the unnamed header scope a
generate loop opens around itself, spanning exactly the item, is
see-through). A module owns its name, not its signals; a declaration
`logic q, r;` owns `q` and `r`; an always block owns nothing (a
`begin : blk` label is owned; an unnamed `begin`'s locals are not); a
generate loop owns its label and its genvar.
- `replace_item` compares the sorted owned names before and after; a
difference is refused unless `rename: true`, and then the answer warns
that references were **not** updated and points at `rename`.
- `delete_item` (`src/tools/item/refs.rs`): for each owned name, if any
text of the whole set (the removed bytes aside) spells it as a whole word,
`vlog_refactor::find_references` over the whole set finds the uses; a use
outside the removed bytes, an engine refusal, a skipped file spelling the
name, or a name also declared outside the item (a non-ANSI header port)
refuses the delete — listing the first five as `file:line:col `name``
and "and N more" — unless `force: true`, which deletes and lists them
under `warnings:`. The whole-word prefilter is sound for everything but a
`.*`, which binds without spelling the name — so the `.*` rule below
runs for every name. In the item's own file the file's semantic tables are
consulted too: a use of the name outside the removed bytes that resolves
to the declaration **or to nothing** counts — that is what catches
`gen_l[0].z`, a hierarchical path into a generate loop the engine does
not follow (MCP-12). It can refuse a safe deletion (an unresolved
same-named use elsewhere in the file); `force` is the way past.
- **Macros** (QA finding 3, `src/tools/item/macros.rs`). A whole-word
spelling of the name inside a macro call's arguments (the lexer keeps
`` `ID(x) `` as one token; nested calls are searched too) or inside a
`` `define`` body (not one of its formal arguments), in any file of the
whole set, that neither the engine nor the file's own reference table
accounted for, is a **possible use**: "possible use (macro) at
file:line `name`" — refused unless `force`, the skipped-file rule's
posture. Comments and strings are not searched (arguments and bodies are
lexed; a body that does not lex — token pasting — is searched as bytes).
A file of the set that spells the name and does not lex is a possible
use too.
- **`.*`** (QA finding 8, `src/tools/item/star.rs`). For each deleted
name, every `.*` instantiation in the item's own scope — its sibling
items and the generate constructs among them, the removed bytes aside —
whose module resolves through the project index to **one** module or
interface declaration with a port of that name is a use ("bound by `.*`
at file:line:col `name` (module `core`)"); a `.*` whose module does not
resolve to exactly one declaration is a possible use. Refused unless
`force`. A `.*` in another module, or in an enclosing scope of a
generate block the item sits in, cannot bind the name and is not
consulted.
- **Selection is `read_item`'s**, quirks included: the label of a generate
`else` branch (`gen_b` in `if (P) begin : gen_a … end else begin : gen_b
… end`) selects the whole `if` — deleting it deletes both branches, and
the note names both labels; the `then` branch's label selects that
branch's block, which is not an item, so it is refused as "part of a
larger item".
### Deliberately not checked
- Whether the new text makes sense: types, widths, the names it reads, a
port list that still matches its instantiations, whether an `always_ff`
still has a clock. `diagnostics` answers those; the tools say so.
- References to a name `replace_item` renamed or dropped (with `rename`).
- The effect of directives the agent writes **as items of their own**
(`` `define`` items at the region's level, `` `default_nettype``,
`` `timescale``) on the code after them — the agent's text means what it
says. A `` `define``/`` `undef`` nested inside another item is refused
(rule 6).
- A hierarchical use in **another file** that `find_references` does not
follow (`u_h.gen_l[0].z` into a generate loop; MCP-12).
- A name reached only through a macro that pastes it together
(`` `a``_b ``): no byte spells it, and no lucisv engine follows it.
### The attack list (`tests/attacks.rs`)
Every case asserts **refused, with every file of the tree hashed and
unchanged**, under `dry_run` and for real; a control beside most cases
asserts the nearest legal edit passes.
| attack | rule that refuses it |
|---|---|
| a `text` opening a block it does not close (replace an `always`; insert a `function` without `endfunction`) | 1 (strict parse) |
| a `text` closing the enclosing module (`logic r;\nendmodule\nmodule sneaky;`; insert `endmodule\nmodule sneaky;` at `end`) | 2 (surroundings) |
| a `text` re-declaring a port (`logic d;`, with and without `rename`; insert `logic [3:0] clk;`) | 4 (duplicates) |
| two items where one was; `logic p;;` (an empty item rides along) | 3 |
| an empty or all-blank `text` (replace and insert) | normalisation |
| a UTF-8 edge: a non-ASCII identifier in the text; control: the multibyte comments hugging the item stay byte-identical, a multibyte comment in the text is accepted | 1 (lex) |
| an item inside a `// lucisv: off` fence: replace, delete, insert before/after; deleting the fence's owner module; deleting the item whose leading comment is the `on` fence | fence |
| a file with an unterminated string (replace, insert); a text with one | lex |
| `insert_item` after `endmodule`: `always_comb`, `assign`, an instance at file scope; `initial` in a package; control: a module after a module | 3 (container) |
| a valid item of another kind (a `function` or `initial` where an `always` was; an `assign` where a declaration was); control: `always_ff` → `always @*` | 3 (class) |
| an escaped name (`\a+b `): renaming without `rename`, deleting while referenced; control: widening it | names, references |
| half an `` `ifdef``: inserted `` `endif``, `` `else``; a module carrying an unclosed `` `ifdef``; replacing with `` `ifdef``+item (two items); controls: a balanced guard, an item inside a guard | 5, 3 |
| insert/delete on a line shared with other code; control: replace on a shared line | line ownership |
| a header port and a non-ANSI body port whose header still names it | not an item; references |
| a generate loop relabelled without `rename`; deleted while `gen_l[0].z` names it; control: a wider body under the same label | names, references (local uses) |
| a 40 000-line file: a refused replace, then replace, insert and delete (timed below) | 1 |
| *(rework)* an open `/*` a later comment closes (replace, insert); a comment left on its own line after the text's item; control: a same-line comment | 1a, 1b |
| *(rework)* a text with leading and trailing comments twice (`unchanged`, the old comments replaced, the banner kept); control: a text without comments keeps the item's | normalisation (comments) |
| *(rework)* a name used only in a macro argument, a nested call, another file's `` `define`` body; forced; control: a name only in a comment and a string | references (macros) |
| *(rework)* a section banner and a file banner a blank line separates from the deleted item | own comments |
| *(rework)* `/* lead */ logic a;` deleted; control: `logic x; /* c */ logic y;` shares | own lines |
| *(rework)* `` `undef``/`` `define`` nested in a replaced, inserted or deleted item; control: a `` `define`` item inserted | 6 |
| *(rework)* a `// lucisv: off` in an inserted text, a `// lucisv: on` inside a replaced `always`; control: an ordinary comment | 7 |
| *(rework)* a signal bound by a `.*` inside a generate block; a `.*` to an unindexed module; forced; controls: a signal no port names, another module's `.*` | references (`.*`) |
## Handshakes
Consumed (public APIs; no library crate changed):
| crate / module | items |
|---|---|
| `vlog_parser` | `parse_source` (strict rule), `tokenize` (rule 1a, the text's comments, macro arguments), `ast::{Item, ItemKind, Meta, Instantiation, Connections}`, `token::{Token, TokenKind, Comment}`, `defines::{collect_defines, DefineKind}`, `span::TextRange`, `LineIndex` |
| `vlog_semantic` | `Semantics::{symbols, scope, file_scope, duplicates, references}`, `Symbol`, `WorkspaceIndex::{units, member}`, `SymbolKind` |
| `vlog_refactor` | `find_references` |
| `vlog_formatter` | `fence::{protected_regions, is_protected, fence_of}` |
| `lucisv_mcp` (M1–M3) | `read_item::{select, child_items}`, `apply::{run, Plan, Change}`, `source::{WholeSet, word_in}`, `edit::DRY_RUN`, `Analysis::of` |
Promised: three tools with the contract above; `verify::check` is private
to `tools::item` (no second user yet).
Edits outside the brief's file list, each forced by the lane:
- `crates/lucisv_mcp/tests/qa_m1.rs`: the tool count in
`qa_everything_but_initialize_and_ping_waits_for_the_handshake` goes from
23 to 26 (M2 and M3 made the same one-line edit).
- `crates/lucisv_mcp/src/tools/item/refs.rs`: a third file under `item/`
(the delete reference rule), split off so `item.rs` stays one sentence;
within the lane's `item` module.
- Rework (2026-09-23): four more files under `item/`, each one sentence —
`span.rs` (own comments, own lines, the replaced span; moved out of
`item.rs`), `lexical.rs` (rules 1a, 1b, 7), `macros.rs` (macro
spellings), `star.rs` (`.*` bindings). All within the lane's `item`
module; no library crate changed.
Requests:
- **MCP-11 → `vlog_refactor` (performance, non-blocking):** a
`find_references_many(files, file, offsets)` that builds the `Scope` once
for several declarations. `delete_item` on `logic a, b, c;` or an enum
typedef runs the whole-set engine once per owned name some other text
spells; one build would serve them all.
- **MCP-12 → `vlog_refactor` / `vlog_semantic` (a missed use, not a
corruption here):** `find_references` on a generate-loop label
(`for (…) begin : gen_l … end`) does not return `gen_l[0].z`. The
same-file case is covered by `refs.rs::local_uses`; a hierarchical use
from another file is not. Repro: `tests/attacks.rs`
`a_generate_loop_owns_its_label` passes only through `local_uses`.
- **MCP-13 → `vlog_linter` (a lint gap, out of lane):** a forced
`delete_item` of a non-ANSI body port declaration leaves
`module k (a, b); output b;` — a header port with no direction — and
`diagnostics` answers "no findings". A rule "a non-ANSI header port has
no direction declaration in the body" would report it. The forced
answer's warning names it today (`qa_a_forced_non_ansi_port_delete…`).
Accepted, not a request: `.en(x)` in a named connection is counted as a
use of the instantiating module's own `en` by the whole-word prefilter +
engine (QA observation) — a false refusal, in the safe direction; `force`
is the way past.
## Status / TODO
- [x] `replace_item`, `insert_item`, `delete_item` registered (`tools/mod.rs`,
Effect rows), sharing `read_item::select`
- [x] the verifier: lex/parse rule, surroundings, content and kind class,
container rule, duplicates, conditionals
- [x] normalisation (trim, line endings), blank-line policy, own lines,
doubled blank line, fences
- [x] `delete_item` reference rule over the whole set, `force`
- [x] wire tests: dry run / real / repeat per tool; prefix and suffix bytes
compared; `read_item` after `replace_item`; insert at `end`, before,
after, `end@UNIT`, byte for byte; delete refused over references,
forced, leading comment gone and neighbour's trailing kept; doubled
blank; CRLF
- [x] `tests/attacks.rs` (15 tests)
- [x] gates; sizes; timings
- [x] rework (QA findings 1–8, lead rulings): rules 1a/1b, the comments a
text brings, own comments up to a blank line, own lines ignore
comments, rule 6 (macro definitions), rule 7 (fence markers), macro
and `.*` uses in `delete_item`; 8 QA tests un-ignored; 8 attacks
- [ ] lead ruling needed: `qa_every_accepted_call_changes_only_its_own_region`
(first replace) contradicts the finding-2 ruling — see the work log
## Work log
**2026-09-23 (dev, M4).**
Built `src/tools/item.rs` (the three tools, selection, lines, blank
lines, normalisation, notes), `src/tools/item/verify.rs` (the verifier and
kind classes, 5 unit tests), `src/tools/item/refs.rs` (the delete
reference rule); three rows in `tools/mod.rs`; fixture tree
`tests/fixtures/item` (a package with a used and an unused function, a
module with a fenced region, a `.*` wrapper, a module instantiated by
name); six wire tests; `tests/attacks.rs`.
Decisions:
1. **One verifier rule instead of the brief's "the item at that position
is one item"**: the whole-outline comparison (rule 2) subsumes it and
also proves nothing *else* re-parsed — the attack that closes the
module parses cleanly and is caught only by it.
2. **A container rule** the brief did not list: the parser accepts module
items at file scope, so "insert after `endmodule`" needed it.
3. **A conditional-balance rule**: directives are raw items, so half an
`` `ifdef`` parses; replace refuses it by item count, insert only by
this rule.
4. **Duplicates are checked always**, not only under `rename`: a port
re-declared by an insert is the same attack.
5. **Insert and delete need items on lines of their own**; replace does
not (its span is the span). A one-line module is refused with "run
`format` first".
6. **An item that is only part of a larger one** (ANSI port, argument —
`read_item` slices those) is refused by these tools.
7. **Equality before the fence check**: an unchanged text is `unchanged`
even for a fenced item (nothing is written either way).
8. **Owned names see through a generate loop's header scope**, and
`delete_item` also counts the file's own unresolved same-named uses —
both found by probing a generate target before QA (the loop's label sits
in an unnamed scope spanning the loop, and the engine does not follow
`gen_l[0].z`).
9. **A non-ANSI body port declaration** whose header still names it is
refused by `delete_item` unless forced (deleting it would leave the
header naming an undeclared port).
Timings (the 40 000-line module of `a_forty_thousand_line_file_is_verified_in_bounded_time`,
wall time per call over stdio, macOS arm64):
| call | debug (ms) | release (ms) |
|---|---|---|
| refused replace (block left open; the first call, analysis included) | 1 446 | 282 |
| replace of one `always_ff` | 781 | 150 |
| insert at `end` | 1 358 | 276 |
| delete of an unused declaration | 1 338 | 258 |
Each call parses the file four to five times (the cached analysis, the
strict parse of old and new, the new analysis, the fence scan).
Tests: `lucisv_mcp` +6 unit (verify), +7 wire (6 M4 + CRLF), +15 attacks.
Gates (each through `tools/guard.sh`, one cargo invocation at a time):
`cargo fmt -p lucisv_mcp -- --check` rc 0; `cargo clippy -p lucisv_mcp
--all-targets` clean; `cargo test -p lucisv_mcp` 50 unit + 15 attacks + 0
(1 ignored, opentitan) + 51 qa_m1 + 43 qa_m2 + 37 qa_m3 (1 ignored) + 37
wire, all passed; `cargo test --workspace` **4 789 passed, 0 failed, 49
ignored** (4 762 before the lane).
Sizes (production lines: non-blank, non-comment, before `mod tests`):
`tools/item.rs` 410, `tools/item/verify.rs` 321, `tools/item/refs.rs` 143,
`tools/mod.rs` 180. `verify::class_of` (a dispatch table over `ItemKind`)
is the longest function, ~50 lines; everything else is under 45.
**2026-09-23 (dev, M4 rework — QA findings 1–8 under the lead's rulings).**
Per finding (all eight `#[ignore = "QA finding N"]` removed from
`tests/qa_m4.rs`, their assertions untouched; one attack per fix added to
`tests/attacks.rs`):
1. *Open comment swallowing a fence* — `item/lexical.rs` (new): rule 1a
(`lexes_alone`: `tokenize(text)` must succeed) and rule 1b
(`same_outside`: the flattened token + comment stream before and after
the region identical, shifted; nothing straddling the new region's end;
no comment of the new bytes attached to a token outside them). Wired in
`verify::check` / `parses_as_well`. `insert_item` now runs the verifier
before its fence check, so a text that cannot stand anywhere is refused
as such (the QA test's insert before the `// lucisv: on` line gets
"would no longer lex … comment", not "fenced"). Attack
`a_text_reaching_past_its_end_is_refused_by_the_lexical_rules`.
2. *Not idempotent with comments in the text* — `item/span.rs::replace_region`:
a text beginning with a comment widens the span back over the item's
own leading comments; one ending in a same-line trailing comment widens
it over the item's trailing comment; `unchanged` compares against the
widened span (`item.rs::replace_item`). `read_item` unchanged. Attack
`a_text_with_comments_replaces_the_items_own_and_repeats_unchanged`.
3. *Macro-argument / `` `define``-body uses* — `item/macros.rs` (new,
`macro_spellings`) + `refs.rs::Scan::macros`: spellings in macro call
arguments (nested calls too) and `` `define`` bodies (formals excluded),
in every file of the set, not accounted for by the engine's hits or the
own file's reference table → "possible use (macro) at file:line
`name`". A set file that spells the name and does not lex is a possible
use too. Attack `a_name_spelled_inside_a_macro_is_a_possible_use`.
4. *Deleting a banner* — `span.rs::own_comments_start`: the walk over
`Meta::leading` stops at the first gap holding a blank line. Attack
`a_delete_leaves_the_comments_a_blank_line_separates_from_the_item`.
5. *`/* lead */ logic a;`* — `span.rs::own_lines`: the first line is judged
from the first own comment, so a same-line leading comment goes with the
item; code of another item on the line still shares it. Attack
`a_same_line_comment_goes_with_its_item_and_code_still_shares_the_line`.
6. *Nested `` `define``/`` `undef``* — `verify.rs::same_macros` (rule 6):
define-table entries in the region equal before/after, those inside a
directive/macro item at the region's level exempt. **Interpretation to
confirm:** the ruling's exception is keyed to "the old item"; an insert
has none, so the literal reading would refuse inserting a `` `define``
item at all — and would turn the passing QA test
`qa_a_line_continued_directive_cannot_swallow_the_code_below_it` (a
`` `define`` item inserted between items) red. I keyed the exemption to
the directive/macro items at the region's level on either side, which
is the ruling for replace and delete and lets an insert add a directive
item but not a define nested in anything. Applied to delete as well (a
nested `` `define`` removed changes the code after it the same way).
Attack `a_macro_definition_nested_in_an_item_is_refused`.
7. *Fence marker in a text* — `lexical.rs::same_fences` (rule 7): the
fence-marker comments starting in the region equal before/after (a
trailing one counts). Attack `a_text_may_not_carry_a_fence_marker`.
8. *`.*` binding* — `item/star.rs` (new, `star_uses`) +
`refs.rs::Scan::stars`, run for every owned name before the whole-word
prefilter: a `.*` in the item's sibling list or a generate construct
among it, outside the removed bytes, whose module resolves to one
indexed module/interface with a port of the name → "bound by `.*` at
file:line:col `name` (module `m`)"; unresolved → "possible use (`.*`)".
`refs::check` now takes a `Place` (item span, removed bytes, scope).
Attack `a_signal_bound_by_a_dot_star_is_still_referenced`.
Also: `item.rs` split — the span and line helpers moved to `item/span.rs`
(a pure move plus the finding 4/5/2 changes); `insert_item` no longer
indexes `outcome.items[0]`; the replace/delete tool descriptions mention
the comment and `.*`/macro behaviour (the replace description is 520
characters, under the 600 cap of `every_schema_is_closed…`). Out-of-lane
notes (the MCP-13 lint gap, the accepted `.en(x)` false refusal) are in
Handshakes.
**For the lead — one QA assertion contradicts ruling 2.**
`qa_every_accepted_call_changes_only_its_own_region` (`tests/qa_m4.rs`,
its first replace: `r` in `rtl/core.sv` with `logic [15:0] r; /* wider */`)
asserts the changed bytes lie inside `read_item`'s span of `r`
(`logic [7:0] r;`, bytes 121–135). The text ends in a trailing comment on
its last line, so under ruling 2 the replaced span widens over `r`'s own
trailing `// the register` (bytes 128–151 change). Before the rework the
call produced `logic [15:0] r; /* wider */ // the register` — which is the
non-idempotent shape finding 2 is about (and which rule 1b now refuses as a
merged comment straddling the region). Left untouched, as instructed; it
is the only failing test. Either the test's text drops its comment, or its
bound for this case becomes the widened span.
Tests: `lucisv_mcp` 54 unit (+4: 3 `span`, 1 `macros`), 23 attacks (+8),
35 qa_m4 (8 un-ignored; 34 pass, 1 fails as above), 37 wire, 51 qa_m1,
43 qa_m2, 37 qa_m3 (1 ignored).
Gates (each through `tools/guard.sh`, one cargo invocation at a time):
`cargo fmt -p lucisv_mcp -- --check` rc 0; `cargo clippy -p lucisv_mcp
--all-targets` clean (rc 0); `cargo test -p lucisv_mcp` all green except
`qa_every_accepted_call_changes_only_its_own_region` (above);
`cargo test --workspace --no-fail-fast` **4 835 passed, 1 failed (that
test), 49 ignored** (4 816 + 8 un-ignored + 8 attacks + 4 unit − 1; 57 − 8
ignored). No guard kill.
Sizes (production lines: non-blank, non-`//`, before `#[cfg(test)]`):
`item.rs` 379, `item/verify.rs` 363, `item/refs.rs` 211, `item/lexical.rs`
132, `item/star.rs` 73, `item/span.rs` 69, `item/macros.rs` 67. Longest
function still `verify::class_of` (the dispatch table, 46); every new one is
under 40.
## QA log
**2026-09-23 (QA, M4) — verdict: REWORK (four blocking findings, 1, 3, 4 and 8).**
This run resumes one an app restart cut off: the earlier QA agent's
`tests/qa_m4.rs` (27 tests, no log) was taken over, compiled and run as
found (21 passing, 6 finding tests failing as they should), kept, extended
by 8 tests and two cases, and every finding re-reproduced by hand over
stdio (`lucisv-mcp` driven by a scratch script). `tests/qa_m4.rs` now holds
35 tests: 27 pass, 8 are `#[ignore = "QA finding N"]` and assert the right
behaviour (each fails today, run with `--include-ignored`).
What holds (each a passing `qa_*` test, refusals asserted with the tree
byte-identical under `dry_run` and for real): directives, `;;` and a second
unit riding along with an item (two items); `endmodule`/a module header/a
dangling attribute in a `text` (surroundings); another kind under the old
name with and without `rename`; `unchanged` for the old bytes plus blank
space and for a fenced item handed back; a BOM (lex); an `always` inside a
generate branch and inside a loop replaced in place, byte for byte, and a
text that closes the branch refused; directive words in comments and
strings do not trip the balance rule, a directive nested in an `always`
must balance inside the text (`` `ifdef``, `` `endif``…`` `ifdef``,
`` `else``; control: a balanced guard); CRLF through all three tools;
`end` with two units, `end@a`, `end@pk`, a package refusing an
`always_comb`, `end@W` refused; a class body (method yes; `always`,
`assign`, a module, a duplicate no); half an item; a file with a parse
error elsewhere (count may not grow; a clean item still goes in); the same
insert twice (declaration refused, `assign` inserted again); first/last
item blank-line policy byte for byte; a line-continued `` `define`` cannot
swallow code (at `end` refused; between items it takes only the blank
line the insert adds); delete refused over a hierarchical use in another
file and over a `bind`, forced with the site listed; a forced delete whose
uses `diagnostics` then reports (`undeclared-identifier`); the non-ANSI
body port (refused, forced result parses strictly); the last items of a
module; a trailing comment running into the next line stays with its item
on both sides; the `gen_b` quirk (the dry-run note names `gen_a`, `gen_b`;
`gen_a` refused as part of a larger item); an item inside a guard; the
fence from every side (insert before/after, replace, forced delete).
**The prefix/suffix guarantee** (attack 4): `qa_every_accepted_call_changes_only_its_own_region`
takes `read_item`'s span before each of 7 replaces (a declaration, two
`always`, a package function, an instance, a generate loop, a whole
module), 4 insert/delete pairs and 3 forced deletes, and compares the
bytes before and after it; `qa_two_hundred_replaces_in_a_row…` does the
same for 200 calls plus 200 repeats (`unchanged`, file unchanged). No
drift anywhere. The strings/comments test and the generate test check it
too.
Findings (numbers match the `#[ignore]` reasons):
1. **BLOCKING — a `text` ending in an open `/*` swallows the fence
below it.** `verify.rs:101-115` (rule 1) asks only that the whole new
file lexes, and rule 2 compares items, not comments; a later `*/` in a
comment closes the new one. Repro: `module f; logic a; // lucisv: off
/* hand aligned */ logic keep_me; …` (one per line); `replace_item a`
with `logic a; /* note` → accepted; `format` (dry run) then rewrites
`logic keep_me;` → `logic keep_me;` and `assign keep_me =` →
`assign keep_me =` — hand-aligned code the fence protected. Same for
`insert_item`. Test `qa_a_text_leaving_a_comment_open_is_refused_even_when_a_later_one_closes_it`.
Fix: a lexical surroundings rule — every comment and token that begins
inside the region ends inside it (equivalently, the comments outside
the region are the old ones, shifted), or at least: `text` lexes on its
own.
2. **MEDIUM — `replace_item` is not idempotent when the text carries a
comment outside its item.** `item.rs:184` compares the text to the
item's span; a leading (`// doc\nlogic r;`) or trailing
(`logic p; // c`) comment lands in `Meta::leading`/`trailing`, outside
the new span, so every repeat adds one more copy — against
`idempotentHint: true`, and an agent retrying a call is the common case.
Test `qa_the_same_replace_twice_is_unchanged_even_with_a_comment_in_the_text`.
Fix (ruling): refuse a text whose items do not span it (comments go
inside the item or through `insert_item`), or compare the text with the
item plus its own comments, or drop the hint.
3. **BLOCKING — a use inside a macro argument or a macro body does not
stop `delete_item`.** `refs.rs:112-139`: `mentioned` sees the spelling,
but `find_references` and `local_uses` return no use there, so the
census is empty and the delete goes through with no warning. Repro:
`logic in_item;` used only in `` `ASSERT_KNOWN(k, in_item)`` (the
OpenTitan pattern), or `in_expr` in `` assign out = `ID(in_expr);``, or
`in_body` reached through `` `define IN_BODY in_body`` → deleted; the
design no longer compiles, reported as success. The README's
"deliberately not checked" names only token-pasted names. Test
`qa_a_use_inside_a_macro_argument_refuses_the_delete`. Fix: a
whole-word spelling outside comments and strings that the engine did
not account for (a macro call's arguments, a `` `define`` body) counts
as a doubt, as a skipped file does.
4. **BLOCKING — `delete_item` takes comments that are not the item's.**
`item.rs:397-403` (`own_lines`) walks `Meta::leading` back across blank
lines: deleting `a` in `// Section: registers\n// (applies to
everything below)\n\n// the a flop\nlogic a;` removes the section
banner; deleting module `m` removes the file banner above the blank
line. The PLAN says "its own leading comments"; the brief says the
header comment must survive. Test
`qa_a_comment_a_blank_line_separates_from_the_item_is_not_deleted`.
Fix: stop at the first gap holding a blank line (or at a comment whose
successor has `blank_before`).
5. **LOW — an item led by a block comment on its own line cannot be an
anchor or deleted.** `/* lead */ logic a;` — `own_lines` (`item.rs:394`)
asks whether the item's first byte starts its line, ignoring the
same-line leading comment; the refusal says "run `format` first", but
`format` keeps it that way, and `replace_item` with a leading block
comment produces exactly this shape. Test
`qa_an_item_led_by_a_block_comment_on_its_line_owns_that_line`.
6. **HIGH, for a ruling — a macro directive nested in a replaced item
changes code outside the span.** `` always_comb begin\n`undef W\n …
end`` (or `` `define W 1'b0``) replaces an `always` and is accepted;
`` assign b = `W;`` below it no longer compiles (or silently changes).
The README lists "the effect of directives the agent writes" as
deliberately not checked; the brief lists it as masked corruption.
`insert_item` of a `` `undef W``/`` `define W``/`` `default_nettype
none`` directive item is accepted the same way (arguably what an insert
of a directive is for). Test
`qa_a_macro_directive_nested_in_a_replaced_item_is_refused` pins the
stricter reading for `replace_item`. Cheap fix: `Analysis::defines`
entries inside the region must be the same before and after a replace.
7. **LOW — a text may carry a fence marker.** `insert_item` with
`// lucisv: off\n logic lo;` (no `on`) is accepted and fences every
line below it: `format` and `delete_item` then refuse code the agent
never touched (over-protection, no corruption). Test
`qa_a_text_carrying_a_fence_marker_is_refused`. Fix: refuse a text
holding a `fence::fence_of` comment.
8. **BLOCKING — a signal bound only by a `.*` connection is deleted
without a word.** `vlog_refactor::find_references` drops every span
that does not slice back to the name (`references.rs:49`), so the `.*`
site is never returned, and `refs.rs` trusts it (the README's argument
covers only the prefilter). Repro: `module star; logic clk; logic en;
logic o; sub u_sub (.*); endmodule` with `sub (input clk, en, output
o)` → `delete_item en` accepted; `u_sub` no longer elaborates. (`.name`
is caught.) Test `qa_a_signal_bound_only_by_a_dot_star_refuses_the_delete`.
Fix: in the item's own file, an instance with `.*` in the item's scope
whose module has a port of the name counts (M3.5's binding print knows
these), or conservatively any `.*` in that scope is a doubt.
Observations (not M4 findings): a forced delete of a non-ANSI body port
leaves `module k (a, b); output b;` and `diagnostics` answers "no
findings" — a lint gap (a header port with no direction), though the
forced warning names it. `.en(x)` in a named connection is counted as a
use of the instantiating module's own `en` (a safe-direction false
refusal, as the README says). Inserting before an item whose leading
comment is `// lucisv: on` is refused as fenced (conservative, fine).
Sizes (production lines: non-blank, non-`//` lines before
`#[cfg(test)]`, awk): `item.rs` 410, `item/verify.rs` 321, `item/refs.rs`
143, `tools/mod.rs` 180 — the dev's numbers. Functions: longest
`verify::class_of` 47 (a commented dispatch table), `refs::check` 41,
`Scan::uses_of` 38; none over 50. No `unwrap`/`expect`/`panic!` outside
`#[cfg(test)]` (the `outcome.items[0]`/`[len - 1]` in `insert_item` are
guarded by `Expect::Some`); no `#[allow]`.
Timings (release, macOS arm64, wall time per call over stdio): the dev's
40 000-line test — refused replace 298 ms, replace 148 ms, insert 267 ms,
delete 257 ms (the dev's figures, reproduced within 20 ms);
`qa_two_hundred_replaces…` (a 200-item module, 200 replaces each followed
by a `read_item`, a strict re-parse in the test and an `unchanged` repeat)
0.69 s for the whole test, under 2 ms a call.
Gates (each through `tools/guard.sh`, one cargo invocation at a time):
`cargo fmt -p lucisv_mcp -- --check` rc 0; `cargo clippy -p lucisv_mcp
--all-targets` clean (rc 0); `cargo test -p lucisv_mcp` 50 unit + 15
attacks + 0 (1 ignored) + 51 qa_m1 + 43 qa_m2 + 37 qa_m3 (1 ignored) + 27
qa_m4 (8 ignored) + 37 wire, all passed; `cargo test --workspace` **4 816
passed, 0 failed, 57 ignored** (4 789 + 27; 49 + 8). No guard kill.
To re-check after the rework: remove the `#[ignore]` of findings 1, 3, 4
and 8 (and of 2, 5, 6, 7 as the lead rules) and run
`cargo test -p lucisv_mcp --test qa_m4`.
**2026-09-23 (QA re-check, M4 rework) — verdict: PASS.**
The eight findings were re-checked against the reworked tree and the
lead's rulings (1a/1b, 2 widening, 3 macros, 4 blank-line gap, 5 same-line
comment, 6 define entries, 7 fence markers, 8 `.*`). The 8 finding tests
the dev un-ignored all pass.
Findings 1, 3, 4 and 8 were also re-derived by hand over stdio (scratch
driver, debug binary). 1: `logic a; /* note` above a fence with a later
`*/` is refused by "rule 1a: unterminated block comment", for both replace
and insert. 3: `in_expr` (`` `ID``), `in_item` (`` `ASSERT_KNOWN``) and
`in_body` (a `` `define`` body) are each refused as "possible use (macro)
at rtl/mac.sv:N". 4: deleting `a` keeps the section banner and the blank
line, and deleting module `c` keeps the file banner. 8: deleting `en` is
refused as "bound by `.*` at rtl/star.sv:5:14 `en` (module `sub`)", and
`force` deletes it with that warning.
Lead ruling applied: in `qa_every_accepted_call_changes_only_its_own_region`
the `r` case's text is now `logic [15:0] r;` (bound: read_item's span).
The new `qa_recheck_a_commented_text_replaces_exactly_the_widened_span`
checks that `logic [15:0] r; /* wider */` changes exactly
`logic [7:0] r; // the register` (the new file is prefix + text + suffix,
byte for byte) and that its repeat is `unchanged`. Two-comment texts on
either side are checked the same way.
The new rules were attacked with 10 more `qa_recheck_*` tests, all
passing:
- **1b, glued text:** `logic a;x` on the shared line `logic a;logic b;` is
refused by rule 1b (the token `xlogic` runs past the region). `logic a`
and `logic c` without `;` are refused by the parse.
- **1b, dangling comment:** a comment left on its own line at the end of a
replace or insert text is refused by rule 1b.
- **1a:** an open string, and an open `/*` with a `*/` further down the
file, are both refused (rule 1a, or the whole-file lex first). A string
holding `/*` and `//` is accepted, and only its span changes.
- **2, widening back:** where the old item had two own comment lines with
a blank line and a banner above them, a text starting with a comment
widens over exactly the two own lines; the repeat is `unchanged`. A
comment trailing the item above is not taken.
- **7, fences:** `logic e; // lucisv: off` and
`// verilog_format: on\nlogic e;` are refused (rule 7). Block comments
spelling `lucisv: on` are not fences (`fence::fence_of` matches `//`
only), which is correct. A commented text whose widened span would
cover `z`'s own `// lucisv: on` is refused as fenced, and a plain text
replaces `z` alone. Deleting the item just above `// lucisv: off` keeps
the marker.
- **3, macros:** `` `define`` bodies spelling `sig_x`/`xsig`/`sig_`, a
formal `sig` and a string `"sig"` are no use: `sig` is deleted with no
warning. `` `ASSERT(chk, u_s.hsig)`` in another file is a possible use.
- **8, `.*`:** a `.*` two generate levels down into a non-ANSI module
binds. A `.*` into an interface instance binds (`module `ifc``). A name
no `.*` target has as a port is deleted. A `.*` into an undeclared
module is a "possible use (`.*`)".
- **6, defines:** an `always` holding a `` `define`` (insert) or an
`` `undef`` (replace) is refused (rule 6). Inserting a `` `define``
item, and a `` `define`` item together with a declaration, is accepted
(the exemption).
Observations (low, not blocking; for the lead):
- **Rule 6 on `delete_item`:** a module holding a nested
`` `define LOCAL`` cannot be deleted, even with `force`. The refusal
says "the text changes a macro definition … edit the `define item
itself", but no selector reaches a `` `define`` item (`delete_item
LOCAL` answers "no declaration matches"), so the delete half of the
exemption is unreachable and the advice cannot be acted on. Pinned as
current behaviour in
`qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always`.
Suggestion: reword the refusal for delete ("the deletion would remove a
`define nested in the item; remove it by hand first").
- **Rule 3 false refusals:** the rule scans the whole set, so a common
name spelled in any macro call anywhere (another module's
`` `ASSERT(…, clk)``) refuses the delete. This errs on the safe side,
and `force` gets past it. Each delete also lexes every file that spells
the name; this was not timed on OpenTitan.
Sizes (production lines, same method as before): `item.rs` 379,
`item/verify.rs` 363, `item/refs.rs` 211, `item/lexical.rs` 132,
`item/star.rs` 73, `item/span.rs` 69, `item/macros.rs` 67, `tools/mod.rs`
180. The only function over 40 lines is `verify::class_of` (47, a
dispatch table). No `unwrap`/`expect`/`panic!` outside tests, and no
`#[allow]`.
Timings (release): the 40 000-line test ran a refused replace in 294 ms,
a replace in 159 ms, an insert in 284 ms and a delete in 263 ms, within
16 ms of the first run. The whole 200-replace test ran in 0.72 s.
Gates (each through `tools/guard.sh`, one at a time, no guard kill):
`cargo fmt -p lucisv_mcp -- --check` rc 0; `cargo clippy -p lucisv_mcp
--all-targets` clean (rc 0); `cargo test -p lucisv_mcp` 54 unit + 23
attacks + 0 (1 ignored) + 51 qa_m1 + 43 qa_m2 + 37 qa_m3 (1 ignored) + 45
qa_m4 + 37 wire, all passed; `cargo test --workspace --no-fail-fast`
**4 846 passed, 0 failed, 49 ignored** (the dev's 4 835 + the fixed test +
10 new).
## Review
**Lead, 2026-09-23 (M4).** This is the block's one new verifier, and it
earned invariant 4's treatment: the first QA round found four masked
corruptions (an open `/*` at the end of a text swallowing a fence; deletes
blind to macro-argument uses and to `.*` bindings; a delete taking a banner
comment), all fixed in a rework by a second dev after the app restart, with
rules 1a/1b (the text lexes alone; every token AND comment outside the region
is byte-identical, shifted), the widened replace span for commented texts,
own-comment and own-line rules stopping at a blank line, the define and
fence-marker invariants, and the macro and `.*` use scans. 45 QA tests and
23 dev attacks pin them. Two low items deferred to the evaluation rounds,
where real agent traffic will rank them: a forced delete of a module that
holds a `` `define`` is refused by rule 6 (ruling for the fix: `force`
relaxes rule 6 on delete, with a warning), and rule 3 lexes every file
spelling a common name on each delete (measure on opentitan before
changing). MCP-11/12/13 filed. Committed as M4.
+4 -2
View File
@@ -89,8 +89,10 @@ arrived.
tree. The build line (`lucisv-mcp: indexed N files in M ms`) is always
written to stderr; `--verbose` adds one timing line per request and the
freshness report per call.
- **`--index-cache DIR` is accepted and stored, and unused** until M6 reads
the LSP's store.
- **`--index-cache DIR`** names the directory holding the language server's
`index-cache` store, read read-only at startup (M6, 2026-09-23:
`docs/features/mcp-cache-and-census`), beside which this server writes its
own `index-cache-mcp` once at exit. A missing directory is a cold start.
- **Argument validation is a tool error, not a protocol error.** A call whose
`arguments` do not fit the tool's schema (unknown argument, wrong type,
missing required one) is answered `isError: true` with a sentence naming
+8
View File
@@ -24,6 +24,14 @@ hour. Record the release, the date and any failure in the table at the end.
| 15 | Hierarchy pane: right-click `aes` → "Star as DUT". | Three sections: "DUT: aes" (open, `aes` and its five children), "Parents of aes" (open, `aes` above `aes_tb`, `aes_wrap`, `tb`), "Other modules" (closed, 297 roots — the 292 plain ones plus the five `aes_tb` held beside `aes`, re-rooted). Right-click `aes` again → "Unstar DUT" puts the plain tree back exactly as it was. |
| 16 | Star `aes`, then `hmac`. | Five sections in that order; "Other modules" has 297 roots; each section opens and closes on its own; a module under both keeps its own open state in each. Title bar "Clear DUTs" removes both. |
| 17 | Add `"lucisv.hierarchy.duts": ["aes"]` to the workspace `.vscode/settings.json`. | The section appears without starring; right-clicking `aes` offers only a greyed "DUT from settings" whose tooltip names the setting; "Clear DUTs" leaves it. Remove the setting again. |
| 18 | MCP (VS Code 1.101+, platform `.vsix` in a clean profile: `code --profile lucisv-mcp-qa --install-extension lucisv-<v>-darwin-arm64.vsix`, opentitan open). Command palette → **MCP: List Servers**. | `lucisv (opentitan)` listed under the `lucisv` provider without opening a Verilog file first (the contribution point activates the extension); no error toast. |
| 19 | Start it from that list; accept VS Code's trust prompt. In Chat (agent mode) ask: "call lucisv's project_overview". | One trust prompt; the tool call answers with `roots: …/opentitan`, the file and unit counts; the server's MCP output log shows `lucisv-mcp: indexed N files` and no error. |
| 20 | Settings → `lucisv.mcp.enabled` off, then on again (no reload). | The server leaves **MCP: List Servers** when off and returns when on; Output → lucisv logged nothing new except, on the next activation with it off, one "lucisv.mcp.enabled is false" line. |
| 21 | File → Add Folder to Workspace… (a second folder); then remove it. | Two servers, `lucisv (opentitan)` and `lucisv (<second>)`, appear without a reload; removing the folder leaves one. |
| 22 | `lucisv.mcp.path` set to `/nowhere/lucisv-mcp`; start the server from the list. Reset the setting. | Not started; Output → lucisv: `cannot start the MCP server: "/nowhere/lucisv-mcp" not found …`; record whether VS Code itself adds a toast (acceptable if it is only VS Code's own "did not start" notice, not an extension error dialog). |
| 23 | Universal `lucisv-<v>.vsix` with no `lucisv-mcp` on PATH; start the server. | Same as 22 with `"lucisv-mcp" not found`; the language server (steps 1–5) unaffected. |
| 24 | **lucisv: Copy MCP server config** → Claude Code; paste into `.mcp.json` of a scratch copy of a project; in a terminal there run `claude`, `/mcp`. Repeat for VS Code → `.vscode/mcp.json` in another window. | The info message names `.mcp.json` and warns the bundled path moves on update; Claude Code lists `lucisv` connected and answers `project_overview`; the `.vscode/mcp.json` server (`"type": "stdio"`) starts too. |
| 25 | Optional, if a VS Code older than 1.101 is at hand: install the platform `.vsix` there. | Extension activates normally; Output → lucisv has one "no MCP server API (needs 1.101+)" line; the copy-config command still works. |
## Runs
+8 -5
View File
@@ -122,7 +122,10 @@ Confirmed against the VS Code extension guide (2026-09-23):
where the provider has `provideMcpServerDefinitions()` returning
`vscode.McpServerDefinition[]`, optional `resolveMcpServerDefinition()`
(called at server start) and `onDidChangeMcpServerDefinitions`.
- `new vscode.McpStdioServerDefinition({ label, command, args, cwd, env, version })`.
- `new vscode.McpStdioServerDefinition(label, command, args?, env?, version?)` —
**positional**, with `cwd` set as a property afterwards (corrected 2026-09-23
by the M5 dev against VS Code 1.138's `vscode.d.ts`; the VS Code guide's
object form is not what the extension host accepts).
- Users see the server under **MCP: List Servers** and the Extensions view;
trust is per server via the Accounts menu. Extension-provided servers are
usable by VS Code's agent mode (Copilot).
@@ -341,7 +344,7 @@ records MCP's own).
- Paths root-relative; a file named once per group, never per line.
- Line numbers 1-based, columns 1-based, in `file:line:col` form.
- Lists capped (`limit`, default 200) with `… and N more` — the agent can
- Lists capped (`limit`, default 500 since feedback-2) with `… and N more` — the agent can
page with `offset`.
- A declaration is shown as its own source line, trimmed, never the
surrounding block.
@@ -375,9 +378,9 @@ still carries no binaries and looks `lucisv-mcp` up on `PATH`.
- if `vscode.lm.registerMcpServerDefinitionProvider` exists and
`lucisv.mcp.enabled` (default `true`), registers provider `lucisv.mcp`
returning one `McpStdioServerDefinition` per workspace folder:
`{ label: "lucisv (<folder>)", command, args: ["--root", folder,
"--index-cache", storagePath], cwd: folder, version }`, re-fired on
workspace-folder changes;
`new McpStdioServerDefinition("lucisv (<folder>)", command, ["--root", folder,
"--index-cache", storagePath], undefined, version)` with `cwd = folder` set
afterwards, re-fired on workspace-folder changes;
- contributes the command **lucisv: Copy MCP server config** that puts a
JSON snippet on the clipboard in the host's dialect (Claude Code
`.mcp.json` → `mcpServers`; Cursor `.cursor/mcp.json`; VS Code
+19
View File
@@ -0,0 +1,19 @@
r1 a base: tokens=91094 tool_calls=10 wall_s=114 outcome=correct (47/47 rows, both params on every row; line numbers cite the module line)
r1 a mcp: tokens=107605 tool_calls=14 wall_s=335 outcome=correct (47/47) — used references on the module (whole-set, ~4 s per shim call) instead of hierarchy up; read files for overrides
r1 b base: tokens=59922 tool_calls=11 wall_s=25 outcome=correct (2 files, 3 lines, style matched, diagnostics clean)
r1 b mcp: tokens=74720 tool_calls=17 wall_s=78 outcome=correct (identical diff to base; used diagnostics to check; edited by hand rather than add_port)
r1 c base: tokens=87546 tool_calls=34 wall_s=172 outcome=correct (8/8 sites incl. the DV string path; nothing else touched; diagnostics clean)
r1 c mcp: tokens=104837 tool_calls=35 wall_s=171 outcome=INCOMPLETE 7/8 (missed the DV string path in entropy_src_path_if.sv); rename warned about the macro arg, agent fixed it; found chip_if by grep
r2 a mcp: tokens=106938 tool_calls=7 wall_s=105 outcome=INCOMPLETE 35/47 — used hierarchy up (good) but paged with a small limit and missed the trailing "… and N more"; feedback: total+range up front
r2 b mcp: tokens=70136 tool_calls=18 wall_s=86 outcome=correct (identical diff)
r2 c mcp: tokens=98636 tool_calls=35 wall_s=206 outcome=correct 8/8 (the unresolved-mentions list surfaced the DV string path; rename + manual fixes)
r2 c base rerun: tokens=92625 tool_calls=30 wall_s=131 outcome=correct 8/8 (variance vs r1 base 87546: +5.8%)
r3 a mcp: tokens=77708 tool_calls=9 wall_s=72 outcome=correct 47/47 (hierarchy up + in filter; -15% tokens vs base)
r3 b mcp: tokens=70030 tool_calls=17 wall_s=79 outcome=correct (identical diff)
r3 c mcp: tokens=109650 tool_calls=40 wall_s=218 outcome=correct 8/8
r3 d base: tokens=102579 tool_calls=33 wall_s=235 outcome=correct (71 instances, 20 modules, all 20 port counts right)
r3 d mcp: tokens=106942 tool_calls=12 wall_s=305 outcome=correct (71/20, all counts); unit_interface templates x20 wasted tokens
r3 c base OPUS: tokens=61092 tool_calls=7 wall_s=44 outcome=correct 8/8
r3 c mcp OPUS: tokens=69849 tool_calls=8 wall_s=62 outcome=correct 8/8
r3b d mcp (final binary): tokens=96416 tool_calls=10 wall_s=231 outcome=correct (71/20, all counts); -10% vs r3, -6% vs base
r3b a mcp (final binary): tokens=111444 tool_calls=12 wall_s=169 outcome=correct 47/47 — did not pass overrides:true, read overrides from files + grep-verified
+21
View File
@@ -1423,3 +1423,24 @@ count and within noise in time (`aes` 14 locations / 9 files, `.clk_i`
before it is rendered — one slice compare per location, unmeasurable —
so a stale index can omit a location but never point at a wrong line
(QA findings 1–4). `docs/features/references-hierarchical-surface/README.md`.
### 2026-09-23 — MCP: `lucisv-mcp` startup and the per-call sweep (TODO-MCP M6)
`lucisv-mcp` builds its index at the first tool call and can start it from
the language server's `index-cache` (read only) or its own
`index-cache-mcp` beside it (`docs/features/mcp-cache-and-census/README.md`).
Release build, the whole opentitan checkout (3 944 files), two runs of
`tests/opentitan.rs::opentitan_startup_cold_and_warm_and_the_stat_sweep`:
| what | wall | the language server's nearest row |
|---|---|---|
| cold start, no store | 1 854–1 887 ms | — |
| warm, own store (3 944 hits) | 837–847 ms | warm quiet workspace start 985–997 ms (§61), workspace scope |
| warm, the editor's store (3 944 hits) | 821–832 ms | — |
| exit, writing the own store (46.3 MB) | 251–272 ms | compaction skipped when unchanged (§P4b) |
| freshness sweep per call (median, 21 calls) | 5.6–6.1 ms (floor `tools/list` 0.38 ms) | — |
| `rename` dry run, whole set (`op_i` in `aes_cipher_core.sv`) | 2 227–2 276 ms | — (MCP-7) |
A warm build is walk 210 ms + store read 87 ms + read/hash/decode 318 ms +
merge 204 ms; a cold one parses instead (1 387 ms). The rows are not
like-for-like with the server's (it scans in stages and answers during the
scan); they sit side by side so a regression in either shows.
+2 -1
View File
@@ -6,7 +6,7 @@ this review. Loop 2 is closed; no uncommitted feature work is included.
## Assessment and current status
lucisv remains an eight-crate toolchain: six reusable Rust libraries, CLI and
lucisv is a nine-crate toolchain (2026-09-23: `lucisv_mcp` joined): six reusable Rust libraries, CLI, MCP and
LSP binaries, editor integration, corpus/release tools, and a static docs site.
The architecture still separates syntax, formatting, semantics, linting,
refactoring, and project inputs. The September 4 audit findings are fixed.
@@ -47,6 +47,7 @@ two edits have disjoint ownership.
| `crates/lucisv_core` | Config, filelists, cycle-aware walks and warning channel, format cache, atomic replacement; no language-engine dependency |
| `crates/lucisv` | Argument handling, input discovery/dedup, worker pool, reports and source writes |
| `crates/lucisv_server` | Ordered LSP loop and workspace overlays; `server/`, `state.rs`, capability handlers including `imports.rs`, `extract.rs`, `inline_module.rs`; project lint validation/logging in `lint/project.rs` |
| `crates/lucisv_mcp` | Model Context Protocol server for coding agents over stdio: `project/` (roots, filelist-or-walk, freshness sweep), `tools/` (26 tools: read, navigation, verified edits, structural edits with their own verifier in `tools/item/`), `apply.rs` (one all-or-nothing write path), `resources.rs`; composes the six libraries, never `lucisv_server` (`docs/mcp/PLAN.md`) |
| `editors/` | VS Code client/grammar/settings/hierarchy UI and other editor configuration; `hierarchySections.js` models DUT sections, `extract.js` supplies the module-name prompt |
| `tools/`, `scripts/`, `.gitea/workflows/` | Resource guard, corpus evaluation, artifact checks and releases |
| `docs/features/` | Implementation contracts, dated measurements, QA and acceptance records |
+1
View File
@@ -43,6 +43,7 @@ export default defineConfig({
{ label: 'Formatter', slug: 'guides/formatter' },
{ label: 'Linter', slug: 'guides/linter' },
{ label: 'Editors & LSP', slug: 'guides/editors' },
{ label: 'Agents (MCP)', slug: 'guides/agents' },
{ label: 'Supported syntax', slug: 'guides/syntax' }
] },
{ label: 'Reference', items: [
+300
View File
@@ -0,0 +1,300 @@
<!DOCTYPE html><html lang="en" dir="ltr" data-theme="dark" data-has-toc data-has-sidebar class="astro-vdxcvpsm"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Agents (MCP) | lucisv</title><link rel="canonical" href="https://lucisv.dev/guides/agents/"/><link rel="sitemap" href="/sitemap-index.xml"/><script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"lucisv","applicationCategory":"DeveloperApplication","operatingSystem":"macOS, Linux, Windows","license":"https://opensource.org/licenses/MIT","description":"A fast Verilog and SystemVerilog formatter, linter, and language server written in Rust.","codeRepository":"https://git.luci.ooo/lucio/verilogrustformatter"}</script><link rel="shortcut icon" href="/favicon.png" type="image/png"/><meta name="generator" content="Astro v7.2.8"/><meta name="generator" content="Starlight v0.41.9"/><meta property="og:title" content="Agents (MCP)"/><meta property="og:type" content="article"/><meta property="og:url" content="https://lucisv.dev/guides/agents/"/><meta property="og:locale" content="en"/><meta property="og:description" content="Give Claude Code, Cursor and VS Code's agent mode lucisv's parser, index and refactorings through the lucisv-mcp Model Context Protocol server."/><meta name="description" content="Give Claude Code, Cursor and VS Code's agent mode lucisv's parser, index and refactorings through the lucisv-mcp Model Context Protocol server."/><meta name="theme-color" content="#07111f"/><meta property="og:site_name" content="lucisv documentation"/><meta property="og:image" content="https://lucisv.dev/og.png"/><meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/><meta property="og:image:alt" content="lucisv — Verilog tooling that stays out of your way."/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:image" content="https://lucisv.dev/og.png"/><script>
window.StarlightThemeProvider = (() => {
const storedTheme =
typeof localStorage !== 'undefined' && localStorage.getItem('starlight-theme');
const theme =
storedTheme ||
(window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark';
return {
updatePickers(theme = storedTheme || 'auto') {
document.querySelectorAll('starlight-theme-select').forEach((picker) => {
const select = picker.querySelector('select');
if (select) select.value = theme;
/** @type {HTMLTemplateElement | null} */
const tmpl = document.querySelector(`#theme-icons`);
const newIcon = tmpl && tmpl.content.querySelector('.' + theme);
if (newIcon) {
const oldIcon = picker.querySelector('svg.label-icon');
if (oldIcon) {
oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
}
}
});
},
};
})();
</script><template id="theme-icons"><svg aria-hidden="true" class="light astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M5 12a1 1 0 0 0-1-1H3a1 1 0 0 0 0 2h1a1 1 0 0 0 1-1Zm.64 5-.71.71a1 1 0 0 0 0 1.41 1 1 0 0 0 1.41 0l.71-.71A1 1 0 0 0 5.64 17ZM12 5a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1a1 1 0 0 0 1 1Zm5.66 2.34a1 1 0 0 0 .7-.29l.71-.71a1 1 0 1 0-1.41-1.41l-.66.71a1 1 0 0 0 0 1.41 1 1 0 0 0 .66.29Zm-12-.29a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.71-.71a1.004 1.004 0 1 0-1.43 1.41l.73.71ZM21 11h-1a1 1 0 0 0 0 2h1a1 1 0 0 0 0-2Zm-2.64 6A1 1 0 0 0 17 18.36l.71.71a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.76-.66ZM12 6.5a5.5 5.5 0 1 0 5.5 5.5A5.51 5.51 0 0 0 12 6.5Zm0 9a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7Zm0 3.5a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-1a1 1 0 0 0-1-1Z"/></svg><svg aria-hidden="true" class="dark astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.64 13a1 1 0 0 0-1.05-.14 8.049 8.049 0 0 1-3.37.73 8.15 8.15 0 0 1-8.14-8.1 8.59 8.59 0 0 1 .25-2A1 1 0 0 0 8 2.36a10.14 10.14 0 1 0 14 11.69 1 1 0 0 0-.36-1.05Zm-9.5 6.69A8.14 8.14 0 0 1 7.08 5.22v.27a10.15 10.15 0 0 0 10.14 10.14 9.784 9.784 0 0 0 2.1-.22 8.11 8.11 0 0 1-7.18 4.32v-.04Z"/></svg><svg aria-hidden="true" class="auto astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg></template><link rel="stylesheet" href="/_astro/print.ehPL0gv-.css" media="print"><link rel="stylesheet" href="/_astro/common.DmBfrBWd.css"><script type="module" src="/_astro/page.Dwipeu-R.js"></script></head><body class="astro-vdxcvpsm"><a class="sl-skip-link astro-vxeigawq" href="#_top">Skip to content</a><div class="page sl-flex astro-gqpr5s5a"><header class="header astro-gqpr5s5a"><div class="header astro-nczgtkxc"><div class="title-wrapper sl-flex astro-nczgtkxc"><a href="/" class="site-title sl-flex astro-clw6ags5"><span class="astro-clw6ags5" translate="no">lucisv</span></a></div><div class="sl-flex print:hidden astro-nczgtkxc"><site-search class="astro-nczgtkxc astro-r5ar4xm7" data-translations="{&quot;placeholder&quot;:&quot;Search&quot;}"><button data-open-modal disabled aria-label="Search" aria-keyshortcuts="Control+K" class="astro-r5ar4xm7"><svg aria-hidden="true" class="astro-r5ar4xm7 astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.71 20.29 18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.39ZM11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z"/></svg><span class="sl-hidden md:sl-block astro-r5ar4xm7" aria-hidden="true">Search</span><kbd class="sl-hidden md:sl-flex astro-r5ar4xm7" style="display: none;"><kbd class="astro-r5ar4xm7">Ctrl</kbd><kbd class="astro-r5ar4xm7">K</kbd></kbd></button><dialog style="padding:0" aria-label="Search" class="astro-r5ar4xm7"><div class="dialog-frame sl-flex astro-r5ar4xm7"><button data-close-modal class="sl-flex md:sl-hidden astro-r5ar4xm7">Cancel</button><div class="search-container astro-r5ar4xm7"><div id="starlight__search" class="astro-r5ar4xm7"></div></div></div></dialog></site-search><script>
(() => {
const openBtn = document.querySelector('button[data-open-modal]');
const shortcut = openBtn?.querySelector('kbd');
if (!openBtn || !(shortcut instanceof HTMLElement)) return;
const platformKey = shortcut.querySelector('kbd');
if (platformKey && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
platformKey.textContent = '⌘';
openBtn.setAttribute('aria-keyshortcuts', 'Meta+K');
}
shortcut.style.display = '';
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
/** @type {HTMLElement | null} */
const target = document.querySelector('sl-sidebar-state-persist');
const state = JSON.parse(sessionStorage.getItem('sl-sidebar-state') || '0');
if (!target || !state || target.dataset.hash !== state.hash) return;
window._starlightScrollRestore = state.scroll;
customElements.define(
'sl-sidebar-restore',
class SidebarRestore extends HTMLElement {
connectedCallback() {
try {
const idx = parseInt(this.dataset.index || '');
const details = this.closest('details');
if (details && typeof state.open[idx] === 'boolean') details.open = state.open[idx];
} catch {}
}
}
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
scroller.scrollTop = window._starlightScrollRestore;
delete window._starlightScrollRestore;
})();
</script></sl-sidebar-state-persist><div class="md:sl-hidden"><div class="mobile-preferences sl-flex astro-b5gddk54"><div class="social-icons astro-b5gddk54"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#install" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Install</span></a><ul class="isMobile astro-cxyftcne" style="--depth: 1;"><li style="--depth: 1;" class="astro-cxyftcne"><a href="#vs-code-nothing-to-do" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">VS Code: nothing to do</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#claude-code-cursor-and-other-agents" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Claude Code, Cursor and other agents</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#standalone" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Standalone</span></a></li></ul></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#tools" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Tools</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#what-it-promises" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">What it promises</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#install" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Install</span></a><ul class="astro-cxyftcne" style="--depth: 1;"><li style="--depth: 1;" class="astro-cxyftcne"><a href="#vs-code-nothing-to-do" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">VS Code: nothing to do</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#claude-code-cursor-and-other-agents" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Claude Code, Cursor and other agents</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#standalone" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Standalone</span></a></li></ul></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#tools" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">TooLine truncated
server. A coding agent spawns it over stdio and asks it about the
Verilog/SystemVerilog tree instead of reading whole files: a module’s ports,
a file’s outline, one <code dir="auto">always</code> block, who instantiates what, every reference
to a signal. It can also make the edits lucisv already knows how to make
safely — format, lint fixes, rename, the port refactorings and single-item
replacements — each one verified before anything is written.</p>
<p>It is the same engine as the CLI and the language server (parser, index,
formatter, linter, refactorings), in a third binary that shares no state with
either.</p>
<div class="sl-heading-wrapper level-h2"><h2 id="install">Install</h2><a class="sl-anchor-link" href="#install"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Install”</span></a></div>
<div class="sl-heading-wrapper level-h3"><h3 id="vs-code-nothing-to-do">VS Code: nothing to do</h3><a class="sl-anchor-link" href="#vs-code-nothing-to-do"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “VS Code: nothing to do”</span></a></div>
<p>The platform <code dir="auto">.vsix</code> packages (<code dir="auto">darwin-arm64</code>, <code dir="auto">darwin-x64</code>, <code dir="auto">linux-x64</code>,
<code dir="auto">linux-arm64</code>, <code dir="auto">win32-x64</code>, and <code dir="auto">all</code>) carry <code dir="auto">lucisv-mcp</code> next to <code dir="auto">lucisv</code>
and <code dir="auto">lucisv-server</code>. On VS Code 1.101 or later the extension registers it
with agent mode, <strong>one server per workspace folder</strong>, named
<code dir="auto">lucisv (&lt;folder&gt;)</code>: open <strong>MCP: List Servers</strong> to see it, trust it once, and
agent mode can call its tools. The extension starts it as</p>
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv-mcp</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--root</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">&lt;folder&gt;</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--index-cache</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">&lt;the</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">extension</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">s workspace storage&gt;</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="lucisv-mcp --root <folder> --index-cache <the extension&#x27;s workspace storage>"><div></div></button></div></figure></div>
<p>Two settings govern it:</p>
<table>
<thead>
<tr>
<th>setting</th>
<th>default</th>
<th>what it does</th>
</tr>
</thead>
<tbody>
<tr>
<td><code dir="auto">lucisv.mcp.enabled</code></td>
<td><code dir="auto">true</code></td>
<td><code dir="auto">false</code> withdraws the server from agent mode (takes effect without a reload)</td>
</tr>
<tr>
<td><code dir="auto">lucisv.mcp.path</code></td>
<td><code dir="auto">""</code></td>
<td>a <code dir="auto">lucisv-mcp</code> to use instead of the bundled one; empty means the bundled one, else <code dir="auto">lucisv-mcp</code> on <code dir="auto">PATH</code></td>
</tr>
</tbody>
</table>
<p>The universal <code dir="auto">.vsix</code> carries no binaries: it looks <code dir="auto">lucisv-mcp</code> up on
<code dir="auto">PATH</code>, and when there is none it says so in the <strong>lucisv</strong> output channel
instead of starting anything. VS Code older than 1.101 has no MCP API; the
extension then registers nothing and everything else works as before.</p>
<div class="sl-heading-wrapper level-h3"><h3 id="claude-code-cursor-and-other-agents">Claude Code, Cursor and other agents</h3><a class="sl-anchor-link" href="#claude-code-cursor-and-other-agents"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Claude Code, Cursor and other agents”</span></a></div>
<p>These read their own config file, not VS Code’s. In VS Code, run
<strong>lucisv: Copy MCP server config</strong>, pick the host, and paste the snippet into
the file the message names. It points at the binary the extension would run
(the bundled one’s path changes when the extension updates — copy it again
then, or point at a <code dir="auto">lucisv-mcp</code> on <code dir="auto">PATH</code>).</p>
<p>By hand, with <code dir="auto">lucisv-mcp</code> on <code dir="auto">PATH</code>:</p>
<div class="expressive-code"><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5F636F"># Claude Code, from the project directory</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">claude</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">mcp</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">add</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">lucisv-mcp</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--root</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">.</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="claude mcp add lucisv -- lucisv-mcp --root ."><div></div></button></div></figure></div>
<p><code dir="auto">.mcp.json</code> (Claude Code, at the project root) or <code dir="auto">.cursor/mcp.json</code> (Cursor):</p>
<div class="expressive-code"><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="json"><code><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">{</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#7FDBCA;--1:#096E72">"mcpServers"</span><span style="--0:#D6DEEB;--1:#403F53">: {</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#7FDBCA;--1:#096E72">"lucisv"</span><span style="--0:#D6DEEB;--1:#403F53">: { </span><span style="--0:#7FDBCA;--1:#096E72">"command"</span><span style="--0:#D6DEEB;--1:#403F53">: </span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#C789D6;--1:#7C5686">lucisv-mcp</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#7FDBCA;--1:#096E72">"args"</span><span style="--0:#D6DEEB;--1:#403F53">: [</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#C789D6;--1:#7C5686">--root</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#C789D6;--1:#7C5686">/path/to/project</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#D6DEEB;--1:#403F53">] }</span></div></div><div class="ec-line"><div class="code"><span class="indent"><span style="--0:#D6DEEB;--1:#403F53"> </span></span><span style="--0:#D6DEEB;--1:#403F53">}</span></div></div><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">}</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="{ &quot;mcpServers&quot;: { &quot;lucisv&quot;: { &quot;command&quot;: &quot;lucisv-mcp&quot;, &quot;args&quot;: [&quot;--root&quot;, &quot;/path/to/project&quot;] } }}"><div></div></button></div></figure></div>
<p><code dir="auto">.vscode/mcp.json</code> (VS Code, when configured by hand instead of through the
extension):</p>
<div class="expressive-code"><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="json"><code><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">{</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#7FDBCA;--1:#096E72">"servers"</span><span style="--0:#D6DEEB;--1:#403F53">: {</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#7FDBCA;--1:#096E72">"lucisv"</span><span style="--0:#D6DEEB;--1:#403F53">: { </span><span style="--0:#7FDBCA;--1:#096E72">"type"</span><span style="--0:#D6DEEB;--1:#403F53">: </span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#C789D6;--1:#7C5686">stdio</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#7FDBCA;--1:#096E72">"command"</span><span style="--0:#D6DEEB;--1:#403F53">: </span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#C789D6;--1:#7C5686">lucisv-mcp</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#7FDBCA;--1:#096E72">"args"</span><span style="--0:#D6DEEB;--1:#403F53">: [</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#C789D6;--1:#7C5686">--root</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#C789D6;--1:#7C5686">/path/to/project</span><span style="--0:#D9F5DD;--1:#111111">"</span><span style="--0:#D6DEEB;--1:#403F53">] }</span></div></div><div class="ec-line"><div class="code"><span class="indent"><span style="--0:#D6DEEB;--1:#403F53"> </span></span><span style="--0:#D6DEEB;--1:#403F53">}</span></div></div><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">}</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="{ &quot;servers&quot;: { &quot;lucisv&quot;: { &quot;type&quot;: &quot;stdio&quot;, &quot;command&quot;: &quot;lucisv-mcp&quot;, &quot;args&quot;: [&quot;--root&quot;, &quot;/path/to/project&quot;] } }}"><div></div></button></div></figure></div>
<div class="sl-heading-wrapper level-h3"><h3 id="standalone">Standalone</h3><a class="sl-anchor-link" href="#standalone"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Standalone”</span></a></div>
<div class="expressive-code"><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">cargo</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">build</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--release</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">-p</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">lucisv_mcp</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#919F9F;--1:#5F636F"># target/release/lucisv-mcp</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="cargo build --release -p lucisv_mcp # target/release/lucisv-mcp"><div></div></button></div></figure></div>
<p>Arguments: <code dir="auto">--root DIR</code> (repeatable; default the current directory),
<code dir="auto">--filelist FILE</code> (index exactly the files an EDA filelist names),
<code dir="auto">--index-cache DIR</code>, <code dir="auto">--verbose</code> (per-call timing on stderr). Anything else is
refused with a usage line and exit status 2.</p>
<div class="sl-heading-wrapper level-h2"><h2 id="tools">Tools</h2><a class="sl-anchor-link" href="#tools"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Tools”</span></a></div>
<p>Generated from the binary’s own <code dir="auto">tools/list</code> (<code dir="auto">node editors/vscode/mcp_smoke.js target/release/lucisv-mcp --tool-table</code>); the first sentence of each
description. The agent sees the full description and input schema.</p>
<table>
<thead>
<tr>
<th>tool</th>
<th>writes</th>
<th>what it answers</th>
</tr>
</thead>
<tbody>
<tr>
<td><code dir="auto">project_overview</code></td>
<td></td>
<td>Files, units by kind, top modules, largest files.</td>
</tr>
<tr>
<td><code dir="auto">list_units</code></td>
<td></td>
<td>Units (modules, interfaces, packages, classes, programs) with file:line.</td>
</tr>
<tr>
<td><code dir="auto">unit_interface</code></td>
<td></td>
<td>A unit’s parameters, ports (direction, type, range), modports or members; <code dir="auto">template: true</code> adds an instantiation.</td>
</tr>
<tr>
<td><code dir="auto">outline</code></td>
<td></td>
<td>A file’s declarations as a tree with line ranges, and its parse errors.</td>
</tr>
<tr>
<td><code dir="auto">read_item</code></td>
<td></td>
<td>One item’s exact source and lines.</td>
</tr>
<tr>
<td><code dir="auto">search_symbols</code></td>
<td></td>
<td>Declarations whose name contains <code dir="auto">query</code> (any case), members included.</td>
</tr>
<tr>
<td><code dir="auto">defines</code></td>
<td></td>
<td>The `define table (name, parameters, body, file:line) of a <code dir="auto">file</code>, a macro <code dir="auto">name</code>, or all.</td>
</tr>
<tr>
<td><code dir="auto">definition</code></td>
<td></td>
<td>Where a name or macro is declared: file:line:col, kind, line.</td>
</tr>
<tr>
<td><code dir="auto">references</code></td>
<td></td>
<td>Uses of one declaration, then its unresolved mentions (strings, comments, macro text).</td>
</tr>
<tr>
<td><code dir="auto">hierarchy</code></td>
<td></td>
<td>Who instantiates a module (<code dir="auto">up</code>, with file:line) or what it instantiates (<code dir="auto">down</code>, default).</td>
</tr>
<tr>
<td><code dir="auto">diagnostics</code></td>
<td></td>
<td>Parse errors and lint findings (<code dir="auto">line:col severity message [rule]</code>) of <code dir="auto">file</code> or all.</td>
</tr>
<tr>
<td><code dir="auto">format</code></td>
<td>yes</td>
<td>Format <code dir="auto">file</code>/<code dir="auto">files</code> as <code dir="auto">lucisv format</code>; <code dir="auto">lines</code> limits it.</td>
</tr>
<tr>
<td><code dir="auto">fix_lint</code></td>
<td>yes</td>
<td>Apply the safe lint fixes to <code dir="auto">file</code>/<code dir="auto">files</code>; says what remains.</td>
</tr>
<tr>
<td><code dir="auto">rename</code></td>
<td>yes</td>
<td>Rename a declaration and its uses; select as <code dir="auto">definition</code>.</td>
</tr>
<tr>
<td><code dir="auto">expand_wildcard</code></td>
<td>yes</td>
<td>Replace one instance’s <code dir="auto">.*</code> with the named connections it binds.</td>
</tr>
<tr>
<td><code dir="auto">convert_ports</code></td>
<td>yes</td>
<td>Rewrite a module’s non-ANSI header as an ANSI port list.</td>
</tr>
<tr>
<td><code dir="auto">organize_imports</code></td>
<td>yes</td>
<td>Remove unused <code dir="auto">import</code>s in the scope at a position; sort the rest.</td>
</tr>
<tr>
<td><code dir="auto">inline_module</code></td>
<td>yes</td>
<td>Replace one instance with its module’s body, connections substituted.</td>
</tr>
<tr>
<td><code dir="auto">propagate_ports</code></td>
<td>yes</td>
<td>Connect by name every port one instance leaves unconnected.</td>
</tr>
<tr>
<td><code dir="auto">remove_port</code></td>
<td>yes</td>
<td>Delete a port and its connection in every instantiation; refused while the body uses it.</td>
</tr>
<tr>
<td><code dir="auto">add_port</code></td>
<td>yes</td>
<td>Add an ANSI port to a module, connected in every instantiation; <code dir="auto">after</code> positions it.</td>
</tr>
<tr>
<td><code dir="auto">extract_module</code></td>
<td>yes</td>
<td>Move whole items in lines <code dir="auto">start_line</code>..<code dir="auto">end_line</code> to a new module instantiated in their place.</td>
</tr>
<tr>
<td><code dir="auto">replace_item</code></td>
<td>yes</td>
<td>Replace one item with <code dir="auto">text</code>: one item, same kind and names (unless <code dir="auto">rename</code>; references untouched).</td>
</tr>
<tr>
<td><code dir="auto">insert_item</code></td>
<td>yes</td>
<td>Insert items <code dir="auto">text</code> before or after item <code dir="auto">anchor</code>, or at <code dir="auto">end</code> (<code dir="auto">end@NAME</code>) of the last unit (unit NAME).</td>
</tr>
<tr>
<td><code dir="auto">delete_item</code></td>
<td>yes</td>
<td>Delete one item and its leading comments; refused while its names are used (sites listed) or it holds a `define, unless <code dir="auto">force</code>.</td>
</tr>
<tr>
<td><code dir="auto">instantiate</code></td>
<td></td>
<td>Instantiation text for module <code dir="auto">name</code>: parameters, instance name, named or <code dir="auto">.*</code> ports.</td>
</tr>
</tbody>
</table>
<div class="sl-heading-wrapper level-h2"><h2 id="what-it-promises">What it promises</h2><a class="sl-anchor-link" href="#what-it-promises"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “What it promises”</span></a></div>
<ul>
<li><strong>Answers come from the disk.</strong> Every call first re-checks the files it
indexes, so no answer is older than the disk at the moment the call
arrived. Unsaved editor buffers are invisible to it — save before asking.</li>
<li><strong>Edits are verified, then written whole.</strong> Every edit tool computes and
verifies every file’s new text before the first write; a refusal names the
reason and touches nothing. The formatter’s own safety net applies to
<code dir="auto">format</code>; <code dir="auto">replace_item</code>, <code dir="auto">insert_item</code> and <code dir="auto">delete_item</code> require the file to
still parse and change no byte outside the item.</li>
<li><strong><code dir="auto">dry_run: true</code></strong> on any edit tool returns the unified diff instead of
writing.</li>
<li><strong>Nothing outside the roots.</strong> Every path a tool takes must resolve inside a
<code dir="auto">--root</code>; anything else is refused.</li>
<li><strong>The language server’s cache is never written.</strong> <code dir="auto">--index-cache</code> names
the directory the extension gives <code dir="auto">lucisv-server</code>; <code dir="auto">lucisv-mcp</code> accepts it
today and will read that store (read-only) for a warm start in a later
release — never write it, so there are never two writers.</li>
</ul>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/agents.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-23T22:59:07.000Z">Sep 23, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/editors/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors &amp; LSP</span></span></a><a href="/guides/syntax/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Supported syntax</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
+3 -3
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
@@ -101,4 +101,4 @@ come from the setting are shown locked.</p>
<p>The repository includes a protocol-level check that starts the server exactly as the VS Code extension does:</p>
<div class="expressive-code"><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">node</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">editors/vscode/smoke.js</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">target/release/lucisv-server</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="node editors/vscode/smoke.js target/release/lucisv-server"><div></div></button></div></figure></div>
<p>See <a href="/reference/language-tools/">Language tools</a> for every advertised request and editor feature.</p>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/editors.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-06T05:04:05.000Z">Sep 6, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/linter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Linter</span></span></a><a href="/guides/syntax/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Supported syntax</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/editors.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-06T05:04:05.000Z">Sep 6, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/linter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Linter</span></span></a><a href="/guides/agents/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Agents (MCP)</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
+3 -3
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
@@ -113,4 +113,4 @@ do not have independent fence scopes. Fenced text must still parse.</p>
<li><strong>Write atomically.</strong> An error leaves the affected file untouched.</li>
<li><strong>Stay deterministic.</strong> Parallel worker count changes performance, never output order or exit status.</li>
</ol>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/formatter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/configuration/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Configuration</span></span></a><a href="/guides/linter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Linter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/formatter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T07:43:13.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/configuration/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Configuration</span></span></a><a href="/guides/linter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Linter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
+3 -3
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
@@ -121,4 +121,4 @@ to the lucisv log whether the file was named by the editor setting or by
are reported under <code dir="auto">unused-waiver</code> at their line of the waiver file, by
<code dir="auto">lucisv check</code> only and only after the whole run.</p>
<p>See the <a href="/reference/rules/">complete rule reference</a>.</p>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/linter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T06:45:48.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/formatter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a><a href="/guides/editors/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors &amp; LSP</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/linter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T07:43:13.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/formatter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a><a href="/guides/editors/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors &amp; LSP</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
+3 -3
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
@@ -110,4 +110,4 @@
<div class="sl-heading-wrapper level-h2"><h2 id="not-supported">Not supported</h2><a class="sl-anchor-link" href="#not-supported"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Not supported”</span></a></div>
<p>Parser acceptance does not imply full elaboration or semantic navigation: generate-block-scoped hierarchical paths and DPI-export name binding remain gaps. lucisv also does not run a preprocessor, so a file that becomes valid only after cross-file macro expansion may not format as a standalone input.</p>
<aside aria-label="Safe failure" class="starlight-aside starlight-aside--caution"><p class="starlight-aside__title" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="starlight-aside__icon"><path d="M12 16a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm10.67 1.47-8.05-14a3 3 0 0 0-5.24 0l-8 14A3 3 0 0 0 3.94 22h16.12a3 3 0 0 0 2.61-4.53Zm-1.73 2a1 1 0 0 1-.88.51H3.94a1 1 0 0 1-.88-.51 1 1 0 0 1 0-1l8-14a1 1 0 0 1 1.78 0l8.05 14a1 1 0 0 1 .05 1.02v-.02ZM12 8a1 1 0 0 0-1 1v4a1 1 0 0 0 2 0V9a1 1 0 0 0-1-1Z"/></svg>Safe failure</p><div class="starlight-aside__content"><p>Whole-file formatting returns an error and writes nothing when parsing is incomplete. lucisv never emits a partially understood file.</p></div></aside>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/syntax.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T06:12:49.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/editors/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors &amp; LSP</span></span></a><a href="/reference/cli/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/syntax.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T07:43:13.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/agents/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Agents (MCP)</span></span></a><a href="/reference/cli/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"version":"1.5.2","languages":{"en":{"hash":"en_5a9cf9ce1e","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
{"version":"1.5.2","languages":{"en":{"hash":"en_51647babd6","wasm":"en","page_count":13}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
Binary file not shown.
Binary file not shown.
+3 -3
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
@@ -202,4 +202,4 @@ decomposition deferred to Loop 3.</p>
</ul>
<div class="sl-heading-wrapper level-h2"><h2 id="release-surface">Release surface</h2><a class="sl-anchor-link" href="#release-surface"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Release surface”</span></a></div>
<p>The supported publication surface is seven VS Code <code dir="auto">.vsix</code> packages plus checksums: five platform packages (Apple Silicon/Intel macOS, x86-64/ARM64 static-musl Linux, Windows), one all-platform package, and one universal package requiring binaries on <code dir="auto">PATH</code>. Both <code dir="auto">lucisv</code> and <code dir="auto">lucisv-server</code> are bundled in platform packages. Standalone binaries are built by the tooling but are not published as release assets. The release tooling audits file type, dynamic linkage, and the glibc ceiling for cross-built artifacts.</p>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/architecture.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rust-api/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/architecture.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T07:43:13.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rust-api/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
+2 -2
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
+3 -3
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
@@ -379,4 +379,4 @@ unchanged <code dir="auto">lucisv/moduleHierarchy</code> snapshot; it adds no se
</table>
<div class="sl-heading-wrapper level-h2"><h2 id="workspace-lifecycle">Workspace lifecycle</h2><a class="sl-anchor-link" href="#workspace-lifecycle"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Workspace lifecycle”</span></a></div>
<p>The server handles <code dir="auto">didOpen</code>, incremental <code dir="auto">didChange</code>, <code dir="auto">didSave</code>, <code dir="auto">didClose</code>, watched-file changes, configuration changes, cancellation, shutdown, and exit. It dynamically registers file watchers, emits work-done progress while building large indexes, coalesces code-lens refreshes, and promotes open-buffer overlays into the workspace without waiting for disk writes.</p>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-06T04:04:14.000Z">Sep 6, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T07:43:13.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
+2 -2
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
+3 -3
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
@@ -734,4 +734,4 @@ recorded in the repository topology, handshakes 32–33.</p>
</tbody>
</table>
<aside aria-label="Types" class="starlight-aside starlight-aside--note"><p class="starlight-aside__title" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="starlight-aside__icon"><path d="M12 11a1 1 0 0 0-1 1v4a1 1 0 0 0 2 0v-4a1 1 0 0 0-1-1Zm.38-3.92a1 1 0 0 0-.76 0 1 1 0 0 0-.33.21 1.15 1.15 0 0 0-.21.33 1 1 0 0 0 .21 1.09c.097.088.209.16.33.21A1 1 0 0 0 13 8a1.05 1.05 0 0 0-.29-.71 1 1 0 0 0-.33-.21ZM12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 18a8 8 0 1 1 0-16.001A8 8 0 0 1 12 20Z"/></svg>Types</p><div class="starlight-aside__content"><p>The crates also expose their data models—AST nodes, diagnostics, rule traits, workspace identifiers, edits, plans, and formatter document nodes. This page intentionally indexes callable behavior; generated Rust API docs remain the right place for field-level type details.</p></div></aside>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rust-api.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/language-tools/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a><a href="/reference/architecture/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Architecture</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rust-api.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T07:43:13.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/language-tools/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a><a href="/reference/architecture/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Architecture</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
+1 -1
View File
@@ -1 +1 @@
<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"><url><loc>https://lucisv.dev/</loc></url><url><loc>https://lucisv.dev/guides/editors/</loc></url><url><loc>https://lucisv.dev/guides/formatter/</loc></url><url><loc>https://lucisv.dev/guides/linter/</loc></url><url><loc>https://lucisv.dev/guides/syntax/</loc></url><url><loc>https://lucisv.dev/reference/architecture/</loc></url><url><loc>https://lucisv.dev/reference/cli/</loc></url><url><loc>https://lucisv.dev/reference/language-tools/</loc></url><url><loc>https://lucisv.dev/reference/rules/</loc></url><url><loc>https://lucisv.dev/reference/rust-api/</loc></url><url><loc>https://lucisv.dev/start/configuration/</loc></url><url><loc>https://lucisv.dev/start/quick-start/</loc></url></urlset>
<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"><url><loc>https://lucisv.dev/</loc></url><url><loc>https://lucisv.dev/guides/agents/</loc></url><url><loc>https://lucisv.dev/guides/editors/</loc></url><url><loc>https://lucisv.dev/guides/formatter/</loc></url><url><loc>https://lucisv.dev/guides/linter/</loc></url><url><loc>https://lucisv.dev/guides/syntax/</loc></url><url><loc>https://lucisv.dev/reference/architecture/</loc></url><url><loc>https://lucisv.dev/reference/cli/</loc></url><url><loc>https://lucisv.dev/reference/language-tools/</loc></url><url><loc>https://lucisv.dev/reference/rules/</loc></url><url><loc>https://lucisv.dev/reference/rust-api/</loc></url><url><loc>https://lucisv.dev/start/configuration/</loc></url><url><loc>https://lucisv.dev/start/quick-start/</loc></url></urlset>
+3 -3
View File
@@ -38,7 +38,7 @@
})();
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
StarlightThemeProvider.updatePickers();
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0nvgbbg" class="astro-f5yvicm7"><script aria-hidden="true">
(() => {
try {
if (!matchMedia('(min-width: 50em)').matches) return;
@@ -61,7 +61,7 @@
);
} catch {}
})();
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors &amp; LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/agents/" class="astro-ojxuodky"><span class="astro-ojxuodky">Agents (MCP)</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
(() => {
const scroller = document.getElementById('starlight__sidebar');
if (!window._starlightScrollRestore || !scroller) return;
@@ -326,4 +326,4 @@ alone can reuse an incorrect clean verdict, including in <code dir="auto">--chec
After toggling it, use <code dir="auto">--no-cache</code> or delete <code dir="auto">.lucisv_cache/</code> (or your custom
cache directory) before formatting or checking again. Editor formatting does
not use this CLI format cache.</p>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/start/configuration.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T06:12:49.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/quick-start/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Quick start</span></span></a><a href="/guides/formatter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/start/configuration.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T07:43:13.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/quick-start/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Quick start</span></span></a><a href="/guides/formatter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more