Files
lucisv/docs/features/refactor/README.md
T

305 lines
18 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 lucisv. 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 lucisv 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 `lucisv-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
### Templates (owner request, 2026-08-24 night)
- [x] **Statement/item template completion** — context-gated snippet items
from the server (both editors): `if`/`if-else`/`else-if`, `case` with
`default`, `always_ff`/`always_comb`/`always @(...)`, `for`/`while`,
`initial`, declarations (`logic x;`-style), each with tabstops (condition
first, then body) → `docs/features/completion-templates/README.md` (M6)
- [x] **Reconcile with the static VS Code snippets** — no prefix offered
twice; file-level templates (module, tb, FSM) stay static → M6
- [x] **Version 0.4.0** → M6
### 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)
### LSP-parity and plumbing gaps (lead triage, 2026-08-24 night)
Found by auditing the shipped capability set against the LSP end goal
(Pylance/ruff parity), the code's own "not shipped" notes, and what M1–M6
built but nothing consumes yet. Ordered by value ÷ cost:
- [x] **Cross-file find-all-references** — `textDocument/references` is
still in-file only (nav.rs:50; lucisv-server README names it "not done"),
yet M2's rename already collects cross-file reference sets in
`vlog_refactor`. Rename can change what references can't even list.
Reuse M2's collection for the references answer — mostly wiring.
- [x] **Folding ranges** — `pairs.rs` already computes every
begin/end/module/generate range for the rainbow; `foldingRange` is the
same data on a standard capability. Cheapest win on this list.
- [x] **Document highlight** — cursor on a symbol highlights its other
occurrences; one `references_of` call, no new analysis.
- [x] **Inlay hints for ordered connections** — `u (clk, rst_n, data)`
shows `.clk:`/`.rst_n:` ghost labels from the instantiated module's
definition (same index facts as M4); parameter names on ordered
`#(...)` overrides too. High everyday value in RTL review.
- [x] **External file-change awareness** — the index rebuilds on save and
didOpen only; a `git pull`, an external edit, or editing the `.f`
filelist itself goes unnoticed until the next save. Register
`workspace/didChangeWatchedFiles` (sources + the filelist) and reindex.
- [x] **`` `include`` navigation and `+incdir+` consumption** — M1 records
incdirs and nothing uses them; `` `include "x.svh" `` is not clickable
and the define table stays per-file. Document links (or definition) on
include lines, resolved through the filelist's incdirs, and a
cross-file define-table lookup along the include graph.
- [x] **Module hierarchy** — "who instantiates X / what does X
instantiate", as LSP callHierarchy (modules as the nodes) or a custom
request the extension renders; the index already knows both directions.
- [x] **Semantic lint rules** — unused-signal, undriven-net,
multiply-driven: TODO.md §7 calls this the differentiation Verible
cannot do, `vlog_semantic` has existed for rounds, and no semantic rule
ships yet.
- [x] **CLI `-f` filelist flag** — the lucisv.toml `filelist` key and the
server consume M1's parser; `lucisv -f files.f` (format/lint exactly the
project's files) still does not exist.
- [x] **Single-step macro expansion on hover** — the define-table README
promised it "later"; hover shows the body but expands nothing.
Already tracked elsewhere, deliberately not duplicated here: the
structural refactorings above, external waiver files, fuzzing, error-case
tests, component-level tests, CST losslessness round-trip, `insta`,
corpus-check CI wiring, `--diff-base`, salsa (TODO.md §4–6).
## 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.
- lucisv 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.
- **`lucisv_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.
- **`lucisv_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 `lucisv.filelist` (string path, default
empty) forwarded like the existing `lucisv.*` 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 `lucisv_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), `lucisv.filelist` VS Code setting + lucisv.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.
6. **M6 `completion-templates`** — context-gated statement/item snippet
templates; version 0.4.0. (0.4.1 hover-highlighting grammar and 0.4.2
color-decorator fix landed as owner-reported fixes, not milestones.)
7. **Backlog** — triaged 2026-08-24 night; next milestone is picked from
the LSP-parity list (cross-file references and folding first) unless
the owner reprioritizes.
## 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
- [x] M6 completion-templates — done, QA clean first pass, reviewed
- [x] Backlog triage after M6 — LSP-parity gap list added, 2026-08-24
- [x] M7 references-nav — done, QA clean first pass, reviewed
- [x] M8 inlay-hints — done, one QA HIGH fixed in-round, reviewed
- [x] M9 file-watching — done, QA clean first pass, reviewed
- [x] M10 include-nav — done, one QA HIGH reworked, reviewed
- [x] M11 hierarchy — done, QA doc-fixes in-round, reviewed
- [x] M12 semantic-lints — done, one QA medium reworked, reviewed
- [x] M13 cli-filelist — done, QA clean first pass, reviewed
- [x] M14 macro-expansion — done, QA clean first pass, reviewed; 0.5.0
## Work log
- **2026-08-24 (lead, backlog triage)**: Audited the feature list against
the shipped capability set. Nine gaps added under "LSP-parity and
plumbing gaps" — the standouts: references is still in-file while rename
is cross-file (M2's machinery makes the fix cheap), folding is free data
the rainbow already computes, inlay hints for ordered connections, file
watching, and the `+incdir+`s M1 records but nothing consumes. Milestone
numbering fixed (duplicate "5."). Nothing shipped was found mis-checked.
- **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`/`lucisv_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 `lucisv_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)