Files
lucisv/docs/features/refactor/README.md
T
lucioandClaude Fable 5 d8e37086df Refactoring M5: keyword + project-wide identifier completion; v0.3.0
Five completion tiers in one response: module skeletons (M4, unchanged
gate), scope-visible symbols with real kinds, workspace-index names and
`define macros (backtick-aware, never inventing punctuation), Verilog/SV
keywords (single-source KEYWORDS list factored from the lexer's table,
lexing unchanged), and token-harvested project words — comments and
strings contribute nothing and get no completions. Candidate tables build
with the index over the M1 scope ladder (94 ms / 860 files, ~1.4 MiB);
a keystroke answers in ~300 µs, budget-tested. Version 0.3.0 across the
workspace and extension, CHANGELOG covers the M1-M5 refactoring layer.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-24 15:07:57 -07:00

228 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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
- [x] **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)
- [x] **`prepareRename`** — reject up front what can't be renamed (keywords,
macro uses, unresolved names), so the editor never offers a broken rename → M2
- [x] **Cross-file rename** through the workspace index (module names update
every instantiation; package members update every import site) → M2
- [x] **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)
- [x] **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)
- [x] **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
- [x] **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)
- [x] **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)
- [x] **Auto-connect**: a port whose name matches a signal in the enclosing
scope is connected to it; the rest get placeholder tabstops → M4
- [x] **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
### Completion (owner request, 2026-08-24 evening)
- [x] **Keyword completion** — Verilog/SV keywords offered as completion
items alongside everything else → `docs/features/completion-core/README.md` (M5)
- [x] **Project-wide identifier completion** — names visible in the current
scope (semantics-ranked first) plus identifiers used anywhere in the
project scope (filelist, else workspace walk, else same-directory —
M1's ladder), harvested from *tokens* so comments and strings never
contribute candidates; no completions offered while typing inside a
comment or string → M5
- [x] **Version 0.3.0** — workspace + extension bump with a CHANGELOG entry
covering the whole refactoring layer (M1–M5) → M5
### 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)
- [ ] **Completion for preprocessor directive words** (`` `ifdef`` …) and
suppressing self-instantiation skeletons — two LOW QA finds from M5
- [ ] **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. **M5 `completion-core`** — keyword + project-wide identifier completion
(token-harvested, comment/string-free), merged with M4's module
snippets; version bump to 0.3.0.
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
- [x] M2 refactor-rename — done, QA clean after one rework round, reviewed
- [x] M3 refactor-ports — done, QA clean after one rework round, reviewed
- [x] M4 refactor-instantiate — done, QA clean after one rework round, reviewed
- [x] M5 completion-core — done, QA clean first pass, reviewed
- [ ] Backlog triage after M5
## Work log
- **2026-08-24 (lead, end of day)**: M1–M4 all landed the same day, each
through the full dev → QA → rework → re-QA → lead-review loop (commits
315bbf2, 33f5819, e338524, 5785fd9). Every milestone needed exactly one
QA-driven rework round; the recurring theme was silent-wrongness at the
preprocessor boundary (`ifdef arms, macro arguments), now handled
uniformly: refuse when placement is uncertain, warn when only visibility
is. Workspace suite grew 1007 → 1232 tests. Backlog triage is the next
session's first task.
- **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)