Refactoring M1: EDA filelist (.f) defines the index scope
Rope-port umbrella plan (docs/features/refactor) + TODO.md §8; M1 ships vfmt_core::filelist (-f nesting with cycle + 256-depth guard, +incdir+/ +define+ recorded, env vars, warnings not errors), the vfmt.toml filelist key, the server scope ladder (filelist > workspace walk > open file's directory when rootless) and the vfmt.filelist VS Code setting. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
78eeef6050
commit
315bbf23ab
15 files changed
+1847
-37
No files matched your search
@@ -0,0 +1,449 @@
|
||||
# filelist
|
||||
|
||||
## Goal
|
||||
|
||||
Teach vfmt the EDA world's own project file. A `.f` filelist — one source
|
||||
path per line, `-f` nesting, `+incdir+`, `+define+`, comments and `$VAR`
|
||||
expansion — is what every Verilog build already has, so it is the honest
|
||||
answer to rope's `.ropeproject`: when a project has one, it defines
|
||||
*exactly* the set of files the server indexes, and the guesswork of walking
|
||||
a workspace folder disappears. This is M1 of
|
||||
`docs/features/refactor/README.md`: the parser lives in `vfmt_core` (next
|
||||
to config and walk, so a future CLI `-f` reuses it unchanged), the scope
|
||||
precedence lives in `vfmt_server`, and the two front doors that name a
|
||||
filelist are a `filelist` key in `vfmt.toml` and the VS Code setting
|
||||
`vfmt.filelist`.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The filelist is a *scope*, not a build description.** M1 records
|
||||
`+incdir+` and `+define+` and uses neither: vfmt does not preprocess, so
|
||||
an include path and a macro value change nothing about what the index
|
||||
contains. They are parsed now because a filelist that silently dropped
|
||||
them would have to be re-parsed later, and because "unknown flag" warnings
|
||||
would otherwise fire on the two flags every real filelist carries.
|
||||
- **A token starting `//` or `#` ends the line.** That is comment handling
|
||||
at token granularity, not at character granularity: `rtl/a.sv // top`
|
||||
comments out `// top`, and a path that genuinely contains a `#` in the
|
||||
middle of a component survives. A path *starting* with `#` cannot be
|
||||
written; nobody writes one.
|
||||
- **Paths resolve against the directory of the filelist that names them**
|
||||
— the EDA convention, and the same rule for source files, nested `-f`
|
||||
targets and `+incdir+` directories. The result carries them normalized
|
||||
(`.`/`..` folded, joined onto the current directory when the filelist
|
||||
itself was named relatively) so the index sees one spelling per file.
|
||||
Symlinks are deliberately **not** resolved, matching
|
||||
`config-discovery`'s "lexical, not symlink-aware" rule.
|
||||
- **An unknown flag is skipped alone, not with its argument.** vfmt has no
|
||||
table of which EDA flags take a value, and inventing one would be a
|
||||
guess. So `-y lib/` warns about `-y` and then reports `lib/` as a missing
|
||||
source file (a directory is not a file). Two warnings for one line is
|
||||
noisier than one, and it is honest: nothing was silently swallowed.
|
||||
- **A repeated filelist is skipped, whether or not it is a true cycle.**
|
||||
One `seen` set covers both, because the effect is identical — the same
|
||||
paths would be added twice — and the warning says which file was skipped.
|
||||
- **`-f` nests at most `MAX_NESTING_DEPTH` = 256 levels**, after which the
|
||||
chain is warned about and abandoned. The `seen` set stops a *cycle*; only
|
||||
a depth limit stops a long chain of **distinct** filelists, which is the
|
||||
shape a generator emits and which recursed until the stack overflowed
|
||||
(QA finding, 2026-08-24). A stack overflow is not a panic — it aborts the
|
||||
process, so the whole language server died on `initialize` rather than one
|
||||
filelist going bad. 256 is far above anything real (a hand-written
|
||||
filelist nests two or three deep) and far below the ~1500 frames at which
|
||||
an unoptimized build overflows, the same margin reasoning as
|
||||
`docs/features/recursion-limit/README.md`.
|
||||
- **A path containing whitespace cannot be listed.** Tokens are split on
|
||||
whitespace with no quoting, so `sp ace/file.sv` is two dead tokens and two
|
||||
"no such file" warnings, not one entry. EDA tools disagree about quoting
|
||||
and Verilog build trees conventionally have no spaces in them; support can
|
||||
be added when someone has such a tree, and until then the failure is at
|
||||
least loud rather than silent.
|
||||
- **An unset environment variable expands to nothing**, with a warning,
|
||||
rather than failing the whole filelist. That is what `vcs`/`xrun` do, and
|
||||
the missing-file warning that usually follows says the same thing again
|
||||
in more useful terms.
|
||||
- **Reading a filelist is I/O the server does on every index rebuild.** No
|
||||
caching, no watching: `rebuild_index` already re-reads the whole workspace
|
||||
on save, and one extra small file is nothing next to that.
|
||||
- **`vfmt.toml`'s `filelist` value is a path, not a glob.** It is resolved
|
||||
against the config file's own directory when the config is loaded, so the
|
||||
`FileConfig` a caller receives already carries a usable path.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `vfmt_core::filelist` (new module)
|
||||
|
||||
```rust
|
||||
pub const MAX_NESTING_DEPTH: usize = 256; // how deep `-f` may nest
|
||||
|
||||
pub struct Filelist {
|
||||
pub files: Vec<PathBuf>, // existing source files, in list order, deduped
|
||||
pub incdirs: Vec<PathBuf>, // recorded, unused in M1
|
||||
pub defines: Vec<(String, Option<String>)>, // recorded, unused in M1
|
||||
pub warnings: Vec<String>, // "<filelist>:<line>: <what>"
|
||||
}
|
||||
|
||||
pub fn read(path: &Path) -> Result<Filelist, String>;
|
||||
```
|
||||
|
||||
`Err` is reserved for the **root** filelist being unreadable — the one case
|
||||
where the caller learns nothing at all. Everything else (a nested `-f` that
|
||||
cannot be read, a listed file that does not exist, an unknown flag, an unset
|
||||
variable, a repeated filelist, a chain nested past `MAX_NESTING_DEPTH`) is a
|
||||
warning on an otherwise usable result. `read` neither panics nor aborts: on
|
||||
any input, including an adversarial one, it returns.
|
||||
|
||||
### `vfmt_core::config`
|
||||
|
||||
`FileConfig` gains `filelist: Option<PathBuf>`, from the new `vfmt.toml` key
|
||||
`filelist = "path"`. `parse` records the path **as written** (it has no idea
|
||||
where the file lives); `Discovery` resolves it against the config file's
|
||||
directory, so every `FileConfig` handed out by `Discovery` carries a
|
||||
resolved path. Same strictness as the other keys: a non-string value, a
|
||||
duplicate, or any unknown key is still a hard error naming file and line.
|
||||
|
||||
### `vfmt_server`
|
||||
|
||||
- `ClientSettings` gains `filelist: Option<String>` from `vfmt.filelist`.
|
||||
An empty string means "unset", which is what the VS Code default is.
|
||||
- `Workspace::set_client_settings` now returns `true` for a `filelist`
|
||||
change as well as an `exclude` change — both change *which files exist*.
|
||||
- `Workspace::rebuild_index()` and `open_roots()` now **return
|
||||
`Vec<String>`**, the warnings from resolving the scope. `state.rs` does
|
||||
no protocol I/O; `server.rs` renders them (one `window/showMessage`,
|
||||
every warning to `window/logMessage`), once per rebuild.
|
||||
- `Workspace::has_roots()` is new: with no workspace root the index scope
|
||||
follows the open buffers, so `server.rs` rebuilds on `didOpen` instead of
|
||||
only on save.
|
||||
|
||||
### The scope ladder (the contract this feature is)
|
||||
|
||||
Highest first, resolved on every index rebuild:
|
||||
|
||||
| # | Scope | When |
|
||||
|---|---|---|
|
||||
| 1 | The files a **filelist** names | `vfmt.filelist` is set (absolute, or relative to the first workspace root), else the workspace root's `vfmt.toml` has a `filelist` key |
|
||||
| 2 | The **workspace-folder walk** | there is a workspace root — unchanged from before this feature |
|
||||
| 3 | Each **open file's own directory**, non-recursive | there is no workspace root at all (a single file opened) |
|
||||
|
||||
Open buffers overlay every rung exactly as they did before: a buffer's text
|
||||
beats what is on disk, and a buffer whose path the scope does not name is
|
||||
added to the index anyway. A configured filelist that cannot be read falls
|
||||
back to rung 2 (or 3) with a visible warning — never a crash, never an empty
|
||||
index.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
New setting `vfmt.filelist` (string, default `""`), forwarded by the
|
||||
existing `synchronize.configurationSection: 'vfmt'` machinery — no
|
||||
extension code change.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/vfmt_core/src/filelist.rs`: parser + `Filelist` + `read`
|
||||
- [x] comments (`//`, `#`), blank lines, `-f` nesting with cycle/repeat
|
||||
detection and a 256-level depth limit, `+incdir+` (multi-`+`),
|
||||
`+define+NAME[=VAL]` (multi-`+`),
|
||||
`$VAR`/`${VAR}` expansion, unknown `+arg`/`-flag` warnings, missing
|
||||
files warned and skipped, relative resolution against the naming
|
||||
filelist
|
||||
- [x] `vfmt.toml` key `filelist`, resolved against the config's directory
|
||||
- [x] `vfmt.filelist` client setting, and the rescan it forces
|
||||
- [x] Server scope ladder (filelist ⊃ workspace walk ⊃ open-file directory)
|
||||
with warnings surfaced once per rebuild
|
||||
- [x] `vfmt.filelist` in `editors/vscode/package.json` + README; root
|
||||
README config and editor sections
|
||||
- [x] Unit tests in `vfmt_core` and `vfmt_server`; `cargo fmt`, `cargo
|
||||
clippy --all-targets`, `cargo test` all clean
|
||||
- [ ] Not done, deliberately: the CLI does not consume `filelist` yet
|
||||
(M1 is config-level plumbing plus the server; a `vfmt -f` flag is its
|
||||
own change with its own exit-code questions).
|
||||
- [ ] Not done, deliberately: `+incdir+`/`+define+` feed nothing. vfmt does
|
||||
not preprocess; when `` `include`` resolution arrives, it consumes
|
||||
`Filelist::incdirs` unchanged.
|
||||
- [ ] Not done, deliberately: no file watching. The filelist is re-read on
|
||||
every index rebuild (save, settings change, open with no root).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-24 — dev agent, M1
|
||||
|
||||
Written in the order the brief lists: parser, config key, server scope,
|
||||
editor setting. Decisions worth recording:
|
||||
|
||||
- **`read` returns `Result` only for the root file.** Every other failure
|
||||
is a warning on a usable result. The alternative — failing the whole
|
||||
filelist because one of 400 listed files was deleted — would make the
|
||||
server fall back to a workspace walk exactly when the user most wanted
|
||||
the filelist honoured.
|
||||
- **Comment stripping is per token, not per line.** A `#` at character
|
||||
granularity would truncate any path containing one; a token-initial `#`
|
||||
or `//` cannot be a path anyone writes. Recorded under Assumptions
|
||||
because it is the one place this parser is deliberately narrower than
|
||||
"strip everything after the first `#`".
|
||||
- **Environment lookup is injected** (`read_with(path, &dyn Fn(&str) ->
|
||||
Option<String>)`, private) so the expansion tests do not mutate the
|
||||
process environment — `std::env::set_var` from parallel test threads is
|
||||
a race even when it compiles. The public `read` closes over
|
||||
`std::env::var`, and one test drives it through a real variable to prove
|
||||
the wiring.
|
||||
- **Paths come out normalized and absolute.** Two spellings of one file
|
||||
(`rtl/../rtl/a.sv`) would otherwise become two `FileId`s in the index.
|
||||
`normalize` folds `.`/`..` textually and joins the current directory,
|
||||
exactly as `config::Discovery::absolute` does, and for the same reason:
|
||||
the path the user typed is the path they mean, symlinks included.
|
||||
- **Scope resolution returns its warnings instead of printing them.**
|
||||
`state.rs` has never spoken protocol and does not start now; the two
|
||||
functions that could produce warnings (`open_roots`, `rebuild_index`)
|
||||
return `Vec<String>` and `server.rs` decides how loud to be. It shows the
|
||||
first warning and logs all of them — a filelist with 40 stale paths must
|
||||
not open 40 popups.
|
||||
- **`didOpen` rebuilds the index when there is no workspace root.** Rung 3
|
||||
is defined by the open buffers, so without this the sibling-directory
|
||||
index would stay empty until the first save. With a root, nothing
|
||||
changed.
|
||||
|
||||
**Files touched outside the brief's scope**, all forced by the new field and
|
||||
kept to the minimum:
|
||||
|
||||
- `crates/vfmt/src/args.rs` — two `FileConfig`/help edits. Adding a public
|
||||
field breaks every struct literal, so the two test literals became
|
||||
`..Default::default()`; and `--help`'s CONFIGURATION paragraph lists the
|
||||
recognized keys by name, which would have been a lie the moment the parser
|
||||
accepted a fourth. The new line says `filelist` is read by `vfmt-server`
|
||||
only, so nobody expects the CLI to act on it.
|
||||
- `crates/vfmt_server/src/format.rs` — the same struct-literal fix in two
|
||||
tests. No behavior in that module changed.
|
||||
|
||||
**Deviations from the brief.** Two, both narrowing:
|
||||
|
||||
1. `Filelist::files` is **deduplicated** (first occurrence wins). The brief
|
||||
named the field but not the policy; `-f` nesting makes a file listed
|
||||
twice ordinary, and "exactly the set of files to index" is a set.
|
||||
2. `+incdir+` directories are **resolved** against the naming filelist's
|
||||
directory and normalized, not recorded verbatim. The brief said
|
||||
"recorded, not used further"; recording an unresolvable relative path
|
||||
would make the eventual consumer resolve it against the wrong
|
||||
directory, and the information needed (which filelist named it) is gone
|
||||
by then.
|
||||
|
||||
Also noted and **not** touched, being outside this feature's scope: the
|
||||
root `README.md`'s editor section still says "the server does **not** read
|
||||
`vfmt.toml` yet", which the `editor-settings` feature already made false.
|
||||
Flagged for the lead rather than fixed here. (The neighbouring sentence
|
||||
"One setting, `vfmt.serverPath`" *was* rewritten, because this feature adds
|
||||
a setting and leaving a count that is now wrong by three would have been
|
||||
worse than the one-line edit.)
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy
|
||||
--all-targets` silent; `cargo test --workspace` green — 1007 tests, of
|
||||
which 34 are new: 23 in `vfmt_core` (20 `filelist` + 3 `config`), 9 in
|
||||
`vfmt_server` (2 `settings`, 7 `state`) and 2 e2e sessions against the real
|
||||
binary (a filelist pushed, narrowed and broken mid-session; a file opened
|
||||
with no workspace folder). `node editors/vscode/smoke.js
|
||||
target/debug/vfmt-server` OK, `node --check` on both JS files, and
|
||||
`package.json` parses.
|
||||
|
||||
### 2026-08-24 — dev agent, QA round 1 fixes
|
||||
|
||||
**Finding 1 (Medium), fixed: unbounded `-f` recursion aborted the process.**
|
||||
`Reader` gained a `depth` counter and `filelist.rs` a documented
|
||||
`MAX_NESTING_DEPTH = 256`; `Reader::nested` checks it before descending and,
|
||||
past it, emits an ordinary warning naming the filelist that stopped and the
|
||||
target it refused (`f256.f:2: filelist \`f257.f\` nests more than 256 levels
|
||||
deep, not descending further`). The `seen` set was doing the job it was
|
||||
written for — cycles — and QA is right that it never bounded a chain of
|
||||
*distinct* files.
|
||||
|
||||
Why a depth guard rather than an iterative worklist: the recursion is what
|
||||
makes files land in list order (a nested filelist's files belong where the
|
||||
`-f` sits), and a worklist would have to carry every pending filelist's text
|
||||
to preserve that. A counter is three lines and matches the precedent the
|
||||
parser already set for the identical failure
|
||||
(`docs/features/recursion-limit/README.md`).
|
||||
|
||||
Why 256: a filelist that nests at all nests two or three deep, so 256 costs
|
||||
nobody anything real, and QA measured the overflow floor at ~1500 frames in
|
||||
an unoptimized build — a ~6× margin, in the direction where being wrong is
|
||||
an uncatchable abort rather than a diagnostic. Reasoning recorded on the
|
||||
constant and in Assumptions.
|
||||
|
||||
**Regression test**
|
||||
(`a_chain_of_distinct_filelists_stops_at_the_depth_limit`): a chain of
|
||||
`MAX_NESTING_DEPTH * 4` uniquely-named filelists, each naming its own source
|
||||
and `-f`-ing the next. Asserts `Ok`, exactly `MAX_NESTING_DEPTH + 1` files,
|
||||
the first and last of them by name, and exactly one warning naming the
|
||||
limit and the filelist that hit it — not one per remaining level, and not
|
||||
silence.
|
||||
|
||||
**Mutation-checked, because a guard test that cannot fail is worthless.**
|
||||
Raised the constant to 1 000 000 and pointed a throwaway test at a
|
||||
20 000-deep chain: `fatal runtime error: stack overflow, aborting`, SIGABRT,
|
||||
exactly QA's reproduction. Restored the constant and the file; the probe
|
||||
test is not in the tree.
|
||||
|
||||
**Re-verified on the real binary, as QA asked.** Built
|
||||
`target/release/vfmt-server`, gave it a scratch workspace whose `vfmt.toml`
|
||||
names a 20 000-level chain, and drove a raw stdio LSP session
|
||||
(`initialize` + `workspace/symbol` + `shutdown`/`exit`): exit code 0, both
|
||||
requests answered, the package declared in the chain found in the index, and
|
||||
one `window/showMessage` + one `window/logMessage` carrying the depth
|
||||
warning. Before the fix this same session died with SIGABRT on `initialize`.
|
||||
Scratch tree deleted.
|
||||
|
||||
**Finding 2 (Low), documented not fixed** — per the coordinator: paths
|
||||
containing whitespace are not representable, now stated in Assumptions with
|
||||
the reason (no quoting, EDA tools disagree, Verilog trees conventionally have
|
||||
no spaces) rather than left as an unstated gap. No parser change.
|
||||
|
||||
**Finding 3** needed nothing: QA agrees the `normalize` /
|
||||
`Discovery::absolute` duplication is deliberate and already justified in the
|
||||
work log above.
|
||||
|
||||
**Gates after the fix.** `cargo fmt --all -- --check` clean, `cargo clippy
|
||||
--all-targets` silent, `cargo test --workspace` green — 1008 tests (one new
|
||||
regression test), `vfmt_core` at 69 unit tests.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-24 — QA agent, M1
|
||||
|
||||
**Verification of the dev's claims.** `cargo fmt --all -- --check` clean,
|
||||
`cargo clippy --all-targets --workspace` silent, `cargo test --workspace`
|
||||
green — 1007 tests, matching the Work log's count exactly. Built
|
||||
`target/debug/vfmt-server` and `target/release/vfmt-server` and ran `node
|
||||
editors/vscode/smoke.js target/debug/vfmt-server` — OK. `node --check` on
|
||||
`editors/vscode/extension.js` and `smoke.js`, and `package.json` parses as
|
||||
JSON. Read `filelist.rs`, the `config.rs` diff, `state.rs`, `server.rs` and
|
||||
`settings.rs` in full; every claim in the Handshakes/Status sections checks
|
||||
out against the code, and the scope-ladder precedence (filelist > workspace
|
||||
walk > sibling directory) matches both the unit tests and my own probing.
|
||||
CLAUDE.md Rust standards: no `unwrap()`/`expect()`/`panic!` outside `#[cfg(test)]`
|
||||
in any changed file (`grep` over the diffs and over `filelist.rs`), no
|
||||
`unsafe`, no new dependency (`Cargo.toml`s unchanged), public items carry doc
|
||||
comments (`Filelist`, `read`, the new `FileConfig::filelist`,
|
||||
`ClientSettings::filelist`, `Workspace::has_roots`, etc.).
|
||||
|
||||
**Adversarial testing.** Built a throwaway `vfmt_core` example (`cargo run -p
|
||||
vfmt_core --example <probe>`, deleted afterwards — not committed) to drive
|
||||
`filelist::read` directly, plus a small Node script driving the real
|
||||
`vfmt-server` binary over stdio the way `smoke.js` does, against a
|
||||
`vfmt.toml`-configured filelist. Tried: a filelist that `-f`s itself, two
|
||||
filelists that `-f` each other, `-f` with no argument, a bare `+define+`
|
||||
line, `+define+N=a=b`, an unterminated `${VAR`, CRLF line endings, a path
|
||||
naming a directory, an empty filelist, a path containing a space, a `$` alone
|
||||
and at end of line, a unicode path, `-y lib/` (unknown flag with an
|
||||
argument-shaped next token), and deep `-f` nesting. All but the last behaved
|
||||
exactly as documented and as the existing unit tests assert:
|
||||
|
||||
- Self-`-f` and mutual `-f` cycles: caught by the `seen` set, one warning,
|
||||
no infinite loop, no crash.
|
||||
- CRLF: `str::lines()` already strips a trailing `\r`, so this needed no
|
||||
special-casing and there isn't any — confirmed it just works.
|
||||
- `+define+N=a=b` → `("N", Some("a=b"))` (first `=` splits, rest is the
|
||||
value) — matches `split_once` semantics, no test for it existed so I added
|
||||
none either (behavior is obvious from the code and not worth pinning).
|
||||
- A bare `+define+` line: silently defines nothing (the split-on-`+`
|
||||
iterator is empty). No warning, but also no claim anywhere that one should
|
||||
fire — not a bug.
|
||||
- `${VAR` and a lone `$`: both fall through to "not a variable reference,"
|
||||
stay literal, and go on to fail the missing-file check exactly as the
|
||||
existing `an_unterminated_brace_is_not_a_variable` test pins.
|
||||
- `-y lib/`: two warnings, `-y` unsupported and `lib/` no-such-file (it's a
|
||||
directory) — exactly the Assumptions section's own worked example.
|
||||
- A path with a space (`sp ace/file.sv`, unquoted): splits into two dead
|
||||
tokens (`sp`, `ace/file.sv`), each warned "no such file". Not a crash, but
|
||||
worth recording — see Finding 2.
|
||||
|
||||
**Finding 1 (Medium) — unbounded `-f` recursion overflows the stack and
|
||||
aborts the whole server process.** `Reader::filelist` → `Reader::nested` →
|
||||
`Reader::filelist` is plain function recursion with no depth limit; the
|
||||
`seen` set only rejects a *repeated* path, not a long chain of distinct
|
||||
ones. A straight chain of uniquely-named filelists, each `-f`-ing the next
|
||||
(no cycle, no repeat), crashes with `fatal runtime error: stack overflow,
|
||||
aborting` (SIGABRT) once it's deep enough:
|
||||
- `filelist::read` alone: overflows around 1500–3000 levels in a debug
|
||||
build, and somewhere between 10 000 and 30 000 in `--release`.
|
||||
- The **real `target/release/vfmt-server` binary**, given a workspace
|
||||
whose `vfmt.toml` names such a filelist, crashes the same way on
|
||||
`initialize` (confirmed via a raw stdio LSP session): `closed: code=null
|
||||
signal=SIGABRT`. This takes down the whole language-server process for
|
||||
every open file, not just a diagnostic on one buffer.
|
||||
|
||||
This contradicts the feature's own promise — `filelist.rs`'s module doc
|
||||
says "Nothing here fails on bad content... `read` never panics" (line 6-9),
|
||||
and the README's Handshakes section says the same ("`read` never panics").
|
||||
A stack overflow isn't technically a Rust `panic!` (it can't be caught by
|
||||
`catch_unwind` either), but the practical effect — an uncontrolled process
|
||||
abort instead of a graceful `Err`/warning — is exactly the failure mode
|
||||
hard invariant 1 and this feature's Assumptions ("never a crash, never an
|
||||
empty index") both rule out. 10k–30k levels of genuine hand-nested `-f` is
|
||||
unrealistic, but it is a very plausible shape for a *generated* filelist
|
||||
(a build script that emits one `.f` per source file, each nesting the
|
||||
next) at the scale of a large SoC's file count, and there's no guard
|
||||
today. Reproduction left as the two temp trees I generated and then
|
||||
deleted (not committed, since 20k+ tiny files don't belong in the repo);
|
||||
regenerate with a Python loop writing `f{i}.f` containing `-f f{i+1}.f`
|
||||
for `i` in `0..N`, terminated by a real source path, `N` in the low
|
||||
thousands for a debug build. Filed for the dev/lead — this is bigger than
|
||||
a QA-fixable typo (it needs either an explicit depth counter with a
|
||||
warning-and-stop, or converting the recursion to an explicit worklist),
|
||||
so I did not attempt a fix myself.
|
||||
|
||||
**Finding 2 (Low) — no quoting, so a path containing a space cannot be
|
||||
listed.** The tokenizer is `raw.split_whitespace()`
|
||||
(`crates/vfmt_core/src/filelist.rs:76`); a filelist line like `sp ace/file.sv`
|
||||
splits into two tokens and neither resolves, producing two spurious
|
||||
"no such file" warnings instead of one correct entry. Real EDA tools vary
|
||||
here (some support `"quoted paths"`, some don't support spaces at all), so
|
||||
this isn't necessarily wrong, but the Assumptions section documents several
|
||||
other narrowing decisions explicitly and this one isn't mentioned anywhere.
|
||||
Suggest either a one-line Assumptions addition ("paths containing whitespace
|
||||
are not representable, matching tools that require no-space build trees") or
|
||||
backlog quoting support — not a functional bug, not fixing myself since it's
|
||||
a documentation/scope call for the dev or lead to make.
|
||||
|
||||
**Finding 3 (trivial, informational only, not fixed) —** `Reader::normalize`
|
||||
(`filelist.rs:183-196`) is a byte-for-byte duplicate of
|
||||
`config::Discovery::absolute` (`config.rs:221-234`). The dev's Work log
|
||||
already calls this out and justifies it ("exactly as `config::Discovery::absolute`
|
||||
does, and for the same reason"); `Discovery::absolute` is a private method on
|
||||
a stateful struct so sharing it isn't a trivial extraction. Not filing as a
|
||||
real finding, just recording that I saw it and agree with leaving it as
|
||||
tracked, deliberate duplication rather than a missed reuse opportunity.
|
||||
|
||||
**Not re-verified independently (accepted on the dev's word, tests back it up):**
|
||||
the exact `Filelist::files` dedup-first-wins order and the `+incdir+`
|
||||
resolution-against-naming-directory behavior — both have direct unit tests
|
||||
(`dotted_paths_are_folded...`, `incdirs_are_recorded_in_both_the_single_and_the_multi_form`)
|
||||
that I read and consider adequate; I did not additionally hand-probe them.
|
||||
|
||||
**Verdict: ship-after-fixes.** Every claim in the feature README checks out,
|
||||
all three gates (`fmt`/`clippy`/`test`) are clean, and the server-side scope
|
||||
ladder is solid under real stdio sessions. Finding 1 is the one thing I would
|
||||
not ship as-is: it's a genuine crash of the whole server process, reachable
|
||||
through nothing more exotic than a large generated filelist, and it
|
||||
contradicts a promise the feature's own docs make twice. Findings 2 and 3
|
||||
are not blockers. Recommend the dev add a depth guard (or iterative
|
||||
worklist) to `Reader::nested`/`Reader::filelist` before this ships, with a
|
||||
masked-corruption-style regression test pinning that a filelist nested
|
||||
past the guard still returns a usable `Filelist` with a warning rather than
|
||||
aborting — and re-run the same deep-chain probe against the real
|
||||
`vfmt-server` binary as part of that fix's verification, since that's where
|
||||
the failure is actually user-visible.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-24 — lead.** Reviewed the full diff, the QA log and the QA-round-1
|
||||
fixes; ran `cargo fmt --check` / `clippy --all-targets` / `test --workspace`
|
||||
independently (28 suites, 0 failures). The parser is the boring, std-only
|
||||
implementation the plan asked for; the depth-guard fix is the right shape
|
||||
(same precedent as the parser's recursion limit), and the mutation check plus
|
||||
the real-binary re-verification is exactly the level of proof wanted for a
|
||||
crash fix. The scope ladder in `state.rs` keeps protocol out of the state
|
||||
layer and the `didOpen`-reindexes-only-when-rootless distinction is correctly
|
||||
reasoned. Deviations (dedup policy, resolved incdirs, the two out-of-scope
|
||||
test-literal touches) are all justified and logged. Accepted; M1 is checked
|
||||
off in the umbrella plan and TODO.md §8. Follow-ups inherited by later
|
||||
milestones: none blocking — the whitespace-path gap and `-F` stay documented
|
||||
non-goals until someone asks.
|
||||
@@ -0,0 +1,201 @@
|
||||
# refactor — a rope for Verilog/SystemVerilog (umbrella plan)
|
||||
|
||||
This is the **umbrella plan** for porting the ideas of
|
||||
[rope](https://github.com/python-rope/rope) — Python's refactoring library —
|
||||
to vfmt. It is the single source of truth for the refactoring roadmap: the
|
||||
feature list below is the checklist the lead crosses off as milestones land
|
||||
and pass QA. Each milestone is implemented as its **own feature** with its own
|
||||
`docs/features/<name>/README.md`, per the repo's document-based workflow; this
|
||||
file links to them.
|
||||
|
||||
## Goal
|
||||
|
||||
Give vfmt the refactoring layer that ruff/Pylance users take for granted and
|
||||
no Verilog tool ships well: rename that actually updates every reference
|
||||
across files, module signature changes (add/remove ports) that update every
|
||||
instantiation, and "module hinting" — instantiation skeletons generated from
|
||||
the module's real definition, the way type hints drive completion in Python.
|
||||
All of it server-first (VS Code + Vim through the one `vfmt-server` binary),
|
||||
scoped by an explicit **filelist** when the user has one and by sensible
|
||||
defaults when they don't, and covered by the same never-corrupt-code contract
|
||||
as the formatter.
|
||||
|
||||
## The rope → Verilog/SV mapping
|
||||
|
||||
What rope does for Python, and what the honest Verilog/SV equivalent is.
|
||||
This mapping is where the feature list comes from.
|
||||
|
||||
| rope feature | Verilog/SV translation |
|
||||
|---|---|
|
||||
| Rename (variables, functions, modules, params; optional in-comments) | Rename nets/variables, ports, parameters, modules, instances, functions/tasks, typedefs, enum members, struct fields, packages, genvars — cross-file through the workspace index |
|
||||
| Change signature (add/remove/reorder args, `autodef` defaults) | Add/remove/reorder **module ports and parameters**, updating the declaration *and every instantiation* (named, ordered, `.*`), plus task/function arguments |
|
||||
| Type hinting driving completion | **Module hinting**: the workspace index knows every module's ports/params, so instantiation is generated, completed and signature-helped from the definition |
|
||||
| Extract method | **Extract module**: lift a selected block of logic into a new module with inferred ports (read → input, driven → output), instantiate it in place |
|
||||
| Inline (function/parameter) | Inline a `localparam`/`parameter` value; inline a net with a single continuous assign into its uses |
|
||||
| Move (class/function to another module) | Move a typedef/function/localparam into a package; move a module to its own file (with `module-filename` agreement) |
|
||||
| Organize imports | Sort/dedupe `import pkg::*` / explicit imports; drop unused imports |
|
||||
| Restructure (pattern-based rewriting) | Deliberately deferred — a pattern language is a project of its own |
|
||||
| Project scope (`.ropeproject`) | **Filelist (`.f`)** — the EDA-native project file; fallback scope rules below |
|
||||
| Undo/redo history | Deliberate non-goal: LSP `WorkspaceEdit` gives client-side undo, and git is the history (rope predates ubiquitous VCS; we don't) |
|
||||
| Preview diffs | `WorkspaceEdit` is previewable in the client; CLI paths get `--diff`/`--check` |
|
||||
| Static object analysis (SOA/DOA) | Already exists: `vlog_semantic` + `WorkspaceIndex` are the analysis layer; refactorings consume them, never re-implement resolution |
|
||||
|
||||
## Feature list — what a good Verilog/SV refactoring tool supports
|
||||
|
||||
The lead checks items off **only after the milestone's QA log is clean and
|
||||
the work is reviewed**. Owner-priority items first (2026-08-24).
|
||||
|
||||
### Scope / project model
|
||||
- [x] **Filelist support** — accept a standard EDA filelist (`-f` style: one
|
||||
path per line, `-f` nesting, `+incdir+`, `+define+`, comments, env vars);
|
||||
when given, it defines *exactly* the set of indexed files
|
||||
→ `docs/features/filelist/README.md` (M1)
|
||||
- [x] **Fallback scope without a filelist** — workspace folders as today;
|
||||
when there is no workspace root (single file opened), index the files
|
||||
sharing the current file's directory → same feature (M1)
|
||||
|
||||
### Rename
|
||||
- [ ] **Rename any symbol** the semantic layer resolves — wire/reg/logic
|
||||
nets and variables, ports, parameters/localparams, genvars, typedefs,
|
||||
enum members, functions/tasks, modules, instances, packages, class
|
||||
members — via LSP `textDocument/rename` → `docs/features/refactor-rename/README.md` (M2)
|
||||
- [ ] **`prepareRename`** — reject up front what can't be renamed (keywords,
|
||||
macro uses, unresolved names), so the editor never offers a broken rename → M2
|
||||
- [ ] **Cross-file rename** through the workspace index (module names update
|
||||
every instantiation; package members update every import site) → M2
|
||||
- [ ] **Rename safety**: refuse on collision with an existing name in any
|
||||
affected scope, on invalid identifiers, and whenever any resulting file
|
||||
would no longer parse — whole-edit-or-nothing, like the formatter → M2
|
||||
- [ ] Rename in comments/strings as an *option* (rope's `docs=True`) — off
|
||||
by default; deferred until asked for
|
||||
|
||||
### Module signature (change signature)
|
||||
- [ ] **Add a port** to a module: declaration + every instantiation gains a
|
||||
named connection (`.p(p)` when a same-named signal is in scope at the
|
||||
instantiation, else `.p(/* connect */)`), non-ANSI decls updated too → `docs/features/refactor-ports/README.md` (M3)
|
||||
- [ ] **Remove a port**: dropped from the declaration and from every
|
||||
instantiation (named connection deleted; ordered connection turned into
|
||||
an explicit empty positional; refuse if the connected expression has
|
||||
visible side effects to preserve) → M3
|
||||
- [ ] **Propagate ports**: diff a module's declaration against each
|
||||
instantiation and add the missing named connections — the code action
|
||||
form that needs no free-form input → M3
|
||||
- [ ] Reorder ports / rename-a-port-as-signature-change (rename already
|
||||
covers the references; this is about connection order) — backlog
|
||||
- [ ] Parameter add/remove with default propagation (rope's `autodef`) — backlog
|
||||
- [ ] Task/function argument add/remove/reorder — backlog
|
||||
|
||||
### Module hinting (instantiation assist)
|
||||
- [ ] **Instantiate-from-definition**: completion on a module name at item
|
||||
position expands a full skeleton — parameter overrides with their
|
||||
declared defaults, every port as `.port(port)` with snippet tabstops → `docs/features/refactor-instantiate/README.md` (M4)
|
||||
- [ ] **Auto-connect**: a port whose name matches a signal in the enclosing
|
||||
scope is connected to it; the rest get placeholder tabstops → M4
|
||||
- [ ] **Signature help inside a connection list** — remaining ports, their
|
||||
directions and types, from the definition → M4
|
||||
- [ ] Declare-missing-signals companion action (generate `logic` decls for
|
||||
unconnected skeleton ports) — backlog
|
||||
|
||||
### Structural refactorings (backlog, post-M4)
|
||||
- [ ] **Extract module** from a selected statement range (infer ports from
|
||||
read/driven sets) — the flagship, hardest one
|
||||
- [ ] **Inline localparam/parameter** value at every use
|
||||
- [ ] **Inline net** with a single continuous assign
|
||||
- [ ] **Expand `.*`** into explicit named connections (and the reverse)
|
||||
- [ ] **Ordered → named connections** conversion
|
||||
- [ ] **Non-ANSI → ANSI header** conversion
|
||||
- [ ] **`reg`/`wire` → `logic`** modernization (pairs with the
|
||||
`wire-reg-mixup` lint rule's fix slot)
|
||||
- [ ] **Move typedef/function/localparam into a package**; update imports
|
||||
- [ ] **Organize imports** (sort, dedupe, drop unused)
|
||||
- [ ] **Rename module together with its file** (`module-filename` rule
|
||||
agreement; needs LSP `workspace/willRenameFiles` plumbing)
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The semantic layer is the ground truth for "what references what".
|
||||
Refactorings **never do textual search-and-replace**; every edit comes
|
||||
from a resolved reference span. Where resolution is honest about
|
||||
uncertainty (`InheritedCandidate`, ambiguous duplicates), the refactoring
|
||||
refuses rather than guesses — rope's "unsure matches" mode is *not* ported.
|
||||
- vfmt does not preprocess. A rename target whose name also appears inside
|
||||
a `` `define`` body or an `` `ifdef``-excluded region is reported as a
|
||||
warning on the response, and those occurrences are left untouched.
|
||||
- Verification budget: re-parsing every touched file after an edit is
|
||||
affordable (files are small; the corpus parses at ~ms each). No
|
||||
refactoring needs the *formatter's* verify pass, and none touches
|
||||
`verify.rs` (hard invariant 4 stays untouched).
|
||||
- Filelist paths are resolved relative to the filelist's own directory,
|
||||
the EDA convention. `+incdir+`/`+define+` are recorded but only paths
|
||||
feed the index in M1.
|
||||
- Owner interpretation (2026-08-24): "no filelist → index files sharing the
|
||||
current file's path" is implemented as the *no-workspace-root* fallback;
|
||||
when the editor did open a workspace, the existing folder walk already
|
||||
covers (and supersedes) the sibling-directory behavior.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_semantic`**: refactorings consume `Semantics` (`symbol_at`,
|
||||
`references_of`), `WorkspaceIndex` and `ExternalResolutions` read-only.
|
||||
Any resolution gap found while refactoring is filed against
|
||||
`vlog-semantic`, not patched around in the refactor crate.
|
||||
- **`vfmt_server`**: owns only the protocol mapping (WorkspaceEdit,
|
||||
completion/snippet encoding, signature help); all edit *computation*
|
||||
lives in the new `vlog_refactor` crate so Vim gets identical behavior.
|
||||
- **`vfmt_core`**: filelist parsing lives here (next to config/walk), so a
|
||||
future CLI `-f` flag reuses it unchanged.
|
||||
- **`vlog_formatter`**: not a dependency. Refactored output is *edited
|
||||
source*, not reformatted source — the user runs the formatter separately.
|
||||
(Keeps refactor edits minimal and reviewable, and keeps the formatter's
|
||||
safety net out of scope.)
|
||||
- **`editors/vscode`**: new setting `vfmt.filelist` (string path, default
|
||||
empty) forwarded like the existing `vfmt.*` settings.
|
||||
|
||||
## Milestones
|
||||
|
||||
Each is one feature dir, one dev agent, one QA pass, one lead review, one
|
||||
commit — in order:
|
||||
|
||||
1. **M1 `filelist`** — `.f` parsing in `vfmt_core` (paths, `-f` nesting with
|
||||
cycle detection, `+incdir+`/`+define+` recorded, `#`//`//` comments,
|
||||
`$VAR`/`${VAR}` expansion; unknown `+args`/`-flags` skipped with a
|
||||
warning), server scope resolution (filelist ⊃ workspace walk ⊃
|
||||
current-file directory), `vfmt.filelist` VS Code setting + vfmt.toml
|
||||
`filelist` key.
|
||||
2. **M2 `refactor-rename`** — new crate `vlog_refactor` with the edit-plan
|
||||
model (`RefactorEdit { file → Vec<TextEdit> }`, verification by
|
||||
re-parse), rename engine, LSP `prepareRename`/`rename`.
|
||||
3. **M3 `refactor-ports`** — add/remove/propagate port across declaration +
|
||||
all instantiations, exposed as code actions + `workspace/executeCommand`.
|
||||
4. **M4 `refactor-instantiate`** — instantiation completion snippets,
|
||||
auto-connect, signature help in connection lists.
|
||||
5. **Backlog** — the unchecked structural items above, re-planned when the
|
||||
first four have soaked.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Plan written; rope docs surveyed (overview: rename, extract, inline,
|
||||
move, change signature, restructure, organize imports, SOA/DOA, history)
|
||||
- [x] M1 filelist — done, QA clean, reviewed
|
||||
- [ ] M2 refactor-rename
|
||||
- [ ] M3 refactor-ports
|
||||
- [ ] M4 refactor-instantiate
|
||||
- [ ] Backlog triage after M4
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-08-24 (lead)**: Umbrella plan created from the rope overview docs
|
||||
and the current state of `vlog_semantic`/`vfmt_server`/`WorkspaceIndex`.
|
||||
Key decisions: server-first (no CLI surface yet), semantic-resolution-only
|
||||
edits (no textual fallback), whole-edit-or-nothing verification by
|
||||
re-parse, filelist in `vfmt_core`, rope's history/restructure explicitly
|
||||
not ported. Milestone READMEs are created by their dev agents.
|
||||
|
||||
## QA log
|
||||
|
||||
(reserved for the QA agents of the milestone features; this umbrella doc
|
||||
itself carries no code)
|
||||
|
||||
## Review
|
||||
|
||||
(reserved)
|
||||
Reference in new issue
Block a user