Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72ff5df1cc | ||
|
|
4edada583f | ||
|
|
14b72f2862 | ||
|
|
82bbba04be | ||
|
|
7a0c8e51f9 | ||
|
|
ef867db004 |
No files matched your search
@@ -4,6 +4,59 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.56.0 — 2026-09-23
|
||||
|
||||
### Rename keeps implicit connections bound; the MCP server, as a preview
|
||||
|
||||
- **Rename no longer cuts a `.name` or `.*` connection.** Renaming a
|
||||
port `d` → `din` of `leaf` used to leave `leaf u (.*)` binding nothing
|
||||
and turn `.d` into `.din` against a parent with no net `din`; renaming
|
||||
the parent's net cut both bindings — and every case verified clean,
|
||||
because nothing records what an implicit connection binds. Now the
|
||||
binding is written out: `.d` becomes `.din(d)`, a `.*` that bound the
|
||||
port gains `.din(d)` beside it, and a renamed net `n` → `m` gives
|
||||
`.n(m)`. Every rewrite is listed in the rename's warnings; a case the
|
||||
engine cannot read — a `.*` into a module lucisv cannot see or finds
|
||||
declared twice, a list split by `ifdef`s, a hierarchical `bind` target,
|
||||
a `.*` that would start binding the new name — is refused with the
|
||||
reason. The verifier now prints every implicit binding before and after
|
||||
and refuses a mismatch, and accepts only the four spelled connection
|
||||
templates at the exact positions the rewrite writes them. The language
|
||||
server hands the engine one more hop of files (the modules a handed-over
|
||||
file instantiates), so a `.*` into a module declaring neither name is
|
||||
read rather than refused. A `bind` onto a bare instance name resolves
|
||||
through the instance table, so `clk_i`/`rst_ni`/`err_o` renames beside
|
||||
opentitan's fifo binds succeed. On opentitan copies: `prim_count`'s
|
||||
`err_o`, `aes_core`'s `clk_i` and `entropy_src`'s `clk_i` rename cleanly
|
||||
with their `.*` cov binds written out; `prim_fifo_sync`'s `clr_i` is
|
||||
refused over the FPV binds that really target fifo instances — the
|
||||
refusal the old engine silently skipped.
|
||||
(`docs/features/refactor-rename/README.md`, "Implicit connections".)
|
||||
- **`lucisv-mcp`, a Model Context Protocol server for coding agents —
|
||||
preview.** A third binary, `cargo build --release -p lucisv_mcp`, MCP
|
||||
over stdio, built from the same library crates as the editor and the
|
||||
CLI and sharing no code path with either. Twenty-three tools:
|
||||
`project_overview`, `list_units`, `unit_interface` (ports, parameters,
|
||||
a paste-ready instantiation), `outline`, `read_item` (one module,
|
||||
function or `always` block — not the file), `search_symbols`,
|
||||
`defines`, `definition`, `references`, `hierarchy`, `diagnostics`
|
||||
(what `lucisv check` says, with the CLI's JSON field names), and the
|
||||
edit tools `format`, `fix_lint`, `rename`, `expand_wildcard`,
|
||||
`convert_ports`, `organize_imports`, `inline_module`,
|
||||
`propagate_ports`, `remove_port`, `add_port`, `extract_module`,
|
||||
`instantiate` — every edit verified by the same engines, all-or-nothing,
|
||||
re-read before the first write, inside the roots only, with `dry_run`
|
||||
returning the diff. Answers are from disk (never an unsaved buffer),
|
||||
fresh at every call, rendered for a token budget. Try it from a
|
||||
checkout with Claude Code
|
||||
(`claude mcp add lucisv -- /path/to/lucisv-mcp --root .`), Cursor
|
||||
(`.cursor/mcp.json`) or VS Code (`.vscode/mcp.json`, `"type": "stdio"`).
|
||||
Not yet inside the `.vsix` and not yet reading the editor's index
|
||||
cache — those are the next lanes (`docs/mcp/PLAN.md`, `TODO-MCP.md`;
|
||||
feature READMEs `docs/features/mcp-*`).
|
||||
- **CLI:** `--diff` output is unchanged; its printer now lives in
|
||||
`lucisv_core::diff`, shared with the MCP server's `dry_run`.
|
||||
|
||||
## 0.55.0 — 2026-09-17
|
||||
|
||||
### Loop 3, round 2 — find-references reaches a module's internals
|
||||
|
||||
Generated
+22
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"vlog_formatter",
|
||||
"vlog_linter",
|
||||
"vlog_parser",
|
||||
"vlog_refactor",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -265,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -278,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+2
-1
@@ -9,10 +9,11 @@ members = [
|
||||
"crates/lucisv_core",
|
||||
"crates/lucisv",
|
||||
"crates/lucisv_server",
|
||||
"crates/lucisv_mcp",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
# TODO-MCP — the Model Context Protocol block
|
||||
|
||||
Planned 2026-09-23 by the lead at 0.55.0. The analysis and design are in
|
||||
[`docs/mcp/PLAN.md`](docs/mcp/PLAN.md); read it before touching any lane.
|
||||
This file is the tracking sheet for the block and stays separate from
|
||||
`TODO.md` on purpose: the block is independent of the LSP and CLI lanes, and
|
||||
its lanes collide with nothing in `docs/topo.md` except where a lane below
|
||||
says so.
|
||||
|
||||
Rules that apply to every lane, restated once: CLAUDE.md in full (guard
|
||||
every suite and sweep through `tools/guard.sh`; no `git commit`/`push`; a
|
||||
feature README kept current as you work; no file outside the lane's list;
|
||||
cross-module wants are Handshake requests, not edits); opentitan is
|
||||
read-only; no `sleep` over 60 s; `cargo fmt -p` per package while another
|
||||
lane is live. Each lane is one Opus dev then one Opus QA (owner's ruling
|
||||
2026-09-23: both Opus 5.5), working directly on trunk, then the lead's
|
||||
self-inspection and a commit; no release until every lane is done. A QA
|
||||
"rework" loops inside its lane.
|
||||
|
||||
## Fixed names (the wire shapes every lane pins by test)
|
||||
|
||||
| thing | name |
|
||||
|---|---|
|
||||
| crate / binary | `crates/lucisv_mcp` / `lucisv-mcp` |
|
||||
| arguments | `--root DIR` (repeatable; default cwd), `--filelist FILE`, `--index-cache DIR`, `--verbose`; anything else → `usage:` on stderr, exit 2 (the server's posture) |
|
||||
| vsix entry | `extension/bin/lucisv-mcp[.exe]` (platform), `extension/bin/<vsce-target>/lucisv-mcp[.exe]` (all) |
|
||||
| VS Code provider id | `lucisv.mcp`; settings `lucisv.mcp.enabled` (true), `lucisv.mcp.path` (""); command `lucisv.mcp.copyConfig` |
|
||||
| feature READMEs | `docs/features/mcp-transport`, `mcp-read-tools`, `mcp-navigation`, `mcp-edit-tools`, `mcp-structural-edits`, `mcp-packaging`, `mcp-cache-and-census` |
|
||||
|
||||
## M1. Transport and the read tools
|
||||
|
||||
**Files:** `Cargo.toml` (workspace `members` += `crates/lucisv_mcp`),
|
||||
`Cargo.lock`, everything under `crates/lucisv_mcp/` (`src/main.rs`,
|
||||
`transport.rs`, `rpc.rs`, `project.rs`, `render.rs`, `tools/mod.rs`,
|
||||
`tools/read.rs`, `tests/wire.rs`, `tests/fixtures/`), the two feature
|
||||
READMEs. Nothing else — in particular no change to any library crate; a
|
||||
missing public query is a Handshake entry.
|
||||
|
||||
- [x] crate skeleton: `main.rs` argument contract (table above), the
|
||||
`PARSE_STACK_SIZE` main thread, the ordered loop; `transport.rs`
|
||||
newline-delimited JSON-RPC over stdio (stdout protocol-only, stderr
|
||||
log-only; a line that is not JSON → `-32700`, never a crash)
|
||||
- [x] `rpc.rs`: `initialize` (version negotiation over a listed set, the
|
||||
pinned current revision first; `serverInfo`; `capabilities`;
|
||||
`instructions`), `notifications/initialized`, `ping`, `tools/list`,
|
||||
`tools/call` envelope (`content` text + `structuredContent`,
|
||||
`isError` for refusals), `notifications/cancelled` accepted, unknown
|
||||
method/tool/params → `-32601`/`-32602`
|
||||
- [x] `project.rs`: roots, `Discovery`, filelist-or-walk file set with the
|
||||
1 MiB cap, `IndexBuilder` build, lazy per-file `Semantics`, the
|
||||
per-call stat sweep + `update_file`/`remove_file` + re-walk policy
|
||||
(PLAN §4.4); a path outside every root is refused by name
|
||||
- [x] tools `project_overview`, `list_units`, `unit_interface` (ports,
|
||||
parameters, template via `instantiation_plan`; modports for an
|
||||
interface; exports for a package), `outline`, `read_item` (incl. the
|
||||
`always@<line>` spelling for unlabelled blocks), `search_symbols` —
|
||||
each with `inputSchema`, `annotations` (`readOnlyHint: true`), a
|
||||
one-sentence description written for the agent, and the compact
|
||||
rendering rules of PLAN §4.5
|
||||
- [x] `tests/wire.rs`: spawns the built binary; the handshake; every tool
|
||||
over a fixture tree of ≥ 6 files (a package, two modules with a
|
||||
`.*` instance, an interface with a modport, a class, a file with a
|
||||
parse error); a freshness test (edit a fixture on disk between two
|
||||
calls, second answer reflects it; delete one, it disappears;
|
||||
fingerprint equals a rebuild after each); a malformed-line test; a
|
||||
`--root` outside-path refusal
|
||||
- [x] README `mcp-transport`: Goal, Assumptions (why no `rmcp`; the pinned
|
||||
protocol revisions; sync one-at-a-time), Handshakes (none consumed
|
||||
beyond public APIs — list them), work log; README `mcp-read-tools`
|
||||
likewise, with the rendering rules as its contract
|
||||
- [x] gates through `tools/guard.sh`; sizes reported per file
|
||||
- [x] QA: protocol attacks (an `id` that is a string, a null `id`, a
|
||||
notification with an `id`, a 10 MB line, a request before
|
||||
`initialize`, an unsupported `protocolVersion`), rendering attacks
|
||||
(a unit named with an escaped identifier, a port with a packed and
|
||||
unpacked range, a file with CRLF line endings — line numbers must
|
||||
still be right), the freshness promise under a rename-then-recreate
|
||||
of a file within one second; verdict in the QA logs
|
||||
|
||||
## M2. Navigation, diagnostics, resources
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/nav.rs`, `resources.rs`,
|
||||
`tools/mod.rs` (registry entries only), `rpc.rs` (the three `resources/*`
|
||||
methods), `tests/wire.rs` (additions), the `mcp-navigation` README.
|
||||
Depends on M1 merged.
|
||||
|
||||
- [x] `definition` (selector: `file,line,col` or `name,unit?`; local via
|
||||
`Semantics::definition_of`, cross-file via `resolve_external`;
|
||||
ambiguity is a list), `references` (`vlog_refactor::find_references`,
|
||||
grouped by file, capped with `limit`/`offset`), `hierarchy` (down from
|
||||
`root` or every top-level module; `up` lists parents; parameter
|
||||
overrides as written; `depth`), `diagnostics` (parse errors,
|
||||
missing-closer warnings via the tolerant tree, lint through
|
||||
`select_rules` + the project's `[lint]` config + external waivers +
|
||||
an index-backed `MentionOracle`; the CLI's JSON field names), `defines`
|
||||
(table; one-step expansion when called with `name` + `args`)
|
||||
- [x] resources `lucisv://overview`, `lucisv://unit/{name}`,
|
||||
`lucisv://rules` (`rules_markdown()`), `lucisv://file/{path}/outline`;
|
||||
`resources/templates/list` for the two parameterised ones
|
||||
- [x] the opentitan parity census as an `#[ignore]` test taking the
|
||||
checkout path from an env var: `references`/`definition` on the
|
||||
`references-nav` symbols and `hierarchy` down from `top_earlgrey`
|
||||
compared with the LSP's answers recorded in that README (read-only;
|
||||
`git status` of the checkout identical before and after)
|
||||
- [x] README `mcp-navigation`; work log; gates; sizes
|
||||
- [x] QA: a `bind` connection's bare name, a `u_x.sig` tail, a name that
|
||||
is both a port and an internal net (must list both, not pick), a
|
||||
class member, a macro-only name (`files_naming_in_macros`), a
|
||||
`hierarchy` over a recursive/generate-instantiated module (must
|
||||
terminate with the depth cap), lint options from `lucisv.toml`
|
||||
honoured; verdict
|
||||
|
||||
## M3. Edit tools (wrapping the verified engines)
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/edit.rs`, `apply.rs`, `tools/mod.rs`
|
||||
(entries), `tests/wire.rs` (additions), `tests/fixtures/` (additions), the
|
||||
`mcp-edit-tools` README. Depends on M2 merged and on the ruling for
|
||||
Handshake MCP-1 (the diff lift) — until MCP-1 lands, `apply.rs` carries a
|
||||
private copy of `unified` marked `// TODO(MCP-1)` and the README says so.
|
||||
|
||||
- [x] `apply.rs`: `RefactorEdit` → (`dry_run`) unified diff per file | the
|
||||
all-computed-then-written loop over `write_atomic`, refusing before
|
||||
the first write on any verifier failure; the summary (files, +/-
|
||||
lines, warnings, created); the "written N of M then failed" report
|
||||
- [x] `format` (`files[]` or `file` + `lines`, `dry_run`), `fix_lint`
|
||||
(`apply_fixes` through `fence::protected_regions`, safe fixes only),
|
||||
`rename`, `expand_wildcard`, `convert_ports`, `organize_imports`,
|
||||
`inline_module`, `propagate_ports`, `remove_port`, `add_port`,
|
||||
`extract_module` (`home`: new file / same file; the created file is
|
||||
written too), `instantiate` (text only; `style`) — every one with
|
||||
`destructiveHint: false`, `idempotentHint` where true
|
||||
- [x] the source-set rule: each refactor gets the whole in-scope file set
|
||||
(PLAN §2.1 — the server narrows; MCP does not, so it can never be
|
||||
narrower than the engine needs); the README states the cost on
|
||||
opentitan and M6 measures it
|
||||
- [x] tests: every tool `dry_run` then real on the fixtures; run twice →
|
||||
second run is a no-op with an empty diff; a refusal leaves the
|
||||
fixture tree byte-identical (hash the tree before/after); an
|
||||
`extract_module` into a new file; a rename that touches three files;
|
||||
a `fix_lint` whose finding sits in a format fence (must not touch it)
|
||||
- [x] README `mcp-edit-tools`; Handshake MCP-1 filed there with the exact
|
||||
move; work log; gates; sizes
|
||||
- [x] QA: an edit whose target file changed on disk between the stat
|
||||
sweep and the write (the freshness promise vs the write — the write
|
||||
must be refused, not applied over the newer bytes; the dev states the
|
||||
mechanism); a read-only file; a path through a symlink leaving the
|
||||
root; concurrent `lucisv --check` on the same tree; a CRLF file
|
||||
through `format`; verdict
|
||||
— done 2026-09-23 (Opus, two rounds + lead fixes): pass for the lane;
|
||||
the write path held under a 50 ms writer race, chmod 444, symlinked
|
||||
escapes and a concurrent CLI; `format`/`fix_lint` byte-identical to
|
||||
the CLI. Findings ruled: skipped files refuse a whole-word match;
|
||||
whole-set tools re-walk first. **Open, out of lane:** the engine's
|
||||
rename breaks `.*`/`.name` shorthand connections → M3.5 below.
|
||||
|
||||
## M3.5. Rename vs implicit connections (inserted 2026-09-23 after M3 QA)
|
||||
|
||||
**Files:** `crates/vlog_refactor/src/rename/**`, `crates/vlog_refactor/src/check/**`
|
||||
only if the verifier must learn the shape, `crates/vlog_refactor/tests/`
|
||||
(or the crate's test modules), `docs/features/refactor-rename/README.md`
|
||||
(a dated section), `crates/lucisv_mcp/src/tools/edit.rs` (drop the
|
||||
known-limit sentence) + `tests/qa_m3.rs` (un-ignore finding 1), `TODO.md`
|
||||
(one line under the §8 rope-port refactorings noting the fix). An engine
|
||||
lane: the LSP's rename inherits the fix.
|
||||
|
||||
- [x] `vlog_refactor::rename` rewrites implicit connections: renaming a port
|
||||
`p` → `q` turns `.p` into `.q(p)` and adds `.q(p)` beside a `.*` that
|
||||
bound it (explicit connections beside `.*` are legal); renaming a net
|
||||
`n` → `m` in a module whose instantiations bind it through `.n` or `.*`
|
||||
turns `.n` into `.n(m)` and adds `.n(m)` beside the `.*`; comments and
|
||||
layout of the connection list preserved (append after the last
|
||||
connection, before the closing paren, on its own line when the list is
|
||||
one-per-line); every such rewrite listed in `warnings` so the user
|
||||
sees it; refuse (never guess) when the instantiation's port list
|
||||
cannot be read (`ifdef`-split, error element)
|
||||
- [x] the verifier sees the new edits as intended (no false "moved"
|
||||
refusal); attack tests: `.*` + explicit of the same port; nested
|
||||
instances; a `.name` whose net and port differ; a bind instance
|
||||
- [x] QA: attack the rewrite on opentitan copies (`prim_fifo_sync` ports
|
||||
under `.*` users); LSP parity via `vlog_refactor::rename` directly
|
||||
|
||||
|
||||
## M4. Structural edits (the one new verifier in the block)
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/item.rs`, `tools/mod.rs` (entries),
|
||||
`tests/wire.rs` and `tests/attacks.rs` (new), fixtures, the
|
||||
`mcp-structural-edits` README. Depends on M3 merged.
|
||||
|
||||
- [ ] `replace_item`, `insert_item`, `delete_item` with the PLAN §4.3
|
||||
contracts: bytes outside the span untouched (asserted by the test,
|
||||
not trusted), strict re-parse of the whole file (or no growth in
|
||||
tolerant error count when it did not parse before), one item at the
|
||||
position, the declared name matches unless `rename: true`,
|
||||
`delete_item` refuses over surviving references unless `force`
|
||||
- [ ] `tests/attacks.rs`, written by the dev, every case asserted
|
||||
**refused with the tree byte-identical**: a `text` opening a block it
|
||||
does not close; one that closes the enclosing module; one that
|
||||
re-declares a port; a UTF-8 boundary inside the span; an item inside
|
||||
a format fence; a file with an unterminated string; an `insert_item`
|
||||
after `end` — the CLAUDE.md invariant-4 discipline applied to the
|
||||
block's own verifier
|
||||
- [ ] README `mcp-structural-edits`: the contract as a table, the attack
|
||||
list, what the tool deliberately does not check (semantic sense of
|
||||
the new text)
|
||||
- [ ] gates; sizes (`item.rs` is expected to be the largest file in the
|
||||
crate; if it passes 600 lines the verifier moves to `item/verify.rs`)
|
||||
- [ ] QA: re-attack with at least eight new cases (a `text` that is two
|
||||
items; an empty `text`; a `text` equal to the old bytes — must be a
|
||||
no-op, not a refusal; a macro-bracketed item; a `generate` block
|
||||
target; an item whose leading comment is shared with the previous
|
||||
item's trailing one; a 40 000-line file for timing; `delete_item` on
|
||||
the last item of a module); verdict
|
||||
|
||||
## M5. Packaging and the extension (parallel with M2–M4)
|
||||
|
||||
**Files:** `tools/release.sh`, `tools/audit_artifacts.sh`,
|
||||
`tools/RELEASING.md`, `.gitea/workflows/ci.yml` (two lines: the MCP wire
|
||||
test is already in `cargo test`; add `node --test editors/vscode/*_test.js`),
|
||||
`editors/vscode/{package.json,package-lock.json,extension.js,mcp.js,
|
||||
mcp_test.js,mcp_smoke.js,.vscodeignore,README.md,CHANGELOG.md}`,
|
||||
`docs/site/src/content/docs/guides/agents.md` (new) and the guides index,
|
||||
`README.md` (an "Agents (MCP)" paragraph under Editor setup), the
|
||||
`mcp-packaging` README. May start once M1's binary answers `initialize` on
|
||||
trunk; touches no Rust. `extension.js` changes are limited to requiring
|
||||
`mcp.js` and calling its `activate(context)`.
|
||||
|
||||
- [ ] `release.sh`: stage `lucisv-mcp[.exe]` into `bin/` (platform) and
|
||||
`bin/<target>/` (all); `expect_vsix_bins` lists grow to three;
|
||||
`mcp_smoke.js` run against the host binary and against the one
|
||||
unzipped from the host vsix and the all-platforms vsix (mirror
|
||||
`smoke_embedded_server`); `audit_artifacts.sh` accepts the third name;
|
||||
the universal vsix still asserts no `extension/bin/*`
|
||||
- [ ] `mcp.js`: the three-rung binary ladder reusing `bundledBinary`;
|
||||
the guarded `registerMcpServerDefinitionProvider("lucisv.mcp", …)`
|
||||
with one `McpStdioServerDefinition` per workspace folder (`--root`,
|
||||
`--index-cache <storagePath>`, `cwd`, `version` from `package.json`),
|
||||
re-fired on folder changes; `lucisv.mcp.enabled` / `lucisv.mcp.path`
|
||||
read like `serverPath` (`inspect()`, blank = unset); the
|
||||
`lucisv.mcp.copyConfig` command with the three dialects (Claude Code
|
||||
`.mcp.json`, Cursor, VS Code `.vscode/mcp.json`) naming the resolved
|
||||
binary; `mcp_test.js` with a stubbed `vscode` (the `hierarchyView_test`
|
||||
pattern) covering the ladder, the guard on an old VS Code (no `lm`),
|
||||
and the three snippets
|
||||
- [ ] `package.json`: `contributes.mcpServerDefinitionProviders`, the two
|
||||
settings, the command + palette entry; engine stays `^1.82.0` unless
|
||||
`vsce package` refuses — then bump to `^1.101.0` and record why in the
|
||||
README and CHANGELOG
|
||||
- [ ] docs: the site guide page (install via vsix → nothing to do; Claude
|
||||
Code / Cursor snippets; the standalone `cargo build` line; the tool
|
||||
list generated from `tools/list` output, checked in); `README.md`
|
||||
paragraph; `tools/RELEASING.md` (three binaries; the smoke); the
|
||||
extension README and CHANGELOG
|
||||
- [ ] CI: `node --test editors/vscode/*_test.js` in `ci.yml`
|
||||
- [ ] README `mcp-packaging`; work log; `node --test` green; a local
|
||||
`tools/release.sh` (host only) producing a darwin-arm64 vsix with the
|
||||
three binaries, unzipped and checked
|
||||
- [ ] QA: install the vsix into a clean VS Code profile: the server listed
|
||||
under **MCP: List Servers**, trusted, `project_overview` answered in
|
||||
agent mode; `lucisv.mcp.enabled: false` removes it; a multi-root
|
||||
workspace registers one server per folder; the universal vsix on a
|
||||
machine without `lucisv-mcp` on PATH degrades to a clear output-channel
|
||||
line, not an error dialog; the Claude Code snippet pasted into a
|
||||
`.mcp.json` works from a terminal; rows in `docs/manual-acceptance.md`;
|
||||
verdict
|
||||
|
||||
## M6. Cache reuse, census, closing release
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/{project.rs,cache.rs}` (new `cache.rs`),
|
||||
`tests/` additions, `docs/mcp/census.md` (new), `docs/perf/README.md` (an
|
||||
MCP section), `docs/topo.md` (§1.1 node + §2.8 rows for `lucisv_mcp`, an
|
||||
§1.4 touch-set row), `docs/manual-acceptance.md`, `CHANGELOG.md`,
|
||||
`docs/repository-analysis.md` (the crate count and map row), the
|
||||
`mcp-cache-and-census` README, `TODO-MCP.md` (this file's closing entries).
|
||||
Depends on M4 and M5 merged.
|
||||
|
||||
- [ ] `cache.rs`: the read-only reader of the LSP's `index-cache` (header
|
||||
check on `CACHE_FORMAT`/`FACTS_FORMAT`/version, per-line checksum,
|
||||
`FileFacts::decode`, `record_path`); on `--index-cache DIR` a file
|
||||
whose `content_hash` has a record is `add_facts`'d instead of parsed;
|
||||
MCP's own `index-cache-mcp` written with the same codec on exit and
|
||||
read on start; never a write to the LSP's file (a test opens the
|
||||
store read-only and asserts its bytes after a full MCP session)
|
||||
- [ ] startup timing on opentitan cold / warm-from-LSP-store /
|
||||
warm-from-own-store, and the per-call stat sweep, recorded in
|
||||
`docs/perf/README.md` next to the LSP's scan trace numbers; the
|
||||
whole-set refactor cost from M3 measured on `rename` in `aes`
|
||||
- [ ] the token census (PLAN §8): the three tasks, each run twice (file
|
||||
tools only / with lucisv-mcp) by the same agent model, tokens in and
|
||||
out from the transcripts, written up in `docs/mcp/census.md` with the
|
||||
transcripts' task ids; if a task saved nothing, say so — the number
|
||||
is the deliverable, not its sign
|
||||
- [ ] `instructions` and tool descriptions revised from what the census
|
||||
transcripts show the agent misunderstood; `prompts/*` added only if
|
||||
the census shows a repeated multi-tool sequence worth one prompt
|
||||
- [ ] `docs/topo.md`: the `lucisv_mcp` node (`──▶` the six libraries; `-.spawn
|
||||
contract.->` from `editors/vscode`; `-.builds/packages.->` from
|
||||
`tools/`), the §2.8 rows, the Handshake MCP-1 status (delivered or
|
||||
still open), and MCP-3 filed in §2.9 if M2's hierarchy walk and the
|
||||
server's snapshot drifted
|
||||
- [ ] `CHANGELOG.md` section, `README.md` architecture table row (nine
|
||||
crates), `docs/repository-analysis.md` map row, CLAUDE.md measurement
|
||||
line refreshed with the new crate's sizes
|
||||
- [ ] release **0.56.0** (or the next minor free at the time): tag, CI
|
||||
green, 8 assets, the darwin-arm64 vsix unzipped and checked for three
|
||||
binaries, the MCP smoke in the release log; the install line and the
|
||||
`claude mcp add` line given to the owner
|
||||
- [ ] QA: the read-only promise on the LSP store attacked (a store with a
|
||||
torn last line; one from a different version; one whose record hash
|
||||
matches but whose facts checksum does not — each must be skipped, not
|
||||
trusted, and the file left byte-identical); a cold start with no
|
||||
store directory permission (must still answer, warn on stderr);
|
||||
the census transcripts spot-checked for a tool answer the agent had
|
||||
to correct by reading the file anyway (each is a finding against a
|
||||
tool's rendering); verdict
|
||||
|
||||
## Open questions for the owner (answer before the lane that needs it)
|
||||
|
||||
1. **Engine bump** (M5): if `vsce` accepts the contribution point on
|
||||
`^1.82.0`, keep it; if not, bump to `^1.101.0` and drop VS Code < 1.101
|
||||
users. The lane records which happened; no ruling needed unless the
|
||||
bump is unwelcome.
|
||||
2. **Whole-set refactors** (M3): MCP hands every refactor the full in-scope
|
||||
set. On opentitan that is a parse of ~3 000 files per `rename` unless
|
||||
`KnownFacts` from the cache is threaded through (M6 can). Acceptable for
|
||||
the first release, or should M3 already narrow with
|
||||
`files_mentioning` the way the server does?
|
||||
3. **Structural edits and the formatter** (M4): after `replace_item`, the
|
||||
agent's text is left as written. The alternative — format the replaced
|
||||
item's lines through `format_range` automatically — costs a refusal
|
||||
path when the safety net objects. Default in this plan: not automatic;
|
||||
the agent calls `format` with `lines`.
|
||||
@@ -671,6 +671,11 @@ section only tracks the milestones.
|
||||
- [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP
|
||||
`prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves,
|
||||
cross-file, whole-edit-or-nothing verified by re-parse.
|
||||
**2026-09-23 (TODO-MCP M3.5):** a rename no longer cuts a `.name` or `.*`
|
||||
connection — the binding is written out explicitly (`.q(p)`, `.n(m)`) and
|
||||
warned about, the unreadable cases are refused, and the verifier prints
|
||||
every implicit binding before and after (`docs/features/refactor-rename/README.md`,
|
||||
"Implicit connections").
|
||||
- [x] **M3 `refactor-ports`** — add/remove/propagate module ports across
|
||||
the declaration and every instantiation (named/ordered/`.*`).
|
||||
**Amended 2026-08-28** (`docs/features/refactor-ports/README.md`): a
|
||||
@@ -6930,6 +6935,7 @@ Nothing else.
|
||||
surface) — done 2026-09-12 (the perf entry records the +25 % on a
|
||||
local-net `references` and the closed-file parse; the
|
||||
`references-nav ──▶ workspace-index` row amended)
|
||||
- [ ] release 0.55.0 with assets verified — owner's call; not run from the
|
||||
`task_d8afe80f` session (a release chain never runs while a lane is
|
||||
in flight, and the lane merges first)
|
||||
- [x] release 0.55.0 with assets verified — done 2026-09-17: **0.55.0**
|
||||
(23e2e4b, v0.55.0), CI green on the release commit, 8 assets, the
|
||||
darwin-arm64 vsix at 0.55.0 with both binaries,
|
||||
`hierarchySections.js`, `extract.js`, no `*_test.js`.
|
||||
+4
-217
@@ -1,218 +1,5 @@
|
||||
//! A small line-oriented unified diff for `--diff`.
|
||||
//!
|
||||
//! The hunks are not a minimal edit script: on a divergence the two
|
||||
//! sides are resynchronized with a bounded forward search. That keeps
|
||||
//! the code short and the memory linear, at the cost of occasionally
|
||||
//! reporting a coarser change than GNU `diff` would.
|
||||
//! `--diff`'s unified diff. The printer lives in `lucisv_core::diff`, shared
|
||||
//! with the MCP server's `dry_run` (Handshake MCP-1, a pure move); this module
|
||||
//! keeps the CLI's `diff::unified` path.
|
||||
|
||||
/// Unchanged lines printed around each hunk.
|
||||
const CONTEXT: usize = 3;
|
||||
/// Unchanged lines that must line up before the sides count as resynced.
|
||||
const SYNC_RUN: usize = 3;
|
||||
/// How far ahead a resynchronization point is searched for.
|
||||
const MAX_SCAN: usize = 200;
|
||||
/// Pseudo-line standing in for a missing final newline.
|
||||
const NO_NEWLINE: &str = "\\ No newline at end of file";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Tag {
|
||||
Keep,
|
||||
Del,
|
||||
Ins,
|
||||
}
|
||||
|
||||
/// Renders the changes from `old` to `new` as a unified-style diff.
|
||||
/// Returns an empty string if the two texts are equal.
|
||||
pub fn unified(path: &str, old: &str, new: &str) -> String {
|
||||
if old == new {
|
||||
return String::new();
|
||||
}
|
||||
let old = split_lines(old);
|
||||
let new = split_lines(new);
|
||||
let edits = edits(&old, &new);
|
||||
let mut out = format!("--- {path}\n+++ {path}\n");
|
||||
render_hunks(&edits, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Splits into lines *keeping* each terminator, so a final line with no
|
||||
/// newline compares unequal to its terminated twin and shows up as a
|
||||
/// change, exactly as GNU diff treats it.
|
||||
fn split_lines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut rest = text;
|
||||
while !rest.is_empty() {
|
||||
let end = rest.find('\n').map_or(rest.len(), |p| p + 1);
|
||||
lines.push(&rest[..end]);
|
||||
rest = &rest[end..];
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn edits<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(Tag, &'a str)> {
|
||||
let mut out = Vec::new();
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < old.len() && j < new.len() {
|
||||
if old[i] == new[j] {
|
||||
out.push((Tag::Keep, old[i]));
|
||||
i += 1;
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((di, dj)) = resync(old, new, i, j) else { break };
|
||||
out.extend(old[i..i + di].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..j + dj].iter().map(|l| (Tag::Ins, *l)));
|
||||
i += di;
|
||||
j += dj;
|
||||
}
|
||||
out.extend(old[i..].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..].iter().map(|l| (Tag::Ins, *l)));
|
||||
out
|
||||
}
|
||||
|
||||
/// Finds the smallest pair of skip counts that puts the two sides back
|
||||
/// in step, preferring the shortest total divergence.
|
||||
fn resync(old: &[&str], new: &[&str], i: usize, j: usize) -> Option<(usize, usize)> {
|
||||
for d in 1..=MAX_SCAN {
|
||||
for k in 0..=d {
|
||||
for (di, dj) in [(d, k), (k, d)] {
|
||||
if i + di <= old.len() && j + dj <= new.len() && in_step(old, new, i + di, j + dj) {
|
||||
return Some((di, dj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn in_step(old: &[&str], new: &[&str], i: usize, j: usize) -> bool {
|
||||
let available = (old.len() - i).min(new.len() - j);
|
||||
if available == 0 {
|
||||
// Both sides running out together is a valid resync point.
|
||||
return old.len() - i == new.len() - j;
|
||||
}
|
||||
(0..SYNC_RUN.min(available)).all(|k| old[i + k] == new[j + k])
|
||||
}
|
||||
|
||||
fn render_hunks(edits: &[(Tag, &str)], out: &mut String) {
|
||||
// Line numbers each edit occupies on the old and the new side.
|
||||
let mut rows = Vec::with_capacity(edits.len());
|
||||
let (mut old_no, mut new_no) = (1usize, 1usize);
|
||||
for &(tag, text) in edits {
|
||||
rows.push((tag, text, old_no, new_no));
|
||||
match tag {
|
||||
Tag::Keep => {
|
||||
old_no += 1;
|
||||
new_no += 1;
|
||||
}
|
||||
Tag::Del => old_no += 1,
|
||||
Tag::Ins => new_no += 1,
|
||||
}
|
||||
}
|
||||
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let Some(first) = (start..rows.len()).find(|&r| rows[r].0 != Tag::Keep) else { break };
|
||||
let mut last = first;
|
||||
// Extend while the next change is close enough that its context
|
||||
// would touch this hunk's.
|
||||
loop {
|
||||
let reach = (last + 2 * CONTEXT + 1).min(rows.len());
|
||||
match (last + 1..reach).find(|&r| rows[r].0 != Tag::Keep) {
|
||||
Some(next) => last = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
let from = first.saturating_sub(CONTEXT);
|
||||
let to = (last + CONTEXT + 1).min(rows.len());
|
||||
render_one_hunk(&rows[from..to], out);
|
||||
start = to;
|
||||
}
|
||||
}
|
||||
|
||||
fn render_one_hunk(rows: &[(Tag, &str, usize, usize)], out: &mut String) {
|
||||
let old_count = rows.iter().filter(|r| r.0 != Tag::Ins).count();
|
||||
let new_count = rows.iter().filter(|r| r.0 != Tag::Del).count();
|
||||
let (old_start, new_start) = (rows[0].2, rows[0].3);
|
||||
out.push_str(&format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n"));
|
||||
for &(tag, text, _, _) in rows {
|
||||
let sign = match tag {
|
||||
Tag::Keep => ' ',
|
||||
Tag::Del => '-',
|
||||
Tag::Ins => '+',
|
||||
};
|
||||
out.push(sign);
|
||||
match text.strip_suffix('\n') {
|
||||
Some(body) => {
|
||||
out.push_str(body);
|
||||
out.push('\n');
|
||||
}
|
||||
None => {
|
||||
// patch(1) expects the marker bare, on its own line,
|
||||
// directly after the unterminated line.
|
||||
out.push_str(text);
|
||||
out.push('\n');
|
||||
out.push_str(NO_NEWLINE);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn equal_texts_produce_nothing() {
|
||||
assert_eq!(unified("f.sv", "a\nb\n", "a\nb\n"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_line_change_keeps_context() {
|
||||
let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n";
|
||||
let new = "1\n2\n3\n4\nX\n6\n7\n8\n9\n";
|
||||
let d = unified("f.sv", old, new);
|
||||
assert!(d.starts_with("--- f.sv\n+++ f.sv\n@@ -2,7 +2,7 @@\n"), "{d}");
|
||||
assert!(d.contains("\n-5\n+X\n"), "{d}");
|
||||
// Context is bounded: the first and last lines stay out of it.
|
||||
assert!(!d.contains("\n 1\n"), "{d}");
|
||||
assert!(!d.contains("\n 9\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distant_changes_become_separate_hunks() {
|
||||
let old: String = (0..40).map(|i| format!("{i}\n")).collect();
|
||||
let new = old.replace("\n1\n", "\nX\n").replace("\n30\n", "\nY\n");
|
||||
let d = unified("f.sv", &old, &new);
|
||||
assert_eq!(d.matches("@@ ").count(), 2, "{d}");
|
||||
assert!(d.contains("-1\n+X\n") && d.contains("-30\n+Y\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insertions_and_deletions_are_reported_separately() {
|
||||
let d = unified("f.sv", "a\nb\nc\n", "a\nb\nb2\nc\n");
|
||||
assert!(d.contains("+b2\n"), "{d}");
|
||||
assert!(!d.contains("-b\n"), "{d}");
|
||||
|
||||
let d = unified("f.sv", "a\nb\nc\nd\n", "a\nc\nd\n");
|
||||
assert!(d.contains("-b\n"), "{d}");
|
||||
// No insertions in the hunk body (the `+++` header line aside).
|
||||
assert!(!d.lines().skip(2).any(|l| l.starts_with('+')), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_final_newline_matches_patch_format() {
|
||||
// The unterminated line is the change; the marker follows it bare.
|
||||
let d = unified("f.sv", "a\nb", "a\nb\n");
|
||||
assert!(d.contains("-b\n\\ No newline at end of file\n+b\n"), "{d}");
|
||||
let d = unified("f.sv", "a\nb\n", "a\nb");
|
||||
assert!(d.contains("-b\n+b\n\\ No newline at end of file\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wholly_different_texts_diff_as_replacement() {
|
||||
let d = unified("f.sv", "a\nb\n", "x\ny\n");
|
||||
assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}");
|
||||
}
|
||||
}
|
||||
pub use lucisv_core::diff::unified;
|
||||
@@ -0,0 +1,221 @@
|
||||
//! A small line-oriented unified diff: the CLI's `--diff` and the MCP
|
||||
//! server's `dry_run` print the same hunks through this one function.
|
||||
//! Moved here from `crates/lucisv/src/diff.rs` unchanged (Handshake MCP-1,
|
||||
//! `docs/features/mcp-edit-tools/README.md`); the CLI re-exports it.
|
||||
//!
|
||||
//! The hunks are not a minimal edit script: on a divergence the two
|
||||
//! sides are resynchronized with a bounded forward search. That keeps
|
||||
//! the code short and the memory linear, at the cost of occasionally
|
||||
//! reporting a coarser change than GNU `diff` would.
|
||||
|
||||
/// Unchanged lines printed around each hunk.
|
||||
const CONTEXT: usize = 3;
|
||||
/// Unchanged lines that must line up before the sides count as resynced.
|
||||
const SYNC_RUN: usize = 3;
|
||||
/// How far ahead a resynchronization point is searched for.
|
||||
const MAX_SCAN: usize = 200;
|
||||
/// Pseudo-line standing in for a missing final newline.
|
||||
const NO_NEWLINE: &str = "\\ No newline at end of file";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Tag {
|
||||
Keep,
|
||||
Del,
|
||||
Ins,
|
||||
}
|
||||
|
||||
/// Renders the changes from `old` to `new` as a unified-style diff.
|
||||
/// Returns an empty string if the two texts are equal.
|
||||
pub fn unified(path: &str, old: &str, new: &str) -> String {
|
||||
if old == new {
|
||||
return String::new();
|
||||
}
|
||||
let old = split_lines(old);
|
||||
let new = split_lines(new);
|
||||
let edits = edits(&old, &new);
|
||||
let mut out = format!("--- {path}\n+++ {path}\n");
|
||||
render_hunks(&edits, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Splits into lines *keeping* each terminator, so a final line with no
|
||||
/// newline compares unequal to its terminated twin and shows up as a
|
||||
/// change, exactly as GNU diff treats it.
|
||||
fn split_lines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut rest = text;
|
||||
while !rest.is_empty() {
|
||||
let end = rest.find('\n').map_or(rest.len(), |p| p + 1);
|
||||
lines.push(&rest[..end]);
|
||||
rest = &rest[end..];
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn edits<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(Tag, &'a str)> {
|
||||
let mut out = Vec::new();
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < old.len() && j < new.len() {
|
||||
if old[i] == new[j] {
|
||||
out.push((Tag::Keep, old[i]));
|
||||
i += 1;
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((di, dj)) = resync(old, new, i, j) else { break };
|
||||
out.extend(old[i..i + di].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..j + dj].iter().map(|l| (Tag::Ins, *l)));
|
||||
i += di;
|
||||
j += dj;
|
||||
}
|
||||
out.extend(old[i..].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..].iter().map(|l| (Tag::Ins, *l)));
|
||||
out
|
||||
}
|
||||
|
||||
/// Finds the smallest pair of skip counts that puts the two sides back
|
||||
/// in step, preferring the shortest total divergence.
|
||||
fn resync(old: &[&str], new: &[&str], i: usize, j: usize) -> Option<(usize, usize)> {
|
||||
for d in 1..=MAX_SCAN {
|
||||
for k in 0..=d {
|
||||
for (di, dj) in [(d, k), (k, d)] {
|
||||
if i + di <= old.len() && j + dj <= new.len() && in_step(old, new, i + di, j + dj) {
|
||||
return Some((di, dj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn in_step(old: &[&str], new: &[&str], i: usize, j: usize) -> bool {
|
||||
let available = (old.len() - i).min(new.len() - j);
|
||||
if available == 0 {
|
||||
// Both sides running out together is a valid resync point.
|
||||
return old.len() - i == new.len() - j;
|
||||
}
|
||||
(0..SYNC_RUN.min(available)).all(|k| old[i + k] == new[j + k])
|
||||
}
|
||||
|
||||
fn render_hunks(edits: &[(Tag, &str)], out: &mut String) {
|
||||
// Line numbers each edit occupies on the old and the new side.
|
||||
let mut rows = Vec::with_capacity(edits.len());
|
||||
let (mut old_no, mut new_no) = (1usize, 1usize);
|
||||
for &(tag, text) in edits {
|
||||
rows.push((tag, text, old_no, new_no));
|
||||
match tag {
|
||||
Tag::Keep => {
|
||||
old_no += 1;
|
||||
new_no += 1;
|
||||
}
|
||||
Tag::Del => old_no += 1,
|
||||
Tag::Ins => new_no += 1,
|
||||
}
|
||||
}
|
||||
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let Some(first) = (start..rows.len()).find(|&r| rows[r].0 != Tag::Keep) else { break };
|
||||
let mut last = first;
|
||||
// Extend while the next change is close enough that its context
|
||||
// would touch this hunk's.
|
||||
loop {
|
||||
let reach = (last + 2 * CONTEXT + 1).min(rows.len());
|
||||
match (last + 1..reach).find(|&r| rows[r].0 != Tag::Keep) {
|
||||
Some(next) => last = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
let from = first.saturating_sub(CONTEXT);
|
||||
let to = (last + CONTEXT + 1).min(rows.len());
|
||||
render_one_hunk(&rows[from..to], out);
|
||||
start = to;
|
||||
}
|
||||
}
|
||||
|
||||
fn render_one_hunk(rows: &[(Tag, &str, usize, usize)], out: &mut String) {
|
||||
let old_count = rows.iter().filter(|r| r.0 != Tag::Ins).count();
|
||||
let new_count = rows.iter().filter(|r| r.0 != Tag::Del).count();
|
||||
let (old_start, new_start) = (rows[0].2, rows[0].3);
|
||||
out.push_str(&format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n"));
|
||||
for &(tag, text, _, _) in rows {
|
||||
let sign = match tag {
|
||||
Tag::Keep => ' ',
|
||||
Tag::Del => '-',
|
||||
Tag::Ins => '+',
|
||||
};
|
||||
out.push(sign);
|
||||
match text.strip_suffix('\n') {
|
||||
Some(body) => {
|
||||
out.push_str(body);
|
||||
out.push('\n');
|
||||
}
|
||||
None => {
|
||||
// patch(1) expects the marker bare, on its own line,
|
||||
// directly after the unterminated line.
|
||||
out.push_str(text);
|
||||
out.push('\n');
|
||||
out.push_str(NO_NEWLINE);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn equal_texts_produce_nothing() {
|
||||
assert_eq!(unified("f.sv", "a\nb\n", "a\nb\n"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_line_change_keeps_context() {
|
||||
let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n";
|
||||
let new = "1\n2\n3\n4\nX\n6\n7\n8\n9\n";
|
||||
let d = unified("f.sv", old, new);
|
||||
assert!(d.starts_with("--- f.sv\n+++ f.sv\n@@ -2,7 +2,7 @@\n"), "{d}");
|
||||
assert!(d.contains("\n-5\n+X\n"), "{d}");
|
||||
// Context is bounded: the first and last lines stay out of it.
|
||||
assert!(!d.contains("\n 1\n"), "{d}");
|
||||
assert!(!d.contains("\n 9\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distant_changes_become_separate_hunks() {
|
||||
let old: String = (0..40).map(|i| format!("{i}\n")).collect();
|
||||
let new = old.replace("\n1\n", "\nX\n").replace("\n30\n", "\nY\n");
|
||||
let d = unified("f.sv", &old, &new);
|
||||
assert_eq!(d.matches("@@ ").count(), 2, "{d}");
|
||||
assert!(d.contains("-1\n+X\n") && d.contains("-30\n+Y\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insertions_and_deletions_are_reported_separately() {
|
||||
let d = unified("f.sv", "a\nb\nc\n", "a\nb\nb2\nc\n");
|
||||
assert!(d.contains("+b2\n"), "{d}");
|
||||
assert!(!d.contains("-b\n"), "{d}");
|
||||
|
||||
let d = unified("f.sv", "a\nb\nc\nd\n", "a\nc\nd\n");
|
||||
assert!(d.contains("-b\n"), "{d}");
|
||||
// No insertions in the hunk body (the `+++` header line aside).
|
||||
assert!(!d.lines().skip(2).any(|l| l.starts_with('+')), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_final_newline_matches_patch_format() {
|
||||
// The unterminated line is the change; the marker follows it bare.
|
||||
let d = unified("f.sv", "a\nb", "a\nb\n");
|
||||
assert!(d.contains("-b\n\\ No newline at end of file\n+b\n"), "{d}");
|
||||
let d = unified("f.sv", "a\nb\n", "a\nb");
|
||||
assert!(d.contains("-b\n+b\n\\ No newline at end of file\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wholly_different_texts_diff_as_replacement() {
|
||||
let d = unified("f.sv", "a\nb\n", "x\ny\n");
|
||||
assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}");
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@
|
||||
//! needs to be processed at all, and `filelist` answers the first one the way
|
||||
//! an EDA project already does, from a `.f` file. `atomic` is the one write
|
||||
//! path all of them share: nothing here ever truncates a file it is
|
||||
//! replacing. See
|
||||
//! replacing. `diff` is the unified diff the CLI's `--diff` and the MCP
|
||||
//! server's `dry_run` both print. See
|
||||
//! `docs/features/lucisv-core-lift/README.md`, and
|
||||
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
|
||||
//! for the rules themselves.
|
||||
@@ -16,5 +17,6 @@
|
||||
pub mod atomic;
|
||||
pub mod cache;
|
||||
pub mod config;
|
||||
pub mod diff;
|
||||
pub mod filelist;
|
||||
pub mod walk;
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "lucisv_mcp"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "lucisv as a Model Context Protocol server: project understanding for coding agents over stdio"
|
||||
|
||||
[[bin]]
|
||||
name = "lucisv-mcp"
|
||||
path = "src/main.rs"
|
||||
|
||||
# No new dependencies: the MCP stdio transport is newline-delimited JSON-RPC,
|
||||
# which serde_json (already pinned by the workspace) handles. Why not `rmcp`:
|
||||
# docs/features/mcp-transport/README.md, Assumptions.
|
||||
[dependencies]
|
||||
lucisv_core = { path = "../lucisv_core" }
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_semantic = { path = "../vlog_semantic" }
|
||||
vlog_refactor = { path = "../vlog_refactor" }
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
vlog_linter = { path = "../vlog_linter" }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,415 @@
|
||||
//! The one write path every edit tool goes through.
|
||||
//!
|
||||
//! A tool hands over a [`Plan`] — per file, the text it computed against and
|
||||
//! the text it wants written — and gets back either the unified diff
|
||||
//! (`dry_run`) or a summary of what was written. The write is all-or-nothing
|
||||
//! as far as a filesystem allows: every file's new text exists before the
|
||||
//! first write; every target is checked to lie inside a root; every file is
|
||||
//! re-read and compared with the text the plan was computed against, and a
|
||||
//! file that moved since refuses the **whole** edit before anything is
|
||||
//! written (the write-freshness rule); then each file goes through
|
||||
//! `write_atomic`, in path order. A write that fails after others landed is
|
||||
//! reported as such — "written N of M" — which is the CLI's posture.
|
||||
//! See `docs/features/mcp-edit-tools/README.md`.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::diff::unified;
|
||||
use serde_json::{json, Value};
|
||||
use vlog_refactor::{RefactorEdit, TextEdit};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::tools::Answer;
|
||||
|
||||
/// One file an edit rewrites or creates.
|
||||
pub struct Change {
|
||||
/// The canonical path of the file.
|
||||
pub path: PathBuf,
|
||||
/// The text the edit was computed against; empty for a created file.
|
||||
pub before: String,
|
||||
/// The text to write.
|
||||
pub after: String,
|
||||
/// Whether the file does not exist yet and the edit creates it.
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
/// Everything one edit tool wants written, and what it has to say.
|
||||
#[derive(Default)]
|
||||
pub struct Plan {
|
||||
/// The files to write, in any order.
|
||||
pub changes: Vec<Change>,
|
||||
/// Files the tool looked at and left as they were (`format`, `fix_lint`).
|
||||
pub unchanged: Vec<PathBuf>,
|
||||
/// The engine's sentences about what it deliberately left alone.
|
||||
pub warnings: Vec<String>,
|
||||
/// One line the tool adds to the summary (`fix_lint`'s rules), if any.
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
/// A refactoring's edit, over the texts it was computed against. A file
|
||||
/// the edit names but `texts` does not hold, and an edit that does not
|
||||
/// fit its file, refuse the whole plan.
|
||||
pub fn from_refactor(edit: RefactorEdit, texts: &[(PathBuf, String)]) -> Result<Plan, String> {
|
||||
let mut plan = Plan { warnings: edit.warnings, ..Plan::default() };
|
||||
for (path, edits) in edit.edits {
|
||||
let created = edit.created.contains(&path);
|
||||
let before = match texts.iter().find(|(held, _)| *held == path) {
|
||||
Some((_, text)) => text.clone(),
|
||||
None if created => String::new(),
|
||||
None => {
|
||||
return Err(format!("the edit names `{}`, which was not read", path.display()))
|
||||
}
|
||||
};
|
||||
let after = apply_edits(&before, &edits)
|
||||
.map_err(|why| format!("the edit does not fit `{}`: {why}", path.display()))?;
|
||||
plan.changes.push(Change { path, before, after, created });
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` with `edits` applied, last first so every offset still points at
|
||||
/// the bytes it was computed for. Overlapping edits, an edit past the end
|
||||
/// and one splitting a UTF-8 character are refused, never guessed at.
|
||||
fn apply_edits(text: &str, edits: &[TextEdit]) -> Result<String, String> {
|
||||
let mut sorted: Vec<&TextEdit> = edits.iter().collect();
|
||||
sorted.sort_by_key(|edit| (edit.range.start, edit.range.end));
|
||||
for pair in sorted.windows(2) {
|
||||
if pair[1].range.start < pair[0].range.end {
|
||||
return Err(format!("two edits overlap at byte {}", pair[1].range.start));
|
||||
}
|
||||
}
|
||||
let mut out = text.to_string();
|
||||
for edit in sorted.iter().rev() {
|
||||
let (start, end) = (edit.range.start as usize, edit.range.end as usize);
|
||||
if start > end || end > out.len() {
|
||||
return Err(format!("an edit ends at byte {end}, past the end ({})", out.len()));
|
||||
}
|
||||
if !out.is_char_boundary(start) || !out.is_char_boundary(end) {
|
||||
return Err(format!("an edit at byte {start} splits a character"));
|
||||
}
|
||||
out.replace_range(start..end, &edit.new_text);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Check, then diff or write, then summarise. `dry_run` writes nothing.
|
||||
pub fn run(project: &Project, plan: Plan, dry_run: bool) -> Result<Answer, String> {
|
||||
for change in &plan.changes {
|
||||
contained(project, change)?;
|
||||
}
|
||||
let mut moved: Vec<&Change> =
|
||||
plan.changes.iter().filter(|c| c.created || c.before != c.after).collect();
|
||||
moved.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
let mut unchanged: Vec<String> = plan
|
||||
.changes
|
||||
.iter()
|
||||
.filter(|c| !c.created && c.before == c.after)
|
||||
.map(|c| project.relative(&c.path))
|
||||
.chain(plan.unchanged.iter().map(|path| project.relative(path)))
|
||||
.collect();
|
||||
unchanged.sort();
|
||||
let files: Vec<Written> = moved.iter().map(|change| Written::of(project, change)).collect();
|
||||
if !dry_run {
|
||||
commit(&moved, |path| project.relative(path))?;
|
||||
}
|
||||
Ok(summary(&files, &unchanged, &plan, dry_run))
|
||||
}
|
||||
|
||||
/// A target must lie inside a root: an existing file resolves into one; a
|
||||
/// created file's directory does, and nothing is at its path yet.
|
||||
fn contained(project: &Project, change: &Change) -> Result<(), String> {
|
||||
let shown = change.path.display();
|
||||
let inside = |dir: Option<PathBuf>| {
|
||||
dir.is_some_and(|dir| project.roots().iter().any(|root| dir.starts_with(root)))
|
||||
};
|
||||
if !change.created {
|
||||
let Ok(real) = fs::canonicalize(&change.path) else {
|
||||
return Err(format!("`{shown}` no longer exists; nothing written."));
|
||||
};
|
||||
if !inside(Some(real)) {
|
||||
return Err(format!(
|
||||
"`{shown}` is outside every root; lucisv-mcp only writes inside its roots."
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if !inside(change.path.parent().and_then(|dir| fs::canonicalize(dir).ok())) {
|
||||
return Err(format!(
|
||||
"`{shown}` would be created outside every root; lucisv-mcp only writes inside its roots."
|
||||
));
|
||||
}
|
||||
if fs::symlink_metadata(&change.path).is_ok() {
|
||||
return Err(format!(
|
||||
"`{}` already exists; nothing written.",
|
||||
project.relative(&change.path)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write every change, or none when any target moved since it was read.
|
||||
///
|
||||
/// First every file is re-read and compared byte for byte with the text the
|
||||
/// plan was computed against (a created file must still not exist, a
|
||||
/// read-only one is refused as `write_atomic` would refuse it); one mismatch
|
||||
/// refuses the whole edit before the first write. Then each file is
|
||||
/// written with `write_atomic`, in the order given. A failure part-way is
|
||||
/// reported with what was already written.
|
||||
pub fn commit(changes: &[&Change], shown: impl Fn(&Path) -> String) -> Result<(), String> {
|
||||
for change in changes {
|
||||
let name = shown(&change.path);
|
||||
if change.created {
|
||||
if fs::symlink_metadata(&change.path).is_ok() {
|
||||
return Err(format!("`{name}` already exists; nothing written."));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if fs::metadata(&change.path).is_ok_and(|meta| meta.permissions().readonly()) {
|
||||
return Err(format!("`{name}` is read-only; nothing written."));
|
||||
}
|
||||
match fs::read(&change.path) {
|
||||
Ok(bytes) if bytes == change.before.as_bytes() => {}
|
||||
Ok(_) => {
|
||||
return Err(format!("`{name}` changed on disk since it was read; nothing written."))
|
||||
}
|
||||
Err(e) => return Err(format!("`{name}` cannot be read again ({e}); nothing written.")),
|
||||
}
|
||||
}
|
||||
let mut done: Vec<String> = Vec::new();
|
||||
for change in changes {
|
||||
let name = shown(&change.path);
|
||||
if let Err(e) = write_atomic(&change.path, change.after.as_bytes()) {
|
||||
let list = if done.is_empty() { "nothing".to_string() } else { done.join(", ") };
|
||||
return Err(format!(
|
||||
"written {} of {}: {list}; failed on `{name}`: {e}",
|
||||
done.len(),
|
||||
changes.len()
|
||||
));
|
||||
}
|
||||
done.push(name);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One file of the summary: its name, its diff and the lines it moves.
|
||||
struct Written {
|
||||
file: String,
|
||||
created: bool,
|
||||
diff: String,
|
||||
added: usize,
|
||||
removed: usize,
|
||||
}
|
||||
|
||||
impl Written {
|
||||
fn of(project: &Project, change: &Change) -> Written {
|
||||
let file = project.relative(&change.path);
|
||||
let diff = unified(&file, &change.before, &change.after);
|
||||
// The two header lines are `---`/`+++`; every later line starting
|
||||
// with a sign is one line of the change.
|
||||
let body = diff.lines().skip(2);
|
||||
let added = body.clone().filter(|line| line.starts_with('+')).count();
|
||||
let removed = body.filter(|line| line.starts_with('-')).count();
|
||||
Written { file, created: change.created, diff, added, removed }
|
||||
}
|
||||
}
|
||||
|
||||
/// The text and JSON an edit answers with.
|
||||
fn summary(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Answer {
|
||||
let created = files.iter().filter(|f| f.created).count();
|
||||
let mut text = if files.is_empty() {
|
||||
"unchanged\n".to_string()
|
||||
} else {
|
||||
let tail = if dry_run { " (dry run: nothing written)" } else { "" };
|
||||
format!("files: {} changed, {created} created{tail}\n", files.len() - created)
|
||||
};
|
||||
for file in files {
|
||||
let mark = if file.created { " (created)" } else { "" };
|
||||
text.push_str(&format!(" {} +{} -{}{mark}\n", file.file, file.added, file.removed));
|
||||
}
|
||||
if !unchanged.is_empty() && !files.is_empty() {
|
||||
text.push_str(&format!("unchanged: {}\n", unchanged.join(", ")));
|
||||
}
|
||||
if let Some(note) = &plan.note {
|
||||
text.push_str(note);
|
||||
text.push('\n');
|
||||
}
|
||||
push_warnings(&mut text, &plan.warnings);
|
||||
if dry_run {
|
||||
files.iter().for_each(|file| text.push_str(&file.diff));
|
||||
}
|
||||
Answer { text, structured: structured(files, unchanged, plan, dry_run) }
|
||||
}
|
||||
|
||||
fn push_warnings(text: &mut String, warnings: &[String]) {
|
||||
if warnings.is_empty() {
|
||||
return;
|
||||
}
|
||||
text.push_str("warnings:\n");
|
||||
for warning in warnings {
|
||||
text.push_str(&format!(" {warning}\n"));
|
||||
}
|
||||
}
|
||||
|
||||
fn structured(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Value {
|
||||
let entry = |file: &Written| {
|
||||
let mut entry = json!({ "file": file.file, "added": file.added, "removed": file.removed });
|
||||
if dry_run {
|
||||
entry["diff"] = Value::from(file.diff.clone());
|
||||
}
|
||||
entry
|
||||
};
|
||||
let changed: Vec<Value> = files.iter().filter(|f| !f.created).map(entry).collect();
|
||||
let created: Vec<Value> = files.iter().filter(|f| f.created).map(entry).collect();
|
||||
json!({
|
||||
"changed": changed,
|
||||
"created": created,
|
||||
"unchanged": unchanged,
|
||||
"warnings": plan.warnings,
|
||||
"note": plan.note,
|
||||
"dry_run": dry_run,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-apply-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
fn edit(start: u32, end: u32, text: &str) -> TextEdit {
|
||||
TextEdit { range: TextRange::new(start, end), new_text: text.to_string() }
|
||||
}
|
||||
|
||||
fn change(path: &Path, before: &str, after: &str) -> Change {
|
||||
Change {
|
||||
path: path.to_path_buf(),
|
||||
before: before.into(),
|
||||
after: after.into(),
|
||||
created: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn name(path: &Path) -> String {
|
||||
path.file_name().unwrap().to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_apply_last_first_and_a_misfit_is_refused() {
|
||||
let edits = [edit(8, 11, "xyz!"), edit(0, 3, "q")];
|
||||
assert_eq!(apply_edits("abc def abc", &edits).unwrap(), "q def xyz!");
|
||||
assert_eq!(apply_edits("abc", &[edit(3, 3, "d")]).unwrap(), "abcd");
|
||||
assert!(apply_edits("abcdef", &[edit(0, 3, "x"), edit(2, 4, "y")]).is_err());
|
||||
assert!(apply_edits("abc", &[edit(2, 9, "x")]).is_err());
|
||||
assert!(apply_edits("é", &[edit(1, 2, "x")]).unwrap_err().contains("splits"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_moved_since_it_was_read_refuses_every_write() {
|
||||
let dir = scratch("stale");
|
||||
let (a, b) = (dir.join("a.sv"), dir.join("b.sv"));
|
||||
fs::write(&a, "module a; endmodule\n").unwrap();
|
||||
fs::write(&b, "module b; endmodule // edited meanwhile\n").unwrap();
|
||||
let first = change(&a, "module a; endmodule\n", "module a2; endmodule\n");
|
||||
let second = change(&b, "module b; endmodule\n", "module b2; endmodule\n");
|
||||
let refused = commit(&[&first, &second], name).unwrap_err();
|
||||
assert_eq!(refused, "`b.sv` changed on disk since it was read; nothing written.");
|
||||
// The first file, whose bytes still matched, was not written either.
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "module a; endmodule\n");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_created_file_that_appeared_meanwhile_is_refused_and_a_fresh_edit_lands() {
|
||||
let dir = scratch("create");
|
||||
let a = dir.join("a.sv");
|
||||
fs::write(&a, "module a; endmodule\n").unwrap();
|
||||
let taken = dir.join("n.sv");
|
||||
fs::write(&taken, "// someone else's\n").unwrap();
|
||||
let edit = change(&a, "module a; endmodule\n", "module a; n u_n (); endmodule\n");
|
||||
let new =
|
||||
Change { path: taken.clone(), before: String::new(), after: "x".into(), created: true };
|
||||
let refused = commit(&[&edit, &new], name).unwrap_err();
|
||||
assert_eq!(refused, "`n.sv` already exists; nothing written.");
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "module a; endmodule\n");
|
||||
fs::remove_file(&taken).unwrap();
|
||||
commit(&[&edit, &new], name).unwrap();
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "module a; n u_n (); endmodule\n");
|
||||
assert_eq!(fs::read_to_string(&taken).unwrap(), "x");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_write_that_fails_after_another_landed_says_what_was_written() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = scratch("partial");
|
||||
let shut = dir.join("shut");
|
||||
fs::create_dir(&shut).unwrap();
|
||||
let (a, b) = (dir.join("a.sv"), shut.join("b.sv"));
|
||||
fs::write(&a, "a\n").unwrap();
|
||||
fs::write(&b, "b\n").unwrap();
|
||||
// A read-only file is refused before any write …
|
||||
fs::set_permissions(&b, fs::Permissions::from_mode(0o444)).unwrap();
|
||||
let (first, second) = (change(&a, "a\n", "a2\n"), change(&b, "b\n", "b2\n"));
|
||||
let refused = commit(&[&first, &second], name).unwrap_err();
|
||||
assert_eq!(refused, "`b.sv` is read-only; nothing written.");
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "a\n");
|
||||
// … but a directory that will not take the temp file fails only at
|
||||
// the write, after `a.sv` landed: said, not hidden.
|
||||
fs::set_permissions(&b, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let refused = commit(&[&first, &second], name).unwrap_err();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(refused.starts_with("written 1 of 2: a.sv; failed on `b.sv`: "), "{refused}");
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "a2\n");
|
||||
assert_eq!(fs::read_to_string(&b).unwrap(), "b\n");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_outside_every_root_is_refused_and_nothing_is_written() {
|
||||
let dir = scratch("roots");
|
||||
let (root, outside) = (dir.join("root"), dir.join("outside"));
|
||||
fs::create_dir(&root).unwrap();
|
||||
fs::create_dir(&outside).unwrap();
|
||||
fs::write(root.join("a.sv"), "module a; endmodule\n").unwrap();
|
||||
fs::write(outside.join("b.sv"), "module b; endmodule\n").unwrap();
|
||||
let project = Project::open(vec![root.clone()], None);
|
||||
let create = |path: PathBuf| Change {
|
||||
path,
|
||||
before: String::new(),
|
||||
after: "module n; endmodule\n".into(),
|
||||
created: true,
|
||||
};
|
||||
let refuse = |change: Change| {
|
||||
let plan = Plan { changes: vec![change], ..Plan::default() };
|
||||
run(&project, plan, false).err().unwrap()
|
||||
};
|
||||
let beside = refuse(create(outside.join("n.sv")));
|
||||
assert!(beside.contains("would be created outside every root"), "{beside}");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// A directory inside the root that is a symlink leading out.
|
||||
std::os::unix::fs::symlink(&outside, root.join("link")).unwrap();
|
||||
let through = refuse(create(root.join("link").join("n.sv")));
|
||||
assert!(through.contains("outside every root"), "{through}");
|
||||
}
|
||||
let existing = outside.join("b.sv");
|
||||
let rewritten = refuse(change(&existing, "module b; endmodule\n", "module c; endmodule\n"));
|
||||
assert!(rewritten.contains("outside every root"), "{rewritten}");
|
||||
assert!(!outside.join("n.sv").exists());
|
||||
assert_eq!(fs::read_to_string(&existing).unwrap(), "module b; endmodule\n");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! `lucisv-mcp` — lucisv as a Model Context Protocol server, over stdio.
|
||||
//!
|
||||
//! A coding agent (Claude Code, Cursor, VS Code's agent mode) spawns this
|
||||
//! binary and asks it about a Verilog/SystemVerilog tree: what units exist,
|
||||
//! what a module's ports are, what a file's outline is. Every answer is a
|
||||
//! composition of the library crates' public APIs; nothing here is shared
|
||||
//! with `lucisv-server` or the `lucisv` CLI. See `docs/mcp/PLAN.md` and
|
||||
//! `docs/features/mcp-transport/README.md`.
|
||||
|
||||
mod apply;
|
||||
mod project;
|
||||
mod render;
|
||||
mod resources;
|
||||
mod rpc;
|
||||
mod tools;
|
||||
mod transport;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
/// What someone who spelled an argument wrong is told, on stderr.
|
||||
const USAGE: &str =
|
||||
"usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--verbose]";
|
||||
|
||||
/// The command line, parsed.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Options {
|
||||
/// `--root DIR`, in the order given; empty means the current directory.
|
||||
pub roots: Vec<PathBuf>,
|
||||
/// `--filelist FILE`: overrides the configured `filelist`.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// `--index-cache DIR`: accepted and stored; read from M6 on.
|
||||
pub index_cache: Option<PathBuf>,
|
||||
/// `--verbose`: per-call timing lines on stderr.
|
||||
pub verbose: bool,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let parsed = parse_args(std::env::args().skip(1)).and_then(|mut options| {
|
||||
options.roots = project::canonical_roots(&options.roots)?;
|
||||
Ok(options)
|
||||
});
|
||||
let options = match parsed {
|
||||
Ok(options) => options,
|
||||
Err(problem) => {
|
||||
eprintln!("error: {problem}");
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
// Every parse happens on this thread, so it gets the stack the parser's
|
||||
// recursion limit was sized for (`docs/features/recursion-limit`).
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("lucisv-mcp".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || rpc::serve(options));
|
||||
match spawned.map(|handle| handle.join()) {
|
||||
Ok(Ok(Ok(()))) => ExitCode::SUCCESS,
|
||||
Ok(Ok(Err(problem))) => {
|
||||
eprintln!("lucisv-mcp: {problem}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
eprintln!("lucisv-mcp: the server thread panicked");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
Err(problem) => {
|
||||
eprintln!("lucisv-mcp: cannot start the server thread: {problem}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the argument contract (TODO-MCP "Fixed names"). Anything else is an
|
||||
/// error naming the offending argument.
|
||||
fn parse_args(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut options = Options::default();
|
||||
let mut args = args;
|
||||
while let Some(arg) = args.next() {
|
||||
let mut value = |flag: &str| {
|
||||
args.next().map(PathBuf::from).ok_or_else(|| format!("{flag} needs a value"))
|
||||
};
|
||||
match arg.as_str() {
|
||||
"--root" => options.roots.push(value("--root")?),
|
||||
"--filelist" => options.filelist = Some(value("--filelist")?),
|
||||
"--index-cache" => options.index_cache = Some(value("--index-cache")?),
|
||||
"--verbose" => options.verbose = true,
|
||||
other => return Err(format!("unknown option: {other}")),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Options, String> {
|
||||
parse_args(args.iter().map(|a| a.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_documented_argument_is_read() {
|
||||
let options = parse(&[
|
||||
"--root",
|
||||
"a",
|
||||
"--root",
|
||||
"b",
|
||||
"--filelist",
|
||||
"f.f",
|
||||
"--index-cache",
|
||||
"c",
|
||||
"--verbose",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(options.roots, vec![PathBuf::from("a"), PathBuf::from("b")]);
|
||||
assert_eq!(options.filelist, Some(PathBuf::from("f.f")));
|
||||
assert_eq!(options.index_cache, Some(PathBuf::from("c")));
|
||||
assert!(options.verbose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_argument_or_a_missing_value_is_refused_by_name() {
|
||||
assert_eq!(parse(&["--stdio"]).unwrap_err(), "unknown option: --stdio");
|
||||
assert_eq!(parse(&["--root"]).unwrap_err(), "--root needs a value");
|
||||
assert_eq!(parse(&[]).unwrap(), Options::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! One file, fully analyzed, and a small cache of them keyed by content.
|
||||
//!
|
||||
//! The index answers workspace questions without keeping any file's text;
|
||||
//! a tool that needs a file's outline, a slice of its text or its
|
||||
//! declarations asks for its [`Analysis`] here. The sequence is the language
|
||||
//! server's `Document::new` minus the cross-file overlay: lex once, parse
|
||||
//! tolerantly, read the `` `define`` table off the tokens, analyze, index the
|
||||
//! lines. The overlay (`resolve_external`) depends on the index, which moves
|
||||
//! under a file whose own text did not, so it is computed per call by the
|
||||
//! tool that needs it ([`Analysis::external`]) and never cached here.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
|
||||
|
||||
/// How many analyses are kept. An agent's calls cluster on a handful of
|
||||
/// files; a whole-design answer never needs a file's analysis at all.
|
||||
const CAPACITY: usize = 16;
|
||||
|
||||
/// Everything one file's text yields on its own.
|
||||
pub struct Analysis {
|
||||
/// The text every span below indexes into.
|
||||
pub text: String,
|
||||
/// The line table over `text`.
|
||||
pub lines: LineIndex,
|
||||
/// The tokens `tree` was parsed from; empty when the text does not lex.
|
||||
pub tokens: Vec<Token>,
|
||||
/// Every `` `define``/`` `undef`` the file writes, in source order.
|
||||
pub defines: DefineTable,
|
||||
/// The tolerant parse.
|
||||
pub tree: SourceFile,
|
||||
/// What the parse could not read; empty for a clean file.
|
||||
pub diagnostics: Vec<ParseDiagnostic>,
|
||||
/// The single-file symbol tables.
|
||||
pub semantics: Semantics,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Analyze `text`. Parses, so it must run on a thread with
|
||||
/// `PARSE_STACK_SIZE` of stack.
|
||||
pub fn of(text: String) -> Analysis {
|
||||
// One lex: a file that does not lex takes the all-error path, exactly
|
||||
// as `parse_source_tolerant` would.
|
||||
// The tokens are kept (a clone before the parse consumes them): the
|
||||
// lint pass and the macro lookups read them again.
|
||||
let (tree, diagnostics, tokens) = match tokenize(&text) {
|
||||
Ok(tokens) => {
|
||||
let (tree, diagnostics) = parse_tolerant(tokens.clone(), &text);
|
||||
(tree, diagnostics, tokens)
|
||||
}
|
||||
Err(_) => {
|
||||
let (tree, diagnostics) = parse_source_tolerant(&text);
|
||||
(tree, diagnostics, Vec::new())
|
||||
}
|
||||
};
|
||||
let defines = collect_defines(&tokens);
|
||||
let semantics = analyze(&tree, &text);
|
||||
let lines = LineIndex::new(&text);
|
||||
Analysis { text, lines, tokens, defines, tree, diagnostics, semantics }
|
||||
}
|
||||
|
||||
/// The workspace overlay over this file's references, against `index` as
|
||||
/// it is now. Not cached: the index moves under an unchanged file.
|
||||
pub fn external(&self, index: &WorkspaceIndex) -> ExternalResolutions {
|
||||
resolve_external(&self.semantics, index)
|
||||
}
|
||||
|
||||
/// The token covering byte `offset`, if any.
|
||||
pub fn token_at(&self, offset: u32) -> Option<&Token> {
|
||||
let after = self.tokens.partition_point(|token| token.span.start <= offset);
|
||||
let token = self.tokens.get(after.checked_sub(1)?)?;
|
||||
token.span.contains(offset).then_some(token)
|
||||
}
|
||||
|
||||
/// The text of 1-based line `line`, without its line ending.
|
||||
pub fn line_text(&self, line: u32) -> &str {
|
||||
match self.lines.line_range(line) {
|
||||
Some(range) => self.slice(range.start, range.end).trim_end_matches('\r'),
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1-based first and last line a byte range covers. A range ending
|
||||
/// just after a newline ends on the line before it.
|
||||
pub fn line_span(&self, start: u32, end: u32) -> (u32, u32) {
|
||||
let (first, _) = self.lines.line_col(start);
|
||||
let (last, _) = self.lines.line_col(end.saturating_sub(1).max(start));
|
||||
(first, last)
|
||||
}
|
||||
|
||||
/// The text of a byte range, or an empty string for a range that does
|
||||
/// not fall on character boundaries of this text.
|
||||
pub fn slice(&self, start: u32, end: u32) -> &str {
|
||||
self.text.get(start as usize..end as usize).unwrap_or("")
|
||||
}
|
||||
}
|
||||
|
||||
/// The last few analyses, newest last, each tagged with the content hash it
|
||||
/// was computed from.
|
||||
#[derive(Default)]
|
||||
pub struct Analyses {
|
||||
held: Vec<(PathBuf, u64, Rc<Analysis>)>,
|
||||
}
|
||||
|
||||
impl Analyses {
|
||||
/// The analysis of `path` whose text hashes to `hash`, when one is held.
|
||||
pub fn get(&mut self, path: &Path, hash: u64) -> Option<Rc<Analysis>> {
|
||||
let at = self.held.iter().position(|(p, h, _)| p == path && *h == hash)?;
|
||||
let entry = self.held.remove(at);
|
||||
let analysis = Rc::clone(&entry.2);
|
||||
self.held.push(entry);
|
||||
Some(analysis)
|
||||
}
|
||||
|
||||
/// Keep `analysis` for `path`, dropping any older one of the same file
|
||||
/// and the oldest entry when full.
|
||||
pub fn put(&mut self, path: PathBuf, hash: u64, analysis: Rc<Analysis>) {
|
||||
self.held.retain(|(p, _, _)| *p != path);
|
||||
if self.held.len() >= CAPACITY {
|
||||
self.held.remove(0);
|
||||
}
|
||||
self.held.push((path, hash, analysis));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn line_spans_are_one_based_and_a_trailing_newline_stays_on_its_line() {
|
||||
let analysis = Analysis::of("module a;\nendmodule\n".to_string());
|
||||
assert_eq!(analysis.line_span(0, 20), (1, 2));
|
||||
assert_eq!(analysis.line_span(0, 10), (1, 1));
|
||||
assert_eq!(analysis.slice(0, 6), "module");
|
||||
assert!(analysis.diagnostics.is_empty());
|
||||
assert_eq!(analysis.line_text(2), "endmodule");
|
||||
assert_eq!(analysis.line_text(9), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_and_defines_are_kept_and_a_token_is_found_by_offset() {
|
||||
let analysis = Analysis::of("`define W 8\r\nmodule a; endmodule\r\n".to_string());
|
||||
assert_eq!(analysis.defines.latest("W").map(|d| d.body.as_str()), Some("8"));
|
||||
assert_eq!(analysis.line_text(1), "`define W 8");
|
||||
let module = analysis.token_at(14).map(|t| t.text.as_str());
|
||||
assert_eq!(module, Some("module"));
|
||||
assert!(analysis.token_at(1000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_answers_by_content_and_evicts_the_oldest() {
|
||||
let mut cache = Analyses::default();
|
||||
let a = Rc::new(Analysis::of(String::new()));
|
||||
cache.put(PathBuf::from("a"), 1, Rc::clone(&a));
|
||||
assert!(cache.get(Path::new("a"), 1).is_some());
|
||||
assert!(cache.get(Path::new("a"), 2).is_none());
|
||||
for n in 0..CAPACITY {
|
||||
cache.put(PathBuf::from(format!("f{n}")), 0, Rc::clone(&a));
|
||||
}
|
||||
assert!(cache.get(Path::new("a"), 1).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! Which files the project is made of, and what each one looked like when it
|
||||
//! was last read: the filelist-or-walk ladder of PLAN §4.4 over
|
||||
//! `lucisv_core`, and the per-file stamp the freshness sweep compares against.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use lucisv_core::cache::content_hash;
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::walk::collect_files_with;
|
||||
|
||||
/// The per-file size cap of a walked tree — the editor's
|
||||
/// `lucisv.index.maxFileSize` default. A larger file is a netlist, not
|
||||
/// something an agent wants summarised.
|
||||
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
|
||||
|
||||
/// A file whose mtime is this close to the moment it was read may have been
|
||||
/// written again within the filesystem's timestamp resolution, so its stamp
|
||||
/// proves nothing: it is re-read (and re-hashed) until it is older than
|
||||
/// this. Git's "racy clean" rule, for the same reason.
|
||||
const RACY: Duration = Duration::from_secs(2);
|
||||
|
||||
/// The files one discovery found, and what it had to say about the rest.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FileSet {
|
||||
/// Canonical paths, sorted, without repeats.
|
||||
pub files: Vec<PathBuf>,
|
||||
/// The filelist the set was read from, when it was.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// Problems worth one line each on stderr and in `project_overview`.
|
||||
pub warnings: Vec<String>,
|
||||
/// Walked files skipped for being over [`MAX_FILE_BYTES`].
|
||||
pub skipped_large: usize,
|
||||
/// Those files' canonical paths: an edit tool must know which files it
|
||||
/// could not read (`docs/features/mcp-edit-tools`, QA finding 2).
|
||||
pub skipped: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// Find the project's files: the filelist (`--filelist`, else the first
|
||||
/// root's configured `filelist`) when there is one that reads, else a walk of
|
||||
/// every root honouring `.gitignore`, each root's `exclude` patterns and the
|
||||
/// size cap. A filelist that does not read falls back to the walk, with a
|
||||
/// warning — the editor's ladder.
|
||||
pub fn discover(roots: &[PathBuf], filelist: Option<&Path>) -> FileSet {
|
||||
let mut set = FileSet::default();
|
||||
let filelist = filelist.map(Path::to_path_buf).or_else(|| configured_filelist(roots));
|
||||
if let Some(path) = filelist {
|
||||
match lucisv_core::filelist::read(&path) {
|
||||
Ok(list) => {
|
||||
set.warnings.extend(list.warnings);
|
||||
set.files = list.files.iter().filter_map(|f| canonical(f)).collect();
|
||||
set.filelist = Some(path);
|
||||
return finish(set);
|
||||
}
|
||||
Err(problem) => {
|
||||
set.warnings.push(format!("{problem} — walking the roots instead"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for root in roots {
|
||||
walk_root(root, roots, &mut set);
|
||||
}
|
||||
finish(set)
|
||||
}
|
||||
|
||||
/// The `filelist` key of the config governing the first root that has one.
|
||||
fn configured_filelist(roots: &[PathBuf]) -> Option<PathBuf> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
|
||||
}
|
||||
|
||||
/// Every source file under one root, as `lucisv` itself would walk it —
|
||||
/// except a file a symlink leads outside every root, which is dropped with a
|
||||
/// warning naming it: the walk is held to the rule `Project::resolve` holds
|
||||
/// a path argument to. (A `--filelist` entry is the user's own choice and
|
||||
/// stays.)
|
||||
fn walk_root(root: &Path, roots: &[PathBuf], set: &mut FileSet) {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let exclude = match discovery.for_dir(root) {
|
||||
Ok(config) => config.exclude.unwrap_or_default(),
|
||||
Err(problem) => {
|
||||
set.warnings.push(problem);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let input = root.to_string_lossy();
|
||||
let mut found: Vec<(PathBuf, Option<u64>)> = Vec::new();
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let walked = collect_files_with(
|
||||
&input,
|
||||
&exclude,
|
||||
true,
|
||||
&mut |path, size| found.push((path, size)),
|
||||
&mut |warning| warnings.push(warning.to_string()),
|
||||
);
|
||||
if let Err(problem) = walked {
|
||||
warnings.push(problem);
|
||||
}
|
||||
set.warnings.extend(warnings);
|
||||
for (path, size) in found {
|
||||
let Some(path) = canonical(&path) else { continue };
|
||||
if !roots.iter().any(|root| path.starts_with(root)) {
|
||||
set.warnings.push(format!(
|
||||
"{}: outside every root (reached through a symlink); not indexed",
|
||||
path.display()
|
||||
));
|
||||
} else if size.unwrap_or(0) > MAX_FILE_BYTES {
|
||||
set.skipped_large += 1;
|
||||
set.skipped.push(path);
|
||||
} else {
|
||||
set.files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut set: FileSet) -> FileSet {
|
||||
set.files.sort();
|
||||
set.files.dedup();
|
||||
set.skipped.sort();
|
||||
set.skipped.dedup();
|
||||
set
|
||||
}
|
||||
|
||||
/// `path` with every symlink resolved, or `None` when it no longer exists.
|
||||
pub fn canonical(path: &Path) -> Option<PathBuf> {
|
||||
fs::canonicalize(path).ok()
|
||||
}
|
||||
|
||||
/// What a file looked like when it was last read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Stamp {
|
||||
/// Its length in bytes.
|
||||
pub size: u64,
|
||||
/// Its modification time, when the filesystem reports one.
|
||||
pub mtime: Option<SystemTime>,
|
||||
/// `content_hash` of its bytes.
|
||||
pub hash: u64,
|
||||
/// When it was read.
|
||||
pub read_at: SystemTime,
|
||||
/// Its ctime and inode — what still moves when a same-size rewrite puts
|
||||
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
|
||||
/// the same problem. Zero off Unix, where size, mtime and the racy rule
|
||||
/// are all there is.
|
||||
pub identity: (i64, i64, u64),
|
||||
/// Whether its text spells `endprogram` — the cheap test that says a
|
||||
/// `Module`-kind unit in it might be a `program` (the semantic layer
|
||||
/// models both as a module).
|
||||
pub program: bool,
|
||||
}
|
||||
|
||||
/// How a file compares with its stamp.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Change {
|
||||
/// Same size, same mtime, and not racy: the stamp still describes it.
|
||||
Same,
|
||||
/// Something moved; the file has to be read to know whether its bytes did.
|
||||
Suspect,
|
||||
/// It is gone, unreadable, or grew past the cap.
|
||||
Gone,
|
||||
}
|
||||
|
||||
impl Stamp {
|
||||
/// Compare the file on disk with this stamp, by one `stat`.
|
||||
pub fn check(&self, path: &Path) -> Change {
|
||||
let Ok(meta) = fs::metadata(path) else {
|
||||
return Change::Gone;
|
||||
};
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
return Change::Gone;
|
||||
}
|
||||
let mtime = meta.modified().ok();
|
||||
let racy = match mtime {
|
||||
Some(mtime) => mtime + RACY > self.read_at,
|
||||
None => true,
|
||||
};
|
||||
let moved = meta.len() != self.size || mtime != self.mtime;
|
||||
if moved || identity(&meta) != self.identity || racy {
|
||||
Change::Suspect
|
||||
} else {
|
||||
Change::Same
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one source file and stamp it. `Err` for a file that is gone or is
|
||||
/// not UTF-8 text — the latter skipped exactly as the language server skips
|
||||
/// it.
|
||||
pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
|
||||
// Stat before reading: a write that lands between the two leaves a stamp
|
||||
// older than the bytes, which the next sweep sees as a change.
|
||||
let meta = fs::metadata(path)?;
|
||||
let read_at = SystemTime::now();
|
||||
let bytes = fs::read(path)?;
|
||||
let hash = content_hash(&bytes);
|
||||
let text = String::from_utf8(bytes)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "not UTF-8 text"))?;
|
||||
let stamp = Stamp {
|
||||
size: meta.len(),
|
||||
mtime: meta.modified().ok(),
|
||||
hash,
|
||||
read_at,
|
||||
identity: identity(&meta),
|
||||
program: text.contains("endprogram"),
|
||||
};
|
||||
Ok((text, stamp))
|
||||
}
|
||||
|
||||
/// A file's ctime (seconds, nanoseconds) and inode number.
|
||||
#[cfg(unix)]
|
||||
fn identity(meta: &fs::Metadata) -> (i64, i64, u64) {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
(meta.ctime(), meta.ctime_nsec(), meta.ino())
|
||||
}
|
||||
|
||||
/// No ctime or inode off Unix: the stamp falls back to size and mtime.
|
||||
#[cfg(not(unix))]
|
||||
fn identity(_: &fs::Metadata) -> (i64, i64, u64) {
|
||||
(0, 0, 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-files-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_honours_gitignore_exclude_and_the_size_cap() {
|
||||
let dir = scratch("walk");
|
||||
fs::write(dir.join("a.sv"), "module a; endmodule\n").unwrap();
|
||||
fs::write(dir.join("big.sv"), vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap();
|
||||
fs::create_dir(dir.join("gen")).unwrap();
|
||||
fs::write(dir.join("gen/g.sv"), "module g; endmodule\n").unwrap();
|
||||
fs::create_dir(dir.join("skip")).unwrap();
|
||||
fs::write(dir.join("skip/s.sv"), "module s; endmodule\n").unwrap();
|
||||
fs::write(dir.join(".gitignore"), "gen/\n").unwrap();
|
||||
fs::write(dir.join("lucisv.toml"), "exclude = [\"skip\"]\n").unwrap();
|
||||
let set = discover(std::slice::from_ref(&dir), None);
|
||||
assert_eq!(set.files, vec![dir.join("a.sv")]);
|
||||
assert_eq!(set.skipped_large, 1);
|
||||
assert_eq!(set.skipped, vec![dir.join("big.sv")]);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_wins_and_an_unreadable_one_falls_back_to_the_walk() {
|
||||
let dir = scratch("filelist");
|
||||
fs::write(dir.join("a.sv"), "module a; endmodule\n").unwrap();
|
||||
fs::write(dir.join("b.sv"), "module b; endmodule\n").unwrap();
|
||||
fs::write(dir.join("files.f"), format!("{}\n", dir.join("b.sv").display())).unwrap();
|
||||
let listed = discover(std::slice::from_ref(&dir), Some(&dir.join("files.f")));
|
||||
assert_eq!(listed.files, vec![dir.join("b.sv")]);
|
||||
assert_eq!(listed.filelist, Some(dir.join("files.f")));
|
||||
let fallback = discover(std::slice::from_ref(&dir), Some(&dir.join("missing.f")));
|
||||
assert_eq!(fallback.files, vec![dir.join("a.sv"), dir.join("b.sv")]);
|
||||
assert!(fallback.warnings[0].contains("walking the roots instead"));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stamp_sees_an_edit_a_deletion_and_distrusts_a_racy_read() {
|
||||
let dir = scratch("stamp");
|
||||
let path = dir.join("a.sv");
|
||||
fs::write(&path, "module a; endmodule\n").unwrap();
|
||||
let (_, stamp) = read_source(&path).unwrap();
|
||||
// Just written: racy, so suspect even though nothing moved.
|
||||
assert_eq!(stamp.check(&path), Change::Suspect);
|
||||
let settled = Stamp { read_at: stamp.read_at + RACY + RACY, ..stamp };
|
||||
assert_eq!(settled.check(&path), Change::Same);
|
||||
fs::write(&path, "module a2; endmodule\n").unwrap();
|
||||
assert_eq!(settled.check(&path), Change::Suspect);
|
||||
fs::remove_file(&path).unwrap();
|
||||
assert_eq!(settled.check(&path), Change::Gone);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
//! The project one server answers about: its roots, its files, the workspace
|
||||
//! index over them, and the promise that no answer is older than the disk
|
||||
//! was when the call arrived (PLAN §4.4).
|
||||
|
||||
mod analysis;
|
||||
mod files;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
|
||||
|
||||
pub use analysis::Analysis;
|
||||
pub use files::Stamp;
|
||||
|
||||
use analysis::Analyses;
|
||||
use files::{canonical, discover, read_source, Change, FileSet};
|
||||
|
||||
/// A walk older than this is re-run at the next call, so new files appear.
|
||||
const REWALK_AFTER: Duration = Duration::from_secs(5);
|
||||
|
||||
/// What one freshness sweep did — logged under `--verbose`.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Refresh {
|
||||
/// Files whose bytes changed and were re-indexed.
|
||||
pub changed: usize,
|
||||
/// Files that appeared.
|
||||
pub added: usize,
|
||||
/// Files that went away.
|
||||
pub removed: usize,
|
||||
/// Whether the roots were walked (or the filelist re-read).
|
||||
pub walked: bool,
|
||||
}
|
||||
|
||||
/// Roots, files, index and the analyses of recently asked-about files.
|
||||
pub struct Project {
|
||||
roots: Vec<PathBuf>,
|
||||
filelist_arg: Option<PathBuf>,
|
||||
config: FileConfig,
|
||||
config_problem: Option<String>,
|
||||
files: BTreeMap<PathBuf, Stamp>,
|
||||
index: WorkspaceIndex,
|
||||
analyses: Analyses,
|
||||
walk: FileSet,
|
||||
walked_at: Instant,
|
||||
updated_at: Instant,
|
||||
build: Duration,
|
||||
/// Discovered files that are not UTF-8 text, with why, recomputed by
|
||||
/// every walk.
|
||||
unreadable: Vec<(PathBuf, String)>,
|
||||
/// Whether the current call has already walked the roots — the open, a
|
||||
/// stale or forced walk in `refresh`, or a miss's retry.
|
||||
walked_in_call: bool,
|
||||
}
|
||||
|
||||
/// The canonical form of every `--root`, the current directory when none
|
||||
/// was given, each distinct directory once in the order first given. A root
|
||||
/// that is not a directory is the user's mistake, named. Nested roots stay
|
||||
/// two roots: they are different directories.
|
||||
pub fn canonical_roots(roots: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
|
||||
let given = if roots.is_empty() { vec![PathBuf::from(".")] } else { roots.to_vec() };
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for root in &given {
|
||||
match canonical(root) {
|
||||
Some(path) if path.is_dir() => {
|
||||
if !out.contains(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
_ => return Err(format!("--root {}: not a directory", root.display())),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// Discover the files under `roots` (already canonical) and index them.
|
||||
/// Parses every file, so it runs on the stack-sized thread.
|
||||
pub fn open(roots: Vec<PathBuf>, filelist: Option<PathBuf>) -> Project {
|
||||
let started = Instant::now();
|
||||
let mut discovery = Discovery::new(true);
|
||||
let (config, config_problem) = match roots.first().map(|r| discovery.for_dir(r)) {
|
||||
Some(Ok(config)) => (config, None),
|
||||
Some(Err(problem)) => (FileConfig::default(), Some(problem)),
|
||||
None => (FileConfig::default(), None),
|
||||
};
|
||||
let walk = discover(&roots, filelist.as_deref());
|
||||
let mut builder = IndexBuilder::new();
|
||||
let mut files = BTreeMap::new();
|
||||
let mut unreadable = Vec::new();
|
||||
for path in &walk.files {
|
||||
match read_source(path) {
|
||||
Ok((text, stamp)) => {
|
||||
builder.add_file(path.clone(), &text);
|
||||
files.insert(path.clone(), stamp);
|
||||
}
|
||||
Err(problem) => {
|
||||
unreadable.push((path.clone(), problem.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let now = Instant::now();
|
||||
Project {
|
||||
roots,
|
||||
filelist_arg: filelist,
|
||||
config,
|
||||
config_problem,
|
||||
files,
|
||||
index: builder.finish(),
|
||||
analyses: Analyses::default(),
|
||||
walk,
|
||||
walked_at: now,
|
||||
updated_at: now,
|
||||
build: now - started,
|
||||
unreadable,
|
||||
walked_in_call: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the index up to the disk: stat every file, re-read the ones
|
||||
/// that moved, drop the ones that went, and — when a file went, when
|
||||
/// `force_walk`, or when the last walk is stale — walk again for new
|
||||
/// ones. One merge for the lot.
|
||||
pub fn refresh(&mut self, force_walk: bool) -> Refresh {
|
||||
let mut report = Refresh::default();
|
||||
self.walked_in_call = false;
|
||||
let mut gone: Vec<PathBuf> = Vec::new();
|
||||
let mut records: Vec<FileFacts> = Vec::new();
|
||||
let mut suspects: Vec<PathBuf> = Vec::new();
|
||||
for (path, stamp) in &self.files {
|
||||
match stamp.check(path) {
|
||||
Change::Same => {}
|
||||
Change::Suspect => suspects.push(path.clone()),
|
||||
Change::Gone => gone.push(path.clone()),
|
||||
}
|
||||
}
|
||||
for path in suspects {
|
||||
self.reread(path, &mut records, &mut gone);
|
||||
}
|
||||
report.changed = records.len();
|
||||
for path in &gone {
|
||||
self.files.remove(path);
|
||||
}
|
||||
if force_walk || !gone.is_empty() || self.walked_at.elapsed() > REWALK_AFTER {
|
||||
report.walked = true;
|
||||
report.added = self.rewalk(&mut records, &mut gone);
|
||||
self.walked_in_call = true;
|
||||
}
|
||||
report.removed = gone.len();
|
||||
if !records.is_empty() || !gone.is_empty() {
|
||||
self.index.absorb(records, &gone);
|
||||
self.updated_at = Instant::now();
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
/// Re-read one file whose stamp is in doubt; a changed hash is a record.
|
||||
fn reread(&mut self, path: PathBuf, records: &mut Vec<FileFacts>, gone: &mut Vec<PathBuf>) {
|
||||
match read_source(&path) {
|
||||
Ok((text, stamp)) => {
|
||||
let moved = self.files.get(&path).is_none_or(|old| old.hash != stamp.hash);
|
||||
if moved {
|
||||
records.push(FileFacts::of(path.clone(), &text));
|
||||
}
|
||||
self.files.insert(path, stamp);
|
||||
}
|
||||
Err(_) => gone.push(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk again: files the walk no longer finds are gone, files it finds
|
||||
/// for the first time are read and recorded. Returns how many were added.
|
||||
fn rewalk(&mut self, records: &mut Vec<FileFacts>, gone: &mut Vec<PathBuf>) -> usize {
|
||||
let walk = discover(&self.roots, self.filelist_arg.as_deref());
|
||||
let wanted: BTreeSet<&PathBuf> = walk.files.iter().collect();
|
||||
let dropped: Vec<PathBuf> =
|
||||
self.files.keys().filter(|path| !wanted.contains(path)).cloned().collect();
|
||||
for path in dropped {
|
||||
self.files.remove(&path);
|
||||
gone.push(path);
|
||||
}
|
||||
let mut added = 0;
|
||||
let mut unreadable = Vec::new();
|
||||
for path in &walk.files {
|
||||
if self.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
match read_source(path) {
|
||||
Ok((text, stamp)) => {
|
||||
records.push(FileFacts::of(path.clone(), &text));
|
||||
self.files.insert(path.clone(), stamp);
|
||||
added += 1;
|
||||
}
|
||||
Err(problem) => unreadable.push((path.clone(), problem.to_string())),
|
||||
}
|
||||
}
|
||||
self.unreadable = unreadable;
|
||||
self.walk = walk;
|
||||
self.walked_at = Instant::now();
|
||||
added
|
||||
}
|
||||
|
||||
/// A by-name lookup found nothing: when this call has not walked yet,
|
||||
/// walk now (a file written since the last walk is otherwise invisible
|
||||
/// for up to `REWALK_AFTER`) and say so, so the caller retries once.
|
||||
pub fn ensure_walked_for_miss(&mut self) -> bool {
|
||||
if self.walked_in_call {
|
||||
return false;
|
||||
}
|
||||
self.refresh(true);
|
||||
true
|
||||
}
|
||||
|
||||
/// The workspace index, as fresh as the last [`Project::refresh`].
|
||||
pub fn index(&self) -> &WorkspaceIndex {
|
||||
&self.index
|
||||
}
|
||||
|
||||
/// The canonical roots, in the order given.
|
||||
pub fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// Every indexed file with its stamp, sorted by path.
|
||||
pub fn files(&self) -> impl Iterator<Item = (&PathBuf, &Stamp)> {
|
||||
self.files.iter()
|
||||
}
|
||||
|
||||
/// The stamp of one indexed file.
|
||||
pub fn stamp(&self, path: &Path) -> Option<&Stamp> {
|
||||
self.files.get(path)
|
||||
}
|
||||
|
||||
/// The config governing the first root, and the problem reading it.
|
||||
pub fn config(&self) -> (&FileConfig, Option<&str>) {
|
||||
(&self.config, self.config_problem.as_deref())
|
||||
}
|
||||
|
||||
/// The last discovery: its filelist, warnings and skipped files.
|
||||
pub fn discovery(&self) -> &FileSet {
|
||||
&self.walk
|
||||
}
|
||||
|
||||
/// Files discovery found but could not read as UTF-8 text.
|
||||
pub fn unreadable(&self) -> Vec<String> {
|
||||
let shown = |(path, why): &(PathBuf, String)| format!("{}: {why}", self.relative(path));
|
||||
self.unreadable.iter().map(shown).collect()
|
||||
}
|
||||
|
||||
/// Every discovered file the index does not hold, with why: over the
|
||||
/// size cap, or not UTF-8 text. An edit over the whole set must not
|
||||
/// pretend these were searched.
|
||||
pub fn skipped(&self) -> Vec<(PathBuf, String)> {
|
||||
let large = self.walk.skipped.iter().map(|path| (path.clone(), "over 1 MiB".to_string()));
|
||||
large.chain(self.unreadable.iter().cloned()).collect()
|
||||
}
|
||||
|
||||
/// How long the startup build took, and how long ago the index last
|
||||
/// changed.
|
||||
pub fn timing(&self) -> (Duration, Duration) {
|
||||
(self.build, self.updated_at.elapsed())
|
||||
}
|
||||
|
||||
/// A path argument, resolved: absolute, or relative to the first root
|
||||
/// holding it; symlinks followed; and refused, by name, unless it lands
|
||||
/// on a file inside a root.
|
||||
pub fn resolve(&self, arg: &str) -> Result<PathBuf, String> {
|
||||
let given = Path::new(arg);
|
||||
let candidates: Vec<PathBuf> = if given.is_absolute() {
|
||||
vec![given.to_path_buf()]
|
||||
} else {
|
||||
self.roots.iter().map(|root| root.join(given)).collect()
|
||||
};
|
||||
let Some(path) = candidates.iter().find_map(|c| canonical(c)) else {
|
||||
return Err(format!("`{arg}` does not exist under any root."));
|
||||
};
|
||||
if !self.roots.iter().any(|root| path.starts_with(root)) {
|
||||
return Err(format!(
|
||||
"`{arg}` resolves outside every root; lucisv-mcp only reads inside its roots."
|
||||
));
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(format!("`{arg}` is not a file."));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// `path` as answers print it: relative to the first root holding it,
|
||||
/// with `/` separators; absolute when no root does.
|
||||
pub fn relative(&self, path: &Path) -> String {
|
||||
relative_to(&self.roots, path)
|
||||
}
|
||||
|
||||
/// The analysis of one file as it is on disk now.
|
||||
pub fn analysis(&mut self, path: &Path) -> Result<Rc<Analysis>, String> {
|
||||
let (text, stamp) =
|
||||
read_source(path).map_err(|e| format!("cannot read `{}`: {e}", self.relative(path)))?;
|
||||
if let Some(held) = self.analyses.get(path, stamp.hash) {
|
||||
return Ok(held);
|
||||
}
|
||||
let analysis = Rc::new(Analysis::of(text));
|
||||
self.analyses.put(path.to_path_buf(), stamp.hash, Rc::clone(&analysis));
|
||||
Ok(analysis)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Project::relative`], for a caller that holds the roots but no project.
|
||||
fn relative_to(roots: &[PathBuf], path: &Path) -> String {
|
||||
let shown = roots.iter().find_map(|root| path.strip_prefix(root).ok()).unwrap_or(path);
|
||||
if shown.is_absolute() {
|
||||
return shown.display().to_string();
|
||||
}
|
||||
let parts: Vec<_> = shown.components().map(|c| c.as_os_str().to_string_lossy()).collect();
|
||||
parts.join("/")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,109 @@
|
||||
//! The freshness promise, against the rebuild oracle: after every update
|
||||
//! path the incrementally maintained index is the index a full build over
|
||||
//! the files now on disk produces (`WorkspaceIndex::fingerprint`).
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-project-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
/// The index a from-scratch build over the project's current files makes.
|
||||
fn rebuilt(project: &Project) -> String {
|
||||
let texts: Vec<(PathBuf, String)> = project
|
||||
.files()
|
||||
.map(|(path, _)| (path.clone(), fs::read_to_string(path).unwrap()))
|
||||
.collect();
|
||||
WorkspaceIndex::build(texts.iter().map(|(p, t)| (p.clone(), t.as_str()))).fingerprint()
|
||||
}
|
||||
|
||||
/// Age every stamp past the racy window, so only a real change is suspect.
|
||||
fn settle(project: &mut Project) {
|
||||
let later = SystemTime::now() + Duration::from_secs(10);
|
||||
for stamp in project.files.values_mut() {
|
||||
stamp.read_at = later;
|
||||
}
|
||||
}
|
||||
|
||||
fn write(dir: &Path, name: &str, text: &str) {
|
||||
fs::write(dir.join(name), text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_update_path_leaves_the_index_a_rebuild_would_make() {
|
||||
let dir = scratch("fingerprint");
|
||||
write(&dir, "a.sv", "module a(input logic x); b u_b(.*); endmodule\n");
|
||||
write(&dir, "b.sv", "module b(input logic x); endmodule\n");
|
||||
let mut project = Project::open(vec![dir.clone()], None);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
settle(&mut project);
|
||||
assert_eq!(project.refresh(false).changed, 0);
|
||||
|
||||
write(&dir, "b.sv", "module b(input logic x, output logic y); endmodule\n");
|
||||
let report = project.refresh(false);
|
||||
assert_eq!((report.changed, report.removed), (1, 0));
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
|
||||
write(&dir, "c.sv", "package c; parameter int W = 4; endpackage\n");
|
||||
let report = project.refresh(true);
|
||||
assert_eq!(report.added, 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
assert_eq!(project.index().units("c").len(), 1);
|
||||
|
||||
fs::remove_file(dir.join("a.sv")).unwrap();
|
||||
let report = project.refresh(false);
|
||||
assert!(report.walked, "a missing file triggers a walk");
|
||||
assert_eq!(report.removed, 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
assert!(project.index().units("a").is_empty());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_removed_and_recreated_between_two_calls_is_one_file_with_new_contents() {
|
||||
let dir = scratch("recreate");
|
||||
write(&dir, "a.sv", "module a; endmodule\n");
|
||||
let mut project = Project::open(vec![dir.clone()], None);
|
||||
settle(&mut project);
|
||||
fs::remove_file(dir.join("a.sv")).unwrap();
|
||||
write(&dir, "a.sv", "module a2; endmodule\n");
|
||||
project.refresh(false);
|
||||
assert!(project.index().units("a").is_empty());
|
||||
assert_eq!(project.index().units("a2").len(), 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_argument_must_land_inside_a_root() {
|
||||
let dir = scratch("resolve");
|
||||
let outside = scratch("resolve-outside");
|
||||
write(&dir, "a.sv", "module a; endmodule\n");
|
||||
write(&outside, "o.sv", "module o; endmodule\n");
|
||||
let project = Project::open(vec![dir.clone()], None);
|
||||
assert_eq!(project.resolve("a.sv").unwrap(), dir.join("a.sv"));
|
||||
assert_eq!(project.relative(&dir.join("a.sv")), "a.sv");
|
||||
let absolute = outside.join("o.sv");
|
||||
let refused = project.resolve(&absolute.to_string_lossy()).unwrap_err();
|
||||
assert!(refused.contains("outside every root"), "{refused}");
|
||||
let dotted = project.resolve("../lucisv-mcp-project-resolve-outside-x/o.sv").unwrap_err();
|
||||
assert!(dotted.contains("does not exist"), "{dotted}");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&absolute, dir.join("link.sv")).unwrap();
|
||||
let linked = project.resolve("link.sv").unwrap_err();
|
||||
assert!(linked.contains("outside every root"), "{linked}");
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
fs::remove_dir_all(outside).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! The rendering rules every tool's text answer follows (PLAN §4.5): the
|
||||
//! token budget is the product.
|
||||
//!
|
||||
//! - paths are root-relative, and a file is named once per group of lines
|
||||
//! about it, never once per line;
|
||||
//! - lines and columns are 1-based, a position is `line:col`, a range is
|
||||
//! `first-last`;
|
||||
//! - lists are capped, the cap is said with `… and N more` and the caller can
|
||||
//! page with `offset`;
|
||||
//! - no prose and no markdown headings: a label is a bare word and a colon,
|
||||
//! a table only where the columns are fixed.
|
||||
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
/// How many entries a list answer holds unless the caller says otherwise.
|
||||
pub const DEFAULT_LIMIT: usize = 200;
|
||||
|
||||
/// A declaration kind as one lower-case word — the keyword that declares it
|
||||
/// where there is one.
|
||||
pub fn kind(kind: SymbolKind) -> &'static str {
|
||||
match kind {
|
||||
SymbolKind::Module => "module",
|
||||
SymbolKind::Interface => "interface",
|
||||
SymbolKind::Modport => "modport",
|
||||
SymbolKind::Clocking => "clocking",
|
||||
SymbolKind::Package => "package",
|
||||
SymbolKind::Port => "port",
|
||||
SymbolKind::Net => "net",
|
||||
SymbolKind::Var => "var",
|
||||
SymbolKind::Param => "parameter",
|
||||
SymbolKind::LocalParam => "localparam",
|
||||
SymbolKind::Genvar => "genvar",
|
||||
SymbolKind::Typedef => "typedef",
|
||||
SymbolKind::EnumVariant => "enum_value",
|
||||
SymbolKind::Function => "function",
|
||||
SymbolKind::Task => "task",
|
||||
SymbolKind::TfArg => "argument",
|
||||
SymbolKind::Instance => "instance",
|
||||
SymbolKind::Block => "block",
|
||||
SymbolKind::StructMember => "field",
|
||||
SymbolKind::Class => "class",
|
||||
SymbolKind::Constraint => "constraint",
|
||||
SymbolKind::Covergroup => "covergroup",
|
||||
SymbolKind::Coverpoint => "coverpoint",
|
||||
SymbolKind::Cross => "cross",
|
||||
SymbolKind::Property => "property",
|
||||
SymbolKind::Sequence => "sequence",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every word [`kind`] can produce — what `read_item` accepts before a `:`.
|
||||
const KIND_WORDS: &[&str] = &[
|
||||
"module",
|
||||
"interface",
|
||||
"modport",
|
||||
"clocking",
|
||||
"package",
|
||||
"port",
|
||||
"net",
|
||||
"var",
|
||||
"parameter",
|
||||
"localparam",
|
||||
"genvar",
|
||||
"typedef",
|
||||
"enum_value",
|
||||
"function",
|
||||
"task",
|
||||
"argument",
|
||||
"instance",
|
||||
"block",
|
||||
"field",
|
||||
"class",
|
||||
"constraint",
|
||||
"covergroup",
|
||||
"coverpoint",
|
||||
"cross",
|
||||
"property",
|
||||
"sequence",
|
||||
];
|
||||
|
||||
/// Whether `word` is one of [`kind`]'s words.
|
||||
pub fn is_kind_word(word: &str) -> bool {
|
||||
KIND_WORDS.contains(&word)
|
||||
}
|
||||
|
||||
/// A line range as the answers print it: `12` or `12-40`.
|
||||
pub fn lines(first: u32, last: u32) -> String {
|
||||
if first == last {
|
||||
first.to_string()
|
||||
} else {
|
||||
format!("{first}-{last}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs of whitespace collapsed to one space, the ends trimmed: a
|
||||
/// declaration shown as one line whatever its source layout.
|
||||
pub fn one_line(text: &str) -> String {
|
||||
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// The window `offset..offset + limit` of a list, and how many entries
|
||||
/// follow it.
|
||||
pub fn page<T>(items: &[T], offset: usize, limit: usize) -> (&[T], usize) {
|
||||
let start = offset.min(items.len());
|
||||
let end = start.saturating_add(limit).min(items.len());
|
||||
(&items[start..end], items.len() - end)
|
||||
}
|
||||
|
||||
/// The line that says a list was cut, or nothing when it was not.
|
||||
pub fn more(out: &mut String, rest: usize) {
|
||||
if rest > 0 {
|
||||
out.push_str(&format!("… and {rest} more\n"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines grouped under the file they are about: the file once, then each
|
||||
/// of its lines indented by two spaces. Entries arrive in any order; groups
|
||||
/// keep the order in which each file first appears.
|
||||
pub fn grouped(entries: &[(String, String)]) -> String {
|
||||
let mut order: Vec<&str> = Vec::new();
|
||||
for (file, _) in entries {
|
||||
if !order.contains(&file.as_str()) {
|
||||
order.push(file);
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for file in order {
|
||||
out.push_str(file);
|
||||
out.push('\n');
|
||||
for (_, line) in entries.iter().filter(|(f, _)| f == file) {
|
||||
out.push_str(" ");
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows whose columns are padded to line up, the last column left ragged.
|
||||
pub fn table(rows: &[Vec<String>]) -> String {
|
||||
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||
let mut widths = vec![0; columns];
|
||||
for row in rows {
|
||||
for (at, cell) in row.iter().enumerate() {
|
||||
widths[at] = widths[at].max(cell.chars().count());
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for row in rows {
|
||||
let mut line = String::new();
|
||||
for (at, cell) in row.iter().enumerate() {
|
||||
if at + 1 < row.len() {
|
||||
// A column that is empty in every row takes no space at all.
|
||||
if widths[at] > 0 {
|
||||
line.push_str(&format!("{cell:<width$} ", width = widths[at]));
|
||||
}
|
||||
} else {
|
||||
line.push_str(cell);
|
||||
}
|
||||
}
|
||||
out.push_str(" ");
|
||||
out.push_str(line.trim_end());
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_kind_word_is_recognised_as_one() {
|
||||
use SymbolKind::*;
|
||||
let all = [
|
||||
Module,
|
||||
Interface,
|
||||
Modport,
|
||||
Clocking,
|
||||
Package,
|
||||
Port,
|
||||
Net,
|
||||
Var,
|
||||
Param,
|
||||
LocalParam,
|
||||
Genvar,
|
||||
Typedef,
|
||||
EnumVariant,
|
||||
Function,
|
||||
Task,
|
||||
TfArg,
|
||||
Instance,
|
||||
Block,
|
||||
StructMember,
|
||||
Class,
|
||||
Constraint,
|
||||
Covergroup,
|
||||
Coverpoint,
|
||||
Cross,
|
||||
Property,
|
||||
Sequence,
|
||||
];
|
||||
for symbol_kind in all {
|
||||
assert!(is_kind_word(kind(symbol_kind)), "{symbol_kind:?}");
|
||||
}
|
||||
assert_eq!(all.len(), KIND_WORDS.len());
|
||||
assert!(!is_kind_word("\\k"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_of_one_line_is_one_number() {
|
||||
assert_eq!(lines(3, 3), "3");
|
||||
assert_eq!(lines(3, 9), "3-9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_says_how_many_entries_follow_it() {
|
||||
let items = [1, 2, 3, 4, 5];
|
||||
assert_eq!(page(&items, 1, 2), (&items[1..3], 2));
|
||||
assert_eq!(page(&items, 9, 2), (&items[5..5], 0));
|
||||
let mut out = String::new();
|
||||
more(&mut out, 2);
|
||||
more(&mut out, 0);
|
||||
assert_eq!(out, "… and 2 more\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_named_once_per_group() {
|
||||
let entries = vec![
|
||||
("b.sv".to_string(), "module b 1".to_string()),
|
||||
("a.sv".to_string(), "module a 1".to_string()),
|
||||
("b.sv".to_string(), "module c 9".to_string()),
|
||||
];
|
||||
assert_eq!(grouped(&entries), "b.sv\n module b 1\n module c 9\na.sv\n module a 1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_columns_line_up_and_empty_columns_vanish() {
|
||||
let rows = vec![
|
||||
vec!["input".into(), "".into(), "logic".into(), "clk".into()],
|
||||
vec!["output".into(), "".into(), "logic [7:0]".into(), "q".into()],
|
||||
];
|
||||
assert_eq!(table(&rows), " input logic clk\n output logic [7:0] q\n");
|
||||
assert_eq!(one_line("a\n b\t c "), "a b c");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! The `lucisv://` resources: the project overview, the lint rule
|
||||
//! reference, one unit's interface and one file's outline — the same answers
|
||||
//! the read tools give, addressable by URI for a host that attaches context
|
||||
//! rather than calling tools.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::tools;
|
||||
|
||||
/// One resource a URI names.
|
||||
pub enum Resource {
|
||||
Overview,
|
||||
Rules,
|
||||
Unit(String),
|
||||
Outline(String),
|
||||
}
|
||||
|
||||
/// The `resources/list` result: the two fixed resources.
|
||||
pub fn list() -> Value {
|
||||
json!({ "resources": [
|
||||
{
|
||||
"uri": "lucisv://overview",
|
||||
"name": "overview",
|
||||
"title": "Project overview",
|
||||
"description": "Files, units by kind, top-level modules and largest files of the indexed project.",
|
||||
"mimeType": "text/plain",
|
||||
},
|
||||
{
|
||||
"uri": "lucisv://rules",
|
||||
"name": "rules",
|
||||
"title": "Lint rules",
|
||||
"description": "Every lucisv lint rule with its severity, default and options.",
|
||||
"mimeType": "text/markdown",
|
||||
},
|
||||
]})
|
||||
}
|
||||
|
||||
/// The `resources/templates/list` result: the two parameterised resources.
|
||||
pub fn templates() -> Value {
|
||||
json!({ "resourceTemplates": [
|
||||
{
|
||||
"uriTemplate": "lucisv://unit/{name}",
|
||||
"name": "unit",
|
||||
"title": "Unit interface",
|
||||
"description": "A module's or interface's parameters, ports and instantiation template; a package's or class's members.",
|
||||
"mimeType": "text/plain",
|
||||
},
|
||||
{
|
||||
"uriTemplate": "lucisv://file/{path}/outline",
|
||||
"name": "outline",
|
||||
"title": "File outline",
|
||||
"description": "The declarations in one root-relative file, with line ranges.",
|
||||
"mimeType": "text/plain",
|
||||
},
|
||||
]})
|
||||
}
|
||||
|
||||
impl Resource {
|
||||
/// The resource `uri` names, or `None` for any other URI.
|
||||
pub fn parse(uri: &str) -> Option<Resource> {
|
||||
let rest = uri.strip_prefix("lucisv://")?;
|
||||
match rest {
|
||||
"overview" => Some(Resource::Overview),
|
||||
"rules" => Some(Resource::Rules),
|
||||
_ => {
|
||||
if let Some(name) = rest.strip_prefix("unit/") {
|
||||
return decoded(name).map(Resource::Unit);
|
||||
}
|
||||
let path = rest.strip_prefix("file/")?.strip_suffix("/outline")?;
|
||||
decoded(path).map(Resource::Outline)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether answering needs the project index (only the rules do not).
|
||||
pub fn needs_project(&self) -> bool {
|
||||
!matches!(self, Resource::Rules)
|
||||
}
|
||||
|
||||
/// Whether answering walks the roots first, as `project_overview` does.
|
||||
pub fn rewalk(&self) -> bool {
|
||||
matches!(self, Resource::Overview)
|
||||
}
|
||||
|
||||
/// The `resources/read` result, or the reason there is no such resource.
|
||||
pub fn read(&self, uri: &str, project: Option<&mut Project>) -> Result<Value, String> {
|
||||
let (mime, text) = match (self, project) {
|
||||
(Resource::Rules, _) => ("text/markdown", vlog_linter::rules_markdown()),
|
||||
(Resource::Overview, Some(project)) => {
|
||||
("text/plain", run(project, "project_overview", None)?)
|
||||
}
|
||||
(Resource::Unit(name), Some(project)) => {
|
||||
// A URI has no `file` argument to pick among declarations.
|
||||
let text = run(project, "unit_interface", Some(("name", name))).map_err(|why| {
|
||||
why.replace(
|
||||
"pass `file` to pick one",
|
||||
"call the unit_interface tool with its file argument to pick one",
|
||||
)
|
||||
})?;
|
||||
("text/plain", text)
|
||||
}
|
||||
(Resource::Outline(path), Some(project)) => {
|
||||
("text/plain", run(project, "outline", Some(("file", path)))?)
|
||||
}
|
||||
(_, None) => return Err("the project is not open".into()),
|
||||
};
|
||||
Ok(json!({ "contents": [{ "uri": uri, "mimeType": mime, "text": text }] }))
|
||||
}
|
||||
}
|
||||
|
||||
/// A read tool's text answer, as the resource's body.
|
||||
fn run(
|
||||
project: &mut Project,
|
||||
tool: &str,
|
||||
argument: Option<(&str, &str)>,
|
||||
) -> Result<String, String> {
|
||||
let tool = tools::find(tool).ok_or_else(|| format!("no tool `{tool}`"))?;
|
||||
let mut arguments = Map::new();
|
||||
if let Some((name, value)) = argument {
|
||||
arguments.insert(name.to_string(), Value::from(value));
|
||||
}
|
||||
let args = tools::validate(tool, arguments)?;
|
||||
(tool.handler)(project, &args).map(|answer| answer.text)
|
||||
}
|
||||
|
||||
/// `%XX` escapes decoded; `None` for a malformed escape, an empty result or
|
||||
/// bytes that are not UTF-8.
|
||||
fn decoded(text: &str) -> Option<String> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut at = 0;
|
||||
while at < bytes.len() {
|
||||
if bytes[at] == b'%' {
|
||||
let hex = text.get(at + 1..at + 3)?;
|
||||
out.push(u8::from_str_radix(hex, 16).ok()?);
|
||||
at += 3;
|
||||
} else {
|
||||
out.push(bytes[at]);
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).ok().filter(|decoded| !decoded.is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parsed(uri: &str) -> Option<String> {
|
||||
Resource::parse(uri).map(|resource| match resource {
|
||||
Resource::Overview => "overview".into(),
|
||||
Resource::Rules => "rules".into(),
|
||||
Resource::Unit(name) => format!("unit {name}"),
|
||||
Resource::Outline(path) => format!("outline {path}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uris_name_their_resource_and_nothing_else_does() {
|
||||
assert_eq!(parsed("lucisv://overview").as_deref(), Some("overview"));
|
||||
assert_eq!(parsed("lucisv://rules").as_deref(), Some("rules"));
|
||||
assert_eq!(parsed("lucisv://unit/leaf").as_deref(), Some("unit leaf"));
|
||||
assert_eq!(parsed("lucisv://unit/%5Cmy-mod%20").as_deref(), Some("unit \\my-mod "));
|
||||
assert_eq!(
|
||||
parsed("lucisv://file/rtl/top.sv/outline").as_deref(),
|
||||
Some("outline rtl/top.sv")
|
||||
);
|
||||
for other in [
|
||||
"lucisv://unit/",
|
||||
"lucisv://unit/%zz",
|
||||
"lucisv://file/rtl/top.sv",
|
||||
"lucisv://file//outline",
|
||||
"file:///etc/passwd",
|
||||
"lucisv://overview/x",
|
||||
] {
|
||||
assert!(parsed(other).is_none(), "{other}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! The JSON-RPC 2.0 envelope and the MCP methods this server answers: the
|
||||
//! `initialize` handshake and its version negotiation, `ping`, the tool
|
||||
//! methods, the `lucisv://` resources, and an empty prompt list.
|
||||
//!
|
||||
//! One synchronous loop, like `lucisv-server`: a request is answered before
|
||||
//! the next line is read, so pipelined requests are answered in order.
|
||||
|
||||
use std::io;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::resources::{self, Resource};
|
||||
use crate::tools;
|
||||
use crate::transport::{Line, Transport};
|
||||
use crate::Options;
|
||||
|
||||
/// The protocol revisions this server speaks, newest first. All are the
|
||||
/// handshake-based ("legacy") era: from `2026-07-28` on, MCP carries the
|
||||
/// version on every request instead of negotiating it in `initialize`, and a
|
||||
/// server of that era is a different server (feature README, Assumptions).
|
||||
pub const PROTOCOL_VERSIONS: &[&str] = &[NEWEST, "2025-06-18"];
|
||||
|
||||
/// What a client asking for a revision we do not speak is offered.
|
||||
const NEWEST: &str = "2025-11-25";
|
||||
|
||||
/// JSON-RPC's own error codes, and the one MCP (after LSP) adds.
|
||||
const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
const METHOD_NOT_FOUND: i64 = -32601;
|
||||
const INVALID_PARAMS: i64 = -32602;
|
||||
const NOT_INITIALIZED: i64 = -32002;
|
||||
/// MCP's "resource not found".
|
||||
const RESOURCE_NOT_FOUND: i64 = -32002;
|
||||
|
||||
/// What the agent is told once, at `initialize`.
|
||||
const INSTRUCTIONS: &str = "lucisv-mcp answers questions about the Verilog/SystemVerilog design under its roots, read from the files on disk (never from unsaved editor buffers). Prefer unit_interface for a module's parameters and ports, outline for what a file declares, and read_item for one module, function or always block over reading whole files; list_units and search_symbols find where things are declared. Paths in answers are relative to the root; lines and columns are 1-based.";
|
||||
|
||||
/// A JSON-RPC error object.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct RpcError {
|
||||
code: i64,
|
||||
message: String,
|
||||
}
|
||||
|
||||
fn fault(code: i64, message: impl Into<String>) -> RpcError {
|
||||
RpcError { code, message: message.into() }
|
||||
}
|
||||
|
||||
/// A response line: exactly one of `result` and `error`.
|
||||
#[derive(Serialize)]
|
||||
struct Response<'a> {
|
||||
jsonrpc: &'static str,
|
||||
id: &'a Value,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
result: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
error: Option<RpcError>,
|
||||
}
|
||||
|
||||
fn response(id: &Value, answer: Result<Value, RpcError>) -> Value {
|
||||
let (result, error) = match answer {
|
||||
Ok(result) => (Some(result), None),
|
||||
Err(error) => (None, Some(error)),
|
||||
};
|
||||
let response = Response { jsonrpc: "2.0", id, result, error };
|
||||
serde_json::to_value(response).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// One incoming line, classified.
|
||||
enum Message {
|
||||
Request {
|
||||
id: Value,
|
||||
method: String,
|
||||
params: Option<Value>,
|
||||
},
|
||||
Notification {
|
||||
method: String,
|
||||
},
|
||||
/// A response to a request we never send: logged, never answered.
|
||||
Response,
|
||||
/// Not a message this protocol has; answered `-32600` with this id.
|
||||
Invalid {
|
||||
id: Value,
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn classify(value: Value) -> Message {
|
||||
let Value::Object(mut object) = value else {
|
||||
return Message::Invalid {
|
||||
id: Value::Null,
|
||||
reason: "a message must be a JSON object".into(),
|
||||
};
|
||||
};
|
||||
let id = object.remove("id");
|
||||
let valid_id = id.as_ref().is_some_and(|id| id.is_string() || id.is_i64() || id.is_u64());
|
||||
// JSON-RPC 2.0 §5: an error answer carries the request's id whenever it
|
||||
// could be read, and `null` only when it could not.
|
||||
let readable_id = if valid_id { id.clone().unwrap_or(Value::Null) } else { Value::Null };
|
||||
if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
|
||||
return Message::Invalid { id: readable_id, reason: "`jsonrpc` must be \"2.0\"".into() };
|
||||
}
|
||||
let Some(method) = object.get("method").and_then(Value::as_str).map(str::to_string) else {
|
||||
if object.contains_key("result") || object.contains_key("error") {
|
||||
return Message::Response;
|
||||
}
|
||||
return Message::Invalid {
|
||||
id: readable_id,
|
||||
reason: "a message needs a string `method`".into(),
|
||||
};
|
||||
};
|
||||
match id {
|
||||
None => Message::Notification { method },
|
||||
Some(id) if valid_id => Message::Request { id, method, params: object.remove("params") },
|
||||
Some(_) => Message::Invalid {
|
||||
id: Value::Null,
|
||||
reason: "`id` must be a string or an integer".into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The server's state across messages.
|
||||
pub struct Server {
|
||||
options: Options,
|
||||
version: Option<&'static str>,
|
||||
project: Option<Project>,
|
||||
}
|
||||
|
||||
/// Run the loop over stdin/stdout until the client closes stdin.
|
||||
/// `options.roots` must already be canonical (`project::canonical_roots`).
|
||||
pub fn serve(options: Options) -> Result<(), String> {
|
||||
let mut transport = Transport::new(io::stdin().lock(), io::stdout().lock());
|
||||
let mut server = Server { options, version: None, project: None };
|
||||
loop {
|
||||
let reply = match transport.read_line().map_err(|e| format!("reading stdin: {e}"))? {
|
||||
Line::Eof => return Ok(()),
|
||||
Line::NotUtf8 => {
|
||||
Some(response(&Value::Null, Err(fault(PARSE_ERROR, "the line is not UTF-8"))))
|
||||
}
|
||||
Line::Text(text) if text.trim().is_empty() => None,
|
||||
Line::Text(text) => server.handle_line(&text),
|
||||
};
|
||||
if let Some(reply) = reply {
|
||||
transport.write_message(&reply).map_err(|e| format!("writing stdout: {e}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Answer one line: `Some` response for a request or a malformed line,
|
||||
/// `None` for a notification or a stray response.
|
||||
pub fn handle_line(&mut self, text: &str) -> Option<Value> {
|
||||
let value: Value = match serde_json::from_str(text) {
|
||||
Ok(value) => value,
|
||||
Err(problem) => {
|
||||
return Some(response(
|
||||
&Value::Null,
|
||||
Err(fault(PARSE_ERROR, format!("parse error: {problem}"))),
|
||||
))
|
||||
}
|
||||
};
|
||||
match classify(value) {
|
||||
Message::Request { id, method, params } => {
|
||||
let started = Instant::now();
|
||||
let answer = self.request(&method, params);
|
||||
if self.options.verbose {
|
||||
eprintln!("lucisv-mcp: {method} {} ms", started.elapsed().as_millis());
|
||||
}
|
||||
Some(response(&id, answer))
|
||||
}
|
||||
Message::Notification { method } => {
|
||||
// `notifications/initialized` and `notifications/cancelled` are
|
||||
// accepted; every other notification is ignored, as the spec
|
||||
// allows. Cancellation cannot interrupt a synchronous call.
|
||||
if self.options.verbose {
|
||||
eprintln!("lucisv-mcp: notification {method}");
|
||||
}
|
||||
None
|
||||
}
|
||||
Message::Response => None,
|
||||
Message::Invalid { id, reason } => {
|
||||
Some(response(&id, Err(fault(INVALID_REQUEST, reason))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Option<Value>) -> Result<Value, RpcError> {
|
||||
match method {
|
||||
"initialize" => Ok(self.initialize(params.as_ref())),
|
||||
"ping" => Ok(json!({})),
|
||||
_ if self.version.is_none() => Err(fault(NOT_INITIALIZED, "server not initialized")),
|
||||
"tools/list" => Ok(tools::list()),
|
||||
"tools/call" => self.call_tool(params),
|
||||
"resources/list" => Ok(resources::list()),
|
||||
"resources/templates/list" => Ok(resources::templates()),
|
||||
"resources/read" => self.read_resource(params),
|
||||
"prompts/list" => Ok(json!({ "prompts": [] })),
|
||||
"prompts/get" => Err(fault(INVALID_PARAMS, "unknown prompt")),
|
||||
other => Err(fault(METHOD_NOT_FOUND, format!("method not found: {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The handshake: echo the client's revision when it is one we speak,
|
||||
/// else offer our newest and let the client decide.
|
||||
fn initialize(&mut self, params: Option<&Value>) -> Value {
|
||||
let asked = params.and_then(|p| p.get("protocolVersion")).and_then(Value::as_str);
|
||||
let version =
|
||||
PROTOCOL_VERSIONS.iter().find(|v| Some(**v) == asked).copied().unwrap_or(NEWEST);
|
||||
self.version = Some(version);
|
||||
json!({
|
||||
"protocolVersion": version,
|
||||
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
|
||||
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
|
||||
"instructions": INSTRUCTIONS,
|
||||
})
|
||||
}
|
||||
|
||||
/// `tools/call`: find the tool, check its arguments, bring the project up
|
||||
/// to the disk, run it. A refusal — including an argument that does not
|
||||
/// fit the schema — is a tool result with `isError`, so the agent reads
|
||||
/// the sentence and can correct itself; only an envelope the method
|
||||
/// cannot read at all, or a tool that does not exist, is a JSON-RPC error.
|
||||
fn call_tool(&mut self, params: Option<Value>) -> Result<Value, RpcError> {
|
||||
let Some(Value::Object(mut params)) = params else {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call params must be an object"));
|
||||
};
|
||||
let Some(Value::String(name)) = params.remove("name") else {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call params need a string `name`"));
|
||||
};
|
||||
let Some(tool) = tools::find(&name) else {
|
||||
return Err(fault(INVALID_PARAMS, format!("unknown tool: {name}")));
|
||||
};
|
||||
let arguments = match params.remove("arguments") {
|
||||
None | Some(Value::Null) => Map::new(),
|
||||
Some(Value::Object(arguments)) => arguments,
|
||||
Some(_) => {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call `arguments` must be an object"))
|
||||
}
|
||||
};
|
||||
let args = match tools::validate(tool, arguments) {
|
||||
Ok(args) => args,
|
||||
Err(refusal) => return Ok(tool_result(Err(refusal))),
|
||||
};
|
||||
let project = self.project(tool.rewalk);
|
||||
Ok(tool_result((tool.handler)(project, &args)))
|
||||
}
|
||||
|
||||
/// `resources/read`: a `lucisv://` URI answered from the project as it is
|
||||
/// on disk now; any other URI, or one naming nothing (a unit or file that
|
||||
/// does not exist), is `-32002` with the reason.
|
||||
fn read_resource(&mut self, params: Option<Value>) -> Result<Value, RpcError> {
|
||||
let Some(uri) = params.as_ref().and_then(|p| p.get("uri")).and_then(Value::as_str) else {
|
||||
return Err(fault(INVALID_PARAMS, "resources/read params need a string `uri`"));
|
||||
};
|
||||
let not_found =
|
||||
|why: &str| fault(RESOURCE_NOT_FOUND, format!("resource not found: {uri}{why}"));
|
||||
let Some(resource) = Resource::parse(uri) else {
|
||||
return Err(not_found(""));
|
||||
};
|
||||
let project = match resource.needs_project() {
|
||||
true => Some(self.project(resource.rewalk())),
|
||||
false => None,
|
||||
};
|
||||
resource.read(uri, project).map_err(|why| not_found(&format!(" ({why})")))
|
||||
}
|
||||
|
||||
/// The project, built on first use and brought up to the disk on every
|
||||
/// later one.
|
||||
fn project(&mut self, rewalk: bool) -> &mut Project {
|
||||
let options = &self.options;
|
||||
let existed = self.project.is_some();
|
||||
let project = self.project.get_or_insert_with(|| open_project(options));
|
||||
if existed {
|
||||
let refresh = project.refresh(rewalk);
|
||||
if options.verbose {
|
||||
eprintln!("lucisv-mcp: refresh {refresh:?}");
|
||||
}
|
||||
}
|
||||
project
|
||||
}
|
||||
}
|
||||
|
||||
/// Discover and index the project, saying on stderr how long it took.
|
||||
fn open_project(options: &Options) -> Project {
|
||||
let project = Project::open(options.roots.clone(), options.filelist.clone());
|
||||
let (build, _) = project.timing();
|
||||
eprintln!("lucisv-mcp: indexed {} files in {} ms", project.files().count(), build.as_millis());
|
||||
project
|
||||
}
|
||||
|
||||
/// A tool's answer as `tools/call` returns it.
|
||||
fn tool_result(answer: Result<tools::Answer, String>) -> Value {
|
||||
match answer {
|
||||
Ok(answer) => json!({
|
||||
"content": [{ "type": "text", "text": answer.text }],
|
||||
"structuredContent": answer.structured,
|
||||
"isError": false,
|
||||
}),
|
||||
Err(refusal) => json!({
|
||||
"content": [{ "type": "text", "text": refusal }],
|
||||
"isError": true,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn server() -> Server {
|
||||
Server { options: Options::default(), version: None, project: None }
|
||||
}
|
||||
|
||||
fn error_code(reply: &Value) -> i64 {
|
||||
reply["error"]["code"].as_i64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handshake_echoes_a_known_revision_and_offers_the_newest_otherwise() {
|
||||
let mut s = server();
|
||||
let reply = s
|
||||
.handle_line(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(reply["result"]["protocolVersion"], "2025-06-18");
|
||||
assert_eq!(reply["result"]["serverInfo"]["name"], "lucisv-mcp");
|
||||
let reply = s
|
||||
.handle_line(r#"{"jsonrpc":"2.0","id":"a","method":"initialize","params":{"protocolVersion":"2026-07-28"}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(reply["result"]["protocolVersion"], NEWEST);
|
||||
assert_eq!(reply["id"], "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_lines_are_answered_with_the_right_code_and_never_crash() {
|
||||
let mut s = server();
|
||||
let reply = s.handle_line("not json").unwrap();
|
||||
assert_eq!((error_code(&reply), reply["id"].clone()), (PARSE_ERROR, Value::Null));
|
||||
assert_eq!(error_code(&s.handle_line("[1,2]").unwrap()), INVALID_REQUEST);
|
||||
assert_eq!(
|
||||
error_code(&s.handle_line(r#"{"jsonrpc":"1.0","id":1,"method":"ping"}"#).unwrap()),
|
||||
INVALID_REQUEST
|
||||
);
|
||||
let null_id = s.handle_line(r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#).unwrap();
|
||||
assert_eq!(error_code(&null_id), INVALID_REQUEST);
|
||||
assert!(s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/cancelled"}"#).is_none());
|
||||
assert!(s.handle_line(r#"{"jsonrpc":"2.0","id":7,"result":{}}"#).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_before_initialize_are_refused_except_ping() {
|
||||
let mut s = server();
|
||||
let ping = s.handle_line(r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#).unwrap();
|
||||
assert_eq!(ping["result"], json!({}));
|
||||
let early = s.handle_line(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#).unwrap();
|
||||
assert_eq!(error_code(&early), NOT_INITIALIZED);
|
||||
s.handle_line(r#"{"jsonrpc":"2.0","id":3,"method":"initialize","params":{}}"#);
|
||||
let unknown = s.handle_line(r#"{"jsonrpc":"2.0","id":4,"method":"sampling/x"}"#).unwrap();
|
||||
assert_eq!(error_code(&unknown), METHOD_NOT_FOUND);
|
||||
let bad_tool = s
|
||||
.handle_line(
|
||||
r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nope"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(error_code(&bad_tool), INVALID_PARAMS);
|
||||
assert!(bad_tool["error"]["message"].as_str().unwrap().contains("nope"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! `defines`: the `` `define`` table — one file's, one macro's every
|
||||
//! definition across the project, or the whole project's — without reading
|
||||
//! the files. Bookkeeping only, like `vlog_parser::defines`: nothing here
|
||||
//! expands a macro (the README says why the one-step expansion is not
|
||||
//! offered).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::defines::{Define, DefineKind};
|
||||
|
||||
use super::source::{self, Texts};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
/// A body longer than this many characters is cut, with `…`.
|
||||
const BODY_CAP: usize = 200;
|
||||
|
||||
pub const DEFINES: Tool = Tool {
|
||||
name: "defines",
|
||||
title: "Macro definitions",
|
||||
description: "The `define table: name, parameters, body (on one line) and file:line — of one `file`, of one macro `name` across the project (every definition; which one a use sees depends on include order, so none is picked), or of the whole project. Prefer it over grepping for `define.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Only this file's table (its `undef`s included), relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Only this macro, written with or without the backtick.",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most entries to return (default 200).",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Entries to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: defines,
|
||||
};
|
||||
|
||||
/// One table row, ready to render.
|
||||
struct Row {
|
||||
file: String,
|
||||
line: u32,
|
||||
define: Define,
|
||||
}
|
||||
|
||||
fn defines(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").map(|name| name.trim_start_matches('`')).filter(|n| !n.is_empty());
|
||||
let (rows, rest, total) = match args.str("file") {
|
||||
Some(file) => in_file(project, file, name, args)?,
|
||||
None => {
|
||||
let mut all = indexed(project, name);
|
||||
if all.is_empty() && name.is_some() && project.ensure_walked_for_miss() {
|
||||
all = indexed(project, name);
|
||||
}
|
||||
let (shown, rest) =
|
||||
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
(rows_of(project, shown), rest, all.len())
|
||||
}
|
||||
};
|
||||
let entries: Vec<(String, String)> = rows
|
||||
.iter()
|
||||
.map(|row| (row.file.clone(), format!("{} {}", row.line, spelled(&row.define))))
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if total == 0 {
|
||||
text = "no defines\n".to_string();
|
||||
}
|
||||
let listed: Vec<Value> = rows.iter().map(row_json).collect();
|
||||
Ok(Answer { text, structured: json!({ "defines": listed, "total": total }) })
|
||||
}
|
||||
|
||||
/// One file's table as it is on disk now, filtered by `name`.
|
||||
fn in_file(
|
||||
project: &mut Project,
|
||||
file: &str,
|
||||
name: Option<&str>,
|
||||
args: &Args,
|
||||
) -> Result<(Vec<Row>, usize, usize), String> {
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let shown_file = project.relative(&path);
|
||||
let all: Vec<&Define> = analysis
|
||||
.defines
|
||||
.entries()
|
||||
.iter()
|
||||
.filter(|define| name.is_none_or(|name| define.name == name))
|
||||
.collect();
|
||||
let (shown, rest) =
|
||||
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let rows = shown
|
||||
.iter()
|
||||
.map(|define| Row {
|
||||
file: shown_file.clone(),
|
||||
line: analysis.lines.line_col(define.span.start).0,
|
||||
define: (*define).clone(),
|
||||
})
|
||||
.collect();
|
||||
Ok((rows, rest, all.len()))
|
||||
}
|
||||
|
||||
/// Every indexed definition (of `name`, when given), in file order.
|
||||
fn indexed(project: &Project, name: Option<&str>) -> Vec<(PathBuf, Define)> {
|
||||
let index = project.index();
|
||||
let of =
|
||||
|file, define: &Define| index.path(file).map(|path| (path.to_path_buf(), define.clone()));
|
||||
match name {
|
||||
Some(name) => index.find_define(name).into_iter().filter_map(|(f, d)| of(f, d)).collect(),
|
||||
None => (0..index.files().len() as u32)
|
||||
.map(vlog_semantic::FileId)
|
||||
.flat_map(|file| {
|
||||
let entries = index.defines(file).map(|table| table.entries()).unwrap_or(&[]);
|
||||
entries
|
||||
.iter()
|
||||
.filter(|d| d.kind == DefineKind::Define)
|
||||
.filter_map(move |d| of(file, d))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows for indexed definitions, each line read off its file now; a
|
||||
/// definition whose file no longer spells its name there is omitted.
|
||||
fn rows_of(project: &Project, shown: &[(PathBuf, Define)]) -> Vec<Row> {
|
||||
let mut texts = Texts::default();
|
||||
shown
|
||||
.iter()
|
||||
.filter_map(|(path, define)| {
|
||||
let line = checked_line(&mut texts, path, define)?;
|
||||
Some(Row { file: project.relative(path), line, define: define.clone() })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_line(texts: &mut Texts, path: &Path, define: &Define) -> Option<u32> {
|
||||
let (text, lines) = texts.get(path)?;
|
||||
let spelled = text.get(define.name_span.as_range())?;
|
||||
(spelled == define.name).then(|| lines.line_col(define.span.start).0)
|
||||
}
|
||||
|
||||
/// A definition as one line: `` `define NAME(a, b) body``, the body capped.
|
||||
fn spelled(define: &Define) -> String {
|
||||
if define.kind == DefineKind::Undef {
|
||||
return format!("`undef {}", define.name);
|
||||
}
|
||||
let mut out = format!("`define {}", define.name);
|
||||
if let Some(params) = &define.params {
|
||||
out.push_str(&format!("({})", params.join(", ")));
|
||||
}
|
||||
let body = source::capped(&define.body, BODY_CAP);
|
||||
if !body.is_empty() {
|
||||
out.push(' ');
|
||||
out.push_str(&body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn row_json(row: &Row) -> Value {
|
||||
let define = &row.define;
|
||||
json!({
|
||||
"file": row.file,
|
||||
"line": row.line,
|
||||
"name": define.name,
|
||||
"kind": if define.kind == DefineKind::Undef { "undef" } else { "define" },
|
||||
"params": define.params,
|
||||
"body": source::capped(&define.body, BODY_CAP),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::defines::collect_defines;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
fn table(text: &str) -> Vec<Define> {
|
||||
collect_defines(&tokenize(text).unwrap()).entries().to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_definition_is_spelled_on_one_line_with_its_parameters() {
|
||||
let all = table("`define ADD(a, b = 1) \\\n ((a) + (b))\n`define W 8\n`undef W\n");
|
||||
assert_eq!(spelled(&all[0]), "`define ADD(a, b = 1) ((a) + (b))");
|
||||
assert_eq!(spelled(&all[1]), "`define W 8");
|
||||
assert_eq!(spelled(&all[2]), "`undef W");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_body_is_cut_at_the_cap() {
|
||||
let body = "x ".repeat(300);
|
||||
let cut = source::capped(&body, BODY_CAP);
|
||||
assert_eq!(cut.chars().count(), BODY_CAP + 1);
|
||||
assert!(cut.ends_with('…'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
//! `diagnostics`: what `lucisv check` would say about one file or the whole
|
||||
//! project — the tolerant parse's errors first, then the lint findings —
|
||||
//! with the CLI's JSON field names, so one contract serves CI and agents.
|
||||
//!
|
||||
//! The lint run is the CLI's, rung for rung: the `lucisv.toml` governing each
|
||||
//! file (`Discovery::for_file`) gives `[lint] select`/`ignore`, the
|
||||
//! `[lint.<rule>]` options, the external `waivers` and the formatter's line
|
||||
//! length; the `rules` argument replaces `select` as `--select` does; the
|
||||
//! workspace rules run, their questions answered by the project index
|
||||
//! ([`Mentions`]). Missing-closer warnings are the language server's own
|
||||
//! (`pairs.rs`, not a library) and are not offered.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use serde_json::{json, Value};
|
||||
use vlog_linter::{
|
||||
lint_with, select_rules, Exports, ExternalWaivers, LintContext, MentionOracle, ModuleInterface,
|
||||
Rule, RuleOptions, Violation, WaiverUse,
|
||||
};
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_semantic::{FileId, PackageExports, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
pub const DIAGNOSTICS: Tool = Tool {
|
||||
name: "diagnostics",
|
||||
title: "Diagnostics",
|
||||
description: "Parse errors and lint findings for one `file`, or for every indexed file, grouped by file as `line:col severity message [rule]` — what `lucisv check` over the whole tree reports (cross-file rules on), under the project's lucisv.toml [lint] settings and waivers. Filter with `rules` (like --select) and `severity`. The whole-project form lints every file and returns the first `limit` findings with the total.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "One file, relative to a root or absolute inside one (default: every indexed file).",
|
||||
},
|
||||
Param {
|
||||
name: "rules",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Comma-separated rule names or severities to run instead of the configured set, like `--select`.",
|
||||
},
|
||||
Param {
|
||||
name: "severity",
|
||||
ty: Ty::Enum(&["error", "warning", "style"]),
|
||||
required: false,
|
||||
description: "Only findings of this severity (parse errors are `error`).",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most findings to return (default 200).",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Findings to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: diagnostics,
|
||||
};
|
||||
|
||||
/// One finding, in the CLI's JSON shape.
|
||||
struct Finding {
|
||||
file: String,
|
||||
rule: String,
|
||||
severity: &'static str,
|
||||
message: String,
|
||||
start: (u32, u32),
|
||||
end: (u32, u32),
|
||||
range: (u32, u32),
|
||||
fix: Value,
|
||||
}
|
||||
|
||||
/// What one config file makes of a lint run.
|
||||
pub(super) struct Run {
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
options: RuleOptions,
|
||||
waivers: ExternalWaivers,
|
||||
line_length: usize,
|
||||
tab_width: usize,
|
||||
/// Which external waivers fired, over every file this run linted.
|
||||
used: RefCell<WaiverUse>,
|
||||
}
|
||||
|
||||
fn diagnostics(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let selected: Option<Vec<String>> = args.str("rules").map(|rules| {
|
||||
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
|
||||
});
|
||||
let mut runs = Runs::new(selected);
|
||||
let mut findings = Vec::new();
|
||||
match args.str("file") {
|
||||
Some(file) => {
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let own = project.index().file_id(&path);
|
||||
let oracle = Mentions::of_file(project.index(), own);
|
||||
findings = file_findings(project, &mut runs, &path, &analysis, &oracle)?;
|
||||
}
|
||||
None => {
|
||||
let census = Census::of(project.index());
|
||||
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
|
||||
for path in paths {
|
||||
let Ok(text) = std::fs::read_to_string(&path) else { continue };
|
||||
let analysis = Analysis::of(text);
|
||||
let own = project.index().file_id(&path);
|
||||
let oracle = Mentions { index: project.index(), census: Some(&census), own };
|
||||
findings.extend(file_findings(project, &mut runs, &path, &analysis, &oracle)?);
|
||||
}
|
||||
// Only a complete run knows a waiver matched nothing.
|
||||
findings.extend(runs.unused_waivers(project));
|
||||
}
|
||||
}
|
||||
if let Some(severity) = args.str("severity") {
|
||||
findings.retain(|finding| finding.severity == severity);
|
||||
}
|
||||
Ok(render_findings(&findings, args))
|
||||
}
|
||||
|
||||
/// The runs met so far in one call, one per governing config file — shared
|
||||
/// with `fix_lint`, so a fix runs under exactly the rules a finding came from.
|
||||
pub(super) struct Runs {
|
||||
discovery: Discovery,
|
||||
held: BTreeMap<Option<PathBuf>, Rc<Run>>,
|
||||
selected: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Runs {
|
||||
/// No run built yet; `selected` replaces each config's `[lint] select`.
|
||||
pub(super) fn new(selected: Option<Vec<String>>) -> Runs {
|
||||
Runs { discovery: Discovery::new(true), held: BTreeMap::new(), selected }
|
||||
}
|
||||
|
||||
/// The run for the config governing `path`, built on first use. A config
|
||||
/// that does not read, an unknown rule, a bad option or an unreadable
|
||||
/// waiver file is a refusal naming it — `lucisv check` fails the same way.
|
||||
pub(super) fn for_file(&mut self, path: &Path) -> Result<Rc<Run>, String> {
|
||||
let config = self.discovery.for_file(path)?;
|
||||
if let Some(run) = self.held.get(&config.source) {
|
||||
return Ok(Rc::clone(run));
|
||||
}
|
||||
let run = Rc::new(self.build(&config)?);
|
||||
self.held.insert(config.source.clone(), Rc::clone(&run));
|
||||
Ok(run)
|
||||
}
|
||||
|
||||
fn build(&self, config: &FileConfig) -> Result<Run, String> {
|
||||
let select = match &self.selected {
|
||||
Some(selected) => selected.clone(),
|
||||
None => config.lint_select.clone().unwrap_or_default(),
|
||||
};
|
||||
let ignore = config.lint_ignore.clone().unwrap_or_default();
|
||||
let rules = select_rules(&select, &ignore, true)?;
|
||||
let mut options = RuleOptions::new();
|
||||
for entry in &config.lint_options {
|
||||
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
|
||||
let file = config
|
||||
.source
|
||||
.as_ref()
|
||||
.map_or("lucisv.toml".into(), |p| p.display().to_string());
|
||||
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
|
||||
})?;
|
||||
}
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
for path in config.lint_waivers.iter().flatten() {
|
||||
let (file, problems) = ExternalWaivers::read(path)?;
|
||||
if let Some(problem) = problems.first() {
|
||||
return Err(problem.clone());
|
||||
}
|
||||
waivers.absorb(file);
|
||||
}
|
||||
let format = vlog_formatter::Config::default();
|
||||
Ok(Run {
|
||||
rules,
|
||||
options,
|
||||
waivers,
|
||||
line_length: config.line_length.unwrap_or(format.max_width),
|
||||
tab_width: config.indent.unwrap_or(format.indent_width),
|
||||
used: RefCell::new(WaiverUse::default()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Runs {
|
||||
/// One `unused-waiver` finding per external directive that suppressed
|
||||
/// nothing in any file its run linted — the CLI's end-of-run report.
|
||||
fn unused_waivers(&self, project: &Project) -> Vec<Finding> {
|
||||
let mut out = Vec::new();
|
||||
for run in self.held.values() {
|
||||
let enabled: Vec<&'static str> = run.rules.iter().map(|rule| rule.name()).collect();
|
||||
for report in run.waivers.unused(&run.used.borrow(), &enabled) {
|
||||
let lines = LineIndex::new(&report.text);
|
||||
let file = project.relative(&report.path);
|
||||
out.extend(report.violations.iter().map(|v| lint_finding(&file, &lines, v)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's findings: its parse errors, then its lint findings.
|
||||
fn file_findings(
|
||||
project: &Project,
|
||||
runs: &mut Runs,
|
||||
path: &Path,
|
||||
analysis: &Analysis,
|
||||
oracle: &Mentions,
|
||||
) -> Result<Vec<Finding>, String> {
|
||||
let file = project.relative(path);
|
||||
let run = runs.for_file(path)?;
|
||||
let mut out: Vec<Finding> = analysis
|
||||
.diagnostics
|
||||
.iter()
|
||||
.map(|error| Finding {
|
||||
file: file.clone(),
|
||||
rule: "parse-error".into(),
|
||||
severity: "error",
|
||||
message: error.message.clone(),
|
||||
start: (error.line, error.col),
|
||||
end: analysis.lines.line_col(error.span.end),
|
||||
range: (error.span.start, error.span.end),
|
||||
fix: Value::Null,
|
||||
})
|
||||
.collect();
|
||||
let violations = violations(&run, path, analysis, oracle);
|
||||
out.extend(violations.iter().map(|violation| lint_finding(&file, &analysis.lines, violation)));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One file's lint findings under `run`, its waivers applied.
|
||||
pub(super) fn violations(
|
||||
run: &Run,
|
||||
path: &Path,
|
||||
analysis: &Analysis,
|
||||
oracle: &Mentions,
|
||||
) -> Vec<Violation> {
|
||||
let ctx = LintContext::from_parse(
|
||||
&analysis.text,
|
||||
&analysis.tokens,
|
||||
&analysis.tree,
|
||||
&analysis.lines,
|
||||
Some(path.to_path_buf()),
|
||||
)
|
||||
.with_semantics(&analysis.semantics)
|
||||
.with_options(&run.options)
|
||||
.with_line_length(run.line_length)
|
||||
.with_tab_width(run.tab_width)
|
||||
.with_oracle(oracle);
|
||||
let (violations, used) = lint_with(&ctx, &run.rules, &run.waivers);
|
||||
run.used.borrow_mut().merge(&used);
|
||||
violations
|
||||
}
|
||||
|
||||
fn lint_finding(file: &str, lines: &LineIndex, violation: &Violation) -> Finding {
|
||||
let span = violation.span;
|
||||
let fix = violation.fix.as_ref().map_or(Value::Null, |fix| {
|
||||
let edits: Vec<Value> = fix
|
||||
.edits
|
||||
.iter()
|
||||
.map(|(range, content)| json!({"start": range.start, "end": range.end, "content": content}))
|
||||
.collect();
|
||||
json!({ "applicability": fix.applicability.as_str(), "edits": edits })
|
||||
});
|
||||
Finding {
|
||||
file: file.to_string(),
|
||||
rule: violation.rule.to_string(),
|
||||
severity: violation.severity.as_str(),
|
||||
message: violation.message.clone(),
|
||||
start: lines.line_col(span.start),
|
||||
end: lines.line_col(span.end),
|
||||
range: (span.start, span.end),
|
||||
fix,
|
||||
}
|
||||
}
|
||||
|
||||
/// Findings grouped by file, paged; the JSON is the CLI's array shape.
|
||||
fn render_findings(findings: &[Finding], args: &Args) -> Answer {
|
||||
let (shown, rest) =
|
||||
render::page(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = shown
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let line =
|
||||
format!("{}:{} {} {} [{}]", f.start.0, f.start.1, f.severity, f.message, f.rule);
|
||||
(f.file.clone(), line)
|
||||
})
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if findings.is_empty() {
|
||||
text = "no findings\n".to_string();
|
||||
}
|
||||
let listed: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|f| {
|
||||
json!({
|
||||
"filename": f.file, "rule": f.rule, "severity": f.severity, "message": f.message,
|
||||
"location": {"line": f.start.0, "column": f.start.1},
|
||||
"end_location": {"line": f.end.0, "column": f.end.1},
|
||||
"range": {"start": f.range.0, "end": f.range.1},
|
||||
"fix": f.fix,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Answer { text, structured: json!({ "diagnostics": listed, "total": findings.len() }) }
|
||||
}
|
||||
|
||||
/// How many files write each word, and the first of them — the whole-project
|
||||
/// form's answer to "does another file mention this", built once per call
|
||||
/// instead of walking every record per question.
|
||||
struct Census<'a> {
|
||||
words: HashMap<&'a str, (usize, FileId)>,
|
||||
}
|
||||
|
||||
impl<'a> Census<'a> {
|
||||
fn of(index: &'a WorkspaceIndex) -> Census<'a> {
|
||||
let mut words: HashMap<&'a str, (usize, FileId)> = HashMap::new();
|
||||
for (at, path) in index.files().iter().enumerate() {
|
||||
let Some(facts) = index.facts_for(path) else { continue };
|
||||
let file = FileId(at as u32);
|
||||
for word in facts.words() {
|
||||
words.entry(word.as_str()).or_insert((0, file)).0 += 1;
|
||||
}
|
||||
}
|
||||
Census { words }
|
||||
}
|
||||
|
||||
fn outside(&self, name: &str, own: Option<FileId>) -> bool {
|
||||
match self.words.get(name) {
|
||||
Some(&(count, first)) => count > 1 || Some(first) != own,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project index answering the linter's cross-file questions — the
|
||||
/// language server's `IndexMentions`, with the census when one was built.
|
||||
pub(super) struct Mentions<'a> {
|
||||
index: &'a WorkspaceIndex,
|
||||
census: Option<&'a Census<'a>>,
|
||||
/// The linted file itself, subtracted from "elsewhere".
|
||||
own: Option<FileId>,
|
||||
}
|
||||
|
||||
impl<'a> Mentions<'a> {
|
||||
/// The oracle for one file, asking the index per question.
|
||||
pub(super) fn of_file(index: &'a WorkspaceIndex, own: Option<FileId>) -> Mentions<'a> {
|
||||
Mentions { index, census: None, own }
|
||||
}
|
||||
}
|
||||
|
||||
impl MentionOracle for Mentions<'_> {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
match self.census {
|
||||
Some(census) => census.outside(name, self.own),
|
||||
None => self.index.mentioned_outside(name, self.own),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ports and overridable parameters of a module declared exactly once.
|
||||
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
|
||||
let [unit] = self.index.units(name) else { return None };
|
||||
if !unit.kind.is_instantiable() {
|
||||
return None;
|
||||
}
|
||||
let mut interface = ModuleInterface::default();
|
||||
for (member, defs) in self.index.members_of(name) {
|
||||
match defs.first().map(|def| def.kind) {
|
||||
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
|
||||
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(interface)
|
||||
}
|
||||
|
||||
fn package_exports(&self, package: &str) -> Exports {
|
||||
PackageExports::exports(self.index, package)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! The refactorings that act at one position — `rename`, and the six the
|
||||
//! editor offers as code actions at a cursor (`expand_wildcard`,
|
||||
//! `convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`,
|
||||
//! `remove_port`) — plus what every edit tool shares: the `dry_run`
|
||||
//! argument, the whole-set read the engines are handed, and the step from a
|
||||
//! verified `RefactorEdit` to `apply::run`.
|
||||
//!
|
||||
//! Each engine gets **every indexed file**, read from disk at call time
|
||||
//! (`source::WholeSet`, M2's ruling for `references`: a use can resolve
|
||||
//! through a file that never spells its name, so no narrowing is sound).
|
||||
//! The texts read are the texts the write-freshness rule compares against.
|
||||
//! A file the index skipped (over 1 MiB, not UTF-8) is never edited around:
|
||||
//! when its bytes spell a name the edit changes, the edit is refused;
|
||||
//! otherwise it is named under `warnings:` (QA finding 2).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::RefactorEdit;
|
||||
|
||||
use super::select::{target, Target};
|
||||
use super::source::WholeSet;
|
||||
use super::{nav, Answer, Args, Param, Tool, Ty};
|
||||
use crate::apply::{self, Plan};
|
||||
use crate::project::{Analysis, Project};
|
||||
|
||||
/// `dry_run`, which every edit tool takes.
|
||||
pub(super) const DRY_RUN: Param = Param {
|
||||
name: "dry_run",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Return the unified diff and write nothing (default false).",
|
||||
};
|
||||
|
||||
const FILE: Param = Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file holding the position, relative to a root or absolute inside one.",
|
||||
};
|
||||
const LINE: Param = Param {
|
||||
name: "line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based line in `file`; alone it means the line's first non-blank character.",
|
||||
};
|
||||
const COL: Param = Param {
|
||||
name: "col",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based column in bytes on `line`.",
|
||||
};
|
||||
const NAME: Param = Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The name written at the position: with `line`, its occurrence on that line; without, its occurrence in `file`.",
|
||||
};
|
||||
|
||||
/// The position arguments of the six cursor refactorings, then `dry_run`.
|
||||
const AT: &[Param] = &[FILE, LINE, COL, NAME, DRY_RUN];
|
||||
|
||||
/// One engine that acts at a position.
|
||||
type Engine = fn(&[(PathBuf, String)], &Path, u32) -> Result<RefactorEdit, String>;
|
||||
|
||||
/// The names an engine acting at a position changes — what a skipped file
|
||||
/// must not spell.
|
||||
type Stake = fn(&Analysis, u32) -> Vec<String>;
|
||||
|
||||
pub const EXPAND_WILDCARD: Tool = Tool {
|
||||
name: "expand_wildcard",
|
||||
title: "Expand .* connections",
|
||||
description: "Replace one instantiation's `.*` with the named connections it binds, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a `bind` instance, a positional list, and a port list whose binding depends on `ifdef`s, with the reason. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: expand_wildcard,
|
||||
};
|
||||
|
||||
pub const CONVERT_PORTS: Tool = Tool {
|
||||
name: "convert_ports",
|
||||
title: "Convert ports to ANSI",
|
||||
description: "Rewrite a module's non-ANSI header (`module m(a, b); input a; …`) as an ANSI port list, verified before anything is written. Point at the module: `file`+`line` (+`col`, or the module `name`). Refuses a header it cannot convert exactly, with the reason. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: convert_ports,
|
||||
};
|
||||
|
||||
pub const ORGANIZE_IMPORTS: Tool = Tool {
|
||||
name: "organize_imports",
|
||||
title: "Organize imports",
|
||||
description: "Remove the unused `import` items of the scope at a position and sort the rest, verified before anything is written. Point into the scope with `file`+`line`. Refuses where it cannot judge (a macro or `include` in the scope, an unknown package), with the reason. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: organize_imports,
|
||||
};
|
||||
|
||||
pub const INLINE_MODULE: Tool = Tool {
|
||||
name: "inline_module",
|
||||
title: "Inline a module instance",
|
||||
description: "Replace one instantiation with the body of the module it instantiates, its connections substituted, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses what it cannot substitute exactly, with the reason. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: inline_module,
|
||||
};
|
||||
|
||||
pub const PROPAGATE_PORTS: Tool = Tool {
|
||||
name: "propagate_ports",
|
||||
title: "Connect missing ports",
|
||||
description: "Add a named connection for every port one instantiation leaves unconnected, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a positional or `.*` list, and an instance that already connects every port. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: propagate_ports,
|
||||
};
|
||||
|
||||
pub const REMOVE_PORT: Tool = Tool {
|
||||
name: "remove_port",
|
||||
title: "Remove a port",
|
||||
description: "Delete one module port and its connection from every instantiation in the project, verified before anything is written. Point at the port: `file`+`line` (+`col`, or the port `name`). Refuses a port the body still uses, a positional instantiation, and a deletion that would drop a comment. `dry_run` returns the diff.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: remove_port,
|
||||
};
|
||||
|
||||
pub const RENAME: Tool = Tool {
|
||||
name: "rename",
|
||||
title: "Rename a symbol",
|
||||
description: "Rename one declaration and every reference to it across the project, verified before anything is written. Select as for `definition`: `file`+`line`+`col`, `file`+`line`+`name`, `file`+`name`, or `name` (+`unit`). Refuses an invalid or clashing name and a use it cannot account for; a name already `new_name` is `unchanged`. A `.*` or `.name` connection that bound the renamed name is written out explicitly (listed in `warnings`).",
|
||||
params: &[
|
||||
Param { required: false, ..FILE },
|
||||
Param {
|
||||
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
|
||||
..LINE
|
||||
},
|
||||
COL,
|
||||
Param {
|
||||
description: "The name to rename: alone, looked up across the project; with `file`, its occurrence there; with `file` and `line`, its occurrence on that line.",
|
||||
..NAME
|
||||
},
|
||||
Param {
|
||||
name: "unit",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "With a bare `name`: the module, interface, package or class declaring it.",
|
||||
},
|
||||
Param {
|
||||
name: "new_name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The new name.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: true,
|
||||
handler: rename,
|
||||
};
|
||||
|
||||
fn expand_wildcard(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated)
|
||||
}
|
||||
|
||||
fn convert_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::convert_to_ansi, enclosing)
|
||||
}
|
||||
|
||||
fn organize_imports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
// Only the file's own `import` items change; nothing another file spells.
|
||||
at_cursor(project, args, vlog_refactor::organize_imports, |_, _| Vec::new())
|
||||
}
|
||||
|
||||
fn inline_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::inline_module, instantiated)
|
||||
}
|
||||
|
||||
fn propagate_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::propagate_ports, instantiated)
|
||||
}
|
||||
|
||||
fn remove_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let port_and_module = |analysis: &Analysis, offset: u32| {
|
||||
let mut names = name_at(analysis, offset);
|
||||
names.extend(instantiated(analysis, offset));
|
||||
names
|
||||
};
|
||||
at_cursor(project, args, vlog_refactor::remove_port, port_and_module)
|
||||
}
|
||||
|
||||
/// The declared name at a position.
|
||||
fn name_at(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::rename_name_at(&analysis.semantics, offset).into_iter().collect()
|
||||
}
|
||||
|
||||
/// The module an instantiation at a position names, or whose port it is on.
|
||||
fn instantiated(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::port_action_modules_in(&analysis.tree, offset)
|
||||
}
|
||||
|
||||
/// The module whose declaration covers a position.
|
||||
pub(super) fn enclosing(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::enclosing_module(&analysis.text, offset).into_iter().collect()
|
||||
}
|
||||
|
||||
/// Run `engine` at the position the arguments name, over the whole set.
|
||||
fn at_cursor(
|
||||
project: &mut Project,
|
||||
args: &Args,
|
||||
engine: Engine,
|
||||
stake: Stake,
|
||||
) -> Result<Answer, String> {
|
||||
let (path, offset) = cursor(project, args)?;
|
||||
let names = stake(&*project.analysis(&path)?, offset);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = engine(&set.files, &path, offset)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
|
||||
/// The position a cursor refactoring acts at: `file` + `line` alone is the
|
||||
/// line's first non-blank byte; anything else is `definition`'s selector,
|
||||
/// which must name a file.
|
||||
fn cursor(project: &mut Project, args: &Args) -> Result<(PathBuf, u32), String> {
|
||||
if let (Some(file), Some(line), None, None) =
|
||||
(args.str("file"), args.int("line"), args.int("col"), args.str("name"))
|
||||
{
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let line = u32::try_from(line).unwrap_or(u32::MAX);
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
let count = analysis.lines.line_count();
|
||||
return Err(format!("line {line} is past the end ({count} lines) (in `{file}`)"));
|
||||
};
|
||||
let text = analysis.line_text(line);
|
||||
let blank = text.len() - text.trim_start().len();
|
||||
return Ok((path, range.start + blank as u32));
|
||||
}
|
||||
match target(project, args)? {
|
||||
Target::At { path, offset, .. } => Ok((path, offset)),
|
||||
Target::Named { .. } => Err("give the `file` the position is in.".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole set an engine is handed — refused when a file the index
|
||||
/// skipped spells one of `names`, since the edit could not reach it.
|
||||
pub(super) fn whole_set(
|
||||
project: &Project,
|
||||
extra: Option<&Path>,
|
||||
names: &[String],
|
||||
) -> Result<WholeSet, String> {
|
||||
let set = WholeSet::read(project, extra);
|
||||
if let Some((path, why, name)) = set.mentioning(names) {
|
||||
return Err(format!(
|
||||
"`{}` (skipped: {why}) may reference `{name}`; lucisv-mcp will not edit around a file it cannot index; nothing written.",
|
||||
project.relative(path)
|
||||
));
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// A verified edit over the set's texts, diffed or written; the files the
|
||||
/// set left out are named under `warnings:`.
|
||||
pub(super) fn finish(
|
||||
project: &Project,
|
||||
edit: RefactorEdit,
|
||||
set: &WholeSet,
|
||||
args: &Args,
|
||||
) -> Result<Answer, String> {
|
||||
let mut plan = Plan::from_refactor(edit, &set.files)?;
|
||||
plan.warnings.extend(set.warning(project));
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
}
|
||||
|
||||
fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let new_name = args.str("new_name").unwrap_or_default();
|
||||
let (path, offset) = match target(project, args)? {
|
||||
Target::At { path, offset, .. } => (path, offset),
|
||||
Target::Named { name, unit } => nav::declaration_position(project, &name, unit.as_deref())?,
|
||||
};
|
||||
let names = name_at(&*project.analysis(&path)?, offset);
|
||||
// Already renamed: a second identical call is a no-op, not a refusal.
|
||||
if names.first().map(String::as_str) == Some(new_name) {
|
||||
return apply::run(project, Plan::default(), args.flag("dry_run", false));
|
||||
}
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = vlog_refactor::rename(&set.files, &path, offset, new_name)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//! `format` and `fix_lint`: the CLI's `lucisv format` and `lucisv check
|
||||
//! --fix`, per file, through the one write path (`apply.rs`).
|
||||
//!
|
||||
//! `format` is `format_source` (or `format_range` for `lines`) under the
|
||||
//! `lucisv.toml` governing each file — the formatter's own safety net decides,
|
||||
//! and a refusal names the file and writes nothing anywhere. `fix_lint` runs
|
||||
//! the lint pass `diagnostics` runs (the same config ladder, waivers and
|
||||
//! cross-file oracle), applies the **safe** fixes whose edits stay out of
|
||||
//! every `// lucisv: off` fence — the CLI's `--fix` filter — until the file
|
||||
//! stops changing, and refuses a result that parses worse than the input.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::panic::{catch_unwind, AssertUnwindSafe};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
use vlog_linter::{apply_fixes, Fix, Violation};
|
||||
|
||||
use super::diagnostics::{violations, Mentions, Runs};
|
||||
use super::edit::DRY_RUN;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::apply::{self, Change, Plan};
|
||||
use crate::project::{Analysis, Project};
|
||||
|
||||
/// How many fix-then-relint rounds one file gets — the CLI's cap, for the
|
||||
/// CLI's reason: two overlapping fixes land in successive rounds.
|
||||
const MAX_FIX_ROUNDS: usize = 10;
|
||||
|
||||
const FILE: Param = Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "One file, relative to a root or absolute inside one.",
|
||||
};
|
||||
const FILES: Param = Param {
|
||||
name: "files",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Several files, comma-separated, instead of `file`.",
|
||||
};
|
||||
|
||||
pub const FORMAT: Tool = Tool {
|
||||
name: "format",
|
||||
title: "Format files",
|
||||
description: "Format `file` (or the comma-separated `files`) as `lucisv format` does, under each file's lucisv.toml; `lines` (`12-40,55`, one file only) formats just the constructs meeting those lines. The formatter verifies its own output: a file it will not format safely refuses the whole call, naming it. An already formatted file is `unchanged`. `dry_run` returns the diff.",
|
||||
params: &[
|
||||
FILE,
|
||||
FILES,
|
||||
Param {
|
||||
name: "lines",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "1-based line ranges such as `12-40,55`; only with a single file.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: format,
|
||||
};
|
||||
|
||||
pub const FIX_LINT: Tool = Tool {
|
||||
name: "fix_lint",
|
||||
title: "Apply safe lint fixes",
|
||||
description: "Apply the safe automatic fixes of the lint findings in `file` (or the comma-separated `files`), as `lucisv check --fix` does: the project's [lint] config and waivers, never inside a `// lucisv: off` fence, never an unsafe fix. Reports which rules were fixed and how many findings remain (`diagnostics` lists them). `rules` narrows the run like --select. `dry_run` returns the diff.",
|
||||
params: &[
|
||||
FILE,
|
||||
FILES,
|
||||
Param {
|
||||
name: "rules",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Comma-separated rule names or severities to fix instead of the configured set.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: fix_lint,
|
||||
};
|
||||
|
||||
/// The files a call names, resolved, each once, in the order given.
|
||||
fn named_files(project: &Project, args: &Args) -> Result<Vec<PathBuf>, String> {
|
||||
let given: Vec<&str> = match (args.str("file"), args.str("files")) {
|
||||
(Some(_), Some(_)) => return Err("give `file` or `files`, not both.".into()),
|
||||
(Some(file), None) => vec![file],
|
||||
(None, Some(files)) => files.split(',').map(str::trim).filter(|f| !f.is_empty()).collect(),
|
||||
(None, None) => return Err("give a `file`, or comma-separated `files`.".into()),
|
||||
};
|
||||
if given.is_empty() {
|
||||
return Err("`files` names no file.".into());
|
||||
}
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for file in given {
|
||||
let path = project.resolve(file)?;
|
||||
if !out.contains(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A file's text as it is on disk now.
|
||||
fn read(project: &Project, path: &Path) -> Result<String, String> {
|
||||
std::fs::read_to_string(path)
|
||||
.map_err(|e| format!("cannot read `{}`: {e}", project.relative(path)))
|
||||
}
|
||||
|
||||
fn format(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let paths = named_files(project, args)?;
|
||||
let lines = match args.str("lines") {
|
||||
None => None,
|
||||
Some(_) if paths.len() > 1 => return Err("`lines` needs a single file.".into()),
|
||||
Some(spec) => Some(LineRanges::parse(spec).map_err(|e| format!("`lines`: {e}"))?),
|
||||
};
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut plan = Plan::default();
|
||||
for path in paths {
|
||||
let before = read(project, &path)?;
|
||||
let config = formatter_config(&discovery.for_file(&path)?);
|
||||
let after = formatted(&before, &config, lines.as_ref()).map_err(|why| {
|
||||
format!("`{}` was not formatted: {why}; nothing written.", project.relative(&path))
|
||||
})?;
|
||||
plan.changes.push(Change { path, before, after, created: false });
|
||||
}
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
}
|
||||
|
||||
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
|
||||
/// `Options::config_with` with no command-line flags.
|
||||
fn formatter_config(file: &FileConfig) -> Config {
|
||||
let mut config = Config::default();
|
||||
if let Some(width) = file.line_length {
|
||||
config.max_width = width;
|
||||
}
|
||||
if let Some(indent) = file.indent {
|
||||
config.indent_width = indent;
|
||||
}
|
||||
if let Some(on) = file.format_uvm_utils_indent {
|
||||
config.uvm_utils_indent = on;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// Format one text; a formatter panic is an error like any other, never the
|
||||
/// end of the server.
|
||||
fn formatted(text: &str, config: &Config, lines: Option<&LineRanges>) -> Result<String, String> {
|
||||
let run = catch_unwind(AssertUnwindSafe(|| match lines {
|
||||
Some(lines) => format_range(text, config, lines),
|
||||
None => format_source(text, config),
|
||||
}));
|
||||
match run {
|
||||
Ok(Ok(out)) => Ok(out),
|
||||
Ok(Err(e)) => Err(e.to_string()),
|
||||
Err(_) => Err("the formatter panicked".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn fix_lint(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let paths = named_files(project, args)?;
|
||||
let selected: Option<Vec<String>> = args.str("rules").map(|rules| {
|
||||
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
|
||||
});
|
||||
let mut runs = Runs::new(selected);
|
||||
let mut plan = Plan::default();
|
||||
let mut fixed: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
let mut left = 0;
|
||||
for path in paths {
|
||||
let before = read(project, &path)?;
|
||||
let outcome = fix_file(project, &mut runs, &path, &before)?;
|
||||
for (rule, count) in outcome.fixed {
|
||||
*fixed.entry(rule).or_default() += count;
|
||||
}
|
||||
left += outcome.left;
|
||||
plan.changes.push(Change { path, before, after: outcome.text, created: false });
|
||||
}
|
||||
plan.note = Some(fixed_note(&fixed, left));
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
}
|
||||
|
||||
/// What fixing one file came to.
|
||||
struct Fixed {
|
||||
text: String,
|
||||
/// Per rule, how many of its findings the fixes removed.
|
||||
fixed: BTreeMap<&'static str, usize>,
|
||||
/// Findings still reported after the last round.
|
||||
left: usize,
|
||||
}
|
||||
|
||||
/// Fix, re-lint, repeat until nothing more applies; refuse a result whose
|
||||
/// tolerant parse reports more errors than the input's did.
|
||||
fn fix_file(
|
||||
project: &Project,
|
||||
runs: &mut Runs,
|
||||
path: &Path,
|
||||
before: &str,
|
||||
) -> Result<Fixed, String> {
|
||||
let run = runs.for_file(path)?;
|
||||
let oracle = Mentions::of_file(project.index(), project.index().file_id(path));
|
||||
let first = Analysis::of(before.to_string());
|
||||
let errors_before = first.diagnostics.len();
|
||||
let found = violations(&run, path, &first, &oracle);
|
||||
let mut remaining = found.clone();
|
||||
let mut text = before.to_string();
|
||||
let mut errors_after = errors_before;
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round = apply_fixes(&text, &outside_fences(&text, &remaining), false);
|
||||
if round.applied == 0 {
|
||||
break;
|
||||
}
|
||||
text = round.output;
|
||||
let analysis = Analysis::of(text.clone());
|
||||
errors_after = analysis.diagnostics.len();
|
||||
remaining = violations(&run, path, &analysis, &oracle);
|
||||
}
|
||||
if errors_after > errors_before {
|
||||
return Err(format!(
|
||||
"fixing `{}` would leave it with {errors_after} parse errors where it had {errors_before}; nothing written.",
|
||||
project.relative(path)
|
||||
));
|
||||
}
|
||||
let fixed = removed_per_rule(&found, &remaining);
|
||||
Ok(Fixed { text, fixed, left: remaining.len() })
|
||||
}
|
||||
|
||||
/// The findings whose fix may be applied: those whose every edit stays out
|
||||
/// of the fenced regions — the CLI's `fixable_outside_fences`, over
|
||||
/// `fence::protected_regions`, the one answer to which bytes are fenced.
|
||||
fn outside_fences(text: &str, found: &[Violation]) -> Vec<Violation> {
|
||||
let regions = fence::protected_regions(text);
|
||||
found
|
||||
.iter()
|
||||
.filter(|v| v.fix.as_ref().is_some_and(|fix| !touches_fence(fix, ®ions)))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
fix.edits
|
||||
.iter()
|
||||
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
|
||||
}
|
||||
|
||||
/// Per rule, how many fewer findings the fixed text has.
|
||||
fn removed_per_rule(before: &[Violation], after: &[Violation]) -> BTreeMap<&'static str, usize> {
|
||||
let count = |found: &[Violation]| {
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
found.iter().for_each(|v| *counts.entry(v.rule).or_default() += 1);
|
||||
counts
|
||||
};
|
||||
let after = count(after);
|
||||
count(before)
|
||||
.into_iter()
|
||||
.filter_map(|(rule, n)| {
|
||||
let gone = n.saturating_sub(after.get(rule).copied().unwrap_or(0));
|
||||
(gone > 0).then_some((rule, gone))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `fixed: rule ×2, rule ×1; 3 findings left`.
|
||||
fn fixed_note(fixed: &BTreeMap<&'static str, usize>, left: usize) -> String {
|
||||
let listed: Vec<String> = fixed.iter().map(|(rule, n)| format!("{rule} ×{n}")).collect();
|
||||
let fixed = if listed.is_empty() { "nothing".to_string() } else { listed.join(", ") };
|
||||
let plural = if left == 1 { "" } else { "s" };
|
||||
format!("fixed: {fixed}; {left} finding{plural} left")
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
//! `hierarchy`: the instance tree, down from a module (or from every
|
||||
//! top-level module) or up to the modules that instantiate it — read off the
|
||||
//! index's instantiation edges, textual rather than elaborated, exactly the
|
||||
//! census the editor's hierarchy view and call hierarchy draw from.
|
||||
//!
|
||||
//! The walk is cut three ways: by `depth`, by a module already on the path
|
||||
//! (a module that instantiates itself, through `generate` or otherwise, ends
|
||||
//! its branch marked `recursive`), and by [`NODE_CAP`]. A module declared
|
||||
//! more than once is not expanded — which declaration an instance means is
|
||||
//! the elaborator's choice, not ours — and says how many there are.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{
|
||||
Def, FileId, InstanceOccurrence, InstantiationEdge, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use super::source::{self, Texts};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
/// The deepest a walk may go, whatever `depth` asks.
|
||||
const MAX_DEPTH: usize = 20;
|
||||
|
||||
/// The longest overrides text a line shows; the JSON carries all of it.
|
||||
const OVERRIDES_CAP: usize = 200;
|
||||
|
||||
/// The most nodes one walk collects before it stops.
|
||||
const NODE_CAP: usize = 50_000;
|
||||
|
||||
pub const HIERARCHY: Tool = Tool {
|
||||
name: "hierarchy",
|
||||
title: "Instance hierarchy",
|
||||
description: "The instance tree as indented `instance : module #(overrides)` lines, down from `root` (default: every top-level module), or with `direction: up` every `parent.instance` that instantiates `root`, with file:line. Textual, not elaborated: `generate` and `ifdef` branches all appear. Prefer it over reading files to find who instantiates what.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "root",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The module to start from; required for `up` (default for `down`: every module nothing instantiates).",
|
||||
},
|
||||
Param {
|
||||
name: "direction",
|
||||
ty: Ty::Enum(&["down", "up"]),
|
||||
required: false,
|
||||
description: "`down` lists what `root` instantiates (default); `up` lists what instantiates it.",
|
||||
},
|
||||
Param {
|
||||
name: "depth",
|
||||
ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 },
|
||||
required: false,
|
||||
description: "Levels to walk (default 3, at most 20).",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most lines to return (default 200).",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Lines to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: hierarchy,
|
||||
};
|
||||
|
||||
/// One instance under an owner, as the index records it.
|
||||
#[derive(Clone)]
|
||||
struct Child {
|
||||
instance: String,
|
||||
module: String,
|
||||
file: FileId,
|
||||
/// The instantiated module's name at the site.
|
||||
site: TextRange,
|
||||
/// The instance's own name.
|
||||
name: TextRange,
|
||||
/// Where the statement's first instance name starts: the `#(...)`
|
||||
/// belongs to the whole statement and ends before it.
|
||||
first: u32,
|
||||
}
|
||||
|
||||
impl Child {
|
||||
/// One instance of an edge to `module`.
|
||||
fn of(module: &str, edge: &InstantiationEdge, occurrence: &InstanceOccurrence) -> Child {
|
||||
let first =
|
||||
edge.instances.first().map_or(occurrence.name_span.start, |i| i.name_span.start);
|
||||
Child {
|
||||
instance: occurrence.name.clone(),
|
||||
module: module.to_string(),
|
||||
file: edge.file,
|
||||
site: edge.site_span,
|
||||
name: occurrence.name_span,
|
||||
first,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One line of the answer. A root line has no instance.
|
||||
struct Node {
|
||||
depth: usize,
|
||||
/// Down: the instance; up: the instance of the line above it.
|
||||
instance: Option<Child>,
|
||||
/// Down: the instantiated module; up: the instantiating one; root: itself.
|
||||
module: String,
|
||||
root: Option<Def>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
/// A walk in progress: the edges by owner, what it collected, and the path
|
||||
/// of modules above the current node.
|
||||
struct Walk<'a> {
|
||||
index: &'a WorkspaceIndex,
|
||||
below: HashMap<(FileId, u32), Vec<Child>>,
|
||||
max_depth: usize,
|
||||
nodes: Vec<Node>,
|
||||
path: Vec<String>,
|
||||
}
|
||||
|
||||
fn hierarchy(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let up = args.str("direction") == Some("up");
|
||||
let root = args.str("root").filter(|root| !root.is_empty());
|
||||
if up && root.is_none() {
|
||||
return Err("`direction: up` needs a `root`.".into());
|
||||
}
|
||||
if let Some(root) = root {
|
||||
if modules_named(project.index(), root).is_empty() {
|
||||
project.ensure_walked_for_miss();
|
||||
}
|
||||
if modules_named(project.index(), root).is_empty() {
|
||||
return Err(format!("no module or interface `{root}` is indexed."));
|
||||
}
|
||||
}
|
||||
let max_depth = args.count("depth", 3);
|
||||
let index = project.index();
|
||||
let mut walk = Walk::new(index, max_depth, !up);
|
||||
let roots: Vec<(String, Def)> = match root {
|
||||
Some(root) => {
|
||||
modules_named(index, root).into_iter().map(|d| (root.to_string(), d)).collect()
|
||||
}
|
||||
None => top_modules(index),
|
||||
};
|
||||
for (name, def) in roots {
|
||||
walk.root(name, def, up);
|
||||
}
|
||||
Ok(render(project, walk.nodes, up, args))
|
||||
}
|
||||
|
||||
/// Every instantiable declaration of `name`.
|
||||
fn modules_named(index: &WorkspaceIndex, name: &str) -> Vec<Def> {
|
||||
index.units(name).iter().filter(|def| def.kind.is_instantiable()).cloned().collect()
|
||||
}
|
||||
|
||||
/// Every module nothing instantiates, in name order.
|
||||
fn top_modules(index: &WorkspaceIndex) -> Vec<(String, Def)> {
|
||||
index
|
||||
.instantiable_units()
|
||||
.filter(|(_, def)| def.kind == SymbolKind::Module)
|
||||
.filter(|(name, _)| index.instantiations_of(name).is_empty())
|
||||
.map(|(name, def)| (name.to_string(), def.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl<'a> Walk<'a> {
|
||||
/// A walk over `index`; the owner table is built only for `down`.
|
||||
fn new(index: &'a WorkspaceIndex, max_depth: usize, down: bool) -> Walk<'a> {
|
||||
let mut below: HashMap<(FileId, u32), Vec<Child>> = HashMap::new();
|
||||
for (module, edges) in index.instantiations().filter(|_| down) {
|
||||
for edge in edges {
|
||||
let owner = (edge.file, edge.owner.name_span.start);
|
||||
let children =
|
||||
edge.instances.iter().map(|occurrence| Child::of(module, edge, occurrence));
|
||||
below.entry(owner).or_default().extend(children);
|
||||
}
|
||||
}
|
||||
for children in below.values_mut() {
|
||||
children.sort_by_key(|child| child.name.start);
|
||||
}
|
||||
Walk { index, below, max_depth, nodes: Vec::new(), path: Vec::new() }
|
||||
}
|
||||
|
||||
fn full(&self) -> bool {
|
||||
self.nodes.len() >= NODE_CAP
|
||||
}
|
||||
|
||||
/// One root line and its tree.
|
||||
fn root(&mut self, name: String, def: Def, up: bool) {
|
||||
if self.full() {
|
||||
return;
|
||||
}
|
||||
self.path = vec![name.clone()];
|
||||
let line = Node {
|
||||
depth: 0,
|
||||
instance: None,
|
||||
module: name.clone(),
|
||||
root: Some(def.clone()),
|
||||
note: None,
|
||||
};
|
||||
self.nodes.push(line);
|
||||
if up {
|
||||
self.up(&name, 1);
|
||||
} else {
|
||||
self.down(&def, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// The instances `def` declares, and theirs, to `max_depth`.
|
||||
fn down(&mut self, def: &Def, depth: usize) {
|
||||
let children =
|
||||
self.below.get(&(def.file, def.name_span.start)).cloned().unwrap_or_default();
|
||||
for child in children {
|
||||
if self.full() {
|
||||
return;
|
||||
}
|
||||
let declared = modules_named(self.index, &child.module);
|
||||
let recursive = self.path.contains(&child.module);
|
||||
let note = match declared.len() {
|
||||
_ if recursive => Some("recursive".to_string()),
|
||||
0 => Some("not indexed".to_string()),
|
||||
1 => None,
|
||||
n => Some(format!("declared {n} times")),
|
||||
};
|
||||
let expand = note.is_none() && depth < self.max_depth;
|
||||
let module = child.module.clone();
|
||||
self.nodes.push(Node {
|
||||
depth,
|
||||
instance: Some(child),
|
||||
module: module.clone(),
|
||||
root: None,
|
||||
note,
|
||||
});
|
||||
if let (true, [only]) = (expand, declared.as_slice()) {
|
||||
self.path.push(module);
|
||||
self.down(only, depth + 1);
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every instance of `module`, then the instances of their owners.
|
||||
fn up(&mut self, module: &str, depth: usize) {
|
||||
let index = self.index;
|
||||
for edge in index.instantiations_of(module) {
|
||||
for occurrence in &edge.instances {
|
||||
if self.full() {
|
||||
return;
|
||||
}
|
||||
let parent = edge.owner.name.clone();
|
||||
let recursive = self.path.contains(&parent);
|
||||
let child = Child::of(module, edge, occurrence);
|
||||
let note = recursive.then(|| "recursive".to_string());
|
||||
self.nodes.push(Node {
|
||||
depth,
|
||||
instance: Some(child),
|
||||
module: parent.clone(),
|
||||
root: None,
|
||||
note,
|
||||
});
|
||||
if !recursive && depth < self.max_depth {
|
||||
self.path.push(parent.clone());
|
||||
self.up(&parent, depth + 1);
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The collected nodes, paged, as indented lines and as a flat JSON list.
|
||||
fn render(project: &Project, nodes: Vec<Node>, up: bool, args: &Args) -> Answer {
|
||||
let (shown, rest) =
|
||||
render::page(&nodes, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let mut texts = Texts::default();
|
||||
let mut text = String::new();
|
||||
let mut listed: Vec<Value> = Vec::new();
|
||||
for node in shown {
|
||||
let line = Line::of(project, &mut texts, node);
|
||||
text.push_str(&" ".repeat(node.depth));
|
||||
text.push_str(&line.text(node, up));
|
||||
text.push('\n');
|
||||
listed.push(line.json(node, up));
|
||||
}
|
||||
render::more(&mut text, rest);
|
||||
if nodes.len() >= NODE_CAP {
|
||||
text.push_str(&format!("tree cut at {NODE_CAP} nodes; lower `depth` or pick a `root`\n"));
|
||||
}
|
||||
if nodes.is_empty() {
|
||||
text = "no modules\n".to_string();
|
||||
}
|
||||
let direction = if up { "up" } else { "down" };
|
||||
let structured = json!({
|
||||
"direction": direction, "nodes": listed, "total": nodes.len(),
|
||||
"cut": nodes.len() >= NODE_CAP,
|
||||
});
|
||||
Answer { text, structured }
|
||||
}
|
||||
|
||||
/// What one node's line needs from its file: where it is and the overrides.
|
||||
struct Line {
|
||||
file: String,
|
||||
line: u32,
|
||||
overrides: Option<String>,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
fn of(project: &Project, texts: &mut Texts, node: &Node) -> Line {
|
||||
let index = project.index();
|
||||
if let Some(def) = &node.root {
|
||||
let path = index.path(def.file).unwrap_or(Path::new(""));
|
||||
return Line { file: project.relative(path), line: def.lines.name, overrides: None };
|
||||
}
|
||||
let Some(child) = &node.instance else {
|
||||
return Line { file: String::new(), line: 0, overrides: None };
|
||||
};
|
||||
let path = index.path(child.file).unwrap_or(Path::new(""));
|
||||
let file = project.relative(path);
|
||||
let Some((text, lines)) = texts.get(path) else {
|
||||
return Line { file, line: 0, overrides: None };
|
||||
};
|
||||
let line = lines.line_col(child.name.start).0;
|
||||
Line { file, line, overrides: overrides(text, child) }
|
||||
}
|
||||
|
||||
fn text(&self, node: &Node, up: bool) -> String {
|
||||
let mut out = match (&node.instance, up) {
|
||||
(None, _) => format!("{} {}:{}", node.module, self.file, self.line),
|
||||
(Some(child), false) => format!("{} : {}", child.instance, child.module),
|
||||
(Some(child), true) => format!("{}.{}", node.module, child.instance),
|
||||
};
|
||||
if let Some(overrides) = &self.overrides {
|
||||
out.push(' ');
|
||||
out.push_str(&source::capped(overrides, OVERRIDES_CAP));
|
||||
}
|
||||
if up && node.instance.is_some() {
|
||||
out.push_str(&format!(" {}:{}", self.file, self.line));
|
||||
}
|
||||
if let Some(note) = &node.note {
|
||||
out.push_str(&format!(" ({note})"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn json(&self, node: &Node, up: bool) -> Value {
|
||||
let child = node.instance.as_ref();
|
||||
json!({
|
||||
"depth": node.depth,
|
||||
"instance": child.map(|child| child.instance.clone()),
|
||||
"module": child.map_or(node.module.clone(), |child| child.module.clone()),
|
||||
"parent": child.filter(|_| up).map(|_| node.module.clone()),
|
||||
"file": self.file,
|
||||
"line": self.line,
|
||||
"overrides": self.overrides,
|
||||
"note": node.note,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The `#(...)` written between the module name and the instance name,
|
||||
/// comments dropped, on one line — when the file still spells the module
|
||||
/// name at the site.
|
||||
fn overrides(text: &str, child: &Child) -> Option<String> {
|
||||
if text.get(child.site.as_range()) != Some(child.module.as_str()) {
|
||||
return None;
|
||||
}
|
||||
let between = text.get(child.site.end as usize..child.first as usize)?;
|
||||
let written = source::without_comments(between);
|
||||
let written = written.trim();
|
||||
written.starts_with('#').then(|| render::one_line(written))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn child(text: &str, module: &str, instance: &str) -> Child {
|
||||
let site = text.find(module).unwrap() as u32;
|
||||
let name = text.find(instance).unwrap() as u32;
|
||||
Child {
|
||||
instance: instance.to_string(),
|
||||
module: module.to_string(),
|
||||
file: FileId(0),
|
||||
site: TextRange::new(site, site + module.len() as u32),
|
||||
name: TextRange::new(name, name + instance.len() as u32),
|
||||
first: text.find(" u_").unwrap() as u32 + 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overrides_are_sliced_between_the_module_and_the_instance_name() {
|
||||
let text = " fifo #( // sizes\n .Width (8),\n .Depth(2)\n ) u_fifo (.*);";
|
||||
let fifo = child(text, "fifo", "u_fifo");
|
||||
assert_eq!(overrides(text, &fifo).as_deref(), Some("#( .Width (8), .Depth(2) )"));
|
||||
let plain = " fifo u_plain (.*);";
|
||||
assert_eq!(overrides(plain, &child(plain, "fifo", "u_plain")), None);
|
||||
let two = " fifo #(.W(2)) u_a (), u_b ();";
|
||||
assert_eq!(overrides(two, &child(two, "fifo", "u_b")).as_deref(), Some("#(.W(2))"));
|
||||
let mut stale = fifo.clone();
|
||||
stale.module = "other".into();
|
||||
assert_eq!(overrides(text, &stale), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! `unit_interface`: what a unit offers the code that uses it — a module's
|
||||
//! or interface's parameters, ports and instantiation template (plus an
|
||||
//! interface's modports), a package's or class's exported members — without
|
||||
//! the agent reading the file that declares it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_refactor::{instantiation_plan, InstantiationPlan, Layout};
|
||||
use vlog_semantic::{Def, ScopeId, Semantics, Symbol, SymbolKind};
|
||||
|
||||
use super::read_item::child_items;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
pub const UNIT_INTERFACE: Tool = Tool {
|
||||
name: "unit_interface",
|
||||
title: "Unit interface",
|
||||
description: "The interface of one unit by name: a module's or interface's parameters with defaults, ports in declaration order (direction, type, range) and a ready-to-paste instantiation; an interface's modports; a package's or class's members. Prefer it over reading the declaring file. Refuses a name declared in several files unless `file` picks one.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The unit's name; a class inside a package may be written `pkg::cls`.",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The declaring file, when the name is declared more than once.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: unit_interface,
|
||||
};
|
||||
|
||||
/// A unit found in the index: where it is, and what it is.
|
||||
struct Found {
|
||||
path: PathBuf,
|
||||
def: Def,
|
||||
}
|
||||
|
||||
fn unit_interface(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").unwrap_or("");
|
||||
let mut found = candidates(project, name, args.str("file"))?;
|
||||
if found.is_empty() && project.ensure_walked_for_miss() {
|
||||
found = candidates(project, name, args.str("file"))?;
|
||||
}
|
||||
let found = pick(project, found, name, args.str("file"))?;
|
||||
let analysis = project.analysis(&found.path)?;
|
||||
let file = project.relative(&found.path);
|
||||
let kind = super::read::unit_kind(project, &found.path, &found.def);
|
||||
let head = format!("{kind} {name} {file}:{}\n", found.def.lines.name);
|
||||
let short = name.rsplit("::").next().unwrap_or(name);
|
||||
match found.def.kind {
|
||||
SymbolKind::Module | SymbolKind::Interface => {
|
||||
instantiable(&analysis, &found, short, head, &file).map(|mut answer| {
|
||||
answer.structured["kind"] = Value::from(kind);
|
||||
answer
|
||||
})
|
||||
}
|
||||
_ => Ok(members(project, &analysis, &found, short, head, &file)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every indexed declaration of `name` (in `file`, when given). `Err` only
|
||||
/// when `file` itself is refused.
|
||||
fn candidates(project: &Project, name: &str, file: Option<&str>) -> Result<Vec<Found>, String> {
|
||||
let index = project.index();
|
||||
let unit_kinds =
|
||||
[SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class];
|
||||
let mut defs: Vec<Def> = match name.split_once("::") {
|
||||
Some((package, class)) => index.member(package, class).to_vec(),
|
||||
None => index.units(name).to_vec(),
|
||||
};
|
||||
defs.retain(|def| unit_kinds.contains(&def.kind));
|
||||
let mut found: Vec<Found> = defs
|
||||
.into_iter()
|
||||
.filter_map(|def| Some(Found { path: index.path(def.file)?.to_path_buf(), def }))
|
||||
.collect();
|
||||
if let Some(file) = file {
|
||||
let path = project.resolve(file)?;
|
||||
found.retain(|f| f.path == path);
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// The one declaration among `found`, or a refusal that says why there is
|
||||
/// not exactly one.
|
||||
fn pick(
|
||||
project: &Project,
|
||||
mut found: Vec<Found>,
|
||||
name: &str,
|
||||
file: Option<&str>,
|
||||
) -> Result<Found, String> {
|
||||
match found.len() {
|
||||
0 => Err(format!(
|
||||
"no module, interface, package or class named `{name}` is indexed{}; search_symbols finds near names.",
|
||||
file.map_or(String::new(), |f| format!(" in `{f}`"))
|
||||
)),
|
||||
1 => Ok(found.remove(0)),
|
||||
_ => {
|
||||
let sites: Vec<String> = found
|
||||
.iter()
|
||||
.map(|f| format!("{}:{}", project.relative(&f.path), f.def.lines.name))
|
||||
.collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); pass `file` to pick one.",
|
||||
sites.len(),
|
||||
sites.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A module's or interface's parameters, ports, modports and template.
|
||||
fn instantiable(
|
||||
analysis: &Analysis,
|
||||
found: &Found,
|
||||
name: &str,
|
||||
head: String,
|
||||
file: &str,
|
||||
) -> Result<Answer, String> {
|
||||
let plan = instantiation_plan(name, &analysis.text, None)?;
|
||||
let scope = unit_symbol(&analysis.semantics, found, name).and_then(|s| s.child_scope);
|
||||
let ports = port_rows(&plan, analysis, scope);
|
||||
let modports = match (found.def.kind, scope) {
|
||||
(SymbolKind::Interface, Some(scope)) => modports_of(analysis, scope),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let template = plan.render(&Layout::default());
|
||||
let text = interface_text(head, &plan, &ports, &modports, &template);
|
||||
let structured = json!({
|
||||
"name": name,
|
||||
"kind": render::kind(found.def.kind),
|
||||
"file": file,
|
||||
"line": found.def.lines.name,
|
||||
"parameters": plan.params.iter().map(|p| json!({ "name": p.name, "default": p.default })).collect::<Vec<_>>(),
|
||||
"ports": ports.iter().map(PortRow::to_json).collect::<Vec<_>>(),
|
||||
"modports": modports,
|
||||
"template": template,
|
||||
"warnings": plan.warnings,
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// An interface's modports, each as its declaration reads on one line.
|
||||
fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec<String> {
|
||||
analysis
|
||||
.semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.filter(|s| s.scope == scope && s.kind == SymbolKind::Modport)
|
||||
.map(|s| render::one_line(analysis.slice(s.decl_span.start, s.decl_span.end)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text answer: the head line, then each non-empty section.
|
||||
fn interface_text(
|
||||
mut text: String,
|
||||
plan: &InstantiationPlan,
|
||||
ports: &[PortRow],
|
||||
modports: &[String],
|
||||
template: &str,
|
||||
) -> String {
|
||||
if !plan.params.is_empty() {
|
||||
text.push_str("parameters:\n");
|
||||
let rows: Vec<Vec<String>> =
|
||||
plan.params.iter().map(|p| vec![p.name.clone(), default_cell(&p.default)]).collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
}
|
||||
if !ports.is_empty() {
|
||||
text.push_str("ports:\n");
|
||||
let rows: Vec<Vec<String>> = ports
|
||||
.iter()
|
||||
.map(|p| vec![p.dir.clone(), p.written_type(), p.name_with_unpacked()])
|
||||
.collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
}
|
||||
if !modports.is_empty() {
|
||||
text.push_str("modports:\n");
|
||||
for modport in modports {
|
||||
text.push_str(&format!(" {modport}\n"));
|
||||
}
|
||||
}
|
||||
for warning in &plan.warnings {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
text.push_str("template:\n");
|
||||
text.push_str(template);
|
||||
if !template.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn default_cell(default: &str) -> String {
|
||||
if default.is_empty() {
|
||||
"(no default)".to_string()
|
||||
} else {
|
||||
format!("= {}", render::one_line(default))
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit's own symbol in the file's analysis: the declaration at the
|
||||
/// indexed name, else the first of its kind spelling the name.
|
||||
fn unit_symbol<'s>(semantics: &'s Semantics, found: &Found, name: &str) -> Option<&'s Symbol> {
|
||||
let mut candidates = semantics
|
||||
.symbols_named(name)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.filter(|s| s.kind == found.def.kind);
|
||||
let first = candidates.next()?;
|
||||
Some(
|
||||
std::iter::once(first)
|
||||
.chain(candidates)
|
||||
.find(|s| s.name_span == found.def.name_span)
|
||||
.unwrap_or(first),
|
||||
)
|
||||
}
|
||||
|
||||
/// One port as the answer shows it.
|
||||
struct PortRow {
|
||||
dir: String,
|
||||
ty: String,
|
||||
range: String,
|
||||
name: String,
|
||||
unpacked: String,
|
||||
}
|
||||
|
||||
impl PortRow {
|
||||
/// The type as the declaration writes it, packed range included — one
|
||||
/// column, so a long type name widens one column rather than two.
|
||||
fn written_type(&self) -> String {
|
||||
match (self.ty.is_empty(), self.range.is_empty()) {
|
||||
(_, true) => self.ty.clone(),
|
||||
(true, false) => self.range.clone(),
|
||||
(false, false) => format!("{} {}", self.ty, self.range),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_with_unpacked(&self) -> String {
|
||||
if self.unpacked.is_empty() {
|
||||
self.name.clone()
|
||||
} else {
|
||||
format!("{} {}", self.name, self.unpacked)
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"direction": self.dir, "type": self.ty, "range": self.range,
|
||||
"name": self.name, "unpacked": self.unpacked,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The plan's ports with the packed range split off the type, and the
|
||||
/// unpacked dimensions an ANSI port writes after its name.
|
||||
fn port_rows(
|
||||
plan: &InstantiationPlan,
|
||||
analysis: &Analysis,
|
||||
scope: Option<ScopeId>,
|
||||
) -> Vec<PortRow> {
|
||||
plan.ports
|
||||
.iter()
|
||||
.map(|port| {
|
||||
let (ty, range) = match port.ty.find('[') {
|
||||
Some(at) => (port.ty[..at].trim().to_string(), port.ty[at..].trim().to_string()),
|
||||
None => (port.ty.clone(), String::new()),
|
||||
};
|
||||
let unpacked =
|
||||
scope.map_or(String::new(), |scope| unpacked(analysis, scope, &port.name));
|
||||
PortRow { dir: port.dir.clone(), ty, range, name: port.name.clone(), unpacked }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `[..]` groups written right after an ANSI port's name. A non-ANSI
|
||||
/// port (completed in the body) answers nothing here.
|
||||
fn unpacked(analysis: &Analysis, scope: ScopeId, name: &str) -> String {
|
||||
let Some(port) = analysis.semantics.symbols_named(name).find_map(|id| {
|
||||
let s = analysis.semantics.symbol(id)?;
|
||||
(s.scope == scope && s.kind == SymbolKind::Port && s.detail_span.is_none()).then_some(s)
|
||||
}) else {
|
||||
return String::new();
|
||||
};
|
||||
let mut rest = analysis.slice(port.name_span.end, port.decl_span.end).trim_start();
|
||||
let mut out = String::new();
|
||||
while rest.starts_with('[') {
|
||||
let mut depth = 0;
|
||||
let Some(end) = rest.char_indices().find_map(|(at, c)| {
|
||||
depth += match c {
|
||||
'[' => 1,
|
||||
']' => -1,
|
||||
_ => 0,
|
||||
};
|
||||
(depth == 0).then_some(at)
|
||||
}) else {
|
||||
break;
|
||||
};
|
||||
out.push_str(&render::one_line(&rest[..=end]));
|
||||
rest = rest[end + 1..].trim_start();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A package's or class's members, in declaration order, and a class's
|
||||
/// base. `name` is the unit's own name, without a package prefix — which
|
||||
/// two classes in two packages may share, so both answers are read off this
|
||||
/// declaration: a member counts only when it is declared inside
|
||||
/// `found.def.decl_span`, and the base is what this declaration's own
|
||||
/// `extends` writes.
|
||||
fn members(
|
||||
project: &Project,
|
||||
analysis: &Analysis,
|
||||
found: &Found,
|
||||
name: &str,
|
||||
mut text: String,
|
||||
file: &str,
|
||||
) -> Answer {
|
||||
let index = project.index();
|
||||
let within = found.def.decl_span;
|
||||
let mut rows: Vec<(u32, &'static str, String)> = index
|
||||
.members_of(name)
|
||||
.flat_map(|(member, defs)| {
|
||||
defs.iter()
|
||||
.filter(|def| index.path(def.file) == Some(found.path.as_path()))
|
||||
.filter(|def| {
|
||||
within.start <= def.name_span.start && def.name_span.end <= within.end
|
||||
})
|
||||
.map(move |def| (def.lines.name, render::kind(def.kind), member.to_string()))
|
||||
})
|
||||
.collect();
|
||||
rows.sort();
|
||||
let base = class_base(&analysis.tree.items, found.def.name_span);
|
||||
if let Some(base) = &base {
|
||||
text.push_str(&format!("extends {base}\n"));
|
||||
}
|
||||
text.push_str("members:\n");
|
||||
let table: Vec<Vec<String>> = rows
|
||||
.iter()
|
||||
.map(|(line, kind, member)| vec![kind.to_string(), member.clone(), line.to_string()])
|
||||
.collect();
|
||||
text.push_str(&render::table(&table));
|
||||
let structured = json!({
|
||||
"name": name,
|
||||
"kind": render::kind(found.def.kind),
|
||||
"file": file,
|
||||
"line": found.def.lines.name,
|
||||
"extends": base,
|
||||
"members": rows.iter().map(|(line, kind, member)| json!({ "name": member, "kind": kind, "line": line })).collect::<Vec<_>>(),
|
||||
});
|
||||
Answer { text, structured }
|
||||
}
|
||||
|
||||
/// The base the class declared at `name_span` names in its `extends`, read
|
||||
/// off the file's own tree; `None` for a class without one (or a package).
|
||||
fn class_base(items: &[Item], name_span: TextRange) -> Option<String> {
|
||||
let item = items
|
||||
.iter()
|
||||
.find(|item| item.span.start <= name_span.start && name_span.end <= item.span.end)?;
|
||||
if let ItemKind::Class(class) = &item.kind {
|
||||
if class.name_span == name_span {
|
||||
return class.extends.as_ref().map(|extends| extends.name.clone());
|
||||
}
|
||||
}
|
||||
child_items(&item.kind).into_iter().find_map(|items| class_base(items, name_span))
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! The tool registry: every tool's name, description, argument list and
|
||||
//! handler, in one table. The argument list is the single source of both the
|
||||
//! `inputSchema` a host shows the agent and the validation a call's
|
||||
//! `arguments` go through, so the two cannot disagree.
|
||||
|
||||
mod defines;
|
||||
mod diagnostics;
|
||||
mod edit;
|
||||
mod format;
|
||||
mod hierarchy;
|
||||
mod interface;
|
||||
mod nav;
|
||||
mod read;
|
||||
mod read_item;
|
||||
mod refactor;
|
||||
mod select;
|
||||
mod source;
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
|
||||
/// What a tool hands back: the compact text rendering the agent reads, and
|
||||
/// the same facts as JSON (`structuredContent`).
|
||||
pub struct Answer {
|
||||
pub text: String,
|
||||
pub structured: Value,
|
||||
}
|
||||
|
||||
/// A tool's body. `Err` is a refusal: one sentence, sent as `isError: true`.
|
||||
pub type Handler = fn(&mut Project, &Args) -> Result<Answer, String>;
|
||||
|
||||
/// The JSON type one argument takes.
|
||||
pub enum Ty {
|
||||
/// A string.
|
||||
Str,
|
||||
/// An integer no smaller than the bound.
|
||||
Int { min: i64 },
|
||||
/// One of a fixed set of strings.
|
||||
Enum(&'static [&'static str]),
|
||||
/// `true` or `false`.
|
||||
Bool,
|
||||
/// An integer inside `min..=max`.
|
||||
Range { min: i64, max: i64 },
|
||||
}
|
||||
|
||||
/// One argument a tool takes.
|
||||
pub struct Param {
|
||||
pub name: &'static str,
|
||||
pub ty: Ty,
|
||||
pub required: bool,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
/// One tool, as `tools/list` shows it and `tools/call` runs it.
|
||||
pub struct Tool {
|
||||
pub name: &'static str,
|
||||
pub title: &'static str,
|
||||
pub description: &'static str,
|
||||
pub params: &'static [Param],
|
||||
/// Whether the call walks the roots again before answering, so files
|
||||
/// created since the last walk are counted (`project_overview`).
|
||||
pub rewalk: bool,
|
||||
pub handler: Handler,
|
||||
}
|
||||
|
||||
/// What a tool does to the disk — the annotations a host shows before it
|
||||
/// lets an agent call it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Effect {
|
||||
/// Nothing on disk changes; the same call on the same disk gives the
|
||||
/// same answer.
|
||||
Read,
|
||||
/// Files inside the roots are rewritten (or created). `idempotent` when
|
||||
/// a second identical call writes nothing more.
|
||||
Edit { idempotent: bool },
|
||||
}
|
||||
|
||||
use Effect::{Edit, Read};
|
||||
|
||||
/// Every tool this server offers, in the order `tools/list` gives them.
|
||||
const TOOLS: &[(Tool, Effect)] = &[
|
||||
(read::PROJECT_OVERVIEW, Read),
|
||||
(read::LIST_UNITS, Read),
|
||||
(interface::UNIT_INTERFACE, Read),
|
||||
(read::OUTLINE, Read),
|
||||
(read_item::READ_ITEM, Read),
|
||||
(read::SEARCH_SYMBOLS, Read),
|
||||
(defines::DEFINES, Read),
|
||||
(nav::DEFINITION, Read),
|
||||
(nav::REFERENCES, Read),
|
||||
(hierarchy::HIERARCHY, Read),
|
||||
(diagnostics::DIAGNOSTICS, Read),
|
||||
(format::FORMAT, Edit { idempotent: true }),
|
||||
(format::FIX_LINT, Edit { idempotent: true }),
|
||||
(edit::RENAME, Edit { idempotent: false }),
|
||||
(edit::EXPAND_WILDCARD, Edit { idempotent: true }),
|
||||
(edit::CONVERT_PORTS, Edit { idempotent: true }),
|
||||
(edit::ORGANIZE_IMPORTS, Edit { idempotent: true }),
|
||||
(edit::INLINE_MODULE, Edit { idempotent: false }),
|
||||
(edit::PROPAGATE_PORTS, Edit { idempotent: false }),
|
||||
(edit::REMOVE_PORT, Edit { idempotent: false }),
|
||||
(refactor::ADD_PORT, Edit { idempotent: false }),
|
||||
(refactor::EXTRACT_MODULE, Edit { idempotent: false }),
|
||||
(refactor::INSTANTIATE, Read),
|
||||
];
|
||||
|
||||
/// The tool called `name`.
|
||||
pub fn find(name: &str) -> Option<&'static Tool> {
|
||||
TOOLS.iter().map(|(tool, _)| tool).find(|tool| tool.name == name)
|
||||
}
|
||||
|
||||
/// The `tools/list` result: every tool, no pagination.
|
||||
pub fn list() -> Value {
|
||||
let tools: Vec<Value> = TOOLS.iter().map(|(tool, effect)| describe(tool, *effect)).collect();
|
||||
json!({ "tools": tools })
|
||||
}
|
||||
|
||||
fn describe(tool: &Tool, effect: Effect) -> Value {
|
||||
// No tool consults anything outside the roots (`openWorldHint`), and no
|
||||
// edit tool destroys: each rewrites files inside the roots through a
|
||||
// verified engine, and `dry_run` shows the diff first.
|
||||
let (read_only, idempotent) = match effect {
|
||||
Read => (true, true),
|
||||
Edit { idempotent } => (false, idempotent),
|
||||
};
|
||||
json!({
|
||||
"name": tool.name,
|
||||
"title": tool.title,
|
||||
"description": tool.description,
|
||||
"inputSchema": schema(tool.params),
|
||||
"annotations": {
|
||||
"title": tool.title,
|
||||
"readOnlyHint": read_only,
|
||||
"destructiveHint": false,
|
||||
"idempotentHint": idempotent,
|
||||
"openWorldHint": false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// A JSON Schema object for an argument list: closed, with its required set.
|
||||
fn schema(params: &[Param]) -> Value {
|
||||
let mut properties = Map::new();
|
||||
for param in params {
|
||||
let mut property = match param.ty {
|
||||
Ty::Str => json!({ "type": "string" }),
|
||||
Ty::Int { min } => json!({ "type": "integer", "minimum": min }),
|
||||
Ty::Enum(values) => json!({ "type": "string", "enum": values }),
|
||||
Ty::Bool => json!({ "type": "boolean" }),
|
||||
Ty::Range { min, max } => json!({ "type": "integer", "minimum": min, "maximum": max }),
|
||||
};
|
||||
property["description"] = Value::from(param.description);
|
||||
properties.insert(param.name.to_string(), property);
|
||||
}
|
||||
let required: Vec<&str> =
|
||||
params.iter().filter(|param| param.required).map(|param| param.name).collect();
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": properties,
|
||||
"required": required,
|
||||
"additionalProperties": false,
|
||||
})
|
||||
}
|
||||
|
||||
/// A call's arguments, checked against the tool's list.
|
||||
pub struct Args(Map<String, Value>);
|
||||
|
||||
impl Args {
|
||||
/// A string argument, when given.
|
||||
pub fn str(&self, name: &str) -> Option<&str> {
|
||||
self.0.get(name).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// An integer argument, when given.
|
||||
pub fn int(&self, name: &str) -> Option<i64> {
|
||||
self.0.get(name).and_then(Value::as_i64)
|
||||
}
|
||||
|
||||
/// A boolean argument, or `default`.
|
||||
pub fn flag(&self, name: &str, default: bool) -> bool {
|
||||
self.0.get(name).and_then(Value::as_bool).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// A non-negative integer argument, or `default`.
|
||||
pub fn count(&self, name: &str, default: usize) -> usize {
|
||||
self.int(name).and_then(|n| usize::try_from(n).ok()).unwrap_or(default)
|
||||
}
|
||||
}
|
||||
|
||||
/// Check `arguments` against `tool`'s list. The refusal names the argument
|
||||
/// and what was wrong with it, so the agent can correct the call.
|
||||
pub fn validate(tool: &Tool, arguments: Map<String, Value>) -> Result<Args, String> {
|
||||
for name in arguments.keys() {
|
||||
if !tool.params.iter().any(|param| param.name == name) {
|
||||
let known: Vec<&str> = tool.params.iter().map(|param| param.name).collect();
|
||||
return Err(format!(
|
||||
"`{}` takes no argument `{name}` (it takes: {}).",
|
||||
tool.name,
|
||||
if known.is_empty() { "nothing".to_string() } else { known.join(", ") }
|
||||
));
|
||||
}
|
||||
}
|
||||
for param in tool.params {
|
||||
match arguments.get(param.name) {
|
||||
None | Some(Value::Null) if param.required => {
|
||||
return Err(format!("`{}` needs the argument `{}`.", tool.name, param.name));
|
||||
}
|
||||
None | Some(Value::Null) => {}
|
||||
Some(value) => check_type(tool.name, param, value)?,
|
||||
}
|
||||
}
|
||||
Ok(Args(arguments))
|
||||
}
|
||||
|
||||
fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
|
||||
let fits = match param.ty {
|
||||
Ty::Str => value.is_string(),
|
||||
Ty::Int { min } => value.as_i64().is_some_and(|n| n >= min),
|
||||
Ty::Enum(values) => value.as_str().is_some_and(|s| values.contains(&s)),
|
||||
Ty::Bool => value.is_boolean(),
|
||||
Ty::Range { min, max } => value.as_i64().is_some_and(|n| (min..=max).contains(&n)),
|
||||
};
|
||||
if fits {
|
||||
return Ok(());
|
||||
}
|
||||
let wanted = match param.ty {
|
||||
Ty::Str => "a string".to_string(),
|
||||
Ty::Int { min } => format!("an integer >= {min}"),
|
||||
Ty::Enum(values) => format!("one of {}", values.join(", ")),
|
||||
Ty::Bool => "true or false".to_string(),
|
||||
Ty::Range { min, max } => format!("an integer from {min} to {max}"),
|
||||
};
|
||||
Err(format!("`{tool}` argument `{}` must be {wanted}, not {value}.", param.name))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(value: Value) -> Map<String, Value> {
|
||||
value.as_object().cloned().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_schema_is_closed_and_names_its_required_arguments() {
|
||||
for (tool, _) in TOOLS {
|
||||
let schema = schema(tool.params);
|
||||
assert_eq!(schema["additionalProperties"], false, "{}", tool.name);
|
||||
assert!(schema["required"].is_array(), "{}", tool.name);
|
||||
assert!(!tool.description.is_empty() && tool.description.len() < 600, "{}", tool.name);
|
||||
}
|
||||
let names: Vec<&str> = TOOLS.iter().map(|(tool, _)| tool.name).collect();
|
||||
let mut unique = names.clone();
|
||||
unique.sort_unstable();
|
||||
unique.dedup();
|
||||
assert_eq!(names.len(), unique.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_names_the_offending_argument() {
|
||||
let tool = find("list_units").unwrap();
|
||||
let unknown = validate(tool, args(json!({"nme": "x"}))).err().unwrap();
|
||||
assert!(unknown.contains("`nme`"), "{unknown}");
|
||||
let wrong = validate(tool, args(json!({"kind": "struct"}))).err().unwrap();
|
||||
assert!(wrong.contains("`kind`") && wrong.contains("module"), "{wrong}");
|
||||
let negative = validate(tool, args(json!({"limit": -1}))).err().unwrap();
|
||||
assert!(negative.contains("`limit`"), "{negative}");
|
||||
let missing = validate(find("outline").unwrap(), Map::new()).err().unwrap();
|
||||
assert!(missing.contains("`file`"), "{missing}");
|
||||
assert!(validate(tool, args(json!({"kind": "module", "glob": null}))).is_ok());
|
||||
let references = find("references").unwrap();
|
||||
let flag = validate(references, args(json!({"name": "x", "include_declaration": "no"})));
|
||||
assert!(flag.err().unwrap().contains("true or false"));
|
||||
let given = validate(references, args(json!({"name": "x", "include_declaration": false})));
|
||||
assert!(!given.unwrap().flag("include_declaration", true));
|
||||
let hierarchy = find("hierarchy").unwrap();
|
||||
let deep = validate(hierarchy, args(json!({"depth": 21}))).err().unwrap();
|
||||
assert!(deep.contains("`depth`") && deep.contains("from 1 to 20"), "{deep}");
|
||||
assert!(validate(hierarchy, args(json!({"depth": 20}))).is_ok());
|
||||
assert_eq!(schema(hierarchy.params)["properties"]["depth"]["maximum"], 20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! `definition` and `references`: where a name is declared, and every place
|
||||
//! the declaration is used — the two questions an agent otherwise answers by
|
||||
//! grepping and reading.
|
||||
//!
|
||||
//! Both take one selector ([`target`]): a position (`file` + `line` + `col`,
|
||||
//! or `file` + `line` + the `name` written on that line), a name in a file
|
||||
//! (`file` + `name`), or a bare `name` (with an optional `unit`) looked up in
|
||||
//! the index. `definition` walks the server's ladder — an `` `include`` line,
|
||||
//! a macro use, the file's own symbol table, the workspace overlay — and
|
||||
//! lists every site, never a guess. `references` hands the declaration to
|
||||
//! `vlog_refactor::find_references` over every indexed file
|
||||
//! (`source::WholeSet`).
|
||||
//! The selector itself is `select.rs`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex};
|
||||
|
||||
use super::select::{macro_name, target, Target};
|
||||
use super::source::{self, checked_site, Site, Texts, WholeSet};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
/// The selector's arguments, shared by both tools.
|
||||
const FILE: Param = Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The file holding the position, relative to a root or absolute inside one.",
|
||||
};
|
||||
const LINE: Param = Param {
|
||||
name: "line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
|
||||
};
|
||||
const COL: Param = Param {
|
||||
name: "col",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based column in bytes on `line`.",
|
||||
};
|
||||
const NAME: Param = Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The name: alone, looked up across the project (`` `NAME`` for a macro); with `file`, its first occurrence there; with `file` and `line`, its occurrence on that line.",
|
||||
};
|
||||
const UNIT: Param = Param {
|
||||
name: "unit",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "With a bare `name`: the module, interface, package or class declaring it.",
|
||||
};
|
||||
|
||||
pub const DEFINITION: Tool = Tool {
|
||||
name: "definition",
|
||||
title: "Go to definition",
|
||||
description: "Where a name is declared: every declaration site as file:line:col, its kind and the declaration's own source line (a name declared in several places lists them all, never a guess). Select by position (`file`, `line`, `col`), by `file`+`line`+`name`, or by `name` (and `unit`) across the project; also answers a macro use and an `include` line. Prefer it over grepping for the declaration.",
|
||||
params: &[FILE, LINE, COL, NAME, UNIT],
|
||||
rewalk: false,
|
||||
handler: definition,
|
||||
};
|
||||
|
||||
pub const REFERENCES: Tool = Tool {
|
||||
name: "references",
|
||||
title: "Find references",
|
||||
description: "Every use of one declaration across the project, grouped by file as line:col and the line's text — the same occurrences a rename would edit. Select as for `definition`; a bare `name` must name one declaration. Refuses a name lucisv cannot resolve to one declaration, with the reason.",
|
||||
params: &[
|
||||
FILE,
|
||||
LINE,
|
||||
COL,
|
||||
NAME,
|
||||
UNIT,
|
||||
Param {
|
||||
name: "include_declaration",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "List the declaration itself too (default true).",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most hits to return (default 200).",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Hits to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: true,
|
||||
handler: references,
|
||||
};
|
||||
|
||||
fn definition(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let sites = match target(project, args)? {
|
||||
Target::At { path, analysis, offset } => at_position(project, &path, &analysis, offset)?,
|
||||
Target::Named { name, unit } => {
|
||||
let mut sites = by_name(project, &name, unit.as_deref());
|
||||
if sites.is_empty() && project.ensure_walked_for_miss() {
|
||||
sites = by_name(project, &name, unit.as_deref());
|
||||
}
|
||||
if sites.is_empty() {
|
||||
return Err(format!(
|
||||
"no declaration of `{name}`{} is indexed.",
|
||||
in_unit(unit.as_deref())
|
||||
));
|
||||
}
|
||||
sites
|
||||
}
|
||||
};
|
||||
Ok(source::answer(&sites, "definitions", "no declaration"))
|
||||
}
|
||||
|
||||
fn in_unit(unit: Option<&str>) -> String {
|
||||
unit.map_or(String::new(), |unit| format!(" in `{unit}`"))
|
||||
}
|
||||
|
||||
/// The server's ladder at one position: `` `include`` line, macro use, then
|
||||
/// both symbol layers.
|
||||
fn at_position(
|
||||
project: &Project,
|
||||
path: &Path,
|
||||
analysis: &Analysis,
|
||||
offset: u32,
|
||||
) -> Result<Vec<Site>, String> {
|
||||
let file = project.relative(path);
|
||||
let (line, col) = analysis.lines.line_col(offset);
|
||||
if let Some(token) = analysis.token_at(offset) {
|
||||
if token.kind == TokenKind::Directive && token.text.starts_with("`include") {
|
||||
return included(project, path, token).map(|site| vec![site]);
|
||||
}
|
||||
if let Some(name) = macro_name(token).filter(|_| token.is_macro()) {
|
||||
return macro_sites(project, analysis, &file, name);
|
||||
}
|
||||
}
|
||||
let external = analysis.external(project.index());
|
||||
match external.definition_of(&analysis.semantics, offset) {
|
||||
Some(Definition::Local(symbol)) if !symbol.name_span.is_empty() => {
|
||||
Ok(local_sites(analysis, &file, symbol))
|
||||
}
|
||||
Some(Definition::External(defs)) => {
|
||||
let reference = analysis.semantics.reference_at(offset);
|
||||
let name = reference.map_or("", |reference| reference.name.as_str());
|
||||
Ok(def_sites(project, defs, name))
|
||||
}
|
||||
_ => Err(format!("nothing at {file}:{line}:{col} names a declaration.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A local declaration: its completing declaration first (a non-ANSI port's
|
||||
/// body line), then the name, then every redeclaration the binder folded
|
||||
/// into it (`output y; wire y;` declares `y` twice) — one site per line.
|
||||
fn local_sites(analysis: &Analysis, file: &str, symbol: &Symbol) -> Vec<Site> {
|
||||
let (text, lines) = (&analysis.text, &analysis.lines);
|
||||
let kind = render::kind(symbol.kind);
|
||||
let detail = symbol.detail_span.filter(|span| !span.is_empty());
|
||||
let mut sites: Vec<Site> = detail
|
||||
.into_iter()
|
||||
.chain([symbol.name_span])
|
||||
.map(|span| Site::at(file.to_string(), text, lines, span, kind))
|
||||
.collect();
|
||||
let id = analysis.semantics.symbol_at(symbol.name_span.start);
|
||||
for again in analysis.semantics.duplicates().iter().filter(|d| Some(d.first) == id) {
|
||||
let site =
|
||||
Site::at(file.to_string(), text, lines, again.name_span, render::kind(again.kind));
|
||||
if !sites.iter().any(|known| known.line == site.line) {
|
||||
sites.push(site);
|
||||
}
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// Indexed declarations of `name`, each checked against its file's bytes.
|
||||
fn def_sites(project: &Project, defs: &[Def], name: &str) -> Vec<Site> {
|
||||
let mut texts = Texts::default();
|
||||
let mut sites: Vec<Site> = Vec::new();
|
||||
for def in defs {
|
||||
let Some(path) = project.index().path(def.file) else { continue };
|
||||
let shown = def.detail_span.unwrap_or(def.name_span);
|
||||
let kind = render::kind(def.kind);
|
||||
let site = checked_site(project, &mut texts, path, def.name_span, shown, name, kind);
|
||||
if let Some(site) = site {
|
||||
if !sites.iter().any(|s| (&s.file, s.line, s.col) == (&site.file, site.line, site.col))
|
||||
{
|
||||
sites.push(site);
|
||||
}
|
||||
}
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// An `` `include`` line: the named file beside the including one. No
|
||||
/// include-directory ladder is searched.
|
||||
fn included(project: &Project, path: &Path, token: &Token) -> Result<Site, String> {
|
||||
let written = token.text.trim_start_matches("`include").trim();
|
||||
let spelled = written.trim_matches(|c| c == '"' || c == '<' || c == '>');
|
||||
let beside = path.parent().unwrap_or(Path::new("")).join(spelled);
|
||||
let found = beside.to_str().and_then(|candidate| project.resolve(candidate).ok());
|
||||
let Some(target) = found else {
|
||||
return Err(format!(
|
||||
"`include {written} is not beside `{}` (only the including file's directory is searched).",
|
||||
project.relative(path)
|
||||
));
|
||||
};
|
||||
let text = render::one_line(&token.text);
|
||||
Ok(Site { file: project.relative(&target), line: 1, col: 1, kind: "include", text })
|
||||
}
|
||||
|
||||
/// A macro use: this file's own last definition when it has one, else every
|
||||
/// indexed definition (the include graph is not modelled, so none is picked).
|
||||
fn macro_sites(
|
||||
project: &Project,
|
||||
analysis: &Analysis,
|
||||
file: &str,
|
||||
name: &str,
|
||||
) -> Result<Vec<Site>, String> {
|
||||
if let Some(define) = analysis.defines.latest(name) {
|
||||
let (text, lines) = (&analysis.text, &analysis.lines);
|
||||
return Ok(vec![Site::at(file.to_string(), text, lines, define.name_span, "define")]);
|
||||
}
|
||||
let sites = define_sites(project, name);
|
||||
if sites.is_empty() {
|
||||
return Err(format!("`{name} is not defined in any indexed file."));
|
||||
}
|
||||
Ok(sites)
|
||||
}
|
||||
|
||||
/// Every indexed `` `define`` of `name`.
|
||||
pub(super) fn define_sites(project: &Project, name: &str) -> Vec<Site> {
|
||||
let index = project.index();
|
||||
let mut texts = Texts::default();
|
||||
index
|
||||
.find_define(name)
|
||||
.into_iter()
|
||||
.filter_map(|(file, define)| {
|
||||
let path = index.path(file)?;
|
||||
let span = define.name_span;
|
||||
checked_site(project, &mut texts, path, span, span, name, "define")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Declarations by name: a unit's member when `unit` is given, else every
|
||||
/// unit, exported member and module internal of that name; a macro when the
|
||||
/// name is written `` `NAME`` or nothing else declares it.
|
||||
fn by_name(project: &Project, name: &str, unit: Option<&str>) -> Vec<Site> {
|
||||
if let Some(spelled) = name.strip_prefix('`') {
|
||||
return define_sites(project, spelled);
|
||||
}
|
||||
let defs = declarations(project.index(), name, unit);
|
||||
let sites = def_sites(project, &defs, name);
|
||||
if sites.is_empty() && unit.is_none() {
|
||||
return define_sites(project, name);
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// Every indexed declaration of `name` (in `unit`, when given).
|
||||
fn declarations(index: &WorkspaceIndex, name: &str, unit: Option<&str>) -> Vec<Def> {
|
||||
if let Some(unit) = unit {
|
||||
return index.member_in(unit, name, Surface::Hierarchical).to_vec();
|
||||
}
|
||||
let mut defs: Vec<Def> = index.units(name).to_vec();
|
||||
let exported = index.workspace_symbols(name);
|
||||
let members = exported.iter().filter(|hit| hit.name == name && hit.container.is_some());
|
||||
defs.extend(members.map(|hit| hit.def.clone()));
|
||||
defs.extend(index.hierarchical_declarations(name).map(|(_, def)| def.clone()));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
defs.retain(|def| seen.insert(DefinitionKey::of(def)));
|
||||
defs
|
||||
}
|
||||
|
||||
fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let (path, analysis, offset) = match target(project, args)? {
|
||||
Target::At { path, analysis, offset } => (path, analysis, offset),
|
||||
Target::Named { name, unit } => {
|
||||
let (path, offset) = declaration_position(project, &name, unit.as_deref())?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
(path, analysis, offset)
|
||||
}
|
||||
};
|
||||
if let Some(name) = analysis.token_at(offset).filter(|t| t.is_macro()).and_then(macro_name) {
|
||||
return Err(format!("`{name} is a macro; {MACRO_REFUSAL}"));
|
||||
}
|
||||
let set = WholeSet::read(project, Some(&path));
|
||||
let include = args.flag("include_declaration", true);
|
||||
let found = vlog_refactor::find_references(&set.files, &path, offset, include)
|
||||
.map_err(engine_refusal)?;
|
||||
let partial = set.warning(project);
|
||||
let mut texts = Texts::default();
|
||||
for (held, text) in set.files {
|
||||
texts.hold(held, text);
|
||||
}
|
||||
let hits: Vec<Site> = found
|
||||
.iter()
|
||||
.filter_map(|(file, span)| {
|
||||
let (text, lines) = texts.get(file)?;
|
||||
Some(Site::at(project.relative(file), text, lines, *span, "use"))
|
||||
})
|
||||
.collect();
|
||||
let mut answer = render_hits(&hits, args);
|
||||
// A file the index skipped was not searched: the census is partial.
|
||||
if let Some(partial) = partial {
|
||||
answer.text.push_str(&format!("warning: {partial}\n"));
|
||||
answer.structured["warning"] = Value::from(partial);
|
||||
}
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// The one declaration a bare `name` selects for `references` (and `rename`).
|
||||
pub(super) fn declaration_position(
|
||||
project: &mut Project,
|
||||
name: &str,
|
||||
unit: Option<&str>,
|
||||
) -> Result<(PathBuf, u32), String> {
|
||||
let mut defs = declarations(project.index(), name, unit);
|
||||
if defs.is_empty() && project.ensure_walked_for_miss() {
|
||||
defs = declarations(project.index(), name, unit);
|
||||
}
|
||||
let sites = def_sites(project, &defs, name);
|
||||
match (defs.as_slice(), sites.len()) {
|
||||
([def], 1) => {
|
||||
let path = project.index().path(def.file).map(Path::to_path_buf);
|
||||
path.map(|path| (path, def.name_span.start))
|
||||
.ok_or_else(|| format!("`{name}`'s file is no longer indexed."))
|
||||
}
|
||||
(_, 0)
|
||||
if unit.is_none()
|
||||
&& !define_sites(project, name.trim_start_matches('`')).is_empty() =>
|
||||
{
|
||||
Err(format!("`{name}` is a macro; {MACRO_REFUSAL}"))
|
||||
}
|
||||
(_, 0) => Err(format!("no declaration of `{name}`{} is indexed.", in_unit(unit))),
|
||||
_ => {
|
||||
let listed: Vec<String> =
|
||||
sites.iter().map(|site| format!("{}:{}", site.file, site.line)).collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); pick one with `file` and `line`.",
|
||||
listed.len(),
|
||||
listed.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `references` does not answer for a macro.
|
||||
const MACRO_REFUSAL: &str =
|
||||
"references follows declarations, not macros (`defines` lists its definitions).";
|
||||
|
||||
/// The engine's refusal, said as ours: prefixed, and its rename wording —
|
||||
/// `find_references` shares the rename's resolution — turned into this
|
||||
/// tool's.
|
||||
fn engine_refusal(sentence: String) -> String {
|
||||
const REWORDED: &[(&str, &str)] = &[
|
||||
("there is no symbol to rename at this position", "there is no symbol at this position"),
|
||||
(
|
||||
"nothing outside the project scope can be renamed",
|
||||
"nothing outside the project scope is followed",
|
||||
),
|
||||
("lucisv found nothing to rename for", "lucisv found no occurrence of"),
|
||||
("the rename was abandoned", "the search was abandoned"),
|
||||
("which declaration this rename means", "which declaration this position means"),
|
||||
(", so a rename here would only be half a rename", ", so its uses cannot all be listed"),
|
||||
];
|
||||
let mut out = sentence;
|
||||
for (from, to) in REWORDED {
|
||||
out = out.replace(from, to);
|
||||
}
|
||||
format!("lucisv cannot follow this position: {out}")
|
||||
}
|
||||
|
||||
/// Hits grouped by file, `line:col text`, paged.
|
||||
fn render_hits(hits: &[Site], args: &Args) -> Answer {
|
||||
let (shown, rest) =
|
||||
render::page(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = shown
|
||||
.iter()
|
||||
.map(|hit| (hit.file.clone(), format!("{}:{} {}", hit.line, hit.col, hit.text)))
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if hits.is_empty() {
|
||||
text = "no references\n".to_string();
|
||||
}
|
||||
let listed: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|hit| json!({ "file": hit.file, "line": hit.line, "col": hit.col, "text": hit.text }))
|
||||
.collect();
|
||||
Answer { text, structured: json!({ "hits": listed, "total": hits.len() }) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::engine_refusal;
|
||||
|
||||
#[test]
|
||||
fn engine_refusals_are_prefixed_and_never_speak_of_renaming() {
|
||||
for sentence in [
|
||||
"there is no symbol to rename at this position.",
|
||||
"`x` is declared outside the files lucisv indexes, so a rename here would only be half a rename.",
|
||||
"lucisv found nothing to rename for `x`.",
|
||||
"`x` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.",
|
||||
] {
|
||||
let said = engine_refusal(sentence.to_string());
|
||||
assert!(said.starts_with("lucisv cannot follow this position: "), "{said}");
|
||||
assert!(!said.contains("rename"), "{said}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
//! The whole-project read tools: `project_overview`, `list_units`,
|
||||
//! `outline` and `search_symbols`. Each answers from the index (or from one
|
||||
//! file's analysis) and renders by the rules in `render.rs`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_semantic::{Def, DocumentSymbol, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
const LIMIT: Param = Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most entries to return (default 200).",
|
||||
};
|
||||
const OFFSET: Param = Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Entries to skip, for paging past `… and N more` (default 0).",
|
||||
};
|
||||
|
||||
pub const PROJECT_OVERVIEW: Tool = Tool {
|
||||
name: "project_overview",
|
||||
title: "Project overview",
|
||||
description: "Summarise the Verilog/SystemVerilog project under the roots: file count, units by kind, top-level modules (nothing instantiates them) and the largest files. Call it first to orient yourself instead of listing directories.",
|
||||
params: &[],
|
||||
rewalk: true,
|
||||
handler: project_overview,
|
||||
};
|
||||
|
||||
pub const LIST_UNITS: Tool = Tool {
|
||||
name: "list_units",
|
||||
title: "List design units",
|
||||
description: "List the modules, interfaces, packages, classes and programs declared in the project with their file:line, optionally filtered by kind and a name glob (`*`, `?`). Prefer it over grepping for `module` to find where a unit lives.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "kind",
|
||||
ty: Ty::Enum(&["module", "interface", "package", "class", "program"]),
|
||||
required: false,
|
||||
description: "Only units of this kind.",
|
||||
},
|
||||
Param {
|
||||
name: "glob",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Only names matching this pattern; `*` is any run, `?` one character.",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: list_units,
|
||||
};
|
||||
|
||||
pub const OUTLINE: Tool = Tool {
|
||||
name: "outline",
|
||||
title: "File outline",
|
||||
description: "The declarations in one file as a tree with 1-based line ranges (units, ports, parameters, signals, functions, instances, blocks), plus its parse errors. Prefer it over reading a file to see what it contains; then use read_item for the part you need.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file, relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "depth",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Levels to show; 1 is the file's units only (default: all).",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: outline,
|
||||
};
|
||||
|
||||
pub const SEARCH_SYMBOLS: Tool = Tool {
|
||||
name: "search_symbols",
|
||||
title: "Search symbols",
|
||||
description: "Find declarations whose name contains `query` (case-insensitive) across the project: units, and the ports, parameters and package/class members other files can name. Answers file and line per hit; a module's internal signals are not included (use outline for those).",
|
||||
params: &[
|
||||
Param {
|
||||
name: "query",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "Substring of the name to find; empty matches everything.",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: search_symbols,
|
||||
};
|
||||
|
||||
/// One unit in a listing.
|
||||
struct Unit {
|
||||
name: String,
|
||||
kind: &'static str,
|
||||
file: String,
|
||||
line: u32,
|
||||
}
|
||||
|
||||
/// Every unit the index holds, file-scope ones and the classes a package
|
||||
/// declares (named `pkg::cls`), sorted by file then line.
|
||||
fn units(project: &Project) -> Vec<Unit> {
|
||||
let index = project.index();
|
||||
let mut out = Vec::new();
|
||||
for kind in [SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class]
|
||||
{
|
||||
for (name, def) in index.units_of(kind) {
|
||||
out.push(unit(project, name.to_string(), def));
|
||||
}
|
||||
}
|
||||
for (package, _) in index.units_of(SymbolKind::Package) {
|
||||
for (name, defs) in index.members_of(package) {
|
||||
for def in defs.iter().filter(|def| def.kind == SymbolKind::Class) {
|
||||
out.push(unit(project, format!("{package}::{name}"), def));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| (&a.file, a.line, &a.name).cmp(&(&b.file, b.line, &b.name)));
|
||||
out
|
||||
}
|
||||
|
||||
fn unit(project: &Project, name: String, def: &Def) -> Unit {
|
||||
let path = project.index().path(def.file).unwrap_or(Path::new(""));
|
||||
Unit {
|
||||
name,
|
||||
kind: unit_kind(project, path, def),
|
||||
file: project.relative(path),
|
||||
line: def.lines.name,
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit's kind word, telling a `program` from the module it is modelled as.
|
||||
pub fn unit_kind(project: &Project, path: &Path, def: &Def) -> &'static str {
|
||||
if def.kind == SymbolKind::Module && is_program(project, path, def) {
|
||||
"program"
|
||||
} else {
|
||||
render::kind(def.kind)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `Module`-kind unit was declared with `program`. The semantic
|
||||
/// layer models the two alike, so the keyword is read off the text between
|
||||
/// the declaration's start and its name — only for the rare file whose text
|
||||
/// spells `endprogram` at all.
|
||||
fn is_program(project: &Project, path: &Path, def: &Def) -> bool {
|
||||
if !project.stamp(path).is_some_and(|stamp| stamp.program) {
|
||||
return false;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return false;
|
||||
};
|
||||
let head = text.get(def.decl_span.start as usize..def.name_span.start as usize);
|
||||
head.is_some_and(|head| head.split_whitespace().any(|word| word == "program"))
|
||||
}
|
||||
|
||||
/// Whether `name` matches a glob of `*` (any run) and `?` (one character).
|
||||
pub fn glob_match(pattern: &str, name: &str) -> bool {
|
||||
let pattern: Vec<char> = pattern.chars().collect();
|
||||
let name: Vec<char> = name.chars().collect();
|
||||
// Classic two-pointer match with one backtrack point per `*`.
|
||||
let (mut p, mut n, mut star, mut resume) = (0, 0, None, 0);
|
||||
while n < name.len() {
|
||||
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
|
||||
p += 1;
|
||||
n += 1;
|
||||
} else if p < pattern.len() && pattern[p] == '*' {
|
||||
star = Some(p);
|
||||
resume = n;
|
||||
p += 1;
|
||||
} else if let Some(at) = star {
|
||||
p = at + 1;
|
||||
resume += 1;
|
||||
n = resume;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
fn list_units(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let mut all = matching_units(project, args);
|
||||
// A glob names something the agent expects to exist — often a file it
|
||||
// has just written — so a miss walks once before it is believed.
|
||||
if all.is_empty() && args.str("glob").is_some() && project.ensure_walked_for_miss() {
|
||||
all = matching_units(project, args);
|
||||
}
|
||||
let (shown, rest) =
|
||||
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = shown
|
||||
.iter()
|
||||
.map(|u| (u.file.clone(), format!("{} {} {}", u.kind, u.name, u.line)))
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if all.is_empty() {
|
||||
text = "no units match\n".to_string();
|
||||
}
|
||||
let structured: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|u| json!({ "name": u.name, "kind": u.kind, "file": u.file, "line": u.line }))
|
||||
.collect();
|
||||
Ok(Answer { text, structured: json!({ "units": structured, "total": all.len() }) })
|
||||
}
|
||||
|
||||
/// The units `list_units`'s `kind` and `glob` select.
|
||||
fn matching_units(project: &Project, args: &Args) -> Vec<Unit> {
|
||||
units(project)
|
||||
.into_iter()
|
||||
.filter(|unit| args.str("kind").is_none_or(|kind| unit.kind == kind))
|
||||
.filter(|unit| args.str("glob").is_none_or(|glob| glob_match(glob, &unit.name)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn project_overview(project: &mut Project, _: &Args) -> Result<Answer, String> {
|
||||
let overview = Overview::of(project);
|
||||
Ok(Answer { text: overview.text(), structured: overview.json() })
|
||||
}
|
||||
|
||||
/// What `project_overview` reports, gathered once and rendered twice.
|
||||
struct Overview {
|
||||
roots: Vec<String>,
|
||||
config: Option<String>,
|
||||
filelist: Option<String>,
|
||||
files: usize,
|
||||
skipped_large: usize,
|
||||
by_kind: Vec<(&'static str, usize)>,
|
||||
build_ms: u128,
|
||||
age_s: u64,
|
||||
tops: Vec<String>,
|
||||
more_tops: usize,
|
||||
largest: Vec<(String, u64)>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Overview {
|
||||
fn of(project: &Project) -> Overview {
|
||||
let all = units(project);
|
||||
let kinds = ["module", "interface", "package", "class", "program"];
|
||||
let by_kind = kinds
|
||||
.iter()
|
||||
.map(|&kind| (kind, all.iter().filter(|u| u.kind == kind).count()))
|
||||
.collect();
|
||||
let tops = top_modules(project.index());
|
||||
let (shown, more_tops) = render::page(&tops, 0, DEFAULT_LIMIT);
|
||||
let (config, config_problem) = project.config();
|
||||
let discovery = project.discovery();
|
||||
let (build, age) = project.timing();
|
||||
let mut warnings: Vec<String> = discovery.warnings.clone();
|
||||
warnings.extend(config_problem.map(str::to_string));
|
||||
warnings.extend(project.unreadable().iter().cloned());
|
||||
Overview {
|
||||
roots: project.roots().iter().map(|r| r.display().to_string()).collect(),
|
||||
config: config.source.as_ref().map(|path| path.display().to_string()),
|
||||
filelist: discovery.filelist.as_ref().map(|path| path.display().to_string()),
|
||||
files: project.files().count(),
|
||||
skipped_large: discovery.skipped_large,
|
||||
by_kind,
|
||||
build_ms: build.as_millis(),
|
||||
age_s: age.as_secs(),
|
||||
tops: shown.to_vec(),
|
||||
more_tops,
|
||||
largest: largest_files(project, 10),
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let mut text = format!("roots: {}\n", self.roots.join(", "));
|
||||
text.push_str(&format!("config: {}\n", self.config.as_deref().unwrap_or("none")));
|
||||
text.push_str(&format!(
|
||||
"filelist: {}\n",
|
||||
self.filelist.as_deref().unwrap_or("none (walked)")
|
||||
));
|
||||
text.push_str(&format!(
|
||||
"files: {} indexed, {} over 1 MiB skipped\n",
|
||||
self.files, self.skipped_large
|
||||
));
|
||||
let counts: Vec<String> =
|
||||
self.by_kind.iter().map(|(kind, n)| format!("{n} {kind}")).collect();
|
||||
text.push_str(&format!("units: {}\n", counts.join(", ")));
|
||||
text.push_str(&format!(
|
||||
"index: built in {} ms, last changed {} s ago\n",
|
||||
self.build_ms, self.age_s
|
||||
));
|
||||
text.push_str(&format!("top: {}\n", self.tops.join(" ")));
|
||||
render::more(&mut text, self.more_tops);
|
||||
text.push_str("largest:\n");
|
||||
let rows: Vec<Vec<String>> =
|
||||
self.largest.iter().map(|(file, size)| vec![size.to_string(), file.clone()]).collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
for warning in self.warnings.iter().take(10) {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
render::more(&mut text, self.warnings.len().saturating_sub(10));
|
||||
text
|
||||
}
|
||||
|
||||
fn json(&self) -> Value {
|
||||
let units: serde_json::Map<String, Value> =
|
||||
self.by_kind.iter().map(|(kind, n)| (kind.to_string(), json!(n))).collect();
|
||||
let largest: Vec<Value> = self
|
||||
.largest
|
||||
.iter()
|
||||
.map(|(file, bytes)| json!({ "file": file, "bytes": bytes }))
|
||||
.collect();
|
||||
json!({
|
||||
"roots": self.roots,
|
||||
"config": self.config,
|
||||
"filelist": self.filelist,
|
||||
"files": self.files,
|
||||
"skipped_large": self.skipped_large,
|
||||
"units": units,
|
||||
"index_build_ms": self.build_ms as u64,
|
||||
"index_age_s": self.age_s,
|
||||
"top_modules": self.tops,
|
||||
"more_top_modules": self.more_tops,
|
||||
"largest_files": largest,
|
||||
"warnings": self.warnings,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Modules (programs included) nothing in the index instantiates, by name.
|
||||
fn top_modules(index: &WorkspaceIndex) -> Vec<String> {
|
||||
let mut tops: Vec<String> = index
|
||||
.instantiable_units()
|
||||
.filter(|(_, def)| def.kind == SymbolKind::Module)
|
||||
.filter(|(name, _)| index.instantiations_of(name).is_empty())
|
||||
.map(|(name, _)| name.to_string())
|
||||
.collect();
|
||||
tops.dedup();
|
||||
tops
|
||||
}
|
||||
|
||||
/// The `n` largest indexed files, largest first.
|
||||
fn largest_files(project: &Project, n: usize) -> Vec<(String, u64)> {
|
||||
let mut sizes: Vec<(u64, &Path)> =
|
||||
project.files().map(|(path, stamp)| (stamp.size, path.as_path())).collect();
|
||||
sizes.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1)));
|
||||
sizes.into_iter().take(n).map(|(size, path)| (project.relative(path), size)).collect()
|
||||
}
|
||||
|
||||
fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let path = project.resolve(args.str("file").unwrap_or(""))?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let depth = args.count("depth", usize::MAX);
|
||||
let mut rows: Vec<(usize, String, &'static str, u32, u32)> = Vec::new();
|
||||
flatten(&analysis, &analysis.semantics.document_symbols(), 0, depth, &mut rows);
|
||||
let (shown, rest) =
|
||||
render::page(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let file = project.relative(&path);
|
||||
let mut text = format!("{file}\n");
|
||||
let errors = &analysis.diagnostics;
|
||||
if let Some(first) = errors.first() {
|
||||
text.push_str(&format!(
|
||||
"parse errors: {} (first {}:{} {})\n",
|
||||
errors.len(),
|
||||
first.line,
|
||||
first.col,
|
||||
first.message
|
||||
));
|
||||
}
|
||||
for (level, name, kind, first, last) in shown {
|
||||
let indent = " ".repeat(level + 1);
|
||||
text.push_str(&format!("{indent}{kind} {name} {}\n", render::lines(*first, *last)));
|
||||
}
|
||||
render::more(&mut text, rest);
|
||||
let symbols: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|(level, name, kind, first, last)| {
|
||||
json!({ "name": name, "kind": kind, "depth": level + 1, "lines": [first, last] })
|
||||
})
|
||||
.collect();
|
||||
let parse_errors: Vec<Value> = errors
|
||||
.iter()
|
||||
.map(|e| json!({ "line": e.line, "col": e.col, "message": e.message }))
|
||||
.collect();
|
||||
let structured = json!({
|
||||
"file": file, "parse_errors": parse_errors, "symbols": symbols, "total": rows.len(),
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The outline tree in pre-order, each node with its depth and line range.
|
||||
fn flatten(
|
||||
analysis: &crate::project::Analysis,
|
||||
nodes: &[DocumentSymbol],
|
||||
level: usize,
|
||||
depth: usize,
|
||||
out: &mut Vec<(usize, String, &'static str, u32, u32)>,
|
||||
) {
|
||||
if level >= depth {
|
||||
return;
|
||||
}
|
||||
for node in nodes {
|
||||
let Some(symbol) = analysis.semantics.symbol(node.symbol) else {
|
||||
continue;
|
||||
};
|
||||
let (first, last) = analysis.line_span(symbol.decl_span.start, symbol.decl_span.end);
|
||||
out.push((level, symbol.name.clone(), render::kind(symbol.kind), first, last));
|
||||
flatten(analysis, &node.children, level + 1, depth, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn search_symbols(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let query = args.str("query").unwrap_or("");
|
||||
// A miss may be a file written since the last walk: walk once, then answer.
|
||||
if project.index().workspace_symbols(query).is_empty() {
|
||||
project.ensure_walked_for_miss();
|
||||
}
|
||||
let index = project.index();
|
||||
let hits = index.workspace_symbols(query);
|
||||
let (shown, rest) =
|
||||
render::page(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let mut entries = Vec::new();
|
||||
let mut structured = Vec::new();
|
||||
for hit in shown {
|
||||
let name = match hit.container {
|
||||
Some(unit) => format!("{unit}{}{}", separator(index, unit), hit.name),
|
||||
None => hit.name.to_string(),
|
||||
};
|
||||
let file = project.relative(index.path(hit.def.file).unwrap_or(Path::new("")));
|
||||
// A line and no column: the index records a client (UTF-16) column
|
||||
// for units only, and every column this server prints is a byte one.
|
||||
let line = hit.def.lines.name;
|
||||
entries.push((file.clone(), format!("{} {name} {line}", render::kind(hit.def.kind))));
|
||||
structured.push(json!({
|
||||
"name": name, "kind": render::kind(hit.def.kind), "file": file, "line": line,
|
||||
}));
|
||||
}
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if hits.is_empty() {
|
||||
text = "no symbols match\n".to_string();
|
||||
}
|
||||
Ok(Answer { text, structured: json!({ "symbols": structured, "total": hits.len() }) })
|
||||
}
|
||||
|
||||
/// How a member is spelled after its unit: `unit.x` for a module or
|
||||
/// interface (a hierarchical name), `unit::x` for a package or a class —
|
||||
/// including a class the index holds only as a package member.
|
||||
fn separator(index: &WorkspaceIndex, unit: &str) -> &'static str {
|
||||
match index.units(unit).first().map(|def| def.kind) {
|
||||
Some(kind) if kind.is_instantiable() => ".",
|
||||
_ => "::",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::glob_match;
|
||||
|
||||
#[test]
|
||||
fn globs_match_runs_and_single_characters() {
|
||||
assert!(glob_match("prim_*", "prim_fifo_sync"));
|
||||
assert!(glob_match("*fifo*", "prim_fifo_sync"));
|
||||
assert!(glob_match("a?c", "abc"));
|
||||
assert!(glob_match("*", ""));
|
||||
assert!(!glob_match("a?c", "ac"));
|
||||
assert!(!glob_match("prim_*_async", "prim_fifo_sync"));
|
||||
assert!(glob_match("*_sync", "prim_fifo_sync"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! `read_item`: one item's exact text, sliced out of its file — a module, a
|
||||
//! function, a declaration, an instance, or an unlabelled `always` block
|
||||
//! named by the line it covers.
|
||||
//!
|
||||
//! The slicing rule is the one the M4 structural edits will replace by, so
|
||||
//! it lives here on its own: an item is the parser's `Item` node (its
|
||||
//! attributes included, its leading comments not) that declares the name,
|
||||
//! or — for a declaration a larger construct only *contains* (an ANSI port
|
||||
//! in a module header, a function argument) — the declaration's own span.
|
||||
|
||||
use serde_json::json;
|
||||
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::Symbol;
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
pub const READ_ITEM: Tool = Tool {
|
||||
name: "read_item",
|
||||
title: "Read one item",
|
||||
description: "The exact source text and 1-based line range of one item in a file: `name`, `kind:name` (e.g. `function:crc`), `name@LINE` when a name is declared twice, or `always@LINE` / `initial@LINE` / `final@LINE` / `assign@LINE` for the unlabelled block or assignment covering that line (`@LINE` is the last `@` followed only by digits, so `\\a@b@1` is `\\a@b` on line 1). Prefer it over reading the whole file; outline shows what there is.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file, relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "item",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "`name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: read_item,
|
||||
};
|
||||
|
||||
/// The keywords that name an unlabelled item by the line it covers.
|
||||
const BY_LINE: &[&str] = &["always", "initial", "final", "assign"];
|
||||
|
||||
fn read_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let path = project.resolve(args.str("file").unwrap_or(""))?;
|
||||
let file = project.relative(&path);
|
||||
let analysis = project.analysis(&path)?;
|
||||
let selector = args.str("item").unwrap_or("").trim();
|
||||
let (kind, span) =
|
||||
select(&analysis, selector).map_err(|problem| format!("{problem} in `{file}`."))?;
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
let body = analysis.slice(span.start, span.end);
|
||||
let mut text = format!("{file}:{}\n{body}", render::lines(first, last));
|
||||
if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
let structured = json!({
|
||||
"file": file, "item": selector, "kind": kind, "lines": [first, last], "text": body,
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The item `selector` names in this file: its kind word and byte span, or
|
||||
/// the reason there is not exactly one.
|
||||
pub fn select(analysis: &Analysis, selector: &str) -> Result<(&'static str, TextRange), String> {
|
||||
let (head, line) = split_line(selector)?;
|
||||
if let (Some(keyword), Some(line)) = (BY_LINE.iter().find(|k| **k == head), line) {
|
||||
return by_line(analysis, keyword, line).map(|span| (*keyword, span));
|
||||
}
|
||||
let (kind, name) = split_kind(head);
|
||||
let symbol = match by_name(analysis, name, kind, line) {
|
||||
// An escaped identifier may itself end in `@digits` (`\a@12 `): when
|
||||
// the `@LINE` reading finds nothing, the whole spelling is the name.
|
||||
Err(problem) if line.is_some() && name.starts_with('\\') => {
|
||||
let (_, whole) = split_kind(selector);
|
||||
by_name(analysis, whole, kind, None).map_err(|_| problem)?
|
||||
}
|
||||
answer => answer?,
|
||||
};
|
||||
Ok((render::kind(symbol.kind), item_span(analysis, symbol)))
|
||||
}
|
||||
|
||||
/// `kind:` is a prefix only when it is one of the kind words; otherwise the
|
||||
/// colon is part of the name (`\k:l`, an escaped identifier).
|
||||
fn split_kind(head: &str) -> (Option<&str>, &str) {
|
||||
match head.split_once(':') {
|
||||
Some((kind, name)) if render::is_kind_word(kind) => (Some(kind), name),
|
||||
_ => (None, head),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `head@LINE` at the last `@` when only digits follow it; any other
|
||||
/// `@` belongs to the name (`\a@b`).
|
||||
fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
|
||||
match selector.rsplit_once('@') {
|
||||
Some((head, digits))
|
||||
if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) =>
|
||||
{
|
||||
let line = digits
|
||||
.parse::<u32>()
|
||||
.map_err(|_| format!("`{selector}`: line {digits} is out of range"))?;
|
||||
Ok((head, Some(line)))
|
||||
}
|
||||
_ => Ok((selector, None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one declaration of `name` matching the optional kind word and line.
|
||||
fn by_name<'a>(
|
||||
analysis: &'a Analysis,
|
||||
name: &str,
|
||||
kind: Option<&str>,
|
||||
line: Option<u32>,
|
||||
) -> Result<&'a Symbol, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let matches: Vec<&Symbol> = semantics
|
||||
.symbols_named(name)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.filter(|s| kind.is_none_or(|kind| render::kind(s.kind) == kind))
|
||||
.filter(|s| line.is_none_or(|line| analysis.lines.line_col(s.name_span.start).0 == line))
|
||||
.collect();
|
||||
match matches.as_slice() {
|
||||
[one] => Ok(one),
|
||||
[] => Err(format!("no declaration matches `{name}`{}{}", on_kind(kind), on_line(line))),
|
||||
many => {
|
||||
let options: Vec<String> = many
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let line = analysis.lines.line_col(s.name_span.start).0;
|
||||
format!("{}:{name}@{line}", render::kind(s.kind))
|
||||
})
|
||||
.collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); name one",
|
||||
many.len(),
|
||||
options.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_kind(kind: Option<&str>) -> String {
|
||||
kind.map_or(String::new(), |kind| format!(" of kind `{kind}`"))
|
||||
}
|
||||
|
||||
fn on_line(line: Option<u32>) -> String {
|
||||
line.map_or(String::new(), |line| format!(" on line {line}"))
|
||||
}
|
||||
|
||||
/// The span of the item that declares `symbol` (see the module comment).
|
||||
fn item_span(analysis: &Analysis, symbol: &Symbol) -> TextRange {
|
||||
let target = symbol.detail_span.unwrap_or(symbol.name_span);
|
||||
let mut innermost = None;
|
||||
innermost_item(&analysis.tree.items, target, &mut innermost);
|
||||
match innermost {
|
||||
Some(item) if !is_container(&item.kind) || item.span.end == symbol.decl_span.end => {
|
||||
item.span
|
||||
}
|
||||
_ => symbol.detail_span.unwrap_or(symbol.decl_span),
|
||||
}
|
||||
}
|
||||
|
||||
/// Items that hold other declarations: one of these is the answer only when
|
||||
/// it is the symbol's own declaration, not merely the construct around it.
|
||||
fn is_container(kind: &ItemKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
ItemKind::Module(_)
|
||||
| ItemKind::Package { .. }
|
||||
| ItemKind::Class(_)
|
||||
| ItemKind::Function(_)
|
||||
| ItemKind::Task(_)
|
||||
| ItemKind::Always { .. }
|
||||
| ItemKind::Initial(_)
|
||||
| ItemKind::Final(_)
|
||||
| ItemKind::GenerateRegion { .. }
|
||||
| ItemKind::GenIf(_)
|
||||
| ItemKind::GenFor(_)
|
||||
| ItemKind::GenCase(_)
|
||||
| ItemKind::GenBlock(_)
|
||||
| ItemKind::Covergroup(_)
|
||||
| ItemKind::PropSeqDecl(_)
|
||||
| ItemKind::Clocking(_)
|
||||
| ItemKind::Constraint(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// The deepest item whose span contains `target`.
|
||||
fn innermost_item<'t>(items: &'t [Item], target: TextRange, found: &mut Option<&'t Item>) {
|
||||
for item in items {
|
||||
if item.span.start <= target.start && target.end <= item.span.end {
|
||||
*found = Some(item);
|
||||
for children in child_items(&item.kind) {
|
||||
innermost_item(children, target, found);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The item lists nested directly inside one item.
|
||||
pub(super) fn child_items(kind: &ItemKind) -> Vec<&[Item]> {
|
||||
match kind {
|
||||
ItemKind::Module(module) => vec![&module.items],
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => vec![items],
|
||||
ItemKind::Class(class) => vec![&class.items],
|
||||
ItemKind::GenBlock(block) => vec![&block.items],
|
||||
ItemKind::GenFor(generate) => vec![&generate.body.items],
|
||||
ItemKind::GenCase(generate) => {
|
||||
generate.items.iter().map(|arm| arm.body.items.as_slice()).collect()
|
||||
}
|
||||
ItemKind::GenIf(generate) => gen_if_items(generate),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_if_items(generate: &GenIf) -> Vec<&[Item]> {
|
||||
let mut out: Vec<&[Item]> = vec![&generate.then.items];
|
||||
match generate.els.as_deref() {
|
||||
Some(GenElse::If(_, nested)) => out.extend(gen_if_items(nested)),
|
||||
Some(GenElse::Block(GenBlock { items, .. })) => out.push(items),
|
||||
None => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The unlabelled `keyword` item whose lines cover `line`.
|
||||
fn by_line(analysis: &Analysis, keyword: &str, line: u32) -> Result<TextRange, String> {
|
||||
let mut hits = Vec::new();
|
||||
collect_keyword(&analysis.tree.items, keyword, &mut hits);
|
||||
hits.into_iter()
|
||||
.find(|span| {
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
first <= line && line <= last
|
||||
})
|
||||
.ok_or_else(|| format!("no `{keyword}` item covers line {line}"))
|
||||
}
|
||||
|
||||
fn collect_keyword(items: &[Item], keyword: &str, out: &mut Vec<TextRange>) {
|
||||
for item in items {
|
||||
let hit = match &item.kind {
|
||||
ItemKind::Always { kw, .. } => kw.starts_with(keyword),
|
||||
ItemKind::Initial(_) => keyword == "initial",
|
||||
ItemKind::Final(_) => keyword == "final",
|
||||
ItemKind::ContAssign(_) => keyword == "assign",
|
||||
_ => false,
|
||||
};
|
||||
if hit {
|
||||
out.push(item.span);
|
||||
}
|
||||
for children in child_items(&item.kind) {
|
||||
collect_keyword(children, keyword, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SRC: &str = r"module m #(parameter int W = 8) (input logic clk, input logic [W-1:0] d);
|
||||
logic [W-1:0] q, r;
|
||||
always_ff @(posedge clk)
|
||||
q <= d;
|
||||
function automatic int f(int a);
|
||||
return a;
|
||||
endfunction
|
||||
sub u_sub (.*);
|
||||
endmodule
|
||||
module n; logic q; endmodule
|
||||
";
|
||||
|
||||
fn text(selector: &str) -> Result<String, String> {
|
||||
let analysis = Analysis::of(SRC.to_string());
|
||||
select(&analysis, selector)
|
||||
.map(|(_, span)| analysis.slice(span.start, span.end).to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_slices_its_whole_item_and_a_contained_declaration_only_itself() {
|
||||
assert!(text("m").unwrap().starts_with("module m #("));
|
||||
assert!(text("m").unwrap().ends_with("endmodule"));
|
||||
assert_eq!(
|
||||
text("f").unwrap(),
|
||||
"function automatic int f(int a);\n return a;\nendfunction"
|
||||
);
|
||||
assert_eq!(text("a").unwrap(), "int a");
|
||||
assert_eq!(text("d").unwrap(), "input logic [W-1:0] d");
|
||||
assert_eq!(text("r").unwrap(), "logic [W-1:0] q, r;");
|
||||
assert_eq!(text("u_sub").unwrap(), "sub u_sub (.*);");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_parameter_and_a_non_ansi_port_slice_their_own_declarations() {
|
||||
assert_eq!(text("W").unwrap(), "parameter int W = 8");
|
||||
let analysis =
|
||||
Analysis::of("module k (a, b);\n input [3:0] a;\n output b;\nendmodule\n".into());
|
||||
let (kind, span) = select(&analysis, "a").unwrap();
|
||||
assert_eq!((kind, analysis.slice(span.start, span.end)), ("port", "input [3:0] a;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_count_lines_the_same_way() {
|
||||
let analysis = Analysis::of(
|
||||
"module a;\r\n logic x;\r\n always_comb\r\n x = 1;\r\nendmodule\r\n".into(),
|
||||
);
|
||||
let (_, span) = select(&analysis, "x").unwrap();
|
||||
assert_eq!(analysis.line_span(span.start, span.end), (2, 2));
|
||||
let (_, block) = select(&analysis, "always@4").unwrap();
|
||||
assert_eq!(analysis.line_span(block.start, block.end), (3, 4));
|
||||
assert_eq!(analysis.slice(block.start, block.end), "always_comb\r\n x = 1;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_names_an_unlabelled_block_and_disambiguates_a_name() {
|
||||
assert_eq!(text("always@4").unwrap(), "always_ff @(posedge clk)\n q <= d;");
|
||||
assert!(text("always@1").unwrap_err().contains("no `always` item covers line 1"));
|
||||
let ambiguous = text("q").unwrap_err();
|
||||
assert!(ambiguous.contains("var:q@2") && ambiguous.contains("var:q@10"), "{ambiguous}");
|
||||
assert_eq!(text("q@10").unwrap(), "logic q;");
|
||||
assert_eq!(text("var:q@2").unwrap(), "logic [W-1:0] q, r;");
|
||||
assert!(text("function:m").unwrap_err().contains("of kind `function`"));
|
||||
assert!(text("q@x").unwrap_err().contains("no declaration matches `q@x`"));
|
||||
assert!(text("q@99999999999").unwrap_err().contains("out of range"));
|
||||
assert!(text("nokind:q").unwrap_err().contains("no declaration matches `nokind:q`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_name_ending_in_at_digits_is_its_own_name_when_no_line_matches() {
|
||||
let analysis = Analysis::of("module \\a@12 (input z); endmodule\n".into());
|
||||
let (kind, span) = select(&analysis, "\\a@12").unwrap();
|
||||
assert_eq!(kind, "module");
|
||||
assert!(analysis.slice(span.start, span.end).starts_with("module \\a@12 "));
|
||||
let (_, by_kind) = select(&analysis, "module:\\a@12").unwrap();
|
||||
assert_eq!(by_kind, span);
|
||||
let refused = select(&analysis, "\\b@12").unwrap_err();
|
||||
assert!(refused.contains("`\\b` on line 12"), "{refused}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
//! The refactorings that are not "act at this cursor": `add_port` (a module
|
||||
//! and a declaration), `extract_module` (a line range and a new name), and
|
||||
//! `instantiate`, which writes nothing at all — it answers with the text of
|
||||
//! an instantiation for the agent to place.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{instantiation_plan, module_definition, Home, Layout, ModuleRef};
|
||||
|
||||
use super::edit::{enclosing, finish, whole_set, DRY_RUN};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
|
||||
pub const ADD_PORT: Tool = Tool {
|
||||
name: "add_port",
|
||||
title: "Add a port",
|
||||
description: "Add one ANSI port to a module and a connection for it to every instantiation in the project, verified before anything is written. Name the module by `module`, or by `file`+`line` inside its declaration; `declaration` is the port as written in the header (`input logic [7:0] cfg`). Refuses a port that exists, an ordered instantiation of a different length, and a list split by `ifdef`s. `dry_run` returns the diff.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "module",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The module's name (declared once in the project).",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Instead of `module`: the file declaring it, with `line`.",
|
||||
},
|
||||
Param {
|
||||
name: "line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "1-based line inside the module's declaration in `file`.",
|
||||
},
|
||||
Param {
|
||||
name: "declaration",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "One directed ANSI port declaration, e.g. `input logic [7:0] cfg`.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: true,
|
||||
handler: add_port,
|
||||
};
|
||||
|
||||
pub const EXTRACT_MODULE: Tool = Tool {
|
||||
name: "extract_module",
|
||||
title: "Extract lines into a module",
|
||||
description: "Move the whole items on lines `start_line`..`end_line` of a module into a new module `new_name`, whose ports come from the dataflow across the selection, and instantiate it in their place; verified before anything is written. `home: new_file` (default) creates `new_name.sv` beside the file (refused if it exists); `same_file` writes it below the module. Refuses a partial item and names it cannot carry. `dry_run` returns the diff.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file holding the module, relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "start_line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: true,
|
||||
description: "First line of the selection (1-based).",
|
||||
},
|
||||
Param {
|
||||
name: "end_line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: true,
|
||||
description: "Last line of the selection (1-based, included).",
|
||||
},
|
||||
Param {
|
||||
name: "new_name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The new module's name; nothing in the project may declare it yet.",
|
||||
},
|
||||
Param {
|
||||
name: "home",
|
||||
ty: Ty::Enum(&["new_file", "same_file"]),
|
||||
required: false,
|
||||
description: "Where the new module goes: `new_file` (default) or `same_file`.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: true,
|
||||
handler: extract_module,
|
||||
};
|
||||
|
||||
pub const INSTANTIATE: Tool = Tool {
|
||||
name: "instantiate",
|
||||
title: "Instantiation template",
|
||||
description: "The text of an instantiation of module `name` for the agent to place — parameters with their defaults, the instance name, and each port connected to a same-named signal (`named`) or as `.*` (`wildcard`). Writes nothing. Refuses a module that is not indexed or is declared twice (pass `file` to pick one).",
|
||||
params: &[
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The module (or interface) to instantiate.",
|
||||
},
|
||||
Param {
|
||||
name: "style",
|
||||
ty: Ty::Enum(&["named", "wildcard"]),
|
||||
required: false,
|
||||
description: "`named` connections (default) or `.*`.",
|
||||
},
|
||||
Param {
|
||||
name: "with_params",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Write the `#( … )` parameter overrides (default true).",
|
||||
},
|
||||
Param {
|
||||
name: "instance",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The instance name (default `u_<name>`).",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The file declaring the module, when more than one does.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: instantiate,
|
||||
};
|
||||
|
||||
fn add_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let declaration = args.str("declaration").unwrap_or_default();
|
||||
match (args.str("module"), args.str("file"), args.int("line")) {
|
||||
(Some(name), None, None) => {
|
||||
let set = whole_set(project, None, &[name.to_string()])?;
|
||||
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(name), declaration)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
(None, Some(file), Some(line)) => {
|
||||
let path = project.resolve(file)?;
|
||||
let offset = line_start(project, &path, line)?;
|
||||
let names = enclosing(&*project.analysis(&path)?, offset);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let module = ModuleRef::At { file: &path, offset };
|
||||
let edit = vlog_refactor::add_port(&set.files, module, declaration)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
_ => Err("name the module by `module`, or by `file` and `line`, not both.".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte offset where 1-based `line` of `path` starts; `end` asks for
|
||||
/// where it ends instead (its line ending excluded).
|
||||
fn line_offset(project: &mut Project, path: &Path, line: i64, end: bool) -> Result<u32, String> {
|
||||
let analysis = project.analysis(path)?;
|
||||
let count = analysis.lines.line_count();
|
||||
let range = u32::try_from(line).ok().and_then(|line| analysis.lines.line_range(line));
|
||||
let Some(range) = range else {
|
||||
let file = project.relative(path);
|
||||
return Err(format!("line {line} is past the end of `{file}` ({count} lines)."));
|
||||
};
|
||||
Ok(if end { range.end } else { range.start })
|
||||
}
|
||||
|
||||
fn line_start(project: &mut Project, path: &Path, line: i64) -> Result<u32, String> {
|
||||
line_offset(project, path, line, false)
|
||||
}
|
||||
|
||||
fn extract_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let file = args.str("file").unwrap_or_default();
|
||||
let path = project.resolve(file)?;
|
||||
let (first, last) = (args.int("start_line").unwrap_or(1), args.int("end_line").unwrap_or(1));
|
||||
if last < first {
|
||||
return Err(format!("`end_line` {last} is before `start_line` {first}."));
|
||||
}
|
||||
let start = line_start(project, &path, first)?;
|
||||
let end = line_offset(project, &path, last, true)?;
|
||||
let home = match args.str("home") {
|
||||
Some("same_file") => Home::SameFile,
|
||||
_ => Home::NewFile,
|
||||
};
|
||||
let new_name = args.str("new_name").unwrap_or_default();
|
||||
let names = enclosing(&*project.analysis(&path)?, start);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = vlog_refactor::extract_module(&set.files, &path, start, end, new_name, home)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
|
||||
fn instantiate(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").unwrap_or_default();
|
||||
let path = declaring_file(project, name, args.str("file"))?;
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("cannot read `{}`: {e}", project.relative(&path)))?;
|
||||
let mut plan = instantiation_plan(name, &text, None)?;
|
||||
if !args.flag("with_params", true) {
|
||||
plan.params.clear();
|
||||
}
|
||||
let wildcard = args.str("style") == Some("wildcard");
|
||||
if wildcard {
|
||||
plan.ports.clear();
|
||||
}
|
||||
let instance = match args.str("instance") {
|
||||
Some(instance) => identifier(instance)?.to_string(),
|
||||
None => plan.instance_name(),
|
||||
};
|
||||
// `render_with` numbers the fill-ins: each parameter, then the instance.
|
||||
let instance_hole = plan.params.len() + 1;
|
||||
let mut hole = |n: usize, default: &str| {
|
||||
if n == instance_hole {
|
||||
instance.clone()
|
||||
} else {
|
||||
default.into()
|
||||
}
|
||||
};
|
||||
let mut skeleton = plan.render_with(&layout(project), &mut hole);
|
||||
if wildcard {
|
||||
// With no ports the skeleton ends `u_x ();`.
|
||||
skeleton.truncate(skeleton.len() - "();".len());
|
||||
skeleton.push_str("(.*);");
|
||||
}
|
||||
skeleton.push('\n');
|
||||
let file = project.relative(&path);
|
||||
let structured = serde_json::json!({
|
||||
"module": name, "file": file, "text": skeleton, "warnings": plan.warnings,
|
||||
});
|
||||
let mut text = skeleton;
|
||||
for warning in &plan.warnings {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The one file declaring module `name` — `file` when given (it must be a
|
||||
/// file the index says declares it), else the index's single answer, after
|
||||
/// one walk for a module written since the last one.
|
||||
fn declaring_file(
|
||||
project: &mut Project,
|
||||
name: &str,
|
||||
file: Option<&str>,
|
||||
) -> Result<PathBuf, String> {
|
||||
if let Some(file) = file {
|
||||
let path = project.resolve(file)?;
|
||||
let declares = project.index().units(name).iter().any(|def| {
|
||||
def.kind.is_instantiable() && project.index().path(def.file) == Some(path.as_path())
|
||||
});
|
||||
if !declares {
|
||||
return Err(format!("`{file}` declares no module named `{name}`."));
|
||||
}
|
||||
return Ok(path);
|
||||
}
|
||||
let found = module_definition(project.index(), name).map(Path::to_path_buf);
|
||||
match found {
|
||||
Err(_) if project.ensure_walked_for_miss() => {
|
||||
module_definition(project.index(), name).map(Path::to_path_buf)
|
||||
}
|
||||
found => found,
|
||||
}
|
||||
.map_err(|why| {
|
||||
if why.contains("more than one") {
|
||||
format!("{why} Pass `file` to pick one.")
|
||||
} else {
|
||||
why
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `name`, when it is one SystemVerilog identifier: a simple one
|
||||
/// (`[A-Za-z_][A-Za-z0-9_$]*`, not a keyword) or an escaped one (`\`, then
|
||||
/// printable non-space characters, then one space). Anything else would
|
||||
/// render text that does not parse.
|
||||
fn identifier(name: &str) -> Result<&str, String> {
|
||||
let simple = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
|
||||
&& !vlog_parser::token::is_keyword(name);
|
||||
let escaped = name
|
||||
.strip_prefix('\\')
|
||||
.and_then(|rest| rest.strip_suffix(' '))
|
||||
.is_some_and(|body| !body.is_empty() && body.chars().all(|c| c.is_ascii_graphic()));
|
||||
if simple || escaped {
|
||||
return Ok(name);
|
||||
}
|
||||
Err(format!(
|
||||
"`instance` must be one identifier — `[A-Za-z_][A-Za-z0-9_$]*` and not a keyword, or an escaped identifier `\\name ` ending in one space; `{name}` is not."
|
||||
))
|
||||
}
|
||||
|
||||
/// Column zero, one indentation step as the project's lucisv.toml spells it.
|
||||
fn layout(project: &Project) -> Layout {
|
||||
let indent =
|
||||
project.config().0.indent.unwrap_or(vlog_formatter::Config::default().indent_width);
|
||||
Layout { base: String::new(), step: " ".repeat(indent) }
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! The selector `definition` and `references` share: a position (`file` +
|
||||
//! `line` + `col`, or `file` + `line` + the `name` written on that line), a
|
||||
//! name in a file (`file` + `name`), or a bare `name` (with an optional
|
||||
//! `unit`) looked up in the index. A position is picked by **token**, never
|
||||
//! by text, so a comment, a string or a macro argument cannot stand in for
|
||||
//! the code; and a pick that would be a guess is refused with the choices.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{Definition, ExternalResolutions, Symbol};
|
||||
|
||||
use super::Args;
|
||||
use crate::project::{Analysis, Project};
|
||||
|
||||
/// What a selector points at.
|
||||
pub(super) enum Target {
|
||||
/// A byte position in a file.
|
||||
At { path: PathBuf, analysis: Rc<Analysis>, offset: u32 },
|
||||
/// A name to look up in the index, optionally inside one unit.
|
||||
Named { name: String, unit: Option<String> },
|
||||
}
|
||||
|
||||
/// Read the selector; the refusal says which combination is wanted.
|
||||
pub(super) fn target(project: &mut Project, args: &Args) -> Result<Target, String> {
|
||||
let Some(file) = args.str("file") else {
|
||||
if args.int("line").is_some() || args.int("col").is_some() {
|
||||
return Err("`line` and `col` need `file`.".into());
|
||||
}
|
||||
let Some(name) = args.str("name").filter(|name| !name.is_empty()) else {
|
||||
return Err("give `file` with `line` and `col` (or `name`), or a `name`.".into());
|
||||
};
|
||||
let unit = args.str("unit").map(str::to_string);
|
||||
return Ok(Target::Named { name: name.to_string(), unit });
|
||||
};
|
||||
if args.str("unit").is_some() {
|
||||
return Err("`unit` belongs to the by-name form; drop `file`, `line` and `col`.".into());
|
||||
}
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let shown = project.relative(&path);
|
||||
let offset =
|
||||
offset_in(project, &shown, &analysis, args).map_err(|e| format!("{e} (in `{file}`)"))?;
|
||||
Ok(Target::At { path, analysis, offset })
|
||||
}
|
||||
|
||||
/// The byte offset the position arguments name in one file.
|
||||
fn offset_in(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
args: &Args,
|
||||
) -> Result<u32, String> {
|
||||
let name = args.str("name").filter(|name| !name.is_empty());
|
||||
let line = args.int("line").map(|line| u32::try_from(line).unwrap_or(u32::MAX));
|
||||
let col = args.int("col").map(|col| u32::try_from(col).unwrap_or(u32::MAX));
|
||||
match (line, col, name) {
|
||||
(Some(line), Some(col), _) => at_column(analysis, line, col),
|
||||
(Some(line), None, Some(name)) => on_line(analysis, line, name),
|
||||
(Some(_), None, None) => Err("with `line`, give `col` or the `name` on that line".into()),
|
||||
(None, Some(_), _) => Err("`col` needs `line`".into()),
|
||||
(None, None, Some(name)) => first_occurrence(project, file, analysis, name),
|
||||
(None, None, None) => Err("say what: `line` with `col` or `name`, or a `name`".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `line:col`, refused when the line does not exist or the column lies past
|
||||
/// its end (one past the last byte is the end itself, and allowed).
|
||||
fn at_column(analysis: &Analysis, line: u32, col: u32) -> Result<u32, String> {
|
||||
let lines = analysis.lines.line_count();
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
return Err(format!("line {line} is past the end ({lines} lines)"));
|
||||
};
|
||||
let length = analysis.line_text(line).len() as u32;
|
||||
if col > length.saturating_add(1) {
|
||||
return Err(format!("line {line} is {length} bytes long; `col` {col} is past its end"));
|
||||
}
|
||||
Ok(range.start + col - 1)
|
||||
}
|
||||
|
||||
/// The first token on `line` that spells `name`: an identifier, or a macro
|
||||
/// use when `name` is written `` `NAME``. A name found only inside a macro
|
||||
/// call's argument text is refused — lucisv does not resolve those.
|
||||
fn on_line(analysis: &Analysis, line: u32, name: &str) -> Result<u32, String> {
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
return Err(format!("line {line} is past the end ({} lines)", analysis.lines.line_count()));
|
||||
};
|
||||
let touching =
|
||||
|| analysis.tokens.iter().filter(|t| t.span.end > range.start && t.span.start <= range.end);
|
||||
let wanted_macro = name.strip_prefix('`');
|
||||
let hit = touching().find(|token| match wanted_macro {
|
||||
Some(spelled) => token.is_macro() && macro_name(token) == Some(spelled),
|
||||
None => {
|
||||
token.kind == TokenKind::Ident && !token.is_macro() && token.text.trim_end() == name
|
||||
}
|
||||
});
|
||||
if let Some(token) = hit {
|
||||
return Ok(token.span.start.max(range.start));
|
||||
}
|
||||
let in_argument =
|
||||
touching().any(|t| t.is_macro() && super::source::word_in(&t.text, name).is_some());
|
||||
if wanted_macro.is_none() && in_argument {
|
||||
return Err(format!(
|
||||
"`{name}` on line {line} is inside a macro argument, which lucisv does not resolve; give `col` on a plain use"
|
||||
));
|
||||
}
|
||||
Err(format!("`{name}` is not written on line {line}"))
|
||||
}
|
||||
|
||||
/// Where `name` occurs in a file: its one declaration, else its uses when
|
||||
/// they all name one declaration, else its first macro use.
|
||||
fn first_occurrence(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
name: &str,
|
||||
) -> Result<u32, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let declared: Vec<&Symbol> =
|
||||
semantics.symbols_named(name).filter_map(|id| semantics.symbol(id)).collect();
|
||||
match declared.as_slice() {
|
||||
[one] => return Ok(one.name_span.start),
|
||||
[] => {}
|
||||
many => {
|
||||
let lines: Vec<String> = many
|
||||
.iter()
|
||||
.map(|symbol| analysis.lines.line_col(symbol.name_span.start).0.to_string())
|
||||
.collect();
|
||||
return Err(format!(
|
||||
"`{name}` is declared {} times (lines {}); add `line`",
|
||||
many.len(),
|
||||
lines.join(", ")
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(offset) = one_use(project, file, analysis, name)? {
|
||||
return Ok(offset);
|
||||
}
|
||||
let spelled = name.strip_prefix('`').unwrap_or(name);
|
||||
analysis
|
||||
.tokens
|
||||
.iter()
|
||||
.find(|token| token.is_macro() && macro_name(token) == Some(spelled))
|
||||
.map(|token| token.span.start)
|
||||
.ok_or_else(|| format!("`{name}` is not written here"))
|
||||
}
|
||||
|
||||
/// The first use of `name` in a file that declares none — refused, listing
|
||||
/// a line per declaration, when its uses name different declarations.
|
||||
fn one_use(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
name: &str,
|
||||
) -> Result<Option<u32>, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let mut uses = semantics.references().iter().filter(|reference| reference.name == name);
|
||||
let Some(first) = uses.next() else { return Ok(None) };
|
||||
let external = analysis.external(project.index());
|
||||
let mut targets: Vec<(u32, String)> = Vec::new();
|
||||
for reference in std::iter::once(first).chain(uses) {
|
||||
let offset = reference.name_span.start;
|
||||
let Some(target) = declared_at(project, file, analysis, &external, offset) else {
|
||||
continue;
|
||||
};
|
||||
if !targets.iter().any(|(_, known)| *known == target) {
|
||||
targets.push((analysis.lines.line_col(offset).0, target));
|
||||
}
|
||||
}
|
||||
if targets.len() > 1 {
|
||||
let listed: Vec<String> =
|
||||
targets.iter().map(|(line, target)| format!("line {line} → {target}")).collect();
|
||||
return Err(format!("`{name}` on {}; add `line`", listed.join(", ")));
|
||||
}
|
||||
Ok(Some(first.name_span.start))
|
||||
}
|
||||
|
||||
/// Where the use at `offset` is declared, as `file:line` (several joined
|
||||
/// with ` or `), or `None` when nothing resolves it.
|
||||
fn declared_at(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
external: &ExternalResolutions,
|
||||
offset: u32,
|
||||
) -> Option<String> {
|
||||
match external.definition_of(&analysis.semantics, offset)? {
|
||||
Definition::Local(symbol) => {
|
||||
Some(format!("{file}:{}", analysis.lines.line_col(symbol.name_span.start).0))
|
||||
}
|
||||
Definition::External(defs) => {
|
||||
let index = project.index();
|
||||
let sites: Vec<String> = defs
|
||||
.iter()
|
||||
.filter_map(|def| {
|
||||
let path = index.path(def.file)?;
|
||||
Some(format!("{}:{}", project.relative(path), def.lines.name))
|
||||
})
|
||||
.collect();
|
||||
(!sites.is_empty()).then(|| sites.join(" or "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The macro a use token names: `` `NAME(args) `` → `NAME`.
|
||||
pub(super) fn macro_name(token: &Token) -> Option<&str> {
|
||||
let rest = token.text.strip_prefix('`')?;
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$');
|
||||
let name = &rest[..end.unwrap_or(rest.len())];
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
//! Declaration sites read back off the disk: the navigation tools answer
|
||||
//! with `file:line:col`, the kind, and the declaration's own source line,
|
||||
//! for declarations in files no analysis is held for. One read per file per
|
||||
//! call ([`Texts`]); the index's spans are checked against the bytes before
|
||||
//! they are printed, so a stale span is omitted, never mislocated.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::render;
|
||||
|
||||
/// File texts read during one call, each with its line table.
|
||||
#[derive(Default)]
|
||||
pub struct Texts {
|
||||
held: HashMap<PathBuf, Option<(String, LineIndex)>>,
|
||||
}
|
||||
|
||||
impl Texts {
|
||||
/// The text of `path` and its line table, read on first use; `None` for
|
||||
/// a file that no longer reads as UTF-8.
|
||||
pub fn get(&mut self, path: &Path) -> Option<(&str, &LineIndex)> {
|
||||
let held = self.held.entry(path.to_path_buf()).or_insert_with(|| {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let lines = LineIndex::new(&text);
|
||||
Some((text, lines))
|
||||
});
|
||||
held.as_ref().map(|(text, lines)| (text.as_str(), lines))
|
||||
}
|
||||
|
||||
/// Keep a text the caller already read, so it is not read again.
|
||||
pub fn hold(&mut self, path: PathBuf, text: String) {
|
||||
let lines = LineIndex::new(&text);
|
||||
self.held.insert(path, Some((text, lines)));
|
||||
}
|
||||
}
|
||||
|
||||
/// One place a declaration (or a use) is written.
|
||||
pub struct Site {
|
||||
pub file: String,
|
||||
pub line: u32,
|
||||
pub col: u32,
|
||||
pub kind: &'static str,
|
||||
/// The source line, whitespace collapsed.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Site {
|
||||
/// The site of `span` in `text`: its 1-based line and byte column, and
|
||||
/// that line collapsed to one line of text.
|
||||
pub fn at(
|
||||
file: String,
|
||||
text: &str,
|
||||
lines: &LineIndex,
|
||||
span: TextRange,
|
||||
kind: &'static str,
|
||||
) -> Site {
|
||||
let (line, col) = lines.line_col(span.start);
|
||||
let source = lines
|
||||
.line_range(line)
|
||||
.and_then(|range| text.get(range.start as usize..range.end as usize))
|
||||
.unwrap_or("");
|
||||
Site { file, line, col, kind, text: render::one_line(source) }
|
||||
}
|
||||
|
||||
/// `file:line:col kind: text`.
|
||||
pub fn render(&self) -> String {
|
||||
format!("{}:{}:{} {}: {}", self.file, self.line, self.col, self.kind, self.text)
|
||||
}
|
||||
|
||||
pub fn json(&self) -> Value {
|
||||
json!({
|
||||
"file": self.file, "line": self.line, "col": self.col,
|
||||
"kind": self.kind, "text": self.text,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The site of an indexed span in `path`, when the file's bytes there still
|
||||
/// spell `name`; `shown` is the span whose line is printed (a non-ANSI port's
|
||||
/// body declaration rather than its header name).
|
||||
pub fn checked_site(
|
||||
project: &Project,
|
||||
texts: &mut Texts,
|
||||
path: &Path,
|
||||
name_span: TextRange,
|
||||
shown: TextRange,
|
||||
name: &str,
|
||||
kind: &'static str,
|
||||
) -> Option<Site> {
|
||||
let (text, lines) = texts.get(path)?;
|
||||
if text.get(name_span.as_range()) != Some(name) {
|
||||
return None;
|
||||
}
|
||||
Some(Site::at(project.relative(path), text, lines, shown, kind))
|
||||
}
|
||||
|
||||
/// Sites as a text answer (one per line, or `none_text`) and as JSON under
|
||||
/// `key`, with the total.
|
||||
pub fn answer(sites: &[Site], key: &str, none_text: &str) -> super::Answer {
|
||||
let mut text: String = sites.iter().map(|site| site.render() + "\n").collect();
|
||||
if sites.is_empty() {
|
||||
text = format!("{none_text}\n");
|
||||
}
|
||||
let listed: Vec<Value> = sites.iter().map(Site::json).collect();
|
||||
super::Answer { text, structured: json!({ key: listed, "total": sites.len() }) }
|
||||
}
|
||||
|
||||
/// `text` on one line, cut at `cap` characters with `…`.
|
||||
pub fn capped(text: &str, cap: usize) -> String {
|
||||
let flat = render::one_line(text);
|
||||
if flat.chars().count() <= cap {
|
||||
return flat;
|
||||
}
|
||||
let cut: String = flat.chars().take(cap).collect();
|
||||
format!("{cut}…")
|
||||
}
|
||||
|
||||
/// `text` with its `//` and `/* */` comments replaced by a space; string
|
||||
/// literals are kept whole.
|
||||
pub fn without_comments(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(at) = rest.find(['/', '"']) {
|
||||
out.push_str(&rest[..at]);
|
||||
let tail = &rest[at..];
|
||||
let skip = if let Some(line) = tail.strip_prefix("//") {
|
||||
out.push(' ');
|
||||
2 + line.find('\n').unwrap_or(line.len())
|
||||
} else if let Some(block) = tail.strip_prefix("/*") {
|
||||
out.push(' ');
|
||||
2 + block.find("*/").map_or(block.len(), |end| end + 2)
|
||||
} else if let Some(string) = tail.strip_prefix('"') {
|
||||
let end = 1 + string.find('"').map_or(string.len(), |end| end + 1);
|
||||
out.push_str(&tail[..end]);
|
||||
end
|
||||
} else {
|
||||
out.push('/');
|
||||
1
|
||||
};
|
||||
rest = &tail[skip..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The whole in-scope set a cross-file engine is handed: every indexed file,
|
||||
/// and one more when asked, read from disk now — plus every file the set
|
||||
/// could not include (over the size cap, not UTF-8, no longer readable),
|
||||
/// so an answer never pretends those were searched (QA finding 2 of M3).
|
||||
pub struct WholeSet {
|
||||
/// `(path, text)` for every file read.
|
||||
pub files: Vec<(PathBuf, String)>,
|
||||
/// The files left out, with why.
|
||||
pub skipped: Vec<(PathBuf, String)>,
|
||||
}
|
||||
|
||||
impl WholeSet {
|
||||
/// Read every indexed file and `extra` from disk now. The whole set,
|
||||
/// always (M2's ruling on QA finding 1): a use can resolve through files
|
||||
/// that never spell its name, so no narrowing by name is sound.
|
||||
pub fn read(project: &Project, extra: Option<&Path>) -> WholeSet {
|
||||
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
|
||||
wanted.extend(extra.map(Path::to_path_buf));
|
||||
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped() };
|
||||
for path in wanted {
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => set.files.push((path, text)),
|
||||
Err(e) => set.skipped.push((path, format!("no longer reads: {e}"))),
|
||||
}
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
/// The first skipped file whose bytes spell one of `names` as a whole
|
||||
/// word, with why it was skipped and the name it spells.
|
||||
pub fn mentioning<'n>(&self, names: &'n [String]) -> Option<(&Path, &str, &'n str)> {
|
||||
self.skipped.iter().find_map(|(path, why)| {
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
let name = names.iter().find(|name| word_in_bytes(&bytes, name.as_bytes()))?;
|
||||
Some((path.as_path(), why.as_str(), name.as_str()))
|
||||
})
|
||||
}
|
||||
|
||||
/// One line naming the skipped files (ten at most), or `None` when the
|
||||
/// set is complete.
|
||||
pub fn warning(&self, project: &Project) -> Option<String> {
|
||||
if self.skipped.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let named: Vec<String> = self
|
||||
.skipped
|
||||
.iter()
|
||||
.take(10)
|
||||
.map(|(path, why)| format!("{} ({why})", project.relative(path)))
|
||||
.collect();
|
||||
let more = self.skipped.len().saturating_sub(10);
|
||||
let tail = if more > 0 { format!(" and {more} more") } else { String::new() };
|
||||
Some(format!("not indexed, so not searched or edited: {}{tail}", named.join(", ")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` occurs in `bytes` not glued to an identifier character on
|
||||
/// either side — how an identifier, escaped or not, is written.
|
||||
fn word_in_bytes(bytes: &[u8], name: &[u8]) -> bool {
|
||||
let glued =
|
||||
|b: Option<&u8>| b.is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_' || b == b'$');
|
||||
if name.is_empty() || name.len() > bytes.len() {
|
||||
return false;
|
||||
}
|
||||
bytes.windows(name.len()).enumerate().any(|(at, window)| {
|
||||
window == name
|
||||
&& !glued(at.checked_sub(1).and_then(|before| bytes.get(before)))
|
||||
&& !glued(bytes.get(at + name.len()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `c` may continue an identifier.
|
||||
fn is_ident_char(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || c == '_' || c == '$'
|
||||
}
|
||||
|
||||
/// The byte offset, within `line`, of the first whole-word occurrence of
|
||||
/// `name` — a hit not glued to a neighbouring identifier character.
|
||||
pub fn word_in(line: &str, name: &str) -> Option<usize> {
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut from = 0;
|
||||
while let Some(found) = line.get(from..).and_then(|rest| rest.find(name)) {
|
||||
let start = from + found;
|
||||
let end = start + name.len();
|
||||
let before = line[..start].chars().next_back();
|
||||
let after = line[end..].chars().next();
|
||||
let glued = |c: Option<char>| c.is_some_and(is_ident_char);
|
||||
if !glued(before) && (name.starts_with('\\') || !glued(after)) {
|
||||
return Some(start);
|
||||
}
|
||||
from = start + name.len().max(1);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_word_is_found_whole_and_never_inside_another() {
|
||||
assert_eq!(word_in(" assign data_q = data;", "data"), Some(18));
|
||||
assert_eq!(word_in("data_q", "data"), None);
|
||||
assert_eq!(word_in("x = a.data", "data"), Some(6));
|
||||
assert_eq!(word_in("\\a@1 x", "\\a@1"), Some(0));
|
||||
assert_eq!(word_in("anything", ""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skipped_file_is_searched_for_whole_words_only() {
|
||||
assert!(word_in_bytes(b"leaf u (.d(x));", b"d"));
|
||||
assert!(word_in_bytes(b"\xa9 d", b"d"));
|
||||
assert!(!word_in_bytes(b"data d_q $d dd", b"d"));
|
||||
assert!(word_in_bytes(b"d", b"d"));
|
||||
assert!(!word_in_bytes(b"", b"d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_dropped_and_strings_kept() {
|
||||
let text = "#( // why\n .W(8), /* old: 4 */ .S(\"a//b\"), .D(4 / 2) )";
|
||||
assert_eq!(
|
||||
render::one_line(&without_comments(text)),
|
||||
"#( .W(8), .S(\"a//b\"), .D(4 / 2) )"
|
||||
);
|
||||
assert_eq!(without_comments("a /* open"), "a ");
|
||||
assert_eq!(capped("x y", 2), "x …");
|
||||
assert_eq!(capped("x y", 3), "x y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_site_prints_its_line_collapsed() {
|
||||
let text = "module m;\n logic [3:0] x;\nendmodule\n";
|
||||
let lines = LineIndex::new(text);
|
||||
let site = Site::at("m.sv".into(), text, &lines, TextRange::new(27, 28), "var");
|
||||
assert_eq!(site.render(), "m.sv:2:18 var: logic [3:0] x;");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! The MCP stdio transport: one JSON-RPC message per line in, one per line
|
||||
//! out. stdout carries protocol lines and nothing else; stderr is the log.
|
||||
//!
|
||||
//! Generic over the reader and writer so the loop can be driven by tests
|
||||
//! without a process, and so nothing but `rpc::serve` ever names the real
|
||||
//! stdin/stdout.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
|
||||
/// One line read from the client.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Line {
|
||||
/// A line of text, its terminator removed. May be empty or not JSON; the
|
||||
/// caller decides.
|
||||
Text(String),
|
||||
/// A line that is not UTF-8 — answered as a parse error, never a crash.
|
||||
NotUtf8,
|
||||
/// The client closed its end: the loop is over.
|
||||
Eof,
|
||||
}
|
||||
|
||||
/// Reads client lines and writes server lines.
|
||||
pub struct Transport<R, W> {
|
||||
reader: R,
|
||||
writer: W,
|
||||
}
|
||||
|
||||
impl<R: BufRead, W: Write> Transport<R, W> {
|
||||
/// A transport over one reader and one writer.
|
||||
pub fn new(reader: R, writer: W) -> Transport<R, W> {
|
||||
Transport { reader, writer }
|
||||
}
|
||||
|
||||
/// The next line, without its `\n` or `\r\n`.
|
||||
pub fn read_line(&mut self) -> io::Result<Line> {
|
||||
let mut bytes = Vec::new();
|
||||
if self.reader.read_until(b'\n', &mut bytes)? == 0 {
|
||||
return Ok(Line::Eof);
|
||||
}
|
||||
if bytes.last() == Some(&b'\n') {
|
||||
bytes.pop();
|
||||
}
|
||||
if bytes.last() == Some(&b'\r') {
|
||||
bytes.pop();
|
||||
}
|
||||
Ok(match String::from_utf8(bytes) {
|
||||
Ok(text) => Line::Text(text),
|
||||
Err(_) => Line::NotUtf8,
|
||||
})
|
||||
}
|
||||
|
||||
/// Write one message as one line and flush it, so the client sees it now.
|
||||
///
|
||||
/// `serde_json` escapes every control character inside strings, so a
|
||||
/// serialized value never contains a raw newline — the framing rule the
|
||||
/// spec states ("MUST NOT contain embedded newlines") holds by
|
||||
/// construction.
|
||||
pub fn write_message(&mut self, message: &serde_json::Value) -> io::Result<()> {
|
||||
let mut line = serde_json::to_vec(message).map_err(io::Error::other)?;
|
||||
line.push(b'\n');
|
||||
self.writer.write_all(&line)?;
|
||||
self.writer.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lines_are_split_on_newlines_with_crlf_and_a_missing_last_newline_accepted() {
|
||||
let input: &[u8] = b"{\"a\":1}\r\n\n{\"b\":2}";
|
||||
let mut transport = Transport::new(input, Vec::new());
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{\"a\":1}".into()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text(String::new()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{\"b\":2}".into()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Eof);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_is_not_utf8_is_reported_not_fatal() {
|
||||
let input: &[u8] = b"\xff\xfe\n{}\n";
|
||||
let mut transport = Transport::new(input, Vec::new());
|
||||
assert_eq!(transport.read_line().unwrap(), Line::NotUtf8);
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{}".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_message_with_a_newline_in_a_string_is_still_one_line() {
|
||||
let mut transport = Transport::new(&b""[..], Vec::new());
|
||||
transport.write_message(&serde_json::json!({"text": "a\nb"})).unwrap();
|
||||
let written = String::from_utf8(transport.writer).unwrap();
|
||||
assert_eq!(written, "{\"text\":\"a\\nb\"}\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Shared types for the fixture design.
|
||||
package types_pkg;
|
||||
parameter int DATA_W = 8;
|
||||
typedef logic [DATA_W-1:0] word_t;
|
||||
|
||||
function automatic word_t invert(word_t w);
|
||||
return ~w;
|
||||
endfunction
|
||||
|
||||
class item;
|
||||
rand word_t data;
|
||||
endclass
|
||||
endpackage
|
||||
@@ -0,0 +1,3 @@
|
||||
module broken (input logic a);
|
||||
assign b = ;
|
||||
endmodule
|
||||
@@ -0,0 +1,5 @@
|
||||
interface bus_if;
|
||||
logic req, gnt;
|
||||
modport master (output req, input gnt);
|
||||
modport slave (input req, output gnt);
|
||||
endinterface
|
||||
@@ -0,0 +1,16 @@
|
||||
module leaf #(
|
||||
parameter int W = 8,
|
||||
parameter bit Pass = 1'b1
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q,
|
||||
input logic [3:0] mem [2]
|
||||
);
|
||||
logic [W-1:0] held;
|
||||
|
||||
always_ff @(posedge clk)
|
||||
held <= d;
|
||||
|
||||
assign q = Pass ? held : '0;
|
||||
endmodule
|
||||
@@ -0,0 +1,16 @@
|
||||
module top
|
||||
import types_pkg::*;
|
||||
(
|
||||
input logic clk
|
||||
);
|
||||
logic [3:0] d, q;
|
||||
logic [3:0] mem [2];
|
||||
word_t data;
|
||||
|
||||
leaf #(.W(4)) u_leaf (.*);
|
||||
bus_if u_bus ();
|
||||
|
||||
always_comb begin
|
||||
data = invert(8'h0f);
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
class scoreboard;
|
||||
int count;
|
||||
function void add();
|
||||
count++;
|
||||
endfunction
|
||||
endclass
|
||||
@@ -0,0 +1,3 @@
|
||||
program test_prog (input logic clk);
|
||||
initial $display("start");
|
||||
endprogram
|
||||
@@ -0,0 +1,4 @@
|
||||
module messy(input logic a,output logic b);
|
||||
assign b=a;
|
||||
// keep this comment
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module cell (
|
||||
input logic clk,
|
||||
input logic en,
|
||||
output logic o
|
||||
);
|
||||
assign o = en;
|
||||
endmodule
|
||||
@@ -0,0 +1,4 @@
|
||||
package edit_pkg;
|
||||
parameter int WIDTH = 8;
|
||||
typedef logic [WIDTH-1:0] word_t;
|
||||
endpackage
|
||||
@@ -0,0 +1,9 @@
|
||||
module ext (
|
||||
input logic clk,
|
||||
input logic [7:0] a,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] s;
|
||||
assign s = a + 8'd1;
|
||||
always_ff @(posedge clk) q <= s;
|
||||
endmodule
|
||||
@@ -0,0 +1,9 @@
|
||||
module inl (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
inv u_inv (
|
||||
.i(x),
|
||||
.o(z)
|
||||
);
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
module inv (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
assign o = ~i;
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module leaf (
|
||||
input logic clk,
|
||||
input logic [7:0] d,
|
||||
output logic [7:0] q
|
||||
);
|
||||
always_ff @(posedge clk) q <= d;
|
||||
endmodule
|
||||
@@ -0,0 +1,11 @@
|
||||
module mid (
|
||||
input logic clk,
|
||||
input logic [7:0] din,
|
||||
output logic [7:0] dout
|
||||
);
|
||||
leaf u_leaf (
|
||||
.clk(clk),
|
||||
.d (din),
|
||||
.q (dout)
|
||||
);
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
module old (a, b, y);
|
||||
input a;
|
||||
input b;
|
||||
output y;
|
||||
assign y = a & b;
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module partial (
|
||||
input logic clk,
|
||||
input logic en,
|
||||
output logic o
|
||||
);
|
||||
cell u_c (.clk(clk));
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module spare (
|
||||
input logic clk,
|
||||
input logic unused_i,
|
||||
output logic o
|
||||
);
|
||||
assign o = clk;
|
||||
endmodule
|
||||
@@ -0,0 +1,10 @@
|
||||
module spare_user (
|
||||
input logic clk,
|
||||
output logic o2
|
||||
);
|
||||
spare u_s (
|
||||
.clk (clk),
|
||||
.unused_i(1'b0),
|
||||
.o (o2)
|
||||
);
|
||||
endmodule
|
||||
@@ -0,0 +1,15 @@
|
||||
module top (
|
||||
input logic clk,
|
||||
input logic [7:0] a,
|
||||
output logic [7:0] y
|
||||
);
|
||||
import edit_pkg::word_t;
|
||||
import edit_pkg::WIDTH;
|
||||
word_t w;
|
||||
assign w = a;
|
||||
leaf u_leaf2 (
|
||||
.clk(clk),
|
||||
.d (w),
|
||||
.q (y)
|
||||
);
|
||||
endmodule
|
||||
@@ -0,0 +1,7 @@
|
||||
module wild (
|
||||
input logic clk,
|
||||
input logic en,
|
||||
output logic o
|
||||
);
|
||||
cell u_cell (.*);
|
||||
endmodule
|
||||
@@ -0,0 +1,2 @@
|
||||
# The chain file is waived for line length.
|
||||
waive --rule=line-length --location=rtl/chain.sv
|
||||
@@ -0,0 +1,7 @@
|
||||
# Lint settings the diagnostics tool must honour.
|
||||
[lint]
|
||||
select = ["line-length", "unused-signal", "no-tabs"]
|
||||
waivers = ["lint/nav.waiver"]
|
||||
|
||||
[lint.line-length]
|
||||
length = 40
|
||||
@@ -0,0 +1,5 @@
|
||||
module chain_a; chain_b u_b (); endmodule
|
||||
module chain_b; chain_c u_c (); endmodule
|
||||
module chain_c; chain_d u_d (); endmodule
|
||||
module chain_d; chain_e u_e (); endmodule
|
||||
module chain_e; missing_m u_missing (); endmodule
|
||||
@@ -0,0 +1,2 @@
|
||||
module checker_m (input logic [3:0] state_q);
|
||||
endmodule
|
||||
@@ -0,0 +1,14 @@
|
||||
`include "defs.svh"
|
||||
module core #(
|
||||
parameter int W = 4
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
logic [W-1:0] state_q;
|
||||
logic spare;
|
||||
always_ff @(posedge clk)
|
||||
state_q <= `ADD(d, 1);
|
||||
assign q = state_q;
|
||||
endmodule
|
||||
@@ -0,0 +1 @@
|
||||
bind core checker_m u_chk (.state_q(state_q));
|
||||
@@ -0,0 +1,2 @@
|
||||
`define NAV_W 4
|
||||
`define ADD(a, b = 1) ((a) + (b))
|
||||
@@ -0,0 +1,6 @@
|
||||
module dual (a, y);
|
||||
input a;
|
||||
output y;
|
||||
wire y;
|
||||
assign y = a;
|
||||
endmodule
|
||||
@@ -0,0 +1,9 @@
|
||||
module top (input logic clk);
|
||||
logic [`NAV_W-1:0] d, q0, q1;
|
||||
logic [`NAV_W-1:0] peek;
|
||||
core #(.W(4)) u_core0 (.clk, .d, .q(q0));
|
||||
core #(
|
||||
.W (8)
|
||||
) u_core1 (.clk, .d, .q(q1));
|
||||
assign peek = u_core0.state_q;
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
module tree #(parameter int N = 4) ();
|
||||
if (N > 1) begin : g_split
|
||||
tree #(.N(N / 2)) u_left ();
|
||||
tree #(.N(N / 2)) u_right ();
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
class env;
|
||||
sb s;
|
||||
function void run();
|
||||
s.count = 0;
|
||||
endfunction
|
||||
endclass
|
||||
@@ -0,0 +1,6 @@
|
||||
class sb;
|
||||
int count;
|
||||
function void add();
|
||||
count++;
|
||||
endfunction
|
||||
endclass
|
||||
@@ -0,0 +1,161 @@
|
||||
//! The opentitan census (TODO-MCP M2): the navigation tools over a real
|
||||
//! checkout, read-only, each answer checked against what the language
|
||||
//! server answers for the same question (`docs/features/references-nav`,
|
||||
//! `references-hierarchical-surface`) and each call's wall time printed.
|
||||
//!
|
||||
//! `#[ignore]`: it needs the checkout. Run with
|
||||
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
|
||||
//! lucisv_mcp --test opentitan -- --ignored --nocapture`.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The checkout: `LUCISV_OPENTITAN`, else the owner's usual path.
|
||||
fn checkout() -> PathBuf {
|
||||
std::env::var_os("LUCISV_OPENTITAN")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/Users/guoliangchen/repo/opentitan"))
|
||||
}
|
||||
|
||||
/// One server over the checkout.
|
||||
struct Session {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
stdout: BufReader<ChildStdout>,
|
||||
next_id: i64,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn over(root: &Path) -> Session {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
|
||||
.args(["--root", root.to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let stdin = child.stdin.take().unwrap();
|
||||
let stdout = BufReader::new(child.stdout.take().unwrap());
|
||||
let mut session = Session { child, stdin, stdout, next_id: 0 };
|
||||
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
|
||||
session
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next_id += 1;
|
||||
let line =
|
||||
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
|
||||
writeln!(self.stdin, "{line}").unwrap();
|
||||
self.stdin.flush().unwrap();
|
||||
let mut answer = String::new();
|
||||
self.stdout.read_line(&mut answer).unwrap();
|
||||
serde_json::from_str(&answer).unwrap()
|
||||
}
|
||||
|
||||
/// A tool call that must succeed, with the wall time printed.
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> Value {
|
||||
let started = Instant::now();
|
||||
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
|
||||
let ms = started.elapsed().as_millis();
|
||||
println!("census: {tool} {arguments} {ms} ms");
|
||||
let result = reply["result"].clone();
|
||||
assert_eq!(result["isError"], false, "{tool}: {result}");
|
||||
result
|
||||
}
|
||||
|
||||
/// [`Session::call`]'s text.
|
||||
fn text(&mut self, tool: &str, arguments: Value) -> String {
|
||||
let result = self.call(tool, arguments);
|
||||
result["content"][0]["text"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// Every `references` hit as `file:line:col`.
|
||||
fn hits(&mut self, arguments: Value) -> Vec<String> {
|
||||
let result = self.call("references", arguments);
|
||||
let hits = result["structuredContent"]["hits"].as_array().unwrap().clone();
|
||||
hits.iter()
|
||||
.map(|h| format!("{}:{}:{}", h["file"].as_str().unwrap(), h["line"], h["col"]))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The language server's answer for the same position (release
|
||||
/// `lucisv-server` over the same checkout, 2026-09-23): every location it
|
||||
/// lists must be in ours.
|
||||
fn assert_covers(ours: &[String], server: &[&str]) {
|
||||
for location in server {
|
||||
assert!(ours.iter().any(|hit| hit == location), "missing {location}: {ours:?}");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// `git status --porcelain` of the checkout, to prove it was only read.
|
||||
fn status(root: &Path) -> Vec<u8> {
|
||||
Command::new("git").arg("-C").arg(root).args(["status", "--porcelain"]).output().unwrap().stdout
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN)"]
|
||||
fn opentitan_navigation_matches_the_language_server() {
|
||||
let root = checkout();
|
||||
let before = status(&root);
|
||||
let mut s = Session::over(&root);
|
||||
// The first call builds the index; its time is the startup cost.
|
||||
s.text("project_overview", json!({}));
|
||||
|
||||
let masking =
|
||||
json!({"file": "hw/ip/aes/rtl/aes.sv", "name": "entropy_masking_req", "limit": 1000});
|
||||
let masking = s.hits(masking);
|
||||
let aes = "hw/ip/aes/rtl/aes.sv";
|
||||
let bind = "hw/ip/aes/dv/sva/aes_bind.sv";
|
||||
let server = [&format!("{bind}:45:27"), &format!("{bind}:54:26"), &format!("{aes}:89:52")];
|
||||
assert_covers(&masking, &server.map(String::as_str));
|
||||
assert_eq!(masking.len(), 6, "{masking:?}");
|
||||
|
||||
let sm = "hw/ip/entropy_src/rtl/entropy_src_main_sm.sv";
|
||||
let state = s.hits(json!({"file": sm, "line": 42, "name": "state_q"}));
|
||||
assert_covers(&state, &["hw/ip/entropy_src/rtl/entropy_src_core.sv:3092:30"]);
|
||||
assert_eq!(state.len(), 5, "{state:?}");
|
||||
|
||||
// The references-nav positions: the `aes` instantiation and its `.clk_i`
|
||||
// in the testbench. The server lists 11 and 9; we list those and the
|
||||
// three top-level `*_pd_main.sv` instantiations it omits (README, work log).
|
||||
let tb = "hw/ip/aes/dv/tb/tb.sv";
|
||||
let instantiated = s.hits(json!({"file": tb, "line": 45, "name": "aes"}));
|
||||
let server = [
|
||||
"hw/ip/aes/dv/cov/aes_cov_bind.sv:8:8",
|
||||
"hw/ip/aes/dv/sva/aes_bind.sv:50:8",
|
||||
"hw/ip/aes/dv/tb/tb.sv:45:3",
|
||||
"hw/ip/aes/pre_dv/aes_tb/rtl/aes_tb.sv:215:3",
|
||||
"hw/ip/aes/rtl/aes.sv:9:8",
|
||||
"hw/ip/aes/rtl/aes_wrap.sv:79:3",
|
||||
];
|
||||
assert_covers(&instantiated, &server);
|
||||
let clock = s.hits(json!({"file": tb, "line": 46, "name": "clk_i"}));
|
||||
assert_covers(&clock, &["hw/ip/aes/rtl/aes.sv:42:53", "hw/ip/aes/rtl/aes.sv:197:31"]);
|
||||
|
||||
let top = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2, "limit": 500}));
|
||||
assert!(top.contains("\n u_aes : aes #("), "{top}");
|
||||
|
||||
let fifo = s.text("definition", json!({"name": "prim_fifo_sync"}));
|
||||
assert!(fifo.starts_with("hw/ip/prim/rtl/prim_fifo_sync.sv:"), "{fifo}");
|
||||
|
||||
let up = s.text("hierarchy", json!({"root": "prim_fifo_sync", "direction": "up", "depth": 1}));
|
||||
assert!(up.contains(".u_"), "{up}");
|
||||
|
||||
s.text("diagnostics", json!({"file": "hw/ip/aes/rtl/aes.sv"}));
|
||||
let clk = json!({"file": "hw/ip/prim/rtl/prim_fifo_sync.sv", "name": "clk_i"});
|
||||
s.text("references", clk);
|
||||
drop(s);
|
||||
assert_eq!(status(&root), before, "the checkout was only read");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -40,7 +40,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
use vlog_semantic::{FileId, WorkspaceIndex};
|
||||
|
||||
/// The extra reach one refactoring asks for.
|
||||
///
|
||||
@@ -80,6 +80,30 @@ pub fn hierarchical_users(index: &WorkspaceIndex, reach: Reach<'_>) -> BTreeSet<
|
||||
out
|
||||
}
|
||||
|
||||
/// The declaring file of every module instantiated in one of `files` — one
|
||||
/// hop down the instantiation edges the index already holds (`bind`
|
||||
/// directives included).
|
||||
///
|
||||
/// A rename's own rungs hand over every file declaring either name, so a
|
||||
/// module a `.*` instantiates is handed over exactly when it declares a port
|
||||
/// that needs a rewrite. When it declares neither name it is not, and the
|
||||
/// engine — which cannot tell "not handed over" from "not in the workspace" —
|
||||
/// refuses the rename as one it cannot check (TODO-MCP M3.5). This rung hands
|
||||
/// those modules over so the engine can see they bind nothing. It can only
|
||||
/// add files, so an edit stays the edit it was; nothing is read or parsed.
|
||||
pub fn instantiated_by(index: &WorkspaceIndex, files: &[&Path]) -> BTreeSet<PathBuf> {
|
||||
let ids: BTreeSet<FileId> = files.iter().filter_map(|path| index.file_id(path)).collect();
|
||||
let mut out = BTreeSet::new();
|
||||
for (module, edges) in index.instantiations() {
|
||||
if !edges.iter().any(|edge| ids.contains(&edge.file)) {
|
||||
continue;
|
||||
}
|
||||
let declared = index.units(module).iter().filter(|def| def.kind.is_instantiable());
|
||||
out.extend(declared.filter_map(|def| index.path(def.file)).map(Path::to_path_buf));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -138,6 +162,15 @@ mod tests {
|
||||
assert!(hierarchical_users(&index, Reach { scopes: &scopes }).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modules_a_file_instantiates_are_one_hop_down_and_no_further() {
|
||||
let index = ladder();
|
||||
let tb = Path::new("/w/tb.sv");
|
||||
let below = instantiated_by(&index, &[tb]);
|
||||
assert_eq!(names(&below), ["wrapper.sv"], "tb instantiates wrapper, and only wrapper");
|
||||
assert!(instantiated_by(&index, &[Path::new("/w/nowhere.sv")]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_reach_asked_for_is_no_work_done() {
|
||||
let index = ladder();
|
||||
|
||||
@@ -359,7 +359,10 @@ mod tests {
|
||||
let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line)
|
||||
.expect("the buffer's own declaration renames");
|
||||
let trace = line.expect("a trace is always written");
|
||||
assert!(trace.contains("reused_files=1"), "only the untouched buffer's record: {trace}");
|
||||
// Two untouched records: the open `bystander.sv`, and `sub.sv`, which
|
||||
// the buffer instantiates and the fan-out's instantiation step hands
|
||||
// over (M3.5) — both reused, and the edited buffer still parsed.
|
||||
assert!(trace.contains("reused_files=2"), "only the untouched files' records: {trace}");
|
||||
assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}");
|
||||
let edits = edit.changes.as_ref().expect("changes").values().flatten().count();
|
||||
assert_eq!(edits, 2, "the declaration and its one use, both in the buffer");
|
||||
|
||||
@@ -58,6 +58,8 @@ mod large_file;
|
||||
mod lint_snapshot;
|
||||
mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod qa_rename_implicit;
|
||||
mod rename_implicit;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod scan_trace;
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! QA M3.5 (2026-09-23): the LSP's rename against `.*`/`.name`, over the wire,
|
||||
//! on the engine tests' fixtures — the fan-out must hand the engine every
|
||||
//! file an implicit connection of the name lives in, open buffer or disk.
|
||||
|
||||
use super::*;
|
||||
|
||||
const LEAF: &str = "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n";
|
||||
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
const TOP2: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
|
||||
|
||||
/// Rename the name at (`line`, `character`) of `uri`.
|
||||
fn rename_at(session: &mut Session, uri: &Uri, line: u32, character: u32, new: &str) -> Response {
|
||||
session.request(
|
||||
Rename::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
"newName": new,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `text` with the LSP edits applied (ASCII fixtures: a character is a byte).
|
||||
fn applied(text: &str, edits: &[Value]) -> String {
|
||||
let starts: Vec<usize> =
|
||||
std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)).collect();
|
||||
let offset = |p: &Value| {
|
||||
let line = p["line"].as_u64().expect("line") as usize;
|
||||
starts[line] + p["character"].as_u64().expect("character") as usize
|
||||
};
|
||||
let mut spans: Vec<(usize, usize, String)> = edits
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let range = &e["range"];
|
||||
let text = e["newText"].as_str().expect("newText").to_string();
|
||||
(offset(&range["start"]), offset(&range["end"]), text)
|
||||
})
|
||||
.collect();
|
||||
spans.sort_by_key(|(start, end, _)| (*start, *end));
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0;
|
||||
for (start, end, new) in spans {
|
||||
out.push_str(&text[cursor..start]);
|
||||
out.push_str(&new);
|
||||
cursor = end;
|
||||
}
|
||||
out.push_str(&text[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// The edits for the file named `name` in a rename answer, or none — found
|
||||
/// by the URI's last segment, so a temp dir's symlinked spelling is moot.
|
||||
fn edits_for(answer: &Value, name: &str) -> Vec<Value> {
|
||||
let Some(changes) = answer["changes"].as_object() else { return Vec::new() };
|
||||
let suffix = format!("/{name}");
|
||||
let found = changes.iter().find(|(uri, _)| uri.ends_with(&suffix));
|
||||
found.and_then(|(_, edits)| edits.as_array().cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `d`'s column on line 0 of the three fixtures.
|
||||
fn d_column(text: &str) -> u32 {
|
||||
text.find("] d").expect("the port") as u32 + 2
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_lsp_port_rename_matches_the_engine_with_the_users_on_disk() {
|
||||
let tree = Tree::new("qa_rename_implicit_disk");
|
||||
tree.write("leaf.sv", LEAF);
|
||||
tree.write("top.sv", TOP);
|
||||
tree.write("top2.sv", TOP2);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("leaf.sv"), LEAF);
|
||||
|
||||
let answer =
|
||||
rename_at(&mut session, &uri, 0, d_column(LEAF), "din").response_result.expect("renames");
|
||||
assert_eq!(applied(TOP, &edits_for(&answer, "top.sv")), TOP.replace("(.*)", "(.*, .din(d))"));
|
||||
assert_eq!(applied(TOP2, &edits_for(&answer, "top2.sv")), TOP2.replace(".d,", ".din(d),"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_lsp_rename_reads_the_open_buffer_not_the_disk() {
|
||||
// On disk top.sv connects explicitly; the unsaved buffer uses `.*`.
|
||||
let tree = Tree::new("qa_rename_implicit_buffer");
|
||||
tree.write("leaf.sv", LEAF);
|
||||
let explicit = TOP.replace("(.*)", "(.clk(clk), .d(d), .q(q))");
|
||||
tree.write("top.sv", &explicit);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let top = session.open(&tree.path.join("top.sv"), TOP);
|
||||
let leaf = session.open(&tree.path.join("leaf.sv"), LEAF);
|
||||
|
||||
let answer =
|
||||
rename_at(&mut session, &leaf, 0, d_column(LEAF), "din").response_result.expect("renames");
|
||||
let top_edits = answer["changes"][top.as_str()].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(applied(TOP, &top_edits), TOP.replace("(.*)", "(.*, .din(d))"), "{answer:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_lsp_net_rename_reaches_a_bind_file_spelling_neither_name() {
|
||||
// binds.sv spells neither `d` nor `x`: only `leaf`'s instantiation sites
|
||||
// (leaf declares a port `d`) bring it into the fan-out.
|
||||
let tree = Tree::new("qa_rename_implicit_bind");
|
||||
let top =
|
||||
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
|
||||
let bind = "module binds;\n bind top leaf u_b (.*);\nendmodule\n";
|
||||
tree.write("leaf.sv", LEAF);
|
||||
tree.write("top.sv", top);
|
||||
tree.write("binds.sv", bind);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), top);
|
||||
|
||||
let answer =
|
||||
rename_at(&mut session, &uri, 0, d_column(top), "x").response_result.expect("renames");
|
||||
assert_eq!(
|
||||
applied(bind, &edits_for(&answer, "binds.sv")),
|
||||
bind.replace("(.*)", "(.*, .d(x))"),
|
||||
"{answer:#}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! A rename against `.*` connections, over the wire (TODO-MCP M3.5).
|
||||
//!
|
||||
//! The engine refuses a rename it cannot check against a `.*` whose module it
|
||||
//! cannot read, and the server hands the engine a *fan-out*, not the
|
||||
//! workspace. These pin the fan-out's instantiation step: every module a
|
||||
//! handed-over file instantiates is handed over too, so a `.*` into a module
|
||||
//! the workspace holds is read, not refused — and one into a module the
|
||||
//! workspace does not hold is still refused.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Rename the `d` at line 0, character `character` of `uri` to `x`.
|
||||
fn rename_d(session: &mut Session, uri: &Uri, character: u32) -> Response {
|
||||
session.request(
|
||||
Rename::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": character },
|
||||
"newName": "x",
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic q);\n quiet u_quiet (.*);\n leaf u_leaf (.*);\n assign q = d[0];\nendmodule\n";
|
||||
|
||||
/// Where the `d` of `input logic [7:0] d` sits on line 0.
|
||||
fn d_column() -> u32 {
|
||||
TOP.find("] d").expect("the port") as u32 + 2
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_rename_beside_a_wildcard_into_a_module_declaring_neither_name_succeeds() {
|
||||
let tree = Tree::new("rename_implicit_ok");
|
||||
// `quiet` declares neither `d` nor `x`, so no rung of the name's own
|
||||
// fan-out asks for it — only the instantiation step does.
|
||||
tree.write("quiet.sv", "module quiet (input logic clk);\nendmodule\n");
|
||||
tree.write("leaf.sv", "module leaf (input logic clk, input logic [7:0] d);\nendmodule\n");
|
||||
tree.write("top.sv", TOP);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
|
||||
let answer = rename_d(&mut session, &uri, d_column()).response_result.expect("renames");
|
||||
let edits = answer["changes"][uri.as_str()].as_array().expect("top.sv is edited").clone();
|
||||
let texts: Vec<&str> = edits.iter().filter_map(|e| e["newText"].as_str()).collect();
|
||||
assert!(texts.contains(&", .d(x)"), "the explicit connection: {answer:#}");
|
||||
assert_eq!(texts.iter().filter(|t| **t == "x").count(), 2, "the port and its use: {answer:#}");
|
||||
assert_eq!(edits.len(), 3, "and nothing for `u_quiet`: {answer:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_rename_beside_a_wildcard_into_a_module_outside_the_workspace_is_refused() {
|
||||
let tree = Tree::new("rename_implicit_refused");
|
||||
tree.write("leaf.sv", "module leaf (input logic clk, input logic [7:0] d);\nendmodule\n");
|
||||
tree.write("top.sv", TOP);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
|
||||
let error = rename_d(&mut session, &uri, d_column()).response_result.expect_err("refused");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
|
||||
assert!(
|
||||
error.message.contains(
|
||||
"`u_quiet` at top.sv:2 connects with `.*` to `quiet`, which lucisv cannot read"
|
||||
),
|
||||
"{}",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
@@ -1756,7 +1756,13 @@ impl Workspace {
|
||||
}
|
||||
wanted.on(Rung::OpenBuffer);
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
let (paths, mut trace) = wanted.finish();
|
||||
let (mut paths, mut trace) = wanted.finish();
|
||||
// One hop down: the modules those files instantiate, so a `.*` into
|
||||
// one is read rather than refused (M3.5). In `selected`, under no rung.
|
||||
let handed: Vec<&Path> = paths.keys().map(PathBuf::as_path).collect();
|
||||
for below in module_select::instantiated_by(&self.index, &handed) {
|
||||
paths.entry(below).or_insert(Rung::Instantiation);
|
||||
}
|
||||
// §P2d's census: which rungs asked for files that write neither name
|
||||
// down, and therefore contribute to this request only by shaping how
|
||||
// the others resolve. One record lookup per selected file, no read.
|
||||
|
||||
@@ -0,0 +1,805 @@
|
||||
//! What the rename verifier learns about implicit connections (`.name` and
|
||||
//! `.*`), and why it had to learn it.
|
||||
//!
|
||||
//! The rename contract was "the token stream may not change shape", and the
|
||||
//! resolution print compares references and declarations — and neither sees
|
||||
//! an implicit binding, because nothing is written for one: `.*` records no
|
||||
//! reference, and `.d` records only the port half. That is exactly how a
|
||||
//! rename used to cut `.*`/`.d` bindings and verify clean (M3 QA finding 1).
|
||||
//! So the fix is in two halves, and this is the second:
|
||||
//!
|
||||
//! 1. **The edits may insert, but only connection text.** A rename that
|
||||
//! rewrites implicit connections writes `(net)` after a shorthand or
|
||||
//! `.port(net)` into a list — never anything else. [`insertions_match`]
|
||||
//! holds such a file to the splice contract (the pieces, comments and
|
||||
//! attributes never dropped, no new parse error) *plus* a shape rule: every
|
||||
//! replacement is the old name becoming the new one, and every insertion
|
||||
//! is one of four connection templates spelling only those two names.
|
||||
//! 2. **Every implicit binding is printed, before and after.** For every
|
||||
//! instance in a watched file, [`bindings`] lists what each connection's
|
||||
//! port half and net half name — the net half of `.name` and of each port
|
||||
//! `.*` reaches looked up exactly where the language looks it up. The two
|
||||
//! lists must be equal, which is what refuses a dangling `.*`, a `.d` left
|
||||
//! pointing at nothing, a `.*` that starts binding the new name, and a
|
||||
//! connection added twice.
|
||||
//!
|
||||
//! Only bindings whose port or net spells the old or the new name are
|
||||
//! printed: a rename adds and removes declarations of those two names alone,
|
||||
//! so a lookup of any other name — and a port of any other name — cannot
|
||||
//! move. That is the watched-file argument, applied one level down.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{Connection, ExprKind, ListElem, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
use vlog_semantic::{
|
||||
resolve_external, ExternalResolutions, Semantics, Surface, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use super::ledger::{pieces_match, Split};
|
||||
use super::{anchor_of, Anchor, Shifts};
|
||||
use crate::rename::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::TextEdit;
|
||||
|
||||
/// The rename's lexical contract for a file whose edits insert connection
|
||||
/// text: the old name replaced by the new one, the four connection templates
|
||||
/// inserted — each **where a connection list takes it** — and nothing else
|
||||
/// changed.
|
||||
pub(super) fn insertions_match(
|
||||
before: &str,
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
names: [&str; 2],
|
||||
path: &Path,
|
||||
) -> Result<(), String> {
|
||||
let refusal =
|
||||
|what: &str| format!("the rename would {what} in {}; no edits were made.", display(path));
|
||||
let Ok(old_tokens) = tokenize(before) else {
|
||||
return Err(refusal("edit a file lucisv cannot lex"));
|
||||
};
|
||||
let slots = Slots::of(before);
|
||||
for edit in edits {
|
||||
let honest = match edit.range.is_empty() {
|
||||
true => template(&edit.new_text, names).is_some(),
|
||||
false => replaces_one_name(&old_tokens, edit, names),
|
||||
};
|
||||
if !honest {
|
||||
return Err(refusal(&format!("write `{}`, which is not a rename", edit.new_text)));
|
||||
}
|
||||
if edit.range.is_empty() && !slots.takes(before, edit, edits, names) {
|
||||
let outside = format!("write `{}` outside a connection list", edit.new_text);
|
||||
return Err(refusal(&outside));
|
||||
}
|
||||
}
|
||||
let split = Split::read(before, after, edits, path, "the rename")?;
|
||||
pieces_match(&split, edits, path, "the rename")?;
|
||||
let grew = parse_source_tolerant(after).1.len() > parse_source_tolerant(before).1.len();
|
||||
match grew {
|
||||
true => Err(refusal("leave a connection list that does not parse")),
|
||||
false => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A replacement is the one identifier token spelling the old name, replaced
|
||||
/// by the new name.
|
||||
fn replaces_one_name(
|
||||
tokens: &[vlog_parser::token::Token],
|
||||
edit: &TextEdit,
|
||||
names: [&str; 2],
|
||||
) -> bool {
|
||||
let [old, new] = names;
|
||||
let covered: Vec<_> =
|
||||
tokens.iter().filter(|t| super::ledger::overlaps(t.span, edit.range)).collect();
|
||||
matches!(covered.as_slice(), [only] if only.kind == TokenKind::Ident
|
||||
&& only.span == edit.range
|
||||
&& only.text == old
|
||||
&& edit.new_text == new)
|
||||
}
|
||||
|
||||
/// The four things a rename may insert.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Template {
|
||||
/// `(X)`: a shorthand's net, written out.
|
||||
Tail,
|
||||
/// `,`: the comma before a `//` comment on a list's last element.
|
||||
Comma,
|
||||
/// `.X(Y)`: a connection after that comment, the comma already written.
|
||||
Connection,
|
||||
/// `, .X(Y)`: a connection appended to a list.
|
||||
Appended,
|
||||
}
|
||||
|
||||
/// Which template an insertion spells — `X` and `Y` the old or the new name,
|
||||
/// no comment — or `None`.
|
||||
fn template(text: &str, names: [&str; 2]) -> Option<Template> {
|
||||
let tokens = tokenize(text).ok()?;
|
||||
let mut code: Vec<&str> = Vec::new();
|
||||
for token in &tokens {
|
||||
if !token.leading.is_empty() || token.trailing.is_some() {
|
||||
return None;
|
||||
}
|
||||
match token.kind {
|
||||
TokenKind::Eof => {}
|
||||
TokenKind::Ident if names.contains(&token.text.as_str()) => code.push("name"),
|
||||
TokenKind::Symbol => code.push(token.text.as_str()),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
match code.as_slice() {
|
||||
["(", "name", ")"] => Some(Template::Tail),
|
||||
[","] => Some(Template::Comma),
|
||||
[".", "name", "(", "name", ")"] => Some(Template::Connection),
|
||||
[",", ".", "name", "(", "name", ")"] => Some(Template::Appended),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn is_connection_text(text: &str, names: [&str; 2]) -> bool {
|
||||
template(text, names).is_some()
|
||||
}
|
||||
|
||||
/// Where a rename may insert into one file, read off the **before** tree with
|
||||
/// the walk the engine plans with (`rename::sites`), so the plan and the
|
||||
/// check cannot disagree about what a connection list is (QA M3.5 finding 1:
|
||||
/// the template check alone admitted `,` into a positional list, `(d)` after
|
||||
/// a call argument, `, .din(d)` into a `#(...)` override).
|
||||
struct Slots {
|
||||
/// The end of every shorthand connection's name (`.d` → after `d`).
|
||||
tails: Vec<u32>,
|
||||
/// Every named list holding `.*`: the end of its last element, and its
|
||||
/// closing `)`.
|
||||
lists: Vec<(u32, u32)>,
|
||||
}
|
||||
|
||||
impl Slots {
|
||||
fn of(before: &str) -> Slots {
|
||||
let (tree, _) = parse_source_tolerant(before);
|
||||
let mut out = Slots { tails: Vec::new(), lists: Vec::new() };
|
||||
for site in sites(&tree.items) {
|
||||
// A list holding text the parser could not read has no slot at
|
||||
// all: an error element's span may stop short of its own `)`,
|
||||
// so an append "after the last element" lands inside it, and the
|
||||
// parse check cannot tell — one diagnostic before, one after
|
||||
// (QA M3.5 finding 4). The engine already refuses such lists.
|
||||
if site.unreadable().next().is_some() {
|
||||
continue;
|
||||
}
|
||||
let shorthands = site.connections().filter(|c| c.expr.is_none() && c.name != "*");
|
||||
out.tails.extend(shorthands.map(|c| c.name_span.end));
|
||||
let last = site.conns.last().map(|e| match e {
|
||||
ListElem::Ok(c) => c.span,
|
||||
ListElem::Error(raw) => raw.span,
|
||||
});
|
||||
let close = site.instance.span.end.checked_sub(1);
|
||||
let closed = close.filter(|&at| before.as_bytes().get(at as usize) == Some(&b')'));
|
||||
if let (true, Some(last), Some(close)) = (site.has_wildcard(), last, closed) {
|
||||
out.lists.push((last.end, close));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `edit` — an insertion — lands where its template belongs: a
|
||||
/// net right after a shorthand's name; a connection between a `.*` list's
|
||||
/// last element (and the comments after it) and the list's `)`; and the
|
||||
/// comma-before-`//` pair as a **pair** — a comma right after the last
|
||||
/// element only with a bare connection written into the same list, and a
|
||||
/// bare connection only behind such a comma. A lone `,` leaves `(.*,)`,
|
||||
/// which the tolerant parser does not flag (QA M3.5 finding 3).
|
||||
fn takes(&self, before: &str, edit: &TextEdit, edits: &[TextEdit], names: [&str; 2]) -> bool {
|
||||
let at = edit.range.start;
|
||||
let within = |at: u32, &(end, close): &(u32, u32)| {
|
||||
let gap = before.get(end as usize..at as usize).unwrap_or(",");
|
||||
end <= at && at <= close && tokenize(gap).is_ok_and(|tokens| tokens.len() == 1)
|
||||
};
|
||||
let comma_at =
|
||||
|end: u32| edits.iter().any(|e| e.range == TextRange::empty(end) && e.new_text == ",");
|
||||
let connection_in = |list: &(u32, u32)| {
|
||||
edits.iter().any(|e| {
|
||||
e.range.is_empty()
|
||||
&& template(&e.new_text, names) == Some(Template::Connection)
|
||||
&& within(e.range.start, list)
|
||||
})
|
||||
};
|
||||
let lists = || self.lists.iter();
|
||||
match template(&edit.new_text, names) {
|
||||
Some(Template::Tail) => self.tails.contains(&at),
|
||||
Some(Template::Comma) => lists().any(|list| list.0 == at && connection_in(list)),
|
||||
Some(Template::Connection) => lists().any(|list| within(at, list) && comma_at(list.0)),
|
||||
Some(Template::Appended) => lists().any(|list| within(at, list)),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where file `file`'s inserted connection text sits once the edits are
|
||||
/// applied. The names it spells are the binding print's to account for, not
|
||||
/// the resolution print's: before the edit they were not written.
|
||||
pub(super) fn inserted_in(edits: &[(usize, Vec<TextEdit>)], file: usize) -> Vec<TextRange> {
|
||||
let edits = edits.iter().find(|(f, _)| *f == file);
|
||||
edits.map(|(_, edits)| inserted_after(edits)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Where each insertion's text sits once the edits are applied, so that the
|
||||
/// resolution print does not compare the names inside it — the binding print
|
||||
/// is what accounts for them.
|
||||
fn inserted_after(edits: &[TextEdit]) -> Vec<TextRange> {
|
||||
let mut out = Vec::new();
|
||||
let mut delta: i64 = 0;
|
||||
for edit in edits {
|
||||
let start = (i64::from(edit.range.start) + delta).max(0) as u32;
|
||||
if edit.range.is_empty() {
|
||||
out.push(TextRange::new(start, start + edit.new_text.len() as u32));
|
||||
}
|
||||
delta += edit.new_text.len() as i64 - i64::from(edit.range.len());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What one half of a connection names.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum Bound {
|
||||
/// These declarations, as (file, name span).
|
||||
At(Vec<(PathBuf, u32, u32)>),
|
||||
/// Nothing lucisv can see.
|
||||
Nothing,
|
||||
/// An expression other than a bare name: the resolution print compares
|
||||
/// what is inside it.
|
||||
Expression,
|
||||
/// A name looked up in a scope lucisv cannot name — a hierarchical `bind`
|
||||
/// target, or the `.*` of a module it cannot read (`probe 0`/`probe 1`).
|
||||
Opaque(String),
|
||||
}
|
||||
|
||||
/// One binding of one instance: where the instance is named, what the port
|
||||
/// half names, and what the net half names.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
struct Binding {
|
||||
at: (u32, u32),
|
||||
port: Bound,
|
||||
net: Bound,
|
||||
}
|
||||
|
||||
/// One side of the comparison: a file's tree, its analysis, the index it
|
||||
/// resolves against, and the shift that maps a before-side span to after.
|
||||
struct Side<'x> {
|
||||
tree: &'x SourceFile,
|
||||
semantics: &'x Semantics,
|
||||
external: &'x ExternalResolutions,
|
||||
index: &'x WorkspaceIndex,
|
||||
path: &'x Path,
|
||||
shifts: &'x Shifts,
|
||||
}
|
||||
|
||||
/// The state after the edits, as [`super::verify`] already built it: each
|
||||
/// edited file's new text and analysis, and the after-index.
|
||||
pub(super) struct After<'x> {
|
||||
pub(super) edited: &'x [(PathBuf, String)],
|
||||
pub(super) analyses: &'x [(PathBuf, Semantics)],
|
||||
pub(super) index: &'x WorkspaceIndex,
|
||||
}
|
||||
|
||||
/// Every watched file's implicit bindings must be the same before and after.
|
||||
/// A file that could write none of either name is skipped, unless the edits
|
||||
/// insert into it.
|
||||
pub(super) fn bindings_match(
|
||||
scope: &Scope,
|
||||
watched: &[usize],
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
shifts: &Shifts,
|
||||
after: &After,
|
||||
names: [&str; 2],
|
||||
) -> Result<(), String> {
|
||||
let abandoned = || "lucisv could not verify the rename, so it made no edits.".to_string();
|
||||
for &i in watched {
|
||||
let (Some(path), Some(text), Some(analysis)) =
|
||||
(scope.path(i), scope.text(i), scope.cached(i))
|
||||
else {
|
||||
return Err(abandoned());
|
||||
};
|
||||
let slot = edits.iter().position(|(f, _)| *f == i);
|
||||
let inserts = slot
|
||||
.and_then(|k| edits.get(k))
|
||||
.is_some_and(|(_, e)| e.iter().any(|e| e.range.is_empty()));
|
||||
if !inserts && !may_connect_implicitly(text, &names) {
|
||||
continue;
|
||||
}
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let side = Side {
|
||||
tree: &tree,
|
||||
semantics: &analysis.semantics,
|
||||
external: &analysis.external,
|
||||
index: scope.index(),
|
||||
path,
|
||||
shifts,
|
||||
};
|
||||
let before = bindings(&side, names);
|
||||
let after = match slot.and_then(|k| after.edited.get(k)) {
|
||||
Some((_, text)) => edited_bindings(path, text, after, names),
|
||||
None => scope.against(i, after.index).map(|(semantics, external)| {
|
||||
let identity = Shifts::default();
|
||||
bindings(
|
||||
&Side {
|
||||
tree: &tree,
|
||||
semantics,
|
||||
external: &external,
|
||||
index: after.index,
|
||||
path,
|
||||
shifts: &identity,
|
||||
},
|
||||
names,
|
||||
)
|
||||
}),
|
||||
};
|
||||
let Some(after) = after else { return Err(abandoned()) };
|
||||
if let Some(instance) = first_difference(&before, &after) {
|
||||
let [old, new] = names;
|
||||
return Err(format!(
|
||||
"renaming `{old}` to `{new}` would change what an implicit connection of `{instance}` binds in {}; the rename was abandoned.",
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An edited file's bindings, read off its new text and the analysis the
|
||||
/// after-index was built with.
|
||||
fn edited_bindings(
|
||||
path: &Path,
|
||||
text: &str,
|
||||
after: &After,
|
||||
names: [&str; 2],
|
||||
) -> Option<Vec<(Binding, String)>> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let (_, semantics) = after.analyses.iter().find(|(p, _)| p == path)?;
|
||||
let external = resolve_external(semantics, after.index);
|
||||
let identity = Shifts::default();
|
||||
Some(bindings(
|
||||
&Side {
|
||||
tree: &tree,
|
||||
semantics,
|
||||
external: &external,
|
||||
index: after.index,
|
||||
path,
|
||||
shifts: &identity,
|
||||
},
|
||||
names,
|
||||
))
|
||||
}
|
||||
|
||||
/// The instance whose bindings differ first, if any do.
|
||||
fn first_difference(before: &[(Binding, String)], after: &[(Binding, String)]) -> Option<String> {
|
||||
for n in 0..before.len().max(after.len()) {
|
||||
match (before.get(n), after.get(n)) {
|
||||
(Some((a, _)), Some((b, name))) if a != b => return Some(name.clone()),
|
||||
(Some((_, name)), None) | (None, Some((_, name))) => return Some(name.clone()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Every binding in one file whose port or net spells one of `names`, sorted,
|
||||
/// each with the instance's name for the refusal.
|
||||
fn bindings(side: &Side, names: [&str; 2]) -> Vec<(Binding, String)> {
|
||||
let mut out: Vec<(Binding, String)> = Vec::new();
|
||||
for site in sites(&side.tree.items) {
|
||||
let at = side.shifts.map(side.path, site.instance.name_span);
|
||||
let mut push = |port: Bound, net: Bound| {
|
||||
out.push((Binding { at: (at.start, at.end), port, net }, site.instance.name.clone()))
|
||||
};
|
||||
for c in site.connections().filter(|c| c.name != "*") {
|
||||
if let Some(net) = net_half(side, &site, c, names) {
|
||||
push(port_half(side, c), net);
|
||||
}
|
||||
}
|
||||
if site.has_wildcard() {
|
||||
for (port, net) in wildcard(side, &site, names) {
|
||||
push(port, net);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// What a named connection's port half names: the reference the semantic
|
||||
/// layer recorded for it.
|
||||
fn port_half(side: &Side, c: &Connection) -> Bound {
|
||||
reference_at(side, c.name_span)
|
||||
}
|
||||
|
||||
/// What a named connection's net half names, when the connection is one the
|
||||
/// print covers: `.name`'s implicit net, an explicit bare name, or (for a port
|
||||
/// spelling one of the names) any other expression.
|
||||
fn net_half(side: &Side, site: &Site, c: &Connection, names: [&str; 2]) -> Option<Bound> {
|
||||
let port_named = names.contains(&c.name.as_str());
|
||||
match c.expr.as_ref().map(|e| (&e.kind, e.span)) {
|
||||
None => port_named.then(|| implicit(side, site, &c.name)),
|
||||
Some((ExprKind::Ident(name), span)) if port_named || names.contains(&name.as_str()) => {
|
||||
Some(reference_at(side, span))
|
||||
}
|
||||
Some(_) => port_named.then_some(Bound::Expression),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bindings a `.*` makes for the ports spelling one of `names` that the
|
||||
/// list does not connect explicitly — or, when the module cannot be read, a
|
||||
/// probe of what each name would find there.
|
||||
fn wildcard(side: &Side, site: &Site, names: [&str; 2]) -> Vec<(Bound, Bound)> {
|
||||
let module = &site.instantiation.module;
|
||||
if instantiable(side.index, module) != 1 {
|
||||
let probe = |(slot, name): (usize, &&str)| {
|
||||
(Bound::Opaque(format!("probe {slot}")), implicit(side, site, name))
|
||||
};
|
||||
return names.iter().enumerate().map(probe).collect();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (port, defs) in side.index.members_of(module) {
|
||||
let ports: Vec<_> = defs.iter().filter(|d| d.kind == SymbolKind::Port).collect();
|
||||
if ports.is_empty() || !names.contains(&port) || site.named(port).is_some() {
|
||||
continue;
|
||||
}
|
||||
let at = ports.iter().map(|d| located(side, d.file, d.name_span)).collect();
|
||||
out.push((at_all(at), implicit(side, site, port)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What `.name` or `.*` binds `name` to at `site`: the nearest declaration
|
||||
/// where the instance is written, or — for a `bind` into one plain module —
|
||||
/// that module's own declaration of it.
|
||||
fn implicit(side: &Side, site: &Site, name: &str) -> Bound {
|
||||
match site.bind_target() {
|
||||
Ok(None) => {
|
||||
// The nearest declaration shadows whatever its kind; one `.*`
|
||||
// cannot bind (a parameter, a module) is a binding to nothing.
|
||||
let found = nearest(side.semantics, site.instance.name_span.start, name)
|
||||
.and_then(|s| side.semantics.symbol(s))
|
||||
.filter(|s| binds_implicitly(s.kind));
|
||||
match found {
|
||||
Some(symbol) => at_all(vec![located_here(side, symbol.name_span)]),
|
||||
None => Bound::Nothing,
|
||||
}
|
||||
}
|
||||
Ok(Some(target)) if instantiable(side.index, target) == 1 => {
|
||||
let defs = side.index.member_in(target, name, Surface::Hierarchical);
|
||||
let defs = defs.iter().filter(|d| binds_implicitly(d.kind));
|
||||
at_all(defs.map(|d| located(side, d.file, d.name_span)).collect())
|
||||
}
|
||||
_ => Bound::Opaque(name.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the reference written exactly at `span` resolves to.
|
||||
fn reference_at(side: &Side, span: TextRange) -> Bound {
|
||||
let Some(id) = side.semantics.reference_id_at(span.start) else { return Bound::Nothing };
|
||||
let Some(reference) = side.semantics.reference(id).filter(|r| r.name_span == span) else {
|
||||
return Bound::Nothing;
|
||||
};
|
||||
let anchor = anchor_of(
|
||||
side.semantics,
|
||||
side.external,
|
||||
side.index,
|
||||
side.path,
|
||||
side.shifts,
|
||||
id.0 as usize,
|
||||
reference,
|
||||
);
|
||||
match anchor {
|
||||
Anchor::Local(start, end) => at_all(vec![(side.path.to_path_buf(), start, end)]),
|
||||
Anchor::External(defs) => at_all(defs),
|
||||
Anchor::Unresolved => Bound::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
fn at_all(mut at: Vec<(PathBuf, u32, u32)>) -> Bound {
|
||||
if at.is_empty() {
|
||||
return Bound::Nothing;
|
||||
}
|
||||
at.sort();
|
||||
Bound::At(at)
|
||||
}
|
||||
|
||||
fn located_here(side: &Side, span: TextRange) -> (PathBuf, u32, u32) {
|
||||
let span = side.shifts.map(side.path, span);
|
||||
(side.path.to_path_buf(), span.start, span.end)
|
||||
}
|
||||
|
||||
fn located(side: &Side, file: vlog_semantic::FileId, span: TextRange) -> (PathBuf, u32, u32) {
|
||||
let path = side.index.path(file).unwrap_or(Path::new("?")).to_path_buf();
|
||||
let span = side.shifts.map(&path, span);
|
||||
(path, span.start, span.end)
|
||||
}
|
||||
|
||||
fn instantiable(index: &WorkspaceIndex, name: &str) -> usize {
|
||||
index.units(name).iter().filter(|d| d.kind.is_instantiable()).count()
|
||||
}
|
||||
|
||||
/// Masked-corruption attacks (CLAUDE.md invariant 4): each is an edit the
|
||||
/// rename engine could plausibly produce if it got implicit connections
|
||||
/// wrong, handed straight to the verifier, and each must be refused. The
|
||||
/// honest edit is the control.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::verify;
|
||||
use super::*;
|
||||
use crate::trace::VerifyTrace;
|
||||
|
||||
const LEAF: &str = "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n";
|
||||
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
const TOP2: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
|
||||
|
||||
fn files(top: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![
|
||||
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
|
||||
(PathBuf::from("/rtl/top.sv"), top.to_string()),
|
||||
(PathBuf::from("/rtl/top2.sv"), TOP2.to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
/// The edit replacing the whole word `name` found after `prefix`.
|
||||
fn swap(text: &str, prefix: &str, name: &str, new: &str) -> TextEdit {
|
||||
let from = text.find(prefix).expect("prefix") + prefix.len();
|
||||
let start = (from + text[from..].find(name).expect("name")) as u32;
|
||||
TextEdit { range: TextRange::new(start, start + name.len() as u32), new_text: new.into() }
|
||||
}
|
||||
|
||||
/// The insertion of `new` right after the first `after`.
|
||||
fn put(text: &str, after: &str, new: &str) -> TextEdit {
|
||||
let at = (text.find(after).expect("anchor") + after.len()) as u32;
|
||||
TextEdit { range: TextRange::empty(at), new_text: new.into() }
|
||||
}
|
||||
|
||||
/// Verify a port rename `d` → `din` of `leaf` whose `top.sv` and
|
||||
/// `top2.sv` edits are the ones given.
|
||||
fn port_rename(
|
||||
top: &str,
|
||||
top_edits: Vec<TextEdit>,
|
||||
top2_edits: Vec<TextEdit>,
|
||||
) -> Result<(), String> {
|
||||
let files = files(top);
|
||||
let mut scope = Scope::build(&files);
|
||||
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, top_i, top2) =
|
||||
(index("/rtl/leaf.sv"), index("/rtl/top.sv"), index("/rtl/top2.sv"));
|
||||
let mut edits =
|
||||
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")])];
|
||||
for (file, list) in [(top_i, top_edits), (top2, top2_edits)] {
|
||||
if !list.is_empty() {
|
||||
edits.push((file, list));
|
||||
}
|
||||
}
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
|
||||
}
|
||||
|
||||
fn shorthand_edits(tail: &str) -> Vec<TextEdit> {
|
||||
vec![swap(TOP2, ".clk, .", "d", "din"), put(TOP2, ".clk, .d", tail)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_honest_rewrite_verifies() {
|
||||
let honest = port_rename(TOP, vec![put(TOP, "(.*", ", .din(d)")], shorthand_edits("(d)"));
|
||||
assert_eq!(honest, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rename_that_cut_both_bindings_is_refused() {
|
||||
// QA finding 1, exactly: `.d` became `.din`, `.*` was left alone.
|
||||
let cut = port_rename(TOP, Vec::new(), vec![swap(TOP2, ".clk, .", "d", "din")]);
|
||||
assert!(cut.expect_err("refused").contains("implicit connection of `u_leaf`"));
|
||||
let wildcard_only = port_rename(TOP, Vec::new(), shorthand_edits("(d)"));
|
||||
assert!(wildcard_only.is_err(), "the `.*` in top.sv no longer binds `din`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shorthand_written_out_with_the_wrong_net_is_refused() {
|
||||
// `(din)` spells only the two names, so only the binding print sees it.
|
||||
let wrong = port_rename(TOP, vec![put(TOP, "(.*", ", .din(d)")], shorthand_edits("(din)"));
|
||||
assert!(wrong.is_err(), "`.din(din)` binds nothing top2 declares");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_connection_to_the_wrong_net_is_refused() {
|
||||
let other = port_rename(TOP, vec![put(TOP, "(.*", ", .din(q)")], shorthand_edits("(d)"));
|
||||
assert!(other.is_err(), "`q` is not one of the two names");
|
||||
let swapped = port_rename(TOP, vec![put(TOP, "(.*", ", .d(din)")], shorthand_edits("(d)"));
|
||||
assert!(swapped.is_err(), "`.d(din)` names a port `leaf` no longer has");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insertion_that_is_not_connection_text_is_refused() {
|
||||
for text in [", .din(d) /* c */", "; wire din;", ", .din(d), .din(d)", ", .din(d"] {
|
||||
let bad = port_rename(TOP, vec![put(TOP, "(.*", text)], shorthand_edits("(d)"));
|
||||
assert!(bad.is_err(), "{text:?} must be refused");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_added_beside_an_explicit_one_of_the_same_port_is_refused() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*, .d(8'h0));\nendmodule\n";
|
||||
let honest =
|
||||
port_rename(top, vec![swap(top, "(.*, .", "d", "din")], shorthand_edits("(d)"));
|
||||
assert_eq!(honest, Ok(()));
|
||||
let doubled = port_rename(
|
||||
top,
|
||||
vec![swap(top, "(.*, .", "d", "din"), put(top, "(8'h0)", ", .din(d)")],
|
||||
shorthand_edits("(d)"),
|
||||
);
|
||||
assert!(doubled.is_err(), "the port is connected twice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insertion_into_the_wrong_instance_is_refused() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\n leaf u_two (.clk, .d(d), .q());\nendmodule\n";
|
||||
let wrong = port_rename(
|
||||
top,
|
||||
vec![swap(top, "u_two (.clk, .", "d", "din"), put(top, ".q(", ".din(d)")],
|
||||
shorthand_edits("(d)"),
|
||||
);
|
||||
assert!(wrong.is_err());
|
||||
}
|
||||
|
||||
/// Verify a rename `d` → `x` of top's own port, with the given edits.
|
||||
fn net_rename(top: &str, extra: Vec<TextEdit>) -> Result<(), String> {
|
||||
let files = files(top);
|
||||
let mut scope = Scope::build(&files);
|
||||
let top_i = scope.index_of(Path::new("/rtl/top.sv")).expect("top");
|
||||
let mut list = vec![swap(top, "[7:0] ", "d", "x")];
|
||||
list.extend(extra);
|
||||
list.sort_by_key(|e| e.range.start);
|
||||
verify(&mut scope, &[(top_i, list)], "d", "x", &mut VerifyTrace::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_rename_that_leaves_the_wildcard_alone_is_refused() {
|
||||
assert_eq!(net_rename(TOP, vec![put(TOP, "(.*", ", .d(x)")]), Ok(()));
|
||||
assert!(net_rename(TOP, Vec::new()).is_err(), "`.*` loses `d`");
|
||||
assert!(net_rename(TOP, vec![put(TOP, "(.*", ", .x(d)")]).is_err(), "the halves swapped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_that_starts_binding_the_new_name_is_refused() {
|
||||
let child = "module child (input logic a, input logic b);\nendmodule\n";
|
||||
let top = "module top (input logic a);\n child u_c (.*);\nendmodule\n";
|
||||
let files = vec![
|
||||
(PathBuf::from("/rtl/child.sv"), child.to_string()),
|
||||
(PathBuf::from("/rtl/top.sv"), top.to_string()),
|
||||
];
|
||||
let mut scope = Scope::build(&files);
|
||||
let top_i = scope.index_of(Path::new("/rtl/top.sv")).expect("top");
|
||||
let edits = vec![(top_i, vec![swap(top, "logic ", "a", "b"), put(top, "(.*", ", .a(b)")])];
|
||||
let captured = verify(&mut scope, &edits, "a", "b", &mut VerifyTrace::default());
|
||||
assert!(captured.is_err(), "`.*` now binds `b` to the renamed port");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_rename_behind_an_unreadable_wildcard_is_refused() {
|
||||
let top = "module top (input logic [7:0] d);\n ghost u_g (.*);\nendmodule\n";
|
||||
let files = vec![(PathBuf::from("/rtl/top.sv"), top.to_string())];
|
||||
let mut scope = Scope::build(&files);
|
||||
let edits = vec![(0usize, vec![swap(top, "[7:0] ", "d", "x")])];
|
||||
let blind = verify(&mut scope, &edits, "d", "x", &mut VerifyTrace::default());
|
||||
assert!(blind.is_err(), "the probe of `d` and `x` moved");
|
||||
}
|
||||
|
||||
/// `top2` with every `.` of its shorthand list blanked out: the same
|
||||
/// bytes at the same offsets, but a **positional** list — so its `d`
|
||||
/// ends exactly where `top2`'s shorthand `.d` does.
|
||||
const POSITIONAL: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf ( clk, d, q);\nendmodule\n";
|
||||
|
||||
/// The position check keys on the file's own sites, not on a byte: `(d)`
|
||||
/// at the offset that is a shorthand's end in `top2.sv` is still refused
|
||||
/// in a file where that offset ends a positional element.
|
||||
#[test]
|
||||
fn a_shorthand_offset_is_no_licence_in_another_file() {
|
||||
let end = TOP2.find(".clk, .d").expect("the shorthand") as u32 + 8;
|
||||
assert_eq!(POSITIONAL.find(" clk, d").map(|at| at as u32 + 8), Some(end));
|
||||
let files = vec![
|
||||
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
|
||||
(PathBuf::from("/rtl/top.sv"), TOP.to_string()),
|
||||
(PathBuf::from("/rtl/top2.sv"), TOP2.to_string()),
|
||||
(PathBuf::from("/rtl/top3.sv"), POSITIONAL.to_string()),
|
||||
];
|
||||
let mut scope = Scope::build(&files);
|
||||
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, top, top2, top3) =
|
||||
(at("/rtl/leaf.sv"), at("/rtl/top.sv"), at("/rtl/top2.sv"), at("/rtl/top3.sv"));
|
||||
let tail = |text: &str| TextEdit { range: TextRange::empty(end), new_text: text.into() };
|
||||
let mut edits = vec![
|
||||
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
|
||||
(top, vec![put(TOP, "(.*", ", .din(d)")]),
|
||||
(top2, shorthand_edits("(d)")),
|
||||
(top3, vec![tail("(d)")]),
|
||||
];
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
let outcome = verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default());
|
||||
let refusal = outcome.expect_err("a positional `d(d)` is not a shorthand");
|
||||
assert!(refusal.contains("outside a connection list in top3.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
/// The same inside one file: `(d)` after the shorthand `.d` of one
|
||||
/// instance is the rewrite, `(d)` after the positional `d` of the next is
|
||||
/// not — and `,` after that positional element is not either.
|
||||
#[test]
|
||||
fn a_shorthand_licenses_only_its_own_position() {
|
||||
let top = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\n leaf u_two (clk, d, q);\nendmodule\n";
|
||||
let files = vec![
|
||||
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
|
||||
(PathBuf::from("/rtl/top2.sv"), top.to_string()),
|
||||
];
|
||||
for extra in ["(d)", ","] {
|
||||
let mut scope = Scope::build(&files);
|
||||
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, top2) = (at("/rtl/leaf.sv"), at("/rtl/top2.sv"));
|
||||
let mut list = vec![
|
||||
swap(top, ".clk, .", "d", "din"),
|
||||
put(top, ".clk, .d", "(d)"),
|
||||
put(top, "u_two (clk, d", extra),
|
||||
];
|
||||
list.sort_by_key(|e| e.range.start);
|
||||
let mut edits = vec![
|
||||
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
|
||||
(top2, list),
|
||||
];
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
let outcome = verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default());
|
||||
assert!(outcome.is_err(), "{extra:?} after a positional `d` must be refused");
|
||||
}
|
||||
}
|
||||
|
||||
/// The comma-before-`//` pair must be one pair: a comma closing one
|
||||
/// `.*` list and a bare connection written into another are each half of
|
||||
/// nothing, however well each half is placed.
|
||||
#[test]
|
||||
fn a_comma_and_its_connection_in_different_lists_are_refused() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (\n .* // one\n );\n leaf u_b (\n .* // two\n );\nendmodule\n";
|
||||
let files = vec![
|
||||
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
|
||||
(PathBuf::from("/rtl/top.sv"), top.to_string()),
|
||||
];
|
||||
let verified = |list: Vec<TextEdit>| {
|
||||
let mut scope = Scope::build(&files);
|
||||
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, top_i) = (at("/rtl/leaf.sv"), at("/rtl/top.sv"));
|
||||
let mut list = list;
|
||||
list.sort_by_key(|e| e.range.start);
|
||||
let mut edits = vec![
|
||||
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
|
||||
(top_i, list),
|
||||
];
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
|
||||
};
|
||||
let pair = |list: &str, comment: &str| {
|
||||
vec![put(top, list, ","), put(top, comment, "\n .din(d)")]
|
||||
};
|
||||
let honest: Vec<TextEdit> =
|
||||
[pair("u_a (\n .*", "// one"), pair("u_b (\n .*", "// two")].concat();
|
||||
assert_eq!(verified(honest), Ok(()), "each list's own pair");
|
||||
let crossed: Vec<TextEdit> = [
|
||||
pair("u_a (\n .*", "// one"),
|
||||
vec![put(top, "u_b (\n .*", ","), put(top, "// one", "\n .din(d)")],
|
||||
]
|
||||
.concat();
|
||||
let refusal = verified(crossed).expect_err("u_b's comma has no connection of its own");
|
||||
assert!(refusal.contains("outside a connection list"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_connection_templates_are_exactly_four() {
|
||||
let names = ["d", "din"];
|
||||
for ok in ["(d)", " (din )", ",", ".din(d)", ",\n .din(d)", ", .d(din)"] {
|
||||
assert!(is_connection_text(ok, names), "{ok:?}");
|
||||
}
|
||||
for bad in ["(q)", ",,", ".din(d),", "(d)//c", ".din[0](d)", "(d + d)"] {
|
||||
assert!(!is_connection_text(bad, names), "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,10 @@
|
||||
//! contract, kept separately, so the formatter's safety net does not widen.
|
||||
|
||||
mod after;
|
||||
mod implicit;
|
||||
mod ledger;
|
||||
#[cfg(test)]
|
||||
mod qa_implicit;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -58,10 +61,7 @@ pub(crate) fn verify(
|
||||
let shifts = Shifts::new(scope, edits, new_name);
|
||||
|
||||
// 1. The token stream of every touched file, before and after.
|
||||
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
|
||||
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
|
||||
trace.tokens.measure(|| tokens_match(before, text, &Shift::new(edits), new_name, path))?;
|
||||
}
|
||||
tokens_verified(scope, edits, &edited, [old_name, new_name], &mut trace.tokens)?;
|
||||
|
||||
// 2. What every name resolves to, before and after — in every file the
|
||||
// rename could possibly have moved, not only the ones it edited. A file
|
||||
@@ -98,9 +98,10 @@ pub(crate) fn verify(
|
||||
let (after_index, edited_analyses) = trace.rebuild.measure(|| after_index(scope, &edited));
|
||||
for (n, &i) in watched.iter().enumerate() {
|
||||
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
|
||||
let inserted = implicit::inserted_in(edits, i);
|
||||
let after = trace
|
||||
.after
|
||||
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &[]));
|
||||
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &inserted));
|
||||
let (Some(after), Some(before)) = (after, before.get(n)) else {
|
||||
return Err(ABANDONED.to_string());
|
||||
};
|
||||
@@ -111,6 +112,33 @@ pub(crate) fn verify(
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// 3. What every implicit connection (`.name`, `.*`) binds, before and
|
||||
// after — the bindings no reference records.
|
||||
let after =
|
||||
implicit::After { edited: &edited, analyses: &edited_analyses, index: &after_index };
|
||||
let names = [old_name, new_name];
|
||||
trace.after.measure(|| implicit::bindings_match(scope, &watched, edits, &shifts, &after, names))
|
||||
}
|
||||
|
||||
/// Step 1 of [`verify`]: every touched file's token stream, before and after.
|
||||
/// A file the rename also rewrites an implicit connection in may insert —
|
||||
/// only connection text, where a connection list takes it, checked piece by
|
||||
/// piece (`implicit`); every other file keeps the strict token identity.
|
||||
fn tokens_verified(
|
||||
scope: &Scope,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
edited: &[(PathBuf, String)],
|
||||
names: [&str; 2],
|
||||
stage: &mut crate::trace::Stage,
|
||||
) -> Result<(), String> {
|
||||
for ((i, edits), (path, text)) in edits.iter().zip(edited) {
|
||||
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
|
||||
stage.measure(|| match edits.iter().any(|e| e.range.is_empty()) {
|
||||
true => implicit::insertions_match(before, text, edits, names, path),
|
||||
false => tokens_match(before, text, &Shift::new(edits), names[1], path),
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
//! QA M3.5 (2026-09-23): masked-corruption attacks on the rename verifier's
|
||||
//! implicit-connection widening (`check::implicit`), CLAUDE.md invariant 4.
|
||||
//!
|
||||
//! Each attack hands `verify` the honest edits of a port rename `d` → `din`
|
||||
//! of `leaf` *plus* one corrupting insertion that spells one of the four
|
||||
//! connection templates `insertions_match` admits, placed somewhere a rename
|
||||
//! never writes. The template check looks at an insertion's text, not at
|
||||
//! where it goes, and the resolution print skips inserted ranges — so an
|
||||
//! insertion outside a named connection list is seen by nothing.
|
||||
//!
|
||||
//! Crate-internal because `verify` is: the dev exposed no public hook.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use super::verify;
|
||||
use crate::rename::Scope;
|
||||
use crate::trace::VerifyTrace;
|
||||
use crate::TextEdit;
|
||||
|
||||
const LEAF: &str = "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n";
|
||||
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
const TOP2: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
|
||||
|
||||
/// The attacked file: a positional instance with a parameter override, a
|
||||
/// function call, a task call, a concatenation, a string and a comment.
|
||||
const T3: &str = "module top3 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf #(.W(8)) u_p (clk, d, q);\n initial $display(\"see .d here\");\n // comment .d here\n function automatic logic [7:0] f(input logic [7:0] a, input logic [7:0] b = 0); return a; endfunction\n logic [7:0] r;\n logic [15:0] c;\n assign r = f(d, d);\n assign c = {d, d};\n (* keep *) wire [7:0] w;\n task automatic t(); endtask\n initial t;\n leaf u_n (.clk(clk), .q({q, q}), .*);\nendmodule\n";
|
||||
|
||||
/// The edit replacing the whole word `name` found after `prefix`.
|
||||
fn swap(text: &str, prefix: &str, name: &str, new: &str) -> TextEdit {
|
||||
let from = text.find(prefix).expect("prefix") + prefix.len();
|
||||
let start = (from + text[from..].find(name).expect("name")) as u32;
|
||||
TextEdit { range: TextRange::new(start, start + name.len() as u32), new_text: new.into() }
|
||||
}
|
||||
|
||||
/// The insertion of `new` right after the first `after`.
|
||||
fn put(text: &str, after: &str, new: &str) -> TextEdit {
|
||||
let at = (text.find(after).expect("anchor") + after.len()) as u32;
|
||||
TextEdit { range: TextRange::empty(at), new_text: new.into() }
|
||||
}
|
||||
|
||||
/// Verify the honest port rename `d` → `din` over leaf/top/top2/top3, with
|
||||
/// `extra` edits added to top3 beside its own honest one (`u_n`'s `.*`).
|
||||
fn attack(extra: Vec<TextEdit>) -> Result<(), String> {
|
||||
let files: Vec<(PathBuf, String)> = [
|
||||
("/rtl/leaf.sv", LEAF),
|
||||
("/rtl/top.sv", TOP),
|
||||
("/rtl/top2.sv", TOP2),
|
||||
("/rtl/top3.sv", T3),
|
||||
]
|
||||
.iter()
|
||||
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
|
||||
.collect();
|
||||
let mut scope = Scope::build(&files);
|
||||
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, top, top2, top3) =
|
||||
(index("/rtl/leaf.sv"), index("/rtl/top.sv"), index("/rtl/top2.sv"), index("/rtl/top3.sv"));
|
||||
let mut t3 = vec![put(T3, "u_n (.clk(clk), .q({q, q}), .*", ", .din(d)")];
|
||||
t3.extend(extra);
|
||||
t3.sort_by_key(|e| (e.range.start, e.range.end));
|
||||
let mut edits = vec![
|
||||
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
|
||||
(top, vec![put(TOP, "(.*", ", .din(d)")]),
|
||||
(top2, vec![swap(TOP2, ".clk, .", "d", "din"), put(TOP2, ".clk, .d", "(d)")]),
|
||||
(top3, t3),
|
||||
];
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_honest_edits_verify() {
|
||||
assert_eq!(attack(Vec::new()), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_insertions_the_verifier_already_refuses() {
|
||||
// Inside a string, a comment, an attribute; an empty named element;
|
||||
// `(d)` after a `.*` or after an explicit connection; a connection
|
||||
// before the first element with no comma; a second `.din(d)`.
|
||||
for (anchor, text) in [
|
||||
("see .d", "(d)"),
|
||||
("comment .d", "(d)"),
|
||||
("(* keep", "(d)"),
|
||||
("u_n (.clk(clk),", ","),
|
||||
("u_n (.clk(clk), .q({q, q}), .*", "(d)"),
|
||||
("u_n (.clk(clk)", "(d)"),
|
||||
("u_n (", ".din(d)"),
|
||||
("u_n (.clk(clk), .q({q, q}), .*", ", .din(d)"),
|
||||
] {
|
||||
let outcome = attack(vec![put(T3, anchor, text)]);
|
||||
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA finding 1: an insertion is checked for its text, never for its place.
|
||||
/// A lone `,` in a positional list shifts every later connection one port
|
||||
/// down — `leaf u_p (clk,, d, q)` connects `d` to `q`'s port.
|
||||
#[test]
|
||||
fn qa_a_comma_inserted_into_a_positional_list_is_refused() {
|
||||
let outcome = attack(vec![put(T3, "u_p (clk,", ",")]);
|
||||
assert!(outcome.is_err(), "`u_p (clk,, d, q)` rewires the instance");
|
||||
}
|
||||
|
||||
/// QA finding 1: a connection template inserted outside any connection list.
|
||||
#[test]
|
||||
fn qa_connection_text_outside_a_connection_list_is_refused() {
|
||||
for (anchor, text) in [
|
||||
("#(.W(8)", ", .din(d)"), // a parameter override
|
||||
("assign r = f(d, d", "(d)"), // `d(d)`: a call on a net
|
||||
("assign r = f(d,", ","), // an empty (defaulted) argument
|
||||
("assign r = f(d, d", ", .din(d)"), // a named argument
|
||||
("initial t", "(d)"), // a task call gains an argument
|
||||
("assign c = {d,", ","), // an empty concatenation element
|
||||
] {
|
||||
let outcome = attack(vec![put(T3, anchor, text)]);
|
||||
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused: {outcome:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA finding 1, inside a named list: the template lands inside an explicit
|
||||
/// connection's expression, which the binding print does not look into
|
||||
/// (`Bound::Expression` is printed only for a port spelling one of the
|
||||
/// names) and the resolution print skips.
|
||||
#[test]
|
||||
fn qa_connection_text_inside_an_explicit_connection_is_refused() {
|
||||
for (anchor, text) in [
|
||||
("u_n (.clk(clk", "(d)"), // `.clk(clk(d))`
|
||||
("u_n (.clk(clk), .q({q", "(d)"), // `.q({q(d), q})`
|
||||
("u_n (.clk(clk), .q({q,", ","), // `.q({q,, q})`
|
||||
] {
|
||||
let outcome = attack(vec![put(T3, anchor, text)]);
|
||||
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused: {outcome:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// M3.5 re-check (2026-09-23): attacks on the position rule (`Slots`)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Verify a port rename `d` → `new` of `leaf` (whose two occurrences are
|
||||
/// renamed honestly) with `top3`'s edits exactly as given — nothing honest
|
||||
/// added there.
|
||||
fn port_rename_with(new: &str, top3: &str, edits3: Vec<TextEdit>) -> Result<(), String> {
|
||||
let files: Vec<(PathBuf, String)> = [("/rtl/leaf.sv", LEAF), ("/rtl/top3.sv", top3)]
|
||||
.iter()
|
||||
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
|
||||
.collect();
|
||||
let mut scope = Scope::build(&files);
|
||||
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, top) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
|
||||
let mut edits3 = edits3;
|
||||
edits3.sort_by_key(|e| (e.range.start, e.range.end));
|
||||
let mut edits =
|
||||
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", new), swap(LEAF, "q <= ", "d", new)])];
|
||||
if !edits3.is_empty() {
|
||||
edits.push((top, edits3));
|
||||
}
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
verify(&mut scope, &edits, "d", new, &mut VerifyTrace::default())
|
||||
}
|
||||
|
||||
fn outside(outcome: &Result<(), String>) -> bool {
|
||||
outcome.as_ref().is_err_and(|refusal| refusal.contains("outside a connection list"))
|
||||
}
|
||||
|
||||
const HEAD: &str = "module top3 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n";
|
||||
|
||||
#[test]
|
||||
fn qa_r_an_append_to_a_named_list_without_a_wildcard_is_outside() {
|
||||
let top = format!("{HEAD} leaf u_c (.clk(clk), .q(q));\nendmodule\n");
|
||||
let appended = port_rename_with("din", &top, vec![put(&top, ".q(q)", ", .din(d)")]);
|
||||
assert!(outside(&appended), "no `.*`, no append: {appended:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r_a_tail_after_an_explicit_connections_name_is_outside() {
|
||||
let top = format!("{HEAD} leaf u_c (.clk(clk), .d(d), .q(q));\nendmodule\n");
|
||||
let honest = vec![swap(&top, "(clk), .", "d", "din")];
|
||||
assert_eq!(port_rename_with("din", &top, honest.clone()), Ok(()));
|
||||
for anchor in ["u_c (.clk", "(clk), .d"] {
|
||||
let mut edits = honest.clone();
|
||||
edits.push(put(&top, anchor, "(d)"));
|
||||
let outcome = port_rename_with("din", &top, edits);
|
||||
assert!(outside(&outcome), "`(d)` after {anchor:?}: {outcome:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r_an_insertion_between_two_elements_of_a_wildcard_list_is_outside() {
|
||||
let top = format!("{HEAD} leaf u_n (.*, .clk(clk));\nendmodule\n");
|
||||
let honest = port_rename_with("din", &top, vec![put(&top, ".clk(clk)", ", .din(d)")]);
|
||||
assert_eq!(honest, Ok(()), "the append after the last element is the rewrite");
|
||||
let early = port_rename_with("din", &top, vec![put(&top, "u_n (.*", ", .din(d)")]);
|
||||
assert!(outside(&early), "between `.*` and `.clk(clk)`: {early:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r_an_insertion_after_the_closing_paren_is_outside() {
|
||||
let top = format!("{HEAD} leaf u_n (.*);\nendmodule\n");
|
||||
for text in [", .din(d)", "(d)", ","] {
|
||||
let outcome = port_rename_with("din", &top, vec![put(&top, "u_n (.*)", text)]);
|
||||
assert!(outside(&outcome), "{text:?} after `)`: {outcome:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r_a_wildcard_list_inside_a_generate_block() {
|
||||
let top = format!(
|
||||
"{HEAD} for (genvar i = 0; i < 2; i++) begin : g\n leaf u_g (.*);\n end\nendmodule\n"
|
||||
);
|
||||
let honest = port_rename_with("din", &top, vec![put(&top, "u_g (.*", ", .din(d)")]);
|
||||
assert_eq!(honest, Ok(()), "the generate-scoped `.*` is a slot like any other");
|
||||
// A bare `.din(d)` needs the `,` written before it.
|
||||
let bare = port_rename_with("din", &top, vec![put(&top, "u_g (.*", ".din(d)")]);
|
||||
assert!(outside(&bare), "{bare:?}");
|
||||
// The same `.*` with nothing added cuts the binding.
|
||||
assert!(port_rename_with("din", &top, Vec::new()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r_a_lone_trailing_comma_is_refused() {
|
||||
// `,` at a `.*` list's end is a slot (the comma before a `//` comment),
|
||||
// but written alone it leaves `(.*,)`, which is not a connection list.
|
||||
let top = format!("{HEAD} leaf u_n (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n");
|
||||
let edits = vec![
|
||||
swap(&top, "u_m (.clk, .", "d", "din"),
|
||||
put(&top, "u_m (.clk, .d", "(d)"),
|
||||
put(&top, "u_n (.*", ", .din(d)"),
|
||||
];
|
||||
assert_eq!(port_rename_with("din", &top, edits.clone()), Ok(()));
|
||||
let mut trailing = edits.clone();
|
||||
trailing.push(put(&top, "u_n (.*", ","));
|
||||
trailing.retain(|e| e.new_text != ", .din(d)");
|
||||
let outcome = port_rename_with("din", &top, trailing);
|
||||
assert!(outcome.is_err(), "`(.*,)`: {outcome:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r_positions_are_before_coordinates_whatever_an_earlier_edit_shifts() {
|
||||
// `d` → `dnw` grows the line by 2... and `dnew` by 3, which is exactly the
|
||||
// distance from `.d`'s end to `.q`'s end in `.d,.q`. A tail computed in
|
||||
// after-coordinates lands on `.q`'s shorthand slot in before-coordinates.
|
||||
let top = format!("{HEAD} leaf u_s (.clk,.d,.q);\nendmodule\n");
|
||||
let rename = swap(&top, "u_s (.clk,.", "d", "dnew");
|
||||
let d_end = top.find("u_s (.clk,.d").expect("d") as u32 + 12;
|
||||
let q_end = top.find("u_s (.clk,.d,.q").expect("q") as u32 + 15;
|
||||
assert_eq!(q_end, d_end + 3, "premise: the shift equals the gap");
|
||||
let tail = |at: u32| TextEdit { range: TextRange::empty(at), new_text: "(d)".into() };
|
||||
assert_eq!(port_rename_with("dnew", &top, vec![rename.clone(), tail(d_end)]), Ok(()));
|
||||
let shifted = port_rename_with("dnew", &top, vec![rename, tail(q_end)]);
|
||||
assert!(shifted.is_err(), "`.dnew,.q(d)` must be refused: {shifted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r_an_append_inside_the_trailing_comment_is_refused() {
|
||||
// The gap from `.*` to the insertion is only trivia, so the slot rule
|
||||
// lets it through; the piece ledger must see the comment change.
|
||||
let top = format!("{HEAD} leaf u_n (\n .* // the rest\n );\nendmodule\n");
|
||||
for anchor in ["// the", "// the rest"] {
|
||||
let outcome = port_rename_with("din", &top, vec![put(&top, anchor, ", .din(d)")]);
|
||||
assert!(outcome.is_err(), "inside/at the end of the comment ({anchor:?}): {outcome:?}");
|
||||
}
|
||||
// The rewrite `layout.rs` writes: `,` before the comment, the connection
|
||||
// on its own line after it.
|
||||
let honest = vec![put(&top, " .*", ","), put(&top, "// the rest", "\n .din(d)")];
|
||||
assert_eq!(port_rename_with("din", &top, honest), Ok(()));
|
||||
// The bare connection without its comma, and the pair with the
|
||||
// connection written inside the comment.
|
||||
let bare = port_rename_with("din", &top, vec![put(&top, "// the rest", "\n .din(d)")]);
|
||||
assert!(outside(&bare), "{bare:?}");
|
||||
let inside = vec![put(&top, " .*", ","), put(&top, "// the", "\n .din(d)")];
|
||||
assert!(port_rename_with("din", &top, inside).is_err(), "the comment is split");
|
||||
}
|
||||
|
||||
/// Verify a net rename `d` → `x` of top's port, the bind file's edits given.
|
||||
fn bind_net_rename(bind_edits: Vec<TextEdit>, bind: &str) -> Result<(), String> {
|
||||
let top =
|
||||
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
|
||||
let files: Vec<(PathBuf, String)> =
|
||||
[("/rtl/leaf.sv", LEAF), ("/rtl/top.sv", top), ("/rtl/binds.sv", bind)]
|
||||
.iter()
|
||||
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
|
||||
.collect();
|
||||
let mut scope = Scope::build(&files);
|
||||
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (top_i, binds) = (index("/rtl/top.sv"), index("/rtl/binds.sv"));
|
||||
let mut edits = vec![(top_i, vec![swap(top, "[7:0] ", "d", "x")])];
|
||||
let mut bind_edits = bind_edits;
|
||||
bind_edits.sort_by_key(|e| e.range.start);
|
||||
if !bind_edits.is_empty() {
|
||||
edits.push((binds, bind_edits));
|
||||
}
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
verify(&mut scope, &edits, "d", "x", &mut VerifyTrace::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r_a_shorthand_in_a_bind() {
|
||||
let bind = "module binds;\n bind top leaf u_b (.clk, .d, .q);\nendmodule\n";
|
||||
assert_eq!(bind_net_rename(vec![put(bind, ".clk, .d", "(x)")], bind), Ok(()));
|
||||
assert!(bind_net_rename(Vec::new(), bind).is_err(), "`.d` left dangling");
|
||||
// `.clk` is a shorthand slot too: the binding print is what refuses it.
|
||||
let wrong = bind_net_rename(vec![put(bind, ".clk", "(x)")], bind);
|
||||
assert!(wrong.is_err_and(|r| r.contains("implicit connection of `u_b`")));
|
||||
let stale = bind_net_rename(vec![put(bind, ".clk, .d", "(d)")], bind);
|
||||
assert!(stale.is_err(), "`.d(d)` names nothing in top any more");
|
||||
}
|
||||
|
||||
/// QA finding 3 (re-check): `Slots::takes` admits a lone `,` at the end of
|
||||
/// *any* `.*` list — the comma half of the comma-before-`//` pair — without
|
||||
/// its `.X(Y)` half. Where the list binds one of the names the binding print
|
||||
/// refuses it (`qa_r_a_lone_trailing_comma_is_refused`); here `other`
|
||||
/// declares neither name, the binding print has nothing to compare, and the
|
||||
/// tolerant parser reports no diagnostic for `(.*,)`, so it verifies.
|
||||
#[test]
|
||||
fn qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name() {
|
||||
let other = "module other (input logic clk);\nendmodule\n";
|
||||
let top = format!("{HEAD} other u_o (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n");
|
||||
let files: Vec<(PathBuf, String)> =
|
||||
[("/rtl/leaf.sv", LEAF), ("/rtl/other.sv", other), ("/rtl/top3.sv", top.as_str())]
|
||||
.iter()
|
||||
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
|
||||
.collect();
|
||||
let edits_with = |extra: Option<TextEdit>| {
|
||||
let mut scope = Scope::build(&files);
|
||||
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, top3) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
|
||||
let mut list =
|
||||
vec![swap(&top, "u_m (.clk, .", "d", "din"), put(&top, "u_m (.clk, .d", "(d)")];
|
||||
list.extend(extra);
|
||||
list.sort_by_key(|e| e.range.start);
|
||||
let mut edits = vec![
|
||||
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
|
||||
(top3, list),
|
||||
];
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
|
||||
};
|
||||
assert_eq!(edits_with(None), Ok(()));
|
||||
let trailing = edits_with(Some(put(&top, "u_o (.*", ",")));
|
||||
assert!(trailing.is_err(), "`other u_o (.*,)` does not compile: {trailing:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// M3.5 final re-check (2026-09-23): attacks on the comma/connection pair
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A `.*` list one per line with a `//` comment on its last element.
|
||||
fn commented(name: &str) -> String {
|
||||
format!("{HEAD} leaf {name} (\n .* // the rest\n );\nendmodule\n")
|
||||
}
|
||||
|
||||
/// Verify the port rename `d` → `din` with the two files' edits as given.
|
||||
fn two_files(top3: &str, e3: Vec<TextEdit>, top4: &str, e4: Vec<TextEdit>) -> Result<(), String> {
|
||||
let files: Vec<(PathBuf, String)> =
|
||||
[("/rtl/leaf.sv", LEAF), ("/rtl/top3.sv", top3), ("/rtl/top4.sv", top4)]
|
||||
.iter()
|
||||
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
|
||||
.collect();
|
||||
let mut scope = Scope::build(&files);
|
||||
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, t3, t4) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"), index("/rtl/top4.sv"));
|
||||
let mut edits =
|
||||
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")])];
|
||||
for (file, list) in [(t3, e3), (t4, e4)] {
|
||||
if !list.is_empty() {
|
||||
edits.push((file, list));
|
||||
}
|
||||
}
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_p_a_comma_in_one_file_and_its_connection_in_another_are_refused() {
|
||||
let (a, b) = (commented("u_a"), commented("u_b"));
|
||||
let comma = |t: &str| put(t, " .*", ",");
|
||||
let conn = |t: &str| put(t, "// the rest", "\n .din(d)");
|
||||
let honest = two_files(&a, vec![comma(&a), conn(&a)], &b, vec![comma(&b), conn(&b)]);
|
||||
assert_eq!(honest, Ok(()));
|
||||
let split = two_files(&a, vec![comma(&a)], &b, vec![conn(&b)]);
|
||||
assert!(outside(&split), "each file holds half a pair: {split:?}");
|
||||
let split = two_files(&a, vec![conn(&a)], &b, vec![comma(&b)]);
|
||||
assert!(outside(&split), "the other way round: {split:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_p_two_commas_and_one_connection_in_one_list_are_refused() {
|
||||
let top = commented("u_n");
|
||||
let comma = || put(&top, " .*", ",");
|
||||
let conn = || put(&top, "// the rest", "\n .din(d)");
|
||||
assert_eq!(port_rename_with("din", &top, vec![comma(), conn()]), Ok(()));
|
||||
let doubled = port_rename_with("din", &top, vec![comma(), comma(), conn()]);
|
||||
assert!(doubled.is_err(), "`.*,, // the rest` must be refused: {doubled:?}");
|
||||
let twice = port_rename_with("din", &top, vec![comma(), conn(), conn()]);
|
||||
assert!(twice.is_err(), "one comma, two connections: {twice:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_p_a_connection_before_its_comma_in_offset_order_is_refused() {
|
||||
let top = commented("u_n");
|
||||
let comma = || put(&top, " .*", ",");
|
||||
// Both at the `.*`'s end, the connection first: `.*\n .din(d), //…`.
|
||||
let early = put(&top, " .*", "\n .din(d)");
|
||||
let reversed = port_rename_with("din", &top, vec![early.clone(), comma()]);
|
||||
assert!(reversed.is_err(), "{reversed:?}");
|
||||
let glued = port_rename_with("din", &top, vec![put(&top, " .*", ".din(d)"), comma()]);
|
||||
assert!(glued.is_err(), "`.*.din(d),`: {glued:?}");
|
||||
// In source order the same two pieces are a legal list whose comment
|
||||
// now ends the new line: `.*,\n .din(d) // the rest` — accepted, and
|
||||
// harmless (same bindings, the comment kept).
|
||||
assert_eq!(port_rename_with("din", &top, vec![comma(), early]), Ok(()));
|
||||
}
|
||||
|
||||
/// `.d(type(q)'(q))` is valid SV (a cast through the type operator) that the
|
||||
/// tolerant parser reads as an error element `.d(type(q)'(q)` — one byte short
|
||||
/// of the connection's `)`.
|
||||
fn cast_list() -> String {
|
||||
format!("{HEAD} leaf u_e (.*, .d(type(q)'(q)));\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_p_a_pair_after_an_error_element() {
|
||||
// After the connection's `)`: the gap to the error element's end is not
|
||||
// trivia, so no slot.
|
||||
let cast = cast_list();
|
||||
let rename = swap(&cast, "u_e (.*, .", "d", "din");
|
||||
let after_conn = put(&cast, "(q)'(q))", ", .din(d)");
|
||||
let outcome = port_rename_with("din", &cast, vec![rename, after_conn]);
|
||||
assert!(outside(&outcome), "{outcome:?}");
|
||||
// Text that is not SV at all (`+.din(x)`): the verifier used to admit
|
||||
// the pair after it (the error element is invisible to the binding
|
||||
// print). Since finding 4 a list holding an error element has no slot at
|
||||
// all, so the pair is refused — the engine refuses such a list too
|
||||
// (`unreadable_elements`). Pinned so a change is noticed.
|
||||
let junk = format!("{HEAD} leaf u_e (\n .*, +.din(x) // the rest\n );\nendmodule\n");
|
||||
let pair = vec![put(&junk, "+.din(x)", ","), put(&junk, "// the rest", "\n .din(d)")];
|
||||
let outcome = port_rename_with("din", &junk, pair);
|
||||
assert!(outside(&outcome), "{outcome:?}");
|
||||
assert!(port_rename_with("din", &junk, Vec::new()).is_err(), "the cut is still seen");
|
||||
}
|
||||
|
||||
/// QA finding 4 (final re-check): a list holding an error element still
|
||||
/// registers a slot at the element's end. For valid SV the parser misreads
|
||||
/// (`.d(type(q)'(q))`, element ending before the connection's own `)`), an
|
||||
/// append there lands *inside* that connection:
|
||||
/// `.din(type(q)'(q), .din(d)))` — valid input, output that does not compile,
|
||||
/// and it verifies: the diagnostic count is compared, not the diagnostics, and
|
||||
/// the binding print cannot see into an error element. The engine never
|
||||
/// writes it (`unreadable_elements` refuses a list whose error element spells
|
||||
/// either name). Loud, not silent — but accepted.
|
||||
#[test]
|
||||
fn qa_p_an_append_at_an_error_elements_end_is_refused() {
|
||||
let cast = cast_list();
|
||||
let rename = swap(&cast, "u_e (.*, .", "d", "din");
|
||||
let at_error = put(&cast, "(q)'(q)", ", .din(d)");
|
||||
let outcome = port_rename_with("din", &cast, vec![rename, at_error]);
|
||||
assert!(outcome.is_err(), "`.din(type(q)'(q), .din(d)))` must be refused: {outcome:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_p_a_clean_list_beside_an_error_element_list_still_verifies() {
|
||||
// Finding 4's fix drops the slots of the list holding the error element
|
||||
// only: an honest rewrite of a clean list in the same file still
|
||||
// verifies, and the same append into the unreadable list is refused.
|
||||
let other = "module other (input logic clk);\nendmodule\n";
|
||||
let top = format!(
|
||||
"{HEAD} other u_x (.*, .clk(type(clk)'(clk)));\n leaf u_n (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n"
|
||||
);
|
||||
let files: Vec<(PathBuf, String)> =
|
||||
[("/rtl/leaf.sv", LEAF), ("/rtl/other.sv", other), ("/rtl/top3.sv", top.as_str())]
|
||||
.iter()
|
||||
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
|
||||
.collect();
|
||||
let run = |extra: Option<TextEdit>| {
|
||||
let mut scope = Scope::build(&files);
|
||||
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (leaf, top3) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
|
||||
let mut list = vec![
|
||||
put(&top, "u_n (.*", ", .din(d)"),
|
||||
swap(&top, "u_m (.clk, .", "d", "din"),
|
||||
put(&top, "u_m (.clk, .d", "(d)"),
|
||||
];
|
||||
list.extend(extra);
|
||||
list.sort_by_key(|e| e.range.start);
|
||||
let mut edits = vec![
|
||||
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
|
||||
(top3, list),
|
||||
];
|
||||
edits.sort_by_key(|(file, _)| *file);
|
||||
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
|
||||
};
|
||||
assert_eq!(run(None), Ok(()), "the error element sits in another instance's list");
|
||||
let into_error = run(Some(put(&top, "(clk)'(clk)", ", .din(d)")));
|
||||
assert!(outside(&into_error), "{into_error:?}");
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! A rename versus the connections that name it **implicitly**: the `.name`
|
||||
//! shorthand and the `.*` wildcard (IEEE 1800 §23.3.2.3–4).
|
||||
//!
|
||||
//! Both bind by *equal names*, so renaming either side cuts the binding
|
||||
//! without a single reference moving — the semantic layer records the port
|
||||
//! half of `.name` and nothing else of either. Two directions:
|
||||
//!
|
||||
//! * **A port `p` → `q` of module `M`.** In every instance of `M`, the
|
||||
//! shorthand `.p` (whose port half the rename already edits to `.q`) gets
|
||||
//! its net written out: `.q(p)`. A `.*` that bound `p` gets an explicit
|
||||
//! `.q(p)` added beside it, which is legal and wins over the wildcard.
|
||||
//! * **A net, variable or port `n` → `m` seen by an instance.** The shorthand
|
||||
//! `.n` becomes `.n(m)`; a `.*` whose module declares a port `n` gets
|
||||
//! `.n(m)` added. That covers the instances written where `n` is visible,
|
||||
//! and the `bind` directives whose target is the module declaring it.
|
||||
//!
|
||||
//! Every rewrite is an **insertion** (the port half of `.p` is the rename's
|
||||
//! own edit), every one is listed in the warnings, and anything lucisv cannot
|
||||
//! read is refused rather than guessed: an unreadable `.*` module, a module
|
||||
//! declared twice, a list split by compiler directives or holding text that
|
||||
//! did not parse, a hierarchical `bind` target, and a `.*` that would start
|
||||
//! binding the new name. `check::implicit` then re-derives every implicit
|
||||
//! binding before and after, so an edit here that got it wrong is refused.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vlog_parser::ast::PortList;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex};
|
||||
use vlog_semantic::{ScopeKind, Surface, SymbolId, SymbolKind};
|
||||
|
||||
use super::layout::{append, connection, shorthand_tail};
|
||||
use super::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
|
||||
use super::{contains_word, display, Scope, Target};
|
||||
use crate::TextEdit;
|
||||
|
||||
/// The insertions a rename's implicit connections need, and the sentences
|
||||
/// that tell the user about each one.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Implicit {
|
||||
pub(super) edits: Vec<(usize, Vec<TextEdit>)>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Where the renamed declaration lives, as far as an implicit binding cares.
|
||||
enum Home {
|
||||
/// Inside module `name`; `top` when directly in the module's own scope,
|
||||
/// which is the only scope a `bind` into that module reaches.
|
||||
Module { name: String, top: bool },
|
||||
/// Inside package `name`: visible wherever it is imported.
|
||||
Package(String),
|
||||
/// Anywhere else (a function, a class, the compilation unit).
|
||||
Elsewhere,
|
||||
}
|
||||
|
||||
/// The rename, as the walk needs it.
|
||||
struct Renamed {
|
||||
old: String,
|
||||
new: String,
|
||||
file: usize,
|
||||
symbol: SymbolId,
|
||||
kind: SymbolKind,
|
||||
home: Home,
|
||||
}
|
||||
|
||||
/// What a `bind` directive's connections can see of the renamed module.
|
||||
enum Reach {
|
||||
/// Its own top-level scope: the bind targets the module by name.
|
||||
Module,
|
||||
/// Possibly it: a target lucisv cannot tie to one module.
|
||||
Maybe,
|
||||
/// Not it: the target is another module, or instances of other modules.
|
||||
Elsewhere,
|
||||
}
|
||||
|
||||
/// A module's declared port names, or why lucisv cannot read them.
|
||||
type Ports = Result<Vec<String>, &'static str>;
|
||||
|
||||
/// One pass over the in-scope files.
|
||||
struct Walk<'r> {
|
||||
renamed: &'r Renamed,
|
||||
/// The rename's own edits: a shorthand is rewritten only where its port
|
||||
/// half is one of them.
|
||||
occurrences: &'r [(usize, Vec<TextEdit>)],
|
||||
out: Implicit,
|
||||
ports: HashMap<String, Ports>,
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// The implicit connections renaming `target` to `new_name` must rewrite.
|
||||
/// `occurrences` are the rename's own edits.
|
||||
pub(super) fn implicit_connections(
|
||||
&mut self,
|
||||
target: &Target,
|
||||
new_name: &str,
|
||||
occurrences: &[(usize, Vec<TextEdit>)],
|
||||
) -> Result<Implicit, String> {
|
||||
let Some(renamed) = self.renamed(target, new_name) else { return Ok(Implicit::default()) };
|
||||
let mut walk = Walk {
|
||||
renamed: &renamed,
|
||||
occurrences,
|
||||
out: Implicit::default(),
|
||||
ports: HashMap::new(),
|
||||
};
|
||||
if let (SymbolKind::Port, Home::Module { name, top: true }) = (renamed.kind, &renamed.home)
|
||||
{
|
||||
self.port_users(&mut walk, name)?;
|
||||
}
|
||||
self.signal_users(&mut walk)?;
|
||||
let mut out = walk.out;
|
||||
for (_, edits) in &mut out.edits {
|
||||
edits.sort_by_key(|e| (e.range.start, e.range.end));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What the target is and where it lives, read off its own analysis.
|
||||
fn renamed(&mut self, target: &Target, new_name: &str) -> Option<Renamed> {
|
||||
let semantics = &self.analysis(target.file)?.semantics;
|
||||
let symbol = semantics.symbol(target.symbol)?;
|
||||
let mut scope = semantics.scope(symbol.scope);
|
||||
let mut top = true;
|
||||
let home = loop {
|
||||
let Some(here) = scope else { break Home::Elsewhere };
|
||||
let owner = here.owner.and_then(|o| semantics.symbol(o)).map(|o| o.name.clone());
|
||||
match (here.kind, owner) {
|
||||
(ScopeKind::Module, Some(name)) => break Home::Module { name, top },
|
||||
(ScopeKind::Package, Some(name)) => break Home::Package(name),
|
||||
(ScopeKind::Generate | ScopeKind::Block, _) => {}
|
||||
_ => break Home::Elsewhere,
|
||||
}
|
||||
top = false;
|
||||
scope = here.parent.and_then(|p| semantics.scope(p));
|
||||
};
|
||||
Some(Renamed {
|
||||
old: target.name.clone(),
|
||||
new: new_name.to_string(),
|
||||
file: target.file,
|
||||
symbol: target.symbol,
|
||||
kind: symbol.kind,
|
||||
home,
|
||||
})
|
||||
}
|
||||
|
||||
/// Direction one: every instance of the module whose port is renamed.
|
||||
fn port_users(&mut self, walk: &mut Walk, module: &str) -> Result<(), String> {
|
||||
let ours = self.unique_module(module).is_some_and(|file| file == walk.renamed.file);
|
||||
let old = [walk.renamed.old.as_str()];
|
||||
for i in 0..self.len() {
|
||||
let wanted =
|
||||
|text: &&str| contains_word(text, module) && may_connect_implicitly(text, &old);
|
||||
let Some(text) = self.text(i).filter(wanted) else { continue };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
for site in sites(&tree.items).iter().filter(|s| s.instantiation.module == module) {
|
||||
self.port_site(walk, i, text, site, ours)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One instance of the module whose port `p` becomes `q`.
|
||||
fn port_site(
|
||||
&mut self,
|
||||
walk: &mut Walk,
|
||||
file: usize,
|
||||
text: &str,
|
||||
site: &Site,
|
||||
ours: bool,
|
||||
) -> Result<(), String> {
|
||||
let (old, new) = (walk.renamed.old.as_str(), walk.renamed.new.as_str());
|
||||
let here = self.describe(file, text, site);
|
||||
unreadable_elements(site, old, new, &here)?;
|
||||
if let Some(c) = site.named(old) {
|
||||
let edited = walk
|
||||
.occurrences
|
||||
.iter()
|
||||
.any(|(f, edits)| *f == file && edits.iter().any(|e| e.range == c.name_span));
|
||||
if c.expr.is_some() || !edited {
|
||||
return Ok(());
|
||||
}
|
||||
if site.bind_target().is_err() {
|
||||
return Err(hierarchical_bind(&here, old));
|
||||
}
|
||||
let written = connection(new, old);
|
||||
walk.push(file, vec![shorthand_tail(c.name_span.end, new, old)]);
|
||||
walk.out.warnings.push(format!(
|
||||
"{here} connected `{old}` by the shorthand `.{old}`; wrote `{written}` so it still binds the same net."
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
if !site.has_wildcard() {
|
||||
return Ok(());
|
||||
}
|
||||
directives(site, &here)?;
|
||||
if !ours {
|
||||
return Err(wildcard_unreadable(&here, &site.instantiation.module, old));
|
||||
}
|
||||
match self.wildcard_sees(file, site, old, new, &here)? {
|
||||
(true, _) => walk.append(file, text, site, &connection(new, old), &here, old),
|
||||
(false, true) => Err(captured(&here, new)),
|
||||
(false, false) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `.*` at `site` binds something named `old`, and whether it
|
||||
/// would bind something named `new` — what decides between adding
|
||||
/// `.new(old)`, refusing, and leaving the wildcard alone.
|
||||
fn wildcard_sees(
|
||||
&mut self,
|
||||
file: usize,
|
||||
site: &Site,
|
||||
old: &str,
|
||||
new: &str,
|
||||
here: &str,
|
||||
) -> Result<(bool, bool), String> {
|
||||
match site.bind_target() {
|
||||
Ok(None) => {
|
||||
let Some(analysis) = self.analysis(file) else { return Ok((false, false)) };
|
||||
let semantics = &analysis.semantics;
|
||||
let offset = site.instance.name_span.start;
|
||||
let binds = |name| {
|
||||
let found = nearest(semantics, offset, name).and_then(|s| semantics.symbol(s));
|
||||
found.is_some_and(|s| binds_implicitly(s.kind))
|
||||
};
|
||||
Ok((binds(old), binds(new)))
|
||||
}
|
||||
Ok(Some(target)) => {
|
||||
if self.unique_module(target).is_none() {
|
||||
return Err(bind_unreadable(here, target));
|
||||
}
|
||||
let binds = |name| {
|
||||
let defs = self.index.member_in(target, name, Surface::Hierarchical);
|
||||
defs.iter().any(|d| binds_implicitly(d.kind))
|
||||
};
|
||||
Ok((binds(old), binds(new)))
|
||||
}
|
||||
Err(()) => Err(hierarchical_bind(here, old)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Direction two: every instance whose implicit connections can see the
|
||||
/// renamed declaration under its old name.
|
||||
fn signal_users(&mut self, walk: &mut Walk) -> Result<(), String> {
|
||||
let renamed = walk.renamed;
|
||||
if !binds_implicitly(renamed.kind) {
|
||||
return Ok(());
|
||||
}
|
||||
let (file, symbol, old) = (renamed.file, renamed.symbol, renamed.old.as_str());
|
||||
let rewrite = !matches!(renamed.home, Home::Package(_));
|
||||
if let Some(text) = self.text(file).filter(|text| may_connect_implicitly(text, &[old])) {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
for site in sites(&tree.items).iter().filter(|s| s.bind.is_none()) {
|
||||
if self.nearest_at(file, site, old) == Some(symbol) {
|
||||
self.signal_site(walk, file, text, site, rewrite)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
match &renamed.home {
|
||||
Home::Module { name, top: true } => self.binds_into(walk, name, rewrite),
|
||||
Home::Package(name) => self.importers(walk, name),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest declaration of `name` where `site`'s implicit connections
|
||||
/// bind, for an ordinary instantiation in `file`.
|
||||
fn nearest_at(&mut self, file: usize, site: &Site, name: &str) -> Option<SymbolId> {
|
||||
let analysis = self.analysis(file)?;
|
||||
nearest(&analysis.semantics, site.instance.name_span.start, name)
|
||||
}
|
||||
|
||||
/// The `bind` directives that bind into module `module`, whose connections
|
||||
/// see its own top-level declarations — and the ones whose target lucisv
|
||||
/// cannot name, which might.
|
||||
fn binds_into(&mut self, walk: &mut Walk, module: &str, rewrite: bool) -> Result<(), String> {
|
||||
let old = [walk.renamed.old.as_str()];
|
||||
for i in 0..self.len() {
|
||||
let wanted =
|
||||
|text: &&str| contains_word(text, "bind") && may_connect_implicitly(text, &old);
|
||||
let Some(text) = self.text(i).filter(wanted) else { continue };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
for site in sites(&tree.items).iter().filter(|s| s.bind.is_some()) {
|
||||
match self.bind_reaches(i, site, module) {
|
||||
Reach::Module => self.signal_site(walk, i, text, site, rewrite)?,
|
||||
Reach::Maybe => self.signal_site(walk, i, text, site, false)?,
|
||||
Reach::Elsewhere => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a `bind`'s connections see `module`'s own scope.
|
||||
///
|
||||
/// A lone target is a module name or an **instance** name (IEEE 1800
|
||||
/// §23.11). A module lucisv indexes is that module; otherwise the index's
|
||||
/// instantiation edges say which modules own an instance of that name
|
||||
/// (QA M3.5 finding 2: `bind i_nopass1 … (.clk_i, …)` into a
|
||||
/// `prim_fifo_sync` refused `clk_i` renames of every other module). Owned
|
||||
/// by other modules only — elsewhere; owned by nobody lucisv indexes, or by
|
||||
/// `module` itself — maybe, which refuses what it would bind: the verifier
|
||||
/// cannot name an instance's scope, so a rewrite there would be refused
|
||||
/// anyway, and saying so up front is the clearer sentence.
|
||||
fn bind_reaches(&self, file: usize, site: &Site, module: &str) -> Reach {
|
||||
let target = match site.bind_target() {
|
||||
Ok(Some(target)) => target,
|
||||
Ok(None) => return Reach::Elsewhere,
|
||||
Err(()) => return Reach::Maybe,
|
||||
};
|
||||
if target == module {
|
||||
return Reach::Module;
|
||||
}
|
||||
if !self.index.units(target).is_empty() {
|
||||
return Reach::Elsewhere;
|
||||
}
|
||||
let owners = self.instance_owners(file, site, target);
|
||||
match owners.is_empty() || owners.contains(&module) {
|
||||
true => Reach::Maybe,
|
||||
false => Reach::Elsewhere,
|
||||
}
|
||||
}
|
||||
|
||||
/// The modules an instance named `target` instantiates, as a `bind`
|
||||
/// written at `site` sees them. A bare instance name is found by upward
|
||||
/// name resolution from the bind's own scope (§23.11), so the instances
|
||||
/// the **enclosing module** declares answer first — `bind dut … (.*)` in
|
||||
/// sram_ctrl's bench means that bench's `dut`, not entropy_src's — and
|
||||
/// only when it declares none does every instance of that name count.
|
||||
fn instance_owners(&self, file: usize, site: &Site, target: &str) -> Vec<&str> {
|
||||
let here = self.file_id(file);
|
||||
let at = site.instance.span.start;
|
||||
let named = |edge: &vlog_semantic::InstantiationEdge| {
|
||||
edge.instances.iter().any(|instance| instance.name == target)
|
||||
};
|
||||
let enclosing = |edge: &vlog_semantic::InstantiationEdge| {
|
||||
Some(edge.file) == here && edge.owner.span.contains(at)
|
||||
};
|
||||
// Keyed by the module *instantiated*, which is what the bind reaches.
|
||||
let mut local: Vec<&str> = Vec::new();
|
||||
let mut anywhere: Vec<&str> = Vec::new();
|
||||
for (instantiated, edges) in self.index.instantiations() {
|
||||
if edges.iter().any(|edge| named(edge) && enclosing(edge)) {
|
||||
local.push(instantiated);
|
||||
}
|
||||
if edges.iter().any(named) {
|
||||
anywhere.push(instantiated);
|
||||
}
|
||||
}
|
||||
if local.is_empty() {
|
||||
anywhere
|
||||
} else {
|
||||
local
|
||||
}
|
||||
}
|
||||
|
||||
/// The instances that may see a package's declaration through an import:
|
||||
/// any instance, in a file naming the package, that declares nothing of
|
||||
/// that name itself. lucisv does not follow imports into `.*`, so these are
|
||||
/// refused rather than rewritten.
|
||||
fn importers(&mut self, walk: &mut Walk, package: &str) -> Result<(), String> {
|
||||
let old = walk.renamed.old.as_str();
|
||||
for i in 0..self.len() {
|
||||
let wanted =
|
||||
|text: &&str| contains_word(text, package) && may_connect_implicitly(text, &[old]);
|
||||
let Some(text) = self.text(i).filter(wanted) else { continue };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
for site in sites(&tree.items).iter() {
|
||||
if site.bind.is_some() || self.nearest_at(i, site, old).is_none() {
|
||||
self.signal_site(walk, i, text, site, false)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One instance whose implicit connections see the renamed declaration.
|
||||
/// `rewrite` is false where lucisv can only refuse what it finds.
|
||||
fn signal_site(
|
||||
&mut self,
|
||||
walk: &mut Walk,
|
||||
file: usize,
|
||||
text: &str,
|
||||
site: &Site,
|
||||
rewrite: bool,
|
||||
) -> Result<(), String> {
|
||||
let renamed = walk.renamed;
|
||||
let (old, new) = (renamed.old.as_str(), renamed.new.as_str());
|
||||
let here = self.describe(file, text, site);
|
||||
unreadable_elements(site, old, new, &here)?;
|
||||
if let Some(c) = site.named(old).filter(|c| c.expr.is_none()) {
|
||||
if !rewrite {
|
||||
return Err(cannot_rewrite(&here, old, &format!(".{old}")));
|
||||
}
|
||||
let written = connection(old, new);
|
||||
walk.push(file, vec![shorthand_tail(c.name_span.end, old, new)]);
|
||||
walk.out.warnings.push(format!(
|
||||
"{here} connected `{old}` by the shorthand `.{old}`; wrote `{written}`."
|
||||
));
|
||||
}
|
||||
if !site.has_wildcard() {
|
||||
return Ok(());
|
||||
}
|
||||
directives(site, &here)?;
|
||||
let module = site.instantiation.module.clone();
|
||||
let ports = match walk.ports_of(self, &module) {
|
||||
Ok(ports) => ports,
|
||||
Err(why) => return Err(wildcard_problem(&here, &module, old, why)),
|
||||
};
|
||||
let declares = |name: &str| ports.iter().any(|port| port == name);
|
||||
if declares(new) && site.named(new).is_none() {
|
||||
return Err(captured(&here, new));
|
||||
}
|
||||
if !declares(old) || site.named(old).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
if !rewrite {
|
||||
return Err(cannot_rewrite(&here, old, ".*"));
|
||||
}
|
||||
walk.append(file, text, site, &connection(old, new), &here, old)
|
||||
}
|
||||
|
||||
/// The one in-scope file declaring module `name`, if exactly one does.
|
||||
fn unique_module(&self, name: &str) -> Option<usize> {
|
||||
let defs: Vec<_> =
|
||||
self.index.units(name).iter().filter(|def| def.kind.is_instantiable()).collect();
|
||||
let [def] = defs.as_slice() else { return None };
|
||||
self.index.path(def.file).and_then(|path| self.index_of(path))
|
||||
}
|
||||
|
||||
/// The declared ports of module `name`, read from its declaring file.
|
||||
fn read_ports(&self, name: &str) -> Ports {
|
||||
let count = self.index.units(name).iter().filter(|d| d.kind.is_instantiable()).count();
|
||||
if count > 1 {
|
||||
return Err(TWICE);
|
||||
}
|
||||
let file = self.unique_module(name).ok_or(UNREADABLE)?;
|
||||
let text = self.text(file).ok_or(UNREADABLE)?;
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let (module, _) = crate::ports::find_module(&tree, name).ok_or(UNREADABLE)?;
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(DIRECTIVES);
|
||||
}
|
||||
let names = match &module.ports {
|
||||
PortList::Ansi(ports) => ports.iter().map(|p| p.ok().map(|p| p.name.clone())).collect(),
|
||||
PortList::NonAnsi(ports) => {
|
||||
ports.iter().map(|p| p.ok().map(|p| p.name.clone())).collect()
|
||||
}
|
||||
PortList::Empty | PortList::None => Some(Vec::new()),
|
||||
};
|
||||
names.ok_or(UNREADABLE)
|
||||
}
|
||||
|
||||
/// "`u_leaf` at top.sv:12", the way every sentence here names an instance.
|
||||
fn describe(&self, file: usize, text: &str, site: &Site) -> String {
|
||||
let path = self.path(file).map(display).unwrap_or_default();
|
||||
let line = LineIndex::new(text).line_col(site.instance.name_span.start).0;
|
||||
format!("`{}` at {path}:{line}", site.instance.name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Walk<'_> {
|
||||
/// Record insertions into one file.
|
||||
fn push(&mut self, file: usize, edits: Vec<TextEdit>) {
|
||||
match self.out.edits.iter_mut().find(|(f, _)| *f == file) {
|
||||
Some((_, existing)) => existing.extend(edits),
|
||||
None => self.out.edits.push((file, edits)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Append `element` to `site`'s connection list, and say so.
|
||||
fn append(
|
||||
&mut self,
|
||||
file: usize,
|
||||
text: &str,
|
||||
site: &Site,
|
||||
element: &str,
|
||||
here: &str,
|
||||
old: &str,
|
||||
) -> Result<(), String> {
|
||||
let Some(edits) = append(text, site.conns, element) else {
|
||||
return Err(format!(
|
||||
"lucisv cannot find where {here}'s connection list ends; it made no edits."
|
||||
));
|
||||
};
|
||||
self.push(file, edits);
|
||||
self.out.warnings.push(format!("{here} bound `{old}` through `.*`; added `{element}`."));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A module's ports, read once per walk.
|
||||
fn ports_of(&mut self, scope: &Scope, module: &str) -> Ports {
|
||||
self.ports.entry(module.to_string()).or_insert_with(|| scope.read_ports(module)).clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The rename's own edits and the implicit-connection insertions, as one
|
||||
/// sorted edit list per file. Two insertions at one offset would be two
|
||||
/// rewrites of one place, which no correct plan makes, so that is a refusal.
|
||||
pub(super) fn combine(
|
||||
mut renamed: Vec<(usize, Vec<TextEdit>)>,
|
||||
inserted: Vec<(usize, Vec<TextEdit>)>,
|
||||
) -> Result<Vec<(usize, Vec<TextEdit>)>, String> {
|
||||
for (file, edits) in inserted {
|
||||
match renamed.iter_mut().find(|(f, _)| *f == file) {
|
||||
Some((_, existing)) => existing.extend(edits),
|
||||
None => renamed.push((file, edits)),
|
||||
}
|
||||
}
|
||||
renamed.sort_by_key(|(file, _)| *file);
|
||||
for (_, edits) in &mut renamed {
|
||||
edits.sort_by_key(|e| (e.range.start, e.range.end));
|
||||
let clash = edits.windows(2).any(|pair| match pair {
|
||||
[a, b] => b.range.start < a.range.end || (a.range.is_empty() && a.range == b.range),
|
||||
_ => false,
|
||||
});
|
||||
if clash {
|
||||
return Err("two rewrites of one connection overlap; the rename was abandoned.".into());
|
||||
}
|
||||
}
|
||||
Ok(renamed)
|
||||
}
|
||||
|
||||
/// The verified edits as the caller receives them: an insertion written right
|
||||
/// where a replacement ends becomes part of it, so `.p` → `.q` plus `(p)` is
|
||||
/// the one edit `.q(p)`. The applied text is the same either way.
|
||||
pub(super) fn fuse(edits: Vec<TextEdit>) -> Vec<TextEdit> {
|
||||
let mut out: Vec<TextEdit> = Vec::with_capacity(edits.len());
|
||||
for edit in edits {
|
||||
match out.last_mut() {
|
||||
Some(last)
|
||||
if edit.range.is_empty()
|
||||
&& !last.range.is_empty()
|
||||
&& last.range.end == edit.range.start =>
|
||||
{
|
||||
last.new_text.push_str(&edit.new_text)
|
||||
}
|
||||
_ => out.push(edit),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Refuse a list holding text a tolerant parse could not read, when that text
|
||||
/// could be an implicit connection of either name.
|
||||
fn unreadable_elements(site: &Site, old: &str, new: &str, here: &str) -> Result<(), String> {
|
||||
let hides = |raw: &str| contains_word(raw, old) || contains_word(raw, new) || raw.contains('*');
|
||||
match site.unreadable().any(hides) {
|
||||
true => Err(format!(
|
||||
"{here}'s connection list holds text lucisv could not parse, so it cannot tell whether it binds `{old}` implicitly; the rename was abandoned."
|
||||
)),
|
||||
false => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse a `.*` list split by compiler directives: which ports it binds
|
||||
/// depends on the configuration.
|
||||
fn directives(site: &Site, here: &str) -> Result<(), String> {
|
||||
match site.instance.conn_directives.is_empty() {
|
||||
true => Ok(()),
|
||||
false => Err(format!(
|
||||
"{here}'s connection list is split by compiler directives, so which ports its `.*` binds depends on the configuration; lucisv does not preprocess, so the rename was abandoned."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
const UNREADABLE: &str = "unreadable";
|
||||
const TWICE: &str = "twice";
|
||||
const DIRECTIVES: &str = "directives";
|
||||
|
||||
fn wildcard_problem(here: &str, module: &str, old: &str, why: &str) -> String {
|
||||
match why {
|
||||
TWICE => format!(
|
||||
"{here} connects with `.*` to `{module}`, which is declared in more than one indexed file, so lucisv cannot tell whether `{old}` is bound implicitly; the rename was abandoned."
|
||||
),
|
||||
DIRECTIVES => format!(
|
||||
"{here} connects with `.*` to `{module}`, whose port list carries compiler directives, so whether `{old}` is bound implicitly depends on the configuration; the rename was abandoned."
|
||||
),
|
||||
_ => wildcard_unreadable(here, module, old),
|
||||
}
|
||||
}
|
||||
|
||||
fn wildcard_unreadable(here: &str, module: &str, old: &str) -> String {
|
||||
format!(
|
||||
"{here} connects with `.*` to `{module}`, which lucisv cannot read, so it cannot tell whether `{old}` is bound implicitly; the rename was abandoned."
|
||||
)
|
||||
}
|
||||
|
||||
fn bind_unreadable(here: &str, target: &str) -> String {
|
||||
format!(
|
||||
"{here} is bound into `{target}`, which lucisv cannot read, so it cannot tell what its `.*` binds; the rename was abandoned."
|
||||
)
|
||||
}
|
||||
|
||||
fn hierarchical_bind(here: &str, old: &str) -> String {
|
||||
format!(
|
||||
"{here} is bound into a hierarchical `bind` target, whose scope lucisv cannot name, so it cannot tell what `{old}` binds there implicitly; the rename was abandoned."
|
||||
)
|
||||
}
|
||||
|
||||
fn captured(here: &str, new: &str) -> String {
|
||||
format!(
|
||||
"{here} connects with `.*`, which would start binding `{new}` to the renamed declaration; the rename was abandoned."
|
||||
)
|
||||
}
|
||||
|
||||
fn cannot_rewrite(here: &str, old: &str, how: &str) -> String {
|
||||
format!(
|
||||
"{here} may bind `{old}` implicitly through `{how}`, from a scope lucisv cannot tie to the renamed declaration (a package import, or a `bind` target it cannot name); the rename was abandoned."
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! The text a rewritten implicit connection is spelled with, and where it is
|
||||
//! written: a `(net)` after a `.name` shorthand, or a whole `.port(net)`
|
||||
//! appended to a connection list that uses `.*`.
|
||||
//!
|
||||
//! Text-level, and only ever an **insertion** — nothing the source wrote is
|
||||
//! replaced, so no comment can be lost and the verifier's piece check sees
|
||||
//! exactly the tokens written here and nothing else move.
|
||||
//!
|
||||
//! The appending rule is `ports::list::append_to_list`'s, restated here
|
||||
//! because that one is private to the port refactorings (see the feature
|
||||
//! README's Handshakes): the list's own layout is kept — one element per line
|
||||
//! stays one per line at the last element's indentation, an inline list stays
|
||||
//! inline — and when the last element carries a `//` comment the comma goes
|
||||
//! before the comment and the new element on the next line, because a `,`
|
||||
//! written after `//` is a `,` inside a comment. The newline is the list's
|
||||
//! own, so a CRLF file stays CRLF.
|
||||
|
||||
use vlog_parser::ast::{Connection, ListElem};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::TextEdit;
|
||||
|
||||
/// `name`, followed by the blank an escaped identifier needs to end: an
|
||||
/// escaped identifier runs to the next whitespace, so `\a-b(x)` would be one
|
||||
/// token swallowing the parenthesis (IEEE 1800 §5.6.1).
|
||||
fn spelled(name: &str) -> String {
|
||||
match name.starts_with('\\') {
|
||||
true => format!("{name} "),
|
||||
false => name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `.port(net)`, as a connection lucisv writes it.
|
||||
pub(super) fn connection(port: &str, net: &str) -> String {
|
||||
format!(".{}({})", spelled(port), spelled(net))
|
||||
}
|
||||
|
||||
/// The insertion that turns the shorthand `.written` into `.written(net)`,
|
||||
/// where `written` is what the port name will spell once the rename's own
|
||||
/// edits are applied (it decides whether a blank must separate the two).
|
||||
pub(super) fn shorthand_tail(name_end: u32, written: &str, net: &str) -> TextEdit {
|
||||
let gap = if written.starts_with('\\') { " " } else { "" };
|
||||
insert(name_end, format!("{gap}({})", spelled(net)))
|
||||
}
|
||||
|
||||
/// The insertions that append `element` after the last element of a
|
||||
/// connection list, or `None` when the list has no element to append after.
|
||||
pub(super) fn append(
|
||||
text: &str,
|
||||
conns: &[ListElem<Connection>],
|
||||
element: &str,
|
||||
) -> Option<Vec<TextEdit>> {
|
||||
let spans: Vec<TextRange> = conns
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
ListElem::Ok(c) => c.span,
|
||||
ListElem::Error(raw) => raw.span,
|
||||
})
|
||||
.collect();
|
||||
let last = *spans.last()?;
|
||||
let first = *spans.first()?;
|
||||
let gap_from = match spans.len() {
|
||||
1 => text.get(..first.start as usize)?.rfind('(')? as u32,
|
||||
n => spans.get(n - 2)?.end,
|
||||
};
|
||||
let gap = text.get(gap_from as usize..last.start as usize)?;
|
||||
let newline = if gap.contains("\r\n") { "\r\n" } else { "\n" };
|
||||
let indent = line_indent(text, last.start);
|
||||
let (at, line_comment) = after_same_line_comments(text, last.end);
|
||||
Some(match (line_comment, gap.contains('\n')) {
|
||||
(true, _) => vec![
|
||||
insert(last.end, ",".to_string()),
|
||||
insert(at, format!("{newline}{indent}{element}")),
|
||||
],
|
||||
(false, true) => vec![insert(at, format!(",{newline}{indent}{element}"))],
|
||||
(false, false) => vec![insert(at, format!(", {element}"))],
|
||||
})
|
||||
}
|
||||
|
||||
fn insert(at: u32, text: String) -> TextEdit {
|
||||
TextEdit { range: TextRange::empty(at), new_text: text }
|
||||
}
|
||||
|
||||
/// Where an append writes once the comments written after the last element
|
||||
/// on its own line are stepped over, and whether the last of them is a `//`
|
||||
/// comment (whose end is the line break, before a CRLF's `\r`).
|
||||
fn after_same_line_comments(text: &str, end: u32) -> (u32, bool) {
|
||||
let mut at = end as usize;
|
||||
loop {
|
||||
let Some(rest) = text.get(at..) else { return (at as u32, false) };
|
||||
let blanks = rest.len() - rest.trim_start_matches([' ', '\t']).len();
|
||||
let rest = &rest[blanks..];
|
||||
if rest.starts_with("//") {
|
||||
let line = rest.find('\n').unwrap_or(rest.len());
|
||||
let line = match rest[..line].ends_with('\r') {
|
||||
true => line - 1,
|
||||
false => line,
|
||||
};
|
||||
return ((at + blanks + line) as u32, true);
|
||||
}
|
||||
if !rest.starts_with("/*") {
|
||||
return (at as u32, false);
|
||||
}
|
||||
match rest.find("*/") {
|
||||
Some(close) if !rest[..close].contains('\n') => at += blanks + close + 2,
|
||||
_ => return (at as u32, false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The blanks the line holding `offset` starts with, or nothing when
|
||||
/// `offset` is not the first thing written on its line.
|
||||
fn line_indent(text: &str, offset: u32) -> String {
|
||||
let offset = offset as usize;
|
||||
let start = text.get(..offset).map_or(0, |before| before.rfind('\n').map_or(0, |n| n + 1));
|
||||
let Some(head) = text.get(start..offset) else { return String::new() };
|
||||
match head.chars().all(|c| c == ' ' || c == '\t') {
|
||||
true => head.to_string(),
|
||||
false => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::ast::{Connections, ItemKind};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
/// The one instance in `module m; … endmodule`, appended to.
|
||||
fn appended(body: &str, element: &str) -> String {
|
||||
let text = format!("module m;\n{body}\nendmodule\n");
|
||||
let (tree, _) = parse_source_tolerant(&text);
|
||||
let Some(ItemKind::Module(module)) = tree.items.first().map(|i| &i.kind) else {
|
||||
panic!("a module")
|
||||
};
|
||||
let conns = module
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|item| match &item.kind {
|
||||
ItemKind::Instantiation(inst) => match &inst.instances[0].conns {
|
||||
Connections::Named(conns) => Some(conns),
|
||||
Connections::Ordered(_) => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.expect("a named list");
|
||||
let edits = append(&text, conns, element).expect("an append");
|
||||
crate::apply(&text, &edits)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_list_stays_inline() {
|
||||
assert!(appended(" c u (.*);", ".d(x)").contains(" c u (.*, .d(x));"));
|
||||
assert!(appended(" c u (.a(b), .* /* all */);", ".d(x)")
|
||||
.contains("(.a(b), .* /* all */, .d(x));"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_one_per_line_gets_its_own_line_at_the_same_indent() {
|
||||
let out = appended(" c u (\n .a(b),\n .*\n );", ".d(x)");
|
||||
assert!(out.contains(" .*,\n .d(x)\n );"), "{out}");
|
||||
let lone = appended(" c u (\n .*\n );", ".d(x)");
|
||||
assert!(lone.contains(" .*,\n .d(x)\n );"), "{lone}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_comment_after_the_last_element_keeps_the_comma_out_of_it() {
|
||||
let out = appended(" c u (\n .* // everything\n );", ".d(x)");
|
||||
assert!(out.contains(" .*, // everything\n .d(x)\n );"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_list_stays_crlf() {
|
||||
let out = appended(" c u (\r\n .* // all\r\n );", ".d(x)");
|
||||
assert!(out.contains(" .*, // all\r\n .d(x)\r\n );"), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_name_is_terminated() {
|
||||
assert_eq!(connection("\\a-b", "c"), ".\\a-b (c)");
|
||||
assert_eq!(shorthand_tail(5, "\\q", "\\p").new_text, " (\\p )");
|
||||
assert_eq!(shorthand_tail(5, "q", "p").new_text, "(p)");
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,16 @@
|
||||
//! This file is the rename itself: the entry points, the new-name check, the
|
||||
//! walk from a cursor to the declaration it means, the occurrences of that
|
||||
//! declaration, and the refusal sentences. `crate::scope` is the in-scope
|
||||
//! workspace every refactoring in this crate reads through, and `warnings` is
|
||||
//! what a finished rename says about the occurrences it could not edit.
|
||||
//! workspace every refactoring in this crate reads through, `warnings` is
|
||||
//! what a finished rename says about the occurrences it could not edit, and
|
||||
//! `connections` (with `sites` and `layout`) rewrites the `.name` and `.*`
|
||||
//! connections that bind the renamed name implicitly.
|
||||
|
||||
mod connections;
|
||||
use connections::{combine, fuse};
|
||||
mod layout;
|
||||
mod preflight;
|
||||
pub(crate) mod sites;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod warnings;
|
||||
@@ -245,7 +251,12 @@ fn renaming(
|
||||
if target.name == new_name {
|
||||
return Err(already_named(new_name));
|
||||
}
|
||||
let edits = trace.edits.measure(|| scope.collect_edits(&target, new_name))?;
|
||||
let edits = trace.edits.measure(|| {
|
||||
let renamed = scope.collect_edits(&target, new_name)?;
|
||||
let implicit = scope.implicit_connections(&target, new_name, &renamed)?;
|
||||
Ok::<_, String>((combine(renamed, implicit.edits)?, implicit.warnings))
|
||||
});
|
||||
let (edits, rewrites) = edits?;
|
||||
trace.edited = edits.len();
|
||||
// Two disjoint fields of one trace: `verify` times the whole pass while
|
||||
// `checks` is filled by its stages, so they are borrowed apart.
|
||||
@@ -253,10 +264,11 @@ fn renaming(
|
||||
verify.measure(|| check::verify(&mut scope, &edits, &target.name, new_name, checks))?;
|
||||
|
||||
let RenameTrace { warnings: stage, warning_scans, .. } = &mut *trace;
|
||||
let warnings = stage.measure(|| scope.warnings(&target, &edits, warning_scans));
|
||||
let mut warnings = stage.measure(|| scope.warnings(&target, &edits, warning_scans));
|
||||
warnings.extend(rewrites);
|
||||
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
|
||||
.into_iter()
|
||||
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
|
||||
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), fuse(edits))))
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(RefactorEdit { edits: out, warnings, created: Vec::new() })
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
//! Where an implicit connection is written, and where its name binds.
|
||||
//!
|
||||
//! `.name` and `.*` (IEEE 1800 §23.3.2.3–4) connect a port to the same-named
|
||||
//! declaration visible where the instance is written — or, for a `bind`, in
|
||||
//! the target's scope (§23.11). The semantic layer records a reference for
|
||||
//! the `.port` half of `.name` and nothing at all for the net half or for
|
||||
//! `.*`, so nothing a reference walk sees says that renaming the net (or the
|
||||
//! port) cuts the binding. This file is the AST walk both halves of the rename
|
||||
//! read that from: the engine (`connections.rs`) to decide the rewrite, the
|
||||
//! verifier (`check::implicit`) to print what every implicit binding names
|
||||
//! before and after it.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
BindDirective, Connection, Connections, GenBlock, GenElse, Instance, Instantiation, Item,
|
||||
ItemKind, ListElem,
|
||||
};
|
||||
use vlog_semantic::{Semantics, SymbolId, SymbolKind};
|
||||
|
||||
/// One instance with a **named** connection list, and the `bind` directive
|
||||
/// it is written in, if it is one. A positional list has no implicit
|
||||
/// connection, so it is not visited.
|
||||
pub(crate) struct Site<'t> {
|
||||
pub(crate) instantiation: &'t Instantiation,
|
||||
pub(crate) instance: &'t Instance,
|
||||
pub(crate) conns: &'t [ListElem<Connection>],
|
||||
pub(crate) bind: Option<&'t BindDirective>,
|
||||
}
|
||||
|
||||
impl<'t> Site<'t> {
|
||||
/// The well-formed connections.
|
||||
pub(crate) fn connections(&self) -> impl Iterator<Item = &'t Connection> {
|
||||
self.conns.iter().filter_map(ListElem::ok)
|
||||
}
|
||||
|
||||
/// True when the list writes `.*`.
|
||||
pub(crate) fn has_wildcard(&self) -> bool {
|
||||
self.connections().any(|c| c.name == "*")
|
||||
}
|
||||
|
||||
/// The connection naming port `name` explicitly (`.name` or `.name(…)`).
|
||||
pub(crate) fn named(&self, name: &str) -> Option<&'t Connection> {
|
||||
self.connections().find(|c| c.name == name)
|
||||
}
|
||||
|
||||
/// The raw text of every element a tolerant parse could not read.
|
||||
pub(crate) fn unreadable(&self) -> impl Iterator<Item = &'t str> {
|
||||
self.conns.iter().filter_map(|e| match e {
|
||||
ListElem::Error(raw) => Some(raw.text.as_str()),
|
||||
ListElem::Ok(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The module a `bind` binds into, when the target is one plain name —
|
||||
/// the only target whose scope lucisv can name without elaborating.
|
||||
/// `Err(())` for a hierarchical or indexed target; `Ok(None)` for an
|
||||
/// ordinary instantiation.
|
||||
pub(crate) fn bind_target(&self) -> Result<Option<&'t str>, ()> {
|
||||
match self.bind.map(|b| b.target.as_slice()) {
|
||||
None => Ok(None),
|
||||
Some([only]) if only.index.is_none() => Ok(Some(only.name.as_str())),
|
||||
Some(_) => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every instance with a named connection list in `items`: modules,
|
||||
/// packages, generate regions and blocks, and `bind` directives.
|
||||
pub(crate) fn sites(items: &[Item]) -> Vec<Site<'_>> {
|
||||
let mut out = Vec::new();
|
||||
walk(items, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn walk<'t>(items: &'t [Item], out: &mut Vec<Site<'t>>) {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Instantiation(inst) => push(inst, None, out),
|
||||
ItemKind::Bind(bind) => push(&bind.inst, Some(bind), out),
|
||||
ItemKind::Module(module) => walk(&module.items, out),
|
||||
ItemKind::Package { items, .. } => walk(items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, out),
|
||||
ItemKind::GenBlock(block) => walk(&block.items, out),
|
||||
ItemKind::GenIf(gen) => {
|
||||
walk_block(&gen.then, out);
|
||||
let mut els = gen.els.as_deref();
|
||||
while let Some(next) = els {
|
||||
match next {
|
||||
GenElse::If(_, gen) => {
|
||||
walk_block(&gen.then, out);
|
||||
els = gen.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
walk_block(block, out);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen) => walk_block(&gen.body, out),
|
||||
ItemKind::GenCase(gen) => gen.items.iter().for_each(|arm| walk_block(&arm.body, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_block<'t>(block: &'t GenBlock, out: &mut Vec<Site<'t>>) {
|
||||
walk(&block.items, out);
|
||||
}
|
||||
|
||||
fn push<'t>(inst: &'t Instantiation, bind: Option<&'t BindDirective>, out: &mut Vec<Site<'t>>) {
|
||||
for instance in &inst.instances {
|
||||
if let Connections::Named(conns) = &instance.conns {
|
||||
out.push(Site { instantiation: inst, instance, conns, bind });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `.name` or `.*` can bind a declaration of this kind: a net, a
|
||||
/// variable, a port of the enclosing module (the reading `ports/expand.rs`
|
||||
/// uses), and an instance — an interface instance is what a `.*` binds an
|
||||
/// interface port to, and writing a module instance's connection out
|
||||
/// explicitly is exactly as wrong as the implicit one was. Anything else (a
|
||||
/// parameter, a type, a module) is never bound, whatever its name.
|
||||
pub(crate) fn binds_implicitly(kind: SymbolKind) -> bool {
|
||||
matches!(kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port | SymbolKind::Instance)
|
||||
}
|
||||
|
||||
/// The declaration a lookup of `name` finds from the innermost scope covering
|
||||
/// `offset`, walking outwards — what `.name` and `.*` bind to at an instance
|
||||
/// written there. The nearest declaration wins whatever its kind; the caller
|
||||
/// judges the kind.
|
||||
///
|
||||
/// Local scopes only: a name a `.*` could only reach through a package import
|
||||
/// is not seen (the README's Assumptions say what that costs).
|
||||
pub(crate) fn nearest(semantics: &Semantics, offset: u32, name: &str) -> Option<SymbolId> {
|
||||
let scopes = semantics.scopes();
|
||||
let mut best: Option<usize> = None;
|
||||
for (i, scope) in scopes.iter().enumerate() {
|
||||
if !scope.span.contains(offset) {
|
||||
continue;
|
||||
}
|
||||
let better = best.is_none_or(|b| {
|
||||
scopes.get(b).is_some_and(|current| scope.span.len() <= current.span.len())
|
||||
});
|
||||
if better {
|
||||
best = Some(i);
|
||||
}
|
||||
}
|
||||
let mut at = best;
|
||||
while let Some(i) = at {
|
||||
let current = scopes.get(i)?;
|
||||
if let Some(symbol) = current.lookup_local(name) {
|
||||
return Some(symbol);
|
||||
}
|
||||
at = current.parent.map(|p| p.0 as usize);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `text` could write an implicit connection naming one of `names`:
|
||||
/// a `.` that starts a list element (see [`opens_an_element`]) followed —
|
||||
/// past blanks and comments — by `*` or by one of the names as a whole word.
|
||||
/// A cheap superset of the parse that answers it exactly, so the engine and
|
||||
/// the verifier parse only the files that pass; a hierarchical `u_x.d` is
|
||||
/// not a connection and does not pass.
|
||||
pub(crate) fn may_connect_implicitly(text: &str, names: &[&str]) -> bool {
|
||||
let bytes = text.as_bytes();
|
||||
let mut from = 0usize;
|
||||
while let Some(hit) = text.get(from..).and_then(|rest| rest.find('.')) {
|
||||
let dot = from + hit;
|
||||
from = dot + 1;
|
||||
if !opens_an_element(text, dot) {
|
||||
continue;
|
||||
}
|
||||
let after = skip_trivia(text, dot + 1);
|
||||
let rest = text.get(after..).unwrap_or("");
|
||||
if rest.starts_with('*') {
|
||||
return true;
|
||||
}
|
||||
let names_it = |name: &&str| {
|
||||
let end = after + name.len();
|
||||
let whole = !bytes.get(end).is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
|
||||
!name.is_empty() && rest.starts_with(*name) && whole
|
||||
};
|
||||
if names.iter().any(names_it) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the `.` at `dot` may begin an element of a connection list: the
|
||||
/// last thing before it, past blanks and block comments, is `(`, `,` or the
|
||||
/// `*)` of an attribute — or a line lucisv does not read backwards (one
|
||||
/// holding a `//` comment, or a compiler directive), which is let through,
|
||||
/// because a superset is what the prefilter promises.
|
||||
fn opens_an_element(text: &str, dot: usize) -> bool {
|
||||
let mut end = dot;
|
||||
loop {
|
||||
let Some(before) = text.get(..end) else { return true };
|
||||
let trimmed = before.trim_end();
|
||||
if trimmed.ends_with("*/") {
|
||||
match trimmed.rfind("/*") {
|
||||
Some(open) => end = open,
|
||||
None => return true,
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let line_start = trimmed.rfind('\n').map_or(0, |n| n + 1);
|
||||
let line = &trimmed[line_start..];
|
||||
let crossed_a_line = before.get(trimmed.len()..).is_some_and(|gap| gap.contains('\n'));
|
||||
if crossed_a_line && (line.contains("//") || line.trim_start().starts_with('`')) {
|
||||
return true;
|
||||
}
|
||||
return trimmed.ends_with('(') || trimmed.ends_with(',') || trimmed.ends_with("*)");
|
||||
}
|
||||
}
|
||||
|
||||
/// The offset of the first byte at or after `at` that is neither blank nor
|
||||
/// inside a comment.
|
||||
fn skip_trivia(text: &str, mut at: usize) -> usize {
|
||||
loop {
|
||||
let Some(rest) = text.get(at..) else { return at };
|
||||
let trimmed = rest.trim_start();
|
||||
at += rest.len() - trimmed.len();
|
||||
if trimmed.starts_with("//") {
|
||||
at += trimmed.find('\n').unwrap_or(trimmed.len());
|
||||
} else if trimmed.starts_with("/*") {
|
||||
at += trimmed.find("*/").map_or(trimmed.len(), |end| end + 2);
|
||||
} else {
|
||||
return at;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_prefilter_sees_a_wildcard_and_a_shorthand_past_comments() {
|
||||
assert!(may_connect_implicitly("u (. /* c */ *);", &["d"]));
|
||||
assert!(may_connect_implicitly("u (.clk, .d);", &["d"]));
|
||||
assert!(may_connect_implicitly("u (.\n // why\n d);", &["d"]));
|
||||
assert!(may_connect_implicitly("u (.a(b), /* c */ .d);", &["d"]));
|
||||
assert!(may_connect_implicitly("u (.a(b), // c\n .d);", &["d"]));
|
||||
assert!(may_connect_implicitly("u (\n`ifdef A\n .*\n`endif\n);", &["d"]));
|
||||
assert!(may_connect_implicitly("u ((* keep *) .d);", &["d"]));
|
||||
assert!(!may_connect_implicitly("u (.dd(x), .e(d));", &["d"]));
|
||||
assert!(!may_connect_implicitly("assign a = b.c;", &["d"]));
|
||||
assert!(!may_connect_implicitly("assign w = u_sub.d;", &["d"]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
//! QA attacks on the rename's implicit-connection rewrite (TODO-MCP M3.5):
|
||||
//! `.name` and `.*` written out explicitly when a rename would cut them.
|
||||
//!
|
||||
//! Every test drives the public `rename` over a little in-memory workspace
|
||||
//! and asserts the whole text of each file afterwards, or the refusal's
|
||||
//! sentence — the harness of `tests/rename_implicit.rs`. The verifier-direct
|
||||
//! attacks (crafted corrupted edits handed to `check::verify`) need the
|
||||
//! crate-internal entry point and live in `src/check/qa_implicit.rs`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{rename, RefactorEdit};
|
||||
|
||||
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
|
||||
}
|
||||
|
||||
fn path(name: &str) -> PathBuf {
|
||||
PathBuf::from("/rtl").join(name)
|
||||
}
|
||||
|
||||
/// The offset of the first whole-word `name` at or after `prefix`.
|
||||
fn at(text: &str, prefix: &str, name: &str) -> u32 {
|
||||
let from =
|
||||
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text")) + prefix.len();
|
||||
let is_word = |b: Option<&u8>| {
|
||||
b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'\\' || *b == b'-')
|
||||
};
|
||||
let bytes = text.as_bytes();
|
||||
let mut search = from;
|
||||
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
|
||||
let start = search + hit;
|
||||
let end = start + name.len();
|
||||
let before_ok = !is_word(start.checked_sub(1).and_then(|i| bytes.get(i)));
|
||||
if before_ok && (name.ends_with(' ') || !is_word(bytes.get(end))) {
|
||||
return start as u32;
|
||||
}
|
||||
search = start + 1;
|
||||
}
|
||||
panic!("`{name}` does not occur after `{prefix}`");
|
||||
}
|
||||
|
||||
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0usize;
|
||||
for e in edit.edits_for(file) {
|
||||
out.push_str(&text[cursor..e.range.start as usize]);
|
||||
out.push_str(&e.new_text);
|
||||
cursor = e.range.end as usize;
|
||||
}
|
||||
out.push_str(&text[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
type Outcome = Result<(Vec<String>, Vec<String>), String>;
|
||||
|
||||
/// Rename the `name` after `prefix` in `file`; every file's text afterwards,
|
||||
/// and the warnings.
|
||||
fn renamed(files: &[(&str, &str)], file: &str, prefix: &str, name: &str, new: &str) -> Outcome {
|
||||
let sources = workspace(files);
|
||||
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
|
||||
let edit = rename(&sources, &path(file), at(text, prefix, name), new)?;
|
||||
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
|
||||
Ok((texts, edit.warnings))
|
||||
}
|
||||
|
||||
/// The same, over already-renamed texts (for the round trip).
|
||||
fn renamed_owned(
|
||||
files: &[(&str, String)],
|
||||
file: &str,
|
||||
prefix: &str,
|
||||
name: &str,
|
||||
new: &str,
|
||||
) -> Outcome {
|
||||
let borrowed: Vec<(&str, &str)> = files.iter().map(|(n, t)| (*n, t.as_str())).collect();
|
||||
renamed(&borrowed, file, prefix, name, new)
|
||||
}
|
||||
|
||||
const LEAF: &str = "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n";
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// port rename: list shapes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_port_rename_over_shorthand_wildcard_explicit_and_mixed_lists() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (.clk, .d, .q);\n leaf u_b (.*);\n leaf u_c (.clk(clk), .d(d), .q(q));\n leaf u_d (.clk, .*);\n leaf u_e (.d, .*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, warnings) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
let want = top
|
||||
.replace("u_a (.clk, .d, .q)", "u_a (.clk, .din(d), .q)")
|
||||
.replace("u_b (.*)", "u_b (.*, .din(d))")
|
||||
.replace("u_c (.clk(clk), .d(d)", "u_c (.clk(clk), .din(d)")
|
||||
.replace("u_d (.clk, .*)", "u_d (.clk, .*, .din(d))")
|
||||
.replace("u_e (.d, .*)", "u_e (.din(d), .*)");
|
||||
assert_eq!(texts[1], want);
|
||||
// One sentence per rewrite: u_a and u_e shorthands, u_b and u_d wildcards.
|
||||
assert_eq!(warnings.len(), 4, "{warnings:?}");
|
||||
for (inst, how) in
|
||||
[("u_a", "shorthand"), ("u_b", "`.*`"), ("u_d", "`.*`"), ("u_e", "shorthand")]
|
||||
{
|
||||
assert!(
|
||||
warnings
|
||||
.iter()
|
||||
.any(|w| w.starts_with(&format!("`{inst}` at top.sv:")) && w.contains(how)),
|
||||
"{inst}: {warnings:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_two_instances_in_one_instantiation_each_get_their_connection() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (.*), u_b (.clk, .d, .q());\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(
|
||||
texts[1],
|
||||
top.replace("u_a (.*)", "u_a (.*, .din(d))")
|
||||
.replace("u_b (.clk, .d,", "u_b (.clk, .din(d),")
|
||||
);
|
||||
let (texts, _) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(
|
||||
texts[1],
|
||||
top.replace("[7:0] d", "[7:0] x")
|
||||
.replace("u_a (.*)", "u_a (.*, .d(x))")
|
||||
.replace("u_b (.clk, .d,", "u_b (.clk, .d(x),")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_instance_array_with_a_wildcard_is_written_out() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q [3:0]);\n leaf u[3:0] (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("(.*)", "(.*, .din(d))"));
|
||||
let (texts, _) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("[7:0] d", "[7:0] x").replace("(.*)", "(.*, .d(x))"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_non_ansi_port_is_written_out() {
|
||||
let leaf = "module leaf (clk, d, q);\n input logic clk;\n input logic [7:0] d;\n output logic [7:0] q;\n always_ff @(posedge clk) q <= d;\nendmodule\n";
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (.*);\n leaf u_b (.clk, .d, .q);\nendmodule\n";
|
||||
let files = [("leaf.sv", leaf), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "(clk, ", "d", "din").expect("renames");
|
||||
assert_eq!(
|
||||
texts[1],
|
||||
top.replace("u_a (.*)", "u_a (.*, .din(d))")
|
||||
.replace("u_b (.clk, .d,", "u_b (.clk, .din(d),")
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// layout
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_one_per_line_with_a_line_comment_on_the_last_element() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (\n .clk (clk), // clock\n .* // the rest\n );\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(
|
||||
texts[1],
|
||||
top.replace(" .* // the rest\n", " .*, // the rest\n .din(d)\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_inline_list_with_a_trailing_line_comment() {
|
||||
// An inline list whose `)` is on the next line: the comma goes before the
|
||||
// comment, the connection on its own line (at column 0 — the `.*` is not
|
||||
// first on its line, so there is no indentation to copy).
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.* // all\n );\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("(.* // all\n", "(.*, // all\n.din(d)\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_attribute_and_a_block_comment_on_the_last_element_survive() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf ((* keep *) .clk, (* dont_touch *) .* /* rest */);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], top.replace(".* /* rest */)", ".* /* rest */, .din(d))"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_escaped_net_is_written_out_with_its_terminating_blank() {
|
||||
let leaf = "module leaf (input logic clk, input logic \\d$x );\nendmodule\n";
|
||||
let top = "module top (input logic clk, input logic \\d$x );\n leaf u_a (.*);\n leaf u_b (.clk, .\\d$x );\nendmodule\n";
|
||||
let files = [("leaf.sv", leaf), ("top.sv", top)];
|
||||
// The parent's escaped net renamed to a plain name.
|
||||
let (texts, _) = renamed(&files, "top.sv", "logic ", "\\d$x ", "dd").expect("renames");
|
||||
assert_eq!(
|
||||
texts[1],
|
||||
// The blank that ended the escaped name stays where it was.
|
||||
top.replacen("logic \\d$x )", "logic dd )", 1)
|
||||
.replace("u_a (.*)", "u_a (.*, .\\d$x (dd))")
|
||||
.replace("u_b (.clk, .\\d$x )", "u_b (.clk, .\\d$x (dd) )")
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// hierarchy: nested wildcards, bind, interfaces, generate
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_a_leaf_port_under_nested_wildcards_touches_only_the_direct_parent() {
|
||||
let mid = "module mid (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n mid u_mid (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("mid.sv", mid), ("top.sv", top)];
|
||||
let (texts, warnings) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], mid.replace("(.*)", "(.*, .din(d))"));
|
||||
assert_eq!(texts[2], top, "top's `.*` binds mid's `d`, which did not move");
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_net_rename_reaches_a_bind_in_a_file_spelling_neither_name() {
|
||||
// The whole-set caller: binds.sv spells neither `d` nor `x`, so neither
|
||||
// the watched-file rule nor a name search finds it — only the bind walk.
|
||||
let bind = "module binds;\n bind top leaf u_b (.*);\nendmodule\n";
|
||||
let top =
|
||||
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top), ("binds.sv", bind)];
|
||||
let (texts, warnings) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("[7:0] d", "[7:0] x"));
|
||||
assert_eq!(texts[2], bind.replace("(.*)", "(.*, .d(x))"));
|
||||
assert_eq!(
|
||||
warnings,
|
||||
vec!["`u_b` at binds.sv:2 bound `d` through `.*`; added `.d(x)`.".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_net_rename_behind_a_hierarchical_bind_is_refused() {
|
||||
let bind = "module binds;\n bind top.u_x leaf u_b (.*);\nendmodule\n";
|
||||
let top =
|
||||
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top), ("binds.sv", bind)];
|
||||
let refusal = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect_err("refused");
|
||||
assert!(
|
||||
refusal.contains("`u_b` at binds.sv:2 may bind `d` implicitly through `.*`"),
|
||||
"{refusal}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_bind_with_an_instance_list_target() {
|
||||
// `bind top : u_t leaf ...` binds into top's instances named `u_t`; its
|
||||
// scope is still `top`'s.
|
||||
let bind = "module binds;\n bind top : u_t leaf u_b (.*);\nendmodule\n";
|
||||
let top =
|
||||
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top), ("binds.sv", bind)];
|
||||
let (texts, warnings) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(texts[2], bind.replace("(.*)", "(.*, .d(x))"));
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_interface_port_bound_by_wildcard_is_written_out() {
|
||||
let bus = "interface bus_if;\n logic v;\nendinterface\n";
|
||||
let sub = "module sub (bus_if bus, input logic clk);\nendmodule\n";
|
||||
let top = "module top (input logic clk);\n bus_if bus ();\n sub u_sub (.*);\nendmodule\n";
|
||||
let files = [("bus_if.sv", bus), ("sub.sv", sub), ("top.sv", top)];
|
||||
let (texts, warnings) = renamed(&files, "sub.sv", "bus_if ", "bus", "b").expect("renames");
|
||||
assert_eq!(texts[1], sub.replace("bus_if bus,", "bus_if b,"));
|
||||
assert_eq!(texts[2], top.replace("(.*)", "(.*, .b(bus))"));
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_generate_shadow_is_left_to_its_own_net() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n if (1) begin : g\n logic [7:0] d;\n leaf u_g (.*);\n leaf u_h (.clk, .d, .q());\n end\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
// The module-level port: only the instance outside the block sees it.
|
||||
let (texts, _) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(
|
||||
texts[1],
|
||||
top.replacen("[7:0] d", "[7:0] x", 1).replace("u_leaf (.*)", "u_leaf (.*, .d(x))")
|
||||
);
|
||||
// The block's own net: only the instances inside it.
|
||||
let (texts, _) = renamed(&files, "top.sv", " logic [7:0] ", "d", "y").expect("renames");
|
||||
assert_eq!(
|
||||
texts[1],
|
||||
top.replace(" logic [7:0] d;", " logic [7:0] y;")
|
||||
.replace("u_g (.*)", "u_g (.*, .d(y))")
|
||||
.replace("u_h (.clk, .d,", "u_h (.clk, .d(y),")
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// refusals
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_a_port_rename_into_a_module_declared_twice_is_refused() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("leaf_copy.sv", LEAF), ("top.sv", top)];
|
||||
let refusal = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect_err("refused");
|
||||
assert!(refusal.contains("u_leaf"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_port_rename_over_an_ifdef_split_wildcard_list_is_refused() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (\n`ifdef A\n .clk(1'b0),\n`endif\n .*\n );\nendmodule\n";
|
||||
let refusal = renamed(&[("leaf.sv", LEAF), ("top.sv", top)], "leaf.sv", "[7:0] ", "d", "din")
|
||||
.expect_err("refused");
|
||||
assert!(refusal.contains("split by compiler directives"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_port_rename_a_parent_wildcard_would_capture_is_refused() {
|
||||
// top declares `din` but no `d`: `.*` bound nothing to `d`, and would
|
||||
// start binding top's `din` to the renamed port.
|
||||
let top = "module top (input logic clk, input logic [7:0] din, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let refusal = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect_err("refused");
|
||||
assert!(refusal.contains("would start binding `din`"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_parameter_named_like_the_port_is_no_binding() {
|
||||
// A parameter `d` in top shadows nothing a `.*` can bind: leave it alone.
|
||||
let top = "module top #(parameter int d = 1) (input logic clk, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, warnings) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], top);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// round trip
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_renaming_back_restores_everything_but_the_written_out_connections() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (.*);\n leaf u_b (.clk, .d, .q);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (once, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
let back: Vec<(&str, String)> = vec![("leaf.sv", once[0].clone()), ("top.sv", once[1].clone())];
|
||||
let (twice, warnings) =
|
||||
renamed_owned(&back, "leaf.sv", "[7:0] ", "din", "d").expect("renames back");
|
||||
assert_eq!(twice[0], LEAF, "the declaring file is byte-identical");
|
||||
// The connections stay explicit: `.*` gains `.d(d)`, `.d` became `.d(d)`.
|
||||
assert_eq!(
|
||||
twice[1],
|
||||
top.replace("u_a (.*)", "u_a (.*, .d(d))").replace("u_b (.clk, .d,", "u_b (.clk, .d(d),")
|
||||
);
|
||||
assert!(warnings.is_empty(), "the explicit connections are plain references now: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_shorthand_into_an_unreadable_module_is_still_written_out() {
|
||||
// The shorthand's port half does not move, so the module need not be read.
|
||||
let top =
|
||||
"module top (input logic clk, input logic [7:0] d);\n ghost u_g (.clk, .d);\nendmodule\n";
|
||||
let (texts, warnings) =
|
||||
renamed(&[("top.sv", top)], "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(texts[0], top.replace("[7:0] d", "[7:0] x").replace(".clk, .d)", ".clk, .d(x))"));
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// QA findings
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// QA finding 2: a `bind` whose target is a lone *instance* name (opentitan's
|
||||
/// `prim/fpv/tb/prim_fifo_sync_bind_fpv.sv`: `bind i_nopass1
|
||||
/// prim_fifo_sync_assert_fpv … (.clk_i, .rst_ni, .clr_i, … .err_o)`) refuses
|
||||
/// the rename of every module-level declaration spelled like one of its
|
||||
/// shorthands, in *any* module — renaming `prim_count`'s `err_o` or
|
||||
/// `aes_core`'s `clk_i` is refused over a bind into a `prim_fifo_sync`. The
|
||||
/// index knows `i_f` is an instance of `fifo`, not of `cnt`.
|
||||
#[test]
|
||||
fn qa_a_bind_into_an_instance_of_another_module_does_not_refuse() {
|
||||
let cnt =
|
||||
"module cnt (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
|
||||
let fifo =
|
||||
"module fifo (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
|
||||
let check = "module fifo_assert (input logic clk_i, input logic err_o);\nendmodule\n";
|
||||
let tb = "module tb;\n logic clk_i, err_o;\n fifo i_f (.clk_i, .err_o);\nendmodule\n";
|
||||
let bind = "module tb_bind;\n bind i_f fifo_assert u_a (.clk_i, .err_o);\nendmodule\n";
|
||||
let files =
|
||||
[("cnt.sv", cnt), ("fifo.sv", fifo), ("check.sv", check), ("tb.sv", tb), ("bind.sv", bind)];
|
||||
let (texts, _) = renamed(&files, "cnt.sv", "output logic ", "err_o", "error_o")
|
||||
.expect("the bind targets an instance of `fifo`, which the rename does not touch");
|
||||
assert_eq!(texts[4], bind);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// M3.5 re-check (2026-09-23): the enclosing-module rule for a bind onto a
|
||||
// bare instance name
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const CNT: &str =
|
||||
"module cnt (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
|
||||
const FIFO: &str =
|
||||
"module fifo (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
|
||||
const CHECK: &str = "module chk (input logic clk_i, input logic err_o);\nendmodule\n";
|
||||
|
||||
/// Rename `cnt`'s `err_o` over the three modules plus `extra`.
|
||||
fn rename_cnt_err(extra: &[(&'static str, &'static str)]) -> Outcome {
|
||||
let mut files = vec![("cnt.sv", CNT), ("fifo.sv", FIFO), ("chk.sv", CHECK)];
|
||||
files.extend_from_slice(extra);
|
||||
renamed(&files, "cnt.sv", "output logic ", "err_o", "error_o")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_b_the_enclosing_modules_own_instance_wins_and_is_another_module() {
|
||||
// A binds onto its own `u` (a fifo); B also has a `u`, a cnt. A's wins.
|
||||
let a = "module a;\n logic clk_i, err_o;\n fifo u (.clk_i, .err_o);\n bind u chk c_u (.clk_i, .err_o);\nendmodule\n";
|
||||
let b = "module b;\n logic clk_i, err_o;\n cnt u (.clk_i, .err_o);\nendmodule\n";
|
||||
let (texts, _) = rename_cnt_err(&[("a.sv", a), ("b.sv", b)])
|
||||
.expect("A's `u` is a fifo: the bind never sees cnt's err_o");
|
||||
assert_eq!(texts[3], a, "a.sv untouched");
|
||||
assert_eq!(texts[4], b.replace(".err_o)", ".error_o(err_o))"), "b's shorthand written out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_b_the_enclosing_modules_own_instance_wins_and_is_ours() {
|
||||
// Swapped: A's own `u` is the cnt, B's is a fifo — refused, not guessed.
|
||||
let a = "module a;\n logic clk_i, err_o;\n cnt u (.clk_i, .err_o);\n bind u chk c_u (.clk_i, .err_o);\nendmodule\n";
|
||||
let b = "module b;\n logic clk_i, err_o;\n fifo u (.clk_i, .err_o);\nendmodule\n";
|
||||
let refusal = rename_cnt_err(&[("a.sv", a), ("b.sv", b)]).expect_err("refused");
|
||||
assert!(refusal.contains("`c_u` at a.sv:4"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_b_a_file_scope_bind_onto_another_modules_instance_is_skipped() {
|
||||
let tb = "module tb;\n logic clk_i, err_o;\n fifo u (.clk_i, .err_o);\nendmodule\n";
|
||||
let bind = "bind u chk c_u (.clk_i, .err_o);\n";
|
||||
let (texts, warnings) =
|
||||
rename_cnt_err(&[("tb.sv", tb), ("bind.sv", bind)]).expect("only a fifo is named `u`");
|
||||
assert_eq!((texts[3].as_str(), texts[4].as_str()), (tb, bind));
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_b_a_file_scope_bind_onto_our_instance_is_refused() {
|
||||
let tb = "module tb;\n logic clk_i, err_o;\n cnt u (.clk_i, .err_o);\nendmodule\n";
|
||||
let bind = "bind u chk c_u (.clk_i, .err_o);\n";
|
||||
let refusal = rename_cnt_err(&[("tb.sv", tb), ("bind.sv", bind)]).expect_err("refused");
|
||||
assert!(refusal.contains("`c_u` at bind.sv:1"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_b_a_bind_onto_a_name_no_indexed_instance_has_is_refused() {
|
||||
let bind = "module tb_bind;\n bind u_ghost chk c_u (.clk_i, .err_o);\nendmodule\n";
|
||||
let refusal = rename_cnt_err(&[("bind.sv", bind)]).expect_err("refused");
|
||||
assert!(refusal.contains("`c_u` at bind.sv:2"), "{refusal}");
|
||||
}
|
||||
|
||||
/// QA note 1 (non-blocking, lead-accepted gap): an instance inside a generate
|
||||
/// block of the enclosing module is counted as the enclosing module's own.
|
||||
/// Upward resolution from `a` does not see `a.g.u`, so `bind u` here reaches
|
||||
/// the parent's `u` — a `cnt` — and its `.err_o` binds `cnt`'s renamed port.
|
||||
/// The engine skips it; the verifier prints a bind onto an instance as
|
||||
/// opaque on both sides, so nothing refuses and the shorthand is cut.
|
||||
#[test]
|
||||
#[ignore = "QA note 1: accepted generate-block gap"]
|
||||
fn qa_b_a_generate_scoped_instance_is_not_the_enclosing_modules_own() {
|
||||
let a = "module a;\n logic clk_i, err_o;\n if (1) begin : g\n fifo u (.clk_i, .err_o);\n end\n bind u chk c_u (.clk_i, .err_o);\nendmodule\n";
|
||||
let p = "module p;\n logic clk_i, err_o;\n a u_a ();\n cnt u (.clk_i, .err_o);\nendmodule\n";
|
||||
let outcome = rename_cnt_err(&[("a.sv", a), ("p.sv", p)]);
|
||||
let refusal = outcome.expect_err("the bind may reach p.u, a cnt");
|
||||
assert!(refusal.contains("`c_u`"), "{refusal}");
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
//! A rename versus the connections that bind by equal names: `.name` and
|
||||
//! `.*` (M3 QA finding 1, TODO-MCP M3.5).
|
||||
//!
|
||||
//! Renaming a port `d` of `leaf` used to leave `leaf u_leaf (.*)` binding
|
||||
//! nothing and turn `.d` into `.din` against a parent with no net `din`;
|
||||
//! renaming the parent's net `d` left both bindings dangling — and each one
|
||||
//! verified clean. Every test here drives the public `rename` over a little
|
||||
//! in-memory workspace and asserts the whole text of each file afterwards,
|
||||
//! or the refusal's sentence.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{rename, RefactorEdit};
|
||||
|
||||
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
|
||||
}
|
||||
|
||||
fn path(name: &str) -> PathBuf {
|
||||
PathBuf::from("/rtl").join(name)
|
||||
}
|
||||
|
||||
/// The offset of the first whole-word `name` at or after `prefix`.
|
||||
fn at(text: &str, prefix: &str, name: &str) -> u32 {
|
||||
let from =
|
||||
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text")) + prefix.len();
|
||||
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
|
||||
let bytes = text.as_bytes();
|
||||
let mut search = from;
|
||||
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
|
||||
let start = search + hit;
|
||||
let end = start + name.len();
|
||||
if !is_word(start.checked_sub(1).and_then(|i| bytes.get(i))) && !is_word(bytes.get(end)) {
|
||||
return start as u32;
|
||||
}
|
||||
search = start + 1;
|
||||
}
|
||||
panic!("`{name}` does not occur after `{prefix}`");
|
||||
}
|
||||
|
||||
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0usize;
|
||||
for e in edit.edits_for(file) {
|
||||
out.push_str(&text[cursor..e.range.start as usize]);
|
||||
out.push_str(&e.new_text);
|
||||
cursor = e.range.end as usize;
|
||||
}
|
||||
out.push_str(&text[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Rename the `name` after `prefix` in `file`; every file's text afterwards,
|
||||
/// and the warnings.
|
||||
fn renamed(
|
||||
files: &[(&str, &str)],
|
||||
file: &str,
|
||||
prefix: &str,
|
||||
name: &str,
|
||||
new_name: &str,
|
||||
) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
let sources = workspace(files);
|
||||
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
|
||||
let edit = rename(&sources, &path(file), at(text, prefix, name), new_name)?;
|
||||
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
|
||||
Ok((texts, edit.warnings))
|
||||
}
|
||||
|
||||
const LEAF: &str = "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n";
|
||||
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
const TOP2: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
|
||||
|
||||
fn qa() -> Vec<(&'static str, &'static str)> {
|
||||
vec![("leaf.sv", LEAF), ("top.sv", TOP), ("top2.sv", TOP2)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_port_writes_out_the_shorthand_and_the_wildcard() {
|
||||
let (texts, warnings) = renamed(&qa(), "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert!(texts[0].contains("input logic [7:0] din") && texts[0].contains("q <= din;"));
|
||||
assert_eq!(texts[1], TOP.replace("(.*)", "(.*, .din(d))"));
|
||||
assert_eq!(texts[2], TOP2.replace(".d,", ".din(d),"));
|
||||
assert!(
|
||||
warnings
|
||||
.contains(&"`u_leaf` at top.sv:2 bound `d` through `.*`; added `.din(d)`.".to_string()),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(
|
||||
warnings
|
||||
.iter()
|
||||
.any(|w| w.starts_with("`u_leaf` at top2.sv:2 connected `d` by the shorthand `.d`")),
|
||||
"{warnings:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shorthand_rewrite_is_one_edit() {
|
||||
let sources = workspace(&qa());
|
||||
let edit = rename(&sources, &path("leaf.sv"), at(LEAF, "[7:0] ", "d"), "din").expect("renames");
|
||||
let top2 = edit.edits_for(&path("top2.sv"));
|
||||
assert_eq!(top2.len(), 1, "{top2:?}");
|
||||
assert_eq!(top2[0].new_text, "din(d)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_the_net_a_wildcard_binds_adds_the_connection() {
|
||||
let (texts, warnings) = renamed(&qa(), "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(texts[1], TOP.replace("[7:0] d", "[7:0] x").replace("(.*)", "(.*, .d(x))"));
|
||||
assert_eq!((texts[0].as_str(), texts[2].as_str()), (LEAF, TOP2));
|
||||
assert_eq!(
|
||||
warnings,
|
||||
vec!["`u_leaf` at top.sv:2 bound `d` through `.*`; added `.d(x)`.".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_the_net_a_shorthand_binds_writes_it_out() {
|
||||
let (texts, _) = renamed(&qa(), "top2.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(texts[2], TOP2.replace("[7:0] d", "[7:0] x").replace(".d,", ".d(x),"));
|
||||
assert_eq!((texts[0].as_str(), texts[1].as_str()), (LEAF, TOP));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_beside_an_explicit_connection_of_the_same_port_is_not_added_to() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*, .d(8'h0));\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, warnings) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], top.replace(".d(8'h0)", ".din(8'h0)"));
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let (texts, warnings) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("[7:0] d", "[7:0] x"));
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_of_a_middle_module_is_rewritten_on_both_sides() {
|
||||
let mid = "module mid (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n mid u_mid (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("mid.sv", mid), ("top.sv", top)];
|
||||
let (texts, warnings) = renamed(&files, "mid.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[0], LEAF);
|
||||
assert_eq!(texts[1], mid.replace("[7:0] d", "[7:0] din").replace("(.*)", "(.*, .d(din))"));
|
||||
assert_eq!(texts[2], top.replace("(.*)", "(.*, .din(d))"));
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shorthand_whose_port_differs_from_a_net_only_by_case_is_left_alone() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n logic [7:0] D;\n assign D = d;\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, warnings) = renamed(&files, "top.sv", "logic [7:0] ", "D", "e").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("[7:0] D", "[7:0] e").replace("assign D", "assign e"));
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert!(
|
||||
texts[1].contains(".din(d), .q);") && texts[1].contains("assign D = d;"),
|
||||
"{}",
|
||||
texts[1]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_into_the_declaring_module_is_rewritten() {
|
||||
let bind = "module binds;\n bind top leaf u_b (.*);\n bind top leaf u_c (.clk, .d, .q);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", TOP), ("binds.sv", bind)];
|
||||
let (texts, warnings) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(
|
||||
texts[2],
|
||||
bind.replace("u_b (.*)", "u_b (.*, .d(x))").replace(".clk, .d,", ".clk, .d(x),")
|
||||
);
|
||||
assert_eq!(warnings.len(), 3, "{warnings:?}");
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(
|
||||
texts[2],
|
||||
bind.replace("u_b (.*)", "u_b (.*, .din(d))").replace(".clk, .d,", ".clk, .din(d),")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_bind_is_refused_not_guessed() {
|
||||
let bind = "module binds;\n bind top.u_x leaf u_b (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", TOP), ("binds.sv", bind)];
|
||||
let refusal = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect_err("refused");
|
||||
assert!(
|
||||
refusal.contains("`u_b` at binds.sv:2 is bound into a hierarchical `bind` target"),
|
||||
"{refusal}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_into_a_module_declared_twice_is_refused() {
|
||||
let files = [("leaf.sv", LEAF), ("leaf_copy.sv", LEAF), ("top.sv", TOP)];
|
||||
let refusal = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect_err("refused");
|
||||
assert!(refusal.contains("`u_leaf` at top.sv:2 connects with `.*` to `leaf`, which is declared in more than one indexed file"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_into_a_module_lucisv_cannot_read_is_refused() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d);\n ghost u_g (.*);\nendmodule\n";
|
||||
let refusal = renamed(&[("top.sv", top)], "top.sv", "[7:0] ", "d", "x").expect_err("refused");
|
||||
assert_eq!(
|
||||
refusal,
|
||||
"`u_g` at top.sv:2 connects with `.*` to `ghost`, which lucisv cannot read, so it cannot tell whether `d` is bound implicitly; the rename was abandoned."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_inside_a_generate_for_are_rewritten() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n for (genvar i = 0; i < 2; i++) begin : g\n leaf u_leaf (.*);\n end\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("[7:0] d", "[7:0] x").replace("(.*)", "(.*, .d(x))"));
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("(.*)", "(.*, .din(d))"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_list_one_per_line_keeps_its_layout_and_comment() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\r\n leaf u_leaf (\r\n .clk(clk),\r\n .* // the rest\r\n );\r\nendmodule\r\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(
|
||||
texts[1],
|
||||
top.replace(" .* // the rest\r\n", " .*, // the rest\r\n .din(d)\r\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_list_split_by_directives_is_refused() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (\n`ifdef A\n .clk(1'b0),\n`endif\n .*\n );\nendmodule\n";
|
||||
let refusal = renamed(&[("leaf.sv", LEAF), ("top.sv", top)], "top.sv", "[7:0] ", "d", "x")
|
||||
.expect_err("refused");
|
||||
assert!(refusal.contains("split by compiler directives"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_that_would_start_binding_the_new_name_is_refused() {
|
||||
let child = "module child (input logic a, input logic b);\nendmodule\n";
|
||||
let top = "module top (input logic a);\n child u_c (.*);\nendmodule\n";
|
||||
let refusal = renamed(&[("child.sv", child), ("top.sv", top)], "top.sv", "logic ", "a", "b")
|
||||
.expect_err("refused");
|
||||
assert!(refusal.contains("which would start binding `b`"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_port_no_wildcard_net_binds_adds_nothing() {
|
||||
let top = "module top (input logic clk);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, warnings) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], top, "nothing named `d` or `din` is visible, so `.*` binds neither");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_whose_new_name_a_wildcard_parent_already_has_is_written_out() {
|
||||
let top = "module top (input logic clk, input logic [7:0] d, input logic [7:0] din, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
|
||||
assert_eq!(texts[1], top.replace("(.*)", "(.*, .din(d))"), "explicit beats the wildcard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_port_is_terminated_where_it_is_written_out() {
|
||||
let leaf = "module leaf (input logic clk, input logic \\d-x );\nendmodule\n";
|
||||
let top = "module top (input logic clk, input logic \\d-x );\n leaf u_leaf (.clk, .\\d-x );\nendmodule\n";
|
||||
let files = [("leaf.sv", leaf), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "leaf.sv", "logic ", "\\d-x", "din").expect("renames");
|
||||
// The escaped name keeps the blank that ends it, inside the parens and
|
||||
// (as the source wrote it) before the list's own `)`.
|
||||
assert_eq!(texts[1], top.replace(".\\d-x )", ".din(\\d-x ) )"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_instance_a_wildcard_binds_is_written_out() {
|
||||
let bus = "interface bus_if;\n logic v;\nendinterface\n";
|
||||
let sub = "module sub (bus_if bus, input logic clk);\nendmodule\n";
|
||||
let top = "module top (input logic clk);\n bus_if bus ();\n sub u_sub (.*);\nendmodule\n";
|
||||
let files = [("bus_if.sv", bus), ("sub.sv", sub), ("top.sv", top)];
|
||||
let (texts, _) = renamed(&files, "top.sv", "bus_if ", "bus", "the_bus").expect("renames");
|
||||
assert_eq!(
|
||||
texts[2],
|
||||
top.replace("bus_if bus ()", "bus_if the_bus ()").replace("(.*)", "(.*, .bus(the_bus))")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_variable_a_wildcard_might_import_is_refused() {
|
||||
let pkg = "package p;\n logic [7:0] d;\nendpackage\n";
|
||||
let top = "module top (input logic clk);\n import p::*;\n leaf u_leaf (.*);\nendmodule\n";
|
||||
let files = [("p.sv", pkg), ("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let refusal = renamed(&files, "p.sv", "[7:0] ", "d", "x").expect_err("refused");
|
||||
assert!(
|
||||
refusal.contains("`u_leaf` at top.sv:3 may bind `d` implicitly through `.*`"),
|
||||
"{refusal}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_no_implicit_connection_can_bind_ignores_the_wildcards() {
|
||||
// A module, a parameter and a type are never bound by `.*`, so an
|
||||
// unreadable `.*` beside them refuses nothing.
|
||||
let top = "module top #(parameter int W = 8) (input logic clk);\n typedef logic [W-1:0] word_t;\n ghost u_g (.*);\nendmodule\n";
|
||||
for (prefix, name, new) in
|
||||
[("module ", "top", "top_r"), ("int ", "W", "WIDTH"), ("] ", "word_t", "w_t")]
|
||||
{
|
||||
let outcome = renamed(&[("top.sv", top)], "top.sv", prefix, name, new);
|
||||
assert!(outcome.is_ok(), "{name} -> {new}: {outcome:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_list_holding_unparsed_text_is_refused() {
|
||||
// `+.d` is an error element spelling the name; the second instance's `.*`
|
||||
// is what makes the file one an implicit connection could live in.
|
||||
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, +.d, .q);\n leaf u_two (.*);\nendmodule\n";
|
||||
let files = [("leaf.sv", LEAF), ("top.sv", top)];
|
||||
let refusal = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect_err("refused");
|
||||
assert!(refusal.contains("holds text lucisv could not parse"), "{refusal}");
|
||||
}
|
||||
|
||||
/// A `bind` into a bare **instance** name (IEEE 1800 §23.11) is tied to the
|
||||
/// modules the index says own an instance of that name. Here `i_x` names an
|
||||
/// instance of `fifo` in one bench and of `cnt` in another: the bind might
|
||||
/// reach `cnt`'s scope, so renaming `cnt`'s `err_o` is refused — whereas with
|
||||
/// `fifo`'s instance alone it is skipped (QA finding 2's own test).
|
||||
#[test]
|
||||
fn a_bind_into_an_instance_name_one_of_whose_instances_is_ours_is_refused() {
|
||||
let cnt =
|
||||
"module cnt (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
|
||||
let fifo =
|
||||
"module fifo (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
|
||||
let check = "module fifo_assert (input logic clk_i, input logic err_o);\nendmodule\n";
|
||||
let tb = "module tb;\n logic clk_i, err_o;\n fifo i_x (.clk_i, .err_o);\nendmodule\n";
|
||||
let tb2 = "module tb2;\n logic clk_i, err_o;\n cnt i_x (.clk_i, .err_o);\nendmodule\n";
|
||||
let bind = "module tb_bind;\n bind i_x fifo_assert u_a (.clk_i, .err_o);\nendmodule\n";
|
||||
let files = [
|
||||
("cnt.sv", cnt),
|
||||
("fifo.sv", fifo),
|
||||
("check.sv", check),
|
||||
("tb.sv", tb),
|
||||
("tb2.sv", tb2),
|
||||
("bind.sv", bind),
|
||||
];
|
||||
let refusal =
|
||||
renamed(&files, "cnt.sv", "output logic ", "err_o", "error_o").expect_err("refused");
|
||||
assert!(refusal.contains("`u_a` at bind.sv:2 may bind `err_o` implicitly"), "{refusal}");
|
||||
let without: Vec<_> = files.iter().filter(|(n, _)| *n != "tb2.sv").copied().collect();
|
||||
let (texts, _) =
|
||||
renamed(&without, "cnt.sv", "output logic ", "err_o", "error_o").expect("skipped");
|
||||
assert_eq!(texts[4], bind);
|
||||
}
|
||||
|
||||
/// A bare instance name resolves upward from the `bind`'s own scope first
|
||||
/// (IEEE 1800 §23.11): `bind dut … (.*)` written in a bench that declares its
|
||||
/// own `dut` means that `dut`, whatever other benches call theirs — the
|
||||
/// opentitan shape of `sram_ctrl`'s and `entropy_src`'s `tb.sv`.
|
||||
#[test]
|
||||
fn a_bind_into_the_enclosing_modules_own_instance_is_that_instance() {
|
||||
let cnt =
|
||||
"module cnt (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
|
||||
let fifo =
|
||||
"module fifo (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
|
||||
let check = "module fifo_assert (input logic clk_i, input logic err_o);\nendmodule\n";
|
||||
let tb = "module tb;\n logic clk_i, err_o;\n fifo dut (.clk_i, .err_o);\n bind dut fifo_assert u_a (.*);\nendmodule\n";
|
||||
let tb2 = "module tb2;\n logic clk_i, err_o;\n cnt dut (.clk_i, .err_o);\nendmodule\n";
|
||||
let files =
|
||||
[("cnt.sv", cnt), ("fifo.sv", fifo), ("check.sv", check), ("tb.sv", tb), ("tb2.sv", tb2)];
|
||||
let (texts, _) = renamed(&files, "cnt.sv", "output logic ", "err_o", "error_o")
|
||||
.expect("tb's own `dut` is a `fifo`");
|
||||
assert_eq!(texts[3], tb);
|
||||
assert_eq!(texts[4], tb2.replace(".err_o)", ".error_o(err_o))"));
|
||||
// And renaming `fifo`'s port is refused: that bind may bind it.
|
||||
let refusal =
|
||||
renamed(&files, "fifo.sv", "output logic ", "err_o", "error_o").expect_err("refused");
|
||||
assert!(refusal.contains("`u_a` at tb.sv:4"), "{refusal}");
|
||||
}
|
||||
@@ -58,7 +58,7 @@ VS Code setting that restarts the server.
|
||||
| `textDocument/foldingRange` | `pairs::analyze` + comment trivia | One `Region` per matched scope pair, folded through the line *before* the closer so `end`/`endmodule` stays visible, plus one `Comment` per multi-line block comment. An unmatched opener folds nothing. Same feature README |
|
||||
| `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical |
|
||||
| `textDocument/prepareRename` | `vlog_refactor::prepare_rename` | Declines with the engine's own sentence (`RequestFailed`), so the box never opens on a rename that would fail |
|
||||
| `textDocument/rename` | `vlog_refactor::rename` | Cross-file `WorkspaceEdit` (`changes`); warnings go out on `window/logMessage`; refusals are `RequestFailed`. See `docs/features/refactor-rename/README.md` |
|
||||
| `textDocument/rename` | `vlog_refactor::rename` | Cross-file `WorkspaceEdit` (`changes`); warnings go out on `window/logMessage`; refusals are `RequestFailed`. See `docs/features/refactor-rename/README.md`. Since 2026-09-23 the fan-out also hands over, one hop down, every module a handed-over file instantiates (`module_select::instantiated_by`), so a `.*` into a module declaring neither name is read rather than refused |
|
||||
| `textDocument/completion` | `vlog_refactor::instantiation_plan` | Module hinting: one item per indexed module, inserting the whole instantiation skeleton as a snippet (plain text for a client that did not advertise `snippetSupport`). Capped at 64 items, `isIncomplete` when truncated; declines every position that is not module-item. See `docs/features/refactor-instantiate/README.md` |
|
||||
| `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README |
|
||||
| `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` |
|
||||
|
||||
@@ -0,0 +1,703 @@
|
||||
# mcp-edit-tools
|
||||
|
||||
Lane **M3** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §4.3).
|
||||
|
||||
## Goal
|
||||
|
||||
Give an agent lucisv's verified edits as single MCP calls: `format`,
|
||||
`fix_lint`, `rename`, the six cursor refactorings (`expand_wildcard`,
|
||||
`convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`,
|
||||
`remove_port`), `add_port`, `extract_module`, and the text-only
|
||||
`instantiate`. An agent that renames a port across a design today reads and
|
||||
edits every file that mentions it; here it makes one call, sees the diff
|
||||
first if it wants (`dry_run`), and gets either the whole verified edit on
|
||||
disk or a sentence saying why nothing was written. Every tool is a wrapper
|
||||
over an engine that already verifies its own output (`vlog_refactor`,
|
||||
`vlog_formatter`, `vlog_linter`); the one new piece is the write path,
|
||||
`src/apply.rs`, which every tool shares.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **All-or-nothing, as far as a filesystem allows.** An engine's
|
||||
`RefactorEdit` is all-or-nothing by construction; `apply.rs` keeps it so
|
||||
on disk: every file's new text is computed (edits applied last-first,
|
||||
refusing on overlap, a range past the end, or a split UTF-8 character)
|
||||
before anything is written; every target is checked to lie inside a root
|
||||
(an existing file by its canonical path; a created file by its parent's
|
||||
canonical path, and nothing — not even a dangling symlink — at its own
|
||||
path); then the write-freshness check (next point); then `write_atomic`
|
||||
per file in path order. A write that fails after others landed is an
|
||||
`isError` result: "written N of M: a.sv, b.sv; failed on `c.sv`: <error>"
|
||||
— the CLI's posture: said, never hidden, never rolled back.
|
||||
- **The write-freshness rule** (the lead's ruling for QA's first attack):
|
||||
immediately before the first write, every file the edit rewrites is
|
||||
re-read and compared **byte for byte** with the text the plan was
|
||||
computed against (the ruling says "content hash"; comparing the bytes
|
||||
themselves costs the same read and cannot collide); a created file must
|
||||
still not exist; a read-only file is refused here, where `write_atomic`
|
||||
would only refuse it later, after other files landed. One mismatch
|
||||
refuses the whole edit: "`f` changed on disk since it was read; nothing
|
||||
written." **The window** that remains is between that check and each
|
||||
file's `rename(2)`: the time to write the files already checked, a few
|
||||
milliseconds for a rename across three files. A writer that lands inside
|
||||
it is overwritten, which is the same exposure `lucisv format` has between
|
||||
its read and its write. There is no lock, for the reason
|
||||
`lucisv_core::atomic` gives: a lock would buy nothing between processes
|
||||
that do not take it.
|
||||
- **Where the texts come from.** A refactoring is handed the whole indexed
|
||||
set plus the selected file, read from disk at call time
|
||||
(`tools/source.rs::WholeSet::read`, the one whole-set read `references`
|
||||
shares) — M2's ruling for `references`, for the same
|
||||
reason: a use can resolve through a file that never spells its name, so no
|
||||
narrowing by name is sound, and a narrowed set turns an unresolvable use
|
||||
into a false refusal. Those same texts are what the freshness rule
|
||||
compares against, so the index is never trusted for bytes. **Cost**: one
|
||||
read and one parse of every indexed file per call — see the timings in the
|
||||
work log (a copy of opentitan's `hw/ip/aes`: 124 files) and, for all of
|
||||
opentitan, M2's `references` numbers (1.6–2.6 s release, 3 944 files).
|
||||
M6 measures `rename` on the whole checkout; Handshake MCP-7's
|
||||
`KnownFacts` variant is the way down, as it is for `references`.
|
||||
- **Files the index skipped are never edited around** (QA finding 2, lead's
|
||||
ruling). The index leaves out files over 1 MiB and files that are not
|
||||
UTF-8 (M1's rules); `project/files.rs` now keeps the large ones' paths
|
||||
(`FileSet::skipped`) and `Project::skipped()` returns both kinds with the
|
||||
reason. `WholeSet::read` carries that list beside the texts, plus any
|
||||
indexed file that no longer reads. Before an engine runs, each edit tool
|
||||
names what it changes — `rename`: the old name; `remove_port`: the port
|
||||
and its module; `propagate_ports`, `expand_wildcard`, `inline_module`:
|
||||
the instantiated module; `convert_ports`, `extract_module`, `add_port` by
|
||||
position: the enclosing module; `add_port` by `module`: that name;
|
||||
`organize_imports`: nothing (it edits only its own file's `import`s) —
|
||||
and when a skipped file's bytes spell one of those names as a **whole
|
||||
word** the edit is refused: "`rtl/big.sv` (skipped: over 1 MiB) may
|
||||
reference `d`; lucisv-mcp will not edit around a file it cannot index;
|
||||
nothing written." Whole-word rather than any substring (a refinement of
|
||||
the ruling's "bytes contain"): an identifier, escaped or not, is always
|
||||
written with a non-identifier byte on each side, so no reference is
|
||||
missed, while a one-letter port such as `d` would otherwise refuse every
|
||||
edit on any tree holding one skipped file. Otherwise the skipped files are
|
||||
named once under `warnings:` ("not indexed, so not searched or edited: …",
|
||||
ten at most, then "and N more"); `references` ends its answer with the
|
||||
same line as `warning:` (and `structuredContent.warning`), since its
|
||||
census is then partial. The search is conservative: a skipped file that
|
||||
spells the name only in a comment still refuses.
|
||||
- **Known limits.** `vlog_refactor::rename` does not rewrite a `.*` or
|
||||
`.name` shorthand connection bound to the renamed name (QA finding 1: the
|
||||
design is silently rewired; the LSP's rename has the same limit). It is
|
||||
the engine's, fixed in lane M3.5; until then the `rename` description
|
||||
says so and tells the agent to check `dry_run` on designs using them.
|
||||
`extract_module` into a CRLF file writes its instantiation with LF
|
||||
(Handshake MCP-10).
|
||||
- **`dry_run: null` means absent** (lead's ruling on QA finding 4): JSON
|
||||
null is "not given" for every argument of every tool (M1's validation),
|
||||
so a null `dry_run` is the default, `false`, and the edit is written;
|
||||
`"true"` and `1` are refused as non-booleans.
|
||||
- **What `dry_run` returns**: the summary with `(dry run: nothing written)`,
|
||||
the warnings, then `lucisv_core::diff::unified` per file, headed by the
|
||||
root-relative path (a created file diffs from empty). `structuredContent`
|
||||
carries each file's `diff` too. Nothing is written and nothing is
|
||||
re-read for freshness. A real run answers the summary only:
|
||||
`files: N changed, M created`, one `path +added -removed` line per file
|
||||
(counted from the diff, whose resync is deliberately coarse — a count can
|
||||
include an unchanged line the resync re-emitted), `unchanged:` for files
|
||||
looked at and left alone (`format`), the tool's note (`fix_lint`), and
|
||||
`warnings:`. Nothing to write answers `unchanged`.
|
||||
- **Idempotency.** `idempotentHint: true` on `format`, `fix_lint`,
|
||||
`expand_wildcard`, `convert_ports`, `organize_imports` (the lead's list).
|
||||
A second identical call writes nothing: `format`, `fix_lint` and `rename`
|
||||
answer `unchanged` (for `rename`, when the name at the position already
|
||||
is `new_name` — checked with `vlog_refactor::rename_name_at` before the
|
||||
engine runs); `expand_wildcard`, `convert_ports` and `organize_imports`
|
||||
answer the engine's own "nothing to do" sentence (`writes no .* to
|
||||
expand`, `already declares its ports ANSI-style`, `already sorted, and
|
||||
every one of them is used`) as a tool error. Turning those sentences into
|
||||
`unchanged` would mean matching engine wording, which drifts; a refusal
|
||||
that writes nothing is idempotent in effect, which is what the hint
|
||||
promises. The wire test asserts "`unchanged` or a refusal, and not one
|
||||
byte moved".
|
||||
- **The fence rule** (`fix_lint`): a fix is applied only when none of its
|
||||
edits touches a region `vlog_formatter::fence::protected_regions` reports
|
||||
(`// lucisv: off` / `// verilog_format: off`) — the CLI's
|
||||
`fixable_outside_fences`, restated in `tools/format.rs::outside_fences`
|
||||
over the same library answer (the CLI's copy is in a binary crate and
|
||||
cannot be called). Only `Applicability::Safe` fixes (`apply_fixes(…,
|
||||
false)`); up to the CLI's 10 fix-then-relint rounds; the run is
|
||||
`diagnostics`'s (`Runs`, the per-file `lucisv.toml`, `[lint]
|
||||
select/ignore`, options, external waivers, the index-backed oracle). The
|
||||
result is refused when its tolerant parse has more errors than the
|
||||
input's (the CLI does not check this; the brief asked for it). The note
|
||||
says `fixed: rule ×n, …; N findings left`, counted as findings that
|
||||
disappeared per rule.
|
||||
- **`format`** takes `file` or comma-separated `files` (no `Ty::List`:
|
||||
a comma string, as the brief allowed) and `lines` with one file only
|
||||
(`LineRanges::parse`, then `format_range`). The config is the CLI's
|
||||
`Options::config_with` with no flags: `line-length`, `indent`,
|
||||
`[format] uvm-utils-indent` from `Discovery::for_file`. One file the
|
||||
formatter refuses refuses the whole call ("`f` was not formatted: <the
|
||||
safety net's reason>; nothing written."); a formatter panic is caught and
|
||||
refused the same way. A CRLF file comes back LF-normalised — the
|
||||
formatter's own behaviour (`docs/features/alignment`), so `format` and
|
||||
`lucisv format` write the same bytes (asserted by the CRLF wire test).
|
||||
- **Selectors.** `rename` takes `definition`'s selector (`tools/select.rs`)
|
||||
and, for a bare `name` (+`unit`), `nav::declaration_position` — the one
|
||||
declaration `references` would pick. The six cursor tools take `file` +
|
||||
`line` with `col` or `name` through the same selector; `file` + `line`
|
||||
alone means the line's first non-blank byte (`organize_imports` wants a
|
||||
scope, not a token). `add_port` takes `module` (`ModuleRef::Name`) or
|
||||
`file` + `line` (`ModuleRef::At` at the line's start), not both.
|
||||
`extract_module`'s selection is `start_line`'s first byte to `end_line`'s
|
||||
last (line ending excluded); `home` is `new_file` (default, the file is
|
||||
`new_name.sv` beside the source, as the engine names it) or `same_file`.
|
||||
- **`instantiate`** is `instantiation_plan` + `render_with` over the file
|
||||
`vlog_refactor::module_definition` names (one walk on a miss; `file`
|
||||
picks among several declarations), with no site — so no auto-connect:
|
||||
every port is connected to a same-named placeholder. `with_params: false`
|
||||
drops the `#(…)`; `instance` replaces the instance hole and must be one
|
||||
identifier — `[A-Za-z_][A-Za-z0-9_$]*` and not a keyword, or an escaped
|
||||
identifier `\name ` ending in its one space — else the call is refused
|
||||
naming the rule (QA finding 5); `wildcard`
|
||||
renders with no ports and writes `(.*)`. The indentation step is the
|
||||
first root's `indent`. Read-only annotations.
|
||||
- **Engine refusals are passed through as written.** They are sentences
|
||||
for a user already (`vlog_refactor`'s convention), and several speak of
|
||||
the refactoring by name, which is right here (unlike `references`, which
|
||||
borrows rename's resolution).
|
||||
|
||||
## Handshakes
|
||||
|
||||
Consumed (public APIs only; no library crate's behaviour was changed):
|
||||
|
||||
| crate | items |
|
||||
|---|---|
|
||||
| `vlog_refactor` | `RefactorEdit`, `TextEdit`, `rename`, `rename_name_at`, `expand_wildcard`, `convert_to_ansi`, `organize_imports`, `inline_module`, `propagate_ports`, `remove_port`, `add_port`, `ModuleRef`, `extract_module`, `Home`, `instantiation_plan`, `InstantiationPlan::{render_with, instance_name}`, `Layout`, `module_definition` |
|
||||
| `vlog_formatter` | `format_source`, `format_range`, `LineRanges::parse`, `Config`, `fence::{protected_regions, is_protected, Region}` |
|
||||
| `vlog_linter` | `apply_fixes`, `Fix`, `Violation` (plus everything `diagnostics` already consumed) |
|
||||
| `lucisv_core` | `atomic::write_atomic`, `diff::unified` (new, below), `config::{Discovery::for_file, FileConfig}` |
|
||||
|
||||
**Handshake MCP-1 — delivered as a pure move (lead's ruling).**
|
||||
`crates/lucisv/src/diff.rs` (the CLI's `--diff` printer, 127 production
|
||||
lines and its six tests) moved unchanged to `crates/lucisv_core/src/diff.rs`,
|
||||
exposed as `lucisv_core::diff::unified` (`pub mod diff;` in
|
||||
`lucisv_core/src/lib.rs`, the crate doc updated). The only edit to the moved
|
||||
text is its module doc comment. `crates/lucisv/src/diff.rs` is now one line,
|
||||
`pub use lucisv_core::diff::unified;`, so `main.rs`'s two `diff::unified`
|
||||
calls are untouched and `--diff` output is byte-identical (same function).
|
||||
The six tests run in `lucisv_core` now; `lucisv_core` is still
|
||||
dependency-free. `docs/topo.md` is the lead's to update (M6).
|
||||
|
||||
Edits outside this lane's files, each a one-liner forced by the lane:
|
||||
|
||||
- `crates/lucisv_mcp/src/tools/nav.rs`: `declaration_position` is
|
||||
`pub(super)` (was private) so `rename` picks the same declaration for a
|
||||
bare `name` that `references` does — a copy would drift.
|
||||
- `crates/lucisv_mcp/src/tools/diagnostics.rs` (allowed by the brief):
|
||||
`Runs`, `Runs::new`, `Runs::for_file`, `Run`, `Mentions`,
|
||||
`Mentions::of_file` are `pub(super)`; the lint call inside
|
||||
`file_findings` became `pub(super) fn violations` so `fix_lint` lints
|
||||
exactly as `diagnostics` does. `diagnostics`' answers are unchanged (its
|
||||
wire and QA tests are green, unedited).
|
||||
- `crates/lucisv_mcp/tests/qa_m1.rs`: the tool count in
|
||||
`qa_everything_but_initialize_and_ping_waits_for_the_handshake` goes from
|
||||
11 to 23 (M2 made the same one-line edit when it added five tools).
|
||||
- Rework (lead's rulings on QA findings 2 and 4): `project/files.rs`
|
||||
(`FileSet::skipped`), `project/mod.rs` (`unreadable` keeps paths;
|
||||
`Project::skipped()`; `unreadable()` returns the same strings as before),
|
||||
`tools/source.rs` (`WholeSet`), `tools/nav.rs` (`all_files` replaced by
|
||||
`WholeSet::read`; `references`' `warning:` line), `tests/qa_m3.rs`
|
||||
(findings 2 and 5 un-ignored, 1 and 3 re-reasoned, 4's test rewritten to
|
||||
the ruling).
|
||||
|
||||
Requests:
|
||||
|
||||
- **MCP-8 → `vlog_refactor` (a false refusal, not a corruption):**
|
||||
`remove_port` refuses a port whose only "use" is a named connection to it
|
||||
from an instantiation in **another module of the same file**:
|
||||
`spare` (with `input logic unused_i`) and `spare_user` (instantiating
|
||||
`spare u_s (.unused_i(1'b0), …)`) in one file → "`unused_i` is still used
|
||||
inside `spare` at s.sv:15; remove those uses first." — line 15 is
|
||||
`spare_user`'s connection. With the two modules in two files the removal
|
||||
succeeds and deletes the connection. `ports/remove.rs::body_uses_in`
|
||||
seems to count the file's connection text rather than `spare`'s body
|
||||
alone. The fixtures put `spare_user` in its own file.
|
||||
- **MCP-9 → `vlog_refactor` (candidate):** the engines' "nothing to do"
|
||||
refusals (`expand_wildcard` rule 5, `convert_to_ansi`'s "already
|
||||
ANSI-style", `organize_imports`' "already sorted") are indistinguishable
|
||||
from real refusals except by wording. A typed `Err` (or an
|
||||
`Ok(RefactorEdit::default())`) for "already done" would let every front
|
||||
end answer `unchanged` for an idempotent second call.
|
||||
- **To M6 (instructions):** `rpc.rs`'s `INSTRUCTIONS` (M1's file) names
|
||||
only the read tools. A sentence such as "edit tools (rename, format,
|
||||
fix_lint, the port refactorings) verify before writing and take `dry_run`
|
||||
to show the diff first" belongs there; M6 revises `instructions` from
|
||||
the census anyway.
|
||||
- **MCP-10 → `vlog_refactor` (non-blocking, QA finding 3):**
|
||||
`extract_module` into a CRLF file writes the instantiation it leaves in
|
||||
place with bare LF (`extract/render.rs` renders `\n` only), so the file
|
||||
ends up with mixed line endings; the created file is LF. Valid Verilog,
|
||||
nothing lost. The engine should render the source file's line ending.
|
||||
QA's `qa_extract_module_keeps_a_crlf_file_crlf` stays ignored for it.
|
||||
- **QA finding 1 → lane M3.5 (lead's ruling):** `rename` and `.*`/`.name`
|
||||
shorthand connections — see Known limits. QA's
|
||||
`qa_rename_never_breaks_an_implicit_port_connection` stays ignored ("engine
|
||||
limit, fixed in M3.5").
|
||||
- Done in the rework: `nav.rs::all_files` and `edit.rs::sources` merged into
|
||||
`source::WholeSet::read` (one function; `nav.rs` calls it).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] MCP-1: `unified` moved to `lucisv_core::diff`, CLI re-exports it,
|
||||
tests moved, CLI `--diff` byte-identical
|
||||
- [x] `apply.rs`: plan from a `RefactorEdit` (reverse-order application,
|
||||
overlap/bounds/char-boundary refusals); containment (existing and
|
||||
created targets); the write-freshness check before the first write;
|
||||
`write_atomic` in path order; "written N of M" on a late failure;
|
||||
dry-run diffs; the summary text and JSON
|
||||
- [x] registry: `tools::Effect` (read / edit, idempotent) drives the
|
||||
annotations; twelve tools registered
|
||||
- [x] `format` (`file`/`files`, `lines`, config ladder, whole-call refusal,
|
||||
panic contained), `fix_lint` (safe, fenced, rounds, parse check,
|
||||
per-rule note)
|
||||
- [x] `rename` (definition's selector, whole set, `unchanged` repeat)
|
||||
- [x] `expand_wildcard`, `convert_ports`, `organize_imports`,
|
||||
`inline_module`, `propagate_ports`, `remove_port`
|
||||
- [x] `add_port` (`module` or `file`+`line`), `extract_module` (new file /
|
||||
same file), `instantiate` (named/wildcard, params, instance)
|
||||
- [x] tests: every tool dry-run / real / repeat; three-file rename; refusals
|
||||
leave the tree byte-identical; extract into a new file and over an
|
||||
existing one; `fix_lint` beside a fence; CRLF `format`; stale-file,
|
||||
created-file-appeared, read-only, late-failure and outside-root unit
|
||||
tests on `apply`
|
||||
- [x] timings on a copy of `hw/ip/aes`
|
||||
- [x] gates through `tools/guard.sh`; sizes
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-23 (dev, M3).**
|
||||
|
||||
Built: `src/apply.rs` (the write path), `src/tools/edit.rs` (`dry_run`, the
|
||||
whole-set read, `rename` and the six cursor refactorings),
|
||||
`src/tools/format.rs` (`format`, `fix_lint`), `src/tools/refactor.rs`
|
||||
(`add_port`, `extract_module`, `instantiate`); `tools/mod.rs` gains
|
||||
`Effect` and the twelve entries; `main.rs` gains `mod apply;`. Fixtures: a
|
||||
new tree `tests/fixtures/edit` (14 files: a package, `leaf` instantiated
|
||||
from `mid.sv` and `top.sv` for the three-file rename, a `.*` instance, a
|
||||
partial instance, a non-ANSI module, a module in its own file to inline, a
|
||||
port only another file connects, an extract target, a badly formatted
|
||||
file); M1's `design` and M2's `nav` trees are untouched.
|
||||
|
||||
Decisions and deviations:
|
||||
|
||||
1. **Byte comparison instead of a content hash** for the freshness rule —
|
||||
same read, no collision (Assumptions).
|
||||
2. **A read-only target is refused in the pre-write pass**, before any
|
||||
file is written; `write_atomic` would refuse it too, but only after the
|
||||
files before it in path order had landed.
|
||||
3. **The "nothing to do" repeat of three engines is a refusal, not
|
||||
`unchanged`** (Assumptions, MCP-9).
|
||||
4. **`fix_lint` takes `rules`** (like `diagnostics`), so an agent can fix
|
||||
one rule's findings; not in the brief, one parameter on the same
|
||||
`Runs`.
|
||||
5. **`instantiate` takes `file`** to pick among several declarations, the
|
||||
way `unit_interface` does.
|
||||
6. **CRLF**: `format` normalises to LF because the formatter does; the
|
||||
test pins "the same bytes as `format_source`", not "CRLF kept".
|
||||
7. **The one-line edits outside the lane** listed under Handshakes
|
||||
(`nav.rs` visibility, `qa_m1.rs` count).
|
||||
|
||||
Timings (release build, macOS arm64, a `cp -R` of opentitan `hw/ip/aes` —
|
||||
124 indexed files, 29 046 lines — into the session scratch directory; the
|
||||
checkout was only read, and its `git status` is the same before and after —
|
||||
three files modified before this lane started, none by it):
|
||||
|
||||
| call | wall (ms) |
|
||||
|---|---|
|
||||
| index build at the first call | 49–57 |
|
||||
| `rename` `op_i` → `cipher_op_i` at `rtl/aes_cipher_core.sv:123`, `dry_run` (3 files, 4 macro-argument warnings) | 136 first call, 76 warm |
|
||||
| the same `rename`, written | 75–79 |
|
||||
| the same position again (`cipher_op_i` → `cipher_op_i`) | 10 (`unchanged`, no engine run) |
|
||||
| `expand_wildcard` at `dv/err_injection_if/fi_core_wrapper.sv:21` (`fi_core_if fi_if (.*)`), `dry_run` | 54–59 |
|
||||
| the same, written | 54–67 |
|
||||
| the same again | 51 (the engine's "`fi_if` writes no `.*` to expand") |
|
||||
|
||||
Each call re-reads and re-parses the 124 files (the whole-set rule); on the
|
||||
whole opentitan checkout that is M2's 1.6–2.6 s per call, which M6 measures
|
||||
for `rename`.
|
||||
|
||||
Tests: `lucisv_mcp` 151 → 166 (+1 ignored, the opentitan census) — 5
|
||||
`apply` unit tests, 10 new wire tests, the `tools/list` wire test rewritten
|
||||
for the edit annotations; `lucisv_core` gains the six
|
||||
diff tests the CLI loses (count unchanged across the two crates).
|
||||
|
||||
Gates (each through `tools/guard.sh`, one cargo invocation at a time):
|
||||
`cargo fmt -p lucisv_mcp -p lucisv_core -p lucisv -- --check` clean;
|
||||
`cargo clippy -p lucisv_mcp -p lucisv_core -p lucisv --all-targets` clean;
|
||||
`cargo test -p lucisv_mcp` 43 + 51 + 43 + 29 passed, 1 ignored;
|
||||
`cargo test -p lucisv -p lucisv_core` 30 + 113 + 117 passed;
|
||||
`cargo test --workspace` 4 625 passed, 0 failed, 47 ignored (4 610 before).
|
||||
|
||||
Sizes (production lines: non-blank, non-comment, before `mod tests`):
|
||||
`apply.rs` 216, `tools/edit.rs` 194, `tools/format.rs` 220,
|
||||
`tools/refactor.rs` 241, `tools/mod.rs` 176, `tools/diagnostics.rs` 330,
|
||||
`lucisv_core/src/diff.rs` 127, `lucisv/src/diff.rs` 1. No function over 40
|
||||
lines.
|
||||
|
||||
**2026-09-23 (dev, M3 rework after QA's FAIL; lead's rulings).**
|
||||
|
||||
- Finding 1 (blocking, engine; ruled out of lane → M3.5): `vlog_refactor`
|
||||
untouched. The `rename` description (`tools/edit.rs:126`) gains "A `.*`
|
||||
or `.name` shorthand connection bound to the renamed name is not
|
||||
rewritten yet (known engine limit, M3.5); check `dry_run` on designs
|
||||
using them."; Assumptions gains *Known limits*. QA's test stays ignored,
|
||||
reason "QA finding 1: engine limit, fixed in M3.5".
|
||||
- Finding 2 (blocking, fixed): `project/files.rs:38` `FileSet::skipped`
|
||||
keeps the paths the size cap drops; `project/mod.rs:256`
|
||||
`Project::skipped()` returns them and the non-UTF-8 files with why
|
||||
(`unreadable` now keeps paths; `unreadable()` answers the same strings).
|
||||
`tools/source.rs:155` `WholeSet` is the one whole-set read (`read`,
|
||||
`mentioning`, `warning`, `word_in_bytes`), replacing both
|
||||
`edit.rs::sources` and `nav.rs::all_files`. `tools/edit.rs:241`
|
||||
`whole_set` refuses when a skipped file spells a name the edit changes,
|
||||
and `finish` (`edit.rs:258`) lists the skipped files under `warnings:`;
|
||||
every edit tool names its stake (`edit.rs:149–210`, `refactor.rs:134,
|
||||
142, 183`). `references` ends with the same line as `warning:`
|
||||
(`nav.rs:311`). Deviation: the byte search is whole-word (Assumptions).
|
||||
QA's test un-ignored; two new wire tests
|
||||
(`a_file_the_index_skipped_is_never_edited_around`: refusal wording,
|
||||
`add_port` by module, the warning line on a name no skipped file spells,
|
||||
`references`' warning) and one unit test (`word_in_bytes`).
|
||||
- Finding 3 (non-blocking, engine): Handshake MCP-10 filed; QA's test stays
|
||||
ignored with that reason.
|
||||
- Finding 4 (ruled no change): `dry_run: null` is absent — Assumptions says
|
||||
so; QA's test renamed `qa_a_null_dry_run_is_absent_and_a_non_boolean_is_refused`
|
||||
and asserts exactly that.
|
||||
- Finding 5 (fixed): `tools/refactor.rs:270` `identifier` — a simple
|
||||
identifier that is not a keyword (`vlog_parser::token::is_keyword`), or an
|
||||
escaped one ending in its space; anything else is refused naming the rule.
|
||||
QA's test un-ignored; a wire test adds `\u-x ` accepted and `1u`, `\u-x`
|
||||
(no space) refused.
|
||||
|
||||
Gates (through `tools/guard.sh`, one at a time): fmt `--check` rc 0;
|
||||
clippy over `lucisv_mcp`/`lucisv_core`/`lucisv` `--all-targets` clean;
|
||||
`cargo test -p lucisv_mcp` 44 + 0 (1 ignored) + 51 + 43 + 27 (2 ignored) +
|
||||
31 passed; `cargo test --workspace` **4 655 passed, 0 failed, 49 ignored**
|
||||
(QA's 4 649 + 3 un-ignored + 3 new; 52 − 3 ignored). Sizes (production
|
||||
lines): `apply.rs` 216 (unchanged — QA's `#[path]` include still builds),
|
||||
`tools/edit.rs` 222, `tools/format.rs` 220, `tools/refactor.rs` 261,
|
||||
`tools/mod.rs` 176, `tools/diagnostics.rs` 330, `tools/nav.rs` 340,
|
||||
`tools/source.rs` 185, `project/mod.rs` 242, `project/files.rs` 153.
|
||||
|
||||
**2026-09-23 (lead, after the QA re-check).** Two fixes applied by the lead
|
||||
rather than a third dev round, both a few lines: every whole-set tool (the
|
||||
nine edits over the indexed set and `references`) now walks the roots
|
||||
before it answers (`rewalk: true`), so a file written in the last 5 s is in
|
||||
the set — QA finding 6, its test un-ignored; and the size-cap branch of the
|
||||
walk makes the same root check the indexed branch makes, so a large file
|
||||
reached through a symlink out of the root is neither indexed nor recorded
|
||||
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`.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-23 (QA, M3). Verdict: FAIL — two blocking findings (1 in
|
||||
`vlog_refactor::rename`, inherited; 2 in this lane's whole-set read), three
|
||||
non-blocking.** Everything the lane itself promises about the write path
|
||||
held under attack: no refusal moved a byte, no write left a root, no file
|
||||
was ever torn, `format`/`fix_lint` are byte-identical to the CLI. The two
|
||||
blockers are wrong answers — a "verified" rename that reports success and
|
||||
leaves the design broken — which the brief ranks blocking wherever they come
|
||||
from.
|
||||
|
||||
Tests: `crates/lucisv_mcp/tests/qa_m3.rs` — 19 `qa_*` tests green + 5
|
||||
`#[ignore = "QA finding N"]` (each confirmed failing under `--ignored`). The
|
||||
file includes the production `src/apply.rs` verbatim through `#[path]` over
|
||||
two stand-ins (`project::Project` with `roots`/`relative`/`open`,
|
||||
`tools::Answer`), so `apply::commit` is attacked directly with stale texts —
|
||||
no black box can hook the gap between a tool's read and its write; the
|
||||
dev's five `apply` unit tests therefore also run a second time in that
|
||||
binary (counted in the 24 it reports).
|
||||
|
||||
What was attacked, and how (all green unless a finding says otherwise):
|
||||
|
||||
1. **Corruption hunt.** Every tool (14 real calls: rename by position and by
|
||||
`name`+`unit`, the six cursor tools, `add_port` both ways, extract new-file
|
||||
and same-file, `format`, `fix_lint`): the files that move are exactly the
|
||||
reported ones; each reported `+a -r` equals the signed lines of the
|
||||
dry-run diff; the dry-run diff equals `lucisv_core::diff::unified` of
|
||||
(before, what the real call wrote); the same call again answers
|
||||
`unchanged` or a refusal and moves nothing. 25 refusals across all twelve
|
||||
edit tools (engine, argument and path refusals) leave every byte **and
|
||||
mode bit** of the tree, and of an outside directory reachable by a
|
||||
symlink, identical. Comments beside every edited span survive (a port
|
||||
with a trailing comment renamed, a `.*` with leading/trailing/block
|
||||
comments expanded, a block with a leading comment and a trailing one
|
||||
extracted; each comment's count over the tree is unchanged). `format` of a
|
||||
file the safety net refuses leaves the tree identical; `fix_lint` leaves
|
||||
`// lucisv: off` and `// verilog_format: off` regions byte-identical and
|
||||
never applies `always-comb`'s unsafe fix, even with `rules:
|
||||
"always-comb"` (answers `unchanged`).
|
||||
2. **Write freshness.** Directly: a stale first, middle and last file (same
|
||||
length, one byte changed — no size or mtime shortcut could catch it), a
|
||||
file deleted, a file replaced by a directory, a created path taken by a
|
||||
dangling symlink or a directory, a read-only last file — each refused
|
||||
naming the file, nothing written; a file rewritten with the same bytes
|
||||
(new inode and mtime) is fresh by the byte rule and lands. Black box: a
|
||||
`rename` back and forth for 80 rounds while a thread rewrites `mid.sv`
|
||||
atomically every 50 ms (unrenamed/renamed text + a marker) — after every
|
||||
call each file is wholly one form or the other, every "changed on disk"
|
||||
refusal names `rtl/mid.sv`, and real writes happen (asserted). The same
|
||||
race on a `cp -R` of opentitan `hw/ip/aes` (`op_i` ↔ `cipher_op_i`,
|
||||
3 files, scratch script): writer at 50 ms — 300 calls, 178 freshness
|
||||
refusals naming `rtl/aes_core.sv`, 122 engine refusals (mixed tree), no
|
||||
torn file; writer at 400 ms — 200 calls, 77 written, 18 freshness
|
||||
refusals, no torn file.
|
||||
3. **Paths.** `extract_module` new names `../evil`, `/tmp/evil`,
|
||||
`\../../evil `, `a/b`, empty — refused by the engine's plain-identifier
|
||||
rule; a source reached through a symlinked directory inside the root, and
|
||||
an absolute path outside — "outside every root"; a dangling symlink (to
|
||||
outside) or a directory at the created path — "already exists"; a
|
||||
read-only `rtl/top.sv` (last of the rename's three) — "is read-only;
|
||||
nothing written." with `leaf.sv`/`mid.sv` untouched; the same for
|
||||
`format` and `fix_lint`. A symlinked file alias: `files: "alias.sv,
|
||||
real.sv"` is one file, the real file is written and the link kept.
|
||||
Symlinked files/dirs pointing outside are not indexed (M1's rule), so a
|
||||
rename never reaches them.
|
||||
4. **Concurrency.** `lucisv --check` in a loop over a 60-file tree while
|
||||
the server formats it five times (tree re-dirtied each round): every
|
||||
check exits 0/1, the final files equal the CLI's in-place output. On the
|
||||
aes copy (124 files, scratch script): 8 rounds of three `lucisv --check`
|
||||
runs plus, every other round, an in-place `lucisv` racing the server's
|
||||
124-file `format` — no crash, every round's final tree byte-identical to
|
||||
the CLI's output.
|
||||
5. **`format` = the CLI's bytes.** CRLF file (CRLF → LF, byte-identical to
|
||||
`lucisv` in place and `--stdout`); a nested `lucisv.toml` (`line-length =
|
||||
40`, `indent = 4`) — its config is used, as the CLI does; a fenced region;
|
||||
`lines` `2,1-2,99`, `4,2`, `4-4,2-2`, `50-60` (past EOF: `unchanged`),
|
||||
`1-999` — each equal to `lucisv --lines`; `3-1` refused; a duplicate in
|
||||
`files` (`w.sv, w.sv,./w.sv`) diffs once. On the aes copy: the server's
|
||||
`format` of all 124 files (242 ms release) is byte-identical to `lucisv`
|
||||
on every file.
|
||||
6. **`rename`.** The fixture rename equals `vlog_refactor::rename` over all
|
||||
files, file for file (in-test oracle); on aes the `op_i` rename equals a
|
||||
throwaway oracle binary (scratch crate) on all three files. A bare `name`
|
||||
picks the declaration `references` picks (same file set); an ambiguous
|
||||
`q` is refused listing `rtl/ext.sv:4` and `rtl/leaf.sv:4`; a keyword, a
|
||||
name already declared, an escaped name (`\a+b `, the engine refuses
|
||||
escaped new names by policy) and an empty name are refused; a hit inside a
|
||||
macro's arguments surfaces the engine's warning in `warnings:`. **See
|
||||
findings 1 and 2.**
|
||||
7. **Engine refusals are refusals.** Two or more per tool, tree unchanged:
|
||||
`expand_wildcard` (positional list; a `bind` instance), `convert_ports`
|
||||
(already ANSI ×2), `organize_imports` (a `` `define`` in scope; a line
|
||||
past the end), `inline_module` (positional; `.*`; no instance),
|
||||
`propagate_ports` (all connected; `.*`; positional), `remove_port` (port
|
||||
still used ×2), `add_port` (existing port; an ordered instantiation of
|
||||
the wrong length), `extract_module` (no item selected; a name already on
|
||||
disk). MCP-8 reproduced as filed (`s.sv:9` is `spare_user`'s connection).
|
||||
8. **`dry_run` diffs.** Dry-run diff = the diff of the real run (test 1).
|
||||
On aes, the three-file rename's dry-run diff applies with `patch -p0`
|
||||
onto a fresh copy and reproduces the real run byte for byte; it lists all
|
||||
three files. Its hunks are coarser than GNU `diff -u` (16 signed lines
|
||||
vs 12 for the same change; a two-line rename in `leaf.sv` reports `+4
|
||||
-4`) — the CLI's resync, documented in Assumptions; noted, not a finding.
|
||||
9. **MCP-1.** `git worktree` of 82bbba0 in the scratch dir (removed
|
||||
afterwards), its release `lucisv` built there: `--diff` over the whole aes
|
||||
copy (36 498 lines) and over `corpus/picorv32/picorv32.v` (6 226),
|
||||
`corpus/common_cells/src/fifo_v3.sv` (277), `.../addr_decode.sv` (96)
|
||||
is byte-identical old vs new, exit codes equal. The moved file differs
|
||||
from 82bbba0's `crates/lucisv/src/diff.rs` only in its module doc comment.
|
||||
10. **Sizes/style** (production lines = non-blank, non-`//` lines before
|
||||
`#[cfg(test)]`): `apply.rs` 216, `tools/edit.rs` 194, `tools/format.rs`
|
||||
220, `tools/refactor.rs` 241, `tools/mod.rs` 176, `tools/diagnostics.rs`
|
||||
330, `tools/nav.rs` 343, `lucisv_core/src/diff.rs` 127,
|
||||
`lucisv/src/diff.rs` 1 — the dev's numbers. No function over 50 lines.
|
||||
No `unwrap`/`expect`/`panic!`/`#[allow]`/`unsafe` in the lane's
|
||||
production code (`format.rs:66` is the word "unsafe" in a description).
|
||||
`cargo tree -p lucisv_core -e normal`: `lucisv_core` alone.
|
||||
11. **Gates** (each through `tools/guard.sh`, one cargo invocation at a
|
||||
time): `cargo fmt -p lucisv_mcp -p lucisv_core -p lucisv -- --check`
|
||||
rc 0; `cargo clippy -p lucisv_mcp -p lucisv_core -p lucisv --all-targets`
|
||||
clean, rc 0; `cargo test -p lucisv_mcp` 43 + 0 (1 ignored) + 51 + 43 +
|
||||
24 (5 ignored) + 29 passed; `cargo test -p lucisv -p lucisv_core` 30 +
|
||||
113 + 117 passed; `cargo test --workspace` **4 649 passed, 0 failed,
|
||||
52 ignored** (4 625 + 24; 47 + 5).
|
||||
|
||||
Findings:
|
||||
|
||||
- **1 — BLOCKING (engine, pre-existing; `vlog_refactor::rename`, reached
|
||||
here and from `lucisv-server`).** Renaming a port bound by an implicit
|
||||
connection, or a net such a connection binds, writes a "verified" edit
|
||||
that silently rewires the design. `leaf (input d)`, `top` instantiating
|
||||
`leaf u_leaf (.*)` with its own `d`, `top2` with `leaf u_leaf (.clk, .d,
|
||||
.q)`:
|
||||
(a) rename `leaf.d` → `din`: `leaf.sv` renamed, `top.sv` untouched — `.*`
|
||||
no longer binds the port (the engine's own `expand_wildcard` then says
|
||||
"no net … named `din` … lucisv wrote it unconnected"); `top2.sv`'s `.d`
|
||||
becomes `.din`, which now names a net `top2` does not have;
|
||||
(b) rename `top.d` → `x`: only the declaration moves; `.*` stops binding
|
||||
`leaf.d`; (c) rename `top2.d` → `x`: `.d` is left naming nothing. All
|
||||
answer success with no warning. Reproduced with a direct
|
||||
`vlog_refactor::rename` call (scratch oracle), so it is the engine's.
|
||||
`check::verify`'s resolution identity (`crates/vlog_refactor/src/check/
|
||||
mod.rs:41`) cannot see it: neither `.*` nor `.name` spells a reference the
|
||||
resolver records. Fix (vlog_refactor, outside this lane — a Handshake
|
||||
request): rewrite `.name` as `.new(old)` / `.old(new)`, and refuse (or
|
||||
expand first) a rename that changes a name a `.*` binds, the way
|
||||
`inline_module` refuses `.*` and `remove_port` warns about it. Test:
|
||||
`qa_rename_never_breaks_an_implicit_port_connection`.
|
||||
- **2 — BLOCKING (this lane; `tools/edit.rs:209` `sources`).** The whole-set
|
||||
read is "every indexed file", and the index skips files over 1 MiB
|
||||
(`project/files.rs:100`) and files that are not UTF-8 (M1's rule, named
|
||||
only in `project_overview`). A rename whose uses sit in such a file writes
|
||||
the others and answers success without a word: a 1.08 MB `big.sv` with
|
||||
`leaf u_l (.clk(clk), .d(x), .q(y))` keeps `.d(x)` after `leaf.d` →
|
||||
`din_i` ("files: 1 changed"); the same for a copy of `mid.sv` with a
|
||||
Latin-1 `©` in its header comment — common in vendor RTL. Every engine
|
||||
that edits instantiations (`rename`, `remove_port`, `add_port`,
|
||||
`propagate_ports`) is exposed the same way. Suggested fix: keep the
|
||||
skipped paths (`FileSet::skipped_large` is a count today) and, before
|
||||
writing, refuse when a skipped file's bytes contain the name being
|
||||
changed (the old name for `rename`, the module name for the port tools):
|
||||
"`rtl/big.sv` is not indexed (over 1 MiB) and spells `d`; nothing
|
||||
written." — or at minimum list the skipped files under `warnings:`. Test:
|
||||
`qa_rename_says_so_when_a_skipped_file_mentions_the_name`.
|
||||
- **3 — non-blocking (engine, pre-existing).** `extract_module` into a CRLF
|
||||
file writes the instantiation with bare LF (`adder u_adder (\n .a(a),\n
|
||||
…`), leaving `ext.sv` mixed; the created file is LF. Valid Verilog,
|
||||
nothing lost; `vlog_refactor/src/extract/render.rs` renders `\n` only.
|
||||
Test: `qa_extract_module_keeps_a_crlf_file_crlf`.
|
||||
- **4 — non-blocking.** `"dry_run": null` is read as absent and the edit is
|
||||
**written**, while `"true"` and `1` are refused as non-booleans. For a
|
||||
flag whose default is "write", an explicit null should be refused like any
|
||||
other non-boolean (`Args` validation of `Ty::Bool`, M1's file). Test:
|
||||
`qa_a_null_dry_run_writes_nothing`.
|
||||
- **5 — non-blocking.** `instantiate` takes any `instance` string: `""`
|
||||
renders `pm #(…) (.*);`, `é`, `a b`, `u_x); evil (` and `module` render
|
||||
text that does not parse (`tools/refactor.rs`, `instantiate`). It writes
|
||||
nothing, so nothing is corrupted, but the text is handed to an agent to
|
||||
paste; the engine's plain-identifier check would refuse these. Test:
|
||||
`qa_instantiate_refuses_an_instance_name_that_is_not_an_identifier`.
|
||||
|
||||
Observations (not findings): the formatter on a CRLF file with a fence (or
|
||||
`lines`) keeps CRLF inside the fence and writes LF elsewhere — CLI
|
||||
identical, the formatter's own behaviour; `fix_lint`'s `posix-eof` fix adds
|
||||
the final newline at the end of an unterminated `// lucisv: off` region —
|
||||
CLI identical (`fence::is_protected` treats EOF as outside); `lucisv check
|
||||
--help` still says `--unsafe-fixes` "changes nothing" though `always-comb`
|
||||
ships an unsafe fix — stale CLI help, out of lane. The opentitan checkout
|
||||
was only copied from (its `git status` shows the same three pre-existing
|
||||
modifications before and after).
|
||||
|
||||
**2026-09-23 (QA, M3 re-check after the rework). Verdict: FAIL — one new
|
||||
blocking finding (6), a one-line-per-tool fix; everything the rulings asked
|
||||
for is verified.** Finding 1 is not counted (lead's ruling: engine, lane
|
||||
M3.5; its test stays ignored with that reason). If the lead rules finding 6
|
||||
a known limit instead, the rest of M3 passes.
|
||||
|
||||
Re-derived by hand (release build, scratch copies of `tests/fixtures/edit`):
|
||||
|
||||
- **Finding 2 — fixed as ruled.** A 1.08 MB `rtl/big.sv` and a Latin-1
|
||||
`rtl/lat.sv`, each with `leaf u_l (.clk(clk), .d(x), .q(y))`: `rename`
|
||||
`d` → `din_i` (dry run and real) is refused, `` `rtl/big.sv` (skipped:
|
||||
over 1 MiB) may reference `d`; … nothing written.`` (resp. `not UTF-8
|
||||
text`), tree unchanged. The name only inside other words (`data`, `d_q`,
|
||||
`dd`, `d$x`, `x$d`, `\dx `, `odd` in a comment): written, three files,
|
||||
the skipped file named once under `warnings:`, its bytes untouched.
|
||||
- **The whole-word rule attacked.** `d` as the file's first byte, as its
|
||||
last byte (no newline), in `.d(1)`, in `f(d)`, as the escaped `\d ` (the
|
||||
same identifier), and between two `\xa9` bytes — all refused. An escaped
|
||||
declaration `\a+b ` (the stake is spelled `\a+b`): the skipped file's
|
||||
`\a+b` ended by a tab, a newline or EOF refuses; `a+b` as an expression
|
||||
and the longer `\a+bc ` do not. An escaped declaration `\dd ` stakes `dd`,
|
||||
so a skipped `.dd(1)` refuses too. The per-tool stakes of the README's
|
||||
table: with a skipped file spelling only `cell old inv ext spare`,
|
||||
`expand_wildcard`, `propagate_ports`, `inline_module`, `convert_ports`,
|
||||
`remove_port` (module `spare`), `add_port` (by module and by position)
|
||||
and `extract_module` are each refused naming their stake;
|
||||
`organize_imports` writes and names the skipped file.
|
||||
- **Leaving and entering the skipped set.** `big.sv` rewritten small and
|
||||
UTF-8: the next call is still refused with the stale reason "(skipped:
|
||||
over 1 MiB)" — the skipped list is the last walk's, so it lags up to
|
||||
`REWALK_AFTER` (5 s), on the safe side; after 5.5 s the rename edits all
|
||||
four files and the warning is gone. The other way, an indexed `mid.sv`
|
||||
gaining a Latin-1 byte is refused on the very next call (the stamp sweep
|
||||
loses it and walks).
|
||||
- **The merge did not change `references`.** The pre-rework binary (82bbba0,
|
||||
built in a scratch worktree, removed after) and the reworked one answer
|
||||
`references` identically — text and `structuredContent` — at all 165
|
||||
identifier positions of `tests/fixtures/nav` and at 600 random positions of
|
||||
the aes copy (158 answered, the rest the same refusals). In-suite: on the
|
||||
nav fixture with one skipped file added, every answer is the plain one plus
|
||||
exactly the trailing `warning:` line and `structuredContent.warning`.
|
||||
- **Finding 5 — fixed.** `""`, `a b`, `u_x); evil (`, `module` refused
|
||||
(the un-ignored test); the dev's wire test covers `\u-x ` accepted.
|
||||
- **Finding 4 test edit.** Renamed to
|
||||
`qa_a_null_dry_run_is_absent_and_a_non_boolean_is_refused`, `#[ignore]`
|
||||
removed, doc comment rewritten for the ruling, and the assertion swapped
|
||||
(null now asserts `fmt/messy.sv` written). It is *not only* a swap: a
|
||||
loop was added asserting `"true"` and `1` are refused with nothing written
|
||||
— extra assertions matching the new name, nothing of mine weakened. The
|
||||
other un-ignored tests (2, 5) are byte-for-byte mine apart from rustfmt;
|
||||
finding 1 and 3's `#[ignore]` reasons were reworded as ruled.
|
||||
- **Race.** `qa_a_rename_racing_a_writer_never_tears_a_file` green; the
|
||||
aes script once more at 50 ms: 150 calls, 82 freshness refusals all naming
|
||||
`rtl/aes_core.sv`, 68 engine refusals, no torn file.
|
||||
|
||||
New findings:
|
||||
|
||||
- **6 — BLOCKING (this lane; every whole-set edit tool's `rewalk: false`,
|
||||
`tools/edit.rs`, `tools/refactor.rs`).** The whole set is "every indexed
|
||||
file", and a file created since the last walk enters the index only after
|
||||
`REWALK_AFTER` (5 s, `project/mod.rs:23`); the edit tools do not walk. A
|
||||
`rename` right after an agent writes `rtl/newer.sv` with `leaf u_l (.d(x))`
|
||||
answers "files: 3 changed" and leaves `.d(x)` behind — the wrong answer of
|
||||
finding 2, reached through time instead of size; a brand-new over-1 MiB
|
||||
file escapes the skipped-file guard the same way (a dry run answered it
|
||||
at once with no refusal; the same call 5.5 s later was refused). Suggested fix: `rewalk: true` on the whole-set edit
|
||||
tools (the flag and `refresh(force_walk)` exist; `project_overview` uses
|
||||
it). Cost measured on the opentitan `hw/` checkout (3 944 files, read
|
||||
only): a forced-walk call 139–146 ms against 9–11 ms without, next to the
|
||||
1.6–2.6 s whole-set read each edit already pays. Test:
|
||||
`qa_an_edit_sees_a_file_created_just_before_it`.
|
||||
- **7 — non-blocking (`project/files.rs:103–105`).** The size-cap branch
|
||||
records a file's canonical path as skipped without the root-containment
|
||||
check the indexed branch makes, so an over-1 MiB file behind a symlink
|
||||
leading out of the root refuses edits inside it, and the refusal prints
|
||||
the file's absolute path outside the root. A small file behind the same
|
||||
link is dropped (M1). Safe side (a false refusal, nothing written). Test:
|
||||
`qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set`.
|
||||
|
||||
Tests: `qa_m3.rs` +8 — seven `qa_recheck_*` green (refusal naming file and
|
||||
reason; substring-only written with the warning; whole-word edges; escaped
|
||||
names; every tool's stake; leaving/entering the skipped set; `references`
|
||||
gains only the warning line) and finding 6's; plus finding 7's ignored. Now
|
||||
34 passed, 4 ignored (1, 3, 6, 7). Sizes (same method): `apply.rs` 216,
|
||||
`tools/edit.rs` 222, `tools/format.rs` 220, `tools/refactor.rs` 261,
|
||||
`tools/source.rs` 185, `tools/nav.rs` 340, `project/mod.rs` 242,
|
||||
`project/files.rs` 153; no `unwrap`/`expect`/`panic!`/`#[allow]` in their
|
||||
production code.
|
||||
|
||||
Gates (through `tools/guard.sh`, one at a time): `cargo fmt -p lucisv_mcp
|
||||
-p lucisv_core -p lucisv -- --check` rc 0; `cargo clippy -p lucisv_mcp -p
|
||||
lucisv_core -p lucisv --all-targets` 0 warnings, rc 0; `cargo test -p
|
||||
lucisv_mcp` 44 + 0 (1 ignored) + 51 + 43 + 34 (4 ignored) + 31 passed;
|
||||
`cargo test --workspace` **4 662 passed, 0 failed, 51 ignored** (4 655 + 7;
|
||||
49 + 2). The M3 QA box in `TODO-MCP.md` stays open on finding 6.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-09-23.** Read `apply.rs` and the three tool files. The write
|
||||
path is the block's safety story and it held under QA's race, permission and
|
||||
symlink attacks: all-or-nothing, re-read before the first write, `write_atomic`
|
||||
inside the roots only. Rulings: a skipped file (over 1 MiB, non-UTF-8) that
|
||||
spells a changed name as a whole word refuses the edit — lucisv-mcp will not
|
||||
edit around a file it cannot see; `dry_run: null` is absent; every whole-set
|
||||
tool re-walks first. MCP-1 delivered as a pure move (`lucisv_core::diff`;
|
||||
CLI `--diff` byte-identical). **The one blocking finding that stays open is
|
||||
not this lane's:** `vlog_refactor::rename` leaves `.*` and `.name` shorthand
|
||||
connections broken when a port or its bound net is renamed — a real
|
||||
corruption the LSP has had all along, now exposed to agents. It is fixed in
|
||||
its own engine lane, M3.5, before M4; until it lands the `rename` tool says
|
||||
so in its description. MCP-8 (a false `remove_port` refusal on same-file
|
||||
instantiations) and MCP-10 (CRLF in `extract_module`) are engine findings
|
||||
filed for the owner. Committed as M3.
|
||||
@@ -0,0 +1,766 @@
|
||||
# mcp-navigation
|
||||
|
||||
TODO-MCP.md **M2** — the navigation, diagnostics and resource half of
|
||||
`lucisv-mcp`: tools `definition`, `references`, `hierarchy`, `diagnostics`,
|
||||
`defines`, and the `lucisv://` resources. Design: `docs/mcp/PLAN.md` §4.2,
|
||||
§4.3 and §4.5. The transport and `Project` they run on are
|
||||
`docs/features/mcp-transport`; the rendering contract is
|
||||
`docs/features/mcp-read-tools`'s.
|
||||
|
||||
## Goal
|
||||
|
||||
Let an agent ask the questions it otherwise answers by grepping and reading
|
||||
whole files — where is this declared, who uses it, what instantiates what,
|
||||
what does `lucisv check` say about this file, what does this macro expand
|
||||
from — and get a compact, root-relative answer in one call. Every answer is
|
||||
a composition of existing library queries (`vlog_semantic`'s index and
|
||||
overlay, `vlog_refactor::find_references`, `vlog_linter`'s run); no language
|
||||
knowledge lives in the MCP crate. The same answers the read tools give are
|
||||
also addressable as `lucisv://` resources for a host that attaches context
|
||||
instead of calling tools.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **One selector for `definition` and `references`** (`tools/select.rs`):
|
||||
`file` + `line` + `col` (1-based, **byte** column — the crate's one column
|
||||
unit; a column past the line's end is refused naming the line's length,
|
||||
one past the last byte is the end and allowed); or `file` + `line` +
|
||||
`name` — the first **token** on that line spelling `name` (an identifier,
|
||||
or a macro use when written `` `NAME``), so a comment or a string never
|
||||
stands in for the code; a name found only inside a macro call's argument
|
||||
text is refused ("inside a macro argument, which lucisv does not resolve;
|
||||
give `col` on a plain use"); or `file` + `name` — the name's one
|
||||
declaration in that file; else, when the file declares none, its uses,
|
||||
provided they all resolve to one declaration (uses naming different
|
||||
declarations are refused listing a line per target, "`sig` on line 2 →
|
||||
leaf.sv:1, line 6 → other.sv:1; add `line`"); else its first macro use; a
|
||||
name declared twice in the file is refused listing the lines; or a bare
|
||||
`name` with an optional `unit`, looked up in the index. `unit` with
|
||||
`file` is refused (two selectors at once); `line`/`col` without `file` is
|
||||
refused.
|
||||
- **`definition` is the language server's ladder** (`nav.rs::at_position`):
|
||||
an `` `include`` line → the named file **beside the including file only**
|
||||
(no include-directory ladder: the MCP has no `+incdir` configuration to
|
||||
honour, and a miss says so); a macro use → the file's own last
|
||||
`` `define`` when it has one, else every indexed definition (the include
|
||||
graph is not modelled, so none is picked); then the file's symbol table,
|
||||
then the workspace overlay (`resolve_external` computed per call against
|
||||
the current index — never cached, because the index moves under an
|
||||
unchanged file). A local declaration answers its completing declaration
|
||||
first (a non-ANSI port's body line), then its name, then every
|
||||
redeclaration the binder folded into it (`Semantics::duplicates`, so
|
||||
`output y; wire y;` lists the port *and* the net — the "both a port and
|
||||
an internal net" case), one site per line. By name: the unit declarations,
|
||||
the connection-surface members (`workspace_symbols` filtered to the exact
|
||||
name), and the hierarchical-only members (`hierarchical_declarations`);
|
||||
with `unit`, `member_in(unit, name, Surface::Hierarchical)`; `` `NAME``
|
||||
(or a name nothing else declares) answers the macro definitions. The
|
||||
by-name form reports what the index records — a redeclaration inside a
|
||||
unit is visible only through the position form, which has the file's own
|
||||
table. Ambiguity is always a list.
|
||||
- **Every indexed span is re-checked against the bytes before it is
|
||||
printed** (`tools/source.rs::checked_site`): the site is shown only when
|
||||
the file still spells the name there, so a stale index omits a site,
|
||||
never mislocates one (the `spells_exactly` rule of
|
||||
`docs/features/references-hierarchical-surface`). One read per file per
|
||||
call (`source::Texts`).
|
||||
- **`references` hands the engine the whole indexed file set, always**
|
||||
(lead's ruling on QA finding 1, replacing the M2 narrowing rule): every
|
||||
indexed file plus the selected one, read from disk at call time
|
||||
(`nav.rs::all_files`). A use resolves through files that never spell its
|
||||
name — `u_a.u_b.sig` needs the file declaring `u_b`, `e.s.count` needs the
|
||||
class declaring `s` — so no narrowing by the name's census is sound, and a
|
||||
narrowed set also turned an unresolvable use into the false refusal
|
||||
"declared outside the files lucisv indexes". **Measured cost** (release,
|
||||
whole opentitan checkout, 3 944 files, after the index exists; each call
|
||||
re-reads and re-parses the set): `entropy_masking_req` 1.62 s, `state_q`
|
||||
from `entropy_src_main_sm.sv` 1.89–1.92 s, the `aes` instantiation in
|
||||
`tb.sv` 1.70 s, `clk_i` from `prim_fifo_sync.sv` 2.55 s (83 hits); peak
|
||||
RSS of the session ~0.98 GB. Handshake MCP-7 is the way down. The
|
||||
engine's refusals are said as ours: prefixed "lucisv cannot follow this
|
||||
position: ", and the rename wording they share with `rename` replaced
|
||||
(`nav.rs::engine_refusal`). A macro use — by position or by a bare name
|
||||
that only a `` `define`` declares — is refused with a pointer to
|
||||
`defines` (the engine follows declarations, not macros).
|
||||
- **`hierarchy` is the textual instance census** (`WorkspaceIndex::
|
||||
instantiations()`, the edges the editor's hierarchy view and call
|
||||
hierarchy read): `generate` and `` `ifdef`` branches all appear; an
|
||||
instantiation at file scope (a `bind`) is not an edge, so a bound module
|
||||
is a "top". Down: `instance : module #(overrides)`, a module instantiated
|
||||
N times under one parent listed N times; a module the index does not hold
|
||||
is marked `(not indexed)`; a module declared more than once is marked
|
||||
`(declared N times)` and **not expanded** (which declaration an instance
|
||||
means is the elaborator's choice); a module already on the path is marked
|
||||
`(recursive)` and not expanded (a self-instantiating `generate` tree
|
||||
terminates at once); `depth` defaults to 3 and the schema accepts 1..=20
|
||||
(`Ty::Range`, so `inputSchema` carries `maximum: 20` and 21 is refused
|
||||
naming `depth`); the walk stops at 50 000 nodes and says so. Up: `parent.instance #(overrides) file:line`
|
||||
per instantiation of `root`, recursively. Without `root`, down starts at
|
||||
every module nothing instantiates (a module that only instantiates itself
|
||||
is therefore not a default root; name it).
|
||||
- **Override slicing**: the text between the instantiated module's name at
|
||||
the site (`InstantiationEdge::site_span`) and the statement's **first**
|
||||
instance name (`edge.instances[0].name_span` — the `#(...)` belongs to the
|
||||
whole statement), read from the file now, comments
|
||||
dropped (`source::without_comments`, strings kept), whitespace collapsed,
|
||||
kept only when it starts with `#` and the file still spells the module
|
||||
name at the site. The text line caps it at 200 characters with `…`
|
||||
(opentitan's `earlgrey_pd_main` instance carries hundreds of overrides);
|
||||
`structuredContent.nodes[].overrides` carries all of it. `leaf #(.W(2))
|
||||
u_a (), u_b ();` shows `#(.W(2))` on both instances.
|
||||
- **Structured `hierarchy`** is a flat, pageable node list in tree order,
|
||||
each `{depth, instance, module, parent, file, line, overrides, note}`
|
||||
(`module` is always the instantiated module; `parent` is set in the `up`
|
||||
direction) — a nested tree cannot be paged with `limit`/`offset`, and the
|
||||
depth field reconstructs it.
|
||||
- **`diagnostics` answers what `lucisv check .` — the whole-tree run, CI's
|
||||
run — reports** (lead's ruling on QA finding 5): the cross-file rules
|
||||
(`unknown-port`, `unused-signal`, …) always run, also when one `file` is
|
||||
asked for, so one file's answer is that file's share of the whole-tree
|
||||
run, not `lucisv check <file>` (which, holding one file, runs none of
|
||||
them). The tool description says so. The config ladder is `lucisv
|
||||
check`'s, per file:
|
||||
`Discovery::for_file` finds the `lucisv.toml` governing it; its `[lint]
|
||||
select` is the base set unless the `rules` argument is given (which
|
||||
replaces it, like `--select`); `[lint] ignore` then removes; the run is
|
||||
`select_rules(select, ignore, workspace = true)`; `[lint.<rule>]` options
|
||||
go through `RuleOptions::set_raw` (a bad one is refused naming
|
||||
`file:line`, as the CLI fails); `[lint] waivers` files are read with
|
||||
`ExternalWaivers::read` and applied by `lint_with`; the line length and
|
||||
tab width are `line-length`/`indent` else the formatter's defaults (100,
|
||||
2). `severity` filters the findings afterwards. The workspace rules'
|
||||
cross-file questions are answered by the project index (`Mentions`, the
|
||||
server's `IndexMentions`): one file asks `mentioned_outside` directly; the
|
||||
whole-project form builds a word → (file count, first file) census once
|
||||
per call from `FileFacts::words`, because the per-question walk over
|
||||
3 944 records would cost minutes. Parse errors come first as rule
|
||||
`parse-error`, severity `error`, from the tolerant parse the file's
|
||||
analysis already holds; the JSON array uses the CLI's field names
|
||||
(`filename`, `rule`, `severity`, `message`, `location{line,column}`,
|
||||
`end_location`, `range{start,end}`, `fix`) with `filename`
|
||||
root-relative. **Missing-closer warnings are not offered**: they are the
|
||||
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.
|
||||
**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`
|
||||
over the usage every file's `lint_with` returned, per config; the
|
||||
severity the linter stamps, as the CLI does), when `unused-waiver` is
|
||||
among the run's rules. The single-file form cannot know — a directive may
|
||||
fire in a file it did not lint — and reports none.
|
||||
- **`defines`**: `file` → that file's table as on disk (its `` `undef``s
|
||||
included); `name` → every indexed definition of it (`find_define`); neither
|
||||
→ every indexed `` `define``, paged. Each row `line `define NAME(params)
|
||||
body`, the body one-lined and cut at 200 characters (UVM macro bodies run
|
||||
to hundreds of lines). **One-step expansion with `args` is not offered**:
|
||||
the server's `expand.rs` is ~260 production lines of argument splitting,
|
||||
default parameters, string/escape handling and token pasting — not the
|
||||
~60 lines the lane allowed, and a second copy of it is exactly the
|
||||
duplication CLAUDE.md forbids. See Handshakes.
|
||||
- **Resources** (`src/resources.rs`): `lucisv://overview` (`text/plain`,
|
||||
`project_overview`'s text, walking first as the tool does) and
|
||||
`lucisv://rules` (`text/markdown`, `vlog_linter::rules_markdown()`, no
|
||||
index needed) in `resources/list`; `lucisv://unit/{name}` (`unit_interface`'s
|
||||
text) and `lucisv://file/{path}/outline` (`outline`'s text, `path`
|
||||
root-relative, `%XX` decoded) in `resources/templates/list`. A read runs
|
||||
the read tool's own handler, so the two can never disagree. Any other
|
||||
URI, and one naming nothing (an unknown unit, a path outside the roots),
|
||||
is JSON-RPC `-32002` "resource not found: <uri> (<reason>)"; a missing
|
||||
`uri` is `-32602`. `initialize` already declared `resources: {}`; no
|
||||
`subscribe`/`listChanged` is offered.
|
||||
- **A boolean argument type** (`tools::Ty::Bool`) was added to the registry
|
||||
for `include_declaration`; it validates like the others (`true or false`
|
||||
in the refusal).
|
||||
- **`Analysis` now keeps the tokens and the `` `define`` table**
|
||||
(`project/analysis.rs`): the lint context and the macro lookups need the
|
||||
tokens the parse consumed, so they are cloned once before the parse.
|
||||
|
||||
## Handshakes
|
||||
|
||||
Consumed (public APIs only; no library crate was modified):
|
||||
|
||||
- `vlog_semantic`: `Semantics::{symbols_named, symbol, symbol_at,
|
||||
reference_at, reference_id_at, references, duplicates, scope}`,
|
||||
`resolve_external`, `ExternalResolutions::{definition_of, get}`,
|
||||
`ExternalTarget::best`, `WorkspaceIndex::{units, member_in,
|
||||
workspace_symbols, hierarchical_declarations, files_mentioning,
|
||||
files_naming_in_macros, mentioned_outside, find_define, defines,
|
||||
instantiations, instantiations_of, instantiable_units, members_of,
|
||||
facts_for, file_id, files, path}`, `FileFacts::words`,
|
||||
`PackageExports::exports`.
|
||||
- `vlog_parser`: `defines::{collect_defines, DefineTable, Define,
|
||||
DefineKind}`, `token::{Token, TokenKind}`, `LineIndex::{offset,
|
||||
line_range, line_col}`.
|
||||
- `vlog_refactor::find_references`.
|
||||
- `vlog_linter`: `LintContext::{from_parse, with_semantics, with_options,
|
||||
with_line_length, with_tab_width, with_oracle}`, `lint_with`,
|
||||
`select_rules`, `RuleOptions::set_raw`, `ExternalWaivers::{read, absorb}`,
|
||||
`MentionOracle`, `ModuleInterface`, `rules_markdown`.
|
||||
- `lucisv_core::config::{Discovery::for_file, FileConfig}`;
|
||||
`vlog_formatter::Config::default` (the line-length and indent defaults).
|
||||
|
||||
Requests (none blocking):
|
||||
|
||||
- **MCP-7 → `vlog_refactor`: a `find_references` variant taking `&dyn
|
||||
KnownFacts`** (as `rename_traced_with` does), so a caller holding a
|
||||
current `FileFacts` record per text — M6's cache, or the MCP's own index —
|
||||
can skip re-parsing the whole set. Until then every `references` call
|
||||
parses all 3 944 opentitan files (~1.6–2.6 s release): the price of a
|
||||
correct answer (QA finding 1).
|
||||
|
||||
- **MCP-5 → `vlog_parser` (candidate): lift the server's `expand.rs`
|
||||
(`single_step`, `has_macro_use`, `CAP`) into `vlog_parser::defines`** as a
|
||||
pure move, so `defines` can offer the one-step expansion the plan lists
|
||||
and hover keeps its own. Until then `defines` answers the table only.
|
||||
- **MCP-6 → `lucisv_server` (informational, a candidate finding):** on
|
||||
opentitan, `textDocument/references` at the `aes` instantiation and its
|
||||
`.clk_i` connection in `hw/ip/aes/dv/tb/tb.sv` answers 11 and 9
|
||||
locations; `references` here answers 14 and 12 — the same locations plus
|
||||
the three top-level instantiations in
|
||||
`hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`
|
||||
(`aes #(` at 2069/1521/933 and their `.clk_i(clkmgr_clocks_i.clk_main_aes)`),
|
||||
which are real (`hierarchy` `up` from `aes` lists `earlgrey_pd_main.u_aes`).
|
||||
Stable after a 30 s settle, so not an indexing race. Not investigated in
|
||||
this lane.
|
||||
- **Resource wording**: `lucisv://unit/{name}` for a unit declared twice
|
||||
answers `-32002` with `unit_interface`'s sentence, its "pass `file`"
|
||||
replaced by "call the unit_interface tool with its file argument to pick
|
||||
one" (`resources.rs`), since a URI has no `file` argument.
|
||||
- **MCP-3 (PLAN §7) stays a candidate:** `hierarchy` walks
|
||||
`instantiations()` keyed by the owner's `(FileId, name_span.start)`
|
||||
exactly as `design_hierarchy::snapshot` does; they agree on the fixtures
|
||||
and on `top_earlgrey`.
|
||||
- Wanted but worked around: a `Semantics::symbol_id(&Symbol)` would save
|
||||
`local_sites` a `symbol_at` lookup.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `definition`: position / line+name / file+name / bare name (+`unit`)
|
||||
selector; `` `include`` line; macro use; local (detail, name,
|
||||
redeclarations); cross-file overlay; by-name units, members,
|
||||
hierarchical members, macros; lists, never guesses
|
||||
- [x] `references`: `find_references` over the whole indexed set; grouped,
|
||||
`line:col text`, `limit`/`offset`, `include_declaration`; one-
|
||||
declaration rule for a bare name; macro refusal
|
||||
- [x] `hierarchy`: down (default: every top) / up, `depth` (3, cap 20),
|
||||
overrides, `(not indexed)`, `(declared N times)`, `(recursive)`,
|
||||
node cap, flat structured list
|
||||
- [x] `diagnostics`: parse errors + lint under the per-file `lucisv.toml`,
|
||||
`rules`, `severity`, waivers, index oracle, census for the workspace
|
||||
form, CLI JSON names, `limit`/`offset`
|
||||
- [x] `defines`: file / name / project table, body capped; expansion not
|
||||
offered (MCP-5)
|
||||
- [x] resources: list, templates, read, `-32002`
|
||||
- [x] QA rework: findings 1–11 fixed or ruled, `qa_m2.rs` 32/32 green
|
||||
- [x] carry-over: M1 QA finding 11 (`read_item` `\a@12`) fixed; the QA test
|
||||
un-ignored
|
||||
- [x] wire tests over the new `tests/fixtures/nav` tree; the opentitan
|
||||
census (`tests/opentitan.rs`, `#[ignore]`)
|
||||
- [x] gates through `tools/guard.sh`; sizes
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-23 (dev, M2).**
|
||||
|
||||
Built: `src/tools/nav.rs` (selector, `definition`, `references`),
|
||||
`src/tools/hierarchy.rs`, `src/tools/diagnostics.rs`, `src/tools/defines.rs`,
|
||||
`src/tools/source.rs` (per-call file texts, checked sites, the word finder,
|
||||
comment stripping and capping shared by the four), `src/resources.rs`;
|
||||
`tools/mod.rs` registers the five tools and gains `Ty::Bool`/`Args::flag`;
|
||||
`rpc.rs` answers the three `resources/*` methods from `resources.rs`;
|
||||
`project/analysis.rs` keeps tokens and defines and computes the overlay on
|
||||
request (`Analysis::external`), with `token_at` and `line_text`.
|
||||
|
||||
Decisions and deviations from PLAN/TODO:
|
||||
|
||||
1. **A new fixture tree `tests/fixtures/nav`** instead of extending
|
||||
`tests/fixtures/design`: M1's wire and QA tests pin that tree's file
|
||||
count, unit counts, top modules and paging (`… and 6 more`), and a
|
||||
lucisv.toml with `[lint]` there would change them. The new tree has every
|
||||
case the brief listed: a `bind` connecting a bare net (`core_bind.sv`), a
|
||||
`u_core0.state_q` tail (`top.sv`), a port that is also a net
|
||||
(`dual.sv`), a class member used through a handle in another file
|
||||
(`tb/sb.sv`, `tb/env.sv`), macros defined in an included `.svh` and used
|
||||
in two files, `core` instantiated twice under `top` with different
|
||||
`#(...)`, a self-instantiating `generate` tree (`tree.sv`), a five-deep
|
||||
chain ending in a missing module (`chain.sv`), and a `lucisv.toml` with
|
||||
`[lint] select`, `[lint.line-length] length = 40` and a waiver file.
|
||||
2. **Two files beyond the brief's list**: `src/tools/defines.rs` (PLAN put
|
||||
`defines` in `read.rs`, M1's file) and `src/tools/source.rs` (helpers
|
||||
the four tools share; without it `hierarchy.rs` and `defines.rs` would
|
||||
import from `nav.rs`). `src/main.rs` gained the one line `mod
|
||||
resources;` — unavoidable for a new top-level module.
|
||||
3. **Two edits to existing tests, both forced by the lane**: `wire.rs`'s
|
||||
`tools_list_describes_every_tool_for_the_agent` lists the eleven tools;
|
||||
`qa_m1.rs`'s `qa_everything_but_initialize_and_ping_waits_for_the_handshake`
|
||||
asserted `tools/list` has 6 entries, now 11 (with a comment). Neither
|
||||
weakens an assertion.
|
||||
4. **The selector grew `file` + `line` + `name` and `file` + `name`**
|
||||
beyond the plan's `file,line,col | name,unit?` — agents rarely know byte
|
||||
columns. `col` stays exact.
|
||||
5. **`references` refuses a macro use** (the engine would say "no symbol to
|
||||
rename", which reads wrong in a references answer) and points at
|
||||
`defines`.
|
||||
6. **`hierarchy` takes `limit`/`offset`** and a 50 000-node cap (PLAN §4.5:
|
||||
every list is capped) and does not expand a module declared more than
|
||||
once (opentitan's technology variants: `pinmux_jtag_breakout` ×4).
|
||||
7. **Missing-closer warnings and one-step expansion are not offered**
|
||||
(Assumptions; MCP-5).
|
||||
8. **Carry-over, M1 QA finding 11** (`tools/read_item.rs::select`): when
|
||||
the `@LINE` reading matches nothing and the name starts with `\`, the
|
||||
whole spelling (after an optional `kind:`) is tried as the name; the
|
||||
first refusal stands if that fails too. Unit test
|
||||
`an_escaped_name_ending_in_at_digits_is_its_own_name_when_no_line_matches`;
|
||||
`qa_rework_an_escaped_name_ending_in_at_digits_is_selectable_by_itself`
|
||||
un-ignored and green.
|
||||
|
||||
The opentitan census (`tests/opentitan.rs`, one session over the whole
|
||||
checkout, read-only). Wall time per call, debug build (the test) / release
|
||||
build (the same calls through a stdio driver):
|
||||
|
||||
| call | debug | release |
|
||||
|---|---|---|
|
||||
| first call (index build, 3 944 files) | 10.1–10.4 s | 1.9 s |
|
||||
| `references` `entropy_masking_req` from `aes.sv` | 62 ms | 18 ms |
|
||||
| `references` `state_q` from `entropy_src_main_sm.sv:42` | 928 ms | 165 ms |
|
||||
| `references` `aes` at `tb.sv:45` | 266 ms | ~50 ms |
|
||||
| `references` `.clk_i` at `tb.sv:46` | 10.0 s | 1.6 s |
|
||||
| `references` `clk_i` from `prim_fifo_sync.sv` | 9.9 s | 1.6 s |
|
||||
| `hierarchy` down `top_earlgrey` depth 2 | 22–384 ms | 10 ms |
|
||||
| `hierarchy` up `prim_fifo_sync` depth 1 (77 instances) | 21 ms | 7 ms |
|
||||
| `definition` `prim_fifo_sync` | 21 ms | 8 ms |
|
||||
| `diagnostics` `hw/ip/aes/rtl/aes.sv` | 8 ms | 7 ms |
|
||||
| `diagnostics` whole project (2 102 findings) | — | 1.9 s |
|
||||
|
||||
Parity with the language server (release `lucisv-server` rebuilt at this
|
||||
commit, same checkout, `textDocument/references`/`definition` at the same
|
||||
positions): `entropy_masking_req` 6 = 6 locations (`aes_bind.sv:45,54`
|
||||
included); `state_q` 5 = 5 (`entropy_src_core.sv:3092` included); `aes` 14
|
||||
⊇ 11 and `.clk_i` 12 ⊇ 9 (MCP-6); every `definition` equal. `hierarchy`
|
||||
down from `top_earlgrey` depth 2 lists `earlgrey_pd_main :
|
||||
earlgrey_pd_main` and under it `u_aes : aes #(...)`. `diagnostics` on
|
||||
`aes.sv` finds nothing, as `lucisv check` does; `uartdpi.sv`'s three
|
||||
`wire-reg-mixup` findings match the CLI's. `git -C opentitan status
|
||||
--porcelain` was byte-identical before and after (the owner's three
|
||||
modified files, untouched).
|
||||
|
||||
Tests: unit 28 → 37 (source 3, defines 2, resources 1, analysis 1,
|
||||
read_item 1, tools/mod 1 extended; hierarchy 1); `wire.rs` 11 → 19;
|
||||
`qa_m1.rs` 50 + 1 ignored → 51 + 0; `opentitan.rs` 1 (ignored).
|
||||
|
||||
Sizes (production lines: non-blank, non-comment, before `#[cfg(test)]`):
|
||||
`tools/nav.rs` 446, `tools/hierarchy.rs` 311, `tools/diagnostics.rs` 293,
|
||||
`tools/defines.rs` 158, `tools/source.rs` 134, `resources.rs` 112,
|
||||
`tools/mod.rs` 146, `rpc.rs` 241, `project/analysis.rs` 77,
|
||||
`tools/read_item.rs` 213, `main.rs` 68. No function over 50 lines.
|
||||
|
||||
Gates (all through `tools/guard.sh`, one cargo invocation at a time):
|
||||
`cargo fmt -p lucisv_mcp -- --check` exit 0; `cargo clippy -p lucisv_mcp
|
||||
--all-targets` `Finished`, no warnings; `cargo test -p lucisv_mcp` unit 37
|
||||
passed, `opentitan` 0 passed / 1 ignored, `qa_m1` 51 passed, `wire` 19
|
||||
passed; `cargo test --workspace` exit 0 in 238 s, **4 566 passed, 0 failed,
|
||||
47 ignored** (4 548 before). The ignored census, run by hand as above:
|
||||
1 passed in 32 s.
|
||||
|
||||
**2026-09-23 (dev, M2 rework after QA).** The lead's rulings on the QA
|
||||
findings, as applied; every `qa_m2.rs` test is un-ignored and green (32).
|
||||
|
||||
- **1 (blocking) — ruled: the whole set.** `tools/nav.rs::all_files`
|
||||
replaces `in_scope`; `leaves_file` and `spelled_at` are gone (nothing else
|
||||
used them). The false "declared outside the files lucisv indexes"
|
||||
refusal went with the narrowing. Wire test
|
||||
`references_reach_bind_connections_hierarchical_tails_and_class_members`
|
||||
now also asks from the use sites (`top.sv:8` tail, `env.sv:4` handle
|
||||
chain) and asserts the declaration's answer. Handshake MCP-7 filed;
|
||||
opentitan timings below.
|
||||
- **2 + 3 (blocking) — fixed.** The selector moved to a new
|
||||
`tools/select.rs` (nav.rs had reached 446 lines); `select.rs::on_line`
|
||||
picks by token and refuses a name found only in a macro argument.
|
||||
- **4 (blocking) — fixed.** `hierarchy.rs`: `Child::first` (the statement's
|
||||
first instance name) ends the override slice; `Child::of` builds both
|
||||
directions' children. Unit test extended with `#(.W(2)) u_a (), u_b ()`.
|
||||
- **5 — ruled: whole-tree semantics kept.** Tool description and
|
||||
Assumptions say so; no code change. `qa_finding_5_…` was written to
|
||||
assert single-file parity "delete it if the project-wide semantics is
|
||||
kept": I rewrote it (renamed
|
||||
`qa_finding_5_one_files_diagnostics_match_lucisv_check_of_the_whole_tree`)
|
||||
to assert the ruling — `unknown-port` reported for `top.sv` alone —
|
||||
rather than delete it, so the ruling stays pinned.
|
||||
- **6 — fixed.** `diagnostics.rs`: `Run::used` (a `RefCell<WaiverUse>`)
|
||||
merges every file's usage; `Runs::unused_waivers` reports after the
|
||||
whole-project loop; `lint_finding` takes a `LineIndex` so a waiver file's
|
||||
findings render like any other. `Runs::held` became a `BTreeMap` so the
|
||||
order is stable.
|
||||
- **7 — fixed.** `tools/mod.rs`: `Ty::Range { min, max }` (schema
|
||||
`minimum`/`maximum`, refusal "an integer from 1 to 20"); `hierarchy`'s
|
||||
`depth` uses it and the silent `.min(MAX_DEPTH)` is gone. `wire.rs`'s
|
||||
depth-99 call became 20 plus a 21-is-refused assertion; `tools/mod.rs`
|
||||
unit test pins the schema.
|
||||
- **8 — fixed.** `select.rs::at_column` refuses "line N is L bytes long;
|
||||
`col` C is past its end".
|
||||
- **9 — fixed.** `nav.rs::engine_refusal` prefixes and rewords the
|
||||
engine's six rename-worded sentences (`vlog_refactor` untouched); unit
|
||||
test `engine_refusals_are_prefixed_and_never_speak_of_renaming`. A bare
|
||||
macro-only `name` is now refused as a macro too (QA's side note).
|
||||
- **10 — fixed.** `resources.rs` rewrites the "pass `file`" clause.
|
||||
QA's test asserts the message does not contain `` `file` `` (backticked),
|
||||
so the wording is "with its file argument" rather than the lead's
|
||||
backticked `` `file` `` — same meaning, test and ruling both honoured.
|
||||
- **11 (blocking) — fixed.** `select.rs::one_use` resolves every use of the
|
||||
name in a file that declares none (`Analysis::external` +
|
||||
`definition_of`); two or more distinct targets are refused listing a
|
||||
line per target.
|
||||
|
||||
Whole-set `references` on opentitan (release, stdio driver, after the
|
||||
index): `entropy_masking_req` 1.62 s, `state_q` 1.92 s / 1.89 s, `aes` at
|
||||
`tb.sv:45` 1.70 s, `clk_i` from `prim_fifo_sync.sv` 2.55 s; debug (the
|
||||
census test): 9.8 s, 12.1 s, 10.9 s, 14.2–14.6 s. Answers unchanged from
|
||||
the narrowed ones on every census symbol (6, 5, 14, 12 hits; the census
|
||||
test's assertions still pass). The census test: 1 passed in 72 s; `git
|
||||
status --porcelain` of the checkout byte-identical before and after.
|
||||
|
||||
Sizes after the rework (same awk rule): `tools/nav.rs` 343,
|
||||
`tools/select.rs` 177 (new), `tools/hierarchy.rs` 316,
|
||||
`tools/diagnostics.rs` 313, `tools/mod.rs` 151, `resources.rs` 118; the
|
||||
rest unchanged. No function over 45 lines.
|
||||
|
||||
Gates (through `tools/guard.sh`, one cargo invocation at a time):
|
||||
`cargo fmt -p lucisv_mcp -- --check` exit 0; `cargo clippy -p lucisv_mcp
|
||||
--all-targets` `Finished`, no warnings; `cargo test -p lucisv_mcp` unit 38
|
||||
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**.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-23 (QA, M2). Verdict: rework needed** — four blocking findings
|
||||
(1, 2, 4, 11: wrong or partial answers), seven non-blocking. No crash, no
|
||||
hang, no write: every attack was answered, the server kept answering after
|
||||
each refusal, and opentitan's `git status --porcelain` was byte-identical
|
||||
before and after the whole session (the owner's three modified files).
|
||||
|
||||
Method: every attack against the real binary over scratch trees
|
||||
(`crates/lucisv_mcp/tests/qa_m2.rs`, 32 tests: 20 green, 12
|
||||
`#[ignore = "QA finding N"]` asserting the correct behaviour, each confirmed
|
||||
failing for the stated reason with `--ignored`). Where "the right answer"
|
||||
was in question, the oracle was `vlog_refactor::find_references` over the
|
||||
*whole* file set (a throwaway binary in the QA scratch directory, not in the
|
||||
tree) and `target/release/lucisv check` for diagnostics.
|
||||
|
||||
### Findings
|
||||
|
||||
**Blocking**
|
||||
|
||||
1. **`references` omits uses reached through a resolution-only file, and
|
||||
refuses from the use with a false sentence** (`tools/nav.rs:444-464`,
|
||||
`in_scope`). (a) `top2.sv: wire w2 = u_a.u_b.sig2;` where `mid.sv`
|
||||
(`leaf u_b`) never writes `sig2`: `references {name: sig2, unit: leaf}`
|
||||
answers only `leaf.sv:2:9`; the whole-set engine also lists
|
||||
`top2.sv:4:21` (and drops it when `mid.sv` is removed from its set — the
|
||||
narrowing is the cause). (b) The class case the brief lists: `e.s.count`
|
||||
in `t.sv`, with `env.sv` (`sb s;`) never writing `count` — same omission.
|
||||
From the use (`{file: t.sv, line: 4, name: count}`) `references` is
|
||||
refused: "`count` is declared outside the files lucisv indexes, so a
|
||||
rename here would only be half a rename" — the declaration *is* indexed
|
||||
(`definition` finds it). The README's known limit names only a struct
|
||||
typedef; multi-level hierarchical tails and UVM handle chains
|
||||
(`cfg.agent_cfg.x`) are the common case. Tests
|
||||
`qa_finding_1_a_two_level_tail_to_an_internal_net_is_a_reference`,
|
||||
`qa_finding_1_a_class_handle_chain_through_a_third_file_is_a_reference`.
|
||||
Suggested fix (for the lead to rule, it touches the narrowing ruling):
|
||||
add the files that resolve the path — for a member of a unit, the
|
||||
up-closure of the unit's instantiating files (`instantiations_of(owner)`
|
||||
→ `edge.file`, recursively over `edge.owner.name`); for a class member,
|
||||
the files declaring the types/classes the selected files name, to a
|
||||
fixed point — or fall back to the whole indexed set for names off the
|
||||
connection surface. At minimum an engine refusal on a narrowed set must
|
||||
not be reported as "declared outside the files lucisv indexes".
|
||||
2. **`file` + `line` + `name` inside a macro call's argument answers the
|
||||
macro's `define`** (`tools/nav.rs:142-149` via `source::word_in`, then
|
||||
`at_position:233-239`). `top.sv:5` is ``assign peek = `ID(u_core0.state_q);``;
|
||||
`definition {file: top.sv, line: 5, name: state_q}` answers
|
||||
`defs.svh:1:9 define: `define ID(x) x` — a declaration of a different
|
||||
name. Test `qa_finding_2_…`. Fix: pick the occurrence by token — the
|
||||
first identifier token on the line spelling `name` (a macro token only
|
||||
when `name` is `` `NAME``); when the word is only inside a macro token,
|
||||
refuse naming the macro. The same change fixes finding 3.
|
||||
4. **`hierarchy` overrides of the 2nd+ instance of one statement include
|
||||
the earlier instances** (`tools/hierarchy.rs:359-367`). `leaf #(.W(2))
|
||||
u_a (), u_b ();` → `u_b : leaf #(.W(2)) u_a (),` (down, and `ov.u_b
|
||||
#(.W(2)) u_a (), ov.sv:4` up; the JSON `overrides` likewise). The
|
||||
README's "`sub u1 (), u2 ();` shows the one `#(...)` on both instances"
|
||||
holds only when there are no overrides. Test `qa_finding_4_…`. Fix: end
|
||||
the slice at the edge's *first* instance name (carry it in `Child`), or
|
||||
take the balanced `#( … )` after the module name.
|
||||
11. **`file` + `name` guesses when the file's uses resolve to different
|
||||
declarations** (`tools/nav.rs:178-181`, `first_occurrence`). `top3.sv`
|
||||
declares no `sig`; `u.sig` names `leaf`'s and `v.sig` names `other`'s.
|
||||
`definition {file: top3.sv, name: sig}` answers `leaf.sv:1:27` alone
|
||||
and `references` lists only `leaf`'s — a pick, where the brief and the
|
||||
tool description say "ambiguity is a list, never a guess". Test
|
||||
`qa_finding_11_…`. Fix: when the file declares nothing, resolve every
|
||||
use of `name`; more than one distinct target → refuse listing the lines
|
||||
(as the declared-twice rule does).
|
||||
|
||||
**Non-blocking**
|
||||
|
||||
3. `file` + `line` + `name` takes the first *textual* occurrence, so one in
|
||||
a comment or string hides the code one: `/* q */ assign q = a;` →
|
||||
"nothing at m.sv:2:6 names a declaration" (also `"a" == a`). Same place
|
||||
and fix as 2. Test `qa_finding_3_…`.
|
||||
5. **One file's `diagnostics` ≠ `lucisv check <file>`** — the brief's
|
||||
parity criterion. `diagnostics.rs:149` always passes `workspace = true`
|
||||
to `select_rules`, so the workspace rules (`unknown-port`,
|
||||
`unused-signal`, `undeclared-identifier`, …) run for one file, where the
|
||||
CLI runs them only when its run holds more than one file. Differences on
|
||||
opentitan: `hw/ip/aes/dv/sva/aes_idle_check.sv` 17:28 unused-signal,
|
||||
`hw/ip/aes/pre_dv/aes_sbox_tb/rtl/aes_sbox_tb.sv` 118:6 unknown-port,
|
||||
`hw/ip/i3c/rtl/i3c_dat.sv` 134:17 unused-signal,
|
||||
`hw/ip/kmac/rtl/sha3pad.sv` 776:37 unused-signal,
|
||||
`hw/ip/entropy_src/pre_dv/entropy_src_tb.sv` 339:9 and 340:9
|
||||
unknown-port — each one exactly what `lucisv check .` reports for that
|
||||
file. Arguably the better answer (the project exists); it needs a lead
|
||||
ruling and a sentence in the tool description and README either way.
|
||||
Test `qa_finding_5_…` (asserts CLI single-file parity; delete it if the
|
||||
project-wide semantics is kept).
|
||||
6. **Unused external waivers are not reported** (`diagnostics.rs:215`
|
||||
discards `lint_with`'s used-waiver answer). A `[lint] waivers` directive
|
||||
matching nothing: `lucisv check .` (and `check m.sv`) report
|
||||
`w.waiver:1:1 unused-waiver`; `diagnostics` says "no findings". Test
|
||||
`qa_finding_6_…`.
|
||||
7. `hierarchy` `depth` above 20 is silently the same as 20: the schema has
|
||||
no `maximum` (`Ty::Int` has only `min`), and a node cut by the depth
|
||||
limit looks like a leaf. `hierarchy.rs:50-55,120`. Test `qa_finding_7_…`.
|
||||
The brief's "depth 21 → schema refusal" is not what happens; 0 and
|
||||
negative are refused.
|
||||
8. A `col` past the end of its line is clamped to the line end
|
||||
(`LineIndex::offset`), and the refusal names the clamped column
|
||||
(`col: 99` → "nothing at clamp.sv:2:15 …"). `nav.rs:135-141`. No wrong
|
||||
answer found (the clamped offset sits after the last token), but the
|
||||
agent is told about a position it did not ask for. Test `qa_finding_8_…`.
|
||||
9. `references` refusals pass the rename engine's sentences through: "there
|
||||
is no symbol to rename at this position" (whitespace, a keyword, a
|
||||
comment) and "… a rename here would only be half a rename".
|
||||
`nav.rs:394`. Test `qa_finding_9_…`. Also a by-name `references
|
||||
{name: ONLY_MAC}` says "no declaration … is indexed" where the position
|
||||
form says "is a macro … (`defines` lists …)".
|
||||
10. `lucisv://unit/{name}` for an ambiguous unit is `-32002` (correct) but
|
||||
the reason says "pass `file` to pick one", which a URI cannot.
|
||||
`resources.rs:94` (the text is `unit_interface`'s). Test
|
||||
`qa_finding_10_…`.
|
||||
|
||||
### Verified (green `qa_*` tests)
|
||||
|
||||
- Selectors: a package member through `import p::*` and through `p::PW`
|
||||
(definition + 4 references from either end); a `bind` connection's bare
|
||||
name (`bind core chk u_chk (.s(state_q))` → `core.sv:2:9`, 4 uses from
|
||||
the bind side and the declaration side); one- and two-level tails to a
|
||||
*port* (`u_a.u_b.sig` → `leaf.sv:1:44`, listed in references); the
|
||||
port-that-is-a-net lists header, body and `wire` (never picks), references
|
||||
4; a class member declared in two classes lists both, `references`
|
||||
refuses naming both, `unit` picks; a name declared twice in one file is
|
||||
refused with its lines; an escaped identifier by name and by position;
|
||||
a macro-only name by name, `` `NAME`` and position, `references` refuses
|
||||
it with the pointer to `defines`; whitespace, a keyword, a comment:
|
||||
clean refusals; `line: 0` a schema refusal; past EOF and `5 000 000 000`
|
||||
refused; a column inside the two bytes of `é` refused (no panic, server
|
||||
alive); byte columns after a multibyte comment (`zz` at 29, not 27) and
|
||||
in a CRLF file; `unit` that does not exist refused naming it.
|
||||
- `references`: a comment and a string in a third file never reported;
|
||||
paging `limit`/`offset` with `total` constant and an offset past the end
|
||||
empty; `include_declaration: false` (also cross-file, from the use).
|
||||
- `hierarchy`: a `generate`-self-instantiation and mutual recursion
|
||||
terminate (`(recursive)`, both directions); a 30-deep chain stops at 20;
|
||||
`depth` 0, -1, 2.5, "3" and `direction` `Up`/`sideways`/`""` refused by
|
||||
the schema; a package, a class and an unknown name as `root` refused; a
|
||||
module declared twice marked `(declared 2 times)` and not expanded; `up`
|
||||
from a leaf with two parents lists both; overrides with a `/* … ) … */`
|
||||
comment, a `// … )` comment, `c#(4)::N` and a string holding `u_x (` are
|
||||
sliced right; 250 × 250 instances stop at 50 000 nodes with `cut: true`.
|
||||
- `diagnostics`: `[lint] select`, `ignore`, `[lint.line-length] length`
|
||||
and a waiver file honoured under the root config, and a file under
|
||||
`b/lucisv.toml` gets that config's own select and top-level
|
||||
`line-length = 60`; `rules` replaces select while the config's `ignore`
|
||||
still applies (as the CLI's `pick`); `severity` filters; parse errors
|
||||
first, then lint, in a file with both; the project form's pages
|
||||
concatenate to the whole list with a constant `total`; a bad option
|
||||
(`length = 30`) refused naming `lucisv.toml:5`; an unknown rule refused.
|
||||
Every expected string was checked against `lucisv check` on the same tree.
|
||||
- `defines`: a macro defined in two files lists both (and `definition` at
|
||||
a use lists both, never picks); a parameterised multi-line body
|
||||
one-lined; an unknown name "no defines"; `file` + `name` filters that
|
||||
file's table (with its `` `undef``); a missing file refused.
|
||||
- Resources: `resources/templates/list` entries carry `uriTemplate`, `name`,
|
||||
`mimeType` (and `title`, `description`); `%20`, `%C3%BC` and `%25` decode;
|
||||
an ambiguous unit, a bad escape (`%`, `%FF`), `..%2F..`, an absolute path
|
||||
outside the root, a directory, a symlink leading out, `LUCISV://`, a query
|
||||
string: all `-32002`, never a crash; a non-string `uri` `-32602`.
|
||||
- Freshness: an edit shows in the next `references` and `hierarchy`; a
|
||||
deleted declaring file makes the root refused and its instance
|
||||
`(not indexed)`; a new file is seen after a miss-walk (M1's 5 s rule
|
||||
otherwise).
|
||||
|
||||
### CLI-vs-MCP diagnostics (opentitan, release builds, no lucisv.toml)
|
||||
|
||||
- Single files, (rule, line, col) sets: `hw/ip/aes/rtl/aes.sv` 0 = 0,
|
||||
`aes_core.sv`, `aes_cipher_core.sv`, `uart_core.sv`, `prim_fifo_sync.sv`,
|
||||
`aes_env_pkg.sv`, `tb.sv` 0 = 0; `aes_scoreboard.sv` 4 = 4,
|
||||
`uartdpi.sv` 4 = 4, `aes_env_cfg.sv`, `dv_utils_pkg.sv`,
|
||||
`aes_base_vseq.sv` 1 = 1 — identical. The five files of finding 5 differ.
|
||||
- Whole project: MCP `diagnostics` 2 102 in 1.77 s vs `lucisv check .`
|
||||
1 158 in 0.92 s. Lint findings identical except the symlink
|
||||
`hw/ip/tlul/rtl/tlul_adapter_shim.sv → tlul_adapter_vh.sv` (the MCP
|
||||
lints the canonical path, M1's ruling, so the CLI's `module-filename` on
|
||||
the shim name has no MCP twin). The other 941 are `parse-error`, which
|
||||
`lucisv check` does not report at all (by the plan).
|
||||
|
||||
### opentitan (release, 3 944 files)
|
||||
|
||||
Index 1.8 s; `references clk_i` from `prim_fifo_sync.sv` 1.60 s (83 hits)
|
||||
and from `tb.sv` (first occurrence = `key_sideload_if`'s port, 5 hits)
|
||||
1.58 s — the huge-census case is bounded as the README says. The generate-
|
||||
scope path `aes_bind.sv:58 …gen_masks.u_aes_prng_masking.u_prim_bivium.
|
||||
state_q` is not among `prim_trivium`'s `state_q` references, but the
|
||||
whole-set engine over 472 aes/prim/tlul files does not list it either: an
|
||||
engine limit, not the narrowing. The dev's census test: 1 passed in
|
||||
32.7 s (debug).
|
||||
|
||||
### Sizes and style
|
||||
|
||||
Production lines (non-blank, not starting with `//`, before the first
|
||||
`#[cfg(test)]`, one awk rule for all): `tools/nav.rs` 446,
|
||||
`tools/hierarchy.rs` 311, `tools/diagnostics.rs` 293, `tools/defines.rs`
|
||||
158, `tools/source.rs` 134, `resources.rs` 112, `tools/mod.rs` 146,
|
||||
`rpc.rs` 241, `project/analysis.rs` 77, `tools/read_item.rs` 213,
|
||||
`main.rs` 68 — the dev's numbers, all under 600. No function over 40 lines
|
||||
(brace-matched scan). No `unwrap`/`expect`/`panic!` outside `#[cfg(test)]`,
|
||||
no `#[allow]`, no `unsafe`.
|
||||
|
||||
### Gates (through `tools/guard.sh`, one cargo invocation at a time)
|
||||
|
||||
- `cargo fmt -p lucisv_mcp -- --check` → exit 0
|
||||
- `cargo clippy -p lucisv_mcp --all-targets` → `Finished`, no warnings
|
||||
- `cargo test -p lucisv_mcp` → unit 37 passed; `opentitan` 0 passed, 1
|
||||
ignored; `qa_m1` 51 passed; `qa_m2` 20 passed, 12 ignored; `wire` 19
|
||||
passed
|
||||
- `cargo test --workspace` (before finding 11's ignored test was added) →
|
||||
exit 0, **4 586 passed, 0 failed, 58 ignored** (4 566 + 20 QA; 47 + 11)
|
||||
- `LUCISV_OPENTITAN=… cargo test -p lucisv_mcp --test opentitan --
|
||||
--ignored` → 1 passed in 32.7 s; checkout status byte-identical
|
||||
- No guard kill.
|
||||
|
||||
TODO-MCP M2 QA box left unticked (rework needed).
|
||||
|
||||
**2026-09-23 (QA, M2 re-check after the rework). Verdict: pass.** All
|
||||
eleven findings are fixed or pinned under the lead's rulings; no new
|
||||
finding. Every earlier `qa_finding_*` test is un-ignored and green with
|
||||
its assertion unchanged, except finding 5's, which the dev rewrote to pin
|
||||
the ruling. It now asserts that one file's `diagnostics` reports
|
||||
`unknown-port` for `top.sv`, as `lucisv check .` does and `lucisv check
|
||||
top.sv` does not. That is exactly the ruling. QA added
|
||||
`qa_recheck_one_files_diagnostics_are_its_lines_of_lucisv_check_dot`, which
|
||||
pins the whole text line (`2:12 error … [unknown-port]`, and nothing for
|
||||
`leaf.sv`) rather than a substring. Finding 10's new wording, "call the
|
||||
unit_interface tool with its file argument to pick one", is acceptable: it
|
||||
names the tool that can pick, and it no longer suggests that the URI takes
|
||||
an argument.
|
||||
|
||||
Re-derived by hand (release binary, scratch trees, then pinned):
|
||||
|
||||
- **1**: the two-level tail `u_a.u_b.sig2` gives the same 3 locations
|
||||
(`leaf.sv:2:9`, `top2.sv:3:21`, `top2.sv:4:21`) from the bare name, from
|
||||
the declaration, and from each of the two uses. The class chain gives the
|
||||
same 4 (`sb.sv:2:7`, `sb.sv:3:24`, `t.sv:4:9`, `t2.sv:3:33`) from the bare
|
||||
name, the declaring file's own use, `e.s.count` and `e2.s.count`. Both
|
||||
lists equal the whole-set oracle (`find_references` over every file).
|
||||
- **2+3**: in `/* q */ initial $display("q"); assign r = `ID(q); assign q = a; // q`
|
||||
the selector picks the code `q` at column 60. `references` lists it with
|
||||
the declaration and the two uses on line 5. A line whose `q` is only in
|
||||
strings: "not written on line 6". `` `ID(q)`` alone on its line and `a`
|
||||
only inside `` `ID(a)`` are refused as "inside a macro argument" by both
|
||||
tools, while `q` elsewhere on line 5 and `` `ID`` are still found.
|
||||
- **4**: three instances in one statement with overrides (`#(.W(2)) u_a,
|
||||
u_b, u_c`) each show `#(.W(2))`. Three without overrides show none. A
|
||||
statement whose `#(` … `)` spans three lines, with a `// three` comment,
|
||||
a `/* between ) , */` comment between instances and the last instance
|
||||
after a leading comma, shows `#( .W(3) )` on all three, down and up. Two
|
||||
separate statements of the same module in one owner keep their own
|
||||
`#(.W(4))`/`#(.W(5))`, and an instance array has none.
|
||||
- **11**: three uses naming three declarations (`l1`, `l2`, `l3`) are
|
||||
refused by both tools with "`sig` on line 3 → l1.sv:1, line 7 → l2.sv:1,
|
||||
line 12 → l3.sv:1; add `line`". `line: 7` then answers `l2.sv:1:25`. Two
|
||||
uses of one declaration answer it. A use of a module declared twice lists
|
||||
both declarations. On opentitan, `references {file: hw/ip/aes/dv/tb/tb.sv,
|
||||
name: clk_i}` now refuses, naming `key_sideload_if.sv:8` (line 35) and
|
||||
`aes.sv:42` (line 46). Before the rework it silently picked the first.
|
||||
|
||||
New attacks (11 `qa_recheck_*` tests, all green): the four hand
|
||||
derivations above; `depth` schema `minimum` 1 / `maximum` 20, where 20
|
||||
walks 20 levels and 21 is refused "from 1 to 20"; `col` on the last byte
|
||||
and one past it are positions, two past is refused "line 2 is 13 bytes
|
||||
long" (CRLF line) or "line 3 is 9 bytes long" (a last line with no
|
||||
newline); `references` from a file the walk skips (a gitignored `.sv` and
|
||||
a `notes.txt`) answers the real uses, including the file asked from,
|
||||
while the by-name answer stays the indexed files, and a path that does not
|
||||
exist is refused naming it, never a crash; whole-set `references` after
|
||||
deleting one file mid-session drops its hit, and after deleting the
|
||||
declaring file the refusal is prefixed "lucisv cannot follow this position:"
|
||||
with no "rename"; unused waivers match `lucisv check .` (one
|
||||
`unused-waiver` at `w.waiver:1:1`; a waiver file named by two configs is
|
||||
read once; `rules: no-tabs` reports nothing, as `--select no-tabs .` does;
|
||||
the per-file form reports none, as ruled).
|
||||
|
||||
Observation for the lead (not a finding): the coordinator's brief expected
|
||||
`references` from a file that is not indexed to be a clean refusal. It
|
||||
answers instead. That is consistent with M1's path rule (`outline`,
|
||||
`definition` and `diagnostics` all read any file inside a root), and the
|
||||
answer is correct. If a refusal is wanted, that is a ruling for all the
|
||||
tools, not a fix in `references`.
|
||||
|
||||
opentitan (release, whole-set `references`): `clk_i` from
|
||||
`prim_fifo_sync.sv` 2.37 s, 83 hits, the same count as the narrowed answer.
|
||||
The dev's census test: 1 passed in 73.1 s (debug; per-call 9.8–14.9 s for
|
||||
the five `references` calls). `git status --porcelain` of the checkout was
|
||||
byte-identical before and after, and identical to the first QA pass's
|
||||
snapshot.
|
||||
|
||||
Sizes (same awk rule): `tools/nav.rs` 343, `tools/select.rs` 177,
|
||||
`tools/hierarchy.rs` 316, `tools/diagnostics.rs` 313, `tools/mod.rs` 151,
|
||||
`resources.rs` 118. The rest are unchanged. No function over 45 lines. No
|
||||
`unwrap`/`expect`/`panic!`/`#[allow]`/`unsafe` outside `#[cfg(test)]`.
|
||||
|
||||
Gates (through `tools/guard.sh`, one cargo invocation at a time, no guard
|
||||
kill):
|
||||
|
||||
- `cargo fmt -p lucisv_mcp -- --check` → exit 0
|
||||
- `cargo clippy -p lucisv_mcp --all-targets` → `Finished`, no warnings
|
||||
- `cargo test -p lucisv_mcp` → unit 38 passed; `opentitan` 1 ignored;
|
||||
`qa_m1` 51 passed; `qa_m2` 43 passed, 0 ignored; `wire` 19 passed
|
||||
- `cargo test --workspace` → exit 0, **4 610 passed, 0 failed, 47 ignored**
|
||||
(the dev's 4 599 + 11 re-check tests)
|
||||
- `LUCISV_OPENTITAN=… cargo test -p lucisv_mcp --test opentitan --
|
||||
--ignored` → 1 passed in 73.1 s; checkout status byte-identical
|
||||
|
||||
TODO-MCP M2 QA box ticked.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-09-23.** Read every source file after the rework. The one
|
||||
ruling worth restating: the reference-narrowing rule in PLAN §2.1 was
|
||||
mine and it was wrong — a two-level tail or a class-handle chain resolves
|
||||
through files that never spell the name, so `references` now hands the
|
||||
engine the whole indexed set (≈ 2 s on opentitan) and MCP-7 asks
|
||||
`vlog_refactor` for a `KnownFacts` variant so M6 can feed cached records.
|
||||
Correctness first; the census will show whether 2 s matters to an agent.
|
||||
Other rulings: `diagnostics` matches `lucisv check .` (the whole-tree
|
||||
run — "what will CI say"); a name on a line is chosen by token, never by
|
||||
text; `hierarchy` overrides belong to the statement, so every instance of
|
||||
one statement shows them; `depth` is 1..=20 in the schema; every read
|
||||
tool reads any file inside a root, indexed or not (QA's closing question —
|
||||
kept, the answer is correct and the rule is M1's). Missing-closer warnings
|
||||
and one-step macro expansion are not offered (server-only code; MCP-5
|
||||
filed). MCP-6 — the LSP omits three real `aes` instantiations in the
|
||||
`*_pd_main.sv` tops — is a possible LSP bug to file in TODO.md at the end
|
||||
of the block. Committed as M2.
|
||||
@@ -0,0 +1,379 @@
|
||||
# mcp-read-tools
|
||||
|
||||
TODO-MCP.md **M1** (second half) — the six read tools of `lucisv-mcp`:
|
||||
`project_overview`, `list_units`, `unit_interface`, `outline`, `read_item`,
|
||||
`search_symbols`. Design: `docs/mcp/PLAN.md` §4.3 and §4.5. The transport,
|
||||
handshake and `Project` they run on are `docs/features/mcp-transport`.
|
||||
|
||||
## Goal
|
||||
|
||||
Let an agent learn what a Verilog/SystemVerilog tree contains, and what one
|
||||
unit offers, in a few hundred tokens instead of reading files: which units
|
||||
exist and where, a module's ports and parameters with a paste-ready
|
||||
instantiation, a file's outline, one item's exact text, a fuzzy symbol
|
||||
search. Every answer is a composition of existing library queries plus
|
||||
rendering; no language knowledge lives in the MCP crate.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Every tool is read-only**: `annotations {readOnlyHint: true,
|
||||
destructiveHint: false, idempotentHint: true, openWorldHint: false}`, and
|
||||
every `inputSchema` is closed (`additionalProperties: false`) with its
|
||||
`required` list. The schema and the argument validation come from one
|
||||
table (`tools::Param`), so they cannot disagree.
|
||||
- **`program` is told apart by its keyword.** `vlog_semantic` models a
|
||||
`program` as a `Module` (`docs/features/interface-semantics`). The tools
|
||||
read the keyword off the text between the declaration's start and its
|
||||
name — only for files whose text spells `endprogram`, recorded when the
|
||||
file is read, so a design without programs pays nothing.
|
||||
- **Classes inside packages are units too**, listed as `pkg::cls`
|
||||
(`list_units`, `unit_interface` accept that spelling). File-scope classes
|
||||
are listed by their own name.
|
||||
- **`search_symbols` is `WorkspaceIndex::workspace_symbols`**: units and the
|
||||
connection-surface members (ports, parameters, package and class members),
|
||||
case-insensitive substring. A module's internal nets are not in it by the
|
||||
index's own design; the description says so and points at `outline`. A
|
||||
hit carries its file and line and **no column** (rework, finding 4): the
|
||||
index records a column only for units and only in UTF-16 units, and the
|
||||
server prints one column unit everywhere (below). A miss walks the roots
|
||||
once before it is answered (finding 3).
|
||||
- **`read_item`'s slice** is the parser's `Item` node that declares the
|
||||
name (attributes included, leading comments not); for a declaration a
|
||||
larger construct merely contains — an ANSI port in a module header, a
|
||||
header parameter, a function argument — the declaration's own span; for a
|
||||
non-ANSI port, its body declaration. A multi-name declaration
|
||||
(`logic q, r;`) is one item for either name. `name@LINE` picks among
|
||||
same-named declarations; `always@LINE` (also `initial`, `final`,
|
||||
`assign`) picks the unlabelled item whose lines cover LINE, any
|
||||
`always_*` flavour included. `@LINE` is the last `@` followed only by
|
||||
digits, and `kind:` is a prefix only when it is one of the kind words
|
||||
`render::kind` produces; otherwise `@` and `:` belong to the name, so the
|
||||
escaped identifiers `\a@b` and `\k:l` are selectable as written, and
|
||||
`\a@b@1` is `\a@b` on line 1 (rework, finding 5). M4's `replace_item` is specified to replace
|
||||
exactly this slice, so the slicer (`tools/read_item.rs::select`) is
|
||||
public to the crate.
|
||||
- **`unit_interface` ports come from `vlog_refactor::instantiation_plan`**
|
||||
(the same plan the editor's instantiate completion uses), with the packed
|
||||
range split off the type in `structuredContent` (`type`, `range`) and the
|
||||
unpacked dimensions an ANSI port writes after its name read off the
|
||||
declaration (`unpacked`). A non-ANSI port's unpacked dimensions are not
|
||||
reported (its name sits in the header, its dimensions in the body, and
|
||||
pairing them is the plan's job — see Handshakes). Parameters are the
|
||||
plan's: overridable ones only, defaults as written; a header `localparam`
|
||||
is not offered. A unit declared in several files is refused with every
|
||||
site listed until `file` picks one — never a guess. A class's `extends`
|
||||
is read off its own declaration in the file's tree, and a member counts
|
||||
only when it is declared inside the found declaration's span — two
|
||||
classes of one name in two packages never answer for each other
|
||||
(rework, finding 1). A name that finds nothing walks the roots once and
|
||||
is looked up again before the refusal (finding 3).
|
||||
- **Columns** are 1-based **byte** columns (`LineIndex::line_col`), the
|
||||
unit parse diagnostics and the CLI already print — the one unit the whole
|
||||
server prints or accepts (`docs/features/mcp-transport`, Assumptions).
|
||||
|
||||
### The rendering contract (PLAN §4.5, `render.rs`)
|
||||
|
||||
| rule | how |
|
||||
|---|---|
|
||||
| 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 |
|
||||
| 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 |
|
||||
|
||||
## Handshakes
|
||||
|
||||
Consumed: see `docs/features/mcp-transport/README.md` (one table for the
|
||||
crate). No library crate was modified.
|
||||
|
||||
Requests (informational, none blocking):
|
||||
|
||||
- **To `vlog_refactor` (candidate):** `PlanPort` carries the packed type but
|
||||
not the unpacked dimensions after the name; `unit_interface` reads them
|
||||
back off an ANSI declaration itself (`tools/interface.rs::unpacked`). A
|
||||
`PlanPort::unpacked` field would let a non-ANSI port report them too and
|
||||
retire that code.
|
||||
- **To `vlog_semantic` (candidate):** a `program` is indistinguishable from
|
||||
a `module` in `SymbolKind`; the tools re-read the keyword from the text.
|
||||
A `SymbolKind::Program` (or a flag on `Def`) would retire that, at the
|
||||
cost of a `FACTS_FORMAT` bump — not worth one on its own.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `project_overview` (roots, config, filelist, file count and skips,
|
||||
units by kind, index build time and age, top-level modules, ten
|
||||
largest files, warnings)
|
||||
- [x] `list_units` (`kind`, `glob`, `limit`, `offset`)
|
||||
- [x] `unit_interface` (`name`, `file`): parameters, ports, template,
|
||||
modports, package/class members, `extends`
|
||||
- [x] `outline` (`file`, `depth`, `limit`, `offset`) with parse errors
|
||||
- [x] `read_item` (`file`, `item`) with `name`, `kind:name`, `name@LINE`,
|
||||
`always@LINE`
|
||||
- [x] `search_symbols` (`query`, `limit`, `offset`)
|
||||
- [x] wire tests for every tool over the fixture tree
|
||||
(`crates/lucisv_mcp/tests/fixtures/design`, 7 files)
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-23 (dev, M1).**
|
||||
|
||||
Six tools in `crates/lucisv_mcp/src/tools/` — `read.rs` (overview,
|
||||
list_units, outline, search_symbols), `interface.rs` (unit_interface),
|
||||
`read_item.rs` (read_item and the slicer) — over the rendering helpers in
|
||||
`src/render.rs`. Fixture tree `tests/fixtures/design`: a package with a
|
||||
class, `leaf` (parameters, an unpacked port, an unlabelled `always_ff`),
|
||||
`top` instantiating `leaf` with `.*` and `bus_if`, `bus_if` with two
|
||||
modports, a file-scope class, a `program`, and a file with a parse error.
|
||||
|
||||
Deviations from the plan's tool table, each small and additive:
|
||||
|
||||
1. `limit`/`offset` on `list_units`, `outline` and `search_symbols` — PLAN
|
||||
§4.5 says every list is capped and pageable; the §4.3 table named only
|
||||
`search_symbols`'s `limit`.
|
||||
2. `unit_interface` takes an optional `file`: opentitan declares many
|
||||
modules twice (`prim_generic_*` vs technology variants); refusing without
|
||||
a way to choose would make the tool useless there.
|
||||
3. `read_item` accepts `name@LINE`, `initial@LINE`, `final@LINE` and
|
||||
`assign@LINE` besides the planned `always@LINE` — one grammar
|
||||
(`head@LINE`) rather than a special case.
|
||||
4. Classes and the `program` kind in `list_units` as above; tool `title`s
|
||||
(a `2025-06-18` field) on every tool.
|
||||
|
||||
Smoke on opentitan (read-only): `unit_interface prim_fifo_sync` over the
|
||||
whole checkout answers 6 parameters, 12 ports and the template in ~1.9 KB of
|
||||
text, 7 ms after the index exists; `project_overview` lists 1 278 modules,
|
||||
236 interfaces, 402 packages, 2 023 classes, 3 programs.
|
||||
|
||||
**2026-09-23 (dev, M1 rework after QA).** The lead's rulings on the QA
|
||||
findings, as applied to the read tools (the transport half is in
|
||||
`docs/features/mcp-transport`'s work log of the same date):
|
||||
|
||||
- **1 (blocking) — fixed.** `tools/interface.rs::members` keeps a member
|
||||
only when its `name_span` lies inside `found.def.decl_span` (same file as
|
||||
before), and `extends` comes from the new `class_base`, which finds the
|
||||
`ClassDecl` whose `name_span` is `found.def.name_span` in the file's own
|
||||
tree (walking with `read_item::child_items`, now `pub(super)`).
|
||||
`WorkspaceIndex::base_of` is no longer called.
|
||||
`qa_a_class_reports_its_own_base_not_a_same_named_class_s` and
|
||||
`qa_two_same_named_classes_in_one_file_do_not_share_members` un-ignored.
|
||||
- **3 — fixed.** `Project::ensure_walked_for_miss` (walks once unless this
|
||||
call already walked, reports whether it did); called by `unit_interface`
|
||||
when no declaration matches (`candidates` then `pick`, split from the old
|
||||
`find_unit`), by `list_units` when a `glob` matches nothing, and by
|
||||
`search_symbols` when the query has no hit. `read_item`/`outline` need
|
||||
no hook: `Project::resolve` and `Project::analysis` read the disk, not
|
||||
the index, so a new file already resolves and reads. Wire test
|
||||
`search_symbols_finds_units_and_members_by_substring` gained a brand-new
|
||||
file found by name; `qa_a_unit_written_just_now_is_found_by_name_without_a_walk_first`
|
||||
un-ignored.
|
||||
- **4 — fixed by removal.** `search_symbols` prints and returns no column
|
||||
(`tools/read.rs::search_symbols`; the `col` key is gone from
|
||||
`structuredContent`). `qa_columns_are_counted_in_one_unit_across_tools`
|
||||
un-ignored, and **its last assertion edited** to the ruling: it asserted
|
||||
`col == 17` (bytes), which removal cannot satisfy; it now asserts
|
||||
`line == 1` and no `col` key. Its first assertion (the parse error at
|
||||
byte column 28) is unchanged. `wire.rs`'s two search assertions dropped
|
||||
`col` likewise.
|
||||
- **5 — fixed.** `read_item::split_line` (the last `@` counts only when
|
||||
digits alone follow it; digits that overflow a `u32` say "out of range")
|
||||
and `render::is_kind_word` (a `KIND_WORDS` table, pinned against every
|
||||
`SymbolKind` by a unit test). The description names the `\a@b@1`
|
||||
spelling. `qa_an_escaped_name_holding_at_or_colon_is_selectable_by_itself`
|
||||
un-ignored. Note: the QA test selects `\a@b` with no line, which the
|
||||
plain "last `@`" rule would still have refused; the digits-only reading
|
||||
is what makes both it and the lead's `\a@b@1` work.
|
||||
- **6 — no action** (a library limit; QA's note stands).
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-23 (QA, M1 — the six read tools).** Verdict: **rework needed**
|
||||
— finding 1 is a wrong answer. Everything else below is non-blocking.
|
||||
Method and the protocol/freshness/roots half: `docs/features/mcp-transport`
|
||||
QA log of the same date; attacks pinned in
|
||||
`crates/lucisv_mcp/tests/qa_m1.rs`.
|
||||
|
||||
Verified correct (pinned by passing `qa_*` tests):
|
||||
|
||||
- An escaped-identifier unit (`\my-mod `): listed, `unit_interface` by its
|
||||
spelled name, a legal template (`\my-mod \u_my-mod (`), `read_item` of the
|
||||
module. A port with packed and unpacked ranges (`input logic [7:0] a
|
||||
[0:3]`, `output logic [3:0][1:0] b [2][0:1]`): `range` and `unpacked` both
|
||||
right, and the text row reads as declared. A header `parameter type T =
|
||||
logic [3:0]` and `parameter int unsigned N = 4` report their defaults; a
|
||||
header `localparam` is not offered.
|
||||
- CRLF: `outline` line ranges, `list_units` lines and `read_item`'s range
|
||||
are right, and `read_item`'s `structuredContent.text` is the exact bytes
|
||||
(`\r\n` kept, the module slice byte-equal to the file's). UTF-8 comments
|
||||
(`été`, `日本`) before items and on the item's own line: lines and slices
|
||||
right.
|
||||
- A module declared in two files: refused naming both `file:line` sites;
|
||||
`file` picks one; the top-module list names it once. A name declared twice
|
||||
in one file: `read_item` refuses with `var:w@1, var:w@3`, and `w@3`
|
||||
answers. `list_units` glob `d?p` matches `dup`, `d_p`, not `dp`/`duup`.
|
||||
`outline` `depth: 0` → `isError` naming `depth`; `limit: i64::MAX` and
|
||||
`offset: i64::MAX` are fine. `search_symbols` with `""` matches all 5
|
||||
symbols and pages with `… and 3 more`.
|
||||
- By hand on opentitan `hw/ip/aes`: `unit_interface aes_core` — all 18
|
||||
ports, in order, with direction and type (`logic [EntropyWidth-1:0]`,
|
||||
`keymgr_pkg::hw_key_req_t`, `aes_reg2hw_t`, …) match
|
||||
`rtl/aes_core.sv:30-57` line by line; 13 parameters with defaults, the
|
||||
header `localparam NumShares` rightly absent. `outline rtl/aes_core.sv`
|
||||
(`module aes_core 9-1145`, 284 entries, paged); `read_item
|
||||
always@346` returns exactly lines 346-358 (`key_init_reg`); `list_units
|
||||
kind=module` lists the 60-odd modules grouped by file. On `hw/`:
|
||||
`unit_interface prim_flop` refuses with its three technology variants.
|
||||
|
||||
Findings (this half; numbering shared with the transport log):
|
||||
|
||||
- **1 — BLOCKING (wrong answer): a class's `extends` and members come from
|
||||
the short name, so same-named classes answer for each other.**
|
||||
`tools/interface.rs:306` asks `index.base_of(name)` with the class's
|
||||
bare name; the index keys bases by bare name, so with `p1::c extends
|
||||
base1` and `p2::c extends base2` (different files) `unit_interface p2::c`
|
||||
says `extends base1`, and a file-scope `class c;` with no base says
|
||||
`extends base1` too. `tools/interface.rs:298-301` takes
|
||||
`index.members_of(name)` filtered by *file* only, so `package p1; class c;
|
||||
int a; …` and `package p2; class c; int b; …` in one file both list `a`
|
||||
and `b`. opentitan census (`--root hw`): 2 023 classes, 298 bare names
|
||||
shared by more than one class (`pwrmgr_env` ×4, `clkmgr_base_test` ×4 …);
|
||||
of the 728 such classes whose header fits one line, none answered a wrong
|
||||
base — the copies are per-top clones with the same base — so the bug is
|
||||
latent there, but any design reusing a class name with a different base
|
||||
(or none) gets a confident wrong `extends`. Repro: `qa_a_class_reports_its_own_base_not_a_same_named_class_s`,
|
||||
`qa_two_same_named_classes_in_one_file_do_not_share_members`. Suggested
|
||||
fix: read `extends` from the found file's own AST (the `ClassDecl` whose
|
||||
`name_span` is `found.def.name_span`), and keep a member only when its
|
||||
`name_span` lies inside `found.def.decl_span`. Small, MCP-side; a
|
||||
library-side key by qualified name would be a Handshake, not needed.
|
||||
- **4 — non-blocking (low): two column units in one server.**
|
||||
`tools/read.rs:421` reports `search_symbols` columns in UTF-16 units (the
|
||||
index's LSP positions) while `outline`'s parse errors use byte columns:
|
||||
in `/* é */ module pe; assign = ; endmodule` the parse error is `1:28`
|
||||
(bytes) and `pe` is `1:16` (UTF-16; `1:17` in bytes). The README states
|
||||
both, but an agent cannot tell which a number is. Repro:
|
||||
`qa_columns_are_counted_in_one_unit_across_tools` (asserts bytes; the
|
||||
dev may pick characters instead and update both sites and the test).
|
||||
- **5 — non-blocking (low): an escaped name holding `@` or `:` cannot be
|
||||
named alone.** `tools/read_item.rs:67` splits on the last `@` and `:79`
|
||||
on the first `:`, so `read_item \a@b` is "`@` must be followed by a line
|
||||
number" and `\k:l` is "no declaration matches `l` of kind `\k`".
|
||||
`\a@b@1` and `module:\k:l` work, but the description does not say so.
|
||||
Repro: `qa_an_escaped_name_holding_at_or_colon_is_selectable_by_itself`.
|
||||
Fix: when the head starts with `\`, split only after the escaped name's
|
||||
end (first whitespace, or the whole string).
|
||||
- **6 — informational (library, no MCP test): a module declared twice in
|
||||
one file is answered from the first silently.** `module x (input a);
|
||||
endmodule module x (input b); endmodule` in one file: the semantic layer
|
||||
keeps only the first (`outline` shows `port b` orphaned at depth 1), so
|
||||
`list_units` has one `x`, `unit_interface x` answers `input a`, and
|
||||
`read_item x` slices the first. Same root: an `` `ifdef``/`` `else``
|
||||
pair of alternative declarations shows only the first branch. Not the
|
||||
MCP's to fix; recorded because PLAN's "ambiguity is a list, never a
|
||||
guess" does not hold here.
|
||||
|
||||
Notes (no action asked): parameters report `name` and `default` as PLAN
|
||||
§4.3 says, not the type, so a `parameter type T` reads like a value
|
||||
parameter; a `type` column (from `vlog_refactor`'s plan) would cost
|
||||
little. `list_units`/`outline` with an `offset` past the end answer an empty
|
||||
text (not `no units match`); `structuredContent.total` still tells the
|
||||
truth. `x@99999999999` says "must be followed by a line number" (u32
|
||||
overflow).
|
||||
|
||||
Size and style (production lines = non-blank, non-comment, before
|
||||
`#[cfg(test)]`, measured by QA): `main.rs` 67, `transport.rs` 38, `rpc.rs`
|
||||
222, `render.rs` 97, `project/mod.rs` 212, `project/files.rs` 130,
|
||||
`project/analysis.rs` 52, `tools/mod.rs` 129, `tools/read.rs` 397,
|
||||
`tools/interface.rs` 285, `tools/read_item.rs` 199 — the dev's numbers,
|
||||
exactly. No function over 50 lines anywhere in the crate (largest: a
|
||||
41-line wire test). `unwrap`/`expect`: only in `#[cfg(test)]` blocks,
|
||||
`project/tests.rs` and the tests (`main.rs:115` is inside `mod tests`).
|
||||
No `panic!`, `unreachable!`, `todo!`, `#[allow]` or `unsafe`.
|
||||
|
||||
Gates (verbatim, all through `tools/guard.sh`):
|
||||
- `cargo fmt -p lucisv_mcp -- --check`: clean (exit 0) — after `rustfmt`
|
||||
on `qa_m1.rs` itself; the dev's files were already clean.
|
||||
- `cargo clippy -p lucisv_mcp --all-targets`: `Finished`, no warnings.
|
||||
- `cargo test -p lucisv_mcp`: unit `27 passed; 0 failed; 0 ignored`;
|
||||
`tests/qa_m1.rs` `30 passed; 0 failed; 10 ignored`; `tests/wire.rs`
|
||||
`11 passed; 0 failed; 0 ignored`. With `-- --ignored` on `qa_m1`:
|
||||
`0 passed; 10 failed` — each for its finding's reason.
|
||||
- `cargo test --workspace` (default guard, 8 GB / 1 800 s): exit 0 in
|
||||
3 min 53 s, summed over every binary **4 527 passed, 0 failed, 56
|
||||
ignored** (the dev's 4 497 / 46 plus this file's 30 / 10). No guard
|
||||
kill; the dev's one 30-minute kill did not reproduce (no concurrent cargo
|
||||
invocation was running).
|
||||
|
||||
|
||||
**2026-09-23 (QA, M1 re-check after the rework).** Verdict: **pass**, with
|
||||
one new non-blocking finding (11). Transport-side re-derivations (2, 3,
|
||||
10) and the check of the dev's edit to `qa_columns_…`: the transport QA
|
||||
log of the same date.
|
||||
|
||||
Re-derived by hand:
|
||||
|
||||
- **1** — `p1::c extends bp::base #(8)` with the base package in another
|
||||
file answers `extends bp::base` (the scope kept, the overrides dropped);
|
||||
`p2::c` with no base answers none, although its nested `class inner
|
||||
extends p1::c` has one — `class_base` matches the exact `name_span`;
|
||||
`p2::c`'s members are `b` and `inner`, not `inner`'s `z`; two `c`s in
|
||||
two packages of one file no longer share members.
|
||||
- **Same-named class twice in one package** (`class d extends lbase` then
|
||||
`class d extends other`): the semantic layer keeps only the first
|
||||
(outline shows the second's `y` orphaned) — finding 6's library limit,
|
||||
unchanged — and the answer is internally consistent: line 2, `extends
|
||||
lbase`, member `x`.
|
||||
- **5** — `\a@b`, `\k:l`, `module:\k:l`, `\port:q` (an escaped name
|
||||
whose text starts with a kind word) and `\a@12@2` all select; `w@3 `
|
||||
and ` always@4\t` select (the handler trims); `module:w` is refused "no
|
||||
declaration matches `w` of kind `module`"; `w@99999999999` says "line …
|
||||
is out of range"; `struct:w` (not a kind word) is read as a name and
|
||||
refused naming it.
|
||||
- **4** — `search_symbols` hits carry `line` and no `col` in both the JSON
|
||||
and the text, for a unit after a multibyte comment and for members.
|
||||
|
||||
New finding:
|
||||
|
||||
- **11 — non-blocking (low): an escaped name that ends in `@` and digits
|
||||
cannot be named alone.** `tools/read_item.rs::split_line` takes `\a@12`
|
||||
as `\a` on line 12, and `select` never tries the whole selector as a
|
||||
name, so `read_item \a@12` (a legal identifier `\a@12 `) is refused "no
|
||||
declaration matches `\a` on line 12" — true, but no hint. `\a@12@2`
|
||||
works, and the description documents the `\a@b@1` spelling, so the
|
||||
agent has a way out if it reads that far. Repro:
|
||||
`qa_rework_an_escaped_name_ending_in_at_digits_is_selectable_by_itself`
|
||||
(`#[ignore = "QA finding 11"]`, confirmed failing on the bare spelling).
|
||||
Suggested fix: when the `@LINE` reading matches nothing and the head
|
||||
starts with `\`, retry with the whole selector as the name. Related,
|
||||
cosmetic: whitespace around `@` (`w @7`, `always@ 8`) is not accepted.
|
||||
|
||||
New tests this round (`qa_rework_*`): a package-scoped base in another
|
||||
file plus a nested class; a class declared twice in one package; a
|
||||
symlinked directory leaving the root, a loop and an alias (dropped,
|
||||
warned, terminates); a real kind word of the wrong kind and an escaped
|
||||
name starting with a kind word; `@` selectors with trailing spaces,
|
||||
overflow and an empty line number; the escaped `@digits` name (ignored,
|
||||
finding 11); every by-name tool finding a file written just now; a
|
||||
legitimate miss not making later hits walk; search hits with a line and
|
||||
no column; a file that stops being UTF-8; a rename-over and a `cp -p`
|
||||
restore with an old mtime and the same size.
|
||||
|
||||
Gates (verbatim, all through `tools/guard.sh`, one cargo invocation at a
|
||||
time): `cargo fmt -p lucisv_mcp -- --check` exit 0; `cargo clippy -p
|
||||
lucisv_mcp --all-targets` `Finished`, no warnings; `cargo test -p
|
||||
lucisv_mcp` unit `28 passed; 0 failed`, `qa_m1` `50 passed; 0 failed; 1
|
||||
ignored`, `wire` `11 passed; 0 failed`; `cargo test --workspace` (default
|
||||
guard) exit 0 in 242 s, **4 548 passed, 0 failed, 47 ignored** (the dev's
|
||||
4 538 / 46 plus this round's 10 / 1). No guard kill.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-09-23.** The six tools read as the plan's table and the
|
||||
rendering follows §4.5 (paths once per group, `… and N more`, no prose).
|
||||
`unit_interface` refusing a name declared in several files with every site
|
||||
listed is the right posture for opentitan's per-top duplicates; the
|
||||
`file` argument is the escape hatch. The M1 QA round's class-base
|
||||
cross-contamination was the one wrong answer and is fixed at the
|
||||
declaration, where it belongs. Committed as M1; the token census (M6) will
|
||||
say whether the renderings are compact *enough*.
|
||||
@@ -0,0 +1,468 @@
|
||||
# mcp-transport
|
||||
|
||||
TODO-MCP.md **M1** (first half) — the `lucisv-mcp` binary, its argument
|
||||
contract, the stdio JSON-RPC transport, the MCP handshake and the
|
||||
`Project` behind every tool. Design: `docs/mcp/PLAN.md` §4.1, §4.2, §4.4.
|
||||
The read tools that sit on this transport are `docs/features/mcp-read-tools`.
|
||||
|
||||
## Goal
|
||||
|
||||
Give coding agents (Claude Code, Cursor, VS Code's agent mode) lucisv's
|
||||
project understanding over the Model Context Protocol, as a third binary
|
||||
that shares no code path with `lucisv-server` or the `lucisv` CLI. This
|
||||
feature is the plumbing every MCP tool stands on: a process an agent host
|
||||
can spawn, a handshake it recognises, a tool-call envelope, and a
|
||||
`Project` — roots, config, file set, workspace index, per-file analyses —
|
||||
that never answers from a file older than the disk was when the call
|
||||
arrived.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **No `rmcp`, no tokio, no new dependency.** MCP's stdio transport is one
|
||||
JSON-RPC message per line; `serde_json` (already pinned by the workspace)
|
||||
reads and writes it, and the envelope is a few `serde` structs in
|
||||
`rpc.rs`. The official Rust SDK brings an async runtime and a large
|
||||
transitive tree to what is one synchronous loop — the same reasoning that
|
||||
picked `lsp-server` over `tower-lsp` for the LSP. `serde` is used with its
|
||||
`derive` feature, which the lock already carried (no new crate in
|
||||
`Cargo.lock` beyond `lucisv_mcp` itself).
|
||||
- **Synchronous, one request at a time.** A request is answered before the
|
||||
next line is read, so pipelined requests are answered strictly in order.
|
||||
`notifications/cancelled` is accepted and ignored: a call cannot be
|
||||
interrupted, and the longest one is the first call's index build (1.6 s
|
||||
for all of opentitan, below).
|
||||
- **Protocol revisions pinned: `2025-11-25` (newest), `2025-06-18`.**
|
||||
Verified against modelcontextprotocol.io on 2026-09-23: the current
|
||||
revision is **`2026-07-28`**, and it is a different *era* — it removes the
|
||||
`initialize` handshake and carries the protocol version in every
|
||||
request's `_meta` (with `server/discover` and error `-32022`). The spec
|
||||
names everything up to `2025-11-25` "legacy" and says a legacy server
|
||||
answers the modern probe with any non-modern error, after which a
|
||||
dual-era client falls back to `initialize`. So this server is a legacy-era
|
||||
server by design: it echoes a client's `protocolVersion` when it is one of
|
||||
the two above and otherwise offers `2025-11-25`, and a `server/discover`
|
||||
probe (or any request before `initialize`) gets `-32002` "server not
|
||||
initialized", which is exactly the fallback signal. Serving the modern
|
||||
era is a separate piece of work (see Handshakes, *MCP-4*).
|
||||
- **Answers are from disk.** No unsaved editor buffer is ever seen. Every
|
||||
`tools/call` starts with a freshness sweep: one `stat` per indexed file
|
||||
(size + mtime); a file whose stamp moved is re-read and re-hashed, and only
|
||||
a changed hash re-indexes it; a missing file is removed and triggers a
|
||||
re-walk; the roots are re-walked when the last walk is older than 5 s and
|
||||
on every `project_overview`, so new files appear. All changes go into the
|
||||
index with one `absorb` (one merge). A file modified within 2 s of being
|
||||
read is re-read on every sweep until it settles — git's "racy clean" rule —
|
||||
so an edit that keeps a file's size inside one mtime tick is still seen.
|
||||
On Unix the stamp also holds the file's ctime and inode (the same
|
||||
`stat`), so a same-size rewrite that puts the old mtime back (`cp -p`,
|
||||
`rsync -t`, `touch -r`) is seen too; elsewhere they are 0 and size, mtime
|
||||
and the racy rule are all there is. A by-name lookup that finds nothing
|
||||
(`unit_interface`, `list_units` with a `glob`, `search_symbols`) walks
|
||||
once more before it answers, unless this call already walked
|
||||
(`Project::ensure_walked_for_miss`) — so a file the agent wrote a moment
|
||||
ago is found by name without waiting for the 5 s walk.
|
||||
- **The file set** is the editor's ladder minus the editor: `--filelist`,
|
||||
else the first root's configured `filelist`, else a walk of every root with
|
||||
`.gitignore` honoured, each root's `exclude` patterns, and a 1 MiB per-file
|
||||
cap. A filelist that does not read falls back to the walk with a warning.
|
||||
Every path is canonicalized (symlinks resolved) and deduplicated. A walked
|
||||
file whose canonical path lies outside every root (a symlink leading out)
|
||||
is dropped with one warning naming it — the same containment rule a path
|
||||
argument meets in `Project::resolve`; a `--filelist` entry is the user's
|
||||
own choice and stays. A file that is not UTF-8 is skipped, as the
|
||||
language server skips it, and named (root-relative) in
|
||||
`project_overview`'s warnings; that list is recomputed by every walk, so
|
||||
a file fixed later drops out of it and one broken later enters it.
|
||||
- **Roots** are canonicalized and deduplicated (the same directory given
|
||||
twice is one root, in first-given order); nested roots stay two roots.
|
||||
- **Columns**: every column the server prints or accepts is a **1-based
|
||||
byte column** — what `LineIndex::line_col` and the parser's diagnostics
|
||||
give. There is no second unit: `search_symbols` prints no column rather
|
||||
than the index's UTF-16 one, and M2's `file,line,col` selectors take
|
||||
byte columns too.
|
||||
- **Paths**: a path argument is absolute or relative to the first root that
|
||||
holds it; after canonicalization it must be a file inside some root, else
|
||||
the tool refuses naming the argument. Answers print paths relative to the
|
||||
first root holding them, `/`-separated.
|
||||
- **The index is built lazily** — on the first `tools/call`, not at
|
||||
`initialize` — so a host's startup handshake is instant however large the
|
||||
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.
|
||||
- **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
|
||||
the argument. `2025-11-25` states this explicitly (SEP-1303: "input
|
||||
validation errors should be returned as Tool Execution Errors rather than
|
||||
Protocol Errors to enable model self-correction") — a host shows the model
|
||||
a tool error, but often not a protocol one. Only an envelope `tools/call`
|
||||
cannot read at all (params not an object, no string `name`, `arguments`
|
||||
not an object) or an **unknown tool** is `-32602`. This deviates from the
|
||||
brief's "invalid params → -32602"; see the work log.
|
||||
- `resources/list`, `resources/templates/list` and `prompts/list` answer
|
||||
empty lists (the capabilities are advertised, per PLAN §4.2, so hosts will
|
||||
ask); `resources/read` is `-32002` "resource not found" and `prompts/get`
|
||||
`-32602` until M2/M6 fill them.
|
||||
- **`structuredContent` beside a compact text.** The spec says a tool with
|
||||
structured output SHOULD also serialize that JSON into a text block; this
|
||||
server deliberately sends its own compact rendering as the text instead
|
||||
(PLAN §4.5 — the token budget is the product). Whether a given host feeds
|
||||
the model the text or the JSON is not something this server controls; the
|
||||
M6 token census is where that shows.
|
||||
|
||||
## Handshakes
|
||||
|
||||
Consumed (public APIs only; no library crate was modified):
|
||||
|
||||
| crate | items |
|
||||
|---|---|
|
||||
| `lucisv_core` | `config::{Discovery::{new, for_dir}, FileConfig}`, `walk::collect_files_with`, `filelist::read`, `cache::content_hash` |
|
||||
| `vlog_parser` | `PARSE_STACK_SIZE`, `tokenize`, `parse_tolerant`, `parse_source_tolerant`, `LineIndex::{new, line_col}`, `ParseDiagnostic`, `ast::{SourceFile, Item, ItemKind, GenBlock, GenElse, GenIf}`, `span::TextRange` |
|
||||
| `vlog_semantic` | `analyze`, `Semantics::{symbols, symbol, symbols_named, document_symbols}`, `Symbol`, `SymbolKind`, `ScopeId`, `DocumentSymbol`, `IndexBuilder::{new, add_file, finish}`, `FileFacts::of`, `WorkspaceIndex::{absorb, fingerprint, files, path, units, units_of, instantiable_units, member, members_of, base_of, instantiations_of, workspace_symbols, build}`, `Def`, `DeclLines` |
|
||||
| `vlog_refactor` | `instantiation_plan`, `InstantiationPlan::render`, `Layout` |
|
||||
| `vlog_formatter`, `vlog_linter` | declared dependencies (PLAN §4.1); nothing called in M1 |
|
||||
|
||||
Promised to later lanes and to M5 (packaging): the binary name
|
||||
`lucisv-mcp`; the arguments `--root DIR` (repeatable, default cwd; a root
|
||||
that is not a directory is a usage error), `--filelist FILE`,
|
||||
`--index-cache DIR`, `--verbose`; anything else → `error: …` + `usage: …` on
|
||||
stderr, exit 2; stdout carries protocol lines only; EOF on stdin exits 0.
|
||||
`tools::Tool` (name, title, description, params, rewalk, handler) is the
|
||||
registry entry shape M2–M4 add to; `tools::read_item::select` is the item
|
||||
slicer M4's structural edits are specified to share.
|
||||
|
||||
Requests:
|
||||
|
||||
- **MCP-4 (new, to the lead):** the modern MCP era (`2026-07-28`:
|
||||
per-request `_meta` version, `server/discover`, no `initialize`). Not
|
||||
needed for any host this block targets today, but a dual-era server is the
|
||||
spec's recommended shape; a later lane, not M1.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] crate skeleton, argument contract, `PARSE_STACK_SIZE` thread, ordered loop
|
||||
- [x] `transport.rs`: newline-delimited JSON-RPC; `-32700` for non-JSON and
|
||||
non-UTF-8 lines; EOF ends cleanly
|
||||
- [x] `rpc.rs`: `initialize` negotiation, `notifications/initialized`, `ping`,
|
||||
`tools/list`, `tools/call`, `-32002` before `initialize`, `-32601`,
|
||||
`-32602`, `-32600` for a malformed envelope (null id, wrong `jsonrpc`,
|
||||
a batch array)
|
||||
- [x] `project.rs`: roots, config, filelist-or-walk, 1 MiB cap, index build,
|
||||
lazy per-file analyses keyed by content hash, per-call freshness sweep,
|
||||
path refusal outside the roots
|
||||
- [x] fingerprint-equals-rebuild after update / add / remove / recreate
|
||||
(`project/tests.rs`)
|
||||
- [x] wire tests over the real binary (`tests/wire.rs`)
|
||||
- [x] gates through `tools/guard.sh`
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-23 (dev, M1).**
|
||||
|
||||
Built `crates/lucisv_mcp` (binary `lucisv-mcp`), added to the workspace
|
||||
`members`. Modules: `main.rs` (arguments, root canonicalization, the
|
||||
stack-sized thread), `transport.rs`, `rpc.rs`, `project/{mod,files,analysis}.rs`
|
||||
(+ `project/tests.rs`), `render.rs`, `tools/{mod,read,interface,read_item}.rs`.
|
||||
The plan's single `tools/read.rs` was split three ways before it reached
|
||||
600 lines (`interface.rs` = `unit_interface`, `read_item.rs` = the item
|
||||
slicer, which M4 will share), and `project.rs` became a directory for the
|
||||
same reason (`files.rs` = discovery + stamps, `analysis.rs` = the
|
||||
per-file analysis cache).
|
||||
|
||||
Decisions and deviations:
|
||||
|
||||
1. **Protocol revisions.** The brief said pin `2025-06-18` plus the newest
|
||||
revision if verifiable. The newest (`2026-07-28`) was verified and is
|
||||
*not* an initialize-based protocol, so pinning it in `initialize` would
|
||||
have been a lie; the newest handshake-based revision, `2025-11-25`, is
|
||||
pinned instead, first. Filed MCP-4 for the modern era.
|
||||
2. **Invalid arguments are `isError: true`, not `-32602`** (Assumptions:
|
||||
SEP-1303 in `2025-11-25`). Unknown tool and unreadable envelopes stay
|
||||
`-32602`, and the message names the offending field or tool.
|
||||
3. **Lazy index build** on the first `tools/call`, so `initialize` is
|
||||
instant; not in the plan, which said "at startup".
|
||||
4. **The per-file analysis omits the `` `define`` table and the
|
||||
`resolve_external` overlay** of the server's `Document::new` sequence —
|
||||
nothing in M1 reads them, and the overlay depends on the index (it would
|
||||
need invalidating on every refresh). M2 adds both where `defines` and
|
||||
`definition` need them.
|
||||
5. **Racy-stamp rule** (Assumptions) — added beyond the plan's size+mtime,
|
||||
because a same-size rewrite within one mtime tick is exactly QA's
|
||||
"rename-then-recreate within one second" attack.
|
||||
6. **`-32002` for `resources/read`** is MCP's "resource not found"; the same
|
||||
number LSP uses for "server not initialized". Both meanings are the spec's.
|
||||
7. **`tools/list` ignores `cursor`** and never sends `nextCursor`.
|
||||
|
||||
Measured (release build, `--verbose`, read-only on opentitan; the checkout's
|
||||
`git status` was the same before and after — three files already modified
|
||||
by the owner, untouched here):
|
||||
|
||||
| root | files | index build (stderr line) | wall, 4 messages | RSS |
|
||||
|---|---|---|---|---|
|
||||
| `hw/ip/aes` | 124 | 64 ms | 1.07 s (incl. guard startup) | — |
|
||||
| `hw/` | 3 944 | 1 813 ms | 2.15 s | 332 MB |
|
||||
| whole checkout | 3 944 (3 over 1 MiB skipped) | 1 556–1 601 ms | 2.12 s | 331 MB |
|
||||
|
||||
Per-call cost on the whole checkout after the build: 7–12 ms for a call
|
||||
whose sweep changed nothing (3 944 `stat`s + the tool), 222 ms for a call
|
||||
that re-walked the tree (`project_overview`).
|
||||
|
||||
Gates (all through `tools/guard.sh`): `cargo fmt -p lucisv_mcp -- --check`
|
||||
clean; `cargo clippy -p lucisv_mcp --all-targets` clean, no `#[allow]`;
|
||||
`cargo test -p lucisv_mcp` 27 unit + 11 wire tests green; `cargo test
|
||||
--workspace` 4 497 passed, 0 failed, 46 ignored (4 459 before + 38 new).
|
||||
**Guard finding:** the first `cargo test --workspace` run was killed at the
|
||||
default 1 800 s wall clock, sitting in `vlog_semantic/tests/semantics.rs`
|
||||
(4 341 tests had passed, none failed). That binary takes 0.00 s on its own
|
||||
and in the re-run; the identical command re-run immediately afterwards
|
||||
finished green in 3 min 08 s. Most likely cause: a second `cargo test -p
|
||||
lucisv_mcp` the dev started during the first run, contending for the build
|
||||
directory lock. Not reproduced; recorded rather than explained away.
|
||||
|
||||
Production lines (non-blank, non-comment, before `#[cfg(test)]`): `main.rs`
|
||||
67, `transport.rs` 38, `rpc.rs` 222, `render.rs` 97, `project/mod.rs` 212,
|
||||
`project/files.rs` 130, `project/analysis.rs` 52, `tools/mod.rs` 129,
|
||||
`tools/read.rs` 397, `tools/interface.rs` 285, `tools/read_item.rs` 199;
|
||||
tests `project/tests.rs` 91, `tests/wire.rs` 390. None over 600; no function
|
||||
over 50 lines.
|
||||
|
||||
**2026-09-23 (dev, M1 rework after QA).** The lead's rulings on the QA
|
||||
findings, transport and `Project` half (the read-tools half — findings 1,
|
||||
3's tool hooks, 4, 5 — is in `docs/features/mcp-read-tools`'s work log).
|
||||
Every ruled `qa_*` test in `crates/lucisv_mcp/tests/qa_m1.rs` is
|
||||
un-ignored and green; nothing in that file was renamed.
|
||||
|
||||
- **2 — fixed.** `project/files.rs::walk_root` now takes every root and
|
||||
drops a canonical path that `starts_with` none of them, with a warning
|
||||
`<path>: outside every root (reached through a symlink); not indexed`.
|
||||
`resolve` unchanged. `qa_the_walk_does_not_index_files_outside_the_roots_through_symlinks`.
|
||||
- **3 — fixed.** `Project::ensure_walked_for_miss` + a `walked_in_call` flag
|
||||
(set by `open`, cleared at the top of `refresh`, set by any walk);
|
||||
called on a miss by the three by-name tools (read-tools log).
|
||||
`qa_a_unit_written_just_now_is_found_by_name_without_a_walk_first`.
|
||||
- **7 — fixed.** `rpc.rs::classify` answers an invalid message with its id
|
||||
whenever the id is readable (a string or an integer) — the missing or
|
||||
non-string `method` branch as well as the wrong-`jsonrpc` one; `null`
|
||||
only when the id itself is unreadable.
|
||||
`qa_an_invalid_request_with_a_readable_id_keeps_that_id`.
|
||||
- **8 — fixed.** The not-UTF-8 warnings are rendered with the new free
|
||||
function `relative_to` (what `Project::relative` now calls) and rebuilt
|
||||
by every `rewalk` from the files it could not read.
|
||||
`qa_an_unreadable_file_warning_is_root_relative_and_current`.
|
||||
- **9 — fixed.** `canonical_roots` keeps each canonical directory once.
|
||||
`qa_a_root_given_twice_is_one_root`.
|
||||
- **10 — fixed.** `Stamp::identity` = (ctime s, ctime ns, inode) under
|
||||
`cfg(unix)` via `std::os::unix::fs::MetadataExt`, `(0, 0, 0)` elsewhere;
|
||||
`Stamp::check` is suspect when it moves.
|
||||
`qa_a_same_size_rewrite_that_restores_an_old_mtime_is_seen`.
|
||||
|
||||
Gates after the rework (all through `tools/guard.sh`, one cargo at a
|
||||
time): fmt `--check` exit 0; clippy `--all-targets` exit 0, no warnings;
|
||||
`cargo test -p lucisv_mcp` unit 28 passed, `qa_m1` 40 passed / 0 ignored,
|
||||
`wire` 11 passed; `cargo test --workspace` exit 0 in 3 min 51 s, **4 538
|
||||
passed, 0 failed, 46 ignored**. Production lines now: `main.rs` 67,
|
||||
`transport.rs` 38, `rpc.rs` 225, `render.rs` 128, `project/mod.rs` 237,
|
||||
`project/files.rs` 149, `project/analysis.rs` 52, `tools/mod.rs` 129,
|
||||
`tools/read.rs` 405, `tools/interface.rs` 322, `tools/read_item.rs` 204.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-23 (QA, M1 — transport, protocol, `Project`).** Verdict:
|
||||
**rework needed** — for read-tools finding 1 (a wrong answer; see
|
||||
`docs/features/mcp-read-tools` QA log). Nothing in this half blocks.
|
||||
|
||||
How: read `PLAN.md` §4, both READMEs and every file under
|
||||
`crates/lucisv_mcp/src`; drove the debug and release binaries by hand
|
||||
(Python over stdin/stdout, scratch trees only); then pinned every attack as
|
||||
a `qa_*` test in `crates/lucisv_mcp/tests/qa_m1.rs` (40 tests: 30 pass
|
||||
and pin correct behaviour, 10 assert the correct behaviour of a finding and
|
||||
are `#[ignore = "QA finding N"]` — each confirmed failing today with
|
||||
`cargo test -p lucisv_mcp --test qa_m1 -- --ignored`, for the stated
|
||||
reason). Findings are numbered across both READMEs; 1, 4, 5 and 6 are the
|
||||
read tools' and are logged there.
|
||||
|
||||
Verified correct (pinned by passing `qa_*` tests):
|
||||
|
||||
- Protocol: a string id (non-ASCII) echoed verbatim; `null`, fractional
|
||||
and object ids → `-32600` with id `null`, server goes on; a notification
|
||||
method sent *with* an id is answered as a request (`-32601`, that id) and
|
||||
a real notification is never answered; a 10 MiB valid line (a
|
||||
`search_symbols` query) is answered and a 10 MiB non-JSON line is
|
||||
`-32700`, and the next `ping` is answered (0.16 s for both); every
|
||||
method but `initialize`/`ping` before the handshake → `-32002`
|
||||
(`server/discover` included, the dev's modern-era fallback signal); an
|
||||
unsupported `protocolVersion` (a string, a number, `null`) → `2025-11-25`;
|
||||
missing / extra / wrong-type / fractional / out-of-enum arguments are
|
||||
`isError: true` and every sentence names the argument (the SEP-1303
|
||||
deviation holds as documented); `arguments` not an object → `-32602`; a
|
||||
`_meta` beside the call is accepted; an unknown tool → `-32602` naming it;
|
||||
two messages on one line → one `-32700`, no second answer, no crash;
|
||||
empty, whitespace-only and bare `\r` lines ignored; EOF after a complete
|
||||
message without its newline answers it and exits 0; EOF mid-message →
|
||||
`-32700` then exit 0; under `--verbose`, stdout of a 16-message session
|
||||
(including a lex-error file and a non-UTF-8 file) parses line by line as
|
||||
JSON-RPC while the log goes to stderr.
|
||||
- Freshness: rename a file away and recreate it with different content and
|
||||
the *old* mtime (a 1-second-mtime filesystem's view) — the next call
|
||||
answers the new content (the racy rule, `files.rs:157`); a same-size
|
||||
rewrite with the mtime put back inside the racy window is caught; a file
|
||||
in a new two-level subdirectory appears after `project_overview`'s walk
|
||||
(and, by hand, after the 5 s re-walk with no overview); a file growing
|
||||
past 1 MiB drops out at the next call and is counted in `skipped_large`;
|
||||
a `.gitignore` added after startup drops its files at the next walk.
|
||||
- Roots: `link.sv` and `linkdir/secret.sv` (symlinks leaving the root), a
|
||||
`../sibling/…` path and an absolute outside path are all refused
|
||||
"outside every root"; `--root A --root A/sub` indexes each file once and
|
||||
`b.sv` resolves against the inner root; a relative `--root` resolves
|
||||
against the working directory.
|
||||
- `rpc.rs`, `transport.rs`, `project/*`: no `unwrap`/`expect`/`panic!`
|
||||
outside `#[cfg(test)]`; no `#[allow]`; no `unsafe`; no `println!` in any
|
||||
library crate the binary calls (stdout is held by one lock for the loop).
|
||||
|
||||
Findings (this half):
|
||||
|
||||
- **2 — non-blocking (medium): the walk is not contained, the arguments
|
||||
are.** `project/files.rs:98` canonicalizes each walked path and keeps it
|
||||
wherever it lands, so a symlink inside a root to a file (or directory)
|
||||
outside it indexes the outside file: `list_units` prints its absolute
|
||||
path and `unit_interface secret_mod` answers its ports, while `outline`
|
||||
on the same file is refused "outside every root" (`Project::resolve`).
|
||||
Repro: `qa_the_walk_does_not_index_files_outside_the_roots_through_symlinks`.
|
||||
Suggested fix: in `walk_root`, drop (and count in a warning) a canonical
|
||||
path that `starts_with` no root; a `--filelist` entry stays allowed as
|
||||
the README says. Alternatively the lead rules that indexed files are
|
||||
readable and `resolve` accepts them — either way one posture.
|
||||
- **3 — non-blocking (medium; plan-conformant): a file written in the last
|
||||
5 s is invisible to every name lookup.** `project/mod.rs:131` walks only
|
||||
when a file went, on `project_overview`, or after `REWALK_AFTER` (5 s).
|
||||
The common agent flow — write `new_mod.sv`, then `unit_interface
|
||||
new_mod` — is refused with "search_symbols finds near names"
|
||||
(`tools/interface.rs:84`), which cannot find it either. Repro:
|
||||
`qa_a_unit_written_just_now_is_found_by_name_without_a_walk_first`.
|
||||
Suggested fix: when a by-name lookup (`unit_interface`, `list_units`
|
||||
with a glob, `search_symbols`) finds nothing and the last walk is more
|
||||
than, say, 100 ms old, walk once and retry (opentitan walk: 157 ms
|
||||
release). PLAN §4.4 permits today's behaviour; this is for the lead.
|
||||
- **7 — non-blocking (low): an invalid request loses a readable id.**
|
||||
`rpc.rs:107` answers `{"jsonrpc":"2.0","id":15}` and
|
||||
`{"jsonrpc":"2.0","id":15,"method":5}` with id `null`; JSON-RPC 2.0 §5
|
||||
wants `null` only when the id could not be detected. Repro:
|
||||
`qa_an_invalid_request_with_a_readable_id_keeps_that_id`. Fix: in that
|
||||
branch use `id` when `valid_id` (two lines).
|
||||
- **8 — non-blocking (low): the unreadable-file warning is absolute and
|
||||
never refreshed.** `project/mod.rs:88` records `path.display()` (PLAN
|
||||
§4.5: root-relative), only at `open`; `rewalk` (`project/mod.rs:173`)
|
||||
skips an unreadable file silently, so a file fixed later is indexed yet
|
||||
still warned about, and one broken later is never warned about. Repro:
|
||||
`qa_an_unreadable_file_warning_is_root_relative_and_current`. Fix: keep
|
||||
the unreadable set in `FileSet`/the rewalk, rendered with
|
||||
`Project::relative`.
|
||||
- **9 — non-blocking (cosmetic): a root given twice is listed twice** in
|
||||
`project_overview` (`project/mod.rs:56` does not dedup; files are not
|
||||
duplicated). Repro: `qa_a_root_given_twice_is_one_root`. Fix: dedup the
|
||||
canonical roots keeping first order.
|
||||
- **10 — non-blocking (low): a same-size rewrite that restores an old mtime
|
||||
is never seen.** `Stamp::check` (`project/files.rs:145-157`) compares
|
||||
size + mtime only; `cp -p`, `rsync -t`, `touch -r` and archive
|
||||
extraction restore mtimes. Repro:
|
||||
`qa_a_same_size_rewrite_that_restores_an_old_mtime_is_seen` (mtime set an
|
||||
hour back before startup, rewritten, set back). Fix: add `ctime` and
|
||||
`ino` (`std::os::unix::fs::MetadataExt`, same `stat`) to `Stamp` — git's
|
||||
own answer to the same problem.
|
||||
|
||||
Notes (no action asked): stdin lines have no length cap — a host that
|
||||
never sends a newline grows one buffer without bound (10 MiB costs
|
||||
nothing; the process is the host's child). `initialize` twice is
|
||||
accepted and re-negotiates. No `catch_unwind` around a tool call — the LSP
|
||||
has none either, and no panic was found.
|
||||
|
||||
Opentitan (read-only, checkout `0098135`; `git status --porcelain`
|
||||
byte-identical before and after — the owner's three modified files, untouched):
|
||||
|
||||
| root | build (stderr line) | first `tools/call` (build + call) | later calls | `project_overview` (re-walk) |
|
||||
|---|---|---|---|---|
|
||||
| `hw/ip/aes` (debug binary) | — | 329 ms (`unit_interface aes_core`) | 0–1 ms | — |
|
||||
| `hw/` (release) | 3 944 files in 1 584 ms | 1 791 ms (`list_units`) | 5–11 ms | 157 ms |
|
||||
|
||||
`initialize` answered in 0 ms (129 ms wall including process start).
|
||||
|
||||
Gates (all through `tools/guard.sh`): see the read-tools QA log entry of
|
||||
the same date (one run for the crate).
|
||||
|
||||
|
||||
**2026-09-23 (QA, M1 re-check after the rework).** Verdict: **pass** — every
|
||||
ruled finding is fixed; one new non-blocking finding (11, read tools).
|
||||
|
||||
Re-derived by hand (scratch trees, debug and release binaries), not only
|
||||
by the tests:
|
||||
|
||||
- **2** — a root holding `vendor -> ../out` (a directory outside, two
|
||||
files), `rtl/loop -> ..`, `alias.sv -> rtl/in.sv`, and `out/back ->
|
||||
root`: the walk ends, indexes one file, and `project_overview` carries two
|
||||
warnings `<outside path>: outside every root (reached through a symlink);
|
||||
not indexed`; `unit_interface secret2` refuses (after its miss walk),
|
||||
`outline vendor/s1.sv` refuses. Note only: the warning names the
|
||||
resolved outside file, not the link inside the root that led there.
|
||||
- **3** — written just before each call: `unit_interface fresh1` (root),
|
||||
`list_units glob=fresh2`, `search_symbols fresh3` (a new two-level
|
||||
subdirectory) and `unit_interface fp::fc` all answer. Walk count, timed
|
||||
on opentitan `hw/` (release; `git status` identical before and after):
|
||||
hits 6–10 ms; `unit_interface no_such_mod`, `list_units glob=no_such*`
|
||||
and `search_symbols zzqqxx` each 140–150 ms, three times running — one
|
||||
walk per miss call (two would be ~290 ms, since one walk is ~145 ms);
|
||||
hits right after the misses 5–8 ms, so a legitimate miss does not make
|
||||
later calls walk. By design (the ruling) every repeated miss re-walks:
|
||||
~145 ms each on 3 944 files. `list_units` with a `kind` and no `glob`
|
||||
never walks on a miss. The miss walk is not in the `--verbose` refresh
|
||||
line (`ensure_walked_for_miss` calls `refresh` without logging) — note
|
||||
only.
|
||||
- **10** — `cp -p` of a same-size file with a 2020 mtime over the indexed
|
||||
one (also 2020): the next call answers the new module; `mv` of a
|
||||
prepared same-size, old-mtime file over it: likewise; `read_item` slices
|
||||
the new bytes.
|
||||
- 7, 8, 9 by their tests (un-ignored, unchanged, green), plus
|
||||
`qa_rework_a_file_that_stops_being_utf8_is_warned_and_leaves_the_index`
|
||||
for the half of 8 the first test did not reach.
|
||||
|
||||
Checked that the dev's edit to `qa_m1.rs` is what the ruling says: the ten
|
||||
`#[ignore]` attributes are gone, and in
|
||||
`qa_columns_are_counted_in_one_unit_across_tools` only the last assertion
|
||||
changed (`col == 17` → `line == 1` and no `col` key, with a two-line
|
||||
comment citing the ruling); the parse-error assertion (`1:28`, bytes) and
|
||||
every other test body read as written (the ten formerly ignored ones
|
||||
compared line by line; key assertions of the other thirty spot-checked).
|
||||
|
||||
New tests this round (`qa_rework_*` in `crates/lucisv_mcp/tests/qa_m1.rs`,
|
||||
11: 10 pass, 1 ignored for finding 11) — see the read-tools QA log for the
|
||||
list. Sizes after the rework (production lines, measured by QA): `main.rs`
|
||||
67, `transport.rs` 38, `rpc.rs` 225, `render.rs` 128, `project/mod.rs`
|
||||
237, `project/files.rs` 149, `project/analysis.rs` 52, `tools/mod.rs`
|
||||
129, `tools/read.rs` 405, `tools/interface.rs` 322, `tools/read_item.rs`
|
||||
204 — the dev's numbers; no function over 45 lines; no `unwrap`/`expect`/
|
||||
`panic!` outside tests, no `#[allow]`, no `unsafe`.
|
||||
|
||||
Gates (verbatim, all through `tools/guard.sh`, one cargo invocation at a
|
||||
time): `cargo fmt -p lucisv_mcp -- --check` exit 0; `cargo clippy -p
|
||||
lucisv_mcp --all-targets` `Finished`, no warnings; `cargo test -p
|
||||
lucisv_mcp` unit `28 passed; 0 failed`, `qa_m1` `50 passed; 0 failed; 1
|
||||
ignored`, `wire` `11 passed; 0 failed`; `cargo test --workspace` (default
|
||||
guard) exit 0 in 242 s, **4 548 passed, 0 failed, 47 ignored** (the dev's
|
||||
4 538 / 46 plus this round's 10 / 1). No guard kill.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-09-23.** Read every source file. The block is what PLAN §4 asked
|
||||
for and nothing more: no library crate touched, no new dependency, one
|
||||
synchronous loop, `PARSE_STACK_SIZE` on the parsing thread, no `unwrap` on a
|
||||
library path. Rulings recorded here so nobody re-litigates them: invalid
|
||||
tool arguments are tool errors (`isError`), not protocol errors — the
|
||||
2025-11-25 spec's own guidance and the better shape for an agent that has
|
||||
to correct itself; the server is a legacy-era (`initialize`) server by
|
||||
design, MCP-4 filed for the modern era; columns are 1-based bytes
|
||||
everywhere, and `search_symbols` reports no column rather than a second
|
||||
unit; a by-name miss walks once per call. The guard kill the dev saw was
|
||||
two concurrent cargo invocations and did not reproduce under either QA
|
||||
run. QA finding 11 (an escaped identifier ending in `@digits` cannot be
|
||||
selected bare) is carried into M2 as a small item. Committed as M1.
|
||||
@@ -138,7 +138,17 @@ sites, `.port(...)` connection names, and `#(.PARAM(...))` overrides.
|
||||
identifier tokens spell the new name — same count, same kinds, same texts,
|
||||
same attached comments, same spans after shifting.
|
||||
|
||||
Rules 12 and 13 are checked over the *whole* edit; either one fails the entire
|
||||
14. **Implicit connections lucisv cannot read** (added 2026-09-23, see
|
||||
"Implicit connections"): a `.*` or `.name` that binds — or could bind —
|
||||
the renamed name through a module lucisv cannot read or finds declared
|
||||
twice, a connection list split by compiler directives or holding text a
|
||||
tolerant parse could not read, a hierarchical `bind` target, a `.*` that
|
||||
would start binding the new name, and a package variable an import might
|
||||
hand to a `.*`.
|
||||
15. **Binding verification** (2026-09-23): what any `.name` or `.*` in a
|
||||
watched file binds — port half and net half — differs before and after.
|
||||
|
||||
Rules 12, 13 and 15 are checked over the *whole* edit; any one fails the entire
|
||||
rename, never part of it (`RefactorEdit` is all-or-nothing, hard invariant 1's
|
||||
shape for refactorings).
|
||||
|
||||
@@ -543,6 +553,138 @@ implemented:
|
||||
- `a label lucisv records no declaration for`, and
|
||||
`an occurrence lucisv cannot attribute to any declaration` for the rest.
|
||||
|
||||
## Implicit connections (2026-09-23)
|
||||
|
||||
**The defect this closes** (TODO-MCP M3.5, M3 QA finding 1, reproduced with
|
||||
`vlog_refactor::rename` directly). `.name` and `.*` (IEEE 1800 §23.3.2.3–4)
|
||||
bind a port to the *same-named* declaration where the instance is written.
|
||||
The semantic layer records a reference for the port half of `.name` and
|
||||
nothing at all for its net half or for `.*` — so renaming a port `d` → `din`
|
||||
of `leaf` left `leaf u_leaf (.*)` binding nothing and turned `.d` into `.din`
|
||||
against a parent with no net `din`, and renaming the parent's net cut both
|
||||
bindings. Every one verified clean: the token check saw one identifier change,
|
||||
and the resolution print saw no reference move, because none was ever
|
||||
recorded. A silent CLAUDE.md invariant-1 corruption in a shipped engine; the
|
||||
LSP's rename shared it.
|
||||
|
||||
**What a rename does now** (`rename/connections.rs`):
|
||||
|
||||
| Renamed | Written at an instance | Becomes |
|
||||
|---|---|---|
|
||||
| port `p` → `q` of `M` | `M u (.p)` | `M u (.q(p))` — one edit, `p` → `q(p)` |
|
||||
| port `p` → `q` of `M` | `M u (.*)` and a net, variable, port or instance named `p` visible | `M u (.*, .q(p))` |
|
||||
| port `p` → `q` of `M` | `M u (.*)`, nothing named `p` or `q` visible | unchanged — the wildcard bound nothing and still binds nothing |
|
||||
| net/var/port/instance `n` → `m` | `C u (.n)` where `n` is the renamed one | `C u (.n(m))` |
|
||||
| net/var/port/instance `n` → `m` | `C u (.*)`, `C` declares port `n` | `C u (.*, .n(m))` |
|
||||
| either | `.*` beside an explicit `.p(...)` / `.n(...)` | nothing added — the explicit one wins, and the rename's own edit handles it |
|
||||
|
||||
Every such rewrite is listed in `RefactorEdit.warnings` — "`u_leaf` at
|
||||
top.sv:2 bound `d` through `.*`; added `.din(d)`." and "`u_leaf` at top2.sv:2
|
||||
connected `d` by the shorthand `.d`; wrote `.din(d)` so it still binds the
|
||||
same net." — so both the LSP and the MCP show it. A port of a module that is
|
||||
itself instantiated gets both directions at once: renaming `mid`'s port `d`
|
||||
adds `.din(d)` to `top`'s `mid u_mid (.*)` and `.d(din)` to `mid`'s own
|
||||
`leaf u_leaf (.*)`.
|
||||
|
||||
**Where an implicit connection binds** (`rename/sites.rs`): an ordinary
|
||||
instance, at the nearest declaration of the name walking outward from the
|
||||
scope the instance is written in (generate blocks included); a `bind` whose
|
||||
target is one plain module name, at that module's own top-level
|
||||
declaration (`WorkspaceIndex::member_in(.., Surface::Hierarchical)`, the
|
||||
table the semantic layer resolves a bind connection's bare name through).
|
||||
Which instances are walked: for a port, every instance of its module in the
|
||||
in-scope files that spell the module's name; for a net, every instance in its
|
||||
own file from whose position the name resolves to it, plus every `bind` into
|
||||
its module when it is declared at the module's top level; for a package
|
||||
variable, every instance in a file that names the package — refused, not
|
||||
rewritten (lucisv does not follow an import into a `.*`).
|
||||
|
||||
**Layout.** An insertion only — nothing the source wrote is replaced, so no
|
||||
comment can move. A `.*` addition goes after the last connection element,
|
||||
before the `)`, in the list's own style: `, .q(p)` on the same line for an
|
||||
inline list; its own line at the last element's indentation for a list
|
||||
written one per line; when the last element carries a `//` comment, the comma
|
||||
goes before the comment and the connection on the next line (a `,` after `//`
|
||||
is inside the comment). The newline is the list's own, so a CRLF file stays
|
||||
CRLF. An escaped identifier gets the blank that terminates it. Nothing adds a
|
||||
trailing comma.
|
||||
|
||||
**Refused, never guessed** — each sentence names the instance and its line:
|
||||
|
||||
- a `.*` whose module lucisv cannot read ("`u_x` at top.sv:4 connects with
|
||||
`.*` to `ghost`, which lucisv cannot read, so it cannot tell whether `d` is
|
||||
bound implicitly; the rename was abandoned."), or finds declared in more
|
||||
than one indexed file, or whose port list carries compiler directives;
|
||||
- a connection list split by compiler directives (when it holds `.*`), or
|
||||
holding text a tolerant parse could not read that spells either name or a
|
||||
`*`;
|
||||
- a `bind` whose target is a hierarchical path, or a lone **instance** name
|
||||
that may be an instance of the renamed module: resolved upward from the
|
||||
bind's own scope first (the enclosing module's instances of that name),
|
||||
else through every indexed instance of that name; refused when one of them
|
||||
is the renamed module's or none is indexed, skipped when all are other
|
||||
modules' (rework, QA finding 2);
|
||||
- a `.*` whose module declares a port spelled like the **new** name, not
|
||||
connected explicitly — the rename would make the wildcard start binding it;
|
||||
- a package variable a `.*` or `.name` might reach through an import.
|
||||
|
||||
**How the verifier accounts for it** (`check/implicit.rs`; `check/` had to
|
||||
learn the shape, because the whole point is that its reference print could
|
||||
not see it). Two additions, both inside the existing `verify`:
|
||||
|
||||
1. **A file whose edits insert is held to the splice contract plus a shape
|
||||
rule.** The token-identity check allows no insertion at all, so such a file
|
||||
is checked by the port refactorings' piece comparison (`ledger::Split`,
|
||||
`pieces_match`: every piece in place, no comment or attribute dropped or
|
||||
duplicated) plus: every replacement is exactly one identifier token
|
||||
spelling the old name, replaced by the new name; every insertion lexes to
|
||||
`(X)`, `,`, `.X(Y)` or `, .X(Y)` with `X`, `Y` the old or the new name and
|
||||
no comment, **at a place a connection list takes it** (rework, QA finding
|
||||
1): `(X)` only right after a shorthand connection's name, `,` only right
|
||||
after the last element of a named list holding `.*`, `, .X(Y)` between
|
||||
that element — past blanks and comments — and the list's `)`, and a bare
|
||||
`.X(Y)` only there behind such a `,`; the places are read off the
|
||||
before-tree with the same `sites` walk the engine plans with. Anything
|
||||
else: "the rename would write `…` outside a connection list in <file>; no
|
||||
edits were made." And the file gains no parse diagnostic. The resolution print
|
||||
excludes the inserted ranges (their names are the next check's to account
|
||||
for).
|
||||
2. **The binding print.** For every watched file that could write an
|
||||
implicit connection of either name (a cheap text prefilter,
|
||||
`sites::may_connect_implicitly`, which is a superset — a `.` that starts a
|
||||
list element followed by `*` or one of the names — and every file the edits
|
||||
insert into), every instance's bindings are printed before and after:
|
||||
`(instance, what the port half names, what the net half names)`, for every
|
||||
named connection whose port or bare-name net spells one of the two names,
|
||||
and every port spelling one of them that a `.*` reaches. The net half of
|
||||
`.name`/`.*` is looked up the way the language looks it up (above); a `.*`
|
||||
into a module that cannot be read prints a *probe* of what each of the two
|
||||
names finds there. Before-side spans are shifted through the edit map. The
|
||||
two prints must be equal. Why only the two names: a rename adds and
|
||||
removes declarations of those two names alone, so no other lookup and no
|
||||
other port can move — the watched-file argument applied one level down.
|
||||
|
||||
The attack pairs (`check::implicit::tests`, CLAUDE.md invariant 4 — the
|
||||
binding print is a new *strictness*, not a forgiveness, but the insertions it
|
||||
admits are a widening of what a rename may write, so they ship with attacks):
|
||||
the QA finding itself (`.d` → `.din`, `.*` untouched) and the wildcard alone;
|
||||
a shorthand written out with the wrong net (`(din)` — spells only the two
|
||||
names, so only the binding print sees it); a wildcard connection to a third
|
||||
name and to the swapped halves (`.d(din)`); insertions that are not connection
|
||||
text (a comment, `; wire din;`, a doubled connection, an unclosed one); a
|
||||
connection added beside an explicit one of the same port; an insertion into
|
||||
the wrong instance; a net rename that leaves `.*` alone, and one with swapped
|
||||
halves; a `.*` that starts binding the new name; a net rename behind an
|
||||
unreadable `.*`. Sabotage-checked: with the binding print disabled, seven of
|
||||
the eleven fail (the rest are caught by the shape rule or the piece ledger
|
||||
as well).
|
||||
|
||||
**What it costs.** A rename with no implicit connection of the name anywhere
|
||||
parses nothing extra: the engine and the verifier both parse only files that
|
||||
pass the prefilter (`the rename parses each input file once and each edited
|
||||
file once more` still holds verbatim). A file that does pass costs the engine
|
||||
one parse and the verifier one per side.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The caller hands over the same file set the workspace index was built from,
|
||||
@@ -573,6 +715,23 @@ implemented:
|
||||
- Refactored output is *edited source*, not reformatted source (umbrella
|
||||
Handshakes): the edits are minimal, and the user runs the formatter
|
||||
separately.
|
||||
- **Implicit connections (2026-09-23).** `.*` and `.name` bind a port to a
|
||||
net, a variable, a port or an instance of the same name
|
||||
(`sites::binds_implicitly`: `ports/expand.rs`'s reading plus the instance,
|
||||
because an interface port binds to an interface instance and writing a
|
||||
module instance's connection out is exactly as wrong as the implicit one);
|
||||
the nearest declaration of the name shadows, so a parameter or a type of
|
||||
that name is a binding to nothing. The lookup is lexical and local — the nearest declaration
|
||||
walking outward from the instance — so a name a `.*` could reach only
|
||||
through a package import is not seen: a rename of a *package* variable is
|
||||
refused wherever a file naming the package writes a candidate implicit
|
||||
connection, and a rename that would make an import-reached name newly
|
||||
visible to a `.*` is caught only when the local lookup moves. A `bind` into
|
||||
a module the fan-out does not hold is outside the rename exactly as any
|
||||
other use in such a file is (the staleness premise); a `bind` whose target
|
||||
is a hierarchical path is refused whenever it writes a candidate implicit
|
||||
connection of the name, since lucisv cannot name its scope. The
|
||||
compilation unit (`$unit`) is treated as one file.
|
||||
|
||||
## Handshakes
|
||||
|
||||
@@ -678,6 +837,49 @@ the only alternative — matching the label textually — would have broken this
|
||||
feature's one structural rule, that every edit comes from a resolved
|
||||
reference.
|
||||
|
||||
**Requested 2026-09-23 (implicit connections), not blocking — each has a
|
||||
workaround in this crate:**
|
||||
|
||||
- **`vlog_refactor::ports` (`ports/list.rs`, `ports/find.rs`).**
|
||||
`append_to_list`, `after_same_line_comments`, `line_indent`,
|
||||
`walk_instantiations` and `declared_ports` are `pub(super)` to the port
|
||||
refactorings; the rename needed the same five, and M3.5 did not own the
|
||||
files. Workaround: `rename/layout.rs` and `rename/sites.rs` restate them
|
||||
(with two differences the rename needed: a CRLF-aware line break, and the
|
||||
`bind` directive handed to the visitor rather than a bool). Request: lift
|
||||
them to `pub(crate)` and let the rename call them, so there is one list
|
||||
layout rule.
|
||||
- **`vlog_semantic`.** Recording an implicit connection's net half as a
|
||||
reference (`.name` → a use of the net; `.*` → one use per port the module
|
||||
declares, when it can be read) would let `collect_occurrences`, find-all-
|
||||
references and the resolution print see these bindings directly, and would
|
||||
retire most of `rename/sites.rs`. Workaround: the AST walk here, which
|
||||
both the engine and the verifier read.
|
||||
|
||||
- ~~**`lucisv_server` (`state/mod.rs::rename_sources_traced`) — the one that
|
||||
matters for the LSP.**~~ **Delivered 2026-09-23 inside M3.5 (lead ruling):
|
||||
see the work log's fan-out entry.** The original request, kept as filed: The rename's fan-out holds every file declaring
|
||||
either name, so a module `C` a `.*` instantiates is in it exactly when `C`
|
||||
declares a port spelled like one of them — which is the case that needs a
|
||||
rewrite. When it does not, `C`'s file is not handed over, and the engine,
|
||||
which cannot tell "not in this subset" from "not in the workspace", reports
|
||||
`C` as a module it cannot read and **refuses**. Safe, and the whole-scope
|
||||
callers (the MCP, the CLI, the tests) never see it; but an LSP rename of a
|
||||
net in a module whose instances use `.*` into modules that do not declare
|
||||
the name is refused where it could succeed. Request: a seventh rung — for
|
||||
every file in the set that writes `.*`, add the declaring file of each
|
||||
module instantiated there (`WorkspaceIndex::units` of the instantiation
|
||||
edges the index already records). No engine change is needed for it.
|
||||
|
||||
- **`vlog_parser` (filed 2026-09-23, QA M3.5 finding 3 and round one's
|
||||
`{d,, d}`).** The tolerant parser accepts a trailing `,` in a named
|
||||
connection list (`other u_o (.*,)`) and an empty concatenation element
|
||||
(`{d,, d}`) without a diagnostic, so the verifiers' "no new parse
|
||||
diagnostic" rule cannot see either. The rename's position check refuses
|
||||
both on its own (a lone comma is not a place a connection list takes);
|
||||
the request is that the parser report them, so every refactoring's
|
||||
splice contract gets the same net for free. Not this lane's to fix.
|
||||
|
||||
**Requested of nobody else.** Hierarchical tails and `defparam` paths remain
|
||||
unresolved by design (`vlog_semantic` non-goal: "resolving a tail needs
|
||||
instance elaboration"), so they stay warned-not-edited; making them edits is
|
||||
@@ -718,6 +920,11 @@ a much larger change than an end label and is not part of M2.
|
||||
the new name, which closes the one refusal the first draft lost. The
|
||||
old name's exemption is argued under "The dangling-use case" and pinned
|
||||
by its own test
|
||||
- [x] Implicit connections (2026-09-23, TODO-MCP M3.5): `.name` and `.*`
|
||||
rewritten explicitly in both directions (port and net), every rewrite
|
||||
warned about, the unreadable cases refused, and the verifier taught the
|
||||
shape (insertions under the splice contract + a shape rule; the binding
|
||||
print) with eleven attack pairs
|
||||
- [ ] Deferred: rename in comments and strings (rope's `docs=True`) — the
|
||||
umbrella lists it as an option, off by default, "until asked for"
|
||||
- [ ] Deferred: renaming a module together with its file
|
||||
@@ -1031,6 +1238,137 @@ Gates after the rework: `cargo fmt --all -- --check` clean,
|
||||
`cargo clippy --all-targets` clean workspace-wide, `cargo test --workspace`
|
||||
green, `node editors/vscode/smoke.js` OK against the release binary.
|
||||
|
||||
**2026-09-23 — dev agent (M3.5, implicit connections).** The engine rewrote
|
||||
nothing it could not see a reference for, and `.name`/`.*` bindings have no
|
||||
reference — see "Implicit connections" for the contract, the refusals and the
|
||||
verifier's new half. Key decisions:
|
||||
|
||||
- **AST walk, not semantic references.** The semantic layer records the port
|
||||
half of `.name` (so a port rename already edited `.d` → `.din`) and nothing
|
||||
of the net half or of `.*` (`bind/item.rs::bind_connection` skips `*` and
|
||||
binds `expr: None` to nothing). `vlog_semantic` is not this lane's to
|
||||
change, so the bindings are re-derived from the parse — one walk
|
||||
(`rename/sites.rs`) that the engine and the verifier both read, so the two
|
||||
cannot disagree about where an implicit connection is or where its name
|
||||
binds. Filed as a Handshake request.
|
||||
- **Insertions only.** The shorthand's port half is already the rename's
|
||||
edit; the net half is an insertion right after it, fused into one
|
||||
`TextEdit` (`p` → `q(p)`) only after verification, so the verifier sees a
|
||||
pure rename edit plus a pure insertion. A `.*` gets an appended element, so
|
||||
nothing the source wrote is replaced and no comment can move.
|
||||
- **`check/` learned the shape rather than being bypassed.** A file with
|
||||
insertions is checked by the splice contract the port refactorings already
|
||||
use plus a four-template shape rule; the binding print is a new check, and
|
||||
it is strictly *more* than the rename had (every file it prints was
|
||||
already compared by the reference print). Sabotage-verified.
|
||||
- **Prefilter.** `sites::may_connect_implicitly` keeps the engine and the
|
||||
verifier from parsing files that cannot hold an implicit connection of
|
||||
either name; the parse-budget tests (`K + E`) are unchanged and pass.
|
||||
- **OpenTitan, read-only, on a scratch copy of `hw/ip/prim` + `hw/ip/aes`
|
||||
(393 files, release, whole-scope).** `prim_fifo_sync`'s port `clr_i` →
|
||||
`clr_q` is **refused**: `prim_fifo_sync_bind_fpv.sv` writes
|
||||
`bind i_nopass1 prim_fifo_sync_assert_fpv … (.clk_i, .rst_ni, .clr_i, …)`,
|
||||
a `bind` into an *instance* named `i_nopass1` — which is a
|
||||
`prim_fifo_sync` in `prim_fifo_sync_tb`, so the old engine would have cut
|
||||
those twelve bindings silently. With that one file left out of scope the
|
||||
same rename succeeds (115 ms, 3 files, 16 edits): eleven `.clr_i` →
|
||||
`.clr_q(clr_i)` in `prim_fifo_sync_tb.sv`, and `prim_fifo_sync`'s own
|
||||
`u_fifo_cnt (.clr_i, …)` → `.clr_i(clr_q)` — both directions in one
|
||||
rename. Renaming the testbench's own port `clr_i` → `clr_tb` writes
|
||||
`(clr_tb)` after the eleven shorthands. A `.*` user: renaming
|
||||
`fi_control_fsm_wrapper`'s port `aes_ctrl_cs` → `ctrl_cs` adds
|
||||
`, .ctrl_cs(aes_ctrl_cs)` to `bind aes_control_fsm … u_fi_ctrl_fsm (.*)`
|
||||
(the bind's target declares `aes_ctrl_cs`) and `, .aes_ctrl_cs(ctrl_cs)` to
|
||||
the wrapper's own `fi_control_if fi_if (.*)`; renaming `aes_control_fsm`'s
|
||||
variable `aes_ctrl_cs` → `ctrl_state_q` adds `.aes_ctrl_cs(ctrl_state_q)`
|
||||
to the same bind. Each rename ~110 ms.
|
||||
- **The server's fan-out step (2026-09-23, lead ruling on Handshake 1).**
|
||||
`Workspace::rename_sources_traced` now adds, after the open buffers, the
|
||||
declaring file of every module instantiated in a handed-over file — one hop
|
||||
down the index's `instantiations()` edges, `bind` included
|
||||
(`module_select::instantiated_by`, a walk over records; nothing is read).
|
||||
So a `.*` into a module that declares neither name is handed over and read
|
||||
as binding nothing, instead of refused as unreadable; a `.*` into a module
|
||||
the workspace does not hold is still refused. The added files count in
|
||||
`selected` and in the indirect census (as `instantiation`) but not in the
|
||||
per-rung counts: `SelectionTrace`'s counter is private to `rename_trace.rs`,
|
||||
which this lane does not own. Pinned by two wire tests
|
||||
(`server/tests/rename_implicit.rs`: an open-buffer net rename beside
|
||||
`quiet u_quiet (.*)` and `leaf u_leaf (.*)` succeeds with `, .d(x)` and no
|
||||
edit to `u_quiet`; the same with `quiet` absent is refused naming `u_quiet`)
|
||||
and one unit test of the helper. The engine is unchanged by it.
|
||||
- **Deviation from the brief:** the MCP tool description's known-limit
|
||||
sentence was replaced by one saying what happens now (the connection is
|
||||
written out and listed in `warnings`), rather than only deleted.
|
||||
|
||||
**2026-09-23 — dev agent (M3.5 rework after QA's FAIL).**
|
||||
|
||||
- **Finding 1 — insertions checked for their text, never their place.**
|
||||
`check/implicit.rs::insertions_match` now also asks `Slots::takes`: each
|
||||
insertion's offset must be a place the before-tree's `sites` walk (the
|
||||
engine's own) says a connection list takes that template — see "How the
|
||||
verifier accounts for it", item 1. QA's three tests
|
||||
(`check/qa_implicit.rs`, registration kept in `check/mod.rs`) are
|
||||
un-ignored and pass unchanged; two attacks of my own pin that the check
|
||||
keys on the file's sites, not on a byte: `(d)` at an offset that is a
|
||||
shorthand's end in `top2.sv` is refused in a file where the same offset
|
||||
ends a positional element, and in one file `(d)`/`,` after the positional
|
||||
`d` of a second instance is refused beside the honest shorthand rewrite of
|
||||
the first. Sabotage-checked: with the position check off, those two and
|
||||
QA's three fail.
|
||||
- **Finding 2 — a `bind` into a bare instance name refused unrelated
|
||||
renames.** `connections.rs::bind_reaches` classifies each bind (module /
|
||||
maybe / elsewhere); `instance_owners` resolves a lone instance name
|
||||
through `WorkspaceIndex::instantiations()` — the enclosing module's own
|
||||
instances of that name first (upward resolution, IEEE 1800 §23.11, which
|
||||
is what opentitan's `bind dut … (.*)` in `sram_ctrl`'s and `entropy_src`'s
|
||||
`tb.sv` means), every indexed instance of that name otherwise. All owned by
|
||||
other modules → skipped; one is the renamed module's, or none is indexed →
|
||||
refused as before. QA's test un-ignored and passing; two of mine: an
|
||||
instance name owned by both `fifo` and `cnt` refuses a `cnt` rename (and
|
||||
is skipped with `cnt`'s bench removed), and a bind written beside its own
|
||||
`fifo dut` is `fifo`'s even though another bench has a `cnt dut`. **One
|
||||
step past the ruling**, stated: the enclosing-module preference. Without
|
||||
it `entropy_src`'s `clk_i` stays refused over `sram_ctrl`'s `bind dut`,
|
||||
since opentitan has eight modules named `dut`; with it that rename
|
||||
succeeds, and the refusal still fires wherever the bind's own module
|
||||
declares an instance of the renamed module. **Known gap (QA note 1,
|
||||
accepted):** a `bind` onto an instance that exists only inside a generate
|
||||
block of the enclosing module is treated as that instance's module's and,
|
||||
when that is another module, skipped silently — upward resolution would not
|
||||
see into the generate block and would look further up.
|
||||
- **Size.** `check::verify` 94 → 79 lines: step 1 (token check) is now
|
||||
`tokens_verified`, the per-file inserted ranges `implicit::inserted_in`,
|
||||
step 3's call a two-liner. Pure moves; no behaviour change, and the same
|
||||
tests pass.
|
||||
- **Rework 2 (QA re-check, finding 3).** `Slots::takes` admitted a lone
|
||||
`,` at the end of any `.*` list; `other u_o (.*)` → `(.*,)` verified clean
|
||||
where the list binds neither name, since the tolerant parser reports no
|
||||
error. The comma is now accepted only when the same file's edits also
|
||||
insert a bare `.X(Y)` into the same list — the comma-before-`//` pair as a
|
||||
pair, mirroring the requirement the bare connection already had. QA's
|
||||
`qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name` is
|
||||
un-ignored; `a_comma_and_its_connection_in_different_lists_are_refused`
|
||||
(mine) crosses two lists' halves and is refused. The parser gap is filed
|
||||
in Handshakes.
|
||||
- **OpenTitan re-run** (scratch copy grown to 489 files: `prim`, `aes`,
|
||||
`entropy_src`, `sram_ctrl`; release, whole-set engine): `prim_count.err_o`
|
||||
→ `error_o` OK (14 files, 17 edits; two shorthands written out);
|
||||
`prim_count.clr_i` OK; `aes_core.clk_i` OK (3 files, 24 edits);
|
||||
`entropy_src.clk_i` OK (5 files, 10 edits, among them the
|
||||
`entropy_src_cov_bind.sv` `.*` gaining `.clk_i(clock_i)`);
|
||||
`prim_packer_fifo.wready_o` OK; `prim_fifo_sync.clr_i` still **refused**
|
||||
over `bind i_nopass1 …` (those instances are `prim_fifo_sync`s); the two
|
||||
`aes_ctrl_cs` renames unchanged.
|
||||
|
||||
**2026-09-23 (lead, after the final re-check).** QA finding 4 fixed by the
|
||||
lead: `check/implicit.rs::Slots::of` registers no slot for a list holding
|
||||
an error element (the engine already refuses such lists); QA's test
|
||||
un-ignored, and QA's own pin of the old behaviour in
|
||||
`qa_p_a_pair_after_an_error_element` flipped to the stricter rule. Gates
|
||||
through `tools/guard.sh`: fmt, clippy, vlog_refactor 616 passed, workspace
|
||||
4 761 passed.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-24 — QA agent.**
|
||||
@@ -1750,6 +2088,384 @@ OpenTitan with no measurable end-to-end regression. No new findings. The
|
||||
macro-invocation warning residue is unchanged and remains the lead's
|
||||
already-accepted, separately-tracked call.
|
||||
|
||||
**2026-09-23 — QA agent, M3.5 QA (implicit connections: `.name` / `.*`).**
|
||||
Charter: TODO-MCP §M3.5 — attack the widened rename verifier first
|
||||
(CLAUDE.md invariant 4), then the rewrite, LSP parity, opentitan copies,
|
||||
sizes, gates. Worked on the uncommitted master checkout; every experiment in a
|
||||
scratch copy of the repo and of opentitan `hw/ip/{prim,aes,entropy_src}`.
|
||||
|
||||
### Verdict: FAIL — one BLOCKING finding (verifier), one BLOCKING false refusal
|
||||
|
||||
### Finding 1 (BLOCKING) — an insertion is checked for its text, never its place
|
||||
|
||||
`check/implicit.rs::insertions_match` holds every inserted string to the four
|
||||
templates (`(X)`, `,`, `.X(Y)`, `, .X(Y)`, X/Y the two names) but never asks
|
||||
*where* it was inserted; the resolution print then skips every inserted range
|
||||
(`inserted_after`) and the binding print only reads named connection lists'
|
||||
connections. So a template placed anywhere else that still parses is seen by
|
||||
nothing. Driven through the crate-internal `check::verify` (the dev exposed no
|
||||
public hook) with the honest edits of a `d` → `din` port rename plus one extra
|
||||
insertion — **each of these verifies `Ok(())`**:
|
||||
|
||||
- `,` into a positional list: `leaf u_p (clk,, d, q)` — every later port
|
||||
shifts by one (silent rewiring);
|
||||
- `, .din(d)` into a parameter override `#(.W(8), .din(d))`;
|
||||
- `(d)` after a net in an expression `f(d, d(d))`; `(d)` after a task call
|
||||
`initial t(d)`; `,` / `, .din(d)` into call arguments;
|
||||
- `,` into a concatenation `{d,, d}` (the tolerant parser reports no
|
||||
diagnostic for the empty element, so the "no new parse error" guard is
|
||||
silent too);
|
||||
- inside a named list, inside an explicit connection's expression:
|
||||
`.clk(clk(d))`, `.q({q(d), q})`, `.q({q,, q})` (`net_half` prints nothing for
|
||||
a non-name expression of a port spelling neither name).
|
||||
|
||||
The engine never writes these today, which is why nothing corrupted in the
|
||||
engine-level tests — but the verifier is the safety net that is supposed to
|
||||
refuse exactly this, and the history note in invariant 4 is this shape.
|
||||
Tests: `crates/vlog_refactor/src/check/qa_implicit.rs` —
|
||||
`qa_a_comma_inserted_into_a_positional_list_is_refused`,
|
||||
`qa_connection_text_outside_a_connection_list_is_refused`,
|
||||
`qa_connection_text_inside_an_explicit_connection_is_refused`, all
|
||||
`#[ignore = "QA finding 1"]` (registered with one `#[cfg(test)] mod
|
||||
qa_implicit;` line in `check/mod.rs`, outside my file list — needed because
|
||||
`verify` is crate-internal; the lead may move it into `implicit.rs`'s tests).
|
||||
**Fix:** tie each insertion to the place `layout.rs` writes it, read off the
|
||||
*before* tree's `sites`: `(X)` only at `c.name_span.end` of a shorthand
|
||||
connection (`c.expr.is_none()`); `,`, `.X(Y)` and `, .X(Y)` only at/after the
|
||||
last element's end of a named list holding `.*`, before its `)` (with the
|
||||
`,`-before-`//` pair as the one two-piece shape). Anything else refused.
|
||||
|
||||
### Finding 2 (BLOCKING — false refusal on a common opentitan shape)
|
||||
|
||||
`connections.rs::binds_into` treats a `bind` target that is a lone name no
|
||||
indexed module answers to as "possibly an instance of the renamed module" and
|
||||
refuses whenever its list writes `.old` or a `.*` reaching `old`. opentitan's
|
||||
`hw/ip/prim/fpv/tb/prim_fifo_sync_bind_fpv.sv` has ten `bind i_nopass1
|
||||
prim_fifo_sync_assert_fpv … (.clk_i, .rst_ni, .clr_i, .wvalid_i, .wready_o,
|
||||
… .err_o)` — so on the scratch copy (449 files) renaming `prim_count`'s
|
||||
`err_o` or `clr_i`, `aes_core`'s `clk_i`, `entropy_src`'s `clk_i` or
|
||||
`prim_packer_fifo`'s `wready_o` is **refused**, over a bind into a
|
||||
`prim_fifo_sync` instance none of them touches (whole-set engine and LSP
|
||||
alike). The refusal is new in M3.5. Any module-level
|
||||
declaration named `clk_i`/`rst_ni`/`err_o`/… in any module is affected while
|
||||
that file is in the workspace; `hw/ip/sram_ctrl/dv/tb.sv`'s `bind dut … (.*)`
|
||||
is the same shape. Test: `tests/qa_rename_implicit.rs::
|
||||
qa_a_bind_into_an_instance_of_another_module_does_not_refuse`
|
||||
(`#[ignore = "QA finding 2"]`). **Fix:** resolve the lone name as an instance
|
||||
name through `WorkspaceIndex::instantiations()` (edges carry their instance
|
||||
names): if every instance so named instantiates a module other than the
|
||||
renamed declaration's, skip the site; refuse only when one is the renamed
|
||||
module's or none is found.
|
||||
|
||||
### Attacks that held
|
||||
|
||||
Verifier (`check/qa_implicit.rs::qa_insertions_the_verifier_already_refuses`,
|
||||
plus scratch experiments): an insertion inside a string, a comment, an
|
||||
attribute; an empty named element `(.a(b),, …)`; `(d)` after `.*` or after an
|
||||
explicit connection; `.din(d)` before the first element with no comma; a
|
||||
second `, .din(d)` beside the honest one (two separate insertions); a
|
||||
case-only different net `(D)` (refused by the template: `D` is neither name);
|
||||
`.d(x)` added to an instance in a generate block whose own `d` shadows the
|
||||
renamed one (binding print); `(d)` written after another module's `.d`
|
||||
shorthand (harmless, `.d(d)`, accepted — same binding); `(din)` there (refused).
|
||||
|
||||
Rewrite (`tests/qa_rename_implicit.rs`, 20 passing, public `rename` only):
|
||||
port rename over `.p` / `.*` / explicit / `.clk, .*` / `.d, .*` in one file;
|
||||
two instances in one instantiation; an instance array `leaf u[3:0] (.*)`; a
|
||||
non-ANSI port; one-per-line list with a `//` comment on the last element
|
||||
(comma before the comment, element on its own line at the element's
|
||||
indent); an inline list with a trailing `//` (element lands at column 0 — no
|
||||
indent to copy; legal, cosmetic); an attribute on a connection and a block
|
||||
comment after `.*`; an escaped net `\d$x ` renamed to a plain name (the
|
||||
terminating blank stays where it was, `.\d$x (dd) )`); a leaf port under
|
||||
nested `.*` (only the direct parent changes); a net rename reaching a `bind`
|
||||
in a file spelling neither name (the whole-set caller); a hierarchical-bind
|
||||
net rename refused; `bind top : u_t …` (instance-list form) rewritten; an
|
||||
interface port bound to an interface instance by `.*`; a generate-scoped
|
||||
shadow (module-level rename touches only the outer instance, the block's net
|
||||
only the inner two); module declared twice, `ifdef`-split list, parent `.*`
|
||||
capturing the new name — all refused with the instance named; a parameter
|
||||
named like the port is no binding; a shorthand into an unreadable module is
|
||||
still written out. **Round trip:** `d`→`din`→`d` leaves the declaring file
|
||||
byte-identical; the parent differs only in the written-out connections —
|
||||
`(.*)` becomes `(.*, .d(d))` and `.d` becomes `.d(d)`; no warnings on the way
|
||||
back.
|
||||
|
||||
### LSP parity (`server/tests/qa_rename_implicit.rs`, 3 passing)
|
||||
|
||||
Port rename with the users on disk only — the same edits as the engine; an
|
||||
unsaved open buffer using `.*` over an on-disk file connecting explicitly —
|
||||
the buffer's text is the one rewritten; a net rename reaching a bind file that
|
||||
spells neither name — handed over by `leaf`'s instantiation sites (the bound
|
||||
module declares the port, so it is a container of the name). `instantiated_by`
|
||||
reads only `self.index`, and `current_text` drops anything not held, so it
|
||||
cannot hand over a file outside the workspace. **One-hop cost on opentitan**
|
||||
(scratch copy, release, `QA_NO_HOP` toggle in a scratch build): `key_len_q` in
|
||||
`aes_core.sv` selected 4 → 23 files, select 0.6 → 1.2 ms, request 4 → 22 ms —
|
||||
and without the hop that rename is *refused* (`u_fi_ctrl_fsm … connects with
|
||||
.* to fi_control_fsm_wrapper, which lucisv cannot read`), as are the three aes
|
||||
fault-injection renames below; `prim_count.err_o` 121 → 181 files, 46 → 59 ms.
|
||||
No explosion.
|
||||
|
||||
### Opentitan dry runs (scratch copy, whole-set engine and LSP agree)
|
||||
|
||||
- `fi_control_fsm_wrapper`'s port `aes_ctrl_cs` → `aes_ctrl_state`:
|
||||
`bind aes_control_fsm … u_fi_ctrl_fsm (.*)` gains
|
||||
`.aes_ctrl_state(aes_ctrl_cs)` (binds `aes_control_fsm`'s own state
|
||||
variable — what `.*` bound) and the wrapper's `fi_if (.*)` gains
|
||||
`.aes_ctrl_cs(aes_ctrl_state)`. Correct by hand.
|
||||
- `aes_control_fsm`'s variable `aes_ctrl_cs` → `aes_ctrl_cs_q`: the bind gains
|
||||
`.aes_ctrl_cs(aes_ctrl_cs_q)`. Correct; the `PRIM_FLOP_SPARSE_FSM`/`ASSERT`
|
||||
invocations still spelling the old name are warned (existing macro policy).
|
||||
- `fi_control_if`'s port `aes_ctrl_cs` → `ctrl_state`: the wrapper's `.*`
|
||||
gains `.ctrl_state(aes_ctrl_cs)`. Correct.
|
||||
- `entropy_src_fsm_cov_if`'s `state_i` → `st_i`: tb.sv's
|
||||
`bind prim_sparse_fsm_flop : dut.… (.clk_i, .state_i, .state_o)` becomes
|
||||
`.st_i(state_i)`. Correct.
|
||||
- `prim_fifo_sync`'s `clr_i`: refused over `prim_fifo_sync_bind_fpv.sv`'s
|
||||
`.clr_i` — a *correct* refusal (those binds target `prim_fifo_sync`
|
||||
instances). `prim_count`/`aes_core`/`entropy_src`/`prim_packer_fifo`: the
|
||||
false refusals of finding 2.
|
||||
- Every rewrite was listed in `warnings`, one sentence each.
|
||||
|
||||
### Sizes / style
|
||||
|
||||
Production lines (non-blank, non-`//` lines before `#[cfg(test)] mod tests {`):
|
||||
`rename/connections.rs` 434, `rename/sites.rs` 168, `rename/layout.rs` 82,
|
||||
`rename/mod.rs` 433 (HEAD 423), `check/implicit.rs` 318, `check/mod.rs` 420
|
||||
(HEAD 405), `module_select.rs` 36, `state/mod.rs` 985 (HEAD 981 — already over,
|
||||
§55). Functions over 50 lines: `check::verify` 94 (HEAD 75 — now past the
|
||||
"investigate at 80" mark), `check::implicit::bindings_match` 60,
|
||||
`rename::renaming` 56 (HEAD 50); `verify_move` 101 is pre-existing. No
|
||||
`unwrap`/`expect`/`panic!`/`#[allow]` in the new production code.
|
||||
|
||||
### Gates (all through `tools/guard.sh`, one at a time)
|
||||
|
||||
- `cargo fmt -p vlog_refactor -p lucisv_server -p lucisv_mcp -- --check` — clean
|
||||
(after formatting my three files).
|
||||
- `cargo clippy -p vlog_refactor -p lucisv_server -p lucisv_mcp --all-targets` —
|
||||
`Finished`, no warnings.
|
||||
- `cargo test -p vlog_refactor` — 587 passed, 0 failed, 6 ignored.
|
||||
- `cargo test -p lucisv_server` — 1713 + 99 + 3 passed, 0 failed.
|
||||
- `cargo test -p lucisv_mcp` — 0 failed; `qa_rename_never_breaks_an_implicit_port_connection`
|
||||
(M3 finding 1, un-ignored) passes.
|
||||
- `cargo test --workspace` — **4 732 passed, 0 failed, 52 ignored**
|
||||
(4 707 + 25 QA tests; 4 new ignored findings tests).
|
||||
|
||||
**2026-09-23 — QA agent, M3.5 re-check (after the dev's rework).** Charter:
|
||||
re-derive both blocking findings against the fix (`Slots` in
|
||||
`check/implicit.rs`; `bind_reaches`/`instance_owners` in
|
||||
`rename/connections.rs`), confirm the three moves out of `verify` are pure,
|
||||
re-run the opentitan copy, gates.
|
||||
|
||||
### Verdict: FAIL — findings 1 and 2 closed; one new BLOCKING finding (3); one non-blocking note
|
||||
|
||||
### Finding 3 (BLOCKING, new) — a lone `,` at the end of any `.*` list verifies
|
||||
|
||||
`Slots::takes` admits `Template::Comma` at the end of every `.*` list, alone.
|
||||
The engine only ever writes it as the first half of the comma-before-`//`
|
||||
pair, whose second half (`.X(Y)`, `Template::Connection`) is already required
|
||||
to have the comma (`comma_at`) — but not the other way round. Where the list
|
||||
binds one of the two names the binding print refuses the cut; where it binds
|
||||
neither (a `.*` into a module declaring neither name, in a file the rename
|
||||
edits for another reason) nothing refuses: the tolerant parser reports no
|
||||
diagnostic for `(.*,)` (the same leniency as `{d,, d}` in round one), the
|
||||
pieces match, and the binding print has nothing to compare. Reproduction:
|
||||
`check/qa_implicit.rs::qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name`
|
||||
(`#[ignore = "QA finding 3"]`) — `other u_o (.*)` becomes `other u_o (.*,)`
|
||||
beside an honest `.d` → `.din(d)` rewrite in the same file, and `verify`
|
||||
returns `Ok(())`. Not a shape the engine writes today; a masked corruption the
|
||||
safety net accepts, the class invariant 4 is about. **Fix** (a few lines in
|
||||
`Slots::takes`): admit `Comma` at a list's end only when the same edit list
|
||||
also inserts a `Connection` into that list (after trivia, before its `)`) —
|
||||
the mirror of `comma_at`. Worth also filing against the tolerant parser: a
|
||||
trailing `,` in a named connection list and an empty concatenation element
|
||||
parse without a diagnostic.
|
||||
|
||||
### Finding 1 re-derived — the position rule (9 new tests + finding 3, `check/qa_implicit.rs::qa_r_*`)
|
||||
|
||||
All verifier-direct (`check::verify`, crate-internal), each a corrupt edit set
|
||||
beside a control that verifies `Ok`:
|
||||
|
||||
- `, .din(d)` appended to a named list **without** `.*` — refused "outside a
|
||||
connection list";
|
||||
- `(d)` after an **explicit** connection's name (`.clk(d)(clk)`,
|
||||
`.din(d)(d)`) — outside;
|
||||
- `, .din(d)` **between** `.*` and a later `.clk(clk)` — outside (the same
|
||||
text after the last element verifies);
|
||||
- `, .din(d)`, `(d)`, `,` **after the `)`** — outside;
|
||||
- a `.*` list **inside a generate-for**: the honest append verifies, a bare
|
||||
`.din(d)` without its comma is outside, nothing added is a cut;
|
||||
- a **lone trailing `,`** at a `.*` list's end (`(.*,)`, a legal *slot* for the
|
||||
comma-before-`//` shape) where the list binds `d` — refused, but by the
|
||||
binding print (`din` loses its binding), not by the position rule; where the
|
||||
list binds neither name it verifies — finding 3;
|
||||
- **shift accounting**: `d` → `dnew` in `(.clk,.d,.q)` grows the line by
|
||||
exactly the distance from `.d`'s end to `.q`'s end, so a tail computed in
|
||||
after-coordinates lands on `.q`'s shorthand slot in before-coordinates.
|
||||
The before-coordinate tail verifies; the shifted one (`.dnew,.q(d)`) is
|
||||
refused by the binding print. Slots and edits are both in before-coordinates
|
||||
(`Slots::of(before)`, `edit.range.start`), so there is no mixed accounting;
|
||||
- an append **inside the trailing `//` comment** (mid-comment and at its end):
|
||||
`Slots::takes` admits it (the gap is trivia), the piece ledger refuses it; the
|
||||
honest `,` + `\n .din(d)` pair verifies; the bare connection without the
|
||||
comma is outside; the pair with the connection written mid-comment is
|
||||
refused;
|
||||
- a **shorthand in a `bind`** (net rename): `(x)` after `.d` verifies,
|
||||
nothing is a cut, `(x)` after `.clk` (a legal slot) is refused by the binding
|
||||
print, `(d)` after `.d` is refused.
|
||||
|
||||
My three round-one tests and the dev's two same-offset tests pass un-ignored.
|
||||
|
||||
### Finding 2 re-derived — the enclosing-module rule (5 new tests + 1 note, `tests/qa_rename_implicit.rs::qa_b_*`)
|
||||
|
||||
Renaming `cnt`'s `err_o`, with `chk` bound by `.clk_i, .err_o` shorthands:
|
||||
|
||||
- a bind in module `a` onto `u`, where `a`'s own `u` is a `fifo` and `b`'s `u`
|
||||
is a `cnt` — **skipped**, `a.sv` untouched, `b`'s own `.err_o` written out;
|
||||
- swapped (`a`'s `u` is the `cnt`) — **refused**, naming `c_u` at a.sv:4;
|
||||
- a bind at **file scope** onto `u` where only `tb`'s `u` exists, a `fifo` —
|
||||
skipped, no warning; the same where `tb`'s `u` is a `cnt` — refused;
|
||||
- a bind onto a name no indexed instance has — refused.
|
||||
|
||||
### Note 1 (non-blocking, lead-accepted) — the generate-block gap, reproduced
|
||||
|
||||
`module a` with `fifo u` only inside `if (1) begin : g`, `bind u chk c_u
|
||||
(.clk_i, .err_o)` in `a`, and a parent `p` holding `a u_a ()` and `cnt u`.
|
||||
Upward resolution from `a` does not see `a.g.u`, so the bind reaches `p.u`, a
|
||||
`cnt`. The engine counts `a.g.u` as `a`'s own, returns `Elsewhere`, and the
|
||||
rename **succeeds** with `a.sv` untouched — the bind's `.err_o` is cut. Note the
|
||||
direction: this is a silent skip, not a refusal, and the verifier cannot catch
|
||||
it (a bind onto an instance prints `Opaque` on both sides). Exotic shape (a
|
||||
same-named instance in a generate block of the binding module *and* in its
|
||||
parent). Pinned as `qa_b_a_generate_scoped_instance_is_not_the_enclosing_modules_own`
|
||||
`#[ignore = "QA note 1: accepted generate-block gap"]`, asserting the refusal.
|
||||
Cheapest fix if the lead wants it: count an edge as local only when its
|
||||
instance is declared in the module's own scope, or refuse whenever a local
|
||||
same-named instance sits inside a generate block.
|
||||
|
||||
### `verify`'s three moves — pure
|
||||
|
||||
Compared the round-one body with the current one line by line: step 1's loop
|
||||
moved verbatim into `tokens_verified` (same `measure` stage — `trace.tokens` —
|
||||
per file, `names[1]` is `new_name`); the `inserted` lookup became
|
||||
`implicit::inserted_in(edits, i)`, the same `find` + `inserted_after` +
|
||||
`unwrap_or_default`; step 3 binds `names` to a local before the same call. No
|
||||
behaviour change. `verify` is 79 lines.
|
||||
|
||||
### Opentitan copy, re-run (engine whole-set and LSP fan-out agree on every edit count)
|
||||
|
||||
| rename | result |
|
||||
|---|---|
|
||||
| `fi_control_fsm_wrapper.aes_ctrl_cs` → `aes_ctrl_state` | 2 files, 3 edits (bind `.*` + wrapper `.*`), as round one |
|
||||
| `aes_control_fsm.aes_ctrl_cs` → `aes_ctrl_cs_q` | 2 files, 4 edits, as round one |
|
||||
| `fi_control_if.aes_ctrl_cs` → `ctrl_state` | 2 files, 3 edits, as round one |
|
||||
| `entropy_src_fsm_cov_if.state_i` → `st_i` | 2 files, 3 edits, as round one |
|
||||
| `prim_fifo_sync.clr_i` → `clear_i` | refused over `prim_fifo_sync_bind_fpv.sv`'s `.clr_i` — correct, those binds target fifo instances |
|
||||
| `prim_count.err_o` → `error_o` | **now succeeds**: 13 files, 16 edits; `.err_o` written out in `prim_count_tb.sv` and `prim_packer.sv` |
|
||||
| `prim_count.clr_i` → `clear_i` | **now succeeds**: 13 files, 16 edits; three `.clr_i` shorthands written out (tb, `prim_fifo_sync_cnt` ×2) |
|
||||
| `aes_core.clk_i` → `clock_i` | **now succeeds**: 3 files, 24 edits |
|
||||
| `aes_core.key_len_q` → `key_len_qq` | 1 file, 3 edits |
|
||||
| `entropy_src.clk_i` → `clock_i` | **now succeeds**: 5 files, 10 edits; `.clk_i(clock_i)` in three internal instances and two `bind entropy_src` asserts, `, .clk_i(clock_i)` on the cov bind's `.*` |
|
||||
| `prim_packer_fifo.wready_o` → `wready_q` | **now succeeds**: 5 files, 13 edits; the two `bind prim_packer_fifo : dut.…` lists get `.wready_o(wready_q)` |
|
||||
|
||||
Each rewrite checked by hand against what the implicit connection bound; each
|
||||
is listed in `warnings`. LSP fan-out sizes: 14–312 files, 9–213 ms per
|
||||
request (`clk_i` of `aes_core`/`entropy_src` are the 312-file ones).
|
||||
|
||||
### Gates (each through `tools/guard.sh`, one at a time)
|
||||
|
||||
- `cargo fmt -p vlog_refactor -p lucisv_server -p lucisv_mcp -- --check` — clean.
|
||||
- `cargo clippy -p vlog_refactor -p lucisv_server -p lucisv_mcp --all-targets` — `Finished`, no warnings.
|
||||
- `cargo test -p vlog_refactor` — 609 passed, 0 failed, 4 ignored.
|
||||
- `cargo test -p lucisv_server` — 1713 + 99 + 3 passed, 0 failed.
|
||||
- `cargo test -p lucisv_mcp` — 206 passed, 0 failed, 2 ignored.
|
||||
- `cargo test --workspace` — **4 754 passed, 0 failed, 50 ignored** (4 740 +
|
||||
14 new QA tests; the two new ignored tests are note 1 and finding 3).
|
||||
|
||||
**2026-09-23 — QA agent, M3.5 final re-check (finding 3 fix: the comma/connection pair).**
|
||||
Charter: re-derive finding 3, attack the pair rule in `Slots::takes`, confirm
|
||||
my finding-3 test is unchanged, re-run the opentitan copy, gates.
|
||||
|
||||
### Verdict: FAIL — finding 3 closed; one new BLOCKING finding (4), same class
|
||||
|
||||
### Finding 3 — closed
|
||||
|
||||
`qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name` now passes
|
||||
un-ignored. Diffed against the text I wrote (reconstructed from my own edit):
|
||||
**byte-identical apart from the removed `#[ignore = "QA finding 3"]` line**.
|
||||
The dev's cross-list test passes.
|
||||
|
||||
### Pair-rule attacks (`check/qa_implicit.rs::qa_p_*`, 4 new passing tests)
|
||||
|
||||
- `,` in one file's list and its `.din(d)` in another file's list, both ways —
|
||||
refused "outside a connection list" (each file's edits are checked alone).
|
||||
The honest pair in both files verifies.
|
||||
- two `,` and one `.din(d)` in one list — refused (the tolerant parser does
|
||||
flag `.*,,` followed by a connection); one `,` and two `.din(d)` — refused
|
||||
(binding print).
|
||||
- `.din(d)` before its `,` at the same offset (`.*\n .din(d), // …`) and
|
||||
glued (`.*.din(d),`) — refused (parse). In source order at the same offset
|
||||
(`.*,\n .din(d) // the rest`) it verifies: a legal list, the same
|
||||
bindings, the comment kept (it now ends the new line) — accepted, harmless.
|
||||
- a pair in a `.*` list whose last element is an error element: see finding 4.
|
||||
Where the "error element" is not SV at all (`+.din(x)`) the before file
|
||||
already does not compile; the verifier admits the pair after it (pinned).
|
||||
|
||||
### Finding 4 (BLOCKING by the rule; loud, not silent) — a slot at an error element's end
|
||||
|
||||
`Slots::of` registers a `.*` list whose last element is `ListElem::Error`,
|
||||
with the element's end as the append point. `.d(type(q)'(q))` is valid SV (a
|
||||
cast through a type reference — 1800-2017 A.8.4 `constant_primary ::=
|
||||
type_reference`) that the tolerant parser reads as the error element
|
||||
`.d(type(q)'(q)`, one byte short of the connection's own `)`. An append there
|
||||
lands **inside** that connection: `leaf u_e (.*, .din(type(q)'(q), .din(d)));`
|
||||
— valid input, output that does not compile — and `verify` returns `Ok(())`:
|
||||
the parse check compares diagnostic *counts* (one before, one after), and the
|
||||
binding print cannot see into an error element. The engine never writes it
|
||||
(`unreadable_elements` refuses a list whose error element spells either
|
||||
name), so nothing ships broken today; it is the verifier accepting what it
|
||||
exists to refuse, the class of findings 1 and 3. Reproduction:
|
||||
`check/qa_implicit.rs::qa_p_an_append_at_an_error_elements_end_is_refused`
|
||||
(`#[ignore = "QA finding 4"]`); the same append after the connection's `)` is
|
||||
refused (`qa_p_a_pair_after_an_error_element`). **Fix** (a few lines in
|
||||
`Slots::of`): register no list slot — and no tail — for a site whose `conns`
|
||||
hold an error element (or, mirroring the engine exactly, one whose error text
|
||||
spells either name or `*`). Worth adding to the vlog_parser handshake: `type(x)'(y)`
|
||||
in a port connection parses as an error element.
|
||||
|
||||
### Opentitan copy, re-run — identical
|
||||
|
||||
All 11 renames of the previous table, whole-set engine and LSP fan-out:
|
||||
the per-edit and per-warning output is **identical** to the previous run
|
||||
(diffed with timings stripped).
|
||||
|
||||
### Gates (each through `tools/guard.sh`, one at a time; no guard kill)
|
||||
|
||||
- `cargo fmt -p vlog_refactor -p lucisv_server -p lucisv_mcp -- --check` — clean.
|
||||
- `cargo clippy -p vlog_refactor -p lucisv_server -p lucisv_mcp --all-targets` — `Finished`, no warnings.
|
||||
- `cargo test -p vlog_refactor` — 615 passed, 0 failed, 4 ignored.
|
||||
- `cargo test --workspace` — **4 760 passed, 0 failed, 50 ignored**, 135 s
|
||||
(4 756 + 4 new QA tests; the new ignored test is finding 4).
|
||||
|
||||
**2026-09-23 — QA agent, M3.5 final confirmation (finding 4 fix, lead-applied).**
|
||||
Read the change: `Slots::of` skips every site with `site.unreadable()` — no
|
||||
shorthand tail, no append point — with the finding cited; the only change to
|
||||
my file is the junk-list pin in `qa_p_a_pair_after_an_error_element` flipped to
|
||||
`outside` (correct: that list has no slot now). Re-derived against the built
|
||||
verifier: the cast-list append inside the connection (`.din(type(q)'(q),
|
||||
.din(d)))`) is refused; the same append after the connection's `)` is
|
||||
refused; new `qa_p_a_clean_list_beside_an_error_element_list_still_verifies`
|
||||
— an honest `.*` append and `.d` → `.din(d)` in clean lists verify beside an
|
||||
untouched `other u_x (.*, .clk(type(clk)'(clk)))` in the same file, and an
|
||||
append into that list is refused "outside a connection list". Consequence
|
||||
noted, non-blocking: a `.*` list holding an error element that genuinely needs
|
||||
a rewrite is now refused by the verifier even where the engine would append
|
||||
(error text spelling neither name) — a refusal, never a corruption, and only
|
||||
for lists lucisv cannot parse. `tools/guard.sh -- cargo test -p vlog_refactor`:
|
||||
617 passed, 0 failed, 3 ignored. **Verdict: PASS** — findings 1–4 closed; QA
|
||||
note 1 (generate-block gap) stands as the lead's accepted known gap.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead, performance-wave Lane A.** Reviewed after QA's
|
||||
@@ -1848,3 +2564,26 @@ engine's more precise words (pinned by the control test
|
||||
costs under 0.2 ms over all 3 979 OpenTitan files and reads nothing, so the
|
||||
`prepare_rename_here` cost stays gone. Details and measurements:
|
||||
`docs/features/macro-word-census/README.md`.
|
||||
|
||||
**Lead, 2026-09-23 (M3.5).** The defect was a CLAUDE.md invariant-1
|
||||
corruption in a shipped engine — a rename cut `.name`/`.*` bindings and
|
||||
verified clean because nothing records what an implicit connection binds —
|
||||
found only when the MCP block put `rename` in front of an adversarial QA.
|
||||
The fix is the right shape: insertion-only rewrites through four spelled
|
||||
templates, every rewrite in the warnings, every unreadable case refused by
|
||||
name, and a verifier that prints every implicit binding before and after
|
||||
(`check/implicit.rs`). That verifier is a widening of the rename's safety
|
||||
contract, so invariant 4's discipline applied: three QA rounds attacked it
|
||||
and found, in order, that it checked what an insertion spells but not where
|
||||
it lands (fixed: slots keyed on the before-tree's sites), that a lone `,`
|
||||
at the end of a `.*` list passed (fixed: the comma and its `.X(Y)` are
|
||||
accepted only as a pair in one list), and that a list holding an error
|
||||
element registered a slot at the element's end (fixed by the lead: such a
|
||||
list has no slot; QA's pin flipped to the stricter rule). Rulings: the
|
||||
enclosing module's own instances win a bare-name `bind` (§23.11); the
|
||||
generate-scoped instance is an accepted, documented gap; the LSP hands the
|
||||
engine one more hop of instantiated modules so a `.*` into a module
|
||||
declaring neither name is read, not refused. Filed for the owner: the
|
||||
tolerant parser's leniency on a trailing `,` and `{d,, d}`, and
|
||||
`type(x)'(y)` in a connection parsing as an error element (vlog_parser).
|
||||
Committed as M3.5; ships in 0.56.0.
|
||||
@@ -0,0 +1,472 @@
|
||||
# MCP for lucisv — the plan
|
||||
|
||||
Written 2026-09-23 by the lead, at 0.55.0 (`ef867db`), before any MCP code
|
||||
exists. Companion: [`TODO-MCP.md`](../../TODO-MCP.md) holds the lanes and
|
||||
checkboxes; this file holds the analysis and the design they follow. Both are
|
||||
deliberately separate from `TODO.md` and `docs/topo.md`: MCP is a new block,
|
||||
and the owner asked that it stay one.
|
||||
|
||||
MCP is the Model Context Protocol: JSON-RPC 2.0 between a *host* (an agent
|
||||
such as Claude Code, Cursor, or VS Code's agent mode) and a *server* that
|
||||
offers **tools** (callable functions with a JSON schema), **resources**
|
||||
(readable URIs) and **prompts**. An agent that has lucisv as an MCP server
|
||||
can ask "what are the ports of `prim_fifo_sync`" and get thirty lines back,
|
||||
instead of reading a 2 000-line file; and can say "rename `req_i` across the
|
||||
design" as one call, instead of forty reads and forty edits.
|
||||
|
||||
## 1. Goal
|
||||
|
||||
Ship `lucisv-mcp`: one binary, MCP over stdio, that gives coding agents
|
||||
**project understanding** (units, interfaces, hierarchy, definitions,
|
||||
references, outlines, diagnostics) and **token-saving edits** (verified
|
||||
refactorings, formatting, lint fixes, and item-level structural replacement)
|
||||
over a Verilog/SystemVerilog tree — using the six library crates directly,
|
||||
sharing no code path with `lucisv-server` (LSP) or the `lucisv` CLI, and
|
||||
shipped inside every platform `.vsix` next to the two binaries already there.
|
||||
|
||||
Three properties the owner asked for, and how they are met:
|
||||
|
||||
| ask | how |
|
||||
|---|---|
|
||||
| **independent from LSP and the CLI** | A new crate `crates/lucisv_mcp` with its own binary. It depends on `lucisv_core`, `vlog_parser`, `vlog_semantic`, `vlog_refactor`, `vlog_formatter`, `vlog_linter`, `serde`, `serde_json` — never on `lucisv_server` (which is bin-only anyway) or `lsp-types`. It has its own workspace loader, its own tool handlers and its own tests. A change to the LSP server cannot break it except through a library crate's public API, which is already the contract every crate lives by |
|
||||
| **supports interacting with them** | Three seams, all one-directional and file-based: (1) the same `lucisv.toml` discovery, filelist and walk (`lucisv_core`) so MCP indexes the set the editor and CLI see; (2) edits are atomic on-disk writes (`lucisv_core::atomic`) that the LSP's file watcher already picks up, so the editor's index follows an agent's MCP edit without either side knowing the other; (3) the LSP's persistent index cache is read **read-only** as a warm-start shortcut when the extension tells both processes the same store path (§6). The VS Code extension is the fourth seam: it spawns the LSP and registers the MCP server, and is the only place that knows both |
|
||||
| **ships with the VS Code plugin** | A third binary in every platform `.vsix` (`extension/bin/lucisv-mcp`), registered through VS Code's `contributes.mcpServerDefinitionProviders` + `vscode.lm.registerMcpServerDefinitionProvider` so VS Code's agent mode finds it with no user configuration; plus a "copy MCP config" command for hosts that do not read VS Code's registry (Claude Code, Cursor) |
|
||||
|
||||
## 2. What we have (the analysis)
|
||||
|
||||
Surveyed 2026-09-23. File:line references are at 0.55.0.
|
||||
|
||||
### 2.1 The engines are all library crates; the orchestration is not
|
||||
|
||||
Every language answer already lives in a library crate with a protocol-free
|
||||
API (`docs/topo.md` §1.2 is the authority):
|
||||
|
||||
- **Semantics**: `vlog_semantic::analyze(&SourceFile, &str) -> Semantics`
|
||||
(never fails), `Semantics::{definition_of, references_of, document_symbols,
|
||||
symbols_named, …}`; `WorkspaceIndex::build((PathBuf, &str)…)` and
|
||||
`IndexBuilder::{add_file, add_facts, finish}` (order-independent); queries
|
||||
`units`, `units_of`, `instantiable_units`, `workspace_symbols`, `members_of`,
|
||||
`member_in(…, Surface)`, `instantiations_of`/`instantiations()`,
|
||||
`subclasses_of`, `references_to`, `find_define`, `files_mentioning`;
|
||||
`resolve_external(&Semantics, &WorkspaceIndex)` for cross-file definition;
|
||||
`FileFacts::{of, analyzed, encode, decode}` with `FACTS_FORMAT = 20`; the
|
||||
incremental `update_file`/`absorb`/`remove_file` with `fingerprint()` as the
|
||||
rebuild-equality oracle.
|
||||
- **Refactorings**: `vlog_refactor` does no I/O — every entry point takes the
|
||||
in-scope `&[(PathBuf, String)]` and returns `Result<RefactorEdit, String>`
|
||||
(edits per file + warnings + created files), whole-edit verified in memory:
|
||||
`rename`, `find_references`, `expand_wildcard`, `add_port`, `remove_port`,
|
||||
`propagate_ports`, `convert_to_ansi`, `organize_imports`, `extract_module`,
|
||||
`inline_module`; `instantiation_plan` (text, no edit); `module_names`,
|
||||
`module_definition`.
|
||||
- **Formatter**: `format_source` / `format_range` + `LineRanges`, the safety
|
||||
net inside; `fence::protected_regions` for "may an automatic edit touch
|
||||
these bytes".
|
||||
- **Linter**: `LintContext::from_parse(...).with_semantics(...).with_oracle(...)`,
|
||||
`lint_with(ctx, rules, &ExternalWaivers)`, `select_rules`, `apply_fixes`,
|
||||
`rules_markdown()`; the `MentionOracle` trait for the cross-file rules.
|
||||
- **Core**: `config::Discovery` (`lucisv.toml` upward search),
|
||||
`filelist::read`, `walk::collect_files_with` (`.gitignore` + `--exclude`
|
||||
+ cycle-safe), `atomic::write_atomic`, `cache::content_hash` (FNV-1a).
|
||||
|
||||
What exists **only** inside `lucisv_server` (bin-only; nothing linkable):
|
||||
|
||||
| orchestration | where | MCP's stance |
|
||||
|---|---|---|
|
||||
| which files to index (filelist → roots walk → folder scope depth 2; 1 MiB cap; client excludes) | `state/discover.rs:283-379` | re-done in ~80 lines over `lucisv_core` with a simpler ladder (§4.2); no editor settings exist here |
|
||||
| the scan loop (batches, cache read-through, merge) | `state/mod.rs:825-1224`, `state/scan.rs` | not needed: MCP builds the index once at startup and keeps it fresh per call (§4.4) |
|
||||
| per-document analysis sequence (tokenize → parse_tolerant → defines → analyze → resolve_external → LineIndex) | `state/mod.rs:119` `Document::new` | the same six library calls, ~30 lines |
|
||||
| cross-file references with open-buffer overlay and stale-span guards | `nav.rs:123-519` | not needed: MCP has no open buffers; `vlog_refactor::find_references` is the whole-scope oracle the server's answer is pinned equal to |
|
||||
| hover card rendering | `hover.rs` | MCP renders its own compact text (§5.1) |
|
||||
| design hierarchy snapshot (pure function of the index) | `design_hierarchy.rs:88` | re-done as a walk over `instantiations()` edges; a later lift into `vlog_semantic` is a §2.9-style candidate, not a plan item |
|
||||
| index-backed `MentionOracle` (`IndexMentions`, ~40 lines) | `lint.rs:487-530` | copied; it is a thin adapter over public index queries |
|
||||
| persistent index cache codec (header + one record per line) | `index_cache.rs:40,545-559,607-640` | a read-only reader (~60 lines) over the public `FileFacts::decode`; §6 |
|
||||
| file watching, cancel, debounce, settings doors | `watch.rs`, `server/` | not applicable: stdio, synchronous, one request at a time |
|
||||
|
||||
The CLI has a second bin-only `MentionOracle` (`crates/lucisv/src/lint.rs:196`)
|
||||
and the unified-diff printer `crates/lucisv/src/diff.rs::unified` — the one
|
||||
piece MCP would like to share (dry-run diffs). It is a Handshake request to
|
||||
lift it into `lucisv_core` (§7), not a silent copy.
|
||||
|
||||
### 2.2 The extension and the packaging
|
||||
|
||||
`editors/vscode` is plain CommonJS, one runtime dependency
|
||||
(`vscode-languageclient` 9.0.1), engine `^1.82.0`. The server binary is found
|
||||
by `extension.js:152` in this order: an explicitly set `lucisv.serverPath`,
|
||||
then `bin/lucisv-server` (platform vsix) or `bin/<platform>-<arch>/lucisv-server`
|
||||
(the all-platforms vsix; `bundledBinary()` at `:121-138` is generic and
|
||||
takes the binary name), then `lucisv-server` on `PATH`. The bundled `lucisv`
|
||||
CLI is chmod'ed but never spawned (`:145`). No second process, no status bar.
|
||||
|
||||
`tools/release.sh` stages `lucisv` and `lucisv-server` into
|
||||
`editors/vscode/bin/` and asserts each platform vsix holds **exactly** those
|
||||
two entries (`:158-191`), the all-platforms vsix every pair (`:202-224`);
|
||||
`tools/audit_artifacts.sh` hard-fails on an unknown artifact name;
|
||||
`tools/prune_release_assets.sh` requires the seven vsix by name; CI's
|
||||
`release.yml` runs all three. Adding a third binary is therefore a
|
||||
three-script change with a test-locked file list — exactly the kind of wire
|
||||
shape `docs/topo.md` §3.4 rule 5 says to change *by test*.
|
||||
|
||||
`ci.yml` runs cargo fmt/clippy/test and the corpus gate; it runs **no**
|
||||
extension JavaScript tests (`*_test.js` are run by hand; `smoke.js` runs in
|
||||
the release workflow only). The MCP work adds a stdio wire test that CI
|
||||
runs, and is a good moment to put `node --test editors/vscode/*_test.js` in
|
||||
CI too (a separate line in the packaging lane).
|
||||
|
||||
### 2.3 How VS Code hosts extension-provided MCP servers
|
||||
|
||||
Confirmed against the VS Code extension guide (2026-09-23):
|
||||
|
||||
- `package.json`: `"contributes": { "mcpServerDefinitionProviders": [{ "id": "lucisv.mcp", "label": "lucisv" }] }`.
|
||||
- Activation: `vscode.lm.registerMcpServerDefinitionProvider("lucisv.mcp", provider)`
|
||||
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 })`.
|
||||
- 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).
|
||||
- The API landed in VS Code 1.101 (June 2025). Our engine is `^1.82.0`.
|
||||
**Decision:** keep the engine, guard the registration with
|
||||
`typeof vscode.lm?.registerMcpServerDefinitionProvider === "function"`, and
|
||||
bump only if `vsce` refuses the contribution point on packaging (it does
|
||||
not validate unknown contribution points today; the lane verifies). An
|
||||
older VS Code simply never sees the MCP server.
|
||||
|
||||
### 2.4 What an agent pays today, and what MCP saves
|
||||
|
||||
Without MCP an agent working on a Verilog tree has file tools and grep. The
|
||||
recurring costs, each of which becomes one small tool call:
|
||||
|
||||
| task | today | with MCP |
|
||||
|---|---|---|
|
||||
| "what does module X take?" | read the whole file (a 40 000-line opentitan file is not rare) | `unit_interface` — ports, parameters, one instantiation template |
|
||||
| "who instantiates X / what is under X?" | grep the tree, read every hit to tell instances from mentions | `hierarchy` — the index's instantiation edges, depth-limited |
|
||||
| "where is `foo` defined / used?" | grep, read, disambiguate by hand across packages and hierarchical tails | `definition` / `references` — the same cross-file semantics the editor has |
|
||||
| "rename / add a port / expand `.*`" | read N files, write N files, hope the edits agree | one verified `RefactorEdit`, applied atomically; a diff summary back |
|
||||
| "rewrite this always block" | read the file, write the whole file back (and re-send it all as tokens) | `replace_item` — send only the new item's text; the tool re-parses and refuses if the file no longer parses |
|
||||
| "is my edit clean?" | run a simulator, or nothing | `diagnostics` — parse errors + lint with the project's rules; `format` — the verified formatter |
|
||||
|
||||
The saving is not asserted with numbers here; it is **measured in M6** on
|
||||
three canonical opentitan tasks with and without the server (§8).
|
||||
|
||||
## 3. Non-goals (stated so nobody builds them by accident)
|
||||
|
||||
- **Not an LSP bridge.** MCP never talks to `lucisv-server`; it never sees
|
||||
unsaved editor buffers. A tool answers from disk, and says so in its
|
||||
description. (VS Code reloads a non-dirty editor when a file changes on
|
||||
disk; a dirty editor shows a conflict — the standard behaviour of any
|
||||
external tool, and the `dry_run` flag exists for agents that prefer to
|
||||
apply edits through their own editor.)
|
||||
- **No HTTP/SSE transport, no OAuth.** Stdio only, like the LSP. A host that
|
||||
needs HTTP can wrap the stdio server; none of our target hosts do.
|
||||
- **No shell, no arbitrary file writes.** Edit tools write only files inside
|
||||
the configured roots, only through `write_atomic`, only text that passed
|
||||
a verifier. There is no "run this command" tool and there never will be.
|
||||
- **No AI in the server.** It calls no model. It is a deterministic engine
|
||||
behind a schema; the agent is on the other side of the pipe.
|
||||
- **No new grammar or semantics.** Every tool is a composition of existing
|
||||
library calls plus rendering. A tool that needs an engine change files a
|
||||
Handshake (the CLAUDE.md rule) — it does not add language knowledge to the
|
||||
MCP crate.
|
||||
|
||||
## 4. Design
|
||||
|
||||
### 4.1 Crate and binary
|
||||
|
||||
`crates/lucisv_mcp`, binary `lucisv-mcp`, `version.workspace = true`.
|
||||
|
||||
```
|
||||
crates/lucisv_mcp/src/
|
||||
main.rs arguments (--root DIR…, --filelist F, --index-cache DIR,
|
||||
--verbose), the stack-sized main thread, the loop
|
||||
transport.rs newline-delimited JSON-RPC 2.0 over stdio: read one line,
|
||||
write one line; stderr is the log
|
||||
rpc.rs the JSON-RPC envelope: id, method, params, error codes;
|
||||
the initialize handshake and protocol-version negotiation
|
||||
tools/mod.rs the tool registry: name → (schema, annotations, handler)
|
||||
tools/read.rs project_overview, list_units, unit_interface, outline,
|
||||
read_item, search_symbols, defines
|
||||
tools/nav.rs definition, references, hierarchy, diagnostics
|
||||
tools/edit.rs format, fix_lint, rename, expand_wildcard, convert_ports,
|
||||
organize_imports, add_port, remove_port, propagate_ports,
|
||||
extract_module, inline_module, instantiate
|
||||
tools/item.rs replace_item, insert_item, delete_item (M4)
|
||||
project.rs Project: roots, config, the file set, the index, the
|
||||
per-file analyses, freshness (§4.4)
|
||||
render.rs the compact text renderings of every answer
|
||||
apply.rs RefactorEdit → dry-run diff | atomic writes; the summary
|
||||
resources.rs lucisv://… resources (M2)
|
||||
```
|
||||
|
||||
Every file targets the CLAUDE.md size rule (300–600 production lines); the
|
||||
tool families are split so that no single module owns more than one family.
|
||||
|
||||
**Dependencies: none new.** The MCP stdio transport is newline-delimited
|
||||
JSON-RPC, which `serde_json` (already pinned) handles; the protocol's data
|
||||
model is small enough to spell out as `serde` structs in `rpc.rs`. The
|
||||
official Rust SDK (`rmcp`) was considered and rejected for the same reason
|
||||
`lsp-server` was chosen over `tower-lsp`: it brings an async runtime and a
|
||||
large transitive tree to a server that is one synchronous loop. The
|
||||
justification lives in the feature README's Assumptions, as CLAUDE.md
|
||||
requires for any dependency decision.
|
||||
|
||||
**Synchronous, one request at a time**, like `lucisv-server`. A host may
|
||||
pipeline requests; they are answered in order. `notifications/cancelled` is
|
||||
accepted and ignored (a tool call is bounded by an index rebuild, seconds at
|
||||
worst on opentitan). The main thread is spawned with
|
||||
`vlog_parser::PARSE_STACK_SIZE` — the recursion-limit handshake every parsing
|
||||
thread in the workspace honours.
|
||||
|
||||
### 4.2 The protocol subset
|
||||
|
||||
Pinned by tests in `crates/lucisv_mcp/tests/wire.rs` (fixtures spawn the
|
||||
binary, as `editors/vscode/smoke.js` does for the LSP):
|
||||
|
||||
| method | answer |
|
||||
|---|---|
|
||||
| `initialize` | `protocolVersion` (the client's if we support it, else our newest), `capabilities: { tools: {}, resources: {}, prompts: {} }`, `serverInfo { name: "lucisv-mcp", version }`, `instructions` — a short paragraph telling the agent to prefer `unit_interface`/`outline`/`read_item` over reading files, and that edits are on-disk and verified |
|
||||
| `notifications/initialized` | accepted |
|
||||
| `ping` | `{}` |
|
||||
| `tools/list` | every tool with `name`, `description`, `inputSchema` (JSON Schema, `additionalProperties: false`, `required`), `annotations` (`readOnlyHint`, `destructiveHint`, `idempotentHint`) — read tools are `readOnlyHint: true`; edit tools `destructiveHint: false` (verified, refusable, atomic) |
|
||||
| `tools/call` | `{ content: [{ type: "text", text }], structuredContent, isError }` — text is the compact rendering, `structuredContent` the JSON the agent can parse; a refusal is `isError: true` with the engine's own sentence (never a JSON-RPC error — the spec reserves those for protocol faults) |
|
||||
| `resources/list`, `resources/read`, `resources/templates/list` | M2: `lucisv://overview`, `lucisv://unit/{name}`, `lucisv://rules` (the linter's `rules_markdown()`), `lucisv://file/{path}/outline` |
|
||||
| `prompts/list`, `prompts/get` | M6, optional: `review-module`, `add-port` walkthroughs — only if the M6 token census shows agents use them |
|
||||
| `notifications/cancelled`, `notifications/progress` | accepted / never sent |
|
||||
| unknown method | JSON-RPC `-32601`; unknown tool `-32602`; invalid params `-32602` with the schema path |
|
||||
|
||||
The protocol revision: the dev pins the **current** spec revision at
|
||||
implementation time (2025-06-18 is the widely deployed one as this plan is
|
||||
written; a newer revision exists) and lists every revision the server
|
||||
accepts in `rpc.rs` — negotiation is "echo the client's if listed". No
|
||||
JSON-RPC batching (removed from the spec). Lines are UTF-8, no embedded
|
||||
newlines, stdout is protocol-only, stderr is human-only.
|
||||
|
||||
### 4.3 The tools
|
||||
|
||||
Inputs name things the way an agent already has them: a **file path**
|
||||
(absolute or root-relative), a **unit name**, a **line** (1-based) and
|
||||
optional **column**, or a **symbol name** with an optional **unit**. Outputs
|
||||
always come in two forms — `structuredContent` (JSON) and the text
|
||||
rendering — and the text is the token-conscious one: no repetition, paths
|
||||
root-relative, one line per fact.
|
||||
|
||||
**Read tools (M1 unless marked).**
|
||||
|
||||
| tool | input | output |
|
||||
|---|---|---|
|
||||
| `project_overview` | — | roots, config file, filelist, file count, units by kind, index age, top-level modules (no parent), the 10 largest files |
|
||||
| `list_units` | `kind?` (module/interface/package/class/program), `glob?` | `name, kind, file:line` per unit |
|
||||
| `unit_interface` | `name` | parameters (name, default), ports (dir, type, range, name) in declaration order, plus an instantiation template (`instantiation_plan`); interfaces list modports; packages list exports |
|
||||
| `outline` | `file`, `depth?` | the hierarchical document symbols with line ranges (`Semantics::document_symbols`) |
|
||||
| `read_item` | `file`, `item` (a name or `kind:name`; for unlabelled blocks `always@<line>`) | the item's exact text and its line range — a slice, not the file |
|
||||
| `search_symbols` | `query`, `limit?` | `WorkspaceIndex::workspace_symbols` (fuzzy) |
|
||||
| `defines` (M2) | `file?`, `name?` | the `` `define `` table; one-step expansion when `name` is given with args |
|
||||
|
||||
**Navigation (M2).**
|
||||
|
||||
| tool | input | output |
|
||||
|---|---|---|
|
||||
| `definition` | `file, line, col` **or** `name, unit?` | every declaration site (ambiguity is a list, never a guess); the declaration's own source line |
|
||||
| `references` | same selector, `include_declaration?` | `vlog_refactor::find_references` — file:line:col + the line's text, grouped by file, capped with a count |
|
||||
| `hierarchy` | `root?`, `direction` (down/up), `depth?` | instance tree: `instance_name : module` with parameter overrides when written, from `instantiations()`; `up` lists parents |
|
||||
| `diagnostics` | `file?` (else the workspace), `rules?`, `severity?` | parse errors, missing-closer warnings, lint findings — the same `{filename, rule, severity, message, location}` shape `lucisv check --output-format json` prints, so one JSON contract serves CI and agents |
|
||||
|
||||
**Edit tools (M3).** All take `dry_run?` (default `false`). `dry_run` returns
|
||||
the unified diff and touches nothing. A real run writes each file with
|
||||
`write_atomic`, then returns the summary: files changed, lines added/removed
|
||||
per file, the engine's warnings, files created. A refusal returns
|
||||
`isError: true` with the engine's sentence and no file is touched — the
|
||||
`RefactorEdit` is all-or-nothing, and so is the write loop (every file's new
|
||||
text is computed and verified before the first write; a write failure after
|
||||
a successful write is reported as such — the same posture the CLI has).
|
||||
|
||||
| tool | wraps |
|
||||
|---|---|
|
||||
| `format` | `format_source` over `files[]`, or `format_range` with `lines` — the safety net decides; `--check`-style `dry_run` diff |
|
||||
| `fix_lint` | `apply_fixes` filtered through `fence::protected_regions` — the CLI's `--fix` path, safe fixes only |
|
||||
| `rename` | `vlog_refactor::rename(files, file, offset, new_name)`; selector as `definition` |
|
||||
| `expand_wildcard`, `convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`, `remove_port` | `(files, file, offset)` |
|
||||
| `add_port` | `ModuleRef::Name` + the declaration text |
|
||||
| `extract_module` | `file, start_line, end_line, new_name, home` (new file / same file) |
|
||||
| `instantiate` | `instantiation_plan` → text only, `style` (named/wildcard, with/without params); never an edit |
|
||||
|
||||
**Structural edits (M4)** — the general token saver, and the one new piece
|
||||
of logic in the block:
|
||||
|
||||
| tool | contract |
|
||||
|---|---|
|
||||
| `replace_item` | `file, item, text`: the bytes of exactly that item (as `read_item` slices it) are replaced by `text`; **nothing outside the span changes**; the result is refused unless the file still parses strictly (or already did not, in which case the error count must not grow), the item at that position is one item, and — when `text` declares a name — the name is the one asked for (or `rename: true` was passed). Comments inside the old item are the agent's to keep; comments *outside* it are structurally untouched |
|
||||
| `insert_item` | `file, anchor (item | "end"), position (before/after), text`: same parse rule; blank-line policy = one blank line each side, like the formatter's |
|
||||
| `delete_item` | `file, item`: the item and its own leading comments (the AST's `Meta::leading`), nothing else; refused if a reference to a declaration it owns survives in the workspace (via `references`) unless `force: true` |
|
||||
|
||||
These three are the closest MCP comes to CLAUDE.md invariant 1. They ship
|
||||
with attack tests in the same change (a `text` that opens a block it does not
|
||||
close; a `text` that closes the enclosing module; an item name that shadows
|
||||
a port; a UTF-8 boundary; a fenced region; a file with an unterminated
|
||||
string), asserted refused, re-attacked by QA. `format` after `replace_item`
|
||||
is the agent's choice, not implicit.
|
||||
|
||||
### 4.4 The workspace model and freshness
|
||||
|
||||
`project.rs` owns one `Project`:
|
||||
|
||||
1. **Roots** from `--root` (repeatable) or the current directory. Every path
|
||||
a tool takes must resolve inside a root; anything else is refused.
|
||||
2. **Config**: `Discovery::for_dir(root)` → `exclude`, `filelist`, format and
|
||||
lint settings — the same ladder the CLI and the editor use, minus editor
|
||||
settings (there are none here).
|
||||
3. **File set**: the configured `filelist` if any (the editor's rung 1), else
|
||||
`walk::collect_files_with` over the roots with `.gitignore` and `exclude`
|
||||
honoured and a 1 MiB per-file cap (the editor's `lucisv.index.maxFileSize`
|
||||
default), each file's size recorded. `--filelist` overrides.
|
||||
4. **Index**: `IndexBuilder::add_file` per file on the stack-sized thread,
|
||||
`finish()`; per-file `Semantics` computed lazily and kept (an
|
||||
`analyzed()` cache keyed by content hash).
|
||||
5. **Freshness**: at the start of every `tools/call`, stat every file in the
|
||||
set (size + mtime); a changed or missing file is re-read, re-hashed and
|
||||
`update_file`d / `remove_file`d; a walk is re-run when a file went missing,
|
||||
on `project_overview`, or when the last walk is older than 5 s, so new
|
||||
files appear. **The promise:** a tool never answers from a file older than
|
||||
the disk at the moment the call arrived. Fingerprint equality with a full
|
||||
rebuild is asserted in tests after every update path (the `update.rs`
|
||||
oracle already exists).
|
||||
|
||||
Opentitan (~3 000 files) is the size reference: the stat sweep is
|
||||
milliseconds; the initial build is whatever `IndexBuilder` costs today (the
|
||||
LSP's scan trace numbers in `docs/perf/README.md` are the baseline — M6
|
||||
records MCP's own).
|
||||
|
||||
### 4.5 Rendering rules (the token budget is the product)
|
||||
|
||||
- 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
|
||||
page with `offset`.
|
||||
- A declaration is shown as its own source line, trimmed, never the
|
||||
surrounding block.
|
||||
- No prose, no markdown headings inside a tool result; a table only where
|
||||
the columns are fixed (ports).
|
||||
- `instructions` at `initialize` and every tool `description` are written
|
||||
for the agent that reads them once: one sentence each on what the tool
|
||||
answers, when to prefer it over reading a file, and what it refuses.
|
||||
|
||||
## 5. Distribution
|
||||
|
||||
### 5.1 The vsix carries three binaries
|
||||
|
||||
`tools/release.sh`: `package_vsix` stages `lucisv-mcp[.exe]` beside the two
|
||||
existing binaries and the `expect_vsix_bins` list grows to three entries per
|
||||
platform (and per pair in the all-platforms package); `audit_artifacts.sh`
|
||||
learns the third name; `prune_release_assets.sh` is unchanged (it keys on
|
||||
the seven vsix names, which do not change). `release.sh` smoke-tests the
|
||||
embedded `lucisv-mcp` the way it smokes `lucisv-server`: a Node script
|
||||
(`editors/vscode/mcp_smoke.js`) sends `initialize`, `tools/list` and one
|
||||
`project_overview` over stdio and checks the answers. The universal vsix
|
||||
still carries no binaries and looks `lucisv-mcp` up on `PATH`.
|
||||
|
||||
### 5.2 The extension registers it
|
||||
|
||||
`editors/vscode/mcp.js` (new, ~80 lines, unit-tested like `restart.js`):
|
||||
|
||||
- resolves the binary with the same three-rung ladder as the server
|
||||
(`lucisv.mcp.path` set explicitly → `bundledBinary(context, "lucisv-mcp")`
|
||||
→ `lucisv-mcp` 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;
|
||||
- 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
|
||||
`.vscode/mcp.json` → `servers`) pointing at the resolved binary — because
|
||||
Claude Code and Cursor do not read VS Code's provider registry, and the
|
||||
vsix is where the binary is;
|
||||
- `package.json`: `contributes.mcpServerDefinitionProviders`, the two settings,
|
||||
the command; `activationEvents` unchanged (the language activation is
|
||||
enough; VS Code also activates on the contribution point).
|
||||
|
||||
Engine stays `^1.82.0` with the runtime guard (§2.3), unless `vsce` objects.
|
||||
|
||||
### 5.3 Standalone
|
||||
|
||||
`cargo build --release` yields `target/release/lucisv-mcp`; the docs site
|
||||
gets an "Agents (MCP)" guide page with the one-line `claude mcp add lucisv --
|
||||
lucisv-mcp --root .` and the Cursor/VS Code snippets. Loose binaries stay
|
||||
unattached on the release page, as today (`docs/features/editor-platform-vsix`).
|
||||
|
||||
## 6. Interaction with the LSP: the index cache
|
||||
|
||||
The LSP persists one `FileFacts` record per file (`index-cache`, header
|
||||
`lucisv-index-cache\t2\t20\t<version>`, one `hash\tfacts\tchecksum` line
|
||||
per record; atomically compacted, appended by single `write_all`s) — safe to
|
||||
read concurrently, keyed by content hash, never by time. Its location is
|
||||
the `lucisv.index.cachePath` setting, else VS Code's `storagePath`, else the
|
||||
OS cache dir keyed by the roots.
|
||||
|
||||
MCP **reads it read-only** when `--index-cache DIR` names it (the extension
|
||||
passes the same `storagePath` to both processes; a CLI user may pass the OS
|
||||
path): a file whose content hash has a record skips its parse at startup.
|
||||
MCP **never writes** that store — two writers would need the coordination
|
||||
`docs/features/atomic-write-coordination` had to build for the CLI, and the
|
||||
warm start is a shortcut, not a need. MCP keeps its own `index-cache-mcp` in
|
||||
the same directory with the same codec (M6), so the LSP could read it in
|
||||
turn if anyone ever wants that (not planned). A version or `FACTS_FORMAT`
|
||||
mismatch ignores the store, exactly as the LSP does.
|
||||
|
||||
## 7. Handshakes filed by this plan (requests, not edits)
|
||||
|
||||
| # | to | request | why |
|
||||
|---|---|---|---|
|
||||
| MCP-1 | `lucisv` CLI → `lucisv_core` | lift `crates/lucisv/src/diff.rs::unified` into `lucisv_core::diff` (pure move; the CLI re-exports) | `dry_run` diffs; two copies of a diff printer is exactly the duplication CLAUDE.md forbids |
|
||||
| MCP-2 | `lucisv_server` (informational) | none required; recorded so `docs/topo.md` §2.8 can add `editors/vscode ─▶ lucisv_mcp` (spawn contract) and `tools/ ─▶ lucisv_mcp` (packaging) rows after M5 merges | the topology stays the authority on collisions |
|
||||
| MCP-3 | `vlog_semantic` (candidate, not requested) | if M2's `hierarchy` and the server's `design_hierarchy::snapshot` drift, lift the snapshot walk into `vlog_semantic::workspace::hierarchy` | one instance tree for the sidebar and the agent |
|
||||
|
||||
## 8. Acceptance (what "done" means for the block)
|
||||
|
||||
- **Protocol**: an `initialize` handshake and every tool exercised by
|
||||
`tests/wire.rs` over the real binary; Claude Code, Cursor and VS Code
|
||||
agent mode each list the tools and complete `project_overview` on a
|
||||
fixture (manual, recorded in `docs/manual-acceptance.md`).
|
||||
- **Parity**: on opentitan (read-only), `references` for the five symbols
|
||||
`docs/features/references-nav` uses, `definition` for the same, and
|
||||
`hierarchy` down from `top_earlgrey`, equal to the LSP's answers modulo
|
||||
rendering (the census is a test with the paths as `#[ignore]` inputs,
|
||||
like the server's perf harness).
|
||||
- **Safety**: every edit tool run twice is a no-op the second time; every
|
||||
refusal leaves the tree byte-identical (`git status` empty in the test);
|
||||
the M4 attack suite is green and QA added to it.
|
||||
- **Token census (M6)**: three canonical tasks on opentitan, each run by an
|
||||
agent with file tools only and with lucisv-mcp — (a) "list every
|
||||
instance of `prim_fifo_sync` with its `Width`/`Depth` overrides", (b)
|
||||
"add an `input logic dbg_i` port to `aes_core` and propagate it to the
|
||||
top", (c) "rename `entropy_src_hw_if_i` in `aes`" — with the tokens in
|
||||
and out recorded in `docs/mcp/census.md`. This is the number the owner
|
||||
asked the block for; it is measured, not asserted.
|
||||
- **Packaging**: every platform vsix holds the three binaries; the
|
||||
darwin-arm64 one installed, the MCP server visible in **MCP: List
|
||||
Servers**, `project_overview` answered inside VS Code agent mode; the
|
||||
universal vsix still installs on a machine with no binaries.
|
||||
- **Gates**: fmt, clippy, workspace tests green through `tools/guard.sh`;
|
||||
no file over 600 production lines in the new crate; no `unwrap` in
|
||||
library paths; every feature README complete with QA log.
|
||||
|
||||
## 9. Order and lanes (the short version; `TODO-MCP.md` has the checkboxes)
|
||||
|
||||
```
|
||||
M1 transport + read tools ──▶ M2 navigation + resources ──▶ M3 edit tools ──▶ M4 structural edits
|
||||
└──▶ M5 packaging + extension (parallel from M1: disjoint files)
|
||||
M4, M5 ──▶ M6 cache reuse, freshness polish, census, docs, release
|
||||
```
|
||||
|
||||
M1 first because everything else is a tool on its transport; M5 can start
|
||||
the moment M1's binary name and arguments are fixed (it packages a binary
|
||||
that already answers `initialize`), and its files (`tools/`, `editors/`,
|
||||
CI) are disjoint from the crate — the one proven-parallel pair. M2/M3/M4
|
||||
are serial (same crate, same registry). M6 closes the block with a release.
|
||||
|
||||
Roles per CLAUDE.md: one Opus dev then one Sonnet QA per lane, in a worktree
|
||||
branched from trunk; the lead reviews and merges; the block ships as a minor
|
||||
release (`0.56.0` if it lands before anything else does).
|
||||
@@ -5,6 +5,19 @@ for you. The extension and its bundled language server share one version
|
||||
number; the full engineering notes live in the
|
||||
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
||||
|
||||
## 0.56.0 — 2026-09-23
|
||||
|
||||
- Rename no longer breaks `.name` shorthand or `.*` wildcard connections:
|
||||
the binding is written out explicitly (`.din(d)`, `.n(m)`) and each
|
||||
rewrite is listed in the rename's warnings; a case lucisv cannot read is
|
||||
refused with the reason instead of silently cut. Renames beside `bind`
|
||||
directives onto instance names (opentitan's FPV binds) now succeed.
|
||||
- Preview, outside the extension for now: `lucisv-mcp`, a Model Context
|
||||
Protocol server that gives coding agents the same project understanding
|
||||
and verified edits, built from the repository (`cargo build --release
|
||||
-p lucisv_mcp`). It will ship inside this extension's platform packages
|
||||
in a coming release.
|
||||
|
||||
## 0.55.0 — 2026-09-17
|
||||
|
||||
- Find All References on a module's internal signal now lists every use
|
||||
|
||||
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
|
||||
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
||||
setup.
|
||||
|
||||
The current release is **0.55.0**. Its platform packages include both
|
||||
The current release is **0.56.0**. Its platform packages include both
|
||||
`lucisv-server` and the `lucisv` command-line tool:
|
||||
|
||||
| Package target | Machines |
|
||||
@@ -374,6 +374,12 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.56.0 highlights
|
||||
|
||||
Version 0.56.0 makes rename write out the `.name` and `.*` connections it
|
||||
used to cut silently, and previews `lucisv-mcp`, a Model Context Protocol
|
||||
server for coding agents built from the repository (not yet bundled).
|
||||
|
||||
## Release 0.55.0 highlights
|
||||
|
||||
Version 0.55.0 makes Find All References see every cross-file use of a
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "lucisv",
|
||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
||||
"version": "0.55.0",
|
||||
"version": "0.56.0",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
|
||||
Reference in new issue
Block a user