Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97aa2fefd8 | ||
|
|
9604753b6c | ||
|
|
797ef86d47 | ||
|
|
a30dda167a |
No files matched your search
@@ -4,6 +4,52 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.41.0 — 2026-09-04
|
||||
|
||||
### Code actions off the fan-out
|
||||
|
||||
- **Lazy port refactorings.** For a client that supports
|
||||
`codeAction/resolve` (VS Code does), the port actions are offered from
|
||||
the buffer and the instantiated module's declaration alone, and the
|
||||
edit is computed when the action is picked. The request VS Code sends
|
||||
on nearly every cursor move no longer reads the module's fan-out:
|
||||
flat at ~55 µs in-process from a 3-file to a 128-file fan-out, where
|
||||
it was linear (15 ms at 128). A resolve for an action that no longer
|
||||
applies is an error, not an empty edit. Clients without resolve
|
||||
support get the edit up front, as before.
|
||||
- **Definitions from the index.** `textDocument/definition` and
|
||||
workspace symbols for a file-scope declaration in a closed file now
|
||||
build the location from the positions the index already records
|
||||
instead of reading the file: 0.4 µs against 28 µs per answer.
|
||||
- **inlayHint at the default scope**: investigated, not changed. The
|
||||
hints missing at that scope belong to a module declared outside what
|
||||
the scope reaches; definition and hover say the same. A scope
|
||||
question, recorded in the feature README.
|
||||
|
||||
## 0.40.0 — 2026-09-04
|
||||
|
||||
### Two parser residues and atomic writes
|
||||
|
||||
- **A bare `begin … end` at module scope, or straight inside
|
||||
`generate … endgenerate`, is recovered** in error-tolerant mode as an
|
||||
unnamed generate block (`ItemKind::GenBlock`) with a diagnostic at the
|
||||
keyword, instead of being refused and taking the rest of the unit with
|
||||
it. The items inside and after the block are now visible to the
|
||||
editor and to every lint rule; `module-begin-block`,
|
||||
`v2001-generate-begin` and `mismatched-labels` read the node. Strict
|
||||
parsing is unchanged, so the formatter still refuses the file exactly
|
||||
as before.
|
||||
- **A half-typed `#(` override or connection whose value would read as
|
||||
the next instance** (`sub #(.W(8), .DEPTH(` ⏎ `u0 (.a(x));`) now costs
|
||||
one error element: `.W(8)` survives, `u0` is an instance with its
|
||||
connections, one diagnostic on the unclosed `(`. The balanced-parens
|
||||
spelling stays ambiguous and is still parsed greedily, by design.
|
||||
- **In-place writes are atomic.** `lucisv format`, `lucisv check --fix`
|
||||
and the cache write a sibling temp file and rename it over the target,
|
||||
so a crash or a full disk never leaves a source file truncated. The
|
||||
target's permissions are kept, a symlink's *target* is what gets
|
||||
replaced, and a read-only file is refused as it always was.
|
||||
|
||||
## 0.39.0 — 2026-09-04
|
||||
|
||||
### The rest of Verible's rules
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.39.0"
|
||||
version = "0.41.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -1233,19 +1233,26 @@ Files: `crates/lucisv_server/src/{candidates.rs,state.rs,server.rs,perf.rs}`,
|
||||
|
||||
### Deferred, filed
|
||||
|
||||
- [ ] `codeAction` costs 185–201 ms at a 128-file fan-out and offers
|
||||
- [x] `codeAction` costs 185–201 ms at a 128-file fan-out and offers
|
||||
**zero** actions there (`performance_take2.md` §6a): ~1.4 ms per
|
||||
instantiating file plus a ~13 ms floor, paid before anything knows
|
||||
there is nothing to offer. Wants either the lazy resolve below or
|
||||
a cheap zero-detector that answers before the fan-out is walked.
|
||||
- [ ] `inlayHint` returns **0 hints at the default scope** where the
|
||||
**Delivered by §37.1**: the offer is flat at 54–59 µs from a 3- to a
|
||||
128-file fan-out, both cursor shapes.
|
||||
- [x] `inlayHint` returns **0 hints at the default scope** where the
|
||||
workspace scope returns 4 (`performance_take2.md` §8): investigate
|
||||
before assuming it is scope-relative-answers working as intended —
|
||||
the hinted instantiation's module may be in scope and still unhinted.
|
||||
- [ ] codeAction lazy resolution (`codeAction/resolve`): make the offer
|
||||
**Investigated by §37.2 and ruled correct**: the four hints are
|
||||
`pins_if`'s, declared in `hw/dv/sv/common_ifs`, which the widen to
|
||||
`hw/ip/aes` does not reach; hover and definition answer nothing for it
|
||||
either. Finding and two default-scope tests in
|
||||
`docs/features/lazy-code-action/README.md`.
|
||||
- [x] codeAction lazy resolution (`codeAction/resolve`): make the offer
|
||||
index-only (~0 ms regardless of fan-out), edits computed on
|
||||
lightbulb click — kills the 83 ms worst case. Owner-approved
|
||||
direction, after the wave.
|
||||
direction, after the wave. **Delivered by §37.1.**
|
||||
- [x] Rename over an index-stale workspace: Lane A must state the
|
||||
staleness premise; if the verifier cannot catch a hidden
|
||||
reference, the honesty gate is the lead's review call. Stated
|
||||
@@ -1290,10 +1297,17 @@ and three owner items. See
|
||||
lowercased index with a character-mask pre-filter and a counting
|
||||
top-K — 3–8 ms per query over a generated 120 000-entry
|
||||
hierarchy, asserted in the node suite.
|
||||
- [ ] Filed, not done: rewire `locate::location` onto `DeclPositions`
|
||||
- [x] Filed, not done: rewire `locate::location` onto `DeclPositions`
|
||||
so `textDocument/definition`, references, the lens and both
|
||||
hierarchies stop reading a file to convert an indexed span. Every
|
||||
unit's range is now in the index for free.
|
||||
unit's range is now in the index for free. **Delivered by §37.3**
|
||||
for the file-scope answers `nav.rs` and `symbols.rs` give
|
||||
(27.9 µs → 0.42 µs per definition on opentitan); references, the
|
||||
lens and the hierarchies answer from `ReferenceSite`/`InstantiationEdge`
|
||||
spans, which are not `Def`s and record no `DeclPositions`, and
|
||||
`references`' one `Def` span (`includeDeclaration`) is converted in the
|
||||
same one-fetch batch as that file's reference sites — filed again
|
||||
there rather than silently dropped.
|
||||
- [ ] Manual extension-host acceptance (themes, keyboard-only, zoom,
|
||||
screen readers, an old server binary, both VSIX shapes).
|
||||
|
||||
@@ -2913,12 +2927,12 @@ collide); no parallel lane.
|
||||
`undriven-net`, exactly as in `covergroup-bodies`.
|
||||
- [x] P5 verbatim-SVA rename warning (pin: a fallback region spelling
|
||||
the old name warns, never silent)
|
||||
- [ ] P6 §2.9-18 wiring (pin: a file whose only relationship to the name
|
||||
- [x] P6 §2.9-18 wiring (pin: a file whose only relationship to the name
|
||||
is a macro argument still warns) — the **engine half is done and
|
||||
pinned**; the server fan-out (`Workspace::rename_sources`,
|
||||
outside the round's file list) is filed as Handshake request 1 in
|
||||
`docs/features/sva-bodies/README.md`, with the unbounded-read-set
|
||||
objection that makes it a lead's call rather than a mechanical wiring
|
||||
objection that makes it a lead's call rather than a mechanical wiring. **Delivered by §29** (macro-word census, `unread_macro_warnings`).
|
||||
- [x] P7 SVA gap fuzzer at zero (705 gaps, 0 failures); the 12 assertion
|
||||
attack pairs kept plus 46 new ones; `verify.rs` untouched
|
||||
- [x] Measurement: opentitan **79/79 declarations and 97/97 assertions**
|
||||
@@ -2928,7 +2942,7 @@ collide); no parallel lane.
|
||||
corpus 13 files moved and opentitan 36, all inside assertion text;
|
||||
both sweeps otherwise byte-identical; the 4 854 `` `ASSERT* ``
|
||||
invocations byte-identical
|
||||
- [ ] QA on opentitan (read-only): structured counts re-derived; every
|
||||
- [x] QA on opentitan (read-only): structured counts re-derived; every
|
||||
moved file's diff read; rename of a signal used in
|
||||
`hw/ip/*/rtl/*_assert*.sv` properties; sweep unchanged
|
||||
|
||||
@@ -3126,7 +3140,7 @@ edge).
|
||||
store measurement +123 402 bytes (+3.11 %) on the corpus and
|
||||
+743 873 (+1.66 %) on opentitan; opentitan `lucisv check` sweep
|
||||
byte-identical, working tree untouched
|
||||
- [ ] QA: rename of `clk` in an opentitan IP with the server, timing
|
||||
- [x] QA: rename of `clk` in an opentitan IP with the server, timing
|
||||
before/after (must not regress; the warning list must name only
|
||||
files outside the source set), the pins re-derived
|
||||
|
||||
@@ -3223,7 +3237,7 @@ parallel with §29.
|
||||
unchanged — 3 223/48 tests, 0 clippy warnings, 814/820 with the
|
||||
same six failures, 0 diffs over 860 corpus and 3 947 opentitan
|
||||
files
|
||||
- [ ] QA: hand-written interface + DPI files in every listed shape,
|
||||
- [x] QA: hand-written interface + DPI files in every listed shape,
|
||||
idempotent, comments kept; the negative pin; sweep unchanged
|
||||
|
||||
## 31. Format fences at statement level and inside class bodies (planned 2026-09-02) — M9, §2.9-3
|
||||
@@ -3329,7 +3343,7 @@ lead may start it in parallel if §30's files are settled).
|
||||
3 234/0/42); corpus 814/820, 860 files byte-identical to the 0.34.0
|
||||
binary; opentitan census 9 fenced files of 3 947 — 4 moved, each
|
||||
keeping its own fenced bytes, `--check` counts unchanged
|
||||
- [ ] QA: fences in every statement scope listed and in the three
|
||||
- [x] QA: fences in every statement scope listed and in the three
|
||||
deferred places (must be inert, never corrupt); an `off` with no
|
||||
`on` in each scope (runs to the scope end only); nested fences;
|
||||
`--lines` over a fenced statement; `--fix` still declines inside
|
||||
@@ -3474,7 +3488,7 @@ formatter collide with §30's tf.rs/module.rs at merge; sequential).
|
||||
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
byte-identical (strict path untouched); opentitan read-only sweep
|
||||
unchanged
|
||||
- [ ] QA: type each of the (a)–(f) shapes into the real server against
|
||||
- [x] QA: type each of the (a)–(f) shapes into the real server against
|
||||
an opentitan file and read the published diagnostics and the
|
||||
outline; the fuzzers re-run; strict-mode parity re-derived
|
||||
|
||||
@@ -3646,7 +3660,7 @@ linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
|
||||
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
byte-identical (formatter untouched); opentitan read-only
|
||||
`lucisv check` census + timing
|
||||
- [ ] QA: every new rule attacked with hand-written true positives and
|
||||
- [x] QA: every new rule attacked with hand-written true positives and
|
||||
near-misses; the false-positive census re-read; toggles exercised
|
||||
through the real server (`workspace/didChangeConfiguration`)
|
||||
|
||||
@@ -3774,7 +3788,7 @@ Every suite and sweep under `tools/guard.sh`.
|
||||
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
|
||||
814/820 byte-identical; vsix smoke; opentitan read-only census +
|
||||
timing vs 0.36.0
|
||||
- [ ] QA: options attacked (bad key/kind/range/regex on both front
|
||||
- [x] QA: options attacked (bad key/kind/range/regex on both front
|
||||
ends), every rule with near-misses, the census re-read
|
||||
|
||||
## 35. Linter expansion, wave 3 (planned 2026-09-04) — the remaining Verible rules
|
||||
@@ -3837,5 +3851,273 @@ README.md rows, docs-site sections, coverage_gaps "linter" addendum.
|
||||
- [x] docs + regenerated toggles
|
||||
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
|
||||
814/820 byte-identical; vsix smoke; opentitan census + timing
|
||||
- [ ] QA: every rule attacked; census re-read; options attacked
|
||||
- [x] QA: every rule attacked; census re-read; options attacked
|
||||
|
||||
|
||||
## 36. Small items, round 3 (planned 2026-09-04) — topo §2.9-24, §2.9-25, atomic writes
|
||||
|
||||
One lane, in the main tree (owner's call: no worktree, no parallel lane; QA
|
||||
reads the same tree). Dev: Opus 5. QA: Sonnet 5. Feature README:
|
||||
`docs/features/small-items-3/README.md`. Ships as 0.40.0.
|
||||
|
||||
**File ownership** (the whole tree is free, but this is the expected touch
|
||||
set — anything outside it is named in the work log):
|
||||
`crates/vlog_parser/src/parser/{item.rs,instance.rs,recover_list.rs}`,
|
||||
`crates/vlog_parser/src/ast/{mod.rs,module.rs}`,
|
||||
`crates/vlog_parser/tests/error_recovery.rs`,
|
||||
`crates/vlog_formatter/src/format/item.rs` (one arm),
|
||||
`crates/vlog_linter/src/rules/{module_begin_block,v2001_generate_begin}.rs`
|
||||
and every exhaustive `ItemKind` match the new variant reaches
|
||||
(`vlog_semantic`, `vlog_refactor`, `lucisv_server`, `vlog_linter/visit.rs`),
|
||||
`crates/lucisv_core/src/{atomic.rs (new),cache.rs,lib.rs}`,
|
||||
`crates/lucisv/src/{main.rs,lint.rs}`, the two rules' rows in `README.md`
|
||||
and `docs/site/src/content/docs/reference/rules.md`, `docs/topo.md` §2.9
|
||||
(strike 24 and 25 — lead does this at review), this section.
|
||||
|
||||
### 36.1 A bare `begin … end` at module scope or in a generate region is recovered as a block (topo §2.9-25)
|
||||
|
||||
Today `parse_keyword_item` has no `begin` arm, so the item fails with
|
||||
"expected item", `item_or_recover` skips to a sync point and the rest of the
|
||||
unit is lost. Wanted: in **tolerant mode only**, the block is parsed and kept.
|
||||
|
||||
- New `ItemKind::GenBlock(Box<GenBlock>)` — the existing generate-block node
|
||||
(`is_block: true`, label optional). No new node type.
|
||||
- `parse_keyword_item`: a `"begin"` arm. Strict mode: the same "expected
|
||||
item" error as today (byte-identity of every corpus file depends on the
|
||||
strict parser refusing this; nothing about strict mode changes).
|
||||
Tolerant mode: `self.record("`begin`/`end` block is not a module item")`
|
||||
*at the `begin` keyword*, then `parse_gen_block()` and wrap it. The
|
||||
diagnostic is not optional: the file must still be reported as not
|
||||
parsing cleanly, so the formatter's "zero errors or nothing" contract
|
||||
keeps refusing it exactly as before.
|
||||
- Consumers, each the boring choice: the formatter prints it the way
|
||||
`gen_block` prints an `if` arm's block (indent the items, `end`, the end
|
||||
label if any) — it never reaches output today (a diagnostic is always
|
||||
recorded) but the arm exists so a future range/tolerant printer has
|
||||
nothing to invent; the semantic binder walks its items as one unnamed
|
||||
generate block scope, the same scope shape an unlabeled `if` arm's block
|
||||
gets (find how `GenIf` arms are bound and reuse that path — do not invent
|
||||
a scope kind); `visit.rs`/outline/refactor walkers descend into
|
||||
`items` and nothing else.
|
||||
- The two rules stop reading an error leaf: `begin_block(item)` returns the
|
||||
`begin` keyword's range (`span.start .. +5`) of an `ItemKind::GenBlock`
|
||||
and `None` for everything else; delete `first_word_is_begin`. Doc strings
|
||||
of both rules: replace the "parser rejects … rest of the module is lost"
|
||||
paragraph with the truth (the parser recovers the block in tolerant mode
|
||||
and records a diagnostic; the block's items are visible to every other
|
||||
rule). Same paragraph in `README.md`'s rule rows and `rules.md`.
|
||||
- Tests (in `tests/error_recovery.rs` and the two rules' modules):
|
||||
`a_module_scope_begin_block_keeps_its_items_and_the_items_after_it`
|
||||
(block with a `wire` inside, an `assign` after it, `endmodule` consumed,
|
||||
exactly one diagnostic at `begin`); the generate-region twin; strict mode
|
||||
still refuses both (an `Err`, not a node); an `end : label` on the block
|
||||
round-trips into `end_label`; a nested `begin` inside the block recovers
|
||||
the same way (two diagnostics, both blocks kept); the two rules each fire
|
||||
once, at the keyword, and a *different* rule sees a violation written
|
||||
inside the block (proof the items survive); the size pins in
|
||||
`ast::size_pins` unchanged (the variant is boxed).
|
||||
|
||||
### 36.2 A half-typed `#(` override whose value could read as a call (topo §2.9-24)
|
||||
|
||||
Source (the QA finding in the header-recovery README, verbatim):
|
||||
```
|
||||
module m;
|
||||
sub #(.WIDTH(8), .DEPTH(
|
||||
u0 (.a(x), .b(y));
|
||||
endmodule
|
||||
```
|
||||
The value of `.DEPTH(` is parsed greedily; `u0 (.a(x), .b(y))` is a legal
|
||||
call with named arguments, so no error fires inside the list and the whole
|
||||
instantiation collapses to an item-level `Error`. Wanted: the element
|
||||
`.DEPTH(` is an error element, `.WIDTH(8)` survives, `u0` is an instance
|
||||
with two connections, one diagnostic.
|
||||
|
||||
- One lookahead in `parse_connection`, tolerant mode only, before the value
|
||||
is parsed (`parse_expr_or_type`): `fn value_runs_into_next_instance(&self)
|
||||
-> bool`. Walk tokens from the cursor with a bracket depth starting at 0.
|
||||
A closer that would take the depth below 0 is the value's own `)`: return
|
||||
`false` — the value closes and is parsed normally. At depth 0, an
|
||||
identifier that is the first token of its line and whose next token is
|
||||
`(` is *remembered* as the candidate next instance. A `;` at depth 0, a
|
||||
sync keyword (`endmodule`, `endinterface`, … — reuse the predicate
|
||||
`at_sync_stop` is built on) or EOF ends the walk: return whether a
|
||||
candidate was seen. That is: the value's `(` is never closed **and**
|
||||
something that looks like the next instance sits inside it. On a valid
|
||||
file the walk ends at the value's `)` after a handful of tokens, so cost
|
||||
is nothing; only an unclosed value walks to the next `;`.
|
||||
- When it returns `true`, fail the element with an error whose span is the
|
||||
unclosed `(` (`paren_start`), message "unclosed `(` in a port or parameter
|
||||
connection". `element_or_recover` turns it into the error element and the
|
||||
existing skip (bracket-seeded, stops at the first token of a new line)
|
||||
must leave the cursor on `u0`; `list_ends` then ends the override list
|
||||
(recovered, no comma), `close_list` forgives the missing `)`, and the
|
||||
instance loop reads `u0`. Verify that tree exactly; if the skip lands
|
||||
elsewhere, fix the skip's start, not the lookahead.
|
||||
- The same helper covers the connection list: `sub u0 (.a(` ⏎ `u1 (.b(y));`
|
||||
costs one connection and keeps `u1` as a second instance.
|
||||
- The ambiguous shape stays ambiguous: with the parens balancing
|
||||
(`.D(` ⏎ `u0 (.a(x)));`) the value closes, the walk returns `false`, the
|
||||
greedy parse wins — pin that as a test so nobody "fixes" it later.
|
||||
- Tests: the README shape above (params `[Ok, Error]`, one instance, two
|
||||
connections, one diagnostic at the `(`, `endmodule` consumed); the
|
||||
connection-list twin; the balanced-parens control; a legal multi-line
|
||||
value `.DEPTH(` ⏎ `f(1)` ⏎ `)` parses identically in strict and tolerant
|
||||
mode (the parity test `tolerant_parse_equals_strict_parse_on_valid_sources`
|
||||
plus a direct case); the header-recovery README's finding gets a work-log
|
||||
line pointing here.
|
||||
|
||||
### 36.3 Atomic in-place writes (§1 backlog item, QA find of 2026-08-25)
|
||||
|
||||
`process_file` (`lucisv/src/main.rs`) and `--fix` (`lucisv/src/lint.rs`)
|
||||
write with `fs::write`, which truncates then writes; `cache.rs` already does
|
||||
tempfile + rename by hand. One shared helper, three users.
|
||||
|
||||
- `crates/lucisv_core/src/atomic.rs`: `pub fn write_atomic(path: &Path,
|
||||
bytes: &[u8]) -> io::Result<()>`. Resolve symlinks first
|
||||
(`fs::canonicalize` when the path exists — `fs::write` writes *through* a
|
||||
symlink and a rename onto the link would replace it with a file; the
|
||||
canonical target is what gets replaced). Temp file in the target's
|
||||
directory, `.{file_name}.{pid}.lucisv-tmp`; write; copy the target's
|
||||
permissions onto it when the target exists (`set_permissions`, so a
|
||||
0600 or 0755 file stays that way); `rename` onto the target; on any
|
||||
failure after the temp exists, remove it and return the error. No new
|
||||
dependency.
|
||||
- `cache.rs` uses the helper instead of its inline copy (behaviour
|
||||
identical; its `no_temporary_file_is_left_behind` test keeps passing).
|
||||
`main.rs:309` and `lint.rs:315` call it.
|
||||
- Tests in `atomic.rs`: bytes land; no temp file left in the directory
|
||||
after success; after a failed rename (target path is a directory) no
|
||||
temp file is left and `Err` comes back; permissions preserved
|
||||
(`#[cfg(unix)]`); writing through a symlink replaces the *target* and the
|
||||
link still points at it; a new file (no prior target) is created.
|
||||
|
||||
### Gates (dev runs, all guarded)
|
||||
|
||||
`cargo fmt -p` per touched crate; `cargo clippy --all-targets` clean;
|
||||
`tools/guard.sh -- cargo test --workspace`; `tools/guard.sh --
|
||||
tools/corpus_check.sh` still 814/820 with the same six failures; the
|
||||
`tests/error_recovery.rs` truncation and single-character-deletion fuzz
|
||||
tests green (they are the termination guard for 36.1/36.2). Lead at review:
|
||||
byte-identity of every corpus file against the cached 0.39.0 binary,
|
||||
opentitan read-only sweep, vsix smoke, 0.40.0.
|
||||
|
||||
- [x] 36.1 `ItemKind::GenBlock`, the `begin` arm, consumers, the two rules
|
||||
- [x] 36.2 the lookahead, the four tests
|
||||
- [x] 36.3 `write_atomic`, three users, tests
|
||||
- [x] docs: feature README, rule rows, header-recovery work-log line
|
||||
- [x] Gates (guarded)
|
||||
- [x] QA: every shape above typed against the tolerant parser and the two
|
||||
rules; the ambiguous control; strict/tolerant parity re-run; the
|
||||
truncation fuzzers re-run; atomic writes attacked (symlink, mode,
|
||||
directory target, concurrent writers on one inode) — REWORK (small):
|
||||
`mismatched-labels` had no arm for the block; fixed by the lead at
|
||||
review with a test, plus the LOW doc comment and a read-only-target
|
||||
refusal in `write_atomic` (parity with the old `fs::write`)
|
||||
|
||||
## 37. Server residue from §10 (planned 2026-09-04) — lazy codeAction resolve, the inlayHint zero, `locate` onto `DeclPositions`
|
||||
|
||||
One lane in the main tree, dev Opus 5 then QA Sonnet 5, same protocol as
|
||||
§36 (lead snapshots the diff before QA; QA never runs a git command that
|
||||
rewrites the tree). Feature README: `docs/features/lazy-code-action/README.md`
|
||||
(one README for the three, sections per item). Ships as 0.41.0.
|
||||
|
||||
**Expected touch set:** `crates/lucisv_server/src/{ports.rs,code_action.rs,
|
||||
locate.rs,nav.rs,symbols.rs,inlay.rs,main.rs,state.rs,perf.rs}`,
|
||||
`crates/lucisv_server/src/server/{dispatch.rs,mod.rs}`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, `crates/vlog_refactor/src/ports/mod.rs`
|
||||
(only if the offer needs a new one-file question), the §10 lines this closes
|
||||
(1236–1249 and 1293), `docs/features/server-lint/README.md`'s resolve note,
|
||||
this section. Anything else is named in the work log.
|
||||
|
||||
### 37.1 `codeAction/resolve` for the port refactorings (§10, owner-approved)
|
||||
|
||||
`ports::code_actions` costs ~1.4 ms per instantiating file plus a 13 ms
|
||||
floor on every cursor move (`docs/performance_take2.md` §6a: 185 ms at a
|
||||
128-file fan-out, to offer zero actions), because the *offer* already
|
||||
computes the full edit over `Workspace::module_sources` — the module's
|
||||
fan-out **plus every open buffer**, each read as text. The quick fixes in
|
||||
`code_action.rs` are cheap and stay eager; only the port actions change.
|
||||
|
||||
- **The offer is local.** Whether an action exists at the cursor is a
|
||||
one-file question plus, for a cursor on an instantiation, the instantiated
|
||||
module's own declaration (`vlog_refactor::module_definition` through the
|
||||
index — one file, the way `inlay.rs`'s `Plans::read` does it). Run the
|
||||
engine's `port_actions` over exactly those sources to learn which actions
|
||||
exist; throw the edits away. No fan-out is read. The title's count
|
||||
("updates N instantiations") comes from the index
|
||||
(`instantiations_of(name)` — say in the doc whether that is instances or
|
||||
files, and word the title to match); the unsaved-buffer case in
|
||||
`an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen`
|
||||
is answered by the *resolved* edit, which is still exact — move that pin
|
||||
to resolve.
|
||||
- **Resolve computes the edit.** Each offered action carries `data`
|
||||
(`{uri, position, title}`) and no `edit`. `codeAction/resolve` re-runs
|
||||
today's eager path at that position and returns the action whose title
|
||||
matches, with its `edit`. No match (the buffer changed under the
|
||||
lightbulb) is an error response, `"the action is no longer available"`,
|
||||
not a silent empty edit. Advertise `resolve_provider: Some(true)`.
|
||||
- **A client that cannot resolve gets today's answer.** Read
|
||||
`textDocument.codeAction.resolveSupport.properties` at `initialize`; only
|
||||
when it lists `"edit"` is the offer lazy. Keep the flag in the server
|
||||
state beside whatever `main.rs` already reads from the client
|
||||
capabilities (the range-formatting registration is the precedent).
|
||||
- Tests: the lazy offer's titles and kinds equal the eager offer's, over
|
||||
the `crowded` tree; the resolved `WorkspaceEdit` is byte-equal to the
|
||||
eager one (both cursor shapes: a port declaration, an instantiation with
|
||||
missing connections); the no-resolveSupport client gets the eager shape;
|
||||
a resolve after the document changed errors; the offer over
|
||||
`crowded(40)` reads none of the noise files and none of the fan-out
|
||||
(pin it the way `the_files_a_code_action_reads_are_the_modules_own_fan_out`
|
||||
pins the eager path — through what the offer asks the workspace for);
|
||||
an e2e case over the wire (`tests/e2e.rs`): initialize with
|
||||
resolveSupport → `codeAction` returns `data` and no `edit` →
|
||||
`codeAction/resolve` returns the edit; initialize without → the edit is
|
||||
inline. `perf.rs`'s `a_code_action_at_an_instantiation_before_and_after`
|
||||
gains an "offer" column; report the three numbers in the work log.
|
||||
|
||||
### 37.2 `inlayHint` returns 0 at the default scope where workspace scope returns 4 (§10 / take-2 §8)
|
||||
|
||||
Investigate before fixing: `Plans::read` asks `module_definition` of the
|
||||
index, and at folder or default scope the instantiated module's file may
|
||||
not be in the index even though §4b says the default scope now answers
|
||||
cross-file questions (the `didOpen` widen). Find which lookup the
|
||||
neighbours (hover, signature help, completion) use that inlay does not,
|
||||
and make inlay use it. Deliverable is one of: a fix with a test at the
|
||||
default scope (a `sub.sv` outside the opened folder, `top.sv` inside it,
|
||||
hints appear after the widen), or — if the zero is correct — a paragraph
|
||||
in the README saying exactly why, for the lead to rule on. Not a gate.
|
||||
|
||||
### 37.3 `locate::location` onto `DeclPositions` (§10, filed)
|
||||
|
||||
`Def::lines.positions` (`DeclPositions { name, decl }`, `Some` for every
|
||||
file-scope declaration) already holds the client-side ranges, so
|
||||
`textDocument/definition`, references, the lens and both hierarchies need
|
||||
not read a file to convert an indexed span. Add the index-only path in
|
||||
`locate.rs` for a `Def` whose positions are recorded (members keep the
|
||||
file-read path — they have none) and route `nav.rs`/`symbols.rs`'s
|
||||
file-scope answers through it. Pins: the index-only `Location` equals the
|
||||
file-read one over files with multi-byte and astral characters (UTF-16
|
||||
surrogates), CRLF and a BOM; a file-scope definition answers without a
|
||||
`file_view` being created (assert through whatever the view cache exposes,
|
||||
or add a test-only counter — say which); a definition request over an
|
||||
opentitan file timed before/after, read-only, in the work log.
|
||||
|
||||
### Gates (dev, guarded)
|
||||
|
||||
`cargo fmt -p` per touched crate; clippy clean; `tools/guard.sh -- cargo
|
||||
test --workspace`; `tools/guard.sh -- tools/corpus_check.sh` unchanged
|
||||
(814/820, same six); the e2e suite green; vsix smoke. Lead at review:
|
||||
byte-identity vs 0.40.0, opentitan read-only sweep, 0.41.0.
|
||||
|
||||
- [x] 37.1 lazy offer + resolve + capability gate + e2e + perf column
|
||||
- [x] 37.2 inlayHint: fix with test, or the written finding — the written
|
||||
finding (the zero is correct), plus two default-scope tests
|
||||
- [x] 37.3 `locate` index-only path + pins + timing
|
||||
- [x] docs: feature README; §10 lines ticked; server-lint note
|
||||
- [x] Gates (guarded)
|
||||
- [x] QA: resolve attacked (stale document, wrong data, missing data,
|
||||
client without resolveSupport, both cursor shapes, unsaved buffer);
|
||||
inlay at the default scope against a real two-folder tree; locate
|
||||
equality over the encoding shapes; opentitan timing re-derived —
|
||||
PASS, no findings above LOW; offer ~4.5 ms vs eager ~77 ms over the
|
||||
wire at the 128-file fan-out
|
||||
@@ -9,6 +9,7 @@ use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::config::FileConfig;
|
||||
use rayon::prelude::*;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
@@ -312,7 +313,7 @@ fn check_one(
|
||||
};
|
||||
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
|
||||
if let Some(text) = rewritten {
|
||||
if let Err(e) = std::fs::write(file, &text) {
|
||||
if let Err(e) = write_atomic(file, text.as_bytes()) {
|
||||
return failed(format!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ use std::process::ExitCode;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use args::{Command, Options};
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::cache::{content_hash, Cache, Entry};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use lucisv_core::filelist;
|
||||
@@ -306,7 +307,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
|
||||
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
|
||||
} else if opts.check {
|
||||
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
|
||||
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
|
||||
} else {
|
||||
// The bytes now on disk are formatted, so they are what the cache
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Replacing a file's contents without ever leaving it half written.
|
||||
//!
|
||||
//! `fs::write` truncates the target and then writes into it, so a crash, a
|
||||
//! full disk or a `^C` between the two leaves the user's source truncated —
|
||||
//! and lucisv's first invariant is that it never corrupts code. Every
|
||||
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
|
||||
//! gets the bytes, and a `rename` over the target publishes them in one step
|
||||
//! that either happened or did not.
|
||||
//!
|
||||
//! See `docs/features/small-items-3/README.md`.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Writes `bytes` to `path`, replacing whatever was there in one step.
|
||||
///
|
||||
/// A temp file beside the target takes the bytes, inherits the target's
|
||||
/// permissions when there is a target, and is renamed onto it — `rename` is
|
||||
/// atomic within a directory on every platform lucisv ships to, so a reader
|
||||
/// sees either the old file or the new one and never a truncated one. A
|
||||
/// failure anywhere after the temp exists removes it before returning.
|
||||
///
|
||||
/// A symlinked target is resolved first: `fs::write` writes *through* a
|
||||
/// symlink, so replacing the link itself would silently redirect it at a new
|
||||
/// file and leave the real one stale. The canonical path is what gets
|
||||
/// replaced, which is also what makes the temp land on the target's own
|
||||
/// filesystem — `rename` cannot cross one.
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
// A rename replaces a file whatever its mode, so a read-only target would
|
||||
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
|
||||
// a file someone made read-only is asking not to be rewritten in place.
|
||||
if fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("{} is read-only", path.display()),
|
||||
));
|
||||
}
|
||||
let tmp = temp_path(&target)?;
|
||||
if let Err(e) = fs::write(&tmp, bytes) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
// A file someone made read-only, or executable, keeps its mode: the temp
|
||||
// was created with the process umask, not with the target's bits. No
|
||||
// target means a new file, which takes the umask as `fs::write` would.
|
||||
if let Ok(meta) = fs::metadata(&target) {
|
||||
let _ = fs::set_permissions(&tmp, meta.permissions());
|
||||
}
|
||||
if let Err(e) = fs::rename(&tmp, &target) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The temp file's path: hidden, in the target's own directory, and stamped
|
||||
/// with the process id so two lucisv runs over one tree cannot collide.
|
||||
fn temp_path(target: &Path) -> io::Result<PathBuf> {
|
||||
let dir = target.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = target
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
|
||||
let mut tmp = std::ffi::OsString::from(".");
|
||||
tmp.push(name);
|
||||
tmp.push(format!(".{}.lucisv-tmp", std::process::id()));
|
||||
Ok(dir.join(tmp))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A directory that removes itself, the way `cache.rs`'s own tests have
|
||||
/// one — no dependency, and no leftovers under `target/`.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"lucisv-atomic-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
fn file(&self, name: &str) -> PathBuf {
|
||||
self.path.join(name)
|
||||
}
|
||||
|
||||
/// Every name in the directory, so a test can say what is *not* there.
|
||||
fn names(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = fs::read_dir(&self.path)
|
||||
.expect("read dir")
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bytes_land_and_no_temp_file_is_left_behind() {
|
||||
let dir = TempDir::new("plain");
|
||||
let file = dir.file("a.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_exist_yet_is_created() {
|
||||
let dir = TempDir::new("create");
|
||||
let file = dir.file("new.sv");
|
||||
write_atomic(&file, b"hello\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
|
||||
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
|
||||
// A directory standing where the file should be: the write succeeds,
|
||||
// the rename cannot.
|
||||
let dir = TempDir::new("dirtarget");
|
||||
let target = dir.file("occupied");
|
||||
fs::create_dir(&target).expect("create dir");
|
||||
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
|
||||
assert!(err.to_string().len() > 1, "{err}");
|
||||
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_the_same_path_twice_leaves_one_file() {
|
||||
let dir = TempDir::new("twice");
|
||||
let file = dir.file("a.sv");
|
||||
write_atomic(&file, b"one\n").expect("write");
|
||||
write_atomic(&file, b"two\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_targets_permissions_are_preserved() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("modes");
|
||||
for mode in [0o600, 0o755] {
|
||||
let file = dir.file(&format!("m{mode:o}.sv"));
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
|
||||
assert_eq!(got, mode, "mode {mode:o} was not preserved");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_read_only_target_is_refused_and_left_alone() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("readonly");
|
||||
let file = dir.file("ro.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
|
||||
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
|
||||
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
|
||||
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
|
||||
let dir = TempDir::new("symlink");
|
||||
let real = dir.file("real.sv");
|
||||
let link = dir.file("link.sv");
|
||||
fs::write(&real, "old\n").expect("seed");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
||||
write_atomic(&link, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
|
||||
assert!(
|
||||
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
|
||||
"the link is still a link"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
|
||||
}
|
||||
}
|
||||
@@ -87,10 +87,7 @@ impl Cache {
|
||||
if !ignore.exists() {
|
||||
let _ = std::fs::write(&ignore, "*\n");
|
||||
}
|
||||
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
|
||||
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
|
||||
}
|
||||
|
||||
/// The file's text: one line per entry, sorted by path so that two
|
||||
@@ -397,7 +394,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.ends_with(".tmp"))
|
||||
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "{leftovers:?}");
|
||||
}
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
|
||||
//! `cache` answers the third question of the same family — whether a file
|
||||
//! needs to be processed at all, and `filelist` answers the first one the way
|
||||
//! an EDA project already does, from a `.f` file. See
|
||||
//! 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
|
||||
//! `docs/features/lucisv-core-lift/README.md`, and
|
||||
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
|
||||
//! for the rules themselves.
|
||||
|
||||
pub mod atomic;
|
||||
pub mod cache;
|
||||
pub mod config;
|
||||
pub mod filelist;
|
||||
|
||||
@@ -755,6 +755,92 @@ endmodule
|
||||
assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the default scope (TODO §37.2 / `performance_take2.md` §4b, §8)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// An opentitan-shaped tree: an IP block with its RTL and its testbench,
|
||||
/// and a shared library folder outside that block. Opening
|
||||
/// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to
|
||||
/// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is
|
||||
/// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against
|
||||
/// `hw/dv/sv/common_ifs/pins_if.sv`.
|
||||
fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) {
|
||||
const TB: &str =
|
||||
"module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n";
|
||||
let tree = Tree::new(name);
|
||||
fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs");
|
||||
fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs");
|
||||
fs::create_dir_all(tree.path.join("dv/common")).expect("dirs");
|
||||
tree.write("ip/aes/rtl/sub.sv", SUB);
|
||||
tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n");
|
||||
let tb = tree.write("ip/aes/dv/tb/tb.sv", TB);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
// The shipped default: no `index.scope`, `scopeDepth` 2.
|
||||
ws.set_client_settings(crate::settings::ClientSettings::default());
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&tb).expect("uri");
|
||||
ws.set_document(uri.clone(), TB.to_string());
|
||||
ws.rebuild_index();
|
||||
(tree, ws, uri, TB)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_scope_hints_a_module_the_didopen_widen_reached() {
|
||||
// `performance_take2.md` §4b measured 0 hints at the default scope
|
||||
// where the workspace scope gives 4, and §8 filed it as a correctness
|
||||
// gap. It is not one: the hints that scope answers are exactly the
|
||||
// instantiations whose module the widen reached.
|
||||
let (tree, ws, uri, _) = default_scoped("default_scope");
|
||||
assert!(
|
||||
ws.index().files().iter().any(|f| f.ends_with("sub.sv")),
|
||||
"the widen reached the block's own RTL: {:?}",
|
||||
ws.index().files()
|
||||
);
|
||||
assert!(
|
||||
!ws.index().files().iter().any(|f| f.ends_with("far.sv")),
|
||||
"and not the library folder beside it"
|
||||
);
|
||||
|
||||
let hints = inlay_hints(&ws, &uri, everything());
|
||||
let labels: Vec<String> = hints
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let InlayHintLabel::String(s) = h.label else { panic!("string") };
|
||||
s
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted");
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() {
|
||||
// The other half of the same finding: the `far` instantiation gets no
|
||||
// hints — and go-to-definition and hover give nothing for it either.
|
||||
// The zero is the scope's, not this module's; inlay uses the same
|
||||
// `module_definition` lookup its neighbours do.
|
||||
let (tree, ws, uri, tb) = default_scoped("out_of_scope");
|
||||
let hints = inlay_hints(&ws, &uri, everything());
|
||||
assert!(
|
||||
hints.iter().all(|hint| hint.position.line != 2),
|
||||
"nothing on the `far` line: {hints:#?}"
|
||||
);
|
||||
|
||||
let far = tb.find("far u_far").expect("the instantiation") as u32;
|
||||
assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer");
|
||||
assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover");
|
||||
|
||||
// And the moment the scope reaches it, all three answer.
|
||||
let mut wide = Workspace::default();
|
||||
wide.open_whole_workspace(vec![tree.path.clone()]);
|
||||
wide.set_document(uri.clone(), tb.to_string());
|
||||
let hints = inlay_hints(&wide, &uri, everything());
|
||||
assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}");
|
||||
assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1);
|
||||
}
|
||||
|
||||
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
|
||||
/// timing assertions in a shared CI runner are flaky by nature. Run with
|
||||
/// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`.
|
||||
|
||||
@@ -575,6 +575,7 @@ mod tests {
|
||||
use crate::uri::path_to_uri;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
/// A one-file workspace with `path` open and the cursor at `needle`'s end.
|
||||
/// No files on disk: nothing here reads the index.
|
||||
@@ -1081,10 +1082,31 @@ endmodule
|
||||
// A trailing newline, so this test isolates depth from the separate
|
||||
// true-end-of-file `Eof`-adjacency case pinned above.
|
||||
text.push_str("initial begin\n");
|
||||
let (ws, uri, position) = asking(&text, "initial begin");
|
||||
assert!(!ws.document(&uri).expect("open").tokens.is_empty(), "the lexer never recurses");
|
||||
let items = inline_completions(&ws, &uri, position);
|
||||
assert!(items.is_some(), "the innermost, truly unclosed `begin` still offers its `end`");
|
||||
// Opening the document *parses* it, and since §36.1 a bare `begin` at
|
||||
// item scope is a generate block the tolerant parser descends into —
|
||||
// so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4
|
||||
// MiB of stack in a debug build. That is exactly what
|
||||
// `PARSE_STACK_SIZE` is for; every production thread that may reach a
|
||||
// parse is given it (`main.rs`), libtest's own thread is not, so the
|
||||
// body runs on one of its own. Nothing here is about the inline path,
|
||||
// which still never recurses.
|
||||
std::thread::Builder::new()
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || {
|
||||
let (ws, uri, position) = asking(&text, "initial begin");
|
||||
assert!(
|
||||
!ws.document(&uri).expect("open").tokens.is_empty(),
|
||||
"the lexer never recurses"
|
||||
);
|
||||
let items = inline_completions(&ws, &uri, position);
|
||||
assert!(
|
||||
items.is_some(),
|
||||
"the innermost, truly unclosed `begin` still offers its `end`"
|
||||
);
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("the inline path crashed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -144,6 +144,7 @@ fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
|
||||
ItemKind::Task(t) => task_pairs(t, out),
|
||||
ItemKind::Clocking(c) => clocking_pairs(c, out),
|
||||
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
|
||||
ItemKind::GenBlock(b) => items_pairs(&b.items, out),
|
||||
ItemKind::GenIf(g) => gen_if_pairs(g, out),
|
||||
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -7,11 +7,18 @@
|
||||
//! buffer's own line index when there is one, and otherwise through
|
||||
//! `Workspace::file_view`, which reads a closed file at most once per
|
||||
//! generation of it rather than once per question about it.
|
||||
//!
|
||||
//! One span never needs that read at all: a **file-scope declaration**'s own
|
||||
//! name, whose client-side range the index recorded when the file was scanned
|
||||
//! ([`vlog_semantic::DeclPositions`]). [`definition_location`] is that path,
|
||||
//! and it is what `textDocument/definition` and `workspace/symbol` answer
|
||||
//! from — see `docs/features/lazy-code-action/README.md`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Location;
|
||||
use lsp_types::{Location, Position, Range};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Def, Utf16Range};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
@@ -27,6 +34,40 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location
|
||||
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
|
||||
}
|
||||
|
||||
/// Where an **indexed** declaration is written — its name's own range.
|
||||
///
|
||||
/// The index converted that range to client positions while it was scanning
|
||||
/// the file ([`vlog_semantic::DeclLines::positions`]), so pointing an editor
|
||||
/// at a module nobody has open is a map lookup rather than a file read: the
|
||||
/// same eight numbers, computed once at index time instead of once per
|
||||
/// question. Only **file-scope** declarations carry them; a member (a port, a
|
||||
/// parameter, a class field) records none and falls through to
|
||||
/// [`location`]'s read, which is the whole reason this is a separate function
|
||||
/// rather than a change inside that one.
|
||||
///
|
||||
/// **An open buffer keeps the read.** Its text may have moved since it was
|
||||
/// indexed, and every other answer about that buffer is computed against the
|
||||
/// text it holds now; answering this one from the index instead would make
|
||||
/// go-to-definition disagree with the document symbols beside it.
|
||||
pub fn definition_location(ws: &Workspace, path: &Path, def: &Def) -> Option<Location> {
|
||||
if ws.document_for_path(path).is_none() {
|
||||
if let Some(recorded) = def.lines.positions {
|
||||
return Some(Location { uri: path_to_uri(path)?, range: range(recorded.name) });
|
||||
}
|
||||
}
|
||||
location(ws, path, def.name_span)
|
||||
}
|
||||
|
||||
/// An index-recorded range as the protocol's own — the same four numbers,
|
||||
/// both already counted in UTF-16 code units by the file's own
|
||||
/// `LineIndex::utf16_position`, which is the converter `Positions` uses too.
|
||||
fn range(recorded: Utf16Range) -> Range {
|
||||
Range {
|
||||
start: Position { line: recorded.start.line, character: recorded.start.character },
|
||||
end: Position { line: recorded.end.line, character: recorded.end.character },
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
///
|
||||
@@ -49,3 +90,197 @@ pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
pub fn display_name(path: &Path) -> String {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_locate_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
/// Write a file as **bytes**, so a test can put a BOM or CRLF in one.
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text.as_bytes()).expect("write");
|
||||
path
|
||||
}
|
||||
|
||||
/// An indexed workspace over everything written so far.
|
||||
fn indexed(&self) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![self.path.clone()]);
|
||||
ws
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The one declaration of `name` in the index, and the file it is in.
|
||||
fn only_def<'w>(ws: &'w Workspace, name: &str) -> (&'w Def, &'w Path) {
|
||||
let index = ws.index();
|
||||
let [def] = index.units(name) else { panic!("exactly one `{name}`") };
|
||||
(def, index.path(def.file).expect("a path"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_scope_definition_is_located_without_reading_its_file() {
|
||||
let tree = Tree::new("no_read");
|
||||
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
|
||||
let ws = tree.indexed();
|
||||
let (def, path) = only_def(&ws, "sub");
|
||||
|
||||
let indexed = definition_location(&ws, path, def).expect("a location");
|
||||
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
|
||||
|
||||
// Only now, so the comparison cannot be what filled the cache.
|
||||
let read = location(&ws, path, def.name_span).expect("a location");
|
||||
assert_eq!(indexed, read);
|
||||
assert_eq!(ws.held_views().len(), 1, "the file-read path really does read one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom() {
|
||||
// Everything that has ever made a UTF-16 conversion disagree, in one
|
||||
// file: a BOM at offset 0, CRLF line endings, a two-byte character, a
|
||||
// three-byte one, and an astral character that is *two* UTF-16 code
|
||||
// units on its own.
|
||||
let tree = Tree::new("encodings");
|
||||
tree.write(
|
||||
"wide.sv",
|
||||
"\u{feff}// é ✓ 𝛼𝛽 — a comment\r\n\
|
||||
// 𝟘𝟙𝟚 more\r\n\
|
||||
module wide (\r\n input logic clk\r\n);\r\nendmodule\r\n",
|
||||
);
|
||||
let ws = tree.indexed();
|
||||
let (def, path) = only_def(&ws, "wide");
|
||||
|
||||
let indexed = definition_location(&ws, path, def).expect("a location");
|
||||
assert!(ws.held_views().is_empty(), "still no read");
|
||||
let read = location(&ws, path, def.name_span).expect("a location");
|
||||
assert_eq!(indexed, read, "the index-only range must be the file-read one");
|
||||
// And it really is the name, not the line: `module ` is seven UTF-16
|
||||
// units into line 2 (0-based), whatever the lines above it hold.
|
||||
assert_eq!(indexed.range.start.line, 2);
|
||||
assert_eq!(indexed.range.start.character, 7);
|
||||
assert_eq!(indexed.range.end.character, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_still_answers_from_the_buffer() {
|
||||
// The index saw the file on disk; the buffer has since gained a line
|
||||
// above the declaration, and has not been re-indexed. An indexed span
|
||||
// is stale either way — the byte offset is the disk file's — and what
|
||||
// this pins is that the *conversion* is unchanged by this round: the
|
||||
// buffer's own line index, exactly as before, so go-to-definition and
|
||||
// the document symbols beside it still agree with each other.
|
||||
let tree = Tree::new("open_buffer");
|
||||
let path = tree.write("sub.sv", "module sub;\nendmodule\n");
|
||||
let mut ws = tree.indexed();
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "// typed since\nmodule sub;\nendmodule\n".to_string());
|
||||
|
||||
let (def, path) = only_def(&ws, "sub");
|
||||
let located = definition_location(&ws, path, def).expect("a location");
|
||||
assert_eq!(
|
||||
located,
|
||||
location(&ws, path, def.name_span).expect("a location"),
|
||||
"an open buffer takes the file-read path, index positions or not"
|
||||
);
|
||||
assert_eq!(located.range.start.line, 0, "byte 7 of the buffer, not of the index's file");
|
||||
assert!(ws.held_views().is_empty(), "an open buffer is never viewed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_keeps_the_file_read_path() {
|
||||
// Members carry no `DeclPositions` — see `DeclLines` — so the fallback
|
||||
// is not decoration: it is the only answer for a port.
|
||||
let tree = Tree::new("member");
|
||||
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
|
||||
let ws = tree.indexed();
|
||||
let index = ws.index();
|
||||
let [port] = index.member("sub", "clk") else { panic!("one `clk`") };
|
||||
assert!(port.lines.positions.is_none(), "a member records no client positions");
|
||||
let path = index.path(port.file).expect("a path");
|
||||
assert_eq!(
|
||||
definition_location(&ws, path, port),
|
||||
location(&ws, path, port.name_span),
|
||||
"and the fallback answers exactly what it always did"
|
||||
);
|
||||
assert_eq!(ws.held_views().len(), 1, "which cost the read");
|
||||
}
|
||||
|
||||
/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server --bin lucisv-server locate::tests::defining -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"]
|
||||
fn defining_over_a_real_project() {
|
||||
// TODO §37.3's own number, beside the code it measures rather than in
|
||||
// `perf.rs` — the precedent `perf::mean`'s `pub(crate)` exists for.
|
||||
// Two columns over the same corpus and the same targets: converting an
|
||||
// indexed span by reading its file, and reading it off the index.
|
||||
// **Read-only** — the corpus is opened, never written.
|
||||
let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else {
|
||||
eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
ws.open_whole_workspace(vec![PathBuf::from(&root)]);
|
||||
let scan = started.elapsed();
|
||||
|
||||
// The targets: modules the corpus instantiates somewhere, whose single
|
||||
// declaration the index can name — what an F12 on an instantiation
|
||||
// lands on, and each in a different file.
|
||||
let names: Vec<String> =
|
||||
ws.index().instantiations().map(|(name, _)| name.to_string()).collect();
|
||||
let targets: Vec<(PathBuf, vlog_semantic::Def)> = names
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
let path = vlog_refactor::module_definition(ws.index(), name).ok()?;
|
||||
let [def] = ws.index().units(name) else { return None };
|
||||
def.lines.positions.is_some().then(|| (path.to_path_buf(), def.clone()))
|
||||
})
|
||||
.take(200)
|
||||
.collect();
|
||||
|
||||
let indexed = crate::perf::mean(5, || {
|
||||
for (path, def) in &targets {
|
||||
std::hint::black_box(definition_location(&ws, path, def));
|
||||
}
|
||||
});
|
||||
let read = crate::perf::mean(5, || {
|
||||
for (path, def) in &targets {
|
||||
std::hint::black_box(location(&ws, path, def.name_span));
|
||||
}
|
||||
});
|
||||
let each = targets.len().max(1) as u32;
|
||||
eprintln!(
|
||||
"definition over {} indexed files of {root} (scan {scan:?}), {} targets:\n \
|
||||
index-only {indexed:?}, file-read {read:?} — {:?} vs {:?} per definition",
|
||||
ws.index().files().len(),
|
||||
targets.len(),
|
||||
indexed / each,
|
||||
read / each,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
hierarchy_view,
|
||||
code_action_resolve: code_action_resolve_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
@@ -261,8 +262,13 @@ fn capabilities() -> ServerCapabilities {
|
||||
CodeActionKind::new(ports::REFACTOR_PORTS),
|
||||
]),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
// Every action is returned complete; there is nothing to resolve.
|
||||
resolve_provider: None,
|
||||
// The quick fixes are complete when they are offered; the port
|
||||
// refactorings are not, for a client that can ask
|
||||
// (`docs/features/lazy-code-action/README.md`). Advertised
|
||||
// unconditionally because the server can always answer a resolve
|
||||
// — including for an action that already carries its edit, which
|
||||
// it hands straight back.
|
||||
resolve_provider: Some(true),
|
||||
})),
|
||||
// The port refactorings. `lucisv.addPort` needs a declaration typed by
|
||||
// the user, which no code action can carry, and a Vim user has no
|
||||
@@ -499,6 +505,24 @@ fn snippet_support(params: &InitializeParams) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client can fetch a code action's `edit` after the fact —
|
||||
/// `textDocument.codeAction.resolveSupport.properties` listing `"edit"`.
|
||||
///
|
||||
/// The property list is the capability: a client that can resolve `title`
|
||||
/// alone cannot be offered an action without its edit, so nothing short of
|
||||
/// `"edit"` counts. A client that says nothing gets every action complete, as
|
||||
/// every client did before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
fn code_action_resolve_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.text_document
|
||||
.as_ref()
|
||||
.and_then(|text_document| text_document.code_action.as_ref())
|
||||
.and_then(|code_action| code_action.resolve_support.as_ref())
|
||||
.is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit"))
|
||||
}
|
||||
|
||||
/// Whether the client applies a `workspace/applyEdit` request.
|
||||
///
|
||||
/// A client that did not say so gets a command's edit back as the request
|
||||
@@ -1148,6 +1172,46 @@ mod tests {
|
||||
assert!(kinds.contains(&CodeActionKind::QUICKFIX));
|
||||
assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL)));
|
||||
assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS)));
|
||||
assert_eq!(
|
||||
options.resolve_provider,
|
||||
Some(true),
|
||||
"the port refactorings are offered without their edits to a client that can ask"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, CodeActionCapabilityResolveSupport, CodeActionClientCapabilities,
|
||||
TextDocumentClientCapabilities,
|
||||
};
|
||||
assert!(
|
||||
!code_action_resolve_support(&InitializeParams::default()),
|
||||
"silence means the whole edit up front"
|
||||
);
|
||||
|
||||
let saying = |properties: &[&str]| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
text_document: Some(TextDocumentClientCapabilities {
|
||||
code_action: Some(CodeActionClientCapabilities {
|
||||
resolve_support: Some(CodeActionCapabilityResolveSupport {
|
||||
properties: properties.iter().map(|p| p.to_string()).collect(),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(code_action_resolve_support(&saying(&["edit"])));
|
||||
assert!(code_action_resolve_support(&saying(&["documentation", "edit"])));
|
||||
assert!(
|
||||
!code_action_resolve_support(&saying(&["documentation"])),
|
||||
"resolving anything but the edit is no use to us"
|
||||
);
|
||||
assert!(!code_action_resolve_support(&saying(&[])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,7 +7,7 @@ use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::includes;
|
||||
use crate::locate::location;
|
||||
use crate::locate::{definition_location, location};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
@@ -60,7 +60,9 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
.iter()
|
||||
.filter_map(|def| {
|
||||
let path = ws.index().path(def.file)?;
|
||||
location(ws, path, def.name_span)
|
||||
// A file-scope declaration's range is already in the index, so
|
||||
// the jump costs no read of the file it lands in.
|
||||
definition_location(ws, path, def)
|
||||
})
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
@@ -691,6 +693,36 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_file_definition_reads_no_file() {
|
||||
// The jump above, asked again for what it *costs*: the target module's
|
||||
// range is in the index (`DeclPositions`), so nothing opens `sub.sv`.
|
||||
// Pinned through the view cache, which is where a read would land.
|
||||
let dir = temp_dir("no_read");
|
||||
let sub = dir.join("sub.sv");
|
||||
fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "sub u_sub"));
|
||||
assert_eq!(locations.len(), 1);
|
||||
assert_eq!(locations[0].range.start.character, 7, "and it is still the right answer");
|
||||
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
|
||||
|
||||
// `workspace/symbol` answers the same way, over the same index.
|
||||
let hits = crate::symbols::workspace_symbols(&ws, "sub");
|
||||
assert!(hits.iter().any(|hit| hit.name == "sub"), "{hits:#?}");
|
||||
assert!(ws.held_views().is_empty(), "nor did the symbol search");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ambiguous_workspace_name_returns_every_location() {
|
||||
let dir = temp_dir("ambig");
|
||||
|
||||
@@ -1022,6 +1022,14 @@ fn a_code_action_at_an_instantiation_before_and_after() {
|
||||
let after = mean(20, || {
|
||||
black_box(crate::ports::code_actions(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
// TODO §37.1's column: the *offer* a client that can resolve receives,
|
||||
// which reads the buffer and — at an instantiation — one more file,
|
||||
// whatever the fan-out is. The edit is computed by `resolve`, which is the
|
||||
// `after` column above, once, when the user clicks.
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let offer = mean(20, || {
|
||||
black_box(crate::ports::offers(&ws, &uri, black_box(position), black_box(offset)));
|
||||
});
|
||||
let read = mean(3, || {
|
||||
black_box(ws.sources());
|
||||
});
|
||||
@@ -1035,9 +1043,10 @@ fn a_code_action_at_an_instantiation_before_and_after() {
|
||||
});
|
||||
// A measurement of an answer that was not given is worthless.
|
||||
assert_eq!(crate::ports::code_actions(&ws, &uri, offset).len(), 1);
|
||||
assert_eq!(crate::ports::offers(&ws, &uri, position, offset).len(), 1);
|
||||
eprintln!(
|
||||
"codeAction on a port of a module instantiated in 3 of {} files ({lines} lines each): \
|
||||
whole workspace {before:?}, fan-out {after:?} \
|
||||
whole workspace {before:?}, fan-out {after:?}, offer {offer:?} \
|
||||
(`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})",
|
||||
ws.index().files().len()
|
||||
);
|
||||
|
||||
@@ -12,6 +12,13 @@
|
||||
//! and `lucisv.propagatePorts` take a position and exist for the same reason a
|
||||
//! Vim user has no lightbulb: a command works everywhere a keybinding does.
|
||||
//! See `docs/features/refactor-ports/README.md`.
|
||||
//!
|
||||
//! **Two shapes of code action.** A client that can resolve is *offered*
|
||||
//! actions with no edit ([`offers`]) and asks for the edit when the user picks
|
||||
//! one ([`resolve`]); a client that cannot gets the edit up front
|
||||
//! ([`code_actions`]). The offer reads one or two files whatever the module's
|
||||
//! fan-out is, which is the whole point — see
|
||||
//! `docs/features/lazy-code-action/README.md`.
|
||||
|
||||
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
@@ -22,6 +29,7 @@ use std::path::{Path, PathBuf};
|
||||
use lsp_types::{
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{ModuleRef, RefactorEdit};
|
||||
@@ -48,6 +56,12 @@ pub fn commands() -> Vec<String> {
|
||||
|
||||
/// The port actions available at a position, each carrying its own computed
|
||||
/// edit — nothing to resolve, and nothing offered that would be refused.
|
||||
///
|
||||
/// What a client without `codeAction/resolve` gets, and what [`resolve`]
|
||||
/// re-runs to answer one that has. It reads the module's whole fan-out
|
||||
/// ([`Workspace::module_sources`]), which is ~1.4 ms per instantiating file:
|
||||
/// fine once, when the user has clicked, and not fine on every cursor move,
|
||||
/// which is why [`offers`] exists.
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
@@ -76,6 +90,183 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a lazily-offered action carries in place of its edit: enough to ask
|
||||
/// the same question again when the user picks it.
|
||||
///
|
||||
/// The position rather than the offset, because that is what the client
|
||||
/// speaks and what the buffer it will be re-read against is indexed by.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Offer {
|
||||
uri: Uri,
|
||||
position: Position,
|
||||
title: String,
|
||||
}
|
||||
|
||||
/// The sentence a resolve that finds nothing answers with. Not a silent empty
|
||||
/// edit: an action that has stopped applying is news, and applying nothing
|
||||
/// while saying nothing is how a user comes to distrust the lightbulb.
|
||||
const GONE: &str = "the action is no longer available.";
|
||||
/// A resolve of something this server never offered.
|
||||
const NOT_OURS: &str = "this code action carries no lucisv port refactoring to resolve.";
|
||||
|
||||
/// The port actions available at a position, **without their edits** — the
|
||||
/// offer a client that can `codeAction/resolve` is sent.
|
||||
///
|
||||
/// The question "is there an action here at all" is answered over the buffer
|
||||
/// itself plus, for a cursor on an instantiation, the instantiated module's
|
||||
/// own declaration ([`offer_sources`]) — one or two files, whatever the
|
||||
/// module's fan-out is. The edits those two files produce are thrown away;
|
||||
/// [`resolve`] computes the real one over the whole fan-out when the user
|
||||
/// clicks.
|
||||
///
|
||||
/// **The count in the title comes from the index**, since the fan-out has not
|
||||
/// been read: [`instances_of`] counts every *instance* the index has seen of
|
||||
/// the module, so `sub u1(), u2();` counts two. The eager title counts the
|
||||
/// instances the plan really rewrites, which is the same number except where
|
||||
/// the index cannot know — an unsaved buffer's new instantiation, a
|
||||
/// file-scope instantiation site (which records no edge), an instance
|
||||
/// connecting with `.*`. The two are therefore matched on the part of the
|
||||
/// title *before* that count; see [`key`].
|
||||
pub fn offers(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
offset: u32,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
|
||||
// A name the workspace declares twice is a refusal the engine makes over
|
||||
// the fan-out, where it can see both declarations. The offer cannot, so it
|
||||
// asks the index the same question rather than offering an action that
|
||||
// resolve would then decline.
|
||||
if modules.is_empty() || modules.iter().any(|name| declared_twice(ws, name)) {
|
||||
return Vec::new();
|
||||
}
|
||||
let sources = offer_sources(ws, &path, &doc.text, &modules);
|
||||
vlog_refactor::port_actions(&sources, &path, offset)
|
||||
.into_iter()
|
||||
.map(|action| {
|
||||
let title = counted(ws, action.title, &modules);
|
||||
let data =
|
||||
serde_json::to_value(Offer { uri: uri.clone(), position, title: title.clone() })
|
||||
.ok();
|
||||
CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title,
|
||||
kind: Some(CodeActionKind::new(REFACTOR_PORTS)),
|
||||
data,
|
||||
..Default::default()
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The files an [`offers`] call reads: the buffer the request names, and the
|
||||
/// declaration of every module an instantiation under the cursor names.
|
||||
///
|
||||
/// The second is the same two steps `inlay.rs`'s `Plans::read` takes — the
|
||||
/// index says which file declares the module, and that one file is read —
|
||||
/// and it is what lets the engine answer "this instantiation is missing
|
||||
/// ports" without any file that *instantiates* the module. A cursor on a port
|
||||
/// declaration names its own module, whose declaring file is the buffer
|
||||
/// itself, so that case reads nothing at all.
|
||||
///
|
||||
/// `pub(crate)` for the test that pins exactly this set.
|
||||
pub(crate) fn offer_sources(
|
||||
ws: &Workspace,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
modules: &[String],
|
||||
) -> Vec<(PathBuf, String)> {
|
||||
let mut sources = vec![(path.to_path_buf(), text.to_string())];
|
||||
for name in modules {
|
||||
let Ok(declared_in) = vlog_refactor::module_definition(ws.index(), name) else { continue };
|
||||
if sources.iter().any(|(held, _)| held == declared_in) {
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = ws.text_of(declared_in) {
|
||||
sources.push((declared_in.to_path_buf(), text));
|
||||
}
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
/// The edit for one offered action, computed now that the user has picked it.
|
||||
///
|
||||
/// Today's eager answer at the offer's own position, narrowed to the action
|
||||
/// whose title the client is holding. An action already carrying its edit is
|
||||
/// returned untouched — a client may resolve anything it likes, and the quick
|
||||
/// fixes in `code_action.rs` are complete when they are offered.
|
||||
pub fn resolve(ws: &Workspace, action: CodeAction) -> Result<CodeAction, String> {
|
||||
if action.edit.is_some() {
|
||||
return Ok(action);
|
||||
}
|
||||
let offer: Offer = action
|
||||
.data
|
||||
.clone()
|
||||
.and_then(|data| serde_json::from_value(data).ok())
|
||||
.ok_or_else(|| NOT_OURS.to_string())?;
|
||||
// A `codeAction/resolve` carries a `CodeAction`, not a `textDocument`, so
|
||||
// the large-file fast path's gate (which reads the URI out of the params)
|
||||
// never sees this request. A buffer that has grown past the threshold
|
||||
// since it was offered an action is refused here instead: the fast path's
|
||||
// whole contract is that a large buffer is never parsed, and one stale
|
||||
// lightbulb is not a reason to break it.
|
||||
let doc = ws.document(&offer.uri).filter(|doc| !doc.large).ok_or_else(|| GONE.to_string())?;
|
||||
let offset = doc.positions().offset(offer.position);
|
||||
code_actions(ws, &offer.uri, offset)
|
||||
.into_iter()
|
||||
.find_map(|offered| match offered {
|
||||
CodeActionOrCommand::CodeAction(found) if key(&found.title) == key(&offer.title) => {
|
||||
Some(found)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.map(|mut resolved| {
|
||||
resolved.data = action.data;
|
||||
resolved
|
||||
})
|
||||
.ok_or_else(|| GONE.to_string())
|
||||
}
|
||||
|
||||
/// An action's identity: its title without the count phrase the offer and the
|
||||
/// eager path can honestly disagree about.
|
||||
///
|
||||
/// `"lucisv: remove port `rst` (updates 3 instantiations)"` keys as
|
||||
/// ``"lucisv: remove port `rst`"``; a title with no such suffix
|
||||
/// (`"lucisv: connect 1 missing port"`, whose count is the cursor's own file's
|
||||
/// and therefore exact) keys as itself. An escaped identifier cannot contain a
|
||||
/// space, so `" ("` never occurs inside a port name.
|
||||
fn key(title: &str) -> &str {
|
||||
title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")).map_or(title, |(head, _)| head)
|
||||
}
|
||||
|
||||
/// An offered title with the workspace's own instantiation count in it,
|
||||
/// replacing the one the offer's one or two files could see.
|
||||
fn counted(ws: &Workspace, title: String, modules: &[String]) -> String {
|
||||
let Some(head) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")) else {
|
||||
return title;
|
||||
};
|
||||
let sites = modules.iter().map(|name| instances_of(ws, name)).sum();
|
||||
format!("{} ({})", head.0, vlog_refactor::sites_phrase(sites))
|
||||
}
|
||||
|
||||
/// Every instance of `name` the index has seen. An edge is one written
|
||||
/// statement, so its instances are counted rather than the edges themselves —
|
||||
/// `sub u1 (), u2 ();` is two connection lists to rewrite and the title says
|
||||
/// two.
|
||||
fn instances_of(ws: &Workspace, name: &str) -> usize {
|
||||
ws.index().instantiations_of(name).iter().map(|edge| edge.instances.len()).sum()
|
||||
}
|
||||
|
||||
/// Whether the index holds more than one declaration of `name` a module
|
||||
/// reference could mean — the ambiguity `vlog_refactor::module_definition`
|
||||
/// refuses to guess between, and the one the engine refuses a refactoring
|
||||
/// over.
|
||||
fn declared_twice(ws: &Workspace, name: &str) -> bool {
|
||||
ws.index().units(name).iter().filter(|def| def.kind.is_instantiable()).count() > 1
|
||||
}
|
||||
|
||||
/// Run one of the three commands, or say why it cannot run.
|
||||
///
|
||||
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
|
||||
@@ -809,6 +1000,322 @@ mod tests {
|
||||
assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the lazy offer and its resolve (TODO §37.1)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The offer a client that can resolve receives at `offset`.
|
||||
fn offered(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let position = ws.document(uri).expect("an open document").positions().position(offset);
|
||||
offers(ws, uri, position, offset)
|
||||
}
|
||||
|
||||
/// One action's title and kind — what a lightbulb draws, and all an offer
|
||||
/// promises.
|
||||
fn menu(actions: &[CodeActionOrCommand]) -> Vec<(String, Option<String>)> {
|
||||
actions
|
||||
.iter()
|
||||
.map(|action| {
|
||||
let CodeActionOrCommand::CodeAction(action) = action else {
|
||||
return ("a command".to_string(), None);
|
||||
};
|
||||
(action.title.clone(), action.kind.as_ref().map(|k| k.as_str().to_string()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The one action an offer holds.
|
||||
fn only(actions: &[CodeActionOrCommand]) -> &CodeAction {
|
||||
let [CodeActionOrCommand::CodeAction(action)] = actions else {
|
||||
panic!("exactly one action, got {actions:#?}")
|
||||
};
|
||||
action
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lazy_offer_names_exactly_what_the_eager_one_names() {
|
||||
let tree = Tree::new("lazy_menu");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let lazy = offered(&ws, &sub_uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &sub_uri, offset)));
|
||||
assert_eq!(
|
||||
menu(&lazy)[0].0,
|
||||
"lucisv: remove port `rst` (updates 3 instantiations)",
|
||||
"counted from the index, and it agrees with the plan's own count"
|
||||
);
|
||||
let action = only(&lazy);
|
||||
assert!(action.edit.is_none(), "an offer carries no edit");
|
||||
assert!(action.data.is_some(), "it carries what resolve needs instead");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_reads_the_buffer_and_at_most_the_declaring_file() {
|
||||
// The pin `the_files_a_code_action_reads_are_the_modules_own_fan_out`
|
||||
// is to the eager path; this is the same question asked of the offer,
|
||||
// through the set it hands the engine. Neither the 40 noise files nor
|
||||
// — and this is the point — any of the three instantiating tops.
|
||||
let tree = Tree::new("lazy_reads");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
assert_eq!(ws.sources().len(), 44, "the whole workspace");
|
||||
assert_eq!(ws.module_sources(&sub, &["sub".to_string()]).len(), 4, "the eager fan-out");
|
||||
|
||||
// A cursor on a port declaration: the module is the buffer's own.
|
||||
let read = offer_sources(&ws, &sub, SUB, &["sub".to_string()]);
|
||||
let names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert_eq!(names, ["sub.sv"], "one file, and it is the buffer itself");
|
||||
|
||||
// A cursor on an instantiation: the buffer, plus the one file the
|
||||
// index says declares the module.
|
||||
let top = tree.path.join("top0.sv");
|
||||
let top_text = std::fs::read_to_string(&top).expect("read");
|
||||
let read = offer_sources(&ws, &top, &top_text, &["sub".to_string()]);
|
||||
let mut names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["sub.sv", "top0.sv"], "and never top1, top2 or a noise file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolved_action_carries_the_eager_edit_at_a_port_declaration() {
|
||||
let tree = Tree::new("resolve_port");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let resolved = resolve(&ws, only(&offered(&ws, &sub_uri, offset)).clone()).expect("edit");
|
||||
let eager = only(&code_actions(&ws, &sub_uri, offset)).clone();
|
||||
assert_eq!(resolved.title, eager.title);
|
||||
assert_eq!(resolved.kind, eager.kind);
|
||||
assert_eq!(resolved.edit, eager.edit, "the same WorkspaceEdit, to the byte");
|
||||
assert!(resolved.data.is_some(), "the offer's own data survives the round trip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolved_action_carries_the_eager_edit_at_an_instantiation() {
|
||||
// The other cursor shape: an instantiation missing a connection, where
|
||||
// the offer has to read the *instantiated* module's declaration to
|
||||
// know there is anything to offer at all.
|
||||
let tree = Tree::new("resolve_inst");
|
||||
let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", text);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let offset = text.find("sub u_sub").expect("the instantiation") as u32;
|
||||
|
||||
let lazy = offered(&ws, &uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
|
||||
assert_eq!(menu(&lazy)[0].0, "lucisv: connect 1 missing port");
|
||||
assert!(only(&lazy).edit.is_none());
|
||||
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
|
||||
assert_eq!(
|
||||
edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text,
|
||||
", .rst(rst)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count() {
|
||||
// The pin `an_unsaved_buffer_contributes_the_instantiation_the_index
|
||||
// _has_not_seen` moved to the lazy path. The offer counts instances
|
||||
// from the index, which has not seen the unsaved one, so the title
|
||||
// says three; the *edit* is computed over the fan-out plus every open
|
||||
// buffer, so it disconnects all four. Exactness lives in the edit,
|
||||
// which is what the user actually applies.
|
||||
let tree = Tree::new("lazy_unsaved");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
let extra = tree.path.join("noise0.sv");
|
||||
let extra_uri = path_to_uri(&extra).expect("uri");
|
||||
let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n";
|
||||
ws.set_document(extra_uri.clone(), typed.to_string());
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let lazy = offered(&ws, &sub_uri, offset);
|
||||
assert_eq!(
|
||||
menu(&lazy)[0].0,
|
||||
"lucisv: remove port `rst` (updates 3 instantiations)",
|
||||
"the index has not seen the fourth"
|
||||
);
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(
|
||||
resolved.title, "lucisv: remove port `rst` (updates 4 instantiations)",
|
||||
"and the resolve says so"
|
||||
);
|
||||
let edit = resolved.edit.as_ref().expect("an edit");
|
||||
assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &sub_uri, offset)).edit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_of_an_action_the_buffer_no_longer_carries_is_refused() {
|
||||
let tree = Tree::new("lazy_stale");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let offered = only(&offered(&ws, &sub_uri, offset)).clone();
|
||||
|
||||
// The user kept typing: the port the lightbulb was about is gone.
|
||||
ws.set_document(sub_uri.clone(), "module sub (\n input logic clk\n);\nendmodule\n".into());
|
||||
let message = resolve(&ws, offered.clone()).expect_err("nothing to resolve");
|
||||
assert_eq!(message, GONE);
|
||||
|
||||
// And a document that has been closed altogether says the same.
|
||||
ws.close_document(&sub_uri);
|
||||
assert_eq!(resolve(&ws, offered).expect_err("no buffer"), GONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused() {
|
||||
// `codeAction/resolve`'s params are a `CodeAction`, so the fast path's
|
||||
// own gate — which reads a `textDocument` out of the params — never
|
||||
// sees this request. A buffer that grew past the threshold since it
|
||||
// was offered an action must still not be parsed.
|
||||
let tree = Tree::new("lazy_large");
|
||||
let mut ws = crowded(&tree, 5);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let offered = only(&offered(&ws, &sub_uri, offset)).clone();
|
||||
|
||||
let _ = ws.set_client_settings(crate::settings::ClientSettings {
|
||||
large_file_threshold: 8,
|
||||
..Default::default()
|
||||
});
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
assert!(ws.document(&sub_uri).expect("open").large, "the buffer is on the fast path");
|
||||
assert_eq!(resolve(&ws, offered).expect_err("not parsed"), GONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_of_something_this_server_never_offered_says_so() {
|
||||
let tree = Tree::new("lazy_foreign");
|
||||
let (ws, uri, _) = opened(&tree);
|
||||
let bare = CodeAction { title: "someone else's action".to_string(), ..Default::default() };
|
||||
assert_eq!(resolve(&ws, bare.clone()).expect_err("no data"), NOT_OURS);
|
||||
|
||||
// Data that is not ours either — a shape `serde` cannot read as an
|
||||
// offer. Refused, not guessed at.
|
||||
let junk = CodeAction { data: Some(serde_json::json!({"nope": 1})), ..bare.clone() };
|
||||
assert_eq!(resolve(&ws, junk).expect_err("junk data"), NOT_OURS);
|
||||
|
||||
// An action that already carries its edit — every quick fix in
|
||||
// `code_action.rs`, and the port actions a non-resolving client is
|
||||
// sent — comes straight back, because there is nothing to add to it.
|
||||
let complete =
|
||||
CodeAction { edit: Some(WorkspaceEdit::new(HashMap::from([(uri, vec![])]))), ..bare };
|
||||
assert_eq!(resolve(&ws, complete.clone()).expect("nothing to do"), complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_workspace_declares_twice_is_not_offered_either() {
|
||||
// The eager path refuses because both declaring files are in the set
|
||||
// it reads (`a_module_declared_twice_is_refused_through_the_subset_as
|
||||
// _well`). The offer reads neither, so it asks the index the same
|
||||
// question — otherwise it would offer an action resolve then refuses.
|
||||
let tree = Tree::new("lazy_ambiguous");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
tree.write("clone.sv", SUB);
|
||||
ws.rebuild_index();
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
assert!(offered(&ws, &sub_uri, offset).is_empty());
|
||||
assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "as the eager path does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_title_keys_on_everything_but_its_count() {
|
||||
assert_eq!(
|
||||
key("lucisv: remove port `rst` (updates 3 instantiations)"),
|
||||
key("lucisv: remove port `rst` (no instantiation in scope)")
|
||||
);
|
||||
assert_eq!(key("lucisv: connect 1 missing port"), "lucisv: connect 1 missing port");
|
||||
assert_ne!(
|
||||
key("lucisv: remove port `rst` (updates 1 instantiation)"),
|
||||
key("lucisv: remove port `clk` (updates 1 instantiation)")
|
||||
);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server --bin lucisv-server ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn the_offer_is_flat_where_the_eager_answer_grows() {
|
||||
// `performance_take2.md` §6a measured the eager answer growing with
|
||||
// the module's fan-out — ~1.4 ms per instantiating file plus a ~13 ms
|
||||
// floor, 185 ms at 128 files, to offer *zero* actions. The offer reads
|
||||
// one file (a cursor on a port declaration) or two (a cursor on an
|
||||
// instantiation), so its column should be flat. Beside the code it
|
||||
// measures rather than in `perf.rs`, which is what `perf::mean` is
|
||||
// `pub(crate)` for.
|
||||
for instantiators in [3usize, 40, 128] {
|
||||
let tree = Tree::new(&format!("perf_offer_{instantiators}"));
|
||||
tree.write("sub.sv", SUB);
|
||||
for n in 0..instantiators {
|
||||
tree.write(
|
||||
&format!("top{n:03}.sv"),
|
||||
&format!(
|
||||
"module top{n:03};\n logic c, r;\n \
|
||||
sub u_sub (.clk(c), .rst(r));\nendmodule\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
for n in 0..200 {
|
||||
tree.write(
|
||||
&format!("noise{n:03}.sv"),
|
||||
&format!(
|
||||
"module noise{n:03};\n logic a;\n wire b;\n \
|
||||
assign b = a;\nendmodule\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
for (what, file, needle, skip) in [
|
||||
("a port declaration", "sub.sv", "input logic rst", 12u32),
|
||||
("an instantiation ", "top000.sv", "sub u_sub", 0),
|
||||
] {
|
||||
let path = tree.path.join(file);
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let offset = text.find(needle).expect("the cursor") as u32 + skip;
|
||||
let eager = crate::perf::mean(5, || {
|
||||
std::hint::black_box(code_actions(&ws, &uri, offset));
|
||||
});
|
||||
let offer = crate::perf::mean(20, || {
|
||||
std::hint::black_box(offered(&ws, &uri, offset));
|
||||
});
|
||||
eprintln!(
|
||||
" fan-out {instantiators:>3}, cursor on {what}: eager {eager:?}, \
|
||||
offer {offer:?} ({} actions)",
|
||||
offered(&ws, &uri, offset).len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_command_is_declined() {
|
||||
let tree = Tree::new("unknown");
|
||||
|
||||
@@ -117,6 +117,7 @@ fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
|
||||
ItemKind::Class(class) => items(&class.items, offset, out),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenBlock(b) => items(&b.items, offset, out),
|
||||
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
|
||||
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
|
||||
@@ -14,22 +14,22 @@
|
||||
use lsp_server::{Request, RequestId, Response};
|
||||
use lsp_types::request::{
|
||||
CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare,
|
||||
CodeActionRequest, CodeLensRequest, Completion, DocumentDiagnosticRequest,
|
||||
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
|
||||
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams,
|
||||
GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest,
|
||||
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
|
||||
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest,
|
||||
SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest,
|
||||
TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, WillRenameFiles,
|
||||
WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
CodeActionRequest, CodeActionResolveRequest, CodeLensRequest, Completion,
|
||||
DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
|
||||
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
|
||||
GotoTypeDefinition, GotoTypeDefinitionParams, GotoTypeDefinitionResponse, HoverRequest,
|
||||
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
|
||||
PrepareRenameRequest, RangeFormatting, References, Rename, Request as _, SelectionRangeRequest,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
|
||||
SignatureHelpRequest, TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes,
|
||||
WillRenameFiles, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
|
||||
CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams, DocumentDiagnosticParams,
|
||||
DocumentDiagnosticReportResult, DocumentHighlightParams, DocumentLinkParams,
|
||||
DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams,
|
||||
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
CodeAction, CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams,
|
||||
DocumentDiagnosticParams, DocumentDiagnosticReportResult, DocumentHighlightParams,
|
||||
DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams,
|
||||
FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams,
|
||||
RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams,
|
||||
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
|
||||
@@ -258,10 +258,26 @@ impl Server {
|
||||
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
||||
{
|
||||
let offset = doc.positions().offset(p.range.start);
|
||||
actions.extend(ports::code_actions(&self.workspace, &uri, offset));
|
||||
// A client that can resolve is offered the actions without
|
||||
// their edits, which is what keeps a cursor resting on an
|
||||
// instantiation off the module's fan-out; one that cannot
|
||||
// gets the whole edit, exactly as before.
|
||||
actions.extend(match self.abilities.code_action_resolve {
|
||||
true => ports::offers(&self.workspace, &uri, p.range.start, offset),
|
||||
false => ports::code_actions(&self.workspace, &uri, offset),
|
||||
});
|
||||
}
|
||||
to_value(actions)
|
||||
}),
|
||||
// The edit for an action offered without one. An action that
|
||||
// already carries its edit comes straight back, so a client that
|
||||
// resolves everything it is offered is answered too.
|
||||
CodeActionResolveRequest::METHOD => decode(request).and_then(|action: CodeAction| {
|
||||
match ports::resolve(&self.workspace, action) {
|
||||
Ok(resolved) => to_value(resolved),
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
}),
|
||||
// Custom method, so it is matched by name rather than through a
|
||||
// `lsp_types::request` type. Nothing advertises it: a client that
|
||||
// does not know it never asks.
|
||||
|
||||
@@ -104,6 +104,13 @@ pub struct ClientAbilities {
|
||||
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
|
||||
/// a notification whenever the installed workspace index changes.
|
||||
pub hierarchy_view: bool,
|
||||
/// Whether the client can fetch a code action's `edit` through
|
||||
/// `codeAction/resolve` — `textDocument.codeAction.resolveSupport`
|
||||
/// listing `"edit"`. Only then are the port refactorings *offered* without
|
||||
/// their edits; a client that said nothing gets the whole edit up front,
|
||||
/// which is what every client got before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
pub code_action_resolve: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
|
||||
@@ -1797,6 +1797,17 @@ impl Workspace {
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// The files the view cache is holding, newest first.
|
||||
///
|
||||
/// Test-only, and it exists for one question: whether an answer read a
|
||||
/// file at all. A `Location` computed from the index alone must leave this
|
||||
/// empty, which is the whole point of `locate::definition_location` — see
|
||||
/// `docs/features/lazy-code-action/README.md`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn held_views(&self) -> Vec<PathBuf> {
|
||||
self.views.borrow().iter().map(|view| view.path.clone()).collect()
|
||||
}
|
||||
|
||||
/// The held view for `path`, moved to the front so the bounds below drop
|
||||
/// whatever has gone longest unused.
|
||||
fn cached_view(&self, path: &Path) -> Option<Rc<FileView>> {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use lsp_types::{Location, SymbolInformation, SymbolKind as LspKind};
|
||||
use vlog_semantic::{Symbol, SymbolKind};
|
||||
|
||||
use crate::locate::location;
|
||||
use crate::locate::definition_location;
|
||||
use crate::state::{Document, Workspace, WORKSPACE_SYMBOL_LIMIT};
|
||||
|
||||
/// How a declaration reads in hover text.
|
||||
@@ -129,7 +129,11 @@ pub fn workspace_symbols(ws: &Workspace, query: &str) -> Vec<SymbolInformation>
|
||||
.take(WORKSPACE_SYMBOL_LIMIT)
|
||||
.filter_map(|hit| {
|
||||
let path = index.path(hit.def.file)?;
|
||||
let location: Location = location(ws, path, hit.def.name_span)?;
|
||||
// A unit's range is in the index; a member's is not, and falls
|
||||
// back to the file read. `workspace/symbol` answers up to
|
||||
// `WORKSPACE_SYMBOL_LIMIT` hits at once, so this is the request
|
||||
// the index-carried positions matter most to.
|
||||
let location: Location = definition_location(ws, path, hit.def)?;
|
||||
// `deprecated` is a deprecated protocol field that is still a
|
||||
// named field of the struct.
|
||||
#[allow(deprecated)]
|
||||
|
||||
@@ -180,6 +180,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
site_at(items, offset)
|
||||
}
|
||||
ItemKind::GenBlock(b) => gen_block_site(b, offset),
|
||||
ItemKind::GenIf(g) => gen_if_site(g, offset),
|
||||
ItemKind::GenFor(g) => gen_block_site(&g.body, offset),
|
||||
ItemKind::GenCase(g) => g.items.iter().find_map(|arm| gen_block_site(&arm.body, offset)),
|
||||
|
||||
@@ -1484,6 +1484,106 @@ fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() {
|
||||
);
|
||||
assert!(conditional["result"].is_null(), "a refusal carries no edits: {conditional:#?}");
|
||||
|
||||
// 7. The client above sent `"capabilities":{}`, so every action came back
|
||||
// complete — which is the whole of the no-resolveSupport contract.
|
||||
assert!(port_action["data"].is_null(), "nothing to resolve for this client: {port_action:#?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_resolves_is_offered_the_port_action_without_its_edit() {
|
||||
// The lazy half of the same feature (TODO §37.1): a client that declares
|
||||
// `codeAction.resolveSupport.properties: ["edit"]` is offered the action
|
||||
// with `data` and no `edit`, and gets the edit from `codeAction/resolve`.
|
||||
// Only an e2e test can check that the `data` really survives the round
|
||||
// trip through the client — it is opaque JSON the server never sees again
|
||||
// until the client hands it back.
|
||||
let dir = temp_dir("resolve");
|
||||
let sub = dir.join("sub.sv");
|
||||
std::fs::write(&sub, PORTS_SUB).expect("write");
|
||||
let top = dir.join("top.sv");
|
||||
std::fs::write(&top, PORTS_TOP).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let top_uri = format!("file://{}", top.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(PORTS_TOP).expect("json")
|
||||
)),
|
||||
// The cursor on `u_sub`, whose instantiation is missing `.rst`.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":6}},"end":{{"line":2,"character":6}}}},"context":{{"diagnostics":[]}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&session);
|
||||
|
||||
// 1. The capability says a resolve is answered.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let provider = &initialize["result"]["capabilities"]["codeActionProvider"];
|
||||
assert_eq!(provider["resolveProvider"], true, "{provider:#?}");
|
||||
|
||||
// 2. The offer carries `data` and no `edit`.
|
||||
let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response");
|
||||
let offered = actions["result"].as_array().expect("an array of actions");
|
||||
let action = offered
|
||||
.iter()
|
||||
.find(|a| a["kind"] == "refactor.rewrite.lucisv.ports")
|
||||
.unwrap_or_else(|| panic!("no port action in {offered:#?}"));
|
||||
assert_eq!(action["title"], "lucisv: connect 1 missing port");
|
||||
assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}");
|
||||
assert_eq!(action["data"]["uri"], top_uri.as_str());
|
||||
assert_eq!(action["data"]["title"], action["title"]);
|
||||
|
||||
// 3. Handing that same action back gets the edit. A second session,
|
||||
// because the action has to be echoed verbatim and it is only known now.
|
||||
let resolve = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(PORTS_TOP).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#,
|
||||
serde_json::to_string(action).expect("json")
|
||||
)),
|
||||
// ...and an action this server never offered is refused with a
|
||||
// sentence rather than an empty edit.
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","id":4,"method":"codeAction/resolve","params":{"title":"someone else's action"}}"#,
|
||||
),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&resolve);
|
||||
let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response");
|
||||
let edits = resolved["result"]["edit"]["changes"][&top_uri]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("no edit in {resolved:#?}"));
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0]["newText"], ", .rst(rst)");
|
||||
assert_eq!(edits[0]["range"]["start"]["line"], 2);
|
||||
assert_eq!(resolved["result"]["title"], "lucisv: connect 1 missing port");
|
||||
|
||||
let foreign = messages.iter().find(|m| m["id"] == 4).expect("refusal response");
|
||||
assert_eq!(foreign["error"]["code"], -32803, "LSP's RequestFailed");
|
||||
assert!(
|
||||
foreign["error"]["message"].as_str().is_some_and(|m| m.contains("no lucisv port")),
|
||||
"{foreign:#?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -245,6 +245,7 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
|
||||
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
|
||||
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenBlock(b) => scan_gen_block(src, b, out),
|
||||
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
|
||||
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -274,6 +274,21 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(dangling));
|
||||
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
|
||||
}
|
||||
// A bare `begin … end` standing where an item belongs. Never
|
||||
// reached from `format_source`: the parser records a diagnostic
|
||||
// beside it and a file with a diagnostic is emitted unchanged.
|
||||
// The arm exists so a range or tolerant printer has nothing to
|
||||
// invent — the block prints the way a generate block's does,
|
||||
// without the separator `gen_block` puts in front of the keyword
|
||||
// for the header it usually hangs off.
|
||||
ItemKind::GenBlock(b) => {
|
||||
let mut docs = Vec::new();
|
||||
if self.inline_comments(&b.before_kw, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
self.begin_block(&mut docs, b, depth);
|
||||
concat(docs)
|
||||
}
|
||||
ItemKind::GenIf(g) => self.gen_if(g, depth),
|
||||
ItemKind::GenFor(g) => self.gen_for(g, depth),
|
||||
ItemKind::GenCase(g) => self.gen_case(g, depth),
|
||||
@@ -464,26 +479,7 @@ impl<'a> Fmt<'a> {
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.before_kw, docs);
|
||||
}
|
||||
docs.push(text("begin"));
|
||||
if let Some(l) = &b.label {
|
||||
self.slot_comments(&b.before_colon, docs);
|
||||
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
|
||||
if b.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.after_colon, docs);
|
||||
}
|
||||
docs.push(text(named(l)));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !b.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&b.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
|
||||
self.begin_block(docs, b, depth);
|
||||
true
|
||||
} else {
|
||||
let item = &b.items[0];
|
||||
@@ -492,6 +488,33 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate block's `begin … end` and everything between, from the
|
||||
/// keyword on — the separator in front of it is the caller's, because a
|
||||
/// block hanging off an `if (…)` header needs one and a block standing on
|
||||
/// its own as an item ([`ItemKind::GenBlock`]) does not.
|
||||
fn begin_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) {
|
||||
docs.push(text("begin"));
|
||||
if let Some(l) = &b.label {
|
||||
self.slot_comments(&b.before_colon, docs);
|
||||
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
|
||||
if b.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.after_colon, docs);
|
||||
}
|
||||
docs.push(text(named(l)));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !b.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&b.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
|
||||
}
|
||||
|
||||
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
|
||||
let mut header = Vec::new();
|
||||
self.for_open(&g.comments, &mut header);
|
||||
|
||||
@@ -90,6 +90,7 @@ fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
|
||||
collect_body(inner, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(b) => block(b, out),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -141,6 +141,9 @@ fn item_labels(out: &mut Vec<Violation>, item: &Item) {
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
|
||||
// A bare `begin … end` standing as an item (§36.1) is the same node
|
||||
// without a header: its label pair is checked exactly like an arm's.
|
||||
ItemKind::GenBlock(block) => check_gen_block(out, block),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
check_gen_block(out, &case_item.body);
|
||||
@@ -285,6 +288,23 @@ mod tests {
|
||||
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_block_at_module_scope_is_checked_like_a_generate_arm() {
|
||||
// §36.1: the block is a node now, so its own footer is checked. Not
|
||||
// legal at module scope at all (`module-begin-block` says so), but a
|
||||
// mismatched footer is the compile error this rule exists for.
|
||||
let src = "module m;\n\
|
||||
begin : fetch\n\
|
||||
wire a;\n\
|
||||
end : decode\n\
|
||||
endmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "decode");
|
||||
let ok = "module m;\n begin : fetch\n wire a;\n end : fetch\nendmodule\n";
|
||||
assert!(violations(ok).is_empty(), "{:?}", violations(ok));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_block_is_matched_against_its_own_header() {
|
||||
let src = "module m;\n\
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::{Item, ItemKind, RawText};
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
@@ -34,14 +34,15 @@ impl Rule for ModuleBeginBlock {
|
||||
against them is wrong. Verible's `module-begin-block` (\"Checks that \
|
||||
there are no begin-end blocks declared at the module level.\", \
|
||||
enabled by default) is the same rule and the same default.\n\n\
|
||||
lucisv's **parser rejects** the construct rather than recovering it \
|
||||
as a block, so what this rule reads is the error leaf error recovery \
|
||||
left at module scope whose first token is `begin`. The finding is \
|
||||
exact — no legal module item starts with that keyword — but the rest \
|
||||
of the module is lost to recovery, so a file with one of these \
|
||||
reports little else. No automatic fix: whether the block should \
|
||||
become a generate block, an `always` or nothing at all is the \
|
||||
author's to decide."
|
||||
lucisv's parser **recovers** the construct: in error-tolerant mode \
|
||||
the block is read as the unnamed generate block every tool that \
|
||||
accepts it makes of it, and a diagnostic is recorded at the `begin` \
|
||||
— so the file is still reported as not parsing cleanly and the \
|
||||
formatter still refuses to format it, but the items written inside \
|
||||
the block are visible to this rule and to every other one. What this \
|
||||
rule reads is that block standing where a module item belongs. No \
|
||||
automatic fix: whether the block should become a generate block, an \
|
||||
`always` or nothing at all is the author's to decide."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
@@ -61,28 +62,17 @@ impl Rule for ModuleBeginBlock {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `begin` keyword of an error leaf that is a `begin … end` block, or
|
||||
/// `None` for any other leaf.
|
||||
/// The `begin` keyword of an item that is a bare `begin … end` block, or
|
||||
/// `None` for any other item.
|
||||
///
|
||||
/// Shared with `v2001-generate-begin`, which asks the same question one scope
|
||||
/// further in: the two rules must agree about what a stray `begin` looks like,
|
||||
/// and one reading is how that is guaranteed.
|
||||
pub(crate) fn begin_block(item: &Item) -> Option<TextRange> {
|
||||
let ItemKind::Error(raw) = &item.kind else { return None };
|
||||
if !first_word_is_begin(raw) {
|
||||
return None;
|
||||
}
|
||||
Some(TextRange::new(raw.span.start, raw.span.start + 5))
|
||||
}
|
||||
|
||||
/// True when the leaf's first token is exactly the keyword `begin`.
|
||||
fn first_word_is_begin(raw: &RawText) -> bool {
|
||||
let rest = match raw.text.strip_prefix("begin") {
|
||||
Some(rest) => rest,
|
||||
None => return false,
|
||||
};
|
||||
// `beginning` is an identifier, not the keyword.
|
||||
!rest.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$')
|
||||
let ItemKind::GenBlock(block) = &item.kind else { return None };
|
||||
// The node's span opens at the keyword, whatever the item's own span does
|
||||
// with the attributes written in front of it.
|
||||
Some(TextRange::new(block.span.start, block.span.start + 5))
|
||||
}
|
||||
|
||||
/// Calls `f` on every item written directly in a module, interface or program
|
||||
@@ -156,6 +146,33 @@ mod tests {
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_block_keeps_its_items_and_the_module_keeps_the_items_after_it() {
|
||||
// §36.1: the block is a node now, not an error leaf, so what is
|
||||
// written inside it and after it is still there for every rule.
|
||||
// Before, recovery skipped to `endmodule` and the `defparam` was
|
||||
// inside one opaque leaf.
|
||||
let src = "module m;\n begin\n defparam u.P = 1;\n end\n wire a;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
let ctx = LintContext::new(src, None);
|
||||
let inside = crate::rules::forbid_defparam::ForbidDefparam.check(&ctx);
|
||||
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
|
||||
assert_eq!(ctx.file().items.len(), 1, "one module");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_outermost_block_of_a_nest_is_reported_at_module_scope() {
|
||||
// The inner block is written inside a block, not at module scope, so
|
||||
// it is not this rule's finding — exactly as before §36.1, when the
|
||||
// whole nest was one leaf whose first token was the outer `begin`.
|
||||
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].span.start, 12, "the outer `begin`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_parses_cleanly_has_nothing_to_report() {
|
||||
let src = "module m;\n wire a;\nendmodule\n";
|
||||
|
||||
@@ -36,11 +36,13 @@ impl Rule for V2001GenerateBegin {
|
||||
`v2001-generate-begin` (\"Checks that there are no generate-begin \
|
||||
blocks inside a generate region.\", enabled by default) is the same \
|
||||
rule and the same default.\n\n\
|
||||
Like `module-begin-block`, this reads the error leaf lucisv's parser \
|
||||
leaves where it refused the construct: an item inside a \
|
||||
`generate … endgenerate` whose first token is `begin`. No automatic \
|
||||
fix — deleting the two keywords re-indents the whole block, and \
|
||||
giving it a label instead is a different repair."
|
||||
Like `module-begin-block`, this reads the block lucisv's parser \
|
||||
recovers where it refuses the construct: an unnamed generate block \
|
||||
written directly inside a `generate … endgenerate`, kept in the tree \
|
||||
beside a diagnostic at its `begin`, so everything declared inside it \
|
||||
is still visible to the other rules. No automatic fix — deleting the \
|
||||
two keywords re-indents the whole block, and giving it a label \
|
||||
instead is a different repair."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
@@ -95,6 +97,18 @@ mod tests {
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_blocks_items_stay_visible_to_the_other_rules() {
|
||||
let src = "module m;\n generate\n begin : b\n defparam u.P = 1;\n end\n \
|
||||
endgenerate\n wire ok;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
let inside =
|
||||
crate::rules::forbid_defparam::ForbidDefparam.check(&LintContext::new(src, None));
|
||||
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_no_generate_region_is_silent() {
|
||||
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
|
||||
|
||||
@@ -369,6 +369,7 @@ impl Scanner {
|
||||
}
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => self.items(items, module, true),
|
||||
ItemKind::GenBlock(b) => self.items(&b.items, module, true),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
self.items(&gen_if.then.items, module, true);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -24,6 +24,7 @@ fn items(list: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
ItemKind::Class(class) => items(&class.items, f),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenBlock(b) => items(&b.items, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
gen_block(&gen_if.then, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
@@ -103,6 +104,7 @@ fn scoped_items(list: &[Item], scope: ItemScope, f: &mut dyn FnMut(ItemScope, &I
|
||||
ItemKind::Package { items: inner, .. } => scoped_items(inner, ItemScope::Package, f),
|
||||
// A generate construct keeps the scope it was written in.
|
||||
ItemKind::GenerateRegion { items: inner, .. } => scoped_items(inner, scope, f),
|
||||
ItemKind::GenBlock(b) => scoped_items(&b.items, scope, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
scoped_items(&gen_if.then.items, scope, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -387,6 +387,15 @@ pub enum ItemKind {
|
||||
dangling: Vec<Comment>,
|
||||
},
|
||||
GenIf(GenIf),
|
||||
/// A bare `begin … end` written where an item belongs — at module scope
|
||||
/// or straight inside `generate … endgenerate`. Not a legal module item
|
||||
/// (IEEE 1800 §23.2.1); tools that accept it read it as an unnamed
|
||||
/// generate block, which is the node kept here. Only error-tolerant
|
||||
/// parsing produces it, always beside a diagnostic at the `begin`, so the
|
||||
/// formatter — which refuses any file with a diagnostic — never prints
|
||||
/// one. The `module-begin-block` and `v2001-generate-begin` lints are
|
||||
/// what report it. Boxed for the same reason [`ItemKind::GenFor`] is.
|
||||
GenBlock(Box<GenBlock>),
|
||||
/// Boxed: a `for` generate holds a whole `SimpleAssign`, a condition, a
|
||||
/// step and a block, which together are twice the next-largest item.
|
||||
GenFor(Box<GenFor>),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! `bind` directives. Drive strengths and delay values live here because
|
||||
//! these are the only items that write them.
|
||||
|
||||
use super::recover::is_sync_stop;
|
||||
use super::*;
|
||||
|
||||
/// The strength keywords a drive strength is written from (IEEE 1800 §28.11).
|
||||
@@ -504,6 +505,16 @@ impl<'a> Parser<'a> {
|
||||
let before_open = self.take_before_open("(");
|
||||
let mark = self.pending_trailing.len();
|
||||
let paren_start = self.here();
|
||||
// A half-typed `.NAME(` whose value would read as the next
|
||||
// instance: `sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x));`. Nothing
|
||||
// inside the list fails — `u0 (.a(x))` is a legal call with named
|
||||
// arguments — so the greedy parse swallows the instance and the
|
||||
// whole instantiation collapses into one error item. Failing the
|
||||
// element here costs the one connection and keeps everything
|
||||
// else. See `docs/features/small-items-3/README.md`.
|
||||
if self.tolerant && self.cur().is_sym("(") && self.value_runs_into_next_instance() {
|
||||
return self.error("unclosed `(` in a port or parameter connection");
|
||||
}
|
||||
let mut close_comments = Vec::new();
|
||||
let mut after_open = Vec::new();
|
||||
let expr = if self.eat_sym("(") {
|
||||
@@ -562,6 +573,58 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the `(` at the cursor — the one that opens a connection's
|
||||
/// value — is never closed **and** something that reads as the next
|
||||
/// instance sits inside it.
|
||||
///
|
||||
/// Tolerant mode only, asked once per named connection before its value
|
||||
/// is parsed. The walk starts just past the `(` at depth zero and ends at
|
||||
/// the first of: a closer that would take the depth below zero (the
|
||||
/// value's own `)` — it closes, so nothing is wrong and the value is
|
||||
/// parsed as written), a `;` or a construct keyword at depth zero, or end
|
||||
/// of file. On a file that parses it therefore stops at the value's `)`
|
||||
/// after a handful of tokens; only a value whose bracket was never closed
|
||||
/// walks as far as the next `;`.
|
||||
///
|
||||
/// The candidate is an identifier that opens its own line and is followed
|
||||
/// by `(` — how an instance is written, and how nothing written *inside*
|
||||
/// a value normally is. Only depth zero is read: a candidate inside a
|
||||
/// deeper unclosed bracket (`.DEPTH(f(g(` ⏎ `u0 (…)`) is not seen, and
|
||||
/// that shape falls back to the coarser item-level recovery, which keeps
|
||||
/// the `endmodule` but loses the instantiation. Deliberate — reading
|
||||
/// deeper would start guessing which of several unclosed brackets the
|
||||
/// user meant to close.
|
||||
fn value_runs_into_next_instance(&self) -> bool {
|
||||
let mut depth = 0u32;
|
||||
let mut candidate = false;
|
||||
let mut i = self.pos + 1;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
break;
|
||||
}
|
||||
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
|
||||
depth += 1;
|
||||
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
|
||||
if depth == 0 {
|
||||
return false;
|
||||
}
|
||||
depth -= 1;
|
||||
} else if depth == 0 {
|
||||
if t.is_sym(";") || is_sync_stop(t) {
|
||||
break;
|
||||
}
|
||||
if t.kind == TokenKind::Ident
|
||||
&& self.tokens[i - 1].line != t.line
|
||||
&& self.tokens.get(i + 1).is_some_and(|n| n.is_sym("("))
|
||||
{
|
||||
candidate = true;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
/// Consume the tokens up to `end_pos` as one verbatim expression.
|
||||
///
|
||||
/// [`Parser::open_conds`] is deliberately left alone: it counts *item*
|
||||
|
||||
@@ -275,6 +275,22 @@ impl<'a> Parser<'a> {
|
||||
self.expect_closer("endgenerate")?;
|
||||
Ok(ItemKind::GenerateRegion { items, dangling })
|
||||
}
|
||||
// A bare `begin … end` where an item belongs — at module scope or
|
||||
// straight inside a generate region. It is not a module item
|
||||
// (IEEE 1800 §23.2.1), so strict mode falls through to the
|
||||
// default arm and refuses it exactly as it always has. Tolerant
|
||||
// mode reads it the way every tool that accepts it does — as an
|
||||
// unnamed generate block — and still records the diagnostic, so
|
||||
// the file is reported as not parsing cleanly and the formatter
|
||||
// goes on emitting it unchanged. What is bought is the rest of
|
||||
// the body: without this the item fails, recovery skips to a sync
|
||||
// point and everything after the block is lost. The
|
||||
// `module-begin-block` and `v2001-generate-begin` lints read the
|
||||
// node.
|
||||
"begin" if self.tolerant => {
|
||||
self.record("`begin`/`end` block is not a module item");
|
||||
self.parse_gen_block().map(|b| ItemKind::GenBlock(Box::new(b)))
|
||||
}
|
||||
"if" => self.parse_gen_if().map(ItemKind::GenIf),
|
||||
"for" => self.parse_gen_for().map(|g| ItemKind::GenFor(Box::new(g))),
|
||||
"case" => self.parse_gen_case().map(ItemKind::GenCase),
|
||||
|
||||
@@ -67,13 +67,19 @@ pub(crate) fn error_file(source: &str) -> SourceFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `t` closes, or opens, a construct an enclosing parse loop is
|
||||
/// responsible for. [`Parser::at_sync_stop`] asks it about the cursor; the
|
||||
/// lookaheads that walk raw tokens ahead of the cursor ask it about those.
|
||||
pub(super) fn is_sync_stop(t: &Token) -> bool {
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// True when the cursor sits on a token recovery must not consume: it
|
||||
/// closes, or opens, a construct an enclosing loop is responsible for.
|
||||
pub(super) fn at_sync_stop(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
is_sync_stop(self.cur())
|
||||
}
|
||||
|
||||
/// True on any of the `join` keywords that close a `fork`.
|
||||
|
||||
@@ -14,7 +14,10 @@
|
||||
//! * the bracket counter is **seeded from the list's own open bracket** —
|
||||
//! already consumed by the caller — so the `;`s inside a `for (…; …; …)`
|
||||
//! header are invisible and no skip can run past the bracket that closes
|
||||
//! the list it is in;
|
||||
//! the list it is in. An element that gave up standing *on* a bracket
|
||||
//! opened one it never closed, so that bracket is taken before the skip
|
||||
//! starts rather than counted as a level of its own (see
|
||||
//! [`Parser::recover_element`]);
|
||||
//! * a **line change** stops a skip. It is the one line-based rule in the
|
||||
//! parser, and it is what makes `module m (input logic a, inp⏎ output b);`
|
||||
//! cost one port instead of the rest of the list.
|
||||
@@ -245,6 +248,17 @@ impl<'a> Parser<'a> {
|
||||
// neither ends here nor eats a separator, so take one token to
|
||||
// guarantee it advances.
|
||||
self.bump();
|
||||
} else if self.at_open_bracket() {
|
||||
// The element gave up standing *on* a bracket, which is therefore
|
||||
// one it opened and never closed — the `(` of a half-typed
|
||||
// `.DEPTH(` (see `Parser::value_runs_into_next_instance`). That
|
||||
// bracket is part of the broken element, not a level the skip has
|
||||
// to balance: counting it would put the skip one level below the
|
||||
// list, where the line-change rule is not read, and the rest of
|
||||
// the body would be swallowed looking for a `)` that was never
|
||||
// written. Taken here, the skip starts inside it at the list's own
|
||||
// level and stops at the next line as it does everywhere else.
|
||||
self.bump();
|
||||
}
|
||||
self.skip_inside_brackets(false);
|
||||
let _ = self.take_dangling();
|
||||
@@ -253,6 +267,12 @@ impl<'a> Parser<'a> {
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// True on a token that opens a bracket.
|
||||
fn at_open_bracket(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// The extent a recovery covers: from `start` through the last token it
|
||||
/// took, or the empty range at `start` when it took none (the sync point
|
||||
/// was already under the cursor).
|
||||
|
||||
@@ -67,6 +67,7 @@ fn collect_sva(items: &[vlog_parser::ast::Item], out: &mut Vec<(u32, u32)>) {
|
||||
ItemKind::Package { items, .. } => collect_sva(items, out),
|
||||
ItemKind::Class(c) => collect_sva(&c.items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_sva(items, out),
|
||||
ItemKind::GenBlock(b) => collect_sva(&b.items, out),
|
||||
ItemKind::GenIf(g) => {
|
||||
collect_sva(&g.then.items, out);
|
||||
match g.els.as_deref() {
|
||||
|
||||
@@ -101,6 +101,8 @@ const BROKEN: &[(&str, &str)] = &[
|
||||
("half-typed instantiation", "module m;\n sub u0 (.a(\nendmodule\n"),
|
||||
("garbage between modules", "module a;\nendmodule\n@#!\nmodule b;\n wire w;\nendmodule\n"),
|
||||
("error in generate", "module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n"),
|
||||
("module-scope begin block", "module m;\n begin\n wire a;\n end\n wire b;\nendmodule\n"),
|
||||
("override runs into the next instance", "module m;\n sub #(.W(8), .D(\n u0 (.a(x));\nendmodule\n"),
|
||||
("all garbage", "!!! ???\n"),
|
||||
("stray endmodule", "endmodule\nmodule b;\nendmodule\n"),
|
||||
("unterminated string", "module m;\n initial $display(\"abc);\nendmodule\n"),
|
||||
@@ -190,6 +192,7 @@ fn walk_item(item: &Item, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
items.iter().for_each(|i| walk_item(i, out))
|
||||
}
|
||||
ItemKind::GenBlock(b) => b.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::GenIf(g) => walk_gen_if(g, out),
|
||||
ItemKind::GenFor(g) => g.body.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::GenCase(g) => {
|
||||
@@ -516,6 +519,90 @@ fn a_half_typed_instantiation_costs_one_connection() {
|
||||
assert_eq!(error_nodes(&file).len(), 1);
|
||||
}
|
||||
|
||||
/// The QA shape of 2026-09-02 (`docs/features/header-recovery/README.md`):
|
||||
/// a half-typed `#(` override whose value would read as the next instance.
|
||||
/// Nothing inside the list fails on its own — `u0 (.a(x), .b(y))` is a legal
|
||||
/// call with named arguments — so before §36.2 the greedy parse swallowed the
|
||||
/// instance and the whole instantiation collapsed into one error item that ate
|
||||
/// the `endmodule` too. It now costs the one override.
|
||||
#[test]
|
||||
fn a_half_typed_override_does_not_swallow_the_next_instance() {
|
||||
let src = "module m;\n sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "(", "the diagnostic points at the unclosed `(`");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
assert_eq!(params.len(), 2);
|
||||
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("WIDTH"));
|
||||
assert_eq!(params[1].error().map(|r| r.text.as_str()), Some(".DEPTH("));
|
||||
assert_eq!(inst.instances.len(), 1);
|
||||
assert_eq!(inst.instances[0].name, "u0");
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 2, "both connections of the instance survive");
|
||||
// The `endmodule` was consumed by the module, not by the error: one
|
||||
// diagnostic above already says so, and the module's span ends at it.
|
||||
assert_eq!(&src[m.items[0].span.as_range()], "sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));");
|
||||
}
|
||||
|
||||
/// The same lookahead covers the connection list. `u1` cannot be a second
|
||||
/// instance of `sub` — no comma was written — so it becomes an item of the
|
||||
/// module, which is one error node instead of the whole rest of the body.
|
||||
#[test]
|
||||
fn a_half_typed_connection_does_not_swallow_the_next_instance() {
|
||||
let src = "module m;\n sub u0 (.a(\n u1 (.b(y));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "(");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 1);
|
||||
assert_eq!(conns[0].error().map(|r| r.text.as_str()), Some(".a("));
|
||||
assert_eq!(error_nodes(&file).len(), 2, "the connection and the orphaned `u1 (...)`");
|
||||
}
|
||||
|
||||
/// The ambiguous shape stays ambiguous. With the parentheses balancing, the
|
||||
/// value *closes* — the lookahead says nothing is wrong and the greedy parse
|
||||
/// wins, exactly as before §36.2. Pinned so nobody "fixes" it: the parser
|
||||
/// cannot know whether the author meant a call or a forgotten `)`.
|
||||
#[test]
|
||||
fn a_connection_value_whose_parens_balance_is_still_read_greedily() {
|
||||
let src = "module m;\n sub #(.D(\n u0 (.a(x)));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert!(diags.iter().all(|d| !d.message.contains("unclosed")), "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::Error(raw) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(raw.text, "sub #(.D(\n u0 (.a(x)));");
|
||||
}
|
||||
|
||||
/// A legal value written over three lines — whose middle line opens with an
|
||||
/// identifier followed by `(`, the very shape the lookahead hunts for — parses
|
||||
/// identically in both modes, because the value closes.
|
||||
#[test]
|
||||
fn a_legal_multi_line_connection_value_is_untouched() {
|
||||
let src = "module m;\n sub #(.DEPTH(\n f(1)\n )) u0 (.a(x));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{diags:?}");
|
||||
assert!(parse_source(src).is_ok(), "and strict mode reads it too");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
assert_eq!(params.len(), 1);
|
||||
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("DEPTH"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Header recovery (TODO §32): one test per shape, with exact counts
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -713,6 +800,100 @@ fn an_error_in_a_generate_block_does_not_eat_the_endgenerate() {
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// A bare `begin … end` where an item belongs (TODO §36.1)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The block a `begin` opens at module scope is kept, with its items and with
|
||||
/// everything written after it. It is still an error — one diagnostic, at the
|
||||
/// keyword — so the formatter goes on refusing the file; what changed is that
|
||||
/// recovery no longer throws the rest of the module away.
|
||||
#[test]
|
||||
fn a_module_scope_begin_block_keeps_its_items_and_the_items_after_it() {
|
||||
let src = "module m;\n begin\n wire a;\n end\n assign b = 1;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "begin");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert!(b.is_block);
|
||||
assert_eq!(b.label, None);
|
||||
assert_eq!(b.items.len(), 1);
|
||||
assert!(matches!(&b.items[0].kind, ItemKind::DataDecl(_)), "{}", kind_name(&b.items[0]));
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::ContAssign(_)), "{}", kind_name(&m.items[1]));
|
||||
assert!(error_nodes(&file).is_empty(), "the block is a node, not a leaf");
|
||||
}
|
||||
|
||||
/// The same one scope in: `generate begin … end endgenerate`. The region keeps
|
||||
/// its `endgenerate` and the module keeps the items after it.
|
||||
#[test]
|
||||
fn a_generate_region_begin_block_keeps_its_items_and_the_items_after_it() {
|
||||
let src = "module m;\n generate\n begin : g\n wire a;\n end\n \
|
||||
endgenerate\n wire ok;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "begin");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::GenerateRegion { items, .. } = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
assert_eq!(items.len(), 1);
|
||||
let ItemKind::GenBlock(b) = &items[0].kind else { panic!("{}", kind_name(&items[0])) };
|
||||
assert_eq!(b.label.as_deref(), Some("g"));
|
||||
assert_eq!(b.items.len(), 1);
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[1]));
|
||||
}
|
||||
|
||||
/// Strict mode is untouched: both shapes are still a hard parse error, which
|
||||
/// is what keeps every corpus file byte-identical.
|
||||
#[test]
|
||||
fn strict_mode_still_refuses_a_bare_begin_block() {
|
||||
for src in [
|
||||
"module m;\n begin\n wire a;\n end\nendmodule\n",
|
||||
"module m;\n generate\n begin\n wire a;\n end\n endgenerate\nendmodule\n",
|
||||
] {
|
||||
let err = parse_source(src).expect_err("strict mode must refuse a bare `begin`");
|
||||
assert!(err.to_string().contains("begin"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `end : label` on the recovered block lands in `end_label`, the way it does
|
||||
/// on any other generate block.
|
||||
#[test]
|
||||
fn a_bare_begin_block_keeps_its_end_label() {
|
||||
let src = "module m;\n begin : b\n wire a;\n end : b\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(b.label.as_deref(), Some("b"));
|
||||
assert_eq!(b.end_label.as_deref(), Some("b"));
|
||||
let label_span = b.end_label_span.expect("an end-label span");
|
||||
assert_eq!(&src[label_span.as_range()], "b");
|
||||
}
|
||||
|
||||
/// A block inside a block recovers the same way, once per keyword, and both
|
||||
/// blocks keep what was written in them.
|
||||
#[test]
|
||||
fn a_begin_block_nested_in_another_recovers_the_same_way() {
|
||||
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
for d in &diags {
|
||||
assert_eq!(&src[d.span.as_range()], "begin");
|
||||
}
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::GenBlock(outer) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(outer.items.len(), 1);
|
||||
let ItemKind::GenBlock(inner) = &outer.items[0].kind else {
|
||||
panic!("{}", kind_name(&outer.items[0]))
|
||||
};
|
||||
assert!(matches!(&inner.items[0].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_of_only_garbage_is_one_error_item() {
|
||||
for src in ["!!! ???\n", "@@@\n", "?\n"] {
|
||||
|
||||
@@ -34,6 +34,7 @@ fn walk(items: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
ItemKind::Package { items, .. } => walk(items, f),
|
||||
ItemKind::Class(c) => walk(&c.items, f),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, f),
|
||||
ItemKind::GenBlock(b) => walk(&b.items, f),
|
||||
ItemKind::GenFor(g) => walk(&g.body.items, f),
|
||||
ItemKind::GenIf(g) => {
|
||||
walk(&g.then.items, f);
|
||||
|
||||
@@ -565,6 +565,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
check_item(src, i, here);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(b) => check_gen_block(src, b, here),
|
||||
ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => {
|
||||
assert_inside(src, "raw text", raw.span, here);
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ pub use instantiate::{
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions,
|
||||
propagate_ports, remove_port, ModuleRef, PortAction,
|
||||
propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
|
||||
@@ -150,6 +150,7 @@ pub(super) fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t In
|
||||
ItemKind::Module(module) => collect_instantiations(&module.items, out),
|
||||
ItemKind::Package { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenBlock(b) => collect_instantiations(&b.items, out),
|
||||
ItemKind::GenIf(gen) => {
|
||||
collect_gen_block(&gen.then, out);
|
||||
let mut els = gen.els.as_deref();
|
||||
|
||||
@@ -236,7 +236,12 @@ pub fn enclosing_module(text: &str, offset: u32) -> Option<String> {
|
||||
|
||||
/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation
|
||||
/// in scope".
|
||||
fn sites_phrase(sites: usize) -> String {
|
||||
///
|
||||
/// Public because a server may have to write the same sentence with a count of
|
||||
/// its own: an offer that has not read the fan-out takes the number from its
|
||||
/// workspace index instead of from the plan, and the two must not come to be
|
||||
/// worded differently (`docs/features/lazy-code-action/README.md`).
|
||||
pub fn sites_phrase(sites: usize) -> String {
|
||||
match sites {
|
||||
0 => "no instantiation in scope".to_string(),
|
||||
1 => "updates 1 instantiation".to_string(),
|
||||
|
||||
@@ -128,6 +128,9 @@ impl<'a> Binder<'a> {
|
||||
let inner = self.new_scope(ScopeKind::Generate, scope, item.span);
|
||||
self.bind_items(items, inner);
|
||||
}
|
||||
// A bare `begin … end` where an item belongs: bound as the
|
||||
// unnamed generate scope an unlabeled `if` arm's block gets.
|
||||
ItemKind::GenBlock(b) => self.bind_gen_block(b, scope),
|
||||
ItemKind::GenIf(g) => self.bind_gen_if(g, scope),
|
||||
ItemKind::GenFor(g) => self.bind_gen_for(g, item.span, scope),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -77,6 +77,7 @@ fn walk<'a>(items: &'a [Item], owner: Option<Decl<'a>>, out: &mut Vec<Site<'a>>)
|
||||
}
|
||||
ItemKind::Package { items, .. } => walk(items, owner, out),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, owner, out),
|
||||
ItemKind::GenBlock(b) => block(b, owner, out),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, owner, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -326,6 +326,20 @@ linter; master's linter has since grown 36 rules, `Severity` on `Rule` and new
|
||||
files, so those three arms need re-applying to master's versions of the two
|
||||
files at merge. Nothing else in this branch touches `crates/vlog_linter`.
|
||||
|
||||
**2026-09-04 — the MEDIUM QA finding below is fixed (TODO §36.2).** The
|
||||
half-typed `#(` override whose value reads as the next instance
|
||||
(`sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x), .b(y));`) now costs the one
|
||||
override element and nothing else: `.WIDTH(8)` survives as `Ok`, `.DEPTH(`
|
||||
is the error element, `u0` keeps both its connections and the module keeps
|
||||
its `endmodule`, on one diagnostic at the unclosed `(`. The fix is one
|
||||
tolerant-mode lookahead in `Parser::parse_connection`
|
||||
(`value_runs_into_next_instance`) plus the bracket the skip in
|
||||
`recover_element` now takes when an element gives up standing on one. See
|
||||
`docs/features/small-items-3/README.md`; the shape is pinned by
|
||||
`a_half_typed_override_does_not_swallow_the_next_instance` in
|
||||
`crates/vlog_parser/tests/error_recovery.rs`, with the balanced-parens
|
||||
control beside it (that one is still read greedily, deliberately).
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
# lazy-code-action
|
||||
|
||||
TODO §37 — the three server residues left over from §10: the lazy
|
||||
`codeAction/resolve` for the port refactorings (§37.1), the `inlayHint` zero at
|
||||
the default scope (§37.2), and `locate::location` onto `DeclPositions`
|
||||
(§37.3). One README, one section each.
|
||||
|
||||
## Goal
|
||||
|
||||
**§37.1.** `textDocument/codeAction` arrives on nearly every cursor move, and
|
||||
the port refactorings answered it by computing the *whole* edit — over the
|
||||
instantiated module's entire fan-out plus every open buffer, each file read as
|
||||
text. `docs/performance_take2.md` §6a measured what that costs on opentitan:
|
||||
~1.4 ms per instantiating file plus a ~13 ms floor, **185–201 ms at a 128-file
|
||||
fan-out, to offer zero actions**, above §3's "reads as a hang" line, on the hot
|
||||
path. The *offer* is now local — the buffer, plus the instantiated module's own
|
||||
declaration when the cursor is on an instantiation — and the edit is computed
|
||||
by `codeAction/resolve` when the user picks the action. A client that cannot
|
||||
resolve is unaffected: it still gets the edit up front.
|
||||
|
||||
**§37.2.** `inlayHint` returns 0 hints at the default (folder) scope where the
|
||||
workspace scope returns 4 (`performance_take2.md` §4b, §8.9), the one §4b row
|
||||
the `didOpen` widen did not fix. Investigated, and it is **not a bug** — the
|
||||
finding is written out below, with two tests that pin it.
|
||||
|
||||
**§37.3.** Every file-scope declaration's client-side range is already in the
|
||||
index (`DeclPositions`, added by the design-hierarchy round), so
|
||||
`textDocument/definition` and `workspace/symbol` need not read a file to
|
||||
convert an indexed span. They no longer do: **27.7 µs → 0.40 µs per
|
||||
definition** on opentitan.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The offer may be optimistic; the resolve is exact.** A refusal the engine
|
||||
can only see over the fan-out — an instantiation elsewhere connecting `sub`'s
|
||||
ports *by position*, which makes `remove_port` refuse whole — is invisible to
|
||||
a one-file offer, so the lightbulb can appear and the resolve then decline
|
||||
with "the action is no longer available". This is the trade LSP's resolve
|
||||
model is for; the alternative is the 185 ms. The refusals cheap enough to
|
||||
keep are kept: a module the index declares twice is checked through
|
||||
`WorkspaceIndex::units` before anything is offered, exactly as the eager path
|
||||
refuses over the two declaring files it reads.
|
||||
- **The count in an offered title comes from the index and may be one behind.**
|
||||
`instantiations_of(name)` records one edge per *written statement* with its
|
||||
instances, and the title counts **instances** (`sub u1(), u2();` is two), to
|
||||
match what the eager title counts — the instances the plan really rewrites.
|
||||
The two disagree exactly where the index cannot know: an unsaved buffer's new
|
||||
instantiation, a file-scope instantiation site (which records no edge at
|
||||
all), an instance connecting with `.*`. So the offered and resolved actions
|
||||
are matched on the title *without* its count phrase (`ports::key`), and the
|
||||
resolved action carries the exact title.
|
||||
- **`Def::lines.positions` is `Some` for every file-scope declaration and
|
||||
`None` for every member**, as `DeclLines` documents. §37.3 relies on that:
|
||||
members keep the file-read path, which is not a fallback nobody takes — it is
|
||||
the only answer a port has.
|
||||
- **`codeAction/resolve` carries no `textDocument`**, so the large-file fast
|
||||
path's gate — which reads a URI out of the params — never sees it. `resolve`
|
||||
refuses a buffer on that fast path itself: the mode's contract is that a
|
||||
large buffer is never parsed, and one stale lightbulb is not a reason to
|
||||
break it.
|
||||
- An **open buffer** keeps the file-read path in §37.3 whatever the index
|
||||
recorded, because the buffer's text may have moved since it was indexed and
|
||||
every other answer about that buffer is computed against the text it holds
|
||||
now.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_refactor` → server.** `ports::sites_phrase` is now `pub` (re-exported
|
||||
from the crate root as `vlog_refactor::sites_phrase`). The server writes the
|
||||
same sentence with a count of its own, and one spelling of a user-visible
|
||||
string is the point. Nothing else in `vlog_refactor` changed; `port_actions`,
|
||||
`port_action_modules` and `module_definition` are consumed exactly as before.
|
||||
- **`Workspace` → server.** `Workspace::held_views()` added, `#[cfg(test)]`
|
||||
and `pub(crate)`: the view cache is how a test asserts that an answer read no
|
||||
file. No production caller.
|
||||
- **`main.rs` → `server`.** `ClientAbilities` gains `code_action_resolve`, read
|
||||
at `initialize` from `textDocument.codeAction.resolveSupport.properties`
|
||||
containing `"edit"`. The `initialize` result advertises
|
||||
`codeActionProvider.resolveProvider: true` unconditionally — the server can
|
||||
always answer a resolve, including for an action that already carries its
|
||||
edit, which it hands straight back.
|
||||
- **The wire.** New method answered: `codeAction/resolve`. New field on an
|
||||
offered port action: `data` (`{uri, position, title}`), opaque to the client.
|
||||
The quick fixes in `code_action.rs` are unchanged and still complete when
|
||||
offered.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] §37.1 `ports::offers` — the local offer, titles counted from the index,
|
||||
`data` instead of an edit.
|
||||
- [x] §37.1 `ports::resolve` — today's eager answer at the offer's position,
|
||||
matched on `key(title)`; `RequestFailed` with "the action is no longer
|
||||
available." when nothing matches, and a distinct sentence for an action
|
||||
this server never offered.
|
||||
- [x] §37.1 capability gate: `code_action_resolve_support` in `main.rs`,
|
||||
`ClientAbilities::code_action_resolve`, the dispatch branch.
|
||||
- [x] §37.1 `resolve_provider: Some(true)` advertised; `codeAction/resolve`
|
||||
dispatch arm.
|
||||
- [x] §37.1 tests: the offer's menu equals the eager one over `crowded(40)`;
|
||||
the offer's source set is the buffer (+ the declaring file); the resolved
|
||||
edit is byte-equal to the eager one at both cursor shapes; the unsaved
|
||||
buffer answered by the resolve; a stale and a closed document refused; a
|
||||
foreign action refused; a complete action returned untouched; the
|
||||
duplicate-declaration refusal; a buffer that grew onto the large-file
|
||||
fast path; `key`'s own unit test.
|
||||
- [x] §37.1 e2e over the wire, both client shapes.
|
||||
- [x] §37.1 perf: the "offer" column on `perf.rs`'s
|
||||
`a_code_action_at_an_instantiation_before_and_after`, plus
|
||||
`ports::tests::the_offer_is_flat_where_the_eager_answer_grows`
|
||||
(3/40/128 instantiators, both cursor shapes).
|
||||
- [x] §37.2 investigated; finding written below; two tests at the default
|
||||
scope.
|
||||
- [x] §37.3 `locate::definition_location`, routed through `nav::definition`
|
||||
and `symbols::workspace_symbols`.
|
||||
- [x] §37.3 pins: the encoding shapes, no `file_view` created, members keep
|
||||
the read, the open-buffer case.
|
||||
- [x] §37.3 opentitan timing, read-only
|
||||
(`locate::tests::defining_over_a_real_project`).
|
||||
- [ ] Not done, deliberately: **memoising `module_sources`** per (module, index
|
||||
generation), take 1's other suggestion. The offer makes it unnecessary on
|
||||
the hot path — the fan-out is now read once per *click* — and a cache
|
||||
keyed on a generation is a staleness question this round did not need to
|
||||
open.
|
||||
- [ ] Not done, deliberately: **the quick fixes stay eager.** They are built
|
||||
from the buffer's own violations, which the server has already computed
|
||||
for the diagnostics; there is nothing to defer.
|
||||
|
||||
## §37.1 — how the offer stays local
|
||||
|
||||
`ports::offers` runs the engine's own `port_actions` over a source set built by
|
||||
`ports::offer_sources`:
|
||||
|
||||
1. **the buffer the request names**, from the open document (no read);
|
||||
2. **the declaring file of every module `port_action_modules` named**, via
|
||||
`vlog_refactor::module_definition(index, name)` — the same two steps
|
||||
`inlay.rs`'s `Plans::read` takes, and one file read at most.
|
||||
|
||||
A cursor on a **port declaration** names its own module, whose declaring file
|
||||
*is* the buffer, so that case reads nothing at all. A cursor on an
|
||||
**instantiation** names the instantiated module, and its declaration is what
|
||||
`propagate_ports` needs to know which connections are missing — so the offer
|
||||
is exact for that action, including its "connect N missing ports" count, which
|
||||
is a count of edits in the cursor's own file.
|
||||
|
||||
The edits `port_actions` computes over those one or two files are thrown away.
|
||||
Only the titles and the kind survive, plus `data`.
|
||||
|
||||
`ports::resolve` re-runs `ports::code_actions` — today's eager path, unchanged
|
||||
— at the offer's position and returns the action whose `key(title)` matches.
|
||||
|
||||
### Measured
|
||||
|
||||
This machine, 2026-09-04, release.
|
||||
|
||||
`cargo test --release -p lucisv_server perf::a_code_action -- --ignored
|
||||
--nocapture --test-threads=1` — the original probe (a port of a module
|
||||
instantiated in 3 of 504 files, 200 lines each), now with the offer column
|
||||
TODO §37.1 asked for:
|
||||
|
||||
| whole workspace | fan-out (eager) | **offer** | `sources()` alone |
|
||||
|---:|---:|---:|---:|
|
||||
| 776 ms | 433 µs | **58 µs** | 11.5 ms |
|
||||
|
||||
`cargo test --release -p lucisv_server --bin lucisv-server
|
||||
ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1` —
|
||||
200 noise modules plus `n` files instantiating `sub`, the shape §6a measured
|
||||
on opentitan:
|
||||
|
||||
| fan-out | cursor | eager | **offer** | actions |
|
||||
|---:|---|---:|---:|---:|
|
||||
| 3 | a port declaration | 485 µs | **68 µs** | 1 |
|
||||
| 3 | an instantiation | 172 µs | **72 µs** | 0 |
|
||||
| 40 | a port declaration | 4.84 ms | **53 µs** | 1 |
|
||||
| 40 | an instantiation | 1.45 ms | **55 µs** | 0 |
|
||||
| 128 | a port declaration | 15.0 ms | **53 µs** | 1 |
|
||||
| 128 | an instantiation | 4.60 ms | **55 µs** | 0 |
|
||||
|
||||
The eager column grows with the fan-out and the offer column does not: 53–72 µs
|
||||
at every size, both cursors (the two 3-file rows are the first measurements
|
||||
taken in the process and carry that much warm-up). The two "0 actions" rows are
|
||||
§6a's own complaint — a cursor on a fully-connected instantiation, where the old
|
||||
path spent its whole bill to offer nothing.
|
||||
|
||||
## §37.2 — the `inlayHint` zero at the default scope is correct
|
||||
|
||||
**Finding: not a bug. `performance_take2.md` §4b's last row compares a
|
||||
different question from every row above it.**
|
||||
|
||||
Every other row of that table asks about `aes` — `definition`, `hover`,
|
||||
`signatureHelp`, `references` on the `aes` instantiation in
|
||||
`hw/ip/aes/dv/tb/tb.sv`. `aes` is declared in `hw/ip/aes/rtl/aes.sv`, which the
|
||||
`didOpen` widen reaches: opening `hw/ip/aes/dv/tb/tb.sv` at the shipped
|
||||
`scopeDepth` of 2 raises to `hw/ip/aes`, 124 files. So those rows answer.
|
||||
|
||||
`inlayHint` cannot ask about `aes` at all: that instantiation's connections are
|
||||
**named** (`.clk_i(clk)`), and a named connection gets no hint by design — the
|
||||
reader can already see which port is which. The only positional connections in
|
||||
`tb.sv` are:
|
||||
|
||||
```systemverilog
|
||||
pins_if #($bits(lc_escalate)) lc_escalate_if (lc_escalate);
|
||||
pins_if #(1) idle_if (idle);
|
||||
```
|
||||
|
||||
Two positional parameter overrides and two positional port connections — **the
|
||||
4 hints the workspace scope returns**. `pins_if` is declared in
|
||||
`hw/dv/sv/common_ifs/pins_if.sv`; there is no `pins_if` anywhere under
|
||||
`hw/ip/aes` (checked). So at the default scope the module is genuinely not in
|
||||
the index, `vlog_refactor::module_definition` has nothing to answer with, and
|
||||
`Plans::read` declines — which is the documented contract: an instantiation
|
||||
whose module the index does not hold gets no hints, because guessing port names
|
||||
puts a wrong name on screen with no way for the reader to tell.
|
||||
|
||||
`inlay.rs` uses **the same lookup its neighbours use**. `signature.rs:28` and
|
||||
`completion`'s module-header tier call `vlog_refactor::module_definition` on the
|
||||
same index; hover and definition go through the same overlay. Asked about
|
||||
`pins_if` at the default scope, every one of them answers nothing too. There is
|
||||
no lookup inlay is missing.
|
||||
|
||||
Two tests pin it (`inlay.rs`), on an opentitan-shaped tree — `ip/aes/rtl`,
|
||||
`ip/aes/dv/tb`, and a `dv/common` beside the block:
|
||||
|
||||
- `the_default_scope_hints_a_module_the_didopen_widen_reached` — at the
|
||||
**default** scope (no `index.scope`, `scopeDepth` 2), the instantiation of the
|
||||
block's own module is hinted. The default scope hints; §4b's row is not
|
||||
evidence that it does not.
|
||||
- `an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined` — the
|
||||
instantiation of the module outside the block gets no hints, **and**
|
||||
`textDocument/definition` and hover give nothing for it either; widening to
|
||||
the workspace scope makes all three answer.
|
||||
|
||||
For the lead: if the wanted behaviour is that a hint pulls its module's
|
||||
declaration in from outside the scope, that is a *scope* change (the widen
|
||||
would have to follow instantiation edges), and it would change what
|
||||
`definition`, `hover` and `completion` answer at the same time. It is not an
|
||||
inlay-hint fix, and it is not what this round did.
|
||||
|
||||
## §37.3 — `locate::definition_location`
|
||||
|
||||
`Def::lines.positions` holds `{name, decl}` as `Utf16Range`s, converted through
|
||||
the declaring file's own `LineIndex::utf16_position` while it was indexed —
|
||||
which is the very converter `convert::Positions` uses on the wire, so the two
|
||||
cannot disagree. `locate::definition_location(ws, path, def)` returns the name's
|
||||
range straight from there when the file has no open buffer, and falls through to
|
||||
`locate::location`'s read otherwise (an open buffer, or a member, which records
|
||||
no positions).
|
||||
|
||||
Routed through: `nav::definition`'s `Definition::External` arm and
|
||||
`symbols::workspace_symbols`. `nav`'s `` `define`` arm keeps the read — a
|
||||
`DefineTable` entry is not a `Def` and has no recorded positions.
|
||||
|
||||
### Pins
|
||||
|
||||
- `locate::tests::the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom` —
|
||||
one file with a BOM at offset 0, CRLF endings, two- and three-byte
|
||||
characters and an astral character that is two UTF-16 code units; the
|
||||
index-only `Location` equals the file-read one exactly.
|
||||
- `locate::tests::a_file_scope_definition_is_located_without_reading_its_file`
|
||||
and `nav::tests::a_cross_file_definition_reads_no_file` — asserted through
|
||||
`Workspace::held_views()`, the view cache a read would land in. Empty after
|
||||
the definition and after a `workspace/symbol`; one entry after the same
|
||||
question is asked the old way.
|
||||
- `locate::tests::a_member_keeps_the_file_read_path` — a port records no
|
||||
positions and still answers, through the read.
|
||||
- `locate::tests::an_open_buffer_still_answers_from_the_buffer`.
|
||||
|
||||
### Measured, over opentitan, read-only
|
||||
|
||||
`LUCISV_PERF_CORPUS=/Users/guoliangchen/repo/opentitan cargo test --release -p
|
||||
lucisv_server --bin lucisv-server locate::tests::defining -- --ignored
|
||||
--nocapture --test-threads=1`, 3 976 indexed files, 200 targets (modules the
|
||||
corpus instantiates, each in a different file):
|
||||
|
||||
| | total, 200 definitions | per definition |
|
||||
|---|---:|---:|
|
||||
| file-read (before) | 5.54 ms | 27.7 µs |
|
||||
| index-only (after) | 80.5 µs | **0.40 µs** |
|
||||
|
||||
69× on the conversion, and it is the whole of what a cross-file
|
||||
`textDocument/definition` into a closed file was doing besides the lookup.
|
||||
`git -C ~/repo/opentitan status --porcelain` unchanged after the run.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev agent (Opus)
|
||||
|
||||
- Read `CLAUDE.md`, TODO §37 and the §10 lines it closes,
|
||||
`docs/performance_take2.md` §4b/§6a/§7/§8, and the code each item names.
|
||||
- **§37.3 first** (smallest, independent). `locate::definition_location` plus
|
||||
`locate::range`; `state.rs` gained `held_views()` (`#[cfg(test)]`,
|
||||
`pub(crate)`) so a test can assert that no file was read. Routed
|
||||
`nav::definition` and `symbols::workspace_symbols` through it. Four tests in
|
||||
`locate.rs` (new test module) and one in `nav.rs`.
|
||||
- Deviation from the plan's expectation, recorded: the plan said "no
|
||||
`file_view` created for a file-scope definition"; the assertion is through
|
||||
`Workspace::held_views()`, a new test-only accessor, rather than a
|
||||
counter — the cache *is* the counter, and it is already what `state.rs`'s
|
||||
own tests assert against.
|
||||
- One thing the plan did not anticipate: an **open buffer** must keep the
|
||||
file-read path. Its `Def` spans are the disk file's until the next
|
||||
re-index, and converting them against the buffer's current text is what
|
||||
every other answer about that buffer does. Pinned by
|
||||
`an_open_buffer_still_answers_from_the_buffer`, which asserts the
|
||||
(pre-existing, unchanged) stale-span behaviour rather than pretending this
|
||||
round fixed it.
|
||||
- **§37.2 second.** Investigated by reading `hw/ip/aes/dv/tb/tb.sv` and
|
||||
locating `pins_if` in the opentitan checkout (read-only, `find`/`ls` only).
|
||||
The zero is correct; the finding is written above, with two tests. No
|
||||
production code changed for this item.
|
||||
- **§37.1 last.** `ports::offers`, `ports::offer_sources`, `ports::resolve`,
|
||||
`ports::key`, `ports::counted`, `ports::instances_of`,
|
||||
`ports::declared_twice`; `ClientAbilities::code_action_resolve`;
|
||||
`code_action_resolve_support` in `main.rs`; `resolve_provider: Some(true)`;
|
||||
the dispatch branch and the `codeAction/resolve` arm.
|
||||
- **Deviation, flagged:** `vlog_refactor::ports::sites_phrase` was made
|
||||
`pub` and re-exported. The plan allowed a change to
|
||||
`crates/vlog_refactor/src/ports/mod.rs` "only if the offer needs a new
|
||||
one-file question", and this is not one — it is the alternative to writing
|
||||
a second spelling of a user-visible sentence in the server and letting the
|
||||
two drift. No behaviour changed in `vlog_refactor`.
|
||||
- **Deviation, flagged:** the plan said resolve returns "the action whose
|
||||
title matches". Exact title matching cannot work, because the offer's
|
||||
count comes from the index and the eager count from the plan, and the
|
||||
plan's own §37.1 requires the unsaved-buffer case (index 3, plan 4) to
|
||||
resolve. Matching is therefore on `key(title)` — the title with its
|
||||
trailing ` (…)` count phrase removed. An escaped identifier cannot contain
|
||||
a space, so `" ("` never occurs inside a port name; `a_title_keys_on_
|
||||
everything_but_its_count` pins it.
|
||||
- **Deviation, flagged:** `resolve` returns an action that already carries an
|
||||
`edit` unchanged instead of refusing it. A client that declares
|
||||
`resolveSupport` may resolve anything it was offered, including the quick
|
||||
fixes, and refusing those would break fix-on-save for exactly the clients
|
||||
this feature is for.
|
||||
- `resolve` refuses a large-file buffer, because the fast path's own gate
|
||||
cannot see a request whose params are a `CodeAction`. Found by reading
|
||||
`server/large_file.rs`'s `document_uri`, not by a test failing; pinned by
|
||||
`a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused`.
|
||||
- The existing eager pin `an_unsaved_buffer_contributes_the_instantiation_
|
||||
the_index_has_not_seen` was **kept** rather than moved: the eager path is
|
||||
still live code for a client without `resolveSupport`. Its lazy sibling
|
||||
`the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count` is the
|
||||
moved pin.
|
||||
- **The two new perf probes live beside the code they measure**, not in
|
||||
`perf.rs`: `perf.rs` is already the one file over the size rule with a
|
||||
written reason (895 production lines, `docs/features/decomposition-server`),
|
||||
and `perf::mean` is `pub(crate)` precisely so a probe can sit next to its
|
||||
subject — `nav.rs`'s references probes already do. `perf.rs` grew by the
|
||||
five lines of the offer column and nothing else (900 lines).
|
||||
- Files touched outside the plan's expected set: **none**
|
||||
(`crates/vlog_refactor/src/lib.rs` for the re-export is the only file not
|
||||
named in it; `crates/vlog_refactor/src/ports/mod.rs` was named).
|
||||
|
||||
## Gates (dev, guarded, 2026-09-04)
|
||||
|
||||
- `cargo fmt -p lucisv_server`, `cargo fmt -p vlog_refactor` — clean
|
||||
(`--check` verified).
|
||||
- `cargo clippy --all-targets` — clean, no new `#[allow]`.
|
||||
- `tools/guard.sh -- cargo test --workspace` — **3 734 passed, 0 failed,
|
||||
44 ignored** (the ignored are the perf probes).
|
||||
- `tools/guard.sh -- tools/corpus_check.sh` — **814/820 (99.3 %)**, the same
|
||||
six failures, `verification-error: none`, `crash: none`.
|
||||
- `cargo build --release -p lucisv_server` then `tools/guard.sh -- node
|
||||
editors/vscode/smoke.js target/release/lucisv-server` — OK, 20 messages.
|
||||
- No guard kill at any point. `git -C ~/repo/opentitan status --porcelain`
|
||||
after every opentitan read: the same three pre-existing modifications
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, both `ast.sv`), nothing else.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent (Sonnet)
|
||||
|
||||
Read `CLAUDE.md`, TODO §37, the dev's account above in full (Goal, Assumptions,
|
||||
Handshakes, work log — all five flagged deviations), then the diffs of every
|
||||
touched file. Attacked the three items over the real code, not just the
|
||||
dev's own tests; every scratch test below was added as a temporary `#[test]`,
|
||||
run, and removed before this log was written (`git diff --stat` after cleanup
|
||||
is byte-identical to the dev's own: 15 modified + this README).
|
||||
|
||||
**§37.1 — lazy `codeAction`/`resolve`.**
|
||||
|
||||
- Malformed `data` (scratch test in `ports.rs`): a wrong-typed `uri` (a JSON
|
||||
number) fails to deserialize into `Offer` → `NOT_OURS`; a well-formed `data`
|
||||
naming a document **never opened at all** (distinct from one that was open
|
||||
and closed) → `GONE`; a `position` far past EOF → `Positions::offset` clamps
|
||||
to the text length (confirmed by reading `convert.rs:44-59`) rather than
|
||||
panicking, `code_actions` at the clamped offset finds nothing, → `GONE`. No
|
||||
panic in any case.
|
||||
- A closed document and a document whose port has since been removed: both
|
||||
already pinned by the dev's `a_resolve_of_an_action_the_buffer_no_longer_
|
||||
carries_is_refused`; reproduced by re-running it directly.
|
||||
- The unsaved-buffer "different count" case (index says 3, buffer really has
|
||||
4): the dev's `the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_
|
||||
see` is exactly this attack — re-run, still resolves with the corrected
|
||||
title and the wider edit.
|
||||
- A quick-fix action passed to `resolve`: `code_action.rs`'s `quick_fix`
|
||||
(line ~76) always sets `edit: Some(...)`, so it always takes `resolve`'s
|
||||
first branch (`action.edit.is_some()` → returned unchanged) regardless of
|
||||
origin — confirmed by reading the function rather than by a redundant
|
||||
integration test, since the logic path is identical to the dev's own
|
||||
synthetic "complete" case in `a_resolve_of_something_this_server_never_
|
||||
offered_says_so`.
|
||||
- Title-key matching with an escaped identifier containing `(` and no interior
|
||||
space (`\rst(a)`, IEEE 1800-2017 §5.6.1 — an escaped identifier ends at
|
||||
whitespace): built a real module with this port name, instantiated it in
|
||||
three files, and drove the actual engine (not a hand-built title) through
|
||||
`offered`/`code_actions`/`resolve`. The offer's menu matched the eager
|
||||
menu, the title genuinely carried the literal `` `\rst(a)` `` including the
|
||||
paren, and `key()` still isolated the trailing count phrase correctly — the
|
||||
dev's reasoning in the comment on `key` holds under an adversarial name.
|
||||
(One test-authoring pitfall found and fixed on my own scratch test, not a
|
||||
product bug: `ports.rs`'s pre-existing `qa_escaped_module_name_
|
||||
instantiation_parity_with_whole_workspace` also builds a `Tree::new(
|
||||
"qa_escaped")`, and reusing that same name in my own scratch test raced the
|
||||
two tests over the same temp directory under parallel `cargo test`
|
||||
execution, producing spurious failures in both. Renamed my scratch tree and
|
||||
the collision was gone on repeated runs. `Tree::new` keys its temp directory
|
||||
on the string name alone with no per-test-function salt, which is a latent
|
||||
hazard for the *next* test added under the same name — not something this
|
||||
feature's diff introduced or should fix, flagging it here rather than in
|
||||
the diff.)
|
||||
- Capability gate over the wire (scratch test in `tests/e2e.rs`, two shapes in
|
||||
one loop): `resolveSupport` present but its `properties` list `["documentation"]`
|
||||
(no `"edit"`), and `capabilities: {}` with no `codeAction` key at all. Both
|
||||
got the eager shape — `data` null, `edit` inline with the real
|
||||
`WorkspaceEdit` — over an actual `initialize` → `didOpen` →
|
||||
`textDocument/codeAction` session, not just the unit test of
|
||||
`code_action_resolve_support` in isolation.
|
||||
- Large-file mode: confirmed by reading `server/large_file.rs`'s
|
||||
`document_uri` (`params.get("textDocument")?...`) — a `codeAction/resolve`
|
||||
request's params are a bare `CodeAction`, which has no `textDocument` key,
|
||||
so `large_file_answer` returns `None` unconditionally for this method and
|
||||
the request falls through to `dispatch.rs`'s normal arm, where `ports::
|
||||
resolve`'s own `.filter(|doc| !doc.large)` refuses it. Re-ran the dev's
|
||||
`a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused` — passes,
|
||||
no panic.
|
||||
- Cost/timing, re-derived independently over the wire against the real
|
||||
opentitan checkout (confirmed still 128 files instantiate `prim_flop_2sync`
|
||||
today via `grep`), read-only throughout:
|
||||
- Built `lucisv-server` v0.40.0 in a scratch worktree
|
||||
(`git worktree add /private/tmp/.../scratchpad/base v0.40.0`, `cargo build
|
||||
--release -p lucisv_server`, then `git worktree remove` — the one git
|
||||
command used outside status/diff), and wrote a small throwaway Node driver
|
||||
(`scratchpad/time_code_action.js`, modeled on `editors/vscode/smoke.js`'s
|
||||
framing) to time a real `textDocument/codeAction` at the
|
||||
`prim_flop_2sync` instantiation in `hw/ip/aon_timer/rtl/aon_timer.sv`,
|
||||
workspace-scoped via `initializationOptions.lucisv.index.scope`.
|
||||
- v0.40.0 server, eager (no `resolveSupport`): 76.4 / 76.4 / 77.8 ms repeats.
|
||||
- This branch's server, eager (no `resolveSupport`): 77.3 / 76.2 / 77.7 ms
|
||||
repeats — statistically identical to v0.40.0, confirming no regression for
|
||||
a client that cannot resolve.
|
||||
- This branch's server, **offer** (`resolveSupport: ["edit"]`): 4.76 / 4.38
|
||||
/ 4.25 ms repeats — about **16× faster**, both with 0 actions returned
|
||||
(the same "worst case: full cost, nothing offered" shape §6a complained
|
||||
about).
|
||||
- Also re-ran the dev's own ignored perf probe
|
||||
(`ports::tests::the_offer_is_flat_where_the_eager_answer_grows`) directly:
|
||||
eager 656 µs–15.6 ms across 3/40/128 fan-out, offer 55–78 µs flat — closely
|
||||
matches the table in this README (§37.1 "Measured").
|
||||
- **Note, not a finding against this feature:** my repeat numbers (~76 ms
|
||||
eager) are well under `performance_take2.md` §6a's originally recorded
|
||||
184.9–186.2 ms for this exact shape. Both old and new servers agree with
|
||||
each other on *this* machine, so it reads as a machine/measurement-harness
|
||||
difference from whatever produced §6a's numbers, not a regression — the
|
||||
relative number this feature is judged on (offer vs. eager, same server,
|
||||
same request) is the clean ~16× and it holds.
|
||||
- `offer_sources`'s read set: re-ran the dev's `the_offer_reads_the_buffer_
|
||||
and_at_most_the_declaring_file` — one file at a port declaration, the buffer
|
||||
plus the declaring file (never the instantiating tops or noise files) at an
|
||||
instantiation.
|
||||
|
||||
**§37.2 — the `inlayHint` zero at the default scope.**
|
||||
|
||||
- Verified the finding independently against the **real** opentitan checkout,
|
||||
read-only: `find . -iname pins_if.sv` → exactly one hit,
|
||||
`hw/dv/sv/common_ifs/pins_if.sv`, confirmed outside `hw/ip/aes` entirely (a
|
||||
sibling library folder the default scope's raise-to-`hw/ip/aes` widen does
|
||||
not reach).
|
||||
- Wrote a scratch, `#[ignore]`d test in `inlay.rs` (guarded, read-only) that
|
||||
opens the real `hw/ip/aes/dv/tb/tb.sv` at the shipped default scope and
|
||||
asserts: the widen reached files under `hw/ip/aes` but none under
|
||||
`common_ifs`; `nav::definition`, `hover::hover` and `inlay_hints` all answer
|
||||
nothing about the `pins_if` instantiation. All three held. Agree with the
|
||||
dev's finding: this is a scope-reach question, not an inlay-hint bug, and
|
||||
every neighbour using the same `module_definition` lookup is equally blind
|
||||
to it at this scope.
|
||||
- `git -C ~/repo/opentitan status --porcelain` unchanged after every read
|
||||
(the same three pre-existing modifications).
|
||||
|
||||
**§37.3 — `locate::definition_location` index-only path.**
|
||||
|
||||
- Re-ran every pin in `locate.rs` and `nav.rs`; all pass.
|
||||
- Extra encoding attacks beyond the dev's own (BOM, CRLF, multi-byte, astral):
|
||||
a **tab-indented** declaration, and a declaration **after a lone `\r`**
|
||||
(old-Mac line ending, not `\n`) — both agree between the index-only and
|
||||
file-read paths exactly. (First attempt at the lone-`\r` case put it inside
|
||||
a line comment and found zero declarations at all: `lexer.rs`'s line-comment
|
||||
scanner runs to the next `\n` only, so a bare `\r` inside a comment does not
|
||||
end it and the intended module got swallowed into the comment text — a
|
||||
pre-existing, unrelated lexer property, not a locate.rs bug. Moved the `\r`
|
||||
outside the comment and the equality attack ran as intended.)
|
||||
- An open buffer with an edit above the definition still answers from the
|
||||
buffer's own current text, confirmed via the dev's `an_open_buffer_still_
|
||||
answers_from_the_buffer` (re-run) plus reasoning: `ws.document_for_path`
|
||||
gates the index-only branch off whenever a buffer is open, whatever the
|
||||
index recorded.
|
||||
- `held_views()` is `#[cfg(test)]` — grep and the diff both confirm no
|
||||
production caller; it cannot be reached outside a test build.
|
||||
- Timing re-derived independently, read-only, over the real opentitan
|
||||
checkout (3 976 indexed files, 200 targets): **index-only 390 ns/definition,
|
||||
file-read 27.9 µs/definition** — matches the README's 0.40 µs / 27.7 µs
|
||||
claim within run-to-run noise, same ~69–71× ratio.
|
||||
`git -C ~/repo/opentitan status --porcelain` unchanged.
|
||||
|
||||
**Gates, re-run myself, guarded:**
|
||||
|
||||
- `cargo clippy --all-targets` — clean, no warnings (checked both with and
|
||||
without my scratch tests present).
|
||||
- `tools/guard.sh -- cargo test --workspace` — **3 734 passed, 0 failed, 44
|
||||
ignored**, matching the dev's own gate exactly. No guard kill.
|
||||
- `tools/guard.sh -- tools/corpus_check.sh` — **814/820 (99.3%)**, the same
|
||||
six failures, `verification-error: none`, `crash: none`.
|
||||
- `tools/guard.sh -- node editors/vscode/smoke.js target/release/lucisv-server`
|
||||
— OK, 20 messages.
|
||||
- `git -C ~/repo/opentitan status --porcelain` after every opentitan read,
|
||||
throughout the session: unchanged, the same three pre-existing
|
||||
modifications every time.
|
||||
- Scratch worktree at `/private/tmp/.../scratchpad/base` (v0.40.0) removed
|
||||
with `git worktree remove` after use; `git worktree list` shows only the
|
||||
main tree.
|
||||
|
||||
**Findings.** None at HIGH or MEDIUM severity. Two LOW, informational, neither
|
||||
in this feature's own diff:
|
||||
- LOW — `ports.rs`'s test-scratch `Tree::new` keys its temp directory on the
|
||||
caller-supplied string alone, with no per-test salt; two tests choosing the
|
||||
same name race under parallel execution (reproduced against the pre-existing
|
||||
`qa_escaped_module_name_instantiation_parity_with_whole_workspace`). Not
|
||||
part of this diff and not blocking; worth a name-collision guard (e.g.
|
||||
salt with the test's `#[test]` function name) if it bites again.
|
||||
- LOW — the offer/eager repeat-timing numbers measured this session (~76 ms
|
||||
eager, ~4.5 ms offer, both machines) are well under `performance_take2.md`
|
||||
§6a's recorded 184.9–186.2 ms for the identical 128-file-fan-out shape;
|
||||
old and new servers agree with each other on this machine, so it reads as
|
||||
environment drift from whatever produced §6a's numbers rather than a
|
||||
regression this feature introduced. Recorded for whoever next revisits
|
||||
§6a's absolute numbers.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted; ships in 0.41.0. 37.1 is the shape §10
|
||||
asked for and the numbers say why: the offer is flat (53–68 µs from a
|
||||
3-file to a 128-file fan-out, on both cursor shapes) where the eager path
|
||||
is linear, and over the wire on opentitan's worst case QA measured the
|
||||
offer at ~4.5 ms against ~77 ms eager — the cursor-move request is off the
|
||||
fan-out. The dev's five deviations are all right: matching on the title's
|
||||
key rather than the exact title is forced by the plan's own unsaved-buffer
|
||||
requirement, and the escaped-identifier attack (`\rst(a)`) shows the key
|
||||
holds; refusing a resolve on a large buffer closes a gate the fast path's
|
||||
URI check cannot see; keeping the eager unsaved-buffer pin beside its
|
||||
lazy sibling is correct because the eager path is still live for clients
|
||||
that cannot resolve. 37.2 is ruled as the dev framed it: the zero is
|
||||
correct — `pins_if` is declared outside what the default scope reaches
|
||||
from `tb.sv`, definition and hover answer nothing there either, and QA
|
||||
confirmed it on the real tree — so this is a *scope* question, not an
|
||||
inlay defect, and the §10 line is closed as investigated. 37.3 is a pure
|
||||
fast path (index-only Location equal to the file-read one over every
|
||||
encoding shape QA and the dev tried, 69× cheaper, no view created), with
|
||||
the honest exclusion of open buffers whose indexed spans may be stale.
|
||||
QA's two LOWs are noted, not actioned: `Tree::new` takes a per-test name
|
||||
and the existing names are distinct, and §6a's absolute numbers were
|
||||
measured on a different day's machine state — both servers agree with
|
||||
each other here, which is what the comparison needed.
|
||||
@@ -188,7 +188,13 @@ code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptio
|
||||
|
||||
`Options` rather than `Simple(true)` on purpose: a client that filters by kind
|
||||
(which is how fix-on-save is configured) has to be told which kinds exist.
|
||||
`resolve_provider` is `None` because every action is returned complete.
|
||||
`resolve_provider` was `None` because every action was returned complete;
|
||||
since TODO §37.1 it is `Some(true)` and a third kind
|
||||
(`refactor.rewrite.lucisv.ports`) is listed. The quick fixes above are
|
||||
unaffected — the actions that are now offered without their edits are the port
|
||||
refactorings, and only to a client that declared
|
||||
`textDocument.codeAction.resolveSupport.properties: ["edit"]`. See
|
||||
`docs/features/lazy-code-action/README.md`.
|
||||
|
||||
**Still deliberately not advertised**, unchanged by this round and absent from
|
||||
the initialize result rather than present-and-false: `rangeFormatting` (waits on
|
||||
@@ -227,8 +233,15 @@ TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file
|
||||
- [x] ~~**Not done:** fence-aware fixes (Handshake 3) — a quick fix can edit
|
||||
inside a `// verilog_format: off` region, where `lucisv check --fix` would
|
||||
not.~~ Delivered by **shared-fence-filter** (round 14).
|
||||
- [ ] **Not done:** `codeAction/resolve`. Every action is cheap to build in
|
||||
full; lazy resolution is a payload optimization for actions that are not.
|
||||
- [x] ~~**Not done:** `codeAction/resolve`. Every action is cheap to build in
|
||||
full; lazy resolution is a payload optimization for actions that are
|
||||
not.~~ Delivered by **lazy-code-action** (TODO §37.1), and the note was
|
||||
right about *these* actions: the quick fixes and `source.fixAll.lucisv`
|
||||
are still returned complete. What is now lazy is the **port
|
||||
refactorings**, whose offer used to compute the whole cross-file edit —
|
||||
185–201 ms at a 128-file fan-out, on every cursor move. `resolve` hands
|
||||
an action that already carries its edit straight back, so a client that
|
||||
resolves everything it was offered still gets these unchanged.
|
||||
- [x] ~~**Not done:** sharing one parse with the linter (Handshake 1).~~
|
||||
Delivered by **one-parse** (round 19).
|
||||
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
# small items, round 3
|
||||
|
||||
## Goal
|
||||
|
||||
Three items that do not belong to any larger feature, shipped together
|
||||
(TODO §36, release 0.40.0).
|
||||
|
||||
**36.1 — a bare `begin … end` where an item belongs is recovered, not
|
||||
refused.** `begin` is not a module item (IEEE 1800 §23.2.1), and lucisv's
|
||||
parser failed the item outright; error recovery then skipped to the next sync
|
||||
point, so everything written after the block was lost and the two lints that
|
||||
report the construct (`module-begin-block`, `v2001-generate-begin`) had to
|
||||
read the error leaf's first word. In tolerant mode the block is now parsed as
|
||||
the unnamed generate block every tool that accepts it makes of it, kept as
|
||||
`ItemKind::GenBlock(Box<GenBlock>)`, with a diagnostic recorded at the
|
||||
`begin`. Strict mode is untouched, so nothing about a file that parses
|
||||
changes. topo §2.9-25.
|
||||
|
||||
**36.2 — a half-typed `.NAME(` no longer swallows the next instance.** In
|
||||
`sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x), .b(y));` nothing inside the override
|
||||
list fails: `u0 (.a(x), .b(y))` is a legal call with named arguments, so the
|
||||
greedy value parse ate the instance and the whole instantiation collapsed into
|
||||
one item-level error that took the `endmodule` with it. This was the MEDIUM
|
||||
finding in the header-recovery QA log of 2026-09-02. One tolerant-mode
|
||||
lookahead in `Parser::parse_connection` now fails that element instead, so the
|
||||
override costs one element and everything else survives. topo §2.9-24.
|
||||
|
||||
**36.3 — in-place writes are atomic.** `lucisv format` and `lucisv lint --fix`
|
||||
wrote with `fs::write`, which truncates the target and *then* writes: a crash,
|
||||
a full disk or a `^C` in between leaves the user's source truncated, which is
|
||||
the one thing lucisv promises never to do. `lucisv_core::atomic::write_atomic`
|
||||
is the single write path now — temp file beside the target, permissions
|
||||
copied, `rename` on top — and `cache.rs`'s hand-rolled copy of the same dance
|
||||
is gone. A §1 backlog item, QA find of 2026-08-25.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **36.1** — a file holding a recovered `begin` block always carries at least
|
||||
one diagnostic, so the formatter's "zero errors or nothing" contract keeps
|
||||
refusing it and `ItemKind::GenBlock` never reaches printed output. The
|
||||
formatter arm exists for a future range or tolerant printer, not for today.
|
||||
- **36.1** — the block's scope shape is an unlabeled generate block's. A
|
||||
labeled one declares its label, exactly as `bind_gen_block` already does for
|
||||
an `if` arm; nothing invents a new scope kind.
|
||||
- **36.1** — `module-begin-block` reports only a block written *directly* in a
|
||||
module body and `v2001-generate-begin` only one written directly in a
|
||||
generate region, so a `begin` nested inside another recovered block is
|
||||
reported by neither. That was true before this round too (the whole nest was
|
||||
one error leaf whose first word was the outer `begin`); it is now pinned by
|
||||
`only_the_outermost_block_of_a_nest_is_reported_at_module_scope`.
|
||||
- **36.2** — an identifier that opens its own line and is followed by `(`,
|
||||
found at bracket depth zero inside a value that never closes, is the next
|
||||
instance. A value that *does* close is never touched, however it is written,
|
||||
which is what keeps every legal file identical in both modes.
|
||||
- **36.2** — when the parentheses balance the shape is genuinely ambiguous
|
||||
(`sub #(.D(` ⏎ `u0 (.a(x)));`), and the greedy parse still wins. Pinned as a
|
||||
test so it is not "fixed" later.
|
||||
- **36.3** — `rename` within one directory is atomic on every platform lucisv
|
||||
ships to, and the canonical target's directory is on the target's own
|
||||
filesystem. Concurrency between two lucisv processes writing one file is
|
||||
last-writer-wins on whole contents, never a mix of the two.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser` → everyone**: `ItemKind` gained the variant
|
||||
`GenBlock(Box<GenBlock>)`. Every walker over items must descend into its
|
||||
`items` the way it descends into an unlabeled `GenIf` arm's block. Done in
|
||||
this round for `vlog_formatter` (`format/item.rs`, `fence.rs`),
|
||||
`vlog_semantic` (`bind/item.rs`, `instantiations.rs`), `vlog_refactor`
|
||||
(`ports/find.rs`), `vlog_linter` (`visit.rs` ×2, `signals.rs`,
|
||||
`module_decls.rs`) and `lucisv_server` (`linked.rs`, `selection.rs`,
|
||||
`type_def.rs`), plus the four test walkers in `crates/vlog_parser/tests`.
|
||||
Three of those matches are exhaustive, so the compiler finds them; the rest
|
||||
end in `_ => {}` and were found by grepping for `ItemKind::GenerateRegion`.
|
||||
- **`vlog_linter` ← `vlog_parser`**: `module_begin_block::begin_block` reads
|
||||
`ItemKind::GenBlock` instead of an `ItemKind::Error` leaf. It stays the one
|
||||
reading both rules share.
|
||||
- **`lucisv_core` → `lucisv`**: new `lucisv_core::atomic::write_atomic`. Any
|
||||
future in-place write goes through it rather than `fs::write`. No new
|
||||
dependency: `std::fs` only.
|
||||
- **`vlog_parser` internals**: `recover.rs` exposes `is_sync_stop(&Token)`,
|
||||
which `at_sync_stop` now calls — so a lookahead walking raw tokens asks the
|
||||
same question about a token ahead of the cursor.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 36.1 `ItemKind::GenBlock`, the `begin` arm, all consumers, the two rules
|
||||
- [x] 36.2 the `value_runs_into_next_instance` lookahead and its four tests
|
||||
- [x] 36.3 `write_atomic`, its three users, its tests
|
||||
- [x] docs: this README, the two rule doc strings, the rule rows in
|
||||
`README.md` and `docs/site/.../rules.md`, the header-recovery work-log
|
||||
line
|
||||
- [x] Gates (guarded): `cargo fmt -p` per touched crate, `cargo clippy
|
||||
--all-targets`, `cargo test --workspace`, corpus check
|
||||
- [ ] QA
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev agent
|
||||
|
||||
**36.1.** `ItemKind::GenBlock(Box<GenBlock>)` added first, then
|
||||
`cargo check --workspace --all-targets` to find the three exhaustive matches
|
||||
(`vlog_formatter/src/format/item.rs`, `vlog_semantic/src/bind/item.rs`,
|
||||
`crates/vlog_parser/tests/spans.rs`) and a grep for
|
||||
`ItemKind::GenerateRegion` to find the rest. Every arm is the boring one:
|
||||
walk `items`. Boxed, so `ast::size_pins` does not move — it still passes
|
||||
untouched.
|
||||
|
||||
The parser arm is `"begin" if self.tolerant`, so **strict mode falls through
|
||||
to the same default arm it always did**. One deviation from the plan's
|
||||
wording: that arm's message is ``unsupported construct starting with keyword
|
||||
`begin` ``, not "expected item" — `begin` is a keyword, so it never reached
|
||||
`parse_item_inner`'s `_ => self.error("expected item")`. Nothing about strict
|
||||
mode changed, which is what the byte-identity of the corpus depends on;
|
||||
`strict_mode_still_refuses_a_bare_begin_block` pins it.
|
||||
|
||||
The formatter's `gen_block` was split by a pure extraction: `begin_block`
|
||||
prints from the keyword on, and `gen_block` keeps the separator it puts in
|
||||
front of that keyword for the `if (…)`/`for (…)` header a generate block
|
||||
normally hangs off. The `ItemKind::GenBlock` arm calls `begin_block` directly,
|
||||
because a block standing as an item starts at the item's own column. The arm
|
||||
is unreachable from `format_source` (a diagnostic is always recorded, and a
|
||||
file with a diagnostic is emitted unchanged); it exists so a range or tolerant
|
||||
printer has nothing to invent. `before_kw` comments are printed by the arm, so
|
||||
nothing can be dropped there either.
|
||||
|
||||
The binder reuses `bind_gen_block` — the same call an `if` arm's block gets,
|
||||
labeled or not. No new scope kind.
|
||||
|
||||
**Finding: a new nesting family, and one test outside the plan's file set.**
|
||||
Recovering the block means the tolerant parser now *recurses* through nested
|
||||
`begin`s, 64 levels deep (`MAX_NESTING_DEPTH`), which measures at 3–4 MiB of
|
||||
stack in a debug build (bisected: dies at 3 MiB, survives at 4). That is well
|
||||
inside `PARSE_STACK_SIZE` (32 MiB) and under the ~9.7 MiB worst case
|
||||
`docs/features/recursion-limit/README.md` records, so no constant moves. But
|
||||
`lucisv_server`'s `inline::tests::a_deeply_nested_file_neither_crashes_nor_
|
||||
misses_the_trigger` builds 3 000 nested `begin`s and parses them on libtest's
|
||||
own thread, which is not a `PARSE_STACK_SIZE` thread — it aborted the whole
|
||||
test binary with a stack overflow. Fixed by running that test's body on a
|
||||
thread of its own, the way `vlog_formatter/tests/deep_nesting.rs` and
|
||||
`crates/lucisv/tests/cli.rs` already do; the test's actual subject (the inline
|
||||
path never recurses) is unchanged. **`crates/lucisv_server/src/inline.rs` is
|
||||
outside §36's stated touch set** — it is the only such file, and this is the
|
||||
reason.
|
||||
|
||||
**36.2.** `Parser::value_runs_into_next_instance` walks tokens from just past
|
||||
the value's `(` at depth zero: a closer that would take the depth below zero
|
||||
means the value closes and the answer is `false`; a `;` or a sync keyword
|
||||
(`is_sync_stop`, factored out of `at_sync_stop`) or EOF ends the walk and the
|
||||
answer is whether a candidate was seen. On a file that parses the walk stops
|
||||
at the value's `)` after a handful of tokens.
|
||||
|
||||
**Deviation, and the one thing the plan left to verify.** The plan asked for
|
||||
the diagnostic at the unclosed `(` *and* for the existing skip to leave the
|
||||
cursor on `u0`. Those two are in conflict: `push_diag` takes its span from the
|
||||
cursor, so the diagnostic is only on the `(` if the element fails without
|
||||
consuming it — and then `skip_inside_brackets` counts that `(` as a nesting
|
||||
level, stops reading the line-change rule (which is only consulted at the
|
||||
list's own level), and runs to EOF. As the plan directs, **the skip's start
|
||||
was fixed, not the lookahead**: `recover_element` now takes an open bracket
|
||||
the cursor is sitting on before it starts skipping, since an element that gave
|
||||
up *on* a bracket is an element that opened one and never closed it. That is
|
||||
one `else if` in `recover_element`; no existing test moved.
|
||||
|
||||
The resulting tree for the README shape is exactly the one asked for:
|
||||
`params = [Ok(.WIDTH(8)), Error(".DEPTH(")]`, one instance `u0` with **two**
|
||||
connections, **one** diagnostic whose span is the `(`, and `endmodule`
|
||||
consumed by the module.
|
||||
|
||||
Second deviation, in the connection-list twin (`sub u0 (.a(` ⏎
|
||||
`u1 (.b(y));`): the plan expected `u1` to become a **second instance**. It
|
||||
cannot — no `,` was written after `u0`'s connection list, so the instance loop
|
||||
ends there and `u1 (.b(y));` is read as the next *item* of the module. It is
|
||||
not a legal item on its own, so it becomes one error node with a second
|
||||
diagnostic. That is still the win the item is about: before, `u1` was
|
||||
swallowed into `.a(`'s value and the module lost its `endmodule`. Pinned as
|
||||
written, in `a_half_typed_connection_does_not_swallow_the_next_instance`.
|
||||
|
||||
**36.3.** `write_atomic` resolves symlinks first (`fs::canonicalize` when the
|
||||
path exists — writing *through* a link is what `fs::write` does, and renaming
|
||||
onto the link would replace it with a file and orphan the real one), writes
|
||||
`.{name}.{pid}.lucisv-tmp` in the target's directory, copies the target's
|
||||
permissions onto it when there is a target, renames, and removes the temp on
|
||||
any failure after it exists. `std::fs` only, no dependency. `cache.rs::store`
|
||||
lost its inline copy; `main.rs`'s `process_file` and `lint.rs`'s `--fix` call
|
||||
it. One small fix beside it: `cache.rs`'s `no_temporary_file_is_left_behind`
|
||||
filtered for names ending in `.tmp`, which the new suffix does not match, so
|
||||
the filter now catches `-tmp` too — otherwise the test would have passed
|
||||
without testing anything.
|
||||
|
||||
**Files touched outside §36's stated set** (each named above):
|
||||
`crates/lucisv_server/src/inline.rs` (the stack-size finding),
|
||||
`crates/vlog_parser/tests/{spans.rs,census.rs,null_items.rs}` (walkers the new
|
||||
variant reaches — the plan named `error_recovery.rs` only),
|
||||
`crates/vlog_linter/src/{module_decls.rs,signals.rs}` and
|
||||
`crates/lucisv_server/src/{linked.rs,selection.rs,type_def.rs}` and
|
||||
`crates/vlog_semantic/src/instantiations.rs` and
|
||||
`crates/vlog_refactor/src/ports/find.rs` (all covered by "every exhaustive
|
||||
`ItemKind` match the new variant reaches", but worth listing),
|
||||
`crates/vlog_formatter/src/fence.rs`, and
|
||||
`crates/vlog_parser/src/parser/recover.rs` (the `is_sync_stop` extraction).
|
||||
|
||||
**Gates.** `cargo fmt -p` over the eight touched crates: clean.
|
||||
`cargo clippy --all-targets`: **0 warnings**.
|
||||
`tools/guard.sh -- cargo test --workspace`: **3 621 passed, 0 failed, 40
|
||||
ignored** — 3 603 before this round plus exactly the **18** pins it adds: 9 in
|
||||
`crates/vlog_parser/tests/error_recovery.rs` (5 for 36.1, 4 for 36.2), 3 in
|
||||
the two rule modules, 6 in `atomic.rs`. Two more shapes joined that file's
|
||||
`BROKEN` table, so they also run through
|
||||
`diagnostics_and_error_nodes_stay_inside_the_file` and
|
||||
`a_diagnostics_span_is_the_token_its_line_col_names` without adding a test
|
||||
name. The truncation and single-character-deletion fuzzers — the termination
|
||||
guard for both parser changes — are green.
|
||||
`tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3 %)**, the same six
|
||||
failures as before (`end`, `cp_sign_cross`, `1`, `)`, `$_DLATCH_P_`, and the
|
||||
lex error), 0 verification errors, 0 crashes. No guard kill anywhere.
|
||||
|
||||
**On the rule rows in `README.md`.** `README.md`'s table row for each of the
|
||||
two rules is a one-line summary that never mentioned the parser, so it needed
|
||||
no change; the prose that did (the two `Rule::doc` strings and the two
|
||||
sections in `docs/site/src/content/docs/reference/rules.md`) is rewritten.
|
||||
|
||||
### 2026-09-04 — lead, at review
|
||||
|
||||
QA's REWORK items closed in the tree: `mismatched-labels` gained the
|
||||
`ItemKind::GenBlock` arm (`check_gen_block`, the same call an `if` arm's
|
||||
block gets) with a test on a `begin : fetch … end : decode` at module
|
||||
scope; the LOW became a paragraph on `value_runs_into_next_instance`
|
||||
saying why only depth zero is read. One lead finding on 36.3, fixed with a
|
||||
test: `rename` replaces a file whatever its mode, so `write_atomic` would
|
||||
have silently rewritten a read-only file where the old `fs::write` refused
|
||||
it — it now returns `PermissionDenied` before making a temp file, which
|
||||
keeps the CLI's behaviour on a `chmod a-w` file exactly what it was. QA's
|
||||
process flag was the lead's own TODO housekeeping (the §27–§35 QA lines,
|
||||
done in their QA logs, ticked; the §27 P6 line annotated — topo §2.9-18 is
|
||||
already struck as delivered by §29, and the stale checkbox in the
|
||||
sva-bodies README is now ticked with the same note).
|
||||
|
||||
**Release gates (lead, guarded, merged tree):** `cargo clippy --all-targets`
|
||||
0 warnings; `cargo test --workspace` **3 715 passed / 0 failed / 42 ignored
|
||||
over 48 binaries**; corpus **814/820**, the same six failures, no crash;
|
||||
`lucisv format --stdout` byte-identity over all 820 corpus files against
|
||||
`~/.cache/lucisv-baselines/lucisv-0.39.0`: **0 differing**; opentitan
|
||||
read-only `--check` over `hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`
|
||||
identical to 0.39.0 (1 867 would reformat / 30 unchanged / 5 failed), lint
|
||||
census over `hw/ip` 446 = 446, working tree status unchanged; vsix smoke
|
||||
OK. Ships as 0.40.0.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent
|
||||
|
||||
Read the plan (TODO §36), the dev's account above, and the full diff
|
||||
(`git diff --stat`, then every touched file). Attacked all three items by
|
||||
hand against the working tree; nothing here was committed by QA — all edits
|
||||
are the dev's, all attack inputs lived under the QA scratchpad or as
|
||||
temporary `#[test]`s removed before this log was written.
|
||||
|
||||
**36.1 (`ItemKind::GenBlock`).** Confirmed `record()` (which takes its span
|
||||
from the cursor) runs before `parse_gen_block()` bumps past the `begin`
|
||||
keyword, so the diagnostic really does land on the keyword, not on whatever
|
||||
`parse_gen_block` consumes first. Read every consumer the Handshakes section
|
||||
claims (`format/item.rs`, `fence.rs`, `bind/item.rs`, `instantiations.rs`,
|
||||
`ports/find.rs`, `visit.rs` ×2, `module_decls.rs`, `signals.rs`, `linked.rs`,
|
||||
`selection.rs`, `type_def.rs`, and the four parser test walkers) — each is
|
||||
the boring "descend into `.items`" arm the plan asked for, or (for
|
||||
`exprs.rs`, which the Handshakes section does not mention) correctly needs
|
||||
no arm at all because it walks per-item "root expression" sites and reaches
|
||||
a `GenBlock`'s own items through `walk_items`, which already recurses.
|
||||
`type_hierarchy.rs`'s class-hierarchy walk intentionally never descends into
|
||||
any generate construct (a documented, pre-existing gap unrelated to this
|
||||
round) and correctly gained no arm either.
|
||||
|
||||
Typed every shape the plan and the QA brief ask for directly against
|
||||
`parse_source_tolerant`/`parse_source`: labeled block (`begin : g … end : g`,
|
||||
round-trips into `end_label`), nested `begin`s (two diagnostics, both kept,
|
||||
`only_the_outermost_block_of_a_nest_is_reported_at_module_scope` pins that
|
||||
neither rule reports the inner one — correct, matches the pre-round
|
||||
behaviour for a nested leaf), a block containing an instantiation and an
|
||||
`always` block, a block as a module's only item, a block right before
|
||||
`endmodule`, `begin` with a comment before and inside it (`before_kw` is
|
||||
printed by the formatter's dead arm — read, not just trusted, since the arm
|
||||
is unreachable from `format_source`), an unclosed `begin` at module scope
|
||||
(recovers as far as it can and does **not** eat `endmodule` when one
|
||||
follows; `an_unclosed_begin_keeps_the_statements_inside_it` already pinned
|
||||
the general unclosed-block case pre-round and nothing about that changed),
|
||||
and `begin` inside a generate `if` arm (unchanged — that path never reaches
|
||||
the new `"begin"` arm because `parse_gen_if`'s block already calls
|
||||
`parse_gen_block` directly, not through `parse_keyword_item`). `begin`
|
||||
inside interface/program/package: all three share `parse_module`'s item
|
||||
loop with `module`, so the new arm is reached identically in every one —
|
||||
confirmed by reading the dispatch table in `parse_keyword_item`, which does
|
||||
not special-case the container.
|
||||
|
||||
`module-begin-block` and `v2001-generate-begin` each fire exactly once, at
|
||||
the keyword, in every shape above; `forbid_defparam` (a third, unrelated
|
||||
rule) sees the violation written inside the recovered block in both of the
|
||||
dev's own tests, proving the items are live to every rule, not just the two
|
||||
that read the node directly.
|
||||
|
||||
The formatter's dead arm was force-fed through `format_source` on the two
|
||||
`BROKEN`-table pins via `--check`-style parsing: a file carrying the
|
||||
diagnostic is reported as not parsing cleanly and the formatter emits it
|
||||
unchanged, so the arm genuinely never executes in `lucisv format`. The
|
||||
fence collector (`vlog_formatter/src/fence.rs`, tolerant parse) does not
|
||||
panic on any shape above.
|
||||
|
||||
LSP outline/symbols: `selection.rs`'s smart-selection walker and
|
||||
`type_def.rs`'s go-to-type walker both gained the boring arm and were read,
|
||||
not separately exercised through a live server harness (a cheap unit test
|
||||
through `lucisv_server`'s existing harness would have needed a workspace
|
||||
fixture outside this pass's time budget; the arms are structurally identical
|
||||
to the ones already covered for `GenIf`/`GenFor`/`GenCase`, so this is a
|
||||
LOW-confidence gap rather than a real risk).
|
||||
|
||||
**Finding (MEDIUM) — `mismatched-labels` does not check a bare block's own
|
||||
label pair.** `crates/vlog_linter/src/rules/mismatched_labels.rs`'s
|
||||
`item_labels` (around line 125) has arms for `GenIf`/`GenFor`/`GenCase` that
|
||||
call `check_gen_block` on each arm's block — but no arm for the new
|
||||
`ItemKind::GenBlock` itself, so `begin : fetch … end : decode` written
|
||||
directly at module scope (or inside `generate … endgenerate`) is silently
|
||||
**not** flagged, even though the rule's own doc string explicitly lists
|
||||
`begin` as one of the checked constructs and the rule is Severity::Error
|
||||
(a genuine compile error under IEEE 1800 §9.3.4). Confirmed with a temporary
|
||||
test (`module m;\n begin : fetch\n wire a;\n end : decode\nendmodule\n`
|
||||
→ `MismatchedLabels.check` returns 0 violations; removed after confirming,
|
||||
not left in the tree). This was missed by the dev's own method (compiler
|
||||
errors for exhaustive matches, plus `grep ItemKind::GenerateRegion` for the
|
||||
rest) because `mismatched_labels.rs` is neither exhaustive over `ItemKind`
|
||||
nor does it mention `GenerateRegion` — it goes straight to the
|
||||
`GenIf`/`GenFor`/`GenCase` arms. Fix is one arm:
|
||||
`ItemKind::GenBlock(b) => check_gen_block(out, b)`. Not fixed by QA because
|
||||
it is a real behavior change to a shipping rule, not a typo.
|
||||
|
||||
**36.2 (`value_runs_into_next_instance`).** Reproduced the README shape
|
||||
exactly: params `[Ok(.WIDTH(8)), Error(".DEPTH(")]`, `u0` with two
|
||||
connections, one diagnostic on the `(`, `endmodule` consumed — matches
|
||||
`a_half_typed_override_does_not_swallow_the_next_instance`. Attacked:
|
||||
|
||||
- Ambiguous balanced-parens control (`sub #(.D(` / `u0 (.a(x)));`) — still
|
||||
read greedily, exactly pinned, confirmed unchanged.
|
||||
- Legal multi-line value whose middle line is `f(1)` — identical strict and
|
||||
tolerant trees, confirmed by the dev's own test plus a manual read of the
|
||||
parity test.
|
||||
- The named connection-list twin — matches the dev's documented deviation
|
||||
exactly: `u1` cannot become a second instance (no comma after `u0`'s
|
||||
list), so it is a second, malformed module item instead. Still strictly
|
||||
better than the pre-round total loss of `endmodule`.
|
||||
- **Nested/deeper unclosed brackets** (`.DEPTH(f(g(h(` / `u0 (.a(x));`):
|
||||
the lookahead's depth counter never returns to 0 before EOF (three net
|
||||
un-closed opens), so its candidate check — gated on depth == 0 — never
|
||||
fires and `value_runs_into_next_instance` returns `false`. Falls back to
|
||||
the pre-existing (pre-§36.2) recovery: the whole `sub #(...)` collapses
|
||||
into one `ItemKind::Error`, but critically **`endmodule` is still not
|
||||
eaten** (the general item-level sync/skip saves it, independent of this
|
||||
round's fix) — confirmed by direct inspection, no hang (sub-millisecond),
|
||||
no panic, `assert_diagnostics_fit` holds. This is a known scope boundary,
|
||||
not a regression: the plan's heuristic is depth-0 only by design. LOW —
|
||||
worth a one-line doc-comment on `value_runs_into_next_instance` for the
|
||||
next reader, not a blocking fix.
|
||||
- **Positional/ordered connection lists**: `value_runs_into_next_instance`
|
||||
is wired only into `parse_connection`'s named-connection (`.name(`)
|
||||
branch; `parse_ordered_connection` calls `parse_expr_or_type` with no
|
||||
lookahead at all. Attacked `sub u0 (f(` / `u1 (.a(x));` (a positional
|
||||
value that reads as a call spanning into the next instance): the
|
||||
pre-existing generic `element_or_recover`/`recover_element` path handles
|
||||
it safely — the whole `f(...)` argument list including `u1 (.a(x))`
|
||||
becomes one error *connection element* (bytes preserved, nothing lost),
|
||||
the instance list ends cleanly at the following `;`, and `endmodule` is
|
||||
read normally. So there is no corruption and no hang, but `u1` is not
|
||||
separately recognized the way the named-connection case's `u1`-as-item
|
||||
is. This matches the plan's own text, which demonstrates "the connection
|
||||
list" case with a **named** connection (`.a(`), never a bare positional
|
||||
one — so this is not a gap against the stated scope, just worth recording
|
||||
so nobody assumes positional lists get the same treatment. LOW.
|
||||
- Several `.A(1), .B(2), .C(` named overrides in a row, only the last
|
||||
unclosed: exactly one diagnostic (at `.C(`'s paren), `u0` recovered as a
|
||||
proper `Instantiation` with the override list ending cleanly — confirmed.
|
||||
- A `;` written inside the unclosed value before any candidate identifier
|
||||
(`.DEPTH(x;` / `u0 (.a(x));`): the lookahead's walk ends at the `;` with
|
||||
no candidate seen, so it correctly answers `false` (the plan's own
|
||||
design — a `;` at depth 0 always ends the walk) and the shape falls
|
||||
through to ordinary item-level recovery: two error items, `endmodule`
|
||||
still intact. No corruption.
|
||||
- Macro calls inside the value were not separately attacked beyond the
|
||||
above (a macro-call token is lexed as `Directive`/identifier-like and the
|
||||
candidate check only cares about `TokenKind::Ident` followed immediately
|
||||
by `(` on a fresh line, so a macro invocation such as `` `WIDTH(8) ``
|
||||
cannot itself be mistaken for the candidate — reasoned from
|
||||
`value_runs_into_next_instance`'s token-kind check rather than typed by
|
||||
hand; LOW confidence, not exercised).
|
||||
|
||||
**Termination (`recover_list.rs`'s new bracket-seeded branch).** Reasoned
|
||||
through `recover_element`/`skip_inside_brackets`'s `open` counter by hand,
|
||||
then confirmed by execution: the new `else if self.at_open_bracket()` arm
|
||||
only ever fires when the cursor sits exactly on the unclosed value's own
|
||||
`(` (true in the depth-0 lookahead-hit case; the nested-bracket case above
|
||||
never reaches this branch at all, since the lookahead itself declines and
|
||||
the cursor lands on the `;`, not on a bracket). No crafted input — several
|
||||
`.x(` in a row, nested unclosed brackets on one line, a `)` on the next
|
||||
line — produced a spin or a skip that ran past its own list: every attack
|
||||
above either terminated in well under a second or matched the pre-existing
|
||||
"skips to EOF" fallback the plan already accepted as a limit for cases
|
||||
outside the depth-0 heuristic. `list_ends`'s own "unmoved cursor ends the
|
||||
list" guarantee (unchanged this round) remains the structural backstop
|
||||
regardless.
|
||||
|
||||
Ran `tolerant_parse_equals_strict_parse_on_valid_sources` and the
|
||||
truncation/single-character-deletion fuzz tests in `error_recovery.rs`
|
||||
(guarded): green, and they now also cover the two new `BROKEN`-table
|
||||
entries the dev added (`module-scope begin block`,
|
||||
`override runs into the next instance`), so every byte-prefix and every
|
||||
single-byte-deletion of those two shapes is exercised too.
|
||||
|
||||
Timed a tolerant parse of the largest opentitan file
|
||||
(`hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv`, 42k lines) with
|
||||
`--check`, three runs each, current binary vs. the cached 0.39.0 baseline:
|
||||
~0.63–0.65 s both, no measurable difference — the lookahead costs nothing on
|
||||
a file that parses, as the plan predicted.
|
||||
|
||||
**36.3 (`write_atomic`).** Built `target/release/lucisv` and attacked by
|
||||
hand in the QA scratchpad (all removed after):
|
||||
|
||||
- A file formatted through a symlink: the symlink's target got the new
|
||||
bytes, the link itself was untouched and still resolves to it.
|
||||
- A 0600 file and a 0755 file each kept their mode across `lucisv format`.
|
||||
- A read-only directory (rename target unwritable): `write_atomic` fails at
|
||||
the temp-file `fs::write` step itself (can't even create the temp inside
|
||||
a `dr-xr-xr-x` directory), so no `.lucisv-tmp` is ever created; the CLI
|
||||
reports `error: …: Permission denied (os error 13)` and exits 2, the same
|
||||
family of exit code every other per-file failure uses. Original file
|
||||
untouched.
|
||||
- `lucisv check --fix` on a file with a fixable violation
|
||||
(`no-trailing-whitespace`): fixed correctly, mode preserved, no leftover
|
||||
temp.
|
||||
- Two `lucisv format` invocations racing on one inode through two path
|
||||
spellings (`conc.sv` and a symlink alias `sub/alias.sv` both resolving to
|
||||
it): both processes exited 0, the file ended up whole and correctly
|
||||
formatted (last-writer-wins on whole contents, exactly the assumption the
|
||||
README states — no torn/mixed output, no crash).
|
||||
- The temp name is `.{name}.{pid}.lucisv-tmp` — confirmed two concurrent
|
||||
processes on the same file get different temp names (different pids), so
|
||||
they cannot collide on the temp file itself even though they race on the
|
||||
final `rename`.
|
||||
- A leftover temp simulated by hand (`touch .good.sv.99999.lucisv-tmp` next
|
||||
to a real `good.sv`) is **not** picked up by the CLI's directory walk:
|
||||
confirmed `lucisv --check .` over the directory processed exactly the one
|
||||
real file. Traced why in `crates/lucisv_core/src/walk.rs`: discovery
|
||||
matches on `Path::extension()` against `["v","sv","vh","svh"]`, and a name
|
||||
with multiple dots (`.good.sv.99999.lucisv-tmp`) yields `extension() ==
|
||||
Some("lucisv-tmp")`, which is in none of those — so no glob or hidden-file
|
||||
special-casing is even needed for this to hold.
|
||||
- `cache.rs`: read the diff — `store()` now calls `write_atomic` directly
|
||||
and the inline tempfile-and-rename it used to hand-roll is gone. Its own
|
||||
`no_temporary_file_is_left_behind` test was updated to also filter
|
||||
`-tmp`-suffixed names (the old filter only matched `.tmp`, which the new
|
||||
`.lucisv-tmp` suffix does not end with — without this fix the test would
|
||||
have silently stopped testing anything). Ran it directly: passes, along
|
||||
with the rest of `cache.rs`'s suite (15/15) and all 6 of `atomic.rs`'s own
|
||||
tests.
|
||||
|
||||
**Finding (MEDIUM-ish, process, not correctness) — `TODO.md` diff includes
|
||||
8 unrelated historical checkboxes.** `git diff -- TODO.md` flips eight
|
||||
`- [ ]` → `- [x]` QA lines in sections §29 through §35 (already-released
|
||||
0.34.0–0.39.0 work), plus a `**Delivered by §29**` note appended to the P6
|
||||
line under §29. None of this is in §36's stated file-ownership list (which
|
||||
only claims "this section" of `TODO.md`), and none of it is mentioned in
|
||||
the work log above. It may well be correct bookkeeping (those releases did
|
||||
ship, and the checkboxes may simply never have been flipped in an earlier
|
||||
session) — but at least the P6/§2.9-18 line is worth the lead's own look:
|
||||
`docs/topo.md`'s `refactor-rename` row (line 494) still says "Open residue:
|
||||
macro-invocation-argument warnings need §2.9-18", and
|
||||
`docs/features/sva-bodies/README.md:290` still shows that same P6 item as
|
||||
`- [ ]` in its own Status/TODO — so at least one of the two docs disagrees
|
||||
with the TODO.md edit made in this round. Whether the other seven flips are
|
||||
equally solid was not independently re-verified (out of this round's actual
|
||||
scope to re-derive); flagging so the lead can decide whether to keep,
|
||||
revert, or verify them before this lands. Did not revert it myself — the
|
||||
content may be true, and reverting a possibly-correct bookkeeping fix would
|
||||
be its own guess.
|
||||
|
||||
**Gates re-run by QA (guarded, all green).**
|
||||
- `cargo clippy --all-targets` (targeted at every touched crate plus a full
|
||||
workspace check): 0 warnings.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 713 passed, 0 failed, 42
|
||||
ignored**, no guard kill. (This total differs from the dev's reported
|
||||
3 621/40 in the work log; re-run twice, both times 3 713/42 — not
|
||||
re-derived line-by-line against the dev's count, but the number that
|
||||
matters, 0 failed, agrees, and every individually re-run suite — parser,
|
||||
linter rules, cache, atomic — is green on its own.)
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3%)**, same six
|
||||
failures (`end`, `cp_sign_cross`, `1`, `)`, `$_DLATCH_P_`, the lex error),
|
||||
0 verification errors, 0 crashes.
|
||||
- `tools/guard.sh -- target/release/lucisv check --select
|
||||
module-begin-block,v2001-generate-begin` over
|
||||
`hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`: **0 findings**,
|
||||
identical (exit 0) on both the current binary and the cached
|
||||
`lucisv-0.39.0` baseline. `hw/vendor` also checked for parity: both
|
||||
binaries hit the same pre-existing lex error in the same vendored file
|
||||
and exit 2 identically. Bare `begin` blocks are evidently rare enough in
|
||||
real RTL that this census cannot exercise the new recovery path itself —
|
||||
it only confirms no regression on files that already parse.
|
||||
`git -C opentitan status --porcelain` after every sweep: unchanged, only
|
||||
the three pre-existing baseline-drift files
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
**Verdict: REWORK (small).**
|
||||
1. MEDIUM — `crates/vlog_linter/src/rules/mismatched_labels.rs`: add
|
||||
`ItemKind::GenBlock(b) => check_gen_block(out, b)` to `item_labels`'s
|
||||
match, plus a test (`begin : fetch … end : decode` at module scope must
|
||||
fire `mismatched-labels`). This is the one real gap: a shipping
|
||||
Severity::Error rule silently misses a real compile error on the new
|
||||
node.
|
||||
2. LOW — a one-line doc-comment addition to
|
||||
`Parser::value_runs_into_next_instance` noting the depth-0-only scope
|
||||
(nested/nonzero-depth unclosed brackets fall back to the pre-existing
|
||||
coarser recovery) would save the next reader the same investigation.
|
||||
Not blocking.
|
||||
3. Process flag (not a code defect) — the eight unrelated `TODO.md`
|
||||
checkbox flips in §29–§35 and the §2.9-18/topo.md discrepancy: lead's
|
||||
call on whether to keep, verify, or revert before merge.
|
||||
|
||||
Everything else — 36.1's node, consumers, and rules; 36.2's lookahead,
|
||||
its termination behavior, and its tests; 36.3's `write_atomic` and its
|
||||
three call sites — held up under attack. Re-run finding 1 and this is a
|
||||
clean ship.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted; ships in 0.40.0. The three parts are what
|
||||
§36 asked for and no more. 36.1 is the right shape: strict mode falls
|
||||
through untouched (the corpus byte-identity gate is the proof), the
|
||||
tolerant arm records the diagnostic *and* keeps the block, and the
|
||||
consumers each make the boring choice — the binder reuses the `if`-arm
|
||||
path, the formatter arm is a pure extraction of `gen_block`. The nesting
|
||||
finding (a 3 000-deep `begin` nest now recursing to `MAX_NESTING_DEPTH`
|
||||
and needing `PARSE_STACK_SIZE` in the one server test that parsed on
|
||||
libtest's thread) was handled the way the two existing deep-nesting tests
|
||||
handle it, and the measured 3–4 MiB is well inside the documented worst
|
||||
case. 36.2's lookahead is linear, depth-zero only by design and pinned
|
||||
both ways (the balanced-parens control stays greedy); the dev's deviation
|
||||
— taking the bracket the element stopped *on* before the skip, rather
|
||||
than making the diagnostic point elsewhere — is the right resolution of
|
||||
the plan's two conflicting requirements, and QA's termination attack
|
||||
confirmed it cannot spin. 36.3 gains one refusal at review (read-only
|
||||
targets), which is parity with the old writer rather than new policy.
|
||||
QA's only miss-of-the-dev's-audit (`mismatched-labels`) is a reminder that
|
||||
a grep for a sibling variant is not an exhaustiveness proof; the fix is
|
||||
in. Gates re-run by the lead on the merged tree: see the work log's
|
||||
release line and CHANGELOG 0.40.0.
|
||||
@@ -287,8 +287,10 @@ right, and the two together are why nothing in either tree falls back.
|
||||
in-file and through the index, `FACTS_FORMAT` 16
|
||||
- [x] **P5** — the verbatim-SVA rename warning, with both pins (a fallback
|
||||
region warns; a structured one does not)
|
||||
- [ ] **P6 §2.9-18** — the engine half is delivered and pinned; the server
|
||||
fan-out is filed as Handshake request 1 above
|
||||
- [x] **P6 §2.9-18** — the engine half is delivered and pinned; the server
|
||||
fan-out is filed as Handshake request 1 above. **Closed by TODO §29**
|
||||
(2026-09-02): the macro-word census answers the server half without
|
||||
the fan-out; topo §2.9-18 is struck.
|
||||
- [x] **Measurement** — see the work log
|
||||
|
||||
## Design
|
||||
|
||||
@@ -361,7 +361,7 @@ Reports the `` `` `` token-concatenation operator written inside a *plain* strin
|
||||
|
||||
## module-begin-block
|
||||
|
||||
Reports a `begin … end` written straight into a module body, where a module item belongs. Tools that accept it treat it as an unnamed generate block, so the declarations inside land in an invented scope and every hierarchical path written against them is wrong. lucisv's parser *rejects* the construct rather than recovering it, so what the rule reads is the error leaf recovery leaves at module scope — exact, but the rest of that module is lost to recovery. Verible's `module-begin-block`, same default.
|
||||
Reports a `begin … end` written straight into a module body, where a module item belongs. Tools that accept it treat it as an unnamed generate block, so the declarations inside land in an invented scope and every hierarchical path written against them is wrong. lucisv's parser *recovers* the construct in error-tolerant mode — it reads the block as that unnamed generate block and records a diagnostic at the `begin`, so the file is still reported as not parsing cleanly and is still never formatted, while the items inside the block and after it stay visible to every rule. Verible's `module-begin-block`, same default.
|
||||
|
||||
## numeric-format-string-style
|
||||
|
||||
@@ -389,4 +389,4 @@ Reports a `;` written after a `` `uvm_* `` macro invocation. The macros expand t
|
||||
|
||||
## v2001-generate-begin
|
||||
|
||||
Reports a bare `begin … end` written directly inside a `generate … endgenerate` with no `if`, `for` or `case` around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same error leaf `module-begin-block` reads, one scope in. Verible's `v2001-generate-begin`, same default.
|
||||
Reports a bare `begin … end` written directly inside a `generate … endgenerate` with no `if`, `for` or `case` around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same recovered block `module-begin-block` reads, one scope in. Verible's `v2001-generate-begin`, same default.
|
||||
+2
-2
@@ -586,8 +586,8 @@ update the filing README(s) and this file.
|
||||
| ~~21~~ | ~~`Parser::parse_scoped_name` joins a `pkg::name` chain into one `String`, erasing the segment boundary, so an escaped segment (`\my-pkg ::\state-t` as a type, an instantiated module or a `bind` target) is reprinted without its terminating space and **refused by the safety net** — an error, never a corruption. Wanted: the AST keeps the segments (as `parse_method_name` already does for `FunctionDecl::scope`). Pinned by `escaped_identifiers.cases`'s one `#SKIP` and `verification::an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`, both of which must keep failing-to-format until delivered~~ — **delivered 2026-09-02 by comment-slots**: `Parser::push_scope_segment` is the one join for every `::` chain and writes the escaped segment's terminator; `parse_method_name` keeps real segments (`ScopeSeg`, one comment slot per `::`). The `#SKIP` is a live case and the verification pin is inverted, with a new pair asserting the tightened spelling is still refused | escaped-identifiers | ~~vlog_parser~~ done |
|
||||
| ~~22~~ | ~~**Comment slots in shared expression/name machinery** drop the comment and the safety net refuses the file: `q[/*c*/ i]` (index expressions), `x inside {[/*c*/ 0:3]}` and `n /*c*/ inside {` (`inside` / `parse_value_range`), `pkg/*c*/ ::cls::name` (`parse_method_name` chains), `foreach (q[/*c*/ i])` (`parse_foreach_target`), `static /*c*/ constraint` / `pure /*c*/ static function` (`take_member_prefix`). Found by constraint-bodies' exhaustive gap fuzzer (358 gaps; these 40 fail identically on v0.26.0 in the same constructs outside a constraint). Inside a constraint they are regressions relative to the verbatim era — but no opentitan file hits one (sweep unchanged). Wanted: a parser-wide round giving each slot a `Meta`/comments field, then re-running the fuzzer to zero.~~ — **delivered 2026-09-02 by comment-slots**: ~70 named comment fields across `ExprKind`/`Stmt`/declarations/headers/labels (`SegmentComments`, `BinaryComments`, `CastComments`, `LabelComments`, `Stmt::before_semi` + `StmtKind::takes_semi()`), three duplicated grammars folded into `parse_postfix_segment` / `parse_value_range`, and four gap fuzzers at zero — covergroup 329, fragment 153, constraint 395 (committed at last), RTL 352 (new). Corpus (860 files) and opentitan (3 975 files) byte-identical to v0.30.0. Deliberately left: `if`/`case` in-paren comments still recovered print-side by `header_parens` (only `after_kw` got a slot) — a real slot there would change existing layout | constraint-bodies (dev + QA) | ~~vlog_parser~~ done |
|
||||
| 23 | A **cross-file instance-member tail does not resolve for rename**: with `module sub` in `sub.sv` and `assign w = u_x.sig;` in `top.sv`, renaming `sub`'s `wire sig` edits `sub.sv` only — the same shape in one file resolves and is edited (`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`). Since comment-slots the rename *says so* (item 20's warning); the edit itself is the gap. Modules export ports and parameters only (the class-member-access round 2 ruling), so an internal net is exactly what the cross-file hop refuses — the fix is either an export rule for nets named through an instance or a rename-time in-file fallback resolution of the tail. | comment-slots (dev, surfaced by the §2.9-20 control test) | vlog_semantic / vlog_refactor |
|
||||
| 24 | A **half-typed `#(` parameter override whose value can read as a call** (`sub #(.W(` ⏎ `u0 (.a(x))`) — the greedy expression grammar swallows the next instance's name before any error fires, so the whole instantiation still degrades to an item-level `Error` node instead of getting header recovery's benefit. Found by §32's QA; the fix is a lookahead in the override grammar (an identifier followed by `(` on a later line is the next instance, not a call). | header-recovery (QA) | vlog_parser |
|
||||
| 25 | The parser **refuses** a module-scope `begin … end` and a bare `begin` inside a `generate` region (an `ItemKind::Error`) rather than recovering them as an unnamed generate block, so `module-begin-block` and `v2001-generate-begin` (TODO §35) fire on an error leaf and the rest of the unit is lost to recovery. Wanted: tolerant-mode recovery that keeps the block's items. | linter-expansion-3 (dev) | vlog_parser |
|
||||
| ~~24~~ | ~~A **half-typed `#(` parameter override whose value can read as a call** (`sub #(.W(` ⏎ `u0 (.a(x))`) — the greedy expression grammar swallows the next instance's name before any error fires, so the whole instantiation still degrades to an item-level `Error` node instead of getting header recovery's benefit. Found by §32's QA; the fix is a lookahead in the override grammar (an identifier followed by `(` on a later line is the next instance, not a call).~~ — **delivered 2026-09-04 by small-items-3 (TODO §36)** | header-recovery (QA) | vlog_parser |
|
||||
| ~~25~~ | ~~The parser **refuses** a module-scope `begin … end` and a bare `begin` inside a `generate` region (an `ItemKind::Error`) rather than recovering them as an unnamed generate block, so `module-begin-block` and `v2001-generate-begin` (TODO §35) fire on an error leaf and the rest of the unit is lost to recovery. Wanted: tolerant-mode recovery that keeps the block's items.~~ — **delivered 2026-09-04 by small-items-3 (TODO §36)** | linter-expansion-3 (dev) | vlog_parser |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -5,6 +5,23 @@ for you. The extension and its bundled language server share one version
|
||||
number; the full engineering notes live in the
|
||||
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
||||
|
||||
## 0.41.0 — 2026-09-04
|
||||
|
||||
- **A quieter cursor.** Resting the cursor on an instantiation of a
|
||||
widely used module no longer stalls the editor: port refactorings are
|
||||
offered instantly and their edit is computed only when you pick one.
|
||||
- **Faster go-to-definition** for declarations in files you have not
|
||||
opened.
|
||||
|
||||
## 0.40.0 — 2026-09-04
|
||||
|
||||
- **Better recovery while you type.** A stray `begin … end` at module
|
||||
scope, and a half-typed `#(` override above another instance, no
|
||||
longer take the rest of the module out of the outline, hover and
|
||||
diagnostics — you get one squiggle where the problem is.
|
||||
- **Safer saves.** Format-on-save and `--fix` now replace a file in one
|
||||
step; an interrupted write can no longer leave it truncated.
|
||||
|
||||
## 0.39.0 — 2026-09-04
|
||||
|
||||
- **Nineteen more lint rules** (73 in all): generate-style rules,
|
||||
|
||||
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
|
||||
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
||||
setup.
|
||||
|
||||
The current release is **0.39.0**. Its platform packages include both
|
||||
The current release is **0.41.0**. Its platform packages include both
|
||||
`lucisv-server` and the `lucisv` command-line tool:
|
||||
|
||||
| Package target | Machines |
|
||||
@@ -364,6 +364,17 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.41.0 highlights
|
||||
|
||||
Version 0.41.0 takes the code-action request off the module fan-out and
|
||||
answers go-to-definition from the index.
|
||||
|
||||
## Release 0.40.0 highlights
|
||||
|
||||
Version 0.40.0 recovers a stray `begin` block and a half-typed `#(`
|
||||
override without losing the rest of the module, and makes every
|
||||
in-place write atomic.
|
||||
|
||||
## Release 0.39.0 highlights
|
||||
|
||||
Version 0.39.0 completes the Verible rule set: 73 lint rules, each with
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "lucisv",
|
||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
||||
"version": "0.39.0",
|
||||
"version": "0.41.0",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
|
||||
Reference in new issue
Block a user