Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc59336d91 | ||
|
|
b2a5f0a171 | ||
|
|
32204eba71 | ||
|
|
243472901d | ||
|
|
4621214a51 | ||
|
|
8e65da1ba8 | ||
|
|
5c9fdb2c62 | ||
|
|
e51a2c7f21 | ||
|
|
dafa4f0500 | ||
|
|
6c1f863417 | ||
|
|
501b36d8b8 | ||
|
|
9c75b7a4e5 | ||
|
|
be084f07b5 | ||
|
|
bbdbfe9045 | ||
|
|
3bd55acb98 | ||
|
|
c37b13de31 | ||
|
|
d8d1791c1c | ||
|
|
d10e57aa6e | ||
|
|
414d501847 | ||
|
|
4123905aa1 | ||
|
|
df4e71411f | ||
|
|
6759f0eea1 |
No files matched your search
@@ -7,3 +7,4 @@
|
||||
.DS_Store
|
||||
/.zcode
|
||||
/.claude
|
||||
__pycache__/
|
||||
@@ -4,6 +4,81 @@ 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.51.0 — 2026-09-08
|
||||
|
||||
### Performance take 5 — the implementation round
|
||||
|
||||
The owner's take-5 plan (`docs/performance_take5.md`) implemented end to
|
||||
end, each stage measured against the 0.50.0 reference on opentitan
|
||||
(`docs/perf/README.md`, 2026-09-08). Behaviour is unchanged everywhere the
|
||||
suites and the byte-identity gates can see; what changed is how much work
|
||||
the same answers cost.
|
||||
|
||||
- **Code actions stop repeating work.** A code-action request runs the
|
||||
lint pass and reads the project configuration only when the client asks
|
||||
for quick fixes or fix-all (`only: []` answers at once); the formatter's
|
||||
fence answer is computed only when a finding carries a fix and once per
|
||||
document revision; the four refactoring selectors read the document's
|
||||
own parse instead of re-parsing the buffer; the ports and
|
||||
organize-imports lightbulbs are answered from the plan-time checks with
|
||||
the same titles and counts, the click still recomputing and verifying.
|
||||
On opentitan's 42 192-line generated file a no-offer cursor move fell
|
||||
from 310 ms to 24 ms, and the navigation queued behind it with it; an
|
||||
offering cursor from 22 ms to 5.5 ms.
|
||||
- **Rename reuses its analysis; the verifier is untouched.** A rename
|
||||
parses and analyses each selected file once and builds its after-index
|
||||
from the edited files' fresh records; every check the verifier makes is
|
||||
the same code, re-attacked. The hierarchical-tail rename fell from 780
|
||||
to 388 ms (2.01×), an ordinary rename 141 → 92 ms, the extract command
|
||||
246 → 149 ms. A `--verbose` session now logs a per-stage rename trace.
|
||||
Topology handshake 33 is closed: inline-module's hierarchical-use
|
||||
refusal now sees every file whose tokens write the dissolved instance's
|
||||
name, including a `bind` in a file that instantiates nothing in the
|
||||
chain.
|
||||
- **The CLI's package census parses once.** With `unused-import` on,
|
||||
`check --select error,warning,style` no longer builds a one-file index
|
||||
for every file: the census reads package exports off its one parse and
|
||||
skips the nine files in ten that declare no package. The rule's cost on
|
||||
`hw/ip` fell from 142 ms to 5 ms; every output is byte-identical.
|
||||
- **Startup.** The server asks for the client's settings before its first
|
||||
scan (2 s bound for a client that never answers) and runs one scan at
|
||||
the answered scope — the empty default-scope scan is gone; the index
|
||||
store is not rewritten when nothing changed and is opened at the first
|
||||
step that needs it; the corpus is read a file at a time in its own step
|
||||
rather than all up front; the open buffers' folders are indexed first
|
||||
and the first navigation after opening a file is answered once that
|
||||
folder is published — correct in every session, at ~250–275 ms, where
|
||||
it used to be 84–208 ms or over a second depending on a race. Warm
|
||||
start 1.33 → ~1.05 s, warm idle RSS −15 to −20 %, the store
|
||||
byte-identical across sessions. `--verbose` logs a per-stage scan trace.
|
||||
- **The harness** (`tools/perf/`) records units, status, result counts and
|
||||
edit fingerprints on every row, measures the extract/inline commands for
|
||||
real, and is what every number above was taken with.
|
||||
|
||||
## 0.50.0 — 2026-09-07
|
||||
|
||||
### The format cache key; performance take 4
|
||||
|
||||
- **`uvm-utils-indent` is part of the format cache key.** In 0.49.0 a
|
||||
clean verdict cached under one setting of `[format] uvm-utils-indent`
|
||||
survived a toggle of the option, so `format --check` could exit 0 where
|
||||
`--no-cache --check` would reformat (found by the repository audit,
|
||||
topo handshake 34). The entry carries the option, the store line has it
|
||||
as a fourth field, and a 0.49.0 store is dropped entry by entry and
|
||||
rebuilt — never trusted, never an error. Regression through the real
|
||||
CLI in both toggle directions.
|
||||
- **Performance take 4** (`docs/performance_take4.md`): 0.49.0 against
|
||||
0.43.0 on opentitan, both binaries driven by one client in one hour.
|
||||
0.44.0's `didOpen` fix confirmed in the release build — 14× on the
|
||||
42 192-line file, 3–7× on ordinary RTL; the CLI unchanged and its
|
||||
formatter verdicts byte-identical on all five trees; the findings filed
|
||||
for the next loop: the lazy code-action offer 2–3 ms dearer per cursor
|
||||
move (the extract and inline gates re-parse a buffer the server already
|
||||
holds), the hierarchical-tail rename at 751 ms, the Style lint class
|
||||
1.27× after `unused-import`, the index 14% bigger at codec 19. The
|
||||
measurement harness now lives in `tools/perf/` and runs from a clean
|
||||
checkout.
|
||||
|
||||
## 0.49.0 — 2026-09-06
|
||||
|
||||
### Inline module; the last coverage gaps
|
||||
|
||||
@@ -70,6 +70,13 @@ is in the decomposition-server README) and `vlog_parser/src/lexer.rs`
|
||||
thresholds: a dev adding to a file near 600 puts the code in a new
|
||||
module.
|
||||
|
||||
Re-measured 2026-09-07 at 0.49.0 (same rule, before `mod tests`): four
|
||||
files over 600 — `lucisv_server/src/state.rs` 958 (grew across §37–§49;
|
||||
a decomposition is filed as TODO §55: scope/widen, the document store,
|
||||
the source selectors are three sentences), `perf.rs` 900 (reasoned),
|
||||
`lexer.rs` 763, `vlog_formatter/src/format/stmt.rs` 604 (at the mark; the
|
||||
next statement arm goes in a new module) — and everything else under it.
|
||||
|
||||
## Rust standards
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -265,11 +265,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -278,7 +278,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.49.0"
|
||||
version = "0.51.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -86,10 +86,9 @@ run over an unchanged tree skips them: the summary says `N files from cache`,
|
||||
and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
|
||||
thread count, where parallelism has already taken the easy win).
|
||||
|
||||
An entry is keyed on **(content hash, `line-length`, `indent`, lucisv version)**
|
||||
per file, and only ever records the *already formatted* verdict — a file that
|
||||
would be reformatted, or that failed, is re-checked on every run, so
|
||||
`--check`'s exit codes and `--diff`'s output never go stale. The store is one
|
||||
An entry is keyed on **(content hash, `line-length`, `indent`,
|
||||
`uvm-utils-indent`, lucisv version)** per file, and only ever records the *already formatted* verdict — a file that
|
||||
would be reformatted, or that failed, is re-checked on every run. The store is one
|
||||
text file in `.lucisv_cache/` (self-ignoring, like cargo's `target/`); deleting
|
||||
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
|
||||
neither reads nor writes it, and `--cache-dir <PATH>` puts it elsewhere (the
|
||||
@@ -97,6 +96,10 @@ default is relative to the current directory). Content hashing is 64-bit
|
||||
FNV-1a and a lookup never crosses files; `docs/features/format-cache/README.md`
|
||||
states the collision posture, the semantics table and the concurrency story.
|
||||
|
||||
(In v0.49.0 only, `uvm-utils-indent` was missing from this key, so a cached
|
||||
clean verdict survived a toggle of the option — fixed in 0.50.0; a 0.49.0
|
||||
store is simply rebuilt.)
|
||||
|
||||
### Ignore files
|
||||
|
||||
While walking a directory, lucisv reads a `.gitignore` in every directory it
|
||||
@@ -177,7 +180,7 @@ formatting choice lucisv leaves to the project, because it changes bytes
|
||||
in existing UVM code (21 of the 860 corpus files).
|
||||
|
||||
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
|
||||
supported subset (tables other than `[lint]` and `[lint.<rule>]`, multi-line
|
||||
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
|
||||
arrays, unsupported string escapes) is a hard error naming the file and
|
||||
line — exit 2, with nothing written. This is deliberate:
|
||||
a silently ignored `line_length` typo costs more than a strict parser does.
|
||||
@@ -468,7 +471,7 @@ of document layout from language rules:
|
||||
| `crates/vlog_formatter/src/format/` | `ruff_python_formatter` | Per-node formatting rules, one module per grammar domain (`item`, `module`, `instance`, `decl`, `stmt`, `expr`, `class`, `cover`, `sva`, …) |
|
||||
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
|
||||
| `crates/vlog_semantic` | — | File scopes and references, workspace index, conservative cross-file resolution |
|
||||
| `crates/vlog_refactor` | — | Verified rename, references, port refactors, instantiation plans |
|
||||
| `crates/vlog_refactor` | — | Verified rename/references, ports, imports, extract/inline module, instantiation plans |
|
||||
| `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement |
|
||||
| `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes |
|
||||
| `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities |
|
||||
@@ -480,7 +483,7 @@ Linting consumes the parser, semantics and `lucisv_core` (for the one
|
||||
refactoring consumes the parser and semantics. The CLI reaches
|
||||
semantics through the linter and has no refactoring dependency. The server
|
||||
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
|
||||
including the linter's formatter dependency used only by tests.
|
||||
including the linter’s and refactor’s formatter dependencies used only by tests.
|
||||
|
||||
Key ideas carried over from ruff/prettier:
|
||||
|
||||
@@ -620,12 +623,19 @@ into ranges. Full semantics, including what happens at a range boundary:
|
||||
|
||||
## Supported syntax
|
||||
|
||||
v0.49.0 adds real `randsequence` productions; nonblocking `->>` event
|
||||
triggers with optional timing; streaming `with [range]`; constant-expression
|
||||
and packed-type cast bases; net drive strengths; statement-level `let`; and
|
||||
min:typ:max clocking skews. The parser, formatter and AST consumers share these
|
||||
nodes. See [coverage gaps](docs/coverage_gaps.md) for the dated survey and
|
||||
remaining semantic limits.
|
||||
|
||||
Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
|
||||
- Modules (ANSI and non-ANSI headers), packages, parameter ports,
|
||||
`import`, `timeunit`
|
||||
- Net/variable declarations (`wire`/`reg`/`logic`/`int`/... , signing,
|
||||
packed/unpacked dimensions, net delays), `parameter`/`localparam`,
|
||||
packed/unpacked dimensions, net delays and net drive strengths), `parameter`/`localparam`,
|
||||
`genvar`, `defparam`
|
||||
- `assign` (with delays), `always`/`always_comb`/`always_ff`/`always_latch`,
|
||||
`initial`/`final`
|
||||
@@ -857,8 +867,8 @@ See `docs/features/corpus-check/README.md` for the 820-file corpus baseline:
|
||||
bucket (26 files) and moved the parse rate from 94.1% to 97.1%; 24 of the
|
||||
26 files format, the other 2 advanced to a macro-items blocker and to the
|
||||
`new obj` shallow-copy expression. `randsequence` remained unsupported at
|
||||
this point; the other vendor/formal constructs listed here landed later in
|
||||
0.30.0
|
||||
this point; it shipped as real nodes in 0.49.0. The other vendor/formal
|
||||
constructs listed here landed in 0.30.0
|
||||
11. ~~A macro statement that ends its line followed by a symbol on the next
|
||||
one, the `new obj` shallow copy (IEEE 1800 §8.12), and a based number
|
||||
whose digits come from a macro (`` 32'h`DM_ADDR ``)~~ — **done**; see
|
||||
@@ -898,6 +908,25 @@ go-to-definition, references and document/workspace symbols — the full list,
|
||||
and what is deliberately *not* advertised yet, is in
|
||||
`docs/features/lucisv-server/README.md`.
|
||||
|
||||
The editor now offers these refactorings alongside rename and port propagation:
|
||||
|
||||
| Action | Behavior |
|
||||
|---|---|
|
||||
| Expand wildcard | Replace `.*` with declaration-order named connections; unmatched ports become `.p()` with a warning |
|
||||
| Convert ports to ANSI | Merge a legacy module header and its body port declarations, preserving comments and attributes |
|
||||
| Organize imports | Remove unused imports, merge exact duplicates and sort a top-of-scope run; uncertainty keeps the action conservative |
|
||||
| Extract module | Move selected whole module items into a named module, infer its interface, and insert the replacement instance; create a file when supported or append below the source module |
|
||||
| Inline module | Copy a separate-file module body into its instance site with simple named-connection substitution and collision-aware internal renaming |
|
||||
|
||||
The [language-tools reference](docs/site/src/content/docs/reference/language-tools.md)
|
||||
records commands and refusal limits. Inline-module has a known transitive
|
||||
source-selection gap; review hierarchical uses through wrapper modules before
|
||||
applying it (topology handshake 33).
|
||||
|
||||
In the VS Code hierarchy, **Star as DUT** groups a module’s children and
|
||||
parents into sections alongside Other Modules. Stars persist per workspace;
|
||||
`lucisv.hierarchy.duts` adds team-configured names, which are locked in the menu.
|
||||
|
||||
**VS Code needs no separate binary**: every release on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases) carries a
|
||||
platform-specific `.vsix` with both binaries inside it — pick yours
|
||||
|
||||
@@ -710,7 +710,7 @@ section only tracks the milestones.
|
||||
- [x] **M14 `macro-expansion`** — single-step macro expansion on hover
|
||||
(the define-table README's promised follow-up); version 0.5.0 with a
|
||||
CHANGELOG entry covering M7–M14.
|
||||
- [ ] Backlog (~~extract module~~, inline, ~~`.*` expansion~~, ~~ANSI
|
||||
- [x] Backlog (~~extract module~~, ~~inline~~, ~~`.*` expansion~~, ~~ANSI
|
||||
conversion~~, ~~organize imports~~, …) — triaged in the umbrella README after M5.
|
||||
**`.*` expansion shipped 2026-09-05 (§50,
|
||||
`docs/features/expand-wildcard/README.md`)**: the wildcard written out as
|
||||
@@ -758,6 +758,7 @@ section only tracks the milestones.
|
||||
crossing the boundary, which no port can carry; **an `initial`/`final`
|
||||
block**, whose meaning is when it runs; and **an unpacked-array or
|
||||
interface-typed name** crossing, which the port renderer will not write.
|
||||
**All five delivered in loop 2** (§50–§53 across 0.46.0–0.49.0); what each one deliberately refuses is listed under "Open items for loop 3" in the Loop 2 order section.
|
||||
|
||||
## 9. LSP 3.18 protocol audit (2026-08-26)
|
||||
|
||||
@@ -4643,8 +4644,77 @@ re-exports (topo 16) → §49 cross-file instance-member tail in rename
|
||||
0.46.0 → §52 organize imports → §53.1 extract module → 0.47.0 →
|
||||
**§56 DUT-centred hierarchy view (owner request 2026-09-06) → 0.48.0** →
|
||||
§53.2 inline module (its own lane; 53.1 consumed the round, as planned)
|
||||
→ §54 coverage gaps L3/L6/L10 → 0.49.0. Sections after §46 are planned when
|
||||
reached.
|
||||
→ §54 coverage gaps L3/L6/L10 → 0.49.0.
|
||||
|
||||
**Closed 2026-09-07.** Every section above shipped in the release named:
|
||||
0.44.0 (§45, §46), 0.45.0 (§47–§49), 0.46.0 (§50, §51), 0.47.0 (§52,
|
||||
§53.1), 0.48.0/0.48.2 (§56; 0.48.0's first packages were built a commit
|
||||
early and 0.48.1 never built — see the changelog), 0.49.0 (§53.2, §54).
|
||||
Loop 2's dev/QA/lead protocol ran in the main tree with no worktrees;
|
||||
its two release slips are recorded in CLAUDE.md's rules of thumb below
|
||||
(§57) and in the lead's memory.
|
||||
|
||||
**Coda (2026-09-07, after the close).** Two owner-requested lanes ran
|
||||
after §57 and shipped together as **0.50.0**: §58 performance take 4
|
||||
(0.49.0 vs 0.43.0; harness committed in `tools/perf/`) and §59 the
|
||||
format-cache key fix for topo §2.9-34, which the owner's doc audit found
|
||||
in 0.49.0. Take 4's findings are in the loop-3 list above.
|
||||
|
||||
**Open items for loop 3** (owner decides; nothing here is in flight):
|
||||
- §44 second finding ruled non-hot; §55 `state.rs` decomposition (958
|
||||
lines, three sentences) — a Fable refactor lane;
|
||||
- topo §2.9-31 DPI-export name binding (dpi-export request (b));
|
||||
- topo §2.9-32 the refactoring verifier and a same-file relocation of a
|
||||
never-dropped piece written as two edits (eq. 3 unreachable);
|
||||
- topo §2.9-33 `module_sources` lacks a transitive-instantiators rung
|
||||
(inline-module's hierarchical scan sees only the handed files);
|
||||
- inline module's deliberate refusals worth their own rounds: same-file
|
||||
`S`, unconnected outputs, any `generate`, prefixing past end labels;
|
||||
extract module's: attributes on absorbed declarations (§51 too), an
|
||||
`interface`'s non-ANSI header (§51), a `.*` inside a `bind` (§50);
|
||||
- `uvm-utils-indent` default (off; 21 corpus files change when on) —
|
||||
revisit after use;
|
||||
- organize imports on files with `` `include``s (refused by design —
|
||||
the preprocessor question, TODO §7's standing non-goal);
|
||||
- **perf take 4 (§58, 2026-09-07) filed:** the lazy `codeAction` offer
|
||||
costs 2–3 ms more at every cursor because `inline_site`/`extract_site`
|
||||
each re-parse the buffer the server already holds (take 4 §8.2 — the
|
||||
fix is §37.1's shape: gate on the document's own tree); §49's tail
|
||||
rename at 751 ms for two files vs 66 ms for one (§8.3 — look at
|
||||
rename's reference walk first, completion on the same surface is
|
||||
free); `check --select error,warning,style` 1.27× on `hw/ip` after
|
||||
`unused-import` (§8.4); two instance-head tails that do not resolve
|
||||
(`pwrmgr.sv` 178:10 in a macro argument, `pinmux.sv` 687:40; §8.5 —
|
||||
a ruling, not a fix); the index +14% at codec 19 (§8.6, watch).
|
||||
- **perf take 5 P1 (§60.1) deferred:** lint-result reuse for the
|
||||
code-action path — a memo of `fixable`'s violations keyed by document
|
||||
revision + tab width + rule set + merged options + waiver contents +
|
||||
index generation (each attacked); worth 24 ms per cursor move on
|
||||
opentitan's largest file, 1–3 ms on ordinary RTL.
|
||||
- **perf take 5 P2d (§60.2) deferred:** the target-scoped rename
|
||||
selector — fan out from the one declaration the open buffer resolves
|
||||
the cursor to, instead of every declaration of the name; the lever
|
||||
left on the tail rename (233 of 388 ms is one parse per selected
|
||||
file, 133 of 238 files being container files a multi-level tail folds
|
||||
through). Needs the whole-scope oracle over the shape list in
|
||||
`docs/features/perf5-p2/README.md` (multi-path references, wildcard
|
||||
imports, package members, `extends`/alias chains, `bind`, `defparam`,
|
||||
`$root`, `` `include``, generate shadows, class members, unsaved
|
||||
buffers) before any file is dropped.
|
||||
- **perf take 5 P3 (§60.3) filed:** the CLI's third parse (the lint
|
||||
pass re-parses every file the census parsed) — retaining the census
|
||||
ASTs was refused as a memory trade (1 805 trees against a 200 MiB
|
||||
peak); and a test pinning `harvest_one`'s lex-only path when neither
|
||||
census half is wanted (needs a `Job` constructor for tests).
|
||||
- **perf take 5 P4b (§60.4) filed:** the first useful answer after a
|
||||
staged startup is ~250 ms cold / ~275 warm (correct in every session)
|
||||
against the old race's 84 / 208 — the gap is the workspace walk in
|
||||
front of the open buffer's folder (`discovery` 158 ms warm: the walk
|
||||
plus one `fs::metadata` per file, which `lucisv_core::walk::collect_files`
|
||||
already stat'd and could hand on), then `cache_open` 89 ms; warm settle
|
||||
~1.04–1.10 s against the plan's < 1 s, the rest being the store open
|
||||
the refused reuse would remove.
|
||||
Sections after §46 are planned when reached.
|
||||
|
||||
## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22
|
||||
|
||||
@@ -4978,7 +5048,10 @@ scope/widen logic, the document store, and the source selectors
|
||||
owner decides where it goes in loop 2.
|
||||
|
||||
- [ ] `state.rs` decomposition (pure move, byte-identical output, test
|
||||
count unchanged); CLAUDE.md's measurement line refreshed
|
||||
count unchanged); CLAUDE.md's measurement line refreshed —
|
||||
**deferred to loop 3 by the lead, 2026-09-07** (958 lines at 0.49.0;
|
||||
the measurement line already says so); a Fable refactor lane when
|
||||
the owner schedules it
|
||||
|
||||
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
|
||||
|
||||
@@ -5451,7 +5524,8 @@ the existing bookmark does (`hierarchyView.js` `BOOKMARK_KEY`).
|
||||
- [x] 56.2 view: section nodes, icons, context values, persistence,
|
||||
setting union
|
||||
- [x] 56.3 commands, menus, package.json, tests, acceptance checklist row
|
||||
- [ ] docs (lead applies README/site)
|
||||
- [x] docs (lead applies README/site) — applied 2026-09-06 (site editors
|
||||
paragraph, topo node; the extension README rows were the dev's)
|
||||
- [x] Gates: `node --test editors/vscode/*_test.js`; vsix smoke; the plain
|
||||
view pinned unchanged
|
||||
- [x] QA: every section shape attacked on the fixture and on opentitan
|
||||
@@ -5462,29 +5536,637 @@ the existing bookmark does (`hierarchyView.js` `BOOKMARK_KEY`).
|
||||
After §53.2 and §54 merge and 0.49.0 ships, the last lane of loop 2 is the
|
||||
lead's own, no dev/QA:
|
||||
|
||||
- [ ] **Tree:** `git status --porcelain` empty; `git worktree list` shows
|
||||
- [x] **Tree:** `git status --porcelain` empty; `git worktree list` shows
|
||||
the main tree only; `git branch` shows `master` only; no local tag
|
||||
that is not on the server; no stray files in the tree
|
||||
(`corpus-check-results.tsv` is ignored — fine); the scratchpad and
|
||||
`~/.cache/lucisv-baselines/wip-*` snapshots deleted.
|
||||
- [ ] **Remote:** `master` pushed and equal to local; every release tag
|
||||
`~/.cache/lucisv-baselines/wip-*` snapshots deleted. — done
|
||||
2026-09-07 at 4c2dae3 (main tree only, `master` only, every local
|
||||
tag on the server, snapshots and scratch leftovers removed).
|
||||
- [x] **Remote:** `master` pushed and equal to local; every release tag
|
||||
on the server; every release with 8 assets; the published vsix of
|
||||
the final release unzipped and checked for the feature files of
|
||||
loop 2 (`hierarchySections.js`, `extract.js`, no `*_test.js`).
|
||||
- [ ] **TODO.md:** every checkbox either ticked or annotated with a
|
||||
— done 2026-09-07: v0.49.0 has 8 assets (run 270); the darwin-arm64
|
||||
vsix carries `hierarchySections.js` and `extract.js`, no `*_test.js`,
|
||||
version 0.49.0.
|
||||
- [x] **TODO.md:** every checkbox either ticked or annotated with a
|
||||
dated ruling (deferred to whom, or dropped why); the "Loop 2 order"
|
||||
section closed with what shipped in which release; §44/§55 and the
|
||||
topo §2.9 open rows (23 done; 29/30 done; 31 DPI export, 32 the
|
||||
verifier same-file relocation) restated in one "open items" list
|
||||
for loop 3.
|
||||
- [ ] **Docs:** `docs/topo.md` rows for every loop-2 lane present;
|
||||
for loop 3. — done 2026-09-07: the only unticked lines left are
|
||||
§55 (deferred, annotated) and the §57 items that wait on the
|
||||
0.49.0 assets.
|
||||
- [x] **Docs:** `docs/topo.md` rows for every loop-2 lane present;
|
||||
`docs/coverage_gaps.md` struck where delivered; CLAUDE.md's
|
||||
measurement line refreshed (`state.rs` 957 lines → whatever §55
|
||||
leaves it; if §55 does not run, the number and the reason);
|
||||
`docs/manual-acceptance.md` rows through §56; the site rebuilt and
|
||||
committed.
|
||||
- [ ] **Memory:** the paused-state memory rewritten as a short current
|
||||
committed. — done 2026-09-07 (CLAUDE.md re-measured at 0.49.0:
|
||||
state.rs 958 with §55 filed; topo rows for §36–§56; L3/L6/L9/L10
|
||||
struck; acceptance rows 15–17; site rebuilt in the §54 commit).
|
||||
- [x] **Memory:** the paused-state memory rewritten as a short current
|
||||
state (not a running log), with the release list and the open items.
|
||||
- [ ] **Closing release:** if anything above changed a shipped file
|
||||
— done 2026-09-07.
|
||||
- [x] **Closing release:** if anything above changed a shipped file
|
||||
(docs count), a final release `0.49.x`/`0.50.0` cut from the clean
|
||||
tree, its assets verified, and the install line given to the owner.
|
||||
— **ruled 2026-09-07: 0.49.0 is the closing release.** The commits
|
||||
after it are TODO/CLAUDE.md/memory bookkeeping only — nothing that
|
||||
reaches a binary, the extension or the site — so no further tag.
|
||||
|
||||
## 58. Performance take 4 on opentitan (owner request 2026-09-07) — 0.49.0 vs 0.43.0 vs take 3
|
||||
|
||||
§40's protocol, one release later. Read-only measurement; a regression is
|
||||
filed with a reproduction, not fixed in this lane. Output:
|
||||
`docs/performance_take4.md`, the same table shapes as
|
||||
`docs/performance_take3.md` so every row is a before/after (take 3's
|
||||
0.43.0 column carried beside the new 0.49.0 column; 0.39.0 where take 3
|
||||
had it), plus a `docs/perf/README.md` entry. Tree:
|
||||
`/Users/guoliangchen/repo/opentitan` (never written; the three
|
||||
pre-existing modified files stay as they are, `git status --porcelain`
|
||||
checked after every phase). Every run under `tools/guard.sh -m 8 -t 1800`.
|
||||
No `cargo` command in any tree during a timed measurement.
|
||||
|
||||
Binaries: the 0.49.0 CLI is `~/.cache/lucisv-baselines/lucisv-0.49.0`
|
||||
(0.43.0 and 0.39.0 beside it); the 0.49.0 server is
|
||||
`target/release/lucisv-server` in the main tree (the tree's code is
|
||||
4c2dae3 = v0.49.0 — verify by sha or `--version` before use, rebuild
|
||||
once with `cargo build --release -p lucisv_server` only if it is stale,
|
||||
before any timing); the 0.43.0 server is built from the `v0.43.0` tag in a
|
||||
scratch `git worktree` under the scratchpad and the worktree removed after.
|
||||
|
||||
- **The harness is committed this time.** Take 2's client was lost and
|
||||
take 3's was reimplemented from prose; take 3's is gone too (the
|
||||
scratchpad is volatile). Take 4's client and drivers live in
|
||||
`tools/perf/` (`lspclient.py`, `bench.py`, `sweep.sh`,
|
||||
`sweeptable.py`, `outcomes.sh`; Python 3 standard library only, a
|
||||
short README saying how to run each phase). Take 5 reuses them.
|
||||
- **Server, the take-3 request table** (take 3 §2, every row): startup
|
||||
and scan per scope config and cache state (cold / warm), the `didOpen`
|
||||
widen at the default scope, `codeAction` at the take-3 cursors (lazy
|
||||
offer and eager, plus `codeAction/resolve` where an action is offered),
|
||||
`prepareRename` / `rename`, `completion`, `definition`, `hover`,
|
||||
`inlayHint`, `references`, `documentSymbol`, `workspaceSymbol`,
|
||||
`semanticTokens/full`, diagnostics publish, the queue-blocking analysis
|
||||
(take 3 §3), the transport baseline and the `--verbose` cross-check
|
||||
(take 3 §0).
|
||||
- **New rows for what 0.44–0.49 added**, each with the 0.43.0 column
|
||||
beside it where the request exists there:
|
||||
- the `didOpen` delay (§46) confirmed on the wire in the release build:
|
||||
`didOpen` → the request behind it for `aes.sv`, `aes_core.sv`,
|
||||
`spi_device.sv`, `pinmux_reg_top.sv` (the perf README's 2026-09-05
|
||||
table was taken with temporary timings — this is the release
|
||||
number);
|
||||
- `codeAction` at the new offer sites: a `.*` instance (expand
|
||||
wildcard), a non-ANSI module header (convert to ANSI), an `import`
|
||||
line (organize imports), a selection of a few module items (extract
|
||||
module), a separate-file instance with named connections (inline
|
||||
module) — the lazy offer and one `resolve` each; how many actions
|
||||
each cursor offers, so the reader knows what was paid for;
|
||||
- `rename` of a net reached through an instance tail (§49's
|
||||
hierarchical surface) and `completion` after `u_x.` on an instance
|
||||
head — pick real opentitan sites and name them;
|
||||
- `lucisv/moduleHierarchy` (the snapshot the DUT view consumes; the
|
||||
sections themselves are client-side and not measured here);
|
||||
- index store size on disk and the server's peak RSS after the
|
||||
workspace scan, 0.43.0 vs 0.49.0 (`FACTS_FORMAT` 18 → 19 added the
|
||||
hierarchical member table and the re-export group).
|
||||
- **CLI sweeps** as take 3 §7 over the same five trees: `format --check`
|
||||
(cold cache and warm), `check` (default rules; `--select
|
||||
error,warning,style`), wall time and peak RSS, 0.49.0 vs 0.43.0 vs
|
||||
0.39.0; failure counts per tree and every per-file outcome that changed
|
||||
since 0.43.0 (expected candidates: §54's grammar — `randsequence`,
|
||||
`->>`, casts, drive strengths, `let`, clocking skews — and §38's
|
||||
outcomes staying fixed; anything else is a finding). The formatter cache
|
||||
goes to a scratch `--cache-dir`; the index cache to a scratch
|
||||
`storagePath`.
|
||||
- **Method** as take 3 §9: three tries per row, first try and repeat
|
||||
range reported, machine state noted (load average before and after
|
||||
each phase; the machine runs a desktop session — say so).
|
||||
- **Findings:** any row slower than take 3 by more than noise is a filed
|
||||
item with a reproduction; anything faster is credited to the section
|
||||
that did it. The eager `codeAction` path is ruled a non-hot path
|
||||
(owner, 2026-09-05) — report it, do not re-file it.
|
||||
- Feature README: `docs/features/performance-take4/README.md` (Goal,
|
||||
Assumptions, Handshakes, Status, Work log, QA log, Review).
|
||||
|
||||
- [x] harness in `tools/perf/` with its README; runs from a clean checkout
|
||||
- [x] server table re-measured, 0.49.0 vs 0.43.0 vs take 3 — take 4 §2
|
||||
- [x] new rows: didOpen release numbers, the five refactoring offer sites,
|
||||
tail rename and instance-head completion, moduleHierarchy, index
|
||||
size and RSS
|
||||
- [x] CLI sweeps, three binaries, RSS included; outcome diff since 0.43.0
|
||||
- [x] `docs/performance_take4.md` + perf README entry
|
||||
- [x] opentitan status unchanged after every phase; no guard kill
|
||||
- [x] QA: a sample of at least eight rows re-run with the committed
|
||||
harness (both binaries) and checked against the document within its
|
||||
stated tolerance; the outcome diff re-derived; opentitan status;
|
||||
every number quoted in the document found in the raw logs
|
||||
|
||||
## 59. The format cache key omits `uvm-utils-indent` (topo §2.9-34, owner's audit 2026-09-07)
|
||||
|
||||
Filed by the repository analysis: `lucisv_core::cache::Entry` and
|
||||
`lucisv/src/main.rs::entry_for` key a verdict on content, `line-length`
|
||||
and `indent` (and the lucisv version), so toggling `[format]
|
||||
uvm-utils-indent` after a clean `--check` keeps the stale clean verdict
|
||||
(`--check` exits 0 while `--no-cache --check` exits 1). Runs after §58
|
||||
(no build during a timed measurement). Feature README:
|
||||
`docs/features/format-cache/README.md` (work log entry, Handshakes
|
||||
amended: the key now names the option).
|
||||
|
||||
- **The key.** `Entry` gains `uvm_utils_indent: bool`; `entry_for`
|
||||
fills it from `Config`; the store line carries it as a fifth field and
|
||||
a line without it (an older store) is dropped individually, like
|
||||
another version's entry. Equality and the codec round-trip tested in
|
||||
`cache.rs`.
|
||||
- **Regression** as the audit's probe, through the real CLI: a UVM class
|
||||
with `uvm_field_int`, cache a clean verdict with the option false,
|
||||
flip to true → `--check` exits 1; and the other direction.
|
||||
- README: the `--no-cache` workaround paragraph in `README.md` and the
|
||||
topo row 34 struck at merge (lead).
|
||||
|
||||
- [x] `Entry`/`entry_for`/store codec, tests
|
||||
- [x] CLI regression, both toggle directions
|
||||
- [x] format-cache README work log + Handshakes
|
||||
- [x] QA: attack the key (another option, another version, a store line
|
||||
with four fields); confirm the audit's probe passes on the fix and
|
||||
fails on 0.49.0
|
||||
|
||||
## 60. Performance take 5 — the implementation plan (owner request 2026-09-07)
|
||||
|
||||
`docs/performance_take5.md` is the spec; `docs/perf/take5-tracking.md`
|
||||
is the ledger every stage fills (baseline columns are the owner's, at
|
||||
0.50.0 / bbdbfe9 — never overwritten); `docs/perf/take5-baseline/` is
|
||||
the evidence. This section only sequences the plan into lanes and names
|
||||
the gates. **Serial, one lane at a time in the main tree** (the plan
|
||||
forbids parallel lanes: P1–P4 share `state.rs`, the selectors and open
|
||||
handshake 33), dev (Opus) → QA (Sonnet) → lead review → commit, the
|
||||
§36 protocol. Every stage: its own feature README
|
||||
(`docs/features/perf5-<stage>/README.md`), the tracker's candidate
|
||||
columns and an experiment entry filled at the exact candidate commit,
|
||||
measured with `tools/perf/` under `tools/guard.sh -m 8 -t 1800`, no
|
||||
build during a timed session, opentitan read-only. A stage's numbers
|
||||
are taken by its dev and re-taken by its QA on the same binary; the
|
||||
lead accepts a number only when both agree within the tracker's
|
||||
tolerance. Targets are the plan's provisional goals: missing one is
|
||||
reported with the measured remaining stage, never hidden.
|
||||
|
||||
### 60.0 P0 — the harness tells the truth (tools/perf only)
|
||||
|
||||
Plan §P0. Files: `tools/perf/*` and its README; no production change.
|
||||
Done 2026-09-07; `docs/features/perf5-p0/README.md`, experiment
|
||||
`P0-2026-09-07` in the tracker.
|
||||
- [x] units and status on every new record (`ms` is latency only; RSS
|
||||
and store size in their own fields with units; `status`
|
||||
ok/error/refused; result counts; a normalized fingerprint of
|
||||
edits/warnings); the schema versioned, the take-4 rows still
|
||||
readable
|
||||
— `tools/perf/schema.py` (new); `record()` validates, `samples()`
|
||||
replaces `Session.ms` so a failed request is never a fast success
|
||||
- [x] edit-bearing offers → `codeAction/resolve`; command-bearing
|
||||
offers (extract, inline) → a separate execute-command scenario
|
||||
that captures the server's `workspace/applyEdit` payload and
|
||||
replies `applied: false` (reason recorded as a client capture,
|
||||
distinct from an engine refusal or an error); created files,
|
||||
edits, refusals, warnings counted
|
||||
— phase `execute`: extraction 257 / 245–247 ms, 2 edits / 2 files
|
||||
/ 1 created, status `capture`; both `aes_wrap.sv` 66:2 offers
|
||||
`refused` with the engine's own sentence
|
||||
- [x] the owner's two supplemental probes become phases
|
||||
(`offerkinds`: the `context.only` families at the five cursors;
|
||||
`offerqueue`: leader/follower); scan completion vs first useful
|
||||
answer separated; fresh-process rows distinguished from repeats
|
||||
- [x] `sweep.sh`: the scratch format cache reset before *each* cold
|
||||
try, warm rows explicitly primed; cold rows show zero hits
|
||||
— verified on `hw/ip` at 0.50.0: cold `0 / 0 / 0`, warm `30 / 30 / 30`
|
||||
- [x] the baseline reproduced on the unchanged binary with the
|
||||
corrected harness — the tracker's "Reference" cells for every
|
||||
row P1/P2 will touch (pinmux comment all-family and `only: []`,
|
||||
`aes`/`aes_reg_top`/`tb.sv` offers, tail rename, `aes` rename,
|
||||
blockers, refactor resolves, the CLI cells) — and a
|
||||
`docs/perf/README.md` note if any baseline row changes meaning
|
||||
— 114 rows, zero guard kills, corpus unchanged after all 16 runs;
|
||||
every CLI stdout hash byte-identical to the baseline's; three rows
|
||||
disagree beyond tolerance and are named, not adjusted
|
||||
- [x] QA: a deliberately rejected request lands as an error; the
|
||||
inline/extract rows show a command and an applyEdit payload or a
|
||||
refusal; cold sweep rows have zero hits; a sample of reference
|
||||
cells re-taken
|
||||
— PASS, 2026-09-07: `docs/features/perf5-p0/README.md` QA log; ten
|
||||
REF cells re-taken (two fingerprints byte-identical), all four
|
||||
acceptance experiments and the schema/`resolve_rows` attacks verified
|
||||
independently, the three named disagreements reproduce and are real
|
||||
|
||||
### 60.1 P1 — code-action discovery stops repeating work
|
||||
|
||||
Plan §P1a then §P1b, one lane, then measured; §P1c only if the ports /
|
||||
import offers still dominate after that measurement (a lead ruling).
|
||||
Files: `lucisv_server/src/{server/dispatch.rs,code_action.rs,lint.rs,
|
||||
ports.rs,imports.rs,extract.rs,inline_module.rs}` plus a *new small
|
||||
module* for any per-revision memo (`state.rs` is over size — §55);
|
||||
`vlog_refactor/src/{ports/,imports.rs,extract/,inline/,lib.rs}` for
|
||||
additive parsed-input selectors beside the text ones. `fence.rs` is
|
||||
NOT touched: the text-only fence authority stays and is memoized per
|
||||
document revision, computed only when a fix needs it
|
||||
(shared-fence-filter's contract).
|
||||
- [x] P1a: the `only` filter checked before config discovery, lint and
|
||||
fence work; `only: []` returns at once; fence regions computed
|
||||
only when a candidate fix exists; kind-prefix semantics,
|
||||
fixes spanning the cursor, fix-all, action order, and a cursor
|
||||
(empty range) still offering extract — all pinned
|
||||
— `only: []` 82.80 → **0.064 ms**; quickfix 84.13 → 23.53; the
|
||||
base separated at last: lint+config 23.5, fence parse 59.3 ms
|
||||
- [x] P1b: selectors over the document's existing parse + diagnostics
|
||||
(large-file mode and parse-diagnostic checks exactly as before);
|
||||
text wrappers retained for standalone consumers and parity
|
||||
tests; fence memo keyed by exact source revision; any lint-result
|
||||
reuse keyed by revision + effective lint/format settings +
|
||||
waivers + workspace generation, or not done
|
||||
— four additive `*_in` selectors; `fences.rs` memo on the
|
||||
`Document`; **lint-result reuse deliberately not done**, reason
|
||||
and number in `P1b-2026-09-07`
|
||||
- [x] work counters (parses per request) prove "no additional parse on
|
||||
a repeated offer" — asserted in tests by count, not by stopwatch
|
||||
— `vlog_parser::stats::parses()`; a repeated no-offer all-family
|
||||
request performs **0** parses, `only: []` **0**, the first
|
||||
request after a `didChange` **≤2**
|
||||
- [x] parity pinned at every sampled cursor/range: no-offer comments,
|
||||
parse errors, CRLF, UTF-16 positions, unsaved edits, untitled and
|
||||
large buffers, action filters, fence insertions, waivers, config
|
||||
change, index refresh
|
||||
— 7 engine tests comparing old against new at *every byte offset*
|
||||
of five fixtures, 12 server tests through the real dispatch
|
||||
- [x] measured: repeated lazy offers < 5 ms; `aes_reg_top` < 10 ms;
|
||||
the pinmux no-offer comment < 16 ms on an unchanged buffer;
|
||||
first-after-edit tracked separately; the pipelined definition
|
||||
re-measured; tracker + experiment entry filled
|
||||
— pinmux 309.60 → **24.02 ms** (−92.2%), queued definition
|
||||
309.40 → **24.61** (−92.0%), `tb.sv` 4.46 → 3.65, `aes_reg_top`
|
||||
23.31 → 21.83. **Two of three targets missed, both residues
|
||||
measured**: the pinmux row is 100% lint, the `aes_reg_top` row is
|
||||
21.15 of 21.83 ms of discarded ports plan. New `offeredit` phase
|
||||
for first-after-edit
|
||||
- [x] lead ruling on P1c from the measurement — **go** (2026-09-07: the
|
||||
`aes_reg_top` offer is 21.8 ms after P1b, 21.2 of it the ports
|
||||
family's discarded plan); lint-result reuse **deferred** to the
|
||||
loop-3 list (24 ms on the largest file; six-surface key; a stale
|
||||
fix offer is the failure mode; the first request after a keystroke
|
||||
pays the pass regardless)
|
||||
— the measurement is in: `aes_reg_top` ports-only 21.15 ms of a
|
||||
21.83 ms row; every other family under 0.15 ms
|
||||
- [x] P1c: engine-owned offer predicates — `vlog_refactor::{port_offers,
|
||||
port_offers_in}` (new `ports/offer.rs`) and `{organize_offer,
|
||||
organize_offer_in}`, each asking only the *plan-time* questions over
|
||||
the buffer's own parse/analysis and at most one parse of the
|
||||
declaring file; no `Scope` for the ports, no `check::verify_splice`
|
||||
for either; `ports::offers` / `imports::offers` on them,
|
||||
`resolve` and `execute` untouched and still verifying
|
||||
— `aes_reg_top` lazy **21.83 → 5.46 ms** (−75.0%), its ports family
|
||||
**21.15 → 3.27** (−84.6%), `aes` **7.76 → 1.74** (−77.6%), the
|
||||
organize-imports offer **15.39 (REF) → 4.88**; **all three targets
|
||||
met**; the eager guardrail unmoved at 492.5 ms
|
||||
- [x] P1c parity: offer ⇔ the eager menu, titles included, at **every byte
|
||||
offset** of eight port fixtures and seven import fixtures (two new
|
||||
engine test files); 50 harness rows field-identical to P1b and 65 to
|
||||
the REF; the three resolve fingerprints byte-identical; a repeated
|
||||
ports offer parses **1** file and a repeated organize-imports offer
|
||||
**3**, asserted by counter against a `resolveSupport` client
|
||||
— residues named, not hidden: the declaring file's parse (2.2–2.4 ms
|
||||
of the ports offer's 3.27) and the buffer's own share of the imports
|
||||
index (~0.8 ms), the second a `vlog_semantic` handshake request
|
||||
- [ ] lead ruling on a lint-result reuse item (new, from P1b's number:
|
||||
24.0 ms, the whole of the pinmux row, for a client that sends no
|
||||
`only`) — a keyed cache in §59's shape, not this lane's to add
|
||||
- [x] QA (P1c): the every-offset parity suites re-attacked, the two
|
||||
counters sabotaged, the numbers re-taken on the same binary
|
||||
— 2026-09-07: ports side clean (three refusal fixtures old vs new
|
||||
vs resolve, counters load-bearing, 13 cells within tolerance, the
|
||||
resolve fingerprints equal to REF); one REWORK finding — the
|
||||
organize-imports offer no longer runs `verify_splice` while its
|
||||
README still called the offer exact — **ruled by the lead**: the
|
||||
narrowing is of the offer's promise only (resolve verifies the same
|
||||
file set before any edit leaves the engine); the organize-imports
|
||||
README amended; the ports/imports offer contract is now the same
|
||||
sentence everywhere.
|
||||
- [x] QA (P1a/P1b): parity attacks as above, the counters, the numbers re-taken
|
||||
— PASS, 2026-09-07: `docs/features/perf5-p1/README.md` QA log; 17
|
||||
cursors byte-identical vs a real v0.50.0 baseline server, counter
|
||||
sabotage caught in 3 places, parity suite verified exhaustive plus
|
||||
one adversarial fixture, a genuine >4 MiB buffer confirmed, all
|
||||
re-measured cells agree within tolerance, gates green
|
||||
|
||||
### 60.2 P2 — rename reuses its analysis, verification untouched
|
||||
|
||||
Plan §P2a → §P2b/§P2c → §P2d only with proof. Handshake 33 (transitive
|
||||
`wrap.u_S.x` users missed by `module_sources`) is resolved and tested
|
||||
*before* any narrower selector is shared with inline/ports. Files:
|
||||
`lucisv_server/src/{rename.rs,state.rs}`, `vlog_refactor/src/{scope.rs,
|
||||
rename/,check/,lib.rs}`, `vlog_semantic/src/workspace/{record.rs,
|
||||
index.rs,update.rs,mod.rs}` as the plan lists — the dev inspects the
|
||||
real paths first and names them in the README.
|
||||
- [x] P2a: stage timings and work counts for the tail rename, `aes`,
|
||||
a unique internal name, `clk`/`rst_n`, an existing/conflicting
|
||||
new name, an unresolved new-name use, the all-sources fallback:
|
||||
selector time, selected paths + bytes with the reason each was
|
||||
included, parses/analyses, occurrence collection, before/after
|
||||
verification, serialization, peak RSS — behind a flag or the
|
||||
`--verbose` channel, never in the default output
|
||||
- [x] P2b: one parse/analysis per file inside the request-local scope
|
||||
(`FileFacts::from_analysis` the starting point); additive
|
||||
prepared-input API, the text API and its answers/refusals
|
||||
unchanged; no workspace-wide AST cache
|
||||
- [x] P2c: the after-index from unchanged facts plus the edited files'
|
||||
one new analysis; untouched watched files keep local semantics
|
||||
and re-resolve externally; token identity, parse-diagnostic
|
||||
preservation, comments/attributes, before/after resolution all
|
||||
still checked; clone/merge/remap cost measured
|
||||
- [x] QA (P2a/P2b/P2c only): PASS — gates, hunk-by-hunk verifier review,
|
||||
sabotage/re-attack (dev's three pairs plus two of QA's own), wire
|
||||
parity (8 `renametrace` rows + 5 QA-chosen renames, old binary vs.
|
||||
candidate), parse-formula sabotage, RSS re-take, traceability; see
|
||||
the QA log in `docs/features/perf5-p2/README.md` (2026-09-07).
|
||||
Handshake 33 and P2d are **not** covered by this QA pass.
|
||||
- [x] handshake 33 closed with tests (multi-level hierarchy, generated
|
||||
scopes, interface/package/class names, macros, duplicate modules,
|
||||
unsaved references) before P2d — an opt-in **fifth rung** on
|
||||
`module_sources`, asked for by inline-module alone: every file whose
|
||||
token census (`files_mentioning`, i.e. `FileFacts::words`) writes
|
||||
the dissolved instance's name. That census is exactly what
|
||||
`no_hierarchy` can refuse from, so the selected set now answers that
|
||||
refusal **as `sources()` does**, asserted by a six-shape
|
||||
whole-workspace equivalence test. Sixteen tests, twelve through the
|
||||
real dispatch; +1.2 ms at the measured site (8 files added); extract
|
||||
and the port actions unchanged in answer and in cost. The
|
||||
transitive-instantiator walk the topology row names was written and
|
||||
**discarded**: it cannot reach a `bind` from a file that
|
||||
instantiates nothing in the chain. Experiment `H33-2026-09-07`
|
||||
- [x] P2d (only with proof): exact-name postings; the selected set
|
||||
unchanged; every edit, warning, ambiguous-use refusal,
|
||||
unresolved new-name capture and unsaved-buffer contribution
|
||||
compared against the whole-scope engine on adversarial cases —
|
||||
**measured; no narrowing shipped, and the proof is why.** The new
|
||||
by-rung census says **133 of the tail rename's 238 selected files
|
||||
(56 %, 58 % of the bytes, ~130 ms) write neither name down**, all of
|
||||
them on the container rungs — and those are what `fold_path` hops
|
||||
through for a multi-level hierarchical tail and what `base_chain`
|
||||
climbs, so dropping them makes a resolved tail `StillUnresolved` (a
|
||||
**missed edit**, §49's own feature) and, where a reference has two
|
||||
paths, lets it fall through onto the target (an **extra edit**).
|
||||
Exact-name postings not implemented: selection is 13.6 ms of 420
|
||||
(3.2 %), below the plan's own materiality gate. The target-scoped
|
||||
selector — fan out from the one declaration the cursor resolves to
|
||||
— is filed with its full shape list and the oracle it needs, as a
|
||||
lane of its own. Experiment `P2d-2026-09-07`
|
||||
- [x] measured: tail rename ≥ 2× faster (stretch < 200 ms), `aes`
|
||||
rename not slower, edit/warning parity exact; queued definition
|
||||
follows; tracker + experiment entries — **1.86×** (780.45 →
|
||||
419.86 ms), so the 2× target is **missed by 29.7 ms**; the
|
||||
measured remaining stage is `Scope::build`'s one parse of each of
|
||||
the 238 *selected* files (225 ms of 420), which only §P2d can
|
||||
reach. `aes` rename −24.8 % (not slower), every edit / warning /
|
||||
refusal fingerprint byte-identical, queued definition −24.5 %,
|
||||
whole-file parses 717 → **240 = K + E**. Experiments
|
||||
`P2a-2026-09-07`, `P2b-2026-09-07`, `P2c-2026-09-07`.
|
||||
**Second lane, 2026-09-07:** still **1.85×** (420.90 ms), because
|
||||
§P2d ships no narrowing; `aes` 106.75 (not slower), queued
|
||||
definition 121.2, every fingerprint still byte-identical, peak RSS
|
||||
not higher (tail 606 MiB, fallback 1 802). The two stages left are
|
||||
`Scope::build` **226 ms (54 %)** and `warnings` **83 ms (20 %)**.
|
||||
`warnings` is **not** dominant, so it was reported rather than
|
||||
fixed: it tokenizes each spelling file up to twice and builds up to
|
||||
four `LineIndex`es, none shared and none of them the parse the scope
|
||||
already made. Two pure dedupes (one tokenize + one index per call;
|
||||
gate `macro_argument_sites` on `files_naming_in_macros`, which is
|
||||
`FileFacts::macro_words`) should take the tail rename to ~375 ms and
|
||||
**over the 2× line**. Filed for the lead.
|
||||
**Third round, 2026-09-07 — the dedupe, and the target met.** One
|
||||
lex and one `LineIndex` per file per `warnings()` call, the five
|
||||
scans sharing them and their sentences concatenated in the order
|
||||
the five loops emitted them: `warnings` **82.2 → 51.4 ms** on the
|
||||
tail rename, 22.9 → 8.3 on `aes`, 848.5 → 437.9 on the `clk_i`
|
||||
fallback. Tail rename **387.95 ms = 2.01× the REF (780.45)**, so
|
||||
the **≥2× target is MET**; `aes` 91.79 (−35.0 %, not slower),
|
||||
queued definition 115.91, every fingerprint byte-identical and the
|
||||
warning **lists** compared as lists across 13 renames against a
|
||||
pre-change binary — identical, order included. Peak RSS tail 596
|
||||
MiB / fallback 1 795. The second gate the finding proposed
|
||||
(`files_naming_in_macros`) is **not shipped**: `macro_words` skips
|
||||
double-quoted runs, so `` `uvm_info("state_q", …) `` is a site the
|
||||
scan reports and the census cannot see. What is left is
|
||||
`Scope::build`, **233 ms of 388 (60 %)**. Experiment
|
||||
`P2d-warnings-2026-09-07`
|
||||
- [x] QA: whole-scope parity suite, the verifier invariant (a faster
|
||||
partial edit is a failure), handshake-33 attacks, numbers re-taken
|
||||
— PASS, 2026-09-07 (Sonnet). Seven handshake-33 attack cases
|
||||
(macro-defined-elsewhere, `$root`, macro-built `bind` target,
|
||||
string/comment negative control, escaped identifier, generate-label
|
||||
path, and a sabotage disabling the rung that proved it load-bearing
|
||||
on the three-level `bind` fixture); the topology row's transitive-
|
||||
instantiator walk independently confirmed structurally unable to
|
||||
reach a `bind` from a non-instantiating file; §P2d's "cannot be
|
||||
dropped" census argument reproduced by experiment (dropping the
|
||||
indirect container file from the dev's own two-level-tail fixture
|
||||
silently loses the tail edit); the `warnings` dedupe re-attacked
|
||||
with two new equality fixtures, a concatenation-order sabotage, and
|
||||
a direct construction of the macro-words-gate non-equivalence; wire
|
||||
parity confirmed over all 13 renames; every fingerprint
|
||||
byte-identical on re-measurement. See the QA log in
|
||||
`docs/features/perf5-p2/README.md`.
|
||||
|
||||
### 60.3 P3 — one parse for the CLI package census
|
||||
|
||||
Plan §P3. Files: `lucisv/src/lint.rs`, `vlog_linter/src/{interfaces.rs,
|
||||
lib.rs}`; a semantic fact-extraction API only if needed, additive; the
|
||||
CLI keeps no direct semantic dependency.
|
||||
- [x] package exports from the census's existing parse; files without a
|
||||
package declaration skip the index work by AST, never by text
|
||||
search; duplicate/unknown packages, nested declarations, malformed
|
||||
source, re-export chains handled exactly as before — additive
|
||||
`vlog_linter::package_exports_in(path, file, tokens, src)`, the gate
|
||||
`walk_items` looking for `ItemKind::Package` (1 624 of `hw/ip`'s
|
||||
1 805 files never build an index), the index itself built from the
|
||||
census's own parse through `FileFacts::from_analysis`; **no
|
||||
`vlog_semantic` change was needed**. Pinned by a 15-fixture equality
|
||||
test against the pre-P3 `WorkspaceIndex::build` body, kept verbatim
|
||||
- [x] default `check` output byte-identical; all-style retains every
|
||||
`unused-import` finding; fixes, waivers, exit codes stable — all
|
||||
five corpus cells' stdout `diff` clean against the reference
|
||||
binary's (`hw/ip` 445 / 7 751 / 7 734, `hw/vendor` 1 666, `hw/dv`
|
||||
1 158), plus six new end-to-end CLI tests
|
||||
- [x] measured: ≥ half of the 123 ms all-style increment removed on
|
||||
`hw/ip`, default time and peak RSS not materially worse; the
|
||||
paired three-configuration experiment; tracker filled — the paired
|
||||
increment **141.7 → 5.0 ms (96 % removed)**, all-style
|
||||
**0.6333 → 0.4817 s (−23.9 %)**, default unchanged (all three
|
||||
binaries median 0.420 s), all-style peak RSS **219.1 → 202.0 MiB**.
|
||||
Experiment `P3-2026-09-07`
|
||||
- [x] QA: full findings/fixes/waivers diffed, not counts; RSS re-taken
|
||||
|
||||
### 60.4 P4 — startup and memory, only after P1–P3
|
||||
|
||||
Plan §P4a (instrument: discovery/config wait, read/hash, decode, merge,
|
||||
completion/include tables, overlay refresh, cache write/compaction,
|
||||
first useful answer; 1/10/100 open buffers; requests during a scan)
|
||||
then §P4b (the dominant measured stage only). Files: `server/index.rs`,
|
||||
`state.rs`, `index_cache.rs`, `candidates.rs`, `includes.rs` and the
|
||||
semantic build/facts owners. Serialized after 60.1–60.3.
|
||||
- [x] P4a instrumentation and the measured breakdown in the tracker
|
||||
(2026-09-07; `docs/features/perf5-p4/README.md`, experiment
|
||||
`P4a-2026-09-07`). Three `timing: scan <n> …` lines per scan on
|
||||
the `--verbose` channel; `tools/perf/phases_p4.py` reads them.
|
||||
**A workspace session pays three scans and the first indexes
|
||||
zero files** — warm it still costs 183.7 ms opening and
|
||||
compacting a 44.3 MiB store it never uses, which is also the
|
||||
whole of §P0's cold-84 / warm-209 first-answer puzzle. Warm
|
||||
settle 1 332.7 ms has no dominant stage but 27.5 % of it is the
|
||||
store's own I/O; cold settle 2 893.6 ms is 58.9 % parse. The
|
||||
encoded-facts retention §P4 hypothesised is real: 44.20 MiB,
|
||||
7.7 % of warm idle RSS. Requests queued behind the configured
|
||||
rescan wait 2.56 s cold / 0.90 s warm, with zero mismatched
|
||||
tables in 18 mid-scan answers
|
||||
- [x] lead ruling: which stage, or none — **2026-09-08: go** on (a) skip
|
||||
`compact` when the store is unchanged and was loaded canonical,
|
||||
(b1) no store open/compact for an empty work list (open deferred to
|
||||
the first file); **refused** (b2) store reuse across rescans (the
|
||||
reopen guards a mid-session cache-path change and a second session's
|
||||
compaction); plus: why the configured rescan does not interleave
|
||||
navigation (fix if routing, file if not), and the trace helpers
|
||||
moved out of `state.rs`
|
||||
- [x] P4b if ruled: warm < 1 s / cold < 2.3 s / idle RSS −15% as
|
||||
investigation goals; interrupted-store recovery, coherent
|
||||
index/candidate/include prefix, content-based freshness, the
|
||||
16 MiB parser stack on any new thread, §46's open path — all
|
||||
preserved and pinned
|
||||
(2026-09-08; `docs/features/perf5-p4/README.md` §P4b, experiment
|
||||
`P4b-2026-09-08`). **(a) + (b1) shipped, (b2) refused, the
|
||||
interleaving question answered and filed.** Measured against a
|
||||
same-window control built from HEAD: **warm settle 1 326.85 →
|
||||
1 137.66 ms, −14.3 %**; cold −1.1 % (unchanged, as predicted);
|
||||
**warm idle RSS −15.3 %**, the one goal §P4a had ruled out — it is
|
||||
the two 44.3 MiB render buffers, not the encoded-facts retention.
|
||||
The store is left byte- **and mtime-**identical across two warm
|
||||
sessions where HEAD rewrote the same 46 486 433 bytes each time.
|
||||
`mismatched_answers` 0, the scope ladder answers identically in all
|
||||
eight cells, §46's `didOpen` path −3.3 %. **Warm < 1 s missed** and
|
||||
needs the refused (b2): `cache_open` is still paid twice, 181.7 ms.
|
||||
**One deviation reported**: `IndexCache::record` now skips a record
|
||||
the store already holds, without which (a) fires in no session that
|
||||
has a buffer open. **One regression named**: the warm first useful
|
||||
answer is bimodal, 117 ms or the whole configured rescan, because
|
||||
removing the empty scan's 181 ms removed the head start the
|
||||
`didOpen` used to win its race with the configuration answer — the
|
||||
`must_wait` order contract, filed for the lead with the narrow fix.
|
||||
**Closed 2026-09-08 by the P4b2 line below**, and not by that narrow
|
||||
fix: the lead ruled the plan's own sentence instead
|
||||
- [x] P4b2 (the lead's ruling on that regression, 2026-09-08): **stage the
|
||||
initial scan until configuration arrives**, with a bounded fallback
|
||||
for clients that never answer, rootless and scope precedence intact
|
||||
(`docs/features/perf5-p4/README.md` §P4b2, experiment
|
||||
`P4b-staged-2026-09-08`; new `server/startup.rs`).
|
||||
`Server::started` sends `workspace/configuration` first and waits up
|
||||
to `CONFIGURATION_WAIT` (2 s) on `recv_timeout` — no poll, no
|
||||
busy-wait — then runs **one** startup scan at the answered scope.
|
||||
The empty default-scope scan and the widen behind it are gone; a
|
||||
`didOpen` in the window is folded into that scan (its file first in
|
||||
the work list) and a request is held and answered *inside* it.
|
||||
Paired against the previous P4b release: **warm settled 1 181.34 →
|
||||
1 097.98 ms, −7.1 %**, and on the shipped binary re-run **1 190.48 →
|
||||
1 037.31 ms, −12.9 %** (the two runs bracket the ≤ ~1.06 s target);
|
||||
cold −4.0 % / −2.5 %; `scopeDepth 0` −89.2 % cold /
|
||||
−72.6 % warm; 1/10/100 open buffers −28.4 / −26.8 / −21.0 %; warm
|
||||
`cache_open` **183.70 → 91.91 ms** — the refused (b2)'s saving,
|
||||
arriving without store reuse; warm idle RSS −5.8 %; store byte- and
|
||||
mtime-identical; all 24 scope answers identical; `didOpen` pinmux
|
||||
−6.3 %; `mismatched_answers` 0. **The `scanserve` "queued behind the
|
||||
configured rescan" mode is gone for the startup case.** **One
|
||||
regression, filed:** the first useful answer is now unimodal but
|
||||
**empty** — 293–411 ms with result count 0, because `begin_scan`'s
|
||||
discovery (292.74 ms warm) is the floor and the first drain
|
||||
publishes the open buffer alone; the fix is an `open_first` ordering
|
||||
change in `state.rs`, which this lane holds calls-only (Handshake
|
||||
11). **One defect found by measuring and fixed**: a settings answer
|
||||
stranded in `held` behind a request cost the whole bound
|
||||
- [x] P4b3 (P4b2's empty first useful answer, closed — Handshake 11
|
||||
granted, 2026-09-08): **the read is lazy and the order is the
|
||||
user's** (`docs/features/perf5-p4/README.md` §P4b3, experiment
|
||||
`P4b-lazy-2026-09-08`; new `crate::scan_order`, `state.rs` split
|
||||
into `state/mod.rs` + `state/scan.rs` as a pure move).
|
||||
`collect_sources` resolves the scope and reads **nothing** off
|
||||
disk; `scan_step` reads a file's text when it indexes it, takes the
|
||||
hash, the parse, the words and the `` `include`` lines out of that
|
||||
one read, and drops it — proved read-once by a thread-local counter
|
||||
in the shape of `vlog_parser::stats::parses`. The work list leads
|
||||
with the open buffers and the folders they raise to, and a held
|
||||
request — or one behind a mid-scan `didOpen` — waits for that
|
||||
folder (`Server::head_owed`, a fifth `must_wait` clause) before it
|
||||
is answered. **The first useful answer is result count 1 in twelve
|
||||
sessions of twelve**, where P4b2 was 0 in twelve of twelve, and
|
||||
faster: cold 287.40 → **249.00 ms (−13.4 %)**, warm 332.68 →
|
||||
**277.37 (−16.6 %)**. `work_kib` **34 973 → 0–16**; idle RSS
|
||||
**−7.0 % cold / −7.2 % warm**, peak still equal to idle;
|
||||
`discovery` **227 → 158 ms** warm with a new `read` stage at 86;
|
||||
`includes` **42 → 8.6 ms**. Settled unchanged within noise
|
||||
(−5.2 % / −3.0 % in `scan`, +0.9 % / +1.9 % in `scanprofile`, both
|
||||
quoted); all 24 scope answers identical; the persistent store
|
||||
**byte-identical** from both binaries; `mismatched_answers` 0;
|
||||
§46's `didOpen` untouched. **The latency target is missed and now
|
||||
explained: the first useful answer is walk-bound** — `discovery` is
|
||||
158 ms of pure scope walk, 58 % of the warm answer, and
|
||||
`cache_open` is another 89 (the refused (b2)). The §P0 REF's
|
||||
84/208 ms was answered off a 124-file *folder* scan that never
|
||||
walked the workspace. **One defect found by measuring**: the
|
||||
ordering alone left five sessions of six empty, because the client
|
||||
answers the settings pull from its own reader thread and beats the
|
||||
editor's `didOpen` — hence the drain rule
|
||||
- [x] QA (P4b2): re-take the paired numbers; attack the bound (an answer
|
||||
at the deadline, twice, an error, a `null`), the window
|
||||
(`shutdown`, `didClose`, a folder change, a filelist push, a burst
|
||||
putting a request in front of the answer),
|
||||
`take_the_answer_out_of_held`'s reordering and the rootless path;
|
||||
rule on the empty first useful answer — **answered by P4b3 above**
|
||||
- [x] QA (P4b3): re-take the paired numbers, in particular the
|
||||
twelve-of-twelve result count and the walk-bound floor; attack the
|
||||
lazy read (a file deleted, truncated or replaced between the walk
|
||||
and its own step — the `unread` path, the skip count, and whether
|
||||
the file really leaves the index), the read-once counter (does any
|
||||
path read a file twice), the ordering (rootless, `untitled:`, a
|
||||
filelist scope, a capped buffer, 100 buffers, and
|
||||
`worth_waiting`'s edges), the drain rule (a `didClose` mid-scan, a
|
||||
`shutdown` behind a `didOpen`, two `didOpen`s in one burst, a
|
||||
cancel behind a held request, and whether `head_owed` can be left
|
||||
true with no scan running), and the include graph and completion
|
||||
tables against a text-built pair on a tree with duplicate
|
||||
spellings and `+incdir+`s
|
||||
- [ ] the walk, filed by P4b3 for the next lane: `discovery` is 158 ms of
|
||||
scope walk plus one `fs::metadata` per file for the size cap, and
|
||||
it is the floor under every first useful answer. Two things to
|
||||
measure before building anything — the cap taking its size from the
|
||||
walk's own metadata (`lucisv_core::walk::collect_files` is not
|
||||
P4b3's file: a handshake request) and handing the first folder to
|
||||
`scan_step` before the walk has finished the workspace
|
||||
- [x] QA (P4a only, 2026-09-08: gates green, 4272/4272, no behaviour
|
||||
change verified by hunk review and by running both binaries —
|
||||
44/44 identical result_counts and identical scan file-counts;
|
||||
instrument cost and every table number reproduced independently;
|
||||
docs/features/perf5-p4/README.md QA log. P4b still needs the
|
||||
lead's ruling and is unimplemented)
|
||||
- [x] QA (P4b): re-take the paired numbers on the same binary against the
|
||||
same-window HEAD control; re-attack the six clauses of the
|
||||
compaction skip and the deferred open (the dev's own attacks are in
|
||||
the work log); rule on the one deviation
|
||||
(`IndexCache::record`'s early return) and on whether the bimodal
|
||||
warm first answer is acceptable while the interleaving finding is
|
||||
open
|
||||
|
||||
### 60.5 Closing
|
||||
|
||||
- [x] P5 stays deferred unless a stage's measurement reopens it (lead)
|
||||
— 2026-09-08: nothing reopened it; the first-after-edit row after
|
||||
P1 is inside the frame, and no user command still blocks navigation
|
||||
for a whole scan on the startup path
|
||||
- [ ] `docs/perf/README.md` entry with the accepted numbers; topo
|
||||
edges/handshakes for every contract amended; the plan's status
|
||||
line updated; a release cut from the clean tree with its assets
|
||||
verified
|
||||
+46
-32
@@ -78,6 +78,44 @@ pub struct Census {
|
||||
packages: HashMap<String, Option<Vec<String>>>,
|
||||
}
|
||||
|
||||
/// What one file contributes to a [`Census`]: its words, the units it
|
||||
/// declares, and the packages it exports from.
|
||||
type PerFile = (
|
||||
Vec<String>,
|
||||
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
|
||||
Vec<(String, Option<Vec<String>>)>,
|
||||
);
|
||||
|
||||
/// One file's three contributions, off **one** parse.
|
||||
///
|
||||
/// The word census wants the tokens, the interface table wants the tree and
|
||||
/// the package table wants both — so a run that asks for either table lexes
|
||||
/// and parses the file exactly once and all three read that. A run that asks
|
||||
/// for neither never parses at all: `harvest_text` lexes and stops, which is
|
||||
/// what the word census alone needs.
|
||||
///
|
||||
/// A file that cannot be read contributes nothing, and so does one that does
|
||||
/// not lex (`harvest_text` and a `ParsedSource` with no tokens agree on that).
|
||||
/// The file's own check is what reports the error.
|
||||
fn harvest_one(job: &Job, interfaces: bool, packages: bool) -> PerFile {
|
||||
let Ok(src) = std::fs::read_to_string(&job.path) else {
|
||||
return (Vec::new(), Vec::new(), Vec::new());
|
||||
};
|
||||
if !interfaces && !packages {
|
||||
return (words::harvest_text(&src), Vec::new(), Vec::new());
|
||||
}
|
||||
let parsed = ParsedSource::parse(&src);
|
||||
let declared = match interfaces {
|
||||
true => vlog_linter::module_interfaces(parsed.file()),
|
||||
false => Vec::new(),
|
||||
};
|
||||
let exports = match packages {
|
||||
true => vlog_linter::package_exports_in(&job.path, parsed.file(), parsed.tokens(), &src),
|
||||
false => Vec::new(),
|
||||
};
|
||||
(words::harvest(parsed.tokens()), declared, exports)
|
||||
}
|
||||
|
||||
impl Census {
|
||||
/// The census of every file in the run, harvested in parallel.
|
||||
///
|
||||
@@ -86,39 +124,15 @@ impl Census {
|
||||
/// file's own check reports the error.
|
||||
///
|
||||
/// `interfaces` says whether the run also needs each unit's ports and
|
||||
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
|
||||
/// of every file on top of the lex the word census already pays for, so
|
||||
/// it is built only when some enabled rule asks — measured on opentitan
|
||||
/// `hw/` in `docs/features/linter-expansion-1/README.md`.
|
||||
/// parameters (`unknown-port`, `unknown-parameter`), and `packages`
|
||||
/// whether it needs each package's exported names (`unused-import`).
|
||||
/// Either costs a **parse** of every file on top of the lex the word
|
||||
/// census already pays for, so each is built only when some enabled rule
|
||||
/// asks — measured on opentitan `hw/` in
|
||||
/// `docs/features/linter-expansion-1/README.md`.
|
||||
fn of(jobs: &[Job], interfaces: bool, packages: bool) -> Census {
|
||||
type PerFile = (
|
||||
Vec<String>,
|
||||
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
|
||||
Vec<(String, Option<Vec<String>>)>,
|
||||
);
|
||||
let per_file: Vec<PerFile> = jobs
|
||||
.par_iter()
|
||||
.map(|job| {
|
||||
let Ok(src) = std::fs::read_to_string(&job.path) else {
|
||||
return (Vec::new(), Vec::new(), Vec::new());
|
||||
};
|
||||
let exports = match packages {
|
||||
true => vlog_linter::package_exports(&job.path, &src),
|
||||
false => Vec::new(),
|
||||
};
|
||||
if !interfaces {
|
||||
return (words::harvest_text(&src), Vec::new(), exports);
|
||||
}
|
||||
// One lex for both halves: the parse is what the interface
|
||||
// table needs, and its tokens are the word census's.
|
||||
let parsed = ParsedSource::parse(&src);
|
||||
(
|
||||
words::harvest(parsed.tokens()),
|
||||
vlog_linter::module_interfaces(parsed.file()),
|
||||
exports,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let per_file: Vec<PerFile> =
|
||||
jobs.par_iter().map(|job| harvest_one(job, interfaces, packages)).collect();
|
||||
|
||||
let mut files: HashMap<String, u32> = HashMap::new();
|
||||
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
|
||||
|
||||
@@ -333,7 +333,12 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
|
||||
/// the key, not the config file that produced them, so identical settings
|
||||
/// from different `lucisv.toml` files share entries.
|
||||
fn entry_for(content: u64, config: &Config) -> Entry {
|
||||
Entry { content, line_length: config.max_width, indent: config.indent_width }
|
||||
Entry {
|
||||
content,
|
||||
line_length: config.max_width,
|
||||
indent: config.indent_width,
|
||||
uvm_utils_indent: config.uvm_utils_indent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds rayon's global pool. Worker stacks are sized for the parser's
|
||||
|
||||
+197
-5
@@ -1267,16 +1267,18 @@ impl TempDir {
|
||||
}
|
||||
}
|
||||
|
||||
/// One hand-written cache line, for the tests that forge entries.
|
||||
/// One hand-written cache line, for the tests that forge entries. The
|
||||
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
|
||||
fn cache_line(
|
||||
path: &str,
|
||||
content: &str,
|
||||
line_length: usize,
|
||||
indent: usize,
|
||||
uvm: bool,
|
||||
version: &str,
|
||||
) -> String {
|
||||
let hash = lucisv_core::cache::content_hash(content.as_bytes());
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{version}\t{path}\n")
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1363,7 +1365,8 @@ fn a_hit_skips_the_work_entirely() {
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 2, "without an entry this file is an error");
|
||||
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, VERSION)).unwrap();
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, false, VERSION))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "a hit does no work at all: {}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
@@ -1388,6 +1391,65 @@ fn a_config_file_change_invalidates_the_entry_too() {
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// A UVM class whose layout depends on `[format] uvm-utils-indent`: with the
|
||||
/// option on, the `` `uvm_field_* `` macro gains a level. Written here as the
|
||||
/// formatter leaves it with the option *off*.
|
||||
const UVM_CLASS: &str = "class c extends uvm_object;\n `uvm_object_utils_begin(c)\n \
|
||||
`uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
|
||||
|
||||
#[test]
|
||||
fn changing_uvm_utils_indent_invalidates_the_entry() {
|
||||
let dir = TempDir::new("cache-uvm");
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
|
||||
let path = dir.write("a.sv", UVM_CLASS);
|
||||
let cache = dir.cache();
|
||||
|
||||
// Clean with the option off, and that verdict is cached.
|
||||
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
|
||||
let flat = dir.read("a.sv");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
// Turning the option on must not hit the entry the option-off run left.
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "uvm-utils-indent is part of the key: {}", stderr(&out));
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
|
||||
// Format under the option on, cache *that*, then flip back off.
|
||||
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
|
||||
assert_ne!(dir.read("a.sv"), flat, "the option really does change the output");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "and the other direction too: {}", stderr(&out));
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_written_before_the_option_joined_the_key_is_rebuilt() {
|
||||
let dir = TempDir::new("cache-oldshape");
|
||||
let path = dir.write("a.sv", FORMATTED);
|
||||
let cache = dir.cache();
|
||||
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
|
||||
|
||||
// The five-field line lucisv wrote before `uvm-utils-indent` was in the
|
||||
// key. Not corruption: the line is dropped on its own and the run
|
||||
// rebuilds the store in the current shape.
|
||||
let hash = lucisv_core::cache::content_hash(FORMATTED.as_bytes());
|
||||
std::fs::write(dir.cache_file(), format!("{hash:016x}\t100\t2\t{VERSION}\t{path}\n")).unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "an older store is never an error: {}", stderr(&out));
|
||||
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
|
||||
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert!(stderr(&out).contains("1 file from cache"), "the store was rebuilt: {}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_from_another_lucisv_version_is_ignored() {
|
||||
let dir = TempDir::new("cache-version");
|
||||
@@ -1397,13 +1459,14 @@ fn an_entry_from_another_lucisv_version_is_ignored() {
|
||||
|
||||
// A forged entry claiming this unformatted file is clean. With this
|
||||
// version's stamp it is believed…
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, VERSION)).unwrap();
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, VERSION))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "the forged entry proves entries are really read");
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
// …and with any other version's stamp it is not.
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, "0.0.0-other"))
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, "0.0.0-other"))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "another version's entry must not be trusted: {}", stderr(&out));
|
||||
@@ -2231,3 +2294,132 @@ fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The package half of the census and `unused-import` (perf5-p3, 2026-09-07)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A package with two exported names, and the two importers the rule has to
|
||||
/// tell apart.
|
||||
const PKG: &str = "package p_pkg;\n localparam int A = 1;\n localparam int B = 2;\nendpackage\n";
|
||||
const USES_PKG: &str = "module uses_pkg;\n import p_pkg::*;\n localparam int C = A;\nendmodule\n";
|
||||
const IGNORES_PKG: &str =
|
||||
"module ignores_pkg;\n import p_pkg::*;\n localparam int C = 1;\nendmodule\n";
|
||||
|
||||
/// The style selection the rule lives in — `unused-import` is `Severity::Style`
|
||||
/// and so is off in a default `check`.
|
||||
const ALL_STYLE: [&str; 2] = ["--select", "error,warning,style"];
|
||||
|
||||
/// The headline: over a project, an import nothing in its file uses is
|
||||
/// reported, and one the file does use is not — and it is the *package
|
||||
/// census* that makes the difference, because the rule can only judge an
|
||||
/// import whose package the run can answer for.
|
||||
#[test]
|
||||
fn an_unused_package_import_is_reported_over_a_project() {
|
||||
let dir = TempDir::new("pkg-census");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let out = run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("unused-import"), "{text}");
|
||||
assert!(text.contains("ignores_pkg.sv"), "{text}");
|
||||
assert!(
|
||||
!text.lines().any(|line| line.contains("uses_pkg.sv") && line.contains("unused-import")),
|
||||
"the file that reads `A` keeps its import: {text}"
|
||||
);
|
||||
assert_eq!(code(&out), 1);
|
||||
}
|
||||
|
||||
/// `unused-import` is a style rule, so a default `check` neither reports it
|
||||
/// nor is changed by the presence of a package in the run.
|
||||
#[test]
|
||||
fn a_default_check_says_nothing_about_imports() {
|
||||
let dir = TempDir::new("pkg-default");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert!(!stdout(&out).contains("unused-import"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
/// A package the run does not contain is a package the run cannot answer
|
||||
/// for, and the rule is silent about every import of it. This is the
|
||||
/// conservative direction the whole feature is built around: an accusation
|
||||
/// needs a known export list.
|
||||
#[test]
|
||||
fn an_import_of_a_package_outside_the_run_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-unknown");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write(
|
||||
"stranger.sv",
|
||||
"module stranger;\n import elsewhere_pkg::*;\n localparam int C = 1;\nendmodule\n",
|
||||
);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("elsewhere_pkg"), "an unknown package is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// A package that re-exports from another one answers `None`: only a whole
|
||||
/// project index settles what a re-export chain lets through, and the CLI's
|
||||
/// one-file census will not guess. Every import of it goes quiet.
|
||||
#[test]
|
||||
fn an_import_of_a_re_exporting_package_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-reexport");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write(
|
||||
"r_pkg.sv",
|
||||
"package r_pkg;\n import p_pkg::*;\n export p_pkg::*;\n localparam int D = 1;\n\
|
||||
endpackage\n",
|
||||
);
|
||||
dir.write(
|
||||
"ignores_r.sv",
|
||||
"module ignores_r;\n import r_pkg::*;\n localparam int C = 1;\nendmodule\n",
|
||||
);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("r_pkg"), "a re-export chain is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// Two files declaring one package name is a name the run cannot answer for,
|
||||
/// whatever the two say — `Census::of`'s merge turns the second contribution
|
||||
/// into `None`, and the rule goes quiet about it.
|
||||
#[test]
|
||||
fn an_import_of_a_package_two_files_declare_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-duplicate");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("p_pkg_copy.sv", "package p_pkg;\n localparam int Z = 9;\nendpackage\n");
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("unused-import"), "a duplicate package is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// The gate is a claim about *cost*, not about answers, so the answers get
|
||||
/// their own end-to-end pin: a run whose only package file is surrounded by
|
||||
/// files holding the word `package` in strings and comments reports exactly
|
||||
/// what a run without those files reports.
|
||||
#[test]
|
||||
fn text_that_merely_says_package_changes_no_finding() {
|
||||
let bare = TempDir::new("pkg-bare");
|
||||
bare.write("p_pkg.sv", PKG);
|
||||
bare.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let plain = stdout(&run(&["check", &bare.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
|
||||
let noisy = TempDir::new("pkg-noisy");
|
||||
noisy.write("p_pkg.sv", PKG);
|
||||
noisy.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
noisy.write(
|
||||
"talker.sv",
|
||||
"// package q_pkg; endpackage\n\
|
||||
module talker;\n initial $display(\"package q_pkg; endpackage\");\nendmodule\n",
|
||||
);
|
||||
let with_noise = stdout(&run(&["check", &noisy.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
for finding in plain.lines().filter(|line| line.contains("unused-import")) {
|
||||
let tail = finding.rsplit('/').next().unwrap_or(finding);
|
||||
assert!(with_noise.contains(tail), "{tail} lost: {with_noise}");
|
||||
}
|
||||
assert_eq!(
|
||||
plain.matches("unused-import").count(),
|
||||
with_noise.matches("unused-import").count(),
|
||||
"{plain}\n---\n{with_noise}"
|
||||
);
|
||||
}
|
||||
@@ -32,6 +32,9 @@ pub struct Entry {
|
||||
pub line_length: usize,
|
||||
/// The `indent` that verdict was reached under.
|
||||
pub indent: usize,
|
||||
/// The `[format] uvm-utils-indent` that verdict was reached under: it
|
||||
/// changes the output of a UVM class, so it is part of the key.
|
||||
pub uvm_utils_indent: bool,
|
||||
}
|
||||
|
||||
/// The cache for one run: loaded once at startup, written once at exit.
|
||||
@@ -104,8 +107,8 @@ impl Cache {
|
||||
let entry = &self.entries[path];
|
||||
let _ = writeln!(
|
||||
text,
|
||||
"{:016x}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent
|
||||
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
|
||||
);
|
||||
}
|
||||
text
|
||||
@@ -137,25 +140,49 @@ fn key(path: &Path) -> Option<&str> {
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// The `(content, line-length, indent)` prefix every store line has ever
|
||||
/// begun with, or `None` when those three fields are not what lucisv writes.
|
||||
fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize, usize)> {
|
||||
Some((u64::from_str_radix(content, 16).ok()?, line_length.parse().ok()?, indent.parse().ok()?))
|
||||
}
|
||||
|
||||
/// Parses the store. `None` means "this file is not something lucisv wrote"
|
||||
/// — one malformed line discards the whole cache, because partial trust in
|
||||
/// a file already caught lying is not worth the branch. Entries from
|
||||
/// another lucisv version are dropped individually; that is staleness, not
|
||||
/// corruption.
|
||||
/// another lucisv version, and lines written in an older field layout, are
|
||||
/// dropped individually; that is staleness, not corruption.
|
||||
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
|
||||
let mut entries = HashMap::new();
|
||||
for line in text.lines() {
|
||||
let mut fields = line.splitn(5, '\t');
|
||||
let content = u64::from_str_radix(fields.next()?, 16).ok()?;
|
||||
let line_length = fields.next()?.parse().ok()?;
|
||||
let indent = fields.next()?.parse().ok()?;
|
||||
let version = fields.next()?;
|
||||
let path = fields.next()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
entries.insert(path.to_string(), Entry { content, line_length, indent });
|
||||
let fields: Vec<&str> = line.splitn(6, '\t').collect();
|
||||
match fields[..] {
|
||||
[content, line_length, indent, uvm, version, path] => {
|
||||
let (content, line_length, indent) = prefix(content, line_length, indent)?;
|
||||
let uvm_utils_indent = uvm.parse().ok()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
entries.insert(
|
||||
path.to_string(),
|
||||
Entry { content, line_length, indent, uvm_utils_indent },
|
||||
);
|
||||
}
|
||||
}
|
||||
// A store written before `uvm-utils-indent` joined the key: a
|
||||
// well-formed line of that older shape says nothing about the
|
||||
// option, so it is dropped individually, exactly like another
|
||||
// version's entry. (The version field alone already makes such
|
||||
// a store miss; the codec stays self-describing anyway.)
|
||||
// Anything else on five fields is corruption and discards the
|
||||
// file like any other malformed line.
|
||||
[content, line_length, indent, _version, path] => {
|
||||
prefix(content, line_length, indent)?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(entries)
|
||||
@@ -201,7 +228,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn entry(content: u64) -> Entry {
|
||||
Entry { content, line_length: 100, indent: 2 }
|
||||
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -234,9 +261,53 @@ mod tests {
|
||||
assert!(!reloaded.is_clean(&file, entry(0xbeef)));
|
||||
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uvm_utils_indent_alone_is_a_different_entry() {
|
||||
let on = Entry { uvm_utils_indent: true, ..entry(0xdead) };
|
||||
assert_ne!(entry(0xdead), on, "the option is part of equality");
|
||||
|
||||
// …and it survives the round trip through the store, on its own.
|
||||
let dir = TempDir::new("uvm");
|
||||
let file = dir.file("a.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&file, on);
|
||||
cache.store();
|
||||
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
|
||||
|
||||
let reloaded = Cache::load(&dir.path);
|
||||
assert!(reloaded.is_clean(&file, on));
|
||||
assert!(!reloaded.is_clean(&file, entry(0xdead)), "the option must invalidate the entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_without_the_option_is_dropped_but_not_fatal() {
|
||||
// The five-field shape lucisv wrote before `uvm-utils-indent` joined
|
||||
// the key: stale, like another version's entry, never corruption.
|
||||
let dir = TempDir::new("oldshape");
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
mine.to_string_lossy()
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), text).unwrap();
|
||||
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&old, entry(1)), "a line without the option must not be trusted");
|
||||
assert!(cache.is_clean(&mine, entry(2)), "and it does not discard the rest of the file");
|
||||
|
||||
// And it is not carried forward.
|
||||
cache.store();
|
||||
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_sorted_and_carries_the_version() {
|
||||
let dir = TempDir::new("format");
|
||||
@@ -254,7 +325,7 @@ mod tests {
|
||||
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
|
||||
assert_eq!(
|
||||
lines[0],
|
||||
format!("{:016x}\t100\t2\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
@@ -277,12 +348,15 @@ mod tests {
|
||||
"0000000000000001\twide\t2\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\t0.2.0\n",
|
||||
"0000000000000001\t100\t2\t0.2.0\t\n",
|
||||
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
|
||||
"\0\0\0\n",
|
||||
] {
|
||||
let dir = TempDir::new("corrupt");
|
||||
let file = dir.file("a.sv");
|
||||
// A good line first: a bad one anywhere discards all of them.
|
||||
let good = format!("{:016x}\t100\t2\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
let good =
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
|
||||
@@ -295,7 +369,8 @@ mod tests {
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t0.0.0-not-this-one\t{}\n{:016x}\t100\t2\t{VERSION}\t{}\n",
|
||||
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
|
||||
@@ -108,23 +108,49 @@ impl Candidates {
|
||||
/// here, exactly as every file used to be. The two produce the same words
|
||||
/// because they are the same function over the same tokens
|
||||
/// ([`words_of_tokens`]).
|
||||
///
|
||||
/// Test-only since 2026-09-08: a scan holds every file's words and no
|
||||
/// file's text, so it calls [`Candidates::from_words`]. This is that call
|
||||
/// with the lex in front of it, which is what a test building tables from
|
||||
/// a fixture's text wants and what makes the two one function.
|
||||
#[cfg(test)]
|
||||
pub fn build(
|
||||
index: &WorkspaceIndex,
|
||||
sources: &[(PathBuf, String)],
|
||||
mut known: HashMap<PathBuf, Vec<String>>,
|
||||
) -> Candidates {
|
||||
let words = sources
|
||||
.iter()
|
||||
.map(|(path, text)| {
|
||||
let words = known.remove(path).unwrap_or_else(|| words_in(text));
|
||||
(path.clone(), words)
|
||||
})
|
||||
.collect();
|
||||
Candidates::from_words(index, words)
|
||||
}
|
||||
|
||||
/// [`Candidates::build`] for a caller that already holds **every** file's
|
||||
/// words — the form a scan uses.
|
||||
///
|
||||
/// Since 2026-09-08 a scan reads a file's text at the step that indexes it
|
||||
/// and drops it again, so there is no text left to lex when the tables are
|
||||
/// built at the end. There never was any lexing to do: since `FACTS_FORMAT`
|
||||
/// 13 a file's identifier census is one of its facts, so a scan already has
|
||||
/// the words of every file it stepped, cached or parsed, and `build`'s
|
||||
/// `known` covered the whole list. This is that call without the text it
|
||||
/// no longer reads (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
///
|
||||
/// Order-independent: the word counts are a sum and `words` is sorted at
|
||||
/// the end, so a map is as good as a list here.
|
||||
pub fn from_words(index: &WorkspaceIndex, words: HashMap<PathBuf, Vec<String>>) -> Candidates {
|
||||
let mut out = Candidates::default();
|
||||
out.take_index_tables(index);
|
||||
for (path, text) in sources {
|
||||
let words = match known.remove(path) {
|
||||
Some(words) => words,
|
||||
None => words_in(text),
|
||||
};
|
||||
for (path, words) in words {
|
||||
for word in &words {
|
||||
*out.word_files.entry(word.clone()).or_default() += 1;
|
||||
}
|
||||
if !words.is_empty() {
|
||||
out.per_file.insert(path.clone(), words);
|
||||
out.per_file.insert(path, words);
|
||||
}
|
||||
}
|
||||
out.words = out.word_files.keys().cloned().collect();
|
||||
@@ -293,6 +319,17 @@ impl Candidates {
|
||||
self.remask_words();
|
||||
}
|
||||
|
||||
/// How many entries each completion table holds, and what the word table
|
||||
/// weighs — the startup memory question, asked of the one table that
|
||||
/// grows with the corpus rather than with its declarations.
|
||||
///
|
||||
/// A walk, so it is asked once at the end of a traced scan and never on a
|
||||
/// request path (`docs/features/perf5-p4/README.md`).
|
||||
pub fn sizes(&self) -> (usize, usize, usize, usize) {
|
||||
let word_bytes: usize = self.words.iter().map(String::len).sum();
|
||||
(self.units.len(), self.macros.len(), self.words.len(), word_bytes)
|
||||
}
|
||||
|
||||
/// Index names starting with `prefix`, case-insensitively.
|
||||
pub fn units(&self, prefix: &str) -> &[Candidate] {
|
||||
matching(&self.units, prefix, |c| &c.name)
|
||||
|
||||
@@ -133,6 +133,18 @@ fn title(violation: &Violation) -> String {
|
||||
format!("lucisv: {what} [{}]", violation.rule)
|
||||
}
|
||||
|
||||
/// Whether a client asking for `only` wants anything [`code_actions`] can
|
||||
/// offer — a quick fix or the fix-all action.
|
||||
///
|
||||
/// The two kinds this module answers for are the only two the **lint pass**
|
||||
/// answers for, so this is the question the dispatcher asks before reading the
|
||||
/// buffer's configuration and running the rules. A client asking for
|
||||
/// `refactor.*` or `source.organizeImports` alone gets neither, and now pays
|
||||
/// for neither (take 5 §P1a).
|
||||
pub fn wants_fixes(only: Option<&[CodeActionKind]>) -> bool {
|
||||
wanted(only, &CodeActionKind::QUICKFIX) || wanted(only, &CodeActionKind::new(FIX_ALL))
|
||||
}
|
||||
|
||||
/// Whether a client asking for `only` wants this kind. A filter is a prefix of
|
||||
/// the kinds it selects (`source` selects `source.fixAll.lucisv`), and no filter
|
||||
/// at all selects everything.
|
||||
|
||||
@@ -40,7 +40,7 @@ use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{Home, RefactorEdit};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// Extract a selection into a module: `[uri, range, name]`.
|
||||
@@ -63,6 +63,19 @@ pub fn kind() -> CodeActionKind {
|
||||
/// "there is nothing here" for almost every selection, and where it does find
|
||||
/// something the offer is a `Command`, so no workspace is read until the user
|
||||
/// has picked the action *and* named the module.
|
||||
/// Whether `[start, end)` is a selection lucisv could extract, asked of the
|
||||
/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b).
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes rather than of the empty analysis that path installs — see
|
||||
/// `ports::modules_at` and `docs/features/perf5-p1/README.md`.
|
||||
fn site_at(doc: &Document, start: u32, end: u32) -> Option<vlog_refactor::ExtractSite> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::extract_site(&doc.text, start, end),
|
||||
false => vlog_refactor::extract_site_in(&doc.tree, &doc.diagnostics, &doc.text, start, end),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
if doc.path.is_none() {
|
||||
@@ -73,7 +86,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOr
|
||||
}
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else { return Vec::new() };
|
||||
let Some(site) = site_at(doc, start, end) else { return Vec::new() };
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).unwrap_or(Value::Null),
|
||||
serde_json::to_value(range).unwrap_or(Value::Null),
|
||||
@@ -110,7 +123,7 @@ pub fn execute(
|
||||
.ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?;
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else {
|
||||
let Some(site) = site_at(doc, start, end) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine looks up every module the selection instantiates and every
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//! The fenced regions of an open buffer, asked once per document revision.
|
||||
//!
|
||||
//! `vlog_formatter::fence::protected_regions` takes **text** and parses it
|
||||
//! itself, on purpose: one fence answer for every front end, and none of them
|
||||
//! able to feed it a stale tree. That contract
|
||||
//! (`docs/features/shared-fence-filter/README.md`) is not amended here, and
|
||||
//! `fence.rs` is not touched — the call is still
|
||||
//! `protected_regions(&doc.text)`, byte for byte the same question.
|
||||
//!
|
||||
//! What this module adds is that the answer is computed **once** for a given
|
||||
//! buffer instead of once per `textDocument/codeAction`. That is safe for one
|
||||
//! structural reason: a `Document` is built whole by
|
||||
//! `Workspace::set_document` and thrown away by it, so the text a `Document`
|
||||
//! holds cannot change without a new `Document` — and `answer_request`
|
||||
//! flushes every pending change before a handler runs. There is no revision
|
||||
//! number to compare because there is no way to be looking at the wrong one.
|
||||
//!
|
||||
//! A 42 192-line generated buffer is where this is worth having: the fence
|
||||
//! parse alone measured ~59 ms of that file's code-action cost (take 5 §P1,
|
||||
//! `docs/features/perf5-p1/README.md`).
|
||||
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// The regions of `doc` no tool may edit automatically.
|
||||
///
|
||||
/// Computed on first use and kept for the life of this `Document`. The
|
||||
/// caller borrows the answer rather than a copy of it, so asking twice costs
|
||||
/// a pointer.
|
||||
pub fn of(doc: &Document) -> &[Region] {
|
||||
doc.fences.get_or_init(|| fence::protected_regions(&doc.text))
|
||||
}
|
||||
@@ -30,7 +30,7 @@ use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Position, Uri,
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Workspace;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// Organize the imports at a position: `[uri, position]`.
|
||||
pub const ORGANIZE_IMPORTS: &str = "lucisv.organizeImports";
|
||||
@@ -74,8 +74,9 @@ pub fn offers(
|
||||
position: Position,
|
||||
offset: u32,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() };
|
||||
let Ok((_, removed, sorted)) = vlog_refactor::organize_counts(&files, &path, offset) else {
|
||||
let Ok((removed, sorted)) = counts_at(doc, &files, &path, offset) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let title = vlog_refactor::organize_title(removed, sorted);
|
||||
@@ -88,6 +89,37 @@ pub fn offers(
|
||||
})]
|
||||
}
|
||||
|
||||
/// The two counts the offered title promises, asked of the buffer's own parse,
|
||||
/// analysis and token stream, and **without** verifying the splice.
|
||||
///
|
||||
/// `organize_counts` computes the whole edit and runs `check::verify_splice`,
|
||||
/// which rebuilds the index over every in-scope file and re-analyzes them —
|
||||
/// about two thirds of the offer's cost for an answer the offer discards (take
|
||||
/// 5 §P1c, `docs/features/perf5-p1/README.md`). [`resolve`] and [`execute`]
|
||||
/// still compute and verify the real edit when the user picks the action.
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, exactly as
|
||||
/// [`packages_at`] does.
|
||||
fn counts_at(
|
||||
doc: &Document,
|
||||
files: &[(PathBuf, String)],
|
||||
path: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(usize, usize), String> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::organize_offer(files, path, offset),
|
||||
false => vlog_refactor::organize_offer_in(
|
||||
files,
|
||||
path,
|
||||
&doc.tree,
|
||||
&doc.diagnostics,
|
||||
&doc.semantics,
|
||||
&doc.tokens,
|
||||
offset,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The edit for an offered action, computed now that the user has picked it.
|
||||
pub fn resolve(ws: &Workspace, action: CodeAction) -> Result<CodeAction, String> {
|
||||
if action.edit.is_some() {
|
||||
@@ -144,10 +176,23 @@ pub fn execute(
|
||||
/// The cheap gate first: `imported_packages` is one parse of one buffer and
|
||||
/// answers "nothing here" for almost every cursor, which is what keeps a
|
||||
/// `textDocument/codeAction` on every keystroke off the index.
|
||||
/// Every package the scope at `offset` imports, asked of the buffer's own
|
||||
/// parse and its own diagnostics rather than of its text (take 5 §P1b). A
|
||||
/// buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes — see `ports::modules_at` for the whole reason.
|
||||
fn packages_at(doc: &Document, offset: u32) -> Vec<String> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::imported_packages(&doc.text, offset),
|
||||
false => {
|
||||
vlog_refactor::imported_packages_in(&doc.tree, &doc.diagnostics, &doc.text, offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn at(ws: &Workspace, uri: &Uri, offset: u32) -> Option<(PathBuf, Vec<(PathBuf, String)>)> {
|
||||
let doc = ws.document(uri)?;
|
||||
let path = doc.path.clone()?;
|
||||
let packages = vlog_refactor::imported_packages(&doc.text, offset);
|
||||
let packages = packages_at(doc, offset);
|
||||
if packages.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -116,14 +116,39 @@ pub struct IncludeGraph {
|
||||
|
||||
impl IncludeGraph {
|
||||
/// Scan every in-scope file for its `` `include``s and resolve them.
|
||||
///
|
||||
/// Test-only since 2026-09-08: the scan that used to hold every file's
|
||||
/// text no longer does, and calls [`IncludeGraph::from_includes`] with the
|
||||
/// lines it read at each file's own step. This is that call with the scan
|
||||
/// in front of it — which is what makes it the right thing for a test to
|
||||
/// build a graph from a fixture with, and the two provably one function.
|
||||
#[cfg(test)]
|
||||
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
|
||||
let scanned: Vec<(PathBuf, Vec<Include>)> =
|
||||
sources.iter().map(|(path, text)| (path.clone(), scan(text))).collect();
|
||||
let borrowed: Vec<(&Path, &[Include])> =
|
||||
scanned.iter().map(|(path, found)| (path.as_path(), found.as_slice())).collect();
|
||||
IncludeGraph::from_includes(&borrowed, incdirs)
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::build`] for a caller that has already read each file's
|
||||
/// `` `include`` lines off its text — the form a scan uses.
|
||||
///
|
||||
/// Since 2026-09-08 a scan reads a file's text at the step that indexes it
|
||||
/// and drops it again, so the text is not there to be scanned when the
|
||||
/// graph is built at the end; [`scan`] runs once per file, at that step,
|
||||
/// and the lines it found are what arrives here
|
||||
/// (`docs/features/perf5-p4/README.md` §P4b3). The two entries are the
|
||||
/// same function over the same lines — `build` is this one with the scan
|
||||
/// in front of it — so a graph built either way is the same graph.
|
||||
pub fn from_includes(sources: &[(&Path, &[Include])], incdirs: Vec<PathBuf>) -> IncludeGraph {
|
||||
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
|
||||
// Learned before the edges: `resolve` consults both tables, and an edge
|
||||
// resolved against a half-filled one would be keyed inconsistently.
|
||||
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
|
||||
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.to_path_buf()).collect();
|
||||
graph.relearn(&paths);
|
||||
for (path, text) in sources {
|
||||
graph.rescan_edges(path, text);
|
||||
for (path, found) in sources {
|
||||
graph.rescan_found(path, found);
|
||||
}
|
||||
graph.respell();
|
||||
graph
|
||||
@@ -151,9 +176,11 @@ impl IncludeGraph {
|
||||
self.respell();
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s
|
||||
/// the scope resolves to right now — the form a scan publishing what it
|
||||
/// has indexed so far uses.
|
||||
/// [`IncludeGraph::update_file`] for a batch of files whose `` `include``
|
||||
/// lines have already been read, with the `+incdir+`s the scope resolves
|
||||
/// to right now — the form a scan publishing what it has indexed so far
|
||||
/// uses. The lines come from the step that indexed each file, for the
|
||||
/// reason [`IncludeGraph::from_includes`] gives.
|
||||
///
|
||||
/// `known` is the scan's whole work list rather than the files it has
|
||||
/// reached, so the known-file and folded-spelling tables are complete from
|
||||
@@ -162,11 +189,16 @@ impl IncludeGraph {
|
||||
/// `relearn` for the batch, for the same reason
|
||||
/// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives
|
||||
/// its index tables once.
|
||||
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) {
|
||||
pub fn absorb_includes(
|
||||
&mut self,
|
||||
incdirs: &[PathBuf],
|
||||
known: &[PathBuf],
|
||||
batch: &[(&Path, &[Include])],
|
||||
) {
|
||||
self.incdirs = incdirs.to_vec();
|
||||
self.relearn(known);
|
||||
for (path, text) in batch {
|
||||
self.rescan_edges(path, text);
|
||||
for (path, found) in batch {
|
||||
self.rescan_found(path, found);
|
||||
}
|
||||
self.respell();
|
||||
}
|
||||
@@ -183,8 +215,14 @@ impl IncludeGraph {
|
||||
/// each one lands. A file that includes nothing holds no entry at all,
|
||||
/// which is what keeps `raw` a set of edges rather than a set of files.
|
||||
fn rescan_edges(&mut self, path: &Path, text: &str) {
|
||||
self.rescan_found(path, &scan(text));
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::rescan_edges`] with the file's `` `include`` lines
|
||||
/// already in hand: where the disk says each one lands, held.
|
||||
fn rescan_found(&mut self, path: &Path, found: &[Include]) {
|
||||
let targets: Vec<PathBuf> =
|
||||
scan(text).iter().filter_map(|include| self.found(Some(path), include)).collect();
|
||||
found.iter().filter_map(|include| self.found(Some(path), include)).collect();
|
||||
match targets.is_empty() {
|
||||
true => self.raw.remove(path),
|
||||
false => self.raw.insert(path.to_path_buf(), targets),
|
||||
@@ -230,6 +268,12 @@ impl IncludeGraph {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many resolved edges the graph holds and how many files it knows —
|
||||
/// the two numbers that say what a rebuilt graph weighs.
|
||||
pub fn sizes(&self) -> (usize, usize) {
|
||||
(self.edges.values().map(Vec::len).sum(), self.known.len())
|
||||
}
|
||||
|
||||
/// The `+incdir+` directories an include is looked for in, in filelist
|
||||
/// order — the search rungs past the including file's own directory.
|
||||
pub fn incdirs(&self) -> &[PathBuf] {
|
||||
|
||||
@@ -24,14 +24,17 @@
|
||||
//! `docs/features/index-persistence/README.md` and is the same one
|
||||
//! `lucisv_core::cache` accepts.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use lucisv_core::cache::content_hash;
|
||||
use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT};
|
||||
|
||||
use crate::scan_trace::CacheWork;
|
||||
use crate::settings::ClientSettings;
|
||||
|
||||
/// The store inside the cache directory.
|
||||
@@ -51,6 +54,45 @@ const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
/// The subdirectory of the OS cache directory this server's stores live in.
|
||||
const OS_DIR: [&str; 2] = ["lucisv", "index"];
|
||||
|
||||
/// What one load of the store found — the numbers that decide whether the file
|
||||
/// on disk is *already* the file a compaction would write.
|
||||
///
|
||||
/// [`IndexCache::render`] writes this build's header and then one line per
|
||||
/// path in path order, so a store this build compacted and nothing has
|
||||
/// appended to since comes back with every line kept, no line dropped, no path
|
||||
/// named twice and the paths ascending. Anything else — another version's
|
||||
/// header, a torn line, a record the checksum rejects, two lines for one path,
|
||||
/// a session's appends still unvacuumed — means the file and the render differ,
|
||||
/// and compaction is what makes them the same.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Load {
|
||||
/// Whether the first line was this build's own header.
|
||||
header: bool,
|
||||
/// Record lines the store held below the header.
|
||||
read: usize,
|
||||
/// Of those, the ones that became an entry of their own.
|
||||
kept: usize,
|
||||
/// Lines that were not a record this build can use.
|
||||
dropped: usize,
|
||||
/// Lines naming a path an earlier line had already named.
|
||||
duplicates: usize,
|
||||
/// Whether the paths arrived strictly ascending, the order `render` writes
|
||||
/// them in.
|
||||
ordered: bool,
|
||||
}
|
||||
|
||||
impl Load {
|
||||
/// Whether these lines are exactly the lines [`IndexCache::render`] would
|
||||
/// write from the entries they produced.
|
||||
fn canonical(&self) -> bool {
|
||||
self.header
|
||||
&& self.ordered
|
||||
&& self.dropped == 0
|
||||
&& self.duplicates == 0
|
||||
&& self.kept == self.read
|
||||
}
|
||||
}
|
||||
|
||||
/// What one entry asserts: a file with exactly this content contributed
|
||||
/// exactly these facts.
|
||||
struct Entry {
|
||||
@@ -75,6 +117,18 @@ pub struct IndexCache {
|
||||
/// False for a missing store — which the first write claims — and for one
|
||||
/// from another version, which the first write replaces wholesale.
|
||||
header_ok: bool,
|
||||
/// What [`IndexCache::open`] read out of the store, which is what
|
||||
/// [`IndexCache::already_compact`] asks whether a rewrite would reproduce.
|
||||
load: Load,
|
||||
/// What this cache's own work has cost since it was opened, for the
|
||||
/// startup breakdown (`docs/features/perf5-p4/README.md`).
|
||||
///
|
||||
/// A `Cell` because [`IndexCache::facts_for`] is a `&self` read and the
|
||||
/// hash/decode split is exactly the number §P4a needed. Counted whether
|
||||
/// anything is going to read it or not: four clock reads per file are
|
||||
/// noise beside the decode they bracket, and a flag threaded down here to
|
||||
/// save them would cost more code than time.
|
||||
work: Cell<CacheWork>,
|
||||
}
|
||||
|
||||
impl IndexCache {
|
||||
@@ -96,24 +150,62 @@ impl IndexCache {
|
||||
/// whose tail was cut inside a multi-byte character costs the record that
|
||||
/// was torn and no other. Reading the whole buffer as text would have
|
||||
/// rejected all of it for one bad byte at the end.
|
||||
///
|
||||
/// The load is *counted* as well as performed — lines read, kept, dropped
|
||||
/// and duplicated, and whether the paths arrived in order — because those
|
||||
/// five numbers are what say whether the file already is what
|
||||
/// [`IndexCache::compact`] would write over it.
|
||||
pub fn open(dir: Option<PathBuf>) -> IndexCache {
|
||||
let Some(dir) = dir else { return IndexCache::disabled() };
|
||||
let bytes = std::fs::read(dir.join(FILE)).unwrap_or_default();
|
||||
let mut lines = store_lines(&bytes).into_iter();
|
||||
let header_ok = lines.next() == Some(header().as_bytes());
|
||||
let mut entries = HashMap::new();
|
||||
let mut load = Load { header: header_ok, ordered: true, ..Load::default() };
|
||||
if header_ok {
|
||||
let mut previous: Option<PathBuf> = None;
|
||||
for line in lines {
|
||||
let Ok(line) = std::str::from_utf8(line) else { continue };
|
||||
if let Some((path, entry)) = parse_entry(line) {
|
||||
// A later record for a path wins: the log is appended to
|
||||
// as a rescan goes, so the last one written is the one
|
||||
// that describes the file as the server last saw it.
|
||||
entries.insert(path, entry);
|
||||
load.read += 1;
|
||||
let Ok(line) = std::str::from_utf8(line) else {
|
||||
load.dropped += 1;
|
||||
continue;
|
||||
};
|
||||
let Some((path, entry)) = parse_entry(line) else {
|
||||
load.dropped += 1;
|
||||
continue;
|
||||
};
|
||||
if let Some(previous) = &previous {
|
||||
load.ordered &= *previous < path;
|
||||
}
|
||||
previous = Some(path.clone());
|
||||
// A later record for a path wins: the log is appended to
|
||||
// as a rescan goes, so the last one written is the one
|
||||
// that describes the file as the server last saw it.
|
||||
match entries.insert(path, entry) {
|
||||
Some(_) => load.duplicates += 1,
|
||||
None => load.kept += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
IndexCache { dir: Some(dir), entries, log: None, header_ok }
|
||||
let work = Cell::new(CacheWork { opens: 1, ..CacheWork::default() });
|
||||
IndexCache { dir: Some(dir), entries, log: None, header_ok, load, work }
|
||||
}
|
||||
|
||||
/// What this cache has spent and moved since it was opened.
|
||||
pub fn work(&self) -> CacheWork {
|
||||
self.work.get()
|
||||
}
|
||||
|
||||
/// How many records this cache is holding.
|
||||
pub fn entry_count(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
/// The encoded bytes those records weigh — the retention §P4's memory
|
||||
/// hypothesis is about, since every one of them sits beside a decoded
|
||||
/// copy in the workspace index.
|
||||
pub fn encoded_bytes(&self) -> usize {
|
||||
self.entries.values().map(|entry| entry.facts.len()).sum()
|
||||
}
|
||||
|
||||
/// Where this cache writes. Test-only: production opens a cache from a
|
||||
@@ -133,11 +225,28 @@ impl IndexCache {
|
||||
/// they were written with, which [`IndexCache::open`] drops before it ever
|
||||
/// gets here.
|
||||
pub fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
let entry = self.entries.get(path)?;
|
||||
if entry.content != content_hash(text.as_bytes()) {
|
||||
let looking = Instant::now();
|
||||
let found =
|
||||
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()));
|
||||
let mut work = self.work.get();
|
||||
work.lookup_ns += elapsed_ns(looking);
|
||||
let Some(entry) = found else {
|
||||
work.misses += 1;
|
||||
self.work.set(work);
|
||||
return None;
|
||||
};
|
||||
let decoding = Instant::now();
|
||||
let facts = FileFacts::decode(&entry.facts);
|
||||
work.decode_ns += elapsed_ns(decoding);
|
||||
work.decoded_bytes += entry.facts.len();
|
||||
// A record that no longer decodes costs a parse, so it is a miss —
|
||||
// the counters say what the scan actually did, not what it looked up.
|
||||
match facts.is_some() {
|
||||
true => work.hits += 1,
|
||||
false => work.misses += 1,
|
||||
}
|
||||
FileFacts::decode(&entry.facts)
|
||||
self.work.set(work);
|
||||
facts
|
||||
}
|
||||
|
||||
/// Record what parsing `text` found, and write it through immediately.
|
||||
@@ -149,13 +258,36 @@ impl IndexCache {
|
||||
/// the checksum of the facts it was written with) for the same reasons it
|
||||
/// rejects any other malformed record. That is the whole crash-safety
|
||||
/// argument, and it is why records are one line each.
|
||||
///
|
||||
/// **A record the store already holds is not written again.** An open
|
||||
/// buffer is indexed from its own analysis on every scan and its record is
|
||||
/// written through with it, so a warm session appends a line for every
|
||||
/// open buffer that is byte-identical to the line already in the store —
|
||||
/// a duplicate the next load collapses, at the price of making the store
|
||||
/// non-canonical and so owing [`IndexCache::compact`] a full rewrite. The
|
||||
/// test is the exact one: same path, same content hash, same encoded
|
||||
/// facts. Anything that differs by a byte is a new record and is appended
|
||||
/// as it always was.
|
||||
pub fn record(&mut self, facts: &FileFacts, text: &str) {
|
||||
if self.dir.is_none() {
|
||||
return;
|
||||
}
|
||||
let encoding = Instant::now();
|
||||
let Some(encoded) = facts.encode() else { return };
|
||||
let content = content_hash(text.as_bytes());
|
||||
let mut work = self.work.get();
|
||||
work.encode_ns += elapsed_ns(encoding);
|
||||
if self.holds(facts.path(), content, &encoded) {
|
||||
work.repeats += 1;
|
||||
self.work.set(work);
|
||||
return;
|
||||
}
|
||||
let writing = Instant::now();
|
||||
self.append(&line(content, &encoded));
|
||||
work.write_ns += elapsed_ns(writing);
|
||||
work.records += 1;
|
||||
work.written_bytes += encoded.len();
|
||||
self.work.set(work);
|
||||
self.entries.insert(facts.path().to_path_buf(), Entry { content, facts: encoded });
|
||||
}
|
||||
|
||||
@@ -171,7 +303,76 @@ impl IndexCache {
|
||||
/// Atomic and silent: written to a temporary file and renamed, and a
|
||||
/// failure anywhere leaves the previous store standing. A cache that could
|
||||
/// fail a rescan would be worse than no cache.
|
||||
///
|
||||
/// **Skipped when the rewrite would reproduce the file byte for byte**
|
||||
/// ([`IndexCache::already_compact`]). A warm session whose every file hit
|
||||
/// the store appends nothing, so the store it loaded is the store it would
|
||||
/// write, and rewriting 44 MiB to produce the same 44 MiB was 182 ms of a
|
||||
/// 1.33 s start (`docs/features/perf5-p4/README.md`, §P4b (a)).
|
||||
pub fn compact(&mut self) {
|
||||
let before = self.store_bytes();
|
||||
let compacting = Instant::now();
|
||||
let rewriting = !self.already_compact();
|
||||
if rewriting {
|
||||
self.compact_now();
|
||||
}
|
||||
let mut work = self.work.get();
|
||||
work.compact_ns += elapsed_ns(compacting);
|
||||
work.compactions += usize::from(rewriting);
|
||||
work.store_before = before;
|
||||
work.store_after = self.store_bytes();
|
||||
self.work.set(work);
|
||||
}
|
||||
|
||||
/// Whether the store on disk is already exactly what [`IndexCache::render`]
|
||||
/// would write over it.
|
||||
///
|
||||
/// Four things have to hold, and any one of them failing compacts as
|
||||
/// before:
|
||||
///
|
||||
/// * the store was **loaded canonical** — this build's header, every line
|
||||
/// a record this build can read, no path named twice, the paths
|
||||
/// ascending ([`Load::canonical`]);
|
||||
/// * **nothing has been appended since**, so no line is out of order and
|
||||
/// no path has a second one;
|
||||
/// * **no entry's file is gone**, because `render` drops those;
|
||||
/// * there is a directory to write in at all.
|
||||
///
|
||||
/// **Crash safety is untouched.** A session that appended nothing left the
|
||||
/// store exactly as it found it, so what is on disk is already the
|
||||
/// compacted file and there is no half-written state a rewrite would
|
||||
/// resolve; skipping it only means the append log — which has no appends —
|
||||
/// stays as it is. The existence sweep is the one part that costs
|
||||
/// anything, one `stat` per entry, against the whole-store render and
|
||||
/// write it stands in for.
|
||||
fn already_compact(&self) -> bool {
|
||||
self.dir.is_some()
|
||||
&& self.load.canonical()
|
||||
&& self.work.get().records == 0
|
||||
&& self.entries.keys().all(|path| path.exists())
|
||||
}
|
||||
|
||||
/// Whether the store already holds exactly this record — the same path,
|
||||
/// the same content hash and the same encoded facts, byte for byte.
|
||||
///
|
||||
/// Only exactly that counts. A record whose facts differ by a byte under
|
||||
/// the same hash is still written, because the line on disk and the facts
|
||||
/// in hand would then disagree and the store must say what this session
|
||||
/// last saw.
|
||||
fn holds(&self, path: &Path, content: u64, encoded: &str) -> bool {
|
||||
self.entries
|
||||
.get(path)
|
||||
.is_some_and(|entry| entry.content == content && entry.facts == encoded)
|
||||
}
|
||||
|
||||
/// The store file's size on disk, or 0 when there is no store.
|
||||
fn store_bytes(&self) -> u64 {
|
||||
let Some(dir) = self.dir.as_ref() else { return 0 };
|
||||
std::fs::metadata(dir.join(FILE)).map(|meta| meta.len()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`IndexCache::compact`] without the accounting around it.
|
||||
fn compact_now(&mut self) {
|
||||
let Some(dir) = self.dir.clone() else { return };
|
||||
// The append handle must go before the rename, or a later append would
|
||||
// write into the file the rename replaced.
|
||||
@@ -342,6 +543,11 @@ fn line(content: u64, facts: &str) -> String {
|
||||
/// `None` for anything that is not a whole record whose facts still match
|
||||
/// their checksum, which includes the torn last line of a store whose writer
|
||||
/// was killed.
|
||||
/// Nanoseconds since `from`, saturated into the counters' `u64`.
|
||||
fn elapsed_ns(from: Instant) -> u64 {
|
||||
from.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64
|
||||
}
|
||||
|
||||
fn parse_entry(line: &str) -> Option<(PathBuf, Entry)> {
|
||||
let (hash, rest) = line.split_once('\t')?;
|
||||
// Exactly as wide as `line` writes it: a hash that reads as a number but
|
||||
@@ -720,6 +926,221 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A store two files were recorded into and then compacted — this build's
|
||||
/// header and one line per path in path order, which is what every
|
||||
/// session after a whole rescan finds on disk.
|
||||
fn compacted_store(dir: &TempDir) -> (PathBuf, PathBuf) {
|
||||
let one = dir.file("a.sv", M);
|
||||
let two = dir.file("b.sv", M);
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.record(&facts(&one, M), M);
|
||||
cache.record(&facts(&two, M), M);
|
||||
cache.compact();
|
||||
assert_eq!(cache.work().compactions, 1, "premise: the store was written");
|
||||
(one, two)
|
||||
}
|
||||
|
||||
/// The store's bytes and its modification time — "not rewritten" as
|
||||
/// something a test can see rather than infer.
|
||||
fn store_stamp(dir: &TempDir) -> (Vec<u8>, std::time::SystemTime) {
|
||||
let path = dir.path.join(FILE);
|
||||
let bytes = std::fs::read(&path).expect("read store");
|
||||
let stamp = std::fs::metadata(&path).expect("meta").modified().expect("mtime");
|
||||
(bytes, stamp)
|
||||
}
|
||||
|
||||
/// Rewrite the store's record lines, keeping this build's header.
|
||||
fn rewrite_records(dir: &TempDir, records: &[String]) {
|
||||
let mut text = header();
|
||||
for record in records {
|
||||
text.push('\n');
|
||||
text.push_str(record);
|
||||
}
|
||||
text.push('\n');
|
||||
std::fs::write(dir.path.join(FILE), text).expect("write store");
|
||||
}
|
||||
|
||||
/// The store's record lines, header excluded.
|
||||
fn records_of(dir: &TempDir) -> Vec<String> {
|
||||
dir.store_text().lines().skip(1).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canonical_store_nothing_appended_to_is_not_rewritten() {
|
||||
// §P4b (a): a warm session hits the store for every file, appends
|
||||
// nothing, and would rewrite 44 MiB to produce the same 44 MiB —
|
||||
// 182 ms of a 1.33 s start. What is on disk is already what `render`
|
||||
// writes, so the rewrite is skipped and the file is not touched at
|
||||
// all: not its bytes, not even its modification time.
|
||||
let dir = TempDir::new("alreadycompact");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let before = store_stamp(&dir);
|
||||
|
||||
let mut warm = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(warm.facts_for(&one, M).is_some(), "premise: a warm session that only reads");
|
||||
warm.compact();
|
||||
|
||||
assert_eq!(warm.work().compactions, 0, "the rewrite would have been byte-identical");
|
||||
assert_eq!(store_stamp(&dir), before, "so the store was not touched");
|
||||
// And what is on disk is still a store: the next session reads it.
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_the_store_already_holds_is_not_appended_again() {
|
||||
// An open buffer is indexed from its own analysis on *every* scan and
|
||||
// its record is written through with it, so a warm session would
|
||||
// append a byte-identical duplicate for each open buffer — which
|
||||
// costs the store its canonical shape and so owes the next scan a
|
||||
// whole 44 MiB rewrite. The same record is a no-op; a changed one is
|
||||
// not (`docs/features/perf5-p4/README.md`, §P4b (a)).
|
||||
let dir = TempDir::new("repeatrecord");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let before = store_stamp(&dir);
|
||||
|
||||
let mut warm = IndexCache::open(Some(dir.path.clone()));
|
||||
warm.record(&facts(&one, M), M);
|
||||
assert_eq!(warm.work().records, 0, "nothing was appended");
|
||||
assert_eq!(warm.work().repeats, 1, "and the store was already holding it");
|
||||
assert_eq!(store_stamp(&dir), before, "so the store on disk did not move");
|
||||
warm.compact();
|
||||
assert_eq!(warm.work().compactions, 0, "which leaves it canonical");
|
||||
assert_eq!(store_stamp(&dir), before);
|
||||
|
||||
// One byte of difference and the record is written exactly as before.
|
||||
let edited = "module m;\n sub u ();\n wire w;\nendmodule\n";
|
||||
warm.record(&facts(&one, edited), edited);
|
||||
assert_eq!(warm.work().records, 1, "different bytes are a new record");
|
||||
assert_eq!(warm.work().repeats, 1);
|
||||
warm.compact();
|
||||
assert_eq!(warm.work().compactions, 1, "and the rewrite is owed again");
|
||||
assert_eq!(
|
||||
IndexCache::open(Some(dir.path.clone())).facts_for(&one, edited),
|
||||
Some(facts(&one, edited)),
|
||||
"the newer record is what the next session reads"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_with_two_lines_for_one_path_is_compacted() {
|
||||
// The growth bound the skip must not cost: a session that saved a
|
||||
// file appended a second line for its path, and only a rewrite folds
|
||||
// the two back into one.
|
||||
let dir = TempDir::new("dupline");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
let repeat = records[0].clone();
|
||||
records.push(repeat);
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a duplicated path is not canonical");
|
||||
assert_eq!(records_of(&dir).len(), 2, "one line per path again");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_with_a_line_this_build_cannot_read_is_compacted() {
|
||||
// A record dropped at load — a torn append, bit rot, a checksum that
|
||||
// no longer matches — means the file on disk holds a line `render`
|
||||
// would not write, so the store is not canonical and the rewrite is
|
||||
// what removes it.
|
||||
let dir = TempDir::new("droppedline");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
records.push(format!("{}\tnot a record at all\t{:016x}", "0".repeat(16), 0));
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a dropped line is not canonical");
|
||||
assert_eq!(records_of(&dir).len(), 2, "the unreadable line is gone");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_whose_records_are_out_of_path_order_is_compacted() {
|
||||
// `render` writes paths sorted, so a store that arrives unsorted was
|
||||
// not written by a compaction of this shape and rewriting it is not a
|
||||
// no-op — even though every line in it is a good record.
|
||||
let dir = TempDir::new("unsorted");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
records.reverse();
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "an unsorted store is not canonical");
|
||||
let sorted: Vec<String> = records_of(&dir);
|
||||
assert_eq!(sorted.len(), 2);
|
||||
assert!(sorted[0] < sorted[1], "path order restored: {sorted:?}");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_recorded_one_file_compacts() {
|
||||
// The moment an append happens the store on disk is no longer the
|
||||
// store `render` would write — the appended line is out of order at
|
||||
// best and a second line for its path at worst — so the rewrite is
|
||||
// owed exactly as it always was.
|
||||
let dir = TempDir::new("appended");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let third = dir.file("c.sv", M);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(cache.facts_for(&one, M).is_some(), "the other two still hit");
|
||||
cache.record(&facts(&third, M), M);
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a session that appended must rewrite");
|
||||
assert_eq!(records_of(&dir).len(), 3);
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&third, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_holding_a_file_that_is_gone_is_compacted() {
|
||||
// `render` drops an entry whose file no longer exists, so a store
|
||||
// holding one is not what a rewrite would produce — and the rewrite
|
||||
// is what prunes it, exactly as before.
|
||||
let dir = TempDir::new("goneentry");
|
||||
let (one, two) = compacted_store(&dir);
|
||||
std::fs::remove_file(&two).expect("remove");
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a gone file must still be pruned");
|
||||
assert_eq!(records_of(&dir).len(), 1, "the vanished file's line is gone");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_from_another_version_is_replaced_even_by_a_session_that_wrote_nothing() {
|
||||
// The header is the one line the skip may never leave standing: its
|
||||
// records were dropped at load, so a session that keeps it leaves a
|
||||
// store nobody can read on disk for ever.
|
||||
let dir = TempDir::new("foreignheader");
|
||||
let file = dir.file("m.sv", M);
|
||||
let encoded = facts(&file, M).encode().expect("encodes");
|
||||
let foreign = format!(
|
||||
"lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-build\n{}\n",
|
||||
line(content_hash(M.as_bytes()), &encoded)
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), foreign).expect("write");
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "another version's header is not canonical");
|
||||
let text = dir.store_text();
|
||||
assert_eq!(text, format!("{}\n", header()), "replaced with this build's own: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure() {
|
||||
// The line is well-formed as far as the store is concerned — hash,
|
||||
|
||||
@@ -23,7 +23,8 @@ use lsp_types::{
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Workspace;
|
||||
use crate::module_select::Reach;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// Inline the module instantiated at a position: `[uri, position]`.
|
||||
pub const INLINE_MODULE: &str = "lucisv.inlineModule";
|
||||
@@ -40,6 +41,19 @@ pub fn kind() -> CodeActionKind {
|
||||
}
|
||||
|
||||
/// The action for the cursor, carrying the command that does the work.
|
||||
/// Whether the cursor is on an instantiation lucisv could inline, asked of the
|
||||
/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b).
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes rather than of the empty analysis that path installs — see
|
||||
/// `ports::modules_at` and `docs/features/perf5-p1/README.md`.
|
||||
fn site_at(doc: &Document, offset: u32) -> Option<vlog_refactor::InlineSite> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::inline_site(&doc.text, offset),
|
||||
false => vlog_refactor::inline_site_in(&doc.tree, &doc.diagnostics, &doc.text, offset),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
if doc.path.is_none() {
|
||||
@@ -48,7 +62,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOr
|
||||
return Vec::new();
|
||||
}
|
||||
let offset = doc.positions().offset(range.start);
|
||||
let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else { return Vec::new() };
|
||||
let Some(site) = site_at(doc, offset) else { return Vec::new() };
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).unwrap_or(Value::Null),
|
||||
serde_json::to_value(range.start).unwrap_or(Value::Null),
|
||||
@@ -80,14 +94,21 @@ pub fn execute(
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?;
|
||||
let offset = doc.positions().offset(position);
|
||||
let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else {
|
||||
let Some(site) = site_at(doc, offset) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine reads the instantiated module's declaration and refuses over
|
||||
// any hierarchical path into the instance, so the file set is the two
|
||||
// units' own fan-out: the declaring file, and every file the index says
|
||||
// mentions either name.
|
||||
let files = ws.module_sources(&path, &site.units);
|
||||
// units' own fan-out — the declaring file, and every file the index says
|
||||
// mentions either name — **plus the fifth rung**: every file whose tokens
|
||||
// write the instance's own name down. A file naming
|
||||
// `u_wrapper.u_top.u_sub.s` reaches this instance through modules it does
|
||||
// not itself instantiate, and the first four rungs have nothing that asks
|
||||
// for it (topology handshake 33). The rung is the exact census
|
||||
// `no_hierarchy` can refuse from, so this set answers that refusal the way
|
||||
// the whole workspace would.
|
||||
let scopes = [site.instance.clone()];
|
||||
let files = ws.module_sources_reaching(&path, &site.units, Reach { scopes: &scopes });
|
||||
let refactoring = vlog_refactor::inline_module(&files, &path, offset)?;
|
||||
Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
@@ -445,13 +445,23 @@ pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec<Violation
|
||||
// line a checked-in waiver file had waived.
|
||||
let ctx = run.context(doc).with_tab_width(tab_width);
|
||||
let found = lint_with(&ctx, &run.rules, &run.external).0;
|
||||
// One tolerant parse per code-action request: `protected_regions` takes
|
||||
// text and parses internally, on purpose — one fence answer for every
|
||||
// front end, none of which can feed it a stale tree (see
|
||||
// `docs/features/shared-fence-filter/README.md`). The per-keystroke
|
||||
// diagnostics path pays nothing, because it never reads a fix.
|
||||
let regions = fence::protected_regions(&doc.text);
|
||||
found.into_iter().filter(|violation| !fix_touches_fence(violation, ®ions)).collect()
|
||||
// The fence answer is a whole second tolerant parse of the buffer:
|
||||
// `protected_regions` takes text and parses internally, on purpose — one
|
||||
// fence answer for every front end, none of which can feed it a stale tree
|
||||
// (see `docs/features/shared-fence-filter/README.md`). It protects
|
||||
// *fixes*, so a pass whose findings carry no fix has nothing to protect
|
||||
// and nothing to ask: the filter below would be the identity. Skipping it
|
||||
// there is take 5 §P1a. The per-keystroke diagnostics path pays nothing
|
||||
// either, because it never reads a fix.
|
||||
if !found.iter().any(|violation| violation.fix.is_some()) {
|
||||
return found;
|
||||
}
|
||||
// Asked once per document revision rather than once per request: the text
|
||||
// a `Document` holds cannot change without a new `Document` (§P1b,
|
||||
// `crate::fences`). The question itself is unchanged — still
|
||||
// `protected_regions` over this buffer's text.
|
||||
let regions = crate::fences::of(doc);
|
||||
found.into_iter().filter(|violation| !fix_touches_fence(violation, regions)).collect()
|
||||
}
|
||||
|
||||
/// True when a violation carries a fix any edit of which lands in a fenced
|
||||
|
||||
@@ -14,6 +14,7 @@ mod design_hierarchy;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod extract;
|
||||
mod fences;
|
||||
mod file_ops;
|
||||
mod folding;
|
||||
mod format;
|
||||
@@ -31,6 +32,7 @@ mod lens;
|
||||
mod linked;
|
||||
mod lint;
|
||||
mod locate;
|
||||
mod module_select;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
@@ -38,6 +40,9 @@ mod pairs;
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod rename_trace;
|
||||
mod scan_order;
|
||||
mod scan_trace;
|
||||
mod selection;
|
||||
mod server;
|
||||
mod settings;
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Which files can name a scope *inside* the module a refactoring rewrites.
|
||||
//!
|
||||
//! [`Workspace::module_sources`](crate::state::Workspace::module_sources)'s
|
||||
//! four rungs answer "who declares, instantiates or refers to these **names**".
|
||||
//! That is enough for the port refactorings and for extract, whose refusals
|
||||
//! are about the names themselves. It is not enough for inline-module, whose
|
||||
//! `no_hierarchy` refusal is about a *path through the design hierarchy*:
|
||||
//! `tb.sv` writing `u_wrapper.u_top.u_sub.s` names the instance `u_sub` that
|
||||
//! inlining dissolves, and `tb.sv` instantiates `wrapper` — not `top`, not
|
||||
//! `sub`. No rung asks for it, `no_hierarchy` only sees what it is handed, and
|
||||
//! the inline was **silently accepted**, dissolving a scope a testbench walks
|
||||
//! through. §53.2's QA reproduced exactly that; it is topology handshake 33.
|
||||
//!
|
||||
//! **The rung is the instance's own word census.** `no_hierarchy` refuses when
|
||||
//! some handed file's token stream holds an `Ident` spelling the instance with
|
||||
//! a `.` (or a `bind`) beside it. [`WorkspaceIndex::files_mentioning`] is the
|
||||
//! census of every file whose token stream writes a word down at all — read
|
||||
//! off `FileFacts::words`, which `vlog_semantic::words::harvest` fills from
|
||||
//! every `Ident` token *and* from the raw text of macro invocations,
|
||||
//! directives and attributes. So a file that could raise that refusal is
|
||||
//! always in this answer, and [`hierarchical_users`] hands inline exactly the
|
||||
//! files that could change its mind.
|
||||
//!
|
||||
//! That is a stronger claim than the transitive-instantiator walk the topology
|
||||
//! row asks for, and it is why this module does not do that walk. Climbing the
|
||||
//! instantiation edges upward from the host module finds the wrapper levels,
|
||||
//! but it misses `bind tb.u_wrapper.u_top.u_sub …` written in an SVA file that
|
||||
//! instantiates nothing in the chain, and `$root`-anchored and macro-built
|
||||
//! paths with it — all shapes `no_hierarchy` refuses over and all shapes the
|
||||
//! word census holds. It also selects files that instantiate up the chain and
|
||||
//! never spell the instance, which no refusal can turn on. The census is both
|
||||
//! the tighter and the more complete answer. Written out in the feature
|
||||
//! README's handshake note, with the failing `bind` fixture that settled it.
|
||||
//!
|
||||
//! The rung can only **add** files, so an edit stays the edit it was and a
|
||||
//! refusal it makes possible is one the whole-workspace engine also makes.
|
||||
//! Nothing here reads a file or parses anything: it is a walk over the records
|
||||
//! the index already holds, binary-searching each file's sorted word list.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
/// The extra reach one refactoring asks for.
|
||||
///
|
||||
/// A caller that needs none passes [`Reach::none`] — which is what
|
||||
/// `module_sources` itself does, so the port and extract paths are unchanged
|
||||
/// by this module in answer and in cost.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Reach<'a> {
|
||||
/// The scope names whose *inside* the refactoring dissolves: for
|
||||
/// inline-module, the instance it removes. Every file whose tokens write
|
||||
/// one of these words is wanted, because every file that could refuse
|
||||
/// over a hierarchical path through it does.
|
||||
pub scopes: &'a [String],
|
||||
}
|
||||
|
||||
impl Reach<'_> {
|
||||
/// No extra reach — the four rungs alone.
|
||||
pub fn none() -> Reach<'static> {
|
||||
Reach { scopes: &[] }
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file whose token stream writes one of `reach`'s scope names.
|
||||
///
|
||||
/// The caller unions this into the set its own rungs filled, so a path this
|
||||
/// rung is the first to ask for is still just a path.
|
||||
pub fn hierarchical_users(index: &WorkspaceIndex, reach: Reach<'_>) -> BTreeSet<PathBuf> {
|
||||
let mut out = BTreeSet::new();
|
||||
for scope in reach.scopes {
|
||||
out.extend(
|
||||
index
|
||||
.files_mentioning(scope)
|
||||
.filter_map(|file| index.path(file))
|
||||
.map(Path::to_path_buf),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `tb` → `wrapper` → `top` → `sub`, the shape §53.2's QA reported: `tb`
|
||||
/// names `u_sub` through two levels it does not itself instantiate, and
|
||||
/// `sva.sv` names it through a `bind` while instantiating nothing at all.
|
||||
fn ladder() -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(vec![
|
||||
(PathBuf::from("/w/sub.sv"), "module sub; logic s; endmodule\n"),
|
||||
(PathBuf::from("/w/top.sv"), "module top; sub u_sub (); endmodule\n"),
|
||||
(PathBuf::from("/w/wrapper.sv"), "module wrapper; top u_top (); endmodule\n"),
|
||||
(
|
||||
PathBuf::from("/w/tb.sv"),
|
||||
"module tb; wrapper u_wrapper (); assign x = u_wrapper.u_top.u_sub.s; endmodule\n",
|
||||
),
|
||||
(
|
||||
PathBuf::from("/w/sva.sv"),
|
||||
"module chk (input logic a); endmodule\nbind tb.u_wrapper.u_top.u_sub chk u_chk (.a(1'b0));\n",
|
||||
),
|
||||
(PathBuf::from("/w/stranger.sv"), "module stranger; logic q; endmodule\n"),
|
||||
])
|
||||
}
|
||||
|
||||
fn names(paths: &BTreeSet<PathBuf>) -> Vec<String> {
|
||||
paths
|
||||
.iter()
|
||||
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_that_writes_the_instance_down_is_wanted() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let found = hierarchical_users(&index, Reach { scopes: &scopes });
|
||||
assert_eq!(
|
||||
names(&found),
|
||||
vec!["sva.sv".to_string(), "tb.sv".to_string(), "top.sv".to_string()],
|
||||
"the declaring file, the bench two levels up, and the bind that instantiates nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_never_writes_it_is_not() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_sub".to_string()];
|
||||
assert!(!names(&hierarchical_users(&index, Reach { scopes: &scopes }))
|
||||
.contains(&"stranger.sv".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_nothing_writes_wants_nothing() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_no_such_instance".to_string()];
|
||||
assert!(hierarchical_users(&index, Reach { scopes: &scopes }).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_reach_asked_for_is_no_work_done() {
|
||||
let index = ladder();
|
||||
assert!(hierarchical_users(&index, Reach::none()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -401,7 +401,7 @@ fn what_a_scan_does_before_its_first_file() {
|
||||
});
|
||||
workspace.adopt_roots(vec![dir.clone()]);
|
||||
let started = Instant::now();
|
||||
let mut scan = workspace.begin_scan(&mut |_| {});
|
||||
let mut scan = workspace.begin_scan(&mut |_| {}, false);
|
||||
let head = started.elapsed();
|
||||
let started = Instant::now();
|
||||
workspace.scan_step(&mut scan, &mut |_| {});
|
||||
@@ -556,7 +556,7 @@ fn what_a_jump_into_a_new_folder_costs_before_and_after() {
|
||||
let added: Vec<PathBuf> =
|
||||
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
|
||||
let started = Instant::now();
|
||||
let mut scan = incremental.begin_widen(&added, &mut |_| {});
|
||||
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
|
||||
while incremental.scan_step(&mut scan, &mut |_| {}) {}
|
||||
black_box(incremental.finish_scan(scan));
|
||||
let widen = started.elapsed();
|
||||
@@ -646,7 +646,7 @@ fn what_a_widen_that_subsumes_the_old_scope_costs() {
|
||||
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
|
||||
let mut read = 0usize;
|
||||
let started = Instant::now();
|
||||
let mut scan = incremental.begin_widen(&added, &mut |_| {});
|
||||
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
|
||||
while incremental.scan_step(&mut scan, &mut |_| read += 1) {}
|
||||
// Split out because it is where the 2026-08-29 round's fix landed: folding
|
||||
// a widen's words into the completion table used to move the table's tail
|
||||
@@ -1120,9 +1120,15 @@ fn a_rename_before_and_after() {
|
||||
let _ = black_box(vlog_refactor::rename(&sources, &path, black_box(offset), "renamed"));
|
||||
});
|
||||
let rename_after = mean(20, || {
|
||||
let _ = black_box(crate::rename::rename(&ws, &uri, black_box(offset), "renamed"));
|
||||
let _ = black_box(crate::rename::rename_traced(
|
||||
&ws,
|
||||
&uri,
|
||||
black_box(offset),
|
||||
"renamed",
|
||||
&mut None,
|
||||
));
|
||||
});
|
||||
let fan_out = ws.rename_sources(&path, "sub", Some("renamed")).len();
|
||||
let fan_out = ws.rename_sources_traced(&path, "sub", Some("renamed")).0.len();
|
||||
// Building the file set at all, and the one rung of it that is a linear
|
||||
// walk over every file's records rather than a keyed lookup
|
||||
// (`WorkspaceIndex::files_spelling`, the new name's dangling-use rung —
|
||||
@@ -1130,7 +1136,7 @@ fn a_rename_before_and_after() {
|
||||
// it is the only part of the set builder whose cost grows with the
|
||||
// workspace rather than with the symbol.
|
||||
let file_set = mean(2_000, || {
|
||||
black_box(ws.rename_sources(black_box(&path), "sub", Some("renamed")));
|
||||
black_box(ws.rename_sources_traced(black_box(&path), "sub", Some("renamed")));
|
||||
});
|
||||
let spelling_rung = mean(2_000, || {
|
||||
black_box(ws.index().files_spelling(black_box("renamed")).count());
|
||||
@@ -1138,7 +1144,8 @@ fn a_rename_before_and_after() {
|
||||
|
||||
// A measurement of an answer that was not given is worthless.
|
||||
assert!(crate::rename::prepare(&ws, &uri, offset).is_ok());
|
||||
let (edit, _) = crate::rename::rename(&ws, &uri, offset, "renamed").expect("renames");
|
||||
let (edit, _) =
|
||||
crate::rename::rename_traced(&ws, &uri, offset, "renamed", &mut None).expect("renames");
|
||||
assert_eq!(edit.changes.map(|c| c.len()), Some(4), "the module and its three tops");
|
||||
|
||||
eprintln!(
|
||||
|
||||
@@ -36,7 +36,7 @@ use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{ModuleRef, RefactorEdit};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
/// The kind every port refactoring is filed under, so a client can ask for
|
||||
@@ -73,6 +73,24 @@ pub fn commands() -> Vec<String> {
|
||||
/// ([`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.
|
||||
/// Every module name a port refactoring at `offset` could act on, asked of
|
||||
/// the buffer's **own parse** rather than of its text.
|
||||
///
|
||||
/// `doc.tree` is the tolerant parse of `doc.text`, which is exactly what the
|
||||
/// text form would build (`docs/features/one-parse/README.md`), so the answer
|
||||
/// is the same and the parse is not paid for twice (take 5 §P1b).
|
||||
///
|
||||
/// A buffer on the large-file fast path is the exception, and deliberately so:
|
||||
/// its `tree` is the analysis of the *empty* file, while the text form parses
|
||||
/// the real bytes and may offer. That is today's behaviour and this reuse does
|
||||
/// not change it — see `docs/features/perf5-p1/README.md`.
|
||||
fn modules_at(doc: &Document, offset: u32) -> Vec<String> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::port_action_modules(&doc.text, offset),
|
||||
false => vlog_refactor::port_action_modules_in(&doc.tree, offset),
|
||||
}
|
||||
}
|
||||
|
||||
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() };
|
||||
@@ -82,7 +100,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
|
||||
// find something, it says which module, so the files handed to the engine
|
||||
// are that module's own fan-out rather than every file in scope
|
||||
// (`Workspace::module_sources`).
|
||||
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
|
||||
let modules = modules_at(doc, offset);
|
||||
if modules.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -146,7 +164,7 @@ pub fn offers(
|
||||
) -> 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);
|
||||
let modules = modules_at(doc, 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
|
||||
@@ -155,10 +173,10 @@ pub fn offers(
|
||||
return Vec::new();
|
||||
}
|
||||
let sources = offer_sources(ws, &path, &doc.text, &modules);
|
||||
vlog_refactor::port_actions(&sources, &path, offset)
|
||||
offered(doc, &sources, &path, offset)
|
||||
.into_iter()
|
||||
.map(|action| {
|
||||
let title = counted(ws, action.title, &modules);
|
||||
.map(|offer| {
|
||||
let title = counted(ws, offer.title, &modules);
|
||||
let data =
|
||||
serde_json::to_value(Offer { uri: uri.clone(), position, title: title.clone() })
|
||||
.ok();
|
||||
@@ -172,6 +190,40 @@ pub fn offers(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Which refactorings the cursor would be offered, and what each title says —
|
||||
/// asked of the buffer's **own** parse and analysis rather than recomputed.
|
||||
///
|
||||
/// `vlog_refactor::port_offers_in` runs each of the four planners' plan-time
|
||||
/// half over `doc`'s existing tree, diagnostics and semantics plus, at most,
|
||||
/// one parse of the instantiated module's declaring file. It builds no index
|
||||
/// and verifies nothing, which is the whole of take 5 §P1c: the offer used to
|
||||
/// compute four verified plans over one or two files and throw all four edits
|
||||
/// away (`docs/features/perf5-p1/README.md`). [`resolve`] still recomputes and
|
||||
/// verifies the real refactoring over the module's whole fan-out when the user
|
||||
/// clicks.
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes — [`modules_at`] draws the same line, and for the same
|
||||
/// reason.
|
||||
fn offered(
|
||||
doc: &Document,
|
||||
sources: &[(PathBuf, String)],
|
||||
path: &Path,
|
||||
offset: u32,
|
||||
) -> Vec<vlog_refactor::PortOffer> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::port_offers(sources, path, offset),
|
||||
false => vlog_refactor::port_offers_in(
|
||||
sources,
|
||||
path,
|
||||
&doc.tree,
|
||||
&doc.diagnostics,
|
||||
&doc.semantics,
|
||||
offset,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The files an [`offers`] call reads: the buffer the request names, and the
|
||||
/// declaration of every module an instantiation under the cursor names.
|
||||
///
|
||||
|
||||
@@ -20,6 +20,7 @@ use vlog_parser::LineIndex;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::locate::display_name;
|
||||
use crate::rename_trace::SelectionTrace;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
@@ -48,11 +49,19 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameRe
|
||||
|
||||
/// The whole rename as a `WorkspaceEdit`, plus whatever the engine wants the
|
||||
/// user told. An `Err` is the engine's own sentence, returned verbatim.
|
||||
pub fn rename(
|
||||
/// `trace` is filled whenever the request got as far as asking the engine,
|
||||
/// refusals included, because a rename that refuses after 800 ms is exactly
|
||||
/// the kind this exists to explain (take 5 §P2a). Its two halves are the
|
||||
/// server's ([`SelectionTrace`]: which rung wanted which file) and the
|
||||
/// engine's ([`vlog_refactor::RenameTrace`]: where the time and the parses
|
||||
/// went); it reaches a user only through `--verbose`'s `timing:` channel, and
|
||||
/// a caller that wants none passes `&mut None`.
|
||||
pub fn rename_traced(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
trace: &mut Option<String>,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
|
||||
@@ -62,11 +71,18 @@ pub fn rename(
|
||||
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
|
||||
// the engine will say so, and saying it is cheap either way.
|
||||
let old_name = vlog_refactor::rename_name_at(&doc.semantics, offset);
|
||||
let sources = match &old_name {
|
||||
Some(name) => ws.rename_sources(&path, name, Some(new_name)),
|
||||
None => ws.sources(),
|
||||
let (sources, selection) = match &old_name {
|
||||
Some(name) => ws.rename_sources_traced(&path, name, Some(new_name)),
|
||||
None => {
|
||||
let all = ws.sources();
|
||||
let selection = SelectionTrace::whole_scope(all.len(), 0.0);
|
||||
(all, selection)
|
||||
}
|
||||
};
|
||||
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
|
||||
let mut engine = vlog_refactor::RenameTrace::default();
|
||||
let outcome = vlog_refactor::rename_traced(&sources, &path, offset, new_name, &mut engine);
|
||||
*trace = Some(format!("{} {}", selection.line(), engine.line()));
|
||||
let refactoring = outcome?;
|
||||
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
|
||||
for (path, edits) in &refactoring.edits {
|
||||
@@ -116,7 +132,7 @@ pub fn rename(
|
||||
/// about the one shape it cannot see.
|
||||
///
|
||||
/// Subtracting the handed set leaves out every open buffer too, because
|
||||
/// [`Workspace::rename_sources`] puts every open buffer in it.
|
||||
/// [`Workspace::rename_sources_traced`] puts every open buffer in it.
|
||||
fn unread_macro_warnings(ws: &Workspace, name: &str, sources: &[(PathBuf, String)]) -> Vec<String> {
|
||||
let index = ws.index();
|
||||
index
|
||||
@@ -141,6 +157,17 @@ mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// [`rename_traced`] with the trace thrown away — what a test that is not
|
||||
/// about the trace asks.
|
||||
fn rename(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
rename_traced(ws, uri, offset, new_name, &mut None)
|
||||
}
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
@@ -281,7 +308,7 @@ mod tests {
|
||||
fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec<PathBuf> {
|
||||
let doc = ws.document_for_path(path).expect("the request's file is open");
|
||||
match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
|
||||
Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0,
|
||||
None => ws.sources(),
|
||||
}
|
||||
.into_iter()
|
||||
@@ -301,7 +328,7 @@ mod tests {
|
||||
let everything = ws.sources();
|
||||
let doc = ws.document_for_path(path).expect("the request's file is open");
|
||||
let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
|
||||
Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0,
|
||||
None => everything.clone(),
|
||||
};
|
||||
for (path, text) in &subset {
|
||||
@@ -955,7 +982,7 @@ mod tests {
|
||||
|
||||
// The premise: `far.svh` is in no rung of the fan-out, so the engine
|
||||
// never sees it. Asked of the same function `rename` asks.
|
||||
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
|
||||
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
|
||||
assert!(
|
||||
!handed.iter().any(|(path, _)| path.ends_with("far.svh")),
|
||||
"premise: the engine is not handed far.svh — {handed:?}"
|
||||
@@ -989,7 +1016,7 @@ mod tests {
|
||||
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
|
||||
let (ws, uri) = macro_workspace(&tree, &far);
|
||||
|
||||
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
|
||||
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
|
||||
assert!(
|
||||
handed.iter().any(|(path, _)| path.ends_with("far.svh")),
|
||||
"premise: instantiating `sub` puts far.svh in the source set"
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Which rung of the rename fan-out put each file in the engine's input.
|
||||
//!
|
||||
//! Take 5 §P2a (`docs/features/perf5-p2/README.md`). `Workspace::rename_sources_traced`
|
||||
//! climbs six rungs and has one escape hatch, and the tracker's own note says
|
||||
//! it plainly: *two output files is not an input count*. A rename of `state_q`
|
||||
//! may hand the engine hundreds of files and nobody could say which rung asked
|
||||
//! for them. This module is the answer — a set of paths that also remembers
|
||||
//! **why** each one was added.
|
||||
//!
|
||||
//! [`Wanted`] is a `BTreeMap<PathBuf, Rung>` with a current [`Rung`]: the
|
||||
//! selector sets the rung it is on and inserts exactly as it did before, so
|
||||
//! the selection logic is not changed by being watched. The first rung to ask
|
||||
//! for a path is the one recorded, which is what makes the counts add up to
|
||||
//! the selected set rather than over-counting a file three rungs want.
|
||||
//!
|
||||
//! Take 5 §P2d added the second question on top of the first: of the files a
|
||||
//! rung asked for, how many **write neither name down** and are therefore in
|
||||
//! the request only to shape how the others resolve ([`indirect_census`]).
|
||||
//! That census is what says which rung a narrower selector would have to
|
||||
//! argue about, and the argument it needs.
|
||||
//!
|
||||
//! Nothing here decides anything. A [`SelectionTrace`] is written, logged once
|
||||
//! behind `--verbose`, and dropped.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
/// Why one file is in a rename's input.
|
||||
///
|
||||
/// One variant per rung of [`crate::state::Workspace::rename_sources_traced`]'s
|
||||
/// ladder, in the order the ladder climbs them.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Rung {
|
||||
/// The file the request was made in.
|
||||
#[default]
|
||||
Request,
|
||||
/// A file declaring one of the two names — its own file, from
|
||||
/// `workspace_symbols` or `hierarchical_declarations`.
|
||||
Declaration,
|
||||
/// A file the index recorded a use of such a declaration in.
|
||||
Reference,
|
||||
/// A file instantiating the name, or one of its containers.
|
||||
Instantiation,
|
||||
/// A file whose `` `define`` table names it or spells it in a macro body.
|
||||
MacroText,
|
||||
/// A file spelling the **new** name in a use this workspace had to look
|
||||
/// outside that file to answer.
|
||||
Speller,
|
||||
/// An open buffer, added whatever else it is.
|
||||
OpenBuffer,
|
||||
}
|
||||
|
||||
impl Rung {
|
||||
/// The name this rung is counted under in the `timing:` line.
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Rung::Request => "request",
|
||||
Rung::Declaration => "declaration",
|
||||
Rung::Reference => "reference",
|
||||
Rung::Instantiation => "instantiation",
|
||||
Rung::MacroText => "macro",
|
||||
Rung::Speller => "speller",
|
||||
Rung::OpenBuffer => "open",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every rung, in ladder order — so a trace line always has the same
|
||||
/// fields whether or not a rung contributed.
|
||||
const ALL: [Rung; 7] = [
|
||||
Rung::Request,
|
||||
Rung::Declaration,
|
||||
Rung::Reference,
|
||||
Rung::Instantiation,
|
||||
Rung::MacroText,
|
||||
Rung::Speller,
|
||||
Rung::OpenBuffer,
|
||||
];
|
||||
}
|
||||
|
||||
/// How many files each rung was the first to ask for, and whether the
|
||||
/// ambiguity escape hatch fired.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct SelectionTrace {
|
||||
counts: Vec<(Rung, usize)>,
|
||||
/// The index could not bound the fan-out, so every in-scope file went.
|
||||
pub fallback: bool,
|
||||
/// How many files went in the end.
|
||||
pub selected: usize,
|
||||
/// Milliseconds the selection itself took, reading and all.
|
||||
pub ms: f64,
|
||||
/// Per rung, how many of its files write **neither** name down —
|
||||
/// [`indirect_census`]. Empty on the fallback path, which climbs no rung.
|
||||
pub indirect: Vec<(Rung, usize)>,
|
||||
}
|
||||
|
||||
impl SelectionTrace {
|
||||
/// The trace of a selection that gave up and handed over the whole scope
|
||||
/// — the ambiguity escape hatch, and a cursor with no name to fan out
|
||||
/// from. No rung ran, so none is counted.
|
||||
pub fn whole_scope(selected: usize, ms: f64) -> SelectionTrace {
|
||||
SelectionTrace { counts: Vec::new(), fallback: true, selected, ms, indirect: Vec::new() }
|
||||
}
|
||||
|
||||
/// One file added by `rung`, if no earlier rung had it.
|
||||
fn add(&mut self, rung: Rung) {
|
||||
match self.counts.iter_mut().find(|(held, _)| *held == rung) {
|
||||
Some((_, count)) => *count += 1,
|
||||
None => self.counts.push((rung, 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many files this rung was the first to ask for.
|
||||
pub fn count(&self, rung: Rung) -> usize {
|
||||
self.counts.iter().find(|(held, _)| *held == rung).map_or(0, |(_, count)| *count)
|
||||
}
|
||||
|
||||
/// The trace as one `timing:`-style fragment.
|
||||
pub fn line(&self) -> String {
|
||||
let rungs: Vec<String> = Rung::ALL
|
||||
.iter()
|
||||
.map(|rung| format!("{}={}", rung.label(), self.count(*rung)))
|
||||
.collect();
|
||||
format!(
|
||||
"select={:.1}ms selected={} fallback={} rungs{{{}}} {}",
|
||||
self.ms,
|
||||
self.selected,
|
||||
self.fallback,
|
||||
rungs.join(" "),
|
||||
census_line(&self.indirect)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The path set a fan-out fills, plus the rung it is currently climbing.
|
||||
///
|
||||
/// `paths` is exactly the `BTreeSet<PathBuf>` the selector built before; the
|
||||
/// only difference is that an insertion also tells the trace which rung made
|
||||
/// it. A path already held is not re-attributed, so the counts partition the
|
||||
/// selected set.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Wanted {
|
||||
paths: BTreeMap<PathBuf, Rung>,
|
||||
trace: SelectionTrace,
|
||||
rung: Rung,
|
||||
}
|
||||
|
||||
impl Wanted {
|
||||
/// An empty set, on the rung a request's own file is added by.
|
||||
pub fn new() -> Wanted {
|
||||
Wanted::default()
|
||||
}
|
||||
|
||||
/// Climb to `rung`: every insertion until the next call is attributed to
|
||||
/// it.
|
||||
pub fn on(&mut self, rung: Rung) {
|
||||
self.rung = rung;
|
||||
}
|
||||
|
||||
/// Add one path, attributed to the current rung if it is new.
|
||||
///
|
||||
/// `entry(…).or_insert(…)`, not `insert(…)`: the map keeps the **first**
|
||||
/// rung to ask for a path, which is what makes the counts partition the
|
||||
/// selected set. A plain `insert` would overwrite with the last.
|
||||
pub fn insert(&mut self, path: PathBuf) {
|
||||
let rung = self.rung;
|
||||
let before = self.paths.len();
|
||||
self.paths.entry(path).or_insert(rung);
|
||||
if self.paths.len() != before {
|
||||
self.trace.add(rung);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Wanted::insert`] over an iterator — the shape the selector's
|
||||
/// `wanted.extend(...)` calls had.
|
||||
pub fn extend(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
|
||||
for path in paths {
|
||||
self.insert(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths, in path order and each with the rung that asked for it, and
|
||||
/// the trace of how they got there.
|
||||
pub fn finish(self) -> (BTreeMap<PathBuf, Rung>, SelectionTrace) {
|
||||
let Wanted { paths, mut trace, .. } = self;
|
||||
trace.selected = paths.len();
|
||||
(paths, trace)
|
||||
}
|
||||
}
|
||||
|
||||
/// How many files each rung asked for that **write neither name down**.
|
||||
///
|
||||
/// The census §P2d turns on. Every direct input of the four verifier checks is
|
||||
/// a file that spells one of the two names: an occurrence is a use of the old
|
||||
/// name, `check::watched_files` watches exactly the files whose text holds
|
||||
/// either as a whole word, `Scope::warnings` speaks only about the two names,
|
||||
/// and an edited file is a subset of the watched ones. A selected file that
|
||||
/// writes neither is therefore in the request for one reason only — **it
|
||||
/// shapes how the others resolve**, by declaring a unit some path hops
|
||||
/// through or a base class a member lookup climbs to.
|
||||
///
|
||||
/// So this is not "files that could be dropped". It is the exact set whose
|
||||
/// contribution is *indirect*, which is the set a narrower selector has to
|
||||
/// argue about one shape at a time. Counting it by rung says which rung the
|
||||
/// argument would have to be made for.
|
||||
///
|
||||
/// The word census is `FileFacts::words`, so this reads no file and parses
|
||||
/// nothing. It is asked of the **selected** files only — one `facts_for` and
|
||||
/// two binary searches each — rather than through
|
||||
/// [`WorkspaceIndex::files_mentioning`], which would walk every record in the
|
||||
/// workspace to answer about a couple of hundred of them. On the tail rename
|
||||
/// that is the difference between ~1.7 ms and ~0.05 ms, and a diagnostic that
|
||||
/// costs a measurable slice of the request it is measuring is a bad
|
||||
/// instrument.
|
||||
///
|
||||
/// A path the index has no record for — an open buffer the scan has not
|
||||
/// reached — counts as spelling the name: the census may not claim a file is
|
||||
/// idle when it does not know.
|
||||
pub fn indirect_census(
|
||||
index: &WorkspaceIndex,
|
||||
paths: &BTreeMap<PathBuf, Rung>,
|
||||
names: [&str; 2],
|
||||
) -> Vec<(Rung, usize)> {
|
||||
let idle = |path: &Path| match index.facts_for(path) {
|
||||
Some(facts) => !names
|
||||
.iter()
|
||||
.any(|name| facts.words().binary_search_by(|w| w.as_str().cmp(name)).is_ok()),
|
||||
None => false,
|
||||
};
|
||||
Rung::ALL
|
||||
.iter()
|
||||
.map(|rung| {
|
||||
let count = paths.iter().filter(|(path, held)| *held == rung && idle(path)).count();
|
||||
(*rung, count)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// [`indirect_census`] as one `timing:`-style fragment — every rung named,
|
||||
/// whether or not it contributed, so the line's shape never moves.
|
||||
pub fn census_line(census: &[(Rung, usize)]) -> String {
|
||||
let fields: Vec<String> = Rung::ALL
|
||||
.iter()
|
||||
.map(|rung| {
|
||||
let count = census.iter().find(|(held, _)| held == rung).map_or(0, |(_, n)| *n);
|
||||
format!("{}={}", rung.label(), count)
|
||||
})
|
||||
.collect();
|
||||
format!("indirect{{{}}}", fields.join(" "))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_first_rung_to_ask_for_a_path_is_the_one_counted() {
|
||||
let mut wanted = Wanted::new();
|
||||
wanted.insert(PathBuf::from("/rtl/a.sv"));
|
||||
wanted.on(Rung::Reference);
|
||||
wanted.insert(PathBuf::from("/rtl/a.sv"));
|
||||
wanted.insert(PathBuf::from("/rtl/b.sv"));
|
||||
let (paths, trace) = wanted.finish();
|
||||
assert_eq!(paths.len(), 2);
|
||||
assert_eq!(trace.count(Rung::Request), 1);
|
||||
assert_eq!(trace.count(Rung::Reference), 1);
|
||||
assert_eq!(trace.selected, 2);
|
||||
// And the map agrees with the counts: a re-insertion does not
|
||||
// re-attribute, which is what makes the census partition the set.
|
||||
assert_eq!(paths[&PathBuf::from("/rtl/a.sv")], Rung::Request);
|
||||
assert_eq!(paths[&PathBuf::from("/rtl/b.sv")], Rung::Reference);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_census_counts_only_the_files_that_write_neither_name() {
|
||||
let index = WorkspaceIndex::build(vec![
|
||||
(PathBuf::from("/w/decl.sv"), "module decl; logic state_q; endmodule\n"),
|
||||
(PathBuf::from("/w/user.sv"), "module user; decl u_d (); endmodule\n"),
|
||||
(PathBuf::from("/w/reads.sv"), "module reads; assign x = u_d.state_q; endmodule\n"),
|
||||
]);
|
||||
let mut paths = BTreeMap::new();
|
||||
paths.insert(PathBuf::from("/w/decl.sv"), Rung::Declaration);
|
||||
paths.insert(PathBuf::from("/w/reads.sv"), Rung::Reference);
|
||||
paths.insert(PathBuf::from("/w/user.sv"), Rung::Instantiation);
|
||||
let census = indirect_census(&index, &paths, ["state_q", "state_q_x"]);
|
||||
let count = |rung: Rung| census.iter().find(|(r, _)| *r == rung).map_or(0, |(_, n)| *n);
|
||||
assert_eq!(count(Rung::Declaration), 0, "it declares the name");
|
||||
assert_eq!(count(Rung::Reference), 0, "it spells the name");
|
||||
assert_eq!(count(Rung::Instantiation), 1, "it only instantiates the container");
|
||||
assert!(census_line(&census).contains("instantiation=1"), "{}", census_line(&census));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rung_appears_in_the_line_even_at_zero() {
|
||||
let trace = SelectionTrace::default();
|
||||
let line = trace.line();
|
||||
for rung in Rung::ALL {
|
||||
assert!(line.contains(&format!("{}=0", rung.label())), "{line} lacks {rung:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! What order a scan walks its work list in, and how much of that order a
|
||||
//! request answered mid-scan is owed.
|
||||
//!
|
||||
//! A scan indexes every in-scope file, and [`vlog_semantic::IndexBuilder`]
|
||||
//! sorts its records by path inside `finish`, so **no insertion order can
|
||||
//! reach the finished index**. What the order decides is what the *prefix* of
|
||||
//! a scan holds — which file the progress bar names first, and what a request
|
||||
//! answered between two files can see (`docs/features/scan-interleave`).
|
||||
//!
|
||||
//! Three groups, in this order:
|
||||
//!
|
||||
//! 1. the **open buffers' own files** — the ones the user is looking at;
|
||||
//! 2. every other file under those buffers' **raised scope directories** —
|
||||
//! the neighbourhood `docs/features/index-scope/README.md`'s folder rung
|
||||
//! would have indexed for them;
|
||||
//! 3. everything else, in path order.
|
||||
//!
|
||||
//! Group 1 was the whole of `Workspace::open_first` until 2026-09-08, and on
|
||||
//! its own it made the first useful answer of a workspace-scoped session
|
||||
//! *empty*: a definition sent with the opening `didOpen` was answered off a
|
||||
//! prefix holding that one buffer and the alphabet after it, and the module it
|
||||
//! named lives in the folder next door. Group 2 is that folder
|
||||
//! (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::index_order;
|
||||
|
||||
/// A scan's work list, ordered, with the length of its head segment.
|
||||
pub struct WorkList {
|
||||
/// Every file the scan will index, in the order it will index them.
|
||||
pub files: Vec<PathBuf>,
|
||||
/// How many files at the front of `files` are the user's own
|
||||
/// neighbourhood — groups 1 and 2 above.
|
||||
///
|
||||
/// **0 means there is no neighbourhood worth waiting for**: no buffer is
|
||||
/// open, none of them has a folder in scope, or the folders cover so much
|
||||
/// of the work list that "the user's own folder" and "the workspace" are
|
||||
/// the same wait. See [`work_list`].
|
||||
pub head: usize,
|
||||
}
|
||||
|
||||
/// The user's own file.
|
||||
const OWN: u8 = 0;
|
||||
/// A file under one of the folders the user's own files raise to.
|
||||
const FOLDER: u8 = 1;
|
||||
/// Everything else.
|
||||
const TAIL: u8 = 2;
|
||||
|
||||
/// Order `files` open-buffers-first, then their folders, then the rest.
|
||||
///
|
||||
/// `open` is every open buffer's own path and `folders` the directories those
|
||||
/// buffers raise to (`Workspace::raised`). Both may be empty, and an empty
|
||||
/// `folders` is the ordering this function had before 2026-09-08.
|
||||
///
|
||||
/// The head is reported raw; [`worth_waiting`] is what bounds it, because the
|
||||
/// bound is against the **whole** scan and this function may be ordering only
|
||||
/// what is left of one.
|
||||
pub fn work_list(files: Vec<PathBuf>, open: &[PathBuf], folders: &[PathBuf]) -> WorkList {
|
||||
// Asked of `vlog_semantic` rather than re-derived here, so the count a
|
||||
// scan reports is the count the index will hold: sorted by path, one entry
|
||||
// per path.
|
||||
let ordered = index_order(files.into_iter().map(|path| (path, ())));
|
||||
let own: HashSet<&Path> = open.iter().map(PathBuf::as_path).collect();
|
||||
let mut ranked: Vec<(u8, PathBuf)> =
|
||||
ordered.into_iter().map(|(path, ())| (rank(&path, &own, folders), path)).collect();
|
||||
// Stable, so each group keeps the path order `index_order` sorted it into.
|
||||
ranked.sort_by_key(|(rank, _)| *rank);
|
||||
let head = ranked.iter().take_while(|(rank, _)| *rank < TAIL).count();
|
||||
WorkList { files: ranked.into_iter().map(|(_, path)| path).collect(), head }
|
||||
}
|
||||
|
||||
/// `pending` — the files a held request would wait for — or **0** when that is
|
||||
/// too many to wait for in a scan of `total` files.
|
||||
///
|
||||
/// A request held for the startup scan waits for the whole neighbourhood
|
||||
/// before it is answered ([`WorkList::head`]), which is a good trade only
|
||||
/// while the neighbourhood is a small part of the scan: a buffer opened from a
|
||||
/// workspace *root* raises to that root, and waiting for "its folder" would be
|
||||
/// waiting for the entire scan and answering nothing at all until it ended. So
|
||||
/// a neighbourhood that is not a minority of the workspace is no
|
||||
/// neighbourhood — the ordering still applies, and the drain falls back to the
|
||||
/// first interleave point exactly as it did before.
|
||||
///
|
||||
/// **`pending` is what is left to wait for, not where the segment ends.** A
|
||||
/// `didOpen` can arrive at any point of a scan, and re-ordering puts its
|
||||
/// folder next: 124 files is 124 files of waiting whether the scan has done
|
||||
/// none of the workspace or nine tenths of it.
|
||||
pub fn worth_waiting(pending: usize, total: usize) -> usize {
|
||||
match pending * 2 > total {
|
||||
true => 0,
|
||||
false => pending,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of the three groups `path` belongs to.
|
||||
fn rank(path: &Path, own: &HashSet<&Path>, folders: &[PathBuf]) -> u8 {
|
||||
if own.contains(path) {
|
||||
return OWN;
|
||||
}
|
||||
match folders.iter().any(|folder| path.starts_with(folder)) {
|
||||
true => FOLDER,
|
||||
false => TAIL,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn paths(names: &[&str]) -> Vec<PathBuf> {
|
||||
names.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
fn names(list: &WorkList) -> Vec<String> {
|
||||
list.files.iter().map(|p| p.display().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_nothing_open_the_list_is_path_order_and_there_is_no_head() {
|
||||
let list = work_list(paths(&["/w/z.sv", "/w/a.sv", "/w/m.sv"]), &[], &[]);
|
||||
assert_eq!(names(&list), ["/w/a.sv", "/w/m.sv", "/w/z.sv"]);
|
||||
assert_eq!(list.head, 0, "nothing is waited for when nothing is open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_open_buffer_leads_then_its_folder_then_the_rest() {
|
||||
let list = work_list(
|
||||
paths(&[
|
||||
"/w/other/far.sv",
|
||||
"/w/ip/aes/rtl/aes.sv",
|
||||
"/w/ip/aes/dv/tb.sv",
|
||||
"/w/other/near.sv",
|
||||
]),
|
||||
&paths(&["/w/ip/aes/dv/tb.sv"]),
|
||||
&paths(&["/w/ip/aes"]),
|
||||
);
|
||||
assert_eq!(
|
||||
names(&list),
|
||||
["/w/ip/aes/dv/tb.sv", "/w/ip/aes/rtl/aes.sv", "/w/other/far.sv", "/w/other/near.sv"],
|
||||
"the buffer, then its folder, then the rest in path order"
|
||||
);
|
||||
assert_eq!(list.head, 2, "the buffer and its folder are what a held request waits for");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_that_is_most_of_the_workspace_is_not_a_head_to_wait_for() {
|
||||
// A buffer opened from the workspace root raises to the root, so
|
||||
// "its folder" is the whole scan. The order is unchanged; the drain
|
||||
// falls back to the first interleave point.
|
||||
let files = paths(&["/w/a.sv", "/w/b.sv", "/w/c.sv"]);
|
||||
let list = work_list(files, &paths(&["/w/a.sv"]), &paths(&["/w"]));
|
||||
assert_eq!(names(&list), ["/w/a.sv", "/w/b.sv", "/w/c.sv"]);
|
||||
assert_eq!(list.head, 3, "the ranking itself says the whole list is the folder");
|
||||
assert_eq!(worth_waiting(list.head, 3), 0, "and that is no head at all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_half_is_still_a_head_and_one_more_is_not() {
|
||||
assert_eq!(worth_waiting(2, 4), 2, "two of four is a minority");
|
||||
assert_eq!(worth_waiting(3, 4), 0, "three of four is not");
|
||||
assert_eq!(worth_waiting(0, 4), 0, "and nothing is nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bound_is_against_the_whole_scan_and_not_against_what_is_left() {
|
||||
// The `didOpen` that names a folder can arrive at any point of a scan.
|
||||
// Measured against the tail alone, a 124-file folder would stop being
|
||||
// worth waiting for once 3 700 of a 3 976-file workspace were done —
|
||||
// which is exactly when it costs least.
|
||||
assert_eq!(worth_waiting(124, 3_976), 124, "124 files of 3 976, at any point of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_handed_over_twice_is_one_file() {
|
||||
let list = work_list(paths(&["/w/a.sv", "/w/a.sv", "/w/b.sv"]), &[], &[]);
|
||||
assert_eq!(names(&list), ["/w/a.sv", "/w/b.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_outside_the_scope_still_lends_its_folder() {
|
||||
// The buffer's own file is not in the work list — it is over the size
|
||||
// cap, say — but the folder it raised is still the neighbourhood.
|
||||
let list = work_list(
|
||||
paths(&["/w/ip/aes/rtl/aes.sv", "/w/other/far.sv"]),
|
||||
&paths(&["/w/ip/aes/dv/huge.sv"]),
|
||||
&paths(&["/w/ip/aes"]),
|
||||
);
|
||||
assert_eq!(names(&list), ["/w/ip/aes/rtl/aes.sv", "/w/other/far.sv"]);
|
||||
assert_eq!(list.head, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
//! What one workspace scan spent its time on, and what the tables it left
|
||||
//! behind weigh — the startup breakdown take 5 §P4a exists to measure.
|
||||
//!
|
||||
//! A [`ScanTrace`] rides on the [`crate::state::Scan`] it describes. It is a
|
||||
//! bag of sums and counters and nothing else: no per-file allocation, no
|
||||
//! per-file string, no `Vec` that grows with the work list, so a traced scan
|
||||
//! costs a handful of clock reads per file and two `format!`s at the end. It
|
||||
//! is off unless `--verbose` asked for it ([`ScanTrace::new`]), and off means
|
||||
//! [`ScanTrace::now`] hands back `None` and every `add` below is a branch.
|
||||
//!
|
||||
//! The three lines it renders go out on the `timing:` channel
|
||||
//! (`docs/features/verbose-timing/README.md`) when the scan ends. They are
|
||||
//! `key=value` after a human prefix because both readers matter: a person
|
||||
//! grepping an output channel, and `tools/perf/phases_p4.py`, which turns
|
||||
//! them into schema-2 rows.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::time::Instant;
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
thread_local! {
|
||||
static READS: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many source files this thread has read off disk for a scan.
|
||||
///
|
||||
/// A work counter, not a timer, and modelled on `vlog_parser::stats::parses`
|
||||
/// for the same reason: the claim a scan makes since 2026-09-08 is that it
|
||||
/// reads each file's bytes **exactly once** — the content hash, the parse and
|
||||
/// the `` `include`` scan all come out of that one read — and the honest way
|
||||
/// to prove that is to count the reads. A stopwatch would be a flake; a count
|
||||
/// is not.
|
||||
///
|
||||
/// Per thread, because `cargo test` runs tests in parallel and a process-wide
|
||||
/// counter would be adding up every other test's scans. Monotone and never
|
||||
/// reset, so a caller measures a delta.
|
||||
///
|
||||
/// Only a test asks — this is a bin crate, so nothing outside it can — while
|
||||
/// [`count_read`] is **unconditional**: one non-atomic add per file is noise
|
||||
/// beside the read it counts, and gating the increment as well would mean the
|
||||
/// path under test and the shipped path were not the same code.
|
||||
#[cfg(test)]
|
||||
pub fn source_reads() -> u64 {
|
||||
READS.with(Cell::get)
|
||||
}
|
||||
|
||||
/// Count one file read off disk — see [`source_reads`].
|
||||
pub fn count_read() {
|
||||
READS.with(|reads| reads.set(reads.get() + 1));
|
||||
}
|
||||
|
||||
use crate::candidates::Candidates;
|
||||
use crate::includes::IncludeGraph;
|
||||
use crate::index_cache::IndexCache;
|
||||
|
||||
/// What the persistent store's own work cost, counted inside
|
||||
/// [`crate::index_cache::IndexCache`] because that is where it happens.
|
||||
///
|
||||
/// Always counted, trace or no trace: the four clock reads a file costs here
|
||||
/// are noise beside the read and the decode they bracket, and a flag threaded
|
||||
/// through the cache to save them would be more code than it saves time.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct CacheWork {
|
||||
/// Hashing the text and finding the entry — what every lookup pays,
|
||||
/// whether it hits or misses.
|
||||
pub lookup_ns: u64,
|
||||
/// Decoding the record of a lookup that hit.
|
||||
pub decode_ns: u64,
|
||||
/// Encoding a record on the way out.
|
||||
pub encode_ns: u64,
|
||||
/// Appending an encoded record to the log.
|
||||
pub write_ns: u64,
|
||||
/// Rewriting the whole store at the end of a whole scan.
|
||||
pub compact_ns: u64,
|
||||
/// Lookups that found a record for exactly these bytes.
|
||||
pub hits: usize,
|
||||
/// Lookups that did not, and so cost a parse.
|
||||
pub misses: usize,
|
||||
/// Records written through.
|
||||
pub records: usize,
|
||||
/// Write-throughs the store already held, byte for byte, and so did not
|
||||
/// append again — one per open buffer on a warm scan (§P4b (a)).
|
||||
pub repeats: usize,
|
||||
/// Encoded bytes handed to `FileFacts::decode`.
|
||||
pub decoded_bytes: usize,
|
||||
/// Encoded bytes appended to the log.
|
||||
pub written_bytes: usize,
|
||||
/// Times the store was read off disk. One per whole rescan that reached a
|
||||
/// file — a scan whose work list is empty opens nothing (§P4b (b1)).
|
||||
pub opens: usize,
|
||||
/// Times the store was actually rewritten. Zero when the rewrite would
|
||||
/// have reproduced the file byte for byte (§P4b (a)).
|
||||
pub compactions: usize,
|
||||
/// The store file's size before and after a compaction, in bytes.
|
||||
pub store_before: u64,
|
||||
pub store_after: u64,
|
||||
}
|
||||
|
||||
impl CacheWork {
|
||||
/// This session's counters minus the ones a scan started with, so a scan
|
||||
/// reports its own work rather than the process's.
|
||||
pub fn since(self, before: CacheWork) -> CacheWork {
|
||||
CacheWork {
|
||||
lookup_ns: self.lookup_ns.saturating_sub(before.lookup_ns),
|
||||
decode_ns: self.decode_ns.saturating_sub(before.decode_ns),
|
||||
encode_ns: self.encode_ns.saturating_sub(before.encode_ns),
|
||||
write_ns: self.write_ns.saturating_sub(before.write_ns),
|
||||
compact_ns: self.compact_ns.saturating_sub(before.compact_ns),
|
||||
hits: self.hits.saturating_sub(before.hits),
|
||||
misses: self.misses.saturating_sub(before.misses),
|
||||
records: self.records.saturating_sub(before.records),
|
||||
repeats: self.repeats.saturating_sub(before.repeats),
|
||||
decoded_bytes: self.decoded_bytes.saturating_sub(before.decoded_bytes),
|
||||
written_bytes: self.written_bytes.saturating_sub(before.written_bytes),
|
||||
opens: self.opens.saturating_sub(before.opens),
|
||||
compactions: self.compactions.saturating_sub(before.compactions),
|
||||
store_before: self.store_before,
|
||||
store_after: self.store_after,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How big the tables a finished scan leaves behind are — the memory half of
|
||||
/// §P4a, in counts and bytes rather than in a resident-set reading.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct TableSizes {
|
||||
pub index_files: usize,
|
||||
pub unit_names: usize,
|
||||
pub unit_defs: usize,
|
||||
pub members: usize,
|
||||
pub hier_members: usize,
|
||||
pub reference_keys: usize,
|
||||
pub reference_sites: usize,
|
||||
pub defines: usize,
|
||||
pub instantiations: usize,
|
||||
pub fact_words: usize,
|
||||
pub fact_word_bytes: usize,
|
||||
pub candidate_units: usize,
|
||||
pub candidate_macros: usize,
|
||||
pub candidate_words: usize,
|
||||
pub candidate_word_bytes: usize,
|
||||
pub include_edges: usize,
|
||||
pub include_known: usize,
|
||||
}
|
||||
|
||||
/// One scan's stage times, counts and end-state sizes.
|
||||
///
|
||||
/// Every `*_ms` is a sum over however many times that stage ran: `parse_ms`
|
||||
/// is every parse of the scan added up, `absorb_ms` is the one final absorb,
|
||||
/// `publish_absorb_ms` is the mid-scan ones.
|
||||
#[derive(Default)]
|
||||
pub struct ScanTrace {
|
||||
on: bool,
|
||||
/// When the scan began — the first thing [`crate::state::Workspace::begin_scan`] does.
|
||||
started: Option<Instant>,
|
||||
/// How long the server had been alive when this scan began.
|
||||
pub since_start_ms: f64,
|
||||
/// Whether this scan rebuilds the whole index or folds a widen in.
|
||||
pub kind: &'static str,
|
||||
/// Which scan of the session this is, counting from 1.
|
||||
pub number: u32,
|
||||
|
||||
// -- discovery ------------------------------------------------------
|
||||
/// Resolving the scope, walking it, asking the size cap about each file
|
||||
/// and taking every open buffer's text. **Not** reading the files: since
|
||||
/// 2026-09-08 that happens at the step that indexes each one, and is
|
||||
/// `read_ms` below (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
pub discovery_ms: f64,
|
||||
/// Sorting into index order and putting the user's own neighbourhood at
|
||||
/// the front ([`crate::scan_order`]).
|
||||
pub order_ms: f64,
|
||||
/// Reading the persistent store off disk.
|
||||
pub cache_open_ms: f64,
|
||||
/// Reading one file's text off disk, at the step that indexes it, summed
|
||||
/// over the scan. An open buffer's text is not read and not timed here:
|
||||
/// the scan took it when the work list was.
|
||||
pub read_ms: f64,
|
||||
/// Files the scan will read, known when the work list is taken — and the
|
||||
/// bytes it has read so far, which only equals the whole list once the
|
||||
/// scan has finished.
|
||||
pub read: usize,
|
||||
pub read_bytes: usize,
|
||||
/// The bytes the scan **holds** for its whole life: the open buffers'
|
||||
/// texts, taken with the work list because their facts were. Every other
|
||||
/// file's text lives from its own step to the end of it, which is what
|
||||
/// `work_kib` on the memory line reports.
|
||||
pub work_bytes: usize,
|
||||
/// Files the size cap kept out.
|
||||
pub skipped: usize,
|
||||
/// Entries the store held when it was opened, and their encoded bytes.
|
||||
pub cache_entries: usize,
|
||||
pub cache_bytes: usize,
|
||||
|
||||
// -- per file -------------------------------------------------------
|
||||
/// Parsing a file the store could not answer for, and its bytes.
|
||||
pub parse_ms: f64,
|
||||
pub parse_bytes: usize,
|
||||
/// Files indexed from an open buffer's own finished analysis. Untimed:
|
||||
/// there is nothing to time — the facts are already in hand, and what
|
||||
/// that file then costs is the record the store writes through, which is
|
||||
/// counted with every other record below.
|
||||
pub buffers: usize,
|
||||
/// The store's own work over this scan.
|
||||
pub cache: CacheWork,
|
||||
|
||||
// -- mid-scan publishes ---------------------------------------------
|
||||
pub publishes: usize,
|
||||
pub published: usize,
|
||||
pub publish_absorb_ms: f64,
|
||||
pub publish_candidates_ms: f64,
|
||||
pub publish_includes_ms: f64,
|
||||
pub publish_overlay_ms: f64,
|
||||
/// When the first publish landed, measured from the start of the scan —
|
||||
/// the earliest moment a request answered mid-scan can see any of it.
|
||||
pub first_publish_ms: f64,
|
||||
|
||||
// -- the end --------------------------------------------------------
|
||||
/// Working out which files left the scope.
|
||||
pub gone_ms: f64,
|
||||
pub absorb_ms: f64,
|
||||
pub candidates_ms: f64,
|
||||
pub includes_ms: f64,
|
||||
/// Re-resolving every open buffer against the finished index.
|
||||
pub overlay_ms: f64,
|
||||
pub overlays: usize,
|
||||
/// The whole scan, `begin_scan` to the end of `finish_scan`.
|
||||
pub total_ms: f64,
|
||||
pub sizes: TableSizes,
|
||||
}
|
||||
|
||||
impl ScanTrace {
|
||||
/// A trace that records, or one that does nothing at all.
|
||||
pub fn new(on: bool) -> ScanTrace {
|
||||
ScanTrace { on, started: on.then(Instant::now), ..ScanTrace::default() }
|
||||
}
|
||||
|
||||
/// A trace for a scan that is starting, numbered so a session's lines can
|
||||
/// be told apart — or an inert one when nobody asked for a trace.
|
||||
///
|
||||
/// `scans` is the session's own count of scans so far and is advanced
|
||||
/// here, so a line's number is the number of the scan that prints it.
|
||||
/// `since_start_ms` is left for the server to stamp: how long the process
|
||||
/// had been alive is the server's own knowledge, not the workspace's.
|
||||
pub fn opened(scans: &mut u32, on: bool, kind: &'static str) -> ScanTrace {
|
||||
*scans = scans.saturating_add(1);
|
||||
ScanTrace { kind, number: *scans, ..ScanTrace::new(on) }
|
||||
}
|
||||
|
||||
/// Whether anything below will be recorded.
|
||||
pub fn on(&self) -> bool {
|
||||
self.on
|
||||
}
|
||||
|
||||
/// The work list's size, the bytes the scan will hold for as long as it
|
||||
/// runs, and the store counters this scan is measured from.
|
||||
///
|
||||
/// `held` is what the scan is carrying — the open buffers' texts — and not
|
||||
/// the work list's own bytes, which are read a file at a time and let go
|
||||
/// again ([`ScanTrace::saw_read`]).
|
||||
///
|
||||
/// `cache` is the baseline [`ScanTrace::landed`] subtracts: a widen
|
||||
/// inherits the store the previous scan opened, so the counters on it are
|
||||
/// the session's and not this scan's. A whole scan that opens one of its
|
||||
/// own resets the baseline when it does.
|
||||
pub fn measure_work(&mut self, files: usize, held: usize, skipped: usize, cache: CacheWork) {
|
||||
if !self.on {
|
||||
return;
|
||||
}
|
||||
self.read = files;
|
||||
self.work_bytes = held;
|
||||
self.skipped = skipped;
|
||||
self.cache = cache;
|
||||
}
|
||||
|
||||
/// One file's text, read at the step that indexes it.
|
||||
pub fn saw_read(&mut self, bytes: usize, from: Option<Instant>) {
|
||||
if !self.on {
|
||||
return;
|
||||
}
|
||||
ScanTrace::add(&mut self.read_ms, from);
|
||||
self.read_bytes += bytes;
|
||||
}
|
||||
|
||||
/// Close this trace: the tables the finished scan left behind, measured.
|
||||
///
|
||||
/// Every size below is a walk, so all of them are behind [`ScanTrace::on`]
|
||||
/// and none of them happens in a session that did not ask for a trace.
|
||||
pub fn landed(
|
||||
&mut self,
|
||||
overlays: usize,
|
||||
cache: &IndexCache,
|
||||
index: &WorkspaceIndex,
|
||||
candidates: &Candidates,
|
||||
includes: &IncludeGraph,
|
||||
) {
|
||||
if !self.on {
|
||||
return;
|
||||
}
|
||||
// Read first, before a single size below is walked: describing a scan
|
||||
// is not part of the scan, and charging the walks to `total_ms` would
|
||||
// make the trace inflate the very number it exists to explain.
|
||||
self.total_ms = self.elapsed_ms();
|
||||
self.overlays = overlays;
|
||||
self.cache = cache.work().since(self.cache);
|
||||
// At the *end*, so the store's retention is what the finished scan
|
||||
// leaves resident rather than what it started from — the two differ
|
||||
// by every record a cold scan wrote.
|
||||
self.cache_entries = cache.entry_count();
|
||||
self.cache_bytes = cache.encoded_bytes();
|
||||
let tables = index.table_sizes();
|
||||
let counts = index.counts();
|
||||
let (units, macros, words, word_bytes) = candidates.sizes();
|
||||
let (include_edges, include_known) = includes.sizes();
|
||||
self.sizes = TableSizes {
|
||||
index_files: counts.files,
|
||||
unit_names: tables.unit_names,
|
||||
unit_defs: tables.unit_defs,
|
||||
members: tables.members,
|
||||
hier_members: tables.hier_members,
|
||||
reference_keys: tables.reference_keys,
|
||||
reference_sites: tables.reference_sites,
|
||||
defines: counts.defines,
|
||||
instantiations: counts.instantiations,
|
||||
fact_words: tables.words,
|
||||
fact_word_bytes: tables.word_bytes,
|
||||
candidate_units: units,
|
||||
candidate_macros: macros,
|
||||
candidate_words: words,
|
||||
candidate_word_bytes: word_bytes,
|
||||
include_edges,
|
||||
include_known,
|
||||
};
|
||||
}
|
||||
|
||||
/// The clock a stage is timed from — `None`, and so free, when off.
|
||||
pub fn now(&self) -> Option<Instant> {
|
||||
self.on.then(Instant::now)
|
||||
}
|
||||
|
||||
/// Add the time since `from` to `slot`. Nothing at all when off, because
|
||||
/// `now` handed out no clock to be since.
|
||||
pub fn add(slot: &mut f64, from: Option<Instant>) {
|
||||
if let Some(from) = from {
|
||||
*slot += millis(from);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long this scan has been running, or 0 when it is not being traced.
|
||||
pub fn elapsed_ms(&self) -> f64 {
|
||||
self.started.map(millis).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Stamp the first publish, if this is the first one.
|
||||
pub fn saw_publish(&mut self, files: usize) {
|
||||
self.publishes += 1;
|
||||
self.published += files;
|
||||
if self.publishes == 1 {
|
||||
self.first_publish_ms = self.elapsed_ms();
|
||||
}
|
||||
}
|
||||
|
||||
/// The stage line: every `*_ms` this scan collected, in the order the
|
||||
/// scan spends them.
|
||||
pub fn stage_line(&self) -> String {
|
||||
let c = &self.cache;
|
||||
format!(
|
||||
"scan {} stages ({}, {} files): discovery={:.2} order={:.2} cache_open={:.2} \
|
||||
read={:.2} lookup={:.2} decode={:.2} parse={:.2} encode={:.2} store_write={:.2} \
|
||||
publish_absorb={:.2} publish_candidates={:.2} publish_includes={:.2} \
|
||||
publish_overlay={:.2} gone={:.2} absorb={:.2} compact={:.2} candidates={:.2} \
|
||||
includes={:.2} overlay={:.2} total={:.2} since_start={:.2} ms",
|
||||
self.number,
|
||||
self.kind,
|
||||
self.read,
|
||||
self.discovery_ms,
|
||||
self.order_ms,
|
||||
self.cache_open_ms,
|
||||
self.read_ms,
|
||||
nanos(c.lookup_ns),
|
||||
nanos(c.decode_ns),
|
||||
self.parse_ms,
|
||||
nanos(c.encode_ns),
|
||||
nanos(c.write_ns),
|
||||
self.publish_absorb_ms,
|
||||
self.publish_candidates_ms,
|
||||
self.publish_includes_ms,
|
||||
self.publish_overlay_ms,
|
||||
self.gone_ms,
|
||||
self.absorb_ms,
|
||||
nanos(c.compact_ns),
|
||||
self.candidates_ms,
|
||||
self.includes_ms,
|
||||
self.overlay_ms,
|
||||
self.total_ms,
|
||||
self.since_start_ms,
|
||||
)
|
||||
}
|
||||
|
||||
/// The count line: how much work of each kind there was to spend that
|
||||
/// time on.
|
||||
pub fn count_line(&self) -> String {
|
||||
let c = &self.cache;
|
||||
format!(
|
||||
"scan {} counts ({}): read={} read_kib={} skipped={} hits={} misses={} buffers={} \
|
||||
records={} repeats={} decoded_kib={} written_kib={} opens={} compactions={} \
|
||||
publishes={} published={} first_publish={:.2} overlays={}",
|
||||
self.number,
|
||||
self.kind,
|
||||
self.read,
|
||||
kib(self.read_bytes),
|
||||
self.skipped,
|
||||
c.hits,
|
||||
c.misses,
|
||||
self.buffers,
|
||||
c.records,
|
||||
c.repeats,
|
||||
kib(c.decoded_bytes),
|
||||
kib(c.written_bytes),
|
||||
c.opens,
|
||||
c.compactions,
|
||||
self.publishes,
|
||||
self.published,
|
||||
self.first_publish_ms,
|
||||
self.overlays,
|
||||
)
|
||||
}
|
||||
|
||||
/// The memory line: what the scan left resident, table by table.
|
||||
pub fn memory_line(&self) -> String {
|
||||
let s = &self.sizes;
|
||||
format!(
|
||||
"scan {} memory ({}): store_before_kib={} store_after_kib={} cache_entries={} \
|
||||
cache_encoded_kib={} index_files={} unit_names={} unit_defs={} members={} \
|
||||
hier_members={} reference_keys={} reference_sites={} defines={} instantiations={} \
|
||||
fact_words={} fact_word_kib={} candidate_units={} candidate_macros={} \
|
||||
candidate_words={} candidate_word_kib={} include_edges={} include_known={} \
|
||||
work_kib={}",
|
||||
self.number,
|
||||
self.kind,
|
||||
kib(self.cache.store_before as usize),
|
||||
kib(self.cache.store_after as usize),
|
||||
self.cache_entries,
|
||||
kib(self.cache_bytes),
|
||||
s.index_files,
|
||||
s.unit_names,
|
||||
s.unit_defs,
|
||||
s.members,
|
||||
s.hier_members,
|
||||
s.reference_keys,
|
||||
s.reference_sites,
|
||||
s.defines,
|
||||
s.instantiations,
|
||||
s.fact_words,
|
||||
kib(s.fact_word_bytes),
|
||||
s.candidate_units,
|
||||
s.candidate_macros,
|
||||
s.candidate_words,
|
||||
kib(s.candidate_word_bytes),
|
||||
s.include_edges,
|
||||
s.include_known,
|
||||
kib(self.work_bytes),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Milliseconds since `from`.
|
||||
fn millis(from: Instant) -> f64 {
|
||||
from.elapsed().as_secs_f64() * 1_000.0
|
||||
}
|
||||
|
||||
/// Nanoseconds as milliseconds, the unit every line is written in.
|
||||
fn nanos(ns: u64) -> f64 {
|
||||
ns as f64 / 1_000_000.0
|
||||
}
|
||||
|
||||
/// Bytes as whole KiB, rounded down — the unit every size field carries.
|
||||
fn kib(bytes: usize) -> usize {
|
||||
bytes / 1024
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_trace_that_is_off_hands_out_no_clock_and_stays_zero() {
|
||||
let trace = ScanTrace::new(false);
|
||||
assert!(!trace.on());
|
||||
assert!(trace.now().is_none());
|
||||
assert_eq!(trace.elapsed_ms(), 0.0);
|
||||
let mut slot = 0.0;
|
||||
ScanTrace::add(&mut slot, trace.now());
|
||||
assert_eq!(slot, 0.0, "an off trace cannot accumulate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trace_that_is_on_accumulates_into_the_slot_it_is_given() {
|
||||
let trace = ScanTrace::new(true);
|
||||
let started = trace.now();
|
||||
assert!(started.is_some());
|
||||
let mut slot = 0.0;
|
||||
ScanTrace::add(&mut slot, started);
|
||||
ScanTrace::add(&mut slot, started);
|
||||
assert!(slot >= 0.0, "two adds are two summands, never a replacement");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_publish_is_the_one_that_is_stamped() {
|
||||
let mut trace = ScanTrace::new(true);
|
||||
trace.saw_publish(10);
|
||||
let first = trace.first_publish_ms;
|
||||
trace.saw_publish(5);
|
||||
assert_eq!(trace.publishes, 2);
|
||||
assert_eq!(trace.published, 15);
|
||||
assert_eq!(trace.first_publish_ms, first, "a later publish never moves the stamp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_work_reports_a_scans_own_share_and_never_goes_negative() {
|
||||
let before = CacheWork { hits: 10, lookup_ns: 500, ..CacheWork::default() };
|
||||
let after = CacheWork { hits: 25, lookup_ns: 900, ..CacheWork::default() };
|
||||
let mine = after.since(before);
|
||||
assert_eq!(mine.hits, 15);
|
||||
assert_eq!(mine.lookup_ns, 400);
|
||||
// A counter that somehow went backwards saturates rather than wrapping
|
||||
// into a nonsense number the tracker would then quote.
|
||||
assert_eq!(before.since(after).hits, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_line_names_its_scan_and_is_one_line() {
|
||||
let mut trace = ScanTrace::new(true);
|
||||
trace.kind = "whole";
|
||||
trace.number = 2;
|
||||
trace.read = 124;
|
||||
for line in [trace.stage_line(), trace.count_line(), trace.memory_line()] {
|
||||
assert!(line.starts_with("scan 2 "), "{line}");
|
||||
assert!(!line.contains('\n'), "a timing line is one line: {line}");
|
||||
assert!(line.contains("(whole, 124 files)") || line.contains("(whole)"), "{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ impl Server {
|
||||
}],
|
||||
};
|
||||
let id = self.send_request(WorkspaceConfiguration::METHOD, params);
|
||||
self.pending.insert(id, Pending::Configuration);
|
||||
self.pending.insert(id, Pending::Configuration(std::time::Instant::now()));
|
||||
}
|
||||
|
||||
/// Ask the client to watch the source files and the filelist for us,
|
||||
@@ -174,7 +174,7 @@ impl Server {
|
||||
pub(super) fn response(&mut self, response: Response) {
|
||||
match self.pending.remove(&response.id) {
|
||||
Some(Pending::ApplyEdit(command)) => self.applied(command, response),
|
||||
Some(Pending::Configuration) => self.configured(response),
|
||||
Some(Pending::Configuration(asked)) => self.configured(asked, response),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
@@ -211,7 +211,8 @@ impl Server {
|
||||
/// string) means the same thing: the client has no settings for us, which
|
||||
/// is the defaults. Nothing here is worth a popup — the user did not ask
|
||||
/// for this request and cannot act on its failure.
|
||||
fn configured(&mut self, response: Response) {
|
||||
fn configured(&mut self, asked: std::time::Instant, response: Response) {
|
||||
self.timed(self.timer().map(|_| asked), |took| format!("configuration answered in {took}"));
|
||||
let answered = response.response_result.unwrap_or(Value::Null);
|
||||
let section = answered.get(0).cloned().unwrap_or(Value::Null);
|
||||
self.apply_settings(settings::from_section(§ion));
|
||||
@@ -271,6 +272,12 @@ impl Server {
|
||||
self.verbose.then(std::time::Instant::now)
|
||||
}
|
||||
|
||||
/// How long this server has been alive, in milliseconds — the clock every
|
||||
/// startup number is read against.
|
||||
pub(super) fn since_start(&self) -> f64 {
|
||||
self.born.elapsed().as_secs_f64() * 1_000.0
|
||||
}
|
||||
|
||||
/// One timing line for work that was being timed — and nothing at all,
|
||||
/// closure included, for work that was not.
|
||||
pub(super) fn timed(
|
||||
@@ -297,7 +304,7 @@ impl Server {
|
||||
}
|
||||
|
||||
/// One line for a request the order contract makes wait, naming which of
|
||||
/// [`Server::must_wait`]'s three clauses held it.
|
||||
/// [`Server::must_wait`]'s four clauses held it.
|
||||
///
|
||||
/// The question this answers is the one a slow-looking editor raises:
|
||||
/// "was that request slow, or was it never started?". Silent for anything
|
||||
@@ -308,11 +315,12 @@ impl Server {
|
||||
}
|
||||
let Message::Request(request) = message else { return };
|
||||
self.timing(format!(
|
||||
"{} HELD behind a rescan (answering={}, wanted={}, already held={})",
|
||||
"{} HELD behind a rescan (answering={}, wanted={}, already held={}, staging={})",
|
||||
request.method,
|
||||
self.answering_a_rescan,
|
||||
self.rescan_wanted,
|
||||
self.held.len()
|
||||
self.held.len(),
|
||||
self.staging
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,17 +26,17 @@ use lsp_types::request::{
|
||||
};
|
||||
use lsp_types::{
|
||||
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
|
||||
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,
|
||||
SemanticTokensResult, SignatureHelpParams, TextDocumentPositionParams,
|
||||
TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, Uri,
|
||||
WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult, WorkspaceSymbolParams,
|
||||
WorkspaceSymbolResponse,
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, 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, SemanticTokensResult, SignatureHelpParams,
|
||||
TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams,
|
||||
TypeHierarchySupertypesParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult,
|
||||
WorkspaceSymbolParams, WorkspaceSymbolResponse,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
@@ -246,14 +246,35 @@ impl Server {
|
||||
let uri = p.text_document.uri;
|
||||
let only = p.context.only;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
// A code-action request carries no `tabSize`, so the width a
|
||||
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
|
||||
// or from the built-in default.
|
||||
let tab_width =
|
||||
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
||||
let run = lint::LintRun::for_document(&self.workspace, doc);
|
||||
let mut actions =
|
||||
code_action::code_actions(&run, &uri, doc, p.range, only.as_deref(), tab_width);
|
||||
// A filter naming no kind at all selects nothing: every
|
||||
// `wanted` below is false, so the answer is empty however much
|
||||
// work is done to reach it. Answering here is what keeps a
|
||||
// client that asks for nothing from paying for config
|
||||
// discovery, a lint pass and four selectors (take 5 §P1a).
|
||||
if only.as_deref().is_some_and(<[CodeActionKind]>::is_empty) {
|
||||
return to_value(Vec::<CodeActionOrCommand>::new());
|
||||
}
|
||||
let mut actions: Vec<CodeActionOrCommand> = Vec::new();
|
||||
// Quick fixes and `source.fixAll.lucisv` are the only two
|
||||
// families the lint pass answers for, so a request for neither
|
||||
// — an organize-on-save, a refactor-only menu — does not read
|
||||
// the project's configuration and does not lint.
|
||||
if code_action::wants_fixes(only.as_deref()) {
|
||||
// A code-action request carries no `tabSize`, so the width a
|
||||
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
|
||||
// or from the built-in default.
|
||||
let tab_width =
|
||||
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
||||
let run = lint::LintRun::for_document(&self.workspace, doc);
|
||||
actions.extend(code_action::code_actions(
|
||||
&run,
|
||||
&uri,
|
||||
doc,
|
||||
p.range,
|
||||
only.as_deref(),
|
||||
tab_width,
|
||||
));
|
||||
}
|
||||
// The port refactorings answer for the cursor, not for a range:
|
||||
// the request's start is where the user is.
|
||||
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
||||
@@ -347,7 +368,16 @@ impl Server {
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
match rename::rename(&self.workspace, &uri, offset, &new_name) {
|
||||
// One `timing: rename trace …` line behind `--verbose`, and
|
||||
// nothing at all otherwise: where a rename's selection, its
|
||||
// stages and its whole-file parses went (take 5 §P2a).
|
||||
let mut trace = None;
|
||||
let outcome =
|
||||
rename::rename_traced(&self.workspace, &uri, offset, &new_name, &mut trace);
|
||||
if let (true, Some(line)) = (self.verbose, trace) {
|
||||
self.timing(format!("rename trace {line}"));
|
||||
}
|
||||
match outcome {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
to_value(edit)
|
||||
|
||||
@@ -28,8 +28,10 @@ impl Server {
|
||||
/// or a file the client renamed or deleted.
|
||||
pub(super) fn reindex(&mut self) {
|
||||
// A rescan asked for by a message this scan answered is *this* scan's
|
||||
// successor, not a scan inside it. See `scan_until_settled`.
|
||||
if self.scanning {
|
||||
// successor, not a scan inside it — and one asked for before the
|
||||
// startup scan has begun is that scan itself. See
|
||||
// `scan_until_settled` and [`Server::scan_owed`].
|
||||
if self.scan_owed() {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
@@ -84,8 +86,9 @@ impl Server {
|
||||
// bytes a moment later. One more scan when this one ends is the whole
|
||||
// answer, and it is the same flag every other mid-scan trigger sets.
|
||||
// `true` because the caller's fallback — a whole rebuild, right now —
|
||||
// is exactly what must not happen.
|
||||
if self.scanning {
|
||||
// is exactly what must not happen. Same for the startup's
|
||||
// configuration wait, whose scan reads this file from disk anyway.
|
||||
if self.scan_owed() {
|
||||
self.rescan_wanted = true;
|
||||
return true;
|
||||
}
|
||||
@@ -122,11 +125,17 @@ impl Server {
|
||||
/// sets, and it is what keeps the coalescing rule one rule
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
pub(super) fn reindex_widened(&mut self, added: Vec<std::path::PathBuf>) {
|
||||
if self.scanning {
|
||||
// Before the startup scan has begun there is nothing to widen *into*:
|
||||
// that scan resolves the scope afresh, the buffer this `didOpen` just
|
||||
// installed is already in it, and `open_first` puts the buffer at the
|
||||
// head of its work list. So the widen is folded into the one scan
|
||||
// rather than run as a second one (`server/startup.rs`).
|
||||
if self.scan_owed() {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
let started = self.timer();
|
||||
let since_start = self.since_start();
|
||||
if started.is_some() {
|
||||
// The folders by name: which folder a jump widened into is the one
|
||||
// thing the file log below it does not say in one line.
|
||||
@@ -138,9 +147,10 @@ impl Server {
|
||||
paths.join(", ")
|
||||
));
|
||||
}
|
||||
let verbose = started.is_some();
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan =
|
||||
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
|
||||
self.watching(bar.as_ref(), |ws, watch| ws.begin_widen(&added, watch, verbose));
|
||||
let total = scan.total();
|
||||
// No drain between the files: a widen is a rescan a message asked for,
|
||||
// and `must_wait` would hold every request queued behind it anyway. It
|
||||
@@ -163,6 +173,7 @@ impl Server {
|
||||
plural(total)
|
||||
)
|
||||
});
|
||||
self.say_scan_trace(since_start);
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
self.generation += 1;
|
||||
@@ -208,6 +219,8 @@ impl Server {
|
||||
};
|
||||
self.answering_a_rescan = false;
|
||||
self.scanning = false;
|
||||
// A neighbourhood can only be owed by a scan, and there is none now.
|
||||
self.head_owed = false;
|
||||
warnings
|
||||
}
|
||||
|
||||
@@ -224,8 +237,10 @@ impl Server {
|
||||
// scope and walking it is part of what a scan costs, and a number that
|
||||
// left it out would be the wrong answer to "why was that slow?".
|
||||
let started = self.timer();
|
||||
let since_start = self.since_start();
|
||||
let verbose = started.is_some();
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
|
||||
let mut scan = self.watching(bar.as_ref(), |ws, watch| ws.begin_scan(watch, verbose));
|
||||
let interleave = scan.total() > INTERLEAVE_ABOVE;
|
||||
let total = scan.total();
|
||||
if started.is_some() {
|
||||
@@ -252,9 +267,27 @@ impl Server {
|
||||
plural(total)
|
||||
)
|
||||
});
|
||||
self.say_scan_trace(since_start);
|
||||
warnings
|
||||
}
|
||||
|
||||
/// The three `timing: scan …` lines the startup breakdown is read from —
|
||||
/// stages, counts and the sizes the scan left resident.
|
||||
///
|
||||
/// Silent without `--verbose`, because a scan that was not traced left a
|
||||
/// trace of zeroes and three lines of them would be a lie
|
||||
/// (`docs/features/perf5-p4/README.md` holds the field list).
|
||||
fn say_scan_trace(&mut self, since_start: f64) {
|
||||
let mut trace = self.workspace.take_scan_trace();
|
||||
if !trace.on() {
|
||||
return;
|
||||
}
|
||||
trace.since_start_ms = since_start;
|
||||
self.timing(trace.stage_line());
|
||||
self.timing(trace.count_line());
|
||||
self.timing(trace.memory_line());
|
||||
}
|
||||
|
||||
/// Do one piece of a scan with the progress bar and the per-file log
|
||||
/// watching it.
|
||||
///
|
||||
@@ -291,25 +324,76 @@ impl Server {
|
||||
/// to and no reason to go on scanning, so it stops the scan the same way a
|
||||
/// `shutdown` does.
|
||||
fn answer_what_is_waiting(&mut self, scan: &mut Scan) -> bool {
|
||||
let mut batch = Vec::new();
|
||||
// Nothing may be answered off a prefix that does not yet hold the
|
||||
// folder the user is working in: a definition into the file next door
|
||||
// would be `[]` (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
self.head_owed = !scan.neighbourhood_indexed();
|
||||
let mut batch = self.waiting_for_this_scan();
|
||||
while let Ok(message) = self.queue.try_recv() {
|
||||
batch.push(message);
|
||||
}
|
||||
if batch.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let opened = opened_in(&batch);
|
||||
// A `didOpen` in this burst names a folder the work list has not been
|
||||
// ordered around yet, so the requests behind it in the burst are owed
|
||||
// that ordering before they are answered — which is exactly what the
|
||||
// widen this `didOpen` used to trigger made them wait for. The flag is
|
||||
// set *before* the batch is applied, so `must_wait` holds them; it is
|
||||
// recomputed below once the new head segment is known.
|
||||
let opened = !opened_in(&batch).is_empty();
|
||||
self.head_owed |= opened;
|
||||
self.workspace.publish_scan(scan);
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
// The file the user has just opened is the one they are looking at, so
|
||||
// it is indexed next rather than when the alphabet reaches it — the
|
||||
// open-first rule, for a file opened after the work list was taken.
|
||||
for path in opened {
|
||||
scan.index_next(&path);
|
||||
// The files the user has just opened, and the folders around them, are
|
||||
// what they are looking at, so they are indexed next rather than when
|
||||
// the alphabet reaches them — the open-first rule, for buffers opened
|
||||
// after the work list was taken.
|
||||
if opened {
|
||||
self.workspace.open_next(scan);
|
||||
self.head_owed = !scan.neighbourhood_indexed();
|
||||
}
|
||||
self.stopped
|
||||
}
|
||||
|
||||
/// What the startup's configuration wait set aside, when this scan is the
|
||||
/// one those messages were waiting for.
|
||||
///
|
||||
/// **Not an exemption from the order contract — the other side of it.** A
|
||||
/// request that arrives before the startup scan has begun is held for the
|
||||
/// same reason one arriving *during* it is answered: there is no index at
|
||||
/// all to answer it from, and the scan it is waiting for is the server's
|
||||
/// own startup, with nothing queued ahead of it and — being the session's
|
||||
/// first — an empty `gone` set. So the startup scan answers it exactly as
|
||||
/// it answers a message that turns up while it runs, off the same
|
||||
/// published prefix.
|
||||
///
|
||||
/// A scan a **message** asked for takes nothing: its held messages are
|
||||
/// queued behind the message that asked for it, and answering them off a
|
||||
/// half-updated index is precisely the trade
|
||||
/// `docs/features/scan-interleave/README.md`'s decision 2 refuses. Same
|
||||
/// for a scan with a further rescan already wanted — the requests behind
|
||||
/// that ask are owed its effect.
|
||||
///
|
||||
/// **And not at the very first file.** A prefix holding the user's own
|
||||
/// buffer and nothing else answers a definition in the file next door with
|
||||
/// `[]` — coherent, and useless, which is what §P4b2 measured
|
||||
/// (`docs/features/perf5-p4/README.md`). So the startup scan takes what it
|
||||
/// was handed once it has stepped the user's whole neighbourhood
|
||||
/// ([`Server::head_owed`], from [`Scan::neighbourhood_indexed`]); the
|
||||
/// `publish_scan` in [`Server::answer_what_is_waiting`] is what then makes
|
||||
/// that neighbourhood answerable, in the same call. A scan with no
|
||||
/// neighbourhood — nothing open, or a folder covering the workspace — says
|
||||
/// so with `head` 0 and drains at the first file exactly as before.
|
||||
/// Requests arriving *after* that are answered at every interleave point,
|
||||
/// as they always were.
|
||||
fn waiting_for_this_scan(&mut self) -> Vec<lsp_server::Message> {
|
||||
if self.answering_a_rescan || self.rescan_wanted || self.head_owed {
|
||||
return Vec::new();
|
||||
}
|
||||
std::mem::take(&mut self.held)
|
||||
}
|
||||
|
||||
/// Publish a new completed hierarchy revision after any index mutation.
|
||||
pub(super) fn hierarchy_index_changed(&mut self) {
|
||||
self.hierarchy_revision = self.hierarchy_revision.saturating_add(1);
|
||||
|
||||
@@ -44,10 +44,9 @@ use lsp_server::{Connection, Message, RequestId};
|
||||
use lsp_types::notification::{Cancel, Notification as _};
|
||||
use lsp_types::{SemanticToken, Uri};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Workspace;
|
||||
|
||||
use batch::{burst, cancelled_in, cancelled_response, forward};
|
||||
use batch::{burst, cancelled_in, cancelled_response};
|
||||
|
||||
mod batch;
|
||||
mod client;
|
||||
@@ -59,6 +58,7 @@ mod large_file;
|
||||
mod notification;
|
||||
mod progress;
|
||||
mod semantic_tokens;
|
||||
mod startup;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -192,6 +192,24 @@ pub struct Server {
|
||||
/// another one, and this is what turns that into the flag below rather
|
||||
/// than a scan inside a scan.
|
||||
scanning: bool,
|
||||
/// Whether the startup scan is still *owed* — the window between the
|
||||
/// `workspace/configuration` request that opens a session and the answer
|
||||
/// that decides the scope its one scan runs at
|
||||
/// (`server/startup.rs`). Nothing has been indexed yet, so a rescan
|
||||
/// trigger in this window is folded into the scan that is about to run
|
||||
/// rather than run as a scan of its own, and every request waits for it —
|
||||
/// there is nothing to answer one from. Never true again after
|
||||
/// construction.
|
||||
staging: bool,
|
||||
/// Whether the scan now running still owes the user's own neighbourhood —
|
||||
/// their open buffers and the folders those raise to, which
|
||||
/// [`crate::scan_order`] puts at the head of its work list. Until it has
|
||||
/// been indexed there is nothing worth answering a request off: the prefix
|
||||
/// holds the alphabet rather than what the user is looking at, and §P4b2
|
||||
/// measured what that answers, which is `[]`
|
||||
/// (`docs/features/perf5-p4/README.md`). False whenever no scan is
|
||||
/// running, and false during a scan with no neighbourhood to wait for.
|
||||
head_owed: bool,
|
||||
/// A rescan asked for while a scan was running. Coalesced: any number of
|
||||
/// requests is one more scan when this one ends, whatever asked for them.
|
||||
rescan_wanted: bool,
|
||||
@@ -214,6 +232,11 @@ pub struct Server {
|
||||
/// costs is the branch that reads this field — see
|
||||
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
|
||||
verbose: bool,
|
||||
/// When this server was built — the moment after `initialize`/`initialized`
|
||||
/// that `main` hands control over. Every startup number is measured from
|
||||
/// here, so a scan's line can say how much of the wait came before it
|
||||
/// (`docs/features/perf5-p4/README.md`).
|
||||
born: std::time::Instant,
|
||||
}
|
||||
|
||||
/// How long a burst of `didChange` notifications may sit unanalyzed once the
|
||||
@@ -252,8 +275,9 @@ enum Pending {
|
||||
/// A `workspace/applyEdit`, remembering the command that asked for it so
|
||||
/// a refusal can be named to the user.
|
||||
ApplyEdit(String),
|
||||
/// A `workspace/configuration` asking for the `lucisv` section.
|
||||
Configuration,
|
||||
/// A `workspace/configuration` asking for the `lucisv` section, and when
|
||||
/// it was asked — the config round trip is part of what a startup costs.
|
||||
Configuration(std::time::Instant),
|
||||
}
|
||||
|
||||
/// One semantic-token answer, kept so the next delta request can be answered
|
||||
@@ -264,136 +288,6 @@ struct TokenAnswer {
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// The server, with its first index built.
|
||||
///
|
||||
/// The startup scan runs at the **default** settings — including the
|
||||
/// folder scope — because neither settings door can deliver anything
|
||||
/// before `initialized`; a client whose `lucisv.index.scope` differs pays
|
||||
/// one extra rescan when its settings land, exactly as `lucisv.exclude`
|
||||
/// has always cost one.
|
||||
pub fn new(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
) -> Server {
|
||||
Server::started(
|
||||
connection,
|
||||
roots,
|
||||
abilities,
|
||||
ClientSettings::default(),
|
||||
storage,
|
||||
verbose,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Server::new`] with a client's settings already in hand — the seam the
|
||||
/// tests start a session from. Only a test has any settings this early:
|
||||
/// one whose subject is not the scope says so here rather than driving a
|
||||
/// `didChangeConfiguration` and then reasoning about the extra rescan it
|
||||
/// buys.
|
||||
///
|
||||
/// `queued` is what the client had already sent when the server was built
|
||||
/// — the opening burst, put straight onto the queue the startup scan
|
||||
/// drains. Empty for [`Server::new`]; a test fills it because racing the
|
||||
/// forwarder thread for it would make the test a coin toss rather than a
|
||||
/// check.
|
||||
fn started(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
client: ClientSettings,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
queued: Vec<Message>,
|
||||
) -> Server {
|
||||
// Started before the first scan, not in `run`: the scan below answers
|
||||
// whatever the client has already sent, and it can only do that off a
|
||||
// queue that is already being filled.
|
||||
let (forwarded, queue) = forward(&connection);
|
||||
for message in queued {
|
||||
let _ = forwarded.send(message);
|
||||
}
|
||||
let mut server = Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
lint_config_problems: std::cell::RefCell::default(),
|
||||
said_lint_names: Vec::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
registrations: 0,
|
||||
request_ids: 0,
|
||||
pending: HashMap::new(),
|
||||
generation: 0,
|
||||
hierarchy_revision: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
queue,
|
||||
scanning: false,
|
||||
rescan_wanted: false,
|
||||
answering_a_rescan: false,
|
||||
stopped: false,
|
||||
held: Vec::new(),
|
||||
verbose,
|
||||
};
|
||||
// Nothing has been built yet, so there is no rebuild to owe: the
|
||||
// `true` this returns for a non-default `client` is the rebuild that
|
||||
// is about to happen anyway.
|
||||
let _ = server.workspace.set_client_settings(client);
|
||||
// Before the first build, because it is one rung of the ladder that
|
||||
// decides where that build reads its cache from
|
||||
// (`docs/features/index-persistence/README.md`).
|
||||
server.workspace.set_storage_path(storage);
|
||||
// The earliest legal moment for anything server-initiated: `main`
|
||||
// builds this only after `initialize_finish`, which returns once the
|
||||
// client's `initialized` notification has arrived — and consumes it,
|
||||
// so the loop below never sees one to hang these off instead. The
|
||||
// first index build is the slowest one of the session, so it gets the
|
||||
// same bar every later rescan gets.
|
||||
//
|
||||
// And it answers messages while it runs, which is what stops the first
|
||||
// request of a session waiting out the whole scan
|
||||
// (`docs/features/scan-interleave/README.md`). Everything below it is
|
||||
// therefore reached with the client's opening burst already handled —
|
||||
// and skipped altogether if that burst shut the server down.
|
||||
server.workspace.adopt_roots(roots);
|
||||
let warnings = server.scan_until_settled(false);
|
||||
if server.stopped {
|
||||
return server;
|
||||
}
|
||||
server.hierarchy_index_changed();
|
||||
// A buffer can now be *opened* during the startup scan, and what was
|
||||
// published for it then was computed against a half-built index. This
|
||||
// is the same debt a rescan pays at the end of `reindex`, owed here
|
||||
// for the first time because before this round no buffer could exist
|
||||
// at this point. Nothing at all is sent when nothing is open, which is
|
||||
// every session whose client did not get a `didOpen` in edgeways.
|
||||
if !server.workspace.open_uris().is_empty() {
|
||||
server.refresh_code_lenses();
|
||||
server.generation += 1;
|
||||
for uri in server.workspace.open_uris() {
|
||||
server.publish(&uri);
|
||||
}
|
||||
}
|
||||
server.report_scope(warnings);
|
||||
server.register_watchers();
|
||||
// The pull half of the settings model. Asked here because this is the
|
||||
// same moment the watchers are registered — the earliest legal one —
|
||||
// and answered later, in the loop: the settings therefore arrive
|
||||
// *after* the first index build, exactly as a pushed
|
||||
// `didChangeConfiguration` always has (it cannot arrive before
|
||||
// `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist`
|
||||
// costs one extra rescan when it lands; nothing is stale in between,
|
||||
// it is simply the default scope until the client answers.
|
||||
server.request_configuration();
|
||||
server
|
||||
}
|
||||
|
||||
/// Receive until the client shuts us down or the channel closes.
|
||||
///
|
||||
/// One blocking receive, then everything already queued behind it, then
|
||||
@@ -528,7 +422,7 @@ impl Server {
|
||||
/// setting or an added workspace folder before a go-to-definition. Those
|
||||
/// four ask for a rescan, and "applied" for them means the rescan has
|
||||
/// **run**: one message at a time, the server would have finished it
|
||||
/// before ever taking the request. Three clauses, one rule:
|
||||
/// before ever taking the request. Four clauses, one rule:
|
||||
///
|
||||
/// * `answering_a_rescan` — this scan is one a message asked for, so
|
||||
/// every request that arrives while it runs arrived *after* that
|
||||
@@ -536,7 +430,19 @@ impl Server {
|
||||
/// * `rescan_wanted` — a message in this very burst has just asked for
|
||||
/// one, and the requests behind it in the burst are owed the same;
|
||||
/// * `held` — a request is already waiting, and answering a newer one
|
||||
/// ahead of it would reorder them just as badly.
|
||||
/// ahead of it would reorder them just as badly;
|
||||
/// * `staging` — the startup scan has not begun, because the settings
|
||||
/// that decide its scope are still in flight. There is no index at all
|
||||
/// to answer from, so a request waits for that scan — and is answered
|
||||
/// *inside* it, mid-way, exactly as one arriving while it runs is
|
||||
/// ([`Server::waiting_for_this_scan`]);
|
||||
/// * `head_owed` — the scan running has not yet reached the end of the
|
||||
/// user's own folder. There *is* an index, but the part of it a request
|
||||
/// is asking about is the part not built yet, and answering off the
|
||||
/// alphabet's prefix returns `[]` rather than an answer. A request
|
||||
/// behind a `didOpen` is owed that `didOpen`'s effect on the scan
|
||||
/// order, which is the same rule the other four state
|
||||
/// ([`Server::head_owed`]).
|
||||
///
|
||||
/// What is left answered mid-scan is exactly what is queued behind
|
||||
/// *nothing*: the opening burst of a session, whose scan is the server's
|
||||
@@ -544,7 +450,23 @@ impl Server {
|
||||
/// the round is about, and it is the one a user feels
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
fn must_wait(&self) -> bool {
|
||||
self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty()
|
||||
self.answering_a_rescan
|
||||
|| self.rescan_wanted
|
||||
|| !self.held.is_empty()
|
||||
|| self.staging
|
||||
|| self.head_owed
|
||||
}
|
||||
|
||||
/// Whether a scan is running or already owed — the two states in which a
|
||||
/// rescan trigger records that one more scan is wanted instead of running
|
||||
/// one itself.
|
||||
///
|
||||
/// The second is the startup's configuration wait (`server/startup.rs`):
|
||||
/// the scan it is waiting for has not begun, and when it does it will
|
||||
/// resolve the scope afresh and read every file in it, so anything asked
|
||||
/// for now is satisfied by it.
|
||||
fn scan_owed(&self) -> bool {
|
||||
self.scanning || self.staging
|
||||
}
|
||||
|
||||
/// Whether the installed index covers the whole scope with no indexing
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
//! What a session does before its message loop: ask the client for its
|
||||
//! settings, wait a bounded moment for the answer, and run **one** startup
|
||||
//! scan at the scope that answer decided.
|
||||
//!
|
||||
//! Before 2026-09-08 the order was the other way round — scan at the
|
||||
//! defaults, then ask — and a client whose `lucisv.index.scope` differs from
|
||||
//! the default folder scope (which is every VS Code session that sets one)
|
||||
//! paid a whole second scan when the answer landed. With no buffer open the
|
||||
//! first of those scans indexes **zero files**, so what it bought was the
|
||||
//! round-trip wait and nothing else; §P4b then made it cost 0.15 ms instead
|
||||
//! of 181 ms, which turned the head start it had accidentally been giving the
|
||||
//! opening `didOpen` into a genuine race and made the first useful answer of
|
||||
//! a warm session bimodal. Staging removes the scan rather than the race:
|
||||
//! there is one scan, it runs at the settings the client actually wants, and
|
||||
//! the opening burst is answered *inside* it exactly as
|
||||
//! `docs/features/scan-interleave/README.md` has always answered the startup
|
||||
//! scan's own arrivals.
|
||||
//!
|
||||
//! The bound below is what a client that advertised
|
||||
//! `workspace/configuration` and then never answers costs: after it, the scan
|
||||
//! runs at the defaults exactly as it used to, and an answer that turns up
|
||||
//! afterwards is an ordinary settings change with an ordinary rescan behind
|
||||
//! it. See `docs/features/perf5-p4/README.md` §P4b2 and
|
||||
//! `docs/features/folders-and-config/README.md`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lsp_server::{Connection, Message};
|
||||
|
||||
use super::batch::{burst, forward};
|
||||
use super::{ClientAbilities, Pending, Server};
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Workspace;
|
||||
|
||||
/// How long a startup waits for the client's `workspace/configuration`
|
||||
/// answer before scanning at the defaults.
|
||||
///
|
||||
/// **Not a budget — a bound on a client that never answers.** The round trip
|
||||
/// itself is single-digit milliseconds: §P4a measured the whole of it,
|
||||
/// including the empty scan that used to run in front of it, at 27–85 ms, and
|
||||
/// with that scan gone what is left is the client's own reply. Two seconds is
|
||||
/// therefore two orders of magnitude of slack for a slow client, and still
|
||||
/// short enough that a client which advertised the capability and then says
|
||||
/// nothing does not leave a workspace unindexed.
|
||||
pub(super) const CONFIGURATION_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Everything a session starts with that is not the connection or the roots.
|
||||
///
|
||||
/// One struct rather than six more parameters: `started` is the seam every
|
||||
/// test starts a session from, and the two fields only a test ever sets
|
||||
/// ([`Startup::queued`] and [`Startup::wait`]) would otherwise be positional
|
||||
/// arguments nobody can read at the call site.
|
||||
pub(super) struct Startup {
|
||||
/// What the client said it can do, read once at `initialize`.
|
||||
pub(super) abilities: ClientAbilities,
|
||||
/// Settings already in hand. Only a test has any this early: one whose
|
||||
/// subject is not the scope says so here rather than driving a
|
||||
/// `didChangeConfiguration` and then reasoning about the extra rescan it
|
||||
/// buys.
|
||||
pub(super) client: ClientSettings,
|
||||
/// `initializationOptions.storagePath` — where the persistent index cache
|
||||
/// goes.
|
||||
pub(super) storage: Option<std::path::PathBuf>,
|
||||
/// `--verbose`: whether every operation says how long it took.
|
||||
pub(super) verbose: bool,
|
||||
/// What the client had already sent when the server was built — the
|
||||
/// opening burst, put straight onto the queue the wait and the startup
|
||||
/// scan drain. Empty for [`Server::new`]; a test fills it because racing
|
||||
/// the forwarder thread for it would make the test a coin toss rather
|
||||
/// than a check.
|
||||
pub(super) queued: Vec<Message>,
|
||||
/// How long to wait for the settings answer before scanning at the
|
||||
/// defaults. [`CONFIGURATION_WAIT`] in a real session; a test says what
|
||||
/// it means to test, and `Duration::ZERO` is the client that never
|
||||
/// answers.
|
||||
pub(super) wait: Duration,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// The server, with its first index built.
|
||||
///
|
||||
/// The startup scan runs at the settings the client answered a
|
||||
/// `workspace/configuration` with — asked first thing and waited for, up
|
||||
/// to [`CONFIGURATION_WAIT`]. A client that cannot be asked, or that does
|
||||
/// not answer inside the bound, gets the scan at the **defaults**
|
||||
/// (including the folder scope) exactly as every client did before
|
||||
/// 2026-09-08, and pays one extra rescan if its settings land later.
|
||||
pub fn new(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
) -> Server {
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: ClientSettings::default(),
|
||||
storage,
|
||||
verbose,
|
||||
queued: Vec::new(),
|
||||
wait: CONFIGURATION_WAIT,
|
||||
};
|
||||
Server::started(connection, roots, startup)
|
||||
}
|
||||
|
||||
/// A server that owns nothing yet: no index, no settings, no roots — only
|
||||
/// its connection, what the client can do, and the queue its messages are
|
||||
/// already arriving on.
|
||||
///
|
||||
/// The forwarder starts here rather than in `run` because both the
|
||||
/// settings wait and the startup scan answer whatever the client has
|
||||
/// already sent, and they can only do that off a queue that is already
|
||||
/// being filled. `queued` is what a test says the client had sent by then.
|
||||
fn empty(
|
||||
connection: Connection,
|
||||
abilities: ClientAbilities,
|
||||
verbose: bool,
|
||||
queued: Vec<Message>,
|
||||
) -> Server {
|
||||
let (forwarded, queue) = forward(&connection);
|
||||
for message in queued {
|
||||
let _ = forwarded.send(message);
|
||||
}
|
||||
Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
lint_config_problems: std::cell::RefCell::default(),
|
||||
said_lint_names: Vec::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
registrations: 0,
|
||||
request_ids: 0,
|
||||
pending: HashMap::new(),
|
||||
generation: 0,
|
||||
hierarchy_revision: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
queue,
|
||||
scanning: false,
|
||||
head_owed: false,
|
||||
staging: false,
|
||||
rescan_wanted: false,
|
||||
answering_a_rescan: false,
|
||||
stopped: false,
|
||||
held: Vec::new(),
|
||||
verbose,
|
||||
born: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Server::new`] with everything spelled out — the seam the tests start
|
||||
/// a session from.
|
||||
pub(super) fn started(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
startup: Startup,
|
||||
) -> Server {
|
||||
let Startup { abilities, client, storage, verbose, queued, wait } = startup;
|
||||
let mut server = Server::empty(connection, abilities, verbose, queued);
|
||||
// Nothing has been built yet, so there is no rebuild to owe: the
|
||||
// `true` this returns for a non-default `client` is the rebuild that
|
||||
// is about to happen anyway.
|
||||
let _ = server.workspace.set_client_settings(client);
|
||||
// Before the first build, because it is one rung of the ladder that
|
||||
// decides where that build reads its cache from
|
||||
// (`docs/features/index-persistence/README.md`).
|
||||
server.workspace.set_storage_path(storage);
|
||||
server.workspace.adopt_roots(roots);
|
||||
// The earliest legal moment for anything server-initiated: `main`
|
||||
// builds this only after `initialize_finish`, which returns once the
|
||||
// client's `initialized` notification has arrived — and consumes it,
|
||||
// so the loop below never sees one to hang these off instead.
|
||||
server.stage_for_configuration(wait);
|
||||
if server.stopped {
|
||||
return server;
|
||||
}
|
||||
// The first index build is the slowest one of the session, so it gets
|
||||
// the same bar every later rescan gets. And it answers messages while
|
||||
// it runs — the ones the wait above set aside included — which is what
|
||||
// stops the first request of a session waiting out the whole scan
|
||||
// (`docs/features/scan-interleave/README.md`). Everything below it is
|
||||
// therefore reached with the client's opening burst already handled —
|
||||
// and skipped altogether if that burst shut the server down.
|
||||
let warnings = server.scan_until_settled(false);
|
||||
if server.stopped {
|
||||
return server;
|
||||
}
|
||||
server.hierarchy_index_changed();
|
||||
// A buffer can be *opened* before or during the startup scan, and what
|
||||
// was published for it then was computed against a half-built index.
|
||||
// This is the same debt a rescan pays at the end of `reindex`, owed
|
||||
// here for the first time because before scan-interleave no buffer
|
||||
// could exist at this point. Nothing at all is sent when nothing is
|
||||
// open, which is every session whose client did not get a `didOpen`
|
||||
// in edgeways.
|
||||
if !server.workspace.open_uris().is_empty() {
|
||||
server.refresh_code_lenses();
|
||||
server.generation += 1;
|
||||
for uri in server.workspace.open_uris() {
|
||||
server.publish(&uri);
|
||||
}
|
||||
}
|
||||
server.report_scope(warnings);
|
||||
server.register_watchers();
|
||||
server
|
||||
}
|
||||
|
||||
/// Ask the client for its settings and hold everything until they arrive,
|
||||
/// so the one startup scan runs at the scope the client actually wants.
|
||||
///
|
||||
/// Silent for a client that never advertised `workspace/configuration`:
|
||||
/// that one is only ever *pushed* settings, so there is nothing to wait
|
||||
/// for and the scan runs at the defaults immediately, byte for byte as it
|
||||
/// always has.
|
||||
///
|
||||
/// [`Server::staging`] is what makes the window safe. While it is set,
|
||||
/// every rescan trigger a message pulls — a `didOpen` that widened the
|
||||
/// scope, a pushed setting, a save — records that one more scan is wanted
|
||||
/// instead of running one, and [`Server::must_wait`] holds every request.
|
||||
/// Clearing `rescan_wanted` afterwards is not dropping those asks: the
|
||||
/// scan about to run is the session's **first**, it resolves the scope
|
||||
/// afresh and reads every file in it from disk, and it runs at the
|
||||
/// settings that have just landed — so it is what every one of them was
|
||||
/// asking for.
|
||||
fn stage_for_configuration(&mut self, wait: Duration) {
|
||||
if !self.abilities.configuration {
|
||||
return;
|
||||
}
|
||||
self.staging = true;
|
||||
self.request_configuration();
|
||||
self.await_configuration(wait);
|
||||
self.staging = false;
|
||||
self.rescan_wanted = false;
|
||||
}
|
||||
|
||||
/// Read the client's messages until it answers the settings pull, the
|
||||
/// bound runs out, or it goes away.
|
||||
///
|
||||
/// **The bound is observed on the receive itself.** `recv_timeout` with
|
||||
/// whatever is left of it blocks in the transport, wakes on the next
|
||||
/// message, and returns `Timeout` at the deadline — so there is no poll,
|
||||
/// no busy-wait and no clock the loop has to be woken to read. A client
|
||||
/// that answers late is not stranded: its answer arrives in `run` as an
|
||||
/// ordinary `Message::Response`, goes through the same `configured` →
|
||||
/// `apply_settings` it always did, and costs the one rescan a settings
|
||||
/// change has always cost — under the order contract, held requests and
|
||||
/// all.
|
||||
fn await_configuration(&mut self, wait: Duration) {
|
||||
if wait.is_zero() {
|
||||
return;
|
||||
}
|
||||
let asked = Instant::now();
|
||||
while self.pending.values().any(|p| matches!(p, Pending::Configuration(_))) {
|
||||
let Some(left) = wait.checked_sub(asked.elapsed()) else { return };
|
||||
let Ok(message) = self.queue.recv_timeout(left) else { return };
|
||||
let batch = burst(&self.queue, message);
|
||||
// A `shutdown` in the burst has already been through
|
||||
// `handle_shutdown` by the time this returns `Ok(true)`;
|
||||
// `started` then returns without scanning at all.
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
if self.stopped {
|
||||
return;
|
||||
}
|
||||
self.take_the_answer_out_of_held();
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a settings answer that a held request took down with it.
|
||||
///
|
||||
/// **Measured, not theorised** (2026-09-08): without this, one warm
|
||||
/// session in three waited the whole two-second bound and then rescanned,
|
||||
/// because `process_batch` moves *everything behind* a request that must
|
||||
/// wait into `held` — the rule that keeps a burst's arrival order intact
|
||||
/// across the wait — and the client's answer to the pull can be in that
|
||||
/// burst behind the editor's opening `textDocument/definition`. Left
|
||||
/// there, the loop above sees the pull still outstanding and blocks until
|
||||
/// the bound, which is the opposite of what staging is for.
|
||||
///
|
||||
/// Reordering it is sound because that rule is about the **client's**
|
||||
/// message stream. The answer to a request the *server* sent is not part
|
||||
/// of it: the client replies to a pull from wherever it handles
|
||||
/// server-initiated requests, and no ordering promise ties that reply to a
|
||||
/// request the editor happened to send at the same moment. Only a
|
||||
/// `Pending::Configuration` answer is taken — everything else in `held`,
|
||||
/// requests included, keeps its place and its order.
|
||||
fn take_the_answer_out_of_held(&mut self) {
|
||||
let waiting = std::mem::take(&mut self.held);
|
||||
let mut answers = Vec::new();
|
||||
for message in waiting {
|
||||
match message {
|
||||
Message::Response(response)
|
||||
if matches!(
|
||||
self.pending.get(&response.id),
|
||||
Some(Pending::Configuration(_))
|
||||
) =>
|
||||
{
|
||||
answers.push(response);
|
||||
}
|
||||
kept => self.held.push(kept),
|
||||
}
|
||||
}
|
||||
for answer in answers {
|
||||
self.response(answer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
//! What a `textDocument/codeAction` request does, and — just as much — what
|
||||
//! it no longer does.
|
||||
//!
|
||||
//! Take 5 §P1 (`docs/features/perf5-p1/README.md`) removed work from this
|
||||
//! path: an empty `context.only` answers before the configuration is read, the
|
||||
//! lint pass runs only when a fix family is asked for, the fence answer is
|
||||
//! computed only when a fix exists and only once per document revision, and
|
||||
//! the four refactoring selectors read the buffer's own parse instead of
|
||||
//! parsing its text again. Every one of those is asserted here **by counting
|
||||
//! parses**, not by timing them: `vlog_parser::stats::parses()` is a
|
||||
//! thread-local count and a request is answered on this thread.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A module with a tab in it — one `no-tabs` finding, carrying a Safe fix —
|
||||
/// an instantiation of `sub`, so the port and inline families have something
|
||||
/// to look at, and a comment line where nothing at all is offered.
|
||||
///
|
||||
/// Line 1 is the tab, line 2 the instantiation, line 3 the comment.
|
||||
const FIXABLE: &str = "module m;\n\twire a;\n sub u_sub (.a(a));\n // nothing here\nendmodule\n";
|
||||
|
||||
/// The declaration `FIXABLE` instantiates.
|
||||
const SUB: &str = "module sub (\n input logic a,\n input logic b\n);\nendmodule\n";
|
||||
|
||||
/// A finding with **no** fix: `module-filename` does not offer to rename a
|
||||
/// file. So a lint pass over this buffer produces a violation, and nothing
|
||||
/// that a fence could protect.
|
||||
const UNFIXABLE: &str = "module other;\nendmodule\n";
|
||||
|
||||
/// A zero-width range at a position — the shape an editor sends on a cursor
|
||||
/// move.
|
||||
fn cursor(uri: &Uri, line: u32, character: u32) -> Value {
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": line, "character": character },
|
||||
"end": { "line": line, "character": character },
|
||||
},
|
||||
"context": { "diagnostics": [] },
|
||||
})
|
||||
}
|
||||
|
||||
/// `cursor`, with a `context.only` filter.
|
||||
fn filtered(uri: &Uri, line: u32, character: u32, only: &[&str]) -> Value {
|
||||
let mut params = cursor(uri, line, character);
|
||||
params["context"]["only"] = serde_json::json!(only);
|
||||
params
|
||||
}
|
||||
|
||||
/// The whole-file parses one request performed.
|
||||
fn parses_during(session: &mut Session, params: Value) -> (u64, Value) {
|
||||
let before = vlog_parser::stats::parses();
|
||||
let result = session.result(CodeActionRequest::METHOD, params);
|
||||
(vlog_parser::stats::parses() - before, result)
|
||||
}
|
||||
|
||||
/// The titles an answer carries, in the order it carries them.
|
||||
fn titles(result: &Value) -> Vec<String> {
|
||||
result
|
||||
.as_array()
|
||||
.expect("an action list")
|
||||
.iter()
|
||||
.map(|action| action["title"].as_str().unwrap_or_default().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The kinds an answer carries, in order.
|
||||
fn kinds(result: &Value) -> Vec<String> {
|
||||
result
|
||||
.as_array()
|
||||
.expect("an action list")
|
||||
.iter()
|
||||
.map(|action| action["kind"].as_str().unwrap_or_default().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A session over a tree holding `m.sv` and `sub.sv`, with `m.sv` open.
|
||||
fn opened(tree: &Tree, text: &str) -> (Session, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
session.drain();
|
||||
(session, uri)
|
||||
}
|
||||
|
||||
/// [`opened`] against a client that can `codeAction/resolve` — the shape that
|
||||
/// is *offered* actions without their edits, which is the path §P1c changed.
|
||||
fn opened_lazily(tree: &Tree, text: &str) -> (Session, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
session.drain();
|
||||
(session, uri)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// §P1a — the work a filtered request no longer does
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_empty_only_filter_answers_empty_and_does_no_work_at_all() {
|
||||
let tree = Tree::new("caempty");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &[]));
|
||||
assert_eq!(result, serde_json::json!([]), "no kind is selected, so no action is");
|
||||
assert_eq!(
|
||||
parses, 0,
|
||||
"an empty filter reads no configuration, lints nothing and parses nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refactor_only_request_never_runs_the_lint_pass() {
|
||||
let tree = Tree::new("carefactor");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// The buffer has a fixable finding, so a lint pass here would ask for the
|
||||
// fence regions — a whole-file parse of its own. One parse means exactly
|
||||
// one selector ran and the lint pass did not.
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &["refactor.extract"]));
|
||||
assert_eq!(parses, 0, "the selector reads the buffer's own parse (§P1b): {result:#?}");
|
||||
assert!(
|
||||
!titles(&result).iter().any(|title| title.contains("no-tabs")),
|
||||
"and no quick fix is offered: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quickfix_only_request_never_runs_the_selectors() {
|
||||
let tree = Tree::new("caquickfix");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert_eq!(parses, 1, "the fence parse alone — no selector ran: {result:#?}");
|
||||
assert_eq!(
|
||||
titles(&result),
|
||||
vec!["lucisv: use spaces, not tabs [no-tabs]".to_string()],
|
||||
"{result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_whose_findings_carry_no_fix_never_asks_about_fences() {
|
||||
let tree = Tree::new("canofix");
|
||||
let (mut session, uri) = opened(&tree, UNFIXABLE);
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 0, 0, &["quickfix"]));
|
||||
assert_eq!(result, serde_json::json!([]), "the finding has no fix to offer");
|
||||
assert_eq!(parses, 0, "and nothing to protect, so no fence parse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kind_filter_is_a_prefix_and_still_selects_the_whole_family() {
|
||||
let tree = Tree::new("caprefix");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// `source` selects `source.fixAll.lucisv`, which is a fix family: the
|
||||
// lint pass must run for it.
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["source"]));
|
||||
assert_eq!(kinds(&result), vec!["source.fixAll.lucisv".to_string()], "{result:#?}");
|
||||
// `refactor` selects every refactoring family and no fix family.
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 2, &["refactor"]));
|
||||
assert!(
|
||||
kinds(&result).iter().all(|kind| kind.starts_with("refactor")),
|
||||
"no fix family under a refactor filter: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfiltered_request_keeps_the_order_quick_fixes_fix_all_then_refactorings() {
|
||||
let tree = Tree::new("caorder");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// The cursor is on the tabbed line, so the quick fix is offered, and the
|
||||
// buffer's one instantiation puts a refactoring family behind it.
|
||||
let result = session.result(CodeActionRequest::METHOD, cursor(&uri, 1, 1));
|
||||
let kinds = kinds(&result);
|
||||
assert_eq!(kinds.first().map(String::as_str), Some("quickfix"), "{result:#?}");
|
||||
assert_eq!(kinds.get(1).map(String::as_str), Some("source.fixAll.lucisv"), "{result:#?}");
|
||||
// Everything after the two fix families is a refactoring, and there is at
|
||||
// least one — an answer of two actions would prove nothing about order.
|
||||
assert!(kinds.len() > 2, "a refactoring is offered here too: {result:#?}");
|
||||
assert!(
|
||||
kinds[2..].iter().all(|kind| kind.starts_with("refactor")),
|
||||
"the refactoring families come last: {kinds:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fix_spanning_the_cursor_is_still_offered() {
|
||||
let tree = Tree::new("caspan");
|
||||
// A trailing-whitespace finding whose span starts before the cursor and
|
||||
// ends after it: the cursor is *inside* the fix, not at its start.
|
||||
let (mut session, uri) = opened(&tree, "module m;\n wire a; \nendmodule\n");
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 10, &["quickfix"]));
|
||||
assert!(
|
||||
titles(&result).iter().any(|title| title.contains("no-trailing-whitespace")),
|
||||
"{result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_with_no_selection_is_still_offered_the_extraction() {
|
||||
let tree = Tree::new("cacursor");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// A zero-width range on a whole item: extraction takes the item the
|
||||
// cursor is in, so an empty selection must not disable it.
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 2, &["refactor"]));
|
||||
assert!(
|
||||
kinds(&result).iter().any(|kind| kind == "refactor.extract"),
|
||||
"an empty range still extracts: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// §P1b — the work a repeated request no longer does
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_repeated_offer_where_nothing_is_offered_parses_nothing_at_all() {
|
||||
let tree = Tree::new("carepeat");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// The comment line: every family is asked, and every family answers
|
||||
// nothing, so the four gates are the whole of the work. This is the
|
||||
// pinmux-comment cursor of take 5's headline row, in miniature.
|
||||
let (first, expected) = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
assert!(first <= 1, "the first request pays for the fence answer at most: {first}");
|
||||
// Every request after it, on the same revision, parses nothing: the four
|
||||
// selectors read `doc.tree` and the fence answer is the one already made.
|
||||
for round in 0..3 {
|
||||
let (parses, again) = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
assert_eq!(parses, 0, "round {round} re-parsed the buffer");
|
||||
assert_eq!(again, expected, "round {round} answered differently");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gate_only_families_parse_nothing_even_where_they_do_offer() {
|
||||
let tree = Tree::new("carepeatgate");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// Extraction and inlining are answered by their gate alone — the offer
|
||||
// carries a command, not an edit, so no engine runs. On the
|
||||
// instantiation both of them offer, and neither parses.
|
||||
let only = &["refactor.extract", "refactor.inline"];
|
||||
let (_, first) = parses_during(&mut session, filtered(&uri, 2, 2, only));
|
||||
assert_eq!(kinds(&first).len(), 2, "both families offer here: {first:#?}");
|
||||
for round in 0..3 {
|
||||
let (parses, again) = parses_during(&mut session, filtered(&uri, 2, 2, only));
|
||||
assert_eq!(parses, 0, "round {round}");
|
||||
assert_eq!(again, first, "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_port_offer_reads_the_declaring_file_once_and_nothing_else() {
|
||||
let tree = Tree::new("carepeatports");
|
||||
let (mut session, uri) = opened_lazily(&tree, FIXABLE);
|
||||
// §P1b gave the port family its *gate* for free, but a gate that said yes
|
||||
// still handed the engine one or two files and paid for four verified
|
||||
// plans whose edits were thrown away — 21.15 ms of a 21.83 ms request on
|
||||
// opentitan. §P1c replaced that with a predicate that reads the buffer's
|
||||
// own parse and, at most, one parse of the instantiated module's
|
||||
// declaring file. This assertion is what would notice a second one
|
||||
// reappearing.
|
||||
let only = &["refactor.rewrite.lucisv.ports"];
|
||||
let (_, first) = parses_during(&mut session, filtered(&uri, 2, 2, only));
|
||||
assert!(!kinds(&first).is_empty(), "the port family offers here: {first:#?}");
|
||||
for round in 0..3 {
|
||||
let (parses, again) = parses_during(&mut session, filtered(&uri, 2, 2, only));
|
||||
assert_eq!(parses, 1, "round {round}: `sub.sv`'s parse, and no other (§P1c)");
|
||||
assert_eq!(again, first, "round {round}: and the same menu every time");
|
||||
}
|
||||
// The buffer's *own* parse is not among them: the gate was answered from
|
||||
// `doc.tree`, and so is everything the predicate asks of the buffer.
|
||||
let (gate_only, _) = parses_during(&mut session, filtered(&uri, 3, 2, only));
|
||||
assert_eq!(gate_only, 0, "at a cursor the gate refuses, nothing is parsed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_organize_imports_offer_never_parses_the_buffer_it_is_offered_on() {
|
||||
let tree = Tree::new("caimports");
|
||||
tree.write("a_pkg.sv", "package a_pkg;\n localparam int A = 1;\nendpackage\n");
|
||||
tree.write("b_pkg.sv", "package b_pkg;\n localparam int B = 2;\nendpackage\n");
|
||||
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(
|
||||
&tree.path.join("user.sv"),
|
||||
"module user;\n import b_pkg::*;\n import a_pkg::*;\n logic q;\n assign q = A;\nendmodule\n",
|
||||
);
|
||||
session.drain();
|
||||
let only = &["source.organizeImports"];
|
||||
let (_, first) = parses_during(&mut session, filtered(&uri, 1, 2, only));
|
||||
assert_eq!(
|
||||
titles(&first),
|
||||
vec!["lucisv: organize imports (removes 1, sorts 1)".to_string()],
|
||||
"the unused import goes and the used one is written back: {first:#?}"
|
||||
);
|
||||
// The buffer's own parse, analysis and token stream are the `Document`'s,
|
||||
// and no splice is verified for a menu (§P1c). What is left is one
|
||||
// `Scope::build` — the index that decides which import supplies a used
|
||||
// name — over the buffer and the two packages it imports: **3** parses,
|
||||
// where verifying the splice used to build a second index over the same
|
||||
// three and re-analyze them. The buffer's own share of that index is the
|
||||
// residue §P1c names and does not remove.
|
||||
for round in 0..3 {
|
||||
let (parses, again) = parses_during(&mut session, filtered(&uri, 1, 2, only));
|
||||
assert_eq!(parses, 3, "round {round}: one index over the buffer and its two packages");
|
||||
assert_eq!(again, first, "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_offer_the_fan_out_refuses_says_so_on_resolve_rather_than_crashing() {
|
||||
let tree = Tree::new("caresolvegone");
|
||||
tree.write("sub.sv", SUB);
|
||||
// `sub`'s one instantiation connects by position, which makes the removal
|
||||
// refuse whole — but it lives in a file the *offer* never reads, since an
|
||||
// offer reads the buffer and the module's declaration and nothing else
|
||||
// (`docs/features/lazy-code-action/README.md`). So the lightbulb appears
|
||||
// and the click declines: the contract §P1c inherited and did not widen.
|
||||
tree.write(
|
||||
"other.sv",
|
||||
"module other;\n logic x;\n logic y;\n sub u_pos (x, y);\nendmodule\n",
|
||||
);
|
||||
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("sub.sv"), SUB);
|
||||
session.drain();
|
||||
|
||||
let only = &["refactor.rewrite.lucisv.ports"];
|
||||
let offered = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 14, only));
|
||||
let titles = titles(&offered);
|
||||
assert_eq!(
|
||||
titles,
|
||||
vec!["lucisv: remove port `b` (updates 1 instantiation)".to_string()],
|
||||
"the offer is made, counted from the index: {offered:#?}"
|
||||
);
|
||||
let action = offered.as_array().and_then(|list| list.first()).expect("the offer").clone();
|
||||
assert!(action.get("edit").is_none(), "a lazy offer carries no edit: {action:#?}");
|
||||
|
||||
let refused = session.request(CodeActionResolveRequest::METHOD, action);
|
||||
let error = refused.response_result.expect_err("the fan-out refuses this removal");
|
||||
assert_eq!(error.message, "lucisv: the action is no longer available.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_filter_parses_nothing_however_often_it_is_asked() {
|
||||
let tree = Tree::new("carepeatempty");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
for round in 0..4 {
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 2, 2, &[]));
|
||||
assert_eq!(parses, 0, "round {round}");
|
||||
assert_eq!(result, serde_json::json!([]), "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_offer_after_a_change_parses_the_buffer_once_and_no_more() {
|
||||
let tree = Tree::new("cachange");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
let _ = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
// A `didChange` is flushed by the request behind it, so the parse
|
||||
// `Document::new` makes is counted inside this request — one parse, plus
|
||||
// the fence answer, and nothing from the four selectors.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": format!("{FIXABLE}// changed\n") }],
|
||||
}),
|
||||
);
|
||||
let (parses, _) = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
assert!(parses <= 2, "the document's own parse, plus at most the fence answer: {parses}");
|
||||
// And the request after that one is free again.
|
||||
let (parses, _) = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
assert_eq!(parses, 0, "the new revision is reused like any other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_typed_into_the_buffer_is_seen_by_the_next_request() {
|
||||
let tree = Tree::new("cafence");
|
||||
// A tab on line 1: a `no-tabs` finding with a Safe fix, offered as a
|
||||
// quick fix.
|
||||
let (mut session, uri) = opened(&tree, "module m;\n\twire a;\nendmodule\n");
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert_eq!(titles(&result).len(), 1, "the fix is offered: {result:#?}");
|
||||
// Now fence that line. The memo is held on the `Document`, and a change
|
||||
// builds a new one — so the answer must be the new text's, not the old
|
||||
// text's.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{
|
||||
"text": "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\nendmodule\n",
|
||||
}],
|
||||
}),
|
||||
);
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 1, &["quickfix"]));
|
||||
assert!(result.as_array().expect("a list").is_empty(), "fenced: {result:#?}");
|
||||
// And back again: removing the fence restores the fix, which a memo that
|
||||
// outlived its revision could not do.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 3 },
|
||||
"contentChanges": [{ "text": "module m;\n\twire a;\nendmodule\n" }],
|
||||
}),
|
||||
);
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert_eq!(titles(&result).len(), 1, "unfenced again: {result:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_external_waiver_still_keeps_its_fix_out_of_the_offer() {
|
||||
let tree = Tree::new("cawaiver");
|
||||
tree.write("waivers.txt", "no-tabs\n");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\twire a;\nendmodule\n");
|
||||
session.drain();
|
||||
// Without the waiver configured the fix is there.
|
||||
let before = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert_eq!(titles(&before).len(), 1, "{before:#?}");
|
||||
// A `lucisv.toml` written between requests changes the pass, and the
|
||||
// configuration is read per request — nothing about it is memoized.
|
||||
tree.write("lucisv.toml", "[lint]\nignore = [\"no-tabs\"]\n");
|
||||
let after = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert!(after.as_array().expect("a list").is_empty(), "the new config is read: {after:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untitled_buffer_is_offered_the_fix_families_and_no_refactoring() {
|
||||
let tree = Tree::new("cauntitled");
|
||||
tree.write("sub.sv", SUB);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
|
||||
session.notify(
|
||||
DidOpenTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": FIXABLE,
|
||||
}
|
||||
}),
|
||||
);
|
||||
session.drain();
|
||||
let result = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
assert!(
|
||||
!kinds(&result).iter().any(|kind| kind == "refactor.extract"),
|
||||
"an untitled buffer has no directory to extract into: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_with_crlf_endings_and_an_astral_character_offers_the_same_actions() {
|
||||
let tree = Tree::new("cacrlf");
|
||||
let lf = "// \u{1F600}\nmodule m;\n sub u_sub (.a(1));\nendmodule\n";
|
||||
let (mut session, uri) = opened(&tree, lf);
|
||||
// Line 2, character 2 is inside the instantiation in both encodings; the
|
||||
// comment above it puts a non-BMP character in front of every offset, so
|
||||
// the UTF-16 conversion is doing real work.
|
||||
let plain = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": lf.replace('\n', "\r\n") }],
|
||||
}),
|
||||
);
|
||||
let windows = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
assert_eq!(titles(&plain), titles(&windows), "{plain:#?}\n{windows:#?}");
|
||||
assert_eq!(kinds(&plain), kinds(&windows));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_parse_offers_what_it_always_offered() {
|
||||
let tree = Tree::new("cabroken");
|
||||
let (mut session, uri) =
|
||||
opened(&tree, "module m;\n sub u_sub (.a(1));\n logic ;;; w\nendmodule\n");
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 6, &["refactor"]));
|
||||
// The three gates that refuse over parse diagnostics still refuse; the
|
||||
// port family, which never had that check, still answers.
|
||||
assert!(
|
||||
!kinds(&result).iter().any(|kind| kind == "refactor.extract" || kind == "refactor.inline"),
|
||||
"a broken parse offers no extraction and no inline: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_refresh_does_not_change_what_the_cursor_offers() {
|
||||
let tree = Tree::new("careindex");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
let before = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
// A saved file elsewhere rebuilds the index; the buffer is untouched, so
|
||||
// its own parse — and its fence answer — stay exactly as they were.
|
||||
tree.write("other.sv", "module other_one;\nendmodule\n");
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
session.drain();
|
||||
let after = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
assert_eq!(titles(&before), titles(&after), "{before:#?}\n{after:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_buffer_still_answers_its_command_from_its_text() {
|
||||
// The large-file fast path installs the analysis of the *empty* file, so
|
||||
// a `doc.tree` reader would find nothing in a large buffer. The four
|
||||
// selectors therefore keep their text form there — which is exactly what
|
||||
// they did before §P1b, and this pins it.
|
||||
//
|
||||
// `textDocument/codeAction` cannot show it: the fast path answers that
|
||||
// method with an empty list before the dispatch is entered
|
||||
// (`server/large_file.rs`). `workspace/executeCommand` is not gated, and
|
||||
// is where a large buffer really does reach a selector.
|
||||
let tree = Tree::new("calarge");
|
||||
tree.write("sub.sv", SUB);
|
||||
let mut body = String::from("module big;\n logic a;\n sub u_sub (.a(a), .b(a));\n");
|
||||
for i in 0..20 {
|
||||
body.push_str(&format!(" logic pad{i};\n"));
|
||||
}
|
||||
body.push_str("endmodule\n");
|
||||
assert!(body.len() > 100, "the premise: over the test threshold");
|
||||
let settings = crate::settings::ClientSettings {
|
||||
large_file_threshold: 100,
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
};
|
||||
let mut session =
|
||||
Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings);
|
||||
let path = tree.path.join("big.sv");
|
||||
std::fs::write(&path, &body).expect("write");
|
||||
let uri = session.open(&path, &body);
|
||||
session.drain();
|
||||
let response = session.request(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({
|
||||
"command": crate::inline_module::INLINE_MODULE,
|
||||
"arguments": [uri, { "line": 2, "character": 2 }],
|
||||
}),
|
||||
);
|
||||
let refusal = match response.response_result {
|
||||
Ok(_) => None,
|
||||
Err(error) => Some(error.message),
|
||||
};
|
||||
assert_ne!(
|
||||
refusal.as_deref(),
|
||||
Some("there is no module instantiation at this position to inline."),
|
||||
"a large buffer's selector reads its text, so the instantiation is found"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Topology handshake 33: the file that reaches an instance through modules
|
||||
//! it does not itself instantiate.
|
||||
//!
|
||||
//! `tb.sv` writes `u_wrapper.u_top.u_sub.s`. It instantiates `wrapper`;
|
||||
//! `wrapper` instantiates `top`; `top` is where `sub u_sub (…)` is written and
|
||||
//! where the inline happens. None of `module_sources`' four rungs asks for
|
||||
//! `tb.sv` — it declares neither `sub` nor `top`, refers to neither, and
|
||||
//! instantiates neither — so `inline/mod.rs::no_hierarchy` never saw the path
|
||||
//! and the inline was **silently accepted**, dissolving a scope a testbench
|
||||
//! walks through. §53.2's QA reproduced exactly this.
|
||||
//!
|
||||
//! `module_select`'s fifth rung is the fix and this file is its pin: the
|
||||
//! ladder, the deeper ladder, the shapes the rung must **not** walk, and the
|
||||
//! callers whose answers must not move.
|
||||
|
||||
use super::*;
|
||||
use crate::module_select::Reach;
|
||||
use crate::state::Workspace;
|
||||
|
||||
const SUB: &str = "\
|
||||
module sub (
|
||||
input logic a,
|
||||
output logic q
|
||||
);
|
||||
logic s;
|
||||
assign s = a;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
sub u_sub (
|
||||
.a(x),
|
||||
.q(z)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
const WRAPPER: &str = "\
|
||||
module wrapper (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
top u_top (
|
||||
.x(x),
|
||||
.z(z)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// The instantiation of `sub` in `top.sv`: line 4, on the module name.
|
||||
fn inline_cursor() -> Value {
|
||||
serde_json::json!({ "line": 4, "character": 2 })
|
||||
}
|
||||
|
||||
/// A tree holding the three-level ladder, with `tb.sv` written by the caller
|
||||
/// so each test can say what the bench does.
|
||||
fn ladder(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
tree.write("wrapper.sv", WRAPPER);
|
||||
tree
|
||||
}
|
||||
|
||||
/// A wide session with `top.sv` open, ready to be asked to inline.
|
||||
fn opened(tree: &Tree) -> (Session, Uri) {
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
session.drain();
|
||||
(session, uri)
|
||||
}
|
||||
|
||||
/// Run `lucisv.inlineModule` at the `sub` instantiation; `Err` is the
|
||||
/// engine's own sentence.
|
||||
fn inline(session: &mut Session, uri: &Uri) -> Result<Value, String> {
|
||||
let response = session.request(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({
|
||||
"command": crate::inline_module::INLINE_MODULE,
|
||||
"arguments": [uri, inline_cursor()],
|
||||
}),
|
||||
);
|
||||
response.response_result.map_err(|error| error.message)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bench_two_levels_above_the_instance_refuses_the_inline() {
|
||||
let tree = ladder("h33ladder");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("the bench names the instance");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
assert!(refusal.contains("tb.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bench_three_levels_above_the_instance_refuses_the_inline() {
|
||||
let tree = ladder("h33deep");
|
||||
tree.write(
|
||||
"outer.sv",
|
||||
"module outer (\n input logic x,\n output logic z\n);\n\
|
||||
\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n outer u_outer (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_outer.u_wrapper.u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("three levels up is still the same scope");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
assert!(refusal.contains("tb.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_level_the_four_rungs_already_saw_still_refuses() {
|
||||
// `wrapper.sv` instantiates `top` directly, so it was always in the set.
|
||||
// The fifth rung must not change what the fourth already answered.
|
||||
let tree = ladder("h33direct");
|
||||
tree.write(
|
||||
"wrapper.sv",
|
||||
"module wrapper (\n input logic x,\n output logic z\n);\n\
|
||||
\n top u_top (.x(x), .z(z));\n logic peek;\n assign peek = u_top.u_sub.s;\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("the direct parent names the instance");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
assert!(refusal.contains("wrapper.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ladder_nobody_reaches_into_still_inlines() {
|
||||
// The rung selects more files; selecting them must not invent a refusal.
|
||||
let tree = ladder("h33clean");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let edit = inline(&mut session, &uri).expect("nothing names the instance");
|
||||
assert!(edit.is_object() || edit.is_null(), "{edit:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_scope_two_levels_above_is_refused_and_stays_refused() {
|
||||
let tree = ladder("h33generate");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_wrapper.gen[0].u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("a generated path walks the same scope");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_two_levels_above_the_instance_refuses_the_inline() {
|
||||
let tree = ladder("h33bind");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
tree.write(
|
||||
"sva.sv",
|
||||
"module checker_m (input logic a);\nendmodule\n\
|
||||
\nbind tb.u_wrapper.u_top.u_sub checker_m u_chk (.a(1'b0));\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("a bind names the instance as a scope");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
assert!(refusal.contains("sva.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_bench_that_adds_the_path_refuses_the_inline() {
|
||||
// The bench on disk names nothing; the buffer does. Open buffers are a
|
||||
// rung of their own, and this pins that the fifth rung did not displace
|
||||
// it.
|
||||
let tree = ladder("h33unsaved");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
session.open(
|
||||
&tree.path.join("tb.sv"),
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
session.drain();
|
||||
let refusal = inline(&mut session, &uri).expect_err("the unsaved text names the instance");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_declaration_of_the_inlined_module_still_refuses_for_being_ambiguous() {
|
||||
let tree = ladder("h33duplicate");
|
||||
tree.write("sub_again.sv", SUB);
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("two `sub`s is ambiguous");
|
||||
assert!(refusal.contains("sub"), "{refusal}");
|
||||
assert!(
|
||||
!refusal.contains("named as a scope of the design hierarchy"),
|
||||
"the ambiguity refusal, not the hierarchy one: {refusal}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_hiding_the_path_selects_the_file_and_still_does_not_refuse() {
|
||||
// Today's behaviour, pinned rather than asserted to be right. The fifth
|
||||
// rung *does* hand `tb.sv` over — `words::harvest` splits raw text, so
|
||||
// `u_sub` written inside a `` `define`` body is in the file's census. But
|
||||
// `no_hierarchy` tokenizes, and a directive line is one opaque token, so
|
||||
// there is no `Ident` spelling `u_sub` for it to find. The selection is
|
||||
// not the limit here; the lexical refusal is. The whole-workspace engine
|
||||
// answers exactly the same way, which is the parity that matters.
|
||||
let tree = ladder("h33macro");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"`define PEEK u_wrapper.u_top.u_sub.s\n\
|
||||
module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", `PEEK);\nendmodule\n",
|
||||
);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let selected = crate::module_select::hierarchical_users(ws.index(), Reach { scopes: &scopes });
|
||||
assert!(selected.contains(&tree.path.join("tb.sv")), "the census sees raw text: {selected:?}");
|
||||
let (mut session, uri) = opened(&tree);
|
||||
inline(&mut session, &uri).expect("a macro-hidden path is not a token `no_hierarchy` can see");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rung_is_the_instances_word_census_and_nothing_wider() {
|
||||
// A package, an interface and a class are not scopes an inline dissolves,
|
||||
// and the rung is keyed by the instance's spelling alone — so a caller
|
||||
// that names one of them by mistake selects only the files that really
|
||||
// do write that word.
|
||||
let tree = Tree::new("h33units");
|
||||
tree.write("p.sv", "package p;\n localparam K = 1;\nendpackage\n");
|
||||
tree.write("user.sv", "module user;\n import p::*;\n logic a;\nendmodule\n");
|
||||
tree.write("stranger.sv", "module stranger;\n logic b;\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let scopes = ["p".to_string()];
|
||||
let found = crate::module_select::hierarchical_users(ws.index(), Reach { scopes: &scopes });
|
||||
assert_eq!(
|
||||
found,
|
||||
[tree.path.join("p.sv"), tree.path.join("user.sv")].into_iter().collect(),
|
||||
"{found:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selected_set_answers_the_inline_exactly_as_the_whole_workspace_does() {
|
||||
// The claim the fifth rung is worth having: `no_hierarchy` refuses from a
|
||||
// token census, and the rung *is* that census, so the narrowed set and
|
||||
// `sources()` cannot disagree. Six shapes, each run through the engine
|
||||
// twice — the one the four rungs missed, the one they saw, the bind, the
|
||||
// generated path, the macro-hidden path, and the clean ladder.
|
||||
let benches = [
|
||||
("h33p1", " initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\n", ""),
|
||||
("h33p2", "", ""),
|
||||
("h33p3", "", "module chk (input logic a);\nendmodule\nbind tb.u_wrapper.u_top.u_sub chk u_chk (.a(1'b0));\n"),
|
||||
("h33p4", " initial $display(\"%b\", u_wrapper.gen[0].u_top.u_sub.s);\n", ""),
|
||||
("h33p5", " initial $display(\"%b\", `PEEK);\n", ""),
|
||||
("h33p6", " initial $display(\"%b\", u_wrapper.u_top.z);\n", ""),
|
||||
];
|
||||
for (name, extra, sva) in benches {
|
||||
let tree = ladder(name);
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
&format!(
|
||||
"`define PEEK u_wrapper.u_top.u_sub.s\n\
|
||||
module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n{extra}endmodule\n"
|
||||
),
|
||||
);
|
||||
if !sva.is_empty() {
|
||||
tree.write("sva.sv", sva);
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let path = tree.path.join("top.sv");
|
||||
let offset = TOP.find("sub u_sub").expect("the instantiation") as u32;
|
||||
let units = ["sub".to_string(), "top".to_string()];
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let narrowed = ws.module_sources_reaching(&path, &units, Reach { scopes: &scopes });
|
||||
let whole = ws.sources();
|
||||
assert_eq!(
|
||||
vlog_refactor::inline_module(&narrowed, &path, offset).map(|edit| edit.edits),
|
||||
vlog_refactor::inline_module(&whole, &path, offset).map(|edit| edit.edits),
|
||||
"{name}: the narrowed set and the whole workspace disagree"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_four_rung_selector_answers_exactly_what_it_did_before() {
|
||||
// Every other caller of `module_sources` — the port actions, extract —
|
||||
// asks with no reach, and the fifth rung must therefore be invisible to
|
||||
// them. Asserted as an equality against the rungs' own answer rather
|
||||
// than as a count, so a file appearing is a failure whatever its name.
|
||||
let tree = ladder("h33unchanged");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let units = ["sub".to_string(), "top".to_string()];
|
||||
let path = tree.path.join("top.sv");
|
||||
let four: Vec<PathBuf> =
|
||||
ws.module_sources(&path, &units).into_iter().map(|(path, _)| path).collect();
|
||||
assert_eq!(
|
||||
four,
|
||||
vec![tree.path.join("sub.sv"), tree.path.join("top.sv"), tree.path.join("wrapper.sv")],
|
||||
"the four rungs, unchanged — and `tb.sv` is exactly what they miss"
|
||||
);
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let five: Vec<PathBuf> = ws
|
||||
.module_sources_reaching(&path, &units, Reach { scopes: &scopes })
|
||||
.into_iter()
|
||||
.map(|(path, _)| path)
|
||||
.collect();
|
||||
assert!(five.contains(&tree.path.join("tb.sv")), "{five:?}");
|
||||
for path in &four {
|
||||
assert!(five.contains(path), "the fifth rung only ever adds: {path:?} went missing");
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
use std::time::Duration;
|
||||
|
||||
use lsp_server::{Notification, Request, Response};
|
||||
use lsp_types::notification::{
|
||||
@@ -19,16 +20,16 @@ use lsp_types::notification::{
|
||||
PublishDiagnostics, ShowMessage,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeLensRefresh, CodeLensRequest,
|
||||
Completion, DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
|
||||
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
|
||||
GotoTypeDefinition, HoverRequest, InlayHintRequest, InlineCompletionRequest,
|
||||
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
|
||||
RegisterCapability, Rename, Request as _, SelectionRangeRequest,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
|
||||
ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, UnregisterCapability,
|
||||
WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceConfiguration,
|
||||
WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeActionResolveRequest,
|
||||
CodeLensRefresh, CodeLensRequest, Completion, DocumentDiagnosticRequest,
|
||||
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
|
||||
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, HoverRequest,
|
||||
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
|
||||
PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
|
||||
SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest,
|
||||
SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare,
|
||||
UnregisterCapability, WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate,
|
||||
WorkspaceConfiguration, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
DidChangeWatchedFilesParams, FileChangeType, FileEvent, LogMessageParams, MessageType,
|
||||
@@ -39,22 +40,28 @@ use serde_json::Value;
|
||||
|
||||
use super::batch::{is_shutdown, widen_of, Widen};
|
||||
use super::progress::{reports, MAX_REPORTS};
|
||||
use super::startup::{Startup, CONFIGURATION_WAIT};
|
||||
use super::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::uri::path_to_uri;
|
||||
use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
|
||||
|
||||
mod apply_edit;
|
||||
mod cancel;
|
||||
mod code_action;
|
||||
mod file_ops;
|
||||
mod folders;
|
||||
mod formatting;
|
||||
mod hierarchy_reach;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod scan_trace;
|
||||
mod settings;
|
||||
mod startup;
|
||||
mod sync;
|
||||
mod tokens;
|
||||
mod watchers;
|
||||
@@ -85,7 +92,11 @@ impl Tree {
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
std::fs::write(self.path.join(rel), text).expect("write");
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("parent");
|
||||
}
|
||||
std::fs::write(&path, text).expect("write");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,8 +168,21 @@ impl Session {
|
||||
// this module counts the messages a session produces, and the
|
||||
// timing lines are tested where they are observable as protocol
|
||||
// traffic — `tests/e2e.rs`, against the real binary and its flag.
|
||||
let server =
|
||||
Server::started(server_end, roots, abilities, settings, storage, false, Vec::new());
|
||||
//
|
||||
// `wait: ZERO` is the client that never answers the settings pull:
|
||||
// the request goes out and the startup scan runs at what this
|
||||
// harness already put in `settings`, which is what every session in
|
||||
// this module was before the startup was staged. The staging itself
|
||||
// is tested in `startup.rs`, where the answer is queued.
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: settings,
|
||||
storage,
|
||||
verbose: false,
|
||||
queued: Vec::new(),
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
let server = Server::started(server_end, roots, startup);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
@@ -185,7 +209,64 @@ impl Session {
|
||||
for message in on_the_wire {
|
||||
client.sender.send(message).expect("the client's wire traffic");
|
||||
}
|
||||
let server = Server::started(server_end, roots, abilities, settings, None, false, queued);
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: settings,
|
||||
storage: None,
|
||||
verbose: false,
|
||||
queued,
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
let server = Server::started(server_end, roots, startup);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
/// A session whose startup is **staged**: the settings pull goes out
|
||||
/// first and the startup scan waits `wait` for the answer
|
||||
/// (`server/startup.rs`). `queued` is what the client had already sent
|
||||
/// when the server was built — the answer among it, for a client that
|
||||
/// answers.
|
||||
///
|
||||
/// The settings start at the defaults, which is the whole point: what a
|
||||
/// staged session indexes is what the *answer* said, not what a test put
|
||||
/// in ahead of it.
|
||||
fn staged(
|
||||
roots: Vec<PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
verbose: bool,
|
||||
wait: Duration,
|
||||
queued: Vec<Message>,
|
||||
) -> Session {
|
||||
let (server_end, client) = Connection::memory();
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: ClientSettings::default(),
|
||||
storage: None,
|
||||
verbose,
|
||||
queued,
|
||||
wait,
|
||||
};
|
||||
Session { server: Server::started(server_end, roots, startup), client }
|
||||
}
|
||||
|
||||
/// [`Session::wide`] against a client that spawned the server with
|
||||
/// `--verbose` — the only sessions that are ever told what a scan spent
|
||||
/// its time on (`docs/features/perf5-p4/README.md`).
|
||||
fn verbose_wide(roots: Vec<PathBuf>, storage: Option<PathBuf>) -> Session {
|
||||
let wide = ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
};
|
||||
let (server_end, client) = Connection::memory();
|
||||
let startup = Startup {
|
||||
abilities: ClientAbilities::default(),
|
||||
client: wide,
|
||||
storage,
|
||||
verbose: true,
|
||||
queued: Vec::new(),
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
let server = Server::started(server_end, roots, startup);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ fn workspace_of(tag: &str, files: usize) -> Tree {
|
||||
}
|
||||
|
||||
/// A `workspace/symbol` request over the wire, by id.
|
||||
fn symbol_request(id: i32, query: &str) -> Message {
|
||||
pub(super) fn symbol_request(id: i32, query: &str) -> Message {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(id),
|
||||
WorkspaceSymbolRequest::METHOD.to_string(),
|
||||
@@ -28,7 +28,7 @@ fn symbol_request(id: i32, query: &str) -> Message {
|
||||
/// Where the indexing bar's `end` sits among everything the server said,
|
||||
/// and where the response to `id` sits. `None` for either if it never
|
||||
/// came.
|
||||
fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
|
||||
pub(super) fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
|
||||
let ended = messages.iter().position(|message| {
|
||||
matches!(message, Message::Notification(n) if n.method == Progress::METHOD
|
||||
&& n.params["value"]["kind"] == "end")
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
//! What a scan says it spent its time on (`docs/features/perf5-p4/README.md`).
|
||||
//!
|
||||
//! Three claims, one test each: the lines exist only under `--verbose`, the
|
||||
//! counts on them are the work the scan actually did, and the stages add up
|
||||
//! to the scan they describe.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A tree of `files` one-package files.
|
||||
pub(super) fn trace_tree(tag: &str, files: usize) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
for n in 0..files {
|
||||
tree.package(&format!("t{n:03}.sv"), &format!("t{n:03}"));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
/// Every `timing: scan …` line the server has said since the last drain.
|
||||
pub(super) fn scan_lines(session: &Session) -> Vec<String> {
|
||||
session
|
||||
.logged()
|
||||
.into_iter()
|
||||
.filter(|(typ, text)| *typ == MessageType::LOG && is_trace_line(text))
|
||||
.map(|(_, text)| text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a log line is one of a scan's three trace lines — `timing: scan
|
||||
/// <number> …` — rather than the `scan started`/`scan finished` pair the
|
||||
/// verbose-timing feature already had.
|
||||
pub(super) fn is_trace_line(text: &str) -> bool {
|
||||
let Some(rest) = text.strip_prefix("timing: scan ") else { return false };
|
||||
rest.split_whitespace().next().is_some_and(|word| word.parse::<u32>().is_ok())
|
||||
}
|
||||
|
||||
/// The one line of `lines` whose prefix says it is that kind.
|
||||
pub(super) fn line_of(lines: &[String], kind: &str) -> String {
|
||||
lines
|
||||
.iter()
|
||||
.find(|line| line.contains(&format!(" {kind} (")))
|
||||
.unwrap_or_else(|| panic!("no {kind} line among {lines:#?}"))
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The value of `key=` on a `key=value` line, as text.
|
||||
pub(super) fn field<'a>(line: &'a str, key: &str) -> &'a str {
|
||||
let at = line.find(&format!("{key}=")).unwrap_or_else(|| panic!("no {key} on {line}"));
|
||||
let rest = &line[at + key.len() + 1..];
|
||||
rest.split_whitespace().next().unwrap_or("")
|
||||
}
|
||||
|
||||
/// The value of `key=` as a number.
|
||||
fn number(line: &str, key: &str) -> f64 {
|
||||
let text = field(line, key);
|
||||
text.parse().unwrap_or_else(|_| panic!("{key}={text} is not a number on {line}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_flag_a_scan_says_nothing_about_its_stages() {
|
||||
// The shipped state. `Session::wide` is every other test in this module,
|
||||
// and none of them may start seeing three extra log lines per scan.
|
||||
let tree = trace_tree("tracequiet", 12);
|
||||
let session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert!(scan_lines(&session).is_empty(), "verbose is off: {:#?}", session.logged());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flag_makes_a_scan_say_what_it_spent_and_what_it_left() {
|
||||
let tree = trace_tree("traceverbose", 12);
|
||||
let session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let lines = scan_lines(&session);
|
||||
// Three lines, and they name the same scan.
|
||||
let stages = line_of(&lines, "stages");
|
||||
let counts = line_of(&lines, "counts");
|
||||
let memory = line_of(&lines, "memory");
|
||||
for line in [&stages, &counts, &memory] {
|
||||
assert!(line.starts_with("timing: scan 1 "), "{line}");
|
||||
assert!(line.contains("whole"), "the startup scan is a whole scan: {line}");
|
||||
}
|
||||
// The counts are this fixture's, exactly: twelve files walked and read,
|
||||
// none skipped, none open, and no store to hit.
|
||||
assert_eq!(field(&counts, "read"), "12");
|
||||
assert_eq!(field(&counts, "skipped"), "0");
|
||||
assert_eq!(field(&counts, "hits"), "0");
|
||||
assert_eq!(field(&counts, "misses"), "12");
|
||||
assert_eq!(field(&counts, "buffers"), "0");
|
||||
// Twelve files is under `INTERLEAVE_ABOVE`, so the scan is one shot and
|
||||
// nothing is published mid-way.
|
||||
assert_eq!(field(&counts, "publishes"), "0");
|
||||
assert_eq!(field(&stages, "since_start"), field(&stages, "since_start"));
|
||||
// And the index it left is those twelve packages.
|
||||
assert_eq!(field(&memory, "index_files"), "12");
|
||||
assert_eq!(field(&memory, "cache_entries"), "0", "no storage path, so no store");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warm_second_session_reports_every_file_as_a_hit() {
|
||||
// The one claim the whole warm-scan column rests on: `hits` counts
|
||||
// records served for exactly these bytes, and `misses` counts the parses.
|
||||
let tree = trace_tree("tracewarm", 9);
|
||||
let storage = std::env::temp_dir().join(format!("lucisv_trace_store_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
let cold = Session::verbose_wide(vec![tree.path.clone()], Some(storage.clone()));
|
||||
let cold_lines = scan_lines(&cold);
|
||||
let cold_counts = line_of(&cold_lines, "counts");
|
||||
assert_eq!(field(&cold_counts, "hits"), "0");
|
||||
assert_eq!(field(&cold_counts, "misses"), "9");
|
||||
assert_eq!(field(&cold_counts, "records"), "9", "a cold scan writes every record through");
|
||||
drop(cold);
|
||||
|
||||
let warm = Session::verbose_wide(vec![tree.path.clone()], Some(storage.clone()));
|
||||
let warm_lines = scan_lines(&warm);
|
||||
let warm_counts = line_of(&warm_lines, "counts");
|
||||
assert_eq!(field(&warm_counts, "hits"), "9", "the same bytes, so every lookup hits");
|
||||
assert_eq!(field(&warm_counts, "misses"), "0");
|
||||
assert_eq!(field(&warm_counts, "records"), "0", "a hit writes nothing back");
|
||||
let warm_memory = line_of(&warm_lines, "memory");
|
||||
assert_eq!(field(&warm_memory, "cache_entries"), "9");
|
||||
assert!(number(&warm_counts, "decoded_kib") >= 0.0);
|
||||
drop(warm);
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stages_add_up_to_the_scan_they_describe() {
|
||||
// The tolerance claim: what the trace attributes must be most of the scan
|
||||
// and can never be more than all of it. The slack is the loop itself —
|
||||
// the progress callbacks, the per-file word `Vec`, the staging pushes —
|
||||
// which is deliberately unattributed rather than silently folded into a
|
||||
// neighbouring stage.
|
||||
let tree = trace_tree("tracesums", 40);
|
||||
let session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let stages = line_of(&scan_lines(&session), "stages");
|
||||
let total = number(&stages, "total");
|
||||
let named = [
|
||||
"discovery",
|
||||
"order",
|
||||
// Since 2026-09-08 a scan reads a file's text at the step that indexes
|
||||
// it, so what `discovery` used to spend on reading the whole scope is
|
||||
// this stage instead — and a list without it accounts for a fifth of
|
||||
// the scan (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
"read",
|
||||
"cache_open",
|
||||
"lookup",
|
||||
"decode",
|
||||
"parse",
|
||||
"encode",
|
||||
"store_write",
|
||||
"publish_absorb",
|
||||
"publish_candidates",
|
||||
"publish_includes",
|
||||
"publish_overlay",
|
||||
"gone",
|
||||
"absorb",
|
||||
"compact",
|
||||
"candidates",
|
||||
"includes",
|
||||
"overlay",
|
||||
];
|
||||
let sum: f64 = named.iter().map(|key| number(&stages, key)).sum();
|
||||
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
|
||||
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
|
||||
assert!(sum >= total * 0.5, "the stages must account for most of it: {sum} of {total}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_is_a_second_scan_with_its_own_three_lines() {
|
||||
// A session pays for more than one scan — the startup scan runs at the
|
||||
// default settings and whatever the client then says can ask for another
|
||||
// (`docs/features/perf5-p4/README.md`, the two-scan startup). Each gets
|
||||
// its own numbered triple so no reader adds two scans together.
|
||||
let tree = trace_tree("tracerescan", 8);
|
||||
let mut session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let first = scan_lines(&session);
|
||||
assert_eq!(first.len(), 3, "one scan, three lines: {first:#?}");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": {
|
||||
"index": { "scope": "workspace" },
|
||||
"exclude": ["**/t000.sv"],
|
||||
} } }),
|
||||
);
|
||||
let second = scan_lines(&session);
|
||||
assert_eq!(second.len(), 3, "the rescan says the same three things: {second:#?}");
|
||||
for line in &second {
|
||||
assert!(line.starts_with("timing: scan 2 "), "{line}");
|
||||
}
|
||||
let counts = line_of(&second, "counts");
|
||||
assert_eq!(field(&counts, "read"), "7", "the exclusion is one file fewer");
|
||||
}
|
||||
|
||||
/// A `--verbose` session at the **default** settings, against a client that
|
||||
/// cannot be asked for its settings at all — the shape every pre-2026-08-27
|
||||
/// editor starts in, and the one the startup staging leaves untouched
|
||||
/// (`server/startup.rs`). There is nothing to wait for, so the startup scan
|
||||
/// runs immediately at the defaults: with no buffer open its folder scope is
|
||||
/// empty and so is its work list.
|
||||
fn verbose_default(roots: Vec<PathBuf>, storage: Option<PathBuf>) -> Session {
|
||||
let (server_end, client) = Connection::memory();
|
||||
let startup = Startup {
|
||||
abilities: ClientAbilities::default(),
|
||||
client: ClientSettings::default(),
|
||||
storage,
|
||||
verbose: true,
|
||||
queued: Vec::new(),
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
let server = Server::started(server_end, roots, startup);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
/// Ask for `lucisv.index.scope: "workspace"`, which is the rescan the pulled
|
||||
/// configuration asks for in a real session.
|
||||
fn widen_to_the_workspace(session: &mut Session) {
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "index": { "scope": "workspace" } } } }),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_startup_scan_with_no_files_opens_no_store_and_a_warm_rescan_rewrites_none() {
|
||||
// §P4b, both halves, over the real dispatch.
|
||||
//
|
||||
// **(b1)** the startup scan indexes nothing, so it opens nothing: warm it
|
||||
// used to read a 44 MiB store and rewrite it byte-identically, 184 ms of
|
||||
// a 1.33 s start, for a scan with no files in it. **(a)** the configured
|
||||
// rescan behind it hits every record, appends nothing, and so would
|
||||
// rewrite the store it just read into itself — which it no longer does.
|
||||
let tree = trace_tree("traceemptyscan", 9);
|
||||
let storage = std::env::temp_dir().join(format!("lucisv_trace_empty_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
let store = storage.join("index-cache");
|
||||
|
||||
// Cold: scan 1 is empty and touches nothing, scan 2 fills the store.
|
||||
let mut cold = verbose_default(vec![tree.path.clone()], Some(storage.clone()));
|
||||
let first = line_of(&scan_lines(&cold), "counts");
|
||||
assert_eq!(field(&first, "read"), "0", "premise: the startup scan indexes nothing");
|
||||
assert_eq!(field(&first, "opens"), "0", "and so reads no store");
|
||||
assert_eq!(field(&first, "compactions"), "0", "and rewrites none");
|
||||
assert!(!store.exists(), "a scan with no files does not even create one");
|
||||
|
||||
widen_to_the_workspace(&mut cold);
|
||||
let filled = line_of(&scan_lines(&cold), "counts");
|
||||
assert_eq!(field(&filled, "read"), "9", "the configured rescan indexes the tree");
|
||||
assert_eq!(field(&filled, "opens"), "1", "which does open the store");
|
||||
assert_eq!(field(&filled, "records"), "9");
|
||||
assert_eq!(field(&filled, "compactions"), "1", "a session that appended must rewrite");
|
||||
drop(cold);
|
||||
|
||||
let bytes = std::fs::read(&store).expect("a store");
|
||||
let stamp = std::fs::metadata(&store).expect("meta").modified().expect("mtime");
|
||||
|
||||
// Warm: the same two scans, and neither writes a byte — with a buffer
|
||||
// open, which is the shape a real session has. An open buffer is indexed
|
||||
// from its own analysis and writes its record through on every scan, and
|
||||
// that write-through is what would otherwise put a duplicate line in the
|
||||
// store and owe the rewrite back.
|
||||
let mut warm = verbose_default(vec![tree.path.clone()], Some(storage.clone()));
|
||||
let empty = line_of(&scan_lines(&warm), "counts");
|
||||
assert_eq!(field(&empty, "read"), "0");
|
||||
assert_eq!(field(&empty, "opens"), "0", "still no store read for a scan with no files");
|
||||
assert_eq!(field(&empty, "compactions"), "0");
|
||||
|
||||
let opened = tree.path.join("t000.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
warm.open(&opened, &text);
|
||||
let _ = scan_lines(&warm);
|
||||
|
||||
widen_to_the_workspace(&mut warm);
|
||||
let warmed = line_of(&scan_lines(&warm), "counts");
|
||||
assert_eq!(field(&warmed, "hits"), "8", "every file but the buffer came out of the store");
|
||||
assert_eq!(field(&warmed, "buffers"), "1", "premise: the buffer indexes itself");
|
||||
assert_eq!(field(&warmed, "repeats"), "1", "and its record was already in the store");
|
||||
assert_eq!(field(&warmed, "records"), "0", "so nothing was appended");
|
||||
assert_eq!(field(&warmed, "opens"), "1", "the store was read once, not twice");
|
||||
assert_eq!(field(&warmed, "compactions"), "0", "and the rewrite would have been identical");
|
||||
drop(warm);
|
||||
|
||||
assert_eq!(std::fs::read(&store).expect("a store"), bytes, "not one byte of the store moved");
|
||||
assert_eq!(
|
||||
std::fs::metadata(&store).expect("meta").modified().expect("mtime"),
|
||||
stamp,
|
||||
"and the file was not touched at all"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
}
|
||||
@@ -26,12 +26,18 @@ fn a_client_that_can_be_asked_is_asked_for_its_settings_at_startup() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
||||
// `Server::new` calls `register_watchers` and then
|
||||
// `request_configuration`, in that order — this pins it on the actual
|
||||
// wire rather than trusting the call order in the source. Every
|
||||
// outgoing request's id is `lucisv-{n}` off one monotonically
|
||||
// increasing counter, so the numeric suffix *is* the send order.
|
||||
fn the_startup_pull_is_the_first_thing_on_the_wire() {
|
||||
// **Amended 2026-09-08 (§P4b2).** This used to pin the opposite order:
|
||||
// `Server::new` registered the watchers and *then* asked for the
|
||||
// settings, because the startup scan ran in front of both and the
|
||||
// answer could not have changed it. Staging the scan reverses that —
|
||||
// the pull is now the first thing a session sends, because the scan is
|
||||
// waiting on its answer to know which scope to run at
|
||||
// (`server/startup.rs`). The claim the test makes is unchanged in kind:
|
||||
// the order is pinned on the actual wire rather than trusted from the
|
||||
// call order in the source. Every outgoing request's id is `lucisv-{n}`
|
||||
// off one monotonically increasing counter, so the numeric suffix *is*
|
||||
// the send order.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item
|
||||
// ("verify on the wire").
|
||||
let tree = Tree::new("pulloraftwatch");
|
||||
@@ -46,7 +52,8 @@ fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
||||
};
|
||||
let watchers = index_of(RegisterCapability::METHOD);
|
||||
let pull = index_of(WorkspaceConfiguration::METHOD);
|
||||
assert!(watchers < pull, "watcher registration must precede the pull: {sent:#?}");
|
||||
assert_eq!(pull, 0, "the pull precedes everything, watchers included: {sent:#?}");
|
||||
assert!(pull < watchers, "including the watcher registration: {sent:#?}");
|
||||
|
||||
let numeric_suffix = |request: &Request| -> u32 {
|
||||
request
|
||||
@@ -57,9 +64,10 @@ fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("not a lucisv-N id: {:?}", request.id))
|
||||
};
|
||||
assert_eq!(numeric_suffix(&sent[pull]), 0, "and it takes the first id: {sent:#?}");
|
||||
assert!(
|
||||
numeric_suffix(&sent[watchers]) < numeric_suffix(&sent[pull]),
|
||||
"the pull's id must be issued after the watcher registration's: {sent:#?}"
|
||||
numeric_suffix(&sent[pull]) < numeric_suffix(&sent[watchers]),
|
||||
"the watcher registration's id must be issued after the pull's: {sent:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,529 @@
|
||||
//! The staged startup (`server/startup.rs`): the settings pull goes out
|
||||
//! first, the one scan runs at the scope the answer decided, and a client
|
||||
//! that never answers is bounded rather than waited on for ever.
|
||||
//!
|
||||
//! Eight claims, one test each, all on the wire: one scan for a client that
|
||||
//! answers, the bounded fallback and the late answer's ordinary rescan for
|
||||
//! one that does not, a `didOpen` that beats the answer folded into that one
|
||||
//! scan (its own file first in the work list), a request that beats it
|
||||
//! answered *inside* the scan rather than after it, a client that cannot be
|
||||
//! asked at all left exactly as it was, and a settings answer stranded behind
|
||||
//! a held request taken back out of it.
|
||||
//!
|
||||
//! Two of them are §P4b3's (`docs/features/perf5-p4/README.md`): the request
|
||||
//! that beats the answer is answered **from the user's own folder** rather
|
||||
//! than off the alphabet, whichever of the two the `didOpen` and the answer
|
||||
//! arrives first.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use super::scan::{positions, symbol_request};
|
||||
use super::scan_trace::{field, is_trace_line, line_of, trace_tree};
|
||||
use super::*;
|
||||
|
||||
/// A client that answers `workspace/configuration` and is told what a scan
|
||||
/// spent its time on.
|
||||
fn pulling() -> ClientAbilities {
|
||||
ClientAbilities { configuration: true, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A client that also renders the indexing bar, so the mid-scan ordering of
|
||||
/// an answer is observable.
|
||||
fn pulling_with_a_bar() -> ClientAbilities {
|
||||
ClientAbilities { configuration: true, work_done_progress: true, ..Default::default() }
|
||||
}
|
||||
|
||||
/// The client's answer to the startup settings pull.
|
||||
///
|
||||
/// The id is `lucisv-0` because the pull is the **first** request a staged
|
||||
/// session makes of its client: `stage_for_configuration` runs before the
|
||||
/// scan, and therefore before the progress `create`, the watcher
|
||||
/// registration and the lens refresh that used to be issued ahead of it.
|
||||
/// `send_request` numbers off one counter that only ever goes up, so that
|
||||
/// first id is a fact about the order, not a guess.
|
||||
fn configuration_answer(section: Value) -> Message {
|
||||
Message::Response(Response::new_ok(
|
||||
RequestId::from("lucisv-0".to_string()),
|
||||
serde_json::json!([section]),
|
||||
))
|
||||
}
|
||||
|
||||
/// `lucisv.index.scope: "workspace"` — the answer that used to cost a whole
|
||||
/// second scan, plus the per-file log that makes the work list's order
|
||||
/// readable.
|
||||
fn the_whole_workspace() -> Value {
|
||||
serde_json::json!({ "index": { "scope": "workspace", "logFiles": true } })
|
||||
}
|
||||
|
||||
/// A `textDocument/didOpen` over the wire, as the client sends it.
|
||||
fn did_open(path: &Path, text: &str) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
DidOpenTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": {
|
||||
"uri": path_to_uri(path).expect("uri"),
|
||||
"languageId": "systemverilog",
|
||||
"version": 1,
|
||||
"text": text,
|
||||
}
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Every `timing: scan …` trace line among `messages` — [`scan_lines`] over
|
||||
/// a drain that has already happened, because a drain is destructive and
|
||||
/// these tests ask two questions of one session.
|
||||
fn trace_lines(messages: &[Message]) -> Vec<String> {
|
||||
messages
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
let params: LogMessageParams =
|
||||
serde_json::from_value(n.params.clone()).expect("log message params");
|
||||
Some(params.message)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.filter(|text| is_trace_line(text))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every log line, trace lines included — where the per-file `indexing:`
|
||||
/// and `analyzed:` lines are read from.
|
||||
fn log_lines(messages: &[Message]) -> Vec<String> {
|
||||
messages
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
let params: LogMessageParams =
|
||||
serde_json::from_value(n.params.clone()).expect("log message params");
|
||||
Some(params.message)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The methods of the requests the server made, in send order.
|
||||
fn asked(messages: &[Message]) -> Vec<String> {
|
||||
messages
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Request(request) => Some(request.method.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_answers_pays_one_scan_at_the_scope_it_asked_for() {
|
||||
// The whole of the change, in one assertion. Before 2026-09-08 this
|
||||
// session ran **two** scans: an empty one at the default folder scope,
|
||||
// because nothing could be known about the client's settings until the
|
||||
// pull it had not yet been sent came back, and then the configured
|
||||
// rescan behind it. Now the pull goes first and there is one scan.
|
||||
let tree = trace_tree("stagedone", 9);
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![configuration_answer(the_whole_workspace())],
|
||||
);
|
||||
let said = session.drain();
|
||||
let lines = trace_lines(&said);
|
||||
assert_eq!(lines.len(), 3, "one scan, three trace lines: {lines:#?}");
|
||||
for line in &lines {
|
||||
assert!(line.starts_with("timing: scan 1 "), "no second scan ran: {line}");
|
||||
assert!(line.contains("whole"), "and it is the startup scan: {line}");
|
||||
}
|
||||
let counts = line_of(&lines, "counts");
|
||||
assert_eq!(field(&counts, "read"), "9", "the one scan read the configured scope");
|
||||
assert_eq!(session.server.workspace.index().files().len(), 9);
|
||||
|
||||
// And the pull really did go out ahead of everything else the startup
|
||||
// sends — the order the id in `configuration_answer` depends on.
|
||||
let methods = asked(&said);
|
||||
assert_eq!(
|
||||
methods.first().map(String::as_str),
|
||||
Some(WorkspaceConfiguration::METHOD),
|
||||
"the settings pull is the first thing a staged session asks: {methods:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_never_answers_is_bounded_and_then_scanned_at_the_defaults() {
|
||||
// The fallback, and the shipped bound it is measured against. Two
|
||||
// seconds is not a budget — the round trip is single-digit
|
||||
// milliseconds — it is what a client that advertised the capability and
|
||||
// then says nothing costs, once, before the workspace is indexed anyway.
|
||||
assert_eq!(
|
||||
CONFIGURATION_WAIT,
|
||||
Duration::from_secs(2),
|
||||
"the shipped bound, which no test may quietly move"
|
||||
);
|
||||
let tree = trace_tree("stagednever", 9);
|
||||
let bound = Duration::from_millis(120);
|
||||
let began = Instant::now();
|
||||
let mut session = Session::staged(vec![tree.path.clone()], pulling(), true, bound, Vec::new());
|
||||
let waited = began.elapsed();
|
||||
assert!(waited >= bound, "the bound is waited out, not skipped: {waited:?}");
|
||||
|
||||
let said = session.drain();
|
||||
let lines = trace_lines(&said);
|
||||
assert_eq!(lines.len(), 3, "one scan, not none and not two: {lines:#?}");
|
||||
let counts = line_of(&lines, "counts");
|
||||
assert_eq!(
|
||||
field(&counts, "read"),
|
||||
"0",
|
||||
"at the defaults — the folder scope, which with no buffer open is empty"
|
||||
);
|
||||
let (id, _) = {
|
||||
let asked: Vec<&Message> = said
|
||||
.iter()
|
||||
.filter(
|
||||
|m| matches!(m, Message::Request(r) if r.method == WorkspaceConfiguration::METHOD),
|
||||
)
|
||||
.collect();
|
||||
assert_eq!(asked.len(), 1, "asked once, not once per retry: {asked:#?}");
|
||||
let Message::Request(request) = asked[0] else { unreachable!("filtered above") };
|
||||
(request.id.clone(), request.params.clone())
|
||||
};
|
||||
|
||||
// The late answer is an ordinary settings change: it costs the one
|
||||
// rescan a changed scope has always cost, and — this is the order
|
||||
// contract, unchanged — a request behind it in the same burst is held
|
||||
// rather than answered off the half-updated index.
|
||||
let answer =
|
||||
Message::Response(Response::new_ok(id, serde_json::json!([the_whole_workspace()])));
|
||||
session.batch(vec![answer, symbol_request(7, "t000")]);
|
||||
let said = session.drain();
|
||||
let lines = trace_lines(&said);
|
||||
assert_eq!(lines.len(), 3, "the late answer's rescan, and only it: {lines:#?}");
|
||||
for line in &lines {
|
||||
assert!(line.starts_with("timing: scan 2 "), "the second scan of the session: {line}");
|
||||
}
|
||||
assert_eq!(field(&line_of(&lines, "counts"), "read"), "9", "which indexed the whole tree");
|
||||
let rescanned = said
|
||||
.iter()
|
||||
.rposition(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
n.params["message"].as_str().is_some_and(|text| text.starts_with("timing: scan 2 "))
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
.expect("the rescan traced itself");
|
||||
let answered = positions(&said, 7).1.expect("the request behind it is still answered");
|
||||
assert!(
|
||||
rescanned < answered,
|
||||
"the request waits the rescan out rather than being answered off the index it was \
|
||||
sent into: {said:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_did_open_that_beats_the_answer_is_folded_into_the_one_scan_and_indexed_first() {
|
||||
// A `didOpen` arriving while the settings are in flight widens the
|
||||
// folder scope, which before this would have been its own scan. Staged,
|
||||
// there is nothing to widen *into* yet: the buffer is installed, the one
|
||||
// scan that follows resolves the scope with it in place, and
|
||||
// `open_first` puts the user's own file at the head of its work list.
|
||||
let tree = trace_tree("stagedopen", 9);
|
||||
let opened = tree.path.join("t005.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![did_open(&opened, &text), configuration_answer(the_whole_workspace())],
|
||||
);
|
||||
let said = session.drain();
|
||||
let lines = trace_lines(&said);
|
||||
assert_eq!(lines.len(), 3, "the widen is the scan, not a scan of its own: {lines:#?}");
|
||||
for line in &lines {
|
||||
assert!(line.starts_with("timing: scan 1 "), "{line}");
|
||||
}
|
||||
let counts = line_of(&lines, "counts");
|
||||
assert_eq!(field(&counts, "read"), "9", "the configured scope, in one pass");
|
||||
assert_eq!(field(&counts, "buffers"), "1", "with the buffer indexed from its own analysis");
|
||||
|
||||
// Open first: the per-file log the answer switched on names the work
|
||||
// list in order, and the user's file is at the head of it.
|
||||
let files: Vec<String> = log_lines(&said)
|
||||
.into_iter()
|
||||
.filter(|line| line.starts_with("indexing: ") || line.starts_with("analyzed: "))
|
||||
.collect();
|
||||
let first = files.first().expect("the scan logged its files");
|
||||
assert!(
|
||||
first.ends_with("t005.sv"),
|
||||
"the open buffer is indexed first, not when the alphabet reaches it: {files:#?}"
|
||||
);
|
||||
|
||||
// And the buffer's diagnostics were published against the finished
|
||||
// index — the debt `started` pays at the end of construction.
|
||||
let uri = path_to_uri(&opened).expect("uri");
|
||||
let published: Vec<&Message> = said
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Notification(n) if n.method == PublishDiagnostics::METHOD))
|
||||
.collect();
|
||||
assert!(
|
||||
published.iter().any(|message| {
|
||||
let Message::Notification(n) = message else { return false };
|
||||
n.params["uri"] == serde_json::json!(uri)
|
||||
}),
|
||||
"the opened buffer is published: {published:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_that_beats_the_answer_is_answered_inside_the_startup_scan() {
|
||||
// The regression §P4b named, closed. A definition sent before the
|
||||
// settings answer used to be held behind the *configured rescan* —
|
||||
// `must_wait`'s first clause — and waited the whole of it out, which on
|
||||
// opentitan was 0.9 s warm. Staged, the scan it waits for is the
|
||||
// **startup** scan: nothing was queued ahead of it, the session has no
|
||||
// prior index and therefore no `gone`, and it is answered mid-way off
|
||||
// the published prefix exactly as a request arriving during that scan
|
||||
// is. The only ordering a test can check without a stopwatch is that
|
||||
// the response goes out before the bar comes down.
|
||||
let tree = trace_tree("stagedrequest", INTERLEAVE_ABOVE + 6);
|
||||
let opened = tree.path.join("t005.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let uri = path_to_uri(&opened).expect("uri");
|
||||
let definition = Message::Request(Request::new(
|
||||
RequestId::from(7),
|
||||
GotoDefinition::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 1, "character": 13 },
|
||||
}),
|
||||
));
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
false,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![
|
||||
configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } })),
|
||||
did_open(&opened, &text),
|
||||
definition,
|
||||
],
|
||||
);
|
||||
let said = session.drain();
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
let answered = answered.expect("the definition is answered at all");
|
||||
let ended = ended.expect("the bar comes down");
|
||||
assert!(answered < ended, "answered inside the scan, not after it: {said:#?}");
|
||||
|
||||
// And it is a real, coherent answer — the buffer's own `localparam K`,
|
||||
// read off the prefix `open_first` put that file at the head of.
|
||||
let Some(Message::Response(response)) = said.get(answered) else {
|
||||
unreachable!("positions found a response there")
|
||||
};
|
||||
let found = response.response_result.clone().expect("a result, not a failure");
|
||||
assert_eq!(found[0]["range"]["start"]["line"], 1, "{found}");
|
||||
assert_eq!(found[0]["uri"], serde_json::json!(uri), "{found}");
|
||||
|
||||
// One scan still, and it finished: nothing was traded for the latency
|
||||
// but the completeness of that one answer.
|
||||
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 6);
|
||||
}
|
||||
|
||||
/// opentitan's shape in miniature: a testbench two folders below its block,
|
||||
/// the module it instantiates in that block's `rtl/`, and enough unrelated
|
||||
/// files ahead of both in the alphabet that a scan reaching them first would
|
||||
/// have nothing useful to answer with.
|
||||
fn a_block_and_a_crowd(tag: &str, padding: usize) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("ip/aes/rtl/aes.sv", "module aes;\n localparam K = 1;\nendmodule\n");
|
||||
tree.write("ip/aes/dv/tb/tb.sv", "module tb;\n aes dut ();\nendmodule\n");
|
||||
for n in 0..padding {
|
||||
tree.package(&format!("crowd/p{n:03}.sv"), &format!("p{n:03}"));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_that_beats_the_answer_is_answered_from_the_users_own_folder() {
|
||||
// **The §P4b2 regression, closed.** Staging made the first useful answer
|
||||
// of a workspace-scoped session unimodal — and *empty*: the request was
|
||||
// drained at the first interleave point, off a prefix holding the user's
|
||||
// own buffer and nothing else, so the module it named was not in it yet.
|
||||
// The work list now leads with the buffer's own **folder** and the drain
|
||||
// waits for that folder, which is the answer the widen used to give
|
||||
// (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
//
|
||||
// `crowd/` sorts before `ip/`, so under plain path order the scan would
|
||||
// reach 70 irrelevant files before `aes.sv` — this answer cannot come
|
||||
// from the alphabet.
|
||||
let tree = a_block_and_a_crowd("stagedfolderfirst", INTERLEAVE_ABOVE + 6);
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let definition = Message::Request(Request::new(
|
||||
RequestId::from(7),
|
||||
GotoDefinition::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": path_to_uri(&opened).expect("uri") },
|
||||
"position": { "line": 1, "character": 3 },
|
||||
}),
|
||||
));
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling_with_a_bar(),
|
||||
false,
|
||||
CONFIGURATION_WAIT,
|
||||
vec![
|
||||
configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } })),
|
||||
did_open(&opened, &text),
|
||||
definition,
|
||||
],
|
||||
);
|
||||
let said = session.drain();
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
let answered = answered.expect("the definition is answered at all");
|
||||
assert!(answered < ended.expect("the bar comes down"), "inside the scan: {said:#?}");
|
||||
|
||||
let Some(Message::Response(response)) = said.get(answered) else {
|
||||
unreachable!("positions found a response there")
|
||||
};
|
||||
let found = response.response_result.clone().expect("a result, not a failure");
|
||||
assert_eq!(found.as_array().map(Vec::len), Some(1), "one location, not none: {found}");
|
||||
assert_eq!(
|
||||
found[0]["uri"],
|
||||
serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")),
|
||||
"the module in the folder next door, which is what the user asked about: {found}"
|
||||
);
|
||||
|
||||
// One scan still, and it finished over the whole workspace: the folder
|
||||
// bought the answer's quality, not a smaller index.
|
||||
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_did_open_answered_mid_scan_pulls_its_folder_in_front_of_the_request_behind_it() {
|
||||
// **The case the opentitan measurement found, and the one an editor
|
||||
// really produces.** The client's reader answers `workspace/configuration`
|
||||
// from its own thread, so the answer usually beats the editor's `didOpen`:
|
||||
// the scan begins with *no* buffer open, its work list is the plain
|
||||
// alphabet, and the `didOpen` and the definition behind it arrive at an
|
||||
// interleave point some way into it. Before this the definition was
|
||||
// answered off that alphabet's prefix and came back `[]`.
|
||||
//
|
||||
// Now the burst's `didOpen` holds what is behind it (`Server::head_owed`),
|
||||
// the work list is re-ordered around the buffer it installed, and the
|
||||
// definition is answered once that folder has been indexed — which is
|
||||
// exactly what the widen this `didOpen` used to trigger made it wait for.
|
||||
//
|
||||
// A client that cannot be asked for settings is the shortest way to a scan
|
||||
// that has already started when the burst lands: nothing is staged, and
|
||||
// the wide scope is given up front.
|
||||
let tree = a_block_and_a_crowd("midscanopen", INTERLEAVE_ABOVE + 6);
|
||||
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let definition = Message::Request(Request::new(
|
||||
RequestId::from(7),
|
||||
GotoDefinition::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": path_to_uri(&opened).expect("uri") },
|
||||
"position": { "line": 1, "character": 3 },
|
||||
}),
|
||||
));
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![did_open(&opened, &text), definition],
|
||||
);
|
||||
let said = session.drain();
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
let answered = answered.expect("the definition is answered at all");
|
||||
assert!(answered < ended.expect("the bar comes down"), "inside the scan: {said:#?}");
|
||||
|
||||
let Some(Message::Response(response)) = said.get(answered) else {
|
||||
unreachable!("positions found a response there")
|
||||
};
|
||||
let found = response.response_result.clone().expect("a result, not a failure");
|
||||
assert_eq!(found.as_array().map(Vec::len), Some(1), "one location, not none: {found}");
|
||||
assert_eq!(
|
||||
found[0]["uri"],
|
||||
serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")),
|
||||
"the module in the folder next door: {found}"
|
||||
);
|
||||
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_be_asked_scans_at_once_exactly_as_it_always_did() {
|
||||
// The other half of the gate. A client that never advertised
|
||||
// `workspace/configuration` is only ever *pushed* settings, so there is
|
||||
// nothing to wait for: the scan runs immediately at the defaults, and
|
||||
// the trace lines say what they said before staging existed. The bound
|
||||
// is the shipped one, so a session that waited on it would take two
|
||||
// seconds — the elapsed check is what proves the gate rather than the
|
||||
// bound.
|
||||
let tree = trace_tree("stagednoconfig", 9);
|
||||
let began = Instant::now();
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
ClientAbilities::default(),
|
||||
true,
|
||||
CONFIGURATION_WAIT,
|
||||
Vec::new(),
|
||||
);
|
||||
let took = began.elapsed();
|
||||
assert!(took < Duration::from_secs(1), "nothing was waited for: {took:?}");
|
||||
|
||||
let said = session.drain();
|
||||
assert!(asked(&said).is_empty(), "nothing is asked of this client: {said:#?}");
|
||||
let lines = trace_lines(&said);
|
||||
assert_eq!(lines.len(), 3, "one startup scan: {lines:#?}");
|
||||
let counts = line_of(&lines, "counts");
|
||||
assert_eq!(field(&counts, "read"), "0", "at the defaults, as it always was");
|
||||
assert_eq!(field(&counts, "opens"), "0", "and §P4b's deferred store open is untouched");
|
||||
assert_eq!(field(&counts, "compactions"), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_behind_a_held_request_is_not_stranded_for_the_whole_bound() {
|
||||
// **A defect this lane measured before it shipped** (2026-09-08). The
|
||||
// editor's opening burst is `didOpen` then a request, and the client's
|
||||
// reader can answer the settings pull into that same burst. The request
|
||||
// must wait — there is no index yet — and `process_batch`'s order rule
|
||||
// takes *everything behind it* into `held` with it, the answer included.
|
||||
// The wait then saw the pull still outstanding and blocked the whole
|
||||
// bound: one warm opentitan session in three took 2.1 s to its first
|
||||
// useful answer instead of 0.39 s. The answer is taken back out;
|
||||
// everything else in the burst keeps its place.
|
||||
let tree = trace_tree("stagedstranded", 9);
|
||||
let opened = tree.path.join("t005.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
let bound = Duration::from_secs(30);
|
||||
let began = Instant::now();
|
||||
let session = Session::staged(
|
||||
vec![tree.path.clone()],
|
||||
pulling(),
|
||||
true,
|
||||
bound,
|
||||
vec![
|
||||
did_open(&opened, &text),
|
||||
symbol_request(7, "t000"),
|
||||
configuration_answer(the_whole_workspace()),
|
||||
],
|
||||
);
|
||||
let took = began.elapsed();
|
||||
assert!(took < Duration::from_secs(5), "the bound was not waited out: {took:?}");
|
||||
|
||||
let said = session.drain();
|
||||
let lines = trace_lines(&said);
|
||||
assert_eq!(lines.len(), 3, "one scan, at the answered scope: {lines:#?}");
|
||||
assert_eq!(field(&line_of(&lines, "counts"), "read"), "9");
|
||||
// And the request is neither lost nor answered off an empty index: nine
|
||||
// files are under `INTERLEAVE_ABOVE`, so this scan answers nothing
|
||||
// mid-way and the request is still waiting for `run` to take it — which
|
||||
// is the order rule it was held for, working exactly as it does for a
|
||||
// short startup scan with nothing staged.
|
||||
assert_eq!(positions(&said, 7).1, None, "a short scan answers nothing mid-way: {said:#?}");
|
||||
assert_eq!(session.server.held.len(), 1, "and the request is still owed an answer");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,297 @@
|
||||
//! One workspace scan in flight: the work list it took, the text and the
|
||||
//! records it has gathered so far, and what it reports about itself as it
|
||||
//! runs.
|
||||
//!
|
||||
//! Split out of `state.rs` on 2026-09-08, as a pure move, when the lazy read
|
||||
//! gave the scan three more things to carry (`docs/features/perf5-p4/README.md`
|
||||
//! §P4b3). [`Workspace`](super::Workspace) drives it — `begin_scan` builds
|
||||
//! one, `scan_step` advances it, `finish_scan` lands it — so the fields are
|
||||
//! `pub(super)` and visible exactly where they were before the move: inside
|
||||
//! `crate::state` and nowhere else.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use crate::includes::Include;
|
||||
use crate::scan_order::{self, WorkList};
|
||||
use crate::scan_trace::{self, ScanTrace};
|
||||
|
||||
/// A `Scope` resolved: which files one index rebuild works from, and the text
|
||||
/// of the ones it already holds.
|
||||
///
|
||||
/// **Nothing on disk has been read.** Until 2026-09-08 this carried every
|
||||
/// in-scope file's text, read in one pass before the first file was indexed —
|
||||
/// 34 MiB and ~293 ms on OpenTitan, held for the whole life of the scan and
|
||||
/// spent before any request could be answered. A file's text is now read at
|
||||
/// the step that indexes it and let go again
|
||||
/// (`docs/features/perf5-p4/README.md` §P4b3). An **open buffer's** text is
|
||||
/// still taken here, with the analysis beside it, because the two must
|
||||
/// describe the same bytes and the buffer may be edited while the scan runs.
|
||||
pub(super) struct Sources {
|
||||
/// Every in-scope file, in scope order: the walked ones the cap and the
|
||||
/// open buffers left, then the buffers' own paths.
|
||||
pub(super) files: Vec<PathBuf>,
|
||||
/// The text of each open buffer among `files`, as it was when the scope
|
||||
/// was resolved.
|
||||
pub(super) buffered: HashMap<PathBuf, String>,
|
||||
/// What the open buffers among `files` already know about themselves.
|
||||
pub(super) analyzed: Analyzed,
|
||||
pub(super) incdirs: Vec<PathBuf>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The index facts and the completion words of the entries `texts` took from an
|
||||
/// **open buffer**, read off the analysis that buffer already holds.
|
||||
///
|
||||
/// Both maps are filled in the same loop that lets a buffer override the disk
|
||||
/// copy, so an entry here is always the analysis of exactly the text beside it
|
||||
/// in `texts` — the two cannot describe different bytes. A file that is not an
|
||||
/// open buffer appears in neither map and is parsed and lexed as it always was.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Analyzed {
|
||||
pub(super) facts: HashMap<PathBuf, FileFacts>,
|
||||
pub(super) words: HashMap<PathBuf, Vec<String>>,
|
||||
}
|
||||
|
||||
/// Whether a caller of `collect_sources` wants [`Analyzed`] filled in.
|
||||
///
|
||||
/// An index rebuild does — it is what it indexes the open buffers from. A
|
||||
/// refactoring reads the texts and nothing else, and reading a record off every
|
||||
/// open buffer for it would be work nothing looks at.
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub(super) enum HeldAnalyses {
|
||||
Wanted,
|
||||
Unused,
|
||||
}
|
||||
|
||||
/// One workspace scan in flight: the work list it took when it began, and how
|
||||
/// far through it the workspace has got.
|
||||
///
|
||||
/// A value rather than a loop inside [`Workspace::rebuild_index_with`] because
|
||||
/// the server answers the client's messages *between* two files of a scan
|
||||
/// (`docs/features/scan-interleave/README.md`), and a message it answers needs
|
||||
/// the very workspace the scan is feeding — which a callback called from
|
||||
/// inside a `&mut self` loop can never be handed. Splitting the loop is what
|
||||
/// puts the scan's state somewhere the message can be answered around.
|
||||
pub struct Scan {
|
||||
/// Whether this scan rebuilds the index or only folds newly-in-scope files
|
||||
/// into it. The whole difference is in [`Workspace::finish_scan`]; every
|
||||
/// step in between is the same code.
|
||||
pub(super) kind: ScanKind,
|
||||
/// Every file this scan indexes, in the order it indexes them: the open
|
||||
/// buffers' own files, then the rest of their folders, then the rest in
|
||||
/// path order ([`crate::scan_order`]). For a widen that is the
|
||||
/// newly-in-scope files plus the open buffers, not the whole scope.
|
||||
///
|
||||
/// **Paths, not texts.** A file's text is read at the step that indexes
|
||||
/// it; see [`Workspace::scan_step`].
|
||||
pub(super) work: Vec<PathBuf>,
|
||||
/// How many files at the front of `work` are the user's own
|
||||
/// neighbourhood — see [`Scan::neighbourhood_indexed`].
|
||||
pub(super) head: usize,
|
||||
/// The text of each open buffer among `work`, taken when the work list
|
||||
/// was, so it describes the same bytes as that buffer's entry in
|
||||
/// `analyzed` however the buffer is edited while the scan runs.
|
||||
pub(super) buffered: HashMap<PathBuf, String>,
|
||||
/// What each file taken so far `` `include``s, read off the text at its
|
||||
/// own step. Staged for the same reason `words` is: the include graph is
|
||||
/// built once at the end and once per mid-scan publish, and by then the
|
||||
/// text is gone.
|
||||
pub(super) includes: HashMap<PathBuf, Vec<Include>>,
|
||||
/// Files of `work` whose text could not be read when their step came, and
|
||||
/// which therefore contribute nothing at all. Empty in every ordinary
|
||||
/// scan: a file has to leave the disk between the walk and its own step.
|
||||
/// Named so that the scan can leave it out of everything it lands —
|
||||
/// `collect_sources` used to drop such a file before the work list
|
||||
/// existed, and a whole scan must still take it *out* of the index.
|
||||
pub(super) unread: Vec<PathBuf>,
|
||||
/// Every file that is in scope once this scan lands, kept flat so the
|
||||
/// include graph's known-file table can be relearned from a slice. Which
|
||||
/// files *exist* is settled the moment the scope is resolved, so this never
|
||||
/// moves while the scan runs — reordering the tail of `work` does not
|
||||
/// reorder a set. Equal to `work`'s paths for a whole scan; for a widen it
|
||||
/// is the index's files plus `work`'s.
|
||||
pub(super) paths: Vec<PathBuf>,
|
||||
/// What this scan takes *out* of the index, known before it starts. Empty
|
||||
/// for a whole scan, which works out what left the scope from its own work
|
||||
/// list once it has one ([`Workspace::finish_scan`]).
|
||||
pub(super) gone: Vec<PathBuf>,
|
||||
/// What the open buffers among `work` already knew about themselves, taken
|
||||
/// from as each of them is reached.
|
||||
pub(super) analyzed: Analyzed,
|
||||
pub(super) incdirs: Vec<PathBuf>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
/// How many of `work` have been indexed.
|
||||
pub(super) at: usize,
|
||||
/// The records taken since the last publish, and which files of `work`
|
||||
/// they came from. Staged rather than merged because a merge is a pass
|
||||
/// over the whole index — see [`vlog_semantic::WorkspaceIndex::absorb`].
|
||||
pub(super) staged: Vec<FileFacts>,
|
||||
pub(super) staged_at: Vec<usize>,
|
||||
/// The completion words of every file taken so far, which the tables built
|
||||
/// when the scan ends are assembled from.
|
||||
pub(super) words: HashMap<PathBuf, Vec<String>>,
|
||||
/// How many files the size cap kept out, and how many came from the
|
||||
/// persistent cache instead of a parse. Facts about this scan, so they
|
||||
/// live on it — the end message names both.
|
||||
pub(super) skipped: usize,
|
||||
pub(super) cached: usize,
|
||||
/// What this scan spent its time on, when `--verbose` asked. Off, it is a
|
||||
/// bag of zeroes nobody reads (`crate::scan_trace`).
|
||||
pub(super) trace: ScanTrace,
|
||||
}
|
||||
|
||||
/// Which of the two shapes a [`Scan`] is.
|
||||
///
|
||||
/// One enum rather than two `finish` methods so a caller cannot pair the wrong
|
||||
/// ending with a scan: the scan itself says how it must be landed.
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub(super) enum ScanKind {
|
||||
/// Every in-scope file, and whatever the index holds that the work list
|
||||
/// does not name has left the scope.
|
||||
Whole,
|
||||
/// Only the files a scope widen brought in, folded into the index beside
|
||||
/// what is already there (`docs/features/index-scope/README.md`).
|
||||
Widen,
|
||||
}
|
||||
|
||||
impl Scan {
|
||||
/// How many files the size cap kept out of this scan.
|
||||
pub fn skipped(&self) -> usize {
|
||||
self.skipped
|
||||
}
|
||||
|
||||
/// How many files came from the persistent cache instead of being parsed.
|
||||
pub fn cached(&self) -> usize {
|
||||
self.cached
|
||||
}
|
||||
|
||||
/// How many files this scan will index — known before the first parse,
|
||||
/// which is what lets the caller decide whether the scan is long enough to
|
||||
/// be worth answering messages in the middle of.
|
||||
pub fn total(&self) -> usize {
|
||||
self.work.len()
|
||||
}
|
||||
|
||||
/// Whether this scan has stepped every file of the user's own
|
||||
/// neighbourhood — the open buffers and the folders they raise to
|
||||
/// ([`crate::scan_order`]).
|
||||
///
|
||||
/// **What a request held for the startup scan waits for.** A mid-scan
|
||||
/// answer reads the published prefix, and a prefix holding the user's own
|
||||
/// buffer and the alphabet after it names nothing they asked about: the
|
||||
/// first useful answer of a workspace-scoped session was measurably
|
||||
/// *empty* (`docs/features/perf5-p4/README.md` §P4b2). Waiting for the
|
||||
/// neighbourhood makes it the answer the folder scope would have given,
|
||||
/// which is what it was before the startup scan was staged. Requests that
|
||||
/// arrive after that are answered at every interleave point as they always
|
||||
/// were, and a scan with no neighbourhood (nothing open, an `untitled:`
|
||||
/// buffer, or a folder covering the workspace) has `head` 0 and answers at
|
||||
/// the first one.
|
||||
pub fn neighbourhood_indexed(&self) -> bool {
|
||||
self.at >= self.head
|
||||
}
|
||||
|
||||
/// The text of one file of this scan's work list, at the moment its step
|
||||
/// comes — `None` when it cannot be read.
|
||||
///
|
||||
/// An open buffer's is the copy taken when the work list was, and it is
|
||||
/// *taken*: a scan indexes each file once, so holding it afterwards would
|
||||
/// be holding a second copy of a buffer the workspace already has. Every
|
||||
/// other file is read from disk here and nowhere else in the scan.
|
||||
pub(super) fn take_text(&mut self, path: &Path) -> Option<String> {
|
||||
if let Some(text) = self.buffered.remove(path) {
|
||||
return Some(text);
|
||||
}
|
||||
let reading = self.trace.now();
|
||||
let text = fs::read_to_string(path).ok()?;
|
||||
scan_trace::count_read();
|
||||
self.trace.saw_read(text.len(), reading);
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// The files this scan has not reached yet, for a caller that wants to
|
||||
/// re-order them ([`Scan::reorder`]).
|
||||
pub fn remaining(&self) -> Vec<PathBuf> {
|
||||
self.work[self.at.min(self.work.len())..].to_vec()
|
||||
}
|
||||
|
||||
/// Put `ordered` — [`Scan::remaining`] ranked again — back as what is left
|
||||
/// to index, and take its head segment as the new neighbourhood.
|
||||
///
|
||||
/// The open-first rule, applied to a buffer opened *after* the work list
|
||||
/// was taken: a `didOpen` answered mid-scan puts that file and the folder
|
||||
/// around it next rather than leaving the user waiting for the alphabet to
|
||||
/// reach them. Reordering the tail cannot change the finished index —
|
||||
/// records are merged in path order whatever order they were taken in
|
||||
/// ([`vlog_semantic::IndexBuilder`]) — so this is a latency decision and
|
||||
/// nothing more.
|
||||
pub fn reorder(&mut self, ordered: WorkList) {
|
||||
let at = self.at.min(self.work.len());
|
||||
self.work.truncate(at);
|
||||
self.work.extend(ordered.files);
|
||||
// What is left to wait for, bounded against the whole scan rather than
|
||||
// against the tail it was ranked from
|
||||
// ([`crate::scan_order::worth_waiting`]), and then placed: the
|
||||
// neighbourhood ends that many files past where the scan has got to.
|
||||
self.head = match scan_order::worth_waiting(ordered.head, self.work.len()) {
|
||||
0 => 0,
|
||||
pending => at + pending,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// What each of `taken` `` `include``s, as [`IncludeGraph`] wants it.
|
||||
///
|
||||
/// Borrowed, never cloned: the lists were read at each file's own step and the
|
||||
/// graph only reads them again ([`crate::includes::IncludeGraph::from_includes`]).
|
||||
///
|
||||
/// A free function rather than a method because the two callers hold the map
|
||||
/// differently — a mid-scan publish still has the whole [`Scan`], and the two
|
||||
/// `finish` paths have taken it apart.
|
||||
pub(super) fn included<'a>(
|
||||
includes: &'a HashMap<PathBuf, Vec<Include>>,
|
||||
taken: &'a [PathBuf],
|
||||
) -> Vec<(&'a Path, &'a [Include])> {
|
||||
taken
|
||||
.iter()
|
||||
.map(|path| (path.as_path(), includes.get(path).map(Vec::as_slice).unwrap_or(&[])))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What an index rebuild reports about itself as it runs.
|
||||
///
|
||||
/// This module speaks no protocol, so an event carries numbers and paths and
|
||||
/// nothing that reads like a message; `server.rs` turns them into a progress
|
||||
/// report and a log line (`docs/features/indexing-ux/README.md`).
|
||||
pub enum IndexEvent<'a> {
|
||||
/// One file is about to be parsed into the index: how many were parsed
|
||||
/// before it, how many there are in all, and which one it is. `done`
|
||||
/// counts from 0, so the file being reported is number `done + 1` of
|
||||
/// `total`.
|
||||
Parsing { done: usize, total: usize, path: &'a Path },
|
||||
/// One file went into the index from the persistent cache instead of
|
||||
/// being parsed. The same three numbers [`IndexEvent::Parsing`] carries,
|
||||
/// because it is the same file of the same work list — it is *how* it got
|
||||
/// there that differs, and a user watching a rescan fly through a
|
||||
/// thousand files deserves to be told why.
|
||||
Cached { done: usize, total: usize, path: &'a Path },
|
||||
/// One file went into the index from the analysis an **open buffer**
|
||||
/// already holds — the parse this server did when the buffer was last
|
||||
/// opened or changed — instead of being parsed again. The same three
|
||||
/// numbers the other two carry, for the same reason.
|
||||
///
|
||||
/// Its own variant rather than [`IndexEvent::Cached`] so that "from cache"
|
||||
/// keeps meaning the persistent store and nothing else
|
||||
/// (`docs/features/index-persistence/README.md`): a buffer's own analysis
|
||||
/// is in memory, is there whether that store exists or not, and is right
|
||||
/// even when the buffer has unsaved edits — which is exactly when a
|
||||
/// content-keyed store has nothing to offer.
|
||||
Analyzed { done: usize, total: usize, path: &'a Path },
|
||||
/// A walked file was skipped without being read, because it is bigger
|
||||
/// than the size cap in force.
|
||||
Skipped { path: &'a Path, size: u64, cap: u64 },
|
||||
}
|
||||
@@ -14,14 +14,29 @@
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{ItemKind, ListElem, Module, ParamPort, PortList, SourceFile};
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
use vlog_parser::defines::collect_defines;
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_semantic::{analyze, FileFacts, IndexBuilder, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use crate::context::ModuleInterface;
|
||||
use crate::visit::walk_items;
|
||||
use crate::ParsedSource;
|
||||
|
||||
/// Every package one file declares, with the names it exports — `None` for a
|
||||
/// package this file alone cannot answer for.
|
||||
///
|
||||
/// The text-taking form, for a caller that has not parsed: exactly one
|
||||
/// [`ParsedSource::parse`] followed by [`package_exports_in`], so the two can
|
||||
/// only ever give the same answer.
|
||||
pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option<Vec<String>>)> {
|
||||
let parsed = ParsedSource::parse(src);
|
||||
package_exports_in(path, parsed.file(), parsed.tokens(), src)
|
||||
}
|
||||
|
||||
/// [`package_exports`] over a parse the caller **already has** — `file` and
|
||||
/// `tokens` from one [`ParsedSource::parse`] of `src`.
|
||||
///
|
||||
/// The CLI's half of [`crate::MentionOracle::package_exports`], on the same
|
||||
/// terms [`module_interfaces`] is the CLI's half of `module_interface`: the
|
||||
/// language server reads the answer off its workspace index, and a run with
|
||||
@@ -31,8 +46,25 @@ use crate::visit::walk_items;
|
||||
/// A package writing `export q::*;` answers `None`: which names that lets
|
||||
/// through is a question only a whole-project index can settle, and a short
|
||||
/// list is what would turn a used import into an accusation.
|
||||
pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option<Vec<String>>)> {
|
||||
let index = WorkspaceIndex::build([(path.to_path_buf(), src)]);
|
||||
///
|
||||
/// Two things make this cheap enough for the CLI to run over a whole project
|
||||
/// (take 5 §P3, `docs/features/perf5-p3/README.md`). The index is built from
|
||||
/// the caller's parse rather than from the text, so the file is lexed and
|
||||
/// parsed once for this and for the interface census together; and a file
|
||||
/// whose tree holds **no package item** never reaches the index at all — nine
|
||||
/// files in ten on opentitan `hw/ip`. The gate reads the AST, never the text:
|
||||
/// a `package` inside a string or a comment is not a declaration, and a file
|
||||
/// that says nothing about packages must cost nothing.
|
||||
pub fn package_exports_in(
|
||||
path: &Path,
|
||||
file: &SourceFile,
|
||||
tokens: &[Token],
|
||||
src: &str,
|
||||
) -> Vec<(String, Option<Vec<String>>)> {
|
||||
if !declares_a_package(file) {
|
||||
return Vec::new();
|
||||
}
|
||||
let index = one_file_index(path, file, tokens, src);
|
||||
index
|
||||
.units_of(SymbolKind::Package)
|
||||
.map(|(name, _)| name.to_string())
|
||||
@@ -48,6 +80,52 @@ pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option<Vec<String
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether this tree holds a `package` item anywhere, which is the gate on
|
||||
/// building an index for the file at all.
|
||||
///
|
||||
/// Deliberately a **superset** of "declares a package unit": `walk_items`
|
||||
/// descends into every container, while only a package item bound in the file
|
||||
/// scope becomes a unit the index records. Answering `true` too often costs
|
||||
/// an index; answering `false` too often would lose a package, so the walk
|
||||
/// errs the one way it may.
|
||||
///
|
||||
/// A **fragment** parse — a file that is the bare middle of something, so its
|
||||
/// items list is empty and its content hangs off `SourceFile::fragment` —
|
||||
/// `walk_items` does not descend into, and is never gated out. No fragment
|
||||
/// shape can hold a package (they are statements, enum members and cover
|
||||
/// items, and a file opening with `package` is never re-read as one), but the
|
||||
/// gate does not rest on that.
|
||||
fn declares_a_package(file: &SourceFile) -> bool {
|
||||
if file.fragment.is_some() {
|
||||
return true;
|
||||
}
|
||||
let mut found = false;
|
||||
walk_items(file, &mut |item| {
|
||||
found |= matches!(item.kind, ItemKind::Package { .. });
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// The one-file index [`WorkspaceIndex::build`] would make of this file,
|
||||
/// built from the caller's parse instead of from its text.
|
||||
///
|
||||
/// `build` is `IndexBuilder::add_file` + `finish`, and `add_file` is
|
||||
/// `add_facts(FileFacts::of(path, src))`. `FileFacts::of` parses, analyses and
|
||||
/// reads the record off; [`FileFacts::from_analysis`] is that same read-off
|
||||
/// with the parse handed in. So this is `build` with the lex and the parse it
|
||||
/// would have done deleted — pinned by the equality test below, not by the
|
||||
/// reading of two functions.
|
||||
fn one_file_index(path: &Path, file: &SourceFile, tokens: &[Token], src: &str) -> WorkspaceIndex {
|
||||
let defines = collect_defines(tokens);
|
||||
let sem = analyze(file, src);
|
||||
let lines = LineIndex::new(src);
|
||||
let facts =
|
||||
FileFacts::from_analysis(path.to_path_buf(), file, &defines, &sem, src, &lines, tokens);
|
||||
let mut builder = IndexBuilder::new();
|
||||
builder.add_facts(facts);
|
||||
builder.finish()
|
||||
}
|
||||
|
||||
/// Every module, interface and program the file declares, with what it
|
||||
/// exposes. `None` for a unit whose header cannot be read whole.
|
||||
///
|
||||
@@ -213,3 +291,196 @@ mod tests {
|
||||
assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The package half: every fixture answers what a one-file `WorkspaceIndex`
|
||||
/// built from the file's **text** answers, and a file with no package item
|
||||
/// never builds one (take 5 §P3).
|
||||
#[cfg(test)]
|
||||
mod package_tests {
|
||||
use super::*;
|
||||
|
||||
/// The construction §P3 replaced, kept here as the thing to be equal to:
|
||||
/// a one-file index built from the text, queried exactly as
|
||||
/// [`package_exports_in`] queries the index it builds from a parse.
|
||||
fn from_text(path: &Path, src: &str) -> Vec<(String, Option<Vec<String>>)> {
|
||||
let index = WorkspaceIndex::build([(path.to_path_buf(), src)]);
|
||||
index
|
||||
.units_of(SymbolKind::Package)
|
||||
.map(|(name, _)| name.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let answer = index.reexported_packages(&name).is_empty().then(|| {
|
||||
index.members_of(&name).map(|(member, _)| member.to_string()).collect()
|
||||
});
|
||||
(name, answer)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every shape the census can meet, named so a failure says which.
|
||||
///
|
||||
/// The list is the §P3 brief's: no package, one, two, a wildcard export,
|
||||
/// a named re-export, a package behind a directive, a package after a
|
||||
/// module, text that does not lex, a parse error inside a package body, a
|
||||
/// class in a package, the word `package` in a string and in a comment,
|
||||
/// and one name declared twice in the same file.
|
||||
fn fixtures() -> Vec<(&'static str, &'static str)> {
|
||||
vec![
|
||||
("no package", "module m ();\n wire a;\nendmodule\n"),
|
||||
(
|
||||
"one package",
|
||||
"package p;\n localparam int A = 1;\n typedef logic [1:0] t;\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"two packages",
|
||||
"package p;\n localparam int A = 1;\nendpackage\n\
|
||||
package q;\n localparam int B = 2;\nendpackage\n",
|
||||
),
|
||||
(
|
||||
"a wildcard export of itself",
|
||||
"package p;\n localparam int A = 1;\n export *::*;\nendpackage\n",
|
||||
),
|
||||
(
|
||||
"a wildcard export of another package",
|
||||
"package p;\n import q::*;\n localparam int A = 1;\n export q::*;\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"a named re-export",
|
||||
"package p;\n import q::x;\n localparam int A = 1;\n export q::x;\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"a package behind a directive",
|
||||
"`ifdef USE_PKG\npackage p;\n localparam int A = 1;\nendpackage\n`endif\n",
|
||||
),
|
||||
(
|
||||
"a package after a module",
|
||||
"module m ();\nendmodule\npackage p;\n localparam int A = 1;\nendpackage\n",
|
||||
),
|
||||
("text that does not lex", "module m;\n wire a = \"unterminated\nendmodule\n"),
|
||||
(
|
||||
"a parse error inside the package",
|
||||
"package p;\n localparam int A = 1;\n @@@ ;\n localparam int B = 2;\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"a class in a package",
|
||||
"package p;\n class c;\n int field;\n endclass\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"the word package in a string",
|
||||
"module m ();\n initial $display(\"package p; endpackage\");\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"the word package in a comment",
|
||||
"// package p; endpackage\nmodule m ();\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"one name declared twice",
|
||||
"package p;\n localparam int A = 1;\nendpackage\n\
|
||||
package p;\n localparam int B = 2;\nendpackage\n",
|
||||
),
|
||||
("an empty file", ""),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_fixture_answers_what_a_text_built_index_answers() {
|
||||
for (name, src) in fixtures() {
|
||||
let path = Path::new("/w/f.sv");
|
||||
assert_eq!(package_exports(path, src), from_text(path, src), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_form_and_the_text_form_agree() {
|
||||
for (name, src) in fixtures() {
|
||||
let path = Path::new("/w/f.sv");
|
||||
let parsed = ParsedSource::parse(src);
|
||||
assert_eq!(
|
||||
package_exports_in(path, parsed.file(), parsed.tokens(), src),
|
||||
package_exports(path, src),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The gate is the whole saving, so it is asserted directly rather than
|
||||
/// inferred from an equal answer: exactly the fixtures that write a
|
||||
/// `package` item reach the index.
|
||||
#[test]
|
||||
fn only_a_package_item_opens_the_gate() {
|
||||
let gated_out = [
|
||||
"no package",
|
||||
"text that does not lex",
|
||||
"the word package in a string",
|
||||
"the word package in a comment",
|
||||
"an empty file",
|
||||
];
|
||||
for (name, src) in fixtures() {
|
||||
let opens = declares_a_package(ParsedSource::parse(src).file());
|
||||
assert_eq!(opens, !gated_out.contains(&name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file that does not lex really is one, or the fixture above tests
|
||||
/// nothing about the lex-error path.
|
||||
#[test]
|
||||
fn the_unlexable_fixture_does_not_lex() {
|
||||
let src = fixtures()
|
||||
.into_iter()
|
||||
.find(|(name, _)| *name == "text that does not lex")
|
||||
.map(|(_, src)| src)
|
||||
.unwrap_or_default();
|
||||
assert!(ParsedSource::parse(src).lex_error().is_some(), "{src:?}");
|
||||
}
|
||||
|
||||
/// The answers themselves, not only their equality to the old
|
||||
/// construction: a file with no package says nothing, a plain package is
|
||||
/// a list, and a re-export is unknowable.
|
||||
#[test]
|
||||
fn the_answers_are_the_conservative_ones() {
|
||||
let path = Path::new("/w/f.sv");
|
||||
assert!(package_exports(path, "module m ();\nendmodule\n").is_empty());
|
||||
|
||||
let plain = package_exports(path, "package p;\n localparam int A = 1;\nendpackage\n");
|
||||
assert_eq!(plain.len(), 1);
|
||||
assert_eq!(plain[0].0, "p");
|
||||
assert_eq!(plain[0].1.as_deref(), Some(["A".to_string()].as_slice()));
|
||||
|
||||
let wildcard = package_exports(
|
||||
path,
|
||||
"package p;\n localparam int A = 1;\n export q::*;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(wildcard, vec![("p".to_string(), None)], "a re-export is unknowable");
|
||||
}
|
||||
|
||||
/// One name declared twice **in one file** — the `` `ifdef``-copied
|
||||
/// package — answers with the *first* declaration's members, not with
|
||||
/// `None`. That is what the one-file index has always said and this lane
|
||||
/// changes nothing about it; the `None` the CLI's census produces is the
|
||||
/// *cross-file* rule, applied by `Census::of`'s merge when two files each
|
||||
/// contribute an entry for one name.
|
||||
///
|
||||
/// Pinned here so a later change to either construction has to notice it.
|
||||
#[test]
|
||||
fn a_name_declared_twice_in_one_file_answers_with_the_first() {
|
||||
let path = Path::new("/w/f.sv");
|
||||
let first = package_exports(
|
||||
path,
|
||||
"package p;\n localparam int A = 1;\nendpackage\n\
|
||||
package p;\n localparam int B = 2;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(first, vec![("p".to_string(), Some(vec!["A".to_string()]))]);
|
||||
let swapped = package_exports(
|
||||
path,
|
||||
"package p;\n localparam int B = 2;\nendpackage\n\
|
||||
package p;\n localparam int A = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(swapped, vec![("p".to_string(), Some(vec!["B".to_string()]))]);
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ mod waiver_file;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
|
||||
pub use interfaces::{module_interfaces, package_exports};
|
||||
pub use interfaces::{module_interfaces, package_exports, package_exports_in};
|
||||
pub use options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions};
|
||||
pub use registry::{
|
||||
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod lexer;
|
||||
pub mod line_index;
|
||||
pub mod parser;
|
||||
pub mod span;
|
||||
pub mod stats;
|
||||
pub mod token;
|
||||
|
||||
pub use lexer::{tokenize, LexError};
|
||||
|
||||
@@ -301,6 +301,7 @@ struct Rewind {
|
||||
/// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process
|
||||
/// instead of returning `Err`.
|
||||
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
|
||||
crate::stats::count_parse();
|
||||
Parser::new(tokens, source, false).parse_source_file()
|
||||
}
|
||||
|
||||
@@ -317,6 +318,7 @@ pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
|
||||
/// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict
|
||||
/// parses of the same over-deep input overflow at the same depth.
|
||||
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
|
||||
crate::stats::count_parse();
|
||||
let mut p = Parser::new(tokens, source, true);
|
||||
match p.parse_source_file() {
|
||||
Ok(file) => (file, p.diagnostics),
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
//! How much parsing this thread has done — a work counter, not a timer.
|
||||
//!
|
||||
//! A `textDocument/codeAction` used to parse the same buffer five times, and
|
||||
//! the only honest way to prove that it no longer does is to count the parses
|
||||
//! rather than to time them (take 5 §P1,
|
||||
//! `docs/features/perf5-p1/README.md`). A stopwatch assertion on a 1.3 MB
|
||||
//! buffer is a flake; a count is not.
|
||||
//!
|
||||
//! **Per thread, deliberately.** A process-wide counter would be unusable as
|
||||
//! an assertion, because `cargo test` runs tests in parallel and every other
|
||||
//! test in the binary would be adding to it; and it would answer the wrong
|
||||
//! question anyway, since what a caller wants to know is what *this* request
|
||||
//! did. A request is answered on one thread, so a thread-local count is that
|
||||
//! number exactly. It costs one non-atomic add per whole-file parse.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static PARSES: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many whole-file parses this thread has run.
|
||||
///
|
||||
/// Counted in [`crate::parse`] and [`crate::parse_tolerant`], which is every
|
||||
/// way a whole file is parsed: [`crate::parse_source`] and
|
||||
/// [`crate::parse_source_tolerant`] both funnel through them. A *lex* failure
|
||||
/// parses nothing and is not counted; neither is a fragment read (macro
|
||||
/// expansion), which re-reads a token slice rather than a file.
|
||||
///
|
||||
/// The count is monotone and never reset, so a caller measures a *delta*
|
||||
/// across the work it is asking about.
|
||||
pub fn parses() -> u64 {
|
||||
PARSES.with(Cell::get)
|
||||
}
|
||||
|
||||
/// Count one whole-file parse.
|
||||
pub(crate) fn count_parse() {
|
||||
PARSES.with(|parses| parses.set(parses.get() + 1));
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
//! The state after the edits: the index the verifier compares against, and
|
||||
//! one watched file's print of it.
|
||||
//!
|
||||
//! Both used to be "do it all again". The after-index was a whole
|
||||
//! `WorkspaceIndex::build` over every in-scope file, of which an edit changes
|
||||
//! two or three; the after-print of an *unedited* watched file was a fresh
|
||||
//! parse and analysis of text nothing had touched. Take 5 §P2c replaced the
|
||||
//! first with the before-index plus the edited files' absorbed records, and
|
||||
//! the second with the analysis the before-pass already made, re-resolved
|
||||
//! against the new index.
|
||||
//!
|
||||
//! **Nothing the verifier compares changed.** The prints are the same prints,
|
||||
//! built by the same `print`, over the same watched set; what changed is where
|
||||
//! their inputs come from. The tests below are the proof that the inputs are
|
||||
//! the same inputs — including on edits crafted to make an incremental index
|
||||
//! disagree with a rebuilt one.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{resolve_external, FileFacts, Semantics, WorkspaceIndex};
|
||||
|
||||
use super::{print, Print, Shifts};
|
||||
use crate::scope::Scope;
|
||||
|
||||
/// The workspace index as it would be after the edits, so that a cross-file
|
||||
/// capture is caught exactly the way an in-file one is — **and** the one new
|
||||
/// analysis of each edited file, which is also its after-print's.
|
||||
///
|
||||
/// The before-index already holds a record per in-scope file, and an edit
|
||||
/// changes at most a handful of them. So this is the before-index with the
|
||||
/// edited files' new records absorbed, and not one unedited file re-read:
|
||||
/// `WorkspaceIndex::absorb` promises "the index a full build over the
|
||||
/// resulting record set would have produced" (`docs/topo.md` §3), and every
|
||||
/// edited path is one the index already holds, so no file id moves either.
|
||||
/// One `absorb` of every edited record rather than an `update_facts` per
|
||||
/// record: both promise that same equality, and `absorb`'s single whole merge
|
||||
/// **measured faster** than the per-file restricted merges, which walk the
|
||||
/// same records with a name-set lookup at every declaration (tail rename
|
||||
/// 37 ms against 53; see the feature README's §P2c entry).
|
||||
/// That equality is what the verifier depends on and what
|
||||
/// `an_absorbed_after_index_is_the_index_a_rebuild_would_give` pins, on
|
||||
/// crafted adversarial edits as well as on ordinary ones (take 5 §P2c).
|
||||
///
|
||||
/// Each edited file is parsed **once**, here, and the analysis that parse
|
||||
/// produced is handed back for the after-print rather than being made again.
|
||||
pub(super) fn after_index(
|
||||
scope: &Scope,
|
||||
edited: &[(PathBuf, String)],
|
||||
) -> (WorkspaceIndex, Vec<(PathBuf, Semantics)>) {
|
||||
let mut records = Vec::with_capacity(edited.len());
|
||||
let mut analyses = Vec::with_capacity(edited.len());
|
||||
for (path, text) in edited {
|
||||
let (facts, semantics) = FileFacts::analyzed(path.clone(), text);
|
||||
records.push(facts);
|
||||
analyses.push((path.clone(), semantics));
|
||||
}
|
||||
let mut index = scope.index().clone();
|
||||
index.absorb(records, &[]);
|
||||
(index, analyses)
|
||||
}
|
||||
|
||||
/// One watched file's after-print: from the edited file's own new analysis
|
||||
/// when the edits touched it, and otherwise from the analysis the before-pass
|
||||
/// computed, re-resolved against the after-index.
|
||||
pub(super) fn after_print(
|
||||
scope: &Scope,
|
||||
i: usize,
|
||||
path: &Path,
|
||||
index: &WorkspaceIndex,
|
||||
edited: &[(PathBuf, Semantics)],
|
||||
excluded: &[TextRange],
|
||||
) -> Option<Print> {
|
||||
match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, semantics)) => {
|
||||
let external = resolve_external(semantics, index);
|
||||
Some(print(semantics, &external, index, path, &Shifts::default(), excluded))
|
||||
}
|
||||
None => {
|
||||
let (semantics, external) = scope.against(i, index)?;
|
||||
Some(print(semantics, &external, index, path, &Shifts::default(), excluded))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::apply;
|
||||
use crate::TextEdit;
|
||||
|
||||
/// What a whole `WorkspaceIndex::build` over the edited texts gives — the
|
||||
/// thing the absorbed index has to equal, and what §P2c replaced.
|
||||
fn rebuilt(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
|
||||
let sources: Vec<(PathBuf, &str)> = (0..scope.len())
|
||||
.filter_map(|i| {
|
||||
let (path, text) = (scope.path(i)?, scope.text(i)?);
|
||||
let text = edited
|
||||
.iter()
|
||||
.find(|(edited_path, _)| edited_path == path)
|
||||
.map_or(text, |(_, edited_text)| edited_text.as_str());
|
||||
Some((path.to_path_buf(), text))
|
||||
})
|
||||
.collect();
|
||||
WorkspaceIndex::build(sources)
|
||||
}
|
||||
|
||||
/// Every query the verifier's prints reach the index through, for one
|
||||
/// name — so "the same index" is checked at the level the checks use it
|
||||
/// and not only through the fingerprint.
|
||||
fn answers(index: &WorkspaceIndex, name: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for def in index.units(name) {
|
||||
out.push_str(&format!(
|
||||
"unit {} {:?} {}..{}\n",
|
||||
def.file.0, def.kind, def.name_span.start, def.name_span.end
|
||||
));
|
||||
for site in index.references_to(def) {
|
||||
out.push_str(&format!(
|
||||
" ref {} {}..{}\n",
|
||||
site.file.0, site.name_span.start, site.name_span.end
|
||||
));
|
||||
}
|
||||
}
|
||||
for edge in index.instantiations_of(name) {
|
||||
out.push_str(&format!("inst {} {}\n", edge.file.0, edge.owner.name));
|
||||
}
|
||||
for (unit, def) in index.hierarchical_declarations(name) {
|
||||
out.push_str(&format!(
|
||||
"hier {unit} {} {}..{}\n",
|
||||
def.file.0, def.name_span.start, def.name_span.end
|
||||
));
|
||||
}
|
||||
for symbol in index.workspace_symbols(name) {
|
||||
out.push_str(&format!("sym {} {:?}\n", symbol.name, symbol.container));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One (workspace, edit) case: build a scope, apply the edits, and assert
|
||||
/// the absorbed after-index is the index a rebuild would give.
|
||||
fn absorbing_equals_rebuilding(
|
||||
files: &[(&str, &str)],
|
||||
edits: &[(&str, &str, &str)],
|
||||
names: &[&str],
|
||||
) {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
files.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let scope = Scope::build(&sources);
|
||||
let mut edited: Vec<(PathBuf, String)> = Vec::new();
|
||||
for (path, from, to) in edits {
|
||||
let i = scope.index_of(Path::new(path)).expect("the edited file is in scope");
|
||||
let text = scope.text(i).expect("its text");
|
||||
let at = text.find(from).expect("the edited text is there") as u32;
|
||||
let edit = TextEdit {
|
||||
range: TextRange::new(at, at + from.len() as u32),
|
||||
new_text: (*to).to_string(),
|
||||
};
|
||||
edited.push((PathBuf::from(*path), apply(text, std::slice::from_ref(&edit))));
|
||||
}
|
||||
let (absorbed, analyses) = after_index(&scope, &edited);
|
||||
let built = rebuilt(&scope, &edited);
|
||||
assert_eq!(absorbed.fingerprint(), built.fingerprint(), "{files:?} / {edits:?}");
|
||||
assert_eq!(absorbed.files(), built.files(), "the file ids moved");
|
||||
assert_eq!(absorbed.files(), scope.index().files(), "an absorb over held paths keeps ids");
|
||||
for name in names {
|
||||
assert_eq!(answers(&absorbed, name), answers(&built, name), "`{name}` differs");
|
||||
}
|
||||
assert_eq!(analyses.len(), edited.len(), "one new analysis per edited file");
|
||||
}
|
||||
|
||||
const SUB: &str = "module sub (input logic clk, output logic q);\n wire sig;\nendmodule\n";
|
||||
const TOP: &str = "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign sig = u_sub.sig;\nendmodule\n";
|
||||
const PKG: &str = "package pkg;\n localparam int SIG = 1;\nendpackage\n";
|
||||
const USER: &str = "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n";
|
||||
|
||||
fn workspace() -> [(&'static str, &'static str); 4] {
|
||||
[("/w/sub.sv", SUB), ("/w/top.sv", TOP), ("/w/pkg.sv", PKG), ("/w/user.sv", USER)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absorbed_after_index_is_the_index_a_rebuild_would_give() {
|
||||
// An ordinary rename edit, in one file and in two.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/top.sv", "logic sig;", "logic sg;")],
|
||||
&["sig", "sg", "top", "sub"],
|
||||
);
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/sub.sv", "wire sig;", "wire sg;"), ("/w/top.sv", "u_sub.sig", "u_sub.sg")],
|
||||
&["sig", "sg", "sub"],
|
||||
);
|
||||
// A file that **gains** a declaration another file can name.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[(
|
||||
"/w/pkg.sv",
|
||||
"localparam int SIG = 1;",
|
||||
"localparam int SIG = 1;\n localparam int X = 2;",
|
||||
)],
|
||||
&["SIG", "X", "pkg"],
|
||||
);
|
||||
// A file that **loses** one — the use in `user.sv` is left dangling,
|
||||
// and neither index may hide that.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/pkg.sv", "localparam int SIG = 1;", "")],
|
||||
&["SIG", "pkg"],
|
||||
);
|
||||
// An edit that changes what **another** file resolves to: the package
|
||||
// is renamed, so `user.sv`'s import points at nothing.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/pkg.sv", "package pkg;", "package pkq;")],
|
||||
&["pkg", "pkq", "SIG"],
|
||||
);
|
||||
// An edited **package**, plus the re-export chain that reads it.
|
||||
const A: &str = "package a_pkg;\n localparam int V = 1;\nendpackage\n";
|
||||
const B: &str = "package b_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n";
|
||||
const C: &str = "module c;\n localparam int W = b_pkg::V;\nendmodule\n";
|
||||
let chain = [("/w/a.sv", A), ("/w/b.sv", B), ("/w/c.sv", C)];
|
||||
absorbing_equals_rebuilding(
|
||||
&chain,
|
||||
&[("/w/a.sv", "localparam int V = 1;", "localparam int V2 = 1;")],
|
||||
&["V", "V2", "a_pkg", "b_pkg"],
|
||||
);
|
||||
absorbing_equals_rebuilding(
|
||||
&chain,
|
||||
&[("/w/b.sv", "export a_pkg::*;", "")],
|
||||
&["V", "a_pkg", "b_pkg"],
|
||||
);
|
||||
// A module that stops being instantiated, and one that starts.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/top.sv", "sub u_sub", "other u_sub")],
|
||||
&["sub", "other", "top"],
|
||||
);
|
||||
// An edit that makes a file stop lexing: it contributes nothing, and
|
||||
// both indexes must agree that it contributes nothing.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/sub.sv", "wire sig;", "wire \"sig;")],
|
||||
&["sig", "sub"],
|
||||
);
|
||||
}
|
||||
|
||||
/// **Attack 3 — an after-index whose file ids shifted.** The absorbed
|
||||
/// index keeps ids because every edited path is one it already holds, but
|
||||
/// the print comparison must not *depend* on that: a `Def` names a file by
|
||||
/// id, and an id is a position in a path-sorted list that any added file
|
||||
/// renumbers. So the print resolves every id back to a **path** before
|
||||
/// comparing, and this pins it — the same file's print against two indexes
|
||||
/// whose ids differ by one everywhere must be the same print.
|
||||
#[test]
|
||||
fn a_print_names_paths_so_shifted_file_ids_cannot_change_it() {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
workspace().iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let mut scope = Scope::build(&sources);
|
||||
// An index over the same four files plus one that sorts *first*, so
|
||||
// every original file's id is one higher in it.
|
||||
let mut shifted: Vec<(PathBuf, &str)> =
|
||||
sources.iter().map(|(p, t)| (p.clone(), t.as_str())).collect();
|
||||
shifted.insert(0, (PathBuf::from("/w/aaa.sv"), "module aaa; endmodule\n"));
|
||||
let shifted = WorkspaceIndex::build(shifted);
|
||||
assert_eq!(
|
||||
shifted.file_id(Path::new("/w/pkg.sv")).map(|f| f.0),
|
||||
scope.index().file_id(Path::new("/w/pkg.sv")).map(|f| f.0 + 1),
|
||||
"the ids really do shift"
|
||||
);
|
||||
|
||||
let i = scope.index_of(Path::new("/w/user.sv")).expect("user.sv is in scope");
|
||||
assert!(scope.analysis(i).is_some(), "its analysis is what a before-pass computes");
|
||||
let path = scope.path(i).expect("its path");
|
||||
let held = after_print(&scope, i, path, scope.index(), &[], &[]).expect("a print");
|
||||
let moved = after_print(&scope, i, path, &shifted, &[], &[]).expect("a print");
|
||||
assert_eq!(held, moved, "a print must not read a file id");
|
||||
}
|
||||
|
||||
/// Absorbing over a path the index already holds moves no file id — the
|
||||
/// property the after-print's path lookups and the `Def`s inside a print
|
||||
/// both stand on.
|
||||
#[test]
|
||||
fn absorbing_an_edited_file_keeps_every_file_id() {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
workspace().iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let scope = Scope::build(&sources);
|
||||
let before: Vec<PathBuf> = scope.index().files().to_vec();
|
||||
let edited = vec![(PathBuf::from("/w/pkg.sv"), PKG.replace("SIG", "SIGNAL"))];
|
||||
let (after, _) = after_index(&scope, &edited);
|
||||
assert_eq!(after.files(), before.as_slice());
|
||||
for (id, path) in before.iter().enumerate() {
|
||||
assert_eq!(after.file_id(path), Some(vlog_semantic::FileId(id as u32)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same
|
||||
//! contract, kept separately, so the formatter's safety net does not widen.
|
||||
|
||||
mod after;
|
||||
mod ledger;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -26,13 +27,14 @@ use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalResolutions, ExternalTarget, ReferenceId, Semantics,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
ExternalResolutions, ExternalTarget, ReferenceId, Semantics, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::rename::{contains_word, display, Scope};
|
||||
use crate::trace::VerifyTrace;
|
||||
use crate::{apply, Shift, TextEdit};
|
||||
|
||||
use after::{after_index, after_print};
|
||||
use ledger::{overlaps, pieces_match, region_of, Split, Transit};
|
||||
|
||||
/// Check the whole edit, or refuse it whole.
|
||||
@@ -41,6 +43,7 @@ pub(crate) fn verify(
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
old_name: &str,
|
||||
new_name: &str,
|
||||
trace: &mut VerifyTrace,
|
||||
) -> Result<(), String> {
|
||||
let edited: Vec<(PathBuf, String)> = edits
|
||||
.iter()
|
||||
@@ -57,7 +60,7 @@ pub(crate) fn verify(
|
||||
// 1. The token stream of every touched file, before and after.
|
||||
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
|
||||
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
|
||||
tokens_match(before, text, &Shift::new(edits), new_name, path)?;
|
||||
trace.tokens.measure(|| tokens_match(before, text, &Shift::new(edits), new_name, path))?;
|
||||
}
|
||||
|
||||
// 2. What every name resolves to, before and after — in every file the
|
||||
@@ -68,40 +71,39 @@ pub(crate) fn verify(
|
||||
// catches a third file whose existing `new_name` reference the rename
|
||||
// would make ambiguous without touching a byte of it.
|
||||
let watched = watched_files(scope, edits, &[old_name, new_name]);
|
||||
trace.watched = watched.len();
|
||||
trace.watched_bytes = watched.iter().filter_map(|&i| scope.text(i)).map(str::len).sum();
|
||||
let mut before: Vec<Print> = Vec::new();
|
||||
for &i in &watched {
|
||||
if scope.analysis(i).is_none() {
|
||||
if !trace.before.measure(|| scope.analysis(i).is_some()) {
|
||||
return Err(ABANDONED.to_string());
|
||||
}
|
||||
}
|
||||
let mut before: Vec<Print> = Vec::new();
|
||||
for &i in &watched {
|
||||
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
|
||||
return Err(ABANDONED.to_string());
|
||||
};
|
||||
before.push(print(
|
||||
&analysis.semantics,
|
||||
&analysis.external,
|
||||
scope.index(),
|
||||
path,
|
||||
&shifts,
|
||||
&[],
|
||||
));
|
||||
trace.before.measure(|| {
|
||||
before.push(print(
|
||||
&analysis.semantics,
|
||||
&analysis.external,
|
||||
scope.index(),
|
||||
path,
|
||||
&shifts,
|
||||
&[],
|
||||
))
|
||||
});
|
||||
}
|
||||
|
||||
let after_index = rebuilt_index(scope, &edited);
|
||||
let (after_index, edited_analyses) = trace.rebuild.measure(|| after_index(scope, &edited));
|
||||
for (n, &i) in watched.iter().enumerate() {
|
||||
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
|
||||
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, edited_text)) => edited_text.as_str(),
|
||||
None => match scope.text(i) {
|
||||
Some(text) => text,
|
||||
None => return Err(ABANDONED.to_string()),
|
||||
},
|
||||
let after = trace
|
||||
.after
|
||||
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &[]));
|
||||
let (Some(after), Some(before)) = (after, before.get(n)) else {
|
||||
return Err(ABANDONED.to_string());
|
||||
};
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let external = resolve_external(&semantics, &after_index);
|
||||
let after = print(&semantics, &external, &after_index, path, &Shifts::default(), &[]);
|
||||
let Some(before) = before.get(n) else { return Err(ABANDONED.to_string()) };
|
||||
if let Some(what) = before.first_difference(&after) {
|
||||
return Err(format!(
|
||||
"renaming `{old_name}` to `{new_name}` would change what {what} means in {}; the rename was abandoned.",
|
||||
@@ -319,27 +321,14 @@ pub(crate) fn verify_move(
|
||||
));
|
||||
}
|
||||
|
||||
let after_index = rebuilt_index(scope, &edited);
|
||||
let (after_index, edited_analyses) = after_index(scope, &edited);
|
||||
for (n, &i) in watched.iter().enumerate() {
|
||||
let Some(path) = scope.path(i) else { return Err(abandoned) };
|
||||
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, edited_text)) => edited_text.as_str(),
|
||||
None => match scope.text(i) {
|
||||
Some(text) => text,
|
||||
None => return Err(abandoned),
|
||||
},
|
||||
let after =
|
||||
after_print(scope, i, path, &after_index, &edited_analyses, excluded.after(path));
|
||||
let (Some(after), Some(before)) = (after, before.get(n)) else {
|
||||
return Err(abandoned);
|
||||
};
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let external = resolve_external(&semantics, &after_index);
|
||||
let after = print(
|
||||
&semantics,
|
||||
&external,
|
||||
&after_index,
|
||||
path,
|
||||
&Shifts::default(),
|
||||
excluded.after(path),
|
||||
);
|
||||
let Some(before) = before.get(n) else { return Err(abandoned) };
|
||||
if let Some(what_moved) = before.first_difference(&after) {
|
||||
return Err(format!(
|
||||
"{what} would change what {what_moved} means in {}; no edits were made.",
|
||||
@@ -409,19 +398,6 @@ fn watched_files(scope: &Scope, edits: &[(usize, Vec<TextEdit>)], names: &[&str]
|
||||
|
||||
const ABANDONED: &str = "lucisv could not verify the rename, so it made no edits.";
|
||||
|
||||
/// The workspace index as it would be after the edits, so that a cross-file
|
||||
/// capture is caught exactly the way an in-file one is.
|
||||
fn rebuilt_index(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
|
||||
let sources = scope.sources().iter().map(|(path, text)| {
|
||||
let text = edited
|
||||
.iter()
|
||||
.find(|(edited_path, _)| edited_path == path)
|
||||
.map_or(*text, |(_, edited_text)| edited_text.as_str());
|
||||
(path.to_path_buf(), text)
|
||||
});
|
||||
WorkspaceIndex::build(sources.collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// token identity
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -1257,7 +1233,7 @@ mod tests {
|
||||
new_text: "sig".into(),
|
||||
}],
|
||||
)];
|
||||
let outcome = verify(&mut scope, &partial, "a", "sig");
|
||||
let outcome = verify(&mut scope, &partial, "a", "sig", &mut VerifyTrace::default());
|
||||
assert!(outcome.is_err(), "a half-done rename must not verify: {outcome:?}");
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,8 @@ mod render;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, SourceFile};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, SymbolKind};
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
@@ -81,10 +81,26 @@ pub struct ExtractSite {
|
||||
/// a whole item to move.
|
||||
pub fn extract_site(text: &str, start: u32, end: u32) -> Option<ExtractSite> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
extract_site_in(&tree, &diagnostics, text, start, end)
|
||||
}
|
||||
|
||||
/// [`extract_site`] over a parse the caller already has.
|
||||
///
|
||||
/// The same answer, refusal on parse diagnostics included — `diagnostics`
|
||||
/// must be `tree`'s own list, and `text` the bytes both were built from
|
||||
/// (`Region::read` copies item text out by span). Take 5 §P1b; see
|
||||
/// `docs/features/perf5-p1/README.md`.
|
||||
pub fn extract_site_in(
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
text: &str,
|
||||
start: u32,
|
||||
end: u32,
|
||||
) -> Option<ExtractSite> {
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let region = Region::read(&tree, text, TextRange::new(start, end)).ok()?;
|
||||
let region = Region::read(tree, text, TextRange::new(start, end)).ok()?;
|
||||
let module = region.module_name().to_string();
|
||||
let mut units = vec![module.clone()];
|
||||
for item in ®ion.items {
|
||||
|
||||
@@ -93,10 +93,26 @@ pub fn unused_imports(files: &[(PathBuf, String)], file: &Path) -> Vec<(TextRang
|
||||
/// them, and nothing else, to the engine.
|
||||
pub fn imported_packages(text: &str, offset: u32) -> Vec<String> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
imported_packages_in(&tree, &diagnostics, text, offset)
|
||||
}
|
||||
|
||||
/// [`imported_packages`] over a parse the caller already has.
|
||||
///
|
||||
/// The same answer, including the refusal on a buffer that did not parse
|
||||
/// cleanly — `diagnostics` is that parse's own list and must come from the
|
||||
/// same run as `tree`. `text` is still needed: the "is the cursor at the top"
|
||||
/// question reads the source bytes of the import run's comment block. Take 5
|
||||
/// §P1b; see `docs/features/perf5-p1/README.md`.
|
||||
pub fn imported_packages_in(
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
text: &str,
|
||||
offset: u32,
|
||||
) -> Vec<String> {
|
||||
if !diagnostics.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(items) = container_at(&tree, offset) else { return Vec::new() };
|
||||
let Some(items) = container_at(tree, offset) else { return Vec::new() };
|
||||
let imports: Vec<&Item> = items.iter().filter(|item| is_import(item)).collect();
|
||||
if imports.is_empty() || !at_the_top(text, items, offset) {
|
||||
return Vec::new();
|
||||
@@ -142,20 +158,10 @@ fn organize(
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
unparsed(file, &diagnostics)?;
|
||||
let semantics = analyze(&tree, text);
|
||||
let Ok(tokens) = tokenize(text) else { return Err(not_in_scope(file)) };
|
||||
|
||||
let here = scope_at(&tree, &semantics, offset)?;
|
||||
let verdicts = import_usage(&semantics, &tokens, here.scope, scope.index())?;
|
||||
let mut blocks = Blocks::read(text, here.items, &verdicts)?;
|
||||
let (edits, warnings, removed, sorted) = blocks.plan(text)?;
|
||||
if edits.is_empty() {
|
||||
return Err(match warnings.first() {
|
||||
Some(sentence) => sentence.clone(),
|
||||
None => "these imports are already sorted, and every one of them is used.".to_string(),
|
||||
});
|
||||
}
|
||||
let (edits, warnings, removed, sorted) =
|
||||
planned(scope.index(), file, text, &tree, &diagnostics, &semantics, &tokens, offset)?;
|
||||
|
||||
let what = "organizing the imports";
|
||||
let plan = vec![(i, edits)];
|
||||
@@ -166,6 +172,96 @@ fn organize(
|
||||
Ok((edit, removed, sorted))
|
||||
}
|
||||
|
||||
/// Everything the organization decides **before** it is verified: its edits,
|
||||
/// the sentences about what it left alone, and the two counts a title
|
||||
/// promises.
|
||||
///
|
||||
/// One reader, so the code action's offer and the edit it resolves to cannot
|
||||
/// come to disagree about how many imports go and how many are sorted.
|
||||
/// `tree`, `diagnostics`, `semantics` and `tokens` must all be of `text`.
|
||||
#[allow(clippy::too_many_arguments)] // one call's worth of already-computed inputs, not state
|
||||
fn planned(
|
||||
index: &vlog_semantic::WorkspaceIndex,
|
||||
file: &Path,
|
||||
text: &str,
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
semantics: &Semantics,
|
||||
tokens: &[vlog_parser::token::Token],
|
||||
offset: u32,
|
||||
) -> Result<(Vec<TextEdit>, Vec<String>, usize, usize), String> {
|
||||
unparsed(file, diagnostics)?;
|
||||
let here = scope_at(tree, semantics, offset)?;
|
||||
let verdicts = import_usage(semantics, tokens, here.scope, index)?;
|
||||
let mut blocks = Blocks::read(text, here.items, &verdicts)?;
|
||||
let (edits, warnings, removed, sorted) = blocks.plan(text)?;
|
||||
if edits.is_empty() {
|
||||
return Err(match warnings.first() {
|
||||
Some(sentence) => sentence.clone(),
|
||||
None => "these imports are already sorted, and every one of them is used.".to_string(),
|
||||
});
|
||||
}
|
||||
Ok((edits, warnings, removed, sorted))
|
||||
}
|
||||
|
||||
/// What an organize-imports code action's title promises — how many imports it
|
||||
/// removes and how many it writes back in order — **without** verifying the
|
||||
/// splice or keeping the edit.
|
||||
///
|
||||
/// [`organize_counts`] answers the same two numbers by computing the whole
|
||||
/// refactoring and running `check::verify_splice`, which rebuilds the index
|
||||
/// over every in-scope file and re-analyzes them. A lazily-offered code action
|
||||
/// throws that edit away and asks for it again on the click, so the offer pays
|
||||
/// for a verification whose result nothing reads: take 5 §P1c measured that
|
||||
/// verification as about two thirds of the offer's cost
|
||||
/// (`docs/features/perf5-p1/README.md`).
|
||||
///
|
||||
/// Everything the *plan* refuses is refused here identically, with the same
|
||||
/// sentence: a buffer that does not parse, no scope at the position, an
|
||||
/// unknown package (`import_usage`'s own refusal), an import sharing a line,
|
||||
/// and the "already sorted, every one used" answer. What is **not** reproduced
|
||||
/// is `check::verify_splice`; the click recomputes and verifies the whole
|
||||
/// refactoring, which is where an edit that would not survive it is refused.
|
||||
pub fn organize_offer(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(usize, usize), String> {
|
||||
let scope = Scope::build(files);
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
let semantics = analyze(&tree, text);
|
||||
let Ok(tokens) = tokenize(text) else { return Err(not_in_scope(file)) };
|
||||
let (_, _, removed, sorted) =
|
||||
planned(scope.index(), file, text, &tree, &diagnostics, &semantics, &tokens, offset)?;
|
||||
Ok((removed, sorted))
|
||||
}
|
||||
|
||||
/// [`organize_offer`] over the parse, analysis and token stream the caller
|
||||
/// already has.
|
||||
///
|
||||
/// All four must be of exactly the text `files` holds for `file` — an open
|
||||
/// buffer's `Document` holds that quartet for its own bytes. A buffer that did
|
||||
/// not lex holds no tokens, but it also holds a parse diagnostic, so
|
||||
/// [`planned`] refuses it before the token stream is read.
|
||||
pub fn organize_offer_in(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
semantics: &Semantics,
|
||||
tokens: &[vlog_parser::token::Token],
|
||||
offset: u32,
|
||||
) -> Result<(usize, usize), String> {
|
||||
let scope = Scope::build(files);
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (_, _, removed, sorted) =
|
||||
planned(scope.index(), file, text, tree, diagnostics, semantics, tokens, offset)?;
|
||||
Ok((removed, sorted))
|
||||
}
|
||||
|
||||
/// The innermost scope covering the cursor that may write `import` items.
|
||||
fn scope_at<'t>(
|
||||
tree: &'t SourceFile,
|
||||
|
||||
@@ -34,9 +34,10 @@ mod source;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
use vlog_parser::{parse_source_tolerant, tokenize, ParseDiagnostic};
|
||||
|
||||
use crate::instantiate::module_definition;
|
||||
use crate::rename::{contains_word, display, Scope};
|
||||
@@ -72,10 +73,25 @@ pub struct InlineSite {
|
||||
/// sentence from the command instead.
|
||||
pub fn inline_site(text: &str, offset: u32) -> Option<InlineSite> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
inline_site_in(&tree, &diagnostics, text, offset)
|
||||
}
|
||||
|
||||
/// [`inline_site`] over a parse the caller already has.
|
||||
///
|
||||
/// The same answer, refusal on parse diagnostics included — `diagnostics`
|
||||
/// must be `tree`'s own list, and `text` the bytes both were built from
|
||||
/// (`Site::read` reads the instantiation's connections out of the source).
|
||||
/// Take 5 §P1b; see `docs/features/perf5-p1/README.md`.
|
||||
pub fn inline_site_in(
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
text: &str,
|
||||
offset: u32,
|
||||
) -> Option<InlineSite> {
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let site = Site::read(&tree, text, offset)?.ok()?;
|
||||
let site = Site::read(tree, text, offset)?.ok()?;
|
||||
Some(InlineSite {
|
||||
units: vec![site.target.clone(), site.module.name.clone()],
|
||||
module: site.target.clone(),
|
||||
|
||||
@@ -36,12 +36,16 @@ mod ports;
|
||||
mod references;
|
||||
mod rename;
|
||||
mod scope;
|
||||
mod trace;
|
||||
|
||||
pub use extract::{extract_module, extract_site, extract_title, ExtractSite, Home};
|
||||
pub use imports::{
|
||||
imported_packages, organize_counts, organize_imports, organize_title, unused_imports,
|
||||
pub use extract::{
|
||||
extract_module, extract_site, extract_site_in, extract_title, ExtractSite, Home,
|
||||
};
|
||||
pub use inline::{inline_module, inline_site, inline_title, InlineSite};
|
||||
pub use imports::{
|
||||
imported_packages, imported_packages_in, organize_counts, organize_imports, organize_offer,
|
||||
organize_offer_in, organize_title, unused_imports,
|
||||
};
|
||||
pub use inline::{inline_module, inline_site, inline_site_in, inline_title, InlineSite};
|
||||
pub use references::find_references;
|
||||
|
||||
pub use instantiate::{
|
||||
@@ -50,12 +54,15 @@ pub use instantiate::{
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, convert_to_ansi, enclosing_module, expand_wildcard, is_sites_phrase,
|
||||
may_have_port_action, port_action_modules, port_actions, propagate_ports, remove_port,
|
||||
sites_phrase, ModuleRef, PortAction,
|
||||
may_have_port_action, port_action_modules, port_action_modules_in, port_actions, port_offers,
|
||||
port_offers_in, propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction, PortOffer,
|
||||
PortOfferKind,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, rename_traced,
|
||||
RenameTarget,
|
||||
};
|
||||
pub use trace::{RenameTrace, Stage, VerifyTrace};
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
|
||||
@@ -64,8 +64,32 @@ pub(super) fn plan_convert(
|
||||
let Some((module, _)) = find_module(&tree, &name) else {
|
||||
return Err(format!("lucisv can no longer find the declaration of `{name}`."));
|
||||
};
|
||||
let ports = convert_header(file, &diagnostics, module)?;
|
||||
let site = locate_module(scope, ModuleRef::Name(&name))?;
|
||||
if site.file != i {
|
||||
return Err(elsewhere(&name));
|
||||
}
|
||||
|
||||
let mut plan = Plan::default();
|
||||
plan.add(i, convert_edits(text, file, module, &ports)?);
|
||||
plan.expected.push((i, shape(text, &name)));
|
||||
Ok(Conversion { site, plan, count: ports.len() })
|
||||
}
|
||||
|
||||
/// Everything the conversion refuses **before** it asks where the module is
|
||||
/// declared: the header it needs, the parse, a name written twice, a directive
|
||||
/// in the port list, a declaration hidden in a generate region.
|
||||
///
|
||||
/// Split out of [`plan_convert`] so the code-action offer earns the same
|
||||
/// refusals from the buffer's own parse (take 5 §P1c, `ports::offer`).
|
||||
pub(super) fn convert_header<'t>(
|
||||
file: &Path,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
module: &'t Module,
|
||||
) -> Result<Vec<&'t NonAnsiPort>, String> {
|
||||
let name = &module.name;
|
||||
let ports = header(module)?;
|
||||
unparsed(file, &diagnostics)?;
|
||||
unparsed(file, diagnostics)?;
|
||||
let names = header_names(module, &ports)?;
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(format!(
|
||||
@@ -77,28 +101,41 @@ pub(super) fn plan_convert(
|
||||
"`{name}` declares `{hidden}` inside a generate region, where lucisv will not read a port's declaration; it made no edits."
|
||||
));
|
||||
}
|
||||
let site = locate_module(scope, ModuleRef::Name(&name))?;
|
||||
if site.file != i {
|
||||
return Err(format!(
|
||||
"`{name}`'s indexed declaration is in another file than the one under the cursor; lucisv made no edits."
|
||||
));
|
||||
}
|
||||
Ok(ports)
|
||||
}
|
||||
|
||||
let absorbed = absorb(text, &name, &module.items, &names)?;
|
||||
attributes_clear(&name, &absorbed)?;
|
||||
/// The sentence a module whose indexed declaration is elsewhere earns.
|
||||
pub(super) fn elsewhere(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}`'s indexed declaration is in another file than the one under the cursor; lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
/// The conversion's edits, once the module's declaration is known to be the
|
||||
/// cursor's own file: the insertions around each header name, then the
|
||||
/// deletions of the body declarations they absorbed.
|
||||
pub(super) fn convert_edits(
|
||||
text: &str,
|
||||
file: &Path,
|
||||
module: &Module,
|
||||
ports: &[&NonAnsiPort],
|
||||
) -> Result<Vec<TextEdit>, String> {
|
||||
let name = &module.name;
|
||||
let names: Vec<String> = ports.iter().map(|port| port.name.clone()).collect();
|
||||
let absorbed = absorb(text, name, &module.items, &names)?;
|
||||
attributes_clear(name, &absorbed)?;
|
||||
directives_clear(text, file, module, &absorbed)?;
|
||||
let comments = comments_of(text, file)?;
|
||||
let mut plan = Plan::default();
|
||||
let mut edits = Vec::new();
|
||||
// One declaration may declare several ports (`input a, b;`), and its
|
||||
// comments belong to the first of them: written onto both they would be
|
||||
// duplicated, which is as much a corruption as dropping them.
|
||||
let mut claimed: Vec<TextRange> = Vec::new();
|
||||
for (port, absorbed) in ports.iter().zip(&absorbed) {
|
||||
plan.add(i, port_edits(text, &name, port, absorbed, &comments, &mut claimed)?);
|
||||
edits.append(&mut port_edits(text, name, port, absorbed, &comments, &mut claimed)?);
|
||||
}
|
||||
plan.add(i, deletions(text, &name, &absorbed, &comments)?);
|
||||
plan.expected.push((i, shape(text, &name)));
|
||||
Ok(Conversion { site, plan, count: ports.len() })
|
||||
edits.append(&mut deletions(text, name, &absorbed, &comments)?);
|
||||
Ok(edits)
|
||||
}
|
||||
|
||||
/// The non-ANSI port list this conversion needs, or the sentence saying why
|
||||
|
||||
@@ -19,7 +19,9 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{Connection, Connections, Instance, Instantiation, Item, ListElem};
|
||||
use vlog_parser::ast::{
|
||||
Connection, Connections, Instance, Instantiation, Item, ListElem, SourceFile,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::SymbolKind;
|
||||
@@ -113,16 +115,16 @@ fn directives(what: &str, list: &str) -> String {
|
||||
|
||||
/// What the cursor found: an instance, its named connection list, and which
|
||||
/// element of it is the `.*`.
|
||||
struct Wildcard<'t> {
|
||||
instantiation: &'t Instantiation,
|
||||
instance: &'t Instance,
|
||||
conns: &'t [ListElem<Connection>],
|
||||
wildcard: usize,
|
||||
pub(super) struct Wildcard<'t> {
|
||||
pub(super) instantiation: &'t Instantiation,
|
||||
pub(super) instance: &'t Instance,
|
||||
pub(super) conns: &'t [ListElem<Connection>],
|
||||
pub(super) wildcard: usize,
|
||||
}
|
||||
|
||||
/// The instantiation the cursor names and the `.*` inside it, or the sentence
|
||||
/// saying why there is none to expand.
|
||||
fn wildcard_at(items: &[Item], offset: u32) -> Result<Wildcard<'_>, String> {
|
||||
pub(super) fn wildcard_at(items: &[Item], offset: u32) -> Result<Wildcard<'_>, String> {
|
||||
let (instantiation, instance, bound) = instance_at(items, offset)?;
|
||||
if bound {
|
||||
return Err(format!(
|
||||
@@ -193,14 +195,26 @@ fn unconnected(
|
||||
let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
unparsed(path, &diagnostics)?;
|
||||
let Some((module, _)) = find_module(&tree, &site.name) else {
|
||||
return Err(not_indexed(&site.name));
|
||||
unconnected_in(path, &tree, &diagnostics, &site.name, conns)
|
||||
}
|
||||
|
||||
/// [`unconnected`] over the declaring file's parse, which the code-action
|
||||
/// offer makes once instead of once per refactoring (take 5 §P1c).
|
||||
pub(super) fn unconnected_in(
|
||||
path: &Path,
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
module: &str,
|
||||
conns: &[ListElem<Connection>],
|
||||
) -> Result<Vec<String>, String> {
|
||||
unparsed(path, diagnostics)?;
|
||||
let Some((declaration, _)) = find_module(tree, module) else {
|
||||
return Err(not_indexed(module));
|
||||
};
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(directives(&site.name, "port list"));
|
||||
if !declaration.port_directives.is_empty() {
|
||||
return Err(directives(module, "port list"));
|
||||
}
|
||||
Ok(declared_ports(module)
|
||||
Ok(declared_ports(declaration)
|
||||
.into_iter()
|
||||
.map(|port| port.name)
|
||||
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
|
||||
|
||||
@@ -27,14 +27,16 @@ mod expand;
|
||||
mod find;
|
||||
mod list;
|
||||
mod merge;
|
||||
mod offer;
|
||||
mod propagate;
|
||||
mod remove;
|
||||
|
||||
pub(crate) use find::{find_module, visible_in};
|
||||
pub use offer::{port_offers, port_offers_in, PortOffer, PortOfferKind};
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{Connections, ItemKind, Module, PortList};
|
||||
use vlog_parser::ast::{Connections, ItemKind, Module, PortList, SourceFile};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
@@ -268,6 +270,22 @@ pub fn may_have_port_action(text: &str, offset: u32) -> bool {
|
||||
/// the whole workspace. Empty for exactly the positions the gate refuses.
|
||||
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
port_action_modules_in(&tree, offset)
|
||||
}
|
||||
|
||||
/// [`port_action_modules`] over a parse the caller already has.
|
||||
///
|
||||
/// The same walk and the same answer; only the parse moves. A server holds
|
||||
/// the tolerant parse of the buffer it is answering about
|
||||
/// (`lucisv_server::state::Document`), so asking it to parse the same bytes
|
||||
/// again is a whole-file parse per cursor move — which is what take 5 §P1b
|
||||
/// removes (`docs/features/perf5-p1/README.md`).
|
||||
///
|
||||
/// `tree` must be the tolerant parse of the same text the offsets index. This
|
||||
/// selector reads **no** parse diagnostics, exactly as the text form does not:
|
||||
/// a port refactoring is offered on a buffer that does not fully parse, and
|
||||
/// the engine refuses later if it must.
|
||||
pub fn port_action_modules_in(tree: &SourceFile, offset: u32) -> Vec<String> {
|
||||
let mut instantiations = Vec::new();
|
||||
collect_instantiations(&tree.items, &mut instantiations);
|
||||
let named: Vec<String> = instantiations
|
||||
@@ -284,7 +302,7 @@ pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
||||
let mut module = None;
|
||||
module_at(&tree.items, offset, &mut module);
|
||||
let Some((name, (module, _))) =
|
||||
module.and_then(|name| Some((name.clone(), find_module(&tree, &name)?)))
|
||||
module.and_then(|name| Some((name.clone(), find_module(tree, &name)?)))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
//! Which port refactorings a cursor would be *offered*, and what each one's
|
||||
//! title promises — without a workspace index, without an analysis of any file
|
||||
//! but the cursor's own, and without verifying anything.
|
||||
//!
|
||||
//! **Why this exists.** [`super::port_actions`] answers the same question by
|
||||
//! computing all four refactorings in full and handing back their verified
|
||||
//! edits. A client that can `codeAction/resolve` throws every one of those
|
||||
//! edits away and asks for the real one when the user clicks, so the offer was
|
||||
//! paying for four `Scope::build`s — an index over the buffer and the
|
||||
//! instantiated module's declaring file, each file lexed, parsed and analyzed
|
||||
//! once per refactoring — to render a menu. Take 5 §P1b measured what that
|
||||
//! costs at one ordinary opentitan cursor: **21.15 ms of a 21.83 ms request,
|
||||
//! for zero offered actions**. See `docs/features/perf5-p1/README.md`.
|
||||
//!
|
||||
//! **What it does instead.** Each of the four is asked its *plan-time*
|
||||
//! questions — the ones that read the cursor's own file, the module's
|
||||
//! declaration, and nothing else — in the same order, with the same helpers,
|
||||
//! so the same conditions produce the same silence. The declaring file is
|
||||
//! parsed at most once and only when a refactoring needs it; the cursor's own
|
||||
//! parse and analysis come from the caller.
|
||||
//!
|
||||
//! **What it cannot see, and who does.** Two refusals live *after* the plan
|
||||
//! and are not reproduced here: [`crate::check::verify_splice`] (the token,
|
||||
//! comment and resolution comparison of the whole edit) and `ports::confirm`
|
||||
//! (reading the edited text back and requiring the port and connection lists
|
||||
//! to say what the plan promised). An offer this query makes that one of those
|
||||
//! two would refuse is answered by `codeAction/resolve`, which recomputes and
|
||||
//! verifies the whole refactoring over the module's real fan-out and says the
|
||||
//! action is no longer available. That is the offer's existing contract —
|
||||
//! "the offer may be optimistic; the resolve is exact"
|
||||
//! (`docs/features/lazy-code-action/README.md`) — and this query widens it by
|
||||
//! exactly those two checks over one or two files, nothing else.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{ItemKind, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, Semantics};
|
||||
|
||||
use crate::TextEdit;
|
||||
|
||||
use super::ansi::{convert_edits, convert_header};
|
||||
use super::expand::{unconnected_in, wildcard_at, Wildcard};
|
||||
use super::find::{declared_ports, find_module, module_at, visible_in};
|
||||
use super::list::{append_to_list, conn_list_open, elem_spans};
|
||||
use super::propagate::{connections_of, instance_at, missing_ports};
|
||||
use super::remove::{body_uses_in, disconnections_in, header_removal, port_at};
|
||||
use super::{port_action_modules_in, sites_phrase, Plan};
|
||||
|
||||
/// Which of the four port refactorings an offer names.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PortOfferKind {
|
||||
/// Remove the port under the cursor.
|
||||
Remove,
|
||||
/// Connect the ports this instantiation is missing.
|
||||
Propagate,
|
||||
/// Write out the `.*` under the cursor.
|
||||
Expand,
|
||||
/// Rewrite this Verilog-2001 header ANSI-style.
|
||||
Convert,
|
||||
}
|
||||
|
||||
/// One refactoring a cursor would be offered: the lightbulb's own words, and
|
||||
/// which refactoring will compute the edit when the user picks it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PortOffer {
|
||||
/// What the lightbulb says — byte for byte what [`super::port_actions`]
|
||||
/// would have written for the same refactoring at the same cursor.
|
||||
pub title: String,
|
||||
/// The refactoring behind the title.
|
||||
pub kind: PortOfferKind,
|
||||
}
|
||||
|
||||
/// Every port refactoring available at a position, **as a menu**: the titles,
|
||||
/// with no edit computed and nothing verified.
|
||||
///
|
||||
/// The in-scope files are the same ones [`super::port_actions`] takes, and the
|
||||
/// answer is the same list of titles at every position except where one of the
|
||||
/// two post-plan checks named in this module's own documentation would have
|
||||
/// refused.
|
||||
pub fn port_offers(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Vec<PortOffer> {
|
||||
let Some((_, text)) = files.iter().find(|(path, _)| path == file) else { return Vec::new() };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
let semantics = analyze(&tree, text);
|
||||
port_offers_in(files, file, &tree, &diagnostics, &semantics, offset)
|
||||
}
|
||||
|
||||
/// [`port_offers`] over a parse and an analysis the caller already has.
|
||||
///
|
||||
/// `tree`, `diagnostics` and `semantics` must be of exactly the text `files`
|
||||
/// holds for `file` — an open buffer's `Document` holds that trio for its own
|
||||
/// bytes, which is the whole point (take 5 §P1c). Every other file is parsed
|
||||
/// here, at most once, and only if a refactoring asks for it.
|
||||
pub fn port_offers_in(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
semantics: &Semantics,
|
||||
offset: u32,
|
||||
) -> Vec<PortOffer> {
|
||||
let Some((_, text)) = files.iter().find(|(path, _)| path == file) else { return Vec::new() };
|
||||
if port_action_modules_in(tree, offset).is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(mut sources) = Files::new(files, file) else { return Vec::new() };
|
||||
let here = Buffer { file, text, tree, diagnostics, semantics };
|
||||
|
||||
let mut out = Vec::new();
|
||||
out.extend(removal(&here, &mut sources, offset));
|
||||
out.extend(propagation(&here, &mut sources, offset));
|
||||
out.extend(expansion(&here, &mut sources, offset));
|
||||
out.extend(conversion(&here, &mut sources, offset));
|
||||
out
|
||||
}
|
||||
|
||||
/// The buffer the cursor is in, with the parse and analysis of exactly its
|
||||
/// bytes.
|
||||
struct Buffer<'a> {
|
||||
file: &'a Path,
|
||||
text: &'a str,
|
||||
tree: &'a SourceFile,
|
||||
diagnostics: &'a [ParseDiagnostic],
|
||||
semantics: &'a Semantics,
|
||||
}
|
||||
|
||||
/// Where the one declaration of a module is.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Declared {
|
||||
/// In the buffer the cursor is in.
|
||||
Here,
|
||||
/// In another in-scope file.
|
||||
In(usize),
|
||||
}
|
||||
|
||||
/// One file's tolerant parse, kept so a second refactoring asking the same
|
||||
/// question does not pay for it again.
|
||||
struct Parsed {
|
||||
tree: SourceFile,
|
||||
diagnostics: Vec<ParseDiagnostic>,
|
||||
}
|
||||
|
||||
/// The in-scope files, normalized exactly the way [`crate::scope::Scope`]
|
||||
/// normalizes them, parsed one at a time and only on demand.
|
||||
struct Files<'a> {
|
||||
sources: Vec<(&'a Path, &'a str)>,
|
||||
/// Index of the buffer the cursor is in.
|
||||
here: usize,
|
||||
parsed: Vec<Option<Parsed>>,
|
||||
}
|
||||
|
||||
impl<'a> Files<'a> {
|
||||
fn new(files: &'a [(PathBuf, String)], file: &Path) -> Option<Files<'a>> {
|
||||
let mut sources: Vec<(&Path, &str)> =
|
||||
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
|
||||
// `Scope::build`'s own normalization, so "which file declares this"
|
||||
// is asked of the same set the eager path asks it of.
|
||||
sources.sort_by(|a, b| a.0.cmp(b.0));
|
||||
sources.dedup_by(|a, b| a.0 == b.0);
|
||||
let here = sources.iter().position(|(path, _)| *path == file)?;
|
||||
let parsed = sources.iter().map(|_| None).collect();
|
||||
Some(Files { sources, here, parsed })
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.sources.len()
|
||||
}
|
||||
|
||||
/// One file's parse, computed on first use. Never called for the buffer:
|
||||
/// its parse is the caller's.
|
||||
fn parsed(&mut self, i: usize) -> Option<&Parsed> {
|
||||
let (_, text) = *self.sources.get(i)?;
|
||||
let slot = self.parsed.get_mut(i)?;
|
||||
if slot.is_none() {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
*slot = Some(Parsed { tree, diagnostics });
|
||||
}
|
||||
slot.as_ref()
|
||||
}
|
||||
|
||||
/// Which in-scope file declares `name`, or nothing when the files declare
|
||||
/// it twice or not at all.
|
||||
///
|
||||
/// This is `find::locate_module`'s question — `WorkspaceIndex::units(name)`
|
||||
/// filtered by `SymbolKind::is_instantiable`, of which there must be
|
||||
/// exactly one — asked of the parses instead of an index. A unit is a
|
||||
/// **file-scope** declaration, and every file-scope `module`, `interface`
|
||||
/// or `program` item is bound as `SymbolKind::Module` or
|
||||
/// `SymbolKind::Interface` (`vlog_semantic::bind::item::bind_module`), so
|
||||
/// the two counts are the same count. A module nested inside another
|
||||
/// module or a package is not a unit, and is not one here either.
|
||||
fn declaring(&mut self, tree: &SourceFile, name: &str) -> Option<Declared> {
|
||||
let mut found = None;
|
||||
let mut units = 0usize;
|
||||
for i in 0..self.sources.len() {
|
||||
let (_, text) = *self.sources.get(i)?;
|
||||
let here = i == self.here;
|
||||
// A file whose bytes never spell the name declares nothing by it,
|
||||
// so it need not be parsed to be ruled out.
|
||||
if !here && !text.contains(name) {
|
||||
continue;
|
||||
}
|
||||
let n = match here {
|
||||
true => units_named(tree, name),
|
||||
false => self.parsed(i).map_or(0, |parsed| units_named(&parsed.tree, name)),
|
||||
};
|
||||
if n > 0 {
|
||||
units += n;
|
||||
found = Some(match here {
|
||||
true => Declared::Here,
|
||||
false => Declared::In(i),
|
||||
});
|
||||
}
|
||||
}
|
||||
(units == 1).then_some(found)?
|
||||
}
|
||||
|
||||
/// The parse of the file declaring a module, and how it is named in a
|
||||
/// refusal.
|
||||
fn declaration<'s, 'b: 's>(
|
||||
&'s mut self,
|
||||
buffer: &'b Buffer<'b>,
|
||||
at: Declared,
|
||||
) -> Option<(&'s Path, &'s SourceFile, &'s [ParseDiagnostic])> {
|
||||
match at {
|
||||
Declared::Here => Some((buffer.file, buffer.tree, buffer.diagnostics)),
|
||||
Declared::In(i) => {
|
||||
let (path, _) = *self.sources.get(i)?;
|
||||
let parsed = self.parsed(i)?;
|
||||
Some((path, &parsed.tree, &parsed.diagnostics))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's share of a removal: the refusal it may earn, and how many
|
||||
/// instantiations it would rewrite.
|
||||
fn disconnections(
|
||||
&mut self,
|
||||
buffer: &Buffer<'_>,
|
||||
i: usize,
|
||||
module: &str,
|
||||
port: &str,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Result<(Vec<TextEdit>, usize), String> {
|
||||
let Some((path, text)) = self.sources.get(i).copied() else { return Ok((Vec::new(), 0)) };
|
||||
if !text.contains(module) {
|
||||
return Ok((Vec::new(), 0));
|
||||
}
|
||||
if i == self.here {
|
||||
return disconnections_in(text, path, buffer.tree, module, port, warnings);
|
||||
}
|
||||
match self.parsed(i) {
|
||||
Some(parsed) => disconnections_in(text, path, &parsed.tree, module, port, warnings),
|
||||
None => Ok((Vec::new(), 0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many file-scope module or interface declarations of `name` a parse
|
||||
/// holds — see [`Files::declaring`] for why that is the index's own count.
|
||||
fn units_named(tree: &SourceFile, name: &str) -> usize {
|
||||
tree.items
|
||||
.iter()
|
||||
.filter(|item| match &item.kind {
|
||||
ItemKind::Module(module) => module.name == name && !module.name_span.is_empty(),
|
||||
_ => false,
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// A settled plan's edits, or nothing where `finish` would have refused before
|
||||
/// verifying: two edits that overlap, or no edit at all.
|
||||
fn settled(plan: &mut Plan) -> Option<usize> {
|
||||
plan.settle().ok()?;
|
||||
let edits: usize = plan.edits.iter().map(|(_, file)| file.len()).sum();
|
||||
(edits > 0).then_some(edits)
|
||||
}
|
||||
|
||||
/// "remove port `p`" — `plan_remove`'s decisions over the buffer's own parse
|
||||
/// and analysis.
|
||||
///
|
||||
/// The count is this query's own census of the instantiations it can see,
|
||||
/// which is what the eager title counts too; a server that has read no fan-out
|
||||
/// replaces the phrase with its index's count (`ports::counted`).
|
||||
fn removal(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<PortOffer> {
|
||||
let (module_name, port) = port_at(buffer.tree, offset).ok()?;
|
||||
if files.declaring(buffer.tree, &module_name)? != Declared::Here {
|
||||
return None;
|
||||
}
|
||||
let (module, _) = find_module(buffer.tree, &module_name)?;
|
||||
let ports = declared_ports(module);
|
||||
let index = ports.iter().position(|declared| declared.name == port)?;
|
||||
let header = header_removal(buffer.text, module, &ports, index, &port).ok()?;
|
||||
if !body_uses_in(buffer.text, buffer.semantics, module, &port, &header).is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut plan = Plan::default();
|
||||
plan.add(files.here, header);
|
||||
let mut warnings = Vec::new();
|
||||
for i in 0..files.len() {
|
||||
let (edits, sites) =
|
||||
files.disconnections(buffer, i, &module_name, &port, &mut warnings).ok()?;
|
||||
plan.sites += sites;
|
||||
plan.add(i, edits);
|
||||
}
|
||||
settled(&mut plan)?;
|
||||
Some(PortOffer {
|
||||
title: format!("lucisv: remove port `{port}` ({})", sites_phrase(plan.sites)),
|
||||
kind: PortOfferKind::Remove,
|
||||
})
|
||||
}
|
||||
|
||||
/// "connect N missing ports" — `plan_propagate`'s decisions, and its own
|
||||
/// append loop, which is what decides N: a connection written after a `//`
|
||||
/// comment takes two edits rather than one, and the title counts edits.
|
||||
fn propagation(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<PortOffer> {
|
||||
let (instantiation, instance) = instance_at(buffer.tree, offset).ok()?;
|
||||
let module_name = instantiation.module.clone();
|
||||
let at = files.declaring(buffer.tree, &module_name)?;
|
||||
let conns = connections_of(instantiation, instance).ok()?;
|
||||
let missing = {
|
||||
let (_, tree, _) = files.declaration(buffer, at)?;
|
||||
let (declaration, _) = find_module(tree, &module_name)?;
|
||||
missing_ports(declaration, conns)
|
||||
};
|
||||
if missing.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
|
||||
let open = conn_list_open(buffer.text, instance, spans.first().copied())?;
|
||||
let cursor = instance.name_span.start;
|
||||
let mut edits = Vec::new();
|
||||
for name in &missing {
|
||||
let expr = match visible_in(buffer.semantics, cursor, name) {
|
||||
true => name.clone(),
|
||||
false => "/* TODO: connect */".to_string(),
|
||||
};
|
||||
let mut written =
|
||||
append_to_list(buffer.text, Some(open), &spans, &format!(".{name}({expr})"));
|
||||
// Each connection is appended after the previous one, so the next
|
||||
// append sees it as the list's last element.
|
||||
let start = written.last().map_or(open, |edit| edit.range.start);
|
||||
spans.push(TextRange::new(start, start));
|
||||
edits.append(&mut written);
|
||||
}
|
||||
let mut plan = Plan::default();
|
||||
plan.add(files.here, edits);
|
||||
let count = settled(&mut plan)?;
|
||||
Some(PortOffer {
|
||||
title: format!("lucisv: connect {count} missing port{}", if count == 1 { "" } else { "s" }),
|
||||
kind: PortOfferKind::Propagate,
|
||||
})
|
||||
}
|
||||
|
||||
/// "expand .* (N connections)" — `plan_expand`'s decisions. N is the number of
|
||||
/// ports the wildcard stands for, which the declaration alone decides; whether
|
||||
/// each is bound only changes what is written, never how many.
|
||||
fn expansion(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<PortOffer> {
|
||||
if !buffer.diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let Wildcard { instantiation, instance, conns, wildcard } =
|
||||
wildcard_at(&buffer.tree.items, offset).ok()?;
|
||||
if !instance.conn_directives.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let module_name = instantiation.module.clone();
|
||||
let at = files.declaring(buffer.tree, &module_name)?;
|
||||
let missing = {
|
||||
let (path, tree, diagnostics) = files.declaration(buffer, at)?;
|
||||
unconnected_in(path, tree, diagnostics, &module_name, conns).ok()?
|
||||
};
|
||||
if missing.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
|
||||
conn_list_open(buffer.text, instance, spans.first().copied())?;
|
||||
spans.get(wildcard)?;
|
||||
let count = missing.len();
|
||||
Some(PortOffer {
|
||||
title: format!(
|
||||
"lucisv: expand .* ({count} connection{})",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
kind: PortOfferKind::Expand,
|
||||
})
|
||||
}
|
||||
|
||||
/// "convert ports to ANSI (N ports)" — `plan_convert`'s decisions, in its own
|
||||
/// order: the header refusals first, then where the module is declared, then
|
||||
/// the merge.
|
||||
fn conversion(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<PortOffer> {
|
||||
let mut found = None;
|
||||
module_at(&buffer.tree.items, offset, &mut found);
|
||||
let name = found?;
|
||||
let (module, _) = find_module(buffer.tree, &name)?;
|
||||
let ports = convert_header(buffer.file, buffer.diagnostics, module).ok()?;
|
||||
if files.declaring(buffer.tree, &name)? != Declared::Here {
|
||||
return None;
|
||||
}
|
||||
let edits = convert_edits(buffer.text, buffer.file, module, &ports).ok()?;
|
||||
let mut plan = Plan::default();
|
||||
plan.add(files.here, edits);
|
||||
settled(&mut plan)?;
|
||||
let count = ports.len();
|
||||
Some(PortOffer {
|
||||
title: format!(
|
||||
"lucisv: convert ports to ANSI ({count} port{})",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
kind: PortOfferKind::Convert,
|
||||
})
|
||||
}
|
||||
@@ -5,7 +5,9 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{Connections, Instance, Instantiation, ListElem};
|
||||
use vlog_parser::ast::{
|
||||
Connection, Connections, Instance, Instantiation, ListElem, Module, SourceFile,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex};
|
||||
|
||||
@@ -19,19 +21,17 @@ use super::find::{
|
||||
use super::list::{append_to_list, conn_list_open, elem_spans};
|
||||
use super::{shape, ModuleRef, Plan};
|
||||
|
||||
pub(super) fn plan_propagate(
|
||||
scope: &mut Scope,
|
||||
file: &Path,
|
||||
/// The instance under the cursor, or the only one of the instantiation the
|
||||
/// cursor's module name belongs to.
|
||||
///
|
||||
/// Read off one file's parse, so the code-action offer asks it of the buffer's
|
||||
/// own tree (take 5 §P1c, `ports::offer`).
|
||||
pub(super) fn instance_at(
|
||||
tree: &SourceFile,
|
||||
offset: u32,
|
||||
) -> Result<(ModuleSite, Plan), String> {
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
) -> Result<(&Instantiation, &Instance), String> {
|
||||
let mut instantiations = Vec::new();
|
||||
collect_instantiations(&tree.items, &mut instantiations);
|
||||
|
||||
// The instance under the cursor, or the only one of the instantiation the
|
||||
// cursor's module name belongs to.
|
||||
let mut found: Option<(&Instantiation, &Instance)> = None;
|
||||
for instantiation in &instantiations {
|
||||
for instance in &instantiation.instances {
|
||||
@@ -50,11 +50,15 @@ pub(super) fn plan_propagate(
|
||||
found = Some((instantiation, only));
|
||||
}
|
||||
}
|
||||
let Some((instantiation, instance)) = found else {
|
||||
return Err("there is no module instantiation at this position.".to_string());
|
||||
};
|
||||
let site = locate_module(scope, ModuleRef::Name(&instantiation.module))?;
|
||||
found.ok_or_else(|| "there is no module instantiation at this position.".to_string())
|
||||
}
|
||||
|
||||
/// The named connection list a propagation can append to, or the sentence
|
||||
/// saying why this instance has none.
|
||||
pub(super) fn connections_of<'t>(
|
||||
instantiation: &Instantiation,
|
||||
instance: &'t Instance,
|
||||
) -> Result<&'t [ListElem<Connection>], String> {
|
||||
let conns = match &instance.conns {
|
||||
Connections::Ordered(_) => {
|
||||
return Err(format!(
|
||||
@@ -62,7 +66,7 @@ pub(super) fn plan_propagate(
|
||||
instance.name, instantiation.module
|
||||
))
|
||||
}
|
||||
Connections::Named(conns) => conns,
|
||||
Connections::Named(conns) => conns.as_slice(),
|
||||
};
|
||||
// An error element names no port: it neither connects one nor blocks one.
|
||||
if conns.iter().filter_map(ListElem::ok).any(|c| c.name == "*") {
|
||||
@@ -71,18 +75,37 @@ pub(super) fn plan_propagate(
|
||||
instance.name
|
||||
));
|
||||
}
|
||||
Ok(conns)
|
||||
}
|
||||
|
||||
/// The ports the instantiated module declares that this instance does not
|
||||
/// connect, in declaration order.
|
||||
pub(super) fn missing_ports(module: &Module, conns: &[ListElem<Connection>]) -> Vec<String> {
|
||||
declared_ports(module)
|
||||
.iter()
|
||||
.map(|p| p.name.clone())
|
||||
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn plan_propagate(
|
||||
scope: &mut Scope,
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(ModuleSite, Plan), String> {
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let (instantiation, instance) = instance_at(&tree, offset)?;
|
||||
let site = locate_module(scope, ModuleRef::Name(&instantiation.module))?;
|
||||
let conns = connections_of(instantiation, instance)?;
|
||||
|
||||
let Some(module_text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let (module_tree, _) = parse_source_tolerant(module_text);
|
||||
let Some((module, _)) = find_module(&module_tree, &site.name) else {
|
||||
return Err(not_indexed(&site.name));
|
||||
};
|
||||
let declared = declared_ports(module);
|
||||
let missing: Vec<String> = declared
|
||||
.iter()
|
||||
.map(|p| p.name.clone())
|
||||
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
|
||||
.collect();
|
||||
let missing = missing_ports(module, conns);
|
||||
if missing.is_empty() {
|
||||
return Err(format!(
|
||||
"`{}` already connects every port `{}` declares.",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{Connections, ItemKind, ListElem, Module, PortList};
|
||||
use vlog_parser::ast::{Connections, ItemKind, ListElem, Module, PortList, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex};
|
||||
use vlog_semantic::SymbolKind;
|
||||
@@ -31,12 +31,27 @@ pub(super) fn locate_port(
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let (module_name, name) = port_at(&tree, offset)?;
|
||||
let site = locate_module(scope, ModuleRef::Name(&module_name))?;
|
||||
if site.file != i {
|
||||
return Err(ambiguous(&module_name));
|
||||
}
|
||||
Ok((site, name))
|
||||
}
|
||||
|
||||
/// The module and port name the cursor sits on, read off one file's parse —
|
||||
/// [`locate_port`] without the workspace half.
|
||||
///
|
||||
/// The cursor may be on the header port or, for a non-ANSI module, on its body
|
||||
/// declaration. Split out so the code-action *offer* can ask the same question
|
||||
/// of the buffer's own parse (take 5 §P1c, `ports::offer`).
|
||||
pub(super) fn port_at(tree: &SourceFile, offset: u32) -> Result<(String, String), String> {
|
||||
let mut module_name = None;
|
||||
module_at(&tree.items, offset, &mut module_name);
|
||||
let Some(module_name) = module_name else {
|
||||
return Err(NOT_A_PORT.to_string());
|
||||
};
|
||||
let Some((module, _)) = find_module(&tree, &module_name) else {
|
||||
let Some((module, _)) = find_module(tree, &module_name) else {
|
||||
return Err(NOT_A_PORT.to_string());
|
||||
};
|
||||
let ports = declared_ports(module);
|
||||
@@ -59,13 +74,14 @@ pub(super) fn locate_port(
|
||||
}
|
||||
}
|
||||
let Some(name) = name else { return Err(NOT_A_PORT.to_string()) };
|
||||
let site = locate_module(scope, ModuleRef::Name(&module_name))?;
|
||||
if site.file != i {
|
||||
return Err(format!(
|
||||
"`{module_name}` is declared in more than one indexed file; lucisv will not guess which module's ports these are."
|
||||
));
|
||||
}
|
||||
Ok((site, name))
|
||||
Ok((module_name, name))
|
||||
}
|
||||
|
||||
/// The sentence a module the in-scope files declare twice earns.
|
||||
pub(super) fn ambiguous(module: &str) -> String {
|
||||
format!(
|
||||
"`{module}` is declared in more than one indexed file; lucisv will not guess which module's ports these are."
|
||||
)
|
||||
}
|
||||
|
||||
const NOT_A_PORT: &str = "there is no module port at this position.";
|
||||
@@ -86,13 +102,13 @@ pub(super) fn plan_remove(
|
||||
return Err(format!("`{}` has no port named `{port}`.", site.name));
|
||||
};
|
||||
|
||||
let mut header: Vec<TextEdit> = remove_element(text, &element_spans(&ports), index)?;
|
||||
if matches!(module.ports, PortList::NonAnsi(_)) {
|
||||
header.append(&mut non_ansi_declaration_removal(text, module, port)?);
|
||||
}
|
||||
let header: Vec<TextEdit> = header_removal(text, module, &ports, index, port)?;
|
||||
// A port still used by the module's own body is a refusal, not a warning:
|
||||
// deleting it would leave the body naming something that no longer exists.
|
||||
let used = body_uses(scope, site.file, module, port, &header);
|
||||
let used = match scope.analysis(site.file) {
|
||||
Some(analysis) => body_uses_in(text, &analysis.semantics, module, port, &header),
|
||||
None => Vec::new(),
|
||||
};
|
||||
if !used.is_empty() {
|
||||
return Err(format!(
|
||||
"`{port}` is still used inside `{}` at {}:{}; remove those uses first.",
|
||||
@@ -169,19 +185,38 @@ fn preprocessor_warnings(scope: &Scope, file: usize, port: &str) -> Vec<String>
|
||||
out
|
||||
}
|
||||
|
||||
/// The header and body deletions the removal makes in the module's own file.
|
||||
///
|
||||
/// Split out of [`plan_remove`] so the code-action offer can make exactly the
|
||||
/// same two decisions — and earn exactly the same refusals — without a
|
||||
/// workspace (take 5 §P1c).
|
||||
pub(super) fn header_removal(
|
||||
text: &str,
|
||||
module: &Module,
|
||||
ports: &[super::find::DeclaredPort],
|
||||
index: usize,
|
||||
port: &str,
|
||||
) -> Result<Vec<TextEdit>, String> {
|
||||
let mut header = remove_element(text, &element_spans(ports), index)?;
|
||||
if matches!(module.ports, PortList::NonAnsi(_)) {
|
||||
header.append(&mut non_ansi_declaration_removal(text, module, port)?);
|
||||
}
|
||||
Ok(header)
|
||||
}
|
||||
|
||||
/// The lines of the module's body that still name the port, ignoring the
|
||||
/// declarations the removal is itself deleting.
|
||||
fn body_uses(
|
||||
scope: &mut Scope,
|
||||
file: usize,
|
||||
///
|
||||
/// `semantics` must be the analysis of `text` — [`Scope::analysis`]'s, or the
|
||||
/// open buffer's own, which is the same thing computed once instead of twice.
|
||||
pub(super) fn body_uses_in(
|
||||
text: &str,
|
||||
semantics: &vlog_semantic::Semantics,
|
||||
module: &Module,
|
||||
port: &str,
|
||||
removed: &[TextEdit],
|
||||
) -> Vec<String> {
|
||||
let Some(text) = scope.text(file) else { return Vec::new() };
|
||||
let lines = LineIndex::new(text);
|
||||
let Some(analysis) = scope.analysis(file) else { return Vec::new() };
|
||||
let semantics = &analysis.semantics;
|
||||
let Some(symbol) = semantics.symbols().iter().position(|s| {
|
||||
s.name == port
|
||||
&& s.kind == SymbolKind::Port
|
||||
@@ -248,13 +283,27 @@ fn disconnection_edits(
|
||||
return Ok((Vec::new(), 0));
|
||||
}
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
disconnections_in(text, path, &tree, &site.name, port, warnings)
|
||||
}
|
||||
|
||||
/// [`disconnection_edits`] over a parse the caller already has, so the offer
|
||||
/// can earn the by-position refusal and count the sites it would rewrite
|
||||
/// without building a workspace (take 5 §P1c).
|
||||
pub(super) fn disconnections_in(
|
||||
text: &str,
|
||||
path: &Path,
|
||||
tree: &SourceFile,
|
||||
module: &str,
|
||||
port: &str,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Result<(Vec<TextEdit>, usize), String> {
|
||||
let mut instantiations = Vec::new();
|
||||
collect_instantiations(&tree.items, &mut instantiations);
|
||||
let lines = LineIndex::new(text);
|
||||
|
||||
let mut edits = Vec::new();
|
||||
let mut sites = 0usize;
|
||||
for instantiation in instantiations.iter().filter(|i| i.module == site.name) {
|
||||
for instantiation in instantiations.iter().filter(|i| i.module == module) {
|
||||
for instance in &instantiation.instances {
|
||||
match &instance.conns {
|
||||
Connections::Ordered(conns) if conns.is_empty() => {}
|
||||
@@ -263,7 +312,7 @@ fn disconnection_edits(
|
||||
"`{}` in {} connects `{}`'s ports by position; dropping one would silently re-bind the rest, so lucisv made no edits — give it named connections first.",
|
||||
instance.name,
|
||||
display(path),
|
||||
site.name
|
||||
module
|
||||
))
|
||||
}
|
||||
Connections::Named(conns) => {
|
||||
|
||||
@@ -31,6 +31,7 @@ use vlog_semantic::{
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::trace::RenameTrace;
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
|
||||
/// The identifier a rename would act on: where it is, and what it spells.
|
||||
@@ -155,17 +156,68 @@ pub fn rename(
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
rename_traced(files, file, offset, new_name, &mut RenameTrace::default())
|
||||
}
|
||||
|
||||
/// [`rename`], with a [`RenameTrace`] filled in as it runs.
|
||||
///
|
||||
/// The same call — `rename` is this one with a trace nobody reads — so there
|
||||
/// is no traced path that could decide anything differently from the plain
|
||||
/// one. The trace is an **out parameter** rather than part of the `Ok` value
|
||||
/// because the stage a slow *refusal* spent its time in is exactly as
|
||||
/// interesting as a successful rename's: a conflicting new name refuses inside
|
||||
/// `collect_edits`, and the extract offer that costs 800 ms refuses after the
|
||||
/// scope build alone (take 5 §P2a).
|
||||
pub fn rename_traced(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
trace: &mut RenameTrace,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
let started = vlog_parser::stats::parses();
|
||||
let out = renaming(files, file, offset, new_name, trace);
|
||||
trace.parses = vlog_parser::stats::parses() - started;
|
||||
out
|
||||
}
|
||||
|
||||
/// The rename itself, so that [`rename_traced`] can count the parses of the
|
||||
/// whole of it — refusals included — in one place.
|
||||
fn renaming(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
trace: &mut RenameTrace,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
check_new_name(new_name)?;
|
||||
let mut scope = Scope::build(files);
|
||||
let target = scope.locate(file, offset)?;
|
||||
trace.selected = files.len();
|
||||
trace.bytes = files.iter().map(|(_, text)| text.len()).sum();
|
||||
// One parse per file, and the analyses this rename is going to want kept
|
||||
// from it (take 5 §P2b). The words worth keeping are the new name and the
|
||||
// name under the cursor — which the request file's own analysis, the first
|
||||
// one the build makes, is what says. A wrong guess costs a re-parse and
|
||||
// can change nothing: retention is a cache.
|
||||
let mut scope = trace.index.measure(|| {
|
||||
Scope::build_keeping(files, file, |here| {
|
||||
let cursor = here.and_then(|semantics| rename_name_at(semantics, offset));
|
||||
cursor.into_iter().chain(Some(new_name.to_string())).collect()
|
||||
})
|
||||
});
|
||||
trace.selected = scope.len();
|
||||
let target = trace.locate.measure(|| scope.locate(file, offset))?;
|
||||
if target.name == new_name {
|
||||
return Err(format!("`{new_name}` is the name it already has."));
|
||||
}
|
||||
let edits = scope.collect_edits(&target, new_name)?;
|
||||
check::verify(&mut scope, &edits, &target.name, new_name)?;
|
||||
let edits = trace.edits.measure(|| scope.collect_edits(&target, new_name))?;
|
||||
trace.edited = edits.len();
|
||||
// Two disjoint fields of one trace: `verify` times the whole pass while
|
||||
// `checks` is filled by its stages, so they are borrowed apart.
|
||||
let RenameTrace { verify, checks, .. } = &mut *trace;
|
||||
verify.measure(|| check::verify(&mut scope, &edits, &target.name, new_name, checks))?;
|
||||
|
||||
let warnings = scope.warnings(&target, &edits);
|
||||
let warnings = trace.warnings.measure(|| scope.warnings(&target, &edits));
|
||||
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
|
||||
.into_iter()
|
||||
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
|
||||
|
||||
@@ -195,3 +195,141 @@ fn the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the trace (take 5 §P2a)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_traced_rename_and_the_plain_one_are_the_same_call() {
|
||||
let sources = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
let mut trace = RenameTrace::default();
|
||||
let traced = rename_traced(&sources, &path, at, "child", &mut trace).expect("renames");
|
||||
let plain = rename(&sources, &path, at, "child").expect("renames");
|
||||
assert_eq!(traced.edits, plain.edits, "same edits");
|
||||
assert_eq!(traced.warnings, plain.warnings, "same warnings");
|
||||
assert_eq!(traced.created, plain.created, "same created files");
|
||||
// And a refusal is traced too, which is why the trace is an out parameter.
|
||||
let mut refused = RenameTrace::default();
|
||||
let outcome = rename_traced(&sources, &path, at, "module", &mut refused);
|
||||
assert!(outcome.is_err(), "a keyword must refuse");
|
||||
assert_eq!(refused.selected, 0, "the refusal is taken before the scope is built");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trace_accounts_for_every_parse_the_rename_ran() {
|
||||
let sources = workspace(&[("sub.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG)]);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
let mut trace = RenameTrace::default();
|
||||
rename_traced(&sources, &path, at, "child", &mut trace).expect("renames");
|
||||
let staged = trace.index.parses
|
||||
+ trace.locate.parses
|
||||
+ trace.edits.parses
|
||||
+ trace.verify.parses
|
||||
+ trace.warnings.parses;
|
||||
assert_eq!(staged, trace.parses, "every parse belongs to a stage: {trace:?}");
|
||||
assert_eq!(
|
||||
trace.verify.parses,
|
||||
trace.checks.tokens.parses
|
||||
+ trace.checks.before.parses
|
||||
+ trace.checks.rebuild.parses
|
||||
+ trace.checks.after.parses
|
||||
+ trace.checks.checks.parses,
|
||||
"and every verification parse to a sub-stage: {trace:?}"
|
||||
);
|
||||
assert_eq!(trace.selected, 3, "three files in, whatever the rename does with them");
|
||||
assert_eq!(trace.bytes, sources.iter().map(|(_, t)| t.len()).sum::<usize>());
|
||||
assert!(trace.edited >= 1 && trace.edited <= trace.selected);
|
||||
assert!(trace.checks.watched >= trace.edited, "a watched set covers the edited one");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the reuse (take 5 §P2b/§P2c) — the parse budget, and three attacks on it
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A workspace of eight files. `sig` is declared in `sub.sv`, named through
|
||||
/// the hierarchy from `top.sv`, and merely mentioned in three others, so a
|
||||
/// rename of it edits two files and watches five.
|
||||
const EIGHT: [(&str, &str); 8] = [
|
||||
("/w/sub.sv", "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n"),
|
||||
("/w/top.sv", "module top;\n logic w;\n sub u_sub (.clk(1'b0), .q(w));\n assign w = u_sub.sig;\nendmodule\n"),
|
||||
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
||||
("/w/user.sv", "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n"),
|
||||
("/w/note.sv", "module note;\n // sig is mentioned here in a comment\n logic other;\nendmodule\n"),
|
||||
("/w/far.sv", "module far;\n logic sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("/w/quiet_a.sv", "module quiet_a;\n logic a;\nendmodule\n"),
|
||||
("/w/quiet_b.sv", "module quiet_b;\n logic b;\nendmodule\n"),
|
||||
];
|
||||
|
||||
/// **K + E.** One whole-file parse per input file, plus one per edited file —
|
||||
/// and not one more, whatever the watched set costs.
|
||||
///
|
||||
/// The counts come out of the trace, so the assertion is on the work the
|
||||
/// engine really did rather than on a stopwatch. Before §P2b/§P2c this same
|
||||
/// rename parsed `K` for the index, again for every file spelling the name,
|
||||
/// `K` again for the after-index and once more for every watched file.
|
||||
#[test]
|
||||
fn a_rename_parses_each_input_file_once_and_each_edited_file_once_more() {
|
||||
let sources = workspace(&EIGHT);
|
||||
let path = PathBuf::from("/w/sub.sv");
|
||||
let text = EIGHT[0].1;
|
||||
let at = text.find("wire sig").expect("the declaration") as u32 + 5;
|
||||
let mut trace = RenameTrace::default();
|
||||
rename_traced(&sources, &path, at, "renamed_sig", &mut trace).expect("renames");
|
||||
|
||||
let (k, e) = (trace.selected as u64, trace.edited as u64);
|
||||
assert_eq!(k, 8, "eight files in");
|
||||
assert_eq!(e, 2, "sub.sv and top.sv are edited");
|
||||
assert!(trace.checks.watched >= 4, "and several more are watched: {trace:?}");
|
||||
assert_eq!(trace.parses, k + e, "K + E and nothing else: {trace:?}");
|
||||
assert_eq!(trace.index.parses, k, "every input file, once, for the index");
|
||||
assert_eq!(trace.locate.parses, 0, "the cursor's file was kept");
|
||||
assert_eq!(trace.edits.parses, 0, "so was every file the occurrence walk reads");
|
||||
assert_eq!(trace.checks.before.parses, 0, "and every watched file");
|
||||
assert_eq!(trace.checks.rebuild.parses, e, "the after-index absorbs, it does not rebuild");
|
||||
assert_eq!(trace.checks.after.parses, 0, "and its analyses are that absorb's own");
|
||||
}
|
||||
|
||||
/// **Attack 1 — a stale retained analysis.** The reuse hands the *edited*
|
||||
/// file's after-print the analysis of its **edited** text. An implementation
|
||||
/// that handed it the retained before-analysis instead would be describing
|
||||
/// text that no longer exists, and this rename — whose edit changes what a
|
||||
/// name in the edited file resolves to — is exactly the one it would wave
|
||||
/// through.
|
||||
#[test]
|
||||
fn a_rename_whose_edit_rebinds_a_name_in_the_edited_file_is_refused() {
|
||||
// `taken` is already declared in `m`. Renaming `sig` to `taken` would
|
||||
// give `assign q = taken;` a different declaration — in the very file the
|
||||
// edit touches, so only a print of the *edited* text can see it.
|
||||
const CAPTURE: &str = "module m (output logic q);\n wire sig;\n wire taken;\n assign q = sig;\n assign taken = 1'b1;\nendmodule\n";
|
||||
let sources = workspace(&[("/w/m.sv", CAPTURE)]);
|
||||
let path = PathBuf::from("/w/m.sv");
|
||||
let at = CAPTURE.find("wire sig").expect("the declaration") as u32 + 5;
|
||||
let outcome = rename(&sources, &path, at, "taken");
|
||||
assert!(outcome.is_err(), "a capture inside the edited file must refuse: {outcome:?}");
|
||||
}
|
||||
|
||||
/// **Attack 2 — an after-index that forgot an unedited file.** The after-index
|
||||
/// is the before-index with the edited records absorbed; absorbing with the
|
||||
/// wrong `gone`, or building it from the edited files alone, would drop the
|
||||
/// third file's declaration and the ambiguity it creates with it. The rename
|
||||
/// below edits `a.sv` and `top.sv` and is refused **because of `b.sv`**, which
|
||||
/// it never touches.
|
||||
#[test]
|
||||
fn a_rename_that_would_make_a_third_files_use_ambiguous_is_refused() {
|
||||
const A: &str = "package a_pkg;\n localparam int V = 1;\nendpackage\n";
|
||||
const B: &str = "package taken_pkg;\n localparam int V = 2;\nendpackage\n";
|
||||
const USE: &str = "import taken_pkg::*;\nmodule u;\n localparam int W = V;\nendmodule\n";
|
||||
let files = [("/w/a.sv", A), ("/w/b.sv", B), ("/w/use.sv", USE)];
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("/w/a.sv");
|
||||
let at = A.find("a_pkg").expect("the package name") as u32;
|
||||
let outcome = rename(&sources, &path, at, "taken_pkg");
|
||||
assert!(outcome.is_err(), "a second `taken_pkg` makes use.sv's import ambiguous: {outcome:?}");
|
||||
// And the untouched declaration is still there to be found afterwards:
|
||||
// the refusal is about `use.sv`, not about `a.sv` alone.
|
||||
assert!(rename(&sources, &path, at, "b_pkg").is_ok(), "an unclaimed name still renames");
|
||||
}
|
||||
@@ -1,16 +1,26 @@
|
||||
//! What a rename could not account for, said out loud: the name inside a
|
||||
//! `` `define`` or a macro invocation's opaque token, inside an assertion the
|
||||
//! SVA grammar could not structure, a reference the workspace could not
|
||||
//! finish, and identifier occurrences no reference was recorded for — each
|
||||
//! found by its own scan of the file, and each a sentence naming where to
|
||||
//! look. The `` `define`` and macro-argument scans are shared with the port
|
||||
//! refactorings, which word their news differently.
|
||||
//! finish, and identifier occurrences no reference was recorded for — each its
|
||||
//! own scan, and each a sentence naming where to look. The `` `define`` and
|
||||
//! macro-argument scans are shared with the port refactorings, which word
|
||||
//! their news differently.
|
||||
//!
|
||||
//! **One lex and one line index per file** (take 5 §P2d's `warnings` finding).
|
||||
//! The five scans used to build their own, so a file spelling the name was
|
||||
//! tokenized twice and indexed four times inside one `warnings` call — none of
|
||||
//! it shared, and none of it the parse the scope had already made. [`FileScan`]
|
||||
//! is that memo. It is a cache of two pure functions of the file's text and
|
||||
//! nothing else, so a scan handed a shared one reads exactly what its own call
|
||||
//! would have built; what each scan *says* is untouched, and the sentences come
|
||||
//! out in the order they always did.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::{tokenize, LineIndex};
|
||||
use vlog_semantic::{ExternalTarget, ReferenceId, Resolution};
|
||||
|
||||
@@ -19,37 +29,116 @@ use crate::TextEdit;
|
||||
use super::Target;
|
||||
use crate::scope::{display, Scope};
|
||||
|
||||
/// One file's token stream and its line index, built at most once per
|
||||
/// [`Scope::warnings`] call and lent to every scan that asks.
|
||||
///
|
||||
/// Both fields are memos of pure functions of the file's text, so sharing one
|
||||
/// cannot change an answer: `tokens` is `tokenize(text).ok()` and `lines` is
|
||||
/// `LineIndex::new(text)`, computed on first use and then handed out.
|
||||
#[derive(Default)]
|
||||
struct FileScan {
|
||||
/// `None` until asked; `Some(None)` for a file that does not lex — which
|
||||
/// every scan reads as "nothing to say", exactly as `tokenize`'s `Err` did.
|
||||
tokens: Option<Option<Vec<Token>>>,
|
||||
lines: Option<LineIndex>,
|
||||
}
|
||||
|
||||
impl FileScan {
|
||||
/// The file's tokens, or `None` when it does not lex.
|
||||
fn tokens(&mut self, text: &str) -> Option<&[Token]> {
|
||||
self.tokens.get_or_insert_with(|| tokenize(text).ok()).as_deref()
|
||||
}
|
||||
|
||||
/// The file's line index.
|
||||
fn lines(&mut self, text: &str) -> &LineIndex {
|
||||
self.lines.get_or_insert_with(|| LineIndex::new(text))
|
||||
}
|
||||
|
||||
/// Both at once, for a scan that walks the tokens and asks the index for
|
||||
/// each hit's line — two borrows it cannot take one after the other.
|
||||
fn tokens_and_lines(&mut self, text: &str) -> (Option<&[Token]>, &LineIndex) {
|
||||
let tokens = self.tokens.get_or_insert_with(|| tokenize(text).ok());
|
||||
let lines = self.lines.get_or_insert_with(|| LineIndex::new(text));
|
||||
(tokens.as_deref(), lines)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// What the rename could not account for: the name inside `` `define``
|
||||
/// text, inside a macro invocation's opaque token, inside an assertion
|
||||
/// the SVA grammar could not structure, and identifier occurrences no
|
||||
/// reference was recorded for.
|
||||
///
|
||||
/// Every scan but the last runs over **every** file that spells the name,
|
||||
/// not only the edited ones: `` `BUMP(a) `` in a file the rename never
|
||||
/// touches still expands to the old name, an assertion the SVA grammar
|
||||
/// could not read is source text wherever it sits, and a reference the
|
||||
/// workspace could not finish is spelled with the old name either way.
|
||||
/// Their sentences are collected per scan and concatenated in that order,
|
||||
/// which is the order they were emitted in when each scan had its own loop.
|
||||
pub(super) fn warnings(
|
||||
&mut self,
|
||||
target: &Target,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
) -> Vec<String> {
|
||||
let mut warnings = self.macro_warnings(&target.name);
|
||||
// Macro *invocations* are scanned in every file that spells the name,
|
||||
// not only the edited ones: `` `BUMP(a) `` in a file the rename never
|
||||
// touches still expands to the old name.
|
||||
let name = &target.name;
|
||||
let (mut defines, mut macro_uses) = (Vec::new(), Vec::new());
|
||||
let (mut fallbacks, mut unfinished) = (Vec::new(), Vec::new());
|
||||
// The edited files' scans outlive the loop: the unaccounted scan runs
|
||||
// after all four of these and must not lex them a second time.
|
||||
let mut kept: HashMap<usize, FileScan> = HashMap::new();
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.macro_use_warnings(i, &target.name));
|
||||
let mut scan = FileScan::default();
|
||||
defines.extend(self.define_warnings(i, name, &mut scan));
|
||||
macro_uses.extend(self.macro_use_warnings(i, name, &mut scan));
|
||||
fallbacks.extend(self.sva_fallback_warnings(i, name, &mut scan));
|
||||
unfinished.extend(self.unresolved_candidate_warnings(i, name, &mut scan));
|
||||
if edits.iter().any(|(file, _)| *file == i) {
|
||||
kept.insert(i, scan);
|
||||
}
|
||||
}
|
||||
// Same reason again: an assertion whose spec the SVA grammar could not
|
||||
// read is kept as source text, and the old name inside it is invisible
|
||||
// to the semantic layer wherever the file sits.
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.sva_fallback_warnings(i, &target.name));
|
||||
let mut warnings = defines;
|
||||
warnings.extend(macro_uses);
|
||||
warnings.extend(fallbacks);
|
||||
warnings.extend(unfinished);
|
||||
for (i, edits) in edits {
|
||||
let mut scan = kept.remove(i).unwrap_or_default();
|
||||
warnings.extend(self.unaccounted_warnings(*i, name, edits, &mut scan));
|
||||
}
|
||||
// Same reason: a reference the workspace could not finish is spelled
|
||||
// with the old name in a file the rename never edits, and silence
|
||||
// there is the same kind of wrong as silence about a macro argument.
|
||||
warnings.dedup();
|
||||
warnings
|
||||
}
|
||||
|
||||
/// [`Scope::warnings`] as it was written before take 5 §P2d shared the
|
||||
/// per-file lex and line index: five loops, and every scan building its
|
||||
/// own inputs from the file's text.
|
||||
///
|
||||
/// The oracle `the_shared_scan_says_exactly_what_the_per_scan_one_did`
|
||||
/// compares against, so the dedupe is pinned against the control flow it
|
||||
/// replaced — both the sharing and the order the sentences come out in —
|
||||
/// rather than against itself.
|
||||
#[cfg(test)]
|
||||
fn warnings_reference(
|
||||
&mut self,
|
||||
target: &Target,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
) -> Vec<String> {
|
||||
let name = &target.name;
|
||||
let mut warnings = Vec::new();
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.unresolved_candidate_warnings(i, &target.name));
|
||||
warnings.extend(self.define_warnings(i, name, &mut FileScan::default()));
|
||||
}
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.macro_use_warnings(i, name, &mut FileScan::default()));
|
||||
}
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.sva_fallback_warnings(i, name, &mut FileScan::default()));
|
||||
}
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.unresolved_candidate_warnings(i, name, &mut FileScan::default()));
|
||||
}
|
||||
for (i, edits) in edits {
|
||||
warnings.extend(self.unaccounted_warnings(*i, &target.name, edits));
|
||||
warnings.extend(self.unaccounted_warnings(*i, name, edits, &mut FileScan::default()));
|
||||
}
|
||||
warnings.dedup();
|
||||
warnings
|
||||
@@ -57,24 +146,22 @@ impl<'a> Scope<'a> {
|
||||
|
||||
/// lucisv does not preprocess, so a name that is also a macro name, or that
|
||||
/// appears in a macro body, is left exactly as written — and said so.
|
||||
fn macro_warnings(&self, name: &str) -> Vec<String> {
|
||||
fn define_warnings(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<String> {
|
||||
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
|
||||
let mut out = Vec::new();
|
||||
for i in 0..self.len() {
|
||||
let where_ = display(self.path(i).unwrap_or(Path::new("?")));
|
||||
for site in self.define_sites(i, name) {
|
||||
let line = site.line;
|
||||
match site.defines_the_name {
|
||||
Some(DefineKind::Define) => out.push(format!(
|
||||
"`{name}` is also a macro defined at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
)),
|
||||
Some(DefineKind::Undef) => out.push(format!(
|
||||
"`{name}` is also a macro undefined at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
)),
|
||||
None => out.push(format!(
|
||||
"`{name}` appears in the body of macro `{}` at {where_}:{line} and was left unchanged; lucisv does not preprocess.",
|
||||
site.macro_name
|
||||
)),
|
||||
}
|
||||
for site in self.define_sites_with(file, name, scan) {
|
||||
let line = site.line;
|
||||
match site.defines_the_name {
|
||||
Some(DefineKind::Define) => out.push(format!(
|
||||
"`{name}` is also a macro defined at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
)),
|
||||
Some(DefineKind::Undef) => out.push(format!(
|
||||
"`{name}` is also a macro undefined at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
)),
|
||||
None => out.push(format!(
|
||||
"`{name}` appears in the body of macro `{}` at {where_}:{line} and was left unchanged; lucisv does not preprocess.",
|
||||
site.macro_name
|
||||
)),
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -84,9 +171,9 @@ impl<'a> Scope<'a> {
|
||||
/// so the name inside `` `BUMP(a) `` is invisible to the semantic layer and
|
||||
/// cannot be edited. It can be seen, though — and silence would be worse
|
||||
/// than a warning, because the expansion still spells the old name.
|
||||
fn macro_use_warnings(&self, file: usize, name: &str) -> Vec<String> {
|
||||
fn macro_use_warnings(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<String> {
|
||||
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
|
||||
self.macro_argument_sites(file, name)
|
||||
self.macro_argument_sites_with(file, name, scan)
|
||||
.into_iter()
|
||||
.map(|site| {
|
||||
format!(
|
||||
@@ -110,15 +197,19 @@ impl<'a> Scope<'a> {
|
||||
/// region is therefore already covered and already edited. So the scan may
|
||||
/// be generous — `expect(word[7:0]);`, an ordinary task call, is claimed as
|
||||
/// a region and contributes nothing.
|
||||
fn sva_fallback_warnings(&mut self, file: usize, name: &str) -> Vec<String> {
|
||||
fn sva_fallback_warnings(
|
||||
&mut self,
|
||||
file: usize,
|
||||
name: &str,
|
||||
scan: &mut FileScan,
|
||||
) -> Vec<String> {
|
||||
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !contains_word(text, name) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
let regions = sva_regions(&tokens);
|
||||
let Some(regions) = scan.tokens(text).map(sva_regions) else { return Vec::new() };
|
||||
if regions.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -126,9 +217,9 @@ impl<'a> Scope<'a> {
|
||||
let mut covered: Vec<TextRange> =
|
||||
analysis.semantics.symbols().iter().map(|s| s.name_span).collect();
|
||||
covered.extend(analysis.semantics.references().iter().map(|r| r.name_span));
|
||||
let lines = LineIndex::new(text);
|
||||
let (Some(tokens), lines) = scan.tokens_and_lines(text) else { return Vec::new() };
|
||||
let mut at: Vec<u32> = Vec::new();
|
||||
for token in &tokens {
|
||||
for token in tokens {
|
||||
if token.kind != TokenKind::Ident || token.text != name {
|
||||
continue;
|
||||
}
|
||||
@@ -158,6 +249,11 @@ impl<'a> Scope<'a> {
|
||||
/// because "was left unchanged" and "no longer exists after the removal"
|
||||
/// are different pieces of news.
|
||||
pub(crate) fn define_sites(&self, file: usize, name: &str) -> Vec<DefineSite> {
|
||||
self.define_sites_with(file, name, &mut FileScan::default())
|
||||
}
|
||||
|
||||
/// [`Scope::define_sites`], reading the caller's shared line index.
|
||||
fn define_sites_with(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<DefineSite> {
|
||||
let (Some(text), Some(id)) = (self.text(file), self.file_id(file)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -165,7 +261,7 @@ impl<'a> Scope<'a> {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(defines) = self.index.defines(id) else { return Vec::new() };
|
||||
let lines = LineIndex::new(text);
|
||||
let lines = scan.lines(text);
|
||||
let mut out = Vec::new();
|
||||
for define in defines.entries() {
|
||||
let line = lines.line_col(define.span.start).0;
|
||||
@@ -187,13 +283,32 @@ impl<'a> Scope<'a> {
|
||||
}
|
||||
|
||||
/// Every macro invocation in one file whose *arguments* spell `name`.
|
||||
///
|
||||
/// The prefilter is `text.contains(name)` and **not**
|
||||
/// `WorkspaceIndex::files_naming_in_macros` (take 5 §P2d proposed that
|
||||
/// gate; it is not equivalent, so it is not taken). That census is
|
||||
/// `FileFacts::macro_words` = `words::harvest_raw`, which reads the same
|
||||
/// invocation tokens this scan reads but **skips every double-quoted run**
|
||||
/// inside them, and skips a word a `'` precedes. So
|
||||
/// `` `uvm_info("state_q", …) `` — the commonest shape a testbench names an
|
||||
/// RTL signal in — is a site this scan reports and the census does not
|
||||
/// know about, and gating on it would silently drop that warning.
|
||||
pub(crate) fn macro_argument_sites(&self, file: usize, name: &str) -> Vec<ArgumentSite> {
|
||||
self.macro_argument_sites_with(file, name, &mut FileScan::default())
|
||||
}
|
||||
|
||||
/// [`Scope::macro_argument_sites`], reading the caller's shared tokens.
|
||||
fn macro_argument_sites_with(
|
||||
&self,
|
||||
file: usize,
|
||||
name: &str,
|
||||
scan: &mut FileScan,
|
||||
) -> Vec<ArgumentSite> {
|
||||
let Some(text) = self.text(file) else { return Vec::new() };
|
||||
if !text.contains(name) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
let lines = LineIndex::new(text);
|
||||
let (Some(tokens), lines) = scan.tokens_and_lines(text) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for token in tokens.iter().filter(|t| t.is_macro()) {
|
||||
// The macro's own name is reported by the `` `define`` scan when
|
||||
@@ -215,7 +330,13 @@ impl<'a> Scope<'a> {
|
||||
/// Identifier tokens spelling the name that no declaration and no
|
||||
/// reference covers — grouped by *why* lucisv could not attribute them, so
|
||||
/// the user is told where to look rather than guessing.
|
||||
fn unaccounted_warnings(&mut self, file: usize, name: &str, edits: &[TextEdit]) -> Vec<String> {
|
||||
fn unaccounted_warnings(
|
||||
&mut self,
|
||||
file: usize,
|
||||
name: &str,
|
||||
edits: &[TextEdit],
|
||||
scan: &mut FileScan,
|
||||
) -> Vec<String> {
|
||||
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -225,8 +346,7 @@ impl<'a> Scope<'a> {
|
||||
covered.extend(analysis.semantics.references().iter().map(|r| r.name_span));
|
||||
covered.extend(edits.iter().map(|e| e.range));
|
||||
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
let lines = LineIndex::new(text);
|
||||
let (Some(tokens), lines) = scan.tokens_and_lines(text) else { return Vec::new() };
|
||||
// Reason → the lines it happened on, in source order.
|
||||
let mut groups: Vec<(&'static str, Vec<u32>)> = Vec::new();
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
@@ -236,7 +356,7 @@ impl<'a> Scope<'a> {
|
||||
if covered.contains(&token.span) {
|
||||
continue;
|
||||
}
|
||||
let reason = stray_reason(&tokens, i);
|
||||
let reason = stray_reason(tokens, i);
|
||||
let line = lines.line_col(token.span.start).0;
|
||||
match groups.iter_mut().find(|(r, _)| *r == reason) {
|
||||
Some((_, at)) => at.push(line),
|
||||
@@ -269,7 +389,12 @@ impl<'a> Scope<'a> {
|
||||
///
|
||||
/// Grouped one line per (file, unit), because a name used against an
|
||||
/// un-indexed module is used against it many times.
|
||||
fn unresolved_candidate_warnings(&mut self, file: usize, name: &str) -> Vec<String> {
|
||||
fn unresolved_candidate_warnings(
|
||||
&mut self,
|
||||
file: usize,
|
||||
name: &str,
|
||||
scan: &mut FileScan,
|
||||
) -> Vec<String> {
|
||||
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -279,7 +404,7 @@ impl<'a> Scope<'a> {
|
||||
return Vec::new();
|
||||
}
|
||||
let where_ = display(path).to_string();
|
||||
let lines = LineIndex::new(text);
|
||||
let lines = scan.lines(text);
|
||||
let Some(analysis) = self.analysis(file) else { return Vec::new() };
|
||||
// Unit that could not be found → the lines it was named on.
|
||||
let mut groups: Vec<(String, Vec<u32>)> = Vec::new();
|
||||
@@ -355,7 +480,7 @@ pub(crate) struct ArgumentSite {
|
||||
/// read off its neighbours in the token stream. Naming the actual construct
|
||||
/// is the difference between a warning the user can act on and one they have
|
||||
/// to decode.
|
||||
fn stray_reason(tokens: &[vlog_parser::token::Token], i: usize) -> &'static str {
|
||||
fn stray_reason(tokens: &[Token], i: usize) -> &'static str {
|
||||
let before = i.checked_sub(1).and_then(|n| tokens.get(n));
|
||||
if before.is_some_and(|t| t.is_sym(".")) {
|
||||
return "a hierarchical or member tail, which lucisv does not resolve";
|
||||
@@ -383,7 +508,7 @@ fn stray_reason(tokens: &[vlog_parser::token::Token], i: usize) -> &'static str
|
||||
/// structure. Deliberately generous: whether a region actually *is* a
|
||||
/// fallback is decided by its caller from the analysis, and a region that
|
||||
/// structured contributes nothing.
|
||||
fn sva_regions(tokens: &[vlog_parser::token::Token]) -> Vec<TextRange> {
|
||||
fn sva_regions(tokens: &[Token]) -> Vec<TextRange> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < tokens.len() {
|
||||
@@ -418,7 +543,7 @@ fn sva_regions(tokens: &[vlog_parser::token::Token]) -> Vec<TextRange> {
|
||||
|
||||
/// The index of the `(` that opens the spec of the concurrent assertion or
|
||||
/// `expect` statement starting at `i`, if one starts there.
|
||||
fn assertion_paren(tokens: &[vlog_parser::token::Token], i: usize) -> Option<usize> {
|
||||
fn assertion_paren(tokens: &[Token], i: usize) -> Option<usize> {
|
||||
let mut k = i;
|
||||
if tokens[i].kind == TokenKind::Ident && tokens.get(i + 1).is_some_and(|t| t.is_sym(":")) {
|
||||
k = i + 2;
|
||||
@@ -441,7 +566,7 @@ fn assertion_paren(tokens: &[vlog_parser::token::Token], i: usize) -> Option<usi
|
||||
}
|
||||
|
||||
/// The index of the `)` matching the `(` at `open`, or the last token.
|
||||
fn closing_paren(tokens: &[vlog_parser::token::Token], open: usize) -> usize {
|
||||
fn closing_paren(tokens: &[Token], open: usize) -> usize {
|
||||
let mut depth = 0usize;
|
||||
for (j, t) in tokens.iter().enumerate().skip(open) {
|
||||
if t.is_sym("(") {
|
||||
@@ -500,7 +625,9 @@ fn is_name_byte(byte: u8) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::contains_word;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::{contains_word, Scope};
|
||||
|
||||
#[test]
|
||||
fn whole_word_search_ignores_substrings() {
|
||||
@@ -510,4 +637,354 @@ mod tests {
|
||||
assert!(contains_word("`WIDTH", "WIDTH"), "a macro use of the name still counts");
|
||||
assert!(!contains_word("x", ""));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// take 5 §P2d: the shared lex and line index say what the old
|
||||
// per-scan ones did
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One rename fixture: the workspace, where the cursor is, and what the
|
||||
/// warnings must say about it.
|
||||
struct Case {
|
||||
/// What this fixture is built to exercise, quoted on failure.
|
||||
what: &'static str,
|
||||
files: &'static [(&'static str, &'static str)],
|
||||
/// The file the cursor sits in, and the text it sits at the start of.
|
||||
file: &'static str,
|
||||
at: &'static str,
|
||||
new_name: &'static str,
|
||||
/// A sentence fragment the warnings must contain, so a case cannot
|
||||
/// pass by producing nothing at all. Empty for the controls, which
|
||||
/// exist to prove the *absence* of a warning is shared too.
|
||||
says: &'static str,
|
||||
}
|
||||
|
||||
/// The six sentences `warnings` can produce, so the table can assert it
|
||||
/// exercises every one of them rather than five.
|
||||
const KINDS: [&str; 6] = [
|
||||
"is also a macro",
|
||||
"appears in the body of macro",
|
||||
"appears in the arguments of the macro invocation",
|
||||
"is spelled inside an assertion lucisv could not structure",
|
||||
"could not be resolved — nothing in the indexed workspace answers",
|
||||
"lucisv records no reference there",
|
||||
];
|
||||
|
||||
/// A file that does not lex — an unterminated block comment — which every
|
||||
/// scan must treat as "nothing to say" whether it lexes the file itself or
|
||||
/// reads a shared answer.
|
||||
const UNLEXABLE: &str = "module unlexable;\n /* sig is in here and the comment never closes\n";
|
||||
|
||||
/// A file whose only spelling of the name is in a comment: `contains_word`
|
||||
/// sees it, the token stream does not.
|
||||
const COMMENT_ONLY: &str =
|
||||
"module note;\n // sig is only mentioned here\n logic other;\nendmodule\n";
|
||||
|
||||
const CASES: &[Case] = &[
|
||||
Case {
|
||||
what: "a macro of the same name, and one whose body spells it, and an undef",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"`define sig 1\n`define USE_SIG assign z = sig;\n`undef sig\nmodule m;\n wire sig;\n assign q = sig;\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;\n assign q",
|
||||
new_name: "signal",
|
||||
says: "is also a macro defined at",
|
||||
},
|
||||
Case {
|
||||
what: "the name inside a macro body",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"`define SET_A assign a = 1;\nmodule m;\n wire a;\n assign a = 0;\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "a;",
|
||||
new_name: "sig",
|
||||
says: "body of macro `SET_A`",
|
||||
},
|
||||
Case {
|
||||
what: "the name inside a macro invocation's arguments",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"`define BUMP(x) x = x + 1\nmodule m;\n int a;\n initial `BUMP(a);\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "a;",
|
||||
new_name: "b",
|
||||
says: "arguments of the macro invocation `BUMP`",
|
||||
},
|
||||
Case {
|
||||
what: "a macro invocation in a file the rename does not edit",
|
||||
files: &[
|
||||
("p.sv", "package p;\n localparam int WIDTH = 8;\nendpackage\n"),
|
||||
(
|
||||
"u.sv",
|
||||
"`define DECL(w) logic [w-1:0] bus\nmodule u;\n import p::*;\n `DECL(WIDTH);\nendmodule\n",
|
||||
),
|
||||
],
|
||||
file: "p.sv",
|
||||
at: "WIDTH",
|
||||
new_name: "BUS_W",
|
||||
says: "macro invocation `DECL`",
|
||||
},
|
||||
Case {
|
||||
what: "a file whose only relationship to the name is a macro argument",
|
||||
files: &[
|
||||
(
|
||||
"lib.sv",
|
||||
"`define CHECK(sig) assert property (sig)\npackage p;\n localparam int WIDTH = 8;\nendpackage\n",
|
||||
),
|
||||
("user.sv", "module u;\n `CHECK(WIDTH)\nendmodule\n"),
|
||||
],
|
||||
file: "lib.sv",
|
||||
at: "WIDTH = 8",
|
||||
new_name: "BUS_W",
|
||||
says: "macro invocation `CHECK`",
|
||||
},
|
||||
Case {
|
||||
what: "an SVA spec the grammar could not structure, in the edited file",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module m;\n logic sig;\n assign x = sig;\n assert property (sig |-> $blah $blah);\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "could not structure",
|
||||
},
|
||||
Case {
|
||||
what: "an SVA fallback in a file the rename does not edit",
|
||||
files: &[
|
||||
("p.sv", "package p;\n localparam int WIDTH = 8;\nendpackage\n"),
|
||||
(
|
||||
"u.sv",
|
||||
"module u;\n import p::*;\n assert property (WIDTH |-> $blah $blah);\nendmodule\n",
|
||||
),
|
||||
],
|
||||
file: "p.sv",
|
||||
at: "WIDTH",
|
||||
new_name: "BUS_W",
|
||||
says: "could not structure",
|
||||
},
|
||||
Case {
|
||||
what: "an assertion the grammar did structure — the control",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module m;\n logic sig;\n assert property (sig |-> sig);\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
},
|
||||
Case {
|
||||
what: "an unresolved candidate spelling the name",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module top;\n wire sig;\n unknown_mod u_x ();\n wire w;\n assign w = u_x.sig;\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "could not be resolved",
|
||||
},
|
||||
Case {
|
||||
what: "an unresolved candidate in a file the rename never edits",
|
||||
files: &[
|
||||
("holder.sv", "module holder;\n wire sig;\nendmodule\n"),
|
||||
(
|
||||
"other.sv",
|
||||
"module other;\n unknown_mod u_y ();\n wire w;\n assign w = u_y.sig;\nendmodule\n",
|
||||
),
|
||||
],
|
||||
file: "holder.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "other.sv",
|
||||
},
|
||||
Case {
|
||||
what: "a tail the workspace can finish — the control",
|
||||
files: &[
|
||||
("sub.sv", "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
(
|
||||
"top.sv",
|
||||
"module top;\n sub u_sub ();\n wire w;\n assign w = u_sub.sig;\nendmodule\n",
|
||||
),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
},
|
||||
Case {
|
||||
what: "a stray occurrence no reference covers — a member tail",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module m;\n wire sig;\n logic s;\n assign x = s.sig;\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "as a hierarchical or member tail",
|
||||
},
|
||||
Case {
|
||||
what: "a stray occurrence no reference covers — a mismatched end label",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module m;\n wire sig;\n initial begin : blk\n end : sig\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "as an end label lucisv could not attach",
|
||||
},
|
||||
Case {
|
||||
what: "a file that mentions the name only in a comment",
|
||||
files: &[
|
||||
("sub.sv", "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("note.sv", COMMENT_ONLY),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
},
|
||||
Case {
|
||||
what: "a file that does not lex",
|
||||
files: &[
|
||||
("sub.sv", "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("unlexable.sv", UNLEXABLE),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
},
|
||||
Case {
|
||||
what: "the §P2b eight-file workspace, whose rename edits two files",
|
||||
files: &[
|
||||
(
|
||||
"/w/sub.sv",
|
||||
"module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"/w/top.sv",
|
||||
"module top;\n logic w;\n sub u_sub (.clk(1'b0), .q(w));\n assign w = u_sub.sig;\nendmodule\n",
|
||||
),
|
||||
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
||||
(
|
||||
"/w/user.sv",
|
||||
"import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n",
|
||||
),
|
||||
("/w/note.sv", COMMENT_ONLY),
|
||||
("/w/far.sv", "module far;\n logic sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("/w/quiet_a.sv", "module quiet_a;\n logic a;\nendmodule\n"),
|
||||
("/w/quiet_b.sv", "module quiet_b;\n logic b;\nendmodule\n"),
|
||||
],
|
||||
file: "/w/sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "renamed_sig",
|
||||
says: "",
|
||||
},
|
||||
// The order test: every kind of warning at once, from several files,
|
||||
// with two files edited — so a concatenation that grouped by file
|
||||
// instead of by scan, or that ran the unaccounted scan too early,
|
||||
// would come out in a different order and be caught.
|
||||
Case {
|
||||
what: "every shape in one workspace, two files edited",
|
||||
files: &[
|
||||
(
|
||||
"sub.sv",
|
||||
"`define sig 1\n`define USE_SIG assign z = sig;\nmodule sub;\n wire sig;\n assign sig = 1'b0;\n logic s;\n assign y = s.sig;\n assert property (sig |-> $blah $blah);\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"top.sv",
|
||||
"`define BUMP(x) x + 1\nmodule top;\n sub u_sub ();\n wire w;\n assign w = u_sub.sig;\n assign w = `BUMP(sig);\n assign w = elsewhere.sig;\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"stray.sv",
|
||||
"module stray;\n unknown_mod u_y ();\n wire w;\n assign w = u_y.sig;\nendmodule\n",
|
||||
),
|
||||
("note.sv", COMMENT_ONLY),
|
||||
("unlexable.sv", UNLEXABLE),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;\n assign sig",
|
||||
new_name: "signal",
|
||||
says: "could not be resolved",
|
||||
},
|
||||
];
|
||||
|
||||
/// One case's warnings, computed both ways over **separate** scopes, so a
|
||||
/// cache the first call warmed cannot flatter the second.
|
||||
fn both_ways(case: &Case) -> (Vec<String>, Vec<String>) {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
case.files.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let path = PathBuf::from(case.file);
|
||||
let text = case.files.iter().find(|(p, _)| *p == case.file).expect("the cursor's file").1;
|
||||
let at = text.find(case.at).expect("the cursor text is in the file") as u32;
|
||||
|
||||
let mut shared = Scope::build(&sources);
|
||||
let target = shared.locate(&path, at).expect("the cursor names something renameable");
|
||||
let edits = shared.collect_edits(&target, case.new_name).expect("the rename has edits");
|
||||
let said = shared.warnings(&target, &edits);
|
||||
|
||||
let mut apart = Scope::build(&sources);
|
||||
let target = apart.locate(&path, at).expect("the cursor names something renameable");
|
||||
let edits = apart.collect_edits(&target, case.new_name).expect("the rename has edits");
|
||||
(said, apart.warnings_reference(&target, &edits))
|
||||
}
|
||||
|
||||
/// **The §P2d proof.** Sharing one lex and one line index per file per call
|
||||
/// changes no sentence and no order: fifteen fixtures — every warning-
|
||||
/// producing shape `crates/vlog_refactor/tests/rename.rs` pins, the three
|
||||
/// controls that must stay silent, a file that only mentions the name in a
|
||||
/// comment, a file that does not lex, and one workspace holding all of them
|
||||
/// with two files edited — asked both ways and compared as lists.
|
||||
#[test]
|
||||
fn the_shared_scan_says_exactly_what_the_per_scan_one_did() {
|
||||
let mut seen = [false; KINDS.len()];
|
||||
for case in CASES {
|
||||
let (shared, reference) = both_ways(case);
|
||||
assert_eq!(shared, reference, "{}: the shared scan disagrees", case.what);
|
||||
if case.says.is_empty() {
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
shared.iter().any(|warning| warning.contains(case.says)),
|
||||
"{}: no warning says `{}`: {shared:?}",
|
||||
case.what,
|
||||
case.says
|
||||
);
|
||||
for (kind, seen) in KINDS.iter().zip(seen.iter_mut()) {
|
||||
*seen |= shared.iter().any(|warning| warning.contains(kind));
|
||||
}
|
||||
}
|
||||
let missed: Vec<&str> =
|
||||
KINDS.iter().zip(seen).filter_map(|(kind, seen)| (!seen).then_some(*kind)).collect();
|
||||
assert!(missed.is_empty(), "these warnings are never exercised: {missed:?}");
|
||||
}
|
||||
|
||||
/// The controls are silent *and* silent in the same way: a workspace where
|
||||
/// the only other spellings of the name are a comment and a file that does
|
||||
/// not lex warns about nothing at all.
|
||||
#[test]
|
||||
fn a_comment_and_an_unlexable_file_are_warned_about_by_neither_scan() {
|
||||
let case = Case {
|
||||
what: "a comment and an unlexable file, together",
|
||||
files: &[
|
||||
("sub.sv", "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("note.sv", COMMENT_ONLY),
|
||||
("unlexable.sv", UNLEXABLE),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
};
|
||||
let (shared, reference) = both_ways(&case);
|
||||
assert!(shared.is_empty(), "nothing there can be warned about: {shared:?}");
|
||||
assert_eq!(shared, reference);
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,24 @@
|
||||
//! Nothing here is specific to a rename: `ports`, `references` and
|
||||
//! `instantiate` read the same workspace, which is why it sits at the crate
|
||||
//! root rather than under one of them.
|
||||
//!
|
||||
//! **One parse per file** (take 5 §P2b). Building the index parses and
|
||||
//! analyses every in-scope file already — `FileFacts::of` is a parse, an
|
||||
//! `analyze` and a read-off — and used to throw that analysis away, so the
|
||||
//! first thing every refactoring did was parse a third of those files a
|
||||
//! second time. [`FileFacts::analyzed`] hands the analysis back instead, and
|
||||
//! [`Scope::build_keeping`] retains the ones a caller says it will want. What
|
||||
//! is retained is a *cache and nothing else*: a file whose analysis was not
|
||||
//! kept is analysed on demand exactly as before, so a retention rule that
|
||||
//! guesses wrong costs time and cannot change an answer.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalResolutions, FileId, Semantics, WorkspaceIndex,
|
||||
analyze, resolve_external, ExternalResolutions, FileFacts, FileId, IndexBuilder, Semantics,
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
/// One file's two analysis layers, as `textDocument/definition` uses them.
|
||||
@@ -30,10 +41,51 @@ pub(crate) struct Scope<'a> {
|
||||
/// Source index → the index's own file id.
|
||||
file_ids: Vec<Option<FileId>>,
|
||||
cache: HashMap<usize, Analysis>,
|
||||
/// The `Semantics` the index build kept, by source index — the half of an
|
||||
/// [`Analysis`] that does not depend on the finished index. Moved into
|
||||
/// `cache` the first time that file's analysis is asked for.
|
||||
kept: HashMap<usize, Semantics>,
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// The in-scope files, indexed, keeping no analysis.
|
||||
///
|
||||
/// Each file is still parsed and analysed exactly once — that is what
|
||||
/// building the index costs — and every later `analysis` call parses
|
||||
/// again, which is the behaviour every caller but the rename has always
|
||||
/// had. [`Scope::build_keeping`] is the one that keeps them.
|
||||
pub(crate) fn build(files: &'a [(PathBuf, String)]) -> Scope<'a> {
|
||||
Scope::assemble(files, None, |_| Vec::new())
|
||||
}
|
||||
|
||||
/// The in-scope files, indexed, **keeping** the analysis of `lead` and of
|
||||
/// every file whose text mentions one of the words `keep` asks for.
|
||||
///
|
||||
/// `lead` — the file the request was made in — is analysed first, and
|
||||
/// `keep` is then asked which words are worth retaining *given that
|
||||
/// analysis*. That ordering is the whole trick: a rename cannot know the
|
||||
/// name under the cursor until something has analysed the cursor's file,
|
||||
/// and this way that analysis is the file's own one-and-only parse rather
|
||||
/// than an extra one.
|
||||
///
|
||||
/// The rule is `text.contains(word)` — a substring test, deliberately the
|
||||
/// same prefilter [`Scope::collect_occurrences`] uses, so every file the
|
||||
/// occurrence walk will analyse and every file
|
||||
/// [`crate::check`] will watch (a whole-word subset) is retained, and
|
||||
/// nothing else is.
|
||||
pub(crate) fn build_keeping(
|
||||
files: &'a [(PathBuf, String)],
|
||||
lead: &Path,
|
||||
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
|
||||
) -> Scope<'a> {
|
||||
Scope::assemble(files, Some(lead), keep)
|
||||
}
|
||||
|
||||
fn assemble(
|
||||
files: &'a [(PathBuf, String)],
|
||||
lead: Option<&Path>,
|
||||
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
|
||||
) -> Scope<'a> {
|
||||
let mut sources: Vec<(&Path, &str)> =
|
||||
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
|
||||
// The same normalization `WorkspaceIndex::build` applies: a stable
|
||||
@@ -41,7 +93,31 @@ impl<'a> Scope<'a> {
|
||||
sources.sort_by(|a, b| a.0.cmp(b.0));
|
||||
sources.dedup_by(|a, b| a.0 == b.0);
|
||||
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.to_path_buf(), *t)));
|
||||
let mut builder = IndexBuilder::new();
|
||||
let mut kept: HashMap<usize, Semantics> = HashMap::new();
|
||||
// The lead file first, so its analysis can be read before the rest are
|
||||
// parsed. `IndexBuilder::finish` sorts by path, so feeding it out of
|
||||
// order cannot reach the index.
|
||||
let first = lead.and_then(|path| sources.iter().position(|(held, _)| *held == path));
|
||||
if let Some(i) = first {
|
||||
let (path, text) = sources[i];
|
||||
let (facts, semantics) = FileFacts::analyzed(path.to_path_buf(), text);
|
||||
builder.add_facts(facts);
|
||||
kept.insert(i, semantics);
|
||||
}
|
||||
let words = keep(first.and_then(|i| kept.get(&i)));
|
||||
for (i, (path, text)) in sources.iter().enumerate() {
|
||||
if Some(i) == first {
|
||||
continue;
|
||||
}
|
||||
let (facts, semantics) = FileFacts::analyzed(path.to_path_buf(), text);
|
||||
builder.add_facts(facts);
|
||||
if words.iter().any(|word| text.contains(word.as_str())) {
|
||||
kept.insert(i, semantics);
|
||||
}
|
||||
}
|
||||
|
||||
let index = builder.finish();
|
||||
let ids: HashMap<&Path, FileId> = index
|
||||
.files()
|
||||
.iter()
|
||||
@@ -49,7 +125,7 @@ impl<'a> Scope<'a> {
|
||||
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
|
||||
.collect();
|
||||
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
|
||||
Scope { sources, index, file_ids, cache: HashMap::new() }
|
||||
Scope { sources, index, file_ids, cache: HashMap::new(), kept }
|
||||
}
|
||||
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
@@ -64,10 +140,6 @@ impl<'a> Scope<'a> {
|
||||
self.sources.get(i).map(|(_, text)| *text)
|
||||
}
|
||||
|
||||
pub(crate) fn sources(&self) -> &[(&'a Path, &'a str)] {
|
||||
&self.sources
|
||||
}
|
||||
|
||||
pub(crate) fn file_id(&self, i: usize) -> Option<FileId> {
|
||||
self.file_ids.get(i).copied().flatten()
|
||||
}
|
||||
@@ -77,11 +149,17 @@ impl<'a> Scope<'a> {
|
||||
}
|
||||
|
||||
/// The two analysis layers for one file, computed on first use.
|
||||
///
|
||||
/// The local half is the one the index build already made, when it was
|
||||
/// kept; otherwise it is parsed here, exactly as it always was. The
|
||||
/// external half is this scope's index resolved against it, and is
|
||||
/// computed here either way — it cannot exist before the index does.
|
||||
pub(crate) fn analysis(&mut self, i: usize) -> Option<&Analysis> {
|
||||
let Scope { sources, index, cache, .. } = self;
|
||||
let Scope { sources, index, cache, kept, .. } = self;
|
||||
let text = sources.get(i).map(|(_, text)| *text)?;
|
||||
Some(cache.entry(i).or_insert_with(|| {
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let semantics =
|
||||
kept.remove(&i).unwrap_or_else(|| analyze(&parse_source_tolerant(text).0, text));
|
||||
let external = resolve_external(&semantics, index);
|
||||
Analysis { semantics, external }
|
||||
}))
|
||||
@@ -93,6 +171,27 @@ impl<'a> Scope<'a> {
|
||||
self.cache.get(&i)
|
||||
}
|
||||
|
||||
/// One watched file's after-print inputs: the local analysis the
|
||||
/// before-pass already computed, and its uses resolved against `index`.
|
||||
///
|
||||
/// A file the edits did not touch has the same declarations and the same
|
||||
/// uses afterwards — its text did not change — so only what the workspace
|
||||
/// answers *for* those uses can have moved, and re-resolving is the whole
|
||||
/// of the difference. Re-parsing it to learn that is the work take 5 §P2c
|
||||
/// removes.
|
||||
///
|
||||
/// `None` when that file's local analysis has not been computed. The
|
||||
/// caller's own before-pass is what computes it, so that is a
|
||||
/// contradiction rather than a fallback.
|
||||
pub(crate) fn against(
|
||||
&self,
|
||||
i: usize,
|
||||
index: &WorkspaceIndex,
|
||||
) -> Option<(&Semantics, ExternalResolutions)> {
|
||||
let semantics = &self.cached(i)?.semantics;
|
||||
Some((semantics, resolve_external(semantics, index)))
|
||||
}
|
||||
|
||||
/// The workspace index the edits were computed against.
|
||||
pub(crate) fn index(&self) -> &WorkspaceIndex {
|
||||
&self.index
|
||||
@@ -104,3 +203,110 @@ impl<'a> Scope<'a> {
|
||||
pub(crate) fn display(path: &Path) -> String {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FILES: [(&str, &str); 4] = [
|
||||
("/w/sub.sv", "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n"),
|
||||
("/w/top.sv", "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign u_sub.sig = 1'b0;\nendmodule\n"),
|
||||
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
||||
("/w/user.sv", "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n"),
|
||||
];
|
||||
|
||||
fn files() -> Vec<(PathBuf, String)> {
|
||||
FILES.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect()
|
||||
}
|
||||
|
||||
/// Every declaration and use one analysis holds, as comparable text — the
|
||||
/// whole observable of a `Semantics` plus its overlay.
|
||||
fn print(analysis: &Analysis) -> String {
|
||||
let mut out = String::new();
|
||||
for symbol in analysis.semantics.symbols() {
|
||||
out.push_str(&format!(
|
||||
"sym {} {:?} {}..{}\n",
|
||||
symbol.name, symbol.kind, symbol.name_span.start, symbol.name_span.end
|
||||
));
|
||||
}
|
||||
for (id, reference) in analysis.semantics.references().iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
"ref {} {}..{} -> {:?} / {:?}\n",
|
||||
reference.name,
|
||||
reference.name_span.start,
|
||||
reference.name_span.end,
|
||||
reference.resolution,
|
||||
analysis.external.get(vlog_semantic::ReferenceId(id as u32))
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The scope's index is the index a plain `WorkspaceIndex::build` gives —
|
||||
/// same fingerprint, same file ids — however the scope was assembled.
|
||||
#[test]
|
||||
fn assembling_the_scope_file_by_file_builds_the_same_index() {
|
||||
let files = files();
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let plain = Scope::build(&files);
|
||||
assert_eq!(plain.index().fingerprint(), built.fingerprint());
|
||||
let keeping =
|
||||
Scope::build_keeping(&files, Path::new("/w/top.sv"), |_| vec!["sig".to_string()]);
|
||||
assert_eq!(keeping.index().fingerprint(), built.fingerprint());
|
||||
for i in 0..plain.len() {
|
||||
assert_eq!(plain.file_id(i), keeping.file_id(i), "file ids move with retention");
|
||||
assert_eq!(plain.path(i), keeping.path(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// A retained analysis is the analysis the on-demand path would compute.
|
||||
/// This is the whole of §P2b's correctness: what is kept is not a second
|
||||
/// opinion, it is the same one, not thrown away.
|
||||
#[test]
|
||||
fn a_retained_analysis_is_the_one_the_on_demand_path_would_compute() {
|
||||
let files = files();
|
||||
let mut plain = Scope::build(&files);
|
||||
let mut keeping = Scope::build_keeping(&files, Path::new("/w/top.sv"), |here| {
|
||||
// Every word in play, so every file is retained.
|
||||
assert!(here.is_some(), "the lead file's analysis is made first");
|
||||
vec!["sig".to_string(), "pkg".to_string(), "u_sub".to_string()]
|
||||
});
|
||||
for i in 0..plain.len() {
|
||||
let one = plain.analysis(i).map(print);
|
||||
let two = keeping.analysis(i).map(print);
|
||||
assert_eq!(one, two, "file {i} analyses differently when it is retained");
|
||||
}
|
||||
}
|
||||
|
||||
/// The lead file's analysis is made **before** the rest are parsed, which
|
||||
/// is what lets a caller read the cursor's name off it and ask for that
|
||||
/// name to be kept — without a second parse of anything.
|
||||
#[test]
|
||||
fn the_lead_files_analysis_is_available_to_the_retention_rule() {
|
||||
let files = files();
|
||||
let mut seen = None;
|
||||
let scope = Scope::build_keeping(&files, Path::new("/w/user.sv"), |here| {
|
||||
seen = here.map(|semantics| semantics.symbols().len());
|
||||
Vec::new()
|
||||
});
|
||||
assert_eq!(seen, Some(2), "`user` and `X` are what user.sv declares");
|
||||
assert_eq!(scope.len(), 4);
|
||||
}
|
||||
|
||||
/// A lead the scope does not hold is not an error: nothing is retained,
|
||||
/// and the rest of the build is what it always was.
|
||||
#[test]
|
||||
fn a_lead_outside_the_scope_retains_nothing_and_still_builds() {
|
||||
let files = files();
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut asked = false;
|
||||
let mut scope = Scope::build_keeping(&files, Path::new("/w/absent.sv"), |here| {
|
||||
asked = true;
|
||||
assert!(here.is_none(), "there is no lead analysis to offer");
|
||||
vec!["sig".to_string()]
|
||||
});
|
||||
assert!(asked, "the retention rule is asked either way");
|
||||
assert_eq!(scope.index().fingerprint(), built.fingerprint());
|
||||
assert!(scope.analysis(0).is_some(), "and every file still analyses on demand");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Where a rename's time and its whole-file parses went.
|
||||
//!
|
||||
//! Take 5 §P2a (`docs/features/perf5-p2/README.md`): the tail rename costs
|
||||
//! ~780 ms and nobody could say which stage that is. A stopwatch on the wire
|
||||
//! cannot, because every stage of a rename is "read the workspace" in some
|
||||
//! form. So the engine says it itself — one value the caller fills as it goes,
|
||||
//! carrying a wall time and a *parse count* per stage.
|
||||
//!
|
||||
//! **Nothing here changes what a rename decides.** A trace is written to, read
|
||||
//! once and dropped; no branch anywhere reads a field of it. The counters are
|
||||
//! `vlog_parser::stats::parses()` deltas, which is a thread-local `Cell` read,
|
||||
//! and the timers are `Instant`s taken at stage boundaries — the cost of the
|
||||
//! whole instrument is a few dozen nanoseconds on a request measured in
|
||||
//! hundreds of milliseconds.
|
||||
//!
|
||||
//! The counts are the honest half. A wall time moves with the machine's load;
|
||||
//! "this rename parsed 5 200 whole files where 1 300 would do" does not, which
|
||||
//! is why the parse-count assertions in the tests are written against these
|
||||
//! fields rather than against a stopwatch.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
/// A stage's wall time and the whole-file parses it ran.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct Stage {
|
||||
/// Milliseconds spent inside the stage.
|
||||
pub ms: f64,
|
||||
/// Whole-file parses the stage ran — a `vlog_parser::stats::parses()`
|
||||
/// delta, so a lex failure (which parses nothing) is not counted.
|
||||
pub parses: u64,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
/// Run `work`, recording its wall time and its parses into `self`.
|
||||
///
|
||||
/// Additive: a stage measured twice accumulates, which is what the
|
||||
/// per-file loops want.
|
||||
pub(crate) fn measure<T>(&mut self, work: impl FnOnce() -> T) -> T {
|
||||
let (started, parses) = (Instant::now(), vlog_parser::stats::parses());
|
||||
let out = work();
|
||||
self.ms += started.elapsed().as_secs_f64() * 1000.0;
|
||||
self.parses += vlog_parser::stats::parses() - parses;
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// What the verification pass did, stage by stage.
|
||||
///
|
||||
/// The five sub-stages of [`crate::check`]'s `verify`, in the order it runs
|
||||
/// them. `checks` is the comments/attributes ledger and the parse-diagnostic
|
||||
/// comparison — zero for a rename, which runs neither (a rename may not change
|
||||
/// the token stream at all, which is a stronger statement than the ledger's).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct VerifyTrace {
|
||||
/// Token identity over every edited file, before against after.
|
||||
pub tokens: Stage,
|
||||
/// How many files the resolution check watches, and their total bytes.
|
||||
pub watched: usize,
|
||||
/// Bytes of those watched files.
|
||||
pub watched_bytes: usize,
|
||||
/// The pre-edit analysis of every watched file (cached ones are free).
|
||||
pub before: Stage,
|
||||
/// Building the index as it would be after the edits.
|
||||
pub rebuild: Stage,
|
||||
/// The post-edit analysis of every watched file, and the comparison.
|
||||
pub after: Stage,
|
||||
/// The ledger and parse-diagnostic checks a splice runs; zero for a
|
||||
/// rename.
|
||||
pub checks: Stage,
|
||||
}
|
||||
|
||||
/// Where one rename's work went: the input it was given, the time and parses
|
||||
/// of each stage, and what came out.
|
||||
///
|
||||
/// Filled by [`crate::rename_traced`] as it runs. Every field is written
|
||||
/// exactly once except the [`Stage`]s inside `verify`, which accumulate over
|
||||
/// their per-file loops.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct RenameTrace {
|
||||
/// Files handed to the engine, after the scope's own dedup.
|
||||
pub selected: usize,
|
||||
/// Their total bytes.
|
||||
pub bytes: usize,
|
||||
/// Building the request-local scope: the index over every selected file.
|
||||
pub index: Stage,
|
||||
/// Resolving the cursor to the declaration the rename acts on.
|
||||
pub locate: Stage,
|
||||
/// Collecting every occurrence and turning it into edits.
|
||||
pub edits: Stage,
|
||||
/// The whole verification pass.
|
||||
pub verify: Stage,
|
||||
/// Its five sub-stages.
|
||||
pub checks: VerifyTrace,
|
||||
/// Describing the occurrences the rename deliberately left alone.
|
||||
pub warnings: Stage,
|
||||
/// Files the rename edits.
|
||||
pub edited: usize,
|
||||
/// Whole-file parses over the entire request, from the first byte of the
|
||||
/// scope build to the last warning.
|
||||
pub parses: u64,
|
||||
}
|
||||
|
||||
impl RenameTrace {
|
||||
/// One line, in the server's `timing:` style — the whole trace, in the
|
||||
/// order the stages ran.
|
||||
pub fn line(&self) -> String {
|
||||
format!(
|
||||
"selected={} bytes={} edited={} index={:.1}ms locate={:.1} edits={:.1} \
|
||||
verify{{total={:.1} tokens={:.1} watched={} watched_bytes={} before={:.1} \
|
||||
rebuild={:.1} after={:.1} checks={:.1}}} warnings={:.1} \
|
||||
parses={} parses{{index={} locate={} edits={} before={} rebuild={} after={}}}",
|
||||
self.selected,
|
||||
self.bytes,
|
||||
self.edited,
|
||||
self.index.ms,
|
||||
self.locate.ms,
|
||||
self.edits.ms,
|
||||
self.verify.ms,
|
||||
self.checks.tokens.ms,
|
||||
self.checks.watched,
|
||||
self.checks.watched_bytes,
|
||||
self.checks.before.ms,
|
||||
self.checks.rebuild.ms,
|
||||
self.checks.after.ms,
|
||||
self.checks.checks.ms,
|
||||
self.warnings.ms,
|
||||
self.parses,
|
||||
self.index.parses,
|
||||
self.locate.parses,
|
||||
self.edits.parses,
|
||||
self.checks.before.parses,
|
||||
self.checks.rebuild.parses,
|
||||
self.checks.after.parses,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! The organize-imports offer promises exactly what the refactoring delivers.
|
||||
//!
|
||||
//! Take 5 §P1c (`docs/features/perf5-p1/README.md`) added
|
||||
//! [`vlog_refactor::organize_offer`], which answers the two counts a code
|
||||
//! action's title carries without rendering a verified edit. This file is the
|
||||
//! proof that its answer — the counts *and* the refusal sentence — is
|
||||
//! [`vlog_refactor::organize_counts`]'s answer at **every byte offset** of
|
||||
//! every fixture, and that the only thing it does not reproduce is
|
||||
//! `check::verify_splice`, which no fixture here reaches.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
use vlog_refactor::{organize_counts, organize_offer, organize_offer_in, organize_title};
|
||||
|
||||
/// A module importing two packages, one of them unused and written first, so
|
||||
/// there is both a removal and a sort to promise.
|
||||
const USER: &str = "\
|
||||
module user (
|
||||
input logic clk_i
|
||||
);
|
||||
import b_pkg::*;
|
||||
import a_pkg::*;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// Imports already sorted with every one used: the refusal that is not an
|
||||
/// error, and the one a lightbulb must not appear for.
|
||||
const TIDY: &str = "\
|
||||
module tidy;
|
||||
import a_pkg::*;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A duplicate import and a commented one, which is the shape that produces a
|
||||
/// warning instead of a deletion.
|
||||
const COMMENTED: &str = "\
|
||||
module commented;
|
||||
import a_pkg::*;
|
||||
// why this one is here
|
||||
import b_pkg::*;
|
||||
import a_pkg::*;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// An import of a package nothing in scope declares — the conservative
|
||||
/// silence, which the offer must keep.
|
||||
const UNKNOWN: &str = "\
|
||||
module unknown;
|
||||
import nowhere_pkg::*;
|
||||
import a_pkg::*;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A compilation-unit import run above a module, and a package with its own.
|
||||
const FILE_SCOPE: &str = "\
|
||||
import b_pkg::*;
|
||||
import a_pkg::*;
|
||||
package inner_pkg;
|
||||
import a_pkg::*;
|
||||
localparam int K = A_ONE;
|
||||
endpackage
|
||||
module uses;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A buffer that does not parse: refused by both, with the same sentence.
|
||||
const BROKEN: &str = "\
|
||||
module broken;
|
||||
import a_pkg::*;
|
||||
logic ;;; w
|
||||
endmodule
|
||||
";
|
||||
|
||||
const A_PKG: &str = "\
|
||||
package a_pkg;
|
||||
localparam int A_ONE = 1;
|
||||
endpackage
|
||||
";
|
||||
|
||||
const B_PKG: &str = "\
|
||||
package b_pkg;
|
||||
localparam int B_ONE = 2;
|
||||
endpackage
|
||||
";
|
||||
|
||||
fn file(name: &str) -> PathBuf {
|
||||
PathBuf::from("/rtl").join(name)
|
||||
}
|
||||
|
||||
fn workspace(name: &str, text: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![
|
||||
(file(name), text.to_string()),
|
||||
(file("a_pkg.sv"), A_PKG.to_string()),
|
||||
(file("b_pkg.sv"), B_PKG.to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
fn crlf(text: &str) -> String {
|
||||
text.replace('\n', "\r\n")
|
||||
}
|
||||
|
||||
/// The counts the refactoring promises, without its edit.
|
||||
fn eager(files: &[(PathBuf, String)], path: &Path, offset: u32) -> Result<(usize, usize), String> {
|
||||
organize_counts(files, path, offset).map(|(_, removed, sorted)| (removed, sorted))
|
||||
}
|
||||
|
||||
fn agree_everywhere(name: &str, text: &str) {
|
||||
let files = workspace(name, text);
|
||||
let path = file(name);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
assert_eq!(
|
||||
eager(&files, &path, offset),
|
||||
organize_offer(&files, &path, offset),
|
||||
"at offset {offset} of {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_promises_what_the_refactoring_delivers_at_every_offset() {
|
||||
agree_everywhere("user.sv", USER);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_tidy_run_is_refused_by_both_with_the_same_sentence() {
|
||||
agree_everywhere("tidy.sv", TIDY);
|
||||
let files = workspace("tidy.sv", TIDY);
|
||||
let at = TIDY.find("import a_pkg").expect("the import") as u32;
|
||||
assert_eq!(
|
||||
organize_offer(&files, &file("tidy.sv"), at),
|
||||
Err("these imports are already sorted, and every one of them is used.".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_commented_import_counts_the_same_in_both_answers() {
|
||||
agree_everywhere("commented.sv", COMMENTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_package_silences_both_answers() {
|
||||
agree_everywhere("unknown.sv", UNKNOWN);
|
||||
let files = workspace("unknown.sv", UNKNOWN);
|
||||
let at = UNKNOWN.find("import nowhere_pkg").expect("the import") as u32;
|
||||
assert!(organize_offer(&files, &file("unknown.sv"), at).is_err(), "the offer stays silent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_scope_run_and_a_package_run_agree_at_every_offset() {
|
||||
agree_everywhere("file_scope.sv", FILE_SCOPE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_parse_is_refused_by_both() {
|
||||
agree_everywhere("broken.sv", BROKEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_agrees_over_crlf_line_endings() {
|
||||
agree_everywhere("user.sv", &crlf(USER));
|
||||
agree_everywhere("commented.sv", &crlf(COMMENTED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_form_answers_what_the_text_form_answers_at_every_offset() {
|
||||
for (name, text) in [("user.sv", USER), ("commented.sv", COMMENTED), ("broken.sv", BROKEN)] {
|
||||
let files = workspace(name, text);
|
||||
let path = file(name);
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let tokens = tokenize(text).expect("the fixture lexes");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
assert_eq!(
|
||||
organize_offer(&files, &path, offset),
|
||||
organize_offer_in(&files, &path, &tree, &diagnostics, &semantics, &tokens, offset),
|
||||
"at offset {offset} of {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixtures really do reach an offer — a parity suite over an action that
|
||||
/// is never offered proves nothing.
|
||||
#[test]
|
||||
fn the_fixture_really_is_offered_the_action_with_the_title_it_promises() {
|
||||
let files = workspace("user.sv", USER);
|
||||
let at = USER.find("import b_pkg").expect("the import") as u32;
|
||||
let (removed, sorted) = organize_offer(&files, &file("user.sv"), at).expect("an offer");
|
||||
assert_eq!((removed, sorted), (1, 1), "one unused import goes and one is written back");
|
||||
assert_eq!(organize_title(removed, sorted), "lucisv: organize imports (removes 1, sorts 1)");
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! The four cheap gates answer the same thing over a parse the caller already
|
||||
//! has as they do over the text they would parse themselves.
|
||||
//!
|
||||
//! Take 5 §P1b (`docs/features/perf5-p1/README.md`) added `*_in` forms of
|
||||
//! `port_action_modules`, `imported_packages`, `extract_site` and
|
||||
//! `inline_site` so a server can spend the parse it already made. The text
|
||||
//! forms stayed and became wrappers, and this file is the proof that the two
|
||||
//! agree — over clean buffers, over buffers that do not parse, over CRLF, over
|
||||
//! text with a non-BMP character in front of the cursor, and at every byte of
|
||||
//! a small buffer rather than at a cursor chosen to pass.
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_refactor::{
|
||||
extract_site, extract_site_in, imported_packages, imported_packages_in, inline_site,
|
||||
inline_site_in, port_action_modules, port_action_modules_in,
|
||||
};
|
||||
|
||||
/// A module that instantiates another, imports two packages, and has items
|
||||
/// worth extracting — so every one of the four gates has something to find
|
||||
/// somewhere in it.
|
||||
const CLEAN: &str = "\
|
||||
module m (
|
||||
input logic clk_i,
|
||||
output logic q_o
|
||||
);
|
||||
import a_pkg::*;
|
||||
import b_pkg::*;
|
||||
logic w;
|
||||
sub u_sub (.a(clk_i), .b(w));
|
||||
assign q_o = w;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// The same text with a construct the parser cannot recover into an item, so
|
||||
/// the tolerant parse reports diagnostics — the case three of the four gates
|
||||
/// refuse over.
|
||||
const BROKEN: &str = "\
|
||||
module m;
|
||||
sub u_sub (.a(1));
|
||||
logic ;;; w
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A Verilog-2001 header, which is the one shape `convert to ANSI` answers at
|
||||
/// and the one `port_action_modules` finds without an instantiation.
|
||||
const NON_ANSI: &str = "\
|
||||
module old (a, b);
|
||||
input a;
|
||||
output b;
|
||||
assign b = a;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A non-BMP character in a comment before everything else: the bytes before
|
||||
/// every cursor differ from the UTF-16 units, which is the shape a client's
|
||||
/// position conversion produces.
|
||||
const ASTRAL: &str = "\
|
||||
// \u{1F600} a comment
|
||||
module m;
|
||||
sub u_sub (.a(1));
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn crlf(text: &str) -> String {
|
||||
text.replace('\n', "\r\n")
|
||||
}
|
||||
|
||||
/// Every gate, both ways, at one offset — asserting the two agree.
|
||||
fn agree_at(text: &str, offset: u32) {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
assert_eq!(
|
||||
port_action_modules(text, offset),
|
||||
port_action_modules_in(&tree, offset),
|
||||
"port_action_modules at {offset}"
|
||||
);
|
||||
assert_eq!(
|
||||
imported_packages(text, offset),
|
||||
imported_packages_in(&tree, &diagnostics, text, offset),
|
||||
"imported_packages at {offset}"
|
||||
);
|
||||
assert_eq!(
|
||||
inline_site(text, offset),
|
||||
inline_site_in(&tree, &diagnostics, text, offset),
|
||||
"inline_site at {offset}"
|
||||
);
|
||||
// Extraction answers for a range: the empty one at the cursor (which is
|
||||
// what an editor sends on a cursor move) and one covering the rest of the
|
||||
// buffer.
|
||||
let end = text.len() as u32;
|
||||
assert_eq!(
|
||||
extract_site(text, offset, offset),
|
||||
extract_site_in(&tree, &diagnostics, text, offset, offset),
|
||||
"extract_site at the cursor {offset}"
|
||||
);
|
||||
assert_eq!(
|
||||
extract_site(text, offset, end),
|
||||
extract_site_in(&tree, &diagnostics, text, offset, end),
|
||||
"extract_site over {offset}..{end}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Every byte offset of a buffer, and one past its end.
|
||||
fn agree_everywhere(text: &str) {
|
||||
for offset in 0..=text.len() as u32 {
|
||||
agree_at(text, offset);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_answer_a_clean_buffer_exactly_as_the_text_gates_do() {
|
||||
agree_everywhere(CLEAN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_answer_a_buffer_that_does_not_parse_exactly_as_the_text_gates_do() {
|
||||
agree_everywhere(BROKEN);
|
||||
// And the three that refuse over diagnostics really do refuse here, so
|
||||
// this case is not agreeing by both answering about a clean buffer.
|
||||
let (tree, diagnostics) = parse_source_tolerant(BROKEN);
|
||||
assert!(!diagnostics.is_empty(), "the fixture must not parse cleanly");
|
||||
let cursor = BROKEN.find("u_sub").expect("the instance") as u32;
|
||||
assert!(imported_packages_in(&tree, &diagnostics, BROKEN, cursor).is_empty());
|
||||
assert!(inline_site_in(&tree, &diagnostics, BROKEN, cursor).is_none());
|
||||
assert!(extract_site_in(&tree, &diagnostics, BROKEN, cursor, cursor).is_none());
|
||||
// The port gate has no diagnostics check and never had one: it still finds
|
||||
// the instantiation under the cursor.
|
||||
assert_eq!(port_action_modules_in(&tree, cursor), vec!["sub".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_agree_over_crlf_line_endings() {
|
||||
agree_everywhere(&crlf(CLEAN));
|
||||
agree_everywhere(&crlf(BROKEN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_agree_with_a_non_bmp_character_before_the_cursor() {
|
||||
agree_everywhere(ASTRAL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_agree_on_a_non_ansi_header() {
|
||||
agree_everywhere(NON_ANSI);
|
||||
// Again, not vacuously: the header cursor really does name its module.
|
||||
let (tree, _) = parse_source_tolerant(NON_ANSI);
|
||||
let cursor = NON_ANSI.find("(a, b)").expect("the header") as u32;
|
||||
assert_eq!(port_action_modules_in(&tree, cursor), vec!["old".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_agree_on_an_empty_buffer() {
|
||||
agree_everywhere("");
|
||||
agree_everywhere("\n\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_find_what_the_fixture_was_written_to_offer() {
|
||||
// A guard on the fixture itself: if `CLEAN` stopped offering anything,
|
||||
// every assertion above would still pass and prove nothing.
|
||||
let (tree, diagnostics) = parse_source_tolerant(CLEAN);
|
||||
let import = CLEAN.find("import a_pkg").expect("the import run") as u32;
|
||||
assert_eq!(
|
||||
imported_packages_in(&tree, &diagnostics, CLEAN, import),
|
||||
vec!["a_pkg".to_string(), "b_pkg".to_string()]
|
||||
);
|
||||
let instance = CLEAN.find("u_sub").expect("the instance") as u32;
|
||||
assert_eq!(port_action_modules_in(&tree, instance), vec!["sub".to_string()]);
|
||||
assert!(inline_site_in(&tree, &diagnostics, CLEAN, instance).is_some());
|
||||
let assign = CLEAN.find("assign q_o").expect("the assign") as u32;
|
||||
assert!(extract_site_in(&tree, &diagnostics, CLEAN, assign, assign).is_some());
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! The offer predicate answers exactly what the four full refactorings answer.
|
||||
//!
|
||||
//! Take 5 §P1c (`docs/features/perf5-p1/README.md`) added
|
||||
//! [`vlog_refactor::port_offers`], which asks each of the four port
|
||||
//! refactorings its plan-time questions and writes the title it would carry —
|
||||
//! no workspace index, no verification, no edits kept. This file is the proof
|
||||
//! that the menu it writes is the menu [`vlog_refactor::port_actions`] writes,
|
||||
//! at **every byte offset** of every fixture, not at cursors chosen to pass.
|
||||
//!
|
||||
//! Where the two may legitimately differ is stated in `ports::offer`'s own
|
||||
//! documentation: `check::verify_splice` and `ports::confirm` run after the
|
||||
//! plan and the predicate does not reproduce them. Every fixture below is
|
||||
//! asserted to be free of that difference, so a change that starts producing
|
||||
//! one fails here rather than reaching a user's lightbulb.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_refactor::{port_actions, port_offers, port_offers_in, PortOfferKind};
|
||||
|
||||
/// A module with a port its body never mentions (so the removal is offered),
|
||||
/// written the ANSI way, instantiating another module by name.
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic clk_i,
|
||||
input logic spare_i,
|
||||
output logic q_o
|
||||
);
|
||||
logic w;
|
||||
logic b;
|
||||
sub u_sub (.a(clk_i));
|
||||
sub u_star (.*);
|
||||
assign q_o = w;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// The module `top` instantiates: two ports, so the instantiation above is
|
||||
/// missing one and the `.*` stands for both.
|
||||
const SUB: &str = "\
|
||||
module sub (
|
||||
input logic a,
|
||||
input logic b
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A Verilog-2001 header — the one shape `convert to ANSI` answers at.
|
||||
const OLD: &str = "\
|
||||
module old (a, b);
|
||||
input a;
|
||||
output b;
|
||||
assign b = a;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// An instantiation connecting by position, a `bind` directive's own, and a
|
||||
/// second `.*`: three of the shapes the planners refuse over.
|
||||
const AWKWARD: &str = "\
|
||||
module awkward;
|
||||
logic a;
|
||||
logic b;
|
||||
sub u_ordered (a, b);
|
||||
sub u_two (.a(a), .b(b));
|
||||
bind awkward sub u_bound (.*);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A module nested inside another and one inside a package: neither is a
|
||||
/// *unit*, so `locate_module` refuses over both and so must the predicate.
|
||||
const NESTED: &str = "\
|
||||
package p;
|
||||
module inner (input logic a);
|
||||
endmodule
|
||||
endpackage
|
||||
module outer (input logic a);
|
||||
module deep (input logic b);
|
||||
endmodule
|
||||
sub u_sub (.a(a));
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A file that does not parse cleanly: the expansion and the conversion refuse
|
||||
/// over it, the removal and the propagation do not.
|
||||
const BROKEN: &str = "\
|
||||
module m (input logic a);
|
||||
sub u_sub (.a(a));
|
||||
logic ;;; w
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A second declaration of `sub`, which makes the name ambiguous and every
|
||||
/// refactoring that has to look it up silent.
|
||||
const TWIN: &str = "\
|
||||
module sub (
|
||||
input logic a
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn file(name: &str) -> PathBuf {
|
||||
PathBuf::from("/rtl").join(name)
|
||||
}
|
||||
|
||||
fn workspace(entries: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
entries.iter().map(|(name, text)| (file(name), (*text).to_string())).collect()
|
||||
}
|
||||
|
||||
fn crlf(text: &str) -> String {
|
||||
text.replace('\n', "\r\n")
|
||||
}
|
||||
|
||||
/// The eager menu and the offered menu at one offset, as comparable lists.
|
||||
fn agree_at(files: &[(PathBuf, String)], path: &Path, offset: u32) {
|
||||
let eager: Vec<String> =
|
||||
port_actions(files, path, offset).into_iter().map(|a| a.title).collect();
|
||||
let offered: Vec<String> =
|
||||
port_offers(files, path, offset).into_iter().map(|o| o.title).collect();
|
||||
assert_eq!(eager, offered, "at offset {offset} of {}", path.display());
|
||||
}
|
||||
|
||||
/// Every byte of one file of a workspace, the end included.
|
||||
fn agree_everywhere(files: &[(PathBuf, String)], name: &str) {
|
||||
let path = file(name);
|
||||
let text = files
|
||||
.iter()
|
||||
.find(|(held, _)| *held == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("the file is in the workspace");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
agree_at(files, &path, offset);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_at_every_offset_of_an_ansi_module() {
|
||||
let files = workspace(&[("top.sv", TOP), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "top.sv");
|
||||
agree_everywhere(&files, "sub.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_at_every_offset_of_a_non_ansi_header() {
|
||||
let files = workspace(&[("old.sv", OLD), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "old.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_over_the_shapes_the_planners_refuse() {
|
||||
let files = workspace(&[("awkward.sv", AWKWARD), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "awkward.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_module_is_no_more_a_unit_to_the_offer_than_to_the_index() {
|
||||
let files = workspace(&[("nested.sv", NESTED), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "nested.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_on_a_buffer_that_does_not_parse() {
|
||||
let files = workspace(&[("broken.sv", BROKEN), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "broken.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_two_files_declare_is_silent_in_both_answers() {
|
||||
let files = workspace(&[("top.sv", TOP), ("sub.sv", SUB), ("twin.sv", TWIN)]);
|
||||
agree_everywhere(&files, "top.sv");
|
||||
// And the ambiguity really is what silences it: the same cursor offers
|
||||
// with only one declaration in scope.
|
||||
let one = workspace(&[("top.sv", TOP), ("sub.sv", SUB)]);
|
||||
let at = TOP.find("sub u_sub").expect("the instantiation") as u32;
|
||||
assert!(!port_offers(&one, &file("top.sv"), at).is_empty(), "one declaration offers");
|
||||
assert!(port_offers(&files, &file("top.sv"), at).is_empty(), "two declarations do not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_over_crlf_line_endings() {
|
||||
let files = workspace(&[("top.sv", &crlf(TOP)), ("sub.sv", &crlf(SUB))]);
|
||||
agree_everywhere(&files, "top.sv");
|
||||
let files = workspace(&[("old.sv", &crlf(OLD)), ("sub.sv", &crlf(SUB))]);
|
||||
agree_everywhere(&files, "old.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_is_empty_for_a_file_the_workspace_does_not_hold() {
|
||||
let files = workspace(&[("top.sv", TOP), ("sub.sv", SUB)]);
|
||||
assert!(port_offers(&files, &file("absent.sv"), 0).is_empty());
|
||||
assert!(port_actions(&files, &file("absent.sv"), 0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_form_answers_what_the_text_form_answers_at_every_offset() {
|
||||
let files = workspace(&[("top.sv", TOP), ("sub.sv", SUB), ("old.sv", OLD)]);
|
||||
for name in ["top.sv", "old.sv"] {
|
||||
let path = file(name);
|
||||
let text = files
|
||||
.iter()
|
||||
.find(|(held, _)| *held == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("the file is in the workspace");
|
||||
let (tree, diagnostics) = parse_source_tolerant(&text);
|
||||
let semantics = vlog_semantic::analyze(&tree, &text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
assert_eq!(
|
||||
port_offers(&files, &path, offset),
|
||||
port_offers_in(&files, &path, &tree, &diagnostics, &semantics, offset),
|
||||
"at offset {offset} of {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each of the four really is reached by one of the fixtures — a parity suite
|
||||
/// over four refactorings none of which ever offers proves nothing.
|
||||
#[test]
|
||||
fn every_one_of_the_four_refactorings_is_offered_somewhere_in_the_fixtures() {
|
||||
let mut seen: Vec<PortOfferKind> = Vec::new();
|
||||
for (entries, name) in [
|
||||
(workspace(&[("top.sv", TOP), ("sub.sv", SUB)]), "top.sv"),
|
||||
(workspace(&[("old.sv", OLD), ("sub.sv", SUB)]), "old.sv"),
|
||||
] {
|
||||
let path = file(name);
|
||||
let text = entries
|
||||
.iter()
|
||||
.find(|(held, _)| *held == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("the file is in the workspace");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
for offer in port_offers(&entries, &path, offset) {
|
||||
if !seen.contains(&offer.kind) {
|
||||
seen.push(offer.kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for wanted in [
|
||||
PortOfferKind::Remove,
|
||||
PortOfferKind::Propagate,
|
||||
PortOfferKind::Expand,
|
||||
PortOfferKind::Convert,
|
||||
] {
|
||||
assert!(seen.contains(&wanted), "{wanted:?} is never offered: {seen:?}");
|
||||
}
|
||||
}
|
||||
@@ -38,8 +38,8 @@ pub use model::{
|
||||
pub use workspace::{
|
||||
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
|
||||
DefinitionKey, ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder,
|
||||
IndexCounts, InheritanceEdge, InstanceOccurrence, InstantiationEdge, ReferenceSite, Utf16Pos,
|
||||
Utf16Range, WorkspaceIndex, WorkspaceSymbol,
|
||||
IndexCounts, IndexTableSizes, InheritanceEdge, InstanceOccurrence, InstantiationEdge,
|
||||
ReferenceSite, Utf16Pos, Utf16Range, WorkspaceIndex, WorkspaceSymbol,
|
||||
};
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -17,8 +17,8 @@ use super::external::{fold_path, last_segment, member_chain, own_members};
|
||||
use super::hierarchy;
|
||||
use super::record::{FileFacts, ReferenceFact};
|
||||
use super::{
|
||||
reexport, Def, DefinitionKey, FileId, IndexCounts, InheritanceEdge, InstantiationEdge,
|
||||
Reexport, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
|
||||
reexport, Def, DefinitionKey, FileId, IndexCounts, IndexTableSizes, InheritanceEdge,
|
||||
InstantiationEdge, Reexport, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
|
||||
};
|
||||
|
||||
impl WorkspaceIndex {
|
||||
@@ -516,6 +516,26 @@ impl WorkspaceIndex {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many entries each table holds — [`IndexCounts`] asked by table
|
||||
/// rather than by declaration kind.
|
||||
pub fn table_sizes(&self) -> IndexTableSizes {
|
||||
IndexTableSizes {
|
||||
unit_names: self.units.len(),
|
||||
unit_defs: self.units.values().map(Vec::len).sum(),
|
||||
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
|
||||
hier_members: self.hier_members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
|
||||
reference_keys: self.reference_sites.len(),
|
||||
reference_sites: self.reference_sites.values().map(Vec::len).sum(),
|
||||
words: self.facts.iter().map(|facts| facts.words().len()).sum(),
|
||||
word_bytes: self
|
||||
.facts
|
||||
.iter()
|
||||
.flat_map(|facts| facts.words())
|
||||
.map(|word| word.len())
|
||||
.sum(),
|
||||
}
|
||||
}
|
||||
|
||||
fn units_of_kind(&self, kind: SymbolKind) -> usize {
|
||||
self.units.values().flatten().filter(|d| d.kind == kind).count()
|
||||
}
|
||||
|
||||
@@ -365,3 +365,30 @@ pub struct IndexCounts {
|
||||
/// `extends` edges recorded, one per class that names a base.
|
||||
pub inheritances: usize,
|
||||
}
|
||||
|
||||
/// How many entries each of a built index's tables holds — the memory
|
||||
/// question, asked in counts rather than in bytes.
|
||||
///
|
||||
/// Additive to [`IndexCounts`] rather than folded into it: those are the
|
||||
/// headline numbers a user is told after a scan ("1 544 modules"), these are
|
||||
/// the per-table sizes a performance round reads once at the end of a traced
|
||||
/// scan. Cheap by construction — map lengths and one sum per table, no walk
|
||||
/// into a `Def` and no allocation — but it is still a walk over the tables, so
|
||||
/// it belongs at the end of a scan and not on a request path.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct IndexTableSizes {
|
||||
/// File-scope names, and the declarations under them once duplicates are
|
||||
/// counted separately.
|
||||
pub unit_names: usize,
|
||||
pub unit_defs: usize,
|
||||
/// Connection-surface member declarations, and the hierarchical-only ones.
|
||||
pub members: usize,
|
||||
pub hier_members: usize,
|
||||
/// Declarations that have at least one recorded use, and the uses.
|
||||
pub reference_keys: usize,
|
||||
pub reference_sites: usize,
|
||||
/// The identifier census every file carries since `FACTS_FORMAT` 13, and
|
||||
/// what those strings weigh.
|
||||
pub words: usize,
|
||||
pub word_bytes: usize,
|
||||
}
|
||||
@@ -201,6 +201,25 @@ impl FileFacts {
|
||||
facts_of(path, src)
|
||||
}
|
||||
|
||||
/// [`FileFacts::of`], handing back the [`Semantics`] the record was read
|
||||
/// off instead of dropping it.
|
||||
///
|
||||
/// The mirror of [`FileFacts::from_analysis`]: that one is for a caller
|
||||
/// who already has an analysis, this one for a caller who is about to want
|
||||
/// the analysis it makes anyway. [`FileFacts::of`] parses the file,
|
||||
/// analyses it, reads the record off that analysis and drops it — so a
|
||||
/// caller who then wants the analysis pays for a second whole-file parse
|
||||
/// of text nothing has touched. A request-local refactoring scope wants
|
||||
/// exactly both (take 5 §P2b, `docs/features/perf5-p2/README.md`).
|
||||
///
|
||||
/// The two are **one function**: `of` is this one with the analysis
|
||||
/// discarded, so the record cannot depend on which was called. The same
|
||||
/// stack requirement applies — call it on a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE`.
|
||||
pub fn analyzed(path: PathBuf, src: &str) -> (FileFacts, Semantics) {
|
||||
analyzed_facts(path, src)
|
||||
}
|
||||
|
||||
/// The same record read off an analysis the caller **already has** — the
|
||||
/// tree, the `` `define`` table and the [`Semantics`] of one file — instead
|
||||
/// of from that file's text.
|
||||
@@ -275,13 +294,20 @@ impl Census {
|
||||
|
||||
/// Parse one file and read off what it declares and what it points at.
|
||||
pub(super) fn facts_of(path: PathBuf, src: &str) -> FileFacts {
|
||||
analyzed_facts(path, src).0
|
||||
}
|
||||
|
||||
/// [`facts_of`], keeping the analysis — the one body both it and
|
||||
/// [`FileFacts::analyzed`] are, so the record is the same either way.
|
||||
fn analyzed_facts(path: PathBuf, src: &str) -> (FileFacts, Semantics) {
|
||||
let (tree, defines, census) = parse_and_collect(src);
|
||||
let sem = analyze(&tree, src);
|
||||
// One pass over the source's newlines, so every declaration below can be
|
||||
// given its line without anyone reading the file again later. It is a
|
||||
// percent of the parse it sits beside (`docs/perf/README.md`).
|
||||
let lines = LineIndex::new(src);
|
||||
facts_from_analysis(path, &tree, defines, &sem, src, &lines, census)
|
||||
let facts = facts_from_analysis(path, &tree, defines, &sem, src, &lines, census);
|
||||
(facts, sem)
|
||||
}
|
||||
|
||||
/// Read off what one file contributes, from its finished analysis.
|
||||
|
||||
@@ -2192,16 +2192,12 @@ fn as_a_server_analyzes(
|
||||
(tree, defines, sem, vlog_parser::LineIndex::new(src), tokens)
|
||||
}
|
||||
|
||||
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
|
||||
///
|
||||
/// The record format is the comparison — the encoded line is every field the
|
||||
/// index and the persistent store ever read — so a byte-equal line is the
|
||||
/// whole equivalence. Two paths that could drift here would be a corruption
|
||||
/// seed: the index would describe a buffer by facts its own parse disagrees
|
||||
/// with.
|
||||
#[test]
|
||||
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
let crafted = [
|
||||
/// The crafted files the two record-equality tests and the §P2b analysis
|
||||
/// tests all read: nothing, nothing that lexes, every file-scope declaration
|
||||
/// kind, macros, external candidates, a file-scope instantiation, a generate
|
||||
/// body and a tree with error nodes.
|
||||
fn crafted_sources() -> &'static [&'static str] {
|
||||
&[
|
||||
// Nothing at all, and nothing that lexes.
|
||||
"",
|
||||
" \n\t\n",
|
||||
@@ -2228,8 +2224,19 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
\x20 sub u_gen (.clk(clk));\n end endgenerate\nendmodule\n",
|
||||
// A tree with error nodes: the tolerant parse still contributes.
|
||||
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n",
|
||||
];
|
||||
for src in crafted {
|
||||
]
|
||||
}
|
||||
|
||||
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
|
||||
///
|
||||
/// The record format is the comparison — the encoded line is every field the
|
||||
/// index and the persistent store ever read — so a byte-equal line is the
|
||||
/// whole equivalence. Two paths that could drift here would be a corruption
|
||||
/// seed: the index would describe a buffer by facts its own parse disagrees
|
||||
/// with.
|
||||
#[test]
|
||||
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
for src in crafted_sources() {
|
||||
let path = PathBuf::from("/w/x.sv");
|
||||
let (tree, defines, sem, lines, tokens) = as_a_server_analyzes(src);
|
||||
let from_text = FileFacts::of(path.clone(), src);
|
||||
@@ -2244,6 +2251,75 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `FileFacts::analyzed` is `FileFacts::of` keeping its analysis (take 5 §P2b).
|
||||
///
|
||||
/// Two claims, both over the same crafted set the record-equality test uses:
|
||||
/// the record is the record `of` gives, byte for byte in its encoded form; and
|
||||
/// the `Semantics` handed back is the one a caller would have computed for
|
||||
/// itself with `analyze(&parse_source_tolerant(src).0, src)` — which is what
|
||||
/// makes retaining it instead of re-parsing a pure saving rather than a second
|
||||
/// opinion. `Semantics` has no `PartialEq`, so the comparison is every
|
||||
/// declaration and every use it holds, with its span, kind and resolution.
|
||||
#[test]
|
||||
fn analyzed_gives_the_record_of_gives_and_the_analysis_a_caller_would_compute() {
|
||||
for src in crafted_sources() {
|
||||
let path = PathBuf::from("/w/x.sv");
|
||||
let (facts, sem) = FileFacts::analyzed(path.clone(), src);
|
||||
let from_text = FileFacts::of(path, src);
|
||||
assert_eq!(facts, from_text, "the records differ for {src:?}");
|
||||
assert_eq!(facts.encode(), from_text.encode(), "and their encoded forms for {src:?}");
|
||||
let alone = semantics(src);
|
||||
assert_eq!(print_of(&sem), print_of(&alone), "the analyses differ for {src:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every declaration and every use one analysis holds, as comparable text.
|
||||
fn print_of(sem: &Semantics) -> String {
|
||||
let mut out = String::new();
|
||||
for symbol in sem.symbols() {
|
||||
out.push_str(&format!(
|
||||
"sym {} {:?} {}..{} decl {}..{} type {:?}\n",
|
||||
symbol.name,
|
||||
symbol.kind,
|
||||
symbol.name_span.start,
|
||||
symbol.name_span.end,
|
||||
symbol.decl_span.start,
|
||||
symbol.decl_span.end,
|
||||
symbol.type_name
|
||||
));
|
||||
}
|
||||
for reference in sem.references() {
|
||||
out.push_str(&format!(
|
||||
"ref {} {}..{} -> {:?}\n",
|
||||
reference.name,
|
||||
reference.name_span.start,
|
||||
reference.name_span.end,
|
||||
reference.resolution
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An index built file-by-file from `FileFacts::analyzed` is the index a whole
|
||||
/// `WorkspaceIndex::build` over the same texts gives — same fingerprint, which
|
||||
/// is the workspace's own witness for "the same index".
|
||||
#[test]
|
||||
fn an_index_from_analyzed_facts_is_the_index_a_build_gives() {
|
||||
let files: Vec<(PathBuf, &str)> = crafted_sources()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, src)| (PathBuf::from(format!("/w/{i}.sv")), *src))
|
||||
.collect();
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, s)| (p.clone(), *s)));
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
for (path, src) in &files {
|
||||
builder.add_facts(FileFacts::analyzed(path.clone(), src).0);
|
||||
}
|
||||
let assembled = builder.finish();
|
||||
assert_eq!(assembled.fingerprint(), built.fingerprint());
|
||||
assert_eq!(assembled.files(), built.files(), "and the same file ids");
|
||||
}
|
||||
|
||||
/// The same claim over every file of the real corpus, which is where the
|
||||
/// constructs nobody thought to craft live.
|
||||
#[test]
|
||||
|
||||
+11
-7
@@ -1,6 +1,6 @@
|
||||
# Verilog/SystemVerilog coverage gaps — ranked (2026-09-01)
|
||||
|
||||
**Reading this report today (2026-09-05).** The survey below is a historical
|
||||
**Reading this report today (2026-09-07).** The survey below is a historical
|
||||
v0.21.0 measurement with later amendments, not a fresh list of current failures.
|
||||
Use [repository-analysis.md](repository-analysis.md) and [topo.md](topo.md) for
|
||||
current implementation status. Original probe counts remain historical.
|
||||
@@ -12,12 +12,16 @@ The prior audit's atomic-write, project lint-selection and directory-cycle
|
||||
findings are also fixed. Bare item-level `begin` blocks are recovered for
|
||||
lint/editor consumers; strict formatting still refuses them.
|
||||
|
||||
At committed `9ef1058`, type-name spans replace `vlog_semantic/src/scan.rs`,
|
||||
and package re-exports resolve through shared member edges (facts codec 18).
|
||||
Both are accepted for the next release. The active hierarchical-tail work
|
||||
proposes codec 19; QA is pending, and handshake 23 remains open. DPI-export
|
||||
name binding is a separate remaining gap (handshake 31), and generate-block
|
||||
hierarchy and cross-file macro expansion remain outside these fixes.
|
||||
Current snapshot **`df4e714`**, latest release **v0.49.0**: type-name spans,
|
||||
package re-exports and hierarchical tails shipped in v0.45.0 (facts codec
|
||||
**19**, handshake 23 closed). v0.46–0.49 added five refactorings, the
|
||||
`unused-import` rule (**74 rules** total), and the DUT hierarchy view. The
|
||||
L3 grammar forms, L6 real `randsequence` nodes, L9 ANSI conversion and L10
|
||||
optional UVM indentation are delivered, as annotated below. DPI-export name
|
||||
binding (handshake 31), generate-block hierarchy and cross-file macro expansion
|
||||
remain gaps. Refactor handshakes 32–33 and the newly reproduced UVM-option
|
||||
cache omission (34, fixed in 0.50.0 by TODO §59) are detailed in the current repository analysis. These
|
||||
status updates do not replace the original survey with a new corpus sweep.
|
||||
|
||||
What lucisv 0.21.0 does not yet handle, ranked by severity, from two
|
||||
independent sweeps crossed against each other:
|
||||
|
||||
@@ -74,6 +74,13 @@ parser** a push does, so the two paths cannot drift.
|
||||
first index is built against the default scope, and a pulled
|
||||
`lucisv.exclude`/`lucisv.filelist` costs one extra rescan when it lands.
|
||||
Nothing is *wrong* in between, it is simply the wider scope.
|
||||
**2026-09-08 (perf5-p4 §P4b2):** no longer true of the common case. The
|
||||
startup is now staged: the pull goes out first and the one startup scan
|
||||
runs at the answered scope (`server/startup.rs`), so a pulled
|
||||
`exclude`/`filelist`/`maxFileSize` costs nothing extra; the sentence above
|
||||
describes only an answer that arrives after the 2 s bound
|
||||
(`CONFIGURATION_WAIT`), which is then an ordinary settings change with an
|
||||
ordinary rescan behind it.
|
||||
**2026-08-27:** `lucisv.index.maxFileSize` joins those two — a pulled cap
|
||||
that differs from the 1 MiB default costs the same one extra rescan — and
|
||||
`lucisv.index.logFiles` shows the other face of the same fact: the startup
|
||||
|
||||
@@ -23,12 +23,17 @@ what they would have been anyway (modulo one extra summary segment).
|
||||
assumption parallel-files already relies on. If that ever stops being
|
||||
true (a formatter that reads the file's *name*, or another file), this
|
||||
cache silently goes wrong and the assumption must be revisited here.
|
||||
- **`line-length` and `indent` are the whole config surface.** They are
|
||||
the only two things `lucisv_core::config::FileConfig` can put into
|
||||
`vlog_formatter::Config`. The key stores the *resolved values*, not the
|
||||
config file's path or mtime — so moving a `lucisv.toml` around, or
|
||||
switching from a file to an equivalent `--line-length` flag, correctly
|
||||
does **not** invalidate anything, while a real value change does.
|
||||
- **The key covers every `FileConfig` field that reaches the formatter.**
|
||||
Today that is `line-length`, `indent` and `[format] uvm-utils-indent` —
|
||||
everything `lucisv_core::config::FileConfig` can put into
|
||||
`vlog_formatter::Config` (see `lucisv/src/args.rs::config_with`). Any
|
||||
future setting that changes formatted output must join `Entry` and the
|
||||
store line in the same change; a setting left out is a stale clean
|
||||
verdict, which is exactly the bug TODO §59 fixed. The key stores the
|
||||
*resolved values*, not the config file's path or mtime — so moving a
|
||||
`lucisv.toml` around, or switching from a file to an equivalent
|
||||
`--line-length` flag, correctly does **not** invalidate anything, while
|
||||
a real value change does.
|
||||
`exclude` is not part of the key: it changes *which* files are visited,
|
||||
never how one is formatted.
|
||||
- **The version string is the workspace version** (`env!("CARGO_PKG_VERSION")`
|
||||
@@ -56,8 +61,8 @@ what they would have been anyway (modulo one extra summary segment).
|
||||
|
||||
### The key
|
||||
|
||||
Per file: **(content hash, line-length, indent, lucisv version)**, keyed on
|
||||
the file path.
|
||||
Per file: **(content hash, line-length, indent, uvm-utils-indent, lucisv
|
||||
version)**, keyed on the file path.
|
||||
|
||||
- **Content hash: hand-rolled FNV-1a, 64-bit**, over the file's bytes
|
||||
(`cache::content_hash`). Two reasons it is not
|
||||
@@ -111,7 +116,7 @@ the hash of **the bytes that were written** goes in.
|
||||
|
||||
| Situation | Cache read | Cache write | Reported as |
|
||||
|---|---|---|---|
|
||||
| Hit (hash + line-length + indent + version all match) | skip all work | entry kept | `left unchanged`, plus `N files from cache` |
|
||||
| Hit (hash + line-length + indent + uvm-utils-indent + version all match) | skip all work | entry kept | `left unchanged`, plus `N files from cache` |
|
||||
| Miss, file is already formatted | — | record `hash(src)` | `left unchanged` |
|
||||
| Miss, file rewritten in place (write succeeded) | — | record `hash(output)` | `reformatted` |
|
||||
| Miss, `--check`/`--diff` says it would reformat | — | **nothing** | `would be reformatted`, exit 1 |
|
||||
@@ -140,7 +145,7 @@ One text file, `<cache-dir>/cache`, one line per path, tab-separated,
|
||||
hand-rolled in the style of the corpus TSV:
|
||||
|
||||
```
|
||||
<content-hash, 16 hex digits>\t<line-length>\t<indent>\t<version>\t<path>
|
||||
<content-hash, 16 hex digits>\t<line-length>\t<indent>\t<uvm-utils-indent, `true`/`false`>\t<version>\t<path>
|
||||
```
|
||||
|
||||
The path is last because it is the only field that can contain
|
||||
@@ -153,7 +158,7 @@ third-party dependency between them (`rayon`, in `lucisv`). `serde` exists
|
||||
in the workspace only because `lucisv_server` needs it for LSP wire
|
||||
messages — `lucisv`/`lucisv_core` do not depend on it, and taking it here
|
||||
would put a proc-macro build step into the CLI's dependency graph to
|
||||
encode five fields. Five fields on a line need no schema; CLAUDE.md's
|
||||
encode six fields. Six fields on a line need no schema; CLAUDE.md's
|
||||
"standard library first" says so.
|
||||
|
||||
Loading, corruption and staleness:
|
||||
@@ -168,6 +173,15 @@ Loading, corruption and staleness:
|
||||
silently (that is not corruption, just another lucisv's entry). It is not
|
||||
carried forward on write, so alternating between two lucisv versions
|
||||
rebuilds the cache each time.
|
||||
- **A well-formed line in an older field layout is dropped the same way.**
|
||||
A five-field line is the shape lucisv wrote before `uvm-utils-indent`
|
||||
joined the key: it says nothing about the option, so it is skipped
|
||||
individually rather than trusted or treated as corruption. (The version
|
||||
field alone already makes a 0.49.0 store miss at 0.50.0; the tolerance
|
||||
is what keeps the codec self-describing when the two ever come apart —
|
||||
a hand-written store, a downgrade.) A five-field line that is *not*
|
||||
well formed in that older shape is corruption like any other, and
|
||||
discards the file.
|
||||
- **Writing is atomic**: the new text goes to `<cache-dir>/cache.<pid>.tmp`
|
||||
and is `rename`d over `cache`. A reader therefore sees the old file or
|
||||
the new one, never a half-written one.
|
||||
@@ -256,12 +270,19 @@ the only writer of an entry is the code path that just observed
|
||||
- **Consumes `docs/features/config-discovery/README.md`'s promise** that
|
||||
the cache key "must include the resolved per-file settings … not just
|
||||
file content + lucisv version". Done, with the *values*
|
||||
(`Config::max_width`, `Config::indent_width`) rather than the config
|
||||
file's identity, so two trees governed by different `lucisv.toml` files
|
||||
that happen to say the same thing share entries correctly.
|
||||
- **Consumes `vlog_formatter::Config`** read-only, for its two fields.
|
||||
Nothing in `vlog_parser` / `vlog_formatter` / `vlog_linter` was
|
||||
touched.
|
||||
(`Config::max_width`, `Config::indent_width`,
|
||||
`Config::uvm_utils_indent`) rather than the config file's identity, so
|
||||
two trees governed by different `lucisv.toml` files that happen to say
|
||||
the same thing share entries correctly.
|
||||
- **Consumes `vlog_formatter::Config`** read-only, for every field
|
||||
`args.rs::config_with` can set from a `lucisv.toml`. **The contract this
|
||||
crate owes back (TODO §59, 2026-09-07):** a new formatter setting that
|
||||
changes output is a change to `cache::Entry`, to
|
||||
`lucisv/src/main.rs::entry_for` and to the store line, in the same
|
||||
commit — otherwise a warm cache serves the old setting's verdict.
|
||||
`Config::uvm_utils_indent` was added in 0.49.0 without that and is the
|
||||
reason this line exists. Nothing in `vlog_parser` / `vlog_formatter` /
|
||||
`vlog_linter` was touched.
|
||||
- **Where the module lives: `lucisv_core::cache`,** next to `config` and
|
||||
`walk`. `lucisv_core` is by its own doc comment "the parts of lucisv that
|
||||
decide *which* files are processed and *with what settings*", and "this
|
||||
@@ -269,8 +290,9 @@ the only writer of an entry is the code path that just observed
|
||||
It also keeps the door open for `lucisv_server`: a language server that
|
||||
wanted to avoid re-formatting an unedited buffer on save would want the
|
||||
same predicate, and would otherwise have to duplicate the file format.
|
||||
Nothing in the module is CLI-specific — it takes paths, `u64`s and two
|
||||
`usize`s and has no opinion about arguments or reporting.
|
||||
Nothing in the module is CLI-specific — it takes paths and the bare
|
||||
scalars of the key (a `u64`, two `usize`s and a `bool`) and has no
|
||||
opinion about arguments or reporting.
|
||||
- **Promises to whoever changes the formatter's output** (alignment
|
||||
inference, `--lines`, any style change): **bump the workspace version**,
|
||||
or every user with a warm cache keeps their old formatting on files
|
||||
@@ -289,7 +311,10 @@ the only writer of an entry is the code path that just observed
|
||||
(`load` / `disabled` / `is_clean` / `record` / `store`).
|
||||
- [x] Hand-rolled tab-separated store, sorted by path, atomic
|
||||
temp+rename write, self-ignoring `.gitignore` in the cache dir.
|
||||
- [x] Corrupt / unreadable / wrong-version entries ignored, never fatal.
|
||||
- [x] Corrupt / unreadable / wrong-version entries ignored, never fatal;
|
||||
so is a line in the pre-`uvm-utils-indent` five-field shape.
|
||||
- [x] `[format] uvm-utils-indent` in `Entry`, in `entry_for` and as the
|
||||
store's fourth field (TODO §59).
|
||||
- [x] `--no-cache` and `--cache-dir <PATH>` in `args.rs` and `--help`,
|
||||
accepted (and inert) for `lucisv check`.
|
||||
- [x] Lookup at the top of `process_file`; entries collected through the
|
||||
@@ -303,7 +328,8 @@ the only writer of an entry is the code path that just observed
|
||||
content change invalidates, indent change invalidates, wrong
|
||||
version ignored, `--no-cache`, corrupt file tolerated, `--check`
|
||||
exit codes, `--threads` determinism with a warm cache, default
|
||||
cache dir is cwd-relative and self-ignoring).
|
||||
cache dir is cwd-relative and self-ignoring, `uvm-utils-indent`
|
||||
invalidates in both directions, an older store is rebuilt).
|
||||
- [x] Root `.gitignore` entry, `README.md` Cache section, `TODO.md` §3
|
||||
box.
|
||||
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test`.
|
||||
@@ -438,6 +464,75 @@ their work lands.
|
||||
- No `Cargo.toml` / `Cargo.lock` change: no new dependency, and
|
||||
`lucisv_core` still has an empty `[dependencies]`.
|
||||
|
||||
### 2026-09-07 — dev agent (TODO §59: `uvm-utils-indent` joins the key)
|
||||
|
||||
The owner's audit (topo §2.9 row 34, and the "Confirmed cache omission"
|
||||
paragraph of `docs/repository-analysis.md`) found the key stale against
|
||||
0.49.0's `[format] uvm-utils-indent`. `args.rs::config_with` sets
|
||||
`Config::uvm_utils_indent`, the formatter indents `` `uvm_field_* ``
|
||||
under it, but `Entry` and `entry_for` still named only content,
|
||||
line-length and indent — so a clean `--check` cached with the option off
|
||||
kept exiting 0 after the option was turned on, while `--no-cache
|
||||
--check` exited 1. Reproduced first, on the fixture from the audit.
|
||||
|
||||
**The fix, four lines of real change.** `Entry` gains
|
||||
`uvm_utils_indent: bool` (equality is derived, so the key follows for
|
||||
free); `lucisv/src/main.rs::entry_for` fills it from the same `Config`
|
||||
the formatter is handed; `render` writes it as the store's fourth field,
|
||||
`true`/`false`, after `indent` and before the version.
|
||||
|
||||
**Why `true`/`false` and not `0`/`1`.** The parser's style is one
|
||||
`.parse()` per field; `bool: FromStr` accepts exactly `true`/`false`, so
|
||||
the round trip is `{}` out and `.parse().ok()?` back, with no mapping
|
||||
either way and no new failure mode. A numeric encoding would have needed
|
||||
a hand-written `"0" => false` match for no gain.
|
||||
|
||||
**The five-field tolerance.** `parse` now matches on the field slice:
|
||||
six fields is the current shape; five fields *that are well formed in
|
||||
the old shape* (hex content, numeric line-length and indent, non-empty
|
||||
path) is a store written before the option joined the key, and is
|
||||
dropped individually exactly like another version's entry; anything else
|
||||
still discards the whole file, because partial trust in a file caught
|
||||
lying is still not worth the branch. The precision matters — a blanket
|
||||
"wrong field count → skip the line" would have quietly forgiven
|
||||
`not-hex\t100\t2\t0.2.0\t/a.sv`, which the corruption tests require to be
|
||||
fatal. The version field alone already makes a 0.49.0 store miss at
|
||||
0.50.0, so this tolerance buys nothing today; it is there so the codec
|
||||
stays self-describing when the two come apart (a hand-written store, a
|
||||
downgrade).
|
||||
|
||||
**Tests.** `cache.rs`:
|
||||
`uvm_utils_indent_alone_is_a_different_entry` (equality differs on the
|
||||
option alone; the line round-trips carrying it),
|
||||
`a_line_without_the_option_is_dropped_but_not_fatal` (an old-shape line
|
||||
next to a current one: the old one is not trusted, the current one
|
||||
survives, and the old one is not carried forward), plus the option's
|
||||
column added to `entries_round_trip_through_the_file`,
|
||||
`the_file_is_sorted_and_carries_the_version`,
|
||||
`another_versions_entry_is_dropped_but_not_fatal` and two new
|
||||
six-field corruption cases (a non-boolean option, an empty path).
|
||||
`crates/lucisv/tests/cli.rs`:
|
||||
`changing_uvm_utils_indent_invalidates_the_entry` — the audit's own
|
||||
probe through the real binary, in both directions (clean under `false`,
|
||||
cached, flip to `true` → exit 1; format under `true`, cached, flip back
|
||||
to `false` → exit 1) — and
|
||||
`a_store_written_before_the_option_joined_the_key_is_rebuilt`. The CLI
|
||||
regression was checked against the bug: with `entry_for` pinned to
|
||||
`false` it fails with "1 file from cache" at exit 0, which is exactly
|
||||
the audit's step 2.
|
||||
|
||||
**Note for the lead.** `README.md`'s key sentence (line ~89, which still
|
||||
lists four fields) and its `--no-cache` workaround paragraph (lines
|
||||
~99-103, "In v0.49.0, the new `uvm-utils-indent` option is missing from
|
||||
this key") are now stale, as is `docs/topo.md` row 34, and
|
||||
`docs/repository-analysis.md`'s "Confirmed cache omission" paragraph
|
||||
describes a fixed bug. Per the brief this lane did not touch those three
|
||||
files; they are the lead's to strike at merge.
|
||||
|
||||
**Gates:** `cargo fmt` clean, `cargo clippy --all-targets` silent,
|
||||
`cargo test -p lucisv_core` / `-p lucisv` / `--workspace` green, all
|
||||
through `tools/guard.sh -m 8 -t 1800`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
@@ -595,8 +690,219 @@ apply, but the same spirit (attack the exact class of thing that could
|
||||
silently corrupt trust) was applied here to the cache's own trust
|
||||
boundary instead.
|
||||
|
||||
### 2026-09-07 — QA agent (TODO §59: `uvm-utils-indent` joins the key)
|
||||
|
||||
Read CLAUDE.md, TODO §59, this README's amended Handshakes and the
|
||||
2026-09-07 dev entry above, then `git diff` for `cache.rs`, `main.rs`,
|
||||
`cli.rs`. The workspace built clean on trunk this time (no concurrent
|
||||
lane mid-landing), so all gates ran directly, no scratchpad rsync
|
||||
needed.
|
||||
|
||||
**Gates.**
|
||||
- `cargo fmt -- --check`: clean.
|
||||
- `tools/guard.sh -m 8 -t 1800 -- cargo clippy --all-targets`: silent.
|
||||
Re-ran scoped with `-p lucisv_core -p lucisv --all-targets --
|
||||
-D warnings` after a touch to force recompilation (not just a cached
|
||||
"Finished"): still silent.
|
||||
- `tools/guard.sh -m 8 -t 1800 -- cargo test -p lucisv_core -p lucisv`:
|
||||
**36** (`lucisv` unit) + **107** (`cli.rs`) + **102** (`lucisv_core`
|
||||
unit) = 245, all green. (The dev's log counts pre-date this run; §59
|
||||
added 2 `cache.rs` unit tests, 2 `cli.rs` tests, and touched shared
|
||||
corruption-vector tests in place, so the totals climbed from the
|
||||
2026-08-19 136 baseline.) Confirmed
|
||||
`a_store_written_before_the_option_joined_the_key_is_rebuilt` and
|
||||
`changing_uvm_utils_indent_invalidates_the_entry` both present and
|
||||
passing.
|
||||
- `cargo build --release -p lucisv`: clean, used for every probe below
|
||||
as `target/release/lucisv`.
|
||||
|
||||
**Step 2 — the audit's probe, by hand, `--cache-dir` in a scratch dir**
|
||||
(fixture: the UVM class from the brief, `[format]
|
||||
uvm-utils-indent = false` first).
|
||||
|
||||
- Fixed binary: format under `false` → `--check` exits 0, `1 file from
|
||||
cache`. Flip to `true` → `--check` exits **1**, `would reformat:
|
||||
c.sv`. Correct.
|
||||
- 0.49.0 baseline (`~/.cache/lucisv-baselines/lucisv-0.49.0`): same
|
||||
sequence — format under `false`, cache hit, flip to `true` →
|
||||
`--check` exits **0**, `1 file from cache` (the bug, reproduced
|
||||
exactly), while `--check --no-cache` on the same binary correctly
|
||||
says `would reformat` / exit 1 — confirming the option really does
|
||||
change output and only the cache is stale.
|
||||
- Other direction on the fixed binary: format under `true` (file is
|
||||
reformatted, output differs from the `false` rendering — confirmed
|
||||
`assert_ne!`-style by hand), cache hit under `true`, flip to `false`
|
||||
→ exits **1**. Correct.
|
||||
|
||||
**Step 3 — attacking the key.**
|
||||
|
||||
- (a) Entry recorded under `true`, then run under `false` with the
|
||||
same content: `--check` reports `would reformat`, no `from cache` —
|
||||
miss, as required.
|
||||
- (b) Option set via a `lucisv.toml` in a **parent** directory (file
|
||||
under `sub/`, config in the parent, config discovery finds it):
|
||||
formatted clean under `false`, cache hit; flipped the *parent*
|
||||
config to `true` → `--check` exits 1, `would reformat`. The key
|
||||
follows the resolved value regardless of which directory in the
|
||||
chain set it, as the Assumptions section claims.
|
||||
- (c) A store written by the real 0.49.0 binary (five fields) read by
|
||||
the fixed binary: not an error, `1 file left unchanged` **without**
|
||||
"from cache" (the old-shape line is dropped individually, not
|
||||
trusted), and the store is six fields after this run. The next
|
||||
`--check` is then `1 file from cache` in the new shape. Matches the
|
||||
five-field-tolerance branch exactly.
|
||||
- (d) A store written by the fixed binary (six fields) read by the
|
||||
real 0.49.0 binary: read `crates/lucisv_core/src/cache.rs` at
|
||||
`v0.49.0` (`git show v0.49.0:...`) — its parser is
|
||||
`line.splitn(5, '\t')`. Against a six-field line this splits on only
|
||||
the first 4 tabs, so 0.49.0's "version" slot actually receives the
|
||||
*uvm* field's text (`"false"`/`"true"`) and its "path" slot receives
|
||||
everything after that, `"<real-version>\t<real-path>"` (with the
|
||||
join tab folded in raw). Since that captured "version" text is never
|
||||
equal to 0.49.0's own `VERSION` constant, the `if version == VERSION`
|
||||
check fails and the line is silently **not inserted** — the same
|
||||
code path 0.49.0 already uses for "another version's entry," not an
|
||||
error return. No `path.is_empty()` trip either (path is nonempty).
|
||||
Verified empirically: 0.49.0 read the six-field store, did not
|
||||
crash, reported plain `1 file left unchanged` (no "from cache" — a
|
||||
real re-verify, not a false hit, and correct anyway since the file
|
||||
is genuinely clean), and rewrote the store back to its own five-field
|
||||
shape on exit. No false hit, no crash, confirmed both by code
|
||||
reading and by running it.
|
||||
- (e) Six-field line with `uvm` = `"1"`: `bool::from_str` only accepts
|
||||
the literal strings `true`/`false`, so `.parse().ok()?` fails and
|
||||
`parse()` returns `None` → whole store discarded. Verified: seeded a
|
||||
store with one genuine clean entry plus this line, `--check` on the
|
||||
genuine file no longer says "from cache" (it re-verified). The
|
||||
`"yes"` case is already the unit test
|
||||
`a_corrupt_file_is_ignored_wholesale`'s `"...\tyes\t0.2.0\t/a.sv\n"`
|
||||
vector — read it, it exercises the same `.parse().ok()?` branch as
|
||||
`"1"` does (both are non-`true`/`false` strings; no reason for one to
|
||||
behave differently from the other, and this run confirms `"1"`
|
||||
directly since the brief calls it out by name). Five-field line with
|
||||
non-hex content (`"nothex\t100\t2\t0.49.0\tc.sv"`): `prefix()`'s
|
||||
`u64::from_str_radix(content, 16)` fails first, `?` short-circuits
|
||||
before the shape is even fully validated → `None` → discarded.
|
||||
Verified by hand: seeded that single bad line, `--check` did not
|
||||
trust it (no "from cache"), file re-verified clean on its own
|
||||
merits.
|
||||
- (f) Two files, one old-shape (five-field, `a.sv`) and one new-shape
|
||||
(six-field, `b.sv`) line in the same store: `--check a.sv b.sv`
|
||||
reports `2 files left unchanged, 1 file from cache` — exactly one
|
||||
hit (`b.sv`), `a.sv` silently rebuilt, neither line poisoned the
|
||||
other. Matches `a_line_without_the_option_is_dropped_but_not_fatal`.
|
||||
|
||||
Also checked, prompted by the TODO item's own wording ("a store line
|
||||
with four fields"): a genuine four-field line (`hash\t100\t2\t0.49.0`,
|
||||
no `uvm`/no path) matches neither the six- nor the five-field pattern
|
||||
in `parse`'s `match`, falls to `_ => return None`, and **discards the
|
||||
whole store** — including a separately-present, otherwise-good
|
||||
six-field entry for another file. Verified: seeded a good entry for
|
||||
`realfile.sv` plus a bogus four-field line, and the previously-good
|
||||
entry was no longer served ("from cache" absent) on the next
|
||||
`--check`. This is the fourth malformed-line shape (three, five,
|
||||
seven+ fields all land here too, by the same `_` arm) and behaves like
|
||||
every other corruption case — correct, and consistent with "guilty
|
||||
until proven innocent" for a change that *could* have silently
|
||||
widened forgiveness but provably didn't.
|
||||
|
||||
**Step 4 — path shapes that could confound the parser.** Read `parse`
|
||||
and `splitn(6, '\t')`. The path field is always the **last** slot
|
||||
(index 5) of an at-most-6-way split, so no matter what the path
|
||||
contains, it receives everything left after the fifth tab is
|
||||
consumed — it cannot be mistaken for field 4 (`uvm`) and cannot cause
|
||||
a `true`/`false` field to be mis-identified as a path or vice versa:
|
||||
- **Path literally `"true"`**: line
|
||||
`42b10c60d1dbc11a\t100\t2\tfalse\t0.49.0\ttrue` parses to
|
||||
`uvm_utils_indent = false`, `path = "true"` — positionally
|
||||
unambiguous. Verified with a real file named `true` in a scratch
|
||||
dir: formats, caches, hits on the next `--check`.
|
||||
- **Path containing an embedded tab**: `key()` (used both to look up
|
||||
and to record) rejects any path containing `\t` or `\n` outright, so
|
||||
**lucisv itself can never write such a line** — this class is only
|
||||
reachable via a hand-forged/corrupted store. Reasoned from
|
||||
`splitn(6, '\t')`: a forged line
|
||||
`deadbeefdeadbeef\t100\t2\ttrue\t0.49.0\ta\tb.sv` (6 tabs, one more
|
||||
than the 5 the split consumes) parses with `path = "a\tb.sv"` intact
|
||||
— the sixth-and-final split field folds the extra tab in, so it
|
||||
round-trips as one field rather than desyncing the columns. Since
|
||||
`key()` can never *produce* a tab-containing lookup key for a real
|
||||
file, this forged entry can never be hit by any real run; verified
|
||||
by seeding exactly this line plus a real file, confirming no crash
|
||||
and no false hit, and that the forged line (path does not exist on
|
||||
disk) is silently pruned by `render()`'s existence check on the next
|
||||
write.
|
||||
|
||||
**Step 5 — README cross-check.** Handshakes' "Consumes
|
||||
`vlog_formatter::Config`" paragraph states the obligation on the next
|
||||
formatter setting explicitly, naming `Entry`, `entry_for` and "the
|
||||
store line" together, in the same commit — matches CLAUDE.md's rule 4
|
||||
posture (widen the safety-adjacent surface only with the accompanying
|
||||
proof). The Storage section's line grammar
|
||||
(`<hash>\t<line-length>\t<indent>\t<uvm-utils-indent>\t<version>\t<path>`)
|
||||
matches `render()`'s `writeln!` argument order exactly
|
||||
(content, line_length, indent, uvm_utils_indent, VERSION, path).
|
||||
|
||||
**Step 6 — size.** `cache.rs`: 191 lines before `mod tests` (118
|
||||
non-blank/non-comment) — nowhere near the 300–600 target.
|
||||
`lucisv/src/main.rs`: 568 lines before `mod tests` — the `entry_for`
|
||||
change added 4 lines and did not push it toward a threshold. No file
|
||||
touched by this diff is newly over any CLAUDE.md size line.
|
||||
|
||||
**One non-blocking observation for the lead.** Step 3(c)/(d) used
|
||||
today's actual pairing — the release-tagged `lucisv-0.49.0` baseline
|
||||
against this uncommitted fix's local build, which *also* self-reports
|
||||
`CARGO_PKG_VERSION = "0.49.0"` because the workspace version has not
|
||||
been bumped for this change. That means in exactly the scenario just
|
||||
tested, the **shape-based** (five- vs six-field) tolerance is what
|
||||
kept the cross-binary read safe — the *version* field could not have,
|
||||
since both binaries carry the identical string. This slightly
|
||||
sharpens (not contradicts, once you know which pairing was meant) the
|
||||
dev's work-log claim that the five-field tolerance "buys nothing
|
||||
today" — that claim is true only *after* whatever release actually
|
||||
ships this fix bumps `Cargo.toml`'s version per the existing
|
||||
release-commit pattern (`git log` shows each `Release X.Y.Z` commit
|
||||
does this), which is a lead/release-time step, not something this
|
||||
diff needed to do itself. Recorded so the version bump isn't skipped
|
||||
at merge — no code change needed here, the fallback already covers
|
||||
the pre-bump window correctly, as demonstrated above.
|
||||
|
||||
**Verdict: PASS.** No corruption, no crash, no false hit, no
|
||||
mis-parse in any attacked case; both directions of the audit's own
|
||||
probe reproduce the bug on 0.49.0 and are fixed on the new binary;
|
||||
the five-field tolerance is precise (old-shape-well-formed lines drop
|
||||
individually, anything else on five fields is fatal like any other
|
||||
malformed line, confirmed with `"nothex"` content); a four-field line
|
||||
(the TODO item's own wording) discards the whole store as corruption,
|
||||
confirmed by direct repro; no file crossed a CLAUDE.md size threshold.
|
||||
Ticking the §59 QA line in `TODO.md`.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-07 (lead, §59).** Accepted. Read the diff (`Entry`, the store
|
||||
line, `parse`'s two arms, `entry_for`, the six cache tests, the two CLI
|
||||
regressions) and both logs.
|
||||
|
||||
- The key now covers every `FileConfig` field that reaches the formatter,
|
||||
and the Handshakes say so as an obligation on whoever adds the next one.
|
||||
That is the actual fix; the codec change is its consequence.
|
||||
- The five-field arm is deliberately *conditional* (well-formed old shape
|
||||
only), so the existing "one malformed line discards the store" posture
|
||||
is unchanged — the corruption tests still bite on a non-hex content,
|
||||
a `yes` option, an empty path. Right call; a blanket field-count skip
|
||||
would have been a forgiveness with no attack test behind it.
|
||||
- QA's cross-version check is the one that matters: a 0.49.0 store is
|
||||
dropped individually and rebuilt; a 0.50.0 store read by 0.49.0 lands
|
||||
the option text in 0.49.0's version slot and is skipped as another
|
||||
version's entry. Neither direction can produce a false hit.
|
||||
- QA's note on the version bump is taken: the release chain bumps
|
||||
`CARGO_PKG_VERSION` to 0.50.0 before the tag, so the version field
|
||||
invalidates a 0.49.0 store on its own and the shape arm is belt and
|
||||
braces.
|
||||
- Docs applied at merge: README.md's key sentence and the workaround
|
||||
paragraph replaced by a one-line history note; topo row 34 struck;
|
||||
repository-analysis and coverage_gaps annotated as fixed.
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed. Warm runs are
|
||||
2-4× faster in parallel and up to 7.7× single-threaded, bought without
|
||||
touching a single correctness property.**
|
||||
|
||||
@@ -101,6 +101,42 @@ and the bar says `860 files indexed, 860 from cache` so the user can see it.
|
||||
the session and one line after the next whole rescan, and a record whose
|
||||
file no longer exists is dropped at that rewrite, exactly as
|
||||
`lucisv_core::cache::store` drops its own.
|
||||
- **…and the rewrite is skipped when it would reproduce the file byte for
|
||||
byte** (2026-09-08, take 5 §P4b (a)). `render` writes this build's header and
|
||||
then one line per path in path order, so a store this build compacted and
|
||||
nothing has appended to since *is already* what the next compaction would
|
||||
write over it. Four conditions, all of them properties of what
|
||||
`IndexCache::open` read: the header was ours, every line was a record this
|
||||
build could use (none dropped), no path was named twice, the paths arrived
|
||||
ascending — **and** the session appended nothing since, **and** no entry's
|
||||
file has gone (`render` drops those). Any one of them failing rewrites
|
||||
exactly as before. **This weakens no promise in this README**: growth is
|
||||
still one line per path, because a store that grew has appends and therefore
|
||||
compacts; a record whose file is gone is still pruned, because a gone file
|
||||
fails the sweep; and crash safety is untouched, since a session that appended
|
||||
nothing left the file exactly as it found it and there is no half-written
|
||||
state for a rewrite to resolve. The one thing that is deliberately *not*
|
||||
claimed: an unreadable line inside an otherwise-good store is dropped at load
|
||||
as it always was, and a rewrite is what removes it from disk — that rewrite
|
||||
now happens on the first scan that also appends something rather than
|
||||
necessarily on the next one. It cost 182 ms of a 1.33 s warm start on
|
||||
opentitan, and every one of the six cases above is pinned
|
||||
(`index_cache::tests::a_canonical_store_nothing_appended_to_is_not_rewritten`
|
||||
and its five siblings).
|
||||
- **A record the store already holds is not appended again** (2026-09-08, take
|
||||
5 §P4b (a)). An open buffer is indexed from its *own* analysis on every scan
|
||||
and its record is written through with it, so a warm session would append one
|
||||
byte-identical duplicate line per open buffer — a line the next load
|
||||
collapses, at the price of making the store non-canonical and so owing the
|
||||
compaction above a full rewrite. `IndexCache::record` now returns early when
|
||||
the entry it is about to write is already there under the same path, the same
|
||||
content hash and the same encoded facts, byte for byte. Anything that differs
|
||||
by a byte is appended exactly as before, which is what keeps "the store says
|
||||
what this session last saw" true. Nothing else changes: the entry map is the
|
||||
same either way, so a hit is the same hit, and a session that appended
|
||||
nothing left the store exactly as it found it. Without this the skip above
|
||||
never fires in a real editor session, measured: opentitan warm, `records` 1
|
||||
and `compact` 88 ms on every scan with a buffer open.
|
||||
- **A save writes its record through too**, on the incremental path, without a
|
||||
second parse — `WorkspaceIndex::facts_for` hands back the record
|
||||
`update_file` just made. An hour of saves is an hour of work the next
|
||||
@@ -276,8 +312,24 @@ pub fn cache_dir(settings: &ClientSettings, storage: Option<&Path>,
|
||||
|
||||
- `Workspace` gains the cache and the storage path:
|
||||
`Workspace::set_storage_path(Option<PathBuf>)`, called once before the first
|
||||
build. The cache is re-opened at the top of every whole rescan, because the
|
||||
settings that decide where it lives arrive after startup.
|
||||
build. The cache is re-opened for every whole rescan, because the settings
|
||||
that decide where it lives arrive after startup. **Amended 2026-09-08 (take
|
||||
5 §P4b (b1)): the re-open is deferred to the first file of that rescan that
|
||||
asks the store something**, rather than run before the work list's first file
|
||||
exists. The rule itself is unchanged — every whole rescan still resolves the
|
||||
directory afresh and reads the store from it, and both of the reasons for
|
||||
that (a mid-session `cachePath`/`persist` change, and a second session's
|
||||
records this one has not seen) hold exactly as written. What changed is that
|
||||
a rescan whose work list is **empty** asks nothing and therefore reads
|
||||
nothing: `Workspace::begin_scan` records the directory as `StoreOpen::Deferred`
|
||||
and `Workspace::scan_step` (and the save path's write-through) opens it. The
|
||||
deferral is a *move*, never a drop — a widen behind an empty rescan still
|
||||
finds the store open at its own first file, which is what keeps its cache
|
||||
hits (`state::tests::a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it`
|
||||
pins both halves). `finish_whole_scan` does not compact a store no scan of
|
||||
this session ever opened. A settings change that drops the cache
|
||||
(`persist`/`cachePath`) drops the deferral with it, so `persist: false` still
|
||||
takes effect at once in both directions.
|
||||
- `IndexEvent::Cached { done, total, path }` — the same three numbers
|
||||
`Parsing` carries, for a file that cost nothing. Every existing consumer of
|
||||
the enum had to grow one arm, which is the compiler making the distinction
|
||||
@@ -852,6 +904,74 @@ after the whole run, still absent. The `#[ignore]`d probe was re-run in both
|
||||
profiles for the Measured table above, and the four-writer race test was run
|
||||
ten times in a row: 100 of 100 records every time.
|
||||
|
||||
### 2026-09-08 — dev agent (perf take 5 §P4b: two things the store stops doing)
|
||||
|
||||
Two changes, both in this feature's contract, both amended above rather than
|
||||
only recorded here. Neither touches the record format, the key, the header,
|
||||
the claim/append protocol, the per-record checksum, the byte-wise load or the
|
||||
torn-record rule; `FACTS_FORMAT` and `CACHE_FORMAT` are untouched.
|
||||
|
||||
- **A compaction that would reproduce the file is skipped** (Assumptions, the
|
||||
new bullet under the write-through rule). The store `render` writes is
|
||||
canonical — this build's header, one line per path, path order — so
|
||||
`IndexCache::open` now *counts* what it read (lines read, kept, dropped,
|
||||
duplicated, and whether the paths ascended) and `compact` asks whether the
|
||||
rewrite would be the same bytes: loaded canonical, nothing appended since,
|
||||
and no entry's file gone. The existence sweep is one `stat` per entry, which
|
||||
is a subset of what `render` already does per entry, so the check costs a
|
||||
fraction of the rewrite it replaces. On opentitan this is the whole of a warm
|
||||
session's two compactions — 182 ms of a 1.33 s start — both of which were
|
||||
measured writing a byte-identical 44.3 MiB file (§P4a: `store_before_kib` =
|
||||
`store_after_kib` = 45 396, `records` 0 and 1).
|
||||
- **A write-through the store already holds is not written again**
|
||||
(Assumptions, the new bullet beside the save's write-through). This was not
|
||||
in the ruling and is reported as a scoped addition, because without it the
|
||||
skip above **never fires in a real session**: an open buffer's record is
|
||||
written through on every scan, so `records` is never 0 and the store is never
|
||||
canonical. Measured on opentitan before it: warm `compact` 88.19 ms and
|
||||
`compactions` 1 on the configured rescan, i.e. the whole of (a) defeated by
|
||||
one duplicate line. After it: `records` 0, `repeats` 1, `compactions` 0,
|
||||
`compact` 10.13 ms — and that 10.13 ms is the skip's own existence sweep over
|
||||
3 976 entries, against the 90.20 ms rewrite it stands in for.
|
||||
- **A rescan opens the store at its first file, not before it** (Handshakes,
|
||||
`lucisv_server::state`). The re-open rule is unchanged and both of its
|
||||
reasons still hold; only the moment moved. It exists because a session's
|
||||
*first* scan runs at the default settings, before `workspace/configuration`
|
||||
can be asked, and with no buffer open its folder scope — and therefore its
|
||||
work list — is empty: warm, that scan was reading 44.3 MiB and rewriting it
|
||||
for a scan that indexes nothing. The deferral is a move, not a drop, which
|
||||
is the one way this could have gone wrong: the widen a `didOpen` triggers
|
||||
never opened the store itself (it reads the handle `begin_scan` left), so
|
||||
dropping the open would have silently cost that widen every one of its cache
|
||||
hits. It is pinned from the failing side —
|
||||
`state::tests::a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it`
|
||||
reports `parsed: ["b.sv"]` when the open is dropped instead of deferred.
|
||||
|
||||
**What was deliberately not done.** Reusing the store a previous scan of the
|
||||
same session already read — the third of §P4a's candidates, worth another
|
||||
91 ms — was **refused by the lead**, and this README is the reason: the reopen
|
||||
guards a mid-session `cachePath`/`persist` change and a second session's
|
||||
compaction replacing the file under an append handle. Nothing here weakens
|
||||
either.
|
||||
|
||||
**Tests.** Eight new in `index_cache.rs` (a canonical store is not rewritten,
|
||||
a record the store already holds is not appended again, and one each for a
|
||||
duplicated path, an unreadable line, out-of-path-order records, a session that
|
||||
appended, a file that is gone, and another version's header), three new in
|
||||
`state.rs` (the warm rescan leaves the store untouched;
|
||||
a scan with no files neither reads nor writes it and the widen behind it still
|
||||
hits; a cold session that indexes nothing creates no store at all), one new
|
||||
wire test in `server/tests/scan_trace.rs` (both halves over the real dispatch,
|
||||
by the trace's own new `opens=` / `compactions=` counters). Every pre-existing
|
||||
test in this feature is untouched and green, the interrupted-store ones
|
||||
included: `a_record_survives_a_session_that_never_compacted`,
|
||||
`a_torn_final_record_costs_one_file_and_nothing_else` and
|
||||
`truncating_the_store_at_every_byte_offset_costs_only_the_torn_record`.
|
||||
Verified that the six guard tests really guard: with `already_compact`
|
||||
widened to "there is a directory", all six fail, as do
|
||||
`compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone` and
|
||||
`nothing_is_created_until_something_is_recorded`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent (attack surfaces on the persistent index cache)
|
||||
|
||||
@@ -606,6 +606,95 @@ and it is where the measured cost was.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-08 — §P4b3: the read moment, and the order the walk is indexed in
|
||||
|
||||
**Two documented behaviours moved. The scope ladder itself — precedence, the
|
||||
rungs, `raised`, the widen chooser, rootless — is unchanged, and no test of it
|
||||
was touched** (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
|
||||
**1. When a file's text is read.** `collect_sources` resolved the scope *and
|
||||
read every in-scope file* before a scan's first step: 34 MiB and ~293 ms on
|
||||
opentitan, held for the whole life of the scan. It now resolves the scope and
|
||||
reads nothing off disk; `Workspace::scan_step` reads a file's text when its
|
||||
step comes and drops it at the end of that step. What follows for this feature:
|
||||
|
||||
- **The size cap is where it was.** `oversize` is still a `fs::metadata` call
|
||||
in `collect_sources`, still ahead of any read, so an oversized file is still
|
||||
never read and its `IndexEvent::Skipped` and its place in `Scan::skipped` are
|
||||
reported before the first step — which is what the progress bar's denominator
|
||||
and the end message depend on.
|
||||
- **An open buffer's text is still taken with the work list**, beside the
|
||||
analysis that describes the same bytes, so a `didChange` mid-scan cannot make
|
||||
the two disagree. That is the rule this README's widen section already
|
||||
states, unchanged.
|
||||
- **A *closed* file's text is now the text it has when the scan reaches it**,
|
||||
not the text it had when the work list was taken. Nothing is incoherent: the
|
||||
facts, the words and the `` `include`` lines of a file all come out of one
|
||||
read, so a file's contribution is internally consistent either way. A file
|
||||
that has left the disk by then contributes nothing and is taken **out** of
|
||||
the index by the whole scan that could not read it, which is what dropping it
|
||||
before the work list existed used to achieve.
|
||||
- `sources()` — what a refactoring reads — is the one caller that still wants
|
||||
every file's text at once, and it is where that read now happens.
|
||||
|
||||
**2. What order the walk is indexed in.** `Workspace::open_first` put the open
|
||||
buffers' own files at the front. It now ranks three groups
|
||||
(`crate::scan_order`): the open buffers' own files, then everything under the
|
||||
directories those buffers **raise** to, then the rest in path order. The raised
|
||||
directory is this feature's own `Workspace::raised`, asked **whichever rung is
|
||||
in force** — under a filelist or an explicit `workspace` scope it is not a
|
||||
*scope* question but the only thing that says which part of a 4 000-file walk
|
||||
to index first, so `Workspace::raised_dirs` answers it where
|
||||
`Workspace::scope_dirs` (a scope question) still answers `[]`.
|
||||
|
||||
It remains a latency and reporting decision and nothing more: `index_order`
|
||||
sorts and dedups first, `IndexBuilder::finish` sorts by path, and the finished
|
||||
index, the completion tables and the include graph are equal to a scan with
|
||||
nothing open — measured on opentitan as **24 of 24 identical scope answers**
|
||||
and a **byte-identical persistent store**, and pinned by
|
||||
`the_open_buffers_folder_is_indexed_before_the_rest_and_the_index_cannot_tell`.
|
||||
|
||||
### 2026-09-08 — dev (Opus), §P4b2: the startup scan now runs at the *answered* scope
|
||||
|
||||
**The ladder is unchanged. What moved is when the first scan reads it.**
|
||||
`Server::started` used to build the index at the **default** rung — the folder
|
||||
scope, which with no buffer open resolves to nothing at all — and only then ask
|
||||
the client for its settings; a client that wanted `index.scope: "workspace"`,
|
||||
a `scopeDepth`, an `exclude` or a `filelist` therefore paid a *second*, whole
|
||||
rescan when its answer landed. Since today the settings pull goes out first and
|
||||
the startup scan waits up to two seconds for the answer, so a session runs
|
||||
**one** scan, at the rung the answer selected (`server/startup.rs`,
|
||||
`docs/features/perf5-p4/README.md` §P4b2).
|
||||
|
||||
Nothing about the ladder itself changed:
|
||||
|
||||
- **precedence is untouched.** `lucisv.filelist` still beats
|
||||
`lucisv.index.scope`, which still beats `scopeDepth`, which still beats the
|
||||
default folder scope; the same `ClientSettings` goes into the same
|
||||
`set_client_settings`, only earlier. Measured across all eight
|
||||
(scope × cache state) cells of `tools/perf/bench.py scan`, which answer with
|
||||
identical file and cache-hit counts.
|
||||
- **the rootless rule is untouched.** A session with no roots resolves its
|
||||
scope from the directories a `didOpen` raised, exactly as before; a `didOpen`
|
||||
arriving during the configuration window installs its buffer and the one scan
|
||||
that follows sees it, with `open_first` putting that file at the head of the
|
||||
work list.
|
||||
- **the widen chooser is untouched.** `widen_of` still decides Nothing / Added
|
||||
/ Whole; what changed is only that a widen asked for *before the first scan
|
||||
has run* is folded into that scan instead of being run as a scan of its own —
|
||||
the same deferral `reindex_widened` has always applied mid-scan, now also
|
||||
applying in the window before the first scan starts.
|
||||
- **a client that cannot be asked, or that never answers, is exactly as it
|
||||
was**: the scan runs at the defaults immediately (or after the bound), and a
|
||||
late answer costs the one rescan a changed scope has always cost.
|
||||
|
||||
The one visible consequence for this feature: the *empty* default-scope startup
|
||||
scan a workspace-scoped client used to pay is gone, and with it the widen the
|
||||
first `didOpen` used to trigger behind it. A session that gets its answer runs
|
||||
one scan; a session that does not runs the two it always ran. Pinned by
|
||||
`server/tests/startup.rs` and by this feature's own ladder tests, green
|
||||
unmodified.
|
||||
|
||||
### 2026-08-29 — dev agent (the first RTL open at the shipped depth)
|
||||
|
||||
**The brief's diagnosis did not survive the first measurement, and that is the
|
||||
|
||||
@@ -192,6 +192,21 @@ pub fn build<'a>(files: …) -> WorkspaceIndex {
|
||||
wants to say about a file that was not parsed.
|
||||
- `ClientSettings::max_file_size` is read in `collect_sources`; nothing else
|
||||
in `state.rs` changed.
|
||||
**Amended (perf5-p4 §P4b3, 2026-09-08):** `collect_sources` no longer reads
|
||||
any file's text — a scan reads a file when it indexes it — but the cap is
|
||||
untouched and is still a `fs::metadata` call *there*, ahead of any read. That
|
||||
matters to this feature for three reasons the bar depends on: the skips are
|
||||
still counted and reported **before the first file is parsed**, so
|
||||
`Scan::total` is still known up front and still excludes them; the events are
|
||||
still emitted in the same order for the same files, so
|
||||
`a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven` is
|
||||
unchanged; and a file whose text has gone by the time its step comes reports
|
||||
**no event at all** and is **not** counted as a cap skip — it is not a file
|
||||
the cap kept out, and saying so would be a lie in the end message. The
|
||||
per-file log's *order* did move: the work list now leads with the open
|
||||
buffers' own files and then the folders those raise to
|
||||
(`docs/features/index-scope/README.md`), so a user watching a rescan sees
|
||||
their own neighbourhood go by first rather than the alphabet.
|
||||
|
||||
### `lucisv_server::settings`
|
||||
|
||||
|
||||
@@ -196,6 +196,20 @@ The attack pair is pinned in `check.rs`:
|
||||
is declared locally, which must pass, so the refusal above is a discriminator
|
||||
and not a blanket.
|
||||
|
||||
**Since take 5 §P1c (2026-09-07) the *offer* no longer runs this net; the
|
||||
*resolve* does.** A lazy client's lightbulb is answered by
|
||||
`vlog_refactor::organize_offer{,_in}`, which runs the same planner (so the
|
||||
"removes N, sorts M" count is the one the click will carry) and stops before
|
||||
`verify_splice`; `codeAction/resolve` and `lucisv.organizeImports` recompute
|
||||
through `organize_imports`, which verifies over the identical file set before
|
||||
any edit leaves the engine. The offer is therefore optimistic in exactly one
|
||||
way — a plan the verifier would refuse is shown and then refused on the
|
||||
click with the sentence — which is the contract every other lazy offer
|
||||
already had (`docs/features/lazy-code-action/README.md`: "the offer may be
|
||||
optimistic; the resolve is exact"). No edit reaches an editor unverified.
|
||||
QA (perf5-p1, P1c) could not construct a plan the verifier refuses that the
|
||||
planner accepts, so the attack pair below is the pin.
|
||||
|
||||
The verifier cannot see a wrong removal of an **unindexed** package's import —
|
||||
before and after, the reference is unresolved either way — which is exactly why
|
||||
"unknown package" is a refusal in the judgement rather than a guess.
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
# perf5-p0 — the harness tells the truth
|
||||
|
||||
Take 5 §P0 / TODO §60.0. Harness only: no Rust source is touched.
|
||||
|
||||
## Goal
|
||||
|
||||
Before any of take 5's optimizations is measured, the measuring instrument
|
||||
has to mean what it says. `docs/performance_take5.md` §P0 names four ways
|
||||
`tools/perf` did not: `phase_refactor` sent extract and inline offers —
|
||||
which carry a **command**, not an edit — to `codeAction/resolve`, where
|
||||
dispatch handed them to the ports resolver and got a refusal, so their tiny
|
||||
times measured nothing; `Session.ms` discarded the response, so a request
|
||||
that *failed* was recorded as a fast success; `phase_rss` put idle RSS in a
|
||||
field called `ms`, which is neither a latency nor a peak; and
|
||||
`sweep.sh::run_cell` deleted the format cache once before three "cold" tries,
|
||||
so two of every three were warm. This stage fixes all four, adds an explicit
|
||||
record schema (version, units, status, result count, client shape,
|
||||
fresh-process flag, edit fingerprint), promotes the owner's two supplemental
|
||||
scratch probes into committed phases, and reproduces the owner's baseline on
|
||||
the unchanged 0.50.0 binary with the corrected harness so later stages have a
|
||||
reference measured by the instrument they will be judged with.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The corpus (`/Users/guoliangchen/repo/opentitan` at `0098135264`) is
|
||||
read-only and stays at its three pre-existing modified files. Every edit a
|
||||
request returns is discarded, and the new `execute` scenario answers the
|
||||
server's `workspace/applyEdit` with `applied: false`.
|
||||
- `target/release/lucisv{,-server}` at 0.50.0 are the baseline binaries
|
||||
(sha256 `894054128…` / `27e0a0df…`); no `cargo` command runs during a timed
|
||||
phase.
|
||||
- A refusal returned as JSON-RPC `RequestFailed` (-32803) is the engine's own
|
||||
sentence; any other error code is a genuine failure. That split is what
|
||||
distinguishes `status: refused` from `status: error`.
|
||||
- `ps -o rss=` polled at 50 ms is an acceptable stand-in for peak RSS on this
|
||||
workload; the row says so rather than claiming a kernel high-water mark.
|
||||
- The machine runs a live desktop session. Load is recorded before and after
|
||||
every phase and was 2.92–5.21 throughout, against the baseline's 2.92–4.59.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **With `lucisv-server` (consumed, unchanged).** The client now advertises
|
||||
`workspace.applyEdit: true` and `workspace.workspaceEdit.resourceOperations:
|
||||
["create", …]` in the `execute` phase, which is what
|
||||
`main.rs::apply_edit_support` and `create_files_support` read. That takes
|
||||
the branch a real editor takes: `server/client.rs::deliver` pushes the edit
|
||||
instead of returning it. No server change is requested or needed.
|
||||
- **With `docs/perf/take5-baseline/` (consumed, never written).** The
|
||||
baseline's rows are schema 1 and stay exactly as they are. Schema 2 is
|
||||
additive: a row without a `schema` key is schema 1, read with take 4's
|
||||
prose.
|
||||
- **With `docs/perf/take5-tracking.md` (produced).** This stage fills the
|
||||
P0 row's candidate identity, every "Reference — agent fills" cell it
|
||||
measured, and one experiment entry. Baseline cells are never overwritten.
|
||||
- **Promised to P1–P4.** New rows carry `schema`, `units`, `status`,
|
||||
`result_count`, `client`, `fresh_process`, and — where an edit exists —
|
||||
`edits`/`files`/`created`/`fingerprint`. **No document may quote a row whose
|
||||
`status` is not `ok` or `capture`**, the sole exception being a row whose
|
||||
`expected_status` names the rejection it was built to get (the transport
|
||||
floor). `schema.quotable(row)` is that rule in code.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `schema.py`: schema 2 — version, units, status vocabulary, result
|
||||
count, normalized edits, `counts()`, `fingerprint()`, `quotable()`
|
||||
- [x] `harness.record()` stamps and validates schema/units/status; a failing
|
||||
status without a message, an unknown status, or `units: ms` with no
|
||||
`ms` list raises instead of reaching a document
|
||||
- [x] `harness.samples()` replaces `Session.ms` in every phase: the responses
|
||||
are kept, so an error is recorded as an error
|
||||
- [x] `lspclient`: `workspace/applyEdit` captured, timed, and declined with
|
||||
`schema.CAPTURE_REASON`; `workspace.applyEdit` / `resourceOperations`
|
||||
capabilities; `client_shape()`; answered server requests no longer
|
||||
accumulate in the inbox
|
||||
- [x] `phases_p0.execute`: command-bearing offers run through
|
||||
`workspace/executeCommand`; edit-computation and delivery halves timed
|
||||
separately; edits/files/created counted and fingerprinted
|
||||
- [x] `phases_new.resolve_rows`: an offer with an `edit` needs nothing, one
|
||||
with only a `command` is routed to `execute` and **not** timed as a
|
||||
resolve, one with neither is resolved
|
||||
- [x] `phases_p0.offerkinds` — the owner's `context.only` probe, promoted
|
||||
- [x] `phases_p0.offerqueue` — the owner's leader/follower probe, promoted,
|
||||
with `leader_ms` and `follower_ms` in their own fields
|
||||
- [x] `scan` reports settled time and first-useful-answer separately, in
|
||||
separate fresh sessions, so the settled series stays comparable
|
||||
- [x] `phase_rss`: `rss_kib` / `peak_rss_kib` / `store_kib`, `units: KiB`,
|
||||
no `ms` field; peak from a 50 ms `ps` poll across the scan
|
||||
- [x] `sweep.sh`: the scratch format cache deleted before **each** cold try;
|
||||
warm cells primed by one explicit untimed run; `sweeptable.py` prints
|
||||
the hits per try and flags a cold try with a hit
|
||||
- [x] verified on `hw/ip` at 0.50.0: cold `0 / 0 / 0`, warm `30 / 30 / 30`
|
||||
- [x] `tools/perf/README.md` documents the schema, the phases, the status
|
||||
vocabulary and the quoting rule
|
||||
- [x] the baseline reproduced on the unchanged binary; tracker reference
|
||||
cells and the P0 experiment entry filled
|
||||
- [x] QA — PASS, 2026-09-07 (see QA log)
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-07 — dev (Opus)
|
||||
|
||||
**Environment, checked first.** `lucisv 0.50.0`; sha256 of
|
||||
`target/release/lucisv` `894054128495b764…` and `lucisv-server`
|
||||
`27e0a0df5b77102e…` — both identical to `take5-baseline/metadata.json`, so
|
||||
**no rebuild was needed and none was run**. Corpus `git status --porcelain`
|
||||
showed exactly the three expected files before the round and after every
|
||||
phase. A CI runner's `cargo build --release -p lucisv` (an `act` host
|
||||
executor, not this tree) was found at 100% of a core at the start of the
|
||||
session; **no timing was taken until it exited**, and load was back to
|
||||
4.04–4.54 before the first timed phase.
|
||||
|
||||
**What changed, file by file.**
|
||||
|
||||
- `tools/perf/schema.py` (new, 168 lines). The record vocabulary: `SCHEMA`,
|
||||
`STATUSES`, `REQUEST_FAILED`, `CAPTURE_REASON`, `status_of`, `quotable`,
|
||||
`worst`, `result_count`, `normalized`, `counts`, `fingerprint`, `edit_of`.
|
||||
`status_of` splits an engine refusal (`RequestFailed`, -32803) from a real
|
||||
error by code. `fingerprint` is sha256 over the sorted
|
||||
`(uri, start, end, newText)` edits, the sorted created paths and the sorted
|
||||
warnings — both `changes` and `documentChanges` shapes are read, because an
|
||||
extraction that creates a file cannot use the map.
|
||||
- `tools/perf/lspclient.py`. `Session(apply_edit=, create_files=)`;
|
||||
`workspace/applyEdit` answered by `_capture_apply_edit`, which stamps the
|
||||
arrival instant, stores the payload and replies `applied: false` with the
|
||||
capture reason; `take_applied()`; `client_shape()`; the capability block
|
||||
gained `workspace.applyEdit` and `resourceOperations`; `_drain_locked` now
|
||||
moves answered server→client requests into `server_requests` instead of
|
||||
leaving them in the inbox forever.
|
||||
- `tools/perf/harness.py`. `record()` stamps `schema`/`units`/`status`/
|
||||
`fresh_process` and *validates*; `Samples`/`samples()` keep every response
|
||||
and expose `.row()` (the `ms`/`status`/`result_count`/`message` a request
|
||||
row always carries); `session()` passes the two new capabilities;
|
||||
`result_count` now comes from `schema`; the old `tries()` was removed
|
||||
because `samples()` supersedes it and nothing else used it.
|
||||
- `tools/perf/phases_p0.py` (new, 304 lines). `execute`, `offerkinds`,
|
||||
`offerqueue`, and `first_useful_rows()` (called by `scan`), plus
|
||||
`shape_of` / `command_of` / `open_and_settle`, which `phases_new` and
|
||||
`bench` also use.
|
||||
- `tools/perf/phases_new.py`. `resolve_rows()` does the routing; `refactor`,
|
||||
`tailrename`, `didopen`, `tailcompletion`, `hierarchy` write schema-2 rows;
|
||||
`phase_rss` rewritten around `rss_kib`/`peak_rss_kib`/`store_kib` and a
|
||||
`Sampler` thread.
|
||||
- `tools/perf/bench.py`. Every phase moved to `samples()`; `codeaction`,
|
||||
`portaction`, `probe` record offer shapes; `blockers` records the leader in
|
||||
`ms` and each follower in `follower_ms`; `scan` calls
|
||||
`phases_p0.first_useful_rows()`; the transport floor carries
|
||||
`expected_status: "error"`.
|
||||
- `tools/perf/sweep.sh`. Cold cache reset **per try**; warm cells primed by
|
||||
one untimed run behind a `--- prime (untimed, not a try) ---` marker; an
|
||||
optional sixth argument narrows the tree list.
|
||||
- `tools/perf/sweeptable.py`. Reads only the blocks after a `--- try N ---`
|
||||
marker (so a prime is never a trial) and prints the format-cache hits per
|
||||
try, flagging any cold try with a hit.
|
||||
- `tools/perf/README.md`. The file table, the new phases, and a
|
||||
"The record schema (`schema` 2)" section: every field, the status
|
||||
vocabulary, the quoting rule, and why `execute` exists.
|
||||
|
||||
**The execute rows — the thing take 4 could not measure.** With
|
||||
`workspace.applyEdit` and `resourceOperations: ["create"]` advertised, the
|
||||
server pushes the edit instead of returning it, and the push is timed and
|
||||
declined.
|
||||
|
||||
| Site | Command | Status | ms (executeCommand → applyEdit) | edits / files / created |
|
||||
|---|---|---|---:|---|
|
||||
| `aes.sv` 220:0–222:53 selection | `lucisv.extractModule` | `capture` | 257.33 / 245.05–247.00 | 2 / 2 / **1** |
|
||||
| `aes_wrap.sv` 66:2 | `lucisv.inlineModule` | `refused` | 6.58 / 5.87–6.20 | — |
|
||||
| `aes_wrap.sv` 66:2 (extract, also offered there) | `lucisv.extractModule` | `refused` | 817.37 / 793.77–809.07 | — |
|
||||
|
||||
The extraction's `applyEdit` label is `lucisv: lucisv.extractModule`;
|
||||
`deliver_ms` (our `applied: false` → the command's response) is
|
||||
0.015–0.033 ms, so essentially all of the 250 ms is the edit computation. The
|
||||
fingerprint is `090e92e7736e0a5a…`. **Nothing was written**: the corpus status
|
||||
was unchanged and `aes_extracted.sv`, which the server's own warning says the
|
||||
edit would create, does not exist.
|
||||
|
||||
The phase was run twice (the second time after a cosmetic fix to the row's
|
||||
`note` and to the fingerprint of a *refused* row, which now records `null`
|
||||
rather than the hash of an empty edit). The second run reproduced the first:
|
||||
extraction 255.90 / 242.17–245.70 ms, inline refusal 6.66 / 6.07–6.49,
|
||||
extract refusal 820.93 / 794.46–806.51, and — the point of the fingerprint —
|
||||
**the same `090e92e7736e0a5a…` for the extraction's edit**. The tracker
|
||||
quotes the first run; both are in the raw evidence
|
||||
(`results.jsonl`, `results-execute2.jsonl`).
|
||||
|
||||
Two findings fall straight out of these rows and are recorded, not fixed:
|
||||
|
||||
- The inline cursor's *extract* offer costs **793–817 ms to refuse**. A
|
||||
refusal is not a measurement of an extraction, but it is a real interactive
|
||||
cost of clicking an offer the engine will decline, and it is the second
|
||||
~800 ms user-command path in this corpus after the tail rename.
|
||||
- Take 4's `refactor` rows named `extract-module resolve: …` and
|
||||
`inline-module resolve: …` are exactly the invalid rows §P0 describes.
|
||||
They are gone; the phase now records those offers as `offer is a command:
|
||||
… | timed by the \`execute\` phase, not by resolve`.
|
||||
|
||||
**Baseline reproduction.** 15 phases, `--tries 3`, one guarded run each, in
|
||||
the order the baseline used, then the paired CLI experiment with the
|
||||
configuration order alternating per trial. 114 rows: 110 `ok`, 1 `capture`
|
||||
(the extraction), 2 `refused` (both engine sentences at the inline cursor),
|
||||
1 `error` (the transport floor, with `expected_status: "error"`). Corpus
|
||||
unchanged after all 16 runs; no guard kill; load 2.92–5.21.
|
||||
|
||||
Every reference cell agreed with the owner's baseline inside the tracker's
|
||||
tolerance except three; all three are recorded in the tracker's experiment
|
||||
entry and neither number was adjusted:
|
||||
|
||||
- `tb.sv` comment lazy: 3.80–4.79 ms against 3.22–3.50 (+27.9% on the
|
||||
medians). A ~4 ms row on a machine whose load band differed slightly.
|
||||
- `didChange` flush: 0.93–1.01 ms against 0.66–0.72 (+35.5%).
|
||||
- `nav definition` (+132%) and the transport floor (+10.6%) are both
|
||||
sub-millisecond and are **not read**, per the round's own rule.
|
||||
|
||||
The CLI cells are stronger than the timings alone: the **stdout sha256 of
|
||||
every configuration matches the baseline's byte for byte** (default,
|
||||
all-style, all-style minus `unused-import`, format cold, format warm), and
|
||||
the paired means are within 2.6% except `default`, whose baseline first trial
|
||||
the owner already flagged as an outlier.
|
||||
|
||||
**Two observations worth carrying into P4** (measured, not acted on):
|
||||
|
||||
- The first useful answer during a **cold** scan arrives in 84–86 ms with a
|
||||
correct result, while the same request during a **warm** scan takes
|
||||
206–219 ms. A warm cache does not make the first answer faster here.
|
||||
- Peak RSS across the scan equals idle RSS to the KiB in all six sessions:
|
||||
the server's resident set rises monotonically to its idle value and there
|
||||
is no transient above it on this workload.
|
||||
|
||||
**Deviations from the brief.**
|
||||
|
||||
- The two supplemental probes became `offerkinds` and `offerqueue`; the CLI
|
||||
probe stayed a scratch script (as the owner's was), because folding its
|
||||
`--ignore unused-import` cell into `sweep.sh` would change the committed
|
||||
sweep's cell set for all five trees. `sweep.sh` got only the cold-cache fix
|
||||
it was asked for, plus an optional tree-list argument.
|
||||
- `scan`'s first-useful-answer rows are measured in *separate* fresh sessions
|
||||
from the settled rows, not the same ones. Serving a request during a scan
|
||||
perturbs the scan, and the settled series has to stay comparable with take
|
||||
4's, which had nothing in flight. Both are `scan` rows and both fields are
|
||||
named; the perturbed settle is kept beside the first answer as
|
||||
`settled_ms`.
|
||||
- The `scan` phase was run twice. The first run's first-useful rows carried a
|
||||
hard-coded `result_count: 1`; that was a bug in the new code, fixed
|
||||
(`result_counts` now holds the real per-session counts), and all four
|
||||
workspace scan cells are quoted from the second run so they come from one
|
||||
consistent build of the harness. Both runs are in the raw evidence.
|
||||
|
||||
**Gates.** `python3 -m py_compile tools/perf/*.py` and `bash -n
|
||||
tools/perf/*.sh` clean. No Rust changed, so `cargo` was not run — and could
|
||||
not have been, mid-round.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-07 — QA (Sonnet)
|
||||
|
||||
**Scope.** Verified TODO §60.0 / `docs/performance_take5.md` §P0 against the
|
||||
working tree (`tools/perf/{schema.py,phases_p0.py}` new;
|
||||
`{bench.py,harness.py,lspclient.py,phases_new.py,sweep.sh,sweeptable.py,
|
||||
README.md}` changed) and the dev's evidence in
|
||||
`~/.cache/lucisv-perf/take5-p0/`. Everything below was re-run independently
|
||||
on the same binaries under `tools/guard.sh -m 8 -t 1800`; my own raw evidence
|
||||
is in
|
||||
`/private/tmp/.../scratchpad/qa-p0/{results.jsonl,attack*.jsonl,schema_attack.jsonl,resolve_attack.jsonl,sweep/,sweep2/}`.
|
||||
Nothing in this section touches the dev's files or the baseline.
|
||||
|
||||
**Environment, checked first and after.** `git -C
|
||||
/Users/guoliangchen/repo/opentitan status --porcelain` showed exactly the
|
||||
three expected files (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
|
||||
before any run and after every phase, every attack script and both sweeps;
|
||||
no `aes_extracted.sv` or any other new file ever appeared. `sha256`
|
||||
of `target/release/lucisv` (`894054128…`) and `lucisv-server` (`27e0a0df5b…`)
|
||||
matched the recorded baseline both before and after the whole session — no
|
||||
`cargo` command was run by QA. Zero guard kills across every invocation.
|
||||
|
||||
**1. Static.** `python3 -m py_compile tools/perf/*.py` and `bash -n
|
||||
tools/perf/*.sh` both clean. Line counts: `bench.py` 476, `lspclient.py` 471,
|
||||
`phases_p0.py` 304, `phases_new.py` 263, `schema.py` 168, `harness.py` 183,
|
||||
`sites.py` 122, `sweeptable.py` 126, `sweep.sh` 76, `outcomes.sh` 47 — all
|
||||
under the 500-line target. `tools/perf/README.md`'s "The record schema"
|
||||
section documents every schema-2 field, the four-value status vocabulary and
|
||||
`quotable()`'s rule, matching `schema.py` exactly. Take-4 rows (schema 1, no
|
||||
`schema` key) in `docs/perf/take5-baseline/results.jsonl` and
|
||||
`~/.cache/lucisv-perf/take4/results.jsonl` are plain JSON objects with no
|
||||
`schema` key; every schema-2 reader (`harness.py`, `phases_new.py`,
|
||||
`bench.py`) accesses fields with `.get()`/dict literals rather than requiring
|
||||
`schema==2`, so they remain parseable — confirmed by loading both files with
|
||||
`json.loads` line by line without error.
|
||||
|
||||
**2. Acceptance experiments — all four reproduced independently.**
|
||||
|
||||
- **(a) Rejected requests land as errors, never `ok`.** Ran the `baseline`
|
||||
phase myself: the transport floor (`$/lucisvNoSuchMethod`) recorded
|
||||
`status: error`, `code -32601: unhandled method`, distinct from an engine
|
||||
refusal. I then hand-crafted two further bad requests through
|
||||
`lspclient.Session` directly (not through a committed phase): a
|
||||
`textDocument/codeAction` with a missing `range` field came back
|
||||
`status: error, code -32602: missing field 'range'`; a `textDocument/rename`
|
||||
at an out-of-bounds position came back `status: refused,
|
||||
"lucisv: there is no symbol to rename at this position."`. Both were
|
||||
correctly *not* logged as `ok` by `record()`/`samples()`. (One weaker probe
|
||||
— `codeAction` on a URI the server had never opened — came back `ok` with
|
||||
`result_count: 0`; that is the server choosing to answer an empty menu
|
||||
rather than reject, which is correct LSP behavior and not a harness gap:
|
||||
the zero count is exactly what `result_count` exists to make legible.)
|
||||
- **(b) `execute` rows show a command and either an applyEdit payload or a
|
||||
refusal.** Re-ran `execute` myself: extraction at `aes.sv` 220:0–222:53 —
|
||||
**258.83 / 241.39–243.00 ms** (dev: 257.33 / 245.05–247.00), status
|
||||
`capture`, 2 edits / 2 files / **1 created**, and the fingerprint came back
|
||||
**byte-identical**: `090e92e7736e0a5a93557d75befa65a5bea0c2f44494d71dc67e3f8d70d05835`.
|
||||
Inline at `aes_wrap.sv` 66:2 refused in 6.11–6.37 ms (dev: 6.58/5.87–6.20)
|
||||
with the same `generate`-construct sentence; extract at the same cursor
|
||||
refused after 798.22–816.94 ms (dev: 817.37/793.77–809.07) with the same
|
||||
`h2d_intg` sentence. Corpus unchanged, no `aes_extracted.sv` created.
|
||||
- **(c) Cold sweep tries have zero hits independently.** Ran `sweep.sh` on
|
||||
`hw/top_earlgrey/ip` (46 files, all already needing reformatting, so it
|
||||
cannot exercise a warm hit) — cold `0/0/0`, confirming the cold-per-try
|
||||
fix. Then ran the full `hw/ip` cell as the plan suggested as a fallback:
|
||||
**cold `0/0/0`, warm `30/30/30`**, byte-for-byte the number the dev
|
||||
reported, plus matching summary lines (445 default violations, 7751 select
|
||||
violations, 1772 files would reformat / 30 unchanged / 4 failed).
|
||||
- **(d) RSS rows carry units, never `ms`.** Ran `rss` fresh: both rows had
|
||||
`units: "KiB"`, `rss_kib`/`peak_rss_kib`/`store_kib` populated, and **no
|
||||
`ms` key present at all** (checked with `'ms' in row` → `False`).
|
||||
`store_kib` was **45404**, identical to the dev's. Idle/peak: cold
|
||||
527.6/529.3/531.7 MiB, warm 575.8/575.7/573.8 MiB — both within the
|
||||
tracker's REF band.
|
||||
|
||||
**3. Re-taken REF cells (ten, exceeding the eight required), both numbers
|
||||
per cell (baseline/dev-REF vs my re-take, all on the unchanged 0.50.0
|
||||
binary):**
|
||||
|
||||
| Cell | Dev REF | QA re-take |
|
||||
|---|---|---|
|
||||
| Pinmux comment, all families (`offerkinds`, `None`) | 333.89 / 307.35–312.97 | 343.03 / 306.82–311.74 |
|
||||
| Pinmux comment, `only: []` | 81.72 / 82.27–84.11 | 82.29 / 82.51–84.68 |
|
||||
| Offerqueue leader/follower | 339.53/339.47 (p1), 309.08/309.07 (p2), 309.73/309.72 (p3) | 341.77/342.65 (p1), 309.59/309.57 (p2), 308.65/308.63 (p3) |
|
||||
| `aes_reg_top` lazy offer (`codeaction`) | 30.64 / 22.72–24.42 | 31.15 / 22.51–24.59 |
|
||||
| `state_q` tail rename | 813.44 / 778.77–782.13; 5/2/0; fp `b39defb21265…` | 823.09 / 779.96–788.93; 5/2/0; fp **identical** `b39defb212655f29e68c0e15b88dda405d2779a24c4b522a1798b6f44c9a04f7` |
|
||||
| `aes` rename | 167.60 / 140.46–142.13; 14/9/0; fp `fa7e31c78382…` | 168.84 / 140.58–141.67; 14/9/0; fp **identical** `fa7e31c78382176d5f96d661228ce82328df8bc77bd6d8575dd38717814cb26c` |
|
||||
| Connect-missing-ports resolve | 171.37 / 165.77–167.45 | 171.995 / 165.26–166.15 |
|
||||
| Cold workspace scan (3 fresh) | 2860.12–2868.45 | 2828.26–2848.97 (baseline 2830.30–2853.06) |
|
||||
| Warm workspace scan (3 fresh) | 1346.02–1352.80 | 1312.68–1361.91 (baseline 1322.24–1344.03) |
|
||||
| `didopen` pinmux row (3 fresh) | 119.01–131.85 | 109.12–135.15 |
|
||||
|
||||
All ten agree with the dev's REF within the tracker's tolerance (the two
|
||||
fingerprinted rows match to the full 64-hex-character hash, which is the
|
||||
strongest form of agreement available). The scan and didopen rows are
|
||||
fresh-process ranges and show the expected extra spread of a 3-sample
|
||||
wall-clock measurement on a shared desktop, but stay centered on the same
|
||||
values.
|
||||
|
||||
**4. Schema attacks — all four raised, plus two negative controls.** Called
|
||||
`harness.record()` directly (`schema_attacks.py`):
|
||||
- `units="ms"` with no `ms` field → raised `ValueError: row 'a' says ms but
|
||||
carries none`.
|
||||
- `status="bogus"` → raised `ValueError: status 'bogus' is not one of (...)`.
|
||||
- `status="error"`/`"refused"`/`"capture"` with no `message` → each raised
|
||||
`ValueError: a '<status>' row must carry its message`.
|
||||
- Negative controls (a well-formed `error` row with a message, and a `KiB`
|
||||
row with no `ms`) did **not** raise, confirming the checks are precise, not
|
||||
overzealous.
|
||||
|
||||
`resolve_rows()` (`resolve_attack.py`): called it with a fake `Session`
|
||||
whose `.request()` raises `AssertionError` if invoked, and a synthetic
|
||||
command-only action (`{"command": {"command": "lucisv.extractModule", ...}}`,
|
||||
no `edit`). `resolve_rows` never called `.request()` — it recorded the
|
||||
offer as `"... offer is a command: ..."`, `note: "timed by the execute
|
||||
phase, not by resolve"`, confirming a command-only offer can never land as a
|
||||
fast `ok` resolve.
|
||||
|
||||
**5. The three "disagrees beyond tolerance" rows — re-taken, and stable, not
|
||||
noise.**
|
||||
- `tb.sv` comment, lazy (`codeaction`, "comment line, lazy"): my re-take was
|
||||
**7.73 / 4.42–5.42 ms**, still elevated over baseline's 3.22–3.50 and, if
|
||||
anything, further from it than the dev's 3.80–4.79. Same direction, same
|
||||
order of magnitude as a ~1–5 ms row on this desktop.
|
||||
- `didChange` flush: my re-take was **1.35–1.64 ms** (first 2.19), against
|
||||
baseline's 0.65–0.72 and the dev's 0.93–1.01 — again elevated, and by more
|
||||
than the dev's own reading.
|
||||
- Format-cold peak RSS: the dev's paired CLI run reported 246.5 MiB against
|
||||
baseline 202.2. My independent `sweep.sh` run on `hw/ip` (not the paired
|
||||
CLI script, but the same cell) reported **239 MB** peak RSS for
|
||||
`format --check` cold — same elevated band, nowhere near the baseline's
|
||||
202.2.
|
||||
|
||||
All three disagreements reproduce independently and in the same direction on
|
||||
a second, unrelated invocation, which argues for a real (if small,
|
||||
machine/load-dependent) effect rather than a one-off noisy sample. Correctly
|
||||
left unadjusted by the dev; nothing here changes that.
|
||||
|
||||
**6. Traceability.** Sampled 20 numbers from the tracker's REF cells and the
|
||||
`P0-2026-09-07` experiment entry and searched
|
||||
`~/.cache/lucisv-perf/take5-p0/*.jsonl` for each. All 20 trace to the raw
|
||||
evidence; the handful that did not match on a first plain-text `grep` (e.g.
|
||||
`333.89`, `245.05`, `2860.12`, `535.2`) turned out to be the tracker's
|
||||
2-decimal rounding of a longer float (`333.8862499804236`,
|
||||
`245.04641597741283`, `2860.1173329807352`, `548032.0`/1024 = `535.19`
|
||||
MiB) — confirmed by loading the exact row and comparing the full-precision
|
||||
value. Nothing was actually missing.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
No findings. All four §P0 acceptance criteria hold under independent
|
||||
re-execution; ten re-taken REF cells (two with byte-identical 64-character
|
||||
fingerprints) agree with the dev's numbers within tolerance; the schema and
|
||||
`resolve_rows` attacks behave exactly as specified, including the negative
|
||||
controls; the three named disagreements reproduce in the same direction on a
|
||||
second run, supporting "real, not noise, and correctly left unadjusted";
|
||||
traceability is complete once rounding is accounted for. Corpus, binaries
|
||||
and guard were clean throughout. No fix was needed in `tools/perf`.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-07 (lead).** Accepted. Read `schema.py`, `resolve_rows`, the
|
||||
sweep change, the tracker's REF cells and experiment entry, both logs.
|
||||
|
||||
- The four §P0 defects are fixed the way the plan asked and nothing else
|
||||
was touched: no production code, the baseline evidence untouched,
|
||||
schema 2 additive over schema 1. `record()` refusing a malformed row
|
||||
and `quotable()` as the quoting rule in code are the right place for
|
||||
the discipline — a document cannot quote a rejection by accident.
|
||||
- The reference re-take is the useful result: every row P1/P2 will be
|
||||
judged against was re-measured by the instrument that will judge them,
|
||||
on the same binary, and agrees with the owner's baseline inside
|
||||
tolerance except three sub-5 ms rows that both dev and QA reproduce in
|
||||
the same direction. Left unadjusted, correctly.
|
||||
- Two new facts feed later stages: the extract command at the inline
|
||||
cursor spends ~800 ms producing a refusal (P1 measures it after the
|
||||
selector reuse, P2 owns it if it is scope work); and the first useful
|
||||
answer during a warm scan is slower than during a cold one (206–219 vs
|
||||
84–86 ms), a P4a lead.
|
||||
- Deviation accepted: the CLI probe stays a scratch script beside
|
||||
`sweep.sh` rather than changing the committed sweep's cell set.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,458 @@
|
||||
# perf5-p3 — one parse for the CLI package census
|
||||
|
||||
## Goal
|
||||
|
||||
`lucisv check` builds a project census before the first rule runs. When
|
||||
`unused-import` is enabled the census asked `vlog_linter::package_exports`
|
||||
for **every** file in the run, and that function built a one-file
|
||||
`WorkspaceIndex` — a lex, a parse, a full analysis and a fact read-off —
|
||||
even for a file that declares no package at all. The census had already
|
||||
parsed the same text a line earlier for the interface table, so every file
|
||||
paid for two whole-file parses and one analysis it almost never needed.
|
||||
Performance take 5 §P3 measured the price: the rule turns a 0.450 s
|
||||
all-style run on opentitan `hw/ip` into a 0.587 s one, **+137 ms (23.3 %)**,
|
||||
and peak RSS 177 → 217 MiB.
|
||||
|
||||
This feature removes the duplication. The census parses each file once and
|
||||
derives both halves from that parse, and the package half opens with an
|
||||
**AST gate**: a file whose tree holds no `package` item contributes nothing
|
||||
and no index is built for it. On `hw/ip` that is 1 624 of 1 805 files.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- `ParsedSource::parse` and `vlog_semantic`'s `parse_and_collect` produce
|
||||
the *same* tree for the same text: both are `tokenize` + `parse_tolerant`
|
||||
on the lex-ok path and `parse_source_tolerant` on the lex-error path. The
|
||||
equality tests in `interfaces.rs` are what hold this true rather than the
|
||||
reading of two functions.
|
||||
- `collect_defines(&[])` equals `DefineTable::default()` (it is `Vec::new()`
|
||||
either way), and `words::harvest(&[])` / `harvest_raw(&[])` are empty — so
|
||||
the lex-error path of `FileFacts::from_analysis` gives the record
|
||||
`FileFacts::of` gives.
|
||||
- Only `bind_item`'s `ItemKind::Package` arm ever declares a
|
||||
`SymbolKind::Package`, so a tree with no `Package` item cannot produce a
|
||||
file-scope package unit. The gate additionally never fires on a
|
||||
**fragment** parse, which `walk_items` does not descend into.
|
||||
- `words::harvest_text(src)` equals `words::harvest(ParsedSource::parse(src)
|
||||
.tokens())`: `harvest_text` is `tokenize` + `harvest`, empty on a lex
|
||||
error, and a `ParsedSource` whose text did not lex holds no tokens.
|
||||
- A rayon worker in `lucisv` has `PARSE_STACK_SIZE` of stack
|
||||
(`main.rs::pool`), which is what lets the census analyse on it. This
|
||||
feature removes a parse from that thread and adds none.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Consumed
|
||||
|
||||
- `vlog_semantic::{analyze, FileFacts::from_analysis, IndexBuilder::{new,
|
||||
add_facts, finish}, WorkspaceIndex::{units_of, members_of,
|
||||
reexported_packages}}` — the one-file index, now built from a parse the
|
||||
caller already has instead of from text. **No semantic change was needed:**
|
||||
`FileFacts::from_analysis` (added by perf5-p2 for the refactoring scope)
|
||||
already accepts exactly `(path, tree, defines, sem, src, lines, tokens)`,
|
||||
and `IndexBuilder::add_facts` + `finish` is what `WorkspaceIndex::build`
|
||||
itself does. `crates/vlog_semantic/` is untouched by this lane.
|
||||
- `vlog_parser::defines::collect_defines`, `vlog_parser::token::Token`,
|
||||
`vlog_parser::LineIndex` — the three inputs `from_analysis` wants that a
|
||||
`ParsedSource` does not already carry.
|
||||
|
||||
### Promised
|
||||
|
||||
- `vlog_linter::package_exports_in(path, file, tokens, src)` — new, additive.
|
||||
Every package the parsed file declares, with the names it exports, `None`
|
||||
for one this file alone cannot answer for. **Byte-identical to
|
||||
`package_exports(path, src)` on the same text**, which is now a wrapper
|
||||
(parse, then `_in`) and stays the API for a caller holding only text.
|
||||
- `MentionOracle::package_exports`' answers are unchanged: the same
|
||||
duplicate-package `None`, the same `export q::*` `None`, the same
|
||||
conservative silence for an unknown package.
|
||||
|
||||
### Requested of the lead (not done by this lane — `docs/topo.md` is not ours)
|
||||
|
||||
1. `lucisv ──▶ vlog_linter`: add `package_exports_in` beside `ParsedSource`
|
||||
— the CLI census hands the linter its own parse for the package half, as
|
||||
it already does for the interface half (`module_interfaces`).
|
||||
2. `vlog_linter ──▶ vlog_semantic`: the edge now also reads
|
||||
`FileFacts::from_analysis` + `IndexBuilder::{add_facts, finish}` to build
|
||||
the one-file package index from a parse the linter already has.
|
||||
`WorkspaceIndex::build` is still what the equality test compares against,
|
||||
so the two constructions are pinned equal.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] package exports from the census's existing parse; AST gate, never a
|
||||
textual `contains("package")`
|
||||
- [x] every-fixture equality test against the old `WorkspaceIndex::build`
|
||||
construction (15 fixtures, plus a gate-answer test and the duplicate pin)
|
||||
- [x] CLI regression: default `check` byte-identical, all-style keeps every
|
||||
`unused-import` finding — six new end-to-end tests, and the corpus run's
|
||||
five stdout captures `diff` clean
|
||||
- [x] paired three-configuration measurement on `hw/ip`, tracker filled
|
||||
- [x] `cargo fmt` / guarded `clippy --all-targets` / guarded
|
||||
`test --workspace` (4 250 → 4 262, 0 failed)
|
||||
- [ ] QA
|
||||
- [ ] lead: the two `docs/topo.md` edges requested above
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-07 — dev
|
||||
|
||||
**The change, file by file.**
|
||||
|
||||
- `crates/vlog_linter/src/interfaces.rs`. New public
|
||||
`package_exports_in(path: &Path, file: &SourceFile, tokens: &[Token], src:
|
||||
&str) -> Vec<(String, Option<Vec<String>>)>` — the same three index queries
|
||||
as before (`units_of(Package)`, `reexported_packages`, `members_of`) over an
|
||||
index built two new ways. `package_exports(path, src)` is now
|
||||
`ParsedSource::parse` + `package_exports_in`, so a text-only caller is
|
||||
unaffected and the two forms cannot disagree. Two private helpers:
|
||||
`declares_a_package(file)` — the gate, `walk_items` looking for
|
||||
`ItemKind::Package`, deliberately a *superset* of "declares a package unit"
|
||||
(the walk descends into every container while only a file-scope binding
|
||||
becomes a unit), and never firing on a fragment parse; and
|
||||
`one_file_index(path, file, tokens, src)` —
|
||||
`collect_defines` + `analyze` + `LineIndex::new` +
|
||||
`FileFacts::from_analysis` + `IndexBuilder::{add_facts, finish}`, which is
|
||||
`WorkspaceIndex::build` with the lex and the parse deleted.
|
||||
- `crates/vlog_linter/src/lib.rs`. One line: `package_exports_in` joins the
|
||||
`interfaces` re-export.
|
||||
- `crates/lucisv/src/lint.rs`. `Census::of`'s rayon closure became a free
|
||||
`harvest_one(job, interfaces, packages) -> PerFile` (the `PerFile` alias
|
||||
moved to module scope with it), so `of` is a `par_iter` line plus the merge
|
||||
and both stay inside the size rule. `harvest_one` parses **once** when
|
||||
either half is wanted and feeds the word census, the interface table and the
|
||||
package table from that one parse; when neither is wanted it still only
|
||||
lexes, via `words::harvest_text`. Production lines (non-blank, non-comment, before `mod tests`): 495 → **494** — the census work moved rather than grew, well under
|
||||
the 600 mark.
|
||||
- `crates/lucisv/tests/cli.rs`. Six end-to-end tests (see below).
|
||||
|
||||
**Why no `vlog_semantic` change.** The plan allowed an additive
|
||||
`FileFacts::from_parsed`. It was not needed: §P2b already added
|
||||
`FileFacts::from_analysis(path, tree, defines, sem, src, lines, tokens)` for
|
||||
the refactoring scope, and that is exactly the second half of `FileFacts::of`.
|
||||
`crates/vlog_semantic/` is byte-unchanged by this lane.
|
||||
|
||||
**The gate, and why it is safe.** `SymbolKind::Package` is created in exactly
|
||||
one place, `bind/item.rs`'s `ItemKind::Package` arm, and only a binding in the
|
||||
*file* scope becomes an indexed unit. So a tree holding no `Package` item
|
||||
anywhere cannot yield a package unit, and returning empty for it is not an
|
||||
approximation. Erring the other way (opening the gate too often) costs an
|
||||
index and nothing else, which is why the fragment case is let through rather
|
||||
than reasoned about.
|
||||
|
||||
**Tests.** `interfaces::package_tests` keeps the **pre-P3 body verbatim** as a
|
||||
`from_text` reference and asserts the new code equal to it over 15 fixtures:
|
||||
no package; one; two; `export *::*`; `export q::*`; a named re-export; a
|
||||
package behind an `` `ifdef``; a package after a module; text that does not
|
||||
lex; a parse error inside a package body; a class in a package; the word
|
||||
`package` in a string; the same in a comment; one name declared twice; an
|
||||
empty file. Three further tests pin what equality cannot see —
|
||||
`only_a_package_item_opens_the_gate` checks the gate's answer fixture by
|
||||
fixture (a gate that always opened would fail it),
|
||||
`the_unlexable_fixture_does_not_lex` stops that fixture going stale, and
|
||||
`a_name_declared_twice_in_one_file_answers_with_the_first` pins a pre-existing
|
||||
answer worth knowing: **within one file** a duplicate package name reports the
|
||||
*first* declaration's members, not `None`. The `None` is the cross-file rule
|
||||
and belongs to `Census::of`'s merge. That behaviour is unchanged by this lane
|
||||
and is not a finding against it, but QA should know it is there.
|
||||
|
||||
The six CLI tests drive the real binary: an unused import reported and a used
|
||||
one not; a default `check` silent about imports; an import of a package
|
||||
outside the run silent; an import of a re-exporting package silent; an import
|
||||
of a package two files declare silent; and a run whose extra files write
|
||||
`package` only inside a string and a comment producing the identical finding
|
||||
set. There were **no** CLI-level `unused-import` tests before this lane.
|
||||
|
||||
**Measurement** (full record: `docs/perf/take5-tracking.md`, experiment
|
||||
`P3-2026-09-07`; raw data `~/.cache/lucisv-perf/take5-p3/`). The owner's
|
||||
paired method — alternating binary order, `/usr/bin/time -l`, every child
|
||||
under `tools/guard.sh -m 8 -t 1800`, opentitan read-only and its
|
||||
`git status --porcelain` asserted after every single invocation.
|
||||
|
||||
| `hw/ip` cell | reference 0.50.0 | trunk rebuilt here | candidate |
|
||||
|---|---:|---:|---:|
|
||||
| default `check` | 0.4183 s (median 0.420) | 0.4450 (0.420) | **0.4233 (0.420)** |
|
||||
| `--select error,warning,style` | 0.6333 | 0.6333 | **0.4817** |
|
||||
| the same, `--ignore unused-import` | 0.4750 | 0.4917 | **0.4767** |
|
||||
| the rule's paired increment | 158.3 ms | 141.7 ms | **5.0 ms** |
|
||||
| all-style peak RSS (max of 6) | 220.9 MiB | 219.1 | **202.0** |
|
||||
|
||||
**96 % of the increment is gone** against the same-toolchain control, where
|
||||
the target was half. All-style falls **−23.9 %**; `hw/vendor` −22.2 % and
|
||||
`hw/dv` −18.5 % in a separate eight-trial pass. Every cell's stdout is
|
||||
**byte-identical** to the reference's, diffed as files: `hw/ip` default 445
|
||||
findings, all-style 7 751 (17 of them `unused-import`), minus rule 7 734;
|
||||
`hw/vendor` 1 666; `hw/dv` 1 158.
|
||||
|
||||
Two notes on honesty. First, the machine was loaded (one-minute load 3.6–9.9
|
||||
against the §P0 baseline's 2.9–4.6), so absolute seconds here are higher than
|
||||
the tracker's REF cells for *both* binaries; only the paired difference is
|
||||
quoted. Second, the first eight-trial pass showed default `check` +4 % on the
|
||||
candidate, which no code path explains (a default run never asks for the
|
||||
package half). A **third binary** — the same trunk source rebuilt here — was
|
||||
added as a control and settled it: the trunk rebuild is +6.4 % on default
|
||||
against the cached reference while the candidate is +1.2 %, and all three
|
||||
medians are 0.420 s. The default cell is unchanged.
|
||||
|
||||
**What remains.** The 5.0 ms left is the `unused-import` rule body's own
|
||||
`import_usage` plus the 181 surviving one-file index builds (now analysis and
|
||||
record only). The next measurable CLI duplicate is the **third parse** — the
|
||||
lint pass parses each of the 1 805 files again after the census has. Retaining
|
||||
the census's ASTs would remove it and would hold 1 805 trees of a 39 MB corpus
|
||||
alive at once against a 202 MiB peak; the plan told this stage to measure peak
|
||||
RSS before making that trade, and it is not made here.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-07 — QA
|
||||
|
||||
**Verdict: PASS.** All gates green, the AST gate independently attacked (9
|
||||
fixtures beyond the dev's 15) and sabotage-tested, lint-silence parity
|
||||
diffed full-output on a fixture tree the dev did not build, all five corpus
|
||||
cells re-run and re-hashed to the exact quoted hashes, the timing claim
|
||||
reproduced within the noise this machine allows, and traceability numbers
|
||||
re-derived independently. No corruption/idempotency/comment risk: this
|
||||
lane touches only census bookkeeping, never emitted text.
|
||||
|
||||
**Setup.** Worked in a fresh clone at
|
||||
`/private/tmp/.../scratchpad/qa-p3/clone` (branched from `5c9fdb2`, `git
|
||||
apply` of `git diff -- crates/ TODO.md` from the working tree — applied
|
||||
clean) plus an unmodified sibling clone `clone-head` at the same `5c9fdb2`
|
||||
for a true pre-P3 baseline. Every cargo/lucisv invocation below went
|
||||
through `tools/guard.sh -m 8 -t 1800`; zero guard kills anywhere in this
|
||||
pass. `git -C /Users/guoliangchen/repo/opentitan status --porcelain` was
|
||||
checked before this session and after every corpus/timing invocation —
|
||||
always exactly the three pre-existing files (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
Machine load was elevated for part of this session (a 1-minute sample of
|
||||
59 was observed mid-session, decaying to ~5 by the timing re-take;
|
||||
unrelated system processes, not a runaway — checked with `top`, nothing
|
||||
of mine was consuming it) — noted per instruction, and the timing section
|
||||
below reads only the paired difference for that reason.
|
||||
|
||||
**1. Gates.**
|
||||
- `cargo fmt --all -- --check` on the clone: clean (exit 0).
|
||||
- `cargo clippy --all-targets` on the clone: clean, zero warnings (exit 0).
|
||||
`grep -n "#\[allow" crates/lucisv/src/lint.rs
|
||||
crates/vlog_linter/src/interfaces.rs`: no hits — no new `#[allow]`.
|
||||
- `cargo test --workspace --release` on the clone (candidate, P3 applied):
|
||||
**4262 passed, 0 failed** (summed across every binary's `test result:`
|
||||
line). Same command on `clone-head` (5c9fdb2, no P3): **4250 passed, 0
|
||||
failed**. Difference is exactly **+12**, matching the dev's own count of
|
||||
new tests (6 `package_tests`/gate tests + 6 CLI tests); nothing existing
|
||||
was lost.
|
||||
- `cargo tree -p lucisv -e normal` on the clone: lists `lucisv_core`,
|
||||
`rayon`, `vlog_formatter`, `vlog_linter`, `vlog_parser` — `vlog_semantic`
|
||||
appears only nested under `vlog_linter`, never as a direct dependency of
|
||||
`lucisv`. Topology claim confirmed.
|
||||
- Production line count, non-blank/non-comment before `mod tests`:
|
||||
`crates/lucisv/src/lint.rs` **494** — confirmed by the same `awk`+`grep -c`
|
||||
method the dev used. Well under the 600 mark.
|
||||
- Binary provenance: rebuilding `5c9fdb2` unmodified in `clone-head`
|
||||
produced sha256 `81bb40a28802e713…` — an **exact match** to the dev's own
|
||||
recorded "trunk-rebuild" control binary. Rebuilding the clone with the
|
||||
P3 diff applied produced sha256 `2c16b321cb2d1083…` — an exact match to
|
||||
the dev's recorded candidate hash, and to `target/release/lucisv` in the
|
||||
main tree (no rebuild was needed there; used as-is for corpus/timing
|
||||
runs below).
|
||||
|
||||
**2. THE AST GATE.** Read `declares_a_package` and `walk_items`
|
||||
(`crates/vlog_linter/src/visit.rs`): the gate is a `matches!(item.kind,
|
||||
ItemKind::Package { .. })` predicate over an AST walk that descends into
|
||||
modules, classes, packages, and every generate-region/if/for/case shape —
|
||||
never a text search. Macros are confirmed **not expanded** by this parser
|
||||
(`ItemKind::MacroItem(MacroCall)` holds the call, not a substituted body —
|
||||
`vlog_parser/src/ast/mod.rs:360`), so a `` `define P package p; endpackage
|
||||
`` followed by `` `P `` cannot manufacture a real `Package` item under
|
||||
either the old or the new construction — confirmed by test, not assumed.
|
||||
|
||||
Nine fixtures beyond the dev's 15, appended as `qa_attack_tests` in the
|
||||
clone's `interfaces.rs` (not shipped; QA-only clone code) and run with
|
||||
`cargo test -p vlog_linter -- interfaces:: --nocapture`: **all 9 pass**,
|
||||
each asserting `package_exports(new) == from_text(old)` (old = the
|
||||
dev's verbatim pre-P3 `WorkspaceIndex::build` construction, duplicated
|
||||
into the QA module since it is private to `package_tests`):
|
||||
(a) package word only in a macro body never invoked, in a string
|
||||
spanning a line continuation, in a block comment, and in an invoked
|
||||
(but not expanded) macro — all agree, all empty;
|
||||
(d) `Package p; ... endpackage` (capital P) — not a keyword, agrees;
|
||||
(e) `program`/`interface`/`class`/`module` all named `package_x` — none
|
||||
is a package, agrees;
|
||||
(c) a parse error (`@@@`) before the first member inside the package
|
||||
body — agrees;
|
||||
(f) an empty package body — agrees, and is `Some(vec![])` not `None`;
|
||||
(g) a package followed by an unterminated second one — agrees;
|
||||
(h) CRLF line endings — agrees;
|
||||
(i) UTF-8 BOM prefix — agrees.
|
||||
|
||||
**Sabotage.** Edited the clone's `declares_a_package` to
|
||||
`{ let _ = file; false }` (gate always closed) and reran `cargo test -p
|
||||
vlog_linter -- interfaces::`: **9 of the dev's+QA's package tests fail**,
|
||||
including the dev's own `every_fixture_answers_what_a_text_built_index_
|
||||
answers`, `only_a_package_item_opens_the_gate`, and
|
||||
`a_name_declared_twice_in_one_file_answers_with_the_first`, plus 6 of the
|
||||
QA attack fixtures. The equality oracle catches a broken gate exactly as
|
||||
intended. `interfaces.rs` was restored byte-for-byte afterward (diffed
|
||||
against the pre-sabotage copy: clean) and the full suite re-run clean (23
|
||||
passed under `interfaces::`, 0 failed).
|
||||
|
||||
**(b) duplicate-in-one-file pin.** Independently re-derived, not just
|
||||
trusted: constructing `package p; A=1; endpackage package p; B=2;
|
||||
endpackage` by hand and calling `package_exports` gives `Some(["A"])` —
|
||||
the first declaration's members, not `None`. This matches the dev's
|
||||
documented pre-existing answer exactly; it is the one-file index's
|
||||
behavior (unchanged by this lane) and the CLI's cross-file `None` comes
|
||||
from `Census::of`'s merge, confirmed separately below.
|
||||
|
||||
**`from_text` verbatim check.** `git show 5c9fdb2:crates/vlog_linter/src/
|
||||
interfaces.rs` has no `package_tests` module (P3 added it), so the
|
||||
"verbatim" claim was checked against the actual pre-P3 production body
|
||||
instead: the current `package_tests::from_text` is character-for-character
|
||||
the same construction `package_exports` used to be at `5c9fdb2` (`let
|
||||
index = WorkspaceIndex::build(...)`, same two-step `units_of` +
|
||||
`reexported_packages`/`members_of` query) — confirmed by diffing the two
|
||||
snippets by hand.
|
||||
|
||||
**3. LINT SILENCE PARITY.** Built a fixture tree the dev did not have
|
||||
(`scratchpad/qa-p3/fixtree`, 16 files) covering every shape the task
|
||||
named: a used import, an unused import, an import of an unknown package,
|
||||
an import of a package declared twice across files, an `a_pkg → b_pkg`
|
||||
re-export chain used through `b_pkg`, a second independent re-export
|
||||
chain (`c_pkg → d_pkg`) used through a wildcard, a package behind an
|
||||
`` `ifdef`` (never defined — the census still sees the package item,
|
||||
matching the dev's own "package behind a directive" fixture's finding:
|
||||
lucisv does not evaluate conditionals structurally), and a waiver file
|
||||
waiving `unused-import`.
|
||||
|
||||
Ran `clone-head/target/release/lucisv` (pre-P3, sha `81bb40a2…`) and the
|
||||
candidate (`target/release/lucisv`, sha `2c16b321…`) over this tree:
|
||||
- `check --select error,warning,style`: stdout **byte-identical**, exit 1
|
||||
both. 2 `unused-import` findings (`unused_import.sv`, `ifdef_import.sv`);
|
||||
the re-export/unknown/duplicate-package imports and the used imports are
|
||||
silent on both binaries, as expected.
|
||||
- `check` (default): stdout byte-identical, exit 1 both (package-filename
|
||||
and endif-comment findings only — `unused-import` is style-only, off by
|
||||
default on both).
|
||||
- `check --select error,warning,style --fix` on two copies of the tree:
|
||||
stdout identical once the two temp-dir paths are normalized out; **the
|
||||
fixed files themselves are byte-identical** (`diff -r` clean) — this
|
||||
answers the "does `unused-import` have a fix, and does `--fix` diff
|
||||
clean" question: yes, it deletes the whole `import` line
|
||||
(`Applicability::Safe`), and both binaries produce the same edit.
|
||||
- A waiver file (`waive --rule=unused-import
|
||||
--location=unused_import.sv`): both binaries silence the waived finding
|
||||
and exit 0, stdout identical (empty).
|
||||
|
||||
**4. CORPUS.** Re-ran all five cells independently (not reusing the dev's
|
||||
saved captures) with `~/.cache/lucisv-baselines/lucisv-0.50.0` as
|
||||
reference and `target/release/lucisv` as candidate (sha confirmed matching
|
||||
the tracker beforehand, no rebuild). Captured stdout only (`2>/dev/null`
|
||||
— the `found N violations` summary is on stderr,
|
||||
`crates/lucisv/src/lint.rs:753`, which the first attempt without
|
||||
redirection discipline conflated; corrected before drawing conclusions).
|
||||
Every cell: reference and candidate stdout **byte-identical**, exit codes
|
||||
equal (1, 1, 1, 2, 1 — `hw/vendor` is 2 for both, a pre-existing format
|
||||
failure unrelated to this lane), and the hashes match the tracker's quoted
|
||||
values exactly:
|
||||
|
||||
| Cell | sha256 | Lines | Matches tracker |
|
||||
|---|---|---:|---|
|
||||
| `hw/ip` default | `c2444712e23e…` | 445 | yes |
|
||||
| `hw/ip` all-style | `97201de03bca…` | 7751 (17 `unused-import`) | yes |
|
||||
| `hw/ip` minus rule | `58780c3e81b8…` | 7734 | yes |
|
||||
| `hw/vendor` all-style | `1ce51659c4ab…` | 1666 | yes |
|
||||
| `hw/dv` all-style | `d7913e5f5846…` | 1158 | yes |
|
||||
|
||||
`git status --porcelain` on opentitan checked and unchanged after every
|
||||
one of these ten invocations.
|
||||
|
||||
**5. TIMING.** Re-took `hw/ip` all-style / minus-rule, 3 trials alternating
|
||||
binary order, `/usr/bin/time -l`, both binaries as in §4, every child under
|
||||
`tools/guard.sh`. **Machine load was elevated** (1-minute sample 4.76–5.11
|
||||
at run time, still carrying a 5-minute average around 22–23 from earlier
|
||||
work this session), so — per instruction — only the paired
|
||||
(all-style − minus-rule) increment is read, not absolute seconds:
|
||||
|
||||
| | trial 1 | trial 2 | trial 3 | median |
|
||||
|---|---:|---:|---:|---:|
|
||||
| reference increment | +150 ms | +140 ms | +160 ms | **+150 ms** |
|
||||
| candidate increment | −30 ms | +30 ms | −20 ms | **−20 ms (noise floor)** |
|
||||
|
||||
The reference's increment lands inside the dev's own reported range
|
||||
(141.7–158.3 ms across the dev's three binaries). The candidate's
|
||||
increment is indistinguishable from zero at `/usr/bin/time`'s ~10 ms
|
||||
rounding — fully consistent with the dev's claimed 5.0 ms residual, and
|
||||
independently confirms **well over 50 %** of the increment is gone (the
|
||||
target). Peak RSS, maximum of 3 trials: reference **211.0 MiB**, candidate
|
||||
**196.2 MiB** — not worse, matching the dev's direction (219–221 → ~196–
|
||||
202 MiB across both passes). `git status --porcelain` on opentitan
|
||||
unchanged after all 12 timed invocations.
|
||||
|
||||
**6. Traceability.** All hashes and counts in the tracker's P3 cells and
|
||||
experiment `P3-2026-09-07` were checked against
|
||||
`~/.cache/lucisv-perf/take5-p3/` and reproduce: `binaries.sha256` matches
|
||||
the two rebuilt QA binaries exactly; the five `stdout-*` capture files'
|
||||
sha256 match the hashes quoted in the README/tracker; `p3-threeway.jsonl`
|
||||
and `p3-results.jsonl` exist and are non-empty. Package-file counts
|
||||
re-derived with a plain `grep -lE '^[[:space:]]*package[[:space:]]+'`
|
||||
over each tree's `.sv`/`.svh` files (a different method than whatever the
|
||||
dev used, deliberately): `hw/ip` **181/1805**, `hw/vendor` **24/285**,
|
||||
`hw/dv` **40/365** — all three exact matches.
|
||||
|
||||
**7. `harvest_one` lex-only path.** Read the function
|
||||
(`crates/lucisv/src/lint.rs:100-108`): the `if !interfaces && !packages`
|
||||
branch returns `words::harvest_text(&src)` before any call to
|
||||
`ParsedSource::parse`, so the neither-wanted path is lex-only by
|
||||
construction — not something that could regress silently without a
|
||||
diff touching this exact `if`. **Finding (non-blocking):** there is no
|
||||
test in `lint.rs`'s own `mod tests` pinning this contract, and adding one
|
||||
is not a one-liner — `Job` has no test constructor and its `config:
|
||||
vlog_formatter::Config` field has no `Default` impl, so a pinning test
|
||||
needs a small `Job`-building test helper first. Left as a finding rather
|
||||
than fixed in the main tree per the QA policy on non-trivial fixes;
|
||||
suggested for a future small addition (a `Job`-builder test helper plus
|
||||
one assertion that `harvest_one(job, false, false)` returns empty
|
||||
`declared`/`exports` and equals `words::harvest_text`).
|
||||
|
||||
**Topology edges for the lead** (from the feature README's Handshakes,
|
||||
independently confirmed correct by the `cargo tree` check in §1 and the
|
||||
code reading in §2): apply both — `lucisv ──▶ vlog_linter` gains
|
||||
`package_exports_in`, and `vlog_linter ──▶ vlog_semantic` gains
|
||||
`FileFacts::from_analysis` + `IndexBuilder::{add_facts, finish}` as a read
|
||||
the CLI package half now depends on.
|
||||
|
||||
**Nothing else was touched.** No production files were edited in the main
|
||||
tree; the sabotage and QA attack fixtures live only in the scratch clone
|
||||
(`/private/tmp/.../scratchpad/qa-p3/clone`), which is left in place as
|
||||
QA evidence rather than deleted.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-07 (lead).** Accepted. Read `package_exports_in`,
|
||||
`declares_a_package`, `one_file_index`, `harvest_one`, the equality test's
|
||||
verbatim pre-P3 reference, the six CLI tests, the tracker's P3 entry and
|
||||
both logs; QA's parity over a fixture tree (`check`, all-style, `--fix`
|
||||
outputs and fixed files, a waiver) against a HEAD build and its byte-diff
|
||||
of the five corpus cells are the acceptance.
|
||||
|
||||
- The plan's own shape, delivered as written: one parse in the census,
|
||||
the package half read off it, the AST gate (never text) sparing the
|
||||
nine files in ten that declare no package, the one-file index assembled
|
||||
from the caller's parse through §P2's `FileFacts::from_analysis` — no
|
||||
new semantic API, the CLI still without a direct semantic dependency.
|
||||
- 96 % of the rule's increment removed (142 → 5 ms on `hw/ip`, RSS down
|
||||
8.6 %) with every output byte-identical; the target was half.
|
||||
- The third parse (the lint pass's own) stays, deliberately: retaining
|
||||
1 805 trees against a 200 MiB peak is the memory-for-time trade the
|
||||
plan says to refuse without a recorded case. Filed as a number, not
|
||||
taken.
|
||||
- QA's non-blocking finding — no test pins `harvest_one`'s lex-only path
|
||||
when neither half is wanted — noted; the code reads correctly and a
|
||||
test needs a `Job` constructor the module does not have. Loop-3 list.
|
||||
- The "duplicate package within one file reports the first declaration's
|
||||
members" answer is pre-existing and now pinned, which is better than
|
||||
before.
|
||||
|
||||
Docs applied at merge: topo edges `lucisv ──▶ vlog_linter`
|
||||
(`package_exports_in`) and `vlog_linter ──▶ vlog_semantic`
|
||||
(`FileFacts::from_analysis` + `IndexBuilder`).
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,355 @@
|
||||
# performance-take4
|
||||
|
||||
TODO §58 — the fourth opentitan performance round. **0.49.0 against 0.43.0**,
|
||||
with take 3's 0.43.0 column carried beside every row so each one is a
|
||||
before/after, and 0.39.0 kept for the CLI sweeps. Output:
|
||||
`docs/performance_take4.md`, a `docs/perf/README.md` entry, and — the round's
|
||||
one durable artefact — a **committed** harness in `tools/perf/`.
|
||||
|
||||
## Goal
|
||||
|
||||
Measure what 0.44–0.49 did to the server and the CLI on a 3 976-file corpus,
|
||||
with the same table shapes take 3 used, so a reader can put the two documents
|
||||
side by side and read a row across four releases. Read-only: a regression is
|
||||
filed with a reproduction, never fixed here. And leave behind the client the
|
||||
last three rounds each lost — take 2's scripts were gone when take 3 ran, and
|
||||
take 3's were gone when this one started, so take 3's numbers had to be
|
||||
re-derived from take 2's *prose*. `tools/perf/` ends that.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The tree at `4c2dae3` is 0.49.0.** Verified: `target/release/lucisv
|
||||
--version` prints `0.49.0`, and the server binary's mtime (01:13) is later
|
||||
than the last change under `crates/` (01:12:49), so no rebuild was needed
|
||||
before timing.
|
||||
- **The two servers differ only in their code.** Both were driven by the same
|
||||
Python client, in the same session, on the same corpus commit, within one
|
||||
hour of each other. That is what makes tonight's 0.43.0 column — not take
|
||||
3's — the honest baseline: the harness and the machine are held fixed.
|
||||
- **The machine is a desktop, and it was busier than take 3's.** Load average
|
||||
3.7–7.1 throughout, with WindowServer at 45–51% and loginwindow at 24–29%.
|
||||
Take 3 measured at load 2–4. Sub-millisecond rows therefore sit on a fatter
|
||||
floor than take 3's; §9 says so and §8.9 dismisses the lot. Every
|
||||
conclusion below is drawn from a 0.49.0-vs-0.43.0 pair taken on this
|
||||
machine, in this state.
|
||||
- **`--select error,warning,style` is not "all rules"** — three rule classes
|
||||
by name, which is what §58 asked for.
|
||||
- **"Cold cache" is lucisv's store, not the OS page cache.** opentitan has now
|
||||
been walked by four measurement rounds.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `lucisv-server`'s wire protocol: `initialize` with
|
||||
`initializationOptions.storagePath` (index-persistence),
|
||||
`workspace/configuration` for the `lucisv` section (index-scope's
|
||||
`index.scope` / `index.scopeDepth`), `--verbose`'s
|
||||
`timing: <method> answered in <n> ms` over `window/logMessage`
|
||||
(verbose-timing), and `lucisv/moduleHierarchy` with `params: {}`
|
||||
(dut-hierarchy). None of these is changed by this round.
|
||||
- **Consumes** the CLI's `format --cache-dir <path> --check`,
|
||||
`format --no-cache --check` and `check [--select …]`. Note the argument
|
||||
order: `--cache-dir` is a *subcommand* option, so it follows `format`.
|
||||
- **Promises** `tools/perf/` to take 5: `lspclient.py` and `bench.py` keep
|
||||
their phase names and their `results.jsonl` row shape
|
||||
(`phase`/`label`/`row`/`ms`/`n`/`note`), so a later round can diff a row
|
||||
against this one by name. A phase that changes what it measures gets a new
|
||||
name rather than a new meaning.
|
||||
- **Requests nothing** of another module. Two observations that a future lane
|
||||
may want are filed as findings in `docs/performance_take4.md` §8, not as
|
||||
handshake requests, because this lane fixes nothing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] harness in `tools/perf/` with its README; runs from a clean checkout
|
||||
- [x] server table re-measured, 0.49.0 vs 0.43.0 vs take 3 — take 4 §2
|
||||
- [x] new rows: didOpen release numbers, the five refactoring offer sites,
|
||||
tail rename and instance-head completion, moduleHierarchy, index size
|
||||
and RSS
|
||||
- [x] CLI sweeps, three binaries, RSS included; outcome diff since 0.43.0
|
||||
- [x] `docs/performance_take4.md` + perf README entry
|
||||
- [x] opentitan status unchanged after every phase; no guard kill
|
||||
- [x] QA (TODO §58's last line) — PASS, see QA log
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-07 (dev).**
|
||||
|
||||
- Read CLAUDE.md, TODO §58, `docs/performance_take3.md` in full, and the perf
|
||||
README's 2026-09-05 entry. Recorded provenance for all five binaries
|
||||
(§1). Confirmed the tree's server binary is current; **no rebuild ran**.
|
||||
- Built the 0.43.0 server from the `v0.43.0` tag in a scratch `git worktree`
|
||||
under the scratchpad (57.75 s, under the guard). The main tree was never
|
||||
checked out, reset or stashed. The worktree was removed after the last
|
||||
measurement.
|
||||
- Wrote `tools/perf/` — `lspclient.py`, `sites.py`, `bench.py`, `sweep.sh`,
|
||||
`sweeptable.py`, `outcomes.sh`, `README.md`. Standard library only.
|
||||
Deviations from take 3's client, all deliberate: sites are resolved from
|
||||
the file *text* at run time rather than hard-coded; the scan barrier is
|
||||
1.5 s of silence rather than the `$/progress` `end` (the end report is
|
||||
followed by more chatter); and there is a `probe` phase, which is how the
|
||||
new offer sites below were found rather than guessed.
|
||||
- **Found the new offer sites empirically.** Swept every instantiation-shaped
|
||||
and `import` line in a set of RTL files with `codeAction` and kept the
|
||||
positions that actually offer. That turned up
|
||||
`sha3_fpv.sv 54:4` (expand `.*`), `aes_sbox_canright_masked.sv 42:2`
|
||||
(organize imports), `aes_wrap.sv 66:2` (inline `tlul_cmd_intg_gen`) and
|
||||
confirmed take 3's `aes_wrap.sv 78:2` (connect 2 missing ports). **There is
|
||||
no `convert to ANSI` site**: a scan of all 1 311 module headers in
|
||||
opentitan's `hw/` found zero non-ANSI ones, so that row measures an ANSI
|
||||
header instead and the corpus fact is reported in §6b.
|
||||
- **Found the §49 tail site empirically too.** The first two candidates did
|
||||
not resolve — `pwrmgr.sv`'s `u_fsm.state_q` sits inside a `` ` ``-macro
|
||||
assertion argument, and `pinmux.sv`'s `u_reg.intg_err` did not resolve
|
||||
either — so the round uses `entropy_src_core.sv`'s
|
||||
`u_entropy_src_main_sm.state_q`, which does. The two that do not are
|
||||
recorded in §8.
|
||||
- Ran the untimed per-file outcome sweeps for all three CLI binaries, then
|
||||
the timed CLI sweeps, then the LSP phases for 0.49.0 and for 0.43.0.
|
||||
`git -C opentitan status --porcelain` was checked after every phase and
|
||||
reported the same three pre-existing modified files every time. **No guard
|
||||
kill occurred**; the largest resident set anything reached was 588 MB
|
||||
(`lucisv-server` after a warm workspace scan), 7% of the 8 GB limit.
|
||||
- Three phases (`widen`, `blockers`, `rss`) were first written with one try
|
||||
per cell; that violated §58's three-tries rule, so they were rewritten to
|
||||
loop and **re-run on both binaries**, and the single-try rows were deleted
|
||||
from `results.jsonl` before the re-run. Nothing else in the file was
|
||||
edited after it was written.
|
||||
- **Split the harness after the measurements and re-verified it.** `bench.py`
|
||||
reached 537 production lines, over §58's ~500; the phases for what 0.44–0.49
|
||||
added moved to `phases_new.py` and the shared registry/config/session code
|
||||
to `harness.py` (330 / 152 / 76 production lines). **Every one of the 20
|
||||
phases was then re-run through the split files**, and ten rows were checked
|
||||
against the document within its stated tolerances — `didOpen
|
||||
pinmux_reg_top.sv` (doc 112.1 / 127.9–130.7 → 125.6 / 113.1–129.7 ms), the
|
||||
tail rename (793.2 / 750.7–751.9 → 785.0 / 746.3–753.9), the 128-fan-out
|
||||
eager `codeAction` (511.8 / 467.1–473.6 → 506.8 / 474.2), `moduleHierarchy`
|
||||
(76.2 / 41.1–53.8 → 68.7 / 41.1–53.1), the port-action resolve
|
||||
(163.9 / 158.2–159.5 → 163.1 / 157.3–160.4), the warm workspace scan
|
||||
(1 266 → 1 248), cold RSS (542 736 → 541 152 KB), `rename` on `aes`
|
||||
(165.1 / 133.5–139.4 → 164.5 / 137.2), `didOpen spi_device.sv`
|
||||
(15.5 / 13.8–15.1 → 13.7 / 15.3–15.0) and `tailcompletion`
|
||||
(1.11 / 0.45–0.53 → 0.96 / 0.47). All inside tolerance; the verification run
|
||||
is `scratchpad/verify.jsonl`, labelled `verify-0.49.0`.
|
||||
- Wrote `docs/performance_take4.md` (§0–§10), the perf README entry, and
|
||||
ticked §58's dev lines in `TODO.md`.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-07 (QA).**
|
||||
|
||||
Read CLAUDE.md, TODO §58, this README, `docs/performance_take4.md` in full
|
||||
(961 lines), `tools/perf/README.md`, the harness source, and the dev's raw
|
||||
logs at `~/.cache/lucisv-perf/take4/{results.jsonl,verify.jsonl}` and the
|
||||
scratchpad (`logs/`, `outcomes/`, `sweep/`, `census.py` +
|
||||
`logs/census-0.49.0.txt`).
|
||||
|
||||
**Setup.** `python3 -m py_compile tools/perf/*.py` — clean. Built the
|
||||
0.43.0 server from a fresh clone (not a worktree, per the hard rules):
|
||||
`git clone -q --no-checkout … && git checkout -q v0.43.0`, then
|
||||
`tools/guard.sh -m 8 -t 1800 -- cargo build --release -p lucisv_server`
|
||||
(58.10 s, no kill). Binary sha256 `7f0f27d6…`, matches §1's row exactly.
|
||||
Verified `target/release/lucisv --version` → `0.49.0` and
|
||||
`lucisv-server` sha256 `c6e40ecd…`, matching §1. All three CLI baseline
|
||||
shas/sizes (`0c943c4c…`/3236768 B for 0.49.0, `89379a12…`/2828576 B for
|
||||
0.43.0) matched by direct `shasum`/`ls`.
|
||||
|
||||
**1. Harness.** Compiles clean. Ran every phase listed below through
|
||||
`tools/perf/bench.py` exactly as `tools/perf/README.md` documents — no
|
||||
undocumented step was needed. One thing the README doesn't spell out:
|
||||
`bench.py`'s `--tries N` is the *repeat* count, and the printed/recorded
|
||||
list is `[first, repeat×N]` (so `--tries 4` prints 5 numbers) — obvious
|
||||
once seen, but worth a line in the README for take 5.
|
||||
|
||||
**2. Rows re-run, both binaries, committed harness** (`--tries 3` or `4`
|
||||
matching the phase; my raw rows are in
|
||||
`scratchpad/qa/results/results.jsonl`, labels `0.49.0-qa`/`0.43.0-qa`):
|
||||
|
||||
| Row | Doc (first / repeats) | **QA re-run 0.49.0** | **QA re-run 0.43.0** | Verdict |
|
||||
|---|---|---|---|---|
|
||||
| Workspace scan, cold | 2712/2691–2712 (49) · 2645/2640–2656 (43) | **2712.4/2690.9–2711.9** | **2637.0/2620.9–2632.3** | in band |
|
||||
| Workspace scan, warm | 1266.1/1239.8–1285.6 (49) · 1173.4/1167.1–1173.6 (43) | **1252.1/1244.7–1271.5** | **1183.6/1168.7–1185.3** | in band |
|
||||
| `didOpen pinmux_reg_top.sv`→request | 112.1/127.9–130.7 (49) · 1605/1604–1611 (43) | **127.5/103.4–126.5** (mean 119.1, doc mean 123.6, −3.6%) | **1621.1/1518.6–1565.7** (mean 1568.4, doc mean 1607.4, −2.4%) | in band (§9's ±10%/±5%) |
|
||||
| `codeAction prim_flop_2sync (128)`, lazy | 15.0/8.1–10.5 | **17.5/7.2–11.0** | **13.3/9.8–11.5** | in band |
|
||||
| `codeAction prim_flop_2sync (128)`, eager | 511.8/467.1–473.6 | **511.8/468.8–473.1** (traced exactly to the dev's own row, see §4 below) — QA re-run: **497.2/468.4–479.1** | **271.0/237.0–241.2** | in band |
|
||||
| `codeAction` comment line, lazy (§8.2) | 4.70/3.18–3.84 (49) · 2.17/1.12–1.32 (43) | **2.81/2.24–2.38** (run1), **7.43/4.11–5.46** (run2) | **1.81/1.15–1.61** | see finding B below |
|
||||
| `rename` on `aes` | 165.1/133.5–139.4 (49) · 159.8/133.2–136.2 (43) | **165.0/133.5–139.4** | **158.5/130.7–135.5** | in band |
|
||||
| `completion` at 0 chars | 7.2/4.2–5.3 (49) · 7.8/4.2–5.4 (43) | **7.1/3.9–5.1** | **9.0/4.4–5.0** | in band |
|
||||
| tail `rename` (§49, new row) | 793.2/750.7–751.9 (49) · 88.0/65.8–66.7 (43) | **777.8/747.9–751.2**, tail edited | **87.4/65.6–66.4**, tail NOT edited | in band, correctness match |
|
||||
| `moduleHierarchy` (new row) | 76.2/41.1–53.8 (49) · 70.3/41.0–48.8 (43) | **71.9/40.8–53.9**, 2 600 051 B, 1546/1529/schema 2 | **70.3/40.8–44.3** (a subset of retries) | in band, payload byte-identical |
|
||||
|
||||
10 rows re-run (task asked for 8), both binaries, all inside §9's stated
|
||||
tolerance bands except the comment-line row, which is finding B.
|
||||
|
||||
**3. CLI outcome diff, independently re-derived**, two trees (`hw/ip`,
|
||||
`hw/top_earlgrey/ip`), plus `hw/top_darjeeling/ip` to nail down the
|
||||
17/2/1 split:
|
||||
|
||||
- `format --check --no-cache`: `diff` against 0.43.0/0.49.0 is **empty**
|
||||
on both `hw/ip` (1777 lines each) and `hw/top_earlgrey/ip` (47 lines
|
||||
each) — byte-identical formatter verdicts, confirmed.
|
||||
- `check` (default rules): `diff` empty on both trees (446/15 lines) —
|
||||
byte-identical, confirmed.
|
||||
- `check --select error,warning,style`: `hw/ip` 7734→7751 (**+17**),
|
||||
`hw/top_earlgrey/ip` 551→553 (**+2**), `hw/top_darjeeling/ip`
|
||||
382→383 (**+1**) — **17+2+1 = 20**, every added line is a
|
||||
`[unused-import]` style finding, nothing else changed anywhere. Doc's
|
||||
claim confirmed exactly.
|
||||
- Re-timed `format --check` warm and `check` default on `hw/ip`, three
|
||||
tries, three binaries, `/usr/bin/time -l`: format warm 0.55–0.67 s
|
||||
across all three binaries (doc: 0.58–0.63); `check` default
|
||||
0.35–0.41 s (doc: 0.34–0.41); `check --select` 0.46–0.60 s, confirming
|
||||
the 1.27×-ish slope (mine: 0.47 mean 0.43 → 0.59 mean 0.49, 1.26×;
|
||||
doc 1.27×). All in band.
|
||||
|
||||
**4. §8.2 mechanism, read not fixed.** `crates/vlog_refactor/src/inline/mod.rs:73`
|
||||
(`inline_site`) and `crates/vlog_refactor/src/extract/mod.rs:82`
|
||||
(`extract_site`) both call `parse_source_tolerant(text)` — a full tolerant
|
||||
parse of the whole buffer — on every invocation, and refuse (`None`) if
|
||||
that parse produced any diagnostic. Both are called from the server's
|
||||
`code_actions` gating on *every* `textDocument/codeAction`:
|
||||
`crates/lucisv_server/src/inline_module.rs:50` and
|
||||
`crates/lucisv_server/src/extract.rs:76`/`:113`. The doc's claim — the
|
||||
gates parse the cursor's buffer on every request, unconditionally, offer
|
||||
or not — is accurate and the two file:line citations for `inline_site`
|
||||
check out exactly; the doc names `extract_site` in prose but doesn't cite
|
||||
its own definition/call site (`extract/mod.rs:82`, `extract.rs:76`) — a
|
||||
cosmetic citation gap, not a wrong claim, since I verified `extract_site`
|
||||
does the identical thing.
|
||||
|
||||
**5. Attack — internal consistency and corpus facts.**
|
||||
|
||||
- **Census (§6b, 2 440 positions, extract 89%/inline 11%).** The dev's
|
||||
`scratchpad/census.py` + `logs/census-0.49.0.txt` gives files 205,
|
||||
positions 2440, extract 2171, inline 263, organize 12, connect 1 —
|
||||
matches the document exactly. I re-ran an independent subset (aes/rtl
|
||||
only, 40 files, edited `dirs=` in a copy of the script) and got 914
|
||||
positions, extract 870 (95.2%), inline 129 (14.1%), organize 12,
|
||||
connect 1 — the organize/connect *sites* are byte-identical to the
|
||||
full run's list (all 12 organize sites and the 1 connect site live in
|
||||
`aes/rtl`), and the extract/inline proportions are in the same range;
|
||||
the difference from 89%/11% is explained by `prim/rtl`'s different mix
|
||||
of item shapes, not an inconsistency.
|
||||
- **"Zero non-ANSI headers of 1 311" (§6b).** No script or log for this
|
||||
claim exists anywhere in `tools/perf/` or the scratchpad — filed as
|
||||
finding A. I wrote an independent census (line-anchored `module NAME`
|
||||
regex, comments stripped, port-list scanned for `input`/`output`/
|
||||
`inout`/`ref`) over all 3 932 `.sv`/`.v` files under `opentitan/hw`:
|
||||
1310 module headers (doc: 1311, a 1-header methodology difference),
|
||||
2 apparent "non-ANSI" hits that turned out to be false positives on
|
||||
inspection (`hw/vendor/lowrisc_ibex/.../tb.sv` and
|
||||
`hw/vendor/pulp_riscv_dbg/tb/tb_top.sv` — both `module NAME #(params) ;`
|
||||
with **no port list at all**, not a non-ANSI port list). Net: **zero
|
||||
genuine non-ANSI headers**, confirming the doc's claim in substance
|
||||
even though it isn't traceable to a committed artifact.
|
||||
- **File-count sanity**: `find hw/ -name '*.sv' -o -name '*.v' | wc -l`
|
||||
→ 3932, matches §6b's "3 932 `.sv`/`.v` files" exactly.
|
||||
|
||||
**6. Traceability sample (task asked for 25; I checked ~30).** Every one
|
||||
of the following was found verbatim in `results.jsonl`, a `sweep/*.txt`
|
||||
log, `logs/sweeptable.txt`, an `outcomes/*.txt` file, or
|
||||
`logs/census-0.49.0.txt`: the §0 `prim_flop_2sync (128) eager` wire/verbose
|
||||
pair, the §1 sha256/size sextet, the §2 workspace-scan cold/warm rows, the
|
||||
`didOpen pinmux_reg_top.sv` row, the tail-rename row, `codeAction
|
||||
prim_flop_2sync (128) eager` and `prim_alert_sender (67) eager`, `didOpen
|
||||
aes_core.sv`, the `expand .*` offer+resolve pair, `rename aes`, the
|
||||
`spi_device.sv` widen cell, `moduleHierarchy` (both binaries, payload
|
||||
2 600 051 B, 1546/1529/schema 2), the cold/warm RSS triples and index
|
||||
sizes (45404/39940 KB) for both binaries, every `hw/ip` row in
|
||||
`sweeptable.txt` (format cold/warm, check default/select, RSS), every
|
||||
outcome-count line (`found 445/446/7751/7734/7735 violations`, `1772/1773
|
||||
files would be reformatted`), and the load-average extremes (7.10, 3.68)
|
||||
in `logs/outcomes-load-before.txt`/`logs/lsp-0.49.0-machine.txt`. **Not
|
||||
traceable**: the §6b "1 311 module headers / zero non-ANSI" pair (finding
|
||||
A above) — no script, log, or note anywhere records how it was computed.
|
||||
|
||||
**7. opentitan and tree status.** `git -C opentitan status --porcelain`
|
||||
checked after every phase of my own re-runs (scan, didopen, codeaction ×2,
|
||||
rename, completion, hierarchy, tailrename, both outcome sweeps, both
|
||||
timed sweeps, the census re-run) — every single time, exactly the three
|
||||
pre-existing files: `hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`.
|
||||
Never written to otherwise. Main tree `git status --short` shows only the
|
||||
dev's untracked/modified files (`TODO.md`, `docs/perf/README.md`,
|
||||
`docs/features/performance-take4/`, `docs/performance_take4.md`,
|
||||
`tools/perf/`) plus this QA-log edit. **No guard kill** in any of my
|
||||
~20 guarded invocations (server sessions, the one `cargo build`, CLI
|
||||
sweeps); largest RSS I observed was the 0.49.0 server's 588 608 KB after
|
||||
a warm scan, same as the doc reports.
|
||||
|
||||
### Findings
|
||||
|
||||
**A (low, traceability).** `docs/performance_take4.md:428-430`'s "zero
|
||||
non-ANSI headers" / "1 311 module headers" claim has no backing script or
|
||||
log anywhere in `tools/perf/` or the scratchpad, unlike every other census
|
||||
in this round. This breaks `tools/perf/README.md:103-104`'s own rule
|
||||
("Nothing in the document may quote a number that is not in this file or
|
||||
in a sweep.sh / outcomes.sh log"). Independently reproduced as
|
||||
substantively correct (§5 above: 1310 headers, 0 genuine non-ANSI after
|
||||
excluding two no-port-list false positives) — not a correctness defect,
|
||||
but the number should not have shipped without a saved script, and a
|
||||
future round should add one before quoting a from-scratch corpus census.
|
||||
|
||||
**B (informational, not blocking).** The comment-line lazy `codeAction`
|
||||
row — §8.2's central piece of evidence for the "2.9×" gate-cost claim —
|
||||
is noisier than its own 1–20 ms/±20% tolerance band. Two independent QA
|
||||
reruns of the `codeaction` phase on the *same* 0.49.0 binary, minutes
|
||||
apart, gave means of 2.42 ms and 5.25 ms for this row (doc: 3.91 ms
|
||||
mean), a 2.2× swing between two back-to-back runs of the identical
|
||||
binary and harness — each individual run falls outside ±20% of the
|
||||
document's number, in opposite directions. The qualitative finding holds
|
||||
(0.49.0 consistently slower than 0.43.0 at this cursor: my 0.43.0 mean
|
||||
was 1.43 ms both times) and the *average* of my two 0.49.0 reruns
|
||||
(≈2.68×) lands close to the doc's claimed 2.9×, but a single three/four-try
|
||||
reading — which is what the document and the harness's default both
|
||||
take — is not reliable at this row's magnitude on this machine. Not a
|
||||
finding against the document's conclusion, but future rounds should take
|
||||
more tries (8–10) for any sub-5 ms row used as load-bearing evidence for a
|
||||
specific multiplier.
|
||||
|
||||
### Verdict: **PASS**
|
||||
|
||||
Both findings are minor and non-blocking: finding A is a traceability gap
|
||||
with a substance-confirmed number, finding B is a reproducibility caveat
|
||||
that strengthens rather than undermines the document's own qualitative
|
||||
claim. Every row I re-ran landed inside §9's tolerance or is explained by
|
||||
machine noise the document already documents; the CLI outcome diff
|
||||
("byte-identical formatter verdicts", "20 new unused-import findings,
|
||||
17/2/1 split") reproduced exactly on three independent trees; the §8.2
|
||||
mechanism claim checks out against the source; opentitan was never
|
||||
written to; the main tree carries only the dev's files; no guard kill
|
||||
occurred anywhere in this QA pass.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-07 (lead).** Accepted. Read the document end to end, the §2 table
|
||||
against take 3's, the perf README entry, the harness README and the QA log.
|
||||
|
||||
- The round answers the question it was asked: 0.49.0 against 0.43.0 with
|
||||
the same client in the same hour, so the columns are comparable in a way
|
||||
take 3's could not be. The one-line reading (four things moved) is
|
||||
supported by the table, and §8.9's dismissal of the sub-millisecond rows
|
||||
is the right call on a desktop-loaded machine.
|
||||
- §8.2 verified in the source by me and by QA: `inline_site` and
|
||||
`extract_site` each re-parse the whole buffer on every `codeAction`
|
||||
(`crates/vlog_refactor/src/inline/mod.rs:74`, `extract/mod.rs:83`),
|
||||
called from `inline_module.rs:51` and `extract.rs:76`, while the server
|
||||
already holds the document's tree. The fix is the shape §37.1 used and is
|
||||
filed for the owner's ruling in TODO's loop-3 list, not done here (this
|
||||
lane fixes nothing, by design).
|
||||
- §8.3 (the tail rename at 751 ms) is filed correctly as a cost of a
|
||||
correct answer; `completion` on the same surface being free points at
|
||||
rename's reference walk, which is where a future lane should look first.
|
||||
- The harness is the durable result: nine files, standard library only,
|
||||
phases named so take 5 can diff rows by name. The 500-line split was the
|
||||
right response to §58's size rule.
|
||||
- QA finding A (the header census untraceable) fixed by a traceability
|
||||
note in §6b naming the method and QA's independent count; finding B (the
|
||||
comment-line row noisier than its band) is already stated in the
|
||||
document's tolerance text and the multiplier holds across both QA
|
||||
reruns, so no change.
|
||||
- Deviations accepted: the busier machine (stated as the largest caveat,
|
||||
mitigated structurally), the six-file harness, the ANSI row measuring an
|
||||
ANSI header because the corpus has no other kind.
|
||||
|
||||
Docs applied at merge: perf README entry (the dev's), TODO §58 ticked, the
|
||||
§8.2 gate and §8.3 walk added to the loop-3 open items.
|
||||
@@ -99,7 +99,9 @@ impl Scan {
|
||||
pub fn skipped(&self) -> usize;
|
||||
pub fn cached(&self) -> usize;
|
||||
pub fn total(&self) -> usize;
|
||||
pub fn index_next(&mut self, path: &Path) -> bool;
|
||||
pub fn neighbourhood_indexed(&self) -> bool; // perf5-p4 §P4b3
|
||||
pub fn remaining(&self) -> Vec<PathBuf>; // perf5-p4 §P4b3
|
||||
pub fn reorder(&mut self, ordered: WorkList); // perf5-p4 §P4b3
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
@@ -299,6 +301,106 @@ attached.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-08 — §P4b3: when a held request is drained, and what it reads
|
||||
|
||||
**The order contract is unchanged. The *moment* a held request is drained
|
||||
moved, and it moved later.** Written here because this README is where "only
|
||||
the startup scan answers mid-way" lives, and it is now "…once the user's own
|
||||
folder is in it" (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
|
||||
Three things changed, none of them a promise:
|
||||
|
||||
1. **A held request is answered once the scan has stepped the user's own
|
||||
neighbourhood** — the open buffers and the directories those buffers raise
|
||||
to — rather than at the first interleave point.
|
||||
`Server::waiting_for_this_scan` consults a new `Server::head_owed`, set from
|
||||
`Scan::neighbourhood_indexed`, and the `publish_scan` that already ran in
|
||||
the same call is what makes that neighbourhood answerable before the answer
|
||||
goes out. A scan with **no** neighbourhood (nothing open, an `untitled:`
|
||||
buffer, or a folder that covers the workspace) reports it with a head of 0
|
||||
and drains at the first interleave point exactly as it always did.
|
||||
*Why:* §P4b2 measured what draining at the first file answers, and it is
|
||||
`[]` — coherent, and useless. Holding a request **longer** is always safe
|
||||
under this contract; answering it earlier is what was not.
|
||||
2. **`head_owed` is a fifth `must_wait` clause**, and it is what a request
|
||||
behind a `didOpen` in a mid-scan burst now waits on. That reinstates, inside
|
||||
one scan, exactly what the widen the `didOpen` used to trigger did: the
|
||||
requests behind it were owed its effect. `Workspace::open_next` then
|
||||
re-orders what is left of the work list around the buffers open now,
|
||||
replacing `Scan::index_next` — a `didOpen` brings its folder, not only its
|
||||
own file.
|
||||
3. **`Scan::index_next` is gone**, replaced by `Scan::remaining` /
|
||||
`Scan::reorder` and `Workspace::open_next`. Reordering the tail still cannot
|
||||
reach the index (`IndexBuilder::finish` sorts by path), which is the
|
||||
argument the removed method's own doc comment made.
|
||||
|
||||
**The coherence contract is untouched**: an answer mid-scan still sees a
|
||||
published prefix of all three tables, published together, and `scanserve`'s
|
||||
`mismatched_answers` is 0 in every row of both binaries. What a scan holds
|
||||
while it runs did change — a file's text is read at the step that indexes it
|
||||
and dropped there, so `Scan` carries paths rather than 34 MiB of source — and
|
||||
`docs/features/index-scope/README.md` carries that amendment.
|
||||
|
||||
### 2026-09-08 — dev (Opus), §P4b2: the startup scan is now staged
|
||||
|
||||
**The order contract is unchanged; what changed is which scan the opening
|
||||
burst waits for.** Before today a session ran its startup scan at the
|
||||
**default** settings and only then asked the client for its own
|
||||
(`workspace/configuration`); a client whose `lucisv.index.scope` differs paid a
|
||||
second, *configured* scan when the answer landed, and — because that second
|
||||
scan is one a message asked for — `Server::must_wait`'s `answering_a_rescan`
|
||||
clause held every request that arrived during it. §P4b measured what that cost
|
||||
on opentitan: **0.9 s warm, 2.6 s cold**, and named it a contract rather than a
|
||||
routing bug (`docs/features/perf5-p4/README.md`, "the interleaving question,
|
||||
answered and filed").
|
||||
|
||||
The lead's ruling took the plan's own sentence — *"if the default scan is
|
||||
routinely discarded, stage the initial scan until configuration arrives"* —
|
||||
rather than the fourth `must_wait` state this lane had proposed. So:
|
||||
|
||||
- `Server::started` now sends the settings pull **first** and waits up to
|
||||
`CONFIGURATION_WAIT` (2 s) for the answer, then runs **one**
|
||||
`scan_until_settled(false)` — the startup scan proper — at the scope that
|
||||
answer decided. The empty default-scope scan no longer happens at all, and
|
||||
neither does the configured rescan behind it.
|
||||
- A client that never answers, or answers after the bound, gets the scan at the
|
||||
defaults exactly as before, and its late answer is an ordinary settings
|
||||
change with an ordinary rescan behind it — held requests and all. A client
|
||||
that never advertised `workspace/configuration` is untouched: nothing is
|
||||
asked, nothing is waited for.
|
||||
|
||||
**Decision 2 of this feature's three is not relaxed.** *"Only the startup scan
|
||||
answers mid-way. A scan a message asked for has that message queued ahead of
|
||||
everything else"* still holds, word for word. What the staging adds is that
|
||||
requests arriving in the **configuration window** — before the startup scan has
|
||||
begun — are held by a fourth `must_wait` clause (`staging`) and then handed to
|
||||
that scan by `Server::waiting_for_this_scan`, which takes `held` only when
|
||||
`answering_a_rescan` and `rescan_wanted` are both clear. The justification is
|
||||
this feature's own, unchanged:
|
||||
|
||||
- the scan they wait for is the **startup** scan: nothing is queued ahead of
|
||||
it, because the message that would have been — the client's settings answer —
|
||||
has already been applied before it starts;
|
||||
- it is the session's **first** scan, so `finish_scan`'s deferred `gone` set is
|
||||
empty by construction. The QA log's argument below (*"every scan capable of
|
||||
having `gone` files non-empty is a rescan … which `must_wait` already
|
||||
blocks"*) is therefore satisfied, not weakened: a rescan still takes nothing
|
||||
from `held`.
|
||||
|
||||
**The widen is folded in rather than run.** A `didOpen` arriving in the window
|
||||
installs its buffer and records that a scan is wanted; the one scan that
|
||||
follows resolves the scope with that buffer in place and `open_first` puts its
|
||||
file at the head of the work list. `rescan_wanted` is cleared before that scan
|
||||
because the scan *is* what every trigger in the window was asking for — it is
|
||||
the session's first, it resolves the scope afresh and reads every file in it.
|
||||
|
||||
Pinned by `server/tests/startup.rs` (five wire tests: one scan at the answered
|
||||
scope; the bounded fallback and the late answer's ordinary rescan; a `didOpen`
|
||||
folded in and indexed first; a definition answered *inside* the startup scan,
|
||||
before the bar comes down; a client that cannot be asked, unchanged) and by
|
||||
this feature's own suite, green unmodified — `INTERLEAVE_ABOVE`'s hard
|
||||
boundary, the held-order tests, the coalescing and shutdown tests included.
|
||||
|
||||
### 2026-08-28 — dev
|
||||
|
||||
**Measured the merge first, and the number chose the design.** The brief left
|
||||
|
||||
@@ -1109,3 +1109,178 @@ measures the same as 0.43.0 everywhere in the "before" column, so this was
|
||||
never a regression — the rule had been ordered that way since it was
|
||||
written. Published diagnostics are byte-identical before and after. Full
|
||||
account: `docs/features/didopen-cost/README.md`.
|
||||
|
||||
### 2026-09-07 — take 4
|
||||
|
||||
TODO §58. **0.49.0 against 0.43.0** on opentitan `0098135264`, both binaries
|
||||
measured in the same hour with the same client. Full document:
|
||||
[`../performance_take4.md`](../performance_take4.md) (§0–§10). Feature
|
||||
README: `docs/features/performance-take4/README.md`.
|
||||
|
||||
**The harness is now in the repository.** Take 2's, take 3's and take 1's
|
||||
clients all lived in a scratch directory and all three are gone — take 3's
|
||||
numbers had to be re-derived from take 2's prose. Take 4's lives in
|
||||
`tools/perf/` (`lspclient.py`, `sites.py`, `bench.py`, `sweep.sh`,
|
||||
`sweeptable.py`, `outcomes.sh`, `README.md`; Python 3 standard library only,
|
||||
runs from a clean checkout). Take 5 reuses it. Sites are resolved from the
|
||||
file text at run time, and the new offer sites were *found* with a `probe`
|
||||
phase rather than guessed.
|
||||
|
||||
**Credits — what got faster.**
|
||||
|
||||
| | 0.43.0 | 0.49.0 | credit |
|
||||
|---|---:|---:|---|
|
||||
| `didOpen pinmux_reg_top.sv` (42 192 L) → next request | 1 605 / 1 604 / 1 611 ms | **112 / 131 / 128 ms** | **§46**, **14×** |
|
||||
| `didOpen spi_device.sv` → next request | 98.7 / 75.2 / 99.5 ms | **15.5 / 13.8 / 15.1 ms** | §46, 6× |
|
||||
| `didOpen aes_core.sv` → next request | 42.6 / 63.0 / 63.1 ms | **11.0 / 4.0 / 10.4 ms** | §46, 7× |
|
||||
| a `didOpen` of an in-scope file at the default scope | 33–69 ms | **5–21 ms** | §46 — take 3's §8.4 **closed** |
|
||||
| `completion` after an instance head + `.` | 24 items, 0.52–0.66 ms | **26 items, 0.45–0.53 ms** | §49, free |
|
||||
| `rename` through an instance tail | 1 file, tail unedited | **2 files, tail edited** | §49, correctness (but see below) |
|
||||
|
||||
The 2026-09-05 entry above took its §46 numbers with temporary timings; **the
|
||||
release build confirms them at the same magnitude**, which was the point of
|
||||
this round's `didopen` phase.
|
||||
|
||||
**Filed findings** (in `performance_take4.md` §8; nothing was fixed here):
|
||||
|
||||
- **§8.2 (medium)** — the *lazy* `codeAction` offer costs 2–5 ms more at every
|
||||
cursor, offered or not: a plain comment line, where **zero** actions are
|
||||
offered on either binary, went 1.12–1.32 → 3.18–3.84 ms (2.9×), and the
|
||||
`definition` pipelined behind a `codeAction` went 3.3–7.3 → 11.2–15.9 ms.
|
||||
The mechanism is the new offers' gates (`inline_site`, `extract_site`) each
|
||||
parsing the cursor's buffer on every cursor move. Still inside a frame; the
|
||||
margin is gone.
|
||||
- **§8.3 (low–medium)** — §49's tail rename is **11.3×** a same-file rename:
|
||||
751 ms for two edited files against 66 ms for one. The correctness is right;
|
||||
the cost freezes the serial queue for three quarters of a second.
|
||||
- **§8.4 (low)** — `check --select error,warning,style` is 1.27× slower on
|
||||
`hw/ip` (0.45 → 0.57 s). 0.48.0's new `unused-import` rule explains part of
|
||||
it; `check` with the *default* rules did **not** move, so take 3's §8.5 has
|
||||
stopped accumulating on the default path.
|
||||
- **§8.5 (low)** — two instance-head tails on this corpus do not resolve
|
||||
(`pwrmgr.sv` 178:10 inside a `` ` ``-macro argument; `pinmux.sv` 687:40).
|
||||
Filed as a question, not a defect claim.
|
||||
- **§8.6 (watch)** — the index is +13.7% on disk (39.0 → 44.3 MB) and
|
||||
+12.6/+15.1% resident (482 → 542 MB cold, 509 → 586 MB warm), which is
|
||||
`FACTS_FORMAT` 18 → 19 and is proportionate.
|
||||
|
||||
**Reported, not re-filed:** the eager `codeAction` path (a client without
|
||||
`codeAction.resolveSupport`) is **1.95–2.07× dearer** at every fan-out —
|
||||
243 → 470 ms at 128 files. The owner ruled it a non-hot path on 2026-09-05, so
|
||||
take 4 reports the number and does not file it again.
|
||||
|
||||
**Outcome diff, 0.43.0 → 0.49.0** (`format --check --no-cache`, `check`,
|
||||
`check --select …` over the same five trees): `format --check` and default
|
||||
`check` are **byte-identical on all five trees** — §54's grammar additions
|
||||
change no per-file verdict on this corpus, and §38's fixes stay fixed. The
|
||||
only change anywhere is **20 new `unused-import` style findings** (`hw/ip`
|
||||
+17, `hw/top_earlgrey/ip` +2, `hw/top_darjeeling/ip` +1), all from the rule
|
||||
0.48.0 added. No violation disappeared. Nothing is unexplained.
|
||||
|
||||
**Two corpus facts worth remembering.** Opentitan has **zero** non-ANSI module
|
||||
headers (all 1 311 headers scanned), so §51's `convert to ANSI` has no site
|
||||
here at all. And take 3's "the lightbulb is almost never lit" no longer
|
||||
describes this corpus: a 205-file, 2 440-position census at 0.49.0 finds
|
||||
`extract selection` offered at **89%** of positions and `inline` at **11%**,
|
||||
against exactly **one** port-refactoring offer — the same `aes_wrap.sv` 78:2
|
||||
take 3 found.
|
||||
|
||||
**Caveat, stated because it is the largest one in the document.** The machine
|
||||
ran a live desktop session throughout (WindowServer 45–51%, load average
|
||||
3.7–7.1); take 3 measured at load 2–4. The transport floor moved 4× between
|
||||
two sessions of the same client minutes apart. The mitigation is structural —
|
||||
both binaries were measured alternating within the hour with one client — and
|
||||
every conclusion above is a 0.49.0-vs-0.43.0 pair from that window. Nothing
|
||||
under 0.5 ms is read. No guard kill; the largest resident set anything reached
|
||||
was 588 MB, 7% of the 8 GB limit. The opentitan checkout was never written and
|
||||
its `git status --porcelain` was checked after every phase.
|
||||
|
||||
---
|
||||
|
||||
## 2026-09-07 — take 5 §P0: two take-4 row meanings are superseded
|
||||
|
||||
TODO §60.0, `docs/features/perf5-p0/README.md`. **No performance number here
|
||||
changes**: P0 touched `tools/perf/` only, and the 0.50.0 binaries it measured
|
||||
are byte-identical to the ones the take-5 baseline used. Two *meanings* do
|
||||
change, and this note exists so nobody reads a take-4 row the wrong way.
|
||||
|
||||
- **The `rss` phase's `ms` field was never a latency.** Take 4's and the take-5
|
||||
baseline's `rss` rows put idle RSS (KiB) in `ms` and the store size (KiB) in
|
||||
`n`. Those rows stand as recorded; **new rows use `rss_kib`, `peak_rss_kib`
|
||||
and `store_kib` with `units: "KiB"` and carry no `ms` at all.** Peak RSS is
|
||||
new (a 50 ms `ps -o rss=` poll across the scan); on this workload it equals
|
||||
idle RSS to the KiB in every session, so the resident set has no transient
|
||||
above its idle value.
|
||||
- **Take 4's `extract-module resolve` and `inline-module resolve` rows
|
||||
measured a refusal, not a refactoring.** Those offers carry a *command*, not
|
||||
an edit; `codeAction/resolve` on them reached the ports resolver, which
|
||||
rejects an offer without its data. Nothing in take 4's document quoted them
|
||||
in a conclusion, and the take-5 baseline README already excluded them. They
|
||||
are now **removed from the harness**, and a new `execute` phase measures the
|
||||
commands for real: `workspace/executeCommand`, the server's
|
||||
`workspace/applyEdit` captured and timed, then declined with
|
||||
`applied: false` so the corpus is never written. First readings on
|
||||
opentitan at 0.50.0: `lucisv.extractModule` at `aes.sv` 220:0–222:53 costs
|
||||
**257 / 245–247 ms** and pushes 2 edits across 2 files plus **1 created
|
||||
file**; `lucisv.inlineModule` at `aes_wrap.sv` 66:2 is **refused**
|
||||
(a `generate` construct) in 6 ms; and the *extract* offer at that same
|
||||
cursor spends **793–817 ms** to produce a refusal — a second ~800 ms
|
||||
user-command path beside §49's tail rename, filed for take 5's P1/P2.
|
||||
|
||||
Also fixed: `sweep.sh` deleted the scratch formatter cache once before three
|
||||
"cold" tries, so tries 2 and 3 read what try 1 wrote. It now deletes it before
|
||||
**each** cold try and primes warm cells with one untimed run, and
|
||||
`sweeptable.py` prints the `N files from cache` each try reported. Verified on
|
||||
`hw/ip` at 0.50.0: cold `0 / 0 / 0`, warm `30 / 30 / 30`. **Take 4's §7 cold
|
||||
sweep numbers were measured with the old behaviour** and should be read as
|
||||
"one cold try plus two warm ones", not as three cold tries.
|
||||
|
||||
Every new row is schema 2 — version, units, status, result count, client
|
||||
capability shape, fresh-process flag, edit fingerprint — and **no document may
|
||||
quote a row whose `status` is not `ok` or `capture`**. `tools/perf/README.md`
|
||||
has the full vocabulary; the reference measurements are in
|
||||
`docs/perf/take5-tracking.md`.
|
||||
|
||||
### 2026-09-08 — take 5, the implementation round (TODO §60)
|
||||
|
||||
The owner's plan (`docs/performance_take5.md`, tracker
|
||||
`docs/perf/take5-tracking.md`, baseline evidence `docs/perf/take5-baseline/`)
|
||||
implemented in seven lanes, each dev → QA → lead, each measured by the
|
||||
committed harness against the §P0 reference on the unchanged 0.50.0 binary.
|
||||
Feature READMEs: `docs/features/perf5-p{0,1,2,3,4}/`. Every number below is a
|
||||
repeat median on opentitan `0098135264`, M1 Max, paired against that
|
||||
reference; the tracker holds the raw rows and the per-stage experiments.
|
||||
|
||||
| what | reference (0.50.0) | after | lane |
|
||||
|---|---:|---:|---|
|
||||
| `codeAction` on a no-offer comment, 42 192-line file | 310 ms | **24 ms** | P1a/b — lint/config/fence gated by the requested kinds; the fence answer asked only when a fix exists and memoized per `Document`; the four offer selectors read the document's own parse; a parse counter proves a repeated offer parses nothing |
|
||||
| definition queued behind that comment | 309 ms | **25 ms** | same |
|
||||
| `codeAction` at `aes_reg_top` (ports family) | 22 ms | **5.5 ms** | P1c — offer predicates: the lightbulb from the plan-time checks, the click still recomputes and verifies |
|
||||
| `codeAction` at `aes`; organize-imports offer | 8 / 15 ms | **1.7 / 4.9 ms** | P1c |
|
||||
| tail rename (`state_q`, 238 files) | 780 ms | **388 ms (2.01×)** | P2 — one parse + analysis per file (`FileFacts::analyzed`), the after-index absorbed from the edited files' records, every verifier check unchanged and re-attacked; the `warnings` stage lexes each file once |
|
||||
| ordinary `aes` rename (9 files) | 141 ms | **92 ms** | P2 |
|
||||
| extract-module command | 246 ms | **149 ms** | P2 (collateral) |
|
||||
| CLI `check --select error,warning,style`, hw/ip: the `unused-import` increment | 142 ms | **5 ms** | P3 — one parse in the census, an AST gate sparing the nine files in ten that declare no package |
|
||||
| warm workspace start, settled | 1 330 ms | **~1 040–1 100 ms** | P4b — no empty default-scope scan (startup staged behind the configuration answer, 2 s bound), the store not rewritten when unchanged, opened at the first step that needs it, the corpus read a file at a time |
|
||||
| warm idle RSS | 570 MiB | **~423–480 MiB** | P4b |
|
||||
| first useful answer after opening a file, warm | 208 ms *or* 1.1 s (a race) | **~275 ms, correct, every session** | P4b — open buffers' folders at the head of the work list; a held opening request answered once that head is published |
|
||||
|
||||
**Filed, not fixed (TODO's loop-3 list):** the lint-result memo for the
|
||||
code-action path (24 ms per cursor move on the largest file); the
|
||||
target-scoped rename selector (P2d's census proved the 133 "unrelated"
|
||||
selected files are the container files a hierarchical tail folds through —
|
||||
no narrowing without a whole-scope oracle); the CLI's third parse; the
|
||||
first-answer gap to the old race's best case (the workspace walk in front
|
||||
of the open folder, 158 ms warm — `walk::collect_files` could hand on the
|
||||
metadata it already stat'd); the store's second open (reuse across rescans
|
||||
refused: it guards a mid-session cache-path change and a second session's
|
||||
compaction).
|
||||
|
||||
**Contracts amended, all recorded in `docs/topo.md`:** the parsed-input
|
||||
selectors and `vlog_parser::stats`; `FileFacts::analyzed` and the absorbed
|
||||
after-index; handshake 33 closed by an opt-in word-census rung (stronger
|
||||
than the transitive walk the row asked for); `package_exports_in`; the
|
||||
parsed `timing:` lines; the staged startup, the per-step read, the
|
||||
`staging`/`head_owed` wait clauses, the compaction skip; `state.rs` split
|
||||
into `state/`. Nothing in `check/`'s comparisons, `fence.rs`, or
|
||||
`verify.rs` changed.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Take 5 baseline evidence — 0.50.0, bbdbfe9
|
||||
|
||||
Read [the analysis and plan](../../performance_take5.md) and [implementation tracker](../take5-tracking.md). These are measured inputs to future implementation; no optimization is included.
|
||||
|
||||
| File | Meaning |
|
||||
|---|---|
|
||||
| `metadata.json` | Commits, binary and modified corpus hashes, environment, limitations |
|
||||
| `results.jsonl` | Standard LSP rows; ordinary `ms` arrays are first + repeats except scan/didOpen and RSS |
|
||||
| `runs.jsonl` | Standard-phase commands, before/after load, exit status and corpus checks |
|
||||
| `offer-breakdown.jsonl` | Filtered action requests/counts; `offer-queue.ms` is leader/follower milliseconds |
|
||||
| `cli-results.jsonl` | Paired CLI times, commands, exit status, summaries, stdout hashes, peak RSS bytes |
|
||||
|
||||
The original `rss` rows use `ms` for **KiB of idle RSS**, and `n` for **KiB of allocated store size**. Do not treat them as latency or peak memory. CLI formatter exit 2 reflects four existing failures; lint exit 1 reflects findings. Tiny extract/inline `resolve` rows are invalid measures of command execution and excluded from conclusions.
|
||||
|
||||
Standard phases ran sequentially under `tools/guard.sh -m 8 -t 1800`, using commands in `runs.jsonl`. Baseline cache warm-up preceded code-action sessions. `scan` resets cold caches; its initial default-scope scan can populate entries before the final workspace scan. No Cargo command ran during retained timing sessions. Source was not modified. CLI raw logs remain in `/tmp/lucisv-perf5-20260907`; summaries and stdout hashes survive here.
|
||||
|
||||
## Reproduce
|
||||
|
||||
Run a guarded release build first. After all builds stop, run the phase command in `runs.jsonl`, replacing its output, label and storage with a new scratch run. Reference and candidate need separate, identically primed caches. Record exact binary/source/corpus hashes. Check corpus status and hashes before/after each phase.
|
||||
|
||||
## Supplemental read-only probes
|
||||
|
||||
These scripts ran from scratch, not as changes to the production harness. Save each block to a scratch `.py` file and update the explicit paths, labels and output names. Run the offer probe under `tools/guard.sh -m 8 -t 1800`; the CLI probe guards each child internally. Do not run either concurrently with another benchmark or a build. Returned edits are discarded.
|
||||
|
||||
### Action-family attribution
|
||||
|
||||
```python
|
||||
import sys, argparse, copy, json, os
|
||||
sys.path.insert(0,'/Users/guoliangchen/repo/verilogrustformatter/tools/perf')
|
||||
import harness as h, sites
|
||||
h.configure(argparse.Namespace(server='/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server',label='0.50.0-bbdbfe9',opentitan='/Users/guoliangchen/repo/opentitan',storage='/tmp/lucisv-perf5-20260907/caches',out='/tmp/lucisv-perf5-20260907/offer-breakdown.jsonl',tries=3))
|
||||
shapes=[('tb-comment',sites.TB,'// ',2),('aes-reg-instance',sites.AES,'aes_reg_top u_reg (',0),('aes-core-comment',sites.AES_CORE,'// ',2),('spi-comment',sites.SPI_DEVICE,'// ',2),('pinmux-comment',sites.PINMUX_REG_TOP,'// ',2)]
|
||||
for label,relative,needle,offset in shapes:
|
||||
with h.session('workspace') as s:
|
||||
h.settled(s)
|
||||
s.did_open(sites.path(relative)); s.wait_quiet(.6); s.take_notifications()
|
||||
p=h.code_action_params(relative,needle,offset=offset)
|
||||
for kind in [None,[],['quickfix'],['refactor.extract'],['refactor.inline'],['refactor.rewrite.lucisv.ports'],['source.organizeImports']]:
|
||||
params=copy.deepcopy(p)
|
||||
if kind is not None: params['context']['only']=kind
|
||||
elapsed=[]; answer=None
|
||||
for i in range(4):
|
||||
ms,answer=s.request('textDocument/codeAction',params)
|
||||
if 'error' in answer: raise RuntimeError(answer)
|
||||
elapsed.append(ms)
|
||||
h.record(phase='offer-breakdown',row=label+' '+str(kind),ms=elapsed,n=len(answer.get('result') or []),file=relative,position=p['range']['start'],load=os.getloadavg())
|
||||
if label=='pinmux-comment':
|
||||
for i in range(3):
|
||||
leader=s.send('textDocument/codeAction',p)
|
||||
follower=s.send('textDocument/definition',h.at(sites.TB,' aes #(',offset=2))
|
||||
lm,lr=s.await_id(leader); fm,fr=s.await_id(follower)
|
||||
h.record(phase='offer-queue',row='pinmux comment -> aes definition',ms=[lm,fm],note='leader/follower ms, not repeats')
|
||||
```
|
||||
|
||||
### Paired CLI and independently cold formatting
|
||||
|
||||
```python
|
||||
import subprocess, pathlib, os, time, json, re, shutil, hashlib
|
||||
root=pathlib.Path('/Users/guoliangchen/repo/verilogrustformatter')
|
||||
out=pathlib.Path('/tmp/lucisv-perf5-20260907'); corpus='/Users/guoliangchen/repo/opentitan'
|
||||
tree=corpus+'/hw/ip'
|
||||
binaries={'0.50.0':str(root/'target/release/lucisv'),'0.49.0':'/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0','0.43.0':'/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.43.0'}
|
||||
initial=subprocess.check_output(['git','-C',corpus,'status','--porcelain'],text=True)
|
||||
def run(label,kind,trial,args):
|
||||
cmd=[str(root/'tools/guard.sh'),'-m','8','-t','1800','--','/usr/bin/time','-l',binaries[label]]+args+[tree]
|
||||
load=os.getloadavg()
|
||||
r=subprocess.run(cmd,cwd=root,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
log=r.stdout+r.stderr
|
||||
(out/f'cli-{label}-{kind}-{trial}.log').write_bytes(log)
|
||||
err=r.stderr.decode(errors='replace')
|
||||
timing=re.search(r'([\d.]+) real\s+([\d.]+) user\s+([\d.]+) sys',err)
|
||||
rss=re.search(r'(\d+)\s+maximum resident set size',err)
|
||||
summary=[x for x in log.decode(errors='replace').splitlines() if re.search(r'files? (checked|already|would|from)|violations? in|failed to format|files?,',x)]
|
||||
record=dict(label=label,row=kind,trial=trial,command=cmd,exit=r.returncode,wall_s=float(timing[1]) if timing else None,user_s=float(timing[2]) if timing else None,sys_s=float(timing[3]) if timing else None,peak_rss_bytes=int(rss[1]) if rss else None,summary=summary[-4:],stdout_sha256=hashlib.sha256(r.stdout).hexdigest(),load_before=load,load_after=os.getloadavg(),corpus_unchanged=initial==subprocess.check_output(['git','-C',corpus,'status','--porcelain'],text=True))
|
||||
with (out/'cli-results.jsonl').open('a') as f:f.write(json.dumps(record)+'\n')
|
||||
print(label,kind,trial,record['wall_s'],record['summary'],flush=True)
|
||||
if r.returncode not in (0,1,2) or not record['corpus_unchanged'] or not timing: raise RuntimeError(record)
|
||||
for trial in range(1,4):
|
||||
for label in (list(binaries) if trial%2 else list(reversed(binaries))):
|
||||
for kind,args in [('default',['check']),('style',['check','--select','error,warning,style']),('style-no-unused-import',['check','--select','error,warning,style','--ignore','unused-import'])]:
|
||||
if label=='0.43.0' and kind=='style-no-unused-import':continue
|
||||
run(label,kind,trial,args)
|
||||
cache=out/'cli-format-cache'
|
||||
shutil.rmtree(cache,ignore_errors=True)
|
||||
for warmth in ['cold','warm']:
|
||||
run('0.50.0','format-'+warmth,trial,['format','--check','--cache-dir',str(cache)])
|
||||
```
|
||||
|
||||
The CLI probe's summary matcher missed `found N violations`; these summary fields were filled from the saved raw logs afterward. Timings, exit codes, hashes and memory figures are unmodified.
|
||||
@@ -0,0 +1,30 @@
|
||||
{"label": "0.50.0", "row": "default", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.59, "user_s": 2.29, "sys_s": 0.27, "peak_rss_bytes": 196067328, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.71826171875, 3.9404296875, 3.4326171875], "load_after": [4.71826171875, 3.9404296875, 3.4326171875], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "style", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.58, "user_s": 3.59, "sys_s": 0.26, "peak_rss_bytes": 218562560, "summary": ["found 7751 violations"], "stdout_sha256": "97201de03bca32fab4761b49902c0bef48fd159c3f4baca625f37446061a1155", "load_before": [4.71826171875, 3.9404296875, 3.4326171875], "load_after": [4.71826171875, 3.9404296875, 3.4326171875], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "style-no-unused-import", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "--select", "error,warning,style", "--ignore", "unused-import", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.44, "user_s": 2.38, "sys_s": 0.24, "peak_rss_bytes": 181452800, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.71826171875, 3.9404296875, 3.4326171875], "load_after": [4.34033203125, 3.875, 3.412109375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "default", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.39, "user_s": 2.32, "sys_s": 0.24, "peak_rss_bytes": 169066496, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.34033203125, 3.875, 3.412109375], "load_after": [4.34033203125, 3.875, 3.412109375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "style", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.57, "user_s": 3.53, "sys_s": 0.28, "peak_rss_bytes": 235339776, "summary": ["found 7751 violations"], "stdout_sha256": "97201de03bca32fab4761b49902c0bef48fd159c3f4baca625f37446061a1155", "load_before": [4.34033203125, 3.875, 3.412109375], "load_after": [4.34033203125, 3.875, 3.412109375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "style-no-unused-import", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "--select", "error,warning,style", "--ignore", "unused-import", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.45, "user_s": 2.46, "sys_s": 0.24, "peak_rss_bytes": 194560000, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.34033203125, 3.875, 3.412109375], "load_after": [4.34033203125, 3.875, 3.412109375], "corpus_unchanged": true}
|
||||
{"label": "0.43.0", "row": "default", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.43.0", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.42, "user_s": 2.36, "sys_s": 0.24, "peak_rss_bytes": 176521216, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.34033203125, 3.875, 3.412109375], "load_after": [4.15283203125, 3.84375, 3.40380859375], "corpus_unchanged": true}
|
||||
{"label": "0.43.0", "row": "style", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.43.0", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.46, "user_s": 2.55, "sys_s": 0.25, "peak_rss_bytes": 194232320, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.15283203125, 3.84375, 3.40380859375], "load_after": [4.15283203125, 3.84375, 3.40380859375], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "format-cold", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "format", "--check", "--cache-dir", "/tmp/lucisv-perf5-20260907/cli-format-cache", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 2, "wall_s": 0.67, "user_s": 3.87, "sys_s": 0.19, "peak_rss_bytes": 212008960, "summary": ["1772 files would be reformatted, 30 files left unchanged, 4 files failed to format"], "stdout_sha256": "fdae6259fca3340f190d63b1625a968d7186a76653d2a5d7f8c25ca489e9d878", "load_before": [4.15283203125, 3.84375, 3.40380859375], "load_after": [4.15283203125, 3.84375, 3.40380859375], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "format-warm", "trial": 1, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "format", "--check", "--cache-dir", "/tmp/lucisv-perf5-20260907/cli-format-cache", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 2, "wall_s": 0.69, "user_s": 3.96, "sys_s": 0.2, "peak_rss_bytes": 210747392, "summary": ["1772 files would be reformatted, 30 files left unchanged, 30 files from cache, 4 files failed to format"], "stdout_sha256": "fdae6259fca3340f190d63b1625a968d7186a76653d2a5d7f8c25ca489e9d878", "load_before": [4.15283203125, 3.84375, 3.40380859375], "load_after": [4.15283203125, 3.84375, 3.40380859375], "corpus_unchanged": true}
|
||||
{"label": "0.43.0", "row": "default", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.43.0", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.4, "user_s": 2.4, "sys_s": 0.24, "peak_rss_bytes": 172195840, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.15283203125, 3.84375, 3.40380859375], "load_after": [4.22021484375, 3.86279296875, 3.4130859375], "corpus_unchanged": true}
|
||||
{"label": "0.43.0", "row": "style", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.43.0", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.46, "user_s": 2.51, "sys_s": 0.24, "peak_rss_bytes": 185712640, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.22021484375, 3.86279296875, 3.4130859375], "load_after": [4.22021484375, 3.86279296875, 3.4130859375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "default", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.38, "user_s": 2.27, "sys_s": 0.24, "peak_rss_bytes": 177340416, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.22021484375, 3.86279296875, 3.4130859375], "load_after": [4.22021484375, 3.86279296875, 3.4130859375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "style", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.58, "user_s": 3.57, "sys_s": 0.26, "peak_rss_bytes": 202326016, "summary": ["found 7751 violations"], "stdout_sha256": "97201de03bca32fab4761b49902c0bef48fd159c3f4baca625f37446061a1155", "load_before": [4.22021484375, 3.86279296875, 3.4130859375], "load_after": [4.22021484375, 3.86279296875, 3.4130859375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "style-no-unused-import", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "--select", "error,warning,style", "--ignore", "unused-import", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.45, "user_s": 2.42, "sys_s": 0.24, "peak_rss_bytes": 183205888, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.22021484375, 3.86279296875, 3.4130859375], "load_after": [4.1220703125, 3.84814453125, 3.41064453125], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "default", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.4, "user_s": 2.29, "sys_s": 0.23, "peak_rss_bytes": 161054720, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.1220703125, 3.84814453125, 3.41064453125], "load_after": [4.1220703125, 3.84814453125, 3.41064453125], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "style", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.58, "user_s": 3.56, "sys_s": 0.27, "peak_rss_bytes": 210288640, "summary": ["found 7751 violations"], "stdout_sha256": "97201de03bca32fab4761b49902c0bef48fd159c3f4baca625f37446061a1155", "load_before": [4.1220703125, 3.84814453125, 3.41064453125], "load_after": [4.1220703125, 3.84814453125, 3.41064453125], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "style-no-unused-import", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "--select", "error,warning,style", "--ignore", "unused-import", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.47, "user_s": 2.45, "sys_s": 0.24, "peak_rss_bytes": 181174272, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.1220703125, 3.84814453125, 3.41064453125], "load_after": [4.1220703125, 3.84814453125, 3.41064453125], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "format-cold", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "format", "--check", "--cache-dir", "/tmp/lucisv-perf5-20260907/cli-format-cache", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 2, "wall_s": 0.59, "user_s": 4.0, "sys_s": 0.23, "peak_rss_bytes": 207667200, "summary": ["1772 files would be reformatted, 30 files left unchanged, 4 files failed to format"], "stdout_sha256": "fdae6259fca3340f190d63b1625a968d7186a76653d2a5d7f8c25ca489e9d878", "load_before": [4.1220703125, 3.84814453125, 3.41064453125], "load_after": [4.11181640625, 3.8505859375, 3.4140625], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "format-warm", "trial": 2, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "format", "--check", "--cache-dir", "/tmp/lucisv-perf5-20260907/cli-format-cache", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 2, "wall_s": 0.63, "user_s": 3.86, "sys_s": 0.2, "peak_rss_bytes": 216088576, "summary": ["1772 files would be reformatted, 30 files left unchanged, 30 files from cache, 4 files failed to format"], "stdout_sha256": "fdae6259fca3340f190d63b1625a968d7186a76653d2a5d7f8c25ca489e9d878", "load_before": [4.11181640625, 3.8505859375, 3.4140625], "load_after": [4.11181640625, 3.8505859375, 3.4140625], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "default", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.4, "user_s": 2.32, "sys_s": 0.25, "peak_rss_bytes": 167739392, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.11181640625, 3.8505859375, 3.4140625], "load_after": [4.11181640625, 3.8505859375, 3.4140625], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "style", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.56, "user_s": 3.52, "sys_s": 0.27, "peak_rss_bytes": 204865536, "summary": ["found 7751 violations"], "stdout_sha256": "97201de03bca32fab4761b49902c0bef48fd159c3f4baca625f37446061a1155", "load_before": [4.11181640625, 3.8505859375, 3.4140625], "load_after": [4.11181640625, 3.8505859375, 3.4140625], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "style-no-unused-import", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "check", "--select", "error,warning,style", "--ignore", "unused-import", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.44, "user_s": 2.39, "sys_s": 0.24, "peak_rss_bytes": 186073088, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.11181640625, 3.8505859375, 3.4140625], "load_after": [4.3427734375, 3.90283203125, 3.43505859375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "default", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.38, "user_s": 2.28, "sys_s": 0.24, "peak_rss_bytes": 175341568, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.3427734375, 3.90283203125, 3.43505859375], "load_after": [4.3427734375, 3.90283203125, 3.43505859375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "style", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.59, "user_s": 3.48, "sys_s": 0.27, "peak_rss_bytes": 210550784, "summary": ["found 7751 violations"], "stdout_sha256": "97201de03bca32fab4761b49902c0bef48fd159c3f4baca625f37446061a1155", "load_before": [4.3427734375, 3.90283203125, 3.43505859375], "load_after": [4.3427734375, 3.90283203125, 3.43505859375], "corpus_unchanged": true}
|
||||
{"label": "0.49.0", "row": "style-no-unused-import", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0", "check", "--select", "error,warning,style", "--ignore", "unused-import", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.48, "user_s": 2.46, "sys_s": 0.24, "peak_rss_bytes": 190054400, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.3427734375, 3.90283203125, 3.43505859375], "load_after": [4.3427734375, 3.90283203125, 3.43505859375], "corpus_unchanged": true}
|
||||
{"label": "0.43.0", "row": "default", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.43.0", "check", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.39, "user_s": 2.34, "sys_s": 0.24, "peak_rss_bytes": 176586752, "summary": ["found 445 violations"], "stdout_sha256": "c2444712e23ea59224972b977a2ad55cae0ad7520ecd71923e13e5d1d28c74a5", "load_before": [4.3427734375, 3.90283203125, 3.43505859375], "load_after": [4.3427734375, 3.90283203125, 3.43505859375], "corpus_unchanged": true}
|
||||
{"label": "0.43.0", "row": "style", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.43.0", "check", "--select", "error,warning,style", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 1, "wall_s": 0.45, "user_s": 2.48, "sys_s": 0.24, "peak_rss_bytes": 182517760, "summary": ["found 7734 violations"], "stdout_sha256": "58780c3e81b897b4104cecd17ca72c69b45a1a14375396d9c21b6fcea3b7bb3f", "load_before": [4.15478515625, 3.87109375, 3.42626953125], "load_after": [4.15478515625, 3.87109375, 3.42626953125], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "format-cold", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "format", "--check", "--cache-dir", "/tmp/lucisv-perf5-20260907/cli-format-cache", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 2, "wall_s": 0.68, "user_s": 3.98, "sys_s": 0.22, "peak_rss_bytes": 173998080, "summary": ["1772 files would be reformatted, 30 files left unchanged, 4 files failed to format"], "stdout_sha256": "fdae6259fca3340f190d63b1625a968d7186a76653d2a5d7f8c25ca489e9d878", "load_before": [4.15478515625, 3.87109375, 3.42626953125], "load_after": [4.15478515625, 3.87109375, 3.42626953125], "corpus_unchanged": true}
|
||||
{"label": "0.50.0", "row": "format-warm", "trial": 3, "command": ["/Users/guoliangchen/repo/verilogrustformatter/tools/guard.sh", "-m", "8", "-t", "1800", "--", "/usr/bin/time", "-l", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv", "format", "--check", "--cache-dir", "/tmp/lucisv-perf5-20260907/cli-format-cache", "/Users/guoliangchen/repo/opentitan/hw/ip"], "exit": 2, "wall_s": 0.61, "user_s": 4.01, "sys_s": 0.2, "peak_rss_bytes": 219955200, "summary": ["1772 files would be reformatted, 30 files left unchanged, 30 files from cache, 4 files failed to format"], "stdout_sha256": "fdae6259fca3340f190d63b1625a968d7186a76653d2a5d7f8c25ca489e9d878", "load_before": [4.15478515625, 3.87109375, 3.42626953125], "load_after": [4.15478515625, 3.87109375, 3.42626953125], "corpus_unchanged": true}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"date": "2026-09-07",
|
||||
"timezone": "America/Chicago",
|
||||
"head": "bbdbfe9045e8a85f8ea471529ea739af6cade77f",
|
||||
"scope": "Latest local HEAD; remote was not fetched or changed",
|
||||
"version": "0.50.0",
|
||||
"host": "Darwin Lu-MacbookPro16-90803.local 27.0.0 Darwin Kernel Version 27.0.0: Tue Aug 11 22:18:52 PDT 2026; root:xnu-13432.1.9~3/RELEASE_ARM64_T6000 arm64",
|
||||
"os": "ProductName:\t\tmacOS\nProductVersion:\t\t27.0\nBuildVersion:\t\t26A5425a",
|
||||
"python": "3.14.7",
|
||||
"rust": "rustc 1.97.1 (8bab26f4f 2026-07-14) (Homebrew)",
|
||||
"cpu": "Apple M1 Max, 10 cores, 64 GB per prior machine record; same Darwin T6000 host",
|
||||
"corpus": "/Users/guoliangchen/repo/opentitan",
|
||||
"corpus_head": "00981352642fb65ef2b6c47143a0f6bb31fd4a97",
|
||||
"corpus_status": "M hw/ip/aes/dv/tb/tb.sv\n M hw/top_darjeeling/ip/ast/rtl/ast.sv\n M hw/top_earlgrey/ip/ast/rtl/ast.sv",
|
||||
"corpus_modified_sha256": {
|
||||
"hw/ip/aes/dv/tb/tb.sv": "09ae059220caa7667bb22acdd3157647b55d36de96ff2ca55a801bbbcd08146e",
|
||||
"hw/top_darjeeling/ip/ast/rtl/ast.sv": "2b63f9d7bc0068388e47a80383eaf048183cf5868b1cfd4692eac325393d2803",
|
||||
"hw/top_earlgrey/ip/ast/rtl/ast.sv": "15efd90c99030c6a43486ef1ed622897b967ad5153697d6b2c2c21cfb6eba35f"
|
||||
},
|
||||
"binaries": {
|
||||
"/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv": "894054128495b764bb966e7b923e08267e57aea83fdc611fad4b4ed7a66b51e3",
|
||||
"/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server": "27e0a0df5b77102ec79c23279da64e722bffd440c604ad6d03ff66c2f6398ad3",
|
||||
"/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.49.0": "0c943c4ccce484b9e5860726cdc46e584b4050d527f9845d20a87ea5eabd679c",
|
||||
"/Users/guoliangchen/.cache/lucisv-baselines/lucisv-0.43.0": "89379a12b2ac9bfe32e58b7555f7b75910f8c375e79f8b6b6322a1082842cb81"
|
||||
},
|
||||
"build": "cargo build --release --locked -p lucisv -p lucisv_server: optimized artifacts up to date, completed in 0.04 s before timed runs",
|
||||
"guard": "8 GiB / 1800 seconds. Initial sandbox attempt could not inspect ps; discarded and rerun outside sandbox with functioning guard. No guard kill in retained measurements.",
|
||||
"scratch": "/tmp/lucisv-perf5-20260907",
|
||||
"limitations": [
|
||||
"Historical LSP comparison, not paired old/new servers: no server/parser/refactor/semantic implementation change from 0.49.0 to HEAD.",
|
||||
"No current parser stage or allocation profile.",
|
||||
"CLI scope limited to hw/ip.",
|
||||
"CLI summary fields enriched from raw logs after collection.",
|
||||
"RSS phase ms values are KiB; n is du -sk KiB. Offer-queue ms holds leader/follower, not repeat trials."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{"phase": "offer-breakdown", "row": "tb-comment None", "ms": [2.648791007231921, 2.2900830081198364, 1.8117910076398402, 1.8046250042971224], "n": 0, "file": "hw/ip/aes/dv/tb/tb.sv", "position": {"line": 0, "character": 2}, "load": [5.73681640625, 3.9775390625, 3.423828125], "ts": "2026-09-07T13:25:31", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "tb-comment []", "ms": [0.9796250087674707, 0.8315420127473772, 0.6832090148236603, 0.6103749910835177], "n": 0, "file": "hw/ip/aes/dv/tb/tb.sv", "position": {"line": 0, "character": 2}, "load": [5.73681640625, 3.9775390625, 3.423828125], "ts": "2026-09-07T13:25:31", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "tb-comment ['quickfix']", "ms": [0.5991249927319586, 0.5691249971278012, 0.6025840120855719, 0.5445409915409982], "n": 0, "file": "hw/ip/aes/dv/tb/tb.sv", "position": {"line": 0, "character": 2}, "load": [5.73681640625, 3.9775390625, 3.423828125], "ts": "2026-09-07T13:25:31", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "tb-comment ['refactor.extract']", "ms": [0.7646669982932508, 0.7779170118737966, 0.8403339888900518, 0.7558340148534626], "n": 0, "file": "hw/ip/aes/dv/tb/tb.sv", "position": {"line": 0, "character": 2}, "load": [5.73681640625, 3.9775390625, 3.423828125], "ts": "2026-09-07T13:25:31", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "tb-comment ['refactor.inline']", "ms": [0.7875830051489174, 0.6747919833287597, 0.6393749790731817, 0.6757920200470835], "n": 0, "file": "hw/ip/aes/dv/tb/tb.sv", "position": {"line": 0, "character": 2}, "load": [5.73681640625, 3.9775390625, 3.423828125], "ts": "2026-09-07T13:25:31", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "tb-comment ['refactor.rewrite.lucisv.ports']", "ms": [0.6737090006936342, 0.6455419934354722, 0.6391670031007379, 0.6369579932652414], "n": 0, "file": "hw/ip/aes/dv/tb/tb.sv", "position": {"line": 0, "character": 2}, "load": [5.73681640625, 3.9775390625, 3.423828125], "ts": "2026-09-07T13:25:31", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "tb-comment ['source.organizeImports']", "ms": [0.760875002015382, 0.6679169891867787, 0.697499985108152, 0.6661249790340662], "n": 0, "file": "hw/ip/aes/dv/tb/tb.sv", "position": {"line": 0, "character": 2}, "load": [5.73681640625, 3.9775390625, 3.423828125], "ts": "2026-09-07T13:25:31", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-reg-instance None", "ms": [45.05770799005404, 27.542458003154024, 23.231625003973022, 23.235833999933675], "n": 2, "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 103, "character": 2}, "load": [5.7578125, 4.0107421875, 3.4384765625], "ts": "2026-09-07T13:25:35", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-reg-instance []", "ms": [0.8259169990196824, 0.7039159827399999, 0.625124986981973, 0.6082919717300683], "n": 0, "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 103, "character": 2}, "load": [5.7578125, 4.0107421875, 3.4384765625], "ts": "2026-09-07T13:25:35", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-reg-instance ['quickfix']", "ms": [0.6680410006083548, 0.604875007411465, 0.565416004974395, 0.6020829896442592], "n": 0, "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 103, "character": 2}, "load": [5.7578125, 4.0107421875, 3.4384765625], "ts": "2026-09-07T13:25:35", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-reg-instance ['refactor.extract']", "ms": [0.94358398928307, 0.9263330139219761, 0.937166012590751, 0.9886669868137687], "n": 1, "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 103, "character": 2}, "load": [5.7578125, 4.0107421875, 3.4384765625], "ts": "2026-09-07T13:25:35", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-reg-instance ['refactor.inline']", "ms": [0.9807079914025962, 1.1194589897058904, 1.0102500091306865, 0.9386250167153776], "n": 1, "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 103, "character": 2}, "load": [5.7578125, 4.0107421875, 3.4384765625], "ts": "2026-09-07T13:25:35", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-reg-instance ['refactor.rewrite.lucisv.ports']", "ms": [21.715665992815048, 21.75687497947365, 21.776000008685514, 21.546458010561764], "n": 0, "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 103, "character": 2}, "load": [5.7578125, 4.0107421875, 3.4384765625], "ts": "2026-09-07T13:25:35", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-reg-instance ['source.organizeImports']", "ms": [0.9921250166371465, 0.9192089783027768, 1.217999990331009, 1.0944170062430203], "n": 0, "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 103, "character": 2}, "load": [5.7578125, 4.0107421875, 3.4384765625], "ts": "2026-09-07T13:25:35", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-core-comment None", "ms": [13.355999981286004, 11.663167009828612, 9.634458983782679, 9.57550000748597], "n": 0, "file": "hw/ip/aes/rtl/aes_core.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:39", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-core-comment []", "ms": [2.8610829904209822, 2.7658749895635992, 2.8542499931063503, 2.7579169836826622], "n": 0, "file": "hw/ip/aes/rtl/aes_core.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:39", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-core-comment ['quickfix']", "ms": [2.780665992759168, 2.753000007942319, 2.9289159865584224, 3.0069169879425317], "n": 0, "file": "hw/ip/aes/rtl/aes_core.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:39", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-core-comment ['refactor.extract']", "ms": [4.185750003671274, 4.111249989364296, 4.002999980002642, 3.9353749889414757], "n": 0, "file": "hw/ip/aes/rtl/aes_core.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:39", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-core-comment ['refactor.inline']", "ms": [3.9425829891115427, 3.880875010509044, 3.857290983432904, 3.8027080008760095], "n": 0, "file": "hw/ip/aes/rtl/aes_core.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:39", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-core-comment ['refactor.rewrite.lucisv.ports']", "ms": [3.784583997912705, 3.891624975949526, 4.187083017313853, 4.086291999556124], "n": 0, "file": "hw/ip/aes/rtl/aes_core.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:39", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "aes-core-comment ['source.organizeImports']", "ms": [3.9099999994505197, 4.066166002303362, 3.8036660116631538, 3.745458001503721], "n": 0, "file": "hw/ip/aes/rtl/aes_core.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:39", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "spi-comment None", "ms": [22.180458006914705, 17.068457993445918, 14.433125004870817, 13.315542018972337], "n": 0, "file": "hw/ip/spi_device/rtl/spi_device.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "spi-comment []", "ms": [3.7312920030672103, 3.6733750021085143, 3.6644999927375466, 3.7191250012256205], "n": 0, "file": "hw/ip/spi_device/rtl/spi_device.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "spi-comment ['quickfix']", "ms": [3.7071249971631914, 3.6136249836999923, 3.4558750048745424, 3.556207986548543], "n": 0, "file": "hw/ip/spi_device/rtl/spi_device.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "spi-comment ['refactor.extract']", "ms": [6.052584009012207, 6.4273330208379775, 6.2445410003419966, 6.224374985322356], "n": 0, "file": "hw/ip/spi_device/rtl/spi_device.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "spi-comment ['refactor.inline']", "ms": [6.242041999939829, 5.9042499924544245, 5.9013749996665865, 5.964167008642107], "n": 0, "file": "hw/ip/spi_device/rtl/spi_device.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "spi-comment ['refactor.rewrite.lucisv.ports']", "ms": [5.973499995889142, 5.905041005462408, 6.065875000786036, 6.319167005131021], "n": 0, "file": "hw/ip/spi_device/rtl/spi_device.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "spi-comment ['source.organizeImports']", "ms": [5.9690419875551015, 5.963416013401002, 6.0141249850858, 5.686499993316829], "n": 0, "file": "hw/ip/spi_device/rtl/spi_device.sv", "position": {"line": 0, "character": 2}, "load": [5.77685546875, 4.04345703125, 3.453125], "ts": "2026-09-07T13:25:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "pinmux-comment None", "ms": [328.4064580220729, 311.72558400430717, 296.77983300643973, 297.5447910139337], "n": 0, "file": "hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv", "position": {"line": 0, "character": 2}, "load": [5.47412109375, 4.00927734375, 3.4443359375], "ts": "2026-09-07T13:25:47", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "pinmux-comment []", "ms": [78.88008299050853, 81.43758299411274, 81.61875000223517, 79.42966697737575], "n": 0, "file": "hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv", "position": {"line": 0, "character": 2}, "load": [5.59619140625, 4.05859375, 3.46484375], "ts": "2026-09-07T13:25:48", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "pinmux-comment ['quickfix']", "ms": [79.54375000554137, 80.05583399790339, 79.7456250002142, 79.73016699543223], "n": 0, "file": "hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv", "position": {"line": 0, "character": 2}, "load": [5.59619140625, 4.05859375, 3.46484375], "ts": "2026-09-07T13:25:48", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "pinmux-comment ['refactor.extract']", "ms": [135.2046249958221, 136.20779200573452, 134.648749983171, 135.7759169768542], "n": 0, "file": "hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv", "position": {"line": 0, "character": 2}, "load": [5.59619140625, 4.05859375, 3.46484375], "ts": "2026-09-07T13:25:49", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "pinmux-comment ['refactor.inline']", "ms": [135.50887498422526, 135.4450420185458, 134.94333298876882, 134.67495801160112], "n": 0, "file": "hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv", "position": {"line": 0, "character": 2}, "load": [5.59619140625, 4.05859375, 3.46484375], "ts": "2026-09-07T13:25:49", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "pinmux-comment ['refactor.rewrite.lucisv.ports']", "ms": [134.87987499684095, 135.46129100723192, 134.47804198949598, 134.0239580022171], "n": 0, "file": "hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv", "position": {"line": 0, "character": 2}, "load": [5.59619140625, 4.05859375, 3.46484375], "ts": "2026-09-07T13:25:50", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-breakdown", "row": "pinmux-comment ['source.organizeImports']", "ms": [135.49237500410527, 135.77187500777654, 134.63645800948143, 133.62404101644643], "n": 0, "file": "hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv", "position": {"line": 0, "character": 2}, "load": [5.59619140625, 4.05859375, 3.46484375], "ts": "2026-09-07T13:25:50", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-queue", "row": "pinmux comment -> aes definition", "ms": [304.2165410006419, 304.10845900769345], "note": "leader/follower ms, not repeats", "ts": "2026-09-07T13:25:50", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-queue", "row": "pinmux comment -> aes definition", "ms": [303.60495898639783, 303.5165830224287], "note": "leader/follower ms, not repeats", "ts": "2026-09-07T13:25:51", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "offer-queue", "row": "pinmux comment -> aes definition", "ms": [300.7473750039935, 300.6589169963263], "note": "leader/follower ms, not repeats", "ts": "2026-09-07T13:25:51", "label": "0.50.0-bbdbfe9"}
|
||||
@@ -0,0 +1,78 @@
|
||||
{"phase": "baseline", "row": "initialize", "ms": [0.3137500025331974], "ts": "2026-09-07T13:18:02", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "baseline", "row": "transport baseline ($/lucisvNoSuchMethod)", "ms": [0.24037499679252505, 0.07041700882837176, 0.0661670055706054, 0.07020801422186196], "ts": "2026-09-07T13:18:05", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "aes_reg_top (fan-out 1), lazy", "ms": [32.81066700583324, 25.08558300905861, 22.44966698344797, 23.075750010320917], "n": 2, "titles": ["lucisv: extract selection into module\u2026", "lucisv: inline `aes_reg_top` here"], "ts": "2026-09-07T13:18:09", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "aes (fan-out 6), lazy", "ms": [12.387124996166676, 9.11420799093321, 8.8751669973135, 8.147999993525445], "n": 1, "titles": ["lucisv: extract selection into module\u2026"], "ts": "2026-09-07T13:18:12", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "prim_lc_sync (fan-out 42), lazy", "ms": [11.492874997202307, 9.207416005665436, 8.418125013122335, 7.53191698458977], "n": 1, "titles": ["lucisv: extract selection into module\u2026"], "ts": "2026-09-07T13:18:15", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "prim_alert_sender (fan-out 67), lazy", "ms": [19.623000000137836, 13.507625000784174, 11.453832994448021, 9.889458015095443], "n": 1, "titles": ["lucisv: extract selection into module\u2026"], "ts": "2026-09-07T13:18:19", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "prim_flop_2sync (fan-out 128), lazy", "ms": [9.839999984251335, 12.11854099528864, 6.341750005958602, 8.040500018978491], "n": 2, "titles": ["lucisv: extract selection into module\u2026", "lucisv: inline `prim_flop_2sync` here"], "ts": "2026-09-07T13:18:22", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "comment line, lazy", "ms": [6.147667008917779, 3.4879590093623847, 3.500791994156316, 3.224957996280864], "n": 0, "ts": "2026-09-07T13:18:25", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "aes_reg_top (fan-out 1), eager", "ms": [37.59024999453686, 29.921082983491942, 25.70075000403449, 24.576958996476606], "n": 2, "titles": ["lucisv: extract selection into module\u2026", "lucisv: inline `aes_reg_top` here"], "ts": "2026-09-07T13:18:29", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "aes (fan-out 6), eager", "ms": [114.37258301884867, 93.29179098131135, 92.19895798014477, 92.72970800520852], "n": 1, "titles": ["lucisv: extract selection into module\u2026"], "ts": "2026-09-07T13:18:32", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "prim_lc_sync (fan-out 42), eager", "ms": [263.883417006582, 269.2695829900913, 256.4913750102278, 257.67983301193453], "n": 1, "titles": ["lucisv: extract selection into module\u2026"], "ts": "2026-09-07T13:18:37", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "prim_alert_sender (fan-out 67), eager", "ms": [412.31600000173785, 383.22150000021793, 384.81245798175223, 387.74637499591336], "n": 1, "titles": ["lucisv: extract selection into module\u2026"], "ts": "2026-09-07T13:18:43", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "prim_flop_2sync (fan-out 128), eager", "ms": [518.3152499957941, 499.6907910099253, 495.78858297900297, 495.6017090007663], "n": 2, "titles": ["lucisv: extract selection into module\u2026", "lucisv: inline `prim_flop_2sync` here"], "ts": "2026-09-07T13:18:49", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "codeaction", "row": "comment line, eager", "ms": [3.577374998712912, 3.116250009043142, 3.099291992839426, 4.0054169949144125], "n": 0, "ts": "2026-09-07T13:18:51", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "tailrename", "row": "tail rename cursor", "ms": [0.0], "note": "{\"line\": 41, \"character\": 19}", "file": "hw/ip/entropy_src/rtl/entropy_src_main_sm.sv", "ts": "2026-09-07T13:18:56", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "tailrename", "row": "rename state_q (tail through u_entropy_src_main_sm)", "ms": [821.5857500035781, 791.3062089937739, 789.496124983998, 809.834250016138], "n": 2, "note": "tail edited", "titles": ["entropy_src_core.sv", "entropy_src_main_sm.sv"], "ts": "2026-09-07T13:19:00", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "blockers", "row": "codeAction on the aes token", "ms": [12.833957996917889, 10.779667005408555, 6.01395801641047], "note": "definition 12.65; hover 12.73; documentSymbol 12.91 | definition 10.63; hover 10.69; documentSymbol 10.82 | definition 5.95; hover 5.95; documentSymbol 6.02", "ts": "2026-09-07T13:19:10", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "blockers", "row": "prepareRename on aes", "ms": [0.36320899380370975, 0.4869579861406237, 0.3209170245099813], "note": "definition 0.26; hover 0.44; documentSymbol 0.52 | definition 0.34; hover 0.33; documentSymbol 0.48 | definition 0.23; hover 0.34; documentSymbol 0.46", "ts": "2026-09-07T13:19:19", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "blockers", "row": "rename on aes", "ms": [168.9289589994587, 146.05179199134, 163.01883399137296], "note": "definition 168.79; hover 168.81; documentSymbol 168.86 | definition 145.99; hover 146.06; documentSymbol 146.12 | definition 162.92; hover 162.95; documentSymbol 163.01", "ts": "2026-09-07T13:19:28", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "blockers", "row": "workspace/symbol 'aes'", "ms": [17.061499995179474, 9.539541992126033, 8.42766699497588], "note": "definition 16.86; hover 16.80; documentSymbol 16.79 | definition 9.29; hover 9.16; documentSymbol 9.14 | definition 8.22; hover 8.16; documentSymbol 8.14", "ts": "2026-09-07T13:19:37", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "didopen", "row": "didOpen aes.sv -> definition", "ms": [4.201541014481336, 2.875334001146257, 1.5770829922985286], "n": 326, "note": "second definition 0.11 / 0.08 / 0.09", "ts": "2026-09-07T13:19:46", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "didopen", "row": "didOpen aes_core.sv -> definition", "ms": [6.704041996272281, 3.9285829989239573, 4.679166013374925], "n": 1145, "note": "second definition 0.08 / 0.11 / 0.07", "ts": "2026-09-07T13:19:54", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "didopen", "row": "didOpen spi_device.sv -> definition", "ms": [12.980458996025845, 13.928459025919437, 8.68691600044258], "n": 1985, "note": "second definition 0.15 / 0.12 / 0.09", "ts": "2026-09-07T13:20:03", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "didopen", "row": "didOpen pinmux_reg_top.sv -> definition", "ms": [129.95958302053623, 128.89612501021475, 128.12949999351986], "n": 42192, "note": "second definition 0.12 / 0.09 / 0.09", "ts": "2026-09-07T13:20:12", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "scan", "row": "default, cold cache", "ms": [90.97966700210236, 110.86883299867623, 98.73374999733642], "note": "0 files indexed | 124 files indexed", "ts": "2026-09-07T13:20:18", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "scan", "row": "default, warm cache", "ms": [56.196375022409484, 49.91412500385195, 52.97879100544378], "note": "0 files indexed | 124 files indexed, 123 from cache", "ts": "2026-09-07T13:20:23", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "scan", "row": "empty-index, cold cache", "ms": [104.49991698260419, 92.73062500869855, 103.43666700646281], "note": "0 files indexed | 124 files indexed", "ts": "2026-09-07T13:20:27", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "scan", "row": "empty-index, warm cache", "ms": [42.02829100540839, 51.617916993563995, 52.5576249929145], "note": "0 files indexed | 124 files indexed, 123 from cache", "ts": "2026-09-07T13:20:32", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "scan", "row": "depth0, cold cache", "ms": [116.60375000792556, 124.47691700072028, 114.59854201530106], "note": "124 files indexed | 1 file indexed", "ts": "2026-09-07T13:20:37", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "scan", "row": "depth0, warm cache", "ms": [62.903957994421944, 58.09541599592194, 62.97554200864397], "note": "124 files indexed, 123 from cache | 1 file indexed", "ts": "2026-09-07T13:20:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "scan", "row": "workspace, cold cache", "ms": [2830.29950002674, 2853.0597079952713, 2845.6383750017267], "note": "124 files indexed | 3976 files indexed, 123 from cache, 3 skipped", "ts": "2026-09-07T13:20:55", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "scan", "row": "workspace, warm cache", "ms": [1322.2372920135967, 1330.9673749899957, 1344.0332919999491], "note": "124 files indexed, 123 from cache | 3976 files indexed, 3975 from cache, 3 skipped", "ts": "2026-09-07T13:21:04", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "rss", "row": "server RSS after workspace scan, cold cache", "ms": [541248.0, 543600.0, 540688.0], "n": 45404, "note": "RSS KB above; index store 45404 KB", "ts": "2026-09-07T13:21:21", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "rss", "row": "server RSS after workspace scan, warm cache", "ms": [579952.0, 587552.0, 586992.0], "n": 45404, "note": "RSS KB above; index store 45404 KB", "ts": "2026-09-07T13:21:33", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "expand-wildcard offer", "ms": [13.727207988267764, 10.321332985768095, 8.66449999739416, 8.051457989495248], "n": 2, "titles": ["lucisv: expand .* (32 connections)", "lucisv: extract selection into module\u2026"], "file": "hw/ip/kmac/fpv/tb/sha3_fpv.sv", "position": {"line": 54, "character": 4}, "ts": "2026-09-07T13:21:37", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "expand-wildcard resolve: lucisv: expand .* (32 connections)", "ms": [73.01820800057612, 70.3485419799108, 70.37633302388713, 70.73025000863709], "n": 1, "ts": "2026-09-07T13:21:37", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "expand-wildcard resolve: lucisv: extract selection into module\u2026", "ms": [0.09695798507891595, 0.0627499830443412, 0.046375003876164556, 0.04379200981929898], "n": 0, "ts": "2026-09-07T13:21:37", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "organize-imports offer", "ms": [17.78845800436102, 16.333790990756825, 16.031375009333715, 14.99787499778904], "n": 2, "titles": ["lucisv: organize imports (removes 1, sorts 1)", "lucisv: extract selection into module\u2026"], "file": "hw/ip/aes/rtl/aes_sbox_canright_masked.sv", "position": {"line": 42, "character": 2}, "ts": "2026-09-07T13:21:41", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "organize-imports resolve: lucisv: organize imports (removes 1, sorts 1)", "ms": [10.307541990187019, 10.010500001953915, 9.585624997271225, 10.693999996874481], "n": 1, "ts": "2026-09-07T13:21:41", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "organize-imports resolve: lucisv: extract selection into module\u2026", "ms": [0.09654200403019786, 0.07049998384900391, 0.045666994992643595, 0.03566697705537081], "n": 0, "ts": "2026-09-07T13:21:41", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "inline-module offer", "ms": [17.295291007030755, 15.189333003945649, 13.657124974997714, 13.23316601337865], "n": 2, "titles": ["lucisv: extract selection into module\u2026", "lucisv: inline `tlul_cmd_intg_gen` here"], "file": "hw/ip/aes/rtl/aes_wrap.sv", "position": {"line": 66, "character": 2}, "ts": "2026-09-07T13:21:44", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "inline-module resolve: lucisv: extract selection into module\u2026", "ms": [0.09745798888616264, 0.05833400064148009, 0.04008298856206238, 0.05237499135546386], "n": 0, "ts": "2026-09-07T13:21:44", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "inline-module resolve: lucisv: inline `tlul_cmd_intg_gen` here", "ms": [0.05062500713393092, 0.034958007745444775, 0.0367090106010437, 0.05716699524782598], "n": 0, "ts": "2026-09-07T13:21:44", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "port-actions offer", "ms": [41.94795899093151, 30.146292003337294, 26.21850001742132, 25.045875023351982], "n": 2, "titles": ["lucisv: connect 2 missing ports", "lucisv: extract selection into module\u2026"], "file": "hw/ip/aes/rtl/aes_wrap.sv", "position": {"line": 78, "character": 2}, "ts": "2026-09-07T13:21:48", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "port-actions resolve: lucisv: connect 2 missing ports", "ms": [170.76995800016448, 165.78358400147408, 164.78945800918154, 165.8231669862289], "n": 1, "ts": "2026-09-07T13:21:49", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "port-actions resolve: lucisv: extract selection into module\u2026", "ms": [0.17820799257606268, 0.06591700366698205, 0.07270899368450046, 0.07120799273252487], "n": 0, "ts": "2026-09-07T13:21:49", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "ansi-header (no offer expected) offer", "ms": [6.597665982553735, 3.4144170058425516, 4.115707997698337, 2.7353339828550816], "n": 0, "titles": [], "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 8, "character": 0}, "ts": "2026-09-07T13:21:52", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "extract-module offer (selection)", "ms": [5.251583002973348, 2.8505839873105288, 2.6334169961046427, 2.9186659958213568], "n": 1, "titles": ["lucisv: extract selection into module\u2026"], "file": "hw/ip/aes/rtl/aes.sv", "position": {"line": 220, "character": 0}, "note": "selection 220:0-222:53", "ts": "2026-09-07T13:21:56", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "refactor", "row": "extract-module resolve: lucisv: extract selection into module\u2026", "ms": [0.11795799946412444, 0.08804097888059914, 0.061291997553780675, 0.059165991842746735], "ts": "2026-09-07T13:21:56", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "rename", "row": "prepareRename on aes", "ms": [0.3741249965969473, 0.1242909929715097, 0.08687499212101102, 0.11412499588914216], "note": "{\"placeholder\": \"aes\", \"range\": {\"end\": {\"character\": 5, \"line\": 44}, \"start\": {\"character\": 2, \"line\": 44}}}", "ts": "2026-09-07T13:22:00", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "rename", "row": "rename aes -> aes_renamed", "ms": [168.67058299249038, 139.3450839968864, 140.34991699736565, 140.02487499965355], "n": 9, "ts": "2026-09-07T13:22:01", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "flush", "row": "didChange flush (foldingRange barrier)", "ms": [1.051125000230968, 0.7182499975897372, 0.6553329876624048, 0.7070830033626407], "ts": "2026-09-07T13:22:05", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "diagnostics", "row": "publish after didChange (incl. ~150 ms debounce)", "ms": [158.02012500353158, 157.61862500221469, 155.95241700066254, 156.7312499973923], "ts": "2026-09-07T13:22:09", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after ''", "ms": [5.074124987004325, 3.3819169912021607, 3.3374999766238034, 3.3187080116476864], "n": 512, "ts": "2026-09-07T13:22:12", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after 'a'", "ms": [4.928332986310124, 3.4707500017248094, 3.705041977809742, 4.101250000530854], "n": 512, "ts": "2026-09-07T13:22:12", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after 'ae'", "ms": [4.227790981531143, 3.2232919766101986, 3.289915999630466, 3.03837499814108], "n": 512, "ts": "2026-09-07T13:22:12", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after 'aes'", "ms": [10.328167001716793, 8.345458016265184, 8.103875006781891, 7.97045900253579], "n": 512, "ts": "2026-09-07T13:22:12", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after 'aes_'", "ms": [8.156291994964704, 7.06891599111259, 7.480166997993365, 8.142542006680742], "n": 512, "ts": "2026-09-07T13:22:12", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after 'prim_'", "ms": [5.011625005863607, 4.2414169874973595, 4.21429198468104, 4.112499998882413], "n": 512, "ts": "2026-09-07T13:22:13", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after 'clk'", "ms": [4.2789580184035, 4.253791994415224, 4.376500000944361, 4.032416007248685], "n": 512, "ts": "2026-09-07T13:22:13", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after 'aes_reg'", "ms": [3.8101660029496998, 3.188000002410263, 3.131667006528005, 3.098332992522046], "n": 512, "ts": "2026-09-07T13:22:13", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "completion", "row": "completion after 'zzzz'", "ms": [1.2714170152321458, 0.34666599822230637, 0.3170420241076499, 0.34087500534951687], "n": 1, "ts": "2026-09-07T13:22:13", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "definition on aes", "ms": [0.3645409888122231, 0.08429199806414545, 0.06970801041461527, 0.04816701402887702], "n": 1, "method": "textDocument/definition", "ts": "2026-09-07T13:22:16", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "hover on aes", "ms": [0.6570420227944851, 0.08033300400711596, 0.07691601058468223, 0.05837497883476317], "n": 1, "method": "textDocument/hover", "ts": "2026-09-07T13:22:19", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "typeDefinition on aes", "ms": [0.26041700039058924, 0.13525001122616231, 0.08075000368990004, 0.06658400525338948], "n": 1, "method": "textDocument/typeDefinition", "ts": "2026-09-07T13:22:22", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "documentHighlight", "ms": [0.2092079957947135, 0.09233300806954503, 0.07170799653977156, 0.060166988987475634], "n": 1, "method": "textDocument/documentHighlight", "ts": "2026-09-07T13:22:25", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "references on aes", "ms": [1.353750005364418, 0.6473749817814678, 0.5687499942723662, 0.6048329814802855], "n": 14, "method": "textDocument/references", "ts": "2026-09-07T13:22:27", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "references on .clk_i", "ms": [1.0404580098111182, 0.5677500157617033, 0.5708749813493341, 0.4852919955737889], "n": 12, "method": "textDocument/references", "ts": "2026-09-07T13:22:30", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "signatureHelp in the port list", "ms": [1.3370420201681554, 0.7152920006774366, 1.3881659833714366, 0.6492499960586429], "n": 1, "method": "textDocument/signatureHelp", "ts": "2026-09-07T13:22:33", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "documentSymbol", "ms": [0.8117920078802854, 1.3970830186735839, 0.30033400980755687, 0.31920798937790096], "n": 1, "method": "textDocument/documentSymbol", "ts": "2026-09-07T13:22:36", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "foldingRange", "ms": [0.29749999521300197, 0.09770799078978598, 0.07483400986529887, 0.06354099605232477], "n": 4, "method": "textDocument/foldingRange", "ts": "2026-09-07T13:22:40", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "codeLens", "ms": [0.2142910088878125, 0.055042008170858026, 0.05558400880545378, 0.051875016652047634], "n": 1, "method": "textDocument/codeLens", "ts": "2026-09-07T13:22:42", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "documentLink", "ms": [0.2509579935576767, 0.0686249986756593, 0.06649998249486089, 0.050915987230837345], "n": 0, "method": "textDocument/documentLink", "ts": "2026-09-07T13:22:45", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "selectionRange", "ms": [0.4040839849039912, 0.10408301022835076, 0.1862499921116978, 0.09975000284612179], "n": 1, "method": "textDocument/selectionRange", "ts": "2026-09-07T13:22:48", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "semanticTokens/full", "ms": [0.5770419957116246, 0.24774999474175274, 0.2038750099018216, 0.21029100753366947], "n": 1, "method": "textDocument/semanticTokens/full", "ts": "2026-09-07T13:22:51", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "inlayHint (whole file)", "ms": [0.5544160085264593, 0.2564169990364462, 0.28700000257231295, 0.4432909772731364], "n": 4, "method": "textDocument/inlayHint", "ts": "2026-09-07T13:22:54", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "diagnostic (pull)", "ms": [0.7375419954769313, 0.2377500059083104, 0.1999999803956598, 0.25483398349024355], "n": 0, "method": "textDocument/diagnostic", "ts": "2026-09-07T13:22:57", "label": "0.50.0-bbdbfe9"}
|
||||
{"phase": "nav", "row": "workspace/symbol 'aes'", "ms": [22.819792007794604, 13.492500002030283, 10.002707975218073, 8.22295801481232], "n": 256, "method": "workspace/symbol", "ts": "2026-09-07T13:23:00", "label": "0.50.0-bbdbfe9"}
|
||||
@@ -0,0 +1,13 @@
|
||||
{"phase": "baseline", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "baseline", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805082.148632, "load_before": [4.09521484375, 3.15234375, 3.04052734375], "exit": 0, "end": 1788805085.3895628, "load_after": [4.24755859375, 3.19921875, 3.0576171875], "corpus_unchanged": true}
|
||||
{"phase": "codeaction", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "codeaction", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805085.4912288, "load_before": [4.24755859375, 3.19921875, 3.0576171875], "exit": 0, "end": 1788805132.387778, "load_after": [4.53564453125, 3.4072265625, 3.13916015625], "corpus_unchanged": true}
|
||||
{"phase": "tailrename", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "tailrename", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805132.4831302, "load_before": [4.53564453125, 3.4072265625, 3.13916015625], "exit": 0, "end": 1788805141.17239, "load_after": [4.58740234375, 3.45849609375, 3.16015625], "corpus_unchanged": true}
|
||||
{"phase": "blockers", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "blockers", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805141.2841558, "load_before": [4.58740234375, 3.45849609375, 3.16015625], "exit": 0, "end": 1788805177.25146, "load_after": [4.06396484375, 3.45263671875, 3.16943359375], "corpus_unchanged": true}
|
||||
{"phase": "didopen", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "didopen", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805177.351585, "load_before": [4.06396484375, 3.45263671875, 3.16943359375], "exit": 0, "end": 1788805213.377633, "load_after": [3.31005859375, 3.3564453125, 3.14697265625], "corpus_unchanged": true}
|
||||
{"phase": "scan", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "scan", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805213.489726, "load_before": [3.31005859375, 3.3564453125, 3.14697265625], "exit": 0, "end": 1788805265.007585, "load_after": [3.19775390625, 3.30322265625, 3.13720703125], "corpus_unchanged": true}
|
||||
{"phase": "rss", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "rss", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805265.102868, "load_before": [3.19775390625, 3.30322265625, 3.13720703125], "exit": 0, "end": 1788805293.521557, "load_after": [3.1826171875, 3.27587890625, 3.13134765625], "corpus_unchanged": true}
|
||||
{"phase": "refactor", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "refactor", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805293.641702, "load_before": [3.1826171875, 3.27587890625, 3.13134765625], "exit": 0, "end": 1788805317.612632, "load_after": [3.3896484375, 3.32080078125, 3.15087890625], "corpus_unchanged": true}
|
||||
{"phase": "rename", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "rename", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805317.737279, "load_before": [3.3896484375, 3.32080078125, 3.15087890625], "exit": 0, "end": 1788805322.05387, "load_after": [3.2783203125, 3.298828125, 3.14404296875], "corpus_unchanged": true}
|
||||
{"phase": "flush", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "flush", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805322.1551218, "load_before": [3.2783203125, 3.298828125, 3.14404296875], "exit": 0, "end": 1788805325.392707, "load_after": [3.255859375, 3.29345703125, 3.14306640625], "corpus_unchanged": true}
|
||||
{"phase": "diagnostics", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "diagnostics", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805325.505455, "load_before": [3.255859375, 3.29345703125, 3.14306640625], "exit": 0, "end": 1788805329.847487, "load_after": [2.9951171875, 3.23876953125, 3.12451171875], "corpus_unchanged": true}
|
||||
{"phase": "completion", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "completion", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805329.958755, "load_before": [2.9951171875, 3.23876953125, 3.12451171875], "exit": 0, "end": 1788805333.194902, "load_after": [2.9150390625, 3.2177734375, 3.11767578125], "corpus_unchanged": true}
|
||||
{"phase": "nav", "command": ["tools/guard.sh", "-m", "8", "-t", "1800", "--", "python3", "tools/perf/bench.py", "nav", "--server", "/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server", "--label", "0.50.0-bbdbfe9", "--opentitan", "/Users/guoliangchen/repo/opentitan", "--storage", "/tmp/lucisv-perf5-20260907/caches", "--out", "/tmp/lucisv-perf5-20260907/results.jsonl", "--tries", "3"], "start": 1788805333.2985768, "load_before": [2.9150390625, 3.2177734375, 3.11767578125], "exit": 0, "end": 1788805381.2481222, "load_after": [3.44091796875, 3.3349609375, 3.16552734375], "corpus_unchanged": true}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,968 @@
|
||||
# lucisv performance against opentitan — take 4
|
||||
|
||||
Same corpus, same scenarios, same machine as [`performance.md`](performance.md)
|
||||
(take 1), [`performance_take2.md`](performance_take2.md) (take 2) and
|
||||
[`performance_take3.md`](performance_take3.md) (take 3). Take 3 measured
|
||||
**0.43.0** against **0.39.0**. Take 4 measures **0.49.0 (`4c2dae3`)** against
|
||||
**0.43.0 (`73799f3`)**, and every table carries take 3's own 0.43.0 column
|
||||
beside a *fresh* 0.43.0 column taken tonight, with tonight's harness, so each
|
||||
row is a before/after with the harness held fixed.
|
||||
|
||||
Six releases separate the two binaries. Four of them added a refactoring
|
||||
(§50 expand `.*`, §51 convert to ANSI, §52 organize imports, §53 extract and
|
||||
inline module), one fixed the `didOpen` delay take 3 filed (§46), one added a
|
||||
hierarchical member surface to rename and completion (§49), and one bumped the
|
||||
index's on-disk format (18 → 19). All six show up below.
|
||||
|
||||
Every LSP number is a client-observed round trip on a monotonic clock
|
||||
(`time.perf_counter`) — what the editor, and therefore the user, actually
|
||||
experiences. **Read §9 before quoting any of them**: this machine was busier
|
||||
than take 3's.
|
||||
|
||||
**The harness is committed this time.** `tools/perf/` — see §10.
|
||||
|
||||
---
|
||||
|
||||
## 0. The transport baseline, and the server's own clock beside the wire
|
||||
|
||||
Take 3 established that the shipped `--verbose` flag
|
||||
(`docs/features/verbose-timing/`) logs `timing: <method> answered in <n> ms`
|
||||
per request, and that the wire is the server plus 0.2–0.4 ms. Take 4 re-takes
|
||||
that cross-check on both binaries. Nothing was instrumented for this round:
|
||||
the default (no `--verbose`) sessions produce every number in this document,
|
||||
and one supplementary session per shape was re-run *with* `--verbose`.
|
||||
|
||||
| `codeAction` at the cursor | wire, no `--verbose` | wire, `--verbose` session | the server's own line |
|
||||
|---|---:|---:|---:|
|
||||
| **0.49.0** `prim_flop_2sync` (128), eager | 481.6 / 468.2–477.3 ms | 508.5 / 469.4–488.2 ms | 508.2 / 469.1–488.0 ms |
|
||||
| **0.49.0** `prim_flop_2sync` (128), lazy | 15.8 / 7.8–11.0 ms | 9.0 / 6.6–8.0 ms | 8.8 / 6.5–7.8 ms |
|
||||
| **0.49.0** `aes` (6), eager | 119.4 / 87.6–91.9 ms | 118.9 / 87.6–91.5 ms | 117.9 / 87.4–91.4 ms |
|
||||
| **0.49.0** comment line | 5.9 / 2.3–2.9 ms | 4.1 / 1.9–2.9 ms | 3.5 / 1.8–2.6 ms |
|
||||
| **0.43.0** `prim_flop_2sync` (128), eager | 239.3 / 238.0–239.7 ms | 255.8 / 237.8–239.5 ms | 255.6 / 237.6–239.3 ms |
|
||||
| **0.43.0** `prim_flop_2sync` (128), lazy | 19.4 / 12.5–13.2 ms | 16.7 / 10.2–12.4 ms | 16.4 / 10.0–12.2 ms |
|
||||
| **0.43.0** `aes` (6), eager | 75.2 / 43.5–43.9 ms | 70.9 / 43.2–44.0 ms | 70.5 / 43.0–43.8 ms |
|
||||
| **0.43.0** comment line | 3.9 / 1.3–2.1 ms | 4.7 / 1.1–1.9 ms | 4.3 / 1.0–1.8 ms |
|
||||
|
||||
**The wire is the server plus 0.1–0.3 ms on every repeat (worst single reading 1.2 ms, a first try).** Take 3's finding
|
||||
holds one release later and on a different harness, which is worth one line:
|
||||
it means every large movement below is server work, not transport.
|
||||
|
||||
The transport baseline — an unknown method, `$/lucisvNoSuchMethod`, rejected
|
||||
without work:
|
||||
|
||||
| | take 1 | take 2 | take 3 (0.43.0) | **take 4, 0.49.0** | **take 4, 0.43.0** |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| first in a settled session | 0.02 ms | 0.019 ms | 0.24 ms | **0.63 ms** | **0.17 ms** |
|
||||
| repeats | ≈0.05 ms | ≈0.05 ms | 0.059–0.092 ms | **0.09–0.32 ms** | **0.04–0.06 ms** |
|
||||
|
||||
The two take-4 columns are the same client, minutes apart, and they differ by
|
||||
3–5×. **That is the noise floor of this machine, not a property of either
|
||||
binary**, and it is the reason no conclusion below is drawn from any movement
|
||||
under 0.5 ms. §8.9 lists them and dismisses them.
|
||||
|
||||
---
|
||||
|
||||
## 1. Environment and provenance
|
||||
|
||||
| | take 3 | **take 4** |
|
||||
|---|---|---|
|
||||
| Machine | Apple M1 Max, 10 cores, 64 GB | **same machine** |
|
||||
| OS | macOS 27.0 (26A5425a) | macOS 27.0 (**26A5425a**) — same build |
|
||||
| Date | 2026-09-05 ~02:45–04:00 | **2026-09-07 ~02:44–03:25** |
|
||||
| Server under test | 0.43.0 `73799f3`, 5 676 528 B | **0.49.0 `4c2dae3`, `target/release/lucisv-server`, 6 273 184 B, sha256 `c6e40ecd…`**, Mach-O arm64 |
|
||||
| Baseline server | 0.39.0, built for the round | **0.43.0 `73799f3`, 5 676 592 B, sha256 `7f0f27d6…`** — built for this round in a scratch `git worktree` at `v0.43.0` (`cargo build --release -p lucisv_server`, 57.75 s), removed afterwards |
|
||||
| CLI binaries | 0.43.0 / 0.41.0 / 0.39.0 | **0.49.0 (3 236 768 B, `0c943c4c…`), 0.43.0 (2 828 576 B, `89379a12…`), 0.39.0 (2 770 688 B, `4caf841f…`)** from `~/.cache/lucisv-baselines/` |
|
||||
| Corpus | `/Users/guoliangchen/repo/opentitan` @ `0098135264` | **same commit**, 3 976 indexed + 3 skipped, same three pre-existing modified files |
|
||||
| Scenario file | `hw/ip/aes/dv/tb/tb.sv`; `aes` at 0-based 44:2 | same file, same position, resolved from the text at run time |
|
||||
| Client | `scratchpad/perf3/*.py` (gone) | **`tools/perf/` — committed** (§10) |
|
||||
| Guard | every run, no kill | **every server session, every `lucisv` invocation and the one `cargo build` went through `tools/guard.sh -m 8 -t 1800`. No guard kill occurred.** |
|
||||
| Machine state | load 2–4, quiet | **load 3.7–7.1 throughout** — a live desktop session (WindowServer 45–51%, loginwindow 24–29%). See §9 |
|
||||
|
||||
### 1a. Why tonight's 0.43.0 column is the one to read
|
||||
|
||||
Take 3's 0.43.0 numbers were taken on a quieter machine with a different
|
||||
Python client. Tonight's were taken on this machine, with this client, within
|
||||
one hour of the 0.49.0 numbers beside them. **Every conclusion in this
|
||||
document is drawn from a take-4 pair**; take 3's column is carried so a reader
|
||||
can see the three-round trend, and where the two 0.43.0 columns disagree that
|
||||
disagreement is the machine and the harness, which §9 quantifies.
|
||||
|
||||
### 1b. The corpus is unchanged from take 3
|
||||
|
||||
`hw/ip/aes/dv/tb/tb.sv` is still modified and still lucisv-clean, so
|
||||
`textDocument/diagnostic` still returns **0 items** and the `aes`
|
||||
instantiation still raises no quick fix. The other two modified files
|
||||
(`hw/top_{darjeeling,earlgrey}/ip/ast/rtl/ast.sv`) are in no scenario.
|
||||
`git -C opentitan status --porcelain` was checked after every phase and
|
||||
reported exactly those three files every time.
|
||||
|
||||
### 1c. What the client does
|
||||
|
||||
Framed JSON-RPC over the server's stdio; `workspace/configuration` answered
|
||||
with a per-session scope word; cache warmth controlled through
|
||||
`initializationOptions.storagePath`; client capabilities settable per session
|
||||
(with and without `codeAction.resolveSupport.properties: ["edit"]`, so the
|
||||
lazy and eager `codeAction` shapes are both measurable); every request timed
|
||||
from send to response. Three differences from take 3's, all deliberate:
|
||||
|
||||
1. **Positions are resolved from the file text at run time**, by searching for
|
||||
the token, not by a hard-coded line number. Every 0-based position quoted
|
||||
below is what that search resolved to on `0098135264`.
|
||||
2. **The scan barrier is 1.5 s of silence, not the `$/progress` `end`.** The
|
||||
end report is followed by more indexing chatter, so silence is the honest
|
||||
barrier. Take 3 used the same rule.
|
||||
3. **There is a `probe` phase**, and it is how §6b's new offer sites were
|
||||
found rather than guessed.
|
||||
|
||||
---
|
||||
|
||||
## 2. Summary table — worst first, take 3 → take 4
|
||||
|
||||
Workspace scope, warm cache, unless the row says otherwise. "Repeats" is the
|
||||
range over the 2nd–4th identical request in the same session; "first" is that
|
||||
request issued as the first real request of a dedicated session, after the
|
||||
scan settled.
|
||||
|
||||
| Action | T3's 0.43.0 | **0.43.0 tonight** | **0.49.0** |
|
||||
|---|---:|---:|---:|
|
||||
| Workspace scan, **cold** cache (didOpen → 3 976 indexed) | 2 867 / 2 754–2 773 ms | **2 645 / 2 640–2 656 ms** | **2 712 / 2 691–2 712 ms** |
|
||||
| `didOpen pinmux_reg_top.sv` (42 192 L) → the request behind it | *not measured* | **1 605 / 1 604–1 611 ms** | **112 / 128–131 ms** |
|
||||
| Workspace scan, **warm** cache | 1 229.8 / 1 220.5–1 229.7 ms | **1 173.4 / 1 167.1–1 173.6 ms** | **1 266.1 / 1 239.8–1 285.6 ms** |
|
||||
| First `didOpen` of an RTL file at the **default** scope (`aes.sv`, widens to `hw/ip`) | 1 081.6 cold / 365.1 warm | **1 046.6 / 1 019.8–1 042.0 cold; 344.9 / 338.9–340.4 warm** | **1 072.4 / 1 051.4–1 075.8 cold; 367.0 / 351.0–378.1 warm** |
|
||||
| `textDocument/rename` on a net named through an **instance tail** (§49) | *no such answer* | **88.0 / 65.8–66.7 ms, 1 file, tail NOT edited** | **793.2 / 750.7–751.9 ms, 2 files, tail edited** |
|
||||
| `textDocument/codeAction`, `prim_flop_2sync` (128), **eager** client | 270.2 / 252.9–255.2 ms | **267.1 / 238.6–243.3 ms** | **511.8 / 467.1–473.6 ms** |
|
||||
| `textDocument/codeAction`, `prim_alert_sender` (67), eager | 213.4 / 196.0–196.5 ms | **211.5 / 183.0–192.4 ms** | **405.1 / 362.3–368.8 ms** |
|
||||
| `textDocument/codeAction`, `prim_lc_sync` (42), eager | 148.0 / 128.9–130.4 ms | **138.6 / 121.5–124.9 ms** | **270.0 / 254.7–255.7 ms** |
|
||||
| `codeAction` at `aes_wrap.sv` 78:2, eager (the one offering cursor) | 143.8 / 123.9–124.4 ms | **145.6 / 115.4–118.6 ms** | **167.9 / 159.9–160.9 ms** |
|
||||
| `codeAction/resolve` at that cursor | 119.5 / 119.5–121.9 ms | **111.0 / 110.4–112.7 ms** | **163.9 / 158.2–159.5 ms** |
|
||||
| `textDocument/rename` on `aes` (edits computed, not applied) | 151.8 / 139.1–140.7 ms (9 files) | **159.8 / 133.2–136.2 ms (9)** | **165.1 / 133.5–139.4 ms (9)** |
|
||||
| — anything queued behind that rename | 160.8 ms | **159.3 / 132.8–157.9 ms** | **160.7 / 145.1–161.7 ms** |
|
||||
| diagnostics **publish** after a `didChange` (~150 ms is the debounce) | 161.1 / 159.6–163.4 ms | **164.0 / 164.3–167.4 ms** | **164.5 / 153.5–160.7 ms** |
|
||||
| `textDocument/codeAction`, `aes` (6), eager | 66.1 / 45.7–48.2 ms | **61.5 / 43.5–46.1 ms** | **114.0 / 88.3–90.7 ms** |
|
||||
| `didOpen spi_device.sv` (1 985 L) → the request behind it | *not measured* | **98.7 / 75.2–99.5 ms** | **15.5 / 13.8–15.1 ms** |
|
||||
| `expand .*` resolve at `sha3_fpv.sv` 54:4 (32 connections) | *no such action* | *no such action* | **67.8 / 66.9–67.0 ms** |
|
||||
| `didOpen aes_core.sv` (1 145 L) → the request behind it | *not measured* | **42.6 / 63.0–63.1 ms** | **11.0 / 4.0–10.4 ms** |
|
||||
| `codeAction` offer at `aes_wrap.sv` 78:2, **lazy** | 33.3 / 21.2–26.8 ms | **20.8 / 18.9–20.2 ms** | **28.6 / 23.6–24.4 ms** |
|
||||
| `codeAction`, `aes_reg_top` (fan-out 1), lazy | 27.1 / 16.4–20.6 ms | **17.6 / 14.2–15.2 ms** | **29.8 / 21.8–23.5 ms** |
|
||||
| `lucisv/moduleHierarchy` (1 546 modules, 2.6 MB) | *not measured* | **70.3 / 41.0–48.8 ms** | **76.2 / 41.1–53.8 ms** |
|
||||
| `codeAction`, `prim_flop_2sync` (128), **lazy** (the offer) | 24.0 / 15.6–16.9 ms | **16.7 / 10.5–13.2 ms** | **15.0 / 8.1–10.5 ms** |
|
||||
| `workspace/symbol "aes"` (256 results) | 8.8 / 7.2–7.9 ms | **18.2 / 8.2–13.3 ms** | **18.2 / 8.7–12.7 ms** |
|
||||
| — anything queued behind it | 11.0 ms | **17.7 / 17.9–18.4 ms** | **18.4 / 15.2–18.0 ms** |
|
||||
| `codeAction`, `prim_alert_sender` (67), lazy | 14.8 / 8.6–10.8 ms | **14.7 / 8.5–12.2 ms** | **13.2 / 9.0–11.5 ms** |
|
||||
| `codeAction` **on the `aes` instantiation**, lazy | 5.15 / 4.05–4.24 ms | **7.4 / 4.0–4.9 ms** | **14.2 / 7.9–9.8 ms** |
|
||||
| — definition pipelined behind that codeAction | 5.15 ms | **7.6 / 3.4–7.6 ms** | **14.7 / 11.4–16.2 ms** |
|
||||
| `codeAction`, `prim_lc_sync` (42), lazy | 17.3 / 7.2–8.6 ms | **18.1 / 7.4–9.4 ms** | **7.0 / 6.0–6.2 ms** |
|
||||
| `didOpen aes.sv` (326 L) → the request behind it | *not measured* | **11.3 / 4.3–11.4 ms** | **5.1 / 3.5–3.7 ms** |
|
||||
| `organize imports` resolve at `aes_sbox_canright_masked.sv` 42:2 | *no such action* | *no such action* | **9.6 / 9.6–9.6 ms** |
|
||||
| `textDocument/completion` at 0 typed characters (512 items) | 9.5 / 2.3–2.8 ms | **7.8 / 4.2–5.4 ms** | **7.2 / 4.2–5.3 ms** |
|
||||
| `textDocument/completion` at `aes` (512 items) | 10.4 / 7.8–9.2 ms | **8.6 / 6.8–7.4 ms** | **9.1 / 7.0–8.2 ms** |
|
||||
| `codeAction` on a **comment line** (contrast), lazy | 1.69 / 0.66–0.81 ms | **2.2 / 1.1–1.3 ms** | **4.7 / 3.2–3.8 ms** |
|
||||
| `textDocument/references` on `.clk_i` (12 hits) | 0.56 / 0.51–0.72 ms | **1.54 / 0.70–0.81 ms** | **1.65 / 1.01–1.15 ms** |
|
||||
| `textDocument/signatureHelp` inside the port list | 0.70 / 0.57–0.62 ms | **2.50 / 1.09–1.24 ms** | **3.06 / 1.12–1.26 ms** |
|
||||
| `didChange` flush (`foldingRange` barrier) | 0.95 / 0.58–0.80 ms | **2.32 / 1.04–1.28 ms** | **1.79 / 0.89–0.97 ms** |
|
||||
| `textDocument/references` on `aes` (14 hits) | 0.85 / 0.54–0.61 ms | **2.80 / 1.32–1.50 ms** | **0.92 / 0.58–0.60 ms** |
|
||||
| `textDocument/completion` after an instance head + `.` (26 items) | *no such answer* | **1.72 / 0.52–0.66 ms (24 items)** | **1.11 / 0.45–0.53 ms (26)** |
|
||||
| `textDocument/inlayHint` (whole file, 4 hints) | 0.49 / 0.26–0.43 ms | **1.90 / 0.65–0.85 ms** | **2.04 / 0.57–0.81 ms** |
|
||||
| `textDocument/semanticTokens/full` | 0.21 / 0.19–0.25 ms | **1.03 / 0.45–0.57 ms** | **0.39 / 0.23–0.30 ms** |
|
||||
| `textDocument/diagnostic` (pull, 0 items — §1b) | 0.34 / 0.17–0.19 ms | **1.02 / 0.46–0.68 ms** | **0.93 / 0.38–0.47 ms** |
|
||||
| `textDocument/documentSymbol` | 0.18 / 0.12–0.15 ms | **0.69 / 0.27–0.31 ms** | **0.61 / 0.25–0.31 ms** |
|
||||
| `textDocument/prepareRename` on `aes` (pressing F2) | 0.31 / 0.08–0.16 ms | **0.37 / 0.13–0.15 ms** | **0.71 / 0.12–0.91 ms** |
|
||||
| — anything queued behind that prepareRename | 0.37 ms | **0.26 / 0.36–0.83 ms** | **0.78 / 0.24–0.63 ms** |
|
||||
| `textDocument/definition` on `aes` | 0.19 / 0.07–0.09 ms | **0.87 / 0.11–0.16 ms** | **0.47 / 0.13–0.17 ms** |
|
||||
| `textDocument/hover` on `aes` | 0.18 / 0.06–0.08 ms | **0.26 / 0.05–0.08 ms** | **0.86 / 0.15–0.18 ms** |
|
||||
| `textDocument/foldingRange` | 0.10 / 0.05–0.07 ms | **0.44 / 0.08–0.10 ms** | **0.73 / 0.12–0.18 ms** |
|
||||
| `textDocument/documentHighlight` | 0.10 / 0.04–0.05 ms | **0.19 / 0.07–0.08 ms** | **0.61 / 0.16–0.21 ms** |
|
||||
| `textDocument/selectionRange` | 0.09 / 0.05 ms | **0.95 / 0.13–0.28 ms** | **1.79 / 0.17–0.27 ms** |
|
||||
| `textDocument/codeLens` | 0.07 / 0.04–0.05 ms | **0.47 / 0.15–0.17 ms** | **0.23 / 0.09–0.10 ms** |
|
||||
| `textDocument/typeDefinition` on `aes` | 0.06 / 0.05–0.06 ms | **0.46 / 0.14–0.17 ms** | **0.67 / 0.11–0.17 ms** |
|
||||
| `textDocument/documentLink` | 0.06 / 0.04–0.05 ms | **0.49 / 0.13–0.16 ms** | **1.09 / 0.08–0.11 ms** |
|
||||
| `initialize` → response | 2.3 – 4.4 ms | **233.5 ms** (a cold `exec`, the session's first spawn) | **0.27 ms** |
|
||||
| *transport baseline (does no work)* | *0.06 – 0.24 ms* | *0.04 – 0.17 ms* | *0.09 – 0.63 ms* |
|
||||
|
||||
**The one-line reading of that table.** Four things moved, and only four:
|
||||
|
||||
1. **§46's `didOpen` fix is real in the release build, and it is the round's
|
||||
headline** — a 42 192-line file's open costs **1 605 ms at 0.43.0 and
|
||||
112 ms at 0.49.0**, a **14×**; every RTL file measured is 3–7× cheaper
|
||||
(§5c).
|
||||
2. **The eager `codeAction` path is ~2× dearer** at every fan-out. It is a
|
||||
ruled non-hot path (owner, 2026-09-05), so it is reported, not re-filed —
|
||||
but the number crossed 500 ms and §6a says who pays it.
|
||||
3. **§49's tail rename buys correctness at 11.3× the cost**: 66 ms answering
|
||||
one file and warning about the tail, against 751 ms answering two files
|
||||
and editing it (§6c). Filed as §8.3.
|
||||
4. **The index costs ~14% more**, on disk and in the server's resident set
|
||||
(§6e), which is what `FACTS_FORMAT` 18 → 19 bought.
|
||||
|
||||
Everything else in the table is inside the machine's noise, and §8.9 says so
|
||||
one row at a time. In particular: **the lazy `codeAction` offer, `rename`,
|
||||
`completion`, the scan, the diagnostics publish and every sub-millisecond
|
||||
navigation request are the same on both binaries.**
|
||||
|
||||
---
|
||||
|
||||
## 3. The queue-blocking analysis
|
||||
|
||||
The server still runs a single-threaded request loop, so the latency a user
|
||||
feels for request *R* is *R*'s cost plus everything queued ahead of it. Each
|
||||
slow request was sent, then — back to back, no wait — the three requests a
|
||||
real editor fires on every cursor move. Three tries; `definition` is the
|
||||
first follower.
|
||||
|
||||
| Sent first (the blocker) | Its own cost, T3 0.43.0 | **0.43.0 tonight** | **0.49.0** | `definition` behind it, **0.43.0** | **0.49.0** |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| `codeAction` on the `aes` token (lazy) | 5.07 ms | **7.55 / 3.35–7.56 ms** | **14.67 / 11.40–16.20 ms** | 3.28 – 7.34 ms | 11.24 – 15.94 ms |
|
||||
| `prepareRename` on `aes` | 0.34 ms | **0.26 / 0.36–0.83 ms** | **0.78 / 0.24–0.63 ms** | 0.19 – 0.38 ms | 0.15 – 0.44 ms |
|
||||
| `rename` on `aes` | 160.8 ms | **159.3 / 132.9–157.9 ms** | **160.7 / 145.2–161.7 ms** | 132.8 – 159.2 ms | 145.1 – 161.5 ms |
|
||||
| `workspace/symbol "aes"` | 11.0 ms | **17.7 / 17.9–18.4 ms** | **18.4 / 15.2–18.0 ms** | 17.1 – 17.3 ms | 14.8 – 17.7 ms |
|
||||
|
||||
`hover` and `documentSymbol` behind each leader land 0.01–0.3 ms after the
|
||||
`definition`, as in all three earlier takes: **the queue is still strictly
|
||||
serial and the follower still pays the leader's bill almost exactly.**
|
||||
|
||||
Take 3's structural conclusion was that "the hot path is clean" — `codeAction`
|
||||
5 ms and `completion` 2–3 ms, both inside a 16 ms frame. **That conclusion
|
||||
survives, with one qualification.** The lazy `codeAction` on the `aes` token
|
||||
is 11.4–16.2 ms at 0.49.0 against 3.4–7.6 at 0.43.0: still under the frame
|
||||
budget, but no longer comfortably. The cost is the new offers' own gates —
|
||||
`inline_site` and `extract_site` each parse the cursor's buffer — and it is
|
||||
paid on every cursor move whether or not anything is offered. §8.2 files it.
|
||||
|
||||
What is left genuinely slow is unchanged in kind: user-initiated (`rename`,
|
||||
160 ms; the tail rename, 751 ms), once-per-session (the scan, 1.2–2.7 s), or
|
||||
paid only by a client that cannot resolve a code action (§6a).
|
||||
|
||||
---
|
||||
|
||||
## 4. Startup and scan, per scope config and cache state
|
||||
|
||||
`didOpen tb.sv` → 1.5 s of silence, three runs per cell. "Cold" = the
|
||||
`storagePath` directory was `rm -rf`'d immediately before; "warm" = it carries
|
||||
a previous run's store.
|
||||
|
||||
| Scope config | Cache | T3 0.43.0 | **0.43.0 tonight** | **0.49.0** | files |
|
||||
|---|---|---:|---:|---:|---|
|
||||
| **default** (`[{}]`) | cold | 81.9 / 92.5 / 93.1 ms | **95.0 / 101.7 / 101.6** | **83.8 / 110.3 / 103.6** | 124 |
|
||||
| **default** | warm | 39.4 / 40.3 / 41.8 ms | **53.1 / 54.8 / 55.5** | **55.8 / 54.7 / 56.6** | 124, 123 from cache |
|
||||
| `{"index":{}}` | cold | 88.8 / 90.1 / 94.5 ms | **96.6 / 91.3 / 103.9** | **98.1 / 95.2 / 103.6** | 124 |
|
||||
| `{"index":{}}` | warm | 34.7 / 39.1 / 39.3 ms | **44.6 / 58.4 / 54.2** | **41.8 / 54.8 / 56.4** | 124 |
|
||||
| explicit `scopeDepth: 0` | cold | 93.5 / 101.6 / 105.5 ms | **107.4 / 114.8 / 106.1** | **107.4 / 108.8 / 115.8** | 1 (after a ~100 ms 124-file scan is thrown away) |
|
||||
| explicit `scopeDepth: 0` | warm | 42.3 / 49.3 / 49.6 ms | **56.6 / 60.4 / 58.9** | **58.8 / 62.3 / 67.9** | 1 |
|
||||
| `workspace` | cold | 2 754 / 2 773 / 2 867 ms | **2 645 / 2 640 / 2 656** | **2 712 / 2 691 / 2 712** | 3 976, 3 skipped |
|
||||
| `workspace` | warm | 1 220.5 / 1 229.7 / 1 229.8 ms | **1 173.4 / 1 167.1 / 1 173.6** | **1 266.1 / 1 239.8 / 1 285.6** | 3 975 from cache |
|
||||
|
||||
- **The scan did not change.** Cold workspace is +2.4% at 0.49.0, warm is
|
||||
+8.7%; the warm band across both binaries is 1 167–1 286 ms, and 0.43.0's
|
||||
own two columns (take 3's 1 220–1 230 and tonight's 1 167–1 174) differ by
|
||||
4.5% on their own. §8.9.
|
||||
- **Every small-scope cell is 10–40% dearer than take 3's**, on *both*
|
||||
binaries, in lockstep. That is the machine (§9), not a release: the 0.43.0
|
||||
binary is the same binary take 3 measured.
|
||||
- **Persistence still buys ~54%** on the workspace scan (2 676 → 1 218 ms,
|
||||
mean of six runs across both binaries) and ~44% on the default scope
|
||||
(99.3 → 55.1 ms). Take 3 measured 57% / 57%
|
||||
on a quieter machine.
|
||||
- **A cold workspace scan is still not fully cold**: the trace is
|
||||
`0 files → 124 files → 3 976 files`, and the workspace bar reports "123 from
|
||||
cache" even on a wiped store — those 123 are the default scan's own writes,
|
||||
read back seconds later. Unchanged from take 3.
|
||||
- `initialize` still does no scanning. The one 233 ms reading is the session's
|
||||
very first process spawn — a cold `exec`, exactly the outlier take 3 saw.
|
||||
|
||||
### 4b. What each scope answers, at 0.49.0
|
||||
|
||||
Take 3's §4b table, re-taken at both binaries. The `aes` instantiation in
|
||||
`tb.sv`. **Every count below is identical on 0.43.0 and 0.49.0.**
|
||||
|
||||
| Request | default | explicit `scopeDepth 0` | workspace |
|
||||
|---|---|---|---|
|
||||
| `definition` | **1 result**, 0.11–0.21 ms | 0 results | 1 result, 0.22–0.30 ms |
|
||||
| `typeDefinition` | 1 result | 0 results | 1 result |
|
||||
| `hover` | 1 result | 0 results | 1 result |
|
||||
| `references` | **11 results**, 0.44–0.50 ms | 0 results | **14 results**, 1.07–1.14 ms |
|
||||
| `documentHighlight` | 1 result | 0 results | 1 result |
|
||||
| `signatureHelp` | 0 results | 0 results | 0 results |
|
||||
| `workspace/symbol "aes"` | 256, 3.4–4.0 ms | 0 results, 0.09 ms | 256, 9.0–12.3 ms |
|
||||
| `inlayHint` (whole file) | **0** | 0 | **4** |
|
||||
|
||||
Take 3's §4b holds on every row, at both binaries: the counts (1 / 11 / 14 /
|
||||
256 / 0-vs-4) are byte-for-byte what take 3 recorded, and §37.2's ruling that
|
||||
`inlayHint`'s zero at the default scope is a scope-reach result rather than an
|
||||
inlay defect still stands.
|
||||
|
||||
---
|
||||
|
||||
## 5. The `didOpen` widen and the `didOpen` delay
|
||||
|
||||
### 5a. At `scopeDepth 0` — apples to apples with all three earlier takes
|
||||
|
||||
`tb.sv` open, then RTL files opened one at a time; the request sent
|
||||
immediately afterwards waits for the widen. Three tries.
|
||||
|
||||
| Widening `didOpen` | T3 0.43.0 cold | T3 warm | **0.43.0 cold** | **0.43.0 warm** | **0.49.0 cold** | **0.49.0 warm** |
|
||||
|---|---:|---:|---:|---:|---:|---:|
|
||||
| `hw/ip/aes/rtl/aes.sv` | 19.3 ms | 18.5 ms | **28.4 / 16.3 / 29.0** | **27.8 / 24.3 / 29.3** | **29.5 / 18.8 / 27.9** | **30.3 / 27.7 / 30.7** |
|
||||
| `hw/ip/kmac/rtl/kmac.sv` | 32.9 ms | 25.9 ms | **46.7 / 56.0 / 56.0** | **33.5 / 32.8 / 35.3** | **52.3 / 53.7 / 53.0** | **35.6 / 34.2 / 37.3** |
|
||||
| `hw/ip/hmac/rtl/hmac.sv` | 30.4 ms | 20.4 ms | **42.4 / 36.9 / 45.9** | **32.9 / 33.4 / 36.2** | **34.8 / 36.0 / 44.0** | **34.7 / 32.7 / 31.8** |
|
||||
| `hw/ip/spi_device/rtl/spi_device.sv` | 85.2 ms | 37.0 ms | **93.5 / 101.9 / 102.0** | **54.7 / 58.0 / 57.5** | **105.4 / 107.5 / 102.1** | **56.9 / 56.0 / 60.0** |
|
||||
|
||||
`spi_device` is still the ceiling, for the reason take 1 gave. **The two
|
||||
binaries are the same on every cell**, and both are 20–50% above take 3's
|
||||
0.43.0 column, which is the machine. At this scope each open *is* a rescan, so
|
||||
§46 has nothing to remove.
|
||||
|
||||
### 5b. At the default scope — the widen row, and the three that follow it
|
||||
|
||||
| Widening `didOpen` | T3 0.43.0 cold | T3 warm | **0.43.0 cold** | **0.43.0 warm** | **0.49.0 cold** | **0.49.0 warm** |
|
||||
|---|---:|---:|---:|---:|---:|---:|
|
||||
| `aes.sv` (widens `hw/ip/aes` → **`hw/ip`, 1 807 files**) | 1 081.6 ms | 365.1 ms | **1 046.6 / 1 042.0 / 1 019.8** | **344.9 / 340.4 / 338.9** | **1 072.4 / 1 075.8 / 1 051.4** | **367.0 / 351.0 / 378.1** |
|
||||
| `kmac.sv` (already in scope) | 24.3 ms | 31.1 ms | **53.4 / 23.9 / 48.5** | **35.3 / 45.0 / 44.7** | **12.7 / 5.5 / 9.6** | **6.6 / 9.5 / 11.6** |
|
||||
| `hmac.sv` (already in scope) | 22.6 ms | 21.1 ms | **31.7 / 38.4 / 26.2** | **36.4 / 35.7 / 33.5** | **17.5 / 9.1 / 7.4** | **9.3 / 11.6 / 4.9** |
|
||||
| `spi_device.sv` (already in scope) | 47.6 ms | 51.2 ms | **68.8 / 35.3 / 55.8** | **46.5 / 58.2 / 68.9** | **19.9 / 6.2 / 18.0** | **8.5 / 21.0 / 15.4** |
|
||||
|
||||
**The widen row itself did not move**: 340 ms warm at 0.43.0, 365 ms at
|
||||
0.49.0, against take 3's 365 — the same number, three ways. Take 2's
|
||||
"1.5-second hang on the most common navigation a Verilog user performs" stays
|
||||
closed.
|
||||
|
||||
**The three rows under it are take 3's §8.4, and they are fixed.** A `didOpen`
|
||||
of a file already in scope cost 21–51 ms in take 3 and 33–69 ms here at
|
||||
0.43.0; at 0.49.0 it is **5–21 ms**, a 3–5× on every cell. That is §46, and
|
||||
§5c measures it properly.
|
||||
|
||||
### 5c. §46 on the wire, in the release build — the round's headline
|
||||
|
||||
Take 3 filed the delay (§8.4); 0.44.0 fixed it; the perf README's 2026-09-05
|
||||
table was taken with *temporary* timings on a release build. These are the
|
||||
release numbers, workspace scope, warm store, `didOpen` → the
|
||||
`textDocument/definition` behind it, three tries.
|
||||
|
||||
| file | lines | perf README "before" | **0.43.0, tonight** | perf README "after" | **0.49.0, tonight** | factor |
|
||||
|---|---:|---|---:|---|---:|---:|
|
||||
| `aes.sv` | 326 | 8.1 / 5.9 / 10.1 ms | **11.3 / 4.3 / 11.4** | 4.3 / 1.8 / 2.3 ms | **5.1 / 3.5 / 3.7** | ~2× |
|
||||
| `aes_core.sv` | 1 145 | 56.2 / 54.0 / 48.0 ms | **42.6 / 63.0 / 63.1** | 5.9 / 6.9 / 6.3 ms | **11.0 / 4.0 / 10.4** | **7×** |
|
||||
| `spi_device.sv` | 1 985 | 94.2 / 103.4 / 88.6 ms | **98.7 / 75.2 / 99.5** | 6.0 / 8.6 / 8.7 ms | **15.5 / 13.8 / 15.1** | **6×** |
|
||||
| `pinmux_reg_top.sv` | 42 192 | 1 742 / 1 740 / 1 757 ms | **1 605 / 1 604 / 1 611** | 116.5 / 116.2 / 117.3 ms | **112.1 / 127.9 / 130.7** | **13×** |
|
||||
|
||||
The release build **confirms the fix at the same magnitude the temporary
|
||||
timings reported**, and the largest file in opentitan opens in a tenth of a
|
||||
frame-budget-heavy second rather than in a second and a half. The absolute
|
||||
values here run 1.3–2× above the perf README's on the small files and are
|
||||
level on the large one, which is the expected shape when the machine is
|
||||
busier: a 4 ms row is mostly floor, a 1 600 ms row is mostly work.
|
||||
|
||||
**The same cost was paid on every keystroke flush**, not just on opens
|
||||
(`docs/features/didopen-cost/`), so this is a typing-latency fix as much as a
|
||||
navigation one. That is the strongest single result in this document.
|
||||
|
||||
---
|
||||
|
||||
## 6. `codeAction`, refactorings, rename and the index
|
||||
|
||||
### 6a. Cost against the module's fan-out — the eager path doubled
|
||||
|
||||
Workspace scope, warm cache, cursor on a module instantiation, four tries
|
||||
each. "Lazy" is a client that advertises
|
||||
`textDocument.codeAction.resolveSupport.properties: ["edit"]` (what VS Code
|
||||
sends); "eager" is a client that does not. Fan-outs re-derived with take 3's
|
||||
`grep -rlE '^\s*<module>( |#|$)' --include='*.sv'` and **identical to take 2's
|
||||
and take 3's** (1 / 6 / 42 / 67 / 128).
|
||||
|
||||
| Module at the cursor | files | T3 0.43 eager | **0.43 eager** | **0.49 eager** | T3 0.43 lazy | **0.43 lazy** | **0.49 lazy** | actions at 0.49 |
|
||||
|---|---:|---:|---:|---:|---:|---:|---:|---:|
|
||||
| `aes_reg_top` (in `aes.sv` 103:0) | 1 | 27.7 / 16.3–21.8 | **36.2 / 16.0–22.6** | **30.6 / 22.8–24.2** | 27.1 / 16.4–20.6 | **17.6 / 14.2–15.2** | **29.8 / 21.8–23.5** | **2** |
|
||||
| `aes` (in `tb.sv` 44:2) | 6 | 66.1 / 45.7–48.2 | **61.5 / 43.5–46.1** | **114.0 / 88.3–90.7** | 5.15 / 4.05–4.24 | **7.4 / 4.0–4.9** | **14.2 / 7.9–9.8** | **1** |
|
||||
| `prim_lc_sync` (in `aes.sv` 118:2) | 42 | 148.0 / 128.9–130.4 | **138.6 / 121.5–124.9** | **270.0 / 254.7–255.7** | 17.3 / 7.2–8.6 | **18.1 / 7.4–9.4** | **7.0 / 6.0–6.2** | **1** |
|
||||
| `prim_alert_sender` (in `aes.sv` 235:4) | 67 | 213.4 / 196.0–196.5 | **211.5 / 183.0–192.4** | **405.1 / 362.3–368.8** | 14.8 / 8.6–10.8 | **14.7 / 8.5–12.2** | **13.2 / 9.0–11.5** | **1** |
|
||||
| `prim_flop_2sync` (in `aon_timer.sv` 83:2) | 128 | 270.2 / 252.9–255.2 | **267.1 / 238.6–243.3** | **511.8 / 467.1–473.6** | 24.0 / 15.6–16.9 | **16.7 / 10.5–13.2** | **15.0 / 8.1–10.5** | **2** |
|
||||
| *(contrast) a comment line* | — | 1.80 / 0.71–0.78 | **2.41 / 1.33–1.58** | **7.44 / 4.34–4.95** | 1.69 / 0.66–0.81 | **2.17 / 1.12–1.32** | **4.70 / 3.18–3.84** | **0** |
|
||||
| **`aes` in `aes_wrap.sv` 78:2 — the offering cursor** | 6 | 143.8 / 123.9–124.4 | **145.6 / 115.4–118.6** | **167.9 / 159.9–160.9** | 33.3 / 21.2–26.8 | **20.8 / 18.9–20.2** | **28.6 / 23.6–24.4** | **2** |
|
||||
|
||||
Two readings, in opposite directions.
|
||||
|
||||
**The lazy offer is still `O(1)` in the fan-out and is unchanged where it
|
||||
matters.** 6.0 ms at 42 files, 9.0 at 67, 8.1 at 128 — flat, and slightly
|
||||
*better* than 0.43.0 at the two largest fan-outs. Take 2's "reads as a hang"
|
||||
line at 200 ms is nowhere near crossed for a resolving client.
|
||||
|
||||
**The eager path is 1.95–2.07× dearer at every fan-out above 1**: 46 → 90 ms
|
||||
at 6 files, 125 → 255 at 42, 192 → 368 at 67, 243 → 473 at 128. A consistent
|
||||
factor across four fan-out points, on the same night, on the same machine,
|
||||
with the `--verbose` server's own clock agreeing to 0.5 ms (§0). **The eager
|
||||
`codeAction` path is a ruled non-hot path (owner, 2026-09-05), so this is
|
||||
reported and not re-filed** — but the number is now half a second at the
|
||||
largest fan-out, and §6b shows the eager client also computes strictly more
|
||||
offers than it used to.
|
||||
|
||||
**The two small-cursor rows moved the wrong way for a lazy client too**, and
|
||||
this one *is* filed (§8.2): the `aes` cursor is 4.0–4.9 → 7.9–9.8 ms and a
|
||||
plain comment line is 1.1–1.3 → 3.2–3.8 ms. Nothing is offered at a comment
|
||||
line on either binary; the extra 2 ms is the new offers' gates asking, on
|
||||
every cursor move.
|
||||
|
||||
### 6b. What is offered now, and how often — the census re-taken
|
||||
|
||||
Take 3 swept every instantiation-shaped line in **205 RTL files** — all 165 of
|
||||
`hw/ip/prim/rtl` and all 40 of `hw/ip/aes/rtl` — and found **exactly one
|
||||
position offering a port refactoring**. Take 4 re-ran that sweep at 0.49.0
|
||||
over the same 205 files, adding `import` lines, and classified every offer.
|
||||
**2 440 positions:**
|
||||
|
||||
| Offer | positions offering it | where |
|
||||
|---|---:|---|
|
||||
| `lucisv: extract selection into module…` (§53.1) | **2 171** (89%) | nearly everywhere a whole module item starts |
|
||||
| ``lucisv: inline `M` here`` (§53.2) | **263** (11%) | every instantiation whose buffer parses clean |
|
||||
| `lucisv: organize imports (removes 1, sorts 1)` (§52) | **12** | 2 files: `aes_sbox_canright_masked{,_noreuse}.sv` |
|
||||
| `lucisv: connect N missing ports` (§37/ports) | **1** | `hw/ip/aes/rtl/aes_wrap.sv` 0-based 78:2 — take 3's cursor, unmoved |
|
||||
| `lucisv: expand .* (N connections)` (§50) | **0** | no `.*` in these 205 files (8 files corpus-wide have one) |
|
||||
| `lucisv: remove port …` | **0** | refuses when the module's body uses the port — real RTL always does |
|
||||
|
||||
**Take 3's §8.7 — "the lightbulb is almost never lit" — is no longer true, and
|
||||
that is the mechanism behind §6a's eager number.** At 0.43.0 a cursor on an
|
||||
instantiation offered nothing at all on this corpus except at one position; at
|
||||
0.49.0 it offers one or two things almost everywhere. Both new offers are
|
||||
cheap by construction — `extract` and `inline` carry a `Command`, not an edit,
|
||||
so neither reads the workspace at offer time — but each has a *gate* that
|
||||
parses the cursor's buffer, and that gate runs on every `codeAction`.
|
||||
|
||||
**There is no `convert to ANSI` (§51) site on this corpus.** A scan of all
|
||||
**1 311 module headers** in opentitan's `hw/` (3 932 `.sv`/`.v` files) found
|
||||
**zero** non-ANSI headers — every one declares its ports in the header. So
|
||||
that row below measures an ANSI header, where the action is correctly not
|
||||
offered, and §51's cost on this corpus is exactly the cost of saying no.
|
||||
|
||||
*Traceability note (lead, after QA).* The header scan was a one-off census,
|
||||
not a harness phase, so it has no log: a line-anchored `module NAME` match
|
||||
over every `.sv`/`.v` under `hw/`, comments stripped, the port list checked
|
||||
for a direction keyword. QA re-derived it independently: 1 310 headers, two
|
||||
apparent non-ANSI hits that are `module NAME #(…);` with **no** port list at
|
||||
all, net zero genuine non-ANSI headers. Read "1 311" as "all of them"; the
|
||||
one-header difference is the two scans' treatment of a macro-wrapped header.
|
||||
|
||||
### 6c. The five new offer sites, offer and resolve
|
||||
|
||||
Lazy client, workspace scope, warm cache, four tries. Each row names a real
|
||||
opentitan position, 0-based.
|
||||
|
||||
| Site | file, position | actions offered | **offer, 0.49.0** | **resolve, 0.49.0** | **0.43.0 offer** |
|
||||
|---|---|---:|---:|---:|---:|
|
||||
| **expand `.*`** — `sha3 #(…) u_sha3 ( .* );` | `hw/ip/kmac/fpv/tb/sha3_fpv.sv` 54:4 | 2 (`expand .* (32 connections)`, `extract`) | **8.2 / 6.2–7.3 ms** | **67.8 / 66.9–67.0 ms**, 1 file | 0 actions, 2.1 / 1.7–1.8 ms |
|
||||
| **organize imports** — 2 imports, 1 unused | `hw/ip/aes/rtl/aes_sbox_canright_masked.sv` 42:2 | 2 (`organize imports (removes 1, sorts 1)`, `extract`) | **30.1 / 13.8–19.5 ms** | **9.6 / 9.6–9.6 ms**, 1 file | 0 actions, 18.5 / 12.7–15.1 ms |
|
||||
| **inline module** — a separate-file instance with named connections | `hw/ip/aes/rtl/aes_wrap.sv` 66:2 (`tlul_cmd_intg_gen u_…`) | 2 (``inline `tlul_cmd_intg_gen` here``, `extract`) | **31.7 / 13.9–19.5 ms** | **0.05 / 0.03–0.04 ms** (a `Command`) | 0 actions, 27.1 / 10.8–16.7 ms |
|
||||
| **extract module** — a 3-item selection | `hw/ip/aes/rtl/aes.sv` 220:0–222:53 (three status `assign`s) | 1 (`extract selection into module…`) | **8.0 / 3.7–5.0 ms** | **0.19 / 0.08–0.13 ms** (a `Command`) | 0 actions, 20.1 / 5.3–7.4 ms |
|
||||
| **port actions** — take 3's cursor | `hw/ip/aes/rtl/aes_wrap.sv` 78:2 | 2 (`connect 2 missing ports`, `extract`) | **28.6 / 23.6–24.4 ms** | **163.9 / 158.2–159.5 ms**, 1 file | 1 action, 20.8 / 18.9–20.2 ms |
|
||||
| **convert to ANSI** — *no site exists* (§6b); an ANSI header instead | `hw/ip/aes/rtl/aes.sv` 8:0 (`module aes`) | 0 | **2.8 / 2.2–2.4 ms** | *n/a* | 0 actions, 5.2 / 3.5–3.9 ms |
|
||||
|
||||
Three things worth stating plainly:
|
||||
|
||||
- **`inline` and `extract` cost nothing to *pick*** — 0.05 and 0.19 ms —
|
||||
because the action carries a `workspace/executeCommand`, not an edit. The
|
||||
work happens when the command runs, which this round does not measure
|
||||
(running it would edit the corpus). The design is deliberate and is
|
||||
documented in `crates/lucisv_server/src/inline_module.rs`'s own header.
|
||||
- **`organize imports` is the opposite shape**: the offer computes the whole
|
||||
edit (30 / 14–19 ms, because judging it means reading the package closure),
|
||||
and the resolve is a cheap re-run at 9.6 ms.
|
||||
- **`expand .*` is `O(connections)` on resolve**: 68 ms for 32 connections,
|
||||
against an 8 ms offer. That is the right split.
|
||||
|
||||
**The port-actions resolve is 1.44× dearer at 0.49.0** (110 → 159 ms) at the
|
||||
one cursor on this corpus that offers it, and the eager one-shot is 1.36×
|
||||
(117 → 160 ms). Filed with §8.2.
|
||||
|
||||
### 6d. `prepareRename`, `rename`, and §49's hierarchical tail
|
||||
|
||||
`prepareRename` remains flat and free — 0.12–0.91 ms at 0.49.0, 0.13–0.15 at
|
||||
0.43.0 — with the byte-identical answer take 2 pinned
|
||||
(`{"placeholder":"aes","range":{"start":{"line":44,"character":2},"end":{"line":44,"character":5}}}`).
|
||||
|
||||
`rename` on `aes` is **165.1 / 133.5–139.4 ms at 0.49.0** against
|
||||
**159.8 / 133.2–136.2 at 0.43.0**, both editing **9 files** — flat, and level
|
||||
with take 3's 151.8 / 139.1–140.7.
|
||||
|
||||
**The tail rename is the round's one large regression, and it is a regression
|
||||
that buys a correctness fix.** §49 gave a module a second, *hierarchical*
|
||||
member surface — its nets, variables and instances, not only its ports — so a
|
||||
rename can follow `u_x.sig` across a file boundary.
|
||||
|
||||
| | **0.43.0** | **0.49.0** |
|
||||
|---|---:|---:|
|
||||
| `rename` `state_q` at `hw/ip/entropy_src/rtl/entropy_src_main_sm.sv` 41:19 | **88.0 / 65.8–66.7 ms** | **793.2 / 750.7–751.9 ms** |
|
||||
| files edited | **1** (`entropy_src_main_sm.sv`) | **2** (+ `entropy_src_core.sv`) |
|
||||
| the tail `u_entropy_src_main_sm.state_q` | **not edited**, warned about | **edited** |
|
||||
|
||||
**11.3× for one extra edited file.** The rename is user-initiated and rare, so
|
||||
this is a low-severity finding — but it is 0.75 s of a frozen single-threaded
|
||||
queue on a keystroke-shaped gesture (F2, type, Enter), and everything queued
|
||||
behind it pays the same. Filed as §8.3.
|
||||
|
||||
**Two tails on this corpus do *not* resolve**, and both are worth recording so
|
||||
nobody re-derives them as bugs:
|
||||
|
||||
- `hw/top_earlgrey/ip_autogen/pwrmgr/rtl/pwrmgr.sv` 178:10,
|
||||
`u_fsm.state_q` — inside a `` ` ``-macro assertion argument. The rename
|
||||
edits `pwrmgr_fsm.sv` alone.
|
||||
- `hw/top_earlgrey/ip_autogen/pinmux/rtl/pinmux.sv` 687:40, `u_reg.intg_err` —
|
||||
likewise not edited, and `completion` after `u_reg.` there returns 0 items.
|
||||
|
||||
§49's own README rules a *generate-block-scoped* tail an honest refusal; these
|
||||
two are a different shape and are filed as §8.5 for a future round to classify.
|
||||
|
||||
### 6e. `completion`, the instance-head tail, `moduleHierarchy`, the index
|
||||
|
||||
**`completion` did not move.** Every prefix is within 0.6 ms of 0.43.0 and
|
||||
every one returns the same item count:
|
||||
|
||||
| Typed prefix | items | **0.43.0** | **0.49.0** | T3 0.43.0 |
|
||||
|---|---:|---:|---:|---:|
|
||||
| `` (empty) | 512 | 7.8 / 4.2–5.4 ms | **7.2 / 4.2–5.3 ms** | 9.5 / 2.3–2.8 |
|
||||
| `a` | 512 | 4.4 / 3.1–3.3 | **4.5 / 3.1–3.3** | 3.2 / 2.5–2.7 |
|
||||
| `ae` | 512 | 3.5 / 2.6–2.7 | **3.6 / 2.7–2.9** | 4.0 / 2.6–2.9 |
|
||||
| `aes` | 512 | 8.6 / 6.8–7.4 | **9.1 / 7.0–8.2** | 10.4 / 7.8–9.2 |
|
||||
| `aes_` | 512 | 6.8 / 6.2–6.4 | **7.1 / 6.7–6.9** | 7.5 / 6.8–8.2 |
|
||||
| `prim_` | 512 | 4.2 / 3.4–3.6 | **4.1 / 3.6–3.8** | 5.1 / 4.0–4.4 |
|
||||
| `clk` | 512 | 3.9 / 3.3–3.3 | **4.2 / 3.3–3.5** | 4.4 / 3.3–3.9 |
|
||||
| `aes_reg` | 512 | 3.2 / 2.6–2.8 | **3.3 / 2.7–2.9** | 3.8 / 2.9–3.0 |
|
||||
| `zzzz` | 1 | 1.2 / 0.29–0.31 | **1.2 / 0.31–0.35** | 1.4 / 0.31–0.34 |
|
||||
|
||||
**Completion after an instance head and a `.`** — §49's other surface, at
|
||||
`hw/ip/entropy_src/rtl/entropy_src_core.sv` 3091:29
|
||||
(`u_entropy_src_main_sm.`):
|
||||
|
||||
| | **0.43.0** | **0.49.0** |
|
||||
|---|---:|---:|
|
||||
| round trip | 1.72 / 0.52–0.66 ms | **1.11 / 0.45–0.53 ms** |
|
||||
| items | **24** | **26** |
|
||||
|
||||
**Two more members for no time at all** — the hierarchical surface arrives
|
||||
free on this path, which is the shape §49 wanted and the opposite of the
|
||||
rename row above.
|
||||
|
||||
**`lucisv/moduleHierarchy`** — the flat snapshot the VS Code DUT sidebar
|
||||
consumes (`params: {}`; the sections are client-side and not measured here):
|
||||
|
||||
| | **0.43.0** | **0.49.0** |
|
||||
|---|---:|---:|
|
||||
| round trip | 70.3 / 41.0–48.8 ms | **76.2 / 41.1–53.8 ms** |
|
||||
| payload | 2 600 051 B | **2 600 051 B** — byte-identical |
|
||||
| content | 1 546 modules over 1 529 files, `schemaVersion` 2 | same |
|
||||
|
||||
Unchanged, and the payload is 2.6 MB — the compaction its own module
|
||||
documents (11.6 MB → 1.9 MB) is holding. It is sent on demand, not on every
|
||||
save, so 40–76 ms is a fair price; it is also the single largest message this
|
||||
server writes, and it blocks the queue for that whole time (§3's rule).
|
||||
|
||||
**The index's size, on disk and resident.** `FACTS_FORMAT` 18 → 19 added the
|
||||
hierarchical member table and the re-export group:
|
||||
|
||||
| | **0.43.0** | **0.49.0** | change |
|
||||
|---|---:|---:|---:|
|
||||
| index store on disk, after a workspace scan | **39 940 KB** (39.0 MB) | **45 404 KB** (44.3 MB) | **+13.7%** |
|
||||
| server RSS after a **cold** workspace scan (3 tries) | 479 520 / 483 056 / 481 936 KB | **544 800 / 539 392 / 542 736 KB** | **+12.6%** |
|
||||
| server RSS after a **warm** workspace scan (3 tries) | 512 544 / 512 400 / 501 872 KB | **581 072 / 588 608 / 587 264 KB** | **+15.1%** |
|
||||
|
||||
**+13.7% on disk and +12.6/+15.1% resident, which is a proportionate price** for what §49 and §48
|
||||
bought — a 3 976-file design costs the editor 530–590 MB resident and 44 MB on
|
||||
disk. Worth a glance next round rather than a finding: the disk and the
|
||||
resident set moved by the same fraction, so this is the index growing, not a
|
||||
leak. Also worth knowing: **a warm scan holds more than a cold one on both
|
||||
binaries** — 27 MB more at 0.43.0, 42 MB more at 0.49.0 — because the store
|
||||
is read into memory as well as built.
|
||||
|
||||
---
|
||||
|
||||
## 7. The CLI sweeps
|
||||
|
||||
`format --check` and `check` over five trees, three binaries, three tries each,
|
||||
wall clock and peak RSS from `/usr/bin/time -l`, everything under
|
||||
`tools/guard.sh`. The formatter cache lives in a scratch `--cache-dir` outside
|
||||
the corpus. File counts: `hw/ip` 1 807, `hw/top_earlgrey/ip` 46,
|
||||
`hw/top_darjeeling/ip` 49, `hw/dv` 365, `hw/vendor` 287 — unchanged from
|
||||
take 3.
|
||||
|
||||
| Tree | command | **0.49.0** | **0.43.0** | 0.39.0 | peak RSS, 0.49 → 0.43 → 0.39 (MB) |
|
||||
|---|---|---:|---:|---:|---:|
|
||||
| `hw/ip` | `format --check`, cold cache | 0.60 / 0.64–0.67 | 0.64 / 0.60–0.64 | 0.60 / 0.60–0.62 | 216 → 237 → 238 |
|
||||
| `hw/ip` | `format --check`, warm cache | 0.60 / 0.62–0.63 | 0.58 / 0.60–0.63 | 0.63 / 0.56–0.57 | 217 → 214 → 228 |
|
||||
| `hw/ip` | `check` (default rules) | 0.37 / 0.38–0.40 | 0.41 / 0.38–0.41 | 0.34 / 0.35 | 190 → 176 → 186 |
|
||||
| `hw/ip` | `check --select error,warning,style` | **0.57 / 0.58–0.60** | 0.45 / 0.44–0.47 | 0.40 / 0.40–0.41 | 212 → 175 → 190 |
|
||||
| `hw/top_earlgrey/ip` | `format --check`, cold / warm | 0.04 / 0.04 | 0.04 / 0.04 | 0.03 / 0.04 | 34 → 32 → 31 |
|
||||
| `hw/top_earlgrey/ip` | `check` / `--select …` | 0.03 / 0.04 | 0.02 / 0.03 | 0.03 / 0.03 | 33 → 38 → 30 |
|
||||
| `hw/top_darjeeling/ip` | `format --check`, cold / warm | 0.04 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 22 → 22 → 24 |
|
||||
| `hw/top_darjeeling/ip` | `check` / `--select …` | 0.02 / 0.03 | 0.02 / 0.02 | 0.02 / 0.03 | 27 → 27 → 26 |
|
||||
| `hw/dv` | `format --check`, cold / warm | 0.07 / 0.07 | 0.07 / 0.07 | 0.06 / 0.06 | 27 → 27 → 29 |
|
||||
| `hw/dv` | `check` / `--select …` | 0.05 / 0.08 | 0.06 / 0.07 | 0.05 / 0.06 | 30 → 33 → 31 |
|
||||
| `hw/vendor` | `format --check`, cold / warm | 0.10 / 0.10 | 0.12 / 0.09 | 0.10 / 0.10 | 45 → 44 → 44 |
|
||||
| `hw/vendor` | `check` / `--select …` | 0.08 / 0.11 | 0.08 / 0.09 | 0.07 / 0.09 | 53 → 50 → 48 |
|
||||
|
||||
- **`format --check` did not move at all.** Every cell on every tree is inside
|
||||
the three binaries' own spread. The biggest tree, 1 807 files, is checked
|
||||
for formatting in 0.6 s on ten cores at ~220 MB, exactly as in take 3.
|
||||
- **`check --select error,warning,style` is 1.27× slower than 0.43.0 on
|
||||
`hw/ip`** (0.45 → 0.57 s), 1.22× on `hw/vendor` (0.09 → 0.11) and 1.14× on
|
||||
`hw/dv` (0.07 → 0.08). **Most of this is more work, not slower work**:
|
||||
0.49.0 runs the new `unused-import` rule (0.48.0, §52's shared judgement)
|
||||
and finds 17 more violations on `hw/ip`. §8.4 files what is left.
|
||||
- **`check` with default rules did *not* slow down** (0.41 → 0.37 s on
|
||||
`hw/ip`), which is the same reading from the other side: `unused-import` is
|
||||
Style and off by default, so the default rule set is untouched. Take 3's
|
||||
§8.5 ("`check` is 6–10% slower than 0.39.0") therefore **stops
|
||||
accumulating** on the default path: 0.34–0.35 s at 0.39.0, 0.38–0.41 at
|
||||
0.43.0, 0.37–0.40 at 0.49.0.
|
||||
- **The formatter cache still buys nothing on opentitan**, and for the reason
|
||||
take 3 gave: it remembers already-formatted files, and opentitan has 30 of
|
||||
1 807 in `hw/ip`, 3 of 365 in `hw/dv`, 12 of 287 in `hw/vendor`. The cold
|
||||
and warm rows are within noise everywhere.
|
||||
- **Peak RSS scales with the tree, not the version.** 22–53 MB for the four
|
||||
small trees, 175–238 MB for `hw/ip`; no version is consistently above
|
||||
another and the ordering flips between rows, so nothing is claimed.
|
||||
|
||||
### 7a. Failure counts, and every per-file outcome that changed
|
||||
|
||||
`format --check --no-cache`, `check` and `check --select error,warning,style`,
|
||||
full runs, all three binaries, paths made relative and sorted so two runs
|
||||
differ only where an *outcome* did.
|
||||
|
||||
| Tree | 0.39.0 `format --check` | 0.43.0 | **0.49.0** |
|
||||
|---|---|---|---|
|
||||
| `hw/ip` | 1773 would reformat, 30 unchanged, 4 failed | 1772, 30, 4 | **1772, 30, 4** |
|
||||
| `hw/top_earlgrey/ip` | 46 would reformat | 46 | **46** |
|
||||
| `hw/top_darjeeling/ip` | 48 would reformat, 1 failed | 48, 1 | **48, 1** |
|
||||
| `hw/dv` | 361, 3 unchanged, 1 failed | 362, 3, 0 | **362, 3, 0** |
|
||||
| `hw/vendor` | 270, 12 unchanged, 5 failed | 271, 12, 4 | **271, 12, 4** |
|
||||
|
||||
**`format --check --no-cache` is byte-identical between 0.43.0 and 0.49.0 on
|
||||
all five trees** — not one per-file verdict changed, and not one parse error
|
||||
appeared or disappeared. §54's grammar additions (`randsequence`, `->>`,
|
||||
casts, drive strengths, `let`, clocking skews) were the expected candidates;
|
||||
**none of them changes an outcome on this corpus**, because none of those
|
||||
shapes appears in a file that lucisv did not already handle. §38's fixes stay
|
||||
fixed.
|
||||
|
||||
**`check` with default rules is byte-identical too** — `hw/ip` 445,
|
||||
`hw/top_earlgrey/ip` 14, `hw/top_darjeeling/ip` 23, `hw/dv` 85, `hw/vendor`
|
||||
231 + 1 file that cannot be checked, at both 0.43.0 and 0.49.0.
|
||||
|
||||
**`check --select error,warning,style` changed in exactly one way: 20 new
|
||||
`unused-import` findings, and nothing else.**
|
||||
|
||||
| Tree | 0.43.0 | **0.49.0** | delta |
|
||||
|---|---:|---:|---:|
|
||||
| `hw/ip` | 7 734 | **7 751** | +17 |
|
||||
| `hw/top_earlgrey/ip` | 551 | **553** | +2 |
|
||||
| `hw/top_darjeeling/ip` | 382 | **383** | +1 |
|
||||
| `hw/dv` | 1 158 | **1 158** | 0 |
|
||||
| `hw/vendor` | 1 666 | **1 666** | 0 |
|
||||
|
||||
Every one of the 20 is a line of the form
|
||||
``<file>:<line>:<col>: style: `pkg::*` is imported but nothing in this scope
|
||||
uses it [unused-import]``, and **no violation disappeared**. `unused-import`
|
||||
is the rule 0.48.0 added out of organize-imports' judgement (CHANGELOG 0.48.0:
|
||||
"Style, off by default, safe fix"), which is why the default rule set is
|
||||
untouched. **The outcome diff is fully explained; there is no unexplained
|
||||
change on any tree, for any command, at any rule set.**
|
||||
|
||||
The files that still fail to parse, unchanged from take 3 apart from the two
|
||||
0.42/0.43 fixes it recorded:
|
||||
`hw/ip/edn/dv/env/edn_env_cfg.sv`, `hw/ip/kmac/fpv/tb/keccak_2share_fpv.sv`,
|
||||
`hw/ip/kmac/pre_dv/kmac_reduced_tb/rtl/kmac_reduced_tb.sv`,
|
||||
`hw/ip/spi_device/dv/env/spi_device_scoreboard.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv` (a locally modified file),
|
||||
`hw/vendor/lowrisc_ibex/dv/formal/check/peek/compare_helper.sv`,
|
||||
`hw/vendor/lowrisc_ibex/dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.tpl.sv`
|
||||
(a template, not SystemVerilog),
|
||||
`hw/vendor/lowrisc_ibex/syn/rtl/latch_map.v`,
|
||||
`hw/vendor/lowrisc_ibex/vendor/google_riscv-dv/src/riscv_instr_cover_group.sv`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Findings — filed, not fixed
|
||||
|
||||
Ordered by how much they matter. Nothing here was fixed in this round.
|
||||
|
||||
### 8.1 CREDIT, not a finding — what got faster
|
||||
|
||||
Stated first so the rest reads in proportion.
|
||||
|
||||
| What | 0.43.0 | **0.49.0** | Credit |
|
||||
|---|---:|---:|---|
|
||||
| `didOpen` of opentitan's largest file → the next request | 1 605 / 1 604–1 611 ms | **112 / 128–131 ms** | **§46** (0.44.0) — **14×** |
|
||||
| `didOpen spi_device.sv` → the next request | 98.7 / 75.2–99.5 ms | **15.5 / 13.8–15.1 ms** | **§46** — 6× |
|
||||
| `didOpen aes_core.sv` → the next request | 42.6 / 63.0–63.1 ms | **11.0 / 4.0–10.4 ms** | **§46** — 7× |
|
||||
| A `didOpen` of a file already in scope, default scope (take 3's §8.4) | 33–69 ms | **5–21 ms** | **§46** — 3–5×; **take 3's §8.4 is closed** |
|
||||
| `rename` through an instance tail | 1 file, tail unedited | **2 files, tail edited** | **§49** — correctness, at a cost (§8.3) |
|
||||
| `completion` after an instance head + `.` | 24 items, 1.72 / 0.52–0.66 ms | **26 items, 1.11 / 0.45–0.53 ms** | **§49** — free |
|
||||
| `codeAction` lazy offer at 42 files | 18.1 / 7.4–9.4 ms | **7.0 / 6.0–6.2 ms** | unattributed; §37.1's shape holding |
|
||||
|
||||
**§46 closes take 3's §8.4 outright**, and it is the largest improvement any
|
||||
of the four rounds has measured on a per-keystroke path.
|
||||
|
||||
### 8.2 FINDING (medium) — the lazy `codeAction` offer costs 2–3 ms more at every cursor, offered or not
|
||||
|
||||
**What.** For a resolving client — the majority since 0.41.0, and what VS Code
|
||||
sends — `textDocument/codeAction` costs 2–5 ms more at 0.49.0 than at 0.43.0
|
||||
at the *small* cursors, including cursors where nothing is offered:
|
||||
|
||||
| cursor | 0.43.0 repeats | **0.49.0 repeats** | factor |
|
||||
|---|---:|---:|---:|
|
||||
| a plain comment line (0 actions on both) | 1.12 – 1.32 ms | **3.18 – 3.84 ms** | **2.9×** |
|
||||
| `aes` in `tb.sv` (1 action at 0.49, 0 at 0.43) | 4.0 – 4.9 ms | **7.9 – 9.8 ms** | 2.0× |
|
||||
| `aes_reg_top` in `aes.sv` (2 actions at 0.49, 0 at 0.43) | 14.2 – 15.2 ms | **21.8 – 23.5 ms** | 1.5× |
|
||||
| pipelined `definition` behind the `aes` codeAction (§3) | 3.3 – 7.3 ms | **11.2 – 15.9 ms** | 2.2× |
|
||||
|
||||
**Why it matters.** `codeAction` fires on every cursor move, and every request
|
||||
behind it in the serial queue pays its bill (§3). At 0.43.0 a cursor move cost
|
||||
the queue 3–7 ms; at 0.49.0 it costs 11–16 ms. Still inside a 16 ms frame, but
|
||||
the margin is gone, and this is a request the user never asked for.
|
||||
|
||||
**The mechanism, as far as this round can see it without bisecting.** The
|
||||
comment-line row is the cleanest evidence: **zero** actions are offered on
|
||||
either binary, so the extra 2 ms is not the cost of producing an offer. It is
|
||||
the cost of the new offers' *gates* — `vlog_refactor::inline_site` and
|
||||
`extract_site` each run a tolerant parse of the cursor's buffer
|
||||
(`crates/vlog_refactor/src/inline/mod.rs:73`,
|
||||
`crates/lucisv_server/src/inline_module.rs:50`) — asked on every cursor move.
|
||||
Not bisected; candidates are §52, §53.1 and §53.2, which are the three that
|
||||
added a gate.
|
||||
|
||||
**Reproduce.** `bench.py codeaction`, then read the `comment line, lazy` rows
|
||||
for the two labels; or `bench.py probe --probe hw/ip/aes/dv/tb/tb.sv:43:2`.
|
||||
Workspace scope, warm store, `tb.sv` open, four tries. The `--verbose`
|
||||
server's own line agrees with the wire to 0.5 ms (§0), so this is server work.
|
||||
|
||||
**A cheap direction, if a future round wants one:** the two gates parse the
|
||||
same buffer the server already has parsed for diagnostics and symbols. Take 3
|
||||
made the same observation about the port offer, and §37.1's answer — do not
|
||||
compute what nobody asked for — is the shape that worked.
|
||||
|
||||
### 8.2b REPORTED, not filed — the eager `codeAction` path is ~2× dearer
|
||||
|
||||
The eager path (a client without
|
||||
`codeAction.resolveSupport.properties: ["edit"]` — Vim/Neovim setups and
|
||||
simple clients) is **1.95–2.07× slower at 0.49.0 than 0.43.0** at every
|
||||
fan-out above 1: 46 → 90 ms at 6 files, 125 → 255 at 42, 192 → 368 at 67,
|
||||
243 → 473 at 128 (§6a). Take 3 filed the earlier 1.37× step as its §8.2; **the
|
||||
owner ruled the eager path a non-hot path on 2026-09-05**, so take 4 reports
|
||||
the number and does not re-file it. Two facts for whoever reads it next: it
|
||||
now crosses half a second at the largest fan-out, and the resolve at the one
|
||||
offering cursor moved with it (110 → 159 ms, §6c), which the *lazy* client
|
||||
pays too — but only on a click.
|
||||
|
||||
### 8.3 FINDING (low–medium) — §49's tail rename is 11× a same-file rename
|
||||
|
||||
**What.** Renaming a variable that a hierarchical tail names from another file
|
||||
costs **793.2 / 750.7–751.9 ms at 0.49.0** against **88.0 / 65.8–66.7 ms at
|
||||
0.43.0**, for one extra edited file.
|
||||
|
||||
**Reproduce.** `bench.py tailrename`. `textDocument/rename` on `state_q` at
|
||||
`hw/ip/entropy_src/rtl/entropy_src_main_sm.sv` 0-based 41:19, newName
|
||||
anything, workspace scope, warm store, with
|
||||
`hw/ip/entropy_src/rtl/entropy_src_core.sv` also open. 0.43.0 returns 1 file
|
||||
and warns about the tail; 0.49.0 returns 2 files and edits it. The edits are
|
||||
discarded.
|
||||
|
||||
**Why it is filed and not credited.** The correctness is unambiguously right —
|
||||
§49's whole point is that the old answer handed back a design that no longer
|
||||
elaborates — and a rename is user-initiated and rare. But 0.75 s freezes the
|
||||
single-threaded queue for three quarters of a second on an F2-shaped gesture,
|
||||
and everything behind it waits (§3). Compare the ordinary `rename` on `aes`,
|
||||
which edits **nine** files in 133–139 ms: the tail rename edits **two** in
|
||||
751 ms, so this is not "more files", it is a different and much more expensive
|
||||
lookup. `completion` on the same surface is *free* (§6e), which suggests the
|
||||
cost is in rename's reference walk rather than in the surface itself.
|
||||
|
||||
**Not bisected.** The candidate is §49's hierarchical member walk in
|
||||
`workspace/record.rs` / `resolve.rs::head_surface`.
|
||||
|
||||
### 8.4 FINDING (low) — `check --select error,warning,style` is 1.27× slower, beyond the new rule's own work
|
||||
|
||||
`hw/ip`: 0.45 → 0.57 s (mean of three); `hw/vendor` 0.09 → 0.11;
|
||||
`hw/dv` 0.07 → 0.08. 0.49.0 does find 20 more violations (§7a), all from
|
||||
0.48.0's `unused-import`, so **some** of this is honest extra work — but 20
|
||||
extra findings across 2 554 files is not obviously 120 ms of work on `hw/ip`,
|
||||
and `check` with the *default* rules did not move at all (0.41 → 0.37 s), so
|
||||
the whole difference sits in the Style class. Take 3's §8.5 asked whether its
|
||||
6–10% would keep accumulating; on the default path the answer is **no**, and
|
||||
on the Style path it is **yes, once, when a rule was added**. Not bisected.
|
||||
120 ms on the largest tree in opentitan is not a user-visible cost; filed so
|
||||
the next round can see whether adding the *next* Style rule costs the same
|
||||
again.
|
||||
|
||||
**Reproduce.** `tools/perf/sweep.sh <binary> <label> <opentitan> <outdir> 3`,
|
||||
then `sweeptable.py <outdir>`; read the `hw/ip` / `check --select …` row.
|
||||
|
||||
### 8.5 FINDING (low) — two hierarchical tails on this corpus do not resolve
|
||||
|
||||
`hw/top_earlgrey/ip_autogen/pwrmgr/rtl/pwrmgr.sv` 178:10 (`u_fsm.state_q`,
|
||||
inside a `` ` ``-macro assertion argument) and
|
||||
`hw/top_earlgrey/ip_autogen/pinmux/rtl/pinmux.sv` 687:40 (`u_reg.intg_err`)
|
||||
are both instance-head tails whose head is instantiated in the same file and
|
||||
whose target is declared in another. Neither is edited by a rename at
|
||||
0.49.0, and `completion` after `u_reg.` at the second returns **0 items**.
|
||||
§49's README rules a *generate-block-scoped* tail an honest refusal and pins
|
||||
it with a test; neither of these is that shape. This is filed as a question,
|
||||
not an assertion of a defect: a future round (or §49's author) should say
|
||||
which of the two rules applies, so the refusal is documented rather than
|
||||
observed.
|
||||
|
||||
**Reproduce.** `bench.py probe` is for `codeAction`; for these, issue
|
||||
`textDocument/rename` at the declaration
|
||||
(`pwrmgr_fsm.sv` 109:28 for the first) with both files open at workspace
|
||||
scope, and read the edit set.
|
||||
|
||||
### 8.6 WATCH — the index is 14% bigger, on disk and resident
|
||||
|
||||
39.0 → 44.3 MB on disk, 482 → 542 MB resident cold (+12.6%), 509 → 586 MB warm (+15.1%) (§6e).
|
||||
Proportionate to what `FACTS_FORMAT` 18 → 19 added and consistent across the
|
||||
two measures, so not a leak. Recorded because half a gigabyte is what an
|
||||
editor session on this design now holds, and because a fifth round should see
|
||||
whether the next format bump costs another 14%.
|
||||
|
||||
### 8.7 STILL SLOW — the cold workspace scan at ~2.7 s
|
||||
|
||||
2 640–2 712 ms across both binaries, essentially unmoved across four takes
|
||||
(3 003 → 2 958 → 2 767 → 2 676 mean) and still the largest absolute number in
|
||||
the document. Once per session per cold cache; never any round's target.
|
||||
|
||||
### 8.8 CLOSED — take 3's findings, one by one
|
||||
|
||||
| Take 3 finding | Status at 0.49.0 |
|
||||
|---|---|
|
||||
| §8.2 eager `codeAction` 1.37× slower than take 2 | **Superseded.** Another 1.95–2.07× on top, but the path was ruled non-hot; reported as §8.2b |
|
||||
| §8.3 `rename` ~1.4× slower in absolute terms | **Still true, still flat.** 133–139 ms at both binaries, 9 files, ~15 ms per edited file |
|
||||
| §8.4 `didOpen` of an in-scope file delays the next request 21–51 ms | **CLOSED — fixed by §46**, measured in the release build at §5c |
|
||||
| §8.5 `check` 6–10% slower than 0.39.0 | **Partly closed.** Default rules stopped accumulating (§7); the Style class took one more step when a rule was added (§8.4) |
|
||||
| §8.6 `workspace/symbol` keeps drifting up | **Not readable this round.** 8.7–12.7 ms at 0.49.0 and 8.2–13.3 at 0.43.0 — the two binaries' bands overlap almost entirely, and both are above take 3's 7.2–7.9 on a busier machine. No conclusion |
|
||||
| §8.7 the port refactorings are offered at 1 of 205 RTL files | **Still 1 of 205 for the *port* refactorings** — the same `aes_wrap.sv` 78:2. But §6b's census now finds `extract` at 89% of positions and `inline` at 11%, so "the lightbulb is almost never lit" is no longer the corpus's shape |
|
||||
| §8.8 the cold workspace scan at ~2.8 s | **Unchanged.** §8.7 above |
|
||||
|
||||
### 8.9 Movements inside the noise, listed and dismissed
|
||||
|
||||
Every sub-millisecond navigation row: `definition` (0.87 → 0.47 first),
|
||||
`hover` (0.26 → 0.86), `typeDefinition` (0.46 → 0.67), `documentHighlight`
|
||||
(0.19 → 0.61), `foldingRange` (0.44 → 0.73), `codeLens` (0.47 → 0.23),
|
||||
`documentLink` (0.49 → 1.09), `selectionRange` (0.95 → 1.79),
|
||||
`semanticTokens/full` (1.03 → 0.39), `documentSymbol` (0.69 → 0.61),
|
||||
`diagnostic` (1.02 → 0.93), `prepareRename` (0.37 → 0.71), the `didChange`
|
||||
flush (2.32 → 1.79), `inlayHint` (1.90 → 2.04), `references` on `aes`
|
||||
(2.80 → 0.92) and on `.clk_i` (1.54 → 1.65), `signatureHelp` (2.49 → 3.06),
|
||||
`workspace/symbol` (both bands overlapping), the diagnostics publish
|
||||
(164.0 → 164.5), and every `scan` cell.
|
||||
|
||||
**Every one of these sits on a transport floor that measured 0.04–0.17 ms on
|
||||
one binary and 0.09–0.63 ms on the other, minutes apart, on the same machine
|
||||
(§0).** They move in both directions with no pattern, their result counts are
|
||||
identical on both binaries (§4b), and take 3 measured the *same* 0.43.0 binary
|
||||
at a third set of values. **No conclusion should be drawn from any of them.**
|
||||
|
||||
---
|
||||
|
||||
## 9. Methodology and caveats — read before quoting any number
|
||||
|
||||
Take 1's, take 2's and take 3's caveats still apply. The take-4-specific ones:
|
||||
|
||||
- **Three tries per row, first try and repeat range both reported.** "First"
|
||||
is the request issued as the first real request of a dedicated session,
|
||||
after the scan settled; "repeats" is the 2nd–4th identical request in that
|
||||
same session. Where a row needed its own session (`codeAction`, `rename`,
|
||||
the tail rename, each fan-out cursor, each scope/cache cell, each widen
|
||||
cell) it got one — and where a phase is a once-per-session event (the scan,
|
||||
the widen, the `didOpen` delay, RSS) each try is a **fresh server process**.
|
||||
- **The comparison is binary-to-binary, on one night, with one client.**
|
||||
0.49.0 is the tree's own `target/release/lucisv-server` at `4c2dae3`,
|
||||
verified current against the last change under `crates/` — **no `cargo
|
||||
build` ran for it**. 0.43.0 was built for this round from the `v0.43.0` tag
|
||||
in a scratch `git worktree` under the scratchpad, and the worktree was
|
||||
removed before this document was finished. The main tree was never checked
|
||||
out, reset or stashed.
|
||||
- **Machine state, and it is the biggest caveat in this document.** Apple M1
|
||||
Max, 10 cores, 64 GB, macOS 27.0 (26A5425a). **This machine runs a live
|
||||
desktop session**, and throughout the round WindowServer sat at 45–51% of a
|
||||
core, loginwindow at 24–29%, with a wallpaper extension and two consumer
|
||||
apps at 8–11% each. **Load average was 3.7–7.1** for every phase; take 3
|
||||
measured at 2–4. Nothing unrelated to the desktop was burning CPU — no
|
||||
`rustc`, no build, no other agent — so the round proceeded rather than
|
||||
waiting, and the mitigation is structural: **both binaries were measured in
|
||||
the same window, alternating within the hour, with the same client.** Every
|
||||
comparison in §2–§7 is 0.49.0 against tonight's 0.43.0; take 3's column is
|
||||
context, never a conclusion. The load average was recorded before and after
|
||||
every phase.
|
||||
- **No `cargo` command ran in any tree while a timed measurement was
|
||||
running.** The one `cargo build` (the 0.43.0 worktree) finished 20 minutes
|
||||
before the first timed run.
|
||||
- **The guard.** Every server session, every `lucisv` invocation and the one
|
||||
`cargo build` went through `tools/guard.sh -m 8 -t 1800`. **No guard kill
|
||||
occurred**, and the largest resident set anything reached was 588 MB
|
||||
(`lucisv-server` after a warm workspace scan), 7% of the 8 GB limit; the
|
||||
largest a CLI run reached was 238 MB.
|
||||
- **The opentitan checkout was never written.**
|
||||
`git -C /Users/guoliangchen/repo/opentitan status --porcelain` was checked
|
||||
after every phase and reported the same three pre-existing modified files
|
||||
throughout: `hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`.
|
||||
`rename`, `codeAction/resolve` and the refactoring resolves all return
|
||||
edits; the client discarded every one. The formatter cache was directed to a
|
||||
scratch `--cache-dir` and the index cache to a scratch
|
||||
`initializationOptions.storagePath`; neither default lands inside the corpus,
|
||||
and both were overridden anyway.
|
||||
- **Tolerances.** Sub-millisecond rows: **±0.5 ms**, and nothing under that is
|
||||
read (§0 measured a 0.04→0.63 ms floor swing between two sessions of the
|
||||
same client). Rows of 1–20 ms: **±20%**. Rows of 20–500 ms: **±10%**.
|
||||
Multi-second rows: **±5%** (the six warm workspace scans span 118 ms across
|
||||
two binaries, 10%; the six cold ones span 72 ms, 2.7%). Take 3's tolerances
|
||||
were tighter on every band because its machine was quieter; a number here
|
||||
that differs from take 3's by less than these bands has not moved.
|
||||
- **Item and result counts are reported beside every timing** where the answer
|
||||
could have changed size, and every one of them is identical on the two
|
||||
binaries except the two the document names (`completion` after an instance
|
||||
head: 24 → 26 items; the tail rename: 1 → 2 files).
|
||||
- **The fan-out counts in §6a are `grep`-derived**
|
||||
(`grep -rlE '^\s*<module>( |#|$)'` over `*.sv`), reproducing take 2's and
|
||||
take 3's counts exactly (1 / 6 / 42 / 67 / 128).
|
||||
- **The offer sites in §6b/§6c were found, not chosen.** Every position was
|
||||
discovered by sweeping `codeAction` over candidate lines and keeping what
|
||||
actually offered; the two sites this document reports as *not* offering
|
||||
(§8.5) are the two candidates that failed, kept rather than dropped.
|
||||
- **`--select error,warning,style` is not "all rules"** — it is the three rule
|
||||
classes by name, which is what §58 asked for.
|
||||
- **Page cache is hot and hotter than ever** — opentitan has now been walked
|
||||
by four measurement rounds plus tonight's outcome sweeps. "Cold cache"
|
||||
means *lucisv's* store was deleted, not that the OS file cache was dropped.
|
||||
- **No code in the lucisv repo was modified for this round** except the
|
||||
creation of `tools/perf/`, this file,
|
||||
`docs/features/performance-take4/README.md`, the `docs/perf/README.md`
|
||||
entry and §58's ticks in `TODO.md`. No Rust source was touched.
|
||||
|
||||
---
|
||||
|
||||
## 10. Raw logs, and where the harness lives
|
||||
|
||||
**The harness is committed**: `tools/perf/` — `lspclient.py`, `sites.py`,
|
||||
`harness.py`, `bench.py`, `phases_new.py`, `sweep.sh`, `sweeptable.py`,
|
||||
`outcomes.sh`, `README.md`. Python 3 standard library only; runs from a clean
|
||||
checkout given an opentitan path and the binaries. `tools/perf/README.md` says
|
||||
how to run each phase. **Take 5 reuses it rather than reimplementing it from
|
||||
this document's prose.**
|
||||
|
||||
The Python was split after the measurements were taken (`bench.py` had reached
|
||||
537 production lines), so **every phase was re-run through the split files and
|
||||
ten rows re-checked against this document within §9's tolerances** — all
|
||||
inside. That verification run is in the raw logs as `verify.jsonl`, labelled
|
||||
`verify-0.49.0`; the feature README lists the ten rows and both readings.
|
||||
|
||||
The raw measurements are under
|
||||
`…/7b09ba01-…/scratchpad/`, and `results.jsonl` is additionally copied to
|
||||
`~/.cache/lucisv-perf/take4/results.jsonl` so it survives the scratchpad.
|
||||
|
||||
| File | What |
|
||||
|---|---|
|
||||
| `verify.jsonl` | the post-split re-run of every phase, label `verify-0.49.0` (§10 above) |
|
||||
| `results.jsonl` | every LSP row, machine-readable: `phase`, `label`, `row`, `ms` (try list), `n`, `titles`, `note`. **Every LSP number in this document is in this file.** Copy at `~/.cache/lucisv-perf/take4/` |
|
||||
| `logs/lsp-0.49.0.log`, `logs/lsp-0.43.0.log` | the phase transcripts, in order |
|
||||
| `logs/lsp-0.49.0-machine.txt`, `logs/lsp-0.43.0-machine.txt` | `uptime` and the top CPU processes, before and after the LSP phases |
|
||||
| `logs/sweep-machine.txt`, `logs/outcomes-load-{before,after}.txt` | the same for the CLI phases |
|
||||
| `sweep/<label>__<tree>__<command>__<cache>.txt` | §7 — the three tries' `/usr/bin/time -l` blocks per cell, 60 files |
|
||||
| `logs/sweeptable.txt` | §7's rendered table and the summary line each cell reported |
|
||||
| `outcomes/<label>.{format,check,check-select}.txt` | §7a — the per-file outcome listings for all three binaries; the diff in §7a is `diff outcomes/0.43.0.* outcomes/0.49.0.*` |
|
||||
| `logs/census-0.49.0.txt` | §6b — the 205-file, 2 440-position offer census |
|
||||
| `caches/` | the scratch `storagePath` stores and the scratch formatter `--cache-dir`; nothing here is inside the corpus |
|
||||
@@ -0,0 +1,189 @@
|
||||
# Performance take 5 — latest analysis and implementation plan
|
||||
|
||||
**Recommendation: optimize code-action discovery first, then reuse rename/refactoring analysis, then remove CLI package-census duplication.** A newly measured no-offer comment cursor in a generated file blocks navigation for about **300 ms**. The earlier small-file measurements hid this size-dependent cost. Hierarchical rename still costs about **0.8 seconds**. Startup and resident memory remain secondary targets.
|
||||
|
||||
**Status (2026-09-08): implemented as TODO §60 — P0, P1a–c, P2a–c (P2d measured, no narrowing: proof negative), handshake 33, P3, P4a–b; results in `docs/perf/README.md`'s 2026-09-08 entry and the tracker.** This document is the plan as the owner wrote it, kept unedited below; it was not an implementation when written. The implementation agent should fill [the performance tracker](perf/take5-tracking.md). Raw results, exact commands/provenance and the read-only supplemental probes are preserved in [take5-baseline](perf/take5-baseline/README.md).
|
||||
|
||||
## Scope and confidence
|
||||
|
||||
- Measured **0.50.0, local HEAD `bbdbfe9045e8a85f8ea471529ea739af6cade77f`**, on 2026-09-07. “Latest” here means the current checkout; no remote was fetched or changed. `cargo build --release --locked -p lucisv -p lucisv_server` confirmed release artifacts were current before timing.
|
||||
- Same OpenTitan commit as take 4: `00981352642fb65ef2b6c47143a0f6bb31fd4a97`, with the same three pre-existing modified files. All commands treated corpus text as read-only; edits were discarded. Corpus status was unchanged after every standard phase and CLI trial, and after the supplementary probe. End-of-run hashes of modified files are in the provenance record.
|
||||
- Same M1 Max machine described in the previous report, macOS 27.0 build `26A5425a`. Standard-phase one-minute load samples were **2.92–4.59**. No builds overlapped benchmarks. Retained runs used the repository's 8 GiB / 1,800-second guard; an initial sandbox run whose guard could not read process memory was discarded and rerun with the guard operating. No guard kill occurred.
|
||||
- Standard phases: baseline, codeaction, tailrename, blockers, didopen, scan, rss, refactor, rename, flush, diagnostics, completion and nav. Added read-only action-family/large-file probes and a paired CLI experiment on `hw/ip`. Other CLI trees, actual inline/extract command execution, allocation profiles and parser-stage timings were not remeasured.
|
||||
- `git diff v0.49.0..HEAD -- crates/` shows production changes only in CLI format-cache key handling and the core cache. The server/parser/semantic/refactor implementation did not change. Therefore the old **0.49.0 LSP column below is historical context, not a controlled regression comparison**. Small timing movements do not establish a 0.50.0 regression. CLI binaries 0.43.0, 0.49.0 and 0.50.0 were measured in the same experiment with alternating binary order.
|
||||
- Four request samples normally mean first request plus three repeats within one session. Scan and file-open rows use three fresh processes. These small samples support prioritization, not p95/p99 or statistical significance. The supplemental action filters were tested sequentially within each file's session; their timing differences are approximate attribution controls, not a CPU profile.
|
||||
|
||||
## Current measurements and what they imply
|
||||
|
||||
All latencies are milliseconds unless marked otherwise. Warm workspace scope, resolving/lazy client unless stated. Historical values come from [take 4](performance_take4.md), whose results in turn compare [take 3](performance_take3.md).
|
||||
|
||||
| Scenario | 0.49.0 historical first / repeats | 0.50.0 first / repeats | Meaning |
|
||||
|---|---:|---:|---|
|
||||
| No-offer comment, 42,192-line `pinmux_reg_top.sv` | not measured | **328.4 / 296.8–311.7** | Highest-priority newly exposed interactive cost; zero actions |
|
||||
| Definition queued behind that comment action | not measured | **300.7–304.1**, three pipelines | Essentially the whole blocker cost |
|
||||
| `state_q` rename through instance tail | 793.2 / 750.7–751.9 | **821.6 / 789.5–809.8** | Two edited files; heavy user-command path persists |
|
||||
| Eager code action, `prim_flop_2sync` (fan-out 128) | 511.8 / 467.1–473.6 | **518.3 / 495.6–499.7** | Expensive fallback remains; prior owner classified it non-hot |
|
||||
| Lazy `aes_reg_top` offer | 29.8 / 21.8–23.5 | **32.8 / 22.4–25.1** | Local offer work can exceed a frame even at fan-out 1 |
|
||||
| Lazy `aes` offer | 14.2 / 7.9–9.8 | **12.4 / 8.1–9.1** | Still repeated work on a frequent request |
|
||||
| No-offer `tb.sv` comment | 4.7 / 3.2–3.8 | **6.2 / 3.2–3.5** | Small-file version of the same unnecessary work |
|
||||
| Ordinary `aes` rename | 165.1 / 133.5–139.4 | **168.7 / 139.3–140.4** | Nine edited files; not explained by output count alone |
|
||||
| Resolve connect-missing-ports action | 163.9 / 158.2–159.5 | **170.8 / 164.8–165.8** | A click in a lazy client still pays engine work |
|
||||
| Resolve expand `.*`, 32 connections | 67.8 / 66.9–67.0 | **73.0 / 70.4–70.7** | Preserve as collateral-benefit control for refactor reuse |
|
||||
| Workspace scan, cold; three fresh sessions | 2691–2712 | **2830–2853** | Mean 2843.0; old/new difference is not attributable to code |
|
||||
| Workspace scan, warm; three fresh sessions | 1240–1286 | **1322–1344** | Mean 1332.4; cache still leaves substantial work |
|
||||
| `didOpen pinmux_reg_top.sv` → definition; fresh sessions | 112 / 128–131 | **128.1–130.0** | §46's former 1.6-second open cost remains fixed |
|
||||
| `didOpen spi_device.sv` → definition; fresh sessions | 15.5 / 13.8–15.1 | **8.7–13.9** | Preserve the already optimized open path |
|
||||
| `didChange tb.sv` → folding barrier | 1.79 / 0.89–0.97 | **1.05 / 0.65–0.72** | Small-buffer flush is not the bottleneck |
|
||||
| `didChange` → diagnostics publication | 164.5 / 153.5–160.7 | **158.0 / 156.0–157.6** | About 150 ms is intentional debounce |
|
||||
| Unblocked definition on `aes` | 0.47 / 0.13–0.17 | **0.36 / 0.05–0.08** | Navigation itself is cheap |
|
||||
| Unknown-method transport control | 0.63 / 0.09–0.32 | **0.24 / 0.066–0.070** | Cannot explain multi-millisecond or 300 ms blockers |
|
||||
|
||||
Idle RSS after workspace scan is **528.0–530.9 MiB cold** and **566.4–573.8 MiB warm**; allocated index-store size is **44.34 MiB** (`du -sk`). These are consistent with take 4's general half-gigabyte resident footprint, not evidence of a new leak. The RSS phase is an idle `ps` observation, not a peak-memory measurement.
|
||||
|
||||
### New attribution: code-action cost follows buffer size and work requested internally
|
||||
|
||||
The generated file is **1,328,188 bytes**, below the default 4 MiB large-file threshold, so it takes the regular analysis path. These are repeated requests on its initial comment line; **every row returns zero actions**.
|
||||
|
||||
| `context.only` | Repeated latency | Interpretation |
|
||||
|---|---:|---|
|
||||
| Unspecified: all families | **296.8–311.7 ms** | Full no-offer cost |
|
||||
| `[]`: no families | **79.4–81.6 ms** | Unconditional lint/fence/config work survives filtering |
|
||||
| `quickfix` | **79.7–80.1 ms** | Essentially the same base cost |
|
||||
| `refactor.extract` | **134.6–136.2 ms** | Base plus one text-based selector |
|
||||
| `refactor.inline` | **134.7–135.4 ms** | Base plus one text-based selector |
|
||||
| `refactor.rewrite.lucisv.ports` | **134.0–135.5 ms** | Base plus one text-based selector |
|
||||
| `source.organizeImports` | **133.6–135.8 ms** | Base plus one text-based selector |
|
||||
|
||||
The source confirms **five separate full-text parse entry points** on this no-offer path: one in fence protection and one in each of four selectors. The filter experiment is consistent with an approximately 80 ms shared base plus roughly 55 ms per selector. It does **not** split that 80 ms between linting, fence parsing and configuration I/O. That split needs counters/profile data before further optimization.
|
||||
|
||||
Size controls, all no-offer comments: `aes_core.sv` repeats **9.6–11.7 ms**; `spi_device.sv` **13.3–17.1 ms**; the generated pinmux file **296.8–311.7 ms**. This is not workspace fan-out: the cursor offers nothing. Unblocked definition on `aes` takes around 0.05–0.08 ms; pipelining it after the generated-file action takes 300.7–304.1 ms.
|
||||
|
||||
There is a second independent offer cost. At `aes_reg_top u_reg` in `aes.sv`, requesting only the ports family takes **21.6–21.8 ms and returns zero port actions**, while the other family filters take roughly 0.6–1.2 ms including the common base. The lazy port path still builds plans on the buffer/declaration file and discards their edits. Reusing just the four selectors will not necessarily eliminate this cost; P1c covers it.
|
||||
|
||||
### Paired CLI control: the Style difference is largely the new rule's path
|
||||
|
||||
`hw/ip`, identical input, default worker count, three independent invocations per cell. Values are **first / range of trials 2–3 in seconds**. Lint exit status is 1 in every row because findings exist.
|
||||
|
||||
| Configuration | 0.43.0 now | 0.49.0 now | 0.50.0 now | Findings |
|
||||
|---|---:|---:|---:|---:|
|
||||
| Default `check` | 0.42 / 0.39–0.40 | 0.39 / 0.38–0.38 | **0.59 / 0.40–0.40** | 445 on all |
|
||||
| `--select error,warning,style` | 0.46 / 0.45–0.46 | 0.57 / 0.58–0.59 | **0.58 / 0.56–0.58** | 7734 old; 7751 at 0.49/0.50 |
|
||||
| Same selection, `--ignore unused-import` | rule absent; not run | 0.45 / 0.45–0.48 | **0.44 / 0.44–0.47** | 7734 |
|
||||
|
||||
At 0.50.0 the all-style mean is **0.573 s**, versus **0.450 s** with only `unused-import` disabled: **123 ms, about 21.5% of all-style wall time**. That includes both the rule and the package-census work it enables; it is not an isolated rule-body timer. It brings the current binary back near 0.43.0's all-style mean of 0.457 s. This is stronger evidence than inferring cost from the 17 additional findings. Default/all-style/ignored-rule stdout is byte-identical between current 0.49.0 and 0.50.0 controls. The first 0.50.0 default invocation is an outlier, not a basis for a regression claim.
|
||||
|
||||
Current all-style peak RSS is **208.4 MiB**, versus **177.5 MiB** with that rule disabled (maximum of three); treat this as a supporting control, not an allocation profile. Current formatter `--check` with an independently reset cache takes **0.67 / 0.59–0.68 s cold**, **0.69 / 0.61–0.63 s warm**. It reports 1772 would-reformat, 30 unchanged, four failures; warm runs hit only those 30 cached clean files. The cache cannot accelerate the many files requiring formatting. No proposed change should cache unverified output or remove runtime verification to improve this number.
|
||||
|
||||
## Causes and implementation plan
|
||||
|
||||
Priorities below are recommendations for the implementation agent, not changes made by this analysis. Targets are provisional acceptance goals on this machine and corpus; they are not measured savings or CI timing assertions. Complete one stage, measure it, then decide whether its next stage is justified.
|
||||
|
||||
### P0 — Make the performance evidence trustworthy
|
||||
|
||||
**Cause.** The committed harness is useful but some rows do not mean what their names imply. `phases_new.py::phase_refactor` sends `codeAction/resolve` for every action without an `edit`, including command-only extract/inline offers. Dispatch sends those to the ports resolver, which rejects offers without its data. Their tiny times do not measure extraction or inlining. `Session.ms` discards the response, so an error can look like a fast success. `phase_rss` puts idle RSS in a field called `ms`; it is neither latency nor peak memory. `sweep.sh::run_cell` deletes the format cache once before the three “cold” tries, making tries 2–3 warm.
|
||||
|
||||
**Work.** Preserve the existing historical raw rows. Add explicit units, request result/error status, client capability shape, exact result counts and normalized edit/warning fingerprints to new records. Route edit-bearing offers to resolve and command-bearing offers to a separate execute-command scenario. Capture the server's `workspace/applyEdit` payload as the edit-computation boundary without applying it to the corpus. Reply `applied: false` with a benchmark-capture reason; record that intentional client rejection separately from an engine refusal or computation error. Count created files, edits, refusals and warnings; do not benchmark an error as a successful operation. Distinguish scan completion from first-useful-answer latency and distinguish fresh processes from repeated requests. Reset only the dedicated scratch format cache before *each* cold try; explicitly prime warm rows.
|
||||
|
||||
**Files and contracts.** `tools/perf/{bench.py,phases_new.py,lspclient.py,harness.py,sweep.sh,sweeptable.py,README.md}`. Keep old log readers compatible or version the schema. No production change is needed. Preserve request framing and exact result validation. Record guard failures as failures.
|
||||
|
||||
**Acceptance.** A deliberately rejected request is recorded as an error. Inline/extract execution rows demonstrably observe a command and an apply-edit payload, or an expected refusal. Cold formatter rows have zero cache hits independently. RSS and peak RSS use separate fields with explicit units. Reproduce this analysis's baseline before interpreting a speedup.
|
||||
|
||||
### P1 — Remove repeated work from code-action discovery
|
||||
|
||||
This is first because it is a frequent editor request, and the serial request loop passes its delay to navigation queued behind it.
|
||||
|
||||
**Confirmed causes.**
|
||||
|
||||
- `server/dispatch.rs` constructs `LintRun` and calls `code_action::code_actions` before checking action-family filters. `code_action.rs::code_actions` calls `lint::fixable` unconditionally. Even `context.only: []` or a refactor-only request pays for lint and fence discovery.
|
||||
- `lint.rs::fixable` reruns the selected lint rules and calls `vlog_formatter::fence::protected_regions`. That function parses the whole text again, even when there is no fix to protect.
|
||||
- `inline_site`, `extract_site`, `imported_packages` and `port_action_modules` each accept text and independently parse it. The server already holds text, tokens, tree, diagnostics and semantics from the same document revision.
|
||||
- The lazy ports offer invokes `port_actions` on one or two source files and throws away its edits. It avoids workspace fan-out, but it still computes more than a menu needs. Import offers compute exact removal/sort counts using their engine. Treat these costs separately from the simple selectors.
|
||||
|
||||
**P1a: skip irrelevant work.** Before config discovery, lint execution and fence discovery, check whether quick fixes or `source.fixAll.lucisv` are wanted. Return immediately for an empty `only` filter. For requests that do want fixes, find whether any candidate carries an applicable fix before computing fence regions. Preserve kind-prefix semantics, fixes spanning the cursor, fix-all behavior and existing action ordering. An empty cursor range must not disable extraction: extraction currently supports an item selected by a cursor.
|
||||
|
||||
**P1b: reuse unchanged-buffer work.** Introduce additive refactor selectors over an existing parse plus its matching diagnostics; retain text-based wrappers for standalone consumers and parity tests. Have all offer families read `Document`'s current parse. Check parse diagnostics and large-file mode exactly as the old paths do. If even AST walks are expensive on generated files, derive only the necessary item/instance/import interval lookup once per document revision; do not introduce a general incremental parser for this step.
|
||||
|
||||
For fences, first retain the existing text-only authority and memoize its result per document revision. This respects the explicit contract in `docs/features/shared-fence-filter/README.md`: accepting arbitrary caller trees was deliberately avoided. Compute it only if a fix needs it. A future parsed-input API requires an explicit amendment to that contract, source/tree provenance and parity with the text API on malformed buffers and every fence shape. Never substitute formatter `collect` alone: the scan backstop is part of protection.
|
||||
|
||||
Do not reuse published diagnostics blindly as fix results: `tab_width`, rule options, inline/external waivers and workspace-dependent lints affect the answer. If lint-result caching remains necessary after the first measurements, key it by document revision, effective lint/format settings, waiver contents and workspace generation; invalidate on each relevant change. Fence caching itself depends only on exact source revision.
|
||||
|
||||
**P1c: offer predicates instead of throwaway edits.** Only if ports/import offers still dominate, expose engine-owned availability/count queries using parsed inputs and the necessary declaration facts. Keep refusal logic in `vlog_refactor`; do not grow an independent server-side refactoring engine. Resolve/execute must revalidate against current document and workspace state. Preserve ambiguous declarations, refusal text and promised counts; do not promise exact counts that the reduced query cannot establish.
|
||||
|
||||
**Files and contracts.** Server: `server/dispatch.rs`, `code_action.rs`, `lint.rs`, `state.rs`, `ports.rs`, `imports.rs`, `extract.rs`, `inline_module.rs`. Engine: selectors in `vlog_refactor/src/{ports/,imports.rs,extract/,inline/,lib.rs}` as applicable. Formatter `fence.rs` only if explicitly needed. Follow `topo.md` §1.2's request-selector parity and §3's shared ownership. `state.rs` already exceeds the preferred size: put new responsibilities in a small module; coordinate with TODO §55 rather than adding another large subsystem there.
|
||||
|
||||
**Validation and targets.** Pin old/new offer equality at every sampled cursor/range, including no-offer comments, parse errors, CRLF, UTF-16 positions, unsaved edits, untitled and large buffers, action filters, fence insertions, waivers, config changes and index refresh. Verify “no additional parse for repeated offers” with work counters, not a brittle stopwatch assertion. Proposed timing goals: ordinary repeated lazy offers below 5 ms; the current slow `aes_reg_top` offer below 10 ms; no-offer generated-file cursor below 16 ms on an unchanged buffer. Track the first request after a change separately, and measure pipelined definition latency. If a goal is missed, identify the measured remaining stage before proceeding.
|
||||
|
||||
### P2 — Reuse refactoring analysis while preserving whole-edit verification
|
||||
|
||||
**Confirmed repeated work.** `rename.rs` selects and materializes source strings. `vlog_refactor::Scope::build` builds an index from them, parsing/analyzing their text. `Scope::analysis` parses/analyzes the same input again on demand. `check::rebuilt_index` rebuilds an index over all selected sources after editing only a few, and `check::verify` parses/analyzes every watched file again, including untouched ones. Cross-file resolution genuinely must be checked again; unchanged syntax/local semantics need not be recomputed just to perform that check.
|
||||
|
||||
**Selection hypothesis requiring measurement.** `state.rs::fan_out_of` searches *all* matching workspace and hierarchical declarations for both old and new names, then includes their containers and instantiation/reference sites. A common internal name such as `state_q` can therefore select much more input than the two output files suggest. `hierarchical_declarations` scans the internal surface. The source confirms this behavior, but this round does not attribute percentages of rename time to selection, parsing, resolution or verification. Do not describe the entire 0.8 seconds as a slow hierarchical lookup.
|
||||
|
||||
**P2a: measure stage and work counts.** Record selector time; selected paths and total bytes; reason each path was included; ambiguity fallback; initial index build; number of parses/analyses; occurrence collection; before/after verification; serialization; peak memory. Compare `state_q`, unique internal names, common `clk`/`rst_n`, module `aes`, existing/conflicting new names, unresolved new-name uses and all-sources fallback. Capture the exact selected set so reduced work cannot masquerade as a faster correct answer.
|
||||
|
||||
**P2b: one input analysis per file.** Give a request-local scope a reusable parsed/semantic bundle from which it can derive `FileFacts` and analyze occurrences. Existing `FileFacts::from_analysis` is the starting point. Keep source text ownership and identity explicit. First eliminate duplicate work *inside the scope*; importing live server documents and index state is a separate step, because file IDs and the subset's name-resolution universe may differ. An additive prepared-input API must retain the current public text API and its answer/refusal behavior. Avoid a whole-workspace AST cache: current idle memory already warrants restraint.
|
||||
|
||||
**P2c: reuse unchanged post-edit inputs.** Construct the after-index from unchanged facts plus newly analyzed edited files. For untouched watched files, reuse local semantics and recompute their external resolutions against the after-index; for changed files, build one new parse/analysis and reuse it for after-facts and verification. Measure the clone/merge/remap cost: an incremental-looking API may still rebuild global tables. Preserve path-based identity and span-shift mapping when file IDs change. Token identity, parse-diagnostic checks, comments/attributes and before/after resolution comparison all remain mandatory.
|
||||
|
||||
**P2d: narrow only with a proof.** After reuse is measured, consider exact-name postings to avoid scanning unrelated declarations without changing the selected set. Further narrowing must preserve every edit, warning, ambiguous-use refusal, unresolved new-name capture and unsaved-buffer contribution. Compare the optimized scope with the whole-scope engine on generated/adversarial cases. Do not remove the all-sources fallback or common-name witnesses merely because they are expensive.
|
||||
|
||||
**Files and contracts.** `lucisv_server/src/{rename.rs,state.rs}`, `vlog_refactor/src/{scope.rs,rename/,check/,lib.rs}`, `vlog_semantic/src/workspace/{record.rs,index.rs,update.rs,mod.rs}` and actual merge owners as needed. Inspect current paths before assigning ownership. Preserve `topo.md` §1.2/§3's `collect_occurrences`, source-superset, `FileId`, `FileFacts`, ambiguity and name-span contracts. New persisted fields require a `FACTS_FORMAT` bump; a transient request bundle does not.
|
||||
|
||||
**Correctness prerequisite.** Topology open handshake **33** already records that `module_sources` can miss transitive hierarchical users such as `wrap.u_S.x`. It is specifically an inline/refactoring refusal gap, not proof that the measured rename has this bug. Resolve and test it before sharing a narrower source-selector implementation with inline/ports. Include multi-level hierarchy, generated scopes, interface/package/class names, macros, duplicate modules and unsaved references. Additional necessary files may increase time; report that as correctness work rather than hiding it.
|
||||
|
||||
**Acceptance and targets.** Identical normalized edits, warnings and refusal sentences to the original whole-scope engine on the parity suite; every valid edit still passes both verifiers. First target: at least 2× lower repeated tail-rename time and no ordinary-rename regression; stretch target below 200 ms only if stage measurements support it. Record selected/watched/edited file counts and bytes beside timing. The queued navigation target follows the same reduction. A faster partial edit is a failure.
|
||||
|
||||
### P3 — Eliminate the extra CLI package-census parse
|
||||
|
||||
**Cause.** `lucisv/src/lint.rs::Census::of` calls `vlog_linter::package_exports(path, src)` for every job whenever `unused-import` is enabled. `vlog_linter/src/interfaces.rs::package_exports` constructs a one-file `WorkspaceIndex`, including lex/parse/analysis, even for files declaring no package. The census then separately constructs `ParsedSource` for interface rules; the actual lint pass later parses again. This is concrete duplicated whole-file work. Finding only a few extra violations does not imply that computing the rule should be cheap: all input files are examined.
|
||||
|
||||
**Work.** Add a package-export query over the census's existing parsed input, sharing semantic/fact extraction only where necessary. Use the parsed AST to skip package-index work for files without package declarations; never use a textual `contains("package")` correctness gate. Preserve duplicate/unknown package treatment, nested declarations, malformed source and the conservative handling of re-export chains. Keep the shared linter/refactor import-use judgment; do not implement a different import resolver in the CLI. Determine whether the census can share its parse with interface extraction before considering retention into the later lint phase. Retaining every project's AST may trade a small wall-time gain for unacceptable memory, so measure peak RSS at each step.
|
||||
|
||||
**Files and contracts.** `crates/lucisv/src/lint.rs`, `crates/vlog_linter/src/{interfaces.rs,lib.rs}`; semantic fact extraction only if needed, by an additive API. The CLI has no direct semantic production dependency; keep that topology. The same package uncertainty must produce the same lint silence, and lint findings/fixes/waivers/exit codes remain stable.
|
||||
|
||||
**Acceptance and targets.** Run default, all-style, and all-style minus `unused-import` on the same binary, then compare paired revisions with matching rules and files. Default results must remain byte-identical; all-style optimization must retain `unused-import`'s findings. Aim to remove at least half the measured incremental all-style cost of this rule with no material default-time or peak-memory regression. Disabling the rule is only the attribution control, not the proposed optimization.
|
||||
|
||||
### P4 — Reduce startup work and memory after interactive costs are addressed
|
||||
|
||||
**Cause supported by source.** A warm index still reads source text to hash it, decodes encoded facts, rebuilds/merges query tables, constructs completion/include tables and refreshes open-buffer overlays. `IndexCache` retains encoded facts alongside the decoded workspace records; cold scans encode/append records and whole-scan completion compacts the store. These explain why a warm cache is not a near-zero-cost startup; their individual time/memory shares are unmeasured. Current scan notes also show a 124-file default scan preceding the final configured scope; explicit depth 0 pays for it and then ends with one file.
|
||||
|
||||
**Work order.** Instrument discovery/config wait, file read/hash, fact decoding, merging, completion/include construction, overlay refresh, cache write/compaction, and time to first useful navigation answer. Use the existing ignored scan/prelude/publish probes where applicable. Measure 1/10/100 open buffers and requests arriving during a scan, not just final idle time. If the default scan is routinely discarded, stage the initial scan until configuration arrives, with a bounded fallback for clients that never answer; keep rootless and scope precedence behavior intact.
|
||||
|
||||
Then optimize the dominant measured stage: avoid unnecessary compaction on unchanged stores; shorten temporary source/encoded-buffer lifetimes; reduce redundant transient copies and repeated full merges; consider representation changes only after profiling shows allocation/decoding cost. Changes must preserve interrupted-store recovery and a coherent index/candidate/include prefix. Preserve content-based freshness checks rather than replacing them with mtime/size-only cache hits. Do not introduce mmap, compression, unsafe code, another dependency or parser worker parallelism without a separate measured case and contract review.
|
||||
|
||||
**Files and contracts.** `server/index.rs`, `state.rs`, `index_cache.rs`, `candidates.rs`, `includes.rs`, and semantic build/facts owners. This shares files/contracts with P1/P2. Preserve scope ladder, live overlays, incremental/fresh-build fingerprint equality, corrupt-store recovery, version rejection, `FACTS_FORMAT` compatibility and the 16 MiB parser stack on any new parsing thread.
|
||||
|
||||
**Acceptance and targets.** Suggested goals: warm workspace settled time below 1 second, cold below 2.3 seconds, and at least 15% lower idle RSS with equivalent indexed content. Measure peak RSS too. These are investigation goals, not simultaneous promised savings; reject memory-for-speed trades that are not recorded and justified. Definition during scan should remain responsive and never observe mismatched published tables. Recheck file-open latency so the already successful §46 fix stays intact.
|
||||
|
||||
### P5 — Conditional follow-ups, not the first implementation
|
||||
|
||||
If first-after-edit latency remains outside the interactive budget after P1, remeasure `Document::new` and the ignored `breaking_down_one_flushed_keystroke` probe on 1k/10k generated files and actual large RTL. Distinguish parse time from the clone included in the existing parse measurement. The historical 79% lex/parse share is a lead to remeasure, not a current profile. A parser/token ownership change reaches six crates, comments/trivia consumers, exhaustive AST walkers and recursion guarantees in `topo.md`; it should not be bundled into an offer-gating patch.
|
||||
|
||||
If expensive user commands still block navigation after P2, separately design cancellable computation over immutable, revision-tagged workspace snapshots. Revalidate all document/workspace versions before returning edits; do not hold a workspace lock during heavy work. The synchronous transport, cancellation queue and stack-size contracts make this a larger architectural project. Measure queue delay before choosing it. Do not begin with an async runtime or thread-pool rewrite.
|
||||
|
||||
The eager-client path remains monitored because it is expensive, but previous owner guidance classified it as non-hot. Preserve eager compatibility and collect its timings as a collateral benefit of P2; do not trade lazy-client latency or correctness for it. Sub-millisecond navigation, the intentional 150 ms diagnostic debounce, and the fixed 0.50.0 format-cache option key are regression controls, not present optimization targets. Never remove formatter token-equivalence or convergence verification to improve throughput.
|
||||
|
||||
## Sequencing, ownership and implementation gates
|
||||
|
||||
Implement serially: **P0 → P1a → P1b → measure → P1c if needed → P2a → P2b/P2c → P2d only with proof → P3 → P4 if justified**. P5 requires a new measured decision. P3 may be chosen ahead of P2 if CLI throughput is the product priority; it has a smaller implementation surface.
|
||||
|
||||
Do not dispatch the server/refactor/parser/semantic work as independent lanes. `docs/topo.md` records direct dependencies, shared `state.rs` ownership and the open transitive-use handshake; P1–P4 have several of these collisions. If work is later delegated, the lead must first name exact files/contracts and follow the repository's isolated-worktree/QA process. No agents or implementation work were dispatched by this analysis.
|
||||
|
||||
For each selected stage, create its feature README with Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log and reserved Review. Update the tracking file with its baseline before edits, after measurements at the exact candidate commit, result parity, resource use and verdict. Do not mark an estimate as an improvement.
|
||||
|
||||
Run affected correctness suites per stage, then the repository's required format, clippy and workspace test gates at integration, plus formatter snapshot/idempotency and corpus checks when the changed contract reaches them. All suites/sweeps go through `tools/guard.sh -m 8 -t 1800`; no Cargo build or other benchmark runs during timed sessions. Keep the corpus read-only and retain exact failure/outcome sets, not only aggregate counts. Update `docs/topo.md` when an interface changes and `docs/perf/README.md` with accepted measured results. This analysis changes documentation and measurement evidence only; it does not mark implementation backlog items complete.
|
||||
|
||||
## Source and contract references for the implementation agent
|
||||
|
||||
| Cause or boundary | Current source / documentation |
|
||||
|---|---|
|
||||
| Action dispatch before kind filters | [dispatch.rs](../crates/lucisv_server/src/server/dispatch.rs), `CodeActionRequest` branch; [code_action.rs](../crates/lucisv_server/src/code_action.rs), `code_actions` |
|
||||
| Repeated lint and fence parse | [server lint.rs](../crates/lucisv_server/src/lint.rs), `fixable`; [fence.rs](../crates/vlog_formatter/src/fence.rs), `protected_regions`; [shared-fence-filter contract](features/shared-fence-filter/README.md) |
|
||||
| Four text-based selectors | [inline/mod.rs](../crates/vlog_refactor/src/inline/mod.rs), [extract/mod.rs](../crates/vlog_refactor/src/extract/mod.rs), [imports.rs](../crates/vlog_refactor/src/imports.rs), [ports/mod.rs](../crates/vlog_refactor/src/ports/mod.rs) |
|
||||
| Lazy offers computing engine edits | [server ports.rs](../crates/lucisv_server/src/ports.rs), `offers`; [server imports.rs](../crates/lucisv_server/src/imports.rs), `offers`; [engine imports.rs](../crates/vlog_refactor/src/imports.rs), `organize_counts` |
|
||||
| Broad rename selection | [state.rs](../crates/lucisv_server/src/state.rs), `rename_sources` / `fan_out_of`; [workspace/index.rs](../crates/vlog_semantic/src/workspace/index.rs), `hierarchical_declarations` |
|
||||
| Rebuilt refactoring analysis | [scope.rs](../crates/vlog_refactor/src/scope.rs), `build` / `analysis`; [check/mod.rs](../crates/vlog_refactor/src/check/mod.rs), `verify` / `rebuilt_index` |
|
||||
| CLI package census | [CLI lint.rs](../crates/lucisv/src/lint.rs), `Census::of`; [linter interfaces.rs](../crates/vlog_linter/src/interfaces.rs), `package_exports` |
|
||||
| Warm-cache work | [index_cache.rs](../crates/lucisv_server/src/index_cache.rs); [state.rs](../crates/lucisv_server/src/state.rs), scan preparation / `scan_step` / `finish_whole_scan`; [server/index.rs](../crates/lucisv_server/src/server/index.rs) |
|
||||
| Shared ownership and handshake 33 | [topo.md](topo.md), §1.2, §2.9 and §3; [repository analysis](repository-analysis.md) |
|
||||
| Previous data and measurement methods | [performance_take4.md](performance_take4.md), [performance_take3.md](performance_take3.md), [perf README](perf/README.md), [harness README](../tools/perf/README.md) |
|
||||
+92
-39
@@ -1,17 +1,17 @@
|
||||
# Repository analysis
|
||||
|
||||
Refreshed **2026-09-05**. Latest release: **v0.44.0** (`66f3898`). This
|
||||
review uses committed snapshot **`9ef1058`**, which also includes accepted
|
||||
type-name-spans and package-reexports work intended for v0.45.0. The active
|
||||
hierarchical-tail changes are described separately; their QA is still open.
|
||||
Refreshed **2026-09-07** against committed snapshot **`df4e714`**. Latest
|
||||
release: **v0.49.0** (`4c2dae3`). The working tree was clean at the start of
|
||||
this review. Loop 2 is closed; no uncommitted feature work is included.
|
||||
|
||||
## Assessment and current status
|
||||
|
||||
lucisv remains an eight-crate toolchain: six reusable Rust libraries, CLI and
|
||||
LSP binaries, editor integration, corpus/release tools, and a static docs site.
|
||||
The architecture still separates syntax, formatting, semantics, linting,
|
||||
refactoring, and project inputs. The three issues raised by the September 4
|
||||
audit have been fixed; they should no longer be treated as open priorities.
|
||||
refactoring, and project inputs. The September 4 audit findings are fixed.
|
||||
This refresh reproduced a new cache-key omission, documented below alongside
|
||||
the remaining refactor limits.
|
||||
|
||||
| Change | Status at this refresh | Implementation and contract |
|
||||
|---|---|---|
|
||||
@@ -22,9 +22,13 @@ audit have been fixed; they should no longer be treated as open priorities.
|
||||
| Cycle-aware walks and net-delay comment slots | Released in v0.43.0 | Directory identity prevents cycles; comments around a delay's `#` are preserved |
|
||||
| Walk warnings, editor rule-name warnings, aggregate overrides and delay-list comments | Released in v0.44.0 | Recoverable walk problems warn and continue; editor name typos log once; aggregate override expressions and delay-list comment slots are handled |
|
||||
| didOpen cost | Released in v0.44.0 | `undriven-net` asks the workspace mention oracle after local guards; findings and synchronous request ordering stay unchanged |
|
||||
| Type-name spans | Committed, accepted for v0.45.0 | `DataType::name_span()` / `segments()` and disable-target spans replace semantic name scanning; `scan.rs` is deleted |
|
||||
| Package re-exports | Committed, accepted for v0.45.0 | Export name halves are references; the shared member walk follows cycle-guarded re-export edges; persisted facts gain `RX`, codec **18** |
|
||||
| Hierarchical tails | **Working tree, QA pending** | Proposed codec **19**, tagged member/reference surfaces, instance-tail resolution and completion, and cross-file rename updates |
|
||||
| Type-name spans | Released in v0.45.0 | `DataType::name_span()` / `segments()` and disable-target spans replace semantic name scanning; `scan.rs` is deleted |
|
||||
| Package re-exports | Released in v0.45.0 | Export name halves are references; the shared member walk follows cycle-guarded re-export edges; persisted facts gain `RX`; current codec **19** |
|
||||
| Hierarchical tails | Released in v0.45.0 | Codec **19**, tagged member/reference surfaces, instance-tail resolution and completion, and cross-file rename updates |
|
||||
| Expand wildcard; convert ports to ANSI | Released in v0.46.0 | `.*` expands in declaration order with `.p()` and a warning for unmatched ports; legacy header/body declarations merge with comments and attributes preserved |
|
||||
| Organize imports; unused-import; extract module | Released in v0.47.0 | Shared semantic import usage feeds linter and refactor; **74 rules**; extraction infers ports/parameters/imports and creates a file when supported, or appends below the source module |
|
||||
| DUT hierarchy | Released in v0.48.0; packaging corrected in v0.48.2 | Client-only children/parents/other sections over the existing snapshot; saved workspace choices plus configured DUTs |
|
||||
| Inline module; final coverage additions | Released in v0.49.0 | Separate-file body copy with connection substitution and collision-aware renaming; six grammar gaps closed; real `randsequence` nodes; optional UVM indentation, default off |
|
||||
|
||||
The current source of truth for feature acceptance is each feature's QA/review
|
||||
log and [TODO.md](../TODO.md). The [topology](topo.md) records the interfaces
|
||||
@@ -37,20 +41,21 @@ two edits have disjoint ownership.
|
||||
|---|---|
|
||||
| `crates/vlog_parser` | Lexer/trivia, strict and tolerant recursive descent, AST/spans; `src/lib.rs`, `parser/`, `ast/` |
|
||||
| `crates/vlog_formatter` | AST → document IR → printer, alignment, fences/ranges, equivalence and convergence; `format/mod.rs`, `verify.rs` |
|
||||
| `crates/vlog_semantic` | File binding/resolution, workspace facts and member lookup; `bind/`, `resolve.rs`, `workspace/`, `facts.rs`; committed `workspace/reexport.rs`, active `workspace/hierarchy.rs` |
|
||||
| `crates/vlog_linter` | 73-rule registry, lazy semantics, options, severities, inline/external waivers and fixes; `lib.rs`, `context.rs`, `registry.rs`, `waiver_file.rs` |
|
||||
| `crates/vlog_refactor` | Rename/references, port edits, instance plans; shared `scope.rs`, whole-edit verification in `check.rs` |
|
||||
| `crates/vlog_semantic` | File binding/resolution, workspace facts and member lookup; `bind/`, `resolve.rs`, `workspace/`, `facts.rs`; `workspace/reexport.rs`, `workspace/hierarchy.rs`, shared import usage in `imports.rs` |
|
||||
| `crates/vlog_linter` | 74-rule registry, lazy semantics, options, severities, inline/external waivers and fixes; `lib.rs`, `context.rs`, `registry.rs`, `waiver_file.rs` |
|
||||
| `crates/vlog_refactor` | Rename/references, ports, imports, extract/inline module, instance plans; `scope.rs`, `ports/`, `imports.rs`, `extract/`, `inline/`, whole-edit verification and piece ledger in `check/` |
|
||||
| `crates/lucisv_core` | Config, filelists, cycle-aware walks and warning channel, format cache, atomic replacement; no language-engine dependency |
|
||||
| `crates/lucisv` | Argument handling, input discovery/dedup, worker pool, reports and source writes |
|
||||
| `crates/lucisv_server` | Ordered LSP loop and workspace overlays; `server/`, `state.rs`, capability handlers; project lint validation/logging in `lint/project.rs` |
|
||||
| `editors/` | VS Code client/grammar/settings/hierarchy UI and configuration for other editors |
|
||||
| `crates/lucisv_server` | Ordered LSP loop and workspace overlays; `server/`, `state.rs`, capability handlers including `imports.rs`, `extract.rs`, `inline_module.rs`; project lint validation/logging in `lint/project.rs` |
|
||||
| `editors/` | VS Code client/grammar/settings/hierarchy UI and other editor configuration; `hierarchySections.js` models DUT sections, `extract.js` supplies the module-name prompt |
|
||||
| `tools/`, `scripts/`, `.gitea/workflows/` | Resource guard, corpus evaluation, artifact checks and releases |
|
||||
| `docs/features/` | Implementation contracts, dated measurements, QA and acceptance records |
|
||||
| `docs/site/` | User-facing static documentation and tracked generated output |
|
||||
|
||||
The crate dependency graph is unchanged. Parser and core have no dependencies;
|
||||
formatter and semantics each depend on parser; linter and refactor depend on
|
||||
parser and semantics. The linter depends on the formatter only in tests.
|
||||
Parser and core have no dependencies; formatter and semantics each depend on
|
||||
parser; linter and refactor depend on parser and semantics. Linter also consumes
|
||||
core’s path matcher for external waivers. Both linter and refactor depend on
|
||||
the formatter **only in tests**.
|
||||
The CLI composes core/parser/formatter/linter; the server composes all six
|
||||
libraries. External Rust dependencies stay in the CLI worker pool and server
|
||||
LSP/JSON stack.
|
||||
@@ -77,24 +82,70 @@ can come from the index; members and open buffers use text-based positions.
|
||||
Refactor source selectors must include every file an engine might edit or
|
||||
refuse over, even when completion or navigation can answer from fewer files.
|
||||
|
||||
**New committed semantic contracts:** a type-name segment is derived from AST
|
||||
**Semantic contracts:** a type-name segment is derived from AST
|
||||
span data and verified against the source by `Binder::exact_or_empty`. The
|
||||
source parameter to analysis remains necessary even though `scan.rs` is gone.
|
||||
A package re-export records reference edges without adding a local import.
|
||||
`export *::*` expands the package's imports into re-export facts; member lookup
|
||||
follows those edges with cycle guards. Cache codec 18 prevents older stores
|
||||
follows those edges with cycle guards. Cache codec 19 prevents older stores
|
||||
from silently omitting this information.
|
||||
|
||||
## Active work and remaining limits
|
||||
The delivered hierarchical-tail contract uses `Surface::{Connection,
|
||||
Hierarchical}`, a second member table, surface tags on persisted declarations
|
||||
and references, and codec 19. Connection completion and port propagation retain
|
||||
the ports/parameters view; instance tails additionally reach internal nets,
|
||||
variables and nested instances. Topology handshake 23 is closed.
|
||||
|
||||
TODO §49 owns hierarchical-tail resolution. At this refresh, its working tree
|
||||
adds `Surface::{Connection, Hierarchical}`, a second member table, surface tags
|
||||
on persisted declarations/references, and codec 19. Connection completion and
|
||||
port propagation retain the existing ports/parameters view; paths behind an
|
||||
instance can additionally reach internal nets, variables and nested instances.
|
||||
Member completion and rename fan-out are part of the same contract. The feature
|
||||
README reports development checks; independent QA is still pending, so topology
|
||||
handshake 23 remains open. No working-tree API is treated as released here.
|
||||
`vlog_semantic::imports` supplies the shared usage judgement for organize-imports
|
||||
and the Style, default-off `unused-import` rule. Package re-exports count as use;
|
||||
unknown packages, macro/conditional uses and external inheritance are treated
|
||||
conservatively. Refactor `check/ledger.rs` tracks comment/attribute text,
|
||||
counts and positions for moves and copies, separately from formatter
|
||||
normalization. `RefactorEdit::created` lists new paths whose initial contents
|
||||
also appear as offset-zero insertions in `edits`; server resource operations
|
||||
honor client file-creation support. Inline copies leave their source file
|
||||
unchanged.
|
||||
|
||||
## Remaining limits and open work
|
||||
|
||||
**Cache omission (topology handshake 34, fixed in 0.50.0).** The CLI applies the new
|
||||
`Config::uvm_utils_indent` field, but `lucisv/src/main.rs::entry_for` and
|
||||
`lucisv_core::cache::Entry` omit it from cache equality and serialization.
|
||||
A private-cache probe using the archived CLI and this class reproduced:
|
||||
|
||||
```systemverilog
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
`uvm_object_utils_end
|
||||
endclass
|
||||
```
|
||||
|
||||
1. `[format] uvm-utils-indent = false`, `--check`: exit **0**, unchanged.
|
||||
2. Change only the option to `true`, `--check`: exit **0**, one cache hit.
|
||||
3. Same config, `--no-cache --check`: exit **1**, would reformat.
|
||||
|
||||
**Fixed 2026-09-07 (TODO §59, ships in 0.50.0):** the option is in the key
|
||||
and in the store line, a 0.49.0 store is rebuilt rather than trusted, and the
|
||||
probe above is a CLI regression test in both toggle directions
|
||||
(`changing_uvm_utils_indent_invalidates_the_entry`). The paragraph is kept as
|
||||
the record of the finding.
|
||||
|
||||
**Refactor limits:** inline-module requires a separate-file source module and
|
||||
simple named connections. It refuses wildcards, positional/expression or
|
||||
unconnected ports, unsupported port types, generate, initial/final,
|
||||
macros/directives, and hierarchical uses found in its inputs. QA recorded a
|
||||
source-selection gap: `module_sources` can omit a file reaching the instance
|
||||
through an intermediate module, bypassing the hierarchical-use refusal
|
||||
(**handshake 33**). The verifier also has a bounded testability gap for
|
||||
same-file relocation of protected pieces (**32**); no current planner produces
|
||||
that edit shape. See the [extract/inline QA record](features/extract-inline-module/README.md).
|
||||
|
||||
TODO **§55** defers `state.rs` decomposition to Loop 3. The September 7
|
||||
measurement in `CLAUDE.md` reports 958 production lines there, `perf.rs` 900
|
||||
with a recorded reason, `lexer.rs` 763, and `format/stmt.rs` 604. TODO §57
|
||||
still has remote-artifact and memory bookkeeping unchecked; this review does
|
||||
not certify remote releases or manual editor acceptance.
|
||||
|
||||
Remaining constraints include generate-block-scoped hierarchical paths,
|
||||
cross-file macro expansion, and compiler elaboration. Package re-export support
|
||||
@@ -128,23 +179,25 @@ is part of this refresh.
|
||||
|
||||
## Validation of this refresh
|
||||
|
||||
Checks ran against an isolated archive of committed `9ef1058`, with a separate
|
||||
build directory and the repository resource guard. This avoids the live agents'
|
||||
target directory and does not certify their uncommitted changes.
|
||||
Checks ran against an isolated archive of committed `df4e714`, with a separate
|
||||
build directory and the repository resource guard. This validates a fixed
|
||||
source snapshot without sharing another task’s build directory.
|
||||
|
||||
- `cargo fmt --all -- --check`: passed.
|
||||
- `cargo clippy --offline --workspace --all-targets -- -D warnings`: passed.
|
||||
- `cargo test --offline --workspace`: **3,829 passed, 0 failed, 44 ignored**,
|
||||
across 49 harnesses, under `tools/guard.sh`. The archive did not include the
|
||||
- `cargo test --offline --workspace`: **4,163 passed, 0 failed, 44 ignored**,
|
||||
across 55 harnesses, under `tools/guard.sh`. The archive did not include the
|
||||
ignored/untracked corpus checkout, and ignored measurement tests were not run.
|
||||
- `node --test editors/vscode/*_test.js`: **5 test files passed** (extract
|
||||
input, hierarchy model/sections/view, restart behavior). The cache probe
|
||||
above also ran under the resource guard.
|
||||
- `ASTRO_TELEMETRY_DISABLED=1 npm run build` in `docs/site`: passed;
|
||||
13 pages, Pagefind search and sitemaps rebuilt.
|
||||
- Generated-site validation: **820** local links, assets and anchors checked,
|
||||
zero errors. Relative links in the root analysis/topology/coverage docs also
|
||||
passed. `git diff --check` passed for these documentation changes.
|
||||
- Generated-site validation: **836** local links, assets and anchors checked,
|
||||
zero errors. All **26** relative file links in README, analysis, topology and
|
||||
coverage docs also passed. `git diff --check` passed for these documentation changes.
|
||||
|
||||
The previous audit's 3,745 passing tests describe its September 4 snapshot;
|
||||
they are not reused as the test result for this revision. This refresh changes
|
||||
documentation only and leaves feature QA logs and backlog checkboxes to their
|
||||
Earlier test totals describe earlier snapshots; the results above were
|
||||
measured again for this revision. This refresh changes documentation only and leaves feature QA logs and backlog checkboxes to their
|
||||
owners. No corpus/OpenTitan sweep, new benchmark, release packaging or
|
||||
publishing was performed.
|
||||
+12
-2
@@ -70,7 +70,7 @@
|
||||
})();
|
||||
</script></sl-sidebar-state-persist><div class="md:sl-hidden"><div class="mobile-preferences sl-flex astro-b5gddk54"><div class="social-icons astro-b5gddk54"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#core-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Core style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#alignment-is-inferred" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Alignment is inferred</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#format-fences" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Format fences</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#range-formatting" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Range formatting</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#safety-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Safety invariants</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#core-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Core style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#alignment-is-inferred" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Alignment is inferred</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#format-fences" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Format fences</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#range-formatting" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Range formatting</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#safety-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Safety invariants</span></a></li></ul></nav></starlight-toc><script type="module" src="/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js"></script></div></div></div></aside><div class="main-pane astro-abfeecmu"><main data-pagefind-body class="astro-vdxcvpsm" lang="en" dir="ltr"><div class="content-panel astro-oLine truncated
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#core-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Core style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#uvm-utilities-indentation" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">UVM utilities indentation</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#alignment-is-inferred" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Alignment is inferred</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#format-fences" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Format fences</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#range-formatting" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Range formatting</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#safety-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Safety invariants</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#core-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Core style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#uvm-utilities-indentation" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">UVM utilities indentation</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#alignment-is-inferred" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Alignment is inferred</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#format-fences" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Format fences</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#range-formatting" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Range formatting</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#safety-invarLine truncated
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="core-style">Core style</h2><a class="sl-anchor-link" href="#core-style"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Core style”</span></a></div>
|
||||
<ul>
|
||||
<li>2-space indentation and 100-column lines by default.</li>
|
||||
@@ -80,12 +80,22 @@
|
||||
<li>At most one preserved blank line between adjacent items.</li>
|
||||
<li>Compiler directives, attributes, and supported verbatim constructs keep their source text.</li>
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="uvm-utilities-indentation">UVM utilities indentation</h2><a class="sl-anchor-link" href="#uvm-utilities-indentation"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “UVM utilities indentation”</span></a></div>
|
||||
<p>To indent field macros inside UVM utilities blocks one additional level:</p>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="toml"><code><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">[format]</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">uvm-utils-indent</span><span style="--0:#D6DEEB;--1:#403F53"> = </span><span style="--0:#FF6A83;--1:#A24848">true</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="[format]uvm-utils-indent = true"><div></div></button></div></figure></div>
|
||||
<p>This v0.49.0 option is off by default. It applies to <code dir="auto">uvm_field_*</code> macros
|
||||
between <code dir="auto">uvm_*_utils_begin</code> and <code dir="auto">uvm_*_utils_end</code>. In editors,
|
||||
<code dir="auto">lucisv.format.uvmUtilsIndent</code> is the fallback; project configuration wins.
|
||||
Short, comment-free enum bodies already fit on one line without another key.</p>
|
||||
<p>After toggling this option, run the CLI with <code dir="auto">--no-cache</code> or remove its format
|
||||
cache: v0.49.0 does not include this option in the cache key. See
|
||||
<a href="/start/configuration/#cache">configuration</a>.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="alignment-is-inferred">Alignment is inferred</h2><a class="sl-anchor-link" href="#alignment-is-inferred"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Alignment is inferred”</span></a></div>
|
||||
<p>lucisv recognizes existing columnar intent in adjacent ANSI ports, named connections, and parameter declarations. If a group is already aligned—or uses four or more spaces where one would suffice—it is normalized as a table. Flush-left input stays flush-left.</p>
|
||||
<p>Groups end at blank lines, standalone comments, attributes, or compiler directives. If the widest row exceeds the line limit, the entire group falls back to flush-left, never a half-aligned mixture.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="format-fences">Format fences</h2><a class="sl-anchor-link" href="#format-fences"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Format fences”</span></a></div>
|
||||
<p>Use a standalone fence to protect hand-laid-out regions:</p>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="system-verilog"><code><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// verilog_format: off</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">localparam int</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">A</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C792EA;--1:#8844AE">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#F78C6C;--1:#AA0982">1</span><span style="--0:#D6DEEB;--1:#403F53">;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">localparam int</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">LONGER</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C792EA;--1:#8844AE">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#F78C6C;--1:#AA0982">22</span><span style="--0:#D6DEEB;--1:#403F53">;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// verilog_format: on</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="// verilog_format: offlocalparam int A = 1;localparam int LONGER = 22;// verilog_format: on"><div></div></button></div></figure></div>
|
||||
<div class="expressive-code"><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="system-verilog"><code><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// verilog_format: off</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">localparam int</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">A</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C792EA;--1:#8844AE">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#F78C6C;--1:#AA0982">1</span><span style="--0:#D6DEEB;--1:#403F53">;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">localparam int</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">LONGER</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C792EA;--1:#8844AE">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#F78C6C;--1:#AA0982">22</span><span style="--0:#D6DEEB;--1:#403F53">;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// verilog_format: on</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="// verilog_format: offlocalparam int A = 1;localparam int LONGER = 22;// verilog_format: on"><div></div></button></div></figure></div>
|
||||
<p><code dir="auto">// lucisv: off</code> and <code dir="auto">// lucisv: on</code> are aliases. Fences preserve exact bytes between items (including class members) and
|
||||
between statements in blocks, forks, functions, tasks, and procedural bodies.
|
||||
They also prevent lint fixes there. A fence must begin on its own line;
|
||||
|
||||
+6
-1
@@ -87,10 +87,15 @@ fence-blind; callers performing automatic edits must apply that protection.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="options-and-diagnostics">Options and diagnostics</h2><a class="sl-anchor-link" href="#options-and-diagnostics"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Options and diagnostics”</span></a></div>
|
||||
<p>Use <code dir="auto">[lint.<rule>]</code> in <code dir="auto">lucisv.toml</code> or <code dir="auto">lucisv.lint.options</code> in the editor for
|
||||
per-rule options. See <a href="/start/configuration/">configuration</a> for precedence.
|
||||
<code dir="auto">lucisv check --rules-doc</code> prints all 73 registered rules, their severity,
|
||||
<code dir="auto">lucisv check --rules-doc</code> prints all 74 registered rules, their severity,
|
||||
default selection, fix applicability, and option defaults.</p>
|
||||
<p>Text output uses <code dir="auto">FILE:LINE:COL: severity: message [rule]</code>. JSON output is one
|
||||
array, with a <code dir="auto">severity</code> field on each diagnostic.</p>
|
||||
<p><code dir="auto">unused-import</code> is a Style rule, off by default even in a project. Enable it
|
||||
explicitly to report unused module/package/class imports using the same
|
||||
analysis as Organize Imports. It stays silent without package facts and
|
||||
preserves uncertain macro or inherited uses. A finding on an import with a
|
||||
comment has no automatic deletion fix.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="waivers">Waivers</h2><a class="sl-anchor-link" href="#waivers"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Waivers”</span></a></div>
|
||||
<div class="expressive-code"><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="system-verilog"><code><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">wire</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C5E478;--1:#3B61B0">a</span><span style="--0:#D6DEEB;--1:#403F53">; </span><span style="--0:#919F9F;--1:#5D6376">// lucisv: waive no-tabs</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// lucisv: waive no-tabs</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">wire</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C5E478;--1:#3B61B0">b</span><span style="--0:#D6DEEB;--1:#403F53">;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// lucisv: waive-start module-name-style</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">module</span><span style="--0:#D6DEEB;--1:#403F53"> LegacyName;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">endmodule</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// lucisv: waive-stop module-name-style</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="wire a; // lucisv: waive no-tabs// lucisv: waive no-tabswire b;// lucisv: waive-start module-name-stylemodule LegacyName;endmodule// lucisv: waive-stop module-name-style"><div></div></button></div></figure></div>
|
||||
<p><code dir="auto">verilog_lint:</code> is accepted in place of <code dir="auto">lucisv:</code> for Verible compatibility. The <code dir="auto">unused-waiver</code> rule reports malformed, unknown, or no-longer-needed suppressions when their target rule is enabled.</p>
|
||||
|
||||
+6
-5
@@ -75,7 +75,7 @@
|
||||
<ul>
|
||||
<li>Modules, interfaces, programs, packages, classes, interface classes, generate regions, and nested classes.</li>
|
||||
<li>ANSI and non-ANSI ports, parameter ports, header imports, <code dir="auto">timeunit</code>, <code dir="auto">genvar</code>, and <code dir="auto">defparam</code>.</li>
|
||||
<li>Net and variable declarations, signing, packed and unpacked dimensions, and net delays.</li>
|
||||
<li>Net and variable declarations, signing, packed and unpacked dimensions, net delays, and net drive strengths.</li>
|
||||
<li><code dir="auto">typedef</code> aliases, enums, packed structs/unions, forward class declarations, anonymous aggregate types, and type parameters.</li>
|
||||
<li>Virtual interfaces, parameterized class types, properties, methods, constructors, prototypes, and out-of-body method definitions.</li>
|
||||
<li>Functions and tasks in ANSI and legacy forms, DPI imports/exports, and package re-exports.</li>
|
||||
@@ -85,7 +85,8 @@
|
||||
<li><code dir="auto">assign</code>, <code dir="auto">always</code>, <code dir="auto">always_comb</code>, <code dir="auto">always_ff</code>, <code dir="auto">always_latch</code>, <code dir="auto">initial</code>, and <code dir="auto">final</code>.</li>
|
||||
<li>Blocks, conditionals, every <code dir="auto">case</code> kind, loops, <code dir="auto">foreach</code>, <code dir="auto">fork/join*</code>, waits, timing controls, events, <code dir="auto">force</code>/<code dir="auto">release</code>, and jump statements.</li>
|
||||
<li>Immediate and concurrent assertions, sequences, properties, <code dir="auto">expect</code>, <code dir="auto">cover sequence</code>, and <code dir="auto">default disable iff</code>. Property and sequence expressions use their LRM precedence and participate in formatting and semantic tools.</li>
|
||||
<li><code dir="auto">randomize() with</code>, <code dir="auto">randcase</code>, <code dir="auto">let</code>, statement labels, array iterator methods, and omitted positional arguments.</li>
|
||||
<li><code dir="auto">randomize() with</code>, <code dir="auto">randcase</code>, real <code dir="auto">randsequence</code> productions, statement-level <code dir="auto">let</code>, statement labels, array iterator methods, and omitted positional arguments.</li>
|
||||
<li>Nonblocking <code dir="auto">->></code> event triggers with optional timing and min:typ:max clocking skews.</li>
|
||||
<li>Constraint blocks and randomization constraint bodies, including <code dir="auto">soft</code>, <code dir="auto">dist</code>, implication, <code dir="auto">foreach</code>, and <code dir="auto">solve before</code>.</li>
|
||||
<li>Covergroups with coverpoints, bins, transitions, crosses, <code dir="auto">with</code>, and <code dir="auto">iff</code> expressions.</li>
|
||||
</ul>
|
||||
@@ -99,7 +100,7 @@
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="expressions">Expressions</h2><a class="sl-anchor-link" href="#expressions"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Expressions”</span></a></div>
|
||||
<ul>
|
||||
<li>Full operator precedence, ternaries, concatenation and replication, slices, streaming concatenations, casts, and assignment patterns.</li>
|
||||
<li>Full operator precedence, ternaries, concatenation and replication, slices, streaming concatenations with <code dir="auto">with [range]</code>, constant-expression and packed-type cast bases, and assignment patterns.</li>
|
||||
<li>Hierarchical and package-scoped names, named call arguments, array methods, <code dir="auto">inside</code>, and all supported <code dir="auto">new</code> forms.</li>
|
||||
<li>Dynamic arrays, queues, associative arrays, empty literals, and <code dir="auto">$</code>-bound indexing.</li>
|
||||
<li>Macro invocations in expression, statement, and item position; macro digits in based numbers.</li>
|
||||
@@ -107,6 +108,6 @@
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="preserved-rather-than-reformatted">Preserved rather than reformatted</h2><a class="sl-anchor-link" href="#preserved-rather-than-reformatted"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Preserved rather than reformatted”</span></a></div>
|
||||
<p>Some constructs are recognized structurally but emitted with their internal source layout intact: compiler directives, macro bodies, <code dir="auto">specify</code>, UDP, checker and config blocks, and carefully recovered conditional-split declarations. Constraint, covergroup and SVA parsers also keep a byte-exact fallback for an unfamiliar body, so unsupported subgrammar does not block the surrounding file.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="not-supported">Not supported</h2><a class="sl-anchor-link" href="#not-supported"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Not supported”</span></a></div>
|
||||
<p>A small set of rare expression/port forms remains outside the formatter grammar. lucisv also does not run a preprocessor, so a file that becomes valid only after cross-file macro expansion may not format as a standalone input.</p>
|
||||
<p>Parser acceptance does not imply full elaboration or semantic navigation: generate-block-scoped hierarchical paths and DPI-export name binding remain gaps. lucisv also does not run a preprocessor, so a file that becomes valid only after cross-file macro expansion may not format as a standalone input.</p>
|
||||
<aside aria-label="Safe failure" class="starlight-aside starlight-aside--caution"><p class="starlight-aside__title" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="starlight-aside__icon"><path d="M12 16a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm10.67 1.47-8.05-14a3 3 0 0 0-5.24 0l-8 14A3 3 0 0 0 3.94 22h16.12a3 3 0 0 0 2.61-4.53Zm-1.73 2a1 1 0 0 1-.88.51H3.94a1 1 0 0 1-.88-.51 1 1 0 0 1 0-1l8-14a1 1 0 0 1 1.78 0l8.05 14a1 1 0 0 1 .05 1.02v-.02ZM12 8a1 1 0 0 0-1 1v4a1 1 0 0 0 2 0V9a1 1 0 0 0-1-1Z"/></svg>Safe failure</p><div class="starlight-aside__content"><p>Whole-file formatting returns an error and writes nothing when parsing is incomplete. lucisv never emits a partially understood file.</p></div></aside>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/syntax.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-03T09:28:11.000Z">Sep 3, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/editors/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors & LSP</span></span></a><a href="/reference/cli/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/syntax.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-07T06:12:49.000Z">Sep 7, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/editors/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors & LSP</span></span></a><a href="/reference/cli/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user