MCP M3: the edit tools — format, fix_lint, rename, the port/import/module refactorings, instantiate — through one all-or-nothing write path; diff printer lifted to lucisv_core (MCP-1)
crates/lucisv_mcp/src/apply.rs is the one write path every edit tool uses: every file's new text is computed first (edits applied last-first; overlap, past-the-end and split-character edits refused), every target must lie inside a root (a created file's directory too, symlinked dirs resolved), every file is re-read and compared byte for byte with the text the plan was computed against before the first write — one mismatch refuses the whole edit — then write_atomic in path order, a failure part-way reported as "written N of M". dry_run returns the unified diff. Tools (tools/{format,edit,refactor}.rs): format (per-file lucisv.toml config, lines ranges, the safety net's refusal names the file, a formatter panic is caught), fix_lint (the diagnostics lint pass, safe fixes only, never inside a lucisv: off fence, refuses a result with more parse errors), rename, expand_wildcard, convert_ports, organize_imports, inline_module, propagate_ports, remove_port, add_port, extract_module (new file or same file), instantiate (text only; instance name validated). Every whole-set tool hands the engine every indexed file read at call time and re-walks the roots first (a file written in the last 5 s is in the set); a file the index skips (over 1 MiB, non-UTF-8) that spells a changed name as a whole word refuses the edit, otherwise it is named once under warnings; references carries the same warning. Annotations from an Effect table (read / edit, idempotent where a second call writes nothing).
MCP-1 delivered as a pure move: crates/lucisv/src/diff.rs::unified → lucisv_core::diff::unified, the CLI re-exports it; --diff output byte-identical (QA compared the 82bbba0 binary over the aes copy); lucisv_core still dependency-free.
QA (Opus, two rounds + two lead fixes): 38 qa_m3 tests; the write path held under a 50 ms writer race (no torn file in 650 calls), chmod 444, symlinked escapes, a concurrent lucisv --check; format/fix_lint byte-identical to the CLI on CRLF, nested configs, fences and all 124 aes files. Open and OUT of this lane: vlog_refactor::rename leaves .* and .name shorthand connections broken when a port or its bound net is renamed — a pre-existing engine corruption the LSP shares, fixed next in lane M3.5 (TODO-MCP.md); the rename tool says so until then. Engine findings filed: MCP-8 (false remove_port refusal on a same-file instantiation), MCP-10 (extract_module writes LF into a CRLF file). Gates through tools/guard.sh: fmt, clippy, workspace 4 664 passed.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
1 parent
82bbba04be
commit
14b72f2862
33 files changed
+4271
-304
No files matched your search
+39
-6
@@ -118,34 +118,67 @@ Depends on M1 merged.
|
||||
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.
|
||||
|
||||
- [ ] `apply.rs`: `RefactorEdit` → (`dry_run`) unified diff per file | the
|
||||
- [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
|
||||
- [ ] `format` (`files[]` or `file` + `lines`, `dry_run`), `fix_lint`
|
||||
- [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
|
||||
- [ ] the source-set rule: each refactor gets the whole in-scope file set
|
||||
- [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
|
||||
- [ ] tests: every tool `dry_run` then real on the fixtures; run twice →
|
||||
- [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)
|
||||
- [ ] README `mcp-edit-tools`; Handshake MCP-1 filed there with the exact
|
||||
- [x] README `mcp-edit-tools`; Handshake MCP-1 filed there with the exact
|
||||
move; work log; gates; sizes
|
||||
- [ ] QA: an edit whose target file changed on disk between the stat
|
||||
- [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.
|
||||
|
||||
- [ ] `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)
|
||||
- [ ] 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
|
||||
- [ ] 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)
|
||||
|
||||
|
||||
+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,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();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
//! 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;
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct FileSet {
|
||||
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
|
||||
@@ -97,17 +100,17 @@ fn walk_root(root: &Path, roots: &[PathBuf], set: &mut FileSet) {
|
||||
}
|
||||
set.warnings.extend(warnings);
|
||||
for (path, size) in found {
|
||||
if size.unwrap_or(0) > MAX_FILE_BYTES {
|
||||
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;
|
||||
} else if let Some(path) = canonical(&path) {
|
||||
if roots.iter().any(|root| path.starts_with(root)) {
|
||||
set.files.push(path);
|
||||
} else {
|
||||
set.warnings.push(format!(
|
||||
"{}: outside every root (reached through a symlink); not indexed",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
set.skipped.push(path);
|
||||
} else {
|
||||
set.files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,6 +118,8 @@ fn walk_root(root: &Path, roots: &[PathBuf], set: &mut FileSet) {
|
||||
fn finish(mut set: FileSet) -> FileSet {
|
||||
set.files.sort();
|
||||
set.files.dedup();
|
||||
set.skipped.sort();
|
||||
set.skipped.dedup();
|
||||
set
|
||||
}
|
||||
|
||||
@@ -241,6 +246,7 @@ mod tests {
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
@@ -48,9 +48,9 @@ pub struct Project {
|
||||
walked_at: Instant,
|
||||
updated_at: Instant,
|
||||
build: Duration,
|
||||
/// Discovered files that are not UTF-8 text, as `path: why`, recomputed
|
||||
/// by every walk.
|
||||
unreadable: Vec<String>,
|
||||
/// 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,
|
||||
@@ -98,7 +98,7 @@ impl Project {
|
||||
files.insert(path.clone(), stamp);
|
||||
}
|
||||
Err(problem) => {
|
||||
unreadable.push(format!("{}: {problem}", relative_to(&roots, path)));
|
||||
unreadable.push((path.clone(), problem.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -194,7 +194,7 @@ impl Project {
|
||||
self.files.insert(path.clone(), stamp);
|
||||
added += 1;
|
||||
}
|
||||
Err(problem) => unreadable.push(format!("{}: {problem}", self.relative(path))),
|
||||
Err(problem) => unreadable.push((path.clone(), problem.to_string())),
|
||||
}
|
||||
}
|
||||
self.unreadable = unreadable;
|
||||
@@ -245,8 +245,17 @@ impl Project {
|
||||
}
|
||||
|
||||
/// Files discovery found but could not read as UTF-8 text.
|
||||
pub fn unreadable(&self) -> &[String] {
|
||||
&self.unreadable
|
||||
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
|
||||
|
||||
@@ -81,7 +81,7 @@ struct Finding {
|
||||
}
|
||||
|
||||
/// What one config file makes of a lint run.
|
||||
struct Run {
|
||||
pub(super) struct Run {
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
options: RuleOptions,
|
||||
waivers: ExternalWaivers,
|
||||
@@ -95,14 +95,14 @@ 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 { discovery: Discovery::new(true), held: BTreeMap::new(), selected };
|
||||
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 { index: project.index(), census: None, own };
|
||||
let oracle = Mentions::of_file(project.index(), own);
|
||||
findings = file_findings(project, &mut runs, &path, &analysis, &oracle)?;
|
||||
}
|
||||
None => {
|
||||
@@ -125,18 +125,24 @@ fn diagnostics(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
Ok(render_findings(&findings, args))
|
||||
}
|
||||
|
||||
/// The runs met so far in one call, one per governing config file.
|
||||
struct Runs {
|
||||
/// 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.
|
||||
fn for_file(&mut self, path: &Path) -> Result<Rc<Run>, String> {
|
||||
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));
|
||||
@@ -224,6 +230,18 @@ fn file_findings(
|
||||
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,
|
||||
@@ -238,8 +256,7 @@ fn file_findings(
|
||||
.with_oracle(oracle);
|
||||
let (violations, used) = lint_with(&ctx, &run.rules, &run.waivers);
|
||||
run.used.borrow_mut().merge(&used);
|
||||
out.extend(violations.iter().map(|violation| lint_finding(&file, &analysis.lines, violation)));
|
||||
Ok(out)
|
||||
violations
|
||||
}
|
||||
|
||||
fn lint_finding(file: &str, lines: &LineIndex, violation: &Violation) -> Finding {
|
||||
@@ -326,13 +343,20 @@ impl<'a> Census<'a> {
|
||||
|
||||
/// The project index answering the linter's cross-file questions — the
|
||||
/// language server's `IndexMentions`, with the census when one was built.
|
||||
struct Mentions<'a> {
|
||||
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 {
|
||||
|
||||
@@ -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` shorthand connection bound to the renamed name is not rewritten yet (known engine limit, M3.5); check `dry_run` on designs using them.",
|
||||
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")
|
||||
}
|
||||
@@ -5,11 +5,14 @@
|
||||
|
||||
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;
|
||||
|
||||
@@ -61,46 +64,76 @@ pub struct Tool {
|
||||
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] = &[
|
||||
read::PROJECT_OVERVIEW,
|
||||
read::LIST_UNITS,
|
||||
interface::UNIT_INTERFACE,
|
||||
read::OUTLINE,
|
||||
read_item::READ_ITEM,
|
||||
read::SEARCH_SYMBOLS,
|
||||
defines::DEFINES,
|
||||
nav::DEFINITION,
|
||||
nav::REFERENCES,
|
||||
hierarchy::HIERARCHY,
|
||||
diagnostics::DIAGNOSTICS,
|
||||
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().find(|tool| tool.name == name)
|
||||
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(describe).collect();
|
||||
let tools: Vec<Value> = TOOLS.iter().map(|(tool, effect)| describe(tool, *effect)).collect();
|
||||
json!({ "tools": tools })
|
||||
}
|
||||
|
||||
fn describe(tool: &Tool) -> Value {
|
||||
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),
|
||||
// Every M1 tool only reads: nothing on disk changes, the same call
|
||||
// gives the same answer on the same disk, and nothing outside the
|
||||
// roots is consulted.
|
||||
"annotations": {
|
||||
"title": tool.title,
|
||||
"readOnlyHint": true,
|
||||
"readOnlyHint": read_only,
|
||||
"destructiveHint": false,
|
||||
"idempotentHint": true,
|
||||
"idempotentHint": idempotent,
|
||||
"openWorldHint": false,
|
||||
},
|
||||
})
|
||||
@@ -211,13 +244,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn every_schema_is_closed_and_names_its_required_arguments() {
|
||||
for tool in TOOLS {
|
||||
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 names: Vec<&str> = TOOLS.iter().map(|(tool, _)| tool.name).collect();
|
||||
let mut unique = names.clone();
|
||||
unique.sort_unstable();
|
||||
unique.dedup();
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
//! 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 ([`all_files`]).
|
||||
//! `vlog_refactor::find_references` over every indexed file
|
||||
//! (`source::WholeSet`).
|
||||
//! The selector itself is `select.rs`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
@@ -19,7 +19,7 @@ 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};
|
||||
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};
|
||||
@@ -94,7 +94,7 @@ pub const REFERENCES: Tool = Tool {
|
||||
description: "Hits to skip, for paging past `… and N more` (default 0).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
rewalk: true,
|
||||
handler: references,
|
||||
};
|
||||
|
||||
@@ -289,12 +289,13 @@ fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
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 files = all_files(project, &path);
|
||||
let set = WholeSet::read(project, Some(&path));
|
||||
let include = args.flag("include_declaration", true);
|
||||
let found =
|
||||
vlog_refactor::find_references(&files, &path, offset, include).map_err(engine_refusal)?;
|
||||
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 files {
|
||||
for (held, text) in set.files {
|
||||
texts.hold(held, text);
|
||||
}
|
||||
let hits: Vec<Site> = found
|
||||
@@ -304,11 +305,17 @@ fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
Some(Site::at(project.relative(file), text, lines, *span, "use"))
|
||||
})
|
||||
.collect();
|
||||
Ok(render_hits(&hits, args))
|
||||
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`.
|
||||
fn declaration_position(
|
||||
/// The one declaration a bare `name` selects for `references` (and `rename`).
|
||||
pub(super) fn declaration_position(
|
||||
project: &mut Project,
|
||||
name: &str,
|
||||
unit: Option<&str>,
|
||||
@@ -347,21 +354,6 @@ fn declaration_position(
|
||||
const MACRO_REFUSAL: &str =
|
||||
"references follows declarations, not macros (`defines` lists its definitions).";
|
||||
|
||||
/// Every indexed file (and the selected one), read from disk now — the
|
||||
/// whole set, always (lead's ruling on QA finding 1): a use can resolve
|
||||
/// 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 name is sound. The cost is a parse of the set per call
|
||||
/// (README; Handshake MCP-7 lets cached facts replace it).
|
||||
fn all_files(project: &Project, path: &Path) -> Vec<(PathBuf, String)> {
|
||||
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
|
||||
wanted.insert(path.to_path_buf());
|
||||
wanted
|
||||
.into_iter()
|
||||
.filter_map(|path| std::fs::read_to_string(&path).ok().map(|text| (path, text)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The engine's refusal, said as ours: prefixed, and its rename wording —
|
||||
/// `find_references` shares the rename's resolution — turned into this
|
||||
/// tool's.
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
//! 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::HashMap;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
@@ -148,6 +148,77 @@ pub fn without_comments(text: &str) -> String {
|
||||
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 == '$'
|
||||
@@ -187,6 +258,15 @@ mod tests {
|
||||
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) )";
|
||||
|
||||
@@ -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
|
||||
@@ -276,8 +276,8 @@ fn qa_everything_but_initialize_and_ping_waits_for_the_handshake() {
|
||||
assert!(s.pings());
|
||||
s.initialize();
|
||||
// M2 added five tools (defines, definition, references, hierarchy,
|
||||
// diagnostics) to M1's six.
|
||||
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 11);
|
||||
// diagnostics) to M1's six; M3 added twelve edit tools.
|
||||
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 23);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -186,18 +186,40 @@ fn tools_list_describes_every_tool_for_the_agent() {
|
||||
"definition",
|
||||
"references",
|
||||
"hierarchy",
|
||||
"diagnostics"
|
||||
"diagnostics",
|
||||
"format",
|
||||
"fix_lint",
|
||||
"rename",
|
||||
"expand_wildcard",
|
||||
"convert_ports",
|
||||
"organize_imports",
|
||||
"inline_module",
|
||||
"propagate_ports",
|
||||
"remove_port",
|
||||
"add_port",
|
||||
"extract_module",
|
||||
"instantiate"
|
||||
]
|
||||
);
|
||||
assert!(reply["result"].get("nextCursor").is_none());
|
||||
// The edit tools write; those whose second identical call writes nothing
|
||||
// more say so. `instantiate` only answers with text.
|
||||
let idempotent_edits =
|
||||
["format", "fix_lint", "expand_wildcard", "convert_ports", "organize_imports"];
|
||||
for tool in tools {
|
||||
let name = tool["name"].as_str().unwrap();
|
||||
let edits = names.iter().position(|n| *n == name).unwrap() >= 11 && name != "instantiate";
|
||||
assert_eq!(tool["inputSchema"]["type"], "object");
|
||||
assert_eq!(tool["inputSchema"]["additionalProperties"], false);
|
||||
assert!(tool["inputSchema"]["required"].is_array());
|
||||
assert_eq!(tool["annotations"]["readOnlyHint"], true);
|
||||
assert_eq!(tool["annotations"]["readOnlyHint"], !edits, "{name}");
|
||||
assert_eq!(tool["annotations"]["destructiveHint"], false);
|
||||
assert_eq!(tool["annotations"]["idempotentHint"], true);
|
||||
let idempotent = !edits || idempotent_edits.contains(&name);
|
||||
assert_eq!(tool["annotations"]["idempotentHint"], idempotent, "{name}");
|
||||
assert_eq!(tool["annotations"]["openWorldHint"], false);
|
||||
if edits {
|
||||
assert_eq!(tool["inputSchema"]["properties"]["dry_run"]["type"], "boolean", "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -765,3 +787,303 @@ fn an_escaped_name_is_followed_across_files() {
|
||||
let at = json!({"file": "rtl/esc_user.sv", "line": 3, "col": 4});
|
||||
assert_eq!(sites(&mut server, at), ["rtl/esc.sv:1:8 module"]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M3: the edit tools, over a fresh copy of `tests/fixtures/edit` per test.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Every file under a tree, root-relative, with its bytes.
|
||||
fn snapshot(tree: &Tree) -> std::collections::BTreeMap<String, Vec<u8>> {
|
||||
fn walk(dir: &Path, root: &Path, out: &mut std::collections::BTreeMap<String, Vec<u8>>) {
|
||||
for entry in fs::read_dir(dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
walk(&path, root, out);
|
||||
} else {
|
||||
let relative =
|
||||
path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
|
||||
out.insert(relative, fs::read(&path).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = std::collections::BTreeMap::new();
|
||||
walk(&tree.0, &tree.0, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The files whose bytes differ between two snapshots (added, removed or
|
||||
/// changed).
|
||||
fn moved(
|
||||
before: &std::collections::BTreeMap<String, Vec<u8>>,
|
||||
after: &std::collections::BTreeMap<String, Vec<u8>>,
|
||||
) -> Vec<String> {
|
||||
let mut names: Vec<&String> = before.keys().chain(after.keys()).collect();
|
||||
names.sort();
|
||||
names.dedup();
|
||||
names.into_iter().filter(|n| before.get(*n) != after.get(*n)).cloned().collect()
|
||||
}
|
||||
|
||||
/// `arguments` with `dry_run` set.
|
||||
fn dry(arguments: &Value, dry_run: bool) -> Value {
|
||||
let mut arguments = arguments.clone();
|
||||
arguments["dry_run"] = Value::from(dry_run);
|
||||
arguments
|
||||
}
|
||||
|
||||
/// One edit tool's life: a dry run shows a diff and writes nothing; the real
|
||||
/// call writes exactly `touched`; the same call again writes nothing more
|
||||
/// (answering `unchanged`, or the engine's "nothing to do" refusal). Returns
|
||||
/// the real call's text.
|
||||
fn exercise(tool: &str, arguments: Value, touched: &[&str]) -> String {
|
||||
let tree = Tree::of("edit");
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let pristine = snapshot(&tree);
|
||||
let preview = server.text(tool, dry(&arguments, true));
|
||||
assert!(preview.contains("(dry run: nothing written)"), "{tool}: {preview}");
|
||||
for file in touched {
|
||||
assert!(preview.contains(&format!("--- {file}\n")), "{tool}: {file} in {preview}");
|
||||
}
|
||||
assert!(moved(&pristine, &snapshot(&tree)).is_empty(), "{tool}: a dry run wrote");
|
||||
let applied = server.text(tool, dry(&arguments, false));
|
||||
assert!(!applied.contains("--- "), "{tool}: a real run answers a summary: {applied}");
|
||||
let written = snapshot(&tree);
|
||||
assert_eq!(moved(&pristine, &written), touched, "{tool}: {applied}");
|
||||
let again = server.call(tool, dry(&arguments, false));
|
||||
let said = again["content"][0]["text"].as_str().unwrap();
|
||||
assert!(
|
||||
said.starts_with("unchanged") || again["isError"] == true,
|
||||
"{tool}: a repeat must write nothing: {said}"
|
||||
);
|
||||
assert!(moved(&written, &snapshot(&tree)).is_empty(), "{tool}: the repeat wrote: {said}");
|
||||
applied
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_writes_three_files_and_a_repeat_is_unchanged() {
|
||||
let args = json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"});
|
||||
let text = exercise("rename", args, &["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"]);
|
||||
assert!(text.starts_with("files: 3 changed, 0 created\n"), "{text}");
|
||||
assert!(text.contains(" rtl/mid.sv +1 -1\n"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_by_name_and_unit_reaches_every_file() {
|
||||
let tree = Tree::of("edit");
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let text = server.text("rename", json!({"name": "d", "unit": "leaf", "new_name": "data_i"}));
|
||||
assert!(text.starts_with("files: 3 changed"), "{text}");
|
||||
let mid = fs::read_to_string(tree.path("rtl/mid.sv")).unwrap();
|
||||
assert!(mid.contains(".data_i (din)"), "{mid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_cursor_refactoring_previews_writes_and_repeats_as_a_no_op() {
|
||||
exercise("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6}), &["rtl/wild.sv"]);
|
||||
exercise(
|
||||
"convert_ports",
|
||||
json!({"file": "rtl/old.sv", "line": 1, "name": "old"}),
|
||||
&["rtl/old.sv"],
|
||||
);
|
||||
exercise("organize_imports", json!({"file": "rtl/top.sv", "line": 6}), &["rtl/top.sv"]);
|
||||
exercise("inline_module", json!({"file": "rtl/inl.sv", "line": 5}), &["rtl/inl.sv"]);
|
||||
exercise(
|
||||
"propagate_ports",
|
||||
json!({"file": "rtl/partial.sv", "line": 6, "name": "u_c"}),
|
||||
&["rtl/partial.sv"],
|
||||
);
|
||||
let removed = exercise(
|
||||
"remove_port",
|
||||
json!({"file": "rtl/spare.sv", "line": 3, "name": "unused_i"}),
|
||||
&["rtl/spare.sv", "rtl/spare_user.sv"],
|
||||
);
|
||||
assert!(removed.contains("was deleted with the port"), "{removed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_port_by_name_or_by_position_connects_every_instantiation() {
|
||||
let added = exercise(
|
||||
"add_port",
|
||||
json!({"module": "spare", "declaration": "input logic en"}),
|
||||
&["rtl/spare.sv", "rtl/spare_user.sv"],
|
||||
);
|
||||
assert!(added.contains("warnings:\n no signal named `en`"), "{added}");
|
||||
let tree = Tree::of("edit");
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let at = json!({"file": "rtl/cell.sv", "line": 2, "declaration": "input logic rst_ni"});
|
||||
let text = server.text("add_port", at);
|
||||
assert!(text.contains(" rtl/cell.sv +"), "{text}");
|
||||
let both =
|
||||
json!({"module": "cell", "file": "rtl/cell.sv", "line": 2, "declaration": "input logic x"});
|
||||
assert!(refusal(&mut server, "add_port", both).contains("not both"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_module_creates_its_file_once_and_never_over_an_existing_one() {
|
||||
let args = json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"});
|
||||
let text = exercise("extract_module", args.clone(), &["rtl/adder.sv", "rtl/ext.sv"]);
|
||||
assert!(text.starts_with("files: 1 changed, 1 created\n"), "{text}");
|
||||
assert!(text.contains(" rtl/adder.sv +6 -0 (created)\n"), "{text}");
|
||||
|
||||
let tree = Tree::of("edit");
|
||||
fs::write(tree.path("rtl/adder.sv"), "// taken\n").unwrap();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let before = snapshot(&tree);
|
||||
let taken = refusal(&mut server, "extract_module", args);
|
||||
assert!(taken.contains("adder.sv"), "{taken}");
|
||||
assert_eq!(before, snapshot(&tree));
|
||||
|
||||
let same = json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder2", "home": "same_file"});
|
||||
let text = server.text("extract_module", same);
|
||||
assert!(text.starts_with("files: 1 changed, 0 created\n"), "{text}");
|
||||
assert!(fs::read_to_string(tree.path("rtl/ext.sv")).unwrap().contains("module adder2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_leaves_the_tree_byte_identical() {
|
||||
let tree = Tree::of("edit");
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let before = snapshot(&tree);
|
||||
let refused = [
|
||||
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "1bad"})),
|
||||
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "q"})),
|
||||
("convert_ports", json!({"file": "rtl/leaf.sv", "line": 1})),
|
||||
("remove_port", json!({"file": "rtl/cell.sv", "line": 3, "name": "en"})),
|
||||
("expand_wildcard", json!({"file": "rtl/mid.sv", "line": 1})),
|
||||
("add_port", json!({"module": "spare", "declaration": "logic nodir"})),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "rtl/ext.sv", "start_line": 8, "end_line": 7, "new_name": "x"}),
|
||||
),
|
||||
("format", json!({"file": "../outside.sv"})),
|
||||
];
|
||||
for (tool, arguments) in refused {
|
||||
let said = refusal(&mut server, tool, arguments.clone());
|
||||
assert!(!said.is_empty(), "{tool} {arguments}");
|
||||
assert_eq!(before, snapshot(&tree), "{tool} {arguments}: {said}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_writes_every_file_or_none_and_repeats_unchanged() {
|
||||
let text = exercise("format", json!({"files": "fmt/messy.sv, rtl/old.sv"}), &["fmt/messy.sv"]);
|
||||
assert!(text.contains("unchanged: rtl/old.sv\n"), "{text}");
|
||||
|
||||
let tree = Tree::of("edit");
|
||||
fs::write(tree.path("fmt/broken.sv"), "module broken(;\nendmodule\n").unwrap();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let before = snapshot(&tree);
|
||||
let said = refusal(&mut server, "format", json!({"files": "fmt/messy.sv,fmt/broken.sv"}));
|
||||
assert!(said.starts_with("`fmt/broken.sv` was not formatted: "), "{said}");
|
||||
assert!(said.ends_with("; nothing written."), "{said}");
|
||||
assert_eq!(before, snapshot(&tree));
|
||||
let lines =
|
||||
refusal(&mut server, "format", json!({"files": "fmt/messy.sv,rtl/leaf.sv", "lines": "1"}));
|
||||
assert!(lines.contains("single file"), "{lines}");
|
||||
let ranged = server.text("format", json!({"file": "fmt/messy.sv", "lines": "2"}));
|
||||
assert!(ranged.starts_with("files: 1 changed"), "{ranged}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_a_crlf_file_is_the_formatters_own_output() {
|
||||
let tree = Tree::of("edit");
|
||||
let source =
|
||||
"module c (\r\n input logic a,\r\n output logic b\r\n);\r\nassign b=a;\r\nendmodule\r\n";
|
||||
fs::write(tree.path("fmt/crlf.sv"), source).unwrap();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let text = server.text("format", json!({"file": "fmt/crlf.sv"}));
|
||||
assert!(text.starts_with("files: 1 changed"), "{text}");
|
||||
let expected =
|
||||
vlog_formatter::format_source(source, &vlog_formatter::Config::default()).unwrap();
|
||||
assert_eq!(fs::read_to_string(tree.path("fmt/crlf.sv")).unwrap(), expected);
|
||||
assert_eq!(server.text("format", json!({"file": "fmt/crlf.sv"})), "unchanged\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fix_lint_fixes_safe_findings_and_never_inside_a_fence() {
|
||||
let tree = Tree::of("edit");
|
||||
let source = "module f (\n input logic a, \n output logic b\n);\n // lucisv: off\n assign b = a; \n // lucisv: on\nendmodule\n";
|
||||
fs::write(tree.path("fmt/fix.sv"), source).unwrap();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let preview = server.text("fix_lint", json!({"file": "fmt/fix.sv", "dry_run": true}));
|
||||
assert!(preview.contains("fixed: no-trailing-whitespace ×1;"), "{preview}");
|
||||
assert_eq!(fs::read_to_string(tree.path("fmt/fix.sv")).unwrap(), source);
|
||||
server.text("fix_lint", json!({"file": "fmt/fix.sv"}));
|
||||
let fixed = fs::read_to_string(tree.path("fmt/fix.sv")).unwrap();
|
||||
assert_eq!(fixed, source.replacen("logic a, \n", "logic a,\n", 1));
|
||||
assert!(fixed.contains(" assign b = a; \n"), "the fenced line is untouched: {fixed}");
|
||||
let again = server.text("fix_lint", json!({"file": "fmt/fix.sv"}));
|
||||
assert!(again.starts_with("unchanged\nfixed: nothing;"), "{again}");
|
||||
// `rules` narrows the run like --select.
|
||||
fs::write(tree.path("fmt/fix.sv"), source).unwrap();
|
||||
let other = json!({"file": "fmt/fix.sv", "rules": "no-tabs", "dry_run": true});
|
||||
assert!(server.text("fix_lint", other).starts_with("unchanged\nfixed: nothing; 0 findings"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instantiate_writes_text_and_no_file() {
|
||||
let tree = Tree::of("edit");
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let before = snapshot(&tree);
|
||||
let named = server.text("instantiate", json!({"name": "leaf"}));
|
||||
assert_eq!(named, "leaf u_leaf (\n .clk(clk),\n .d(d),\n .q(q)\n);\n");
|
||||
let wild =
|
||||
server.text("instantiate", json!({"name": "cell", "style": "wildcard", "instance": "u_x"}));
|
||||
assert_eq!(wild, "cell u_x (.*);\n");
|
||||
let missing = refusal(&mut server, "instantiate", json!({"name": "nothing_here"}));
|
||||
assert!(missing.contains("nothing_here"), "{missing}");
|
||||
assert_eq!(before, snapshot(&tree));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_the_index_skipped_is_never_edited_around() {
|
||||
let tree = Tree::of("edit");
|
||||
let filler =
|
||||
"// filler .......................................................\n".repeat(17_000);
|
||||
let big = format!("module big;\n{filler} leaf u_l (.clk(c), .d(x), .q(y));\nendmodule\n");
|
||||
fs::write(tree.path("rtl/big.sv"), big).unwrap();
|
||||
fs::write(tree.path("rtl/latin1.sv"), b"// \xa9 vendor\nmodule other; endmodule\n").unwrap();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let before = snapshot(&tree);
|
||||
// `d` is spelled in the skipped big.sv: the rename could not reach it.
|
||||
let rename = json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"});
|
||||
let refused = refusal(&mut server, "rename", rename);
|
||||
assert_eq!(
|
||||
refused,
|
||||
"`rtl/big.sv` (skipped: over 1 MiB) may reference `d`; lucisv-mcp will not edit around a file it cannot index; nothing written."
|
||||
);
|
||||
let port = json!({"module": "leaf", "declaration": "input logic en"});
|
||||
assert!(refusal(&mut server, "add_port", port).contains("`leaf`"));
|
||||
assert_eq!(before, snapshot(&tree));
|
||||
// A name no skipped file spells: written, and the skipped files named.
|
||||
let text = server.text("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6}));
|
||||
assert!(
|
||||
text.contains(" not indexed, so not searched or edited: rtl/big.sv (over 1 MiB), rtl/latin1.sv (not UTF-8 text)\n"),
|
||||
"{text}"
|
||||
);
|
||||
let found = server.text("references", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22}));
|
||||
assert!(found.ends_with("warning: not indexed, so not searched or edited: rtl/big.sv (over 1 MiB), rtl/latin1.sv (not UTF-8 text)\n"), "{found}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instantiate_takes_only_an_identifier_for_the_instance() {
|
||||
let tree = Tree::of("edit");
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let escaped = server
|
||||
.text("instantiate", json!({"name": "cell", "style": "wildcard", "instance": "\\u-x "}));
|
||||
assert_eq!(escaped, "cell \\u-x (.*);\n");
|
||||
for bad in ["", "1u", "a b", "module", "\\u-x", "u_x); evil ("] {
|
||||
let said = refusal(&mut server, "instantiate", json!({"name": "cell", "instance": bad}));
|
||||
assert!(said.starts_with("`instance` must be one identifier"), "{bad}: {said}");
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
Reference in new issue
Block a user