Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
464929262b | ||
|
|
e4db0ac1fc | ||
|
|
857b82d58a | ||
|
|
14213f6a93 | ||
|
|
c1076f9405 | ||
|
|
6844fbecb6 | ||
|
|
3132c24b21 | ||
|
|
ea586d29bc | ||
|
|
e115f9fc8f | ||
|
|
d8119aa9c6 | ||
|
|
2854bcaa2f | ||
|
|
3598a9145e | ||
|
|
a8c4a2ecf8 | ||
|
|
66bf27617e | ||
|
|
9dc567c72a | ||
|
|
92875e6c6d | ||
|
|
51b975bf68 | ||
|
|
ec492cdd86 | ||
|
|
75d2d376cf | ||
|
|
31b7db16a3 | ||
|
|
5e4af0be3d | ||
|
|
41a90917bb | ||
|
|
4fae8fb63a | ||
|
|
ca83f6f99f | ||
|
|
58520e586e | ||
|
|
a062f62581 | ||
|
|
6d1957076a | ||
|
|
38244e6aaf | ||
|
|
eadee02c37 | ||
|
|
e8e22c2364 | ||
|
|
7794d3938b | ||
|
|
b9ee399ac6 |
No files matched your search
+301
@@ -4,6 +4,307 @@ 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.65.0 — 2026-11-19
|
||||
|
||||
### Module instantiation syntax highlighting
|
||||
|
||||
(`docs/features/instantiation-highlighting`; TODO §69.)
|
||||
|
||||
- **Every part of a module instantiation gets its own colour.** Module names,
|
||||
instance names, `.PARAM` overrides, `.port` names and connected signals used
|
||||
to collapse to the same default foreground colour whenever the instantiated
|
||||
module lived in another file or a theme left bare semantic tokens unstyled.
|
||||
The language server now layers AST-guided semantic token overrides (and
|
||||
cross-file `ExternalResolutions` lookups) over the existing 14-type legend:
|
||||
- **Module / interface names** (`uart_core`, `pkg::uart_core` with `pkg` as
|
||||
`namespace`, and lone `bind` targets) highlight as `class`.
|
||||
- **`#` and parameters share one colour** (`parameter`), distinct from `()`:
|
||||
the `#` introducing a module, class, `extends`, instantiation or
|
||||
parameterized-type parameter list, every `.PARAM` override (`.` and name),
|
||||
and parameter values inside `#(...)` all carry `parameter`. Delay `#`
|
||||
tokens (`#5`, `#(1:2:3)`) are left unemitted.
|
||||
- **Instance names** (`u_uart`, gate instances, `bind` instance lists, and
|
||||
hierarchical uses like `u_uart.sig`) highlight as `function`.
|
||||
- **Port names** (`.clk_i` dot and name, implicit `.rst_ni`, and wildcard
|
||||
`.*`), including unfinished entries being typed, highlight as `property`.
|
||||
- **Port connections** (`clk`, `data_q`) stay `variable` so signals keep one
|
||||
consistent colour across the file.
|
||||
- **VS Code: semantic highlighting on by default with theme-safe scope maps.**
|
||||
`configurationDefaults` enables `editor.semanticHighlighting.enabled` for
|
||||
`[verilog]` and `[systemverilog]` (user settings still win), and
|
||||
`contributes.semanticTokenScopes` maps the language's semantic token types to
|
||||
distinct TextMate scopes so every role renders in colour across Dark+, Dark
|
||||
Modern, Light+, GitHub Dark, One Dark Pro and Visual Studio Dark.
|
||||
|
||||
## 0.64.0 — 2026-11-17
|
||||
|
||||
### Completion that keeps up with typing
|
||||
|
||||
(`docs/features/completion-ux`, `docs/features/port-entry-grace`; TODO §68.)
|
||||
|
||||
- **`begin` + Enter writes the `end`.** The newline on-type answer, when
|
||||
the line above ends in `begin` (or `begin : label`) and a block is still
|
||||
open, also inserts `end` on the line after the new one, at the
|
||||
indentation of the statement that owns the `begin`; the cursor stays on
|
||||
the new, indented line. Nothing is added when the blocks already balance
|
||||
(an `end` under the owner or under a `begin` on its own line counts), nor
|
||||
for a `begin` left open inside an `ifdef` region that has an `else`.
|
||||
Setting `lucisv.autoEnd` (default on). The VS Code extension sends the
|
||||
request itself when `editor.formatOnType` is off.
|
||||
- **`always_ff @(` and `always @(` expand with clock and reset**:
|
||||
`posedge clk or negedge rst_n`, both names tab stops, as the ghost text
|
||||
and as the first popup template. The clock-only forms follow.
|
||||
- **This file's names rank first.** The popup's order is now: the scope at
|
||||
the cursor, names declared anywhere in this buffer, words used in it,
|
||||
then the workspace index, templates, keywords and project words.
|
||||
- **Keyword ghosts.** Two or more letters of a keyword show the rest as
|
||||
grey inline text (Tab accepts); with the popup open the ghost follows its
|
||||
selected entry. A word that is exactly a name the buffer declares gets
|
||||
none. A `.v` file is offered Verilog-2005 keywords only. Setting
|
||||
`lucisv.inlineKeywords` (default on). The `begin` ghost now also appears
|
||||
for a `begin` typed inside a block that already balances.
|
||||
- **Port suggestions.** After `.` in an instance, unconnected ports come
|
||||
first and already-connected ones follow, marked `connected`; they used to
|
||||
be left out. Accepting a port inserts `name()` with the cursor inside,
|
||||
pre-filled with a same-named signal when one is visible; parameter lists
|
||||
(`#(.`) behave the same.
|
||||
- **An unfinished connection stays in its own entry.** In the editor's
|
||||
tolerant parse, a lone `.`, a `.name(` still open at the end of its line
|
||||
and a trailing `,` are each recovered inside their entry — always with a
|
||||
diagnostic — so the rest of the list and the file still parse, colour and
|
||||
lint. Strict parsing, and so the formatter and the CLI, are unchanged.
|
||||
- **Errors on the connection being typed wait.** Diagnostics that start
|
||||
inside the entry the last edit touched, in a named-connection list of an
|
||||
instance, are withheld and published after 1.5 s without typing, on an
|
||||
edit elsewhere, or on save. A client that pulls diagnostics and supports
|
||||
it is sent `workspace/diagnostic/refresh`. Nothing outside that entry is
|
||||
ever withheld.
|
||||
- **Changed: a trailing `,` in a named connection list (`.a(x),)`) is now
|
||||
reported in the editor.** The formatter and the CLI always refused it;
|
||||
the editor's tolerant parse used to accept it silently. Format Selection
|
||||
elsewhere in such a file now works instead of refusing the whole file.
|
||||
|
||||
## 0.63.1 — 2026-11-11
|
||||
|
||||
### Sticky scroll shows every layer
|
||||
|
||||
(TODO §67.)
|
||||
|
||||
- **VS Code: sticky scroll pins the first line of every block you are
|
||||
inside.** Only the module header used to stay at the top of the editor,
|
||||
because sticky scroll follows the document outline by default and the
|
||||
outline stops at declarations. The extension now defaults
|
||||
`editor.stickyScroll.defaultModel` to `foldingProviderModel` for Verilog
|
||||
and SystemVerilog, so the pinned lines come from the server's folding
|
||||
ranges — the module, the `always`, the `case`, the case item, the `if` —
|
||||
and raises `editor.stickyScroll.maxLineCount` to 10 for those languages
|
||||
(VS Code's 5 fits exactly that example and nothing deeper). Your own
|
||||
settings still win.
|
||||
- Known limit: a layer without `begin` (a one-statement `if`, a case item
|
||||
with no `begin`) has no fold and so no pinned line; a `begin` on its own
|
||||
line pins that line, not the `always` above it.
|
||||
- No engine change: the server, formatter and linter are 0.63.0's.
|
||||
|
||||
## 0.63.0 — 2026-11-09
|
||||
|
||||
### Format Selection that fits where it stands; comment toggling in VS Code
|
||||
|
||||
(`docs/features/selection-formatting`; TODO §66.)
|
||||
|
||||
- **Format Selection lays out only the block you selected.** Selecting an
|
||||
`always` block, a `case` statement or a few statements used to re-lay the
|
||||
whole enclosing module-level item — at the formatter's own depth, so a
|
||||
block in a 4-space or tab-indented file moved, and the blank lines at the
|
||||
selection's edges were eaten. The new engine
|
||||
(`vlog_formatter::format_selection`) finds the smallest run of sibling
|
||||
items or statements the selected lines cover, lays out that run alone and
|
||||
puts it back starting at the leading whitespace it already has (tabs
|
||||
kept). The parent is not touched. `textDocument/rangeFormatting`,
|
||||
`rangesFormatting` and the on-type `;` all run on it.
|
||||
- **A parse error elsewhere in the file no longer refuses the request.** The
|
||||
selection is formatted when the error lies outside it, and refused only
|
||||
when it lies inside.
|
||||
- **How a selection picks its block.** Touching a block's first line takes
|
||||
the whole block; a selection that starts inside it takes only the
|
||||
statements it covers, even when it reaches the closing `end`; the `end`
|
||||
line alone takes the block it closes. A selection of whole module-level
|
||||
items behaves as before.
|
||||
- **Still verified.** Every result passes the whole-file equivalence check
|
||||
and a convergence replay, or the buffer is left unchanged; the verifier
|
||||
itself is unchanged. CRLF files keep every line ending.
|
||||
- The on-type `;` now tidies its statement in a buffer whose error is
|
||||
elsewhere, and no longer adds a final newline to a file without one.
|
||||
- The reply is still one whole-document edit; the CLI's `--lines` is
|
||||
unchanged (whole module-level items).
|
||||
- **VS Code: `Ctrl+/` toggles comments.** The extension now declares the
|
||||
language's `//` and `/* */` comments, bracket pairs and auto-closing
|
||||
pairs for Verilog and SystemVerilog, so Toggle Line Comment and Toggle
|
||||
Block Comment work on one line or a selection.
|
||||
|
||||
## 0.62.0 — 2026-10-19
|
||||
|
||||
### Paths rooted at a top-level module; a dependable release gate
|
||||
|
||||
(`docs/features/top-rooted-paths`, `docs/features/release-gates`,
|
||||
`docs/features/references-fanout-pd-main`.)
|
||||
|
||||
- **A hierarchical path that starts at a top-level module now resolves.**
|
||||
`tb.dut.u_core.sig` written in a file that does not declare `tb` used to
|
||||
stop at `tb`; now every segment is a reference — `find_references` and LSP
|
||||
references list it, and a rename of `dut`, `u_core`, `sig` or a generate
|
||||
label on the way rewrites the path. `$root.tb…` works; a local `tb`
|
||||
shadows. The LSP's rename also reads the files of the path's root and the
|
||||
modules it passes through. **Rooted only when lucisv can prove the head is
|
||||
a top-level module**: not when the name could come from a wildcard import
|
||||
(including `import uvm_pkg::*` with `uvm_pkg` outside the project), not
|
||||
inside a class, not beside a macro that stands where a declaration could,
|
||||
and not when the name is also a package or several modules share it —
|
||||
those paths are left unchanged and warned about exactly as before. The
|
||||
index cache format moves to 22, so a 0.61.0 cache is rebuilt once.
|
||||
- An unresolved path through the renamed name is warned about once (it was
|
||||
sometimes named twice).
|
||||
- **Find All References across blocks is relative to the index scope, by
|
||||
design.** On a default `folder` scope a module's references and rename
|
||||
reach only the folders the index covers; the `lucisv.index.scope` setting
|
||||
now says that a rename of a module instantiated outside the scope leaves
|
||||
those instantiations unchanged (use `workspace`, or open the file first).
|
||||
- **`tools/gates.sh`** is the release gate: fmt, clippy, the test build,
|
||||
each crate's suites, the doc-tests, the corpus gate and the extension
|
||||
tests, each a separately guarded step with its own log and a summary; a
|
||||
step the guard kills is retried once and reported as `KILLED → retried`.
|
||||
- **`tools/guard.sh` fixes:** its memory limit now sees every process in the
|
||||
tree (a pid-list bug hid everything three or more levels down, so builds
|
||||
and test-spawned servers were never capped), and a closed stdin no longer
|
||||
makes the command silently not run.
|
||||
|
||||
## 0.61.0 — 2026-10-14
|
||||
|
||||
### Call hierarchy from anywhere, functions and tasks as nodes; full-line references in VS Code
|
||||
|
||||
(`docs/features/call-hierarchy-everywhere`, `docs/features/vscode-references-view`.)
|
||||
|
||||
- **`textDocument/prepareCallHierarchy` answers from any position in a
|
||||
body.** It answered only on a module name, so Show Call Hierarchy was empty
|
||||
almost everywhere. Now: an instance name prepares the instantiated module;
|
||||
a function or task's declaration, call or end label prepares a
|
||||
`Function`/`Method` item; a position inside a function or task body
|
||||
prepares that function or task; one inside a module, interface or program
|
||||
prepares the enclosing module. Module items answer exactly as before.
|
||||
- **Functions and tasks are call-hierarchy nodes.** `incomingCalls` lists
|
||||
every call site, grouped by the enclosing function or task (else the
|
||||
module, interface, program, package or class), over the same files
|
||||
`references` reads; `outgoingCalls` lists the resolved callees, skipping
|
||||
system tasks and unresolved names. A function's own name read inside its
|
||||
body (`clog2 = clog2 + 1`) is its result variable, not recursion. Calls
|
||||
through `this.`, `super.`, a typed handle and an `import` resolve; virtual
|
||||
dispatch and calls inside macro bodies are not modelled.
|
||||
- **`textDocument/prepareTypeHierarchy`** answers the enclosing class
|
||||
anywhere inside a class body, and the base class on `super`.
|
||||
- **VS Code: Find All References with whole lines.** VS Code's references
|
||||
pane starts each preview a few characters before the match. The extension's
|
||||
new **References** view (lucisv sidebar) lists every reference's full line
|
||||
with the identifier highlighted, grouped by file, the declaration marked;
|
||||
`Shift+Alt+F12` opens it in Verilog/SystemVerilog editors while
|
||||
`lucisv.references.fullLineView` is on (the default). Closed files are read
|
||||
without opening them on the server.
|
||||
|
||||
### Review fixes and housekeeping
|
||||
|
||||
- The closing-label fallback of an unnamed block no longer attaches a
|
||||
mismatched `end : a` (or an `endfunction : g` beside block `g`) to a
|
||||
same-named block.
|
||||
- `duplicate-declaration` reports sibling `for` generate blocks of one label,
|
||||
and a procedural block beside a generate block in either order.
|
||||
- Rename warnings: a comment between `.` and the name is still a path; a file
|
||||
that fails to lex is warned about instead of skipped.
|
||||
- Refactoring messages name a file by its path wherever another file shares
|
||||
its base name (the `.*` expansion, ANSI conversion, inline and extract too).
|
||||
- `lucisv_server`'s workspace state is split into seven modules (a pure
|
||||
move); `tools/release.sh` refuses to build when the extension's
|
||||
`package.json` / `package-lock.json` versions disagree with the binaries.
|
||||
|
||||
## 0.60.0 — 2026-10-08
|
||||
|
||||
### Rename and references through a generate block label
|
||||
|
||||
TODO §65.1, topo §2.9 row 43 (MCP-14). (`docs/features/generate-label-rename`.)
|
||||
|
||||
- **`rename` of a block label rewrites every path through it.** Renaming
|
||||
`g_lane` in `for (…) begin : g_lane` used to rewrite the label alone,
|
||||
leaving `g_lane[0].lane_q` (and `u_x.g_lane[1].sig` in another file)
|
||||
naming a block that no longer existed, with no warning. The label, its
|
||||
closing `end : g_lane`, and every path segment naming the block — bare,
|
||||
indexed (`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), behind an instance
|
||||
path from another file — are now one reference set, renamed all or
|
||||
nothing; a spelling inside macro text or a string is a warning. A name
|
||||
declared *inside* a block is likewise renamed through such a path. Named
|
||||
procedural blocks: `begin : lbl`, `end : lbl` and `disable lbl;` (and the
|
||||
`lbl: begin … end : lbl` form) are one set.
|
||||
- **`find_references`** (LSP `textDocument/references`, `lucisv-mcp find
|
||||
refs`) lists the declaration, the closing label and every segment, same
|
||||
file and cross-file, with the declaring file open or closed.
|
||||
- **`lucisv-mcp rename`** no longer refuses a `block`-kind declaration.
|
||||
- Resolution changes every consumer sees: a `for` generate block's label is a
|
||||
name of the enclosing module (its genvar is not); `generate … endgenerate`
|
||||
is not a scope; `blk.x` and `arr[0].field` (a packed struct array) resolve
|
||||
their tails; an unnamed `genblk1` still names nothing. The index cache
|
||||
format moves to 21, so a 0.59.0 cache is rebuilt once.
|
||||
- **A rename says so when a path it cannot resolve spells the name**: a
|
||||
hierarchical path segment in any file of the rename's set that resolved to
|
||||
no declaration (`tb.dut.gen_x[0].q`, rooted at a top module) is left
|
||||
unchanged and warned about with its lines, for every kind of declaration;
|
||||
and renaming a member one arm of a generate `if`/`case` declares warns
|
||||
about the same-named member of the arm sharing its label.
|
||||
- `duplicate-declaration` now also reports a block label beside a net,
|
||||
variable, parameter or instance of the same name, and such a label is no
|
||||
longer counted as a read of the net.
|
||||
- Rename and port warnings name a file by its path whenever another file of
|
||||
the set shares its base name (two `pwrmgr_if.sv` are two findable lines,
|
||||
root-relative in `lucisv-mcp`), and a line a path warning names is not
|
||||
repeated under `unresolved:`. Same-named members are warned about through
|
||||
every enclosing same-label generate arm (`g.h.x`), and an escaped name's
|
||||
unresolved paths are found too.
|
||||
- **Rename warnings and mentions are about the renamed declaration.** For a
|
||||
member of a module or interface (a net, variable, port, parameter, block,
|
||||
…), a bare spelling of its name in a macro argument, a `` `define`` body, an
|
||||
unstructured assertion, a comment or a string is reported only where it can
|
||||
mean it: in the declaration's **home set** — the declaring file,
|
||||
everything it `` `include``s, whatever includes it (transitively), and the
|
||||
files the rename edits. In code, a spelling in the declaring file is
|
||||
reported after a scope lookup finds the declaration there (an instantiating
|
||||
module's own same-named signal is not); one in an included fragment always;
|
||||
a `` `define`` body when the macro is invoked from the home set (through
|
||||
other macros too — `ASSERT_DEFAULT_CLK`'s `clk_i`); a macro argument inside
|
||||
a `bind` into the declaring module; and a bare use in the plain code of an
|
||||
included fragment (`prim_util_memload.svh`'s `mem`) is named as a use the
|
||||
rename could not edit. Reported wherever they are written: a dotted
|
||||
spelling (`.state_q`, a possible hierarchical path); a bare macro argument
|
||||
the macro carries to the declaration — after a `.` (`` `CONN(state_q)``
|
||||
building `.state_q(state_q)`, `` `FORCE(state_q)`` building
|
||||
`force u_m.state_q`), into a `bind` into the declaring module, or into a
|
||||
macro lucisv has no definition of; and the body of a macro that expands to
|
||||
such a `bind`. Not reported: a body whose spellings are only its own
|
||||
parameter named like the declaration (unless the body also spells the name
|
||||
after a `.`, or a default argument spells it), and a backtick inside a
|
||||
string. Any doubt means no scoping: a module, interface, package or
|
||||
package member, a declaration outside a module, or one whose home set holds
|
||||
an include lucisv cannot resolve (a macro-built name, a file outside the
|
||||
project such as `uvm_macros.svh`) is reported everywhere as before. On
|
||||
opentitan the `state_q` rename's answer went from 274 lines (61 kB, 230
|
||||
macro warnings, 229 about other modules) to about 72 lines (12 kB),
|
||||
`hmac_core.StIdle`'s from 48 lines to 3.
|
||||
- `duplicate-declaration` also reports a block label beside a port, genvar,
|
||||
typedef, function or task, and two named procedural blocks of one label in
|
||||
one scope.
|
||||
- `lucisv-mcp rename` with many warnings is fast again: rooting the warning
|
||||
paths was quadratic per warning (a `state_q` rename on opentitan: 125 s →
|
||||
3.3 s). Naming the files in warnings no longer scans the whole set once per
|
||||
file either: the engine's part of that rename went from 2.9 s to 2.2 s.
|
||||
- A use in a file that includes the declaring file (or that it includes) is
|
||||
no longer reported as "left unchanged" when the rename did rewrite it —
|
||||
renaming a module whose instantiation sits in a file included beside it
|
||||
said so wrongly.
|
||||
|
||||
## 0.59.0 — 2026-09-29
|
||||
|
||||
### MCP read-only mode
|
||||
|
||||
@@ -84,11 +84,19 @@ now): largest files `tools/read.rs` 405, `tools/item.rs` 379, `tools/item/verify
|
||||
`vlog_refactor/src/rename/connections.rs` at 477 and `check/mod.rs` at 426,
|
||||
and `lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55).
|
||||
|
||||
Re-measured 2026-10-14 after TODO §55 (pure move, `docs/features/decomposition-state`):
|
||||
`state/mod.rs` 63, the largest `state/` file `discover.rs` 412 (`rescan.rs` 411);
|
||||
files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
|
||||
`vlog_parser/src/lexer.rs` 771, `vlog_formatter/src/format/stmt.rs` 604.
|
||||
|
||||
## Rust standards
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
without a comment explaining why), `cargo test` green — all three
|
||||
before declaring any work finished.
|
||||
before declaring any work finished. **Before a release, and whenever
|
||||
the whole workspace is gated, run `tools/gates.sh`** (every gate as a
|
||||
separate guarded step with kept logs; `--only`/`--skip` for a subset)
|
||||
instead of a bare `cargo test --workspace`.
|
||||
- No `unwrap()`/`expect()`/`panic!` in library code paths; return
|
||||
`Result`. Tests and `main.rs` argument handling may use them.
|
||||
- Public items get a one-line doc comment. Doc comments say what/why,
|
||||
@@ -131,6 +139,19 @@ Rules:
|
||||
|
||||
## Workflow
|
||||
|
||||
- **Agent models**: the lead plans and reviews; coding goes to one dev
|
||||
agent and verification to one QA agent, **both Claude Opus 5.5**
|
||||
(`model: "opus"`). This holds for a single lane and for each of two
|
||||
parallel lanes.
|
||||
- **Refactor lanes** (pure moves, decompositions): the dev is **Claude
|
||||
Fable 5.2 at high reasoning effort** — the `refactor-dev` agent in
|
||||
`.claude/agents/`. Its brief says: no new tests beyond what the move
|
||||
forces, the gates are the proof, spend the effort on module
|
||||
boundaries, naming and readability. QA is unchanged (Opus 5.5).
|
||||
- **Escalation**: a first QA failure gets a normal Opus 5.5 fix round.
|
||||
When a fix round fails QA a **second** time on the same feature, redo
|
||||
the round with **Claude Fable 5.2 as both dev and QA**
|
||||
(`model: "fable"`).
|
||||
- Do **not** run `git commit` or `git push` — the lead reviews and
|
||||
commits all work.
|
||||
- Do not touch files outside your feature's stated scope. If you need a
|
||||
@@ -155,6 +176,9 @@ process tree when its resident set or wall clock exceeds the limits
|
||||
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
|
||||
- A guard kill is a finding: report the command and the limit it hit;
|
||||
do not raise the limit to make it pass.
|
||||
- The release gate is `tools/gates.sh`, which guards each step with its
|
||||
own limits and retries a killed step once (shown as `KILLED → retried`);
|
||||
do not wrap it in another `guard.sh`.
|
||||
|
||||
## Parallel lanes (the 2-agent loop)
|
||||
|
||||
@@ -176,8 +200,9 @@ proven independent and run serially. Rules for a parallel wave:
|
||||
while lanes are in flight; the lead merges each lane back only after
|
||||
that lane's QA verdict and lead review, and re-runs the full gates on
|
||||
the merged tree before pushing.
|
||||
- **Roles per lane are unchanged**: one dev (Opus), then one QA
|
||||
(Sonnet) in the same worktree, then the lead's review — so at most
|
||||
- **Roles per lane are unchanged**: one dev, then one QA — **both
|
||||
Claude Opus 5.5** (owner, 2026-11-09; QA was Sonnet before) — in the
|
||||
same worktree, then the lead's review — so at most
|
||||
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
|
||||
its own dev is done. A QA rework loops inside its lane without
|
||||
blocking the other lane.
|
||||
|
||||
Generated
+9
-9
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
@@ -126,7 +126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -279,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -292,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -13,7 +13,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.59.0"
|
||||
version = "0.65.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -1037,11 +1037,13 @@ expected; no PRs or review required.
|
||||
|
||||
```bash
|
||||
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
|
||||
tools/gates.sh # every gate: fmt, clippy, build, each crate's suites, doc tests, corpus, node
|
||||
tools/gates.sh --only suites # just the per-crate test suites
|
||||
```
|
||||
|
||||
`tools/gates.sh` runs each gate as its own guarded step with a kept log and
|
||||
prints a summary (`docs/features/release-gates/README.md`).
|
||||
|
||||
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
|
||||
expected outputs only for intentional formatting changes with
|
||||
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
|
||||
|
||||
@@ -5084,11 +5084,14 @@ scope/widen logic, the document store, and the source selectors
|
||||
(`module_sources`, `rename_sources`) are three sentences. Not planned; the
|
||||
owner decides where it goes in loop 2.
|
||||
|
||||
- [ ] `state.rs` decomposition (pure move, byte-identical output, test
|
||||
- [x] `state.rs` decomposition (pure move, byte-identical output, test
|
||||
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
|
||||
the owner schedules it — **done 2026-10-14**
|
||||
(`docs/features/decomposition-state/README.md`: `state/` is ten
|
||||
modules, largest 412 production lines; the CLAUDE.md measurement
|
||||
line is the lead's, requested in that README's Handshakes)
|
||||
|
||||
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
|
||||
|
||||
@@ -6939,3 +6942,324 @@ Nothing else.
|
||||
(23e2e4b, v0.55.0), CI green on the release commit, 8 assets, the
|
||||
darwin-arm64 vsix at 0.55.0 with both binaries,
|
||||
`hierarchySections.js`, `extract.js`, no `*_test.js`.
|
||||
|
||||
## 65. Stabilization round 1 (planned 2026-09-30, owner's order) — two correctness gaps, then the doc-test stall
|
||||
|
||||
Three lanes, one at a time on trunk, dev (Opus) → QA (Opus) → lead review →
|
||||
commit. Rules as §63/§64: every suite and sweep through `tools/guard.sh`,
|
||||
never piped (log to a file, check `guard exit` and the suite count); no
|
||||
`sleep` over 60 s; never `grep` without a path; opentitan read-only (the
|
||||
eval clone `~/.cache/lucisv-eval/ot` may be read and, for an edit test,
|
||||
restored with `git -C … checkout -- <file>`). ~~Ships as 0.60.0.~~
|
||||
**Release targets (corrected 2026-10-19):** 65.1 shipped in **0.60.0**
|
||||
(2026-10-08); 65.2, 65.3 and 65.4 are open and target **0.62.0** (wave
|
||||
below, §65.7); 65.6 is unscheduled.
|
||||
|
||||
### 65.1 Rename and references through a generate block label (topo §2.9-43, MCP-14)
|
||||
|
||||
`rename` of a generate block label (`for (…) begin : g_lane … end`) rewrites
|
||||
the label and nothing else: a hierarchical path through it
|
||||
(`g_lane[0].lane_q`, `u_x.g_lane[1].sig` from another file) keeps the old
|
||||
name and no longer resolves, with no warning; `find_references` on the label
|
||||
reports no use. The MCP layer refuses the rename (any `block`-kind
|
||||
declaration); the LSP and the CLI still perform it. Feature README
|
||||
`docs/features/generate-label-rename`.
|
||||
|
||||
The contract to reach, in `vlog_semantic` (resolution) and `vlog_refactor`
|
||||
(`find_references`, `rename`, the verifier):
|
||||
|
||||
- [x] a path segment that names a generate block — bare (`g.x`), indexed
|
||||
(`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), and behind an instance
|
||||
path from another file (`u_x.g[0].x`) — resolves to the block's label
|
||||
and is a reference to it
|
||||
- [x] `find_references` on the label lists the declaration, the closing
|
||||
`end : label` and every such segment, same-file and cross-file, through
|
||||
the same fan-out §64.1 uses for hierarchical-surface declarations
|
||||
- [x] `rename` rewrites all of them, all-or-nothing; a closing label is
|
||||
rewritten with its opening one; a segment it cannot resolve (macro
|
||||
text, a string) is a warning, as for any other declaration; an
|
||||
unnamed block (`genblk1`) is not renameable
|
||||
- [x] named procedural blocks (`begin : lbl` in `always`/`initial`/
|
||||
functions/tasks): the label, its closing label and `disable lbl;` are
|
||||
one reference set
|
||||
- [x] the verifier accepts exactly these rewrites and nothing more:
|
||||
masked-corruption attack tests for any normalization it gains
|
||||
(CLAUDE.md invariant 4)
|
||||
- [x] the LSP (`textDocument/references`, `rename`, `prepareRename`) and
|
||||
the CLI get it through the engine; `lucisv-mcp`'s refusal of a
|
||||
`block`-kind rename (`crates/lucisv_mcp/src/tools/edit.rs`) is lifted
|
||||
and its tests (`tests/qa_m7.rs`) assert the rename instead
|
||||
- [x] opentitan: a generate label with cross-file uses renamed on the eval
|
||||
clone — every site rewritten, the files still parse, clone restored
|
||||
- [x] rename warnings and mentions are scoped to the renamed declaration
|
||||
(lead's inspection 2026-09-30: a module member's bare spelling
|
||||
elsewhere is not news; a dotted one and a unit/package name's every
|
||||
spelling still are)
|
||||
- [x] QA: attack the index forms, nesting, shadowing (a net and a block of
|
||||
the same name in different scopes), a label used only in a closing
|
||||
label, `disable`, an escaped label, a label inside an `ifdef`
|
||||
|
||||
### 65.2 LSP `references` omits three `aes` instantiations (topo §2.9-36, MCP-6)
|
||||
|
||||
On opentitan, `textDocument/references` at the `aes` instantiation in
|
||||
`hw/ip/aes/dv/tb/tb.sv` (and at its `.clk_i` connection) answers 11 and 9
|
||||
locations; the whole-set engine answers 14 and 12 — the same plus the three
|
||||
top-level instantiations in
|
||||
`hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`
|
||||
(`aes #(` and `.clk_i(clkmgr_clocks_i.clk_main_aes)`). Stable after a 30 s
|
||||
settle, so not an indexing race. Feature README
|
||||
`docs/features/references-fanout-pd-main`.
|
||||
|
||||
- [x] root cause named (the fan-out/scope selection in `lucisv_server` —
|
||||
`module_select`, `state/` scope widening, or the index's
|
||||
instantiation facts for those three files; they are large generated
|
||||
files, check the 1 MiB cap and the word census)
|
||||
- [x] ~~the LSP answer equals the whole-set engine's for the module name and
|
||||
for a port of it, from the declaration and from a use; a regression
|
||||
test with a fixture that reproduces the cause (not only opentitan)~~ — **closed by the owner's ruling 2026-10-19: scope-relative by design.** The LSP answer equals the engine over the same file set (pinned for both scopes in `server/tests/references_scope.rs`); the default `folder` scope does not reach the three tops, `workspace` does (14/12).
|
||||
- [x] an opentitan test (ignored by default, like `tests/opentitan.rs`)
|
||||
pinning the 14 and 12
|
||||
- [x] ~~QA: the same comparison for five other modules instantiated from a
|
||||
`*_pd_main.sv` top, and for `rename`'s fan-out (does rename see the
|
||||
three sites?)~~ — not run: no production code changed under the ruling
|
||||
|
||||
### 65.3 The combined test command stalls entering the doc-tests
|
||||
|
||||
`cargo test --workspace` under `tools/guard.sh`: on 2026-09-29 (0.59.0 gate)
|
||||
every suite finished in about two minutes and the run then sat 25 minutes
|
||||
in `Doc-tests vlog_linter` until the guard cut it; on 2026-09-30 an
|
||||
independent session's run hit its 600 s guard "entering the final doc-test
|
||||
harness". `cargo test --workspace --doc` alone passes in under a minute.
|
||||
|
||||
- [x] reproduce (how often, which doc-test, what the stuck process tree
|
||||
is — `rustdoc`, `rust_out`, stdin?) and name the cause; `guard.sh`
|
||||
runs the command with `0<&3` — check what the doc-test harness
|
||||
inherits as stdin when the gate runs in the background
|
||||
- [x] fix at the cause (the harness, the doc-test, or the guard), and make
|
||||
the release gate a script (`tools/gates.sh`) that runs fmt, clippy,
|
||||
the test build, the suites, the doc-tests, the corpus gate and the
|
||||
node tests as separate guarded steps with logs kept and a summary
|
||||
that shows a kill — `tools/RELEASING.md` and CLAUDE.md point at it
|
||||
- [x] ten consecutive green runs of the gate script recorded
|
||||
|
||||
### 65.4 Resolve a hierarchical path rooted at a top-level module name (lead to schedule; from §65.1 QA F1)
|
||||
|
||||
A path whose head is a top module declared in another file — `tb.dut.u_x.sig`,
|
||||
the shape every opentitan DV `force`/`$deposit`/`uvm_hdl_*` path takes
|
||||
(IEEE 1800 §23.6: a top-level module name is the root of a hierarchical
|
||||
name) — resolves nothing today: `tb` is bound as a `Target::Lexical` use,
|
||||
misses in the writing file, and `resolve::member_site`'s `head_site` stops
|
||||
the spine, so no segment after it is a reference and a rename of `dut`'s
|
||||
declarations leaves the path behind (since §65.1 with a warning, not
|
||||
silently). The root lookup belongs in `vlog_semantic/src/resolve.rs`
|
||||
`head_site`: when the lexical walk misses **and** the head is followed by a
|
||||
`.`, answer `MemberSite::Unit { path: head, surface: Hierarchical }` so the
|
||||
workspace's `fold_path` walks `tb` → `dut`'s type → … exactly as it walks an
|
||||
instance path today — with the head itself recorded as a `Target::Module`-like
|
||||
use so `tb` stops being `NotFound`. QA's repro: `vlog_refactor/tests/
|
||||
qa_generate_label.rs` `a_path_rooted_at_another_files_top_module_is_never_silently_left_behind`
|
||||
(`probe.sv`: `assign o = tb.dut.g_sw[0].buf_q;`), and on opentitan
|
||||
`hw/ip/keymgr_dpe/dv/env/keymgr_dpe_if.sv:514,515,517` (`force
|
||||
tb.dut.gen_sw_assigns[i]…`) under `rename gen_sw_assigns`. Watch: a name
|
||||
that is both a local and a top module (the local wins), `$root.tb…`, and the
|
||||
index cost of the extra external candidates on every DV path.
|
||||
|
||||
- [x] root lookup in `head_site`, the head recorded as a module use
|
||||
- [x] QA's repro renames the path instead of warning; the §65.1 warning
|
||||
still fires for a root the workspace does not declare
|
||||
|
||||
### 65.6 Rename inside included fragments (lead to schedule; from §65.1 QA final H4)
|
||||
|
||||
A module that `` `include``s a fragment of its own body (`prim_ram_1p.sv`
|
||||
including `prim_util_memload.svh`, every opentitan `*_assert.svh`) has that
|
||||
fragment's text pasted into its scope, but lucisv analyses the fragment as a
|
||||
file of its own: a bare `mem` there resolves to nothing, so `rename
|
||||
prim_ram_1p.mem` edits the module and — since §65.1 — only *warns*
|
||||
(`prim_util_memload.svh:12,24,32,43: `mem` is used in a file `prim_ram_1p.sv`
|
||||
includes and was left unchanged`). Renaming there means binding a fragment
|
||||
in the scope of the file that includes it (the include site's scope chain as
|
||||
the fragment's outer scope, as `fragment-mode` does for a bare body) and
|
||||
verifying the edit against that binding; a fragment included from two
|
||||
modules is two bindings and must agree or be refused. QA's repro:
|
||||
`vlog_refactor/tests/qa_warning_scope.rs`
|
||||
`a_bare_use_in_plain_included_code_is_renamed_or_said` (`m_body.svh`:
|
||||
`assign o = state_q;` included by `m.sv`).
|
||||
|
||||
- [ ] a fragment included by exactly one unit is bound in that unit's scope
|
||||
and renamed with it; one included by several is refused unless every
|
||||
binding agrees
|
||||
- [ ] QA's repro renames the fragment's use; the §65.1 warning remains for
|
||||
what cannot be bound
|
||||
|
||||
|
||||
### 65.7 Wave for 0.62.0 (planned 2026-10-19, owner's order: "fix those that are true")
|
||||
|
||||
Two parallel lanes first (disjoint files; neither touches `vlog_semantic`),
|
||||
then 65.4 serially (it changes `vlog_semantic` resolution, which §65.2's
|
||||
lane might also need — run after it merges).
|
||||
|
||||
**Lane A — §65.2 references fan-out** (Opus dev → QA → lead), files:
|
||||
`crates/lucisv_server/src/state/sources.rs`, `crates/lucisv_server/src/nav.rs`,
|
||||
new test files under `crates/lucisv_server/src/server/tests/`, a new
|
||||
ignored-by-default `crates/lucisv_server/tests/opentitan_references.rs`,
|
||||
`docs/features/references-fanout-pd-main/README.md`.
|
||||
|
||||
- [x] §65.2's checklist above (closed by ruling: scope-relative by design)
|
||||
|
||||
**Lane B — §65.3 gate script** (Opus dev → QA → lead), files:
|
||||
`tools/gates.sh` (new), `tools/guard.sh` (only if the cause is there),
|
||||
`tools/RELEASING.md`, `docs/features/release-gates/README.md` (new);
|
||||
CLAUDE.md's pointer is the lead's at merge.
|
||||
|
||||
- [x] §65.3's checklist above
|
||||
|
||||
**Then — §65.4 top-module-rooted paths** (serial, after lane A merges).
|
||||
|
||||
- [x] §65.4's checklist above (conservative by the owner's ruling: a head with an import candidate, inside a class, or beside a macro that could declare it is not rooted)
|
||||
|
||||
|
||||
### 65.8 Completion after a top-rooted path head (deferred from §65.4 H2, 2026-10-19)
|
||||
|
||||
`tb.` offers nothing in completion: the completion walk keeps "an unknown
|
||||
head answers nothing" (two `lucisv_server` completion tests pin it), while
|
||||
resolution now roots an unknown head at a top module. Decide whether
|
||||
completion should offer `tb.`'s hierarchical members, answering `None` when
|
||||
the index has no unit of that name. `docs/features/top-rooted-paths`.
|
||||
|
||||
- [ ] owner/lead decision; if yes, `completion/member.rs` + tests
|
||||
|
||||
## 66. Format Selection that fits where it stands (planned 2026-11-09, owner's order)
|
||||
|
||||
Owner's report: *Format Selection* "fails more than half of the time". The
|
||||
usual selection is one whole `always` block or one whole `case` statement,
|
||||
often nested inside blocks the selection does not cover. Reproduced on trunk
|
||||
(`lucisv --lines`, the engine `textDocument/rangeFormatting` shares): selecting
|
||||
a `case` re-lays the whole `always` around it; the block is re-indented to the
|
||||
formatter's own depth × width, so in a file indented any other way it no
|
||||
longer lines up with its neighbours; a selection inside `generate` re-lays the
|
||||
whole region; and a file with a parse error anywhere is refused outright.
|
||||
Owner's rule: do not worry about the parent — the selected block keeps the
|
||||
indentation level it starts at, and stays functionally the same.
|
||||
|
||||
### 66.1 VS Code language configuration (lead, done 2026-11-09)
|
||||
|
||||
- [x] `editors/vscode/language-configuration.json` (comment tokens, brackets,
|
||||
auto-closing and surrounding pairs) wired to both language ids in
|
||||
`editors/vscode/package.json` — Toggle Line/Block Comment (Ctrl+/) works
|
||||
without another Verilog extension installed.
|
||||
|
||||
### 66.2 Selection formatting (one lane: dev, then QA)
|
||||
|
||||
Feature README: `docs/features/selection-formatting/README.md`. Files:
|
||||
`crates/vlog_formatter/src/selection.rs` (+ a `selection/` split if it nears
|
||||
600 lines), `crates/vlog_formatter/src/{lib.rs,printer.rs,format/mod.rs}`,
|
||||
`crates/vlog_formatter/tests/selection.rs`, `crates/lucisv_server/src/format.rs`,
|
||||
`crates/lucisv_server/src/server/tests/formatting.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`. `verify.rs`, `range.rs`, `fence.rs`, the
|
||||
parser and the CLI's `--lines` are not touched.
|
||||
|
||||
- [x] `format_selection`: the smallest run of sibling items/statements the
|
||||
selected lines cover, laid out alone at the indentation it was written
|
||||
at, spliced into otherwise untouched bytes.
|
||||
- [x] Verified whole-file (`verify_equivalence`, unchanged) and converged by
|
||||
replaying the located target, not the line numbers.
|
||||
- [x] Fences outrank the selection; a module/package-level target defers to
|
||||
`format_range` (header/footer splitting).
|
||||
- [x] A file that does not parse: the target is located in the tolerant tree
|
||||
and refused when a diagnostic falls inside it.
|
||||
- [x] `textDocument/rangeFormatting` / `rangesFormatting` call it.
|
||||
- [x] Tests: the owner's shapes (whole `always`, whole `case`, inside
|
||||
`generate`, inside a function), off-grid and tab indentation, partial
|
||||
selections, comments, fences, broken files, masked-corruption attacks on
|
||||
the splice.
|
||||
|
||||
## 67. Sticky scroll shows every layer (planned 2026-11-11, owner's order)
|
||||
|
||||
VS Code pinned only the module header, because sticky scroll follows the
|
||||
document-symbol outline by default and the outline stops at declarations.
|
||||
The server's folding ranges already carry every `begin`/`end`, `case`,
|
||||
`fork`, `generate` and function — one fold per layer, starting on its header
|
||||
line.
|
||||
|
||||
- [x] `editors/vscode/package.json` `configurationDefaults` for both language
|
||||
ids: `editor.stickyScroll.defaultModel` = `foldingProviderModel` and
|
||||
`editor.stickyScroll.maxLineCount` = 10 (VS Code's default of 5 is the
|
||||
owner's example exactly, with nothing to spare). A user's own setting
|
||||
still wins.
|
||||
- [x] `crates/lucisv_server/src/folding.rs`: a test pinning that each layer
|
||||
of the owner's example (module, `always`, `case`, case item, `if`)
|
||||
starts a fold on its header line.
|
||||
- [ ] Seen in a running VS Code (owner).
|
||||
- Known limit: a layer with no `begin` (a one-statement `if`, a case item
|
||||
without `begin`) has no fold and so no pinned line; a `begin` written on
|
||||
its own line pins that `begin` line, not the `always` above it.
|
||||
|
||||
## 68. Completion that keeps up with typing (planned 2026-11-17, owner's order)
|
||||
|
||||
Five asks from the owner, about the VS Code extension. Two serial lanes
|
||||
(`lucisv_server` depends on `vlog_parser`, so they are not independent):
|
||||
68.1 first, then 68.2. Each lane: one dev, then one QA, both Opus 5.5.
|
||||
|
||||
### 68.1 Lane A — auto-`end`, templates, ranking, keyword ghosts, port items
|
||||
|
||||
Feature README: `docs/features/completion-ux/README.md`. Files:
|
||||
`crates/lucisv_server/src/{on_type.rs,inline.rs,templates.rs,pairs.rs,settings.rs,main.rs}`,
|
||||
`crates/lucisv_server/src/completion/*`, new modules beside them where a
|
||||
file is near 600 production lines, `crates/lucisv_server/tests/e2e.rs`,
|
||||
`editors/vscode/{extension.js,package.json,smoke.js,README.md}` and a new
|
||||
`editors/vscode/*_test.js` if the extension logic is factored out. No
|
||||
parser, formatter, linter or semantic crate change.
|
||||
|
||||
- [x] **`begin` + Enter writes the `end`** (owner: "more like begin +
|
||||
<return>, the cursor should be the next line of begin, at the correct
|
||||
indentation, and ready for the first statement"). The newline on-type
|
||||
answer, when the line above ends in `begin` (or `begin : label`) and
|
||||
the file has an unclosed `begin`, also inserts `end` on the line after
|
||||
the new one, at the indentation of the statement the `begin` belongs
|
||||
to; the cursor stays on the new, indented line. No `end` when the
|
||||
blocks already balance. Setting `lucisv.autoEnd` (default on). The
|
||||
extension sends the request itself when `editor.formatOnType` is off
|
||||
and puts the cursor back.
|
||||
- [x] **`always_ff @(` / `always @(` expand with clock and reset**:
|
||||
`posedge ${1:clk} or negedge ${2:rst_n}`, both tab stops, in the ghost
|
||||
and as the first popup template; the clock-only form stays available
|
||||
second.
|
||||
- [x] **Names from the current file rank first** in the popup: declared
|
||||
anywhere in this buffer, then words used in it, ahead of other files'
|
||||
names and of keywords.
|
||||
- [x] **Keyword ghosts**: a typed prefix of a keyword shows the rest of it
|
||||
as grey inline text (Tab accepts), following the popup's selected item
|
||||
when the popup is open. Setting `lucisv.inlineKeywords` (default on).
|
||||
- [x] **Port items**: unconnected ports first; already-connected ports
|
||||
listed after them, marked `connected` in the dimmed detail; accepting
|
||||
a port writes `.name($1)` with the cursor inside the parentheses.
|
||||
|
||||
### 68.2 Lane B — no rushed errors on the connection being typed
|
||||
|
||||
Feature README: `docs/features/port-entry-grace/README.md`. Files:
|
||||
`crates/vlog_parser/src/parser/instance.rs` (+ its tests),
|
||||
`crates/lucisv_server/src/{diagnostics.rs,server/diagnostics.rs,state/*}`.
|
||||
|
||||
- [x] Parser recovery keeps an unfinished connection (`.`, `.name(` open to
|
||||
the end of its line, a missing `,` before the next `.name`) inside its
|
||||
own entry — still a diagnostic, never silent — so the rest of the file
|
||||
parses, colours and lints as if the entry were complete.
|
||||
- [x] The server withholds the diagnostics that fall inside the entry the
|
||||
last edit touched, and releases them after a quiet period or when the
|
||||
next edit lands elsewhere.
|
||||
|
||||
## 69. Module instantiation syntax highlighting (2026-11-17, owner's order)
|
||||
|
||||
Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
|
||||
`crates/lucisv_server/src/{tokens.rs,tokens/instantiation.rs}`,
|
||||
`editors/vscode/{package.json,.vscodeignore,semanticTokens_test.js}`,
|
||||
`docs/features/{lucisv-server,large-file-mode}/README.md`.
|
||||
|
||||
- [x] Distinct semantic highlights across module instantiations (14-type wire
|
||||
legend unchanged): module name (`class`), `#` + `.PARAM` overrides +
|
||||
parameter values (`parameter`, distinct from `()`), instance name
|
||||
(`function`), `.port`/`.*` (`property`), and port connections
|
||||
(`variable`), including unfinished entries while typing.
|
||||
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
|
||||
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
|
||||
non-white TextMate scopes across themes.
|
||||
@@ -45,10 +45,14 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
}
|
||||
let set = whole_set(project, Some(&path), std::slice::from_ref(&name))?;
|
||||
let edit = vlog_refactor::rename(&set.files, &path, declaration.offset, new_name)
|
||||
.map_err(|why| set.rooted(project, &why))?;
|
||||
.map_err(|why| set.rooted(&why))?;
|
||||
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
|
||||
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
|
||||
let told = Told { name: &name, home: &path, unit: unit.as_deref() };
|
||||
// A member of a module is named bare only where it is declared or used;
|
||||
// the module (or interface, program) itself is named anywhere.
|
||||
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
|
||||
let member = unit.is_some() && !unit_itself;
|
||||
let told = Told { name: &name, home: &path, unit: unit.as_deref(), member };
|
||||
let done = write_telling(project, edit, &set, &told)?;
|
||||
let (sites, files) = (render::count(sites, "site"), render::count(done.files, "file"));
|
||||
let mut lines = vec![format!("renamed {sites} in {files}")];
|
||||
@@ -62,6 +66,8 @@ struct Picked {
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
offset: u32,
|
||||
/// The declaration's kind word (`module`, `var`, …).
|
||||
kind: &'static str,
|
||||
}
|
||||
|
||||
fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String> {
|
||||
@@ -87,16 +93,9 @@ fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String>
|
||||
[one] if one.is_macro() => {
|
||||
Err(format!("`{name}` is a macro; lucisv does not rename macros."))
|
||||
}
|
||||
// The engine rewrites no hierarchical path through a block and
|
||||
// reports none as a use, so the rename could not be complete
|
||||
// (topo §2.9 MCP-14).
|
||||
[one] if one.kind == "block" => Err(format!(
|
||||
"`rename` does not rename generate block labels: paths through the block (`{}[0].…`) would not be rewritten; edit the file.",
|
||||
names::qualified(name).1
|
||||
)),
|
||||
[one] => {
|
||||
let name = names::qualified(name).1.to_string();
|
||||
Ok(Picked { name, path: one.path.clone(), offset: one.offset })
|
||||
Ok(Picked { name, path: one.path.clone(), offset: one.offset, kind: one.kind })
|
||||
}
|
||||
many => Err(names::ambiguous(name, many, "pass `file`, and `name@LINE` within one file")),
|
||||
}
|
||||
@@ -129,6 +128,10 @@ pub(super) struct Told<'a> {
|
||||
pub name: &'a str,
|
||||
pub home: &'a Path,
|
||||
pub unit: Option<&'a str>,
|
||||
/// Whether the name is a member of a module or interface: its bare
|
||||
/// mentions outside its home set (`vlog_refactor::home_set`) are not
|
||||
/// listed.
|
||||
pub member: bool,
|
||||
}
|
||||
|
||||
/// What a written edit says after its first line: how many files it wrote,
|
||||
@@ -151,21 +154,58 @@ pub(super) fn write_telling(
|
||||
let accounted: Vec<(PathBuf, Vec<TextRange>)> =
|
||||
edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect();
|
||||
let plan = Plan::from_refactor(edit, &set.files)?;
|
||||
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(w)).collect();
|
||||
let named = path_warned(&warnings);
|
||||
let written = set.files.iter().map(|(path, text)| {
|
||||
let change = plan.changes.iter().find(|change| &change.path == path);
|
||||
(path.as_path(), change.map_or(text.as_str(), |change| change.after.as_str()))
|
||||
});
|
||||
let focus = Focus { name: told.name, home: told.home, unit: told.unit, accounted: &accounted };
|
||||
// The member's home set (the declaring file, what it includes and what
|
||||
// includes it, and the edited files): where a bare mention can mean it.
|
||||
let edited: Vec<PathBuf> = plan.changes.iter().map(|change| change.path.clone()).collect();
|
||||
// `None` — list every mention — for a non-member, and for a member whose
|
||||
// home set is not known (an include the engine cannot resolve).
|
||||
let local = match told.member {
|
||||
true => vlog_refactor::home_set(&set.files, told.home, &edited),
|
||||
false => None,
|
||||
};
|
||||
let focus = Focus {
|
||||
name: told.name,
|
||||
home: told.home,
|
||||
unit: told.unit,
|
||||
accounted: &accounted,
|
||||
named: &named,
|
||||
local: local.as_deref(),
|
||||
};
|
||||
let mentions = mentions::find(project, written, &focus);
|
||||
let done = apply::run(project, &plan)?;
|
||||
let mut tail = Vec::new();
|
||||
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(project, w)).collect();
|
||||
render::warnings(&mut tail, &warnings);
|
||||
tail.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
|
||||
tail.extend(mentions.block());
|
||||
Ok(Done { files: done.changed.len() + done.created.len(), tail })
|
||||
}
|
||||
|
||||
/// The `(file, line)` pairs the engine's unresolved-path warnings name
|
||||
/// (`rtl/a.sv:3,7: a hierarchical path through …`), so the `unresolved:`
|
||||
/// block does not list them a second time.
|
||||
fn path_warned(warnings: &[String]) -> Vec<(String, u32)> {
|
||||
let mut out = Vec::new();
|
||||
for warning in warnings {
|
||||
let Some((head, _)) = warning.split_once(": a hierarchical path through `") else {
|
||||
continue;
|
||||
};
|
||||
let Some((file, lines)) = head.rsplit_once(':') else { continue };
|
||||
out.extend(
|
||||
lines
|
||||
.split(',')
|
||||
.filter_map(|line| line.parse().ok())
|
||||
.map(|line| (file.to_string(), line)),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where each of one file's edits lands in the text as written: its start
|
||||
/// shifted by what the edits before it added or removed, its length the
|
||||
/// new text's.
|
||||
|
||||
@@ -83,7 +83,7 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
|
||||
account(&mut accounted, hits);
|
||||
}
|
||||
Err(why) => {
|
||||
let why = engine_refusal(&set.rooted(project, &why));
|
||||
let why = engine_refusal(&set.rooted(&why));
|
||||
lines.push(format!(" uses not listed: {why}"));
|
||||
}
|
||||
}
|
||||
@@ -93,13 +93,46 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
|
||||
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
|
||||
}
|
||||
let home = &found[0].path;
|
||||
let focus = Focus { name, home, unit: None, accounted: &accounted };
|
||||
let local = member_files(&set, found, &accounted);
|
||||
let focus = Focus {
|
||||
name,
|
||||
home,
|
||||
unit: None,
|
||||
accounted: &accounted,
|
||||
named: &[],
|
||||
local: local.as_deref(),
|
||||
};
|
||||
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
|
||||
lines.extend(mentions::find(project, files, &focus).block());
|
||||
lines.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
|
||||
lines
|
||||
}
|
||||
|
||||
/// The files a bare mention of a **module member** can mean it in — each
|
||||
/// declaration's home set (`vlog_refactor::home_set`) with every file the
|
||||
/// engine found a use in — or `None` when
|
||||
/// any declaration is not a member (a unit, a package member, a macro), whose
|
||||
/// every mention is listed (§65.1, lead's inspection: a `state_q` found in forty
|
||||
/// modules is not news about this one).
|
||||
fn member_files(
|
||||
set: &WholeSet,
|
||||
found: &[Declaration],
|
||||
accounted: &[(PathBuf, Vec<TextRange>)],
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
if found.iter().any(Declaration::is_macro) {
|
||||
return None;
|
||||
}
|
||||
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
|
||||
let mut local: Vec<PathBuf> = Vec::new();
|
||||
for declaration in found {
|
||||
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
|
||||
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
|
||||
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)?;
|
||||
local.extend(vlog_refactor::home_set(&set.files, &declaration.path, &hit_files)?);
|
||||
}
|
||||
Some(local)
|
||||
}
|
||||
|
||||
/// The engine's hits, one file per line: `file:12,40`.
|
||||
fn uses(project: &Project, set: &WholeSet, hits: &[(PathBuf, TextRange)]) -> Vec<String> {
|
||||
let mut sites: Vec<(String, u32)> = Vec::new();
|
||||
|
||||
@@ -52,6 +52,17 @@ pub struct Focus<'a> {
|
||||
pub unit: Option<&'a str>,
|
||||
/// Per file, the spans an engine returned (hits) or rewrote (edits).
|
||||
pub accounted: &'a [(PathBuf, Vec<TextRange>)],
|
||||
/// `(file, line)` pairs an engine warning already names — a `rename`'s
|
||||
/// unresolved-path warning — which are not repeated as mentions.
|
||||
pub named: &'a [(String, u32)],
|
||||
/// For a member of a module or interface (a net, a port, a block, …):
|
||||
/// the files where a bare spelling can mean it — its home set: the
|
||||
/// declaring file, what it includes and what includes it, and the files
|
||||
/// the edit wrote or the engine found uses in. Elsewhere only a
|
||||
/// spelling right after a `.` (`".state_q"`, `` `HIER.u.state_q``) is
|
||||
/// listed. `None` for a name any file may spell bare (a unit, a package
|
||||
/// member): every mention is listed.
|
||||
pub local: Option<&'a [PathBuf]>,
|
||||
}
|
||||
|
||||
impl Mentions {
|
||||
@@ -93,7 +104,13 @@ pub fn find<'t>(
|
||||
let spans = accounted.map_or(&[][..], |(_, spans)| spans.as_slice());
|
||||
let lines = LineIndex::new(text);
|
||||
let mut last_line = 0;
|
||||
let foreign = focus.local.is_some_and(|local| !local.iter().any(|p| p == path));
|
||||
for (at, _) in spellings(text, focus.name) {
|
||||
if foreign
|
||||
&& !text.as_bytes().get((at as usize).wrapping_sub(1)).is_some_and(|&b| b == b'.')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let end = at + focus.name.len() as u32;
|
||||
if spans.iter().any(|span| span.start <= at && end <= span.end) {
|
||||
continue;
|
||||
@@ -109,6 +126,9 @@ pub fn find<'t>(
|
||||
.unwrap_or("");
|
||||
let rank = rank(accounted.is_some(), focus.unit, source);
|
||||
let mention = Mention { file: project.relative(path), line };
|
||||
if focus.named.iter().any(|(file, at)| *file == mention.file && *at == line) {
|
||||
continue;
|
||||
}
|
||||
found.push((rank, shared_components(path, focus.home), mention));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,18 +63,18 @@ fn add_port(
|
||||
) -> Result<Answer, String> {
|
||||
let set = whole_set(project, None, &[module.to_string()])?;
|
||||
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(module), declaration)
|
||||
.map_err(|why| set.rooted(project, &why))?;
|
||||
.map_err(|why| set.rooted(&why))?;
|
||||
let tokens = vlog_parser::tokenize(declaration).unwrap_or_default();
|
||||
let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default();
|
||||
let show = &|path: &Path| project.relative(path);
|
||||
let edit = match after.map(str::trim) {
|
||||
Some(after) => {
|
||||
let spec = place::Spec { module, file, after, port: &port, declaration, show };
|
||||
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(project, &why))?
|
||||
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(&why))?
|
||||
}
|
||||
None => edit,
|
||||
};
|
||||
let told = Told { name: &port, home: file, unit: Some(module) };
|
||||
let told = Told { name: &port, home: file, unit: Some(module), member: true };
|
||||
let (count, files) = instantiations(project, module);
|
||||
let done = write_telling(project, edit, &set, &told)?;
|
||||
let head = format!("added port {port} in module {module}: {}", census(count, files));
|
||||
@@ -89,9 +89,9 @@ fn remove_port(
|
||||
) -> Result<Answer, String> {
|
||||
let offset = port_offset(project, module, file, port)?;
|
||||
let set = whole_set(project, Some(file), &[port.to_string(), module.to_string()])?;
|
||||
let edit = vlog_refactor::remove_port(&set.files, file, offset)
|
||||
.map_err(|why| set.rooted(project, &why))?;
|
||||
let told = Told { name: port, home: file, unit: Some(module) };
|
||||
let edit =
|
||||
vlog_refactor::remove_port(&set.files, file, offset).map_err(|why| set.rooted(&why))?;
|
||||
let told = Told { name: port, home: file, unit: Some(module), member: true };
|
||||
let (count, files) = instantiations(project, module);
|
||||
let done = write_telling(project, edit, &set, &told)?;
|
||||
let head = format!("removed port {port} in module {module}: {}", census(count, files));
|
||||
|
||||
@@ -76,6 +76,10 @@ pub struct WholeSet {
|
||||
pub files: Vec<(PathBuf, String)>,
|
||||
/// The files left out, with why.
|
||||
pub skipped: Vec<(PathBuf, String)>,
|
||||
/// How an engine sentence names each file of the set, and the
|
||||
/// root-relative spelling it becomes — built once per set by
|
||||
/// [`WholeSet::read`] ([`WholeSet::rooted`]).
|
||||
names: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl WholeSet {
|
||||
@@ -85,13 +89,14 @@ impl WholeSet {
|
||||
pub fn read(project: &Project, extra: Option<&Path>) -> WholeSet {
|
||||
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
|
||||
wanted.extend(extra.map(Path::to_path_buf));
|
||||
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped() };
|
||||
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped(), names: Vec::new() };
|
||||
for path in wanted {
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => set.files.push((path, text)),
|
||||
Err(e) => set.skipped.push((path, format!("no longer reads: {e}"))),
|
||||
}
|
||||
}
|
||||
set.names = names_of(project, &set.files);
|
||||
set
|
||||
}
|
||||
|
||||
@@ -105,18 +110,17 @@ impl WholeSet {
|
||||
})
|
||||
}
|
||||
|
||||
/// An engine sentence with each bare file name written root-relative
|
||||
/// (`p1.sv:2` → `rtl/p1.sv:2`), where the name is the base name of
|
||||
/// exactly one file of the set — the engines name files by base name,
|
||||
/// and only an unambiguous one can be placed.
|
||||
pub fn rooted(&self, project: &Project, sentence: &str) -> String {
|
||||
/// An engine sentence with every file of the set written root-relative.
|
||||
/// The engines name a file by its base name when that is unique in the
|
||||
/// set they were handed (`p1.sv:2` → `rtl/p1.sv:2`) and by the path they
|
||||
/// were given otherwise (`/abs/…/top_a/pwrmgr_if.sv:80` →
|
||||
/// `top_a/…/pwrmgr_if.sv:80`, generate-label-rename R1). One pass over
|
||||
/// the set's spellings per sentence; the table itself is built once.
|
||||
pub fn rooted(&self, sentence: &str) -> String {
|
||||
let mut out = sentence.to_string();
|
||||
for (path, _) in &self.files {
|
||||
let Some(base) = path.file_name().and_then(|name| name.to_str()) else { continue };
|
||||
let same = self.files.iter().filter(|(other, _)| other.file_name() == path.file_name());
|
||||
let shown = project.relative(path);
|
||||
if same.count() == 1 && shown != base {
|
||||
out = replace_file_name(&out, base, &shown);
|
||||
for (spelled, shown) in &self.names {
|
||||
if out.contains(spelled.as_str()) {
|
||||
out = replace_file_name(&out, spelled, shown);
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -140,6 +144,34 @@ impl WholeSet {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file's engine spelling and its root-relative one: the full path for
|
||||
/// a base name several files share, else the base name (skipped when it is
|
||||
/// already the relative path). Full paths first, so a bare base name never
|
||||
/// rewrites the tail of one.
|
||||
fn names_of(project: &Project, files: &[(PathBuf, String)]) -> Vec<(String, String)> {
|
||||
let mut count: HashMap<&std::ffi::OsStr, usize> = HashMap::new();
|
||||
for (path, _) in files {
|
||||
if let Some(base) = path.file_name() {
|
||||
*count.entry(base).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let (mut full, mut bare) = (Vec::new(), Vec::new());
|
||||
for (path, _) in files {
|
||||
let Some(base) = path.file_name() else { continue };
|
||||
let shown = project.relative(path);
|
||||
match count.get(base) {
|
||||
Some(1) => {
|
||||
if let Some(base) = base.to_str().filter(|base| *base != shown) {
|
||||
bare.push((base.to_string(), shown));
|
||||
}
|
||||
}
|
||||
_ => full.push((path.display().to_string(), shown)),
|
||||
}
|
||||
}
|
||||
full.extend(bare);
|
||||
full
|
||||
}
|
||||
|
||||
/// `text` with every occurrence of the file name `base` that stands alone —
|
||||
/// not the tail of a longer path or name — replaced by `path`.
|
||||
fn replace_file_name(text: &str, base: &str, path: &str) -> String {
|
||||
|
||||
@@ -544,8 +544,11 @@ const SM: &str = "module main_sm (\n input logic clk_i,\n output logic busy_o
|
||||
|
||||
const DV: &str = "module dv_x;\n logic a, b;\n assign a = `HIER.u_a[2].state_q;\n assign b = `HIER.u_a[2].state_q_d;\n assign b = `HIER.u_a[state_q].x;\nendmodule\n";
|
||||
|
||||
// Dotted spellings: `state_q` is a member of `main_sm`, so since §65.1's
|
||||
// scoping of mentions a bare spelling in another file is not listed, and a
|
||||
// path-like one (`.state_q`) still is — which keeps this CRLF check alive.
|
||||
const CRLF: &str =
|
||||
"module c;\r\n // one\r\n // state_q two\r\n string s = \"state_q\";\r\nendmodule\r\n";
|
||||
"module c;\r\n // one\r\n // u.state_q two\r\n string s = \"u.state_q\";\r\n // state_q bare, not listed\r\nendmodule\r\n";
|
||||
|
||||
#[test]
|
||||
fn qa_mentions_find_every_kind_and_only_whole_words() {
|
||||
@@ -580,7 +583,9 @@ fn qa_mentions_find_every_kind_and_only_whole_words() {
|
||||
|
||||
#[test]
|
||||
fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
|
||||
let far: String = (0..60).map(|i| format!("// state_q far {i}\n")).collect::<String>()
|
||||
// Path-like, so listed from a file that neither declares nor uses the
|
||||
// member (§65.1's scoping of mentions drops a bare one there).
|
||||
let far: String = (0..60).map(|i| format!("// u.state_q far {i}\n")).collect::<String>()
|
||||
+ "module far; endmodule\n";
|
||||
let files = [("rtl/sm.sv", SM), ("zz/far.sv", far.as_str())];
|
||||
let (tree, mut server) = served(&files);
|
||||
|
||||
@@ -277,7 +277,10 @@ const MACRO_ARG: &[(&str, &str)] = &[
|
||||
"top.sv",
|
||||
"`include \"defs.svh\"\nmodule top (input logic clk);\n logic peek;\n core u_core0 (.clk, .q());\n assign peek = `ID(u_core0.state_q);\nendmodule\n",
|
||||
),
|
||||
("third.sv", "module third;\n // state_q is mentioned here\n initial $display(\"state_q\");\nendmodule\n"),
|
||||
(
|
||||
"third.sv",
|
||||
"module third;\n // u_core0.state_q is mentioned here\n initial $display(\"u_core0.state_q\");\n // a bare state_q here is another module's word\nendmodule\n",
|
||||
),
|
||||
("m.sv", "module m (input logic a, output logic q);\n /* q */ assign q = a;\nendmodule\n"),
|
||||
];
|
||||
|
||||
@@ -285,7 +288,9 @@ const MACRO_ARG: &[(&str, &str)] = &[
|
||||
fn qa_uses_never_include_a_comment_a_string_or_macro_text() {
|
||||
let scratch = Scratch::with(MACRO_ARG);
|
||||
let mut s = Session::ready(&scratch);
|
||||
// `third.sv` writes the word only in a comment and a string; `top.sv`
|
||||
// `third.sv` writes the word only in a comment and a string (dotted —
|
||||
// a bare spelling in a file that neither declares nor uses the member
|
||||
// is not listed since §65.1's scoping of mentions); `top.sv`
|
||||
// only inside a macro call's argument, which the engine does not follow:
|
||||
// those are the unresolved mentions, never uses.
|
||||
assert_eq!(
|
||||
|
||||
@@ -717,17 +717,19 @@ fn qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit() {
|
||||
|
||||
#[test]
|
||||
fn qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind() {
|
||||
// `find g_lane refs` lists no use and `rename` answers `renamed 1 site`,
|
||||
// leaving `g_lane[0].lane_q` naming a block that no longer exists —
|
||||
// while `edit_item delete g_lane` sees the use (`rtl/fsm.sv:19:18`).
|
||||
// `find g_lane refs` used to list no use and `rename` answered `renamed
|
||||
// 1 site`, leaving `g_lane[0].lane_q` naming a block that no longer
|
||||
// existed — while `edit_item delete g_lane` saw the use
|
||||
// (`rtl/fsm.sv:19:18`). Lead's ruling R1 had the MCP layer refuse the
|
||||
// rename; TODO §65.1 fixed the engine (a path segment through a block is
|
||||
// a reference to its label), and the refusal is lifted.
|
||||
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
|
||||
// Lead's ruling R1: the MCP layer refuses the rename, and the source
|
||||
// is untouched.
|
||||
let said = session(&tree, &[("rename", json!({"name": "g_lane", "new_name": "g_ln"}))]);
|
||||
assert!(said[0].refused, "{}", said[0].text);
|
||||
let why = &said[0].text;
|
||||
assert!(why.starts_with("`rename` does not rename generate block labels"), "{why}");
|
||||
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS);
|
||||
let found = text(&tree, "find", json!({"name": "g_lane", "refs": true}));
|
||||
assert_eq!(found, "block g_lane rtl/fsm.sv:12\n rtl/fsm.sv:19\n");
|
||||
let renamed = text(&tree, "rename", json!({"name": "g_lane", "new_name": "g_ln"}));
|
||||
assert_eq!(renamed, "renamed 2 sites in 1 file\n");
|
||||
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS.replace("g_lane", "g_ln"));
|
||||
assert!(tree.read("rtl/fsm.sv").contains("busy = tmp | g_ln[0].lane_q;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -747,10 +749,15 @@ fn qa_rework_a_shared_base_name_is_named_by_path_or_left_alone() {
|
||||
assert_eq!(text(&tree, "rename", one), "renamed 2 sites in 1 file\n");
|
||||
assert!(tree.read("rtl/y/p1.sv").contains("logic d2;"));
|
||||
assert!(tree.read("rtl/x/p1.sv").contains("logic dup;"));
|
||||
// The engine's sentences: `p1.sv` is two files, so it stays as said;
|
||||
// `p1b.sv` is one, so it is named by its path.
|
||||
// The engine's sentences: `p1.sv` is two files, so the engine names it by
|
||||
// the path it was given and the answer makes that root-relative (§65.1
|
||||
// re-check R1 — it used to stay a bare, unplaceable `p1.sv`); `p1b.sv`
|
||||
// is one, so it is named by its path too.
|
||||
let added = text(&tree, "port", json!({"module": "sub", "add": "input logic zz"}));
|
||||
assert!(added.contains("`u_s` at p1.sv:4 connects with `.*` and p1.sv has"), "{added}");
|
||||
assert!(
|
||||
added.contains("`u_s` at rtl/y/p1.sv:4 connects with `.*` and rtl/y/p1.sv has"),
|
||||
"{added}"
|
||||
);
|
||||
assert!(added.contains("(rtl/z/p1b.sv:3)"), "{added}");
|
||||
assert!(!added.contains("rtl/z/rtl/"), "{added}");
|
||||
}
|
||||
@@ -807,3 +814,56 @@ fn qa_rework_an_escaped_local_outline_lists_is_found() {
|
||||
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
|
||||
assert_eq!(text(&tree, "find", json!({"name": "\\loc.v"})), "var \\loc.v rtl/g.sv:3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_names_each_same_named_file_by_its_root_relative_path_once() {
|
||||
// §65.1 re-check R1 and the lead's fifth ruling: two `x_if.sv` holding an
|
||||
// unresolved path through the label are two findable warning lines, and
|
||||
// neither line is repeated under `unresolved:`.
|
||||
let probe = "module probe_IDX (output logic o);\n assign o = tb.dut.g_sw.q;\nendmodule\n";
|
||||
let (a, b) = (probe.replace("IDX", "a"), probe.replace("IDX", "b"));
|
||||
let tree = Tree::with(&[
|
||||
("rtl/dut.sv", "module dut_x;\n if (1) begin : g_sw\n logic q;\n end\nendmodule\n"),
|
||||
("dv/a/x_if.sv", a.as_str()),
|
||||
("dv/b/x_if.sv", b.as_str()),
|
||||
]);
|
||||
let said = text(&tree, "rename", json!({"name": "g_sw", "new_name": "g_hw"}));
|
||||
let path_lines: Vec<&str> =
|
||||
said.lines().filter(|line| line.contains("a hierarchical path through")).collect();
|
||||
assert_eq!(path_lines.len(), 2, "{said}");
|
||||
assert!(path_lines[0].starts_with("warning: dv/a/x_if.sv:2: "), "{said}");
|
||||
assert!(path_lines[1].starts_with("warning: dv/b/x_if.sv:2: "), "{said}");
|
||||
assert!(!said.contains("unresolved:"), "each line is said once: {said}");
|
||||
assert!(tree.read("rtl/dut.sv").contains("begin : g_hw"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_members_rename_lists_only_its_own_mentions_and_dotted_ones_elsewhere() {
|
||||
// §65.1, lead's inspection: two modules each with a `state_q`, each
|
||||
// spelling it in an `ASSERT argument, a comment and a string. Renaming
|
||||
// `a`'s warns and lists only `a`'s — plus `b`'s dotted spellings, which
|
||||
// may be paths to it. A package-level name still lists everything.
|
||||
let defs = "`define ASSERT(n, e) n: assert property (e);\n";
|
||||
let a = "module a (input logic clk);\n logic state_q;\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(A_T, state_q)\n // state_q is a's\n initial $display(\"state_q\");\nendmodule\n";
|
||||
let b = "module b (input logic clk);\n logic state_q;\n a u_a (.clk);\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(B_T, state_q)\n `ASSERT(B_P, u_a.state_q)\n // state_q is b's\n initial $display(\"state_q\");\n initial $display(\"u_a.state_q\");\nendmodule\n";
|
||||
let pkg = "package p;\n localparam int W = 1;\nendpackage\n";
|
||||
let user = "module u import p::*;\n // W is p's\n localparam int X = W;\nendmodule\n";
|
||||
let tree = Tree::with(&[
|
||||
("rtl/defs.svh", defs),
|
||||
("rtl/a.sv", a),
|
||||
("rtl/b.sv", b),
|
||||
("rtl/p.sv", pkg),
|
||||
("rtl/u.sv", user),
|
||||
]);
|
||||
let said = text(&tree, "rename", json!({"name": "a.state_q", "new_name": "state_r"}));
|
||||
let macro_lines: Vec<&str> = said.lines().filter(|l| l.contains("macro invocation")).collect();
|
||||
assert_eq!(macro_lines.len(), 2, "{said}");
|
||||
assert!(
|
||||
macro_lines[0].contains("rtl/a.sv:4") && macro_lines[1].contains("rtl/b.sv:6"),
|
||||
"{said}"
|
||||
);
|
||||
assert!(said.ends_with("unresolved:\n rtl/a.sv:4,5,6\n rtl/b.sv:6,9\n"), "{said}");
|
||||
assert!(tree.read("rtl/b.sv").contains("logic state_q;"), "b's own stays");
|
||||
let found = text(&tree, "find", json!({"name": "p.W", "refs": true}));
|
||||
assert!(found.contains("unresolved:\n rtl/u.sv:2\n"), "a package member lists all: {found}");
|
||||
}
|
||||
@@ -795,7 +795,13 @@ fn rename_lists_the_old_names_unresolved_mentions() {
|
||||
text.contains("\nwarning: `state_q` appears in the body of macro `SM_STATE`"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4,6\n"), "{text}");
|
||||
// Line 6 is `tb.…state_q`, a path nothing resolves: the engine's own
|
||||
// warning names it (§65.1 F1), so it is not repeated as a mention.
|
||||
assert!(
|
||||
text.contains("\nwarning: dv/probe_if.sv:6: a hierarchical path through `state_q`"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4\n"), "{text}");
|
||||
// The hierarchical use in core.sv is renamed, so it is not a mention;
|
||||
// the text the block names is left as it was.
|
||||
assert!(read(&tree, "rtl/core.sv").contains("u_main_sm.main_state_q"));
|
||||
@@ -894,12 +900,13 @@ fn engine_sentences_name_files_root_relative() {
|
||||
assert_eq!(before, snapshot(&tree));
|
||||
let added = server.text("port", json!({"module": "spare", "add": "input logic en"}));
|
||||
assert!(added.contains("at `u_s` (rtl/spare_user.sv:5)"), "{added}");
|
||||
// A base name two files share cannot be placed: left as the engine said.
|
||||
// A base name two files share: the engine names it by its path (§65.1
|
||||
// re-check R1), which the answer makes root-relative like any other.
|
||||
let (tree, mut server) = served("edit");
|
||||
fs::create_dir_all(tree.path("alt")).unwrap();
|
||||
fs::write(tree.path("alt/cell.sv"), "module cell2; endmodule\n").unwrap();
|
||||
let twice = refusal(&mut server, "port", json!({"module": "cell", "remove": "en"}));
|
||||
assert!(twice.contains("inside `cell` at cell.sv:6"), "{twice}");
|
||||
assert!(twice.contains("inside `cell` at rtl/cell.sv:6"), "{twice}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Tiers 2 and 3: what the buffer being typed in declares, and the words it
|
||||
//! uses (TODO §68.1, `completion-ux`).
|
||||
//!
|
||||
//! The current file first: a name this buffer declares anywhere — in another
|
||||
//! module, a sibling block, a function three screens down — and then a word
|
||||
//! it merely uses, both ahead of what other files declare and ahead of the
|
||||
//! templates and keywords. Both are read from the buffer's own `Semantics`
|
||||
//! and token stream, recomputed on every change, so an unsaved declaration
|
||||
//! ranks as soon as it is typed. Tier 1 (the scope chain) still comes first:
|
||||
//! what is visible at the cursor is a better answer than what is merely in
|
||||
//! the file.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_semantic::Symbol;
|
||||
|
||||
use super::word::Word;
|
||||
use super::{completion_kind, declaration_detail, Items, TIER_BUFFER_WORD, TIER_DECLARED};
|
||||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query};
|
||||
use crate::state::Document;
|
||||
|
||||
/// Tier 2: every declaration in the buffer, whatever scope holds it.
|
||||
pub(super) fn declared_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
|
||||
let symbols: Vec<&Symbol> = doc.semantics.symbols().iter().collect();
|
||||
for symbol in matching(symbols, |symbol| symbol.name.as_str(), word, fuzzy) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(
|
||||
&symbol.name,
|
||||
completion_kind(symbol.kind),
|
||||
TIER_DECLARED,
|
||||
declaration_detail(doc, symbol),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 3: every identifier the buffer's token stream holds, except the one
|
||||
/// being typed — offering the user their own half-word back is noise.
|
||||
pub(super) fn buffer_word_tier(
|
||||
items: &mut Items,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
if items.full() {
|
||||
return;
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let words: Vec<&str> =
|
||||
buffer_words(doc, word.start).filter(|name| seen.insert(*name)).collect();
|
||||
for name in matching(words, |name| name, word, fuzzy) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(name, CompletionItemKind::TEXT, TIER_BUFFER_WORD, "used in this file".into());
|
||||
}
|
||||
}
|
||||
|
||||
/// The candidates `word` reaches, in the order they are offered: by prefix
|
||||
/// below the fuzzy floor (in the buffer's own order), ranked by subsequence
|
||||
/// score from it up — the house rule every tier applies.
|
||||
fn matching<'a, T: Copy + 'a>(
|
||||
candidates: Vec<T>,
|
||||
name: impl Fn(T) -> &'a str,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) -> Vec<T> {
|
||||
match fuzzy {
|
||||
None => candidates
|
||||
.into_iter()
|
||||
.filter(|c| starts_with_ignore_case(name(*c), &word.text))
|
||||
.collect(),
|
||||
Some(query) => {
|
||||
let mut hits: Vec<(T, _)> =
|
||||
candidates.into_iter().filter_map(|c| Some((c, query.score(name(c))?))).collect();
|
||||
hits.sort_by(|a, b| rank_cmp((name(a.0), a.1), (name(b.0), b.1)));
|
||||
hits.into_iter().map(|(c, _)| c).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier the buffer holds, as the project-word tier counts one —
|
||||
/// `Ident` and `SystemIdent` only, neither a macro usage nor an escaped
|
||||
/// identifier — but not the token starting at `typing`, the word under the
|
||||
/// cursor.
|
||||
fn buffer_words(doc: &Document, typing: u32) -> impl Iterator<Item = &str> {
|
||||
doc.tokens
|
||||
.iter()
|
||||
.filter(move |token| token.span.start != typing)
|
||||
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
|
||||
.map(|token| token.text.as_str())
|
||||
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
|
||||
const TOP: &str = "\
|
||||
module top;
|
||||
logic data_q;
|
||||
always_comb begin
|
||||
da
|
||||
end
|
||||
endmodule
|
||||
module other;
|
||||
logic data_other;
|
||||
assign data_word = 1;
|
||||
always_comb al_used = 0;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn this_files_declarations_and_words_rank_after_the_scope_and_before_other_files() {
|
||||
let (_tree, ws, uri, position) = asking("bufferrank", TOP, " da");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let tier_of = |label: &str| tier(find(&items, label).unwrap_or_else(|| panic!("{label}")));
|
||||
assert_eq!(tier_of("data_q"), TIER_SCOPE, "visible at the cursor");
|
||||
assert_eq!(tier_of("data_other"), TIER_DECLARED, "declared in another module of this file");
|
||||
assert_eq!(tier_of("data_word"), TIER_BUFFER_WORD, "only used in this file");
|
||||
assert_eq!(tier_of("data"), TIER_INDEX, "a port only `sub.sv` declares");
|
||||
assert!(TIER_SCOPE < TIER_DECLARED && TIER_DECLARED < TIER_BUFFER_WORD);
|
||||
assert!(TIER_BUFFER_WORD < TIER_INDEX && TIER_INDEX < TIER_TEMPLATE);
|
||||
assert!(TIER_TEMPLATE < TIER_KEYWORD && TIER_KEYWORD < TIER_WORD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_this_file_uses_sorts_ahead_of_the_keywords() {
|
||||
let top = TOP.replace(" da\n", " al\n");
|
||||
let (_tree, ws, uri, position) = asking("bufferkw", &top, " al");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let sort = |label: &str| {
|
||||
find(&items, label)
|
||||
.and_then(|i| i.sort_text.clone())
|
||||
.unwrap_or_else(|| panic!("{label}"))
|
||||
};
|
||||
assert!(sort("al_used") < sort("always"), "{items:#?}");
|
||||
assert!(sort("al_used") < sort("always_ff"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! What a connection-list entry inserts (TODO §68.1, `completion-ux`).
|
||||
//!
|
||||
//! After the `.` of `sub u_sub (.cl|` or `sub #(.WI|`, accepting a port or a
|
||||
//! parameter writes the whole entry — `.clk(|)` with the cursor inside the
|
||||
//! parentheses — rather than the bare name. When the instantiating scope can
|
||||
//! see a net, variable or port of the same name (a parameter, for the
|
||||
//! parameter list), it is pre-filled as the placeholder: `.clk(${1:clk})`,
|
||||
//! one Tab to keep it, one keystroke to replace it.
|
||||
//!
|
||||
//! The bare name stays the answer where the snippet would be wrong: a client
|
||||
//! that never said it reads snippets, a `(` already written after the word
|
||||
//! being replaced (re-editing `.clk(x)`'s name), and a name the snippet
|
||||
//! grammar would have to escape (an escaped identifier).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
use super::snippet_hole;
|
||||
use super::tiers::visible_symbols;
|
||||
use super::word::Word;
|
||||
use crate::signature;
|
||||
use crate::state::Document;
|
||||
|
||||
/// A connection-list entry, beyond its name.
|
||||
pub(super) struct Connection {
|
||||
/// Whether the list already connects this port elsewhere — it sorts after
|
||||
/// the rest and is marked `connected`.
|
||||
pub(super) connected: bool,
|
||||
/// The snippet accepting it writes, or `None` for the bare name.
|
||||
pub(super) snippet: Option<String>,
|
||||
}
|
||||
|
||||
/// Everything about the cursor's entry that every candidate's insertion
|
||||
/// shares: whether to write the parentheses, and the names a placeholder may
|
||||
/// be pre-filled with.
|
||||
pub(super) struct EntrySite<'a> {
|
||||
wrap: bool,
|
||||
visible: HashSet<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> EntrySite<'a> {
|
||||
/// The entry being typed at `word`, in a list of `kind`.
|
||||
pub(super) fn new(
|
||||
doc: &'a Document,
|
||||
word: &Word,
|
||||
kind: signature::Kind,
|
||||
snippets: bool,
|
||||
) -> EntrySite<'a> {
|
||||
let wrap = snippets && !paren_follows(&doc.text, word.start);
|
||||
let admits = |symbol_kind: SymbolKind| match kind {
|
||||
signature::Kind::Ports => {
|
||||
matches!(symbol_kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port)
|
||||
}
|
||||
signature::Kind::Params => {
|
||||
matches!(symbol_kind, SymbolKind::Param | SymbolKind::LocalParam)
|
||||
}
|
||||
};
|
||||
let visible = match wrap {
|
||||
true => visible_symbols(&doc.semantics, word.start)
|
||||
.into_iter()
|
||||
.filter(|symbol| admits(symbol.kind))
|
||||
.map(|symbol| symbol.name.as_str())
|
||||
.collect(),
|
||||
false => HashSet::new(),
|
||||
};
|
||||
EntrySite { wrap, visible }
|
||||
}
|
||||
|
||||
/// The entry for the port or parameter `name`.
|
||||
pub(super) fn connection(&self, name: &str, connected: bool) -> Connection {
|
||||
let plain = name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
let snippet = (self.wrap && plain).then(|| {
|
||||
let fill = if self.visible.contains(name) { name } else { "" };
|
||||
format!("{name}({})", snippet_hole(1, fill))
|
||||
});
|
||||
Connection { connected, snippet }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `(` follows the identifier run that starts at `start`, past any
|
||||
/// spaces or tabs — the entry is already written and only its name is being
|
||||
/// re-edited.
|
||||
fn paren_follows(text: &str, start: u32) -> bool {
|
||||
let Some(rest) = text.get(start as usize..) else { return false };
|
||||
let rest = rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$');
|
||||
rest.trim_start_matches([' ', '\t']).starts_with('(')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_paren_after_the_word_means_the_entry_is_already_written() {
|
||||
assert!(paren_follows(".clk(x)", 1));
|
||||
assert!(paren_follows(".cl (x)", 1));
|
||||
assert!(!paren_follows(".cl", 1));
|
||||
assert!(!paren_follows(".cl\n (x)", 1), "only on the same line");
|
||||
assert!(!paren_follows(".cl, .b(x)", 1));
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use lsp_types::CompletionResponse;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::connection::{self, Connection};
|
||||
use super::site::balanced;
|
||||
use super::tiers::innermost_scope;
|
||||
use super::word::{Sep, Word};
|
||||
@@ -54,6 +55,7 @@ pub(super) fn member_answer(
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
offset: u32,
|
||||
snippets: bool,
|
||||
) -> Option<CompletionResponse> {
|
||||
let members = match word.spine.as_ref() {
|
||||
Some(spine) => {
|
||||
@@ -69,7 +71,7 @@ pub(super) fn member_answer(
|
||||
// question, and it is the commonest completion position in RTL there
|
||||
// is: a `.` opening a connection or a parameter override.
|
||||
None => match word.sep? {
|
||||
Sep::Dot => connection_members(ws, doc, word)?,
|
||||
Sep::Dot => connection_members(ws, doc, word, snippets)?,
|
||||
Sep::Scope => return None,
|
||||
},
|
||||
};
|
||||
@@ -77,7 +79,7 @@ pub(super) fn member_answer(
|
||||
// Prefix below [`FUZZY_MIN`], subsequence from it up — the house rule, on
|
||||
// the same `Query` every other tier scores with.
|
||||
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
|
||||
let matched: Vec<Member> = match &fuzzy {
|
||||
let mut matched: Vec<Member> = match &fuzzy {
|
||||
None => members
|
||||
.into_iter()
|
||||
.filter(|member| starts_with_ignore_case(&member.name, &word.text))
|
||||
@@ -95,12 +97,20 @@ pub(super) fn member_answer(
|
||||
}
|
||||
};
|
||||
|
||||
// A connection list's already-connected ports go after the rest, each
|
||||
// group in the order it was matched in (`completion-ux`, TODO §68.1).
|
||||
matched.sort_by_key(|member| member.connection.as_ref().is_some_and(|c| c.connected));
|
||||
|
||||
let mut items = Items::new(doc, word.range(offset));
|
||||
for member in matched {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(&member.name, completion_kind(member.kind), TIER_MEMBER, member.detail);
|
||||
let kind = completion_kind(member.kind);
|
||||
match member.connection {
|
||||
Some(connection) => items.connection(&member.name, kind, member.detail, connection),
|
||||
None => items.simple(&member.name, kind, TIER_MEMBER, member.detail),
|
||||
}
|
||||
}
|
||||
// **The `isIncomplete` trap, in its member form.** The request that
|
||||
// matters is the one the trigger character fires, with nothing typed
|
||||
@@ -132,6 +142,9 @@ struct Member {
|
||||
name: String,
|
||||
kind: SymbolKind,
|
||||
detail: String,
|
||||
/// What a connection list's entry carries beyond its name; `None` for
|
||||
/// every other member.
|
||||
connection: Option<Connection>,
|
||||
}
|
||||
|
||||
/// What a member declared **in another file** shows beside its name.
|
||||
@@ -225,10 +238,17 @@ fn members_at(
|
||||
/// list to what may legally be written; it never offers a name the
|
||||
/// resolution could not find.
|
||||
///
|
||||
/// Ports already connected earlier in the same list are dropped. `None` — no
|
||||
/// Ports already connected elsewhere in the same list stay on offer, marked
|
||||
/// (`completion-ux`, 2026-11-17 — they used to be dropped), and every entry
|
||||
/// carries the `.name($1)` snippet [`connection::entry`] spells. `None` — no
|
||||
/// popup — when the cursor is not in such a list at all, or is inside a
|
||||
/// connected *expression* (`.clk(` opens a paren of its own).
|
||||
fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec<Member>> {
|
||||
fn connection_members(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
snippets: bool,
|
||||
) -> Option<Vec<Member>> {
|
||||
let dot = word.start.checked_sub(1)?;
|
||||
let list = signature::enclosing_list(&doc.tokens, word.start)?;
|
||||
let open = doc.tokens.get(list.open)?.span.end;
|
||||
@@ -250,27 +270,33 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
|
||||
signature::Kind::Ports => SymbolKind::Port,
|
||||
};
|
||||
let taken = connected_names(&doc.tokens, list.open, dot);
|
||||
let entry = connection::EntrySite::new(doc, word, list.kind, snippets);
|
||||
let mut members = Members::new();
|
||||
let mut push = |name: &str, kind: SymbolKind, detail: String| {
|
||||
let connection = entry.connection(name, taken.contains(name));
|
||||
members.push_member(Member {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
detail,
|
||||
connection: Some(connection),
|
||||
});
|
||||
};
|
||||
match doc.semantics.instantiable_scope(&list.module) {
|
||||
// This file declares the module: its own scope is the whole answer,
|
||||
// and no other file's module of the same name may override it.
|
||||
Some(scope) => {
|
||||
let scope = doc.semantics.scope(scope)?;
|
||||
for symbol in scope.symbols.iter().filter_map(|&id| doc.semantics.symbol(id)) {
|
||||
if symbol.kind == wanted && !taken.contains(symbol.name.as_str()) {
|
||||
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
|
||||
if symbol.kind == wanted {
|
||||
push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for (name, defs) in ws.index().members_of(&list.module) {
|
||||
let Some(def) = defs.first() else { continue };
|
||||
if def.kind == wanted && !taken.contains(name) {
|
||||
members.push(
|
||||
name,
|
||||
def.kind,
|
||||
indexed_detail(def.kind, def.type_name.as_deref()),
|
||||
);
|
||||
if def.kind == wanted {
|
||||
push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,12 +308,11 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
|
||||
/// token at `open`, except the one whose `.` sits at `skip` — the entry being
|
||||
/// typed, which must stay on offer.
|
||||
///
|
||||
/// Dropping them is the friendlier half of a choice the other way round would
|
||||
/// be simpler: in a sixty-port instantiation the fifty-five already connected
|
||||
/// are the ones the user is *not* looking for, and a popup that keeps offering
|
||||
/// them is a popup they scroll past. It cannot mislead — a name dropped here
|
||||
/// is one the buffer already spells two lines up — and a re-edited entry is
|
||||
/// still offered, because its own dot is the one `skip` names.
|
||||
/// In a sixty-port instantiation the fifty-five already connected are the ones
|
||||
/// the user is *not* looking for, so they sort after the rest and say so; they
|
||||
/// are not dropped (`completion-ux`, 2026-11-17), because a port connected
|
||||
/// twice by mistake is exactly the one a user goes looking for. A re-edited
|
||||
/// entry is not marked, because its own dot is the one `skip` names.
|
||||
fn connected_names(tokens: &[Token], open: usize, skip: u32) -> HashSet<&str> {
|
||||
let mut taken = HashSet::new();
|
||||
let mut depth = 0i32;
|
||||
@@ -328,8 +353,12 @@ impl Members {
|
||||
}
|
||||
|
||||
fn push(&mut self, name: &str, kind: SymbolKind, detail: String) {
|
||||
if self.seen.insert(name.to_string()) {
|
||||
self.out.push(Member { name: name.to_string(), kind, detail });
|
||||
self.push_member(Member { name: name.to_string(), kind, detail, connection: None });
|
||||
}
|
||||
|
||||
fn push_member(&mut self, member: Member) {
|
||||
if self.seen.insert(member.name.clone()) {
|
||||
self.out.push(member);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -823,28 +852,55 @@ endmodule
|
||||
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
|
||||
}
|
||||
|
||||
/// The answer against [`WIRING`] in the order the client shows it — by
|
||||
/// `sortText` — as `(label, marked connected)` pairs.
|
||||
fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> {
|
||||
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
|
||||
let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole);
|
||||
let mut found = items(completions(&ws, &uri, position, true));
|
||||
found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text));
|
||||
found
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let marked = item
|
||||
.label_details
|
||||
.as_ref()
|
||||
.and_then(|d| d.description.as_deref())
|
||||
.is_some_and(|d| d == "connected");
|
||||
(item.label, marked)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> {
|
||||
list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
|
||||
assert_eq!(wiring_labels("comma", ".clk(clk), ."), vec!["data", "ready"]);
|
||||
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
|
||||
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
|
||||
assert_eq!(
|
||||
wiring_labels("newline", ".clk(clk),\n ."),
|
||||
vec!["data", "ready"],
|
||||
wiring_order("newline", ".clk(clk),\n ."),
|
||||
expected,
|
||||
"an indented continuation line is the ordinary way this is written",
|
||||
);
|
||||
}
|
||||
|
||||
/// Already-connected ports are dropped: in a sixty-port instantiation the
|
||||
/// ones still to wire are the whole of what the user is looking for.
|
||||
/// Already-connected ports sort after the ones still to wire and say so
|
||||
/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a
|
||||
/// sixty-port instantiation the ones still to wire are what the user is
|
||||
/// looking for, but a port connected twice by mistake is findable.
|
||||
#[test]
|
||||
fn a_port_already_connected_is_not_offered_again() {
|
||||
fn a_port_already_connected_is_offered_last_and_marked() {
|
||||
assert_eq!(
|
||||
wiring_labels("taken", ".clk(clk), .data(d), ."),
|
||||
vec!["ready"],
|
||||
"two written, one left",
|
||||
wiring_order("taken", ".clk(clk), .data(d), ."),
|
||||
pairs(&[("ready", false), ("clk", true), ("data", true)]),
|
||||
"two written, one left, and the two after it",
|
||||
);
|
||||
// …and the entry being *re-typed* is still offered, because the dot
|
||||
// the cursor follows is the one that is skipped.
|
||||
assert_eq!(wiring_labels("retype", ".clk(clk), .data(d), .re"), vec!["ready"]);
|
||||
// …and the entry being *re-typed* is not marked, because the dot the
|
||||
// cursor follows is the one that is skipped.
|
||||
assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -945,17 +1001,21 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_item_inserts_the_bare_name_and_shows_its_declaration() {
|
||||
fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() {
|
||||
let top = WIRING.replace(" HOLE\n", " .\n");
|
||||
let tree = Tree::new("portitem");
|
||||
let (_tree, ws, uri, position) = opened(tree, &top, " .");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
let data = find(&answer, "data").expect("the port");
|
||||
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
|
||||
// The user types the `(` themselves; inventing it would be guessing
|
||||
// at what is connected.
|
||||
assert_eq!(inserted(data), "data");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
// `.data(|)`: the parentheses come with it, the cursor inside
|
||||
// (`completion-ux`, 2026-11-17). Nothing named `data` is visible in
|
||||
// `wiring_top`, so the placeholder is empty…
|
||||
assert_eq!(inserted(data), "data(${1})");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET));
|
||||
// …while `clk` is, so it is pre-filled.
|
||||
let clk = find(&answer, "clk").expect("the clock");
|
||||
assert_eq!(inserted(clk), "clk(${1:clk})");
|
||||
// The declaration line carries the direction and the width, which is
|
||||
// the whole of what a connection list needs to know.
|
||||
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
|
||||
@@ -965,6 +1025,33 @@ endmodule
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() {
|
||||
// A `(` already after the word: only the name is being re-edited.
|
||||
let top = WIRING.replace(" HOLE\n", " .da(d)\n");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(inserted(find(&answer, "data").expect("the port")), "data");
|
||||
// A client without snippet support gets the name, as before.
|
||||
let top = WIRING.replace(" HOLE\n", " .\n");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " .");
|
||||
let answer = items(completions(&ws, &uri, position, false));
|
||||
let data = find(&answer, "data").expect("the port");
|
||||
assert_eq!(inserted(data), "data");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_item_is_pre_filled_from_a_visible_parameter() {
|
||||
let top = WIRING
|
||||
.replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n")
|
||||
.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(.");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})");
|
||||
assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})");
|
||||
}
|
||||
|
||||
/// A **non-ANSI** port list writes its directions in the module body, so
|
||||
/// the header alone names the ports and the body types them. Both halves
|
||||
/// bind a `Port`, so the list is the same.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `textDocument/completion` — module hinting, templates, keywords, and every
|
||||
//! name the project uses.
|
||||
//!
|
||||
//! One response, six tiers, ordered by `sortText`:
|
||||
//! One response, eight tiers, ordered by `sortText`:
|
||||
//!
|
||||
//! 0. **module names** — at module-item position only, every module the
|
||||
//! workspace declares whose name contains what is typed. The item inserts
|
||||
@@ -10,12 +10,15 @@
|
||||
//! 2026-08-30);
|
||||
//! 1. **what is visible here** — the declarations the scope chain at the
|
||||
//! cursor binds, from this file's `Semantics`;
|
||||
//! 2. **what the project declares** — packages, their members, typedefs,
|
||||
//! 2. **what this file declares** — every declaration in the buffer, in any
|
||||
//! scope (`buffer.rs`, `completion-ux` 2026-11-17);
|
||||
//! 3. **what this file uses** — every identifier its token stream holds;
|
||||
//! 4. **what the project declares** — packages, their members, typedefs,
|
||||
//! classes, modules and `` `define`` names, from the workspace index;
|
||||
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
||||
//! 5. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
||||
//! tabstops, offered only where the construct may be written;
|
||||
//! 4. **keywords** — every reserved word `vlog_parser` knows;
|
||||
//! 5. **project words** — every identifier the in-scope files' *token
|
||||
//! 6. **keywords** — every reserved word `vlog_parser` knows;
|
||||
//! 7. **project words** — every identifier the in-scope files' *token
|
||||
//! streams* contain, the rope/VS Code word-completion tier.
|
||||
//!
|
||||
//! A name is offered once, by the highest tier that claims it. Nothing is
|
||||
@@ -47,8 +50,9 @@
|
||||
//! list included;
|
||||
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
|
||||
//! `instantiate.rs` share;
|
||||
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
|
||||
//! the response.
|
||||
//! * `buffer` — tiers 2 and 3, the current file's declarations and words;
|
||||
//! * `tiers` — the other ordinary tiers, in the order they fill the
|
||||
//! response.
|
||||
//!
|
||||
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
|
||||
//! entry points other modules of the crate use keep their paths through the
|
||||
@@ -58,9 +62,9 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::{
|
||||
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
|
||||
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
|
||||
TextEdit, Uri,
|
||||
CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionList,
|
||||
CompletionResponse, CompletionTextEdit, Documentation, InsertTextFormat, InsertTextMode,
|
||||
MarkupContent, MarkupKind, Position, Range, TextEdit, Uri,
|
||||
};
|
||||
use vlog_parser::token::{Comment, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
@@ -71,6 +75,8 @@ use crate::candidates::Query;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::Template;
|
||||
use buffer::{buffer_word_tier, declared_tier};
|
||||
use connection::Connection;
|
||||
use member::member_answer;
|
||||
use module::module_tier;
|
||||
use site::{at_module_item, at_statement, enclosing_scopes};
|
||||
@@ -85,6 +91,8 @@ pub(crate) use module::module_header;
|
||||
pub(crate) use site::at_instantiation_site;
|
||||
pub(crate) use tiers::layout_at;
|
||||
|
||||
mod buffer;
|
||||
mod connection;
|
||||
#[cfg(test)]
|
||||
mod harness;
|
||||
mod member;
|
||||
@@ -134,11 +142,19 @@ const TIER_MODULE: char = '0';
|
||||
/// would say there is a ranking against the other tiers to express, and there
|
||||
/// is not.
|
||||
const TIER_MEMBER: char = '0';
|
||||
/// A connection list's already-connected ports: after every port still to
|
||||
/// connect, inside the same exclusive answer (`completion-ux`).
|
||||
const TIER_CONNECTED: char = '1';
|
||||
const TIER_SCOPE: char = '1';
|
||||
const TIER_INDEX: char = '2';
|
||||
const TIER_TEMPLATE: char = '3';
|
||||
const TIER_KEYWORD: char = '4';
|
||||
const TIER_WORD: char = '5';
|
||||
/// What this buffer declares anywhere, and then the words it uses — the
|
||||
/// current file ahead of every other file and of the templates and keywords
|
||||
/// (`completion-ux`, TODO §68.1).
|
||||
const TIER_DECLARED: char = '2';
|
||||
const TIER_BUFFER_WORD: char = '3';
|
||||
const TIER_INDEX: char = '4';
|
||||
const TIER_TEMPLATE: char = '5';
|
||||
const TIER_KEYWORD: char = '6';
|
||||
const TIER_WORD: char = '7';
|
||||
|
||||
/// What a multi-line item tells the client about its own whitespace.
|
||||
///
|
||||
@@ -203,7 +219,7 @@ pub fn completions(
|
||||
// A `.` or a `::` admits exactly one kind of name too — a member of what
|
||||
// stands before it — so the answer is only those. See [`member_answer`].
|
||||
if word.sep.is_some() {
|
||||
return member_answer(ws, doc, &word, offset);
|
||||
return member_answer(ws, doc, &word, offset, snippets);
|
||||
}
|
||||
|
||||
// Both position gates read the same scope chain, and neither can be true
|
||||
@@ -225,10 +241,12 @@ pub fn completions(
|
||||
let mut items = Items::new(doc, word.range(offset));
|
||||
module_tier(&mut items, ws, doc, &word, at_item);
|
||||
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
declared_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
buffer_word_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
index_tier(&mut items, ws, &word, fuzzy.as_ref());
|
||||
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
|
||||
keyword_tier(&mut items, &word);
|
||||
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
|
||||
word_tier(&mut items, ws, &word, fuzzy.as_ref());
|
||||
// **The `isIncomplete` trap.** VS Code asks the server again on the next
|
||||
// keystroke *only* when the last answer said it was incomplete; otherwise
|
||||
// it filters the list it already holds. A complete two-character prefix
|
||||
@@ -307,13 +325,54 @@ impl Items {
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
/// A port or parameter after a connection list's `.`: the bare name, or
|
||||
/// the `name($1)` entry when the connection carries one, and a dimmed
|
||||
/// `connected` beside the label when the list already connects it.
|
||||
fn connection(
|
||||
&mut self,
|
||||
name: &str,
|
||||
kind: CompletionItemKind,
|
||||
detail: String,
|
||||
connection: Connection,
|
||||
) {
|
||||
if self.full() || self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
let tier = if connection.connected { TIER_CONNECTED } else { TIER_MEMBER };
|
||||
let format = match connection.snippet {
|
||||
Some(_) => InsertTextFormat::SNIPPET,
|
||||
None => InsertTextFormat::PLAIN_TEXT,
|
||||
};
|
||||
let item = CompletionItem {
|
||||
label: name.to_string(),
|
||||
kind: Some(kind),
|
||||
detail: Some(detail),
|
||||
label_details: connection.connected.then(|| CompletionItemLabelDetails {
|
||||
detail: None,
|
||||
description: Some("connected".to_string()),
|
||||
}),
|
||||
sort_text: Some(format!("{tier}{name}")),
|
||||
insert_text_format: Some(format),
|
||||
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
||||
range: self.range,
|
||||
new_text: connection.snippet.unwrap_or_else(|| name.to_string()),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
/// One template: the skeleton it inserts, the word it is reached by, and
|
||||
/// the shape it expands to.
|
||||
///
|
||||
/// A client that never said it understands snippets gets the same text
|
||||
/// with every hole filled in rather than nothing at all — the M4 ruling,
|
||||
/// applied to a body whose defaults were chosen so that the result parses.
|
||||
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
|
||||
///
|
||||
/// `rank` is the template's place in the registry, which is what orders the
|
||||
/// templates among themselves: the label alone would put `always @(*)`
|
||||
/// before the clocked blocks.
|
||||
fn template(&mut self, template: &Template, rank: usize, layout: &Layout, snippets: bool) {
|
||||
if self.full() || self.seen.contains(template.label) {
|
||||
return;
|
||||
}
|
||||
@@ -329,7 +388,7 @@ impl Items {
|
||||
// types to reach the item — otherwise `if` would not match
|
||||
// `if begin/end` at all.
|
||||
filter_text: Some(template.prefix.to_string()),
|
||||
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
|
||||
sort_text: Some(format!("{TIER_TEMPLATE}{rank:03}{}", template.label)),
|
||||
insert_text_format: Some(match snippets {
|
||||
true => InsertTextFormat::SNIPPET,
|
||||
false => InsertTextFormat::PLAIN_TEXT,
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Semantics, Symbol};
|
||||
@@ -66,7 +65,7 @@ pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy:
|
||||
/// Every declaration the scope chain covering `offset` binds, innermost scope
|
||||
/// first, each name only once — the inner declaration shadows the outer one,
|
||||
/// which is the rule `vlog_semantic`'s own lookup follows.
|
||||
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
|
||||
pub(super) fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
|
||||
let mut out = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut at = innermost_scope(semantics, offset);
|
||||
@@ -158,7 +157,7 @@ pub(super) fn template_tier(
|
||||
}
|
||||
let layout = layout_at(ws, doc, word.start);
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
for template in templates::for_dialect(dialect) {
|
||||
for (rank, template) in templates::for_dialect(dialect).enumerate() {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
@@ -168,7 +167,7 @@ pub(super) fn template_tier(
|
||||
if !starts_with_ignore_case(template.prefix, &word.text) {
|
||||
continue;
|
||||
}
|
||||
items.template(template, &layout, snippets);
|
||||
items.template(template, rank, &layout, snippets);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,45 +204,26 @@ pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 5: identifiers used anywhere in the project scope.
|
||||
/// Tier 7: identifiers used anywhere in the project scope.
|
||||
///
|
||||
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
|
||||
/// buffer being typed in is harvested afresh from its own token stream, so an
|
||||
/// unsaved edit contributes to its own file's completions immediately.
|
||||
pub(super) fn word_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
/// The prebuilt table is as of the last index rebuild, which is `didSave`. The
|
||||
/// buffer being typed in is harvested afresh from its own token stream by
|
||||
/// tier 3 (`buffer.rs`), so an unsaved edit still contributes immediately.
|
||||
pub(super) fn word_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
|
||||
// Gathering and sorting the names is the one tier whose *setup* costs
|
||||
// something, so a response that is already full skips it outright.
|
||||
if items.full() {
|
||||
return;
|
||||
}
|
||||
// The buffer's own words were offered by tier 3 already, so only the
|
||||
// prebuilt table is read here; a name in both is offered once anyway,
|
||||
// because `Items` drops a repeated label.
|
||||
let names: Vec<&str> = match fuzzy {
|
||||
None => {
|
||||
let mut names: Vec<&str> =
|
||||
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
|
||||
names
|
||||
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
None => ws.candidates().words(&word.text).iter().map(String::as_str).collect(),
|
||||
Some(query) => {
|
||||
// The table's hits come back ranked; the buffer's own words are
|
||||
// scored here and the two are ranked together, so a name the user
|
||||
// typed a moment ago sits where its match deserves rather than
|
||||
// after everything the table knows.
|
||||
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
|
||||
let hits = ws.candidates().words_fuzzy(query, LIMIT);
|
||||
// A full return is a truncation; see `index_tier`.
|
||||
items.incomplete |= hits.len() >= LIMIT;
|
||||
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
|
||||
hits.sort_by(|a, b| rank_cmp(*a, *b));
|
||||
// A name in both lists is offered once: `Items` drops the second
|
||||
// by label, so no dedup is needed here.
|
||||
hits.into_iter().map(|(name, _)| name).collect()
|
||||
}
|
||||
};
|
||||
@@ -255,21 +235,6 @@ pub(super) fn word_tier(
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
|
||||
///
|
||||
/// The live half of the tier: the prebuilt table is as of the last index
|
||||
/// rebuild, and this is the buffer's own token stream, recomputed on every
|
||||
/// change. The filter is `candidates::is_word`'s, in the other direction —
|
||||
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
|
||||
/// identifier.
|
||||
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
|
||||
doc.tokens
|
||||
.iter()
|
||||
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
|
||||
.map(|token| token.text.as_str())
|
||||
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -374,7 +339,7 @@ endmodule
|
||||
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
|
||||
assert_eq!(
|
||||
template_labels(&at_item),
|
||||
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
|
||||
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
|
||||
"and `alw` finds every one of them"
|
||||
);
|
||||
|
||||
@@ -419,7 +384,7 @@ endmodule
|
||||
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
|
||||
assert_eq!(
|
||||
template_labels(&always),
|
||||
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
|
||||
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
|
||||
"and no always_ff, which a .v file's compiler would reject"
|
||||
);
|
||||
}
|
||||
@@ -637,7 +602,8 @@ endmodule
|
||||
#[test]
|
||||
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
|
||||
// `inner` is declared in a block the cursor is not in, so it may only
|
||||
// arrive as a project word — never as a visible declaration.
|
||||
// arrive as one of this file's declarations (tier 2, `completion-ux`)
|
||||
// — never as a visible declaration.
|
||||
let top = "\
|
||||
module top;
|
||||
initial begin : b
|
||||
@@ -650,8 +616,8 @@ endmodule
|
||||
";
|
||||
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "inner_only").expect("known as a word at least");
|
||||
assert_eq!(tier(item), TIER_WORD, "{item:#?}");
|
||||
let item = find(&items, "inner_only").expect("known as a declaration at least");
|
||||
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -750,12 +716,13 @@ endmodule
|
||||
fn the_short_answers_are_what_they_always_were() {
|
||||
let (_tree, mut ws, uri) = typing("fuzzygolden");
|
||||
for (typed, expected) in [
|
||||
// `c` itself is in the list because the buffer being typed in
|
||||
// holds it as an `Ident` token — behaviour this round did not
|
||||
// touch, pinned here because a golden that quietly lost it would
|
||||
// be a change.
|
||||
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
|
||||
("ce", vec!["ce", "celsius"]),
|
||||
// `c` itself used to be in the list, because the buffer being
|
||||
// typed in holds it as an `Ident` token. `completion-ux`
|
||||
// (2026-11-17) dropped it on purpose: the buffer-word tier skips
|
||||
// the token under the cursor, and offering the user their own
|
||||
// half-word back is noise.
|
||||
("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]),
|
||||
("ce", vec!["celsius"]),
|
||||
] {
|
||||
let found = items(after_typing(&mut ws, &uri, typed));
|
||||
let named: Vec<&str> = found
|
||||
|
||||
@@ -148,6 +148,39 @@ mod tests {
|
||||
assert_eq!(folds(text), vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_layer_a_reader_is_inside_starts_a_fold_on_its_header_line() {
|
||||
// VS Code's sticky scroll is told (the extension's
|
||||
// `editor.stickyScroll.defaultModel`) to pin the first line of every
|
||||
// fold around the top of the viewport. So the header of each layer —
|
||||
// module, `always`, `case`, the case item, the `if` — must be a fold's
|
||||
// start line, and each fold must reach the innermost statement.
|
||||
let text = concat!(
|
||||
"module m (\n", // 0
|
||||
" input a\n", // 1
|
||||
");\n", // 2
|
||||
" always @(*) begin\n", // 3
|
||||
" case (st)\n", // 4
|
||||
" st_1: begin\n", // 5
|
||||
" if (cond_1) begin\n", // 6
|
||||
" x = 1;\n", // 7
|
||||
" y = 2;\n", // 8
|
||||
" end\n", // 9
|
||||
" end\n", // 10
|
||||
" endcase\n", // 11
|
||||
" end\n", // 12
|
||||
"endmodule\n", // 13
|
||||
);
|
||||
let ranges = folds(text);
|
||||
for header in [0, 3, 4, 5, 6] {
|
||||
let fold = ranges.iter().find(|(start, _, _)| *start == header);
|
||||
let Some((_, end, _)) = fold else {
|
||||
panic!("no fold starts on line {header}: {ranges:?}")
|
||||
};
|
||||
assert!(*end >= 8, "the fold from line {header} must cover line 8, got {ranges:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_that_opens_and_closes_on_one_line_folds_nothing() {
|
||||
// `end_line <= start_line` means there is no hidden line to gain.
|
||||
|
||||
@@ -6,13 +6,16 @@
|
||||
//! output, or no edit at all and an error for the user to read. That holds for
|
||||
//! the range requests too — their output is verified over the whole buffer,
|
||||
//! and what makes a request a *range* format is which constructs it laid out,
|
||||
//! not which bytes it was allowed to replace.
|
||||
//! not which bytes it was allowed to replace. The range requests go through
|
||||
//! `format_selection`: the smallest run of sibling items or statements the
|
||||
//! selection covers, laid out at the indentation it was written at — see
|
||||
//! `docs/features/selection-formatting/README.md`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
use vlog_formatter::{format_selection, format_source, Config, LineRanges};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Document;
|
||||
@@ -122,10 +125,12 @@ pub fn range_formatting(
|
||||
///
|
||||
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
|
||||
/// before the engine sees them, so overlapping, adjacent, repeated and
|
||||
/// unsorted input from the client all reach the same answer. No range is
|
||||
/// formatted on its own — one `format_range` call lays out the union, which is
|
||||
/// what keeps the all-or-nothing contract (CLAUDE.md invariant #1) whole
|
||||
/// rather than making it a promise per range.
|
||||
/// unsorted input from the client all reach the same answer. Each merged span
|
||||
/// selects its own target (targets that overlap are re-selected from the hull
|
||||
/// of their spans), but no range is formatted on its own — one
|
||||
/// `format_selection` call lays out and verifies them all, which is what keeps
|
||||
/// the all-or-nothing contract (CLAUDE.md invariant #1) whole rather than
|
||||
/// making it a promise per range.
|
||||
///
|
||||
/// The reply is still one whole-document edit: the engine's contract is
|
||||
/// all-or-nothing over the file, and a partial run's output differs from the
|
||||
@@ -140,7 +145,7 @@ pub fn ranges_formatting(
|
||||
return Ok(None);
|
||||
}
|
||||
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
|
||||
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
||||
let formatted = format_selection(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
||||
if formatted == doc.text {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -700,6 +705,39 @@ mod tests {
|
||||
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
|
||||
}
|
||||
|
||||
/// A file indented four spaces with a `case` nested in an `always`: the
|
||||
/// shape VS Code's "Format Selection" most often sends.
|
||||
const NESTED: &str = "module m;\n always @* begin\n case (s)\n 0: y=a;\n default:y=b;\n endcase\n z = 1;\n end\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_selected_case_is_laid_out_alone_at_the_indentation_it_starts_at() {
|
||||
let edit = ranged(NESTED, at(2, 0, 6, 0)).expect("formats").expect("changed");
|
||||
assert_eq!(
|
||||
edit.new_text,
|
||||
"module m;\n always @* begin\n case (s)\n 0: y = a;\n default: y = b;\n endcase\n z = 1;\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_indented_selection_keeps_its_tabs() {
|
||||
let text = "module m;\n\talways @* begin\n\t\tx=1;\n\tend\nendmodule\n";
|
||||
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
|
||||
assert_eq!(edit.new_text, "module m;\n\talways @* begin\n\t\tx = 1;\n\tend\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parse_error_outside_the_selection_does_not_block_it() {
|
||||
let text = "module m;\n always @* begin\n x=1;\n end\n assign y = ;\nendmodule\n";
|
||||
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
|
||||
assert_eq!(
|
||||
edit.new_text,
|
||||
"module m;\n always @* begin\n x = 1;\n end\n assign y = ;\nendmodule\n"
|
||||
);
|
||||
// Inside it, the request is refused with a message to read.
|
||||
let message = ranged(text, at(4, 0, 4, 4)).expect_err("must refuse");
|
||||
assert!(message.contains("syntax error"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparsable_buffer_produces_no_range_edit_either() {
|
||||
// Range formatting cannot rescue broken input; the strict parse still
|
||||
@@ -802,7 +840,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() {
|
||||
// No partial output on either path (CLAUDE.md invariant #1), and the
|
||||
// same message: both are one `format_range` call away from the engine.
|
||||
// same message: both are one `format_selection` call away from the engine.
|
||||
let broken = "module m;\n wire ;\nendmodule\n";
|
||||
let one = ranged(broken, at(0, 0, 0, 9));
|
||||
let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]);
|
||||
|
||||
@@ -30,12 +30,18 @@ use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
/// The module the cursor names, as the root of a hierarchy — its own
|
||||
/// declaration, or an instantiation of it.
|
||||
mod calls;
|
||||
mod tf;
|
||||
|
||||
/// The root of a hierarchy at the cursor.
|
||||
///
|
||||
/// `None` for every other position, which is what stops an editor from opening
|
||||
/// an empty hierarchy view on a `wire`. A name the workspace index does not
|
||||
/// hold as a module declines the same way: there is no node to stand on.
|
||||
/// In order: a module's own declaration name, or the module name of an
|
||||
/// instantiation (both unchanged since M11); an instance name, which stands
|
||||
/// for the instantiated module; a function or task the cursor names — its
|
||||
/// declaration, a call, its end label; the function or task whose body holds
|
||||
/// the cursor; and the module, interface or program whose body holds it.
|
||||
/// `None` only where nothing encloses the cursor, which is what stops an
|
||||
/// editor from opening an empty view.
|
||||
///
|
||||
/// A name two files declare returns *both* items rather than a guess, the same
|
||||
/// answer `textDocument/definition` gives for the same ambiguity — the client
|
||||
@@ -51,11 +57,27 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
|
||||
let positions = doc.positions();
|
||||
return Some(vec![item(uri.clone(), &positions, decl)?]);
|
||||
}
|
||||
// The cursor on an instantiation names the module being instantiated.
|
||||
// The cursor on an instantiation names the module being instantiated —
|
||||
// through its module name or through one of its instance names.
|
||||
let sites = instantiations::sites(&doc.tree.items);
|
||||
let site = sites.iter().find(|site| touches(site.inst.module_span, offset))?;
|
||||
let items = declarations_of(ws, &site.inst.module);
|
||||
(!items.is_empty()).then_some(items)
|
||||
let on_module = sites.iter().find(|site| touches(site.inst.module_span, offset));
|
||||
let on_instance = || {
|
||||
sites.iter().find(|site| site.inst.instances.iter().any(|i| touches(i.name_span, offset)))
|
||||
};
|
||||
if let Some(site) = on_module.or_else(on_instance) {
|
||||
let items = declarations_of(ws, &site.inst.module);
|
||||
if !items.is_empty() {
|
||||
return Some(items);
|
||||
}
|
||||
}
|
||||
if let Some(items) = tf::prepare(ws, doc, uri, offset) {
|
||||
return Some(items);
|
||||
}
|
||||
let decl = instantiations::declarations(&doc.tree.items)
|
||||
.into_iter()
|
||||
.filter(|decl| tf::holds(decl.span, offset))
|
||||
.min_by_key(|decl| decl.span.end - decl.span.start)?;
|
||||
Some(vec![item(uri.clone(), &doc.positions(), decl)?])
|
||||
}
|
||||
|
||||
/// Who instantiates this module: one call per **instantiating module**, with
|
||||
@@ -63,7 +85,14 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
|
||||
///
|
||||
/// One name asked of the batch below, which is the only census in this server
|
||||
/// — the code lens counts what this lists.
|
||||
///
|
||||
/// A function or task item (one carrying `data`) is answered by its call
|
||||
/// sites instead (`hierarchy/calls.rs`); a package or class caller item has
|
||||
/// no incoming calls.
|
||||
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
|
||||
if let Some(data) = tf::Data::of(item) {
|
||||
return calls::incoming(ws, item, &data);
|
||||
}
|
||||
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -131,7 +160,13 @@ pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyI
|
||||
/// silently. A hierarchy node has nowhere to say "and one more I could not
|
||||
/// find", and a node pointing at the wrong one of two same-named modules would
|
||||
/// send the user to the wrong file with no way to tell.
|
||||
///
|
||||
/// A function or task item is answered by the calls in its body instead
|
||||
/// (`hierarchy/calls.rs`). A module item never lists function calls.
|
||||
pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
|
||||
if let Some(data) = tf::Data::of(item) {
|
||||
return calls::outgoing(ws, item, &data);
|
||||
}
|
||||
let Some(text) = text_of(ws, &item.uri) else { return Vec::new() };
|
||||
let (tree, _) = parse_source_tolerant(&text);
|
||||
let line_index = LineIndex::new(&text);
|
||||
@@ -431,12 +466,17 @@ endmodule
|
||||
);
|
||||
}
|
||||
|
||||
/// Reversed by call-hierarchy-everywhere (2026-10-14): the `module`
|
||||
/// keyword and a connected expression are inside `top` and prepare it,
|
||||
/// and an instance name stands for the instantiated module. Only a
|
||||
/// position no module encloses still prepares nothing.
|
||||
#[test]
|
||||
fn a_position_on_no_module_prepares_nothing() {
|
||||
fn a_position_on_no_module_prepares_the_enclosing_one_or_nothing() {
|
||||
let (_tree, ws, uri) = three("none");
|
||||
assert!(prepare(&ws, &uri, 0).is_none(), "the `module` keyword");
|
||||
assert!(prepare(&ws, &uri, at(TOP, "u_a")).is_none(), "the instance name");
|
||||
assert!(prepare(&ws, &uri, at(TOP, "1'b0")).is_none(), "a connected expression");
|
||||
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0;
|
||||
assert_eq!(name(0), "top", "the `module` keyword is inside `top`");
|
||||
assert_eq!(name(at(TOP, "u_a")), "sub", "the instance name stands for its module");
|
||||
assert_eq!(name(at(TOP, "1'b0")), "top", "a connected expression is inside `top`");
|
||||
let (_tree, ws, uri) = workspace("nonmodule", &[("p.sv", "package p;\nendpackage\n")]);
|
||||
assert!(prepare(&ws, &uri, at("package p;", "p;")).is_none(), "a package is not a module");
|
||||
}
|
||||
@@ -448,11 +488,14 @@ endmodule
|
||||
assert!(prepare(&ws, &uri, at(SUB, "sub") + 3).is_some());
|
||||
}
|
||||
|
||||
/// Reversed by call-hierarchy-everywhere (2026-10-14): no item for
|
||||
/// `nope`, which nothing declares, but the module the cursor is inside.
|
||||
#[test]
|
||||
fn an_instantiation_of_a_module_nothing_declares_prepares_nothing() {
|
||||
fn an_instantiation_of_a_module_nothing_declares_prepares_the_enclosing_module() {
|
||||
let top = "module top;\n nope u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("undeclared", &[("top.sv", top)]);
|
||||
assert!(prepare(&ws, &uri, at(top, "nope")).is_none());
|
||||
let items = prepare(&ws, &uri, at(top, "nope")).expect("the enclosing module");
|
||||
assert_eq!(shape(&items[0]), ("top".to_string(), "top.sv".to_string(), 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -894,18 +937,38 @@ endmodule
|
||||
assert_eq!(inner_calls[0].to.name, "sub");
|
||||
}
|
||||
|
||||
/// Reversed by call-hierarchy-everywhere (2026-10-14): a comment or a
|
||||
/// string inside `top` prepares `top` — never the `sub` its text spells.
|
||||
#[test]
|
||||
fn qa_prepare_on_a_string_or_comment_is_null() {
|
||||
fn qa_prepare_on_a_string_or_comment_is_the_enclosing_module_not_the_text() {
|
||||
let text = "module top;\n // sub lives here\n string s = \"sub\";\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("qa_string_comment", &[("top.sv", text)]);
|
||||
let comment_offset = at(text, "// sub");
|
||||
let string_offset = at(text, "\"sub\"") + 1;
|
||||
assert!(prepare(&ws, &uri, comment_offset + 3).is_none(), "cursor inside a comment");
|
||||
assert!(prepare(&ws, &uri, string_offset + 1).is_none(), "cursor inside a string literal");
|
||||
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0;
|
||||
assert_eq!(name(comment_offset + 3), "top", "cursor inside a comment");
|
||||
assert_eq!(name(string_offset + 1), "top", "cursor inside a string literal");
|
||||
}
|
||||
|
||||
/// Reversed by call-hierarchy-everywhere (2026-10-14): the bind target
|
||||
/// is still not read as a module name, but the cursor is inside the
|
||||
/// module the `bind` is written in, and that is what it prepares. The
|
||||
/// fixture moves the `bind` into `harness` so the two cannot coincide.
|
||||
#[test]
|
||||
fn qa_prepare_on_a_bind_target_module_name_is_currently_null() {
|
||||
fn qa_prepare_on_a_bind_target_module_name_is_the_enclosing_module() {
|
||||
let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n";
|
||||
let top = "module top;\nendmodule\n";
|
||||
let chk = "module chk;\nendmodule\n";
|
||||
let files = [("harness.sv", harness), ("top.sv", top), ("chk.sv", chk)];
|
||||
let (_tree, ws, uri) = workspace("qa_bind_target2", &files);
|
||||
let items = prepare(&ws, &uri, at(harness, "bind top") + 5).expect("the enclosing module");
|
||||
assert_eq!(shape(&items[0]).0, "harness", "not the bind target `top`");
|
||||
}
|
||||
|
||||
/// The M11 QA pin, kept for its history: the answer it pinned is the
|
||||
/// enclosing module now, which in this fixture is `top` itself.
|
||||
#[test]
|
||||
fn qa_prepare_on_a_bind_target_module_name_was_null() {
|
||||
// `bind top chk u_chk ();` — cursor on `top`, the bind's *target*
|
||||
// module. `top` is a real, declared module and a genuine reference to
|
||||
// it, but neither `declarations()` (which only sees `module ...`
|
||||
@@ -919,10 +982,8 @@ endmodule
|
||||
let chk = "module chk;\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("qa_bind_target", &[("top.sv", top), ("chk.sv", chk)]);
|
||||
let target_offset = at(top, "bind top") + 5;
|
||||
assert!(
|
||||
prepare(&ws, &uri, target_offset).is_none(),
|
||||
"pinning today's answer, not endorsing it"
|
||||
);
|
||||
let items = prepare(&ws, &uri, target_offset).expect("the enclosing module");
|
||||
assert_eq!(shape(&items[0]).0, "top", "the module the bind is written in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,512 @@
|
||||
//! `incomingCalls` and `outgoingCalls` for a function or task item.
|
||||
//!
|
||||
//! A call is a *use* of the function's name that the semantic layer resolved
|
||||
//! to its declaration — in this file through the symbol table, in another
|
||||
//! file through the workspace overlay — and that is not one of the three
|
||||
//! uses of a name that are not calls: the `endfunction : f` label, the name
|
||||
//! of an out-of-body definition (`function void c::f();`), and the Verilog
|
||||
//! result variable (`f = f + 1;` inside `f`).
|
||||
//!
|
||||
//! **Incoming** reads the same files `textDocument/references` reads: the
|
||||
//! declaring file, every open buffer, and every closed file the index holds a
|
||||
//! reference posting for. An ambiguous target falls back to the declaring
|
||||
//! file alone, as references falls back to the cursor's file. Each call is
|
||||
//! credited to its caller: the enclosing function or task, else the enclosing
|
||||
//! module, interface, program, package or class.
|
||||
//!
|
||||
//! **Outgoing** reads the item's own body and resolves every call in it; a
|
||||
//! system task, an unresolved name and an ambiguous one are skipped, as an
|
||||
//! ambiguous instantiation is for a module.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::{CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, Uri};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{
|
||||
Def, ExternalTarget, Reference, ReferenceId, ScopeId, ScopeKind, Semantics, SymbolId,
|
||||
SymbolKind as Kind,
|
||||
};
|
||||
|
||||
use super::tf::{self, Analysis, Data};
|
||||
use crate::nav::indexed_def_for_symbol;
|
||||
use crate::state::{first_token_from, Document, Workspace};
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// Every call of the function or task an item names, one entry per caller.
|
||||
pub(super) fn incoming(
|
||||
ws: &Workspace,
|
||||
item: &CallHierarchyItem,
|
||||
data: &Data,
|
||||
) -> Vec<CallHierarchyIncomingCall> {
|
||||
let Some((decl, symbol)) = tf::target(ws, item, data) else { return Vec::new() };
|
||||
let Some(name) = decl.semantics.symbol(symbol).map(|s| s.name.clone()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
// Only a declaration the index holds — a package or class member — can be
|
||||
// named through the workspace overlay, from another file or from its own
|
||||
// (`super.f()` reaches a base class's method that way).
|
||||
let def = decl
|
||||
.path
|
||||
.as_ref()
|
||||
.and_then(|_| indexed_def_for_symbol(ws, &decl, decl.semantics.symbol(symbol)?));
|
||||
let mut calls = callers(&item.uri, &decl, &name, |reference, id| {
|
||||
reference.resolved() == Some(symbol) || def.is_some_and(|def| names_def(&decl, id, def))
|
||||
});
|
||||
if let Some(elsewhere) = def.and_then(|def| other_files(ws, &decl, def, &name)) {
|
||||
calls.extend(elsewhere);
|
||||
}
|
||||
calls.sort_by(|a, b| {
|
||||
(a.from.uri.as_str(), super::key(a.from.selection_range))
|
||||
.cmp(&(b.from.uri.as_str(), super::key(b.from.selection_range)))
|
||||
});
|
||||
calls
|
||||
}
|
||||
|
||||
/// The calls written in every file but the declaring one, or `None` when the
|
||||
/// workspace cannot say which declaration a use names.
|
||||
///
|
||||
/// The same files `textDocument/references` reads for an indexed
|
||||
/// declaration: every open buffer, and every closed file holding a reference
|
||||
/// posting for it.
|
||||
fn other_files(
|
||||
ws: &Workspace,
|
||||
decl: &Document,
|
||||
def: &Def,
|
||||
name: &str,
|
||||
) -> Option<Vec<CallHierarchyIncomingCall>> {
|
||||
let declaring = decl.path.as_deref()?;
|
||||
if declined(ws, def, name, declaring) {
|
||||
return None;
|
||||
}
|
||||
let index = ws.index();
|
||||
let is_call_of_def = |doc: &Document, id: ReferenceId| names_def(doc, id, def);
|
||||
let mut calls = Vec::new();
|
||||
for (_, doc) in ws.open_documents() {
|
||||
let Some(path) = doc.path.as_deref().filter(|path| *path != declaring) else { continue };
|
||||
let Some(uri) = path_to_uri(path) else { continue };
|
||||
calls.extend(callers(&uri, doc, name, |_, id| is_call_of_def(doc, id)));
|
||||
}
|
||||
let mut closed: Vec<PathBuf> = index
|
||||
.references_to(def)
|
||||
.iter()
|
||||
.filter_map(|site| index.path(site.file))
|
||||
.filter(|path| *path != declaring && ws.document_for_path(path).is_none())
|
||||
.map(Path::to_path_buf)
|
||||
.collect();
|
||||
closed.sort();
|
||||
closed.dedup();
|
||||
for path in closed {
|
||||
let (Some(uri), Some(doc)) = (path_to_uri(&path), tf::load_path(ws, &path)) else {
|
||||
continue;
|
||||
};
|
||||
calls.extend(callers(&uri, &doc, name, |_, id| is_call_of_def(&doc, id)));
|
||||
}
|
||||
Some(calls)
|
||||
}
|
||||
|
||||
/// Whether the workspace cannot say which declaration a use of `def` names —
|
||||
/// the index marks its uses ambiguous, or an open buffer other than the
|
||||
/// declaring file holds a use that could be `def` or another declaration.
|
||||
/// References declines in exactly these two cases.
|
||||
///
|
||||
/// In a consistent workspace neither can hold for a `def` that
|
||||
/// `indexed_def_for_symbol` accepted (it demands a single record under the
|
||||
/// very key every use's lookup reads), so this is the defensive half of the
|
||||
/// contract; the tests reach it with a buffer the index does not hold and
|
||||
/// with a lookup asked directly.
|
||||
fn declined(ws: &Workspace, def: &Def, name: &str, declaring: &Path) -> bool {
|
||||
ws.index().references_are_ambiguous(def)
|
||||
|| ws.open_documents().any(|(_, doc)| {
|
||||
doc.path.as_deref().is_some_and(|path| path != declaring)
|
||||
&& names_it_ambiguously(doc, name, def)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the workspace overlay answered one use with exactly `def`.
|
||||
fn names_def(doc: &Document, id: ReferenceId, def: &Def) -> bool {
|
||||
matches!(doc.external.get(id), Some(ExternalTarget::Resolved(found)) if found == def)
|
||||
}
|
||||
|
||||
/// Whether an open buffer holds a use of `name` that could be `def` or
|
||||
/// another declaration equally — the case references declines.
|
||||
fn names_it_ambiguously(doc: &Document, name: &str, def: &Def) -> bool {
|
||||
doc.semantics.references().iter().enumerate().any(|(at, reference)| {
|
||||
reference.name == name
|
||||
&& matches!(
|
||||
doc.external.get(ReferenceId(at as u32)),
|
||||
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(def)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// One file's calls, grouped by caller, for the uses `names_target` accepts.
|
||||
fn callers(
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
name: &str,
|
||||
names_target: impl Fn(&Reference, ReferenceId) -> bool,
|
||||
) -> Vec<CallHierarchyIncomingCall> {
|
||||
let semantics = &doc.semantics;
|
||||
let mut groups: Vec<(SymbolId, Vec<TextRange>)> = Vec::new();
|
||||
for (at, reference) in semantics.references().iter().enumerate() {
|
||||
if reference.name != name || !names_target(reference, ReferenceId(at as u32)) {
|
||||
continue;
|
||||
}
|
||||
if !is_call(doc, reference) {
|
||||
continue;
|
||||
}
|
||||
let Some(caller) = caller_of(semantics, reference.scope) else { continue };
|
||||
match groups.iter_mut().find(|(held, _)| *held == caller) {
|
||||
Some((_, spans)) => spans.push(reference.name_span),
|
||||
None => groups.push((caller, vec![reference.name_span])),
|
||||
}
|
||||
}
|
||||
let positions = doc.positions();
|
||||
groups
|
||||
.into_iter()
|
||||
.filter_map(|(caller, spans)| {
|
||||
Some(CallHierarchyIncomingCall {
|
||||
from: caller_item(uri, doc, caller)?,
|
||||
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The declaration a call written in `scope` is credited to: the innermost
|
||||
/// function or task, else the module, interface, program, package or class.
|
||||
/// `None` for a call at file scope, which has no honest caller.
|
||||
fn caller_of(semantics: &Semantics, mut scope: ScopeId) -> Option<SymbolId> {
|
||||
loop {
|
||||
let held = semantics.scope(scope)?;
|
||||
let owner = held.owner;
|
||||
match held.kind {
|
||||
ScopeKind::Function
|
||||
| ScopeKind::Task
|
||||
| ScopeKind::Module
|
||||
| ScopeKind::Package
|
||||
| ScopeKind::Class
|
||||
if owner.is_some() =>
|
||||
{
|
||||
return owner;
|
||||
}
|
||||
ScopeKind::File => return None,
|
||||
_ => scope = held.parent?,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The item a caller is shown as. A module caller is the very item the
|
||||
/// module hierarchy hands out — no `data` — so expanding it walks
|
||||
/// instantiations, one level up the design.
|
||||
fn caller_item(uri: &Uri, doc: &Document, caller: SymbolId) -> Option<CallHierarchyItem> {
|
||||
let symbol = doc.semantics.symbol(caller)?;
|
||||
match symbol.kind {
|
||||
Kind::Function | Kind::Task => tf::item(uri.clone(), doc, symbol),
|
||||
Kind::Package | Kind::Class => tf::container_item(uri.clone(), doc, symbol),
|
||||
_ => super::item_of(
|
||||
uri.clone(),
|
||||
&doc.positions(),
|
||||
&symbol.name,
|
||||
symbol.name_span,
|
||||
symbol.decl_span,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a use of a function or task's name is a call of it.
|
||||
///
|
||||
/// Three uses are not: an end label (`endfunction : f`, recorded in the
|
||||
/// scope *around* the function although written inside its extent), the name
|
||||
/// of an out-of-body definition (recorded as a redeclaration), and the
|
||||
/// Verilog result variable — a function's own name inside its own body with
|
||||
/// no `(` after it, written (`f = a;`) or read (`f = f + 1;`).
|
||||
fn is_call(doc: &Document, reference: &Reference) -> bool {
|
||||
let semantics = &doc.semantics;
|
||||
if semantics.duplicates().iter().any(|dup| dup.name_span == reference.name_span) {
|
||||
return false;
|
||||
}
|
||||
let Some(id) = reference.resolved() else { return true };
|
||||
let Some(symbol) = semantics.symbol(id) else { return true };
|
||||
if let Some(body) = symbol.child_scope {
|
||||
let inside = semantics.scope(body).is_some_and(|scope| {
|
||||
tf::holds(scope.span, reference.name_span.start)
|
||||
&& tf::holds(scope.span, reference.name_span.end)
|
||||
});
|
||||
if inside && !within(semantics, reference.scope, &[body]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
!(symbol.kind == Kind::Function
|
||||
&& in_own_body(semantics, reference.scope, id)
|
||||
&& !followed_by_paren(doc, reference.name_span))
|
||||
}
|
||||
|
||||
/// Whether `scope` is, or is nested in, a function body `function` owns — the
|
||||
/// prototype's own scope or an out-of-body definition's.
|
||||
fn in_own_body(semantics: &Semantics, mut scope: ScopeId, function: SymbolId) -> bool {
|
||||
loop {
|
||||
let Some(held) = semantics.scope(scope) else { return false };
|
||||
if held.kind == ScopeKind::Function && held.owner == Some(function) {
|
||||
return true;
|
||||
}
|
||||
match held.parent {
|
||||
Some(parent) => scope = parent,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the token after `span` is `(` — what makes a function's own name
|
||||
/// inside its body a recursive call rather than its result variable.
|
||||
fn followed_by_paren(doc: &Document, span: TextRange) -> bool {
|
||||
let next = first_token_from(&doc.tokens, span.end);
|
||||
doc.tokens.get(next).is_some_and(|token| token.is_sym("("))
|
||||
}
|
||||
|
||||
/// Whether `scope` is one of `bodies` or nested inside one.
|
||||
fn within(semantics: &Semantics, mut scope: ScopeId, bodies: &[ScopeId]) -> bool {
|
||||
loop {
|
||||
if bodies.contains(&scope) {
|
||||
return true;
|
||||
}
|
||||
match semantics.scope(scope).and_then(|held| held.parent) {
|
||||
Some(parent) => scope = parent,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a callee is, before its item is built: a declaration in the same
|
||||
/// file, or one the workspace index answered.
|
||||
#[derive(PartialEq)]
|
||||
enum Callee {
|
||||
Local(SymbolId),
|
||||
Indexed(Def),
|
||||
}
|
||||
|
||||
/// Every function and task the item's body calls, one entry per callee.
|
||||
pub(super) fn outgoing(
|
||||
ws: &Workspace,
|
||||
item: &CallHierarchyItem,
|
||||
data: &Data,
|
||||
) -> Vec<CallHierarchyOutgoingCall> {
|
||||
let Some((doc, symbol)) = tf::target(ws, item, data) else { return Vec::new() };
|
||||
let groups = callees(&doc, symbol);
|
||||
let positions = doc.positions();
|
||||
// Three hundred callees in one closed package are one parse, not three
|
||||
// hundred.
|
||||
let mut loaded = tf::Loaded::new(ws);
|
||||
groups
|
||||
.into_iter()
|
||||
.filter_map(|(callee, spans)| {
|
||||
let to = match callee {
|
||||
Callee::Local(id) => tf::item(item.uri.clone(), &doc, doc.semantics.symbol(id)?),
|
||||
Callee::Indexed(def) => loaded.item(&def),
|
||||
}?;
|
||||
let from_ranges = spans.into_iter().map(|span| positions.range(span)).collect();
|
||||
Some(CallHierarchyOutgoingCall { to, from_ranges })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The calls written in `symbol`'s bodies, grouped by what they resolve to.
|
||||
///
|
||||
/// "Bodies", plural: an `extern` prototype and its out-of-body definition are
|
||||
/// two scopes owned by one symbol, and the definition is where the calls are.
|
||||
fn callees(doc: &Analysis, symbol: SymbolId) -> Vec<(Callee, Vec<TextRange>)> {
|
||||
let semantics = &doc.semantics;
|
||||
let bodies: Vec<ScopeId> = semantics
|
||||
.scopes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, scope)| scope.owner == Some(symbol))
|
||||
.filter(|(_, scope)| matches!(scope.kind, ScopeKind::Function | ScopeKind::Task))
|
||||
.map(|(at, _)| ScopeId(at as u32))
|
||||
.collect();
|
||||
let mut groups: Vec<(Callee, Vec<TextRange>)> = Vec::new();
|
||||
for (at, reference) in semantics.references().iter().enumerate() {
|
||||
if !within(semantics, reference.scope, &bodies) || !is_call(doc, reference) {
|
||||
continue;
|
||||
}
|
||||
let Some(callee) = callee_of(doc, reference, ReferenceId(at as u32)) else { continue };
|
||||
match groups.iter_mut().find(|(held, _)| *held == callee) {
|
||||
Some((_, spans)) => spans.push(reference.name_span),
|
||||
None => groups.push((callee, vec![reference.name_span])),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// The function or task one use resolves to, or `None` for anything else —
|
||||
/// a variable, an unresolved name, a name two files declare.
|
||||
fn callee_of(doc: &Document, reference: &Reference, id: ReferenceId) -> Option<Callee> {
|
||||
if let Some(local) = reference.resolved() {
|
||||
let symbol = doc.semantics.symbol(local)?;
|
||||
return tf::is_tf(symbol.kind).then_some(Callee::Local(local));
|
||||
}
|
||||
match doc.external.get(id)? {
|
||||
ExternalTarget::Resolved(def) if tf::is_tf(def.kind) => Some(Callee::Indexed(def.clone())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every use of `name` in `text`, as `(line, is a call)`.
|
||||
fn classified(text: &str, name: &str) -> Vec<(usize, bool)> {
|
||||
let doc = Document::new(None, text.to_string(), &vlog_semantic::WorkspaceIndex::default());
|
||||
doc.semantics
|
||||
.references()
|
||||
.iter()
|
||||
.filter(|reference| reference.name == name)
|
||||
.map(|r| (text[..r.name_span.start as usize].matches('\n').count(), is_call(&doc, r)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_label_a_result_assignment_and_a_redeclaration_are_not_calls() {
|
||||
let text = "\
|
||||
class c;
|
||||
extern function int f(int a);
|
||||
endclass
|
||||
function int c::f(int a);
|
||||
f = a;
|
||||
f += 1;
|
||||
return f(a - 1) + f;
|
||||
endfunction : f
|
||||
";
|
||||
assert_eq!(
|
||||
classified(text, "f"),
|
||||
[(3, false), (4, false), (5, false), (6, true), (6, false)],
|
||||
"the out-of-body name, two result writes, a recursive call, a result read (the \
|
||||
binder records no use for an out-of-body definition's end label)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_result_variable_read_in_its_own_body_is_not_a_call() {
|
||||
// QA finding 1: the classic Verilog-2001 `clog2`.
|
||||
let text = "\
|
||||
module lg;
|
||||
function integer clog2(input integer v);
|
||||
begin
|
||||
clog2 = 0;
|
||||
while (v > 1) begin
|
||||
clog2 = clog2 + 1;
|
||||
v = v >> 1;
|
||||
end
|
||||
end
|
||||
endfunction
|
||||
initial $display(clog2(16));
|
||||
endmodule
|
||||
";
|
||||
assert_eq!(
|
||||
classified(text, "clog2"),
|
||||
[(3, false), (5, false), (5, false), (10, true)],
|
||||
"written, written, read inside its own body; called from the module"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_function_name_in_another_body_is_a_call() {
|
||||
// A function with no arguments may be called without parentheses.
|
||||
let text = "\
|
||||
module m;
|
||||
function int g(); return 1; endfunction
|
||||
function int h(); return g + 1; endfunction
|
||||
function int k(); k = g; endfunction
|
||||
endmodule
|
||||
";
|
||||
assert_eq!(classified(text, "g"), [(2, true), (3, true)]);
|
||||
assert_eq!(classified(text, "k"), [(3, false)], "`k`'s own result, beside the call");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_label_is_not_a_call_but_a_recursive_call_is() {
|
||||
let text =
|
||||
"module m;\n function int f(int a);\n return f(a);\n endfunction : f\nendmodule\n";
|
||||
assert_eq!(classified(text, "f"), [(2, true), (3, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_enable_without_parentheses_is_a_call() {
|
||||
let text = "module m;\n task t; endtask\n initial t;\nendmodule\n";
|
||||
assert_eq!(classified(text, "t"), [(2, true)]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The two ambiguity fallbacks (QA finding 4)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Package `p` declared twice, each with `f`; the caller writes `p::f()`.
|
||||
const Z: &str = "package p;\n function int f(); return 1; endfunction\nendpackage\n";
|
||||
const USER: &str = "module user;\n int k = p::f();\nendmodule\n";
|
||||
|
||||
/// A workspace over `root` holding the two `p`s and, if `user` is set,
|
||||
/// a closed `user.sv`; plus `z1.f`'s indexed record and `z1.sv`'s path.
|
||||
fn ambiguous(name: &str, user: bool) -> (std::path::PathBuf, Workspace, Def, PathBuf) {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("lucisv_server_calls_{}_{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("src")).expect("dir");
|
||||
std::fs::write(root.join("src/z1.sv"), Z).expect("z1");
|
||||
std::fs::write(root.join("src/z2.sv"), Z).expect("z2");
|
||||
if user {
|
||||
std::fs::write(root.join("src/user.sv"), USER).expect("user");
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![root.join("src")]);
|
||||
let z1 = root.join("src/z1.sv");
|
||||
let def = ws
|
||||
.index()
|
||||
.member_in("p", "f", vlog_semantic::Surface::Connection)
|
||||
.iter()
|
||||
.find(|def| ws.index().path(def.file) == Some(z1.as_path()))
|
||||
.cloned()
|
||||
.expect("z1's f");
|
||||
(root, ws, def, z1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_that_marks_the_uses_ambiguous_declines() {
|
||||
let (root, ws, def, z1) = ambiguous("index", true);
|
||||
assert!(ws.index().references_are_ambiguous(&def), "premise: user.sv is indexed");
|
||||
assert_eq!(ws.open_documents().count(), 0, "premise: no buffer is open");
|
||||
assert!(declined(&ws, &def, "f", &z1));
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_holding_an_ambiguous_use_declines() {
|
||||
// The buffer lives outside the indexed folder, so only its own
|
||||
// overlay — not the index — knows the use is ambiguous.
|
||||
let (root, mut ws, def, z1) = ambiguous("buffer", false);
|
||||
assert!(!ws.index().references_are_ambiguous(&def), "premise: nothing indexed uses it");
|
||||
assert!(!declined(&ws, &def, "f", &z1), "nothing ambiguous yet");
|
||||
let outside = root.join("user.sv");
|
||||
let uri = path_to_uri(&outside).expect("uri");
|
||||
ws.set_document(uri, USER.to_string());
|
||||
assert!(declined(&ws, &def, "f", &z1));
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ambiguous_use_in_the_declaring_file_itself_does_not_decline() {
|
||||
let (root, mut ws, def, z1) = ambiguous("declaring", false);
|
||||
ws.set_document(path_to_uri(&z1).expect("uri"), format!("{Z}{USER}"));
|
||||
assert!(!declined(&ws, &def, "f", &z1), "the declaring file answers for itself");
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_at_file_scope_has_no_caller() {
|
||||
let text = "function int f(); return 1; endfunction\nlocalparam int P = f();\n";
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let call = semantics.references().iter().find(|r| r.name == "f").expect("the call");
|
||||
assert_eq!(caller_of(&semantics, call.scope), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! Function and task items for the call hierarchy: what the cursor names,
|
||||
//! what encloses it, and how an item handed back by the client is found
|
||||
//! again.
|
||||
//!
|
||||
//! A module item carries no `data` and is re-found by name, exactly as it
|
||||
//! always was. A function or task item carries a small [`Data`] object — its
|
||||
//! kind, its name and the byte offset of its name — because two functions of
|
||||
//! one name are ordinary (every module may declare its own `log2`) and the
|
||||
//! name alone cannot tell them apart.
|
||||
//!
|
||||
//! See `docs/features/call-hierarchy-everywhere/README.md`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Deref;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::{CallHierarchyItem, SymbolKind, Uri};
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Def, Definition, ScopeKind, Semantics, Symbol, SymbolId, SymbolKind as Kind};
|
||||
|
||||
use crate::nav::indexed_def_for_symbol;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
/// What a non-module item carries in `CallHierarchyItem.data`.
|
||||
///
|
||||
/// Serialized as `{"kind": "function"|"task"|"package"|"class", "name": …,
|
||||
/// "offset": …}`, where `offset` is the byte offset of the declared name in
|
||||
/// the item's file when the item was built.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct Data {
|
||||
pub kind: ItemKind,
|
||||
pub name: String,
|
||||
pub offset: u32,
|
||||
}
|
||||
|
||||
/// Which declaration a [`Data`] item stands for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum ItemKind {
|
||||
Function,
|
||||
Task,
|
||||
/// A package caller: the body of a package called a function outside any
|
||||
/// function of its own. It has no calls of its own to expand.
|
||||
Package,
|
||||
/// A class caller, for a call written in a class body outside a method.
|
||||
Class,
|
||||
}
|
||||
|
||||
impl ItemKind {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
ItemKind::Function => "function",
|
||||
ItemKind::Task => "task",
|
||||
ItemKind::Package => "package",
|
||||
ItemKind::Class => "class",
|
||||
}
|
||||
}
|
||||
|
||||
fn of_tag(tag: &str) -> Option<ItemKind> {
|
||||
match tag {
|
||||
"function" => Some(ItemKind::Function),
|
||||
"task" => Some(ItemKind::Task),
|
||||
"package" => Some(ItemKind::Package),
|
||||
"class" => Some(ItemKind::Class),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The semantic kind a function or task item re-finds; `None` for the
|
||||
/// container kinds, which are never re-found.
|
||||
fn semantic(self) -> Option<Kind> {
|
||||
match self {
|
||||
ItemKind::Function => Some(Kind::Function),
|
||||
ItemKind::Task => Some(Kind::Task),
|
||||
ItemKind::Package | ItemKind::Class => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Data {
|
||||
/// The JSON object the item carries.
|
||||
fn to_value(&self) -> Value {
|
||||
json!({ "kind": self.kind.tag(), "name": self.name, "offset": self.offset })
|
||||
}
|
||||
|
||||
/// The data of an item this server built, or `None` for a module item
|
||||
/// (which carries none) and for anything it does not recognise.
|
||||
pub fn of(item: &CallHierarchyItem) -> Option<Data> {
|
||||
let data = item.data.as_ref()?;
|
||||
let kind = ItemKind::of_tag(data.get("kind")?.as_str()?)?;
|
||||
let name = data.get("name")?.as_str()?.to_string();
|
||||
let offset = u32::try_from(data.get("offset")?.as_u64()?).ok()?;
|
||||
Some(Data { kind, name, offset })
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a declaration is something a call hierarchy can stand on as a
|
||||
/// function or task.
|
||||
pub(super) fn is_tf(kind: Kind) -> bool {
|
||||
matches!(kind, Kind::Function | Kind::Task)
|
||||
}
|
||||
|
||||
/// One file's analysis: the open buffer's own, or one built from the text on
|
||||
/// disk for a file no editor has open.
|
||||
pub(super) enum Analysis<'a> {
|
||||
Open(&'a Document),
|
||||
Fresh(Box<Document>),
|
||||
}
|
||||
|
||||
impl Deref for Analysis<'_> {
|
||||
type Target = Document;
|
||||
|
||||
fn deref(&self) -> &Document {
|
||||
match self {
|
||||
Analysis::Open(doc) => doc,
|
||||
Analysis::Fresh(doc) => doc,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The analysis behind an item's URI: the open buffer, else the file on disk.
|
||||
pub(super) fn load<'a>(ws: &'a Workspace, uri: &Uri) -> Option<Analysis<'a>> {
|
||||
match ws.document(uri) {
|
||||
Some(doc) => Some(Analysis::Open(doc)),
|
||||
None => load_path(ws, &uri_to_path(uri)?),
|
||||
}
|
||||
}
|
||||
|
||||
/// The analysis of one path: the open buffer for it, else a fresh analysis
|
||||
/// of the text on disk against the current index.
|
||||
pub(super) fn load_path<'a>(ws: &'a Workspace, path: &Path) -> Option<Analysis<'a>> {
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
return Some(Analysis::Open(doc));
|
||||
}
|
||||
let text = ws.text_of(path)?;
|
||||
Some(Analysis::Fresh(Box::new(Document::new(Some(path.to_path_buf()), text, ws.index()))))
|
||||
}
|
||||
|
||||
/// The analyses one request has loaded, one per path, so a request that
|
||||
/// builds items in one closed file many times — `outgoingCalls` on a function
|
||||
/// calling three hundred functions of one package — parses it once.
|
||||
///
|
||||
/// Lives for one request and no longer: nothing here may outlast a change to
|
||||
/// the text it was built from.
|
||||
pub(super) struct Loaded<'a> {
|
||||
ws: &'a Workspace,
|
||||
held: HashMap<PathBuf, Option<Analysis<'a>>>,
|
||||
}
|
||||
|
||||
impl<'a> Loaded<'a> {
|
||||
pub fn new(ws: &'a Workspace) -> Loaded<'a> {
|
||||
Loaded { ws, held: HashMap::new() }
|
||||
}
|
||||
|
||||
/// The analysis of `path`, loaded on first ask.
|
||||
pub fn get(&mut self, path: &Path) -> Option<&Analysis<'a>> {
|
||||
let ws = self.ws;
|
||||
self.held.entry(path.to_path_buf()).or_insert_with(|| load_path(ws, path)).as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
/// The function or task the cursor names — its declaration, a call, an end
|
||||
/// label — or, failing that, the one whose body encloses the cursor.
|
||||
///
|
||||
/// A call two files could answer returns both declarations, as
|
||||
/// `textDocument/definition` does; the client asks the user which one.
|
||||
pub(super) fn prepare(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
uri: &Uri,
|
||||
offset: u32,
|
||||
) -> Option<Vec<CallHierarchyItem>> {
|
||||
let named = doc
|
||||
.external
|
||||
.definition_of(&doc.semantics, offset)
|
||||
.or_else(|| doc.external.definition_of(&doc.semantics, offset.checked_sub(1)?));
|
||||
let items: Vec<CallHierarchyItem> = match named {
|
||||
Some(Definition::Local(symbol)) if is_tf(symbol.kind) => {
|
||||
item(uri.clone(), doc, symbol).into_iter().collect()
|
||||
}
|
||||
Some(Definition::External(defs)) => {
|
||||
let mut loaded = Loaded::new(ws);
|
||||
defs.iter().filter(|def| is_tf(def.kind)).filter_map(|def| loaded.item(def)).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if !items.is_empty() {
|
||||
return Some(items);
|
||||
}
|
||||
let symbol = enclosing(&doc.semantics, offset)?;
|
||||
Some(vec![item(uri.clone(), doc, doc.semantics.symbol(symbol)?)?])
|
||||
}
|
||||
|
||||
/// The function or task whose body holds `offset`, innermost first.
|
||||
///
|
||||
/// An out-of-body method definition (`function void c::f(); … endfunction`)
|
||||
/// is a scope owned by the prototype's symbol, so its body answers the
|
||||
/// prototype.
|
||||
fn enclosing(semantics: &Semantics, offset: u32) -> Option<SymbolId> {
|
||||
semantics
|
||||
.scopes()
|
||||
.iter()
|
||||
.filter(|scope| matches!(scope.kind, ScopeKind::Function | ScopeKind::Task))
|
||||
.filter(|scope| holds(scope.span, offset))
|
||||
.filter(|scope| {
|
||||
scope.owner.and_then(|id| semantics.symbol(id)).is_some_and(|s| is_tf(s.kind))
|
||||
})
|
||||
.min_by_key(|scope| scope.span.end - scope.span.start)
|
||||
.and_then(|scope| scope.owner)
|
||||
}
|
||||
|
||||
/// The item for a function or task declared in `doc`, reported against `uri`.
|
||||
pub(super) fn item(uri: Uri, doc: &Document, symbol: &Symbol) -> Option<CallHierarchyItem> {
|
||||
let kind = if symbol.kind == Kind::Task { ItemKind::Task } else { ItemKind::Function };
|
||||
let in_class = scope_kind(&doc.semantics, symbol) == Some(ScopeKind::Class);
|
||||
let lsp_kind = if in_class { SymbolKind::METHOD } else { SymbolKind::FUNCTION };
|
||||
built(uri, doc, symbol, kind, lsp_kind)
|
||||
}
|
||||
|
||||
/// The item for a package or class that is a caller.
|
||||
pub(super) fn container_item(
|
||||
uri: Uri,
|
||||
doc: &Document,
|
||||
symbol: &Symbol,
|
||||
) -> Option<CallHierarchyItem> {
|
||||
match symbol.kind {
|
||||
Kind::Package => built(uri, doc, symbol, ItemKind::Package, SymbolKind::PACKAGE),
|
||||
Kind::Class => built(uri, doc, symbol, ItemKind::Class, SymbolKind::CLASS),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An item with [`Data`], framed against `doc`'s text.
|
||||
fn built(
|
||||
uri: Uri,
|
||||
doc: &Document,
|
||||
symbol: &Symbol,
|
||||
kind: ItemKind,
|
||||
lsp_kind: SymbolKind,
|
||||
) -> Option<CallHierarchyItem> {
|
||||
let mut item =
|
||||
super::item_of(uri, &doc.positions(), &symbol.name, symbol.name_span, symbol.decl_span)?;
|
||||
item.kind = lsp_kind;
|
||||
item.detail = container_name(&doc.semantics, symbol);
|
||||
let data = Data { kind, name: symbol.name.clone(), offset: symbol.name_span.start };
|
||||
item.data = Some(data.to_value());
|
||||
Some(item)
|
||||
}
|
||||
|
||||
/// The kind of the scope a declaration is bound in.
|
||||
fn scope_kind(semantics: &Semantics, symbol: &Symbol) -> Option<ScopeKind> {
|
||||
semantics.scope(symbol.scope).map(|scope| scope.kind)
|
||||
}
|
||||
|
||||
/// The name of the module, package or class a function is declared in —
|
||||
/// shown beside the name, so two `log2`s in one list can be told apart.
|
||||
fn container_name(semantics: &Semantics, symbol: &Symbol) -> Option<String> {
|
||||
let owner = semantics.scope(symbol.scope)?.owner?;
|
||||
Some(semantics.symbol(owner)?.name.clone())
|
||||
}
|
||||
|
||||
impl Loaded<'_> {
|
||||
/// The item for a function or task another file declares, re-found in
|
||||
/// that file's live analysis so its ranges are the text's as it is now.
|
||||
pub fn item(&mut self, def: &Def) -> Option<CallHierarchyItem> {
|
||||
let ws = self.ws;
|
||||
let path = ws.index().path(def.file)?;
|
||||
let uri = path_to_uri(path)?;
|
||||
let doc = self.get(path)?;
|
||||
let symbol = live_symbol(ws, doc, def)?;
|
||||
item(uri, doc, doc.semantics.symbol(symbol)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbol in `doc` that is the indexed declaration `def`: by identity —
|
||||
/// asked first of the symbol still at the recorded position, which is the
|
||||
/// answer unless the file moved — and by position as a last resort.
|
||||
fn live_symbol(ws: &Workspace, doc: &Document, def: &Def) -> Option<SymbolId> {
|
||||
let candidates: Vec<SymbolId> = doc
|
||||
.semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, symbol)| symbol.kind == def.kind)
|
||||
.map(|(at, _)| SymbolId(at as u32))
|
||||
.collect();
|
||||
let symbol = |id: &SymbolId| doc.semantics.symbol(*id);
|
||||
let is_def =
|
||||
|id: &&SymbolId| symbol(id).and_then(|s| indexed_def_for_symbol(ws, doc, s)) == Some(def);
|
||||
let at_position = |id: &&SymbolId| symbol(id).is_some_and(|s| s.name_span == def.name_span);
|
||||
let positioned = candidates.iter().find(at_position);
|
||||
positioned.filter(is_def).or_else(|| candidates.iter().find(is_def)).or(positioned).copied()
|
||||
}
|
||||
|
||||
/// The declaration a function or task item stands for, in its file's live
|
||||
/// analysis.
|
||||
///
|
||||
/// The recorded offset wins; an edit since the item was built moves it, and
|
||||
/// then the item's own selection range is tried. Failing both, the name
|
||||
/// decides only when it is unambiguous: the one declaration of that name and
|
||||
/// kind whose container is the item's `detail`.
|
||||
/// Otherwise nothing — two `log2`s in two modules are ordinary, and answering
|
||||
/// for the wrong one would be a confident wrong hierarchy.
|
||||
pub(super) fn target<'a>(
|
||||
ws: &'a Workspace,
|
||||
item: &CallHierarchyItem,
|
||||
data: &Data,
|
||||
) -> Option<(Analysis<'a>, SymbolId)> {
|
||||
let kind = data.kind.semantic()?;
|
||||
let doc = load(ws, &item.uri)?;
|
||||
let candidates: Vec<SymbolId> = doc
|
||||
.semantics
|
||||
.symbols_named(&data.name)
|
||||
.filter(|id| doc.semantics.symbol(*id).is_some_and(|s| s.kind == kind))
|
||||
.collect();
|
||||
let starts_at = |offset: u32| {
|
||||
candidates
|
||||
.iter()
|
||||
.find(|id| doc.semantics.symbol(**id).is_some_and(|s| s.name_span.start == offset))
|
||||
.copied()
|
||||
};
|
||||
let selected = doc.positions().offset(item.selection_range.start);
|
||||
let found = starts_at(data.offset)
|
||||
.or_else(|| starts_at(selected))
|
||||
.or_else(|| by_name(&doc.semantics, &candidates, item.detail.as_deref()))?;
|
||||
Some((doc, found))
|
||||
}
|
||||
|
||||
/// The one candidate a name alone can stand for: the only one declared in
|
||||
/// the container the item's `detail` names (no container for `$unit`).
|
||||
///
|
||||
/// The container is asked even of a lone candidate: when `mb`'s `log2` has
|
||||
/// been renamed away, `ma`'s is the only `log2` left, and it is still not the
|
||||
/// function the item stood for.
|
||||
fn by_name(
|
||||
semantics: &Semantics,
|
||||
candidates: &[SymbolId],
|
||||
detail: Option<&str>,
|
||||
) -> Option<SymbolId> {
|
||||
let mut inside = candidates.iter().filter(|id| {
|
||||
semantics.symbol(**id).is_some_and(|s| container_name(semantics, s).as_deref() == detail)
|
||||
});
|
||||
match (inside.next(), inside.next()) {
|
||||
(Some(one), None) => Some(*one),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `span` holds `offset`, its end included.
|
||||
pub(super) fn holds(span: TextRange, offset: u32) -> bool {
|
||||
span.start <= offset && offset <= span.end
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::str::FromStr;
|
||||
|
||||
use lsp_types::{Position, Range};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn bare(data: Option<Value>) -> CallHierarchyItem {
|
||||
let range = Range::new(Position::new(0, 0), Position::new(0, 1));
|
||||
CallHierarchyItem {
|
||||
name: "f".to_string(),
|
||||
kind: SymbolKind::FUNCTION,
|
||||
tags: None,
|
||||
detail: None,
|
||||
uri: Uri::from_str("file:///x.sv").expect("uri"),
|
||||
range,
|
||||
selection_range: range,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_round_trips_through_its_json() {
|
||||
for kind in [ItemKind::Function, ItemKind::Task, ItemKind::Package, ItemKind::Class] {
|
||||
let data = Data { kind, name: "f".to_string(), offset: 42 };
|
||||
assert_eq!(Data::of(&bare(Some(data.to_value()))), Some(data));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_item_and_foreign_data_carry_no_data_of_ours() {
|
||||
assert_eq!(Data::of(&bare(None)), None, "a module item");
|
||||
for foreign in [
|
||||
json!({ "kind": "rocket", "name": "f", "offset": 1 }),
|
||||
json!({ "kind": "function", "name": "f" }),
|
||||
json!({ "kind": "function", "name": 7, "offset": 1 }),
|
||||
json!({ "kind": "function", "name": "f", "offset": -1 }),
|
||||
json!({ "kind": "function", "name": "f", "offset": 5_000_000_000u64 }),
|
||||
json!("function"),
|
||||
] {
|
||||
assert_eq!(Data::of(&bare(Some(foreign.clone()))), None, "{foreign}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_innermost_function_or_task_encloses_an_offset() {
|
||||
let text = "module m;\n task t;\n begin\n x = 1;\n end\n endtask\n \
|
||||
wire w;\nendmodule\n";
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let name = |offset| {
|
||||
enclosing(&semantics, offset)
|
||||
.and_then(|id| semantics.symbol(id))
|
||||
.map(|s| s.name.clone())
|
||||
};
|
||||
let at = |needle: &str| text.find(needle).expect("needle") as u32;
|
||||
assert_eq!(name(at("x = 1")).as_deref(), Some("t"), "through a nested block");
|
||||
assert_eq!(name(at("endtask") + 7).as_deref(), Some("t"), "the end included");
|
||||
assert_eq!(name(at("wire")), None, "a module item is in no task");
|
||||
}
|
||||
}
|
||||
@@ -27,16 +27,19 @@
|
||||
//! because the editor prepends that line's own indentation when it inserts the
|
||||
//! snippet; see `render`. See `docs/features/inline-templates/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, Uri};
|
||||
use lsp_types::{Position, Range, SelectedCompletionInfo, Uri};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::{Layout, Site};
|
||||
|
||||
use crate::completion;
|
||||
use crate::on_type;
|
||||
use crate::pairs;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::templates::{self, Dialect};
|
||||
|
||||
mod keywords;
|
||||
|
||||
/// One line of a body: how many indent steps it sits in, and its text. The
|
||||
/// same shape `templates.rs` writes its skeletons in.
|
||||
type Line = (u8, &'static str);
|
||||
@@ -96,6 +99,13 @@ const BEGIN_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "end")];
|
||||
const FORK_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "join")];
|
||||
const GENERATE_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "endgenerate")];
|
||||
|
||||
/// The event control of a flop with an async active-low reset, both edges a
|
||||
/// tabstop. First in both `always` families (TODO §68.1): the commoner flop.
|
||||
const CLOCK_AND_RESET: &[Line] =
|
||||
&[(0, "posedge ${1:clk} or negedge ${2:rst_n}) begin"), (1, "$0"), (0, "end")];
|
||||
/// The clock-only event control, one cycle away.
|
||||
const CLOCK_ONLY: &[Line] = &[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")];
|
||||
|
||||
/// Every construct that offers ghost text.
|
||||
///
|
||||
/// The order is the order `triggered` tries them, which only matters when two
|
||||
@@ -156,19 +166,16 @@ const TRIGGERS: &[Trigger] = &[
|
||||
opener: EVENT,
|
||||
dialect: Some(Dialect::SystemVerilog),
|
||||
gate: Unclosed::Paren,
|
||||
bodies: &[&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")]],
|
||||
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY],
|
||||
},
|
||||
Trigger {
|
||||
keyword: "always",
|
||||
opener: EVENT,
|
||||
dialect: None,
|
||||
gate: Unclosed::Paren,
|
||||
// Two items, clocked first: `always @(` is overwhelmingly a flop, and
|
||||
// the client cycles to the second with one keystroke.
|
||||
bodies: &[
|
||||
&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
&[(0, "*) begin"), (1, "$0"), (0, "end")],
|
||||
],
|
||||
// Three items, clocked first: `always @(` is overwhelmingly a flop,
|
||||
// and the client cycles to the next with one keystroke.
|
||||
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY, &[(0, "*) begin"), (1, "$0"), (0, "end")]],
|
||||
},
|
||||
Trigger {
|
||||
keyword: "begin",
|
||||
@@ -237,7 +244,15 @@ pub struct InlineItems {
|
||||
/// `None` rather than an empty list wherever there is nothing to say: an
|
||||
/// editor treats both the same, and `null` is the cheaper answer to a request
|
||||
/// that arrives on every keystroke.
|
||||
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
|
||||
///
|
||||
/// `selected` is the request's `context.selectedCompletionInfo` — the popup's
|
||||
/// selected entry, when one is showing. Only the keyword ghost reads it.
|
||||
pub fn inline_completions_in_context(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
selected: Option<&SelectedCompletionInfo>,
|
||||
) -> Option<InlineItems> {
|
||||
let doc = ws.document(uri)?;
|
||||
// No token stream, no answer — the same trade `completion.rs` makes. A
|
||||
// half-typed string or block comment is what breaks the lexer, and those
|
||||
@@ -260,14 +275,24 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
|
||||
return instantiation(ws, doc, name, at);
|
||||
}
|
||||
let last = last_token(doc, offset)?;
|
||||
match doc.tokens.get(last)?.kind {
|
||||
// A name with nothing after it is not an offer (owner ruling,
|
||||
// 2026-08-30): `aes` may still be growing into `aes_dft`, and the
|
||||
// space is the user saying that it is not. No trigger's own last token
|
||||
// is an `Ident` either, so nothing is lost by stopping here.
|
||||
TokenKind::Ident => None,
|
||||
_ => template(ws, doc, last, at),
|
||||
// A name with nothing after it is not an instantiation offer (owner
|
||||
// ruling, 2026-08-30): `aes` may still be growing into `aes_dft`, and the
|
||||
// space is the user saying that it is not. No trigger's own last token is
|
||||
// an `Ident` either, so only the keyword ghost is asked about one.
|
||||
if doc.tokens.get(last)?.kind != TokenKind::Ident {
|
||||
if let Some(items) = template(ws, doc, last, at) {
|
||||
return Some(items);
|
||||
}
|
||||
}
|
||||
// The fallback: the rest of a keyword the word is a proper prefix of.
|
||||
keywords::keyword_ghost(ws, doc, last, position, selected)
|
||||
}
|
||||
|
||||
/// [`inline_completions_in_context`] with no popup open — what every test
|
||||
/// that is not about the popup asks.
|
||||
#[cfg(test)]
|
||||
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
|
||||
inline_completions_in_context(ws, uri, position, None)
|
||||
}
|
||||
|
||||
/// The identifier the user has just finished and armed with a space: the token
|
||||
@@ -299,7 +324,7 @@ fn template(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<In
|
||||
return None;
|
||||
}
|
||||
let (trigger, opened) = triggered(doc, last)?;
|
||||
if !unfinished(doc, trigger, opened) {
|
||||
if !unfinished(doc, trigger, opened, last) {
|
||||
return None;
|
||||
}
|
||||
Some(InlineItems {
|
||||
@@ -487,13 +512,20 @@ fn triggered(doc: &Document, index: usize) -> Option<(&'static Trigger, Opened)>
|
||||
}
|
||||
|
||||
/// Whether the construct the user opened really is still waiting to be closed.
|
||||
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened) -> bool {
|
||||
///
|
||||
/// `last` is the index of the token just typed — for `begin`, the keyword
|
||||
/// itself, which is asked the auto-`end` question (`on_type::auto_end`)
|
||||
/// rather than "is this span unmatched": a `begin` typed inside a balanced
|
||||
/// block steals that block's `end` in the stack matcher, and would otherwise
|
||||
/// get no ghost (`completion-ux` fix round, 2026-11-17).
|
||||
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened, last: usize) -> bool {
|
||||
let paren = || !paren_is_closed(&doc.tokens, opened.last);
|
||||
let scope = || {
|
||||
pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened.keyword)
|
||||
};
|
||||
match trigger.gate {
|
||||
Unclosed::Paren => paren(),
|
||||
Unclosed::Scope if trigger.keyword == "begin" => on_type::begin_owes_an_end(doc, last),
|
||||
Unclosed::Scope => scope(),
|
||||
// The paren check first: it is a flat pass over the tokens, and
|
||||
// skipping `pairs::analyze` when it already says no is what keeps this
|
||||
@@ -822,15 +854,16 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_at_offers_the_clocked_block_first_and_the_star_second() {
|
||||
fn an_always_at_offers_clock_and_reset_first_then_clock_only_then_the_star() {
|
||||
let text = "module top;\n always @(\nendmodule\n";
|
||||
assert_eq!(
|
||||
all_offered(text, "always @("),
|
||||
vec![
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend".to_string(),
|
||||
"posedge ${1:clk}) begin\n\t$0\nend".to_string(),
|
||||
"*) begin\n\t$0\nend".to_string(),
|
||||
],
|
||||
"clocked first: `always @(` is overwhelmingly a flop"
|
||||
"clocked first: `always @(` is overwhelmingly a flop, and most flops reset"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -839,7 +872,10 @@ endmodule
|
||||
let text = "module top;\n always_ff @(\nendmodule\n";
|
||||
assert_eq!(
|
||||
offered_in("/rtl/top.sv", text, "always_ff @("),
|
||||
vec!["posedge ${1:clk}) begin\n\t$0\nend"]
|
||||
vec![
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend",
|
||||
"posedge ${1:clk}) begin\n\t$0\nend"
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
offered_in("/rtl/top.v", text, "always_ff @(").is_empty(),
|
||||
@@ -930,6 +966,15 @@ endmodule
|
||||
assert!(offered(text, "initial begin").is_some(), "this one lost its end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_typed_inside_a_balanced_block_still_offers_its_end() {
|
||||
// The new `begin` steals the `always_comb` block's `end` in the stack
|
||||
// matcher; the gate asks the auto-`end` question instead
|
||||
// (`completion-ux` fix round, 2026-11-17).
|
||||
let text = "module top;\n always_comb begin\n if (x) begin\n end\nendmodule\n";
|
||||
assert_eq!(offered(text, "if (x) begin").as_deref(), Some("\n\t$0\nend"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_keyword_that_already_has_its_closer_offers_nothing() {
|
||||
// The same rule as `begin`, for the three keywords that joined it.
|
||||
@@ -1019,8 +1064,10 @@ endmodule
|
||||
fn an_always_without_its_event_control_offers_nothing() {
|
||||
// The opener is a *sequence*: both `@` and `(` must be there, in that
|
||||
// order, or the user has not committed to an event-controlled block.
|
||||
// A bare `always` grows no block — only the keyword ghost's `_ff`,
|
||||
// which is a different feature with its own setting.
|
||||
let text = "module top;\n always\nendmodule\n";
|
||||
assert_eq!(offered(text, " always"), None);
|
||||
assert_eq!(offered(text, " always").as_deref(), Some("_ff"));
|
||||
let text = "module top;\n always @\nendmodule\n";
|
||||
assert_eq!(offered(text, "always @"), None);
|
||||
let text = "module top;\n always (\nendmodule\n";
|
||||
@@ -1140,7 +1187,7 @@ endmodule
|
||||
assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
|
||||
// ...and the same for a two-symbol opener written tight.
|
||||
let text = "module top;\n always@(\nendmodule\n";
|
||||
assert_eq!(all_offered(text, "always@(").len(), 2);
|
||||
assert_eq!(all_offered(text, "always@(").len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1532,7 +1579,7 @@ endmodule
|
||||
// `no_space_between_the_keyword_and_the_paren_still_triggers`, this
|
||||
// pins the opposite spacing.
|
||||
let text = "module top;\n always @ (\nendmodule\n";
|
||||
assert_eq!(all_offered(text, "always @ (").len(), 2);
|
||||
assert_eq!(all_offered(text, "always @ (").len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1588,7 +1635,7 @@ endmodule
|
||||
// counterpart — both must still offer.
|
||||
let text = "module top;\n if (\n always @(\nendmodule\n";
|
||||
assert!(offered(text, " if (").is_some());
|
||||
assert_eq!(all_offered(text, " always @(").len(), 2);
|
||||
assert_eq!(all_offered(text, " always @(").len(), 3);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1629,6 +1676,16 @@ endmodule
|
||||
serde_json::to_value(&items).expect("serializes"),
|
||||
serde_json::json!({
|
||||
"items": [
|
||||
{
|
||||
"insertText": {
|
||||
"kind": "snippet",
|
||||
"value": "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
|
||||
},
|
||||
"range": {
|
||||
"start": { "line": 1, "character": 11 },
|
||||
"end": { "line": 1, "character": 11 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"insertText": {
|
||||
"kind": "snippet",
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
//! Keyword ghosts (TODO §68.1): a typed proper prefix of a keyword shows the
|
||||
//! rest of it as grey text — `alw` grows `ays_ff`, Tab accepts.
|
||||
//!
|
||||
//! The fallback ghost: asked only where no template trigger answered, and
|
||||
//! only for an identifier-like word of two characters or more that ends
|
||||
//! exactly at the cursor. Three rules decide which keyword, in order:
|
||||
//!
|
||||
//! 1. **The popup's choice.** While VS Code's suggest widget is open it shows
|
||||
//! an inline item only if it extends the selected entry over the selected
|
||||
//! entry's range (LSP 3.18 `selectedCompletionInfo`). So with a selection,
|
||||
//! the ghost is exactly that keyword when it is one, and nothing otherwise.
|
||||
//! 2. **A fixed priority list** of the words an RTL designer types all day.
|
||||
//! 3. **Shortest, then alphabetical**, over every keyword of the buffer's
|
||||
//! dialect.
|
||||
//!
|
||||
//! A word that is already a keyword is only extended across an underscore:
|
||||
//! `always` grows `_ff`, but `for` stays `for` and `end` stays `end` — the
|
||||
//! keystroke after a finished keyword is a space or a newline far more often
|
||||
//! than another letter, and a ghost there is noise a stray Tab accepts.
|
||||
//! See `docs/features/completion-ux/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, SelectedCompletionInfo};
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
|
||||
use super::{InlineItem, InlineItems, SnippetValue};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::templates::{self, Dialect};
|
||||
|
||||
/// The shortest word worth a ghost. One letter is a prefix of half the
|
||||
/// keyword list, and the ghost would change on every keystroke.
|
||||
const MIN_WORD: usize = 2;
|
||||
|
||||
/// The keywords tried first, in this order, whenever more than one extends
|
||||
/// the typed word. Everything else falls back to shortest-then-alphabetical.
|
||||
const PRIORITY: &[&str] = &[
|
||||
"always_ff",
|
||||
"always_comb",
|
||||
"always",
|
||||
"assign",
|
||||
"begin",
|
||||
"logic",
|
||||
"input",
|
||||
"output",
|
||||
"inout",
|
||||
"module",
|
||||
"endmodule",
|
||||
"parameter",
|
||||
"localparam",
|
||||
"function",
|
||||
"endfunction",
|
||||
"task",
|
||||
"endtask",
|
||||
"generate",
|
||||
"endgenerate",
|
||||
"genvar",
|
||||
"case",
|
||||
"endcase",
|
||||
"default",
|
||||
"initial",
|
||||
"integer",
|
||||
"posedge",
|
||||
"negedge",
|
||||
"typedef",
|
||||
"struct",
|
||||
"enum",
|
||||
"package",
|
||||
"endpackage",
|
||||
"interface",
|
||||
"endinterface",
|
||||
"foreach",
|
||||
"forever",
|
||||
"return",
|
||||
"automatic",
|
||||
"unique",
|
||||
"wire",
|
||||
"reg",
|
||||
];
|
||||
|
||||
/// The IEEE 1364-2005 reserved words: what a `.v` buffer may be offered. The
|
||||
/// lexer's list is one list for both dialects, and `logic` grown in a file a
|
||||
/// Verilog compiler reads is a ghost that hands the user an error.
|
||||
const VERILOG: &[&str] = &[
|
||||
"always",
|
||||
"and",
|
||||
"assign",
|
||||
"automatic",
|
||||
"begin",
|
||||
"buf",
|
||||
"bufif0",
|
||||
"bufif1",
|
||||
"case",
|
||||
"casex",
|
||||
"casez",
|
||||
"cell",
|
||||
"cmos",
|
||||
"config",
|
||||
"deassign",
|
||||
"default",
|
||||
"defparam",
|
||||
"design",
|
||||
"disable",
|
||||
"edge",
|
||||
"else",
|
||||
"end",
|
||||
"endcase",
|
||||
"endconfig",
|
||||
"endfunction",
|
||||
"endgenerate",
|
||||
"endmodule",
|
||||
"endprimitive",
|
||||
"endspecify",
|
||||
"endtable",
|
||||
"endtask",
|
||||
"event",
|
||||
"for",
|
||||
"force",
|
||||
"forever",
|
||||
"fork",
|
||||
"function",
|
||||
"generate",
|
||||
"genvar",
|
||||
"highz0",
|
||||
"highz1",
|
||||
"if",
|
||||
"ifnone",
|
||||
"incdir",
|
||||
"include",
|
||||
"initial",
|
||||
"inout",
|
||||
"input",
|
||||
"instance",
|
||||
"integer",
|
||||
"join",
|
||||
"large",
|
||||
"liblist",
|
||||
"library",
|
||||
"localparam",
|
||||
"macromodule",
|
||||
"medium",
|
||||
"module",
|
||||
"nand",
|
||||
"negedge",
|
||||
"nmos",
|
||||
"nor",
|
||||
"noshowcancelled",
|
||||
"not",
|
||||
"notif0",
|
||||
"notif1",
|
||||
"or",
|
||||
"output",
|
||||
"parameter",
|
||||
"pmos",
|
||||
"posedge",
|
||||
"primitive",
|
||||
"pull0",
|
||||
"pull1",
|
||||
"pulldown",
|
||||
"pullup",
|
||||
"pulsestyle_ondetect",
|
||||
"pulsestyle_onevent",
|
||||
"rcmos",
|
||||
"real",
|
||||
"realtime",
|
||||
"reg",
|
||||
"release",
|
||||
"repeat",
|
||||
"rnmos",
|
||||
"rpmos",
|
||||
"rtran",
|
||||
"rtranif0",
|
||||
"rtranif1",
|
||||
"scalared",
|
||||
"showcancelled",
|
||||
"signed",
|
||||
"small",
|
||||
"specify",
|
||||
"specparam",
|
||||
"strong0",
|
||||
"strong1",
|
||||
"supply0",
|
||||
"supply1",
|
||||
"table",
|
||||
"task",
|
||||
"time",
|
||||
"tran",
|
||||
"tranif0",
|
||||
"tranif1",
|
||||
"tri",
|
||||
"tri0",
|
||||
"tri1",
|
||||
"triand",
|
||||
"trior",
|
||||
"trireg",
|
||||
"unsigned",
|
||||
"use",
|
||||
"uwire",
|
||||
"vectored",
|
||||
"wait",
|
||||
"wand",
|
||||
"weak0",
|
||||
"weak1",
|
||||
"while",
|
||||
"wire",
|
||||
"wor",
|
||||
"xnor",
|
||||
"xor",
|
||||
];
|
||||
|
||||
/// The keyword ghost for the word ending at `position`, or `None`.
|
||||
///
|
||||
/// `last` is the index of the token ending exactly at the cursor — the
|
||||
/// caller's `last_token` — and `selected` the popup's selected entry, when
|
||||
/// the client said one is showing.
|
||||
pub(super) fn keyword_ghost(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
last: usize,
|
||||
position: Position,
|
||||
selected: Option<&SelectedCompletionInfo>,
|
||||
) -> Option<InlineItems> {
|
||||
if !ws.client_settings().inline_keywords.unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
let (word, start) = typed_word(doc, last)?;
|
||||
// A name this buffer declares is what the user is typing, not the front
|
||||
// of a keyword: `in`, `re`, `out` as signals stay quiet (fix round).
|
||||
if doc.semantics.symbols().iter().any(|symbol| symbol.name == word) {
|
||||
return None;
|
||||
}
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
// A selection that does not cover exactly the typed word is about some
|
||||
// other text, and is read as no selection at all — never echoed back.
|
||||
let word_range = Range { start: doc.positions().position(start), end: position };
|
||||
let selected = selected.filter(|info| info.range == word_range);
|
||||
let (keyword, range) = match selected {
|
||||
// An explicit selection wins over the finished-keyword rule: `end`
|
||||
// with `endmodule` selected ghosts `endmodule`.
|
||||
Some(info) => {
|
||||
let text = info.text.as_str();
|
||||
(reserved_extension(word, text, dialect).then_some(text)?, info.range)
|
||||
}
|
||||
None => (best_keyword(word, dialect)?, Range { start: position, end: position }),
|
||||
};
|
||||
// Without a selection the item inserts at the cursor, as every other
|
||||
// ghost here does; with one it must replace the selection's range with
|
||||
// the whole word, which is the shape the client compares against.
|
||||
let value = match selected {
|
||||
Some(_) => keyword.to_string(),
|
||||
None => keyword[word.len()..].to_string(),
|
||||
};
|
||||
Some(InlineItems {
|
||||
items: vec![InlineItem { insert_text: SnippetValue { kind: "snippet", value }, range }],
|
||||
})
|
||||
}
|
||||
|
||||
/// The word a keyword ghost may extend: the token at `last` when it is a
|
||||
/// plain identifier or a keyword, at least [`MIN_WORD`] long, spelled with
|
||||
/// identifier characters only, and not a member name after a `.` or `::`.
|
||||
///
|
||||
/// A macro use (`` `alw ``), an escaped identifier and a `$system` name all
|
||||
/// fail the character test or the kind test; a comment and a string never
|
||||
/// produce a token ending at the cursor at all.
|
||||
fn typed_word(doc: &Document, last: usize) -> Option<(&str, u32)> {
|
||||
let token = doc.tokens.get(last)?;
|
||||
if !matches!(token.kind, TokenKind::Ident | TokenKind::Keyword) {
|
||||
return None;
|
||||
}
|
||||
let text = token.text.as_str();
|
||||
let plain = text.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
|
||||
&& text.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
if !plain || text.len() < MIN_WORD {
|
||||
return None;
|
||||
}
|
||||
let after_separator = last
|
||||
.checked_sub(1)
|
||||
.and_then(|i| doc.tokens.get(i))
|
||||
.is_some_and(|prev| prev.is_sym(".") || prev.is_sym("::") || prev.is_sym("`"));
|
||||
(!after_separator).then_some((text, token.span.start))
|
||||
}
|
||||
|
||||
/// The keyword to ghost behind `word` with no popup selection to follow.
|
||||
fn best_keyword(word: &str, dialect: Dialect) -> Option<&'static str> {
|
||||
if let Some(first) = PRIORITY.iter().copied().find(|kw| extends(word, kw, dialect)) {
|
||||
return Some(first);
|
||||
}
|
||||
KEYWORDS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|kw| extends(word, kw, dialect))
|
||||
.min_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)))
|
||||
}
|
||||
|
||||
/// Whether `keyword` is a reserved word of `dialect` that properly extends
|
||||
/// `word` — across an underscore only, when `word` is already a keyword.
|
||||
fn extends(word: &str, keyword: &str, dialect: Dialect) -> bool {
|
||||
reserved_extension(word, keyword, dialect)
|
||||
&& (!KEYWORDS.contains(&word) || keyword.as_bytes()[word.len()] == b'_')
|
||||
}
|
||||
|
||||
/// Whether `keyword` is a reserved word of `dialect` that properly extends
|
||||
/// `word` — the whole test for a keyword the popup has selected.
|
||||
fn reserved_extension(word: &str, keyword: &str, dialect: Dialect) -> bool {
|
||||
keyword.len() > word.len()
|
||||
&& keyword.starts_with(word)
|
||||
&& KEYWORDS.contains(&keyword)
|
||||
&& (dialect == Dialect::SystemVerilog || VERILOG.contains(&keyword))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::inline::inline_completions_in_context;
|
||||
use crate::settings::ClientSettings;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// The ghosts at the end of `needle` in `text`, opened as `/rtl/top.sv`,
|
||||
/// as `(value, range)` pairs.
|
||||
fn ghosts(
|
||||
text: &str,
|
||||
needle: &str,
|
||||
selected: Option<SelectedCompletionInfo>,
|
||||
settings: ClientSettings,
|
||||
) -> Vec<(String, Range)> {
|
||||
let uri = Uri::from_str("file:///rtl/top.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(settings);
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let offset = (text.find(needle).expect("needle") + needle.len()) as u32;
|
||||
let position = doc.positions().position(offset);
|
||||
inline_completions_in_context(&ws, &uri, position, selected.as_ref())
|
||||
.map(|found| {
|
||||
found.items.into_iter().map(|item| (item.insert_text.value, item.range)).collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn plain(text: &str, needle: &str) -> Vec<String> {
|
||||
ghosts(text, needle, None, ClientSettings::default())
|
||||
.into_iter()
|
||||
.map(|(value, _)| value)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn at(line: u32, character: u32) -> Position {
|
||||
Position { line, character }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keyword_prefix_grows_the_rest_of_the_keyword_at_the_cursor() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let found = ghosts(text, " alw", None, ClientSettings::default());
|
||||
let cursor = at(1, 5);
|
||||
assert_eq!(found, vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })]);
|
||||
assert_eq!(
|
||||
plain("module top;\n logic a;\n assign a = 1;\n endm\n", " endm"),
|
||||
["odule"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_popups_selection_is_followed_over_its_own_range() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let range = Range { start: at(1, 2), end: at(1, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
|
||||
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
|
||||
assert_eq!(found, vec![("always_comb".to_string(), range)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_is_not_a_keyword_extension_silences_the_ghost() {
|
||||
let text = "module top;\n logic alw_q;\n alw\nendmodule\n";
|
||||
let range = Range { start: at(2, 2), end: at(2, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "alw_q".to_string() };
|
||||
assert!(ghosts(text, "\n alw", Some(selected), ClientSettings::default()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ghost_after_a_separator_in_a_comment_or_for_one_letter() {
|
||||
assert!(plain("module top;\n assign x = s.al\nendmodule\n", "s.al").is_empty());
|
||||
assert!(plain("module top;\n import p::al\nendmodule\n", "p::al").is_empty());
|
||||
assert!(plain("module top;\n // alw\nendmodule\n", "// alw").is_empty());
|
||||
assert!(plain("module top;\n a\nendmodule\n", " a").is_empty());
|
||||
assert!(plain("module top;\n `alw\nendmodule\n", "`alw").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ghost_when_the_rest_of_the_line_is_written() {
|
||||
assert!(plain("module top;\n alw x;\nendmodule\n", " alw").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setting_turns_keyword_ghosts_off_and_leaves_templates_on() {
|
||||
let off = ClientSettings { inline_keywords: Some(false), ..Default::default() };
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
assert!(ghosts(text, " alw", None, off.clone()).is_empty());
|
||||
let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n";
|
||||
assert_eq!(ghosts(text, "if (", None, off).len(), 1, "the template ghost is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_trigger_wins_over_the_keyword_ghost() {
|
||||
// `begin` is a finished keyword and a trigger: its ghost is the block.
|
||||
let text = "module top;\n initial begin\nendmodule\n";
|
||||
assert_eq!(plain(text, "initial begin"), ["\n\t$0\nend"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_priority_list_picks_among_several_extensions() {
|
||||
let sv = Dialect::SystemVerilog;
|
||||
assert_eq!(best_keyword("al", sv), Some("always_ff"));
|
||||
assert_eq!(best_keyword("always_c", sv), Some("always_comb"));
|
||||
assert_eq!(best_keyword("as", sv), Some("assign"));
|
||||
assert_eq!(best_keyword("lo", sv), Some("logic"));
|
||||
assert_eq!(best_keyword("endm", sv), Some("endmodule"));
|
||||
assert_eq!(best_keyword("par", sv), Some("parameter"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_the_list_the_shortest_then_alphabetical_keyword_wins() {
|
||||
assert_eq!(best_keyword("tr", Dialect::SystemVerilog), Some("tri"), "tri before tran");
|
||||
assert_eq!(best_keyword("tri", Dialect::SystemVerilog), None, "`tri` is finished");
|
||||
assert_eq!(best_keyword("xn", Dialect::SystemVerilog), Some("xnor"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_keyword_only_grows_across_an_underscore() {
|
||||
let sv = Dialect::SystemVerilog;
|
||||
assert_eq!(best_keyword("always", sv), Some("always_ff"));
|
||||
assert_eq!(best_keyword("end", sv), None, "`end` is finished");
|
||||
assert_eq!(best_keyword("for", sv), None, "`for` is finished");
|
||||
assert_eq!(best_keyword("case", sv), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verilog_buffer_is_only_offered_verilog_words() {
|
||||
let v = Dialect::Verilog;
|
||||
assert_eq!(best_keyword("al", v), Some("always"));
|
||||
assert_eq!(best_keyword("lo", v), Some("localparam"), "no `logic` in a .v file");
|
||||
assert_eq!(best_keyword("always", v), None, "no `always_ff` either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_listed_word_is_a_reserved_word_the_lexer_knows() {
|
||||
for word in PRIORITY {
|
||||
assert!(KEYWORDS.contains(word), "{word}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA (2026-11-17): the shape an unbridged client sends — VS Code's
|
||||
/// `Range` serialized by its `toJSON` as `[start, end]`, trigger kind 0 —
|
||||
/// still decodes (serde reads a struct from a sequence), so the
|
||||
/// extension's middleware is a spelling fix, not what keeps the request
|
||||
/// alive.
|
||||
#[test]
|
||||
fn qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode() {
|
||||
let params: lsp_types::InlineCompletionParams = serde_json::from_value(serde_json::json!({
|
||||
"textDocument": { "uri": "file:///rtl/top.sv" },
|
||||
"position": { "line": 1, "character": 5 },
|
||||
"context": {
|
||||
"triggerKind": 0,
|
||||
"selectedCompletionInfo": {
|
||||
"range": [{ "line": 1, "character": 2 }, { "line": 1, "character": 5 }],
|
||||
"text": "always_comb"
|
||||
}
|
||||
}
|
||||
}))
|
||||
.expect("decodes");
|
||||
let selected = params.context.selected_completion_info.expect("kept");
|
||||
assert_eq!(selected.range, Range { start: at(1, 2), end: at(1, 5) });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_extends_a_word_that_is_no_keyword_prefix() {
|
||||
assert_eq!(best_keyword("clk", Dialect::SystemVerilog), None);
|
||||
assert!(extends("al", "always", Dialect::SystemVerilog));
|
||||
assert!(!extends("Al", "always", Dialect::SystemVerilog), "case matters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_this_buffer_declares_grows_no_keyword() {
|
||||
let text = "module top;\n logic re, in;\n assign x = re\nendmodule\n";
|
||||
assert!(plain(text, "= re").is_empty(), "`re` is a signal here, not `return`");
|
||||
// An undeclared word still ghosts, expression position or not.
|
||||
let text = "module top;\n assign x = ou\nendmodule\n";
|
||||
assert_eq!(plain(text, "= ou"), ["tput"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_selection_wins_over_the_finished_keyword_rule() {
|
||||
let text = "module top;\n logic a;\n end\nendmodule\n";
|
||||
assert!(plain(text, "\n end").is_empty(), "no popup: `end` is finished");
|
||||
let range = Range { start: at(2, 2), end: at(2, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "endmodule".to_string() };
|
||||
let found = ghosts(text, "\n end", Some(selected), ClientSettings::default());
|
||||
assert_eq!(found, vec![("endmodule".to_string(), range)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_over_some_other_range_is_read_as_no_selection() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let cursor = at(1, 5);
|
||||
for range in [
|
||||
Range { start: at(1, 2), end: at(1, 4) },
|
||||
Range { start: at(1, 3), end: cursor },
|
||||
Range { start: at(0, 0), end: at(0, 6) },
|
||||
] {
|
||||
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
|
||||
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
|
||||
assert_eq!(
|
||||
found,
|
||||
vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })],
|
||||
"{range:?} is never echoed back"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
// capabilities have no field for it and drop it on the floor — see
|
||||
// `ranges_formatting_support`.
|
||||
let ranges_formatting = ranges_formatting_support(¶ms);
|
||||
let diagnostic_refresh = diagnostic_refresh_support(¶ms);
|
||||
// Read from the raw params for the same reason, and because it is not a
|
||||
// capability at all: `initializationOptions` is whatever the client's
|
||||
// extension put there.
|
||||
@@ -133,6 +134,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
pull_diagnostics: pull_diagnostics_support(¶ms),
|
||||
work_done_progress: work_done_progress_support(¶ms),
|
||||
code_lens_refresh: code_lens_refresh_support(¶ms),
|
||||
diagnostic_refresh,
|
||||
show_document: show_document_support(¶ms),
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
@@ -645,6 +647,21 @@ fn code_lens_refresh_support(params: &InitializeParams) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client can be asked to pull its diagnostics again
|
||||
/// (`workspace/diagnostic/refresh`), read from the **raw** `initialize`
|
||||
/// params.
|
||||
///
|
||||
/// Server-initiated, so the spec makes this capability the gate, exactly as
|
||||
/// for the code-lens refresh. It has to be the raw JSON: the protocol's key is
|
||||
/// `workspace.diagnostics`, and `lsp-types` 0.97 spells its field
|
||||
/// `diagnostic` with no rename, so the typed decode never sees what VS Code
|
||||
/// sends. Anything but a literal `true` means no. Sent when a connection entry
|
||||
/// held back while it was typed is released
|
||||
/// (`docs/features/port-entry-grace/README.md`).
|
||||
fn diagnostic_refresh_support(params: &serde_json::Value) -> bool {
|
||||
params["capabilities"]["workspace"]["diagnostics"]["refreshSupport"] == true
|
||||
}
|
||||
|
||||
/// Whether the client opens a document the server asks it to.
|
||||
///
|
||||
/// This is what makes the instantiation lens actually navigate: an
|
||||
@@ -1352,6 +1369,28 @@ mod tests {
|
||||
assert!(!code_lens_refresh_support(&saying(None)), "an empty `codeLens` is not a yes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_refresh_support_is_read_from_the_raw_params_and_only_when_literally_true() {
|
||||
let saying = |refresh: serde_json::Value| {
|
||||
serde_json::json!({
|
||||
"processId": null,
|
||||
"capabilities": { "workspace": { "diagnostics": { "refreshSupport": refresh } } }
|
||||
})
|
||||
};
|
||||
assert!(diagnostic_refresh_support(&saying(serde_json::json!(true))));
|
||||
assert!(!diagnostic_refresh_support(&saying(serde_json::json!(false))));
|
||||
assert!(!diagnostic_refresh_support(&saying(serde_json::json!("yes"))));
|
||||
assert!(!diagnostic_refresh_support(&saying(serde_json::Value::Null)));
|
||||
assert!(!diagnostic_refresh_support(&serde_json::json!({ "capabilities": {} })));
|
||||
assert!(!diagnostic_refresh_support(&serde_json::Value::Null));
|
||||
// The protocol's key is plural; `lsp-types`' singular field name is
|
||||
// not what any client sends, and is not read.
|
||||
let singular = serde_json::json!({
|
||||
"capabilities": { "workspace": { "diagnostic": { "refreshSupport": true } } }
|
||||
});
|
||||
assert!(!diagnostic_refresh_support(&singular));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_document_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
|
||||
@@ -170,16 +170,10 @@ fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool {
|
||||
}
|
||||
// A member is reachable as `unit::name`, as `.name` in a connection list
|
||||
// or as the tail of a hierarchical path, so the unit that owns the
|
||||
// declaring scope is what to ask about.
|
||||
let owner = doc
|
||||
.semantics
|
||||
.scope(symbol.scope)
|
||||
.and_then(|scope| scope.owner)
|
||||
.and_then(|owner| doc.semantics.symbol(owner));
|
||||
match owner {
|
||||
Some(owner) => {
|
||||
!ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical).is_empty()
|
||||
}
|
||||
// declaring scope is what to ask about — under the key the index files
|
||||
// it by, which for a named block is `module.label`.
|
||||
match doc.semantics.member_key(symbol.scope) {
|
||||
Some(key) => !ws.index().member_in(&key, &symbol.name, Surface::Hierarchical).is_empty(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
@@ -262,11 +256,8 @@ fn indexed_def_in_file<'a>(
|
||||
let defs = if symbol.scope == semantics.file_scope() {
|
||||
ws.index().units(&symbol.name)
|
||||
} else {
|
||||
let owner = semantics
|
||||
.scope(symbol.scope)
|
||||
.and_then(|scope| scope.owner)
|
||||
.and_then(|owner| semantics.symbol(owner))?;
|
||||
ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical)
|
||||
let key = semantics.member_key(symbol.scope)?;
|
||||
ws.index().member_in(&key, &symbol.name, Surface::Hierarchical)
|
||||
};
|
||||
if defs.len() != 1 {
|
||||
return None;
|
||||
@@ -1510,8 +1501,8 @@ endmodule
|
||||
);
|
||||
assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "and the module is a unit");
|
||||
assert!(
|
||||
!leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5),
|
||||
"but a generate-block-scoped net is on neither surface"
|
||||
leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5),
|
||||
"and since TODO §65.1 so is a generate-block-scoped net, under `m.g`: `u_m.g.gen_only`"
|
||||
);
|
||||
assert!(
|
||||
!leaves_this_file(&ws, doc, at(text, "assign b") + 7),
|
||||
@@ -2248,13 +2239,13 @@ endpackage
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A net declared inside a **generate block** is on neither surface: its
|
||||
/// scope is the block's, not the module's (`hierarchical-tail`, "a unit's
|
||||
/// members are the symbols of its own scope"). So the gate still says no
|
||||
/// and the answer is still the honest single-file one — the same refusal
|
||||
/// a rename gives `u_x.g.sig`.
|
||||
/// A net declared inside a **generate block**. Until TODO §65.1 it was on
|
||||
/// neither surface and this pinned the honest single-file answer; a named
|
||||
/// block is now on its module's hierarchical surface and its members under
|
||||
/// `gleaf.g` (`docs/features/generate-label-rename/README.md`), so the gate
|
||||
/// says yes and `u_g.g.gsig` in the other file is one of the references.
|
||||
#[test]
|
||||
fn a_generate_block_scoped_net_still_never_asks_the_workspace() {
|
||||
fn a_generate_block_scoped_net_is_found_through_the_instance_path() {
|
||||
let dir = temp_dir("hier_generate");
|
||||
let leaf = "\
|
||||
module gleaf;
|
||||
@@ -2278,11 +2269,15 @@ endmodule
|
||||
|
||||
let decl = at(leaf, "wire gsig") + 5;
|
||||
let doc = ws.document(&leaf_uri).expect("open");
|
||||
assert!(!leaves_this_file(&ws, doc, decl), "the index exports it on no surface");
|
||||
assert!(leaves_this_file(&ws, doc, decl), "the index exports it hierarchically");
|
||||
assert_eq!(
|
||||
places(&references(&ws, &leaf_uri, decl, true)),
|
||||
vec![("gleaf.sv".to_string(), 2), ("gleaf.sv".to_string(), 3)],
|
||||
"this file only, and `u_g.g.gsig` is left to the editor"
|
||||
vec![
|
||||
("gleaf.sv".to_string(), 2),
|
||||
("gleaf.sv".to_string(), 3),
|
||||
("guser.sv".to_string(), 3)
|
||||
],
|
||||
"this file and `u_g.g.gsig`"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -2941,12 +2936,11 @@ endmodule
|
||||
}
|
||||
|
||||
/// Case (a), sharpened: an **indexed generate array**, not just a named
|
||||
/// block. `u_g.gen[0].gsig` is still on neither surface — the array
|
||||
/// index changes how many instances of the scope exist, not which scope
|
||||
/// `gsig` belongs to — so the honest single-file fallback must hold here
|
||||
/// too.
|
||||
/// block. The array index changes how many instances of the scope exist,
|
||||
/// not which scope `gsig` belongs to — which since TODO §65.1 is exactly
|
||||
/// why `u_g.gen[0].gsig` is walked as `u_g.gen.gsig` and found.
|
||||
#[test]
|
||||
fn qa_a_generate_for_arrays_scoped_net_still_never_asks_the_workspace() {
|
||||
fn qa_a_generate_for_arrays_scoped_net_is_found_through_the_indexed_path() {
|
||||
let dir = temp_dir("qa_generate_for");
|
||||
let leaf = "\
|
||||
module gfleaf;
|
||||
@@ -2970,11 +2964,15 @@ endmodule
|
||||
|
||||
let decl = at(leaf, "wire gsig") + 5;
|
||||
let doc = ws.document(&leaf_uri).expect("open");
|
||||
assert!(!leaves_this_file(&ws, doc, decl), "an indexed generate scope is on no surface");
|
||||
assert!(leaves_this_file(&ws, doc, decl), "a generate array's scope is exported too");
|
||||
assert_eq!(
|
||||
places(&references(&ws, &leaf_uri, decl, true)),
|
||||
vec![("gfleaf.sv".to_string(), 2), ("gfleaf.sv".to_string(), 3)],
|
||||
"this file only; `u_g.gen[0].gsig` is left to the editor"
|
||||
vec![
|
||||
("gfleaf.sv".to_string(), 2),
|
||||
("gfleaf.sv".to_string(), 3),
|
||||
("gfuser.sv".to_string(), 3)
|
||||
],
|
||||
"this file and `u_g.gen[0].gsig`"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -28,6 +28,10 @@ use crate::format;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, first_token_reaching, Document};
|
||||
|
||||
mod auto_end;
|
||||
|
||||
pub(crate) use auto_end::begin_owes_an_end;
|
||||
|
||||
/// The character the client is told to trigger on. A newline is the one
|
||||
/// keystroke that opens a line whose indentation nobody has chosen yet.
|
||||
pub const NEWLINE: &str = "\n";
|
||||
@@ -40,12 +44,21 @@ pub const SEMICOLON: &str = ";";
|
||||
///
|
||||
/// Never an `Err`: every refusal on this path — an unknown trigger, a client
|
||||
/// out of step, a buffer the formatter will not touch — is the empty answer.
|
||||
///
|
||||
/// `auto_end` is `lucisv.autoEnd`: whether a newline typed after a `begin`
|
||||
/// that still owes its `end` also writes that `end` (see `auto_end.rs`).
|
||||
pub fn on_type_formatting(
|
||||
doc: &Document,
|
||||
position: Position,
|
||||
typed: &str,
|
||||
config: &Config,
|
||||
auto_end: bool,
|
||||
) -> Vec<TextEdit> {
|
||||
if auto_end && typed == NEWLINE {
|
||||
if let Some(edits) = auto_end::begin_newline_edits(doc, position, config.indent_width) {
|
||||
return edits;
|
||||
}
|
||||
}
|
||||
let edit = match typed {
|
||||
NEWLINE => indent_edit(doc, position, config.indent_width),
|
||||
SEMICOLON => statement_edit(doc, position, config),
|
||||
@@ -61,9 +74,9 @@ pub fn on_type_formatting(
|
||||
/// Lay out the statement the `;` just ended, through the range engine.
|
||||
///
|
||||
/// The range asked for is the `;`'s **own line** and nothing else. That is not
|
||||
/// a narrower request than "the statement's lines": `format_range` selects by
|
||||
/// *unit*, so any line of a statement selects the whole statement (see
|
||||
/// `docs/features/range-formatting/README.md`). It is, however, a much safer
|
||||
/// a narrower request than "the statement's lines": `format_selection` selects
|
||||
/// by *unit*, so any line of a statement selects the whole statement (see
|
||||
/// `docs/features/selection-formatting/README.md`). It is, however, a much safer
|
||||
/// one — the `;` closing `module m (\n input a\n);` ends no statement at all,
|
||||
/// and naming its enclosing node's lines there would ask for the whole module
|
||||
/// back on a keystroke.
|
||||
@@ -715,7 +728,7 @@ mod tests {
|
||||
|
||||
fn newline_with(text: &str, line: u32, indent_width: usize) -> Vec<TextEdit> {
|
||||
let at = Position { line, character: 0 };
|
||||
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width)))
|
||||
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width), false))
|
||||
}
|
||||
|
||||
/// The `new_text` of the single edit a newline produced, or `None` when it
|
||||
@@ -732,7 +745,7 @@ mod tests {
|
||||
let content = source[line as usize].trim_end_matches('\n');
|
||||
let character = content.rfind(';').expect("the line ends a statement") as u32 + 1;
|
||||
let at = Position { line, character };
|
||||
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)))
|
||||
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -793,7 +806,7 @@ mod tests {
|
||||
// it means the client is not talking about a newline it just typed.
|
||||
let text = "module m;\nwire a;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 4 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
@@ -955,7 +968,7 @@ mod tests {
|
||||
with(text, |doc| {
|
||||
for line in 1..text.lines().count() as u32 {
|
||||
let at = Position { line, character: 0 };
|
||||
for edit in on_type_formatting(doc, at, NEWLINE, &config(2)) {
|
||||
for edit in on_type_formatting(doc, at, NEWLINE, &config(2), false) {
|
||||
assert_eq!(edit.range.start, at, "always column zero of the asked-for line");
|
||||
assert_eq!(edit.range.end.line, line, "and never past that line");
|
||||
let source = doc.text.lines().nth(line as usize).unwrap_or("");
|
||||
@@ -1174,13 +1187,25 @@ mod tests {
|
||||
#[test]
|
||||
fn a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all() {
|
||||
// Half-typed code is the normal case on this trigger, not a failure.
|
||||
assert_eq!(semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1), Vec::new());
|
||||
// The error is on the keystroke's own line: one elsewhere in the
|
||||
// buffer no longer refuses (selection-formatting, TODO §66.2).
|
||||
let text = "module m;\n wire a = ;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 13 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semicolon_still_lays_out_its_statement_when_the_error_is_elsewhere() {
|
||||
let edits = semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1);
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\n wire ;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semicolon_that_is_not_where_the_client_said_answers_nothing() {
|
||||
let at = Position { line: 1, character: 3 };
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
@@ -1191,7 +1216,7 @@ mod tests {
|
||||
assert_eq!(semicolon(text, 1), Vec::new());
|
||||
let text = "module m;\n string s = \"a;\";\n wire a;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 16 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "the `;` inside the quotes");
|
||||
}
|
||||
|
||||
@@ -1202,12 +1227,12 @@ mod tests {
|
||||
// the whole document.
|
||||
let text = "module m;\n wire a;\nendmodule";
|
||||
let at = Position { line: 1, character: 11 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
// The engine's own canonicalization adds the missing final newline —
|
||||
// exactly what `textDocument/rangeFormatting` would also do here, and
|
||||
// not a moved byte this path invented on its own.
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule\n");
|
||||
// Only the statement moves: the file's tail is outside the splice, so
|
||||
// the missing final newline stays missing — exactly what
|
||||
// `textDocument/rangeFormatting` answers here too.
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1241,7 +1266,7 @@ mod tests {
|
||||
// inside a string or a comment.
|
||||
let text = "`define FOO x = 1;\nmodule m;\nendmodule\n";
|
||||
let at = Position { line: 0, character: 19 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "no Symbol(;) token ends inside a Directive");
|
||||
}
|
||||
|
||||
@@ -1269,7 +1294,7 @@ mod tests {
|
||||
// guess at what it meant.
|
||||
let at = Position { line: 1, character: 9 };
|
||||
for typed in ["}", ")", "\t", ""] {
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2)));
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "trigger {typed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
//! `begin` + Enter writes the `end` (TODO §68.1).
|
||||
//!
|
||||
//! The newline answer's second half. When the line above the one a `\n` just
|
||||
//! opened ends in `begin` (or `begin : label`) and that block still owes an
|
||||
//! `end`, the answer is two edits instead of one: the new line's body
|
||||
//! indentation, as the plain newline answer would give it, and a line after
|
||||
//! it holding `end` at the indentation of the statement the `begin` belongs
|
||||
//! to. The cursor's line stays blank, so the user types the first statement
|
||||
//! where they already are.
|
||||
//!
|
||||
//! **Which `begin` owes an `end`.** `pairs::analyze` is a stack matcher, so a
|
||||
//! `begin` typed inside a block that already balances *steals* that block's
|
||||
//! `end`: the new inner `begin` comes out matched, and the outer one is
|
||||
//! reported unclosed. "Is *this* `begin` unmatched" is therefore the wrong
|
||||
//! question. The one asked here is: is any `begin` at or before this one
|
||||
//! unclosed — unless this `begin` is matched by an `end` that starts its line
|
||||
//! at exactly the indentation this answer would have written, which is the
|
||||
//! block the user already closed. See `docs/features/completion-ux/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, TextEdit};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use super::level_at;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// The keywords whose header a `begin` may be the body of. Reading backwards,
|
||||
/// one of these is where the header starts.
|
||||
const HEADER_KEYWORDS: &[&str] = &[
|
||||
"if",
|
||||
"for",
|
||||
"foreach",
|
||||
"while",
|
||||
"repeat",
|
||||
"forever",
|
||||
"always",
|
||||
"always_ff",
|
||||
"always_comb",
|
||||
"always_latch",
|
||||
"initial",
|
||||
"final",
|
||||
];
|
||||
|
||||
/// The words that may stand in front of a header on the same statement:
|
||||
/// `else if`, `unique case`-style qualifiers, and a bare `else` before its
|
||||
/// `begin`.
|
||||
const QUALIFIERS: &[&str] = &["else", "unique", "unique0", "priority"];
|
||||
|
||||
/// The edits for a newline typed right after a `begin` that still owes its
|
||||
/// `end`, or `None` when this newline is not that — the caller then answers
|
||||
/// the plain indentation question instead.
|
||||
pub(super) fn begin_newline_edits(
|
||||
doc: &Document,
|
||||
position: Position,
|
||||
indent_width: usize,
|
||||
) -> Option<Vec<TextEdit>> {
|
||||
let line = NewLine::at(doc, position)?;
|
||||
let begin = begin_ending_line_above(doc, line.range.start)?;
|
||||
let end_indent = owner_indent(doc, begin);
|
||||
if !owes_an_end(doc, begin, &end_indent) {
|
||||
return None;
|
||||
}
|
||||
let body = body_indent(level_at(doc, line.content), &end_indent, indent_width);
|
||||
Some(edits(doc, &line, &body, &end_indent))
|
||||
}
|
||||
|
||||
/// The blank line a `\n` just opened, as far as this answer needs it.
|
||||
struct NewLine {
|
||||
/// The whole line, its `\r` included when the file has one.
|
||||
range: TextRange,
|
||||
/// The end of its leading whitespace.
|
||||
content: u32,
|
||||
/// The line ending the file writes, read off the newline just typed.
|
||||
eol: &'static str,
|
||||
}
|
||||
|
||||
impl NewLine {
|
||||
/// The line at `position`, when a newline opened it, the cursor sits in
|
||||
/// its leading whitespace, and nothing but whitespace is on it — Enter
|
||||
/// pressed in the middle of a line carries text down, and a body that is
|
||||
/// already written owes nothing.
|
||||
fn at(doc: &Document, position: Position) -> Option<NewLine> {
|
||||
let range = doc.line_index.line_range(position.line.checked_add(1)?)?;
|
||||
let bytes = doc.text.as_bytes();
|
||||
if range.start == 0 || bytes.get(range.start as usize - 1) != Some(&b'\n') {
|
||||
return None;
|
||||
}
|
||||
let text = doc.text.get(range.start as usize..range.end as usize)?;
|
||||
let rest = text.trim_start_matches([' ', '\t']);
|
||||
if !rest.trim_end_matches('\r').is_empty() {
|
||||
return None;
|
||||
}
|
||||
let content = range.start + (text.len() - rest.len()) as u32;
|
||||
if doc.positions().offset(position) > content {
|
||||
return None;
|
||||
}
|
||||
let crlf = range.start >= 2 && bytes.get(range.start as usize - 2) == Some(&b'\r');
|
||||
Some(NewLine { range, content, eol: if crlf { "\r\n" } else { "\n" } })
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the `begin` the line above `line_start` ends with — the last
|
||||
/// token on it, or the one before a `: label` — when it does.
|
||||
///
|
||||
/// Comments are trivia, not tokens, so `begin // why` ends in `begin` here
|
||||
/// without a check of its own.
|
||||
fn begin_ending_line_above(doc: &Document, line_start: u32) -> Option<usize> {
|
||||
let last = first_token_from(&doc.tokens, line_start).checked_sub(1)?;
|
||||
let above = doc.line_index.line_col(line_start).0.checked_sub(1)?;
|
||||
let on_line_above =
|
||||
|index: usize| doc.tokens.get(index).is_some_and(|token| line_of(doc, token) == above);
|
||||
let token = doc.tokens.get(last)?;
|
||||
let begin = match token.kind {
|
||||
TokenKind::Ident if last >= 2 && doc.tokens.get(last - 1)?.is_sym(":") => last - 2,
|
||||
_ => last,
|
||||
};
|
||||
(doc.tokens.get(begin)?.is_kw("begin") && on_line_above(begin) && on_line_above(last))
|
||||
.then_some(begin)
|
||||
}
|
||||
|
||||
/// The leading whitespace of the line the statement owning the `begin` at
|
||||
/// `begin` starts on, as written — tabs stay tabs.
|
||||
///
|
||||
/// Read backwards from the `begin` over what may stand between a statement's
|
||||
/// first token and its body: a parenthesised header, an `@`/`#` control and
|
||||
/// its operand, and [`HEAD_KEYWORDS`]. Anything else — a `;`, an `end`, a
|
||||
/// case item's `:` — is where the statement starts. A header with no `(` to
|
||||
/// match leaves the `begin`'s own line as the answer.
|
||||
fn owner_indent(doc: &Document, begin: usize) -> String {
|
||||
let tokens = &doc.tokens;
|
||||
let mut first = begin;
|
||||
// Once a header keyword is read, only a qualifier may still precede it:
|
||||
// `always_comb` on the line above an `if` is the `if`'s *owner*, not part
|
||||
// of its header.
|
||||
let mut keyword_seen = false;
|
||||
while let Some(prev) = first.checked_sub(1) {
|
||||
let token = &tokens[prev];
|
||||
let step = match keyword_seen {
|
||||
true => is_keyword_in(token, QUALIFIERS).then_some(prev),
|
||||
false => header_step(tokens, prev),
|
||||
};
|
||||
let Some(step) = step else { break };
|
||||
keyword_seen |= is_keyword_in(token, HEADER_KEYWORDS) || is_keyword_in(token, QUALIFIERS);
|
||||
first = step;
|
||||
}
|
||||
line_indent(doc, tokens[first].span.start)
|
||||
}
|
||||
|
||||
/// Where reading a header backwards goes from the token at `prev`: over a
|
||||
/// parenthesised group to its `(`, onto a header keyword, a qualifier, an
|
||||
/// `@`/`#`, or the operand right after one — or nowhere, when `prev` is
|
||||
/// already outside the header.
|
||||
fn header_step(tokens: &[Token], prev: usize) -> Option<usize> {
|
||||
let token = &tokens[prev];
|
||||
if token.is_sym(")") {
|
||||
return matching_open(tokens, prev);
|
||||
}
|
||||
let after_control = prev
|
||||
.checked_sub(1)
|
||||
.and_then(|i| tokens.get(i))
|
||||
.is_some_and(|t| t.is_sym("@") || t.is_sym("#"));
|
||||
let in_header = is_keyword_in(token, HEADER_KEYWORDS)
|
||||
|| is_keyword_in(token, QUALIFIERS)
|
||||
|| token.is_sym("@")
|
||||
|| token.is_sym("#")
|
||||
|| after_control;
|
||||
in_header.then_some(prev)
|
||||
}
|
||||
|
||||
fn is_keyword_in(token: &Token, words: &[&str]) -> bool {
|
||||
token.kind == TokenKind::Keyword && words.contains(&token.text.as_str())
|
||||
}
|
||||
|
||||
/// The `(` the `)` at `close` closes, counting parentheses only.
|
||||
fn matching_open(tokens: &[Token], close: usize) -> Option<usize> {
|
||||
let mut depth = 0u32;
|
||||
for index in (0..=close).rev() {
|
||||
let token = &tokens[index];
|
||||
if token.is_sym(")") {
|
||||
depth += 1;
|
||||
} else if token.is_sym("(") {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
return Some(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether the block the `begin` at `begin` opens still needs an `end`
|
||||
/// written for it. See the module comment for why this is not "is this
|
||||
/// `begin` unmatched".
|
||||
///
|
||||
/// Two layouts count as "already closed": the `end` under the statement (the
|
||||
/// formatter's own layout) and the `end` under the `begin`'s own line (the GNU
|
||||
/// layout, `begin` on a line of its own — QA finding 1, fix round
|
||||
/// 2026-11-17). And an unmatched `begin` inside a `` `ifdef `` that has an
|
||||
/// `` `else ``/`` `elsif `` arms nothing: two branches each opening a block
|
||||
/// closed by one shared `end` are an unmatched `begin` to the stack matcher
|
||||
/// and complete code to the compiler.
|
||||
fn owes_an_end(doc: &Document, begin: usize, end_indent: &str) -> bool {
|
||||
let span = doc.tokens[begin].span;
|
||||
let own_indent = line_indent(doc, span.start);
|
||||
let analysis = pairs::analyze(&doc.tokens);
|
||||
let closed_here = analysis.pairs.iter().any(|pair| {
|
||||
pair.open == span
|
||||
&& (starts_line_at(doc, pair.close, end_indent)
|
||||
|| starts_line_at(doc, pair.close, &own_indent))
|
||||
});
|
||||
if closed_here {
|
||||
return false;
|
||||
}
|
||||
let branched = branched_regions(&doc.tokens);
|
||||
analysis.unmatched_open.iter().any(|open| {
|
||||
open.keyword == "begin"
|
||||
&& open.span.start <= span.start
|
||||
&& !branched.iter().any(|region| region.contains(&open.span.start))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the `begin` at token index `begin` opens a block that still needs
|
||||
/// an `end` — [`owes_an_end`] with the `end` at its owner's indentation. The
|
||||
/// inline `begin` ghost asks the same question.
|
||||
pub(crate) fn begin_owes_an_end(doc: &Document, begin: usize) -> bool {
|
||||
owes_an_end(doc, begin, &owner_indent(doc, begin))
|
||||
}
|
||||
|
||||
/// The byte ranges of every `` `ifdef ``/`` `ifndef `` … `` `endif `` region
|
||||
/// that holds an `` `else `` or `` `elsif `` of its own. A region never closed
|
||||
/// runs to the end of the buffer.
|
||||
fn branched_regions(tokens: &[Token]) -> Vec<std::ops::Range<u32>> {
|
||||
let mut open: Vec<(u32, bool)> = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for token in tokens {
|
||||
match conditional(token) {
|
||||
Some("`ifdef" | "`ifndef") => open.push((token.span.start, false)),
|
||||
Some("`else" | "`elsif") => {
|
||||
if let Some(last) = open.last_mut() {
|
||||
last.1 = true;
|
||||
}
|
||||
}
|
||||
Some("`endif") => {
|
||||
if let Some((start, true)) = open.pop() {
|
||||
out.push(start..token.span.end);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let end = tokens.last().map_or(0, |token| token.span.end);
|
||||
out.extend(open.into_iter().filter(|(_, branched)| *branched).map(|(start, _)| start..end));
|
||||
out
|
||||
}
|
||||
|
||||
/// The conditional-compilation directive a token spells, by its first word.
|
||||
fn conditional(token: &Token) -> Option<&str> {
|
||||
let word = token.text.split_whitespace().next()?;
|
||||
matches!(word, "`ifdef" | "`ifndef" | "`else" | "`elsif" | "`endif").then_some(word)
|
||||
}
|
||||
|
||||
/// Whether `span` is the first thing on its line and that line is indented
|
||||
/// by exactly `indent`.
|
||||
fn starts_line_at(doc: &Document, span: TextRange, indent: &str) -> bool {
|
||||
let line = doc.line_index.line_col(span.start).0;
|
||||
let Some(range) = doc.line_index.line_range(line) else { return false };
|
||||
doc.text.get(range.start as usize..span.start as usize) == Some(indent)
|
||||
}
|
||||
|
||||
/// The body line's indentation: the nesting model's answer when it has one
|
||||
/// that sits inside the `end`, else one step in from the `end`. A file
|
||||
/// indented with tabs gets one more tab — the model speaks spaces, and mixing
|
||||
/// the two on adjacent lines would be worse than either.
|
||||
fn body_indent(level: Option<usize>, end_indent: &str, indent_width: usize) -> String {
|
||||
if end_indent.contains('\t') {
|
||||
return format!("{end_indent}\t");
|
||||
}
|
||||
match level {
|
||||
Some(level) if level * indent_width > end_indent.len() => " ".repeat(level * indent_width),
|
||||
_ => format!("{end_indent}{}", " ".repeat(indent_width)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The edits themselves: re-indent the new line when it needs it, and write
|
||||
/// the `end` line after it.
|
||||
///
|
||||
/// The `end` goes in at the **start of the following line** whenever there is
|
||||
/// one, so no edit touches the cursor's own position and an editor applying
|
||||
/// them leaves the cursor on the body line. The new line being the file's last
|
||||
/// is the one case with nowhere else to put it, and there the two are one
|
||||
/// edit.
|
||||
fn edits(doc: &Document, line: &NewLine, body: &str, end_indent: &str) -> Vec<TextEdit> {
|
||||
let positions = doc.positions();
|
||||
let start = positions.position(line.range.start);
|
||||
let indent = Range { start, end: positions.position(line.content) };
|
||||
let end_line = format!("{end_indent}end");
|
||||
if line.range.end as usize >= doc.text.len() {
|
||||
let new_text = format!("{body}{}{end_line}", line.eol);
|
||||
return vec![TextEdit {
|
||||
range: Range { start, end: positions.position(line.range.end) },
|
||||
new_text,
|
||||
}];
|
||||
}
|
||||
let mut edits = Vec::new();
|
||||
if doc.text.get(line.range.start as usize..line.content as usize) != Some(body) {
|
||||
edits.push(TextEdit { range: indent, new_text: body.to_string() });
|
||||
}
|
||||
let next = positions.position(line.range.end + 1);
|
||||
edits.push(TextEdit {
|
||||
range: Range { start: next, end: next },
|
||||
new_text: format!("{end_line}{}", line.eol),
|
||||
});
|
||||
edits
|
||||
}
|
||||
|
||||
/// The 1-based line a token starts on.
|
||||
fn line_of(doc: &Document, token: &Token) -> u32 {
|
||||
doc.line_index.line_col(token.span.start).0
|
||||
}
|
||||
|
||||
/// The leading whitespace of the line holding `offset`.
|
||||
fn line_indent(doc: &Document, offset: u32) -> String {
|
||||
let line = doc.line_index.line_col(offset).0;
|
||||
let Some(range) = doc.line_index.line_range(line) else { return String::new() };
|
||||
let text = doc.text.get(range.start as usize..range.end as usize).unwrap_or("");
|
||||
text[..text.len() - text.trim_start_matches([' ', '\t']).len()].to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::on_type::{on_type_formatting, NEWLINE};
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_formatter::Config;
|
||||
|
||||
/// The buffer after the newline answer for a `\n` that opened `line`
|
||||
/// (0-based), with `lucisv.autoEnd` as given — and the edits themselves.
|
||||
fn typed(text: &str, line: u32, auto_end: bool) -> (String, Vec<TextEdit>) {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let at = Position { line, character: 0 };
|
||||
let config = Config { indent_width: 2, ..Config::default() };
|
||||
let edits = on_type_formatting(doc, at, NEWLINE, &config, auto_end);
|
||||
(apply(doc, &edits), edits)
|
||||
}
|
||||
|
||||
/// `edits` applied to the buffer, last first so the offsets stay true.
|
||||
fn apply(doc: &Document, edits: &[TextEdit]) -> String {
|
||||
let mut spans: Vec<(usize, usize, &str)> = edits
|
||||
.iter()
|
||||
.map(|edit| {
|
||||
let start = doc.positions().offset(edit.range.start) as usize;
|
||||
let end = doc.positions().offset(edit.range.end) as usize;
|
||||
(start, end, edit.new_text.as_str())
|
||||
})
|
||||
.collect();
|
||||
spans.sort_by_key(|(start, _, _)| std::cmp::Reverse(*start));
|
||||
let mut text = doc.text.to_string();
|
||||
for (start, end, new_text) in spans {
|
||||
text.replace_range(start..end, new_text);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newline_after_an_unclosed_begin_writes_the_end_under_its_statement() {
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \n end\nendmodule\n");
|
||||
// Nothing lands on the cursor's own position: the `end` goes in at the
|
||||
// start of the line after it, so the cursor stays on the body line.
|
||||
assert!(edits
|
||||
.iter()
|
||||
.all(|edit| edit.range.start.line != 2 || edit.range.end.character == 0));
|
||||
assert_eq!(
|
||||
edits.last().map(|edit| edit.range.start),
|
||||
Some(Position { line: 3, character: 0 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_typed_inside_a_balanced_block_still_gets_its_end() {
|
||||
// The new `if`'s `begin` steals the `always_comb` block's `end` in the
|
||||
// stack matcher, and the *outer* `begin` is what comes out unclosed.
|
||||
let text =
|
||||
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert_eq!(
|
||||
after,
|
||||
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n \n end\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_whose_blocks_already_balance_gets_no_end() {
|
||||
let text = "module m;\n always_comb begin\n\n end\nendmodule\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n always_comb begin\n \n end\nendmodule\n");
|
||||
assert_eq!(edits.len(), 1, "the indentation alone: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_inner_block_with_an_outer_end_missing_gets_no_second_end() {
|
||||
// The outer `begin` is the unclosed one, but this `begin` already has
|
||||
// its `end`, at exactly the indentation the answer would write.
|
||||
let text = "module m;\n always_comb begin\n if (x) begin\n\n end\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_labelled_begin_and_a_trailing_comment_both_count() {
|
||||
let text = "module m;\n initial begin : boot // first\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n initial begin : boot // first\n \n end\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_lines_up_with_the_first_line_of_a_wrapped_header() {
|
||||
let text = "module m;\n always_comb\n if (a &&\n b) begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert!(after.contains(" b) begin\n \n end\nendmodule"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_else_branch_ends_under_the_line_that_holds_the_else() {
|
||||
let text = "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end else begin\n\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 5, true);
|
||||
assert!(after.contains(" end else begin\n \n end\n end\n"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_case_item_ends_under_the_item() {
|
||||
let text = "module m;\n always_comb begin\n case (s)\n 2'b01: begin\n\n endcase\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert!(after.contains(" 2'b01: begin\n \n end\n endcase"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_stay_tabs() {
|
||||
let text = "module m;\n\talways_comb begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n\talways_comb begin\n\t\t\n\tend\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_file_gets_a_crlf_end_line() {
|
||||
let text = "module m;\r\n initial begin\r\n\r\nendmodule\r\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\r\n initial begin\r\n \r\n end\r\nendmodule\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_line_of_the_file_gets_one_edit() {
|
||||
let text = "module m;\n initial begin\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n initial begin\n \n end");
|
||||
assert_eq!(edits.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_but_the_indent_when_the_setting_is_off() {
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, false);
|
||||
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_end_where_the_line_above_does_not_end_in_begin() {
|
||||
for text in [
|
||||
"module m;\n initial begin x = 1;\n\nendmodule\n",
|
||||
"module m;\n initial // begin\n\nendmodule\n",
|
||||
"module m;\n initial $display(\"begin\");\n\nendmodule\n",
|
||||
"module m;\n initial fork\n\nendmodule\n",
|
||||
] {
|
||||
let (_, edits) = typed(text, 2, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{text:?}: {edits:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_end_when_enter_carried_text_down_to_the_new_line() {
|
||||
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
|
||||
let (_, edits) = typed(text, 2, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_two_lines_up_is_not_the_line_above() {
|
||||
let text = "module m;\n initial begin\n\n\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
/// QA (2026-11-17): buffers just after an Enter on `line`, each of which
|
||||
/// gets an `end`.
|
||||
const QA_ARMED: &[(&str, u32)] = &[
|
||||
("module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n", 4),
|
||||
("module m;\n generate\n if (P) begin : g\n\n endgenerate\nendmodule\n", 3),
|
||||
("module m;\n initial fork\n begin\n\n join\nendmodule\n", 3),
|
||||
("module m;\n initial `MY_MACRO begin\n\nendmodule\n", 2),
|
||||
("module m;\n initial #5 begin\n\nendmodule\n", 2),
|
||||
("module m;\n always @* begin\n\nendmodule\n", 2),
|
||||
("class c;\n function void f();\n if (a) begin\n\n endfunction\nendclass\n", 3),
|
||||
("module m;\r\n always_comb begin\r\n\r\nendmodule\r\n", 2),
|
||||
("module m;\n initial begin\n", 2),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_asking_again_after_the_answer_is_applied_adds_no_second_end() {
|
||||
for &(text, line) in QA_ARMED {
|
||||
let (after, edits) = typed(text, line, true);
|
||||
assert!(edits.iter().any(|edit| edit.new_text.contains("end")), "{text:?}: {edits:?}");
|
||||
let (again, second) = typed(&after, line, true);
|
||||
assert!(
|
||||
second.iter().all(|edit| !edit.new_text.contains("end")),
|
||||
"{after:?}: {second:?}"
|
||||
);
|
||||
assert_eq!(again, after, "the second answer changes nothing: {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_declined_newline_is_exactly_the_plain_indent_answer() {
|
||||
for (text, line) in [
|
||||
("module m;\n always_comb begin\n\n end\nendmodule\n", 2),
|
||||
("`define OPEN begin\n\nmodule m;\nendmodule\n", 1),
|
||||
("`define BLK(x) if (x) begin \\\n\nmodule m;\nendmodule\n", 1),
|
||||
("module m;\n initial $display(\"begin\n\nendmodule\n", 2),
|
||||
("module m;\n`ifdef A\n always_ff @(posedge clk) begin\n`else\n always_ff @(posedge clk or negedge rst_n) begin\n\n`endif\n x <= 1;\n end\nendmodule\n", 5),
|
||||
("module m;\n always_comb begin\n\nend\nendmodule\n", 2),
|
||||
("module m;\n initial begin end\n\nendmodule\n", 2),
|
||||
("module m;\n wire \\begin \n\nendmodule\n", 2),
|
||||
("module m;\n initial begin\nfoo = 1;\nendmodule\n", 2),
|
||||
] {
|
||||
let (_, with) = typed(text, line, true);
|
||||
let (_, without) = typed(text, line, false);
|
||||
assert_eq!(with, without, "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any edit writes an `end`.
|
||||
fn wrote_an_end(edits: &[TextEdit]) -> bool {
|
||||
edits.iter().any(|edit| edit.new_text.contains("end"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gnu_style_begin_already_closed_under_itself_gets_no_end() {
|
||||
// Another `begin` above is unclosed (mid-edit), and this block's `end`
|
||||
// sits under the `begin`'s own line rather than under the `if`.
|
||||
let text = "module m;\n initial begin\n always_comb\n if (x)\n begin\n\n y = 1;\n end\nendmodule\n";
|
||||
let (_, edits) = typed(text, 5, true);
|
||||
assert!(!wrote_an_end(&edits), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_ifdef_branches_sharing_one_end_get_no_second_end() {
|
||||
// QA finding 1: two `ifdef` branches each open the `always` block and
|
||||
// one `end` after the `endif` closes whichever was compiled.
|
||||
let shared = "module m;\n`ifdef A\n always @(posedge clk) begin\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n if (x)\n begin\n\n y <= 1;\n end\n end\nendmodule\n";
|
||||
let (_, edits) = typed(shared, 8, true);
|
||||
assert!(!wrote_an_end(&edits), "after the GNU-style begin: {edits:?}");
|
||||
// The cursor after the *first* branch's `begin`: that block's `end`
|
||||
// is the shared one after the `endif`, so writing one would be wrong.
|
||||
let first = "module m;\n`ifdef A\n always @(posedge clk) begin\n\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n y <= 1;\n end\nendmodule\n";
|
||||
let (_, edits) = typed(first, 3, true);
|
||||
assert!(!wrote_an_end(&edits), "inside the first branch: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ifdef_with_no_else_still_arms_the_answer() {
|
||||
let text = "module m;\n`ifdef A\n initial begin\n\n`endif\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(wrote_an_end(&edits), "{edits:?}");
|
||||
}
|
||||
}
|
||||
@@ -1168,7 +1168,12 @@ mod tests {
|
||||
#[test]
|
||||
fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() {
|
||||
let tree = Tree::new("macrocontrol");
|
||||
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
|
||||
// Spelled after a `.`: since §65.1's scoping of rename warnings, a
|
||||
// *bare* `sig` in `far`'s own macro is `far`'s word, not `sub`'s port,
|
||||
// and the engine rightly says nothing about it; a dotted one may be a
|
||||
// path to the port and is still said — once.
|
||||
let dotted = M_FAR.replace("sig)", "u_far.sig)");
|
||||
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {dotted}endmodule\n");
|
||||
let (ws, uri) = macro_workspace(&tree, &far);
|
||||
|
||||
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
|
||||
|
||||
@@ -53,6 +53,7 @@ impl Server {
|
||||
let buffers = self.dirty.len();
|
||||
for (uri, text) in std::mem::take(&mut self.dirty) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.workspace.locate_port_entry(&uri);
|
||||
crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri));
|
||||
}
|
||||
self.timed(started, |took| {
|
||||
@@ -100,7 +101,48 @@ impl Server {
|
||||
// (`docs/features/semantic-lints-on/`).
|
||||
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
|
||||
self.report_config_problems(&run);
|
||||
diagnostics::all_in(doc, &run)
|
||||
// Except what the connection being typed would say, while it is being
|
||||
// typed (`docs/features/port-entry-grace/README.md`).
|
||||
self.workspace.port_grace().withhold(uri, doc, diagnostics::all_in(doc, &run))
|
||||
}
|
||||
|
||||
/// Say everything again about each buffer whose connection entry is no
|
||||
/// longer being typed: its quiet period ran out, or an edit landed in
|
||||
/// another buffer.
|
||||
///
|
||||
/// The generation moves first, so a pulling client's next pull gets the
|
||||
/// full list rather than "unchanged" against the withheld one; a pulling
|
||||
/// client that accepts `workspace/diagnostic/refresh` is asked — once per
|
||||
/// release, however many buffers it covers — to make that pull now. Its
|
||||
/// answer is ignorable and rides `response`'s fall-through. A pulling
|
||||
/// client without the capability sees the release at its own next pull.
|
||||
pub(super) fn release_port_entries(&mut self) {
|
||||
let due = self.workspace.port_grace_mut().due(std::time::Instant::now());
|
||||
if due.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.generation += 1;
|
||||
for uri in &due {
|
||||
self.publish(uri);
|
||||
}
|
||||
if self.abilities.pull_diagnostics && self.abilities.diagnostic_refresh {
|
||||
use lsp_types::request::{Request as _, WorkspaceDiagnosticRefresh};
|
||||
self.send_request(WorkspaceDiagnosticRefresh::METHOD, ());
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the loop may wait for a message before it owes something: a
|
||||
/// dirty buffer's quiet period, or the end of a connection entry's grace,
|
||||
/// whichever comes first. `None` is "nothing is owed; wait for ever".
|
||||
pub(super) fn quiet_wait(&self) -> Option<std::time::Duration> {
|
||||
let debounce = (!self.dirty.is_empty()).then_some(super::CHANGE_DEBOUNCE);
|
||||
let now = std::time::Instant::now();
|
||||
let grace =
|
||||
self.workspace.port_grace().deadline().map(|at| at.saturating_duration_since(now));
|
||||
match (debounce, grace) {
|
||||
(Some(a), Some(b)) => Some(a.min(b)),
|
||||
(a, b) => a.or(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
|
||||
|
||||
@@ -568,7 +568,8 @@ impl Server {
|
||||
decode(request).and_then(|p: InlineCompletionParams| {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
inline::inline_completions(&self.workspace, &uri, position)
|
||||
let selected = p.context.selected_completion_info.as_ref();
|
||||
inline::inline_completions_in_context(&self.workspace, &uri, position, selected)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -98,7 +98,9 @@ impl Server {
|
||||
return to_value(Vec::<lsp_types::TextEdit>::new());
|
||||
};
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let edits = on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config);
|
||||
let auto_end = self.workspace.client_settings().auto_end.unwrap_or(true);
|
||||
let edits =
|
||||
on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config, auto_end);
|
||||
to_value(edits)
|
||||
}
|
||||
|
||||
|
||||
@@ -88,6 +88,12 @@ pub struct ClientAbilities {
|
||||
/// that said nothing is never asked, and keeps the instantiation counts it
|
||||
/// last requested until it asks again for its own reasons.
|
||||
pub code_lens_refresh: bool,
|
||||
/// Whether the client accepts a `workspace/diagnostic/refresh` — what
|
||||
/// makes a pulling client pull again when a connection entry held back
|
||||
/// while it was typed is released
|
||||
/// (`docs/features/port-entry-grace/README.md`). A client that said
|
||||
/// nothing sees the release at its own next pull.
|
||||
pub diagnostic_refresh: bool,
|
||||
/// Whether the client opens a document the server asks it to
|
||||
/// (`window/showDocument`). This is what lets the instantiation lens
|
||||
/// navigate; a client without it still gets the sites back as the
|
||||
@@ -316,7 +322,9 @@ impl Server {
|
||||
///
|
||||
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
|
||||
/// flushed here rather than left waiting for a request that may never
|
||||
/// come — diagnostics are the one answer the client never asks for.
|
||||
/// come — diagnostics are the one answer the client never asks for. The
|
||||
/// same wake-up releases a connection entry whose diagnostics were held
|
||||
/// back while it was typed, once its grace has run out.
|
||||
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
loop {
|
||||
@@ -338,20 +346,24 @@ impl Server {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let message = if self.dirty.is_empty() {
|
||||
match self.queue.recv() {
|
||||
// A connection entry whose grace ran out while messages kept
|
||||
// arriving is released here, not only when the wait below times
|
||||
// out (`docs/features/port-entry-grace/README.md`).
|
||||
self.release_port_entries();
|
||||
let message = match self.quiet_wait() {
|
||||
None => match self.queue.recv() {
|
||||
Ok(message) => message,
|
||||
Err(_) => return Ok(()),
|
||||
}
|
||||
} else {
|
||||
match self.queue.recv_timeout(CHANGE_DEBOUNCE) {
|
||||
},
|
||||
Some(wait) => match self.queue.recv_timeout(wait) {
|
||||
Ok(message) => message,
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
self.flush_dirty();
|
||||
self.release_port_entries();
|
||||
continue;
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => return Ok(()),
|
||||
}
|
||||
},
|
||||
};
|
||||
let batch = burst(&self.queue, message);
|
||||
if self.process_batch(batch)? {
|
||||
|
||||
@@ -51,6 +51,10 @@ impl Server {
|
||||
self.dirty.retain(|(pending, _)| *pending != uri);
|
||||
}
|
||||
}
|
||||
// A buffer saved, closed or opened afresh holds nothing back any more
|
||||
// (`docs/features/port-entry-grace/README.md`). Forgotten before the
|
||||
// flush, so the flush below already publishes everything.
|
||||
let released = self.forget_port_entry(&method, ¬ification);
|
||||
// Everything but a `didChange` needs the buffers' analyses current —
|
||||
// a `didSave` rebuilds the index on top of them — so the same flush a
|
||||
// request gets happens here, with the one exception that *is* the
|
||||
@@ -58,6 +62,14 @@ impl Server {
|
||||
if method != DidChangeTextDocument::METHOD {
|
||||
self.flush_dirty();
|
||||
}
|
||||
// A save of a buffer that was not dirty: nothing above said the full
|
||||
// list, so it is said here, under a new generation for a pulling
|
||||
// client. (The rescan the save starts says it again; that is the same
|
||||
// list twice, never a stale one.)
|
||||
if let Some(uri) = released {
|
||||
self.generation += 1;
|
||||
self.publish(&uri);
|
||||
}
|
||||
match method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
||||
@@ -103,7 +115,7 @@ impl Server {
|
||||
return;
|
||||
}
|
||||
let uri = p.text_document.uri;
|
||||
let text = {
|
||||
let (text, end) = {
|
||||
let base = self
|
||||
.dirty
|
||||
.iter()
|
||||
@@ -111,8 +123,12 @@ impl Server {
|
||||
.map(|(_, text)| text.as_str())
|
||||
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
|
||||
.unwrap_or("");
|
||||
sync::apply_changes(base, &p.content_changes)
|
||||
sync::apply_changes_at(base, &p.content_changes)
|
||||
};
|
||||
// Where the edit ended is where someone is typing: the
|
||||
// flush looks it up for a connection entry to hold back.
|
||||
let now = std::time::Instant::now();
|
||||
self.workspace.port_grace_mut().edited(&uri, end, now);
|
||||
self.mark_dirty(uri, text);
|
||||
}
|
||||
}
|
||||
@@ -315,6 +331,23 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget the connection entry a `didOpen`, `didSave` or `didClose` names,
|
||||
/// answering the buffer whose full list a save now owes the client. An
|
||||
/// open publishes on its own and a close clears, so only a save asks.
|
||||
fn forget_port_entry(&mut self, method: &str, notification: &Notification) -> Option<Uri> {
|
||||
let ends_typing = [
|
||||
DidOpenTextDocument::METHOD,
|
||||
DidSaveTextDocument::METHOD,
|
||||
DidCloseTextDocument::METHOD,
|
||||
];
|
||||
if !ends_typing.contains(&method) {
|
||||
return None;
|
||||
}
|
||||
let uri = document_uri(notification)?;
|
||||
let held = self.workspace.port_grace_mut().forget(&uri);
|
||||
(held && method == DidSaveTextDocument::METHOD).then_some(uri)
|
||||
}
|
||||
|
||||
/// The rule selection in force, as a value two settings pushes can be
|
||||
/// compared by.
|
||||
///
|
||||
@@ -346,6 +379,13 @@ fn closing_uri(notification: &Notification) -> Option<Uri> {
|
||||
.map(|p| p.text_document.uri)
|
||||
}
|
||||
|
||||
/// The `textDocument.uri` a document notification names, read without
|
||||
/// consuming it; `None` when the params carry none that parses.
|
||||
fn document_uri(notification: &Notification) -> Option<Uri> {
|
||||
let uri = notification.params.get("textDocument")?.get("uri")?.as_str()?;
|
||||
uri.parse().ok()
|
||||
}
|
||||
|
||||
/// The paths behind a `didChangeWorkspaceFolders` list.
|
||||
///
|
||||
/// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once
|
||||
|
||||
@@ -125,7 +125,7 @@ fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
|
||||
// directory is raised on its own and none of them is ever dropped — so
|
||||
// this is an add like any other, and the widen's own file diff is what
|
||||
// stops the overlap being read twice
|
||||
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
|
||||
// (`state::tests::widen::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
|
||||
let ip = PathBuf::from("/w");
|
||||
assert_eq!(
|
||||
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
|
||||
|
||||
@@ -135,6 +135,27 @@ fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
|
||||
assert!(session.shown().is_empty(), "a clean config says nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_inside_a_nested_block_lays_out_only_that_block() {
|
||||
// The owner's report (TODO §66.2): a `case` selected inside an `always`
|
||||
// in a four-space file. Only the `case` moves, and it stays where it
|
||||
// starts; the statement after it and the parent keep their bytes.
|
||||
let tree = Tree::new("rangesnested");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let text = "module m;\n always @* begin\n case (s)\n 0: y=a;\n endcase\n z = 1;\n end\nendmodule\n";
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
|
||||
let one = range_result(&mut session, &uri, json_range(2, 0, 5, 0));
|
||||
assert_eq!(
|
||||
one[0]["newText"],
|
||||
"module m;\n always @* begin\n case (s)\n 0: y = a;\n endcase\n z = 1;\n end\nendmodule\n",
|
||||
"{one:#?}"
|
||||
);
|
||||
// The multi-range method gives the same answer for the same selection.
|
||||
assert_eq!(ranges_result(&mut session, &uri, vec![json_range(2, 0, 5, 0)]), one);
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_range_through_the_new_method_answers_what_the_old_method_answers() {
|
||||
// The two requests are the same engine, and a client must never have
|
||||
@@ -250,9 +271,11 @@ fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
|
||||
// user cannot type past would arrive on every semicolon.
|
||||
let tree = Tree::new("ontypequiet");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
|
||||
// The error sits on the keystroke's own line: since selection formatting
|
||||
// (TODO §66.2) an error on *another* line no longer refuses the request.
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a = ;\n");
|
||||
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 13), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
|
||||
// ...and the whole-document request on the same buffer still does say
|
||||
// something, so the silence is this path's decision and not a
|
||||
|
||||
@@ -0,0 +1,691 @@
|
||||
//! Call hierarchy from wherever the cursor is, and for functions and tasks
|
||||
//! (`docs/features/call-hierarchy-everywhere/README.md`), driven through the
|
||||
//! real dispatch.
|
||||
//!
|
||||
//! The fixture is a small design: a package of functions (one recursive), a
|
||||
//! module that imports it and calls through a function, a task and an
|
||||
//! `always` block, a top that instantiates that module and calls the package
|
||||
//! with a scoped name, and a class whose methods call each other through
|
||||
//! `this.` and through a handle.
|
||||
|
||||
use lsp_types::request::{CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls};
|
||||
use lsp_types::{CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall};
|
||||
|
||||
use super::*;
|
||||
|
||||
const PKG: &str = "\
|
||||
package util_pkg;
|
||||
function automatic int add1(int a);
|
||||
return a + 1;
|
||||
endfunction : add1
|
||||
|
||||
function automatic int fact(int n);
|
||||
if (n <= 1) return 1;
|
||||
return n * fact(n - 1);
|
||||
endfunction
|
||||
endpackage
|
||||
";
|
||||
|
||||
const CORE: &str = "\
|
||||
module core (input logic clk, output int q);
|
||||
import util_pkg::*;
|
||||
int r;
|
||||
|
||||
function automatic int twice(int a);
|
||||
twice = add1(a) + add1(a);
|
||||
endfunction
|
||||
|
||||
task automatic kick(input int v);
|
||||
r = twice(v);
|
||||
$display(\"%0d\", v);
|
||||
endtask
|
||||
|
||||
always_ff @(posedge clk) begin
|
||||
q <= twice(r);
|
||||
end
|
||||
|
||||
initial kick(3);
|
||||
endmodule
|
||||
";
|
||||
|
||||
const TOP: &str = "\
|
||||
// the top of the design
|
||||
module top;
|
||||
logic clk;
|
||||
int q;
|
||||
core u_core (.clk(clk), .q(q));
|
||||
int z = util_pkg::add1(2);
|
||||
endmodule
|
||||
";
|
||||
|
||||
const CLS: &str = "\
|
||||
class counter;
|
||||
int n;
|
||||
extern function void reset();
|
||||
function void bump();
|
||||
n++;
|
||||
endfunction
|
||||
function void bump_twice();
|
||||
bump();
|
||||
this.bump();
|
||||
endfunction
|
||||
task run();
|
||||
counter h;
|
||||
h = new;
|
||||
h.bump();
|
||||
endtask
|
||||
endclass
|
||||
|
||||
class fancy extends counter;
|
||||
function void bump_more();
|
||||
super.bump();
|
||||
endfunction
|
||||
endclass
|
||||
|
||||
function void counter::reset();
|
||||
bump();
|
||||
endfunction
|
||||
";
|
||||
|
||||
/// The design on disk, a wide session over it, `core.sv` open.
|
||||
fn design(name: &str) -> (Tree, Session, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("util_pkg.sv", PKG);
|
||||
tree.write("core.sv", CORE);
|
||||
tree.write("top.sv", TOP);
|
||||
tree.write("cls.sv", CLS);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("core.sv"), CORE);
|
||||
session.drain();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
/// The LSP position of the `nth` occurrence of `needle` in `text`, `skip`
|
||||
/// bytes in.
|
||||
fn pos(text: &str, needle: &str, nth: usize, skip: usize) -> Value {
|
||||
let mut at = text.find(needle).expect("needle");
|
||||
for _ in 0..nth {
|
||||
at = text[at + 1..].find(needle).expect("nth needle") + at + 1;
|
||||
}
|
||||
let at = at + skip;
|
||||
let line = text[..at].matches('\n').count();
|
||||
let character = at - text[..at].rfind('\n').map_or(0, |nl| nl + 1);
|
||||
serde_json::json!({ "line": line, "character": character })
|
||||
}
|
||||
|
||||
/// `prepareCallHierarchy` at a position: `None` for a `null` answer.
|
||||
fn prepare(session: &mut Session, uri: &Uri, position: Value) -> Option<Vec<CallHierarchyItem>> {
|
||||
let result = session.result(
|
||||
CallHierarchyPrepare::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "position": position }),
|
||||
);
|
||||
serde_json::from_value(result).expect("items or null")
|
||||
}
|
||||
|
||||
/// The one item prepared at a position.
|
||||
fn one(session: &mut Session, uri: &Uri, position: Value) -> CallHierarchyItem {
|
||||
let items = prepare(session, uri, position).expect("an item");
|
||||
assert_eq!(items.len(), 1, "{items:#?}");
|
||||
items.into_iter().next().expect("one")
|
||||
}
|
||||
|
||||
fn incoming(session: &mut Session, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
|
||||
let result =
|
||||
session.result(CallHierarchyIncomingCalls::METHOD, serde_json::json!({ "item": item }));
|
||||
serde_json::from_value(result).expect("incoming calls")
|
||||
}
|
||||
|
||||
fn outgoing(session: &mut Session, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
|
||||
let result =
|
||||
session.result(CallHierarchyOutgoingCalls::METHOD, serde_json::json!({ "item": item }));
|
||||
serde_json::from_value(result).expect("outgoing calls")
|
||||
}
|
||||
|
||||
/// An item as `(name, file name, selection line)`.
|
||||
fn shape(item: &CallHierarchyItem) -> (String, String, u32) {
|
||||
let file = item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string();
|
||||
(item.name.clone(), file, item.selection_range.start.line)
|
||||
}
|
||||
|
||||
/// Each incoming call as `(caller name, caller file, lines of its ranges)`.
|
||||
fn callers(calls: &[CallHierarchyIncomingCall]) -> Vec<(String, String, Vec<u32>)> {
|
||||
calls
|
||||
.iter()
|
||||
.map(|call| {
|
||||
let (name, file, _) = shape(&call.from);
|
||||
(name, file, call.from_ranges.iter().map(|r| r.start.line).collect())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each outgoing call as `(callee name, callee file, lines of its ranges)`.
|
||||
fn callees(calls: &[CallHierarchyOutgoingCall]) -> Vec<(String, String, Vec<u32>)> {
|
||||
calls
|
||||
.iter()
|
||||
.map(|call| {
|
||||
let (name, file, _) = shape(&call.to);
|
||||
(name, file, call.from_ranges.iter().map(|r| r.start.line).collect())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn s(text: &str) -> String {
|
||||
text.to_string()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// prepare, every position
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_instance_name_prepares_the_instantiated_module() {
|
||||
let (tree, mut session, _) = design("hev_instance");
|
||||
let top = session.open(&tree.path.join("top.sv"), TOP);
|
||||
let item = one(&mut session, &top, pos(TOP, "u_core", 0, 2));
|
||||
assert_eq!(shape(&item), (s("core"), s("core.sv"), 0));
|
||||
assert_eq!(item.kind, lsp_types::SymbolKind::MODULE);
|
||||
assert!(item.data.is_none(), "a module item is the M11 item, unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_declaration_a_call_and_its_end_label_prepare_the_function() {
|
||||
let (tree, mut session, core) = design("hev_function");
|
||||
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
|
||||
let declared = one(&mut session, &pkg, pos(PKG, "add1(int", 0, 1));
|
||||
let labelled = one(&mut session, &pkg, pos(PKG, ": add1", 0, 3));
|
||||
let called = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
|
||||
for item in [&declared, &labelled, &called] {
|
||||
assert_eq!(shape(item), (s("add1"), s("util_pkg.sv"), 1));
|
||||
assert_eq!(item.kind, lsp_types::SymbolKind::FUNCTION);
|
||||
assert_eq!(item.detail.as_deref(), Some("util_pkg"));
|
||||
let data = item.data.as_ref().expect("data");
|
||||
assert_eq!(data["kind"], "function");
|
||||
assert_eq!(data["name"], "add1");
|
||||
assert!(data["offset"].is_u64(), "{data}");
|
||||
}
|
||||
assert_eq!(declared, called, "one item, wherever it was prepared from");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_just_past_a_call_name_prepares_the_function() {
|
||||
let (_tree, mut session, core) = design("hev_caret");
|
||||
let item = one(&mut session, &core, pos(CORE, "twice(v)", 0, 5));
|
||||
assert_eq!(shape(&item), (s("twice"), s("core.sv"), 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_declaration_and_a_call_prepare_the_task() {
|
||||
let (_tree, mut session, core) = design("hev_task");
|
||||
for position in [pos(CORE, "kick(input", 0, 0), pos(CORE, "kick(3)", 0, 1)] {
|
||||
let item = one(&mut session, &core, position);
|
||||
assert_eq!(shape(&item), (s("kick"), s("core.sv"), 8));
|
||||
assert_eq!(item.data.as_ref().expect("data")["kind"], "task");
|
||||
assert_eq!(item.kind, lsp_types::SymbolKind::FUNCTION);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_a_function_or_task_body_prepares_it() {
|
||||
let (_tree, mut session, core) = design("hev_body");
|
||||
let in_task = one(&mut session, &core, pos(CORE, "$display", 0, 2));
|
||||
assert_eq!(shape(&in_task), (s("kick"), s("core.sv"), 8), "a system task names no item");
|
||||
let on_arg = one(&mut session, &core, pos(CORE, "v);", 0, 0));
|
||||
assert_eq!(shape(&on_arg).0, "kick", "a use of an argument");
|
||||
let on_keyword = one(&mut session, &core, pos(CORE, "endfunction", 0, 3));
|
||||
assert_eq!(shape(&on_keyword).0, "twice", "the closing keyword");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_a_module_body_prepares_the_module() {
|
||||
let (_tree, mut session, core) = design("hev_module");
|
||||
for (what, position) in [
|
||||
("a net declaration", pos(CORE, "int r", 0, 4)),
|
||||
("inside an always block", pos(CORE, "q <=", 0, 0)),
|
||||
("an import", pos(CORE, "import", 0, 2)),
|
||||
] {
|
||||
let item = one(&mut session, &core, position);
|
||||
assert_eq!(shape(&item), (s("core"), s("core.sv"), 0), "{what}");
|
||||
assert!(item.data.is_none(), "{what}: the module item, as M11 builds it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn where_nothing_encloses_the_cursor_prepare_is_null() {
|
||||
let (tree, mut session, _) = design("hev_null");
|
||||
let top = session.open(&tree.path.join("top.sv"), TOP);
|
||||
assert!(prepare(&mut session, &top, pos(TOP, "the top", 0, 0)).is_none(), "a file comment");
|
||||
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
|
||||
assert!(
|
||||
prepare(&mut session, &pkg, pos(PKG, "\n\n", 0, 1)).is_none(),
|
||||
"a package body outside its functions"
|
||||
);
|
||||
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||
assert!(
|
||||
prepare(&mut session, &cls, pos(CLS, "int n", 0, 4)).is_none(),
|
||||
"a class property: the call hierarchy has no class node to open"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_module_answers_are_unchanged() {
|
||||
let (tree, mut session, core) = design("hev_unchanged");
|
||||
let top = session.open(&tree.path.join("top.sv"), TOP);
|
||||
let declared = one(&mut session, &core, pos(CORE, "module core", 0, 7));
|
||||
let instantiated = one(&mut session, &top, pos(TOP, "core u_core", 0, 1));
|
||||
assert_eq!(declared, instantiated);
|
||||
assert!(declared.data.is_none());
|
||||
assert_eq!(callers(&incoming(&mut session, &declared)), [(s("top"), s("top.sv"), vec![4])]);
|
||||
assert!(outgoing(&mut session, &declared).is_empty(), "a module lists no function calls");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// incoming and outgoing for functions and tasks
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_function_called_from_a_task_and_an_always_block() {
|
||||
let (_tree, mut session, core) = design("hev_twice");
|
||||
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
|
||||
let calls = incoming(&mut session, &twice);
|
||||
assert_eq!(
|
||||
callers(&calls),
|
||||
[(s("core"), s("core.sv"), vec![14]), (s("kick"), s("core.sv"), vec![9])],
|
||||
"the task and the module of the always block; not `twice = …`, which is a result"
|
||||
);
|
||||
assert_eq!(calls[0].from.kind, lsp_types::SymbolKind::MODULE);
|
||||
assert!(calls[0].from.data.is_none(), "a module caller is the M11 item");
|
||||
assert_eq!(calls[1].from.data.as_ref().expect("data")["kind"], "task");
|
||||
let from = calls[1].from_ranges[0];
|
||||
assert_eq!((from.start.character, from.end.character), (8, 13), "the call's name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_called_from_an_initial_block_and_its_outgoing_calls() {
|
||||
let (_tree, mut session, core) = design("hev_kick");
|
||||
let kick = one(&mut session, &core, pos(CORE, "kick(input", 0, 0));
|
||||
assert_eq!(callers(&incoming(&mut session, &kick)), [(s("core"), s("core.sv"), vec![17])]);
|
||||
assert_eq!(
|
||||
callees(&outgoing(&mut session, &kick)),
|
||||
[(s("twice"), s("core.sv"), vec![9])],
|
||||
"`$display` is a system task and is skipped"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_calls_resolve_into_another_file_grouped_by_callee() {
|
||||
let (_tree, mut session, core) = design("hev_out");
|
||||
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
|
||||
let calls = outgoing(&mut session, &twice);
|
||||
assert_eq!(callees(&calls), [(s("add1"), s("util_pkg.sv"), vec![5, 5])]);
|
||||
assert_eq!(calls[0].to.data.as_ref().expect("data")["kind"], "function");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_function_is_called_from_modules_in_other_files() {
|
||||
// `util_pkg.sv` and `top.sv` are closed: the item is prepared from the
|
||||
// call in `core.sv`, and the callers are found the way references are.
|
||||
let (_tree, mut session, core) = design("hev_cross");
|
||||
let add1 = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
|
||||
let calls = incoming(&mut session, &add1);
|
||||
assert_eq!(
|
||||
callers(&calls),
|
||||
[(s("twice"), s("core.sv"), vec![5, 5]), (s("top"), s("top.sv"), vec![5])],
|
||||
"a function caller in an open file, a module caller in a closed one; the end label is no call"
|
||||
);
|
||||
let top = &calls[1].from;
|
||||
let instantiated = outgoing(&mut session, top);
|
||||
assert_eq!(
|
||||
callees(&instantiated),
|
||||
[(s("core"), s("core.sv"), vec![4])],
|
||||
"expanding a module caller walks the design, one level down"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cross_file_answer_matches_references() {
|
||||
let (_tree, mut session, core) = design("hev_refs");
|
||||
let add1 = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
|
||||
let mut from_calls: Vec<(String, u32, u32)> = incoming(&mut session, &add1)
|
||||
.iter()
|
||||
.flat_map(|call| {
|
||||
let file = shape(&call.from).1;
|
||||
call.from_ranges.iter().map(move |r| (file.clone(), r.start.line, r.start.character))
|
||||
})
|
||||
.collect();
|
||||
let references = session.result(
|
||||
References::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": core },
|
||||
"position": pos(CORE, "add1(a)", 0, 0),
|
||||
"context": { "includeDeclaration": false },
|
||||
}),
|
||||
);
|
||||
let mut from_refs: Vec<(String, u32, u32)> = references
|
||||
.as_array()
|
||||
.expect("locations")
|
||||
.iter()
|
||||
.map(|loc| {
|
||||
let file =
|
||||
loc["uri"].as_str().unwrap_or("").rsplit('/').next().unwrap_or("").to_string();
|
||||
let start = &loc["range"]["start"];
|
||||
(
|
||||
file,
|
||||
start["line"].as_u64().unwrap_or(0) as u32,
|
||||
start["character"].as_u64().unwrap_or(0) as u32,
|
||||
)
|
||||
})
|
||||
.filter(|(file, line, _)| !(file == "util_pkg.sv" && *line == 3))
|
||||
.collect();
|
||||
from_calls.sort();
|
||||
from_refs.sort();
|
||||
assert_eq!(from_calls, from_refs, "every reference but the end label is a call");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recursive_function_is_its_own_caller_and_callee() {
|
||||
let (tree, mut session, _) = design("hev_fact");
|
||||
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
|
||||
let fact = one(&mut session, &pkg, pos(PKG, "fact(int", 0, 0));
|
||||
assert_eq!(callers(&incoming(&mut session, &fact)), [(s("fact"), s("util_pkg.sv"), vec![7])]);
|
||||
assert_eq!(callees(&outgoing(&mut session, &fact)), [(s("fact"), s("util_pkg.sv"), vec![7])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn class_methods_called_through_this_a_handle_and_super() {
|
||||
let (tree, mut session, _) = design("hev_class");
|
||||
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||
let bump = one(&mut session, &cls, pos(CLS, "bump();\n n++", 0, 0));
|
||||
assert_eq!(bump.kind, lsp_types::SymbolKind::METHOD);
|
||||
assert_eq!(bump.detail.as_deref(), Some("counter"));
|
||||
assert_eq!(
|
||||
callers(&incoming(&mut session, &bump)),
|
||||
[
|
||||
(s("reset"), s("cls.sv"), vec![24]),
|
||||
(s("bump_twice"), s("cls.sv"), vec![7, 8]),
|
||||
(s("run"), s("cls.sv"), vec![13]),
|
||||
(s("bump_more"), s("cls.sv"), vec![19]),
|
||||
],
|
||||
"a bare call and `this.`; a handle; the out-of-body definition's body, \
|
||||
credited to its prototype; `super.` from a subclass"
|
||||
);
|
||||
let twice = one(&mut session, &cls, pos(CLS, "bump_twice", 0, 0));
|
||||
assert_eq!(callees(&outgoing(&mut session, &twice)), [(s("bump"), s("cls.sv"), vec![7, 8])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_body_definition_prepares_and_expands_its_prototype() {
|
||||
let (tree, mut session, _) = design("hev_extern");
|
||||
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||
let inside = one(&mut session, &cls, pos(CLS, "bump();\nendfunction", 0, 0));
|
||||
assert_eq!(shape(&inside).0, "bump", "on the call");
|
||||
let body = one(&mut session, &cls, pos(CLS, "endfunction\n", 3, 3));
|
||||
assert_eq!(shape(&body), (s("reset"), s("cls.sv"), 2), "the prototype");
|
||||
assert_eq!(callees(&outgoing(&mut session, &body)), [(s("bump"), s("cls.sv"), vec![24])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_super_method_call_resolves_through_the_workspace_overlay() {
|
||||
// `super.bump()` inside `fancy` is answered by the workspace overlay
|
||||
// (the base class is a file-scope declaration the index holds), not by
|
||||
// the file's own symbol table — both directions must read both layers.
|
||||
let (tree, mut session, _) = design("hev_super");
|
||||
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||
let more = one(&mut session, &cls, pos(CLS, "bump_more", 0, 0));
|
||||
assert_eq!(callees(&outgoing(&mut session, &more)), [(s("bump"), s("cls.sv"), vec![19])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_method_called_through_a_handle_from_another_file() {
|
||||
let pkg = "\
|
||||
package env_pkg;
|
||||
class driver;
|
||||
task drive();
|
||||
endtask
|
||||
endclass
|
||||
endpackage
|
||||
";
|
||||
let tb = "\
|
||||
module tb;
|
||||
import env_pkg::*;
|
||||
driver d;
|
||||
initial begin
|
||||
d = new;
|
||||
d.drive();
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let tree = Tree::new("hev_handle");
|
||||
tree.write("env_pkg.sv", pkg);
|
||||
tree.write("tb.sv", tb);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("env_pkg.sv"), pkg);
|
||||
session.drain();
|
||||
let drive = one(&mut session, &uri, pos(pkg, "drive()", 0, 0));
|
||||
assert_eq!(drive.kind, lsp_types::SymbolKind::METHOD);
|
||||
assert_eq!(drive.detail.as_deref(), Some("driver"));
|
||||
assert_eq!(callers(&incoming(&mut session, &drive)), [(s("tb"), s("tb.sv"), vec![5])]);
|
||||
let tb_uri = session.open(&tree.path.join("tb.sv"), tb);
|
||||
let from_call = one(&mut session, &tb_uri, pos(tb, "drive()", 0, 1));
|
||||
assert_eq!(from_call, drive, "the call through the handle prepares the method");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_scope_function_answers_in_its_own_file_only() {
|
||||
// A `$unit` function works like any other in the file that declares it.
|
||||
// A call from *another* file is a documented limit: the semantic layer
|
||||
// resolves an unqualified value-position name through imports only, so
|
||||
// `ufn(1)` in `user.sv` names nothing and the cursor there falls back to
|
||||
// the enclosing module (README, Handshakes).
|
||||
let unit = "\
|
||||
function automatic int ufn(int a);
|
||||
return a;
|
||||
endfunction
|
||||
module local_user;
|
||||
int j = ufn(2);
|
||||
endmodule
|
||||
";
|
||||
let user = "module user;\n int k = ufn(1);\nendmodule\n";
|
||||
let tree = Tree::new("hev_unit");
|
||||
tree.write("unit.sv", unit);
|
||||
tree.write("user.sv", user);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("unit.sv"), unit);
|
||||
session.drain();
|
||||
let ufn = one(&mut session, &uri, pos(unit, "ufn", 0, 0));
|
||||
assert_eq!(shape(&ufn), (s("ufn"), s("unit.sv"), 0));
|
||||
assert_eq!(ufn.detail, None, "declared at `$unit`, in no container");
|
||||
assert_eq!(one(&mut session, &uri, pos(unit, "ufn(2)", 0, 0)), ufn);
|
||||
assert_eq!(
|
||||
callers(&incoming(&mut session, &ufn)),
|
||||
[(s("local_user"), s("unit.sv"), vec![4])],
|
||||
"the call in `user.sv` is not resolved, so it is not listed"
|
||||
);
|
||||
let user_uri = session.open(&tree.path.join("user.sv"), user);
|
||||
let there = one(&mut session, &user_uri, pos(user, "ufn", 0, 0));
|
||||
assert_eq!(shape(&there).0, "user", "the limit: the enclosing module, not `ufn`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_since_the_item_was_built_is_followed() {
|
||||
// The item's recorded offset no longer matches once a line is added
|
||||
// above the function; the selection range is stale too, so the item is
|
||||
// re-found by name — `twice` is the only one, in its container `core`.
|
||||
let (tree, mut session, core) = design("hev_stale");
|
||||
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
|
||||
let edited = format!("// a new first line\n{CORE}");
|
||||
session.open(&tree.path.join("core.sv"), &edited);
|
||||
let calls = incoming(&mut session, &twice);
|
||||
assert_eq!(
|
||||
callers(&calls),
|
||||
[(s("core"), s("core.sv"), vec![15]), (s("kick"), s("core.sv"), vec![10])]
|
||||
);
|
||||
}
|
||||
|
||||
/// QA finding 3: two `log2`s in one file. After an edit moves both, the old
|
||||
/// item for `mb`'s answers `mb`'s callers (its `detail` breaks the tie); once
|
||||
/// `mb`'s is renamed away it answers nothing — never `ma`'s.
|
||||
#[test]
|
||||
fn a_stale_item_never_answers_for_a_same_named_function_elsewhere() {
|
||||
let text = "\
|
||||
module ma;
|
||||
function int log2(int v); return v; endfunction
|
||||
int a = log2(1);
|
||||
endmodule
|
||||
module mb;
|
||||
function int log2(int v); return v; endfunction
|
||||
int b = log2(2);
|
||||
int c = log2(3);
|
||||
endmodule
|
||||
";
|
||||
let tree = Tree::new("hev_ma_mb");
|
||||
tree.write("two.sv", text);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let path = tree.path.join("two.sv");
|
||||
let uri = session.open(&path, text);
|
||||
session.drain();
|
||||
let in_mb = one(&mut session, &uri, pos(text, "log2(int", 1, 0));
|
||||
assert_eq!(in_mb.detail.as_deref(), Some("mb"));
|
||||
let moved = format!("// one\n// two\n// three\n{text}");
|
||||
session.open(&path, &moved);
|
||||
assert_eq!(
|
||||
callers(&incoming(&mut session, &in_mb)),
|
||||
[(s("mb"), s("two.sv"), vec![9, 10])],
|
||||
"the tie broken by the container"
|
||||
);
|
||||
let renamed = moved.replace(
|
||||
"log2(int v); return v; endfunction\n int b",
|
||||
"lg(int v); return v; endfunction\n int b",
|
||||
);
|
||||
session.open(&path, &renamed);
|
||||
assert!(incoming(&mut session, &in_mb).is_empty(), "never `ma`'s `log2`");
|
||||
assert!(outgoing(&mut session, &in_mb).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_classic_clog2_is_not_its_own_caller() {
|
||||
// QA finding 1: `clog2 = clog2 + 1;` reads the result variable.
|
||||
let text = "\
|
||||
module lg (output integer o);
|
||||
function integer clog2(input integer v);
|
||||
begin
|
||||
clog2 = 0;
|
||||
while (v > 1) begin
|
||||
clog2 = clog2 + 1;
|
||||
v = v >> 1;
|
||||
end
|
||||
end
|
||||
endfunction
|
||||
initial o = clog2(16);
|
||||
endmodule
|
||||
";
|
||||
let tree = Tree::new("hev_clog2");
|
||||
tree.write("lg.sv", text);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("lg.sv"), text);
|
||||
session.drain();
|
||||
let clog2 = one(&mut session, &uri, pos(text, "clog2(input", 0, 0));
|
||||
assert_eq!(callers(&incoming(&mut session, &clog2)), [(s("lg"), s("lg.sv"), vec![10])]);
|
||||
assert!(outgoing(&mut session, &clog2).is_empty(), "no false recursion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untitled_buffer_answers_from_itself() {
|
||||
let text = "module m;\n function int f(); return 1; endfunction\n int x = f();\nendmodule\n";
|
||||
let tree = Tree::new("hev_untitled");
|
||||
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": text }
|
||||
}),
|
||||
);
|
||||
session.drain();
|
||||
let f = one(&mut session, &uri, pos(text, "f()", 1, 0));
|
||||
assert_eq!(f.uri, uri);
|
||||
assert_eq!(callers(&incoming(&mut session, &f)), [(s("m"), s("untitled:Untitled-1"), vec![2])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_functions_of_one_name_are_told_apart_by_data() {
|
||||
let text = "\
|
||||
module a;
|
||||
function int f(); return 1; endfunction
|
||||
initial $display(f());
|
||||
endmodule
|
||||
|
||||
module b;
|
||||
function int f(); return 2; endfunction
|
||||
int x = f();
|
||||
int y = f();
|
||||
endmodule
|
||||
";
|
||||
let tree = Tree::new("hev_same_name");
|
||||
tree.write("two.sv", text);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("two.sv"), text);
|
||||
session.drain();
|
||||
let in_b = one(&mut session, &uri, pos(text, "f()", 2, 0));
|
||||
assert_eq!(shape(&in_b), (s("f"), s("two.sv"), 6), "the declaration in `b`");
|
||||
assert_eq!(callers(&incoming(&mut session, &in_b)), [(s("b"), s("two.sv"), vec![7, 8])]);
|
||||
let in_a = one(&mut session, &uri, pos(text, "f()", 0, 0));
|
||||
assert_eq!(callers(&incoming(&mut session, &in_a)), [(s("a"), s("two.sv"), vec![2])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_item_whose_data_is_not_ours_is_treated_as_a_module_item() {
|
||||
let (_tree, mut session, core) = design("hev_foreign");
|
||||
let mut item = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
|
||||
item.data = Some(serde_json::json!({ "kind": "rocket" }));
|
||||
assert!(incoming(&mut session, &item).is_empty(), "no module is called `twice`");
|
||||
assert!(outgoing(&mut session, &item).is_empty());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// type hierarchy inside a class body
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn prepare_type(session: &mut Session, uri: &Uri, position: Value) -> Vec<String> {
|
||||
let result = session.result(
|
||||
TypeHierarchyPrepare::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "position": position }),
|
||||
);
|
||||
match result.as_array() {
|
||||
Some(items) => {
|
||||
items.iter().map(|i| i["name"].as_str().unwrap_or("?").to_string()).collect()
|
||||
}
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_a_class_body_prepares_the_class_and_super_prepares_its_base() {
|
||||
let (tree, mut session, core) = design("hev_type");
|
||||
let cls = session.open(&tree.path.join("cls.sv"), CLS);
|
||||
assert_eq!(
|
||||
prepare_type(&mut session, &cls, pos(CLS, "int n", 0, 4)),
|
||||
["counter"],
|
||||
"a property"
|
||||
);
|
||||
assert_eq!(
|
||||
prepare_type(&mut session, &cls, pos(CLS, "n++", 0, 0)),
|
||||
["counter"],
|
||||
"a method body"
|
||||
);
|
||||
assert_eq!(
|
||||
prepare_type(&mut session, &cls, pos(CLS, "this.bump", 0, 1)),
|
||||
["counter"],
|
||||
"`this`"
|
||||
);
|
||||
assert_eq!(
|
||||
prepare_type(&mut session, &cls, pos(CLS, "super.bump", 0, 2)),
|
||||
["counter"],
|
||||
"`super`"
|
||||
);
|
||||
assert_eq!(
|
||||
prepare_type(&mut session, &cls, pos(CLS, "super.bump", 0, 7)),
|
||||
["fancy"],
|
||||
"the method name after `super.` is inside `fancy`"
|
||||
);
|
||||
assert!(prepare_type(&mut session, &core, pos(CORE, "int r", 0, 4)).is_empty(), "a module");
|
||||
}
|
||||
@@ -52,14 +52,20 @@ mod code_action;
|
||||
mod file_ops;
|
||||
mod folders;
|
||||
mod formatting;
|
||||
mod hierarchy_everywhere;
|
||||
mod hierarchy_reach;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod lint_snapshot;
|
||||
mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod qa_generate_label;
|
||||
mod qa_rename_implicit;
|
||||
mod references_scope;
|
||||
mod references_top_rooted;
|
||||
mod rename_generate_label;
|
||||
mod rename_implicit;
|
||||
mod rename_top_rooted_scope;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod scan_trace;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//! QA attacks on TODO §65.1 over the wire: `references` and `rename` through
|
||||
//! a block label with the other files closed, and the `member_key` spelling
|
||||
//! of a block that lives inside a function.
|
||||
//! `docs/features/generate-label-rename/README.md`, QA log 2026-09-30.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `(file name, line)` of every location in a `references` answer.
|
||||
fn places(found: &Value) -> Vec<(String, u64)> {
|
||||
let mut out: Vec<(String, u64)> = found
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let uri = l["uri"].as_str().unwrap_or("?");
|
||||
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
|
||||
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
fn position(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
|
||||
let row = text.lines().nth(line).expect("the line");
|
||||
let character = row.find(name).expect("the name on that line");
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
"context": { "includeDeclaration": true },
|
||||
})
|
||||
}
|
||||
|
||||
/// A module `ff` with a block `fb` holding `t`, and — in another file — a
|
||||
/// function `ff` with a named block `fb` holding its own `t`. The function's
|
||||
/// `t` is a local: nothing outside the function can name it, and the module's
|
||||
/// `t` is a different declaration.
|
||||
const MODULE_FF: &str = "module ff;\n if (1) begin : fb\n logic t;\n end\nendmodule\n";
|
||||
const USER: &str =
|
||||
"module user (output logic o);\n ff u_ff ();\n assign o = u_ff.fb.t;\nendmodule\n";
|
||||
const FUNC: &str = "module host;\n function automatic void ff();\n begin : fb\n logic t;\n t = 1'b0;\n end\n endfunction\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_function_local_in_a_named_block_is_never_mistaken_for_a_modules_block_member() {
|
||||
let tree = Tree::new("qa_genlabel_member_key");
|
||||
tree.write("ff.sv", MODULE_FF);
|
||||
tree.write("user.sv", USER);
|
||||
tree.write("host.sv", FUNC);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let host = session.open(&tree.path.join("host.sv"), FUNC);
|
||||
let found = places(&session.result(References::METHOD, position(&host, FUNC, 3, "t;")));
|
||||
assert_eq!(found, vec![("host.sv".to_string(), 3), ("host.sv".to_string(), 4)]);
|
||||
|
||||
let mut params = position(&host, FUNC, 3, "t;");
|
||||
params["newName"] = serde_json::json!("t2");
|
||||
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
assert_eq!(changes.len(), 1, "only host.sv: {answer:#}");
|
||||
}
|
||||
|
||||
/// Three files: the block's module, an intermediate module instantiating it,
|
||||
/// and a testbench naming a member through two instances and the block. Only
|
||||
/// the declaring file is open.
|
||||
const LEAF: &str = "module leaf;\n for (genvar i = 0; i < 2; i++) begin : g_l\n logic s;\n end : g_l\nendmodule\n";
|
||||
const MID: &str = "module mid;\n leaf u_leaf ();\nendmodule\n";
|
||||
const TB: &str = "module tbq (output logic o);\n mid u_mid ();\n assign o = u_mid.u_leaf.g_l[1].s;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_two_instance_path_through_a_block_is_renamed_with_every_other_file_closed() {
|
||||
let tree = Tree::new("qa_genlabel_two_hops");
|
||||
tree.write("leaf.sv", LEAF);
|
||||
tree.write("mid.sv", MID);
|
||||
tree.write("tbq.sv", TB);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let leaf = session.open(&tree.path.join("leaf.sv"), LEAF);
|
||||
let found = places(&session.result(References::METHOD, position(&leaf, LEAF, 1, "g_l")));
|
||||
let at = |f: &str, l| (f.to_string(), l);
|
||||
assert_eq!(found, vec![at("leaf.sv", 1), at("leaf.sv", 3), at("tbq.sv", 2)]);
|
||||
|
||||
let mut params = position(&leaf, LEAF, 2, "s;");
|
||||
params["newName"] = serde_json::json!("s_q");
|
||||
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
let tb = path_to_uri(&tree.path.join("tbq.sv")).expect("a uri");
|
||||
assert_eq!(changes.get(tb.as_str()).and_then(Value::as_array).map_or(0, Vec::len), 1);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! TODO §65.2 over the wire: `references` from a testbench answers within
|
||||
//! the active index scope, and within an equal file set it answers exactly
|
||||
//! what the whole-set engine (`vlog_refactor::find_references`) answers.
|
||||
//! `docs/features/references-fanout-pd-main/README.md`.
|
||||
//!
|
||||
//! The fixture is opentitan's shape in miniature: an IP block with `rtl/`
|
||||
//! and `dv/tb/`, and a generated top two directories away that instantiates
|
||||
//! the block with a multi-line `blk #( … ) u_blk (`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::*;
|
||||
|
||||
const BLK: &str = "module blk #(\n parameter int W = 1\n) (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n";
|
||||
const TB: &str = "module tb;\n logic clk, rst_n;\n blk #(\n .W ( 2 )\n ) dut (\n .clk_i ( clk ),\n .rst_ni ( rst_n )\n );\nendmodule\n";
|
||||
const PD_MAIN: &str = "module top_pd_main (\n input logic clk_main_i,\n input logic rst_main_ni\n);\n blk #(\n .W ( 4 )\n ) u_blk (\n // Clock and reset connections\n .clk_i ( clk_main_i ),\n .rst_ni ( rst_main_ni )\n );\nendmodule\n";
|
||||
|
||||
/// The three files, at their opentitan-shaped paths.
|
||||
fn fixture(tag: &str) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("ip/blk/rtl/blk.sv", BLK);
|
||||
tree.write("ip/blk/dv/tb/tb.sv", TB);
|
||||
tree.write("top/rtl/autogen/top_pd_main.sv", PD_MAIN);
|
||||
tree
|
||||
}
|
||||
|
||||
/// `(path relative to the root, line)` of every location in an answer.
|
||||
fn answered(root: &Path, found: &Value) -> Vec<(String, u64)> {
|
||||
let mut out: Vec<(String, u64)> = found
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let uri = l["uri"].as_str().unwrap_or("?");
|
||||
let path =
|
||||
crate::uri::uri_to_path(&Uri::from_str(uri).expect("a uri")).expect("a path");
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).display().to_string();
|
||||
(rel, l["range"]["start"]["line"].as_u64().unwrap_or(0))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// What the whole-set engine answers over `files`, as [`answered`] spells it.
|
||||
fn engine(
|
||||
root: &Path,
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Vec<(String, u64)> {
|
||||
let found =
|
||||
vlog_refactor::find_references(files, file, offset, true).expect("the engine answers");
|
||||
let mut out: Vec<(String, u64)> = found
|
||||
.into_iter()
|
||||
.map(|(path, range)| {
|
||||
let text = &files.iter().find(|(p, _)| *p == path).expect("a read file").1;
|
||||
let line = text[..range.start as usize].matches('\n').count() as u64;
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).display().to_string();
|
||||
(rel, line)
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// Every file under the tree — the set the MCP's `references` hands the engine.
|
||||
fn every_file(tree: &Tree) -> Vec<(PathBuf, String)> {
|
||||
["ip/blk/rtl/blk.sv", "ip/blk/dv/tb/tb.sv", "top/rtl/autogen/top_pd_main.sv"]
|
||||
.iter()
|
||||
.map(|rel| {
|
||||
let path = tree.path.join(rel);
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
(path, text)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A references request at the first `needle` on line `line` of `text`, and
|
||||
/// the byte offset the engine is asked at.
|
||||
fn at(uri: &Uri, text: &str, line: usize, needle: &str) -> (Value, u32) {
|
||||
let row = text.lines().nth(line).expect("the line");
|
||||
let character = row.find(needle).expect("the needle on that line");
|
||||
let before: usize = text.lines().take(line).map(|l| l.len() + 1).sum();
|
||||
let params = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
"context": { "includeDeclaration": true },
|
||||
});
|
||||
(params, (before + character) as u32)
|
||||
}
|
||||
|
||||
/// The four positions the §65.2 checklist names: the module name and one of
|
||||
/// its ports, each from its declaration and from a use.
|
||||
fn positions(tree: &Tree) -> [(PathBuf, &'static str, usize, &'static str); 4] {
|
||||
let blk = tree.path.join("ip/blk/rtl/blk.sv");
|
||||
let tb = tree.path.join("ip/blk/dv/tb/tb.sv");
|
||||
[
|
||||
(blk.clone(), BLK, 0, "blk"),
|
||||
(tb.clone(), TB, 2, "blk"),
|
||||
(blk, BLK, 3, "clk_i"),
|
||||
(tb, TB, 5, "clk_i"),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_the_whole_workspace_references_equal_the_whole_set_engine() {
|
||||
let tree = fixture("refscope_wide");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let all = every_file(&tree);
|
||||
for (path, text, line, needle) in positions(&tree) {
|
||||
let uri = session.open(&path, text);
|
||||
let (params, offset) = at(&uri, text, line, needle);
|
||||
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
|
||||
let whole = engine(&tree.path, &all, &path, offset);
|
||||
assert_eq!(lsp, whole, "{needle} at {}:{line}", path.display());
|
||||
assert!(
|
||||
lsp.iter().any(|(file, _)| file.ends_with("top_pd_main.sv")),
|
||||
"the generated top is listed: {lsp:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cause, pinned: under the shipped folder scope a testbench in
|
||||
/// `ip/blk/dv/tb/` raises to `ip/blk/`, the generated top is not in the
|
||||
/// index, and `references` answers what the engine answers over the scope —
|
||||
/// not over every file. Opening the top widens the scope, and the answer
|
||||
/// becomes the whole set's.
|
||||
#[test]
|
||||
fn under_the_folder_scope_references_equal_the_engine_over_the_scope() {
|
||||
let tree = fixture("refscope_folder");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let top = tree.path.join("top/rtl/autogen/top_pd_main.sv");
|
||||
for (path, text, line, needle) in positions(&tree) {
|
||||
let uri = session.open(&path, text);
|
||||
let in_index = session.server.workspace.index().files().contains(&top);
|
||||
assert!(!in_index, "the top is outside the folder scope");
|
||||
let (params, offset) = at(&uri, text, line, needle);
|
||||
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
|
||||
let scoped = engine(&tree.path, &session.server.workspace.sources(), &path, offset);
|
||||
assert_eq!(lsp, scoped, "{needle} at {}:{line}", path.display());
|
||||
assert!(!lsp.iter().any(|(file, _)| file.ends_with("top_pd_main.sv")), "{lsp:?}");
|
||||
}
|
||||
|
||||
let _ = session.open(&top, PD_MAIN);
|
||||
let all = every_file(&tree);
|
||||
for (path, text, line, needle) in positions(&tree) {
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let (params, offset) = at(&uri, text, line, needle);
|
||||
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
|
||||
assert_eq!(lsp, engine(&tree.path, &all, &path, offset), "{needle}, widened");
|
||||
}
|
||||
}
|
||||
|
||||
/// `rename`'s fan-out has no gap of its own: over the whole workspace a
|
||||
/// module rename from the testbench edits the generated top too.
|
||||
#[test]
|
||||
fn over_the_whole_workspace_a_module_rename_edits_the_generated_top() {
|
||||
let tree = fixture("refscope_rename");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let tb = tree.path.join("ip/blk/dv/tb/tb.sv");
|
||||
let uri = session.open(&tb, TB);
|
||||
let (mut params, _) = at(&uri, TB, 2, "blk");
|
||||
params["newName"] = serde_json::json!("blk2");
|
||||
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
let top = path_to_uri(&tree.path.join("top/rtl/autogen/top_pd_main.sv")).expect("uri");
|
||||
assert_eq!(changes.get(top.as_str()).and_then(Value::as_array).map_or(0, Vec::len), 1);
|
||||
assert_eq!(changes.len(), 3, "blk.sv, tb.sv and the top: {answer:#}");
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! A hierarchical path rooted at a top module another file declares, over
|
||||
//! the wire (TODO §65.4): `references` at a member of the DUT lists every
|
||||
//! segment of `tb.dut.g_sw[0].buf_q` in a DV file, whichever side is open,
|
||||
//! and `rename` rewrites them. `docs/features/top-rooted-paths/README.md`.
|
||||
|
||||
use super::*;
|
||||
|
||||
const DUT: &str = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n";
|
||||
const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n";
|
||||
const PROBE: &str = "module probe (output logic o);\n assign o = tb.dut.g_sw[0].buf_q;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n";
|
||||
|
||||
/// The LSP position of the first `name` on 0-based `line` of `text`.
|
||||
fn at(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
|
||||
let row = text.lines().nth(line).expect("the line");
|
||||
let character = row.find(name).expect("the name on that line");
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
})
|
||||
}
|
||||
|
||||
/// `(file name, 0-based line)` of every location in a `references` answer.
|
||||
fn places(found: &Value) -> Vec<(String, u64)> {
|
||||
let mut out: Vec<(String, u64)> = found
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let uri = l["uri"].as_str().unwrap_or("?");
|
||||
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
|
||||
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The three-file tree with the named files open; the uris of `dut_a.sv`
|
||||
/// and `probe.sv`.
|
||||
fn session_with(tag: &str, open: &[&str]) -> (Tree, Session, Uri, Uri) {
|
||||
let tree = Tree::new(tag);
|
||||
let files = [("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)];
|
||||
for (name, text) in files {
|
||||
tree.write(name, text);
|
||||
}
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
for (name, text) in files.into_iter().filter(|(name, _)| open.contains(name)) {
|
||||
session.open(&tree.path.join(name), text);
|
||||
}
|
||||
let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri");
|
||||
let (dut, probe) = (uri("dut_a.sv"), uri("probe.sv"));
|
||||
(tree, session, dut, probe)
|
||||
}
|
||||
|
||||
fn expected() -> Vec<(String, u64)> {
|
||||
let place = |file: &str, line| (file.to_string(), line);
|
||||
vec![place("dut_a.sv", 2), place("probe.sv", 1), place("probe.sv", 2)]
|
||||
}
|
||||
|
||||
fn references(session: &mut Session, mut params: Value) -> Vec<(String, u64)> {
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
||||
places(&session.result(References::METHOD, params))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_at_the_member_list_the_path_in_the_closed_dv_file() {
|
||||
let (_tree, mut session, dut, _) = session_with("toproot_refs_decl", &["dut_a.sv"]);
|
||||
assert_eq!(references(&mut session, at(&dut, DUT, 2, "buf_q")), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_at_the_paths_segment_reach_the_closed_declaration() {
|
||||
let (_tree, mut session, _, probe) = session_with("toproot_refs_path", &["probe.sv"]);
|
||||
assert_eq!(references(&mut session, at(&probe, PROBE, 2, "buf_q")), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_with_both_files_open_are_the_same_set() {
|
||||
let (_tree, mut session, _, probe) =
|
||||
session_with("toproot_refs_both", &["dut_a.sv", "probe.sv"]);
|
||||
assert_eq!(references(&mut session, at(&probe, PROBE, 1, "buf_q")), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_at_the_root_list_every_path_it_heads() {
|
||||
let (_tree, mut session, _, probe) = session_with("toproot_refs_root", &["probe.sv"]);
|
||||
let found = references(&mut session, at(&probe, PROBE, 1, "tb"));
|
||||
let tb = ("tb.sv".to_string(), 0);
|
||||
assert_eq!(found, vec![("probe.sv".to_string(), 1), ("probe.sv".to_string(), 2), tb]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_at_the_block_label_rewrites_the_paths_in_the_dv_file() {
|
||||
let (tree, mut session, dut, _) = session_with("toproot_rename", &["dut_a.sv"]);
|
||||
let mut params = at(&dut, DUT, 1, "g_sw");
|
||||
params["newName"] = serde_json::json!("g_hw");
|
||||
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
let count = |path: &str| {
|
||||
let uri = path_to_uri(&tree.path.join(path)).expect("a uri");
|
||||
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
|
||||
};
|
||||
assert_eq!((count("dut_a.sv"), count("probe.sv"), count("tb.sv")), (1, 2, 0), "{answer:#}");
|
||||
let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten());
|
||||
assert!(texts.all(|e| e["newText"] == "g_hw"), "{answer:#}");
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! A generate block label over the wire (TODO §65.1, topo §2.9-43).
|
||||
//!
|
||||
//! `references`, `prepareRename` and `rename` at a block label reach the
|
||||
//! closing label and every path through the block — the same-file
|
||||
//! `g_lane[0].sig` and another file's `u_x.g_lane[1].sig` — through the
|
||||
//! engine and the index's hierarchical surface, whether the other file is
|
||||
//! open or closed.
|
||||
|
||||
use super::*;
|
||||
|
||||
const SUB: &str = "module sub (input logic clk, output logic o);\n for (genvar i = 0; i < 2; i++) begin : g_lane\n logic sig;\n assign sig = clk;\n end : g_lane\n assign o = g_lane[0].sig;\nendmodule\n";
|
||||
const TOP: &str = "module top (input logic clk, output logic o);\n sub u_x (.clk, .o());\n assign o = u_x.g_lane[1].sig;\nendmodule\n";
|
||||
|
||||
/// The LSP position of the `g_lane` on 0-based `line` of `text`.
|
||||
fn at_label(uri: &Uri, text: &str, line: usize) -> Value {
|
||||
let row = text.lines().nth(line).expect("the line");
|
||||
let character = row.find("g_lane").expect("the label on that line");
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
})
|
||||
}
|
||||
|
||||
/// `(file name, line)` of every location in a `references` answer.
|
||||
fn places(found: &Value) -> Vec<(String, u64)> {
|
||||
let mut out: Vec<(String, u64)> = found
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let uri = l["uri"].as_str().unwrap_or("?");
|
||||
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
|
||||
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The two-file tree, with `sub.sv` and/or `top.sv` open.
|
||||
fn session_with(tag: &str, open_sub: bool, open_top: bool) -> (Tree, Session, Uri, Uri) {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri");
|
||||
let (sub, top) = (uri("sub.sv"), uri("top.sv"));
|
||||
if open_sub {
|
||||
session.open(&tree.path.join("sub.sv"), SUB);
|
||||
}
|
||||
if open_top {
|
||||
session.open(&tree.path.join("top.sv"), TOP);
|
||||
}
|
||||
(tree, session, sub, top)
|
||||
}
|
||||
|
||||
fn expected() -> Vec<(String, u64)> {
|
||||
let sub = |line| ("sub.sv".to_string(), line);
|
||||
vec![sub(1), sub(4), sub(5), ("top.sv".to_string(), 2)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_at_the_label_reach_the_closing_label_and_every_path_with_the_user_closed() {
|
||||
let (_tree, mut session, sub, _) = session_with("genlabel_refs_closed", true, false);
|
||||
let mut params = at_label(&sub, SUB, 1);
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
||||
assert_eq!(places(&session.result(References::METHOD, params)), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_from_the_other_files_segment_are_the_same_set_with_the_declarer_closed() {
|
||||
// The declaring file is closed, so its own uses (the closing label and
|
||||
// `g_lane[0].sig`) come from §64.1's one-file re-analysis: a block is a
|
||||
// hierarchical-only declaration.
|
||||
let (_tree, mut session, _, top) = session_with("genlabel_refs_open", false, true);
|
||||
let mut params = at_label(&top, TOP, 2);
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
||||
assert_eq!(places(&session.result(References::METHOD, params)), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_with_both_files_open_are_the_same_set() {
|
||||
let (_tree, mut session, _, top) = session_with("genlabel_refs_both", true, true);
|
||||
let mut params = at_label(&top, TOP, 2);
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
||||
assert_eq!(places(&session.result(References::METHOD, params)), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_rename_and_rename_rewrite_every_site_in_both_files() {
|
||||
let (tree, mut session, sub, _) = session_with("genlabel_rename", true, false);
|
||||
let prepared = session.result(PrepareRenameRequest::METHOD, at_label(&sub, SUB, 4));
|
||||
assert_eq!(prepared["placeholder"], "g_lane", "{prepared:#}");
|
||||
|
||||
let mut params = at_label(&sub, SUB, 4);
|
||||
params["newName"] = serde_json::json!("g_ln");
|
||||
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
let count = |path: &str| {
|
||||
let uri = path_to_uri(&tree.path.join(path)).expect("a uri");
|
||||
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
|
||||
};
|
||||
assert_eq!((count("sub.sv"), count("top.sv")), (3, 1), "{answer:#}");
|
||||
let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten());
|
||||
assert!(texts.all(|e| e["newText"] == "g_ln"), "{answer:#}");
|
||||
}
|
||||
|
||||
/// A member of a **nested** block is found on the index's `sub.g_a.g_b` key
|
||||
/// (`Semantics::member_key`), so the reference list from its declaration in
|
||||
/// an open buffer reaches the closed file's path to it.
|
||||
#[test]
|
||||
fn references_at_a_nested_blocks_member_reach_the_path_from_another_file() {
|
||||
const NSUB: &str = "module nsub;\n if (1) begin : g_a\n for (genvar j = 0; j < 2; j++) begin : g_b\n logic deep;\n end\n end\nendmodule\n";
|
||||
const NTOP: &str = "module ntop (output logic o);\n nsub u_n ();\n assign o = u_n.g_a.g_b[1].deep;\nendmodule\n";
|
||||
let tree = Tree::new("genlabel_nested");
|
||||
tree.write("nsub.sv", NSUB);
|
||||
tree.write("ntop.sv", NTOP);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("nsub.sv"), NSUB);
|
||||
let params = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 3, "character": NSUB.lines().nth(3).and_then(|l| l.find("deep")) },
|
||||
"context": { "includeDeclaration": true },
|
||||
});
|
||||
let found = places(&session.result(References::METHOD, params));
|
||||
assert_eq!(found, vec![("nsub.sv".to_string(), 3), ("ntop.sv".to_string(), 2)]);
|
||||
}
|
||||
|
||||
/// QA F1 over the wire: an open buffer is always in the rename's set, so its
|
||||
/// path through the label that resolves to nothing (`tb.u_x.…`, rooted at a
|
||||
/// top module no file in the tree declares — TODO §65.4 resolves the root
|
||||
/// when one does) is shown as a warning, unedited.
|
||||
#[test]
|
||||
fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() {
|
||||
const PROBE: &str =
|
||||
"module probe (output logic o);\n assign o = tb.u_x.g_lane[0].sig;\nendmodule\n";
|
||||
let (tree, mut session, sub, _) = session_with("genlabel_unresolved", true, false);
|
||||
tree.write("probe.sv", PROBE);
|
||||
session.open(&tree.path.join("probe.sv"), PROBE);
|
||||
let _ = session.drain();
|
||||
let mut params = at_label(&sub, SUB, 1);
|
||||
params["newName"] = serde_json::json!("g_ln");
|
||||
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
|
||||
let probe = path_to_uri(&tree.path.join("probe.sv")).expect("a uri");
|
||||
assert!(answer["changes"].get(probe.as_str()).is_none(), "probe.sv is not edited: {answer:#}");
|
||||
let shown = session.shown();
|
||||
assert!(
|
||||
shown.iter().any(|(_, m)| m.contains("probe.sv:2:") && m.contains("`g_lane`")),
|
||||
"{shown:?}"
|
||||
);
|
||||
assert!(!shown.iter().any(|(_, m)| m.contains("more")), "said once: {shown:?}");
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! A rename through a hierarchical path rooted at a top module, under the
|
||||
//! shipped **folder** scope (top-rooted-paths QA F3): the rename's file set
|
||||
//! holds the files declaring every unit the path walks through — the root
|
||||
//! `tb` and each hop's type — so a three-hop `tb.dut.u_core.sig` is renamed
|
||||
//! exactly as the whole-set engine renames it, from the declaration or from
|
||||
//! the segment. A hop outside the scope leaves the path warned about, and a
|
||||
//! rename from its segment is refused with the accurate reason.
|
||||
|
||||
use super::*;
|
||||
|
||||
const CORE: &str = "module core;\n logic sig;\nendmodule\n";
|
||||
const DUT: &str = "module dut_a;\n core u_core ();\n logic top_sig;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n";
|
||||
const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n";
|
||||
const PROBE: &str = "module probe;\n initial force tb.dut.u_core.sig = 1'b0;\n initial force tb.dut.top_sig = 1'b0;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n";
|
||||
|
||||
/// The opentitan shape: `ip/blk/{rtl,dv}`, with `tb.sv` at `tb_at`.
|
||||
fn fixture(tag: &str, tb_at: &str) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("ip/blk/rtl/core.sv", CORE);
|
||||
tree.write("ip/blk/rtl/dut_a.sv", DUT);
|
||||
tree.write(tb_at, TB);
|
||||
tree.write("ip/blk/dv/probe.sv", PROBE);
|
||||
tree
|
||||
}
|
||||
|
||||
/// The LSP position of the first `name` on 0-based `line` of `text`.
|
||||
fn at(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
|
||||
let row = text.lines().nth(line).expect("the line");
|
||||
let character = row.find(name).expect("the name on that line");
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
})
|
||||
}
|
||||
|
||||
/// The number of edits a rename answer makes in each of `files`.
|
||||
fn edits(tree: &Tree, answer: &Value, files: &[&str]) -> Vec<usize> {
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
files
|
||||
.iter()
|
||||
.map(|rel| {
|
||||
let uri = path_to_uri(&tree.path.join(rel)).expect("a uri");
|
||||
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rename(session: &mut Session, mut params: Value, new: &str) -> Result<Value, String> {
|
||||
params["newName"] = serde_json::json!(new);
|
||||
session.request(Rename::METHOD, params).response_result.map_err(|e| format!("{e:?}"))
|
||||
}
|
||||
|
||||
const FILES: [&str; 2] = ["ip/blk/rtl/core.sv", "ip/blk/dv/probe.sv"];
|
||||
|
||||
#[test]
|
||||
fn a_three_hop_path_is_renamed_from_the_declaration() {
|
||||
let tree = fixture("toproot_scope_decl", "ip/blk/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let core = session.open(&tree.path.join(FILES[0]), CORE);
|
||||
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
|
||||
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}");
|
||||
assert!(session.shown().is_empty(), "nothing to warn about: {:?}", session.shown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_three_hop_path_is_renamed_from_its_segment() {
|
||||
let tree = fixture("toproot_scope_seg", "ip/blk/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let probe = session.open(&tree.path.join(FILES[1]), PROBE);
|
||||
let answer = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig2").expect("renames");
|
||||
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_of_a_generate_block_is_renamed_through_the_path() {
|
||||
let tree = fixture("toproot_scope_block", "ip/blk/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let dut = session.open(&tree.path.join("ip/blk/rtl/dut_a.sv"), DUT);
|
||||
let answer = rename(&mut session, at(&dut, DUT, 4, "buf_q"), "buf_r").expect("renames");
|
||||
let files = ["ip/blk/rtl/dut_a.sv", "ip/blk/dv/probe.sv"];
|
||||
assert_eq!(edits(&tree, &answer, &files), vec![1, 1], "{answer:#}");
|
||||
}
|
||||
|
||||
/// The LSP rename equals the engine's over the scope's files.
|
||||
#[test]
|
||||
fn the_lsp_rename_equals_the_engine_over_the_scope() {
|
||||
let tree = fixture("toproot_scope_engine", "ip/blk/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let core = session.open(&tree.path.join(FILES[0]), CORE);
|
||||
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
|
||||
let sources = session.server.workspace.sources();
|
||||
let path = tree.path.join(FILES[0]);
|
||||
let offset = CORE.find("sig").expect("sig") as u32;
|
||||
let engine = vlog_refactor::rename(&sources, &path, offset, "sig2").expect("engine renames");
|
||||
let lsp = edits(&tree, &answer, &FILES);
|
||||
let whole: Vec<usize> =
|
||||
FILES.iter().map(|rel| engine.edits_for(&tree.path.join(rel)).len()).collect();
|
||||
assert_eq!(lsp, whole);
|
||||
}
|
||||
|
||||
/// `tb.sv` outside the folder scope: the index cannot resolve the root, so
|
||||
/// the open probe's path is left and warned about, and a rename asked from
|
||||
/// its segment is refused for what it is — an unresolved path.
|
||||
#[test]
|
||||
fn a_root_outside_the_scope_is_warned_and_refused_accurately() {
|
||||
let tree = fixture("toproot_scope_out", "top/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let probe = session.open(&tree.path.join(FILES[1]), PROBE);
|
||||
let core = session.open(&tree.path.join(FILES[0]), CORE);
|
||||
let in_index =
|
||||
session.server.workspace.index().files().contains(&tree.path.join("top/dv/tb.sv"));
|
||||
assert!(!in_index, "premise: the root's file is outside the scope");
|
||||
let _ = session.drain();
|
||||
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
|
||||
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 0], "{answer:#}");
|
||||
let shown = session.shown();
|
||||
assert!(shown.iter().any(|(_, m)| m.contains("probe.sv:2:")), "{shown:?}");
|
||||
let why = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig3").expect_err("refused");
|
||||
assert!(why.contains("hierarchical path"), "{why}");
|
||||
assert!(!why.contains("declared outside"), "{why}");
|
||||
}
|
||||
@@ -121,6 +121,14 @@ pub struct ClientSettings {
|
||||
/// followed by a space. Unset means on, the same way `inline_templates`
|
||||
/// does — see `docs/features/inline-instantiation/README.md`.
|
||||
pub inline_instantiation: Option<bool>,
|
||||
/// `lucisv.inlineKeywords`: whether a typed proper prefix of a keyword
|
||||
/// grows the rest of it as ghost text. Unset means on, independent of
|
||||
/// `inline_templates` — see `docs/features/completion-ux/README.md`.
|
||||
pub inline_keywords: Option<bool>,
|
||||
/// `lucisv.autoEnd`: whether a newline typed after `begin` also writes
|
||||
/// the `end` the block still owes. Unset means on — see
|
||||
/// `docs/features/completion-ux/README.md`.
|
||||
pub auto_end: Option<bool>,
|
||||
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
|
||||
/// the buffer. A plain `bool` rather than an `Option`, because unset and
|
||||
/// off are the same answer here: an editor with a format-on-save of its
|
||||
@@ -246,6 +254,8 @@ impl Default for ClientSettings {
|
||||
uvm_utils_indent: None,
|
||||
inline_templates: None,
|
||||
inline_instantiation: None,
|
||||
inline_keywords: None,
|
||||
auto_end: None,
|
||||
format_on_save: false,
|
||||
max_file_size: DEFAULT_MAX_FILE_SIZE,
|
||||
log_files: true,
|
||||
@@ -345,6 +355,8 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
|
||||
inline_templates: flag(lucisv.get("inlineTemplates")),
|
||||
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
|
||||
inline_keywords: flag(lucisv.get("inlineKeywords")),
|
||||
auto_end: flag(lucisv.get("autoEnd")),
|
||||
// Anything that is not `true` leaves the hook declining, wrong-typed
|
||||
// values included: the safe direction for a setting that rewrites the
|
||||
// user's buffer on every save is the one that does nothing.
|
||||
@@ -623,6 +635,8 @@ mod tests {
|
||||
"filelist": "",
|
||||
"inlineTemplates": true,
|
||||
"inlineInstantiation": true,
|
||||
"inlineKeywords": true,
|
||||
"autoEnd": true,
|
||||
"formatOnSave": false,
|
||||
"index": {
|
||||
"maxFileSize": 1048576, "logFiles": true,
|
||||
@@ -838,7 +852,13 @@ mod tests {
|
||||
// The two ghost-text settings are the ones whose absence resolves to
|
||||
// `true` here, so a `false` default in the manifest would make the
|
||||
// settings UI and the server disagree about a feature being on.
|
||||
for ghost in ["lucisv.inlineTemplates", "lucisv.inlineInstantiation"] {
|
||||
// `autoEnd` is the same kind of switch: absent means on.
|
||||
for ghost in [
|
||||
"lucisv.inlineTemplates",
|
||||
"lucisv.inlineInstantiation",
|
||||
"lucisv.inlineKeywords",
|
||||
"lucisv.autoEnd",
|
||||
] {
|
||||
assert_eq!(properties[ghost]["default"], json!(true), "{ghost}");
|
||||
assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}");
|
||||
}
|
||||
@@ -1103,6 +1123,8 @@ mod tests {
|
||||
ClientSettings {
|
||||
inline_templates: Some(true),
|
||||
inline_instantiation: Some(true),
|
||||
inline_keywords: Some(true),
|
||||
auto_end: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
"the only difference from silence must be the settings whose \
|
||||
@@ -1141,6 +1163,24 @@ mod tests {
|
||||
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_keywords_and_auto_end_are_booleans_and_nothing_else() {
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": false, "autoEnd": false } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (Some(false), Some(false)));
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": true, "autoEnd": true } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (Some(true), Some(true)));
|
||||
// Absence is not `false`: both are on unless a client says no.
|
||||
let found = settings(json!({ "lucisv": {} }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (None, None));
|
||||
for bad in [json!("false"), json!(0), json!(null), json!([false])] {
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": bad, "autoEnd": bad } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (None, None), "{bad} ignored");
|
||||
}
|
||||
// Independent of the template ghosts: one off leaves the other alone.
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": false } }));
|
||||
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_save_is_off_until_a_client_asks_for_it() {
|
||||
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! The open buffers: installing, closing and finding them, and which
|
||||
//! text — the buffer's or the disk's — speaks for a path when the index
|
||||
//! or a refactoring asks.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Uri;
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use super::discover::{oversize, Found};
|
||||
use super::{Document, Workspace};
|
||||
use crate::uri::uri_to_path;
|
||||
|
||||
impl Workspace {
|
||||
pub fn document(&self, uri: &Uri) -> Option<&Document> {
|
||||
self.docs.get(uri)
|
||||
}
|
||||
|
||||
/// The open document backed by `path`, if there is one.
|
||||
pub fn document_for_path(&self, path: &Path) -> Option<&Document> {
|
||||
self.docs.values().find(|doc| doc.path.as_deref() == Some(path))
|
||||
}
|
||||
|
||||
/// Every open document and its URI.
|
||||
pub fn open_documents(&self) -> impl Iterator<Item = (&Uri, &Document)> {
|
||||
self.docs.iter()
|
||||
}
|
||||
|
||||
/// Replace a buffer's contents and re-analyze it.
|
||||
///
|
||||
/// Also the one place a directory enters the folder scope: a buffer with a
|
||||
/// path puts its own directory on the list `scope_dirs` raises. An
|
||||
/// `untitled:` buffer has no path and contributes none.
|
||||
///
|
||||
/// And the one place the **large-file fast path** is chosen: a text over
|
||||
/// `lucisv.largeFile.threshold` is line-indexed and nothing more. Because
|
||||
/// the decision lives here it is re-taken on every `didOpen`, `didChange`
|
||||
/// and text-carrying `didSave`, which is what makes a buffer edited past
|
||||
/// the threshold — or back under it — change mode at that moment and not
|
||||
/// before (`docs/features/large-file-mode/README.md`).
|
||||
pub fn set_document(&mut self, uri: Uri, text: String) {
|
||||
let path = uri_to_path(&uri);
|
||||
if let Some(dir) = path.as_deref().and_then(Path::parent) {
|
||||
if !self.opened_dirs.iter().any(|seen| seen == dir) {
|
||||
self.opened_dirs.push(dir.to_path_buf());
|
||||
self.opened_dirs.sort();
|
||||
}
|
||||
}
|
||||
// This path now has a buffer speaking for it, so whatever the view
|
||||
// cache holds for it is both unwanted and possibly older than the
|
||||
// edits the buffer carries.
|
||||
if let Some(path) = path.as_deref() {
|
||||
self.forget_view(path);
|
||||
}
|
||||
let doc = match self.is_large(&text) {
|
||||
true => Document::large(path, text),
|
||||
false => Document::new(path, text, &self.index),
|
||||
};
|
||||
self.docs.insert(uri, doc);
|
||||
}
|
||||
|
||||
/// Whether a buffer of this text takes the fast path. `0` disables it, and
|
||||
/// the comparison is strict, so a buffer of exactly the threshold is still
|
||||
/// analyzed in full.
|
||||
fn is_large(&self, text: &str) -> bool {
|
||||
let threshold = self.client.large_file_threshold;
|
||||
threshold != 0 && text.len() as u64 > threshold
|
||||
}
|
||||
|
||||
/// Whether any open buffer is on the large-file fast path.
|
||||
///
|
||||
/// The gate in `server.rs` runs before every request, and this is what
|
||||
/// keeps that from costing a URI parse per request in the session where
|
||||
/// nothing is large — which is every session but one.
|
||||
pub fn has_large_documents(&self) -> bool {
|
||||
self.docs.values().any(|doc| doc.large)
|
||||
}
|
||||
|
||||
pub fn close_document(&mut self, uri: &Uri) {
|
||||
let closed = self.docs.remove(uri);
|
||||
// Disk is the authority again, and a view made before this buffer was
|
||||
// opened predates every save it made.
|
||||
if let Some(path) = closed.and_then(|doc| doc.path) {
|
||||
self.forget_view(&path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every open buffer's URI, for republishing diagnostics after a rebuild.
|
||||
pub fn open_uris(&self) -> Vec<Uri> {
|
||||
self.docs.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// The text of a workspace file: the open buffer if there is one, else
|
||||
/// what is on disk. Same precedence the index rebuild uses, so a location
|
||||
/// is never computed against text the index did not see.
|
||||
pub fn text_of(&self, path: &Path) -> Option<String> {
|
||||
let open = self.docs.values().find(|d| d.path.as_deref() == Some(path));
|
||||
match open {
|
||||
Some(doc) => Some(doc.text.clone()),
|
||||
None => fs::read_to_string(path).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text one in-scope file contributes right now, by `collect_sources`'s
|
||||
/// rules — `None` when it contributes nothing at all.
|
||||
pub(super) fn current_text(&self, path: &Path) -> Option<String> {
|
||||
if let Some(doc) = self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) {
|
||||
// A fast-path buffer contributes nothing, exactly as it does in
|
||||
// `collect_sources` — indexing it is the parse the fast path
|
||||
// exists to skip.
|
||||
return (!doc.large).then(|| doc.text.clone());
|
||||
}
|
||||
if oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_some() {
|
||||
return None;
|
||||
}
|
||||
fs::read_to_string(path).ok()
|
||||
}
|
||||
|
||||
/// The index facts and the completion words of the open buffer backing
|
||||
/// `path`, read off the analysis it already holds — `None` when no buffer
|
||||
/// does, or when the one that does is on the large-file fast path and has
|
||||
/// no analysis of its own text to read.
|
||||
///
|
||||
/// The buffer is found the same way [`Workspace::current_text`] finds the
|
||||
/// text, so the two always speak for the same `Document`.
|
||||
pub(super) fn analysis_of(&self, path: &Path) -> Option<(FileFacts, Vec<String>)> {
|
||||
let doc = self.docs.values().find(|doc| doc.path.as_deref() == Some(path))?;
|
||||
(!doc.large).then(|| (doc.facts(path.to_path_buf()), doc.words()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! One open buffer, analyzed once from its text — [`Document`] and
|
||||
//! everything derived from it — and the two binary searches that find a
|
||||
//! token in it by offset without sweeping the buffer.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalResolutions, FileFacts, Semantics, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::convert::Positions;
|
||||
|
||||
/// One open buffer, fully analyzed. Every field is derived from `text`, so a
|
||||
/// change throws the whole thing away and builds a new one.
|
||||
pub struct Document {
|
||||
/// The buffer's path, absent for a `untitled:` document.
|
||||
pub path: Option<PathBuf>,
|
||||
pub text: String,
|
||||
pub line_index: LineIndex,
|
||||
/// Empty when the file does not lex — the lexer is all-or-nothing.
|
||||
pub tokens: Vec<Token>,
|
||||
/// The tolerant parse of `text` — the tree `semantics` was analyzed from,
|
||||
/// kept so the lint pass reads it instead of parsing the buffer again
|
||||
/// ("one parse, two tools", `docs/features/one-parse/README.md`).
|
||||
pub tree: SourceFile,
|
||||
pub diagnostics: Vec<ParseDiagnostic>,
|
||||
pub semantics: Semantics,
|
||||
pub defines: DefineTable,
|
||||
/// The workspace layer's answers for this file's external candidates.
|
||||
pub external: ExternalResolutions,
|
||||
/// Whether this buffer was opened on the **large-file fast path**: every
|
||||
/// field above except `text` and `line_index` is the empty analysis of an
|
||||
/// empty file, because nothing lexed it. Handlers that would scan the text
|
||||
/// itself check this flag; the ones that read the analysis need not, since
|
||||
/// there is nothing in it to find. See
|
||||
/// `docs/features/large-file-mode/README.md`.
|
||||
pub large: bool,
|
||||
/// The formatter's fence answer for exactly this `text`, computed on
|
||||
/// first use and never again — a whole tolerant parse the code-action
|
||||
/// path used to pay for on every request. Filled through
|
||||
/// [`crate::fences::of`], which is the only thing that may touch it; it
|
||||
/// is bound to this revision because a change builds a new `Document`.
|
||||
pub fences: std::sync::OnceLock<Vec<vlog_formatter::fence::Region>>,
|
||||
/// This buffer's lint findings, kept while every input that produced them
|
||||
/// is unchanged — read by the diagnostics pass and by quick-fix discovery
|
||||
/// alike, so one revision is linted once rather than twice (review round
|
||||
/// §R1a, `crate::lint_snapshot`). Bound to this revision for the same
|
||||
/// structural reason `fences` is; the inputs that can move *without* a new
|
||||
/// `Document` are the snapshot's own key, and the index moving is
|
||||
/// [`Document::refresh_overlay`], which clears it.
|
||||
pub lint: crate::lint_snapshot::Slot,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Analyze a buffer from scratch against the current workspace index.
|
||||
pub fn new(path: Option<PathBuf>, text: String, index: &WorkspaceIndex) -> Document {
|
||||
// One lex: the tree is built from a clone of the token stream instead
|
||||
// of re-lexing the buffer (`parse_source_tolerant` is exactly
|
||||
// `tokenize` + `parse_tolerant`, so the tree is identical). A buffer
|
||||
// that does not lex keeps the old path, so its all-error tree and its
|
||||
// lex diagnostic are byte-for-byte what they always were.
|
||||
use crate::lint_trace::{rebuild, Rebuild};
|
||||
crate::lint_trace::saw_document();
|
||||
let (tokens, (tree, diagnostics)) = match rebuild(Rebuild::Lex, || tokenize(&text)) {
|
||||
Ok(tokens) => {
|
||||
let parsed = rebuild(Rebuild::Parse, || parse_tolerant(tokens.clone(), &text));
|
||||
(tokens, parsed)
|
||||
}
|
||||
Err(_) => (Vec::new(), rebuild(Rebuild::Parse, || parse_source_tolerant(&text))),
|
||||
};
|
||||
let defines = rebuild(Rebuild::Defines, || collect_defines(&tokens));
|
||||
let semantics = rebuild(Rebuild::Analyze, || analyze(&tree, &text));
|
||||
let external = rebuild(Rebuild::External, || resolve_external(&semantics, index));
|
||||
let line_index = rebuild(Rebuild::Lines, || LineIndex::new(&text));
|
||||
let large = false;
|
||||
Document {
|
||||
path,
|
||||
text,
|
||||
line_index,
|
||||
tokens,
|
||||
tree,
|
||||
diagnostics,
|
||||
semantics,
|
||||
defines,
|
||||
external,
|
||||
large,
|
||||
fences: std::sync::OnceLock::new(),
|
||||
lint: crate::lint_snapshot::Slot::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a buffer on the **fast path**: index its lines and nothing else.
|
||||
///
|
||||
/// One newline scan is the whole cost of opening a 100 MB netlist. The
|
||||
/// derived fields are the analysis of the *empty* file rather than of this
|
||||
/// one — built by parsing `""`, which costs nothing and needs no new API
|
||||
/// from `vlog_parser` — so every handler that reads the analysis finds
|
||||
/// exactly nothing and answers empty without knowing this path exists.
|
||||
pub fn large(path: Option<PathBuf>, text: String) -> Document {
|
||||
let (tree, _) = parse_source_tolerant("");
|
||||
let semantics = analyze(&tree, "");
|
||||
let line_index = LineIndex::new(&text);
|
||||
Document {
|
||||
path,
|
||||
text,
|
||||
line_index,
|
||||
tokens: Vec::new(),
|
||||
tree,
|
||||
diagnostics: Vec::new(),
|
||||
semantics,
|
||||
defines: DefineTable::default(),
|
||||
external: ExternalResolutions::default(),
|
||||
large: true,
|
||||
fences: std::sync::OnceLock::new(),
|
||||
lint: crate::lint_snapshot::Slot::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// This document's position converter.
|
||||
pub fn positions(&self) -> Positions<'_> {
|
||||
Positions::new(&self.text, &self.line_index)
|
||||
}
|
||||
|
||||
/// The source token covering `offset`, found without sweeping the buffer.
|
||||
pub fn token_at(&self, offset: u32) -> Option<&Token> {
|
||||
let after = self.tokens.partition_point(|token| token.span.start <= offset);
|
||||
let token = self.tokens.get(after.checked_sub(1)?)?;
|
||||
token.span.contains(offset).then_some(token)
|
||||
}
|
||||
|
||||
/// Re-run only the workspace overlay, after the index was rebuilt. The
|
||||
/// single-file analysis is unaffected by other files, by construction.
|
||||
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
|
||||
self.external = resolve_external(&self.semantics, index);
|
||||
// The index is what the census oracle answers from, so a lint result
|
||||
// taken under the old one is no longer this buffer's answer. This is
|
||||
// the whole of the snapshot's index invalidation: every mutation of
|
||||
// `Workspace::index` ends in the loop that calls this, so there is no
|
||||
// generation counter to keep in step (review round §R1a).
|
||||
self.lint.clear();
|
||||
}
|
||||
|
||||
/// What this buffer contributes to the workspace index, read off the
|
||||
/// analysis it already holds instead of from its text.
|
||||
///
|
||||
/// [`FileFacts::of`] is `tokenize` + `parse_tolerant` + `analyze` followed
|
||||
/// by the fact walk, and the first three are exactly what [`Document::new`]
|
||||
/// already did to fill `tree`, `defines` and `semantics` — from the same
|
||||
/// text, with the same functions, down to the lex-failure branch. So this
|
||||
/// is `FileFacts::of(path, &self.text)` with the parse already paid for,
|
||||
/// not a second way of computing it
|
||||
/// (`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus`).
|
||||
///
|
||||
/// Never called for a buffer on the large-file fast path: its analysis is
|
||||
/// the analysis of the empty file, and such a buffer contributes nothing to
|
||||
/// the index at all (see `collect_sources`).
|
||||
pub fn facts(&self, path: PathBuf) -> FileFacts {
|
||||
FileFacts::from_analysis(
|
||||
path,
|
||||
&self.tree,
|
||||
&self.defines,
|
||||
&self.semantics,
|
||||
&self.text,
|
||||
&self.line_index,
|
||||
&self.tokens,
|
||||
)
|
||||
}
|
||||
|
||||
/// The completion words this buffer contributes, read off the tokens it was
|
||||
/// analyzed from rather than by lexing its text a second time.
|
||||
pub fn words(&self) -> Vec<String> {
|
||||
crate::candidates::words_of_tokens(&self.tokens)
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Finding a token by offset without sweeping the buffer
|
||||
// ----------------------------------------------------------------------
|
||||
//
|
||||
// The lexer emits tokens in source order and they never overlap, so
|
||||
// `span.start` and `span.end` both rise across the vector: `end[i] <=
|
||||
// start[i+1] <= end[i+1]`. That makes both predicates below monotone, which
|
||||
// is the whole precondition `partition_point` needs. Every handler that used
|
||||
// to sweep the vector looking for a token at the cursor is one comparison
|
||||
// away from one of these two indices — see
|
||||
// `docs/features/interactive-latency/README.md` for the per-call-site
|
||||
// argument that each swap returns exactly what the sweep returned.
|
||||
|
||||
/// The index of the first token that **reaches** `offset` — the first with
|
||||
/// `span.end >= offset`. `tokens.len()` when none does.
|
||||
///
|
||||
/// Every token before it ends strictly before `offset`, so it cannot cover,
|
||||
/// end at, or contain `offset`. The token *at* this index is therefore the
|
||||
/// first candidate any such question has.
|
||||
pub fn first_token_reaching(tokens: &[Token], offset: u32) -> usize {
|
||||
tokens.partition_point(|token| token.span.end < offset)
|
||||
}
|
||||
|
||||
/// The index of the first token that **begins** at or after `offset` — the
|
||||
/// first with `span.start >= offset`. `tokens.len()` when none does.
|
||||
pub fn first_token_from(tokens: &[Token], offset: u32) -> usize {
|
||||
tokens.partition_point(|token| token.span.start < offset)
|
||||
}
|
||||
|
||||
/// A buffer of `blocks` repeated blocks, for the tests that check a binary
|
||||
/// search against the sweep it replaced.
|
||||
///
|
||||
/// Deliberately awkward: tokens written with no space between them (`a=b;`),
|
||||
/// line and block comments, a string, nested `begin`/`end` and several depths
|
||||
/// of parentheses. The offsets those tests walk are *every byte*, and the ones
|
||||
/// that could tell a binary search from a sweep are exactly the bytes two
|
||||
/// tokens share — which only adjacent punctuation produces.
|
||||
#[cfg(test)]
|
||||
pub fn mixed_buffer(blocks: usize) -> String {
|
||||
let mut src = String::from("module mixed (input logic clk, output logic [7:0] q);\n");
|
||||
for n in 0..blocks {
|
||||
src.push_str(&format!(
|
||||
" // block {n}\n \
|
||||
wire [7:0] w{n};assign w{n}=(q[0]?8'd1:8'd2)+{{4'h0,4'hF}};\n \
|
||||
/* {n} */ always @(posedge clk) begin\n \
|
||||
if (w{n}[0]) begin q<=w{n}; end else begin q<=8'd0; end\n \
|
||||
end\n \
|
||||
initial $display(\"block {n}\", w{n});\n"
|
||||
));
|
||||
}
|
||||
src.push_str("endmodule\n");
|
||||
src
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Re-indexing one saved file the index already holds, patching every
|
||||
//! table rather than rebuilding it — the cheap path a `didSave` takes
|
||||
//! before falling back to a whole rescan.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::Workspace;
|
||||
use crate::scan_trace::ScanTrace;
|
||||
|
||||
impl Workspace {
|
||||
/// Rebuild the index for **one** file, leaving every other file's
|
||||
/// contribution exactly as it is. Reports whether it could.
|
||||
///
|
||||
/// `false` means the caller must fall back to [`Workspace::rebuild_index`]:
|
||||
/// the file is not one this index already holds, which is the one case the
|
||||
/// cheap path cannot settle. A file appearing changes which *other* files
|
||||
/// exist as far as the include graph is concerned (a `` `include`` that had
|
||||
/// nothing to resolve to now has something), and answering that takes a
|
||||
/// walk — so the rule is simply "a file the index already holds".
|
||||
///
|
||||
/// The four pieces of state a rebuild produces, and what happens to each:
|
||||
///
|
||||
/// * **the workspace index** — [`WorkspaceIndex::update_file`] /
|
||||
/// [`WorkspaceIndex::remove_file`], which promise the index a whole
|
||||
/// rebuild over the same file set would have produced;
|
||||
/// * **the completion tables** — the two index-derived ones re-derived, the
|
||||
/// word table patched by this file's words alone;
|
||||
/// * **the include graph** — this file's edges re-scanned, the known-file
|
||||
/// and folded-spelling tables re-learned from the index's list;
|
||||
/// * **every open buffer's overlay** — refreshed, exactly as a rebuild
|
||||
/// refreshes it, because any of them may resolve into the file that moved.
|
||||
///
|
||||
/// The text is chosen by `collect_sources`'s rules, for one path: an open
|
||||
/// buffer beats disk and is never capped; a walked file over
|
||||
/// `lucisv.index.maxFileSize`, one that has been deleted, and one that
|
||||
/// cannot be read are all "this file is not in the index any more".
|
||||
pub fn update_one(&mut self, path: &Path) -> bool {
|
||||
if !self.index.files().iter().any(|held| held == path) {
|
||||
return false;
|
||||
}
|
||||
// Re-indexing one file *is* the claim that its bytes moved.
|
||||
self.forget_view(path);
|
||||
match self.current_text(path) {
|
||||
Some(text) => {
|
||||
// The same rule a whole rebuild follows: when the text came
|
||||
// from an open buffer, that buffer's finished analysis is the
|
||||
// facts and the words, and neither is derived from the text a
|
||||
// second time. `current_text` answers with a buffer's text only
|
||||
// when that buffer is not on the large-file fast path, so the
|
||||
// analysis found here is a real one.
|
||||
match self.analysis_of(path) {
|
||||
Some((facts, words)) => {
|
||||
self.index.update_facts(facts);
|
||||
self.candidates.update_words(&self.index, path, words);
|
||||
}
|
||||
None => {
|
||||
self.index.update_file(path.to_path_buf(), &text);
|
||||
// The words come back out of the record the update
|
||||
// just wrote, so the file is lexed once rather than
|
||||
// twice (`FACTS_FORMAT` 13). A path the index somehow
|
||||
// does not hold falls back to lexing, which is what
|
||||
// this line always did.
|
||||
match self.index.facts_for(path).map(|facts| facts.words().to_vec()) {
|
||||
Some(words) => self.candidates.update_words(&self.index, path, words),
|
||||
None => self.candidates.update_file(&self.index, path, &text),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.includes.update_file(path, &text, self.index.files());
|
||||
// Written through here too, so an hour of saves is an hour of
|
||||
// work the next session does not repeat. The record is the
|
||||
// one the update just made — no second parse — and it is
|
||||
// keyed by the text it was made from, which is the buffer's
|
||||
// when a buffer beat disk. That record is simply never hit
|
||||
// again if the file on disk says something else.
|
||||
// A save is the other thing that asks the store something, so
|
||||
// it opens a re-open a scan deferred rather than writing into
|
||||
// the store the previous rescan left in hand ([`StoreOpen`]).
|
||||
self.open_store(&mut ScanTrace::default());
|
||||
if let Some(facts) = self.index.facts_for(path) {
|
||||
self.cache.record(facts, &text);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
self.index.remove_file(path);
|
||||
self.candidates.remove_file(&self.index, path);
|
||||
self.includes.remove_file(path, self.index.files());
|
||||
}
|
||||
}
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// [`Workspace::update_one`], then a whole rebuild over the same
|
||||
/// workspace, asserting the two produced the same thing — the paranoid
|
||||
/// form, for tests.
|
||||
///
|
||||
/// It is the incremental path's whole claim, checked rather than argued:
|
||||
/// the index's fingerprint (ids, disambiguation order, member tables,
|
||||
/// edges, define counts) and the completion word table, which is the one
|
||||
/// piece of derived state that is patched rather than re-derived. The
|
||||
/// workspace is left holding the *rebuilt* index, which is the same index,
|
||||
/// so a test may keep using it.
|
||||
#[cfg(test)]
|
||||
pub fn update_one_checked(&mut self, path: &Path) -> bool {
|
||||
if !self.update_one(path) {
|
||||
return false;
|
||||
}
|
||||
let index = self.index.fingerprint();
|
||||
let words = self.candidates.words("").to_vec();
|
||||
self.rebuild_index();
|
||||
assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index");
|
||||
assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words");
|
||||
true
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,332 @@
|
||||
//! The connection being typed: where each buffer's last edit ended, the
|
||||
//! connection-list entry around it, and the diagnostics held back from that
|
||||
//! entry while the typing goes on (`docs/features/port-entry-grace/README.md`).
|
||||
//!
|
||||
//! Someone typing `.po` into `sub u0 (…)` passes through a lone `.`, a `.p`
|
||||
//! that names no port, a `.po(` with nothing closed — and every one of those
|
||||
//! keystrokes used to draw a squiggle. While the last edit sits inside an
|
||||
//! instantiation's port or parameter list, the diagnostics whose range starts
|
||||
//! inside the entry around it are withheld from what is published or pulled.
|
||||
//! Nothing outside that entry is ever withheld, and the entry is released —
|
||||
//! the full list said again — when the next edit lands outside it, when
|
||||
//! [`PORT_ENTRY_GRACE`] passes with no edit at all, or when the buffer is
|
||||
//! saved, closed or reopened.
|
||||
//!
|
||||
//! The lookup is a token scan of the buffer just analyzed, no extra parse.
|
||||
//! The parser's half — keeping the unfinished entry inside its own entry so
|
||||
//! the rest of the file parses as if it were complete — is in
|
||||
//! `vlog_parser`'s `recover_list.rs`, and the two agree on where an entry
|
||||
//! ends: a `,` or the list's `)` at the list's own level, or the end of the
|
||||
//! line when the next line opens a new `.` entry.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lsp_types::{Diagnostic, Uri};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use super::Document;
|
||||
use crate::signature::enclosing_list;
|
||||
|
||||
/// How long the diagnostics of the entry being typed are held back after the
|
||||
/// last edit. Long enough to finish typing a port name and its connection,
|
||||
/// short enough that a real mistake left behind is shown before the eye has
|
||||
/// moved on.
|
||||
pub const PORT_ENTRY_GRACE: Duration = Duration::from_millis(1500);
|
||||
|
||||
/// Every buffer's last edit, while it may still be withholding something.
|
||||
#[derive(Default)]
|
||||
pub struct PortGrace {
|
||||
edits: HashMap<Uri, LastEdit>,
|
||||
}
|
||||
|
||||
/// One buffer's last edit.
|
||||
struct LastEdit {
|
||||
/// Where the edit ended, in the buffer's newest text.
|
||||
offset: u32,
|
||||
/// When it arrived.
|
||||
at: Instant,
|
||||
/// Where it stands in the analysis of that text.
|
||||
state: Located,
|
||||
/// An edit has since landed in another buffer: release at the next
|
||||
/// chance rather than when the quiet period ends.
|
||||
released: bool,
|
||||
}
|
||||
|
||||
/// Whether a buffer's last edit has been looked up in its analysis yet.
|
||||
enum Located {
|
||||
/// The buffer is dirty; its analysis is not the text the edit is in.
|
||||
Pending,
|
||||
/// The edit is inside this connection-list entry.
|
||||
Entry(TextRange),
|
||||
}
|
||||
|
||||
impl PortGrace {
|
||||
/// Note a buffer's edit, `end` being where the last of its changes ended
|
||||
/// in the new text — `None` for a full-document replacement, which says
|
||||
/// nothing about where anyone is typing and so withholds nothing.
|
||||
///
|
||||
/// An edit is "elsewhere" for every other buffer, so whatever those are
|
||||
/// withholding is released at the next chance.
|
||||
pub fn edited(&mut self, uri: &Uri, end: Option<u32>, now: Instant) {
|
||||
for (other, edit) in self.edits.iter_mut() {
|
||||
if other != uri {
|
||||
edit.released = true;
|
||||
}
|
||||
}
|
||||
match end {
|
||||
Some(offset) => {
|
||||
let edit = LastEdit { offset, at: now, state: Located::Pending, released: false };
|
||||
self.edits.insert(uri.clone(), edit);
|
||||
}
|
||||
None => {
|
||||
self.edits.remove(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Look a buffer's pending edit up in `doc`, its freshly analyzed text.
|
||||
/// An edit outside every connection list is forgotten on the spot: it
|
||||
/// withholds nothing and needs no release.
|
||||
pub fn locate(&mut self, uri: &Uri, doc: &Document) {
|
||||
let Some(edit) = self.edits.get_mut(uri) else { return };
|
||||
if !matches!(edit.state, Located::Pending) {
|
||||
return;
|
||||
}
|
||||
match entry_around(doc, edit.offset) {
|
||||
Some(entry) => edit.state = Located::Entry(entry),
|
||||
None => {
|
||||
self.edits.remove(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `diagnostics` without the ones whose range starts inside the entry
|
||||
/// `uri`'s last edit is in. Everything, when there is no such entry.
|
||||
pub fn withhold(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
) -> Vec<Diagnostic> {
|
||||
let Some(entry) = self.entry_of(uri) else { return diagnostics };
|
||||
let positions = doc.positions();
|
||||
diagnostics
|
||||
.into_iter()
|
||||
.filter(|d| !inside(entry, positions.offset(d.range.start)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The entry `uri`'s last edit is in, while it is withholding.
|
||||
pub fn entry_of(&self, uri: &Uri) -> Option<TextRange> {
|
||||
match self.edits.get(uri)?.state {
|
||||
Located::Entry(entry) => Some(entry),
|
||||
Located::Pending => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop a buffer's edit — it was saved, closed or opened afresh — and say
|
||||
/// whether it was withholding anything, i.e. whether its full list is
|
||||
/// owed now.
|
||||
pub fn forget(&mut self, uri: &Uri) -> bool {
|
||||
matches!(self.edits.remove(uri), Some(LastEdit { state: Located::Entry(_), .. }))
|
||||
}
|
||||
|
||||
/// When the next release is due: the end of the earliest quiet period,
|
||||
/// or right away for an entry an edit elsewhere released.
|
||||
pub fn deadline(&self) -> Option<Instant> {
|
||||
self.edits.values().filter_map(LastEdit::due_at).min()
|
||||
}
|
||||
|
||||
/// Take every buffer whose release is due at `now`: their full lists are
|
||||
/// owed to the client.
|
||||
pub fn due(&mut self, now: Instant) -> Vec<Uri> {
|
||||
let due: Vec<Uri> = self
|
||||
.edits
|
||||
.iter()
|
||||
.filter(|(_, edit)| edit.due_at().is_some_and(|at| at <= now))
|
||||
.map(|(uri, _)| uri.clone())
|
||||
.collect();
|
||||
for uri in &due {
|
||||
self.edits.remove(uri);
|
||||
}
|
||||
due
|
||||
}
|
||||
}
|
||||
|
||||
impl LastEdit {
|
||||
/// When this edit's entry is to be released; `None` while it has no
|
||||
/// entry yet.
|
||||
fn due_at(&self) -> Option<Instant> {
|
||||
if !matches!(self.state, Located::Entry(_)) {
|
||||
return None;
|
||||
}
|
||||
if self.released {
|
||||
return Some(self.at);
|
||||
}
|
||||
Some(self.at.checked_add(PORT_ENTRY_GRACE).unwrap_or(self.at))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `offset` lies in `entry`, both ends included: a diagnostic on the
|
||||
/// token that ends the entry (the `,` of `.b(y),)`, the `.` that proves a
|
||||
/// comma missing) is the entry's own news.
|
||||
fn inside(entry: TextRange, offset: u32) -> bool {
|
||||
entry.start <= offset && offset <= entry.end
|
||||
}
|
||||
|
||||
/// The extent of the connection-list entry around `offset`, or `None` when
|
||||
/// `offset` is not inside an instantiation's port or parameter list.
|
||||
///
|
||||
/// The entry starts at the last separator before `offset` at the list's own
|
||||
/// level — a `,`, which it includes, or the list's `(`, which it does not —
|
||||
/// or at a `.` that opens its own line, which is where the parser ends an
|
||||
/// entry left open on the line above. It ends at the first `,`, `;` or
|
||||
/// closing bracket after `offset` at the level `offset` is at, or at the end
|
||||
/// of `offset`'s line — reaching on to the next line's first token when that
|
||||
/// is a `.`, the token that proves a `,` is missing. A `;` ends it at any
|
||||
/// level: no connection list holds one.
|
||||
pub fn entry_around(doc: &Document, offset: u32) -> Option<TextRange> {
|
||||
let tokens = &doc.tokens;
|
||||
let list = enclosing_list(tokens, offset)?;
|
||||
let next = tokens.partition_point(|t| t.span.start < offset);
|
||||
// The bracket count above takes a value left open (`.po(`) for the list
|
||||
// never closing, so a list "around" an edit three items further down is
|
||||
// only believed when no `;` stands between them: a connection list never
|
||||
// holds one, and every item after it ends in one.
|
||||
if tokens.get(list.open + 1..next)?.iter().any(|t| t.is_sym(";")) {
|
||||
return None;
|
||||
}
|
||||
// Only an instance's *named* list: `enclosing_list` also accepts a
|
||||
// header's `name #(`, a positional list, a call after a block label and a
|
||||
// function whose return type is a name, and none of those is typed the
|
||||
// way a `.name(…)` connection is.
|
||||
if !holds_a_named_entry(tokens, list.open) || in_a_declaration_header(tokens, list.open) {
|
||||
return None;
|
||||
}
|
||||
let (start, depth) = entry_start(tokens, list.open, next);
|
||||
let (line, _) = doc.line_index.line_col(offset);
|
||||
let end = entry_end(&tokens[next..], depth, offset, line);
|
||||
Some(TextRange::new(start, end.max(start)))
|
||||
}
|
||||
|
||||
/// Walk from the list's `(` up to the token at `next`: where the entry there
|
||||
/// starts, and how many brackets are open inside it at that point.
|
||||
fn entry_start(tokens: &[Token], open: usize, next: usize) -> (u32, u32) {
|
||||
let mut start = tokens[open].span.end;
|
||||
let mut depth = 0u32;
|
||||
for i in open + 1..next {
|
||||
let t = &tokens[i];
|
||||
if t.is_sym(".") && tokens[i - 1].line != t.line {
|
||||
// A `.` opening its line starts an entry even inside a bracket:
|
||||
// the parser ends a value left open on the line above here.
|
||||
start = t.span.start;
|
||||
depth = 0;
|
||||
} else if is_open(t) {
|
||||
depth += 1;
|
||||
} else if is_close(t) {
|
||||
depth = depth.saturating_sub(1);
|
||||
} else if depth == 0 && t.is_sym(",") {
|
||||
start = t.span.start;
|
||||
}
|
||||
}
|
||||
(start, depth)
|
||||
}
|
||||
|
||||
/// Walk on from `offset` (`after` being the tokens from there on, `depth`
|
||||
/// the brackets open inside the entry, `line` 1-based): where the entry ends.
|
||||
fn entry_end(after: &[Token], mut depth: u32, offset: u32, line: u32) -> u32 {
|
||||
let mut end = offset;
|
||||
for t in after {
|
||||
if t.kind == TokenKind::Eof {
|
||||
break;
|
||||
}
|
||||
if t.line != line {
|
||||
return if t.is_sym(".") { t.span.start } else { end };
|
||||
}
|
||||
if is_close(t) {
|
||||
if depth == 0 {
|
||||
return t.span.start;
|
||||
}
|
||||
depth -= 1;
|
||||
} else if is_open(t) {
|
||||
depth += 1;
|
||||
} else if t.is_sym(";") || (depth == 0 && t.is_sym(",")) {
|
||||
return t.span.start;
|
||||
}
|
||||
end = t.span.end;
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
/// The keywords whose header lists (`name #(`, `name (`) are declarations,
|
||||
/// never an instance's connections.
|
||||
const DECLARATION_HEADERS: &[&str] = &[
|
||||
"module",
|
||||
"macromodule",
|
||||
"interface",
|
||||
"program",
|
||||
"class",
|
||||
"package",
|
||||
"primitive",
|
||||
"function",
|
||||
"task",
|
||||
"checker",
|
||||
];
|
||||
|
||||
/// Whether the list opened at `open` holds an entry, at its own level, that
|
||||
/// starts with `.` — the entry being typed counts. A `.` opening its own line
|
||||
/// counts at any depth, as it does for [`entry_start`]: the parser ends a
|
||||
/// value left open on the line above there. The walk ends at the list's `)`,
|
||||
/// a `;`, or the end of the file.
|
||||
fn holds_a_named_entry(tokens: &[Token], open: usize) -> bool {
|
||||
let mut depth = 0u32;
|
||||
for i in open + 1..tokens.len() {
|
||||
let t = &tokens[i];
|
||||
let prev = &tokens[i - 1];
|
||||
if t.kind == TokenKind::Eof || t.is_sym(";") {
|
||||
return false;
|
||||
}
|
||||
if t.is_sym(".") {
|
||||
let entry_start = i == open + 1
|
||||
|| prev.line != t.line
|
||||
|| (depth == 0 && (prev.is_sym(",") || prev.kind == TokenKind::Attribute));
|
||||
if entry_start {
|
||||
return true;
|
||||
}
|
||||
} else if is_open(t) {
|
||||
depth += 1;
|
||||
} else if is_close(t) {
|
||||
if depth == 0 {
|
||||
return false;
|
||||
}
|
||||
depth -= 1;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the list opened at `open` belongs to a declaration's header: a
|
||||
/// [`DECLARATION_HEADERS`] keyword stands between it and the `;` that ended
|
||||
/// the item before.
|
||||
fn in_a_declaration_header(tokens: &[Token], open: usize) -> bool {
|
||||
tokens[..open]
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|t| !t.is_sym(";"))
|
||||
.any(|t| t.kind == TokenKind::Keyword && DECLARATION_HEADERS.contains(&t.text.as_str()))
|
||||
}
|
||||
|
||||
/// True on `(`, `[` or `{`.
|
||||
fn is_open(t: &Token) -> bool {
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// True on `)`, `]` or `}`.
|
||||
fn is_close(t: &Token) -> bool {
|
||||
t.is_sym(")") || t.is_sym("]") || t.is_sym("}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,350 @@
|
||||
//! The entry bounds, the withhold/release state machine with time injected,
|
||||
//! and what the parser's half buys the editor: the tokens and the findings
|
||||
//! after an unfinished entry are those of the completed one.
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use lsp_types::{DiagnosticSeverity, SemanticToken};
|
||||
|
||||
use super::*;
|
||||
use crate::state::Workspace;
|
||||
|
||||
fn uri(name: &str) -> Uri {
|
||||
Uri::from_str(&format!("file:///rtl/{name}")).expect("uri")
|
||||
}
|
||||
|
||||
/// A workspace holding `text` as `m.sv`.
|
||||
fn open(text: &str) -> (Workspace, Uri) {
|
||||
let uri = uri("m.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// `text` with the `|` marking the cursor taken out, and the cursor's offset.
|
||||
fn cursor(marked: &str) -> (String, u32) {
|
||||
let at = marked.find('|').expect("a `|` marks the cursor");
|
||||
(marked.replacen('|', "", 1), at as u32)
|
||||
}
|
||||
|
||||
/// The text of the entry around the `|` in `marked`, or `None`.
|
||||
fn entry_text(marked: &str) -> Option<String> {
|
||||
let (text, at) = cursor(marked);
|
||||
let (ws, uri) = open(&text);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
entry_around(doc, at).map(|r| text[r.as_range()].to_string())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Entry bounds
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_entry_runs_from_the_comma_before_to_the_close_after() {
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .p|);\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .p"));
|
||||
let got = entry_text("module m;\n sub u0 (.p|, .a(x));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".p"), "the list's own `(` is not the entry's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_inside_a_value_takes_the_whole_entry() {
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .b(y|), .c(z));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .b(y)"));
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .b({p, q|}), .c(z));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .b({p, q})"), "a `,` inside a bracket is the value's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_left_open_ends_with_its_line_and_reaches_the_next_dot() {
|
||||
// The parser's diagnostic is on the `(`; the next line opens a new entry,
|
||||
// whose `.` the entry reaches to.
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .po(|\n .b(y));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .po(\n "));
|
||||
// Typing on the line below an entry left open: the entry is that line's.
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .po(\n .b(y|));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".b(y)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_comma_is_inside_the_entry_typed_on_either_side_of_it() {
|
||||
// Typed below: the entry starts at its own line's `.`, which is where the
|
||||
// parser reports the missing `,`.
|
||||
let got = entry_text("module m;\n sub u0 (.a(x)\n .b(y|));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".b(y)"));
|
||||
// Typed above: the entry reaches the next line's `.`.
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .po|\n .b(y));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .po\n "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comma_is_inside_the_entry_after_it() {
|
||||
let got = entry_text("module m;\n sub u0 (.a(x),|\n );\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(","));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_list_has_entries_too() {
|
||||
let got = entry_text("module m;\n sub #(.W(8), .D|) u0 (.a(x));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .D"));
|
||||
let got = entry_text("module m;\n sub #(.W(|\n u0 (.a(x));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".W("), "an override typed open");
|
||||
}
|
||||
|
||||
/// The entry being typed is enough to make a list a named one, and so is
|
||||
/// any other named entry when the one being typed is still empty.
|
||||
#[test]
|
||||
fn a_named_list_is_recognised_from_any_named_entry() {
|
||||
let got = entry_text("module m;\n sub u0 (.po|);\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".po"));
|
||||
let got = entry_text("module m;\n sub u0 (.|);\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some("."));
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), |);\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", "), "a fresh entry after a `,`");
|
||||
}
|
||||
|
||||
/// QA's list (2026-11-17): every list `enclosing_list` accepts that is not
|
||||
/// an instance's named list withholds nothing.
|
||||
#[test]
|
||||
fn lists_that_are_not_named_connections_withhold_nothing() {
|
||||
for marked in [
|
||||
// A module header's parameter list.
|
||||
"module hm #(parameter W = |) (input logic a);\nendmodule\n",
|
||||
"interface hi #(parameter W = 1|);\nendinterface\n",
|
||||
"class hc #(type T = int|);\nendclass\n",
|
||||
// A positional instance list.
|
||||
"module m;\n sub u0 (x, y|, z);\nendmodule\n",
|
||||
// A function declaration with a user-type return.
|
||||
"module m;\n function automatic my_t f(input a|);\n endfunction\nendmodule\n",
|
||||
// A call right after a block label.
|
||||
"module m;\n initial begin : blk\n my_task(a, b|);\n end\nendmodule\n",
|
||||
// A fresh, still empty instance list: nothing named in it yet.
|
||||
"module m;\n sub u0 (|);\nendmodule\n",
|
||||
] {
|
||||
assert_eq!(entry_text(marked), None, "{marked}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_outside_a_connection_list_is_an_entry() {
|
||||
for marked in [
|
||||
"module m;\n wire w|;\nendmodule\n",
|
||||
"module m;\n sub u0| (.a(x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x));|\nendmodule\n",
|
||||
"module m;\n initial f(a, b|);\nendmodule\n",
|
||||
"module m (input a|, input b);\nendmodule\n",
|
||||
// A value left open makes the list's bracket look unclosed to the
|
||||
// end of the file; the `;` after it says the list is over.
|
||||
"module m;\n sub u0 (.a(x), .po(\n .b(y));\n wire w|;\nendmodule\n",
|
||||
] {
|
||||
assert_eq!(entry_text(marked), None, "{marked}");
|
||||
}
|
||||
// The next instance's own list is still found, and is its own.
|
||||
let marked = "module m;\n sub u0 (.a(x), .po(\n .b(y));\n sub u1 (.c|(z));\nendmodule\n";
|
||||
assert_eq!(entry_text(marked).as_deref(), Some(".c(z)"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Withholding
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A module whose port list is fine, so only the instance's entries say
|
||||
/// anything, plus one unrelated parse error far from the list.
|
||||
const TYPING: &str =
|
||||
"module m;\n logic x, y;\n sub u0 (.a(x),\n .po(\n .b(y));\n wire ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn only_the_entry_being_typed_is_withheld() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
|
||||
let now = Instant::now();
|
||||
ws.port_grace_mut().edited(&uri, Some(at), now);
|
||||
ws.locate_port_entry(&uri);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let all = crate::diagnostics::all(doc);
|
||||
let errors: Vec<_> =
|
||||
all.iter().filter(|d| d.severity == Some(DiagnosticSeverity::ERROR)).collect();
|
||||
assert_eq!(errors.len(), 2, "the open `(` and the `wire ;`: {all:#?}");
|
||||
let shown = ws.port_grace().withhold(&uri, doc, all.clone());
|
||||
assert_eq!(shown.len(), all.len() - 1, "exactly the entry's one: {shown:#?}");
|
||||
assert!(shown.iter().any(|d| d.range.start.line == 5), "the `wire ;` is still said");
|
||||
assert!(shown.iter().all(|d| d.range.start.line != 3), "{shown:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_outside_every_list_withholds_nothing() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let at = TYPING.find("wire ;").expect("wire") as u32 + 4;
|
||||
ws.port_grace_mut().edited(&uri, Some(at), Instant::now());
|
||||
ws.locate_port_entry(&uri);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let all = crate::diagnostics::all(doc);
|
||||
assert_eq!(ws.port_grace().withhold(&uri, doc, all.clone()), all);
|
||||
assert_eq!(ws.port_grace().deadline(), None, "no release is owed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_document_change_withholds_nothing() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
|
||||
ws.port_grace_mut().edited(&uri, Some(at), Instant::now());
|
||||
ws.port_grace_mut().edited(&uri, None, Instant::now());
|
||||
ws.locate_port_entry(&uri);
|
||||
assert_eq!(ws.port_grace().entry_of(&uri), None);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The release, with time injected
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A grace with one located entry in `uri`, edited at `t0`.
|
||||
fn held(ws: &mut Workspace, uri: &Uri, t0: Instant) {
|
||||
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
|
||||
ws.port_grace_mut().edited(uri, Some(at), t0);
|
||||
ws.locate_port_entry(uri);
|
||||
assert!(ws.port_grace().entry_of(uri).is_some(), "premise: the edit is in an entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_entry_is_released_when_the_quiet_period_ends() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let t0 = Instant::now();
|
||||
held(&mut ws, &uri, t0);
|
||||
assert_eq!(ws.port_grace().deadline(), Some(t0 + PORT_ENTRY_GRACE));
|
||||
let almost = t0 + PORT_ENTRY_GRACE - Duration::from_millis(1);
|
||||
assert!(ws.port_grace_mut().due(almost).is_empty(), "not a moment early");
|
||||
assert_eq!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE), vec![uri.clone()]);
|
||||
assert_eq!(ws.port_grace().entry_of(&uri), None, "released means withholding nothing");
|
||||
assert_eq!(ws.port_grace().deadline(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_edit_restarts_the_quiet_period() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let t0 = Instant::now();
|
||||
held(&mut ws, &uri, t0);
|
||||
let t1 = t0 + Duration::from_millis(1000);
|
||||
held(&mut ws, &uri, t1);
|
||||
assert!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE).is_empty());
|
||||
assert_eq!(ws.port_grace_mut().due(t1 + PORT_ENTRY_GRACE), vec![uri]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unanalyzed_edit_is_not_due() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let t0 = Instant::now();
|
||||
ws.port_grace_mut().edited(&uri, Some(3), t0);
|
||||
assert_eq!(ws.port_grace().deadline(), None, "pending: the flush has not looked yet");
|
||||
assert!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_in_another_buffer_releases_at_once() {
|
||||
let (mut ws, a) = open(TYPING);
|
||||
let b = uri("other.sv");
|
||||
let t0 = Instant::now();
|
||||
held(&mut ws, &a, t0);
|
||||
let t1 = t0 + Duration::from_millis(100);
|
||||
ws.port_grace_mut().edited(&b, Some(0), t1);
|
||||
assert_eq!(ws.port_grace().deadline(), Some(t0), "due already");
|
||||
assert_eq!(ws.port_grace_mut().due(t1), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forgetting_says_whether_anything_was_held() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
assert!(!ws.port_grace_mut().forget(&uri), "nothing to forget");
|
||||
ws.port_grace_mut().edited(&uri, Some(3), Instant::now());
|
||||
assert!(!ws.port_grace_mut().forget(&uri), "pending withholds nothing");
|
||||
held(&mut ws, &uri, Instant::now());
|
||||
assert!(ws.port_grace_mut().forget(&uri));
|
||||
assert_eq!(ws.port_grace().entry_of(&uri), None);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The parser's half, as the editor sees it
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The module `sub` and an instance of it with `entry` as its second
|
||||
/// connection, on a line of its own (line 4, 0-based), then more after it.
|
||||
fn with_entry(entry: &str) -> String {
|
||||
format!(
|
||||
"module sub (input logic a, input logic po, output logic b);\nendmodule\n\
|
||||
module m;\n logic x, y;\n sub u0 (.a(x),\n {entry}\n .b(y));\n \
|
||||
assign x = y;\n sub u1 (.a(y), .po(x), .b());\nendmodule\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Semantic tokens as absolute `(line, start, length, type, modifiers)`.
|
||||
fn absolute(tokens: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
let (mut line, mut start) = (0u32, 0u32);
|
||||
tokens
|
||||
.iter()
|
||||
.map(|t| {
|
||||
if t.delta_line > 0 {
|
||||
start = 0;
|
||||
}
|
||||
line += t.delta_line;
|
||||
start += t.delta_start;
|
||||
(line, start, t.length, t.token_type, t.token_modifiers_bitset)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the editor shows after the entry's line: the semantic tokens and the
|
||||
/// diagnostics, the latter as `(line, character, message)`.
|
||||
type After = (Vec<(u32, u32, u32, u32, u32)>, Vec<(u32, u32, String)>);
|
||||
|
||||
fn after_entry(text: &str) -> After {
|
||||
let (ws, uri) = open(text);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let entry_line = 5;
|
||||
let tokens = absolute(&crate::tokens::semantic_tokens(doc))
|
||||
.into_iter()
|
||||
.filter(|t| t.0 > entry_line)
|
||||
.collect();
|
||||
let diags = crate::diagnostics::all(doc)
|
||||
.into_iter()
|
||||
.filter(|d| d.range.start.line > entry_line)
|
||||
.map(|d| (d.range.start.line, d.range.start.character, d.message))
|
||||
.collect();
|
||||
(tokens, diags)
|
||||
}
|
||||
|
||||
/// The owner's ask: the rest of the file colours and lints as the
|
||||
/// auto-completed version (`.po` → `.po()`) would.
|
||||
#[test]
|
||||
fn after_an_unfinished_entry_the_file_reads_as_with_the_entry_completed() {
|
||||
// An entry the parser had to recover reads on to the next `.` as though
|
||||
// its `,` had been typed too.
|
||||
let done = after_entry(&with_entry(".po(),"));
|
||||
assert!(!done.0.is_empty(), "premise: there are tokens after the entry");
|
||||
assert!(done.1.is_empty(), "premise: the completed file says nothing: {:?}", done.1);
|
||||
for unfinished in [".po(", ".", ".po(x"] {
|
||||
assert_eq!(after_entry(&with_entry(unfinished)), done, "after `{unfinished}`");
|
||||
}
|
||||
// `.po` is already a whole (implicit) connection; what it still lacks is
|
||||
// the `,`, and so does its completion — the same one diagnostic, on the
|
||||
// `.` of the line after, in both.
|
||||
let done = after_entry(&with_entry(".po()"));
|
||||
assert_eq!(done.1.len(), 1, "{:?}", done.1);
|
||||
for unfinished in [".po", ".p"] {
|
||||
assert_eq!(after_entry(&with_entry(unfinished)), done, "after `{unfinished}`");
|
||||
}
|
||||
}
|
||||
|
||||
/// The unfinished entry is one parse error and nothing else: the entries
|
||||
/// written after it still resolve, so nothing about them is reported.
|
||||
#[test]
|
||||
fn an_unfinished_entry_costs_one_error_and_no_cascade() {
|
||||
for unfinished in [".po(", "."] {
|
||||
let (ws, uri) = open(&with_entry(unfinished));
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let errors: Vec<_> = crate::diagnostics::all(doc)
|
||||
.into_iter()
|
||||
.filter(|d| d.severity == Some(DiagnosticSeverity::ERROR))
|
||||
.collect();
|
||||
assert_eq!(errors.len(), 1, "`{unfinished}`: {errors:#?}");
|
||||
assert_eq!(errors[0].range.start.line, 5, "on the entry's own line");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,758 @@
|
||||
//! Driving a scan, whole or widen, from its work list to the landed
|
||||
//! tables: `begin_scan`/`begin_widen` take the list, `scan_step` indexes
|
||||
//! one file, `publish_scan` makes the tables answer for what has been
|
||||
//! staged so far, and `finish_scan` lands them. The one-shot forms the
|
||||
//! tests use are at the end.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use super::discover::oversize;
|
||||
use super::scan::{self, Analyzed, IndexEvent, Scan, ScanKind};
|
||||
use super::{StoreOpen, Workspace};
|
||||
use crate::candidates::Candidates;
|
||||
use crate::includes::{self, IncludeGraph};
|
||||
use crate::index_cache::IndexCache;
|
||||
use crate::scan_order::{self, WorkList};
|
||||
use crate::scan_trace::{CacheWork, ScanTrace};
|
||||
#[cfg(test)]
|
||||
use crate::settings::IndexScope;
|
||||
|
||||
impl Workspace {
|
||||
/// Take the work list one scan will run through: resolve the scope and put
|
||||
/// the user's own neighbourhood at the front of it.
|
||||
///
|
||||
/// **No file's text is read here** — only the open buffers', which are in
|
||||
/// memory already. Everything else is read at the step that indexes it
|
||||
/// ([`Workspace::scan_step`]), so the first file can be indexed as soon as
|
||||
/// the walk is done rather than after the whole scope has been read.
|
||||
///
|
||||
/// Nothing is indexed here and the live index is untouched, so a scan that
|
||||
/// is never stepped changes nothing but the view cache and the open cache
|
||||
/// handle.
|
||||
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent), trace: bool) -> Scan {
|
||||
let mut trace = ScanTrace::opened(&mut self.scans, trace, "whole");
|
||||
// A rescan says nothing about *which* file moved, so nothing held from
|
||||
// before it can be trusted.
|
||||
self.views.borrow_mut().clear();
|
||||
let discovering = trace.now();
|
||||
let mut skipped = 0usize;
|
||||
// The cap's skips are reported by `collect_sources` and counted here,
|
||||
// because the end message names them and the scan is what owns that
|
||||
// number now.
|
||||
let mut counting = |event: IndexEvent<'_>, skipped: &mut usize| {
|
||||
if matches!(event, IndexEvent::Skipped { .. }) {
|
||||
*skipped += 1;
|
||||
}
|
||||
watch(event);
|
||||
};
|
||||
let (mut scope, pending) = {
|
||||
let mut count = |event: IndexEvent<'_>| counting(event, &mut skipped);
|
||||
self.first_scope(&mut count, &mut trace)
|
||||
};
|
||||
ScanTrace::add(&mut trace.discovery_ms, discovering);
|
||||
let buffered = std::mem::take(&mut scope.buffered);
|
||||
let analyzed = std::mem::take(&mut scope.analyzed);
|
||||
let ordering = trace.now();
|
||||
// The same list the index will be built from, with the user's own
|
||||
// neighbourhood moved to the front of it.
|
||||
let WorkList { files: work, head } = self.open_first(std::mem::take(&mut scope.files));
|
||||
// A scan that has not walked the whole workspace yet cannot ask
|
||||
// whether its head is a minority of it — the count that would answer
|
||||
// is the walk it is postponing. `splits_discovery` is what bounds the
|
||||
// head instead, and it refuses exactly the case `worth_waiting`
|
||||
// refuses: a buffer whose folder is the workspace.
|
||||
let head = match pending.is_some() {
|
||||
true => head,
|
||||
false => scan_order::worth_waiting(head, work.len()),
|
||||
};
|
||||
let paths = work.clone();
|
||||
ScanTrace::add(&mut trace.order_ms, ordering);
|
||||
// Re-opened rather than held across rescans: the directory it belongs
|
||||
// in depends on settings that arrive after startup, and a second
|
||||
// session over the same workspace may have written records this one
|
||||
// has not seen. **Deferred** to the first file that asks the store
|
||||
// anything ([`StoreOpen`]), so a scan with no files reads nothing.
|
||||
self.store = StoreOpen::Deferred(self.cache_dir());
|
||||
trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work());
|
||||
Scan {
|
||||
kind: ScanKind::Whole,
|
||||
work,
|
||||
head,
|
||||
buffered,
|
||||
includes: HashMap::new(),
|
||||
unread: Vec::new(),
|
||||
paths,
|
||||
gone: Vec::new(),
|
||||
analyzed,
|
||||
incdirs: scope.incdirs,
|
||||
warnings: scope.warnings,
|
||||
at: 0,
|
||||
pending,
|
||||
staged: Vec::new(),
|
||||
staged_at: Vec::new(),
|
||||
words: HashMap::new(),
|
||||
skipped,
|
||||
cached: 0,
|
||||
trace,
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the work list for a **scope widen**: the files `added` brings into
|
||||
/// scope that the index does not already hold, plus every open buffer's own
|
||||
/// analysis.
|
||||
///
|
||||
/// The cheap answer to a `didOpen` in a folder the scope had not reached.
|
||||
/// A whole rescan re-reads, re-hashes and re-merges every file already
|
||||
/// indexed to learn about a handful of new ones; this reads only the new
|
||||
/// ones, and [`Workspace::finish_scan`] folds them in beside what is
|
||||
/// already there. What comes out is the index, the completion tables and
|
||||
/// the include graph a whole rescan would have produced — **given that the
|
||||
/// disk files already indexed have not changed since they were indexed**,
|
||||
/// which is the file watcher's job and is written down in
|
||||
/// `docs/features/index-scope/README.md`.
|
||||
///
|
||||
/// Two halves make that equivalence hold, and both are why this is not
|
||||
/// simply "index the new files":
|
||||
///
|
||||
/// * **every open buffer is re-indexed from the analysis it holds**, so a
|
||||
/// buffer carrying unsaved edits contributes those edits exactly as a
|
||||
/// whole rescan's `collect_sources` overlay would. That costs a fact walk
|
||||
/// and a word set per open buffer (~5 ms for a 1.4 MB buffer, rescan-reuse
|
||||
/// round) and no parse at all.
|
||||
/// * **a buffer on the large-file fast path contributes nothing**, so a
|
||||
/// file the index holds whose buffer has grown past the threshold is
|
||||
/// taken back out — the one thing a widen removes, and the same rule
|
||||
/// `collect_sources` follows.
|
||||
///
|
||||
/// `added` is the directories that entered [`Workspace::scope_dirs`]; the
|
||||
/// caller decides that they really are an addition and nothing else
|
||||
/// (`server.rs`'s `widen_of`).
|
||||
pub fn begin_widen(
|
||||
&mut self,
|
||||
added: &[PathBuf],
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
trace: bool,
|
||||
) -> Scan {
|
||||
let mut trace = ScanTrace::opened(&mut self.scans, trace, "widen");
|
||||
let discovering = trace.now();
|
||||
let held: HashSet<PathBuf> = self.index.files().iter().cloned().collect();
|
||||
let cap = self.client.max_file_size;
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let mut skipped = 0usize;
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
// The walk of the *added* directories alone, by the same rung-3 rules
|
||||
// `folder_files` follows — the whole scope is the union of these walks,
|
||||
// so the files this one finds beyond what is already indexed are
|
||||
// exactly the ones the widen owes.
|
||||
let mut stats = 0usize;
|
||||
for found in self.widened_files(added, &mut |w| warnings.push(w), &mut trace) {
|
||||
let path = found.path.clone();
|
||||
// Already indexed: by another scope directory this walk overlaps,
|
||||
// or by an earlier scan. Re-reading it is the cost this path
|
||||
// exists to avoid.
|
||||
if held.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
watch(IndexEvent::Skipped { path: &path, size, cap });
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if spoken_for.contains(path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
files.push(path);
|
||||
}
|
||||
let mut analyzed = Analyzed::default();
|
||||
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
|
||||
let mut gone: Vec<PathBuf> = Vec::new();
|
||||
for doc in self.docs.values() {
|
||||
let Some(path) = doc.path.clone() else { continue };
|
||||
files.retain(|taken| taken != &path);
|
||||
if doc.large {
|
||||
if held.contains(&path) {
|
||||
gone.push(path);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
|
||||
analyzed.words.insert(path.clone(), doc.words());
|
||||
buffered.insert(path.clone(), doc.text.clone());
|
||||
files.push(path);
|
||||
}
|
||||
ScanTrace::add(&mut trace.discovery_ms, discovering);
|
||||
let ordering = trace.now();
|
||||
let WorkList { files: work, head } = self.open_first(files);
|
||||
let head = scan_order::worth_waiting(head, work.len());
|
||||
ScanTrace::add(&mut trace.order_ms, ordering);
|
||||
trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work());
|
||||
// A whole scan drops the view cache entire, because a rescan claims
|
||||
// nothing about *which* file moved. A widen names exactly the files it
|
||||
// is reading, so it drops exactly those — which keeps the cache's own
|
||||
// rule ("every way a file's text can move drops its entry",
|
||||
// [`Workspace::file_view`]) literally true rather than nearly so.
|
||||
for path in &work {
|
||||
self.views.borrow_mut().retain(|view| &view.path != path);
|
||||
}
|
||||
// Which files exist once this widen lands: what the index holds, less
|
||||
// what it is about to lose, plus what the widen brings in.
|
||||
let mut paths: Vec<PathBuf> =
|
||||
held.into_iter().filter(|path| !gone.contains(path)).collect();
|
||||
paths.extend(work.iter().cloned());
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
gone.sort();
|
||||
Scan {
|
||||
kind: ScanKind::Widen,
|
||||
work,
|
||||
head,
|
||||
buffered,
|
||||
includes: HashMap::new(),
|
||||
unread: Vec::new(),
|
||||
paths,
|
||||
gone,
|
||||
analyzed,
|
||||
// Rung 3 is the only rung an open buffer can widen, and it names no
|
||||
// `+incdir+`. Carried from the graph in hand rather than assumed
|
||||
// empty, so folding a widen in never *changes* the search path.
|
||||
incdirs: self.includes.incdirs().to_vec(),
|
||||
// A widen resolves no filelist — rung 1 is not a scope an open
|
||||
// buffer can widen — so the only warnings here are the walk's own.
|
||||
warnings,
|
||||
at: 0,
|
||||
// A widen names the directories it is about to walk, so there is
|
||||
// never anything left to discover.
|
||||
pending: None,
|
||||
staged: Vec::new(),
|
||||
staged_at: Vec::new(),
|
||||
words: HashMap::new(),
|
||||
skipped,
|
||||
cached: 0,
|
||||
trace,
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the rest of the workspace, once the user's own neighbourhood has
|
||||
/// been indexed and published — the second half of a split discovery
|
||||
/// ([`PendingDiscovery`]). Reports whether there was anything to walk.
|
||||
///
|
||||
/// **Its own step, indexing nothing.** The step it shares a call with
|
||||
/// would otherwise report a file against a denominator that grew inside
|
||||
/// the same call, and a bar whose percentage falls is worse than one that
|
||||
/// waits (`docs/features/indexing-ux/README.md`). So this discovers, says
|
||||
/// "there is more", and lets the next step be an ordinary one.
|
||||
fn discover_the_rest(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
|
||||
let Some(mut pending) = scan.take_pending() else { return false };
|
||||
let discovering = scan.trace.now();
|
||||
let mut skipped = 0usize;
|
||||
let (files, warnings, walked_skips) = {
|
||||
let mut counting = |event: IndexEvent<'_>| {
|
||||
if matches!(event, IndexEvent::Skipped { .. }) {
|
||||
skipped += 1;
|
||||
}
|
||||
watch(event);
|
||||
};
|
||||
self.rest_of_scope(&mut pending, &mut counting, &mut scan.trace)
|
||||
};
|
||||
debug_assert_eq!(skipped, walked_skips, "the cap reports every skip it counts");
|
||||
ScanTrace::add(&mut scan.trace.discovery_ms, discovering);
|
||||
scan.land_discovery(files, warnings, walked_skips, pending.tracker.has_conflict());
|
||||
scan.trace.measure_work(
|
||||
scan.work.len(),
|
||||
held_bytes(&scan.buffered),
|
||||
scan.skipped,
|
||||
scan.trace.cache,
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
/// Open the store a whole rescan asked for, if this is the first thing to
|
||||
/// need it ([`StoreOpen`]).
|
||||
///
|
||||
/// Called from the two places that ask the store anything — a scan's step
|
||||
/// and a save's write-through — so a rescan that reaches no file never
|
||||
/// reads it, and the widen behind that rescan still finds it open the
|
||||
/// moment it reaches one.
|
||||
pub(super) fn open_store(&mut self, trace: &mut ScanTrace) {
|
||||
let StoreOpen::Deferred(dir) = std::mem::replace(&mut self.store, StoreOpen::Done) else {
|
||||
return;
|
||||
};
|
||||
let opening = trace.now();
|
||||
self.cache = IndexCache::open(dir);
|
||||
ScanTrace::add(&mut trace.cache_open_ms, opening);
|
||||
// The counters this scan is charged for start where the store it has
|
||||
// just opened does. A scan that never opens one keeps the baseline
|
||||
// `measure_work` took, so its delta is the nothing it did.
|
||||
trace.cache = CacheWork::default();
|
||||
}
|
||||
|
||||
/// Index the next file of `scan`, reporting whether there was one.
|
||||
///
|
||||
/// One file is the whole step: **its text is read**, its record is taken —
|
||||
/// from the open buffer's own analysis, from the persistent cache, or from
|
||||
/// a parse — its `` `include``s are scanned off that text and its
|
||||
/// completion words are taken off the record. All three are *staged* on
|
||||
/// the scan rather than merged, because merging is a pass over the whole
|
||||
/// workspace and one per file would be quadratic
|
||||
/// ([`WorkspaceIndex::absorb`]).
|
||||
///
|
||||
/// **The text is read here and dropped here** (2026-09-08). Everything the
|
||||
/// scan will ever want from it — the content hash the store is keyed by,
|
||||
/// the parse, the include lines — is taken in this one step, so a whole
|
||||
/// scan reads each file's bytes exactly once and holds one file's text at
|
||||
/// a time rather than the whole scope's. An **open buffer's** text is not
|
||||
/// read: it was taken with the work list, beside the analysis that
|
||||
/// describes the same bytes, so a `didChange` mid-scan cannot make the two
|
||||
/// disagree. A file that cannot be read is remembered as `unread` and
|
||||
/// contributes nothing, which is what a file `collect_sources` could not
|
||||
/// read used to do before the work list existed.
|
||||
pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
|
||||
let (done, total) = (scan.at, scan.work.len());
|
||||
if done == total {
|
||||
return self.discover_the_rest(scan, watch);
|
||||
}
|
||||
scan.at += 1;
|
||||
// The first file of a scan is the first thing to ask the store
|
||||
// anything, so it is where the store this scan asked for is opened.
|
||||
self.open_store(&mut scan.trace);
|
||||
let path = scan.work[done].clone();
|
||||
let Some(source) = scan.take_text(&path) else {
|
||||
scan.unread.push(path);
|
||||
return true;
|
||||
};
|
||||
let text = source.as_str();
|
||||
let held = scan.analyzed.facts.remove(&path);
|
||||
let known_words = scan.analyzed.words.remove(&path);
|
||||
let facts = match held {
|
||||
// An open buffer's own finished analysis comes first. It is the
|
||||
// only source of facts that is right when the buffer has unsaved
|
||||
// edits, which is precisely when the content-keyed cache below has
|
||||
// nothing to offer. The record is written through all the same, so
|
||||
// the next session starts from it.
|
||||
Some(facts) => {
|
||||
watch(IndexEvent::Analyzed { done, total, path: &path });
|
||||
scan.trace.buffers += 1;
|
||||
self.cache.record(&facts, text);
|
||||
facts
|
||||
}
|
||||
// The cache answers for the exact bytes about to be indexed, so a
|
||||
// hit is the parse and not a guess at it. A miss — a new file, a
|
||||
// changed one, a record this version cannot read — parses, and
|
||||
// the result is written through immediately, which is what makes
|
||||
// an interrupted scan resumable.
|
||||
None => match self.cache.facts_for(&path, text) {
|
||||
Some(facts) => {
|
||||
scan.cached += 1;
|
||||
watch(IndexEvent::Cached { done, total, path: &path });
|
||||
facts
|
||||
}
|
||||
None => {
|
||||
watch(IndexEvent::Parsing { done, total, path: &path });
|
||||
let parsing = scan.trace.now();
|
||||
let facts = FileFacts::of(path.clone(), text);
|
||||
ScanTrace::add(&mut scan.trace.parse_ms, parsing);
|
||||
scan.trace.parse_bytes += text.len();
|
||||
self.cache.record(&facts, text);
|
||||
facts
|
||||
}
|
||||
},
|
||||
};
|
||||
// Read off the record rather than lexed here: since `FACTS_FORMAT` 13
|
||||
// a file's identifier census *is* one of its facts, so a cached hit
|
||||
// brings its words with it and a parse harvested them from the tokens
|
||||
// it already had. That retires the per-file re-lex a scan used to pay
|
||||
// for the completion word table (TODO §10's deferred item;
|
||||
// `docs/features/semantic-lints-on/README.md` has the measurement).
|
||||
// An open buffer's words are still the caller's, read off the tokens
|
||||
// it was analyzed from.
|
||||
let words = known_words.unwrap_or_else(|| facts.words().to_vec());
|
||||
// Scanned here, off the text this step read, because the include graph
|
||||
// is built when the scan ends and by then the text is gone. It is a
|
||||
// line scan over bytes already in cache, and it replaces the identical
|
||||
// scan `IncludeGraph::build` used to run over the same text later.
|
||||
scan.includes.insert(path.clone(), includes::scan(text));
|
||||
scan.words.insert(path, words);
|
||||
scan.staged.push(facts);
|
||||
scan.staged_at.push(done);
|
||||
true
|
||||
}
|
||||
|
||||
/// The work list in the order a scan walks it: the open buffers' own
|
||||
/// files, then the rest of the folders those buffers raise to, then
|
||||
/// everything else in path order ([`crate::scan_order`]).
|
||||
///
|
||||
/// **A reporting and latency decision and nothing else.**
|
||||
/// `vlog_semantic::IndexBuilder` sorts by path inside `finish` since
|
||||
/// 2026-08-27, so no insertion order can reach the index: this changes
|
||||
/// which file the progress bar names first — the user's own, and then
|
||||
/// what they are looking at across the folder — and changes nothing about
|
||||
/// the result. Pinned both ends: the builder's own
|
||||
/// `no_insertion_order_can_change_what_the_builder_produces`, and
|
||||
/// `the_open_files_are_indexed_first_and_the_index_cannot_tell` here.
|
||||
/// Re-order what is left of `scan` around the buffers open **now** — the
|
||||
/// same ranking [`Workspace::begin_scan`] applied, re-applied because a
|
||||
/// `didOpen` answered mid-scan changed the answer to "where is the user
|
||||
/// working?".
|
||||
///
|
||||
/// Called after the burst carrying that `didOpen` has been applied, so the
|
||||
/// buffer is installed and the folder it raises to is known. What was
|
||||
/// already indexed is untouched; only the tail moves, and the finished
|
||||
/// index cannot tell ([`Scan::reorder`]).
|
||||
/// **The rest of the workspace is walked first when it has not been.** A
|
||||
/// split startup is leading with the folder the user *was* in; a `didOpen`
|
||||
/// says they are somewhere else now, and re-ordering a work list that does
|
||||
/// not yet contain the new folder would answer the request behind that
|
||||
/// `didOpen` off a prefix that cannot hold what it is asking about. The
|
||||
/// walk this order postpones is exactly what makes the new folder
|
||||
/// nameable, so it happens here
|
||||
/// (`docs/features/perf5r-first-answer/README.md`).
|
||||
pub fn open_next(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) {
|
||||
self.discover_the_rest(scan, watch);
|
||||
let ordered = self.open_first(scan.remaining());
|
||||
scan.reorder(ordered);
|
||||
}
|
||||
|
||||
fn open_first(&self, files: Vec<PathBuf>) -> WorkList {
|
||||
let open: Vec<PathBuf> = self.docs.values().filter_map(|doc| doc.path.clone()).collect();
|
||||
scan_order::work_list(files, &open, &self.raised_dirs())
|
||||
}
|
||||
|
||||
/// Make every table answer for the files `scan` has taken since the last
|
||||
/// publish — the moment a mid-scan answer is worth paying a merge for.
|
||||
///
|
||||
/// **All three tables together, never one of them.** The index, the
|
||||
/// completion tables and the include graph are what an answer reads, and a
|
||||
/// hover that saw a scanned file while a completion or an include link
|
||||
/// could not would make "the workspace as far as it has been scanned"
|
||||
/// three different things at once. Each is folded in with the batch form
|
||||
/// of the incremental update it already had, so one publish is one pass
|
||||
/// over the index and not one per file.
|
||||
pub fn publish_scan(&mut self, scan: &mut Scan) {
|
||||
if scan.staged.is_empty() {
|
||||
return;
|
||||
}
|
||||
let taken = std::mem::take(&mut scan.staged_at);
|
||||
let absorbing = scan.trace.now();
|
||||
self.index.absorb(std::mem::take(&mut scan.staged), &[]);
|
||||
ScanTrace::add(&mut scan.trace.publish_absorb_ms, absorbing);
|
||||
let completing = scan.trace.now();
|
||||
let published: Vec<PathBuf> = taken.iter().map(|&at| scan.work[at].clone()).collect();
|
||||
let words = published
|
||||
.iter()
|
||||
.map(|path| (path.clone(), scan.words.get(path).cloned().unwrap_or_default()))
|
||||
.collect();
|
||||
self.candidates.absorb(&self.index, words);
|
||||
ScanTrace::add(&mut scan.trace.publish_candidates_ms, completing);
|
||||
let including = scan.trace.now();
|
||||
let found = scan::included(&scan.includes, &published);
|
||||
self.includes.absorb_includes(&scan.incdirs, &scan.paths, &found);
|
||||
ScanTrace::add(&mut scan.trace.publish_includes_ms, including);
|
||||
let refreshing = scan.trace.now();
|
||||
// Every open buffer resolves against the index, so a buffer whose
|
||||
// cross-file names the scan has just reached must be able to see them.
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
ScanTrace::add(&mut scan.trace.publish_overlay_ms, refreshing);
|
||||
scan.trace.saw_publish(taken.len());
|
||||
}
|
||||
|
||||
/// Finish `scan`: the index, the completion tables, the include graph and
|
||||
/// every open buffer's overlay. Reports the warnings from resolving the
|
||||
/// scope.
|
||||
///
|
||||
/// **What comes out is the index a one-shot scan over the same work list
|
||||
/// would have produced**, however many times [`Workspace::publish_scan`]
|
||||
/// ran in between: a publish only ever folds records in, and the index's
|
||||
/// tables are a pure function of the records it holds
|
||||
/// ([`WorkspaceIndex::absorb`]).
|
||||
pub fn finish_scan(&mut self, scan: Scan) -> Vec<String> {
|
||||
match scan.kind {
|
||||
ScanKind::Whole => self.finish_whole_scan(scan),
|
||||
ScanKind::Widen => self.finish_widen(scan),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Workspace::finish_scan`] for a whole scan.
|
||||
fn finish_whole_scan(&mut self, scan: Scan) -> Vec<String> {
|
||||
let Scan {
|
||||
mut work, unread, incdirs, warnings, staged, words, includes, mut trace, ..
|
||||
} = scan;
|
||||
// What the scan really indexed, which is its work list unless a file
|
||||
// left the disk between the walk and its own step. Such a file is not
|
||||
// in scope any more, so it must land in `gone` exactly as it would
|
||||
// have if the walk had missed it.
|
||||
work.retain(|path| !unread.contains(path));
|
||||
let found = scan::included(&includes, &work);
|
||||
let leaving = trace.now();
|
||||
// Whatever the last scan left in the index that this one's work list
|
||||
// does not name is a file that is no longer in scope.
|
||||
let held: HashSet<&Path> = work.iter().map(PathBuf::as_path).collect();
|
||||
let gone: Vec<PathBuf> = self
|
||||
.index
|
||||
.files()
|
||||
.iter()
|
||||
.filter(|path| !held.contains(path.as_path()))
|
||||
.cloned()
|
||||
.collect();
|
||||
ScanTrace::add(&mut trace.gone_ms, leaving);
|
||||
let absorbing = trace.now();
|
||||
self.index.absorb(staged, &gone);
|
||||
ScanTrace::add(&mut trace.absorb_ms, absorbing);
|
||||
// The one moment the live set of entries is known, so the one moment
|
||||
// the append log is worth rewriting — and only when this scan reached
|
||||
// a file at all. A scan with an empty work list asked the store
|
||||
// nothing and never opened it, so there is nothing of this session's
|
||||
// in it and nothing to rewrite it from (§P4b (b1)); the rewrite of a
|
||||
// store that *is* open is itself skipped when it would reproduce the
|
||||
// file byte for byte ([`IndexCache::compact`], §P4b (a)).
|
||||
if matches!(self.store, StoreOpen::Done) {
|
||||
self.cache.compact();
|
||||
}
|
||||
let completing = trace.now();
|
||||
// Built from the words every step took off its own record — the same
|
||||
// list, so a file the scope ladder excluded contributes no completion
|
||||
// candidates either, and nothing is lexed twice.
|
||||
self.candidates = Candidates::from_words(&self.index, words);
|
||||
ScanTrace::add(&mut trace.candidates_ms, completing);
|
||||
let including = trace.now();
|
||||
// Same list again: an `` `include`` in a file the scope excluded is
|
||||
// not an edge, and a file it excluded is not a hop away from anything.
|
||||
// The lines themselves were read at each file's own step.
|
||||
self.includes = IncludeGraph::from_includes(&found, incdirs);
|
||||
ScanTrace::add(&mut trace.includes_ms, including);
|
||||
let refreshing = trace.now();
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
ScanTrace::add(&mut trace.overlay_ms, refreshing);
|
||||
self.landed(trace);
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Close a scan's trace: the tables it left behind, measured, and the
|
||||
/// whole thing set aside for the server to log.
|
||||
///
|
||||
/// Every size it reads is a walk, so the trace itself decides whether to
|
||||
/// take them ([`ScanTrace::landed`]); a scan nobody traced sets nothing
|
||||
/// aside.
|
||||
fn landed(&mut self, mut trace: ScanTrace) {
|
||||
trace.landed(self.docs.len(), &self.cache, &self.index, &self.candidates, &self.includes);
|
||||
if trace.on() {
|
||||
self.last_trace = trace;
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace of the scan that just finished, taken away — an inert one
|
||||
/// when the scan was not being traced.
|
||||
pub fn take_scan_trace(&mut self) -> ScanTrace {
|
||||
std::mem::take(&mut self.last_trace)
|
||||
}
|
||||
|
||||
/// [`Workspace::finish_scan`] for a widen: the same three tables, folded
|
||||
/// into rather than replaced.
|
||||
///
|
||||
/// Each table is landed with the batch form of the incremental update it
|
||||
/// already had, which is the same one [`Workspace::publish_scan`] uses —
|
||||
/// so what comes out is what a whole scan over the union of the old files
|
||||
/// and the new ones would have produced. The three claims that makes, one
|
||||
/// per table:
|
||||
///
|
||||
/// * **the index** — [`WorkspaceIndex::absorb`] keeps the records
|
||||
/// path-sorted and one to a path and merges them the way a whole build
|
||||
/// does;
|
||||
/// * **the completion tables** — the two index-derived ones are re-derived
|
||||
/// from the index, and the word table is patched per file into the same
|
||||
/// total order a whole build sorts into;
|
||||
/// * **the include graph** — the known-file and folded-spelling tables are
|
||||
/// relearned from the whole in-scope list and every held edge is
|
||||
/// re-spelled against it (the graph is rebuilt from every file's staged
|
||||
/// include list, [`IncludeGraph::from_includes`]), so a file that is in
|
||||
/// scope for the first time can lend its spelling to an edge that was
|
||||
/// resolved before it arrived.
|
||||
///
|
||||
/// One thing a whole scan does that this deliberately does not: the
|
||||
/// persistent store is **not compacted**. A widen does not know the live
|
||||
/// set of entries — it only added to it — and the next whole rescan
|
||||
/// rewrites the log anyway.
|
||||
fn finish_widen(&mut self, scan: Scan) -> Vec<String> {
|
||||
let Scan {
|
||||
mut work,
|
||||
mut paths,
|
||||
gone,
|
||||
incdirs,
|
||||
warnings,
|
||||
staged,
|
||||
words,
|
||||
includes,
|
||||
mut trace,
|
||||
unread,
|
||||
..
|
||||
} = scan;
|
||||
// A widen only ever adds, so a file whose text had gone by its own
|
||||
// step is simply not added — it is in neither list below.
|
||||
work.retain(|path| !unread.contains(path));
|
||||
paths.retain(|path| !unread.contains(path));
|
||||
let found = scan::included(&includes, &work);
|
||||
let absorbing = trace.now();
|
||||
self.index.absorb(staged, &gone);
|
||||
ScanTrace::add(&mut trace.absorb_ms, absorbing);
|
||||
// Before the additions, so the two never disagree about a path that is
|
||||
// in both lists — which cannot happen today (a large buffer is in
|
||||
// neither `work` nor `paths`) and would be a silent wrong answer if it
|
||||
// ever did.
|
||||
for path in &gone {
|
||||
self.candidates.remove_file(&self.index, path);
|
||||
self.includes.remove_file(path, &paths);
|
||||
}
|
||||
let batch: Vec<(PathBuf, Vec<String>)> = work
|
||||
.iter()
|
||||
.map(|path| (path.clone(), words.get(path).cloned().unwrap_or_default()))
|
||||
.collect();
|
||||
let completing = trace.now();
|
||||
self.candidates.absorb(&self.index, batch);
|
||||
ScanTrace::add(&mut trace.candidates_ms, completing);
|
||||
let including = trace.now();
|
||||
self.includes.absorb_includes(&incdirs, &paths, &found);
|
||||
ScanTrace::add(&mut trace.includes_ms, including);
|
||||
let refreshing = trace.now();
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
ScanTrace::add(&mut trace.overlay_ms, refreshing);
|
||||
self.landed(trace);
|
||||
warnings
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The one-shot forms: the protocol above run to the end in one call.
|
||||
// Test-only, every one of them — the server drives the three calls
|
||||
// itself so that it can answer messages between two of them.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Adopt the workspace roots and build the index for the first time.
|
||||
/// Returns whatever the caller should tell the user about the scope.
|
||||
///
|
||||
/// The unwatched form. `server.rs` always watches (it has a progress bar
|
||||
/// to move), so this is reachable from tests alone — of which there are
|
||||
/// several dozen across this crate, and none of them has an opinion about
|
||||
/// progress reporting.
|
||||
#[cfg(test)]
|
||||
pub fn open_roots(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
|
||||
self.open_roots_with(roots, &mut |_| {})
|
||||
}
|
||||
|
||||
/// [`Workspace::open_roots`] with `lucisv.index.scope` set to
|
||||
/// `"workspace"`: adopt the roots and index **all** of them, which is what
|
||||
/// every session did before 2026-08-27.
|
||||
///
|
||||
/// Test-only, and used by the dozens of tests across this crate that are
|
||||
/// about something other than scope — a hover, a rename, an inlay hint —
|
||||
/// and want the whole fixture tree in the index without opening a buffer
|
||||
/// in each of its directories first. Spelling it out at the call site is
|
||||
/// what keeps "this test wants the wide scope" a statement rather than an
|
||||
/// accident. The folder scope's own behaviour is tested by the tests named
|
||||
/// in `docs/features/index-scope/README.md`.
|
||||
#[cfg(test)]
|
||||
pub fn open_whole_workspace(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
|
||||
self.open_whole_workspace_with(roots, &mut |_| {})
|
||||
}
|
||||
|
||||
/// [`Workspace::open_whole_workspace`], watched. Test-only, for the two
|
||||
/// tests that want the wide scope *and* the events.
|
||||
#[cfg(test)]
|
||||
pub fn open_whole_workspace_with(
|
||||
&mut self,
|
||||
roots: Vec<PathBuf>,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
) -> Vec<String> {
|
||||
self.client.index_scope = IndexScope::Workspace;
|
||||
self.open_roots_with(roots, watch)
|
||||
}
|
||||
|
||||
/// [`Workspace::open_roots`], watched — the unwatched form's sibling, and
|
||||
/// test-only for the same reason: the server drives the scan itself now,
|
||||
/// one file at a time, so it adopts the roots and steps the scan rather
|
||||
/// than calling this.
|
||||
#[cfg(test)]
|
||||
pub fn open_roots_with(
|
||||
&mut self,
|
||||
roots: Vec<PathBuf>,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
) -> Vec<String> {
|
||||
self.adopt_roots(roots);
|
||||
self.rebuild_index_with(watch)
|
||||
}
|
||||
|
||||
/// Re-scan the workspace and rebuild the index and the completion tables,
|
||||
/// then refresh every open buffer's overlay. Called on `initialize` and on
|
||||
/// every `didSave`.
|
||||
///
|
||||
/// Returns the warnings from resolving the scope — a filelist naming a
|
||||
/// file that is gone, say. Rendering them is `server.rs`'s job; this
|
||||
/// module speaks no protocol.
|
||||
///
|
||||
/// The unwatched form, reachable from tests alone for the same reason
|
||||
/// `open_roots` is.
|
||||
#[cfg(test)]
|
||||
pub fn rebuild_index(&mut self) -> Vec<String> {
|
||||
self.rebuild_index_with(&mut |_| {})
|
||||
}
|
||||
|
||||
/// [`Workspace::rebuild_index`], watched: `watch` is called once for every
|
||||
/// file the size cap skipped and once for every file about to be parsed,
|
||||
/// in index order and before the parse, so a caller can report where the
|
||||
/// rescan has got to.
|
||||
///
|
||||
/// The events cover the index build alone. The completion tables and the
|
||||
/// include graph are built from the same list afterwards and are not
|
||||
/// reported: they cost a small fraction of the parse, and a bar that went
|
||||
/// to 100% and then sat there would be worse than one that ends.
|
||||
///
|
||||
/// A scan with nothing happening between its files, which is what every
|
||||
/// caller but the server's message loop wants. The loop drives the same
|
||||
/// three calls itself and answers messages between two of them
|
||||
/// (`docs/features/scan-interleave/README.md`) — so "one shot" and
|
||||
/// "interleaved" are not two scans that have to be kept in step, they are
|
||||
/// this loop with and without a drain in it.
|
||||
///
|
||||
/// Test-only for that reason: the server takes the three calls, and this
|
||||
/// is what every test that just wants an index calls instead.
|
||||
#[cfg(test)]
|
||||
pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec<String> {
|
||||
let mut scan = self.begin_scan(watch, false);
|
||||
while self.scan_step(&mut scan, watch) {}
|
||||
self.finish_scan(scan)
|
||||
}
|
||||
|
||||
/// [`Workspace::begin_widen`] run to the end in one shot, the way
|
||||
/// [`Workspace::rebuild_index_with`] runs a whole scan. Test-only for the
|
||||
/// same reason: the server drives the three calls itself.
|
||||
#[cfg(test)]
|
||||
pub fn widen_index(&mut self, added: &[PathBuf]) -> Vec<String> {
|
||||
self.widen_index_with(added, &mut |_| {})
|
||||
}
|
||||
|
||||
/// [`Workspace::widen_index`], watched.
|
||||
#[cfg(test)]
|
||||
pub fn widen_index_with(
|
||||
&mut self,
|
||||
added: &[PathBuf],
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
) -> Vec<String> {
|
||||
let mut scan = self.begin_widen(added, watch, false);
|
||||
while self.scan_step(&mut scan, watch) {}
|
||||
self.finish_scan(scan)
|
||||
}
|
||||
}
|
||||
|
||||
/// How many bytes of buffer text a scan carries for its whole life — every
|
||||
/// other file's text lives from its own step to the end of that step.
|
||||
fn held_bytes(buffered: &HashMap<PathBuf, String>) -> usize {
|
||||
buffered.values().map(String::len).sum()
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! What decides the scope: the workspace roots, the `lucisv.*` settings a
|
||||
//! client pushed, and the ladder they select — which rung is in force and
|
||||
//! which directories it walks.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::{StoreOpen, Workspace};
|
||||
use crate::index_cache::IndexCache;
|
||||
use crate::settings::{ClientSettings, IndexScope};
|
||||
|
||||
impl Workspace {
|
||||
/// Take the workspace roots without indexing anything.
|
||||
///
|
||||
/// The half of [`Workspace::open_roots_with`] that is not a scan, for the
|
||||
/// caller that drives the scan itself — the server, which runs the startup
|
||||
/// scan through the same interleaved path every later rescan takes.
|
||||
pub fn adopt_roots(&mut self, roots: Vec<PathBuf>) {
|
||||
self.roots = roots;
|
||||
}
|
||||
|
||||
/// Add and remove workspace roots mid-session, reporting whether the set
|
||||
/// actually moved — which is whether the caller owes a rebuild.
|
||||
///
|
||||
/// Removals are applied before additions, so a folder named in both lists
|
||||
/// (which the protocol does not forbid, and which is how some clients
|
||||
/// spell "this folder moved") ends up present. Adding a root that is
|
||||
/// already held and removing one that was never held are both no-ops, and
|
||||
/// say so by leaving the set equal: `didChangeWorkspaceFolders` is a
|
||||
/// notification, so there is nowhere to report a disagreement to and
|
||||
/// nothing to gain from re-scanning for one.
|
||||
pub fn change_roots(&mut self, added: Vec<PathBuf>, removed: &[PathBuf]) -> bool {
|
||||
let before = self.roots.clone();
|
||||
self.roots.retain(|root| !removed.contains(root));
|
||||
for root in added {
|
||||
if !self.roots.contains(&root) {
|
||||
self.roots.push(root);
|
||||
}
|
||||
}
|
||||
self.roots != before
|
||||
}
|
||||
|
||||
/// Whether the client opened a workspace at all.
|
||||
///
|
||||
/// Without one there is nothing to walk but the open buffers' own
|
||||
/// directories, and nothing to clamp the folder scope's climb against.
|
||||
///
|
||||
/// Test-only since 2026-08-27: `didOpen` used to branch on it, and now
|
||||
/// branches on whether the file widened the scope, which is the same
|
||||
/// question asked of the rung that is actually in force.
|
||||
#[cfg(test)]
|
||||
pub fn has_roots(&self) -> bool {
|
||||
!self.roots.is_empty()
|
||||
}
|
||||
|
||||
/// The workspace folders, in the order the client named them.
|
||||
///
|
||||
/// The first one is what a relative path in a setting is resolved against,
|
||||
/// which is what [`Workspace::filelist_path`] does inline and what
|
||||
/// `lucisv.lint.waivers` needs too.
|
||||
pub fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// The directories the folder scope walks: every directory a buffer has
|
||||
/// been opened from this session, each raised `lucisv.index.scopeDepth`
|
||||
/// levels. **Empty when the folder scope is not the active rung** — a
|
||||
/// filelist and the whole-workspace walk are scopes an open buffer cannot
|
||||
/// widen.
|
||||
///
|
||||
/// Public because `server.rs` compares it across a `didOpen` to decide
|
||||
/// whether the file just opened widened the scope, which is the one thing
|
||||
/// that makes a `didOpen` worth a rebuild.
|
||||
pub fn scope_dirs(&self) -> Vec<PathBuf> {
|
||||
if !self.folder_scoped() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
|
||||
dirs.sort();
|
||||
dirs.dedup();
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Whether rung 3 — the folder scope — is the one in force.
|
||||
///
|
||||
/// A filelist outranks it, and so does an explicit
|
||||
/// `lucisv.index.scope: "workspace"` **when there is a workspace to
|
||||
/// walk**: with no roots there is nothing that setting could name, so a
|
||||
/// rootless session is folder-scoped whatever it says.
|
||||
fn folder_scoped(&self) -> bool {
|
||||
self.filelist_path().is_none() && !self.walks_the_workspace()
|
||||
}
|
||||
|
||||
/// Whether rung 2 — the walk of every workspace folder — is in force.
|
||||
pub(super) fn walks_the_workspace(&self) -> bool {
|
||||
self.client.index_scope == IndexScope::Workspace && !self.roots.is_empty()
|
||||
}
|
||||
|
||||
/// `dir` raised `lucisv.index.scopeDepth` ancestor levels, clamped twice:
|
||||
/// it never climbs above the workspace root that contains it — the deepest
|
||||
/// one, for nested roots — and never above the filesystem root, which is
|
||||
/// where a directory belonging to no root stops.
|
||||
///
|
||||
/// The root clamp is what keeps a `scopeDepth` of 5 in a two-deep project
|
||||
/// from indexing the user's home directory.
|
||||
///
|
||||
/// **A rootless session does not climb at all** (2026-08-28). The clamp is
|
||||
/// the whole reason a raise is safe, and with no workspace folder there is
|
||||
/// nothing to clamp against: a lone file opened from
|
||||
/// `~/work/chip/hw/ip/aes/rtl/` would otherwise raise the shipped
|
||||
/// [`crate::settings::DEFAULT_SCOPE_DEPTH`] into `~/work/chip/hw/ip/` and
|
||||
/// walk a tree the user never named. The single-file case stays what it
|
||||
/// has always been — the buffer's own directory, read flat — and a user
|
||||
/// who wants more opens the folder, which is what gives the climb a floor.
|
||||
fn raised(&self, dir: &Path) -> PathBuf {
|
||||
if self.roots.is_empty() {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
let floor = self
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|root| dir.starts_with(root))
|
||||
.max_by_key(|root| root.components().count());
|
||||
let mut out = dir;
|
||||
for _ in 0..self.client.index_scope_depth {
|
||||
if Some(out) == floor.map(PathBuf::as_path) {
|
||||
break;
|
||||
}
|
||||
let Some(parent) = out.parent() else { break };
|
||||
out = parent;
|
||||
}
|
||||
out.to_path_buf()
|
||||
}
|
||||
|
||||
/// The directories the open buffers' own folders raise to, whichever rung
|
||||
/// of the ladder is in force.
|
||||
///
|
||||
/// [`Workspace::scope_dirs`] answers the same question *as a scope* and is
|
||||
/// therefore empty unless rung 3 is in force. This one is an **ordering**
|
||||
/// question — where in the workspace the user is working — and it has the
|
||||
/// same answer under a filelist or an explicit `workspace` scope, where it
|
||||
/// is the only thing that says which part of a 4 000-file walk to index
|
||||
/// first.
|
||||
pub(super) fn raised_dirs(&self) -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
|
||||
dirs.sort();
|
||||
dirs.dedup();
|
||||
dirs
|
||||
}
|
||||
|
||||
/// The `lucisv.*` settings in force, for the resolution points in
|
||||
/// `format.rs` to fold in.
|
||||
pub fn client_settings(&self) -> &ClientSettings {
|
||||
&self.client
|
||||
}
|
||||
|
||||
/// Adopt the settings a client pushed.
|
||||
///
|
||||
/// Returns `true` when the caller must rebuild the index: `exclude`,
|
||||
/// `filelist`, `index.maxFileSize`, `index.scope` and `index.scopeDepth`
|
||||
/// are the five that change *which files exist* as far as this server is
|
||||
/// concerned. `lineLength` and `indent` are read afresh by every
|
||||
/// formatting request, so they need no invalidation at all — and neither
|
||||
/// does `index.logFiles`, which changes only how loudly the *next* rescan
|
||||
/// narrates itself.
|
||||
///
|
||||
/// `largeFile.threshold` asks for no rescan either, and deliberately: it
|
||||
/// is consulted where a `Document` is *built*, so a change to it reaches
|
||||
/// each open buffer at that buffer's next `didOpen`/`didChange` and not
|
||||
/// before. A rescan now would index by the mode each buffer is still in,
|
||||
/// which is the mode the index already reflects
|
||||
/// (`docs/features/large-file-mode/README.md`).
|
||||
pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool {
|
||||
let rescan = self.client.exclude != settings.exclude
|
||||
|| self.client.filelist != settings.filelist
|
||||
|| self.client.max_file_size != settings.max_file_size
|
||||
|| self.client.index_scope != settings.index_scope
|
||||
|| self.client.index_scope_depth != settings.index_scope_depth;
|
||||
// Neither cache setting changes *which files exist*, so neither asks
|
||||
// for a rescan — but both change where, or whether, the cache writes,
|
||||
// and the cache in hand was opened under the old ones. Dropping it
|
||||
// here is what makes `persist: false` take effect at once in both
|
||||
// directions: nothing more is written, and nothing held is read. The
|
||||
// next whole rescan opens the store the new settings name.
|
||||
if self.client.index_persist != settings.index_persist
|
||||
|| self.client.index_cache_path != settings.index_cache_path
|
||||
{
|
||||
self.cache = IndexCache::disabled();
|
||||
// And a deferred re-open goes with it, or the next file to want
|
||||
// the store would open the directory the old settings named.
|
||||
self.store = StoreOpen::Done;
|
||||
}
|
||||
self.client = settings;
|
||||
rescan
|
||||
}
|
||||
|
||||
/// Where the persistent index cache should live, by
|
||||
/// [`crate::index_cache::cache_dir`]'s ladder — the client's setting, the
|
||||
/// editor's storage folder, this platform's cache directory, or nowhere.
|
||||
pub(super) fn cache_dir(&self) -> Option<PathBuf> {
|
||||
// In this crate's own tests nothing falls through to the OS cache
|
||||
// directory: a unit test must not write into the developer's own
|
||||
// `~/Library/Caches`, and every test that is *about* the cache names
|
||||
// a directory of its own — a `cachePath` or a `storagePath` — which
|
||||
// the ladder below still answers with. The OS rung itself is tested
|
||||
// where it is written, against `index_cache::cache_dir` directly.
|
||||
#[cfg(test)]
|
||||
if self.client.index_cache_path.is_none() && self.storage.is_none() {
|
||||
return None;
|
||||
}
|
||||
crate::index_cache::cache_dir(
|
||||
&self.client,
|
||||
self.storage.as_deref(),
|
||||
&self.roots,
|
||||
self.filelist_path().as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Adopt `initializationOptions.storagePath` — the folder the editor set
|
||||
/// aside for this workspace's server state.
|
||||
///
|
||||
/// Called once, before the first index build, because it is one rung of
|
||||
/// the ladder that decides where the cache is read from. A client that
|
||||
/// sends nothing leaves the OS cache directory to decide.
|
||||
pub fn set_storage_path(&mut self, storage: Option<PathBuf>) {
|
||||
self.storage = storage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! The file sets handed to the refactorings: the whole scope, or — for a
|
||||
//! port edit, a rename, a file rename — the fan-out the index already
|
||||
//! bounds, so a request reads a handful of files instead of the workspace.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use vlog_semantic::{Def, FileId};
|
||||
|
||||
use super::scan::{HeldAnalyses, Sources};
|
||||
use super::Workspace;
|
||||
use crate::module_select::{self, Reach};
|
||||
use crate::rename_trace::{self, Rung, SelectionTrace, Wanted};
|
||||
use crate::scan_trace::ScanTrace;
|
||||
|
||||
impl Workspace {
|
||||
/// The in-scope files and their current text — what a refactoring reads.
|
||||
///
|
||||
/// The same list `rebuild_index` feeds the index, recomputed rather than
|
||||
/// kept: a refactoring is a rare, user-initiated request, and a second
|
||||
/// copy of the workspace in memory is a high price for saving one walk.
|
||||
///
|
||||
/// This is the one caller that really does want every file's text at once,
|
||||
/// so it is where the read a scan no longer does in one pass still
|
||||
/// happens. A file that cannot be read contributes nothing, exactly as it
|
||||
/// did when `collect_sources` read them all.
|
||||
pub fn sources(&self) -> Vec<(PathBuf, String)> {
|
||||
let Sources { files, mut buffered, .. } =
|
||||
self.collect_sources(&mut |_| {}, HeldAnalyses::Unused, &mut ScanTrace::new(false));
|
||||
files
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let text = match buffered.remove(&path) {
|
||||
Some(text) => text,
|
||||
None => fs::read_to_string(&path).ok()?,
|
||||
};
|
||||
Some((path, text))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The in-scope files a port refactoring on `modules`, requested in `file`,
|
||||
/// can read or write — [`Workspace::sources`] narrowed to the fan-out the
|
||||
/// index already holds.
|
||||
///
|
||||
/// A `textDocument/codeAction` arrives on every cursor move and
|
||||
/// `sources()` reads the whole file set from disk, so a cursor resting on
|
||||
/// an instantiation used to cost one workspace read per keystroke (3.1 s
|
||||
/// on OpenTitan, and every queued request waited behind it). The index
|
||||
/// knows who declares a module and who instantiates it, so the engine can
|
||||
/// be handed those files and nothing else. Why the smaller set gives the
|
||||
/// same answer is argued in `docs/features/refactor-ports/README.md`; the
|
||||
/// four rungs are:
|
||||
///
|
||||
/// * **the file the request names**, whatever else it is;
|
||||
/// * **every file declaring one of `modules`** ([`WorkspaceIndex::units`])
|
||||
/// — all of them, so a name declared twice still refuses instead of
|
||||
/// quietly picking the one definer that made it into the set;
|
||||
/// * **every file that instantiates one** ([`WorkspaceIndex::instantiations_of`])
|
||||
/// or otherwise refers to one ([`WorkspaceIndex::references_to`]) —
|
||||
/// between them, every file the plan can edit and every file whose
|
||||
/// meaning the verifier could see move;
|
||||
/// * **every open buffer**, because its unsaved text may add or remove an
|
||||
/// instantiation the saved edges do not know about.
|
||||
///
|
||||
/// Each file's text comes from the same place `collect_sources` takes it:
|
||||
/// the open buffer when there is one, disk otherwise, and neither for a
|
||||
/// buffer on the large-file fast path or a file over the size cap.
|
||||
pub fn module_sources(&self, file: &Path, modules: &[String]) -> Vec<(PathBuf, String)> {
|
||||
self.module_sources_reaching(file, modules, Reach::none())
|
||||
}
|
||||
|
||||
/// [`Workspace::module_sources`] plus the **fifth rung**: every file whose
|
||||
/// tokens write one of `reach`'s scope names down
|
||||
/// ([`crate::module_select`], topology handshake 33).
|
||||
///
|
||||
/// Only inline-module asks for it, and only because its `no_hierarchy`
|
||||
/// refusal is about a path *through* the instance it dissolves rather
|
||||
/// than about either module's name: a testbench two wrapper levels above
|
||||
/// is in none of the four rungs. The rung can only add files, so every
|
||||
/// other caller's answer is untouched — and so is its cost, since
|
||||
/// [`Reach::none`] walks nothing.
|
||||
pub fn module_sources_reaching(
|
||||
&self,
|
||||
file: &Path,
|
||||
modules: &[String],
|
||||
reach: Reach<'_>,
|
||||
) -> Vec<(PathBuf, String)> {
|
||||
let mut wanted: BTreeSet<PathBuf> = module_select::hierarchical_users(&self.index, reach);
|
||||
wanted.insert(file.to_path_buf());
|
||||
for name in modules {
|
||||
for def in self.index.units(name) {
|
||||
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
|
||||
for site in self.index.references_to(def) {
|
||||
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
for edge in self.index.instantiations_of(name) {
|
||||
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
wanted
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let text = self.current_text(&path)?;
|
||||
Some((path, text))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The in-scope files a rename of `name` — to `new_name`, when the request
|
||||
/// carries one — can read, write or refuse over: [`Workspace::sources`]
|
||||
/// narrowed to what the index already knows about those two spellings.
|
||||
///
|
||||
/// A `textDocument/rename` cost 3.6–8.7 s on OpenTitan and a
|
||||
/// `prepareRename` 2.5–3.0 s, almost all of it re-reading, re-parsing and
|
||||
/// re-indexing 3 976 files to find the handful that spell one name. The
|
||||
/// index holds every declaration of a name and every use it resolved, so
|
||||
/// the engine can be handed those files and nothing else. **Why the
|
||||
/// smaller set gives the same answer is argued in full in
|
||||
/// `docs/features/refactor-rename/README.md`**; the rungs are:
|
||||
///
|
||||
/// * **the file the request names**, whatever else it is;
|
||||
/// * **every open buffer**, whose unsaved text the index has not seen —
|
||||
/// the one place this set deliberately does not trust the index;
|
||||
/// * per spelling `N` in `{name, new_name}`:
|
||||
/// * **every file declaring `N`** — as a unit or as a member of one
|
||||
/// ([`WorkspaceIndex::workspace_symbols`], filtered to the exact
|
||||
/// name). This is the rung the whole equality argument turns on:
|
||||
/// `follow_paths` only ever looks a reference's *own* name up, so a
|
||||
/// set holding every declarer of `N` resolves every reference spelling
|
||||
/// `N` exactly as the whole workspace does;
|
||||
/// * **every file declaring `N` on a module's hierarchical surface**
|
||||
/// ([`WorkspaceIndex::hierarchical_declarations`]) — an internal net
|
||||
/// is not a workspace symbol, and a hierarchical tail in another file
|
||||
/// resolves to one;
|
||||
/// * **every file with a use the index resolved to one of them**
|
||||
/// ([`WorkspaceIndex::references_to`]) — every file a rename can edit,
|
||||
/// and every file whose meaning the verifier could see move;
|
||||
/// * **every file instantiating `N`**
|
||||
/// ([`WorkspaceIndex::instantiations_of`]), which records a site whose
|
||||
/// reference resolved to nothing and therefore has no posting;
|
||||
/// * **every file whose `` `define`` table names `N` or spells it in a
|
||||
/// macro body**, walked over the tables the index already holds, for
|
||||
/// the two `` `define`` warnings;
|
||||
/// * **the units that export `N` as a member**, and every file
|
||||
/// declaring, referring to or instantiating one of those — how a third
|
||||
/// file's `.N(...)` connection or `u::N` is reached.
|
||||
/// * and, for the **new** name only, **every file that spells it in a use
|
||||
/// this workspace had to look outside that file to answer, including
|
||||
/// the uses it could not answer at all**
|
||||
/// ([`WorkspaceIndex::files_spelling`]).
|
||||
///
|
||||
/// **Why that last rung is the new name's alone.** It exists because a
|
||||
/// rename can give a name that meant *nothing* a meaning: `import
|
||||
/// taken_pkg::*` in a file with no other tie to the rename resolves to
|
||||
/// nothing today and to the renamed package tomorrow, which the
|
||||
/// whole-workspace verifier refuses over and the first five rungs cannot
|
||||
/// see. The old name has no such case, because a rename only ever
|
||||
/// **removes** declarations of it: a use of the old name that resolves is
|
||||
/// in that declaration's postings (rung 2, which walks *every* declaration
|
||||
/// of the name, not only the target's), and one that resolves to nothing
|
||||
/// still resolves to nothing afterwards — a lookup cannot start
|
||||
/// succeeding because a candidate was taken away. So the old name's uses
|
||||
/// are either already in the set or provably unmoved, and scanning for
|
||||
/// them would buy nothing.
|
||||
///
|
||||
/// One escape hatch, and it is the honest one: when the index says a
|
||||
/// declaration of `N` is named by an **ambiguous** use
|
||||
/// ([`WorkspaceIndex::references_are_ambiguous`]), the file holding that
|
||||
/// use is in no posting table, and the whole-workspace rename refuses
|
||||
/// because of it. Rather than lose that refusal, this hands back
|
||||
/// `sources()` and the slow path answers.
|
||||
/// It also says **which rung asked for each file**: [`Wanted`] is a path
|
||||
/// set that records the first rung to insert a path, so watching the
|
||||
/// selection cannot change it (take 5 §P2a).
|
||||
pub fn rename_sources_traced(
|
||||
&self,
|
||||
file: &Path,
|
||||
name: &str,
|
||||
new_name: Option<&str>,
|
||||
) -> (Vec<(PathBuf, String)>, SelectionTrace) {
|
||||
let started = Instant::now();
|
||||
let elapsed = |at: Instant| at.elapsed().as_secs_f64() * 1000.0;
|
||||
let mut wanted = Wanted::new();
|
||||
wanted.insert(file.to_path_buf());
|
||||
for spelling in [Some(name), new_name].into_iter().flatten() {
|
||||
if !self.fan_out_of(spelling, &mut wanted) {
|
||||
let sources = self.sources();
|
||||
let trace = SelectionTrace::whole_scope(sources.len(), elapsed(started));
|
||||
return (sources, trace);
|
||||
}
|
||||
}
|
||||
// The sixth rung, and the **new** name's alone. See the doc comment
|
||||
// above for why the old name does not need it.
|
||||
if let Some(new_name) = new_name {
|
||||
wanted.on(Rung::Speller);
|
||||
self.want_spellers(new_name, &mut wanted);
|
||||
}
|
||||
wanted.on(Rung::OpenBuffer);
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
let (mut paths, mut trace) = wanted.finish();
|
||||
// One hop down: the modules those files instantiate, so a `.*` into
|
||||
// one is read rather than refused (M3.5). In `selected`, under no rung.
|
||||
let handed: Vec<&Path> = paths.keys().map(PathBuf::as_path).collect();
|
||||
for below in module_select::instantiated_by(&self.index, &handed) {
|
||||
paths.entry(below).or_insert(Rung::Instantiation);
|
||||
}
|
||||
// §P2d's census: which rungs asked for files that write neither name
|
||||
// down, and therefore contribute to this request only by shaping how
|
||||
// the others resolve. One record lookup per selected file, no read.
|
||||
trace.indirect =
|
||||
rename_trace::indirect_census(&self.index, &paths, [name, new_name.unwrap_or(name)]);
|
||||
let texts: Vec<(PathBuf, String)> = paths
|
||||
.into_keys()
|
||||
.filter_map(|path| {
|
||||
let text = self.current_text(&path)?;
|
||||
Some((path, text))
|
||||
})
|
||||
.collect();
|
||||
// A file a rung wanted whose text this workspace no longer contributes
|
||||
// (deleted, oversize, a fast-path buffer) is counted by its rung and
|
||||
// is not in the input: the rungs total the *wanted* set, `selected`
|
||||
// the one the engine gets.
|
||||
trace.selected = texts.len();
|
||||
trace.ms = elapsed(started);
|
||||
(texts, trace)
|
||||
}
|
||||
|
||||
/// Add one spelling's fan-out to `wanted`. `false` means the index cannot
|
||||
/// bound it — see [`Workspace::rename_sources_traced`]'s escape hatch.
|
||||
fn fan_out_of(&self, name: &str, wanted: &mut Wanted) -> bool {
|
||||
// Every declaration of the name, wherever it is written. `units` alone
|
||||
// would miss a port, a parameter or a package member, and those are
|
||||
// exactly the declarations a `.port` connection or a `pkg::x` reaches
|
||||
// across files for.
|
||||
let mut containers: BTreeSet<&str> = BTreeSet::new();
|
||||
for symbol in self.index.workspace_symbols(name) {
|
||||
if symbol.name != name {
|
||||
continue;
|
||||
}
|
||||
if self.index.references_are_ambiguous(symbol.def) {
|
||||
return false;
|
||||
}
|
||||
containers.extend(symbol.container);
|
||||
self.want_declaration(symbol.def, wanted);
|
||||
}
|
||||
// And every declaration of it on a module's **hierarchical** surface,
|
||||
// which `workspace_symbols` deliberately does not list: an internal
|
||||
// net is not a workspace symbol, but `assign w = u_x.sig;` in another
|
||||
// file resolves to one and a rename must edit both ends. Without this
|
||||
// rung the fan-out would hold the file that *names* the net and not
|
||||
// the file that declares it (`docs/features/hierarchical-tail`).
|
||||
for (unit, def) in self.index.hierarchical_declarations(name) {
|
||||
if self.index.references_are_ambiguous(def) {
|
||||
return false;
|
||||
}
|
||||
containers.insert(unit);
|
||||
self.want_declaration(def, wanted);
|
||||
}
|
||||
self.want_sites(name, wanted);
|
||||
self.want_macro_text(name, wanted);
|
||||
for unit in containers {
|
||||
for def in self.index.units(unit) {
|
||||
self.want_declaration(def, wanted);
|
||||
}
|
||||
self.want_sites(unit, wanted);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// One declaration's own file, and every file the index recorded a use of
|
||||
/// it in.
|
||||
fn want_declaration(&self, def: &Def, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::Declaration);
|
||||
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
|
||||
wanted.on(Rung::Reference);
|
||||
for site in self.index.references_to(def) {
|
||||
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
|
||||
}
|
||||
// A use written as a hierarchical path (`tb.dut.u_core.sig`) resolves
|
||||
// inside the engine's set only if the set declares every unit the
|
||||
// path walks through — the top module it is rooted at and each hop's
|
||||
// type — so their declaring files come too (top-rooted-paths QA F3).
|
||||
// Only files the index has: a unit outside the scope is not in it,
|
||||
// and the path stays unresolved and warned about.
|
||||
wanted.on(Rung::Declaration);
|
||||
for unit in self.index.path_units_to(def) {
|
||||
for unit_def in self.index.units(&unit) {
|
||||
wanted.extend(self.index.path(unit_def.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file that instantiates a name — the census the reference postings
|
||||
/// cannot speak for, because an instantiation of something the workspace
|
||||
/// does not declare resolves to nothing and is posted nowhere.
|
||||
fn want_sites(&self, name: &str, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::Instantiation);
|
||||
for edge in self.index.instantiations_of(name) {
|
||||
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file that spells a name in a use the index had to look outside
|
||||
/// that file to answer, **including the uses it could not answer at all**
|
||||
/// ([`WorkspaceIndex::files_spelling`]).
|
||||
///
|
||||
/// The rung that closes the rename's one lost refusal (QA, 2026-08-28).
|
||||
/// A file whose only tie to the new name is `import new_name::*` of a
|
||||
/// package nothing declares yet holds no declaration, no posting, no
|
||||
/// instantiation edge and no macro entry — and the rename is exactly what
|
||||
/// gives that import a meaning, which the whole-workspace verifier refuses
|
||||
/// over. Only the postings' *keys* miss it; the per-file records keep every
|
||||
/// external use by the name it spells, so this reads it back.
|
||||
fn want_spellers(&self, name: &str, wanted: &mut Wanted) {
|
||||
for file in self.index.files_spelling(name) {
|
||||
wanted.extend(self.index.path(file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file whose `` `define`` table names the name or spells it in a
|
||||
/// macro **body** — the two warnings `Scope::define_sites` produces.
|
||||
///
|
||||
/// The index holds every file's `DefineTable` already, so this is a walk
|
||||
/// over tables in memory: no file is read and nothing is parsed. The
|
||||
/// question is asked with `vlog_refactor::contains_word`, which is the
|
||||
/// function `define_sites` itself decides with, so the fan-out and the
|
||||
/// warning cannot disagree about which files carry one.
|
||||
fn want_macro_text(&self, name: &str, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::MacroText);
|
||||
for id in 0..self.index.files().len() {
|
||||
let file = FileId(id as u32);
|
||||
let Some(defines) = self.index.defines(file) else { continue };
|
||||
let touched = defines.entries().iter().any(|define| {
|
||||
define.name == name || vlog_refactor::contains_word(&define.body, name)
|
||||
});
|
||||
if touched {
|
||||
wanted.extend(self.index.path(file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The in-scope files a `workspace/willRenameFiles` can rewrite: the ones
|
||||
/// the include graph recorded a resolving `` `include`` in, plus every open
|
||||
/// buffer.
|
||||
///
|
||||
/// `will_rename` reads a file only to scan its `` `include``s and asks the
|
||||
/// graph where each one lands; a file whose includes all resolve to nothing
|
||||
/// — or that has none — contributes neither an edit nor a warning, and the
|
||||
/// graph's edge table is exactly the set of files that have at least one
|
||||
/// resolving include. So reading the rest was reading the whole workspace
|
||||
/// to answer "nothing" 3 900 times. Open buffers are added whatever the
|
||||
/// graph holds: the graph is rebuilt on save, so an `` `include`` typed and
|
||||
/// not yet saved is in the buffer and not in the edges.
|
||||
pub fn include_sources(&self) -> Vec<(PathBuf, String)> {
|
||||
let mut wanted: BTreeSet<PathBuf> = self.includes.includers().cloned().collect();
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
wanted
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let text = self.current_text(&path)?;
|
||||
Some((path, text))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! A `Document`'s own analysis: the two token searches against the sweep
|
||||
//! they replaced, what a buffer holds once analyzed, and — TODO §63.2 QA —
|
||||
//! the trace's arithmetic, attacked with the three shapes TODO.md names: a
|
||||
//! buffer that fails to lex, a `define` edit that changes the macro table,
|
||||
//! and (via the server-level parity re-run) an edit that moves a fence.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The precondition both binary searches rest on. If the lexer ever emits
|
||||
/// a token out of order, or two tokens that overlap, `partition_point`'s
|
||||
/// predicates stop being monotone and every handler that calls
|
||||
/// [`first_token_reaching`] or [`first_token_from`] starts answering
|
||||
/// something else. This is the test that would fail first.
|
||||
#[test]
|
||||
fn the_token_stream_rises_and_never_overlaps() {
|
||||
let text = mixed_buffer(20);
|
||||
let doc = Document::new(None, text, &WorkspaceIndex::default());
|
||||
assert!(doc.tokens.len() > 500, "premise: a stream worth searching");
|
||||
for pair in doc.tokens.windows(2) {
|
||||
assert!(pair[0].span.start <= pair[1].span.start, "{pair:?}");
|
||||
assert!(pair[0].span.end <= pair[1].span.start, "overlapping tokens: {pair:?}");
|
||||
assert!(pair[0].span.start <= pair[0].span.end, "an inverted span: {pair:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Both searches, against the sweep they stand in for, at every byte of a
|
||||
/// buffer full of tokens that touch.
|
||||
#[test]
|
||||
fn every_offset_finds_the_token_a_sweep_would_have_found() {
|
||||
let text = mixed_buffer(20);
|
||||
let doc = Document::new(None, text.clone(), &WorkspaceIndex::default());
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc.tokens.iter().position(|t| t.span.end >= offset);
|
||||
assert_eq!(
|
||||
first_token_reaching(&doc.tokens, offset),
|
||||
swept.unwrap_or(doc.tokens.len()),
|
||||
"first token reaching {offset}"
|
||||
);
|
||||
let swept = doc.tokens.iter().position(|t| t.span.start >= offset);
|
||||
assert_eq!(
|
||||
first_token_from(&doc.tokens, offset),
|
||||
swept.unwrap_or(doc.tokens.len()),
|
||||
"first token from {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_analyzes_a_clean_file() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(doc.diagnostics.is_empty());
|
||||
assert_eq!(doc.path.as_deref(), Some(Path::new("/rtl/m.sv")));
|
||||
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"));
|
||||
assert!(!doc.tokens.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_file_still_analyzes() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire ;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(!doc.diagnostics.is_empty(), "a broken buffer must report");
|
||||
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"), "and still bind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_lex_has_no_tokens_but_has_a_diagnostic() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a; /* unterminated\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(doc.tokens.is_empty());
|
||||
assert_eq!(doc.diagnostics.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untitled_buffer_has_no_path() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("untitled:Untitled-1"), "module m;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("untitled:Untitled-1")).expect("open");
|
||||
assert_eq!(doc.path, None);
|
||||
}
|
||||
|
||||
/// A buffer that never lexes still reports a `Lex` stage (the failed
|
||||
/// attempt is real work and costs real time) and a `Parse` stage (the
|
||||
/// `parse_source_tolerant` fallback), and still counts as one document.
|
||||
/// `defines`/`analyze`/`external`/`lines` all still run over the empty
|
||||
/// token stream and empty-error tree exactly as the un-instrumented
|
||||
/// path always did — the wrapping must not skip a stage just because
|
||||
/// an earlier one errored.
|
||||
#[test]
|
||||
fn a_buffer_that_fails_to_lex_still_records_every_rebuild_stage() {
|
||||
crate::lint_trace::arm();
|
||||
// An unterminated string literal is an unambiguous lex error that
|
||||
// does not depend on lexer internals that could drift between
|
||||
// versions (`vlog_parser::tokenize` is documented all-or-nothing).
|
||||
let text = "module m;\n string s = \"unterminated\nendmodule\n".to_string();
|
||||
let doc = Document::new(None, text, &WorkspaceIndex::default());
|
||||
assert!(doc.tokens.is_empty(), "a lex failure leaves an empty token stream");
|
||||
assert!(!doc.diagnostics.is_empty(), "a lex failure is a diagnostic");
|
||||
let trace = crate::lint_trace::disarm().expect("armed");
|
||||
// Every stage's field is present on the line, whether or not it
|
||||
// took measurable time (`saw_document`, not a duration, is what
|
||||
// says a rebuild happened at all — see the flaky test this round
|
||||
// fixed in `lint_trace.rs`).
|
||||
let line = trace.line();
|
||||
assert!(line.contains("documents=1"), "{line}");
|
||||
for stage in ["lex=", "parse=", "defines=", "analyze=", "external=", "lines=", "publish="] {
|
||||
assert!(line.contains(stage), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `` `define `` edit changes the macro table `collect_defines`
|
||||
/// produces, and nothing about wrapping that call in `rebuild` changes
|
||||
/// which tokens it sees or what it returns: the new revision's table
|
||||
/// reflects only the new text, never a stale value from the revision
|
||||
/// before it (`Document::new` builds a fresh `DefineTable` every time,
|
||||
/// same as before this round).
|
||||
#[test]
|
||||
fn a_define_edit_changes_the_macro_table_the_rebuild_reports_on() {
|
||||
crate::lint_trace::arm();
|
||||
let before = Document::new(
|
||||
None,
|
||||
"`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] w;\nendmodule\n".to_string(),
|
||||
&WorkspaceIndex::default(),
|
||||
);
|
||||
assert_eq!(before.defines.latest("WIDTH").map(|d| d.body.trim()), Some("8"));
|
||||
assert!(before.defines.latest("DEPTH").is_none());
|
||||
|
||||
let after = Document::new(
|
||||
None,
|
||||
"`define DEPTH 16\nmodule m;\n wire [`DEPTH-1:0] w;\nendmodule\n".to_string(),
|
||||
&WorkspaceIndex::default(),
|
||||
);
|
||||
assert!(after.defines.latest("WIDTH").is_none(), "no macro survives across documents");
|
||||
assert_eq!(after.defines.latest("DEPTH").map(|d| d.body.trim()), Some("16"));
|
||||
|
||||
let trace = crate::lint_trace::disarm().expect("armed");
|
||||
let line = trace.line();
|
||||
assert!(line.contains("documents=2"), "two fresh Document::new calls, two rebuilds: {line}");
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Rung 1 of the scope ladder: a filelist defines the index exactly, its
|
||||
//! warnings reach the caller, and its `+incdir+`s reach the include graph.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A tree with three packages, one of which a filelist deliberately omits.
|
||||
fn filelist_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
tree.package("rtl/unlisted.sv", "unlisted");
|
||||
tree.write("files.f", "// the project\nrtl/a.sv\nrtl/b.sv\n");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_filelist_defines_the_index_exactly() {
|
||||
// The point of a filelist: a file sitting in the tree that the project
|
||||
// does not build is not indexed, however much the walk would find it.
|
||||
let tree = filelist_tree("filelistkey");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
let warnings = ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_filelist_setting_beats_the_config_key_and_may_be_absolute() {
|
||||
let tree = filelist_tree("filelistsetting");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
tree.write("other.f", "rtl/unlisted.sv\n");
|
||||
|
||||
// Relative: against the workspace root, not the current directory.
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("other.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"], "the setting wins");
|
||||
|
||||
// Absolute: taken as written.
|
||||
let absolute = tree.path.join("other.f");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist(&absolute.display().to_string()));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so() {
|
||||
// The failure that must never happen: an empty index and no
|
||||
// explanation because a path in a settings UI has a typo.
|
||||
let tree = filelist_tree("filelistgone");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("typo.f"));
|
||||
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"], "the walk ran");
|
||||
assert_eq!(warnings.len(), 1);
|
||||
assert!(warnings[0].contains("typo.f"), "{warnings:?}");
|
||||
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
|
||||
// TODO §45.2: the walk's warnings ride out on the scope's own
|
||||
// warnings, which the server logs once per scan. Before the channel
|
||||
// existed the walk returned an error the index simply dropped, so a
|
||||
// permission-denied directory cost every file after it silently.
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tree = Tree::new("walkwarn");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/z.sv", "z");
|
||||
tree.package("locked/hidden.sv", "hidden");
|
||||
std::os::unix::fs::symlink("nowhere.sv", tree.path.join("rtl/gone.sv")).expect("symlink");
|
||||
let locked = tree.path.join("locked");
|
||||
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o755));
|
||||
|
||||
assert_eq!(indexed(&ws, &["a", "z", "hidden"]), ["a", "z"], "the scan finished");
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("locked")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("gone.sv: broken symbolic link")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelists_own_warnings_reach_the_caller() {
|
||||
let tree = filelist_tree("filelistwarn");
|
||||
tree.write("files.f", "rtl/a.sv\nrtl/moved.sv\n-nonsense\n");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
let warnings = ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a"], "the rest is still indexed");
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("moved.sv")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("-nonsense")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_is_indexed_even_when_the_filelist_omits_it() {
|
||||
// Open buffers overlay every rung of the ladder: a scratch file the
|
||||
// project does not build still gets its own symbols.
|
||||
let tree = filelist_tree("filelistbuffer");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
|
||||
let path = tree.path.join("rtl/unlisted.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package unlisted;\n localparam K = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_no_workspace_root_the_open_files_own_directory_is_indexed() {
|
||||
// The single-file case: no folder was opened, so the scope is what
|
||||
// sits beside the buffer — and nothing below it.
|
||||
let tree = Tree::new("noroot");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.package("rtl/sibling.sv", "sibling");
|
||||
tree.package("rtl/deeper/below.sv", "below");
|
||||
tree.package("elsewhere/far.sv", "far");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
assert!(!ws.has_roots(), "the premise: no workspace folder");
|
||||
let path = tree.path.join("rtl/open.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
|
||||
assert_eq!(
|
||||
indexed(&ws, &["open_pkg", "sibling", "below", "far"]),
|
||||
["open_pkg", "sibling"],
|
||||
"the buffer and its neighbours only"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_still_wins_when_there_is_no_workspace_root() {
|
||||
let tree = filelist_tree("norootfilelist");
|
||||
let mut ws = Workspace::default();
|
||||
// With no root a relative setting cannot be anchored, so an absolute
|
||||
// path is the only sensible way to name one — and it works.
|
||||
ws.set_client_settings(using_filelist(&tree.path.join("files.f").display().to_string()));
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
|
||||
}
|
||||
|
||||
/// Where `ws` would look for `` `include "<name>" `` written in `from`.
|
||||
fn resolved_include(ws: &Workspace, from: &Path, name: &str) -> Option<PathBuf> {
|
||||
let text = format!("`include \"{name}\"\n");
|
||||
let include = crate::includes::scan(&text).into_iter().next().expect("one include");
|
||||
ws.includes().resolve(Some(from), &include)
|
||||
}
|
||||
|
||||
/// A tree whose filelist names one `+incdir+` and nests a filelist naming
|
||||
/// another, with a header in each — plus one only the nested incdir holds.
|
||||
fn incdir_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("first/defs.svh", "`define W 1\n");
|
||||
tree.write("ip/include/defs.svh", "`define W 2\n");
|
||||
tree.write("ip/include/ip_only.svh", "`define X 1\n");
|
||||
tree.write("ip/ip.f", "+incdir+include\n");
|
||||
tree.write("files.f", "+incdir+first\n-f ip/ip.f\nrtl/a.sv\n");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelists_incdirs_reach_the_include_graph_in_filelist_order() {
|
||||
// M1 recorded `+incdir+` and used it for nothing; this is the wire
|
||||
// that spends it. A nested `-f`'s incdirs come through flattened,
|
||||
// *after* the ones named before the `-f` — which is the order an
|
||||
// include is searched in, so it is worth pinning here and not only in
|
||||
// the parser.
|
||||
let tree = incdir_tree("incdirs");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
let warnings = ws.open_roots(vec![tree.path.clone()]);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
|
||||
let from = tree.path.join("rtl/a.sv");
|
||||
assert_eq!(
|
||||
resolved_include(&ws, &from, "defs.svh"),
|
||||
Some(tree.path.join("first/defs.svh")),
|
||||
"the root filelist's incdir is searched before the nested one's"
|
||||
);
|
||||
assert_eq!(
|
||||
resolved_include(&ws, &from, "ip_only.svh"),
|
||||
Some(tree.path.join("ip/include/ip_only.svh")),
|
||||
"and the nested one is searched at all"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_filelist_there_are_no_incdirs_at_all() {
|
||||
// Rungs 2 and 3 of the ladder name no include path, so an `` `include``
|
||||
// there has only the including file's own directory to go on.
|
||||
let tree = incdir_tree("noincdirs");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_filelist_leaves_the_include_graph_without_incdirs() {
|
||||
let tree = incdir_tree("badfilelistincdirs");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("typo.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"),
|
||||
None,
|
||||
"the walk fallback names no include path"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
//! The folder scope (index-scope, 2026-08-27): rung 3's climb and the two
|
||||
//! clamps on it, what outranks it, and the inherited obligations from that
|
||||
//! round's review.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A project laid out the way the owner described it: the file being
|
||||
/// worked on in `rtl/`, a header folder beside it, and a third folder that
|
||||
/// has nothing to do with either.
|
||||
fn two_folder_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.package("rtl/beside.sv", "beside_pkg");
|
||||
tree.package("rtl/deeper/below.sv", "below_pkg");
|
||||
tree.package("include/defs.sv", "defs_pkg");
|
||||
tree.package("elsewhere/far.sv", "far_pkg");
|
||||
tree
|
||||
}
|
||||
|
||||
/// The four fixture packages, as the ones that are in the index.
|
||||
fn scoped(ws: &Workspace) -> Vec<String> {
|
||||
indexed(ws, &["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_folder_scope_at_depth_zero_is_the_open_files_own_folder_and_everything_under_it() {
|
||||
// The headline of the index-scope round: a workspace root is open, but
|
||||
// the index covers the folder the user is working in, not the project.
|
||||
// At depth 0 — the shipped default until 2026-08-28, and still exactly
|
||||
// what an explicit `scopeDepth: 0` asks for.
|
||||
let tree = two_folder_tree("scopedefault");
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert!(scoped(&ws).is_empty(), "premise: nothing is open, so nothing is in scope");
|
||||
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "beside_pkg", "below_pkg"],
|
||||
"the buffer's own folder and its subtree — and no sibling folder"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_depth_of_one_reaches_the_folder_beside_it() {
|
||||
// `rtl/` plus `../include`: the layout the setting exists for.
|
||||
let tree = two_folder_tree("scopedepth");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
|
||||
"one level up is the whole tree here, sibling folders included"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_climb_stops_at_the_workspace_root() {
|
||||
// The clamp that keeps a depth of 99 in a two-deep project from
|
||||
// indexing the user's home directory. Asserted on the directories
|
||||
// themselves rather than on an index, because the failure this guards
|
||||
// against is a walk that should never be started.
|
||||
let tree = two_folder_tree("scopeclamp");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/deeper/below.sv");
|
||||
assert_eq!(ws.scope_dirs(), vec![tree.path.clone()], "clamped at the root, not above it");
|
||||
|
||||
// The deepest containing root wins, so a nested root clamps tighter.
|
||||
assert!(ws.change_roots(vec![tree.path.join("rtl")], &[]));
|
||||
assert_eq!(ws.scope_dirs(), vec![tree.path.join("rtl")], "the deepest root is the floor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rootless_session_does_not_climb_at_all() {
|
||||
// Changed 2026-08-28, with the shipped depth. The climb used to run
|
||||
// with `/` as its only floor, which was survivable while the shipped
|
||||
// depth was 0 and nobody climbed by accident. It is not survivable at
|
||||
// depth 2: a lone file opened from `~/work/chip/hw/ip/aes/rtl/` would
|
||||
// raise into `~/work/chip/hw/ip/` and walk a tree the user never
|
||||
// named. The clamp is what makes a raise safe, so with nothing to
|
||||
// clamp against there is no raise, whatever the depth says.
|
||||
let tree = two_folder_tree("scoperootless");
|
||||
for depth in [0, 1, 99] {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: depth, ..Default::default() });
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
assert!(!ws.has_roots(), "the premise: no workspace folder to clamp against");
|
||||
assert_eq!(
|
||||
ws.scope_dirs(),
|
||||
vec![tree.path.join("rtl")],
|
||||
"depth {depth}: the buffer's own directory, and nothing above it"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rootless_session_reads_its_own_directory_flat_until_the_depth_is_raised() {
|
||||
// The `folder_files` exception, from the other side. The *directory*
|
||||
// is the buffer's own whatever the depth (no root, no climb — see
|
||||
// above), but the depth still chooses how it is read: 0 reads it flat,
|
||||
// one level, no `.gitignore`, and a raise means the user has asked for
|
||||
// a tree, so the tree below the buffer is walked.
|
||||
let tree = two_folder_tree("scoperootlesswalk");
|
||||
for (depth, expected) in
|
||||
[(0, vec!["open_pkg", "beside_pkg"]), (1, vec!["open_pkg", "beside_pkg", "below_pkg"])]
|
||||
{
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: depth, ..Default::default() });
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(scoped(&ws), expected, "depth {depth}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_workspace_scope_setting_restores_the_walk_of_every_root() {
|
||||
// The migration line in the README, pinned: with `scope: "workspace"`
|
||||
// the index is the whole tree with no buffer open at all — which is
|
||||
// exactly what this fixture gave before this round.
|
||||
let tree = two_folder_tree("scopewide");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
index_scope: IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
|
||||
"every file under the root, no buffer needed"
|
||||
);
|
||||
// And the depth is not consulted at all on that rung.
|
||||
let mut raised = Workspace::default();
|
||||
raised.set_client_settings(ClientSettings {
|
||||
index_scope: IndexScope::Workspace,
|
||||
index_scope_depth: 3,
|
||||
..Default::default()
|
||||
});
|
||||
raised.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(raised.index().files(), ws.index().files(), "the depth changes nothing here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_still_defines_the_scope_exactly_whatever_the_folder_rung_would_say() {
|
||||
// Rung 1 outranks rung 3 as it always outranked rung 2: the filelist
|
||||
// is the project file, and it names files in folders no buffer has
|
||||
// been opened from.
|
||||
let tree = two_folder_tree("scopefilelist");
|
||||
tree.write("files.f", "include/defs.sv\nelsewhere/far.sv\n");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "defs_pkg", "far_pkg"],
|
||||
"the filelist, plus the open buffer that overlays every rung"
|
||||
);
|
||||
assert!(ws.scope_dirs().is_empty(), "and no `didOpen` can widen a filelist");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_file_never_narrows_the_scope() {
|
||||
// The decision, pinned: the scope only grows within a session. A
|
||||
// rebuild after a close must not take away answers the user had a
|
||||
// moment ago, and no `didClose` costs a rescan.
|
||||
let tree = two_folder_tree("scopeclose");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() });
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
open(&mut ws, &tree, "include/defs.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"]);
|
||||
|
||||
let closed = crate::uri::path_to_uri(&tree.path.join("include/defs.sv")).expect("uri");
|
||||
ws.close_document(&closed);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"],
|
||||
"the closed file's folder is still indexed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_folder_scope_honours_every_exclude_and_the_gitignores_below_it() {
|
||||
// Rung 3 walks with the same function rung 2 walks with, so nothing a
|
||||
// user excluded comes back because the scope narrowed — with **one
|
||||
// honest exception**, pinned here rather than left to be discovered:
|
||||
// `lucisv_core`'s walk reads `.gitignore` files from its own starting
|
||||
// directory downwards, so a rule written at the workspace root does
|
||||
// not reach a walk that starts below it. The `exclude` patterns are
|
||||
// matched against whole paths and are unaffected either way. Stated in
|
||||
// `walked_files` and in `docs/features/index-scope/README.md`.
|
||||
let tree = Tree::new("scopefilters");
|
||||
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
|
||||
tree.write(".gitignore", "generated/\n");
|
||||
tree.write("rtl/.gitignore", "dumps/\n");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.package("rtl/vendor/ip.sv", "vendor_pkg");
|
||||
tree.package("rtl/dumps/net.sv", "dumps_pkg");
|
||||
tree.package("rtl/generated/net.sv", "generated_pkg");
|
||||
tree.package("rtl/scratch/wip.sv", "scratch_pkg");
|
||||
|
||||
let names = &["open_pkg", "vendor_pkg", "dumps_pkg", "generated_pkg", "scratch_pkg"];
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(excluding(&["scratch"]));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
indexed(&ws, names),
|
||||
["open_pkg", "generated_pkg"],
|
||||
"both excludes and the .gitignore inside the scope applied; the one at the \
|
||||
root, above where this walk starts, did not"
|
||||
);
|
||||
|
||||
// ...and the wide scope, whose walk starts at the root, does apply it.
|
||||
let mut wide = Workspace::default();
|
||||
wide.set_client_settings(ClientSettings {
|
||||
exclude: vec!["scratch".to_string()],
|
||||
index_scope: IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
wide.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&wide, names), ["open_pkg"], "everything filtered, from the root");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_added_mid_session_widens_nothing_until_a_file_in_it_is_opened() {
|
||||
// The interaction between the two ways a scope can move. Under the
|
||||
// folder rung a workspace folder is a *clamp*, not a work list, so
|
||||
// adding one changes which files exist only once a buffer in it makes
|
||||
// it a scope directory.
|
||||
let first = Tree::new("scopefolderfirst");
|
||||
first.package("a.sv", "a");
|
||||
let second = Tree::new("scopefoldersecond");
|
||||
second.package("b.sv", "b");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![first.path.clone()]);
|
||||
open(&mut ws, &first, "a.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: the first folder's file");
|
||||
|
||||
assert!(ws.change_roots(vec![second.path.clone()], &[]), "the root set moved");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "but no buffer lives there yet");
|
||||
|
||||
open(&mut ws, &second, "b.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "opening one widens the scope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_or_a_depth_change_asks_for_a_rescan() {
|
||||
// Both change which files exist, so both join `exclude`, `filelist`
|
||||
// and the size cap in the rescan test.
|
||||
let mut ws = Workspace::default();
|
||||
let wide = ClientSettings { index_scope: IndexScope::Workspace, ..Default::default() };
|
||||
assert!(ws.set_client_settings(wide.clone()), "a new scope rescans");
|
||||
assert!(!ws.set_client_settings(wide.clone()), "the same one does not");
|
||||
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
|
||||
|
||||
let deep = ClientSettings { index_scope_depth: 5, ..Default::default() };
|
||||
assert!(ws.set_client_settings(deep.clone()), "a new depth rescans");
|
||||
assert!(!ws.set_client_settings(deep), "the same one does not");
|
||||
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_open_files_are_indexed_first_and_the_index_cannot_tell() {
|
||||
// Two halves of one claim. First: the progress events name the open
|
||||
// buffers before anything else, which is what makes a big rescan feel
|
||||
// like it is working on the user's own files.
|
||||
let tree = Tree::new("scopeorder");
|
||||
tree.package("rtl/a_first.sv", "a_first");
|
||||
tree.package("rtl/m_open.sv", "m_open");
|
||||
tree.package("rtl/z_last.sv", "z_last");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/m_open.sv");
|
||||
// Every file of the work list, however it got into the index: since
|
||||
// 2026-08-28 the open buffer goes in from its own analysis and reports
|
||||
// `Analyzed` rather than `Parsing`, and the claim under test is about
|
||||
// the *order* the work list is walked in, not about who parses.
|
||||
let mut seen: Vec<PathBuf> = Vec::new();
|
||||
ws.rebuild_index_with(&mut |event| match event {
|
||||
IndexEvent::Parsing { path, .. }
|
||||
| IndexEvent::Cached { path, .. }
|
||||
| IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
});
|
||||
assert_eq!(
|
||||
seen,
|
||||
vec![
|
||||
tree.path.join("rtl/m_open.sv"),
|
||||
tree.path.join("rtl/a_first.sv"),
|
||||
tree.path.join("rtl/z_last.sv"),
|
||||
],
|
||||
"the open buffer first, then the rest in path order"
|
||||
);
|
||||
|
||||
// Second, and the reason the first is allowed to be true: the index
|
||||
// is byte-identical to the one the plain path order builds. The
|
||||
// builder sorts inside `finish`, so the order above is a reporting
|
||||
// decision and nothing more (`vlog_semantic`'s
|
||||
// `no_insertion_order_can_change_what_the_builder_produces` is the
|
||||
// other end of this).
|
||||
let mut plain = Workspace::default();
|
||||
plain.set_client_settings(ClientSettings {
|
||||
index_scope: IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
plain.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().files(), plain.index().files(), "same files, same ids");
|
||||
assert_eq!(ws.index().counts(), plain.index().counts(), "and the same index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowering_the_scope_depth_narrows_the_index_on_the_next_rescan() {
|
||||
// The scope grows only along the *open* axis — a `didClose` never
|
||||
// narrows it. A settings change is the other axis and moves both ways,
|
||||
// because it is a deliberate statement about how much of this machine's
|
||||
// time to spend. Verified by hand by the previous round's QA; pinned
|
||||
// here.
|
||||
let tree = two_folder_tree("depthdown");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert!(scoped(&ws).contains(&"defs_pkg".to_string()), "premise: depth 1 reaches beside");
|
||||
|
||||
assert!(
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }),
|
||||
"lowering the depth asks for a rescan"
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "narrowed, not kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one() {
|
||||
// Not just "asks for a rescan" — that the index really becomes the
|
||||
// filelist's files, from a folder scope that was covering something
|
||||
// else entirely.
|
||||
let tree = two_folder_tree("filelistmid");
|
||||
tree.write("files.f", "elsewhere/far.sv\n");
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "premise: the folder rung");
|
||||
|
||||
assert!(ws.set_client_settings(using_filelist("files.f")), "a rescan is owed");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "far_pkg"],
|
||||
"rung 1 defines the scope exactly — plus the open buffer, which overlays every rung"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one() {
|
||||
// `raised()`'s floor is the deepest root *containing* the directory, and
|
||||
// there is none here — so the climb stops at `/`, exactly as it does
|
||||
// with no root at all. Verified by hand by the previous round's QA;
|
||||
// pinned here, on the directories rather than by walking one.
|
||||
let inside = Tree::new("outsideroot_in");
|
||||
inside.package("rtl/a.sv", "a_pkg");
|
||||
let outside = Tree::new("outsideroot_out");
|
||||
outside.package("other/b.sv", "b_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![inside.path.clone()]);
|
||||
open(&mut ws, &outside, "other/b.sv");
|
||||
assert_eq!(
|
||||
ws.scope_dirs(),
|
||||
vec![outside.path.join("other")],
|
||||
"at depth 0 it is the buffer's own directory and nothing else"
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a_pkg", "b_pkg"]), ["b_pkg"], "the root's own tree is not in it");
|
||||
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
|
||||
assert_eq!(
|
||||
ws.scope_dirs(),
|
||||
vec![PathBuf::from("/")],
|
||||
"and with nothing to clamp against the climb stops at the filesystem root"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! Workspace folders added and removed mid-session
|
||||
//! (`didChangeWorkspaceFolders`): what widens the scan, what narrows it,
|
||||
//! what changes nothing, and what is left when the last root goes.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() {
|
||||
let first = Tree::new("rootsfirst");
|
||||
first.package("a.sv", "a");
|
||||
let second = Tree::new("rootssecond");
|
||||
second.package("b.sv", "b");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![first.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: one folder");
|
||||
|
||||
assert!(ws.change_roots(vec![second.path.clone()], &[]), "a new folder moves the set");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "both folders are scanned");
|
||||
|
||||
assert!(ws.change_roots(Vec::new(), from_ref(&first.path)), "and so does dropping one");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["b"], "the dropped folder's files are gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed() {
|
||||
// Overlap does not duplicate a file's registration: `walked_files`
|
||||
// walks each root independently and `dedup`s the combined, sorted
|
||||
// list by path, so a file both roots would reach lands in the index
|
||||
// once, not twice (a second identical registration would show up as
|
||||
// an *ambiguous* member — `indexed` below only counts a name found
|
||||
// exactly once).
|
||||
//
|
||||
// It is NOT exclude-proof, though, and that half is a genuine
|
||||
// consequence of "each root is governed by its own config"
|
||||
// (documented on `walked_files`): a directory the parent root's
|
||||
// `lucisv.toml` excludes is added *as a root in its own right* here,
|
||||
// and nothing excludes a root from itself. QA (2026-08-27): flagged
|
||||
// in the QA log as a finding, not a bug fix — this is consistent
|
||||
// with the per-root config model, but it was unreachable before this
|
||||
// round (roots used to be frozen at `initialize`), so it is worth a
|
||||
// pin and a name.
|
||||
let tree = Tree::new("subdirroot");
|
||||
tree.write("lucisv.toml", "exclude = [\"sub\"]\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("sub/hidden.sv", "hidden_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["kept", "hidden_pkg"]), ["kept"], "excluded, as configured");
|
||||
|
||||
assert!(ws.change_roots(vec![tree.path.join("sub")], &[]));
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
indexed(&ws, &["kept", "hidden_pkg"]),
|
||||
["kept", "hidden_pkg"],
|
||||
"reachable once through the added root, and only once — not ambiguous"
|
||||
);
|
||||
}
|
||||
|
||||
/// A workspace whose tree links back into itself. Before the walk kept a
|
||||
/// visited set (`docs/features/walk-cycles/README.md`) this scan never
|
||||
/// finished — the editor's index simply never came up. Each directory is
|
||||
/// entered once now, so each package is registered exactly once: a second
|
||||
/// registration would make the name *ambiguous*, and `indexed` only
|
||||
/// counts a name found exactly once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_cyclic_workspace_is_scanned_once_and_finishes() {
|
||||
let tree = Tree::new("cycle");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/sub/b.sv", "b");
|
||||
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level
|
||||
// down. Either one alone runs until the OS refuses a path.
|
||||
std::os::unix::fs::symlink("../rtl", tree.path.join("rtl/self")).expect("symlink");
|
||||
std::os::unix::fs::symlink("..", tree.path.join("rtl/sub/up")).expect("symlink");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"]);
|
||||
assert_eq!(
|
||||
ws.walked_files(from_ref(&tree.path), &mut |_| {}, &mut ScanTrace::new(false)).len(),
|
||||
2,
|
||||
"two files, once each"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
|
||||
// Every no-op shape a client can send. Each must leave the root set
|
||||
// exactly as it was, and say so — a rescan here is pure cost.
|
||||
let tree = Tree::new("rootsnoop");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
|
||||
assert!(!ws.change_roots(Vec::new(), &[]), "an empty event");
|
||||
assert!(!ws.change_roots(vec![tree.path.clone()], &[]), "a folder already held");
|
||||
let never = tree.path.join("never-added");
|
||||
assert!(!ws.change_roots(Vec::new(), from_ref(&never)), "a folder never held");
|
||||
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&never)), "and both at once");
|
||||
assert!(ws.has_roots(), "the root survived every one of them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_slash_in_the_removed_folder_still_matches_the_held_root() {
|
||||
// `uri_to_path` decodes a URI verbatim, trailing slash and all, and
|
||||
// `change_roots` compares by `PathBuf` equality — which compares
|
||||
// components, not raw strings, so `/a/b/` and `/a/b` are already the
|
||||
// same path as far as `retain`/`contains` are concerned. Pinned
|
||||
// because the doc README calls this out as a boundary worth
|
||||
// checking, not because the standard library needed help.
|
||||
let tree = Tree::new("trailingslash");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
|
||||
let mut with_slash = tree.path.clone().into_os_string();
|
||||
with_slash.push("/");
|
||||
assert!(
|
||||
ws.change_roots(Vec::new(), from_ref(&PathBuf::from(with_slash))),
|
||||
"the trailing slash must not hide the match"
|
||||
);
|
||||
assert!(!ws.has_roots());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_named_in_both_halves_of_one_event_stays() {
|
||||
// Removals run first, so "removed and added again" — which is how a
|
||||
// moved folder reaches some clients — is not a way to lose a root.
|
||||
let tree = Tree::new("rootsboth");
|
||||
tree.package("a.sv", "a");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&tree.path)), "no net change");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a"]), ["a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_added_twice_across_two_events_is_absent_after_one_removal() {
|
||||
// The root set is a set, not a multiset: `change_roots` dedups on
|
||||
// push (`if !self.roots.contains(&root)`), so a second add of the
|
||||
// same path — even from a *later*, separate notification — never
|
||||
// grows a reference count for it. One removal is therefore always
|
||||
// enough, however many times a client (redundantly) added it.
|
||||
// QA (2026-08-27): pinned per the review checklist's multiset-vs-set
|
||||
// question.
|
||||
let tree = Tree::new("addedtwice");
|
||||
let extra = Tree::new("addedtwiceextra");
|
||||
extra.package("x.sv", "x");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
// Whole-workspace scope, so the indexed-content assertions below see
|
||||
// the roots at all — under the default folder scope nothing is
|
||||
// walked until a buffer opens, and the closing assertion was vacuous
|
||||
// (QA finding, 2026-08-27, lead-fixed).
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(ws.change_roots(vec![extra.path.clone()], &[]), "the first add moves the set");
|
||||
assert!(
|
||||
!ws.change_roots(vec![extra.path.clone()], &[]),
|
||||
"a second, separate add of the same path is a no-op"
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["x"]), vec!["x".to_string()], "present while added");
|
||||
assert!(
|
||||
ws.change_roots(Vec::new(), from_ref(&extra.path)),
|
||||
"one removal is enough to take it out"
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["x"]), Vec::<String>::new(), "gone, not merely decremented");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_last_root_falls_back_to_the_rootless_model() {
|
||||
// Rung 3 of the ladder is not a startup-only state: a session that
|
||||
// closes its last folder becomes the single-file case, and an open
|
||||
// buffer must still resolve against the files beside it.
|
||||
let tree = Tree::new("rootslast");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.package("rtl/sibling.sv", "sibling");
|
||||
tree.package("elsewhere/far.sv", "far");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["open_pkg", "sibling", "far"]), ["open_pkg", "sibling", "far"]);
|
||||
|
||||
let path = tree.path.join("rtl/open.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
|
||||
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
|
||||
assert!(!ws.has_roots(), "the workspace is rootless now");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
indexed(&ws, &["open_pkg", "sibling", "far"]),
|
||||
["open_pkg", "sibling"],
|
||||
"the buffer and its neighbours, as if the file had been opened on its own"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_last_root_leaves_a_relative_filelist_unanchored() {
|
||||
// `filelist_path` anchors a relative setting at `roots.first()`. With
|
||||
// no roots left there is nothing to anchor it to, and the path comes
|
||||
// back exactly as the client wrote it — not resolved against the
|
||||
// folder that is now gone, and not resolved against anything else
|
||||
// either. Nothing panics: `source_files` still falls back to the
|
||||
// rootless walk with a warning when that bare path cannot be read
|
||||
// (`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so`
|
||||
// covers that fallback). QA (2026-08-27): pinned because this is new
|
||||
// reachable behaviour this round — losing the last root used to be
|
||||
// impossible.
|
||||
let tree = Tree::new("rootslastfilelist");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.write("files.f", "rtl/open.sv\n");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
ws.filelist_path(),
|
||||
Some(tree.path.join("files.f")),
|
||||
"anchored at the root while it exists"
|
||||
);
|
||||
|
||||
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
|
||||
assert_eq!(
|
||||
ws.filelist_path(),
|
||||
Some(PathBuf::from("files.f")),
|
||||
"with no roots left, the same setting comes back bare — anchored at nothing"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! The incremental path (incremental-index, 2026-08-27): one saved file
|
||||
//! re-indexed in place, checked against the whole rebuild it stands in for.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_file_the_index_already_holds_takes_the_incremental_path() {
|
||||
// The whole gate, from both sides. A file the index holds is one the
|
||||
// update can replace; anything else is a rebuild's business, because a
|
||||
// file appearing changes what *other* files' includes resolve to.
|
||||
let tree = Tree::new("incrgate");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(ws.update_one_checked(&tree.path.join("rtl/a.sv")), "a file the index holds");
|
||||
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "a file it does not");
|
||||
assert!(!ws.update_one(&tree.path.join("rtl/a.txt")), "and a path it never would");
|
||||
// A file that appears is exactly the "not held" case, and stays so
|
||||
// until something rebuilds.
|
||||
tree.package("rtl/new.sv", "new_pkg");
|
||||
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "still not held");
|
||||
ws.rebuild_index();
|
||||
assert!(ws.update_one_checked(&tree.path.join("rtl/new.sv")), "held now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_files_edit_reaches_every_table_the_index_answers_from() {
|
||||
// The four pieces of derived state a rebuild produces, checked one by
|
||||
// one after an update that moves all four: a declaration, an
|
||||
// instantiation edge, an inheritance edge, a completion word and an
|
||||
// `` `include`` edge.
|
||||
let tree = Tree::new("incrtables");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
tree.write("rtl/sub.sv", "module sub;\nendmodule\nclass base;\nendclass\n");
|
||||
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n sub u1 ();\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let top = tree.path.join("rtl/top.sv");
|
||||
assert_eq!(ws.index().instantiations_of("sub").len(), 1, "premise: one site");
|
||||
assert_eq!(
|
||||
ws.includes().reachable(vec![top.clone()]).len(),
|
||||
2,
|
||||
"premise: top.sv reaches defs.svh"
|
||||
);
|
||||
assert_eq!(ws.candidates().words("u1").len(), 1, "premise: the instance name is a word");
|
||||
|
||||
fs::write(
|
||||
&top,
|
||||
"module top;\n logic renamed_wire;\nendmodule\nclass leaf extends base;\nendclass\n",
|
||||
)
|
||||
.expect("write");
|
||||
assert!(ws.update_one_checked(&top));
|
||||
assert!(ws.index().instantiations_of("sub").is_empty(), "the site went");
|
||||
assert_eq!(ws.index().subclasses_of("base").len(), 1, "and an inheritance edge came");
|
||||
assert!(ws.candidates().words("u1").is_empty(), "the old word was given back");
|
||||
assert_eq!(ws.candidates().words("renamed_wire").len(), 1, "the new one taken");
|
||||
assert_eq!(ws.includes().reachable(vec![top]).len(), 1, "the include edge went too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_the_cap_or_the_disk_takes_away_leaves_the_index() {
|
||||
let tree = Tree::new("incrremove");
|
||||
tree.package("rtl/keep.sv", "keep_pkg");
|
||||
tree.package("rtl/gone.sv", "gone_pkg");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]).len(), 2, "premise");
|
||||
|
||||
// Deleted on disk: the update is a removal.
|
||||
let gone = tree.path.join("rtl/gone.sv");
|
||||
fs::remove_file(&gone).expect("remove");
|
||||
assert!(ws.update_one_checked(&gone), "a held file, even a vanished one");
|
||||
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]), ["keep_pkg"]);
|
||||
|
||||
// And a file that grew past the cap is the same answer for the same
|
||||
// reason: it is not a file this server reads any more.
|
||||
let mut ws = Workspace::default();
|
||||
let tree = Tree::new("incrcap");
|
||||
tree.package("rtl/keep.sv", "keep_pkg");
|
||||
fat_package(&tree, "rtl/netlist.sv", "netlist_pkg", 4096);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]).len(), 2, "premise: under no cap");
|
||||
ws.set_client_settings(wide(capping(1024)));
|
||||
assert!(ws.update_one_checked(&tree.path.join("rtl/netlist.sv")));
|
||||
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]), ["keep_pkg"], "the cap took it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_beats_disk_on_the_incremental_path_too() {
|
||||
let tree = Tree::new("incrbuffer");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let path = tree.path.join("rtl/a.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package buffered_pkg;\n localparam K = 1;\nendpackage\n".to_string());
|
||||
assert!(ws.update_one_checked(&path));
|
||||
assert_eq!(
|
||||
indexed(&ws, &["a_pkg", "buffered_pkg"]),
|
||||
["buffered_pkg"],
|
||||
"the buffer's text, not the file's"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus() {
|
||||
// The paranoid sweep: take real files out of a real workspace, put a
|
||||
// mutated version back through the incremental path, and check the
|
||||
// result against a whole rebuild every time. `update_one_checked` is
|
||||
// what does the checking; this test is the corpus it does it over.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
// Copied into a scratch tree, because the sweep rewrites files. Every
|
||||
// fifth file: `update_one_checked` rebuilds the whole workspace to
|
||||
// check itself, so the sweep costs a full rebuild per mutation and a
|
||||
// third of the corpus is still hundreds of real files.
|
||||
let tree = Tree::new("incrcorpus");
|
||||
let mut copied = 0;
|
||||
let mut sample: Vec<PathBuf> = Vec::new();
|
||||
for (n, source) in walk_sources(&corpus).into_iter().step_by(5).enumerate() {
|
||||
let Ok(text) = fs::read_to_string(&source) else { continue };
|
||||
let rel = format!("f{n:04}.sv");
|
||||
tree.write(&rel, &text);
|
||||
copied += 1;
|
||||
if n % 31 == 0 {
|
||||
sample.push(tree.path.join(&rel));
|
||||
}
|
||||
}
|
||||
assert!(copied > 100, "premise: the corpus was really copied ({copied} files)");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(sample.len() > 5, "a sample worth sweeping: {}", sample.len());
|
||||
|
||||
for path in &sample {
|
||||
let text = fs::read_to_string(path).expect("the copy is on disk");
|
||||
// Four shapes of edit, each checked against a whole rebuild.
|
||||
assert!(ws.update_one_checked(path), "unchanged");
|
||||
fs::write(
|
||||
path,
|
||||
format!("{text}\nmodule qa_added_module;\n qa_added_sub u1 ();\nendmodule\n"),
|
||||
)
|
||||
.expect("write");
|
||||
assert!(ws.update_one_checked(path), "a declaration and an edge added");
|
||||
fs::write(path, "class qa_leaf extends qa_base;\nendclass\n").expect("write");
|
||||
assert!(ws.update_one_checked(path), "replaced wholesale");
|
||||
fs::write(path, "").expect("write");
|
||||
assert!(ws.update_one_checked(path), "emptied");
|
||||
fs::remove_file(path).expect("remove");
|
||||
assert!(ws.update_one_checked(path), "removed");
|
||||
}
|
||||
eprintln!("paranoid sweep: {copied} files, {} of them mutated five ways", sample.len());
|
||||
}
|
||||
|
||||
/// What one file's rescan costs on the incremental path, against the whole
|
||||
/// rebuild it replaces, over the real corpus.
|
||||
///
|
||||
/// `#[ignore]`d like the crate's other measurement probes: it prints
|
||||
/// numbers rather than asserting one. The numbers themselves are in
|
||||
/// `docs/features/incremental-index/README.md`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn qa_perf_one_file_against_the_whole_rebuild() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let files = ws.index().files().len();
|
||||
let one = ws.index().files().last().cloned().expect("a file");
|
||||
|
||||
let mut whole = std::time::Duration::MAX;
|
||||
let mut single = std::time::Duration::MAX;
|
||||
for _ in 0..3 {
|
||||
let started = std::time::Instant::now();
|
||||
ws.rebuild_index();
|
||||
whole = whole.min(started.elapsed());
|
||||
let started = std::time::Instant::now();
|
||||
assert!(ws.update_one(&one));
|
||||
single = single.min(started.elapsed());
|
||||
}
|
||||
eprintln!(
|
||||
"reindex over {files} files: whole rebuild {whole:?}, one file {single:?} \
|
||||
({:.0}x)",
|
||||
whole.as_secs_f64() / single.as_secs_f64().max(f64::MIN_POSITIVE)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! An interleaved scan against the one-shot scan it must equal: the
|
||||
//! publication cadence, the tables however often they were published, a
|
||||
//! buffer opened mid-scan, and the events in the same order either way.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Run a scan the way `server.rs` does, publishing after **every** file —
|
||||
/// the worst case the interleaved path can produce, and the one a
|
||||
/// one-shot scan has to agree with.
|
||||
fn scan_publishing_every_file(ws: &mut Workspace) -> Vec<String> {
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
while ws.scan_step(&mut scan, &mut |_| {}) {
|
||||
ws.publish_scan(&mut scan);
|
||||
}
|
||||
ws.finish_scan(scan)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_publication_cadence_holds_a_publish_until_enough_has_been_staged() {
|
||||
// **The whole of the cadence, at its exact boundary.** A publish is a
|
||||
// pass over the whole index, and before §61.4 the drain paid one per
|
||||
// burst of requests — 13 to 18 in one warm opentitan scan, 46 % of it
|
||||
// (`docs/features/perf5r-publication/README.md`). `publish_is_due`
|
||||
// spaces them by work done rather than by how often a client asks: no
|
||||
// publish is due until `PUBLISH_EVERY` records are staged, one is due
|
||||
// the moment the 512th lands, and publishing clears the debt.
|
||||
let tree = Tree::new("publishcadence");
|
||||
for n in 0..scan::PUBLISH_EVERY + 2 {
|
||||
tree.package(&format!("p{n:04}.sv"), &format!("p{n:04}"));
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
for taken in 1..scan::PUBLISH_EVERY {
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: file {taken} exists");
|
||||
assert!(!scan.publish_is_due(), "{taken} staged is not yet a publish");
|
||||
}
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: the 512th file exists");
|
||||
assert!(scan.publish_is_due(), "{} staged is", scan::PUBLISH_EVERY);
|
||||
ws.publish_scan(&mut scan);
|
||||
assert!(!scan.publish_is_due(), "and publishing clears the debt");
|
||||
|
||||
// The cadence is a latency decision and nothing else: what this scan
|
||||
// lands is what a one-shot scan over the same tree lands.
|
||||
while ws.scan_step(&mut scan, &mut |_| {}) {}
|
||||
ws.finish_scan(scan);
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(everything(&one_shot), everything(&ws));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishing_between_every_file_leaves_what_a_one_shot_scan_leaves() {
|
||||
// The round's central invariant. The interleaved scan and the one-shot
|
||||
// scan are the same three calls with and without a drain between them,
|
||||
// so this pins the thing a drain could break: that folding records in
|
||||
// as they are taken lands the same index, the same completion tables
|
||||
// and the same include graph as folding them all in at the end.
|
||||
let tree = tangled("interleavesame");
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let mut stepped = Workspace::default();
|
||||
stepped.client.index_scope = IndexScope::Workspace;
|
||||
stepped.adopt_roots(vec![tree.path.clone()]);
|
||||
scan_publishing_every_file(&mut stepped);
|
||||
|
||||
assert_eq!(everything(&one_shot), everything(&stepped));
|
||||
assert!(one_shot.index().files().len() == 4, "premise: every file was scanned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_that_publishes_as_it_goes_still_drops_what_left_the_scope() {
|
||||
// A publish only ever folds records *in*, so the removal a rescan owes
|
||||
// — files the last scan held that this one's work list does not name —
|
||||
// has to survive every publish that happened before it.
|
||||
let tree = tangled("interleavegone");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(!ws.index().units("c").is_empty(), "premise: c.sv is indexed");
|
||||
|
||||
std::fs::remove_file(tree.path.join("c.sv")).expect("remove");
|
||||
scan_publishing_every_file(&mut ws);
|
||||
|
||||
let mut fresh = Workspace::default();
|
||||
fresh.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(everything(&fresh), everything(&ws));
|
||||
assert!(ws.index().units("c").is_empty(), "the file that left the scope is gone");
|
||||
assert_eq!(ws.index().files().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes() {
|
||||
// The scan holds the text every file had when its work list was taken,
|
||||
// and indexes *that* — which is exactly what a `didOpen` or a
|
||||
// `didChange` landing a moment after the scan finished would leave in
|
||||
// the index too (neither touches it; a save is what does). So a
|
||||
// message answered in the middle of a scan cannot move the scan's
|
||||
// result, and the fingerprint is the witness.
|
||||
let tree = tangled("interleavemidchange");
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let mut stepped = Workspace::default();
|
||||
stepped.client.index_scope = IndexScope::Workspace;
|
||||
stepped.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut scan = stepped.begin_scan(&mut |_| {}, false);
|
||||
assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: there is a first file");
|
||||
stepped.publish_scan(&mut scan);
|
||||
// The client opens `b.sv` and types in it, mid-scan.
|
||||
let opened = uri(&format!("file://{}", tree.path.join("b.sv").display()));
|
||||
stepped.set_document(opened.clone(), "module b;\n localparam MID = 1;\nendmodule\n".into());
|
||||
while stepped.scan_step(&mut scan, &mut |_| {}) {
|
||||
stepped.publish_scan(&mut scan);
|
||||
}
|
||||
stepped.finish_scan(scan);
|
||||
|
||||
assert_eq!(everything(&one_shot), everything(&stepped));
|
||||
assert_eq!(
|
||||
stepped.document(&opened).map(|doc| doc.text.as_str()),
|
||||
Some("module b;\n localparam MID = 1;\nendmodule\n"),
|
||||
"the buffer keeps the text it was given, index or no index"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell() {
|
||||
// The open-first rule for a file opened *after* the work list was
|
||||
// taken. It moves to the front of what is left, everything it passed
|
||||
// keeps its place behind it, and the finished index is byte-identical
|
||||
// — records are merged in path order whatever order they arrived in.
|
||||
let tree = tangled("interleaveopenfirst");
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let mut stepped = Workspace::default();
|
||||
stepped.client.index_scope = IndexScope::Workspace;
|
||||
stepped.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut scan = stepped.begin_scan(&mut |_| {}, false);
|
||||
assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: a.sv goes first");
|
||||
assert!(stepped.index().units("c").is_empty(), "premise: c.sv is not indexed yet");
|
||||
|
||||
// The client opens `c.sv`, and the work list is re-ordered around the
|
||||
// buffers open now — since 2026-09-08 that is one call rather than one
|
||||
// per opened path, because a buffer brings its folder with it
|
||||
// (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
let jumped = uri(&format!("file://{}", tree.path.join("c.sv").display()));
|
||||
let jumped_text = fs::read_to_string(tree.path.join("c.sv")).expect("the fixture");
|
||||
stepped.set_document(jumped, jumped_text);
|
||||
stepped.open_next(&mut scan, &mut |_| {});
|
||||
assert!(stepped.scan_step(&mut scan, &mut |_| {}));
|
||||
stepped.publish_scan(&mut scan);
|
||||
assert!(!stepped.index().units("c").is_empty(), "c.sv was indexed next, not last");
|
||||
|
||||
while stepped.scan_step(&mut scan, &mut |_| {}) {}
|
||||
stepped.finish_scan(scan);
|
||||
assert_eq!(everything(&one_shot), everything(&stepped));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven() {
|
||||
// The progress bar and the per-file log are the same two things a
|
||||
// one-shot scan reports, in the same order, against the same total:
|
||||
// interleaving adds drains between the events, never events.
|
||||
let tree = tangled("interleaveevents");
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.client.index_scope = IndexScope::Workspace;
|
||||
one_shot.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut said = Vec::new();
|
||||
one_shot.rebuild_index_with(&mut |event| said.push(seen(&event)));
|
||||
|
||||
let mut stepped = Workspace::default();
|
||||
stepped.client.index_scope = IndexScope::Workspace;
|
||||
stepped.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut also = Vec::new();
|
||||
let mut scan = stepped.begin_scan(&mut |event| also.push(seen(&event)), false);
|
||||
while stepped.scan_step(&mut scan, &mut |event| also.push(seen(&event))) {
|
||||
stepped.publish_scan(&mut scan);
|
||||
}
|
||||
assert_eq!(scan.skipped(), 0);
|
||||
assert_eq!(scan.cached(), 0);
|
||||
stepped.finish_scan(scan);
|
||||
|
||||
assert_eq!(said, also);
|
||||
assert_eq!(said.len(), 4, "one event per file, and nothing else: {said:?}");
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! The large-file fast path: the threshold is strict and `0` turns it off,
|
||||
//! a fast-path buffer holds the analysis of an empty file and contributes
|
||||
//! nothing to the index, and a buffer changes mode as it crosses the line.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A workspace whose fast path starts at `threshold` bytes.
|
||||
fn thresholded(threshold: u64) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
large_file_threshold: threshold,
|
||||
..ClientSettings::default()
|
||||
});
|
||||
ws
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_threshold_is_strict_at_the_boundary() {
|
||||
let sizes = [99, 100, 101];
|
||||
let large: Vec<bool> = sizes
|
||||
.iter()
|
||||
.map(|&size| {
|
||||
let mut ws = thresholded(100);
|
||||
ws.set_document(uri("file:///rtl/big.v"), filler(size));
|
||||
ws.document(&uri("file:///rtl/big.v")).expect("open").large
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(large, [false, false, true], "under, at, over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_threshold_of_zero_turns_the_fast_path_off_entirely() {
|
||||
let mut ws = thresholded(0);
|
||||
ws.set_document(uri("file:///rtl/big.v"), filler(200_000));
|
||||
let doc = ws.document(&uri("file:///rtl/big.v")).expect("open");
|
||||
assert!(!doc.large);
|
||||
assert!(!doc.tokens.is_empty(), "it really was lexed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_path_buffer_holds_the_analysis_of_an_empty_file() {
|
||||
let mut ws = thresholded(100);
|
||||
ws.set_document(uri("file:///rtl/big.v"), filler(500));
|
||||
let doc = ws.document(&uri("file:///rtl/big.v")).expect("open");
|
||||
assert!(doc.large);
|
||||
assert!(doc.tokens.is_empty(), "nothing was lexed");
|
||||
assert!(doc.diagnostics.is_empty(), "nothing was parsed");
|
||||
assert!(doc.semantics.symbols().is_empty(), "nothing was analyzed");
|
||||
assert!(doc.defines.entries().is_empty(), "no defines were collected");
|
||||
// But the two things the fast path *does* build are real.
|
||||
assert_eq!(doc.text.len(), 500);
|
||||
assert!(doc.line_index.line_count() > 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind() {
|
||||
let tree = Tree::new("largefile");
|
||||
tree.write("pkg.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n");
|
||||
let path = tree.path.join("pkg.sv");
|
||||
|
||||
let mut ws = thresholded(100);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk was indexed");
|
||||
|
||||
// The same file, opened as a buffer the fast path takes.
|
||||
let mut text = String::from("package p;\n localparam IN_BUFFER = 1;\nendpackage\n");
|
||||
text.push_str(&" ".repeat(200));
|
||||
ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the buffer was not parsed");
|
||||
assert_eq!(
|
||||
ws.index().member("p", "ON_DISK").len(),
|
||||
0,
|
||||
"and the disk copy the buffer supersedes is not indexed in its place"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_edited_past_the_threshold_changes_mode_and_back() {
|
||||
let mut ws = thresholded(200);
|
||||
let file = uri("file:///rtl/grow.v");
|
||||
ws.set_document(file.clone(), "module m;\nendmodule\n".into());
|
||||
assert!(!ws.document(&file).expect("open").large);
|
||||
ws.set_document(file.clone(), filler(1_000));
|
||||
assert!(ws.document(&file).expect("open").large, "grew past the threshold");
|
||||
ws.set_document(file.clone(), "module m;\nendmodule\n".into());
|
||||
let doc = ws.document(&file).expect("open");
|
||||
assert!(!doc.large, "and shrank back under it");
|
||||
assert!(!doc.tokens.is_empty(), "with a full analysis again");
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//! The lazy read and the folder-first order (perf5-p4 §P4b3, 2026-09-08):
|
||||
//! each file's bytes read once, at its own step, with the open buffer's
|
||||
//! neighbourhood indexed before the rest of the workspace is even walked.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The paths a scan reported, whichever way each file got into the index.
|
||||
fn walked(ws: &mut Workspace) -> Vec<PathBuf> {
|
||||
let mut seen: Vec<PathBuf> = Vec::new();
|
||||
ws.rebuild_index_with(&mut |event| match event {
|
||||
IndexEvent::Parsing { path, .. }
|
||||
| IndexEvent::Cached { path, .. }
|
||||
| IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
});
|
||||
seen
|
||||
}
|
||||
|
||||
/// A workspace whose buffer sits two folders below a root, so the folder
|
||||
/// the scope ladder raises it to is a real neighbourhood rather than the
|
||||
/// whole tree — opentitan's `hw/ip/aes/dv/tb/tb.sv` in miniature.
|
||||
fn neighbourhood_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("ip/aes/dv/tb/tb.sv", "tb_pkg");
|
||||
tree.package("ip/aes/rtl/aes.sv", "aes_pkg");
|
||||
tree.package("ip/aes/rtl/aes_core.sv", "aes_core_pkg");
|
||||
tree.package("ip/kmac/rtl/kmac.sv", "kmac_pkg");
|
||||
tree.package("ip/uart/rtl/uart.sv", "uart_pkg");
|
||||
tree.package("dv/common/util.sv", "util_pkg");
|
||||
// The crowd the folder has to be a minority of — opentitan's `ip/aes`
|
||||
// is 124 files of 3 976 (`crate::scan_order::worth_waiting`).
|
||||
for n in 0..6 {
|
||||
tree.package(&format!("zz/z{n:03}.sv"), &format!("z{n:03}_pkg"));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_scan_reads_each_files_bytes_exactly_once() {
|
||||
// The claim the lazy read makes. Everything the scan wants from a
|
||||
// file's text — the store's content hash, the parse, the `include`
|
||||
// lines — comes out of one read, and the open buffer's text is not
|
||||
// read from disk at all.
|
||||
let tree = neighbourhood_tree("readonce");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
|
||||
let before = crate::scan_trace::source_reads();
|
||||
assert_eq!(ws.rebuild_index().len(), 0, "premise: the walk is clean");
|
||||
assert_eq!(
|
||||
crate::scan_trace::source_reads() - before,
|
||||
12,
|
||||
"twelve files in the tree, twelve reads and not one more"
|
||||
);
|
||||
|
||||
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
|
||||
let before = crate::scan_trace::source_reads();
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
crate::scan_trace::source_reads() - before,
|
||||
11,
|
||||
"the open buffer's own text is in memory and is never read off disk"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_open_buffers_folder_is_indexed_before_the_rest_and_the_index_cannot_tell() {
|
||||
// The ordering §P4b2 asked for: the user's own file, then the folder
|
||||
// the scope ladder raises it to — `ip/aes`, two levels above
|
||||
// `ip/aes/dv` — and only then the workspace's alphabet.
|
||||
let tree = neighbourhood_tree("folderfirst");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
|
||||
|
||||
assert_eq!(
|
||||
walked(&mut ws),
|
||||
[
|
||||
vec![
|
||||
tree.path.join("ip/aes/dv/tb/tb.sv"),
|
||||
tree.path.join("ip/aes/rtl/aes.sv"),
|
||||
tree.path.join("ip/aes/rtl/aes_core.sv"),
|
||||
tree.path.join("dv/common/util.sv"),
|
||||
tree.path.join("ip/kmac/rtl/kmac.sv"),
|
||||
tree.path.join("ip/uart/rtl/uart.sv"),
|
||||
],
|
||||
(0..6).map(|n| tree.path.join(format!("zz/z{n:03}.sv"))).collect(),
|
||||
]
|
||||
.concat(),
|
||||
"the buffer, then its folder in path order, then the rest in path order"
|
||||
);
|
||||
|
||||
// And the reason that is allowed to be true: the finished index does
|
||||
// not depend on it. `IndexBuilder::finish` sorts by path, so a scan
|
||||
// with nothing open builds the same thing.
|
||||
let mut plain = Workspace::default();
|
||||
plain.client.index_scope = IndexScope::Workspace;
|
||||
plain.adopt_roots(vec![tree.path.clone()]);
|
||||
plain.rebuild_index();
|
||||
assert_eq!(plain.index().fingerprint(), ws.index().fingerprint(), "same index");
|
||||
assert_eq!(everything(&plain), everything(&ws), "and the same tables around it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_neighbourhood_is_what_a_held_request_waits_for() {
|
||||
// The drain rule's own arithmetic, at the workspace level: `head`
|
||||
// counts the buffer and its folder and nothing beyond.
|
||||
let tree = neighbourhood_tree("headsegment");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
|
||||
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
assert!(!scan.neighbourhood_indexed(), "nothing is indexed yet");
|
||||
// Three files are the neighbourhood — the buffer and `ip/aes` — and
|
||||
// the nine behind it are not.
|
||||
for expected in [false, false, true, true, true, true, true, true, true, true, true, true] {
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}));
|
||||
assert_eq!(scan.neighbourhood_indexed(), expected, "at {}", scan.at);
|
||||
}
|
||||
ws.finish_scan(scan);
|
||||
|
||||
// With nothing open there is no neighbourhood, and a held request is
|
||||
// answered at the first interleave point exactly as it always was.
|
||||
let mut bare = Workspace::default();
|
||||
bare.client.index_scope = IndexScope::Workspace;
|
||||
bare.adopt_roots(vec![tree.path.clone()]);
|
||||
let scan = bare.begin_scan(&mut |_| {}, false);
|
||||
assert!(scan.neighbourhood_indexed(), "no buffer, no wait");
|
||||
bare.finish_scan(scan);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_opened_mid_scan_lengthens_the_neighbourhood_it_jumps_into() {
|
||||
// `index_next` moves a file to the front of what is left. When it
|
||||
// comes from beyond the head segment it pushes one of that segment's
|
||||
// files a place later, and a held request must not be answered one
|
||||
// file short of the folder it is waiting for.
|
||||
let tree = neighbourhood_tree("headjump");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
|
||||
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "the buffer's own file goes first");
|
||||
open(&mut ws, &tree, "ip/uart/rtl/uart.sv");
|
||||
ws.open_next(&mut scan, &mut |_| {});
|
||||
// `uart.sv` is now the head of what is left, and at the shipped
|
||||
// `scopeDepth: 2` its own folder raises to `ip` — which brings
|
||||
// `ip/kmac` in with it. Four files of waiting, one behind the file
|
||||
// already stepped, so the segment ends at five rather than three.
|
||||
for expected in [false, false, false, true, true] {
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}));
|
||||
assert_eq!(scan.neighbourhood_indexed(), expected, "at {}", scan.at);
|
||||
}
|
||||
ws.finish_scan(scan);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_leaves_the_disk_between_the_walk_and_its_step_leaves_the_index() {
|
||||
// What `collect_sources` used to do by dropping an unreadable file
|
||||
// before the work list existed: the file contributes nothing, is not
|
||||
// counted among the cap's skips, and — for a whole scan — is taken
|
||||
// *out* of the index rather than left in it stale.
|
||||
let tree = Tree::new("vanished");
|
||||
tree.package("rtl/stays.sv", "stays_pkg");
|
||||
tree.package("rtl/goes.sv", "goes_pkg");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
ws.rebuild_index();
|
||||
assert!(!ws.index().units("goes_pkg").is_empty(), "premise: it was indexed once");
|
||||
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
assert_eq!(scan.total(), 2, "the walk found both");
|
||||
fs::remove_file(tree.path.join("rtl/goes.sv")).expect("remove");
|
||||
let mut said: Vec<String> = Vec::new();
|
||||
while ws.scan_step(&mut scan, &mut |event| said.push(seen(&event))) {}
|
||||
assert_eq!(scan.skipped(), 0, "an unreadable file is not one the size cap skipped");
|
||||
assert_eq!(said.len(), 1, "and it reports no event of its own: {said:?}");
|
||||
ws.finish_scan(scan);
|
||||
|
||||
assert!(ws.index().units("goes_pkg").is_empty(), "it left the scope, so it left the index");
|
||||
assert!(!ws.index().units("stays_pkg").is_empty(), "and the file beside it did not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tables_a_scan_lands_are_the_ones_the_texts_would_have_built() {
|
||||
// The lazy read's equivalence, table by table. The scan builds the
|
||||
// completion tables from the words it took off each record and the
|
||||
// include graph from the lines it scanned at each step; both must
|
||||
// equal what `Candidates::build` and `IncludeGraph::build` produce
|
||||
// from the same files' text.
|
||||
let tree = tangled("lazytables");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
ws.rebuild_index();
|
||||
|
||||
let texts: Vec<(PathBuf, String)> = ws
|
||||
.index()
|
||||
.files()
|
||||
.iter()
|
||||
.map(|path| (path.clone(), fs::read_to_string(path).expect("fixture")))
|
||||
.collect();
|
||||
let eagerly = Candidates::build(ws.index(), &texts, HashMap::new());
|
||||
assert_eq!(eagerly.sizes(), ws.candidates().sizes(), "the same completion tables");
|
||||
assert_eq!(eagerly.words(""), ws.candidates().words(""), "word for word");
|
||||
|
||||
let rebuilt = IncludeGraph::build(&texts, Vec::new());
|
||||
assert_eq!(rebuilt.sizes(), ws.includes().sizes(), "the same include graph");
|
||||
for (path, _) in &texts {
|
||||
assert_eq!(
|
||||
rebuilt.reachable(vec![path.clone()]),
|
||||
ws.includes().reachable(vec![path.clone()]),
|
||||
"the same hops from {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! The `Workspace` tests: one file per topic, every one driven through the
|
||||
//! real `Workspace` against a scratch tree on disk.
|
||||
//!
|
||||
//! This file is the harness — `Tree`, a workspace root removed on drop —
|
||||
//! followed by the helpers more than one file uses: settings as a client
|
||||
//! would push them, a buffer opened from disk, and the ways a scan's
|
||||
//! outcome is read back. The sibling files are the sections the one big
|
||||
//! test module used to have, under the names they had; a helper used by
|
||||
//! one section only stayed with it.
|
||||
|
||||
use std::fs;
|
||||
use std::slice::from_ref;
|
||||
use std::str::FromStr;
|
||||
|
||||
use super::*;
|
||||
use crate::settings::IndexScope;
|
||||
|
||||
mod document;
|
||||
mod filelist;
|
||||
mod folder_scope;
|
||||
mod folders;
|
||||
mod incremental;
|
||||
mod interleave;
|
||||
mod large_file;
|
||||
mod lazy_read;
|
||||
mod open_buffers;
|
||||
mod persistence;
|
||||
mod settings;
|
||||
mod size_cap;
|
||||
mod views;
|
||||
mod widen;
|
||||
|
||||
fn uri(s: &str) -> Uri {
|
||||
Uri::from_str(s).expect("test uri parses")
|
||||
}
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv_server_scan_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).expect("parent");
|
||||
}
|
||||
fs::write(&path, text).expect("write");
|
||||
}
|
||||
|
||||
/// A package declaring one localparam, so the index can be asked
|
||||
/// whether this file was scanned at all.
|
||||
fn package(&self, rel: &str, name: &str) {
|
||||
self.write(rel, &format!("package {name};\n localparam K = 1;\nendpackage\n"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Open `rel` in `ws` as the buffer it is on disk.
|
||||
fn open(ws: &mut Workspace, tree: &Tree, rel: &str) {
|
||||
let path = tree.path.join(rel);
|
||||
let text = fs::read_to_string(&path).expect("the fixture is on disk");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, text);
|
||||
}
|
||||
|
||||
/// A buffer of exactly `bytes` bytes that is also real Verilog.
|
||||
fn filler(bytes: usize) -> String {
|
||||
let mut text = String::from("module m;\n");
|
||||
while text.len() + 9 <= bytes {
|
||||
text.push_str(" wire a;\n");
|
||||
}
|
||||
while text.len() < bytes {
|
||||
text.push(' ');
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// A tree of three files that declare each other's names and include each
|
||||
/// other, so a half-published index has something to get wrong.
|
||||
fn tangled(tag: &str) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("defs.svh", "`define WIDE 32\n");
|
||||
tree.write(
|
||||
"a.sv",
|
||||
"`include \"defs.svh\"\npackage a;\n localparam K = 1;\n \
|
||||
typedef logic [`WIDE-1:0] word_t;\nendpackage\n",
|
||||
);
|
||||
tree.write(
|
||||
"b.sv",
|
||||
"`include \"defs.svh\"\nmodule b;\n import a::*;\n word_t w;\n \
|
||||
localparam K2 = a::K;\nendmodule\n",
|
||||
);
|
||||
tree.write("c.sv", "module c;\n b inner ();\nendmodule\n");
|
||||
tree
|
||||
}
|
||||
|
||||
/// `settings` with the pre-2026-08-27 whole-workspace scope asked for —
|
||||
/// the push-door twin of [`Workspace::open_whole_workspace`], needed
|
||||
/// wherever a test pushes settings *after* opening its roots, since a push
|
||||
/// replaces every field including the scope.
|
||||
fn wide(settings: ClientSettings) -> ClientSettings {
|
||||
ClientSettings { index_scope: IndexScope::Workspace, ..settings }
|
||||
}
|
||||
|
||||
/// `lucisv.exclude` as a client would push it.
|
||||
fn excluding(patterns: &[&str]) -> ClientSettings {
|
||||
ClientSettings {
|
||||
exclude: patterns.iter().map(|p| p.to_string()).collect(),
|
||||
index_scope_depth: 0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder rung at `scopeDepth: 0` — the open file's own folder and
|
||||
/// nothing above it.
|
||||
///
|
||||
/// Said out loud since 2026-08-28, when the shipped default became
|
||||
/// [`crate::settings::DEFAULT_SCOPE_DEPTH`]: a test about *this* rung
|
||||
/// names the depth it is about rather than riding whatever the default is
|
||||
/// this month. The behaviour it selects is unchanged.
|
||||
fn own_folder_only(ws: &mut Workspace) {
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() });
|
||||
}
|
||||
|
||||
/// `lucisv.filelist` as a client would push it.
|
||||
fn using_filelist(path: &str) -> ClientSettings {
|
||||
ClientSettings { filelist: Some(path.to_string()), ..Default::default() }
|
||||
}
|
||||
|
||||
/// A `ClientSettings` with the size cap set to `bytes`.
|
||||
fn capping(bytes: u64) -> ClientSettings {
|
||||
ClientSettings { max_file_size: bytes, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A file of `bytes` bytes that would declare `name` if anything read it.
|
||||
/// Padded with a trailing comment, so what makes it big is not what makes
|
||||
/// it a package.
|
||||
fn fat_package(tree: &Tree, rel: &str, name: &str, bytes: usize) {
|
||||
let head = format!("package {name};\n localparam K = 1;\nendpackage\n// ");
|
||||
let mut text = String::with_capacity(bytes + head.len());
|
||||
text.push_str(&head);
|
||||
while text.len() < bytes {
|
||||
text.push('x');
|
||||
}
|
||||
text.push('\n');
|
||||
tree.write(rel, &text);
|
||||
}
|
||||
|
||||
/// A client that keeps its index cache in `dir`.
|
||||
fn caching(dir: &Path) -> ClientSettings {
|
||||
ClientSettings {
|
||||
index_cache_path: Some(dir.to_string_lossy().into_owned()),
|
||||
index_scope_depth: 0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the index holds, as the names of the packages it found.
|
||||
fn indexed(ws: &Workspace, names: &[&str]) -> Vec<String> {
|
||||
names.iter().filter(|n| ws.index().member(n, "K").len() == 1).map(|n| n.to_string()).collect()
|
||||
}
|
||||
|
||||
/// Everything a scan produces, rendered as one comparable value: the
|
||||
/// index's own witness, the completion tables and the include graph.
|
||||
///
|
||||
/// The index's fingerprint alone would not do — this round publishes all
|
||||
/// three tables together, so all three have to be shown to come out the
|
||||
/// same however many publishes happened on the way.
|
||||
fn everything(ws: &Workspace) -> String {
|
||||
let mut out = ws.index().fingerprint();
|
||||
out.push_str(&format!("words {:?}\n", ws.candidates().words("")));
|
||||
out.push_str(&format!(
|
||||
"units {:?}\n",
|
||||
ws.candidates().units("").iter().map(|c| &c.name).collect::<Vec<_>>()
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"macros {:?}\n",
|
||||
ws.candidates().macros("").iter().map(|m| &m.name).collect::<Vec<_>>()
|
||||
));
|
||||
let mut reachable: Vec<String> = ws
|
||||
.index()
|
||||
.files()
|
||||
.iter()
|
||||
.map(|path| {
|
||||
let mut hops: Vec<String> = ws
|
||||
.includes()
|
||||
.reachable(vec![path.clone()])
|
||||
.iter()
|
||||
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
.collect();
|
||||
hops.sort();
|
||||
format!("reaches {} {hops:?}", path.display())
|
||||
})
|
||||
.collect();
|
||||
reachable.sort();
|
||||
out.push_str(&reachable.join("\n"));
|
||||
out
|
||||
}
|
||||
|
||||
/// One [`IndexEvent`] as the word and the numbers a caller would report.
|
||||
fn seen(event: &IndexEvent) -> String {
|
||||
match event {
|
||||
IndexEvent::Parsing { done, total, path } => {
|
||||
format!("indexing {done}/{total} {}", path.display())
|
||||
}
|
||||
IndexEvent::Cached { done, total, path } => {
|
||||
format!("cached {done}/{total} {}", path.display())
|
||||
}
|
||||
IndexEvent::Analyzed { done, total, path } => {
|
||||
format!("analyzed {done}/{total} {}", path.display())
|
||||
}
|
||||
IndexEvent::Skipped { path, size, cap } => {
|
||||
format!("skipped {} {size} {cap}", path.display())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What one whole scan did, file by file: what it parsed, what it took
|
||||
/// from the cache instead, and what came from an open buffer's own
|
||||
/// analysis. The three together are the work list.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
struct Scan {
|
||||
parsed: Vec<String>,
|
||||
cached: Vec<String>,
|
||||
analyzed: Vec<String>,
|
||||
}
|
||||
|
||||
/// Scan `roots` (or rescan what is already open, with `None`) and record
|
||||
/// which files were parsed and which came out of the cache.
|
||||
fn scan(ws: &mut Workspace, roots: Option<Vec<PathBuf>>) -> Scan {
|
||||
let mut out = Scan::default();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, .. } => out.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => out.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => out.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
match roots {
|
||||
Some(roots) => ws.open_whole_workspace_with(roots, &mut see),
|
||||
None => ws.rebuild_index_with(&mut see),
|
||||
};
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn file_name(path: &Path) -> String {
|
||||
path.file_name().expect("a file").to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Every source file under `dir`, for the corpus sweep above.
|
||||
fn walk_sources(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![dir.to_path_buf()];
|
||||
while let Some(next) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&next) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh"))
|
||||
{
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
//! An open buffer's own analysis (index-scope, 2026-08-28) beats disk in
|
||||
//! the index and is what the index reuses — and the QA attacks on that:
|
||||
//! staleness across a close, and crossing the large-file threshold.
|
||||
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_overrides_disk_in_the_index() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_server_state_{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("temp dir");
|
||||
let path = dir.join("pkg.sv");
|
||||
fs::write(&path, "package p;\n localparam ON_DISK = 1;\nendpackage\n").expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1);
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0);
|
||||
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "buffer must win");
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk must lose");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would() {
|
||||
// The equivalence the reuse stands on. A rescan takes an open buffer's
|
||||
// facts and its words off the analysis that buffer already holds; the
|
||||
// claim is that the index and the completion tables are then byte for
|
||||
// byte the ones a *parse of those bytes* builds. The buffer carries
|
||||
// unsaved edits on purpose — bytes that are nowhere on disk, which is
|
||||
// exactly the case the content-keyed cache cannot help with and the
|
||||
// one the owner's report was about.
|
||||
let tree = Tree::new("openfacts");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
tree.package("rtl/other.sv", "other_pkg");
|
||||
tree.write("rtl/top.sv", "module top;\n a_sub u ();\nendmodule\n");
|
||||
|
||||
let edited = "`define TAG 1\nimport a_pkg::*;\npackage edited_pkg;\n \
|
||||
localparam K = 1;\n class c extends a_base; int x; endclass\n\
|
||||
endpackage\nmodule top;\n logic [K-1:0] w;\n \
|
||||
a_sub u (.clk(w));\n a_sub v (.clk(w));\nendmodule\n";
|
||||
let path = tree.path.join("rtl/top.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
ws.set_document(uri, edited.to_string());
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(
|
||||
seen.analyzed,
|
||||
["top.sv"],
|
||||
"the open buffer went in from its own analysis: {seen:?}"
|
||||
);
|
||||
assert_eq!(seen.parsed, ["a.sv", "other.sv"], "and nothing else changed route: {seen:?}");
|
||||
let from_buffer = ws.index().fingerprint();
|
||||
let words_from_buffer = ws.candidates().words("").to_vec();
|
||||
let units_from_buffer: Vec<String> =
|
||||
ws.candidates().units("").iter().map(|c| c.name.clone()).collect();
|
||||
|
||||
// The same bytes on disk, nothing open: the parse route, end to end.
|
||||
tree.write("rtl/top.sv", edited);
|
||||
let mut plain = Workspace::default();
|
||||
plain.set_client_settings(wide(ClientSettings::default()));
|
||||
let mut route = Scan::default();
|
||||
plain.open_roots_with(vec![tree.path.clone()], &mut |event| match event {
|
||||
IndexEvent::Parsing { path, .. } => route.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => route.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => route.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
});
|
||||
assert_eq!(route.parsed, ["a.sv", "other.sv", "top.sv"], "premise: it really parsed");
|
||||
|
||||
assert_eq!(from_buffer, plain.index().fingerprint(), "the same index, byte for byte");
|
||||
assert_eq!(words_from_buffer, plain.candidates().words(""), "and the same words");
|
||||
let units_plain: Vec<String> =
|
||||
plain.candidates().units("").iter().map(|c| c.name.clone()).collect();
|
||||
assert_eq!(units_from_buffer, units_plain, "and the same index-derived candidates");
|
||||
|
||||
// And through the incremental door as well: `update_one` takes the same
|
||||
// shortcut, and `update_one_checked` holds it to a whole rebuild.
|
||||
assert!(ws.update_one_checked(&path), "the buffer's file is one the index holds");
|
||||
assert_eq!(ws.index().fingerprint(), from_buffer, "still the same index after an update");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus() {
|
||||
// `Document::new` and `FileFacts::of` each lex, parse and analyze one
|
||||
// file, and the reuse is only sound while those two agree. Nothing
|
||||
// enforces it at compile time — they are separate call sites — so it is
|
||||
// swept over real files, in the encoded record form, which is every
|
||||
// field the index and the persistent store ever read.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let empty = WorkspaceIndex::default();
|
||||
let mut checked = 0usize;
|
||||
for path in walk_sources(&corpus).into_iter().step_by(3) {
|
||||
let Ok(text) = fs::read_to_string(&path) else { continue };
|
||||
let doc = Document::new(Some(path.clone()), text.clone(), &empty);
|
||||
assert!(!doc.large, "premise: a full analysis, not the fast path");
|
||||
assert_eq!(
|
||||
doc.facts(path.clone()).encode(),
|
||||
FileFacts::of(path.clone(), &text).encode(),
|
||||
"the records differ for {}",
|
||||
path.display()
|
||||
);
|
||||
let mut from_buffer = doc.words();
|
||||
let mut from_text =
|
||||
crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default());
|
||||
from_buffer.sort();
|
||||
from_text.sort();
|
||||
assert_eq!(from_buffer, from_text, "the words differ for {}", path.display());
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked > 100, "premise: the corpus was really swept ({checked} files)");
|
||||
eprintln!("open-buffer equivalence: {checked} corpus files, facts and words identical");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_attack_crafted_non_corpus_shapes_drift_check() {
|
||||
// Run on a dedicated thread with a generous stack: `cargo test`'s
|
||||
// default per-test-thread stack (2 MiB) is smaller than a normal
|
||||
// process's main-thread stack, and a couple of the crafted shapes
|
||||
// below are deep enough to overflow the smaller one even though
|
||||
// `FileFacts::of` alone — no `Document`, no reuse — overflows it
|
||||
// identically on pristine, unmodified `master`. That is a real,
|
||||
// pre-existing recursion-depth ceiling in the parser/analyzer,
|
||||
// independent of this round; it is filed separately (QA log,
|
||||
// 2026-08-28) rather than blocking this round, since both routes
|
||||
// being compared here fail *identically*, which is the opposite of
|
||||
// the drift this test hunts for. Run at 64 MiB so the drift check
|
||||
// exercises real depth without tripping that unrelated ceiling.
|
||||
std::thread::Builder::new()
|
||||
.stack_size(64 * 1024 * 1024)
|
||||
.spawn(qa_attack_crafted_non_corpus_shapes_drift_check_body)
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("no panic");
|
||||
}
|
||||
|
||||
fn qa_attack_crafted_non_corpus_shapes_drift_check_body() {
|
||||
let empty = WorkspaceIndex::default();
|
||||
let cases: Vec<(&str, String)> = vec![
|
||||
("bom_plain", "\u{feff}module m;\nendmodule\n".to_string()),
|
||||
("crlf", "module m;\r\n logic w;\r\nendmodule\r\n".to_string()),
|
||||
("bom_crlf", "\u{feff}module m;\r\n logic w;\r\nendmodule\r\n".to_string()),
|
||||
("unterminated_block_comment", "module m; /* never closed\nendmodule\n".to_string()),
|
||||
("unterminated_attribute", "(* foo module m; endmodule\n".to_string()),
|
||||
(
|
||||
"unterminated_macro_call",
|
||||
"`define M(a,b) a+b\nmodule m; logic w = `M(1,2\nendmodule\n".to_string(),
|
||||
),
|
||||
("unterminated_string", "module m; string s = \"never closed\nendmodule\n".to_string()),
|
||||
("unexpected_char", "module m; logic w = \u{1}; endmodule\n".to_string()),
|
||||
("deeply_nested_begin_end", {
|
||||
let mut s = String::from("module m;\ninitial begin\n");
|
||||
for _ in 0..500 {
|
||||
s.push_str("begin\n");
|
||||
}
|
||||
for _ in 0..500 {
|
||||
s.push_str("end\n");
|
||||
}
|
||||
s.push_str("end\nendmodule\n");
|
||||
s
|
||||
}),
|
||||
("deeply_nested_parens", {
|
||||
let mut s = String::from("module m;\n localparam int W = ");
|
||||
for _ in 0..2000 {
|
||||
s.push('(');
|
||||
}
|
||||
s.push('1');
|
||||
for _ in 0..2000 {
|
||||
s.push(')');
|
||||
}
|
||||
s.push_str(";\nendmodule\n");
|
||||
s
|
||||
}),
|
||||
("macro_heavy", {
|
||||
let mut s = String::new();
|
||||
for i in 0..500 {
|
||||
s.push_str(&format!("`define M{i} {i}\n"));
|
||||
}
|
||||
s.push_str("module m;\nendmodule\n");
|
||||
s
|
||||
}),
|
||||
(
|
||||
"include_bearing",
|
||||
"`include \"foo.svh\"\n`include \"bar/baz.vh\"\nmodule m;\nendmodule\n".to_string(),
|
||||
),
|
||||
(
|
||||
"parse_error_recovery",
|
||||
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n"
|
||||
.to_string(),
|
||||
),
|
||||
("mixed_line_endings", "module m;\n logic a;\r\n logic b;\nendmodule\n".to_string()),
|
||||
("null_byte", "module m;\n logic a; // \0 embedded\nendmodule\n".to_string()),
|
||||
("tab_and_form_feed", "module m;\n\t\u{c}logic a;\nendmodule\n".to_string()),
|
||||
];
|
||||
let total = cases.len();
|
||||
let mut failures = Vec::new();
|
||||
for (name, text) in cases {
|
||||
let path = PathBuf::from(format!("/w/{name}.sv"));
|
||||
let doc = Document::new(Some(path.clone()), text.clone(), &empty);
|
||||
let from_buffer = doc.facts(path.clone()).encode();
|
||||
let from_text = FileFacts::of(path.clone(), &text).encode();
|
||||
if from_buffer != from_text {
|
||||
failures
|
||||
.push(format!("FACTS DRIFT in {name}: buffer={from_buffer:?} text={from_text:?}"));
|
||||
}
|
||||
let mut wb = doc.words();
|
||||
let mut wt = crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default());
|
||||
wb.sort();
|
||||
wt.sort();
|
||||
if wb != wt {
|
||||
failures.push(format!("WORDS DRIFT in {name}: buffer={wb:?} text={wt:?}"));
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "drift found:\n{}", failures.join("\n"));
|
||||
eprintln!("qa attack: {total} crafted non-corpus shapes, no drift found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse() {
|
||||
// The one buffer whose held analysis is not an analysis of its text —
|
||||
// it is the analysis of the empty file. Such a buffer contributes
|
||||
// nothing to the index at all, which is what keeps the reuse from ever
|
||||
// meeting it: it is absent from the work list, so it is absent from
|
||||
// every list a rescan reports.
|
||||
let tree = Tree::new("openfactslarge");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let big = format!(
|
||||
"package big_pkg;\n localparam K = 1;\n{}endpackage\n",
|
||||
" // filler\n".repeat(200)
|
||||
);
|
||||
tree.write("rtl/big.sv", &big);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(wide(ClientSettings {
|
||||
large_file_threshold: 100,
|
||||
..Default::default()
|
||||
}));
|
||||
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
|
||||
let uri = crate::uri::path_to_uri(&tree.path.join("rtl/big.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), big);
|
||||
assert!(ws.document(&uri).expect("open").large, "premise: the fast path");
|
||||
|
||||
let seen = scan(&mut ws, None);
|
||||
assert!(seen.analyzed.is_empty(), "nothing came from an analysis: {seen:?}");
|
||||
assert_eq!(seen.parsed, ["a.sv"], "and the big buffer is on no list at all: {seen:?}");
|
||||
assert_eq!(indexed(&ws, &["a_pkg", "big_pkg"]), ["a_pkg"], "nor in the index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan() {
|
||||
// Charter attack 2 (staleness). An open buffer's *unsaved* edits must
|
||||
// win a rescan (the whole reason the reuse is sound even though the
|
||||
// content-keyed cache has nothing to key unsaved bytes by), and
|
||||
// closing the buffer without saving must let the next rescan see disk
|
||||
// again — nothing about the buffer's now-gone analysis may linger.
|
||||
let tree = Tree::new("qastaleness");
|
||||
tree.write("rtl/p.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n");
|
||||
let path = tree.path.join("rtl/p.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk's member");
|
||||
|
||||
// Open the buffer and edit it — never saved, so disk still says
|
||||
// `ON_DISK` — then rescan.
|
||||
ws.set_document(uri.clone(), "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.analyzed, ["p.sv"], "the live buffer's own analysis went in: {seen:?}");
|
||||
assert!(seen.parsed.is_empty() && seen.cached.is_empty(), "{seen:?}");
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "the live edit is indexed");
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk's stale member is gone");
|
||||
|
||||
// Close without saving. Disk still says `ON_DISK`; the buffer's
|
||||
// analysis of `IN_BUFFER` no longer exists anywhere to be reused.
|
||||
ws.close_document(&uri);
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.parsed, ["p.sv"], "reparsed from disk, not reused: {seen:?}");
|
||||
assert!(seen.analyzed.is_empty(), "no buffer left to analyze from: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "back to disk's member");
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the unsaved edit is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session() {
|
||||
// Charter attack 3 (large-file path), the direction the dev's own
|
||||
// test does not cover: small **on disk**, edited **huge in the
|
||||
// buffer** without saving. `doc.large` is re-decided on every
|
||||
// `set_document`, so the very next rescan must drop the buffer from
|
||||
// the analyzed-reuse route (and from the index) the moment the edit
|
||||
// crosses the threshold — not one rescan later.
|
||||
let tree = Tree::new("qathreshgrow");
|
||||
tree.write("rtl/p.sv", "package p;\n localparam SMALL = 1;\nendpackage\n");
|
||||
let path = tree.path.join("rtl/p.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(wide(ClientSettings {
|
||||
large_file_threshold: 200,
|
||||
..Default::default()
|
||||
}));
|
||||
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
|
||||
ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into());
|
||||
assert!(!ws.document(&uri).expect("open").large, "premise: a real analysis");
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.analyzed, ["p.sv"], "small buffer reused: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SMALL").len(), 1);
|
||||
|
||||
// Edited past the threshold, never saved.
|
||||
ws.set_document(uri.clone(), filler(1_000));
|
||||
assert!(ws.document(&uri).expect("open").large, "now on the fast path");
|
||||
let seen = scan(&mut ws, None);
|
||||
assert!(seen.analyzed.is_empty(), "the now-huge buffer offers no analysis: {seen:?}");
|
||||
assert!(seen.parsed.is_empty(), "and disk is not read in its place either: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SMALL").len(), 0, "contributes nothing at all");
|
||||
|
||||
// And back under the threshold: a real analysis again, reused again.
|
||||
ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into());
|
||||
assert!(!ws.document(&uri).expect("open").large, "shrank back");
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.analyzed, ["p.sv"], "reused again: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SMALL").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse() {
|
||||
// The other direction of charter attack 3: **huge on disk** (over the
|
||||
// fast-path threshold if it were read fresh — moot here, since a
|
||||
// buffer's `large` flag is decided from its own live text, never
|
||||
// disk), edited down **small in the buffer**. Included for the
|
||||
// opposite-direction symmetry the brief asks for; the on-disk size is
|
||||
// irrelevant to `doc.large` by construction (`is_large` reads
|
||||
// `text.len()`), so this is really the same claim from the other
|
||||
// starting point.
|
||||
let tree = Tree::new("qathreshshrink");
|
||||
let huge_on_disk = filler(1_000);
|
||||
tree.write("rtl/p.sv", &huge_on_disk);
|
||||
let path = tree.path.join("rtl/p.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(wide(ClientSettings {
|
||||
large_file_threshold: 200,
|
||||
..Default::default()
|
||||
}));
|
||||
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
|
||||
// Disk alone: `filler` is real Verilog (`module m; wire a; ...`), well
|
||||
// under no cap, so it is walked and parsed whole — the large-file
|
||||
// threshold applies to *buffers*, not to the walk.
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.parsed, ["p.sv"], "disk copy parsed in full: {seen:?}");
|
||||
|
||||
// Opened as a buffer with that same huge text: the fast path, same as
|
||||
// any buffer over the threshold.
|
||||
ws.set_document(uri.clone(), huge_on_disk);
|
||||
assert!(ws.document(&uri).expect("open").large, "premise: fast path from the live text");
|
||||
|
||||
// Edited down to something small, never saved.
|
||||
ws.set_document(uri.clone(), "package p;\n localparam SHRUNK = 1;\nendpackage\n".into());
|
||||
assert!(!ws.document(&uri).expect("open").large, "back to a real analysis");
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.analyzed, ["p.sv"], "the shrunk buffer's own analysis is reused: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SHRUNK").len(), 1);
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
//! The persistent index cache (docs/features/index-persistence): what a
|
||||
//! warm scan parses, what the key is, where the store lives, and when it
|
||||
//! is read, written or left exactly as it was found.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A workspace that keeps its cache in `store` and indexes every root.
|
||||
fn cached_workspace(store: &Path) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(wide(caching(store)));
|
||||
ws
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_session_over_the_same_store_parses_nothing_it_parsed_before() {
|
||||
let tree = Tree::new("cachewarm");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
tree.package("b.sv", "b_pkg");
|
||||
let store = Tree::new("cachewarm_store");
|
||||
|
||||
let mut cold = cached_workspace(&store.path);
|
||||
let first = scan(&mut cold, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(first.parsed, ["a.sv", "b.sv"], "a cold scan parses everything");
|
||||
assert!(first.cached.is_empty(), "{first:?}");
|
||||
let fingerprint = cold.index().fingerprint();
|
||||
|
||||
// A whole new server over the same tree and the same store — which is
|
||||
// what reopening the editor is.
|
||||
let mut warm = cached_workspace(&store.path);
|
||||
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
|
||||
assert!(second.parsed.is_empty(), "a warm scan parses nothing: {second:?}");
|
||||
assert_eq!(second.cached, ["a.sv", "b.sv"]);
|
||||
assert_eq!(
|
||||
warm.index().fingerprint(),
|
||||
fingerprint,
|
||||
"and the index it built is the index the parses built"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_warm_scan_parses_exactly_what_the_store_cannot_answer_for() {
|
||||
// The resume case, which is the whole feature: a store holding some
|
||||
// of the workspace — because the last session was killed halfway, or
|
||||
// because files have changed since — costs exactly the files it does
|
||||
// not answer for, and nothing else.
|
||||
let tree = Tree::new("cachehalf");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
tree.package("b.sv", "b_pkg");
|
||||
let store = Tree::new("cachehalf_store");
|
||||
|
||||
let mut first = cached_workspace(&store.path);
|
||||
scan(&mut first, Some(vec![tree.path.clone()]));
|
||||
|
||||
tree.package("b.sv", "b_renamed_pkg"); // changed since
|
||||
tree.package("c.sv", "c_pkg"); // never seen
|
||||
let mut second = cached_workspace(&store.path);
|
||||
let half = scan(&mut second, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(half.cached, ["a.sv"], "only the untouched file: {half:?}");
|
||||
assert_eq!(half.parsed, ["b.sv", "c.sv"]);
|
||||
|
||||
let mut fresh = Workspace::default();
|
||||
fresh.set_client_settings(wide(ClientSettings::default()));
|
||||
fresh.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
second.index().fingerprint(),
|
||||
fresh.index().fingerprint(),
|
||||
"a half-cached index is the index a cacheless scan would have built"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_is_the_content_and_only_the_content() {
|
||||
// Both directions of "no timestamp is trusted": a file rewritten with
|
||||
// the same bytes still hits (its modification time moved and nothing
|
||||
// else did), and a file rewritten with *different* bytes of the same
|
||||
// length misses. A cache keyed on size and mtime would get both of
|
||||
// these exactly the wrong way round.
|
||||
let tree = Tree::new("cachekey");
|
||||
tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n");
|
||||
let store = Tree::new("cachekey_store");
|
||||
|
||||
let mut ws = cached_workspace(&store.path);
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
|
||||
tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n");
|
||||
let touched = scan(&mut ws, None);
|
||||
assert_eq!(touched.cached, ["a.sv"], "the same bytes are the same file: {touched:?}");
|
||||
|
||||
tree.write("a.sv", "package a_pkg;\n localparam K = 2;\nendpackage\n");
|
||||
let changed = scan(&mut ws, None);
|
||||
assert_eq!(changed.parsed, ["a.sv"], "one byte of difference is a miss: {changed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_never_puts_back_a_file_the_scan_no_longer_visits() {
|
||||
// A record is not a file. The scope ladder decides what is walked;
|
||||
// the cache only ever answers *for* something already on the work
|
||||
// list, so a session whose scope has narrowed has an index that
|
||||
// narrowed with it, records or no records.
|
||||
let tree = Tree::new("cachescope");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
tree.package("tb/b.sv", "b_pkg");
|
||||
let store = Tree::new("cachescope_store");
|
||||
|
||||
let mut wide_session = cached_workspace(&store.path);
|
||||
scan(&mut wide_session, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(indexed(&wide_session, &["a_pkg", "b_pkg"]), ["a_pkg", "b_pkg"]);
|
||||
|
||||
// The next session is folder-scoped and only ever opens a file in
|
||||
// `rtl/`, so `tb/` is not walked at all.
|
||||
let mut narrow = Workspace::default();
|
||||
narrow.set_client_settings(caching(&store.path));
|
||||
narrow.open_roots_with(vec![tree.path.clone()], &mut |_| {});
|
||||
open(&mut narrow, &tree, "rtl/a.sv");
|
||||
let narrowed = scan(&mut narrow, None);
|
||||
// `rtl/a.sv` is this session's open buffer, so it goes in from the
|
||||
// analysis that buffer already holds rather than from the store —
|
||||
// beside this test's point, and named so the point stays legible:
|
||||
// `tb/b.sv` appears on no list at all.
|
||||
assert_eq!(narrowed.analyzed, ["a.sv"], "{narrowed:?}");
|
||||
assert!(narrowed.parsed.is_empty() && narrowed.cached.is_empty(), "{narrowed:?}");
|
||||
assert_eq!(
|
||||
indexed(&narrow, &["a_pkg", "b_pkg"]),
|
||||
["a_pkg"],
|
||||
"the record for tb/b.sv exists and is still not an indexed file"
|
||||
);
|
||||
}
|
||||
|
||||
/// The store's bytes and its modification time — "not touched" as
|
||||
/// something a test can see rather than infer.
|
||||
fn store_stamp(store: &Path) -> (Vec<u8>, std::time::SystemTime) {
|
||||
let path = store.join("index-cache");
|
||||
let bytes = fs::read(&path).expect("read store");
|
||||
let stamp = fs::metadata(&path).expect("meta").modified().expect("mtime");
|
||||
(bytes, stamp)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warm_rescan_that_appended_nothing_leaves_the_store_exactly_as_it_found_it() {
|
||||
// §P4b (a) through the workspace: every file hits the store, so the
|
||||
// session appends nothing, so the compaction at the end of the scan
|
||||
// would rewrite the file it read into itself. It does not run, and
|
||||
// the store on disk is not touched — not its bytes, not its mtime.
|
||||
let tree = Tree::new("compactskip");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
tree.package("b.sv", "b_pkg");
|
||||
let store = Tree::new("compactskip_store");
|
||||
|
||||
let mut cold = cached_workspace(&store.path);
|
||||
scan(&mut cold, Some(vec![tree.path.clone()]));
|
||||
let before = store_stamp(&store.path);
|
||||
|
||||
let mut warm = cached_workspace(&store.path);
|
||||
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(second.cached, ["a.sv", "b.sv"], "premise: a scan that appends nothing");
|
||||
assert_eq!(store_stamp(&store.path), before, "the store was not rewritten");
|
||||
|
||||
// A third session still reads it, and a file that *did* change still
|
||||
// costs the rewrite that folds its new record in.
|
||||
tree.package("b.sv", "b_renamed_pkg");
|
||||
let mut third = cached_workspace(&store.path);
|
||||
let changed = scan(&mut third, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(changed.parsed, ["b.sv"], "{changed:?}");
|
||||
let after = fs::read_to_string(store.path.join("index-cache")).expect("a store");
|
||||
assert!(after.contains("b_renamed_pkg"), "the changed file's record landed");
|
||||
assert_eq!(after.lines().count(), 3, "and the store is one line per path: {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it() {
|
||||
// §P4b (b1). `Server::started` builds the index at the **default**
|
||||
// settings, before `workspace/configuration` can even be asked — and
|
||||
// the folder scope is derived from the directories a buffer has been
|
||||
// opened from, of which there are none, so that scan's work list is
|
||||
// empty. Warm it still opened a 44 MiB store and rewrote it
|
||||
// byte-identically: 184 ms of a 1.33 s start, for a scan that indexes
|
||||
// nothing (`docs/features/perf5-p4/README.md`).
|
||||
let tree = Tree::new("emptyscan");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
tree.package("rtl/b.sv", "b_pkg");
|
||||
let store = Tree::new("emptyscan_store");
|
||||
|
||||
let mut filling = cached_workspace(&store.path);
|
||||
scan(&mut filling, Some(vec![tree.path.clone()]));
|
||||
let before = store_stamp(&store.path);
|
||||
|
||||
// The startup shape: the folder scope, no buffer open.
|
||||
let mut empty = Workspace::default();
|
||||
empty.set_client_settings(caching(&store.path));
|
||||
empty.adopt_roots(vec![tree.path.clone()]);
|
||||
let nothing = scan(&mut empty, None);
|
||||
assert_eq!(nothing, Scan::default(), "premise: this scan indexes no file");
|
||||
assert_eq!(store_stamp(&store.path), before, "so the store is neither read nor written");
|
||||
|
||||
// And the widen the first `didOpen` triggers still hits every record
|
||||
// the store holds — the open was deferred to the first file that
|
||||
// wants it, not dropped.
|
||||
let opened = tree.path.join("rtl/a.sv");
|
||||
let uri = crate::uri::path_to_uri(&opened).expect("uri");
|
||||
empty.set_document(uri, fs::read_to_string(&opened).expect("read"));
|
||||
let added: Vec<PathBuf> = empty.scope_dirs();
|
||||
assert_eq!(added, vec![tree.path.join("rtl")], "premise: the open widened the scope");
|
||||
let mut widened = Scan::default();
|
||||
empty.widen_index_with(&added, &mut |event| match event {
|
||||
IndexEvent::Parsing { path, .. } => widened.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => widened.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => widened.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
});
|
||||
assert_eq!(widened.analyzed, ["a.sv"], "the open buffer indexes itself: {widened:?}");
|
||||
assert_eq!(widened.cached, ["b.sv"], "the widen reads the store the scan left: {widened:?}");
|
||||
assert!(widened.parsed.is_empty(), "not one file reparsed: {widened:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cold_session_that_indexes_nothing_creates_no_store_at_all() {
|
||||
// The same rule the other way up: with no store yet and no file to
|
||||
// index, nothing is created — no directory, no `.gitignore`, no
|
||||
// header-only store — and the session that *does* index a file makes
|
||||
// all three.
|
||||
let tree = Tree::new("emptycold");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let store = Tree::new("emptycold_store");
|
||||
let dir = store.path.join("inner");
|
||||
|
||||
let mut empty = Workspace::default();
|
||||
empty.set_client_settings(caching(&dir));
|
||||
empty.adopt_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(scan(&mut empty, None), Scan::default(), "premise");
|
||||
assert!(!dir.exists(), "a scan with no files creates no cache directory");
|
||||
|
||||
let mut indexing = cached_workspace(&dir);
|
||||
scan(&mut indexing, Some(vec![tree.path.clone()]));
|
||||
assert!(dir.join("index-cache").exists(), "and a scan with files still writes one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_off_reads_nothing_and_writes_nothing() {
|
||||
let tree = Tree::new("cacheoff");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let store = Tree::new("cacheoff_store");
|
||||
|
||||
// Nothing is written while it is off…
|
||||
let mut off = Workspace::default();
|
||||
off.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
|
||||
scan(&mut off, Some(vec![tree.path.clone()]));
|
||||
assert!(!store.path.join("index-cache").exists(), "persist: false must not write");
|
||||
|
||||
// …and a store that already exists is not read when it goes off.
|
||||
let mut on = cached_workspace(&store.path);
|
||||
scan(&mut on, Some(vec![tree.path.clone()]));
|
||||
assert!(store.path.join("index-cache").exists(), "premise: a store to ignore");
|
||||
let mut ignoring = Workspace::default();
|
||||
ignoring
|
||||
.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
|
||||
let scanned = scan(&mut ignoring, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(scanned.parsed, ["a.sv"], "persist: false must not read: {scanned:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_persistence_off_mid_session_stops_the_write_through_at_once() {
|
||||
// A save takes the incremental path, which writes its record through
|
||||
// without any rescan — so `persist: false` has to reach it the moment
|
||||
// it lands, not at the next scan.
|
||||
let tree = Tree::new("cachemidsession");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let store = Tree::new("cachemidsession_store");
|
||||
|
||||
let mut ws = cached_workspace(&store.path);
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
tree.package("a.sv", "a_pkg_v2");
|
||||
assert!(ws.update_one(&tree.path.join("a.sv")), "premise: the fast path took it");
|
||||
let after_save = fs::read_to_string(store.path.join("index-cache")).expect("a store");
|
||||
assert!(after_save.contains("a_pkg_v2"), "a save writes its record through");
|
||||
|
||||
ws.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
|
||||
tree.package("a.sv", "a_pkg_v3");
|
||||
assert!(ws.update_one(&tree.path.join("a.sv")));
|
||||
let after_off = fs::read_to_string(store.path.join("index-cache")).expect("a store");
|
||||
assert_eq!(after_off, after_save, "nothing more is written once it is off");
|
||||
}
|
||||
|
||||
/// QA (2026-08-27), the no-mtime deviation's save-path half: the
|
||||
/// write-through on `update_one` must key its record on the *buffer's*
|
||||
/// bytes, never on what happens to be on disk — that is the argument the
|
||||
/// README gives for why a stored `(size, mtime)` would have been unsound
|
||||
/// (a save's text can come from an unsaved buffer). Constructed
|
||||
/// directly: open a buffer whose text disagrees with the file on disk,
|
||||
/// let the incremental path write its record through, and check the
|
||||
/// store's record is keyed by the *buffer's* hash and holds the
|
||||
/// *buffer's* facts — and that disk's actual bytes, hashed, do not
|
||||
/// match what got written.
|
||||
#[test]
|
||||
fn a_saved_buffers_record_is_keyed_and_filled_from_the_buffer_not_stale_disk() {
|
||||
let tree = Tree::new("cachebuffer");
|
||||
tree.package("a.sv", "a_pkg_on_disk");
|
||||
let store = Tree::new("cachebuffer_store");
|
||||
|
||||
let mut ws = cached_workspace(&store.path);
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
|
||||
// The buffer disagrees with disk — as it does the moment a user
|
||||
// types, before the editor's next `didSave` reaches disk at all.
|
||||
let path = tree.path.join("a.sv");
|
||||
let buffer_text = "package a_pkg_in_buffer;\n localparam K = 1;\nendpackage\n";
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, buffer_text.to_string());
|
||||
assert!(ws.update_one(&path), "premise: the fast path took it");
|
||||
|
||||
// The append log still holds the earlier, disk-keyed line too — it is
|
||||
// not rewritten until the next whole-scan compaction — so the write
|
||||
// itself is checked by what it added, and the *effective* record
|
||||
// (what `open` resolves a repeated path to: the last line wins) is
|
||||
// checked separately below, which is the property that actually
|
||||
// matters for correctness.
|
||||
let store_text = fs::read_to_string(store.path.join("index-cache")).expect("a store");
|
||||
assert!(
|
||||
store_text.contains("a_pkg_in_buffer"),
|
||||
"the write-through must have appended the buffer's facts: {store_text}"
|
||||
);
|
||||
let buffer_hash = lucisv_core::cache::content_hash(buffer_text.as_bytes());
|
||||
assert!(
|
||||
store_text.contains(&format!("{buffer_hash:016x}")),
|
||||
"the appended record's key is the buffer's content hash: {store_text}"
|
||||
);
|
||||
|
||||
let disk_text = fs::read_to_string(&path).expect("disk");
|
||||
let disk_hash = lucisv_core::cache::content_hash(disk_text.as_bytes());
|
||||
assert_ne!(disk_hash, buffer_hash, "premise: disk and buffer really do disagree");
|
||||
|
||||
let reopened = IndexCache::open(Some(store.path.clone()));
|
||||
assert_eq!(
|
||||
reopened.facts_for(&path, buffer_text),
|
||||
Some(FileFacts::of(path.clone(), buffer_text)),
|
||||
"the record a fresh session resolves to is the buffer's, not disk's stale one"
|
||||
);
|
||||
assert!(
|
||||
reopened.facts_for(&path, &disk_text).is_none(),
|
||||
"disk's own current bytes must not hit — no record was ever keyed on them"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_cache_path_beats_the_editors_storage_folder() {
|
||||
// Rung 1 over rung 2 of `index_cache::cache_dir`'s ladder, through
|
||||
// the workspace rather than against the function: the store lands
|
||||
// where the *setting* says, and the editor's folder is left alone.
|
||||
let tree = Tree::new("cacheladder");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let storage = Tree::new("cacheladder_storage");
|
||||
let configured = Tree::new("cacheladder_configured");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_storage_path(Some(storage.path.clone()));
|
||||
ws.set_client_settings(wide(caching(&configured.path)));
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
assert!(configured.path.join("index-cache").exists(), "the setting won");
|
||||
assert!(!storage.path.join("index-cache").exists(), "the editor's folder is untouched");
|
||||
|
||||
// Unset it and the editor's folder is what is left standing — on the
|
||||
// next scan, which is when the store is re-opened.
|
||||
ws.set_client_settings(wide(ClientSettings::default()));
|
||||
ws.set_storage_path(Some(storage.path.clone()));
|
||||
scan(&mut ws, None);
|
||||
assert!(storage.path.join("index-cache").exists(), "and now the editor's folder");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_storage_folder_that_does_not_exist_yet_is_made_on_demand() {
|
||||
// What VS Code hands over: `context.storageUri` names a folder the
|
||||
// editor has not necessarily created.
|
||||
let tree = Tree::new("cachemkdir");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let storage = Tree::new("cachemkdir_storage");
|
||||
let nested = storage.path.join("deep/inner");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_storage_path(Some(nested.clone()));
|
||||
ws.set_client_settings(wide(ClientSettings::default()));
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
assert!(nested.join("index-cache").exists(), "made on demand");
|
||||
|
||||
let mut warm = Workspace::default();
|
||||
warm.set_storage_path(Some(nested));
|
||||
warm.set_client_settings(wide(ClientSettings::default()));
|
||||
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(second.cached, ["a.sv"], "{second:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus() {
|
||||
// The paranoid sweep, against the real corpus: every file in, every
|
||||
// file out of the cache, and the two indexes compared observable by
|
||||
// observable through the fingerprint.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let store = Tree::new("cachecorpus_store");
|
||||
|
||||
let mut cold = cached_workspace(&store.path);
|
||||
let first = scan(&mut cold, Some(vec![corpus.clone()]));
|
||||
assert!(first.parsed.len() > 500, "premise: the corpus was really scanned");
|
||||
assert!(first.cached.is_empty());
|
||||
|
||||
let mut warm = cached_workspace(&store.path);
|
||||
let second = scan(&mut warm, Some(vec![corpus]));
|
||||
assert_eq!(second.cached.len(), first.parsed.len(), "every file came back");
|
||||
assert!(second.parsed.is_empty(), "and none was parsed again");
|
||||
assert_eq!(
|
||||
warm.index().fingerprint(),
|
||||
cold.index().fingerprint(),
|
||||
"the cached index is the parsed index, file ids and all"
|
||||
);
|
||||
assert_eq!(warm.index().counts(), cold.index().counts());
|
||||
// The completion tables and the include graph are built from the
|
||||
// files' text either way, so they cannot drift — pinned rather than
|
||||
// assumed, since the cache is the one thing that skips a file's parse.
|
||||
assert_eq!(warm.candidates().words(""), cold.candidates().words(""));
|
||||
}
|
||||
|
||||
/// QA (2026-08-27), attack surface 1/4, fixed 2026-08-27: the negative
|
||||
/// control the equivalence sweep above cannot run on its own, through the
|
||||
/// whole workspace rather than the store. A record used to be verified
|
||||
/// only against the *file's* content hash, so a line whose hash matched
|
||||
/// `a.sv`'s real bytes but whose facts were altered was a hit and the
|
||||
/// index it produced silently diverged from what a fresh parse gives.
|
||||
/// Every record now carries a checksum of its own facts, so the damaged
|
||||
/// line is dropped: the file is parsed, the scan reports it as parsed
|
||||
/// rather than cached, and the fingerprint is exactly a fresh scan's.
|
||||
/// That is `docs/features/index-persistence`'s "a performance artifact
|
||||
/// and never a correctness input" holding against *accidental* damage of
|
||||
/// any shape; a store deliberately reforged is out of the threat model
|
||||
/// and pinned as such in `index_cache.rs`.
|
||||
#[test]
|
||||
fn a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans() {
|
||||
let tree = Tree::new("poisonfingerprint");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let store = Tree::new("poisonfingerprint_store");
|
||||
|
||||
let mut cold = cached_workspace(&store.path);
|
||||
scan(&mut cold, Some(vec![tree.path.clone()]));
|
||||
let honest = cold.index().fingerprint();
|
||||
|
||||
// Hand-tamper the store on disk: keep the header, the hash of `a.sv`'s
|
||||
// *real* bytes and the checksum the genuine record was written with,
|
||||
// but swap in facts a parse of those bytes never produced (a different
|
||||
// package name entirely) — which is what every accidental way a
|
||||
// written record can change looks like from the reader's side.
|
||||
let store_file = store.path.join("index-cache");
|
||||
let text = fs::read_to_string(&store_file).expect("a store");
|
||||
let header_line = text.lines().next().expect("header").to_string();
|
||||
let record = text.lines().nth(1).expect("a record").to_string();
|
||||
let checksum = record.rsplit('\t').next().expect("a checksum field");
|
||||
let real_text = "package a_pkg;\n localparam K = 1;\nendpackage\n";
|
||||
let hash = lucisv_core::cache::content_hash(real_text.as_bytes());
|
||||
let evil = FileFacts::of(
|
||||
tree.path.join("a.sv"),
|
||||
"package poisoned_pkg;\n localparam K = 999;\nendpackage\n",
|
||||
);
|
||||
let poisoned =
|
||||
format!("{header_line}\n{hash:016x}\t{}\t{checksum}\n", evil.encode().expect("encodes"));
|
||||
fs::write(&store_file, poisoned).expect("write");
|
||||
|
||||
let mut warm = cached_workspace(&store.path);
|
||||
let scanned = scan(&mut warm, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(scanned.parsed, ["a.sv"], "the tampered record is dropped: {scanned:?}");
|
||||
assert!(scanned.cached.is_empty(), "and it is not served: {scanned:?}");
|
||||
assert_eq!(
|
||||
warm.index().fingerprint(),
|
||||
honest,
|
||||
"a record whose facts no longer match their checksum cannot reach the index, so \
|
||||
the equivalence sweep's own claim holds against damage as well as staleness"
|
||||
);
|
||||
}
|
||||
|
||||
/// The measurement behind the README's numbers: a scan with no cache at
|
||||
/// all, a cold one that fills the store, a warm one that reads it, and a
|
||||
/// half-warm one with a single file changed.
|
||||
#[test]
|
||||
#[ignore = "measurement, not a test"]
|
||||
fn qa_perf_cold_warm_and_half_warm_scans() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let store = Tree::new("cacheperf_store");
|
||||
let timed = |ws: &mut Workspace| {
|
||||
let started = std::time::Instant::now();
|
||||
let scanned = scan(ws, None);
|
||||
(started.elapsed(), scanned)
|
||||
};
|
||||
|
||||
// The baseline: what a rescan cost before this feature existed.
|
||||
let mut off = Workspace::default();
|
||||
off.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
|
||||
scan(&mut off, Some(vec![corpus.clone()]));
|
||||
let (cacheless, _) = timed(&mut off);
|
||||
|
||||
let mut ws = cached_workspace(&store.path);
|
||||
let started = std::time::Instant::now();
|
||||
let cold_scan = scan(&mut ws, Some(vec![corpus.clone()]));
|
||||
let cold = started.elapsed();
|
||||
let (warm, warm_scan) = timed(&mut ws);
|
||||
|
||||
// Half-warm: the store answers for every file but the one edited.
|
||||
let one = ws.index().files()[0].clone();
|
||||
let text = fs::read_to_string(&one).expect("read");
|
||||
fs::write(&one, format!("{text}\n// edited\n")).expect("write");
|
||||
let (half, half_scan) = timed(&mut ws);
|
||||
fs::write(&one, &text).expect("restore");
|
||||
|
||||
let files = ws.index().files().len();
|
||||
eprintln!(
|
||||
"{files} files: no cache {cacheless:?}; cold {cold:?} ({} parsed); \
|
||||
warm {warm:?} ({} cached); half-warm {half:?} ({} parsed, {} cached) — \
|
||||
warm is {:.2}x the cacheless scan",
|
||||
cold_scan.parsed.len(),
|
||||
warm_scan.cached.len(),
|
||||
half_scan.parsed.len(),
|
||||
half_scan.cached.len(),
|
||||
cacheless.as_secs_f64() / warm.as_secs_f64().max(f64::MIN_POSITIVE)
|
||||
);
|
||||
let store_size = fs::metadata(store.path.join("index-cache")).expect("a store").len();
|
||||
eprintln!("store: {store_size} bytes for {files} files");
|
||||
|
||||
// What the key costs, which is the whole argument for keying on
|
||||
// content rather than on a timestamp: the text is read on every scan
|
||||
// anyway (the completion tables and the include graph are built from
|
||||
// it), so the alternative would only ever have saved this.
|
||||
let texts: Vec<String> =
|
||||
ws.index().files().iter().filter_map(|path| fs::read_to_string(path).ok()).collect();
|
||||
let bytes: usize = texts.iter().map(String::len).sum();
|
||||
let started = std::time::Instant::now();
|
||||
let mut sink = 0u64;
|
||||
for text in &texts {
|
||||
sink ^= lucisv_core::cache::content_hash(text.as_bytes());
|
||||
}
|
||||
eprintln!("hashing {bytes} bytes of {files} files: {:?} ({sink:016x})", started.elapsed());
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! What the walk takes — source extensions, gitignores, the root config's
|
||||
//! excludes and the client's — and which pushed settings ask for a rescan.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_scan_skips_what_a_gitignore_skips() {
|
||||
let tree = Tree::new("gitignore");
|
||||
tree.write(".gitignore", "generated/\n*_gen.sv\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("generated/netlist.sv", "generated_pkg");
|
||||
tree.package("rtl/top_gen.sv", "gen_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1, "a plain file is indexed");
|
||||
assert_eq!(ws.index().member("generated_pkg", "K").len(), 0, "an ignored directory");
|
||||
assert_eq!(ws.index().member("gen_pkg", "K").len(), 0, "an ignored name, at depth");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scan_honours_the_root_configs_excludes() {
|
||||
let tree = Tree::new("excludes");
|
||||
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("vendor/ip.sv", "vendor_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1);
|
||||
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "lucisv.toml excludes apply");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_root_config_does_not_stop_the_scan() {
|
||||
// Exit 2 is the CLI's answer to a broken config; a server that indexed
|
||||
// nothing because of a typo would look simply broken instead.
|
||||
let tree = Tree::new("brokencfg");
|
||||
tree.write("lucisv.toml", "bogus = 1\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_exclude_hides_files_from_the_index() {
|
||||
let tree = Tree::new("clientexclude");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("scratch/wip.sv", "scratch_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 1, "premise: indexed at first");
|
||||
|
||||
assert!(ws.set_client_settings(wide(excluding(&["scratch"]))), "an exclude change rescans");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
|
||||
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "the excluded one is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_exclude_is_appended_to_the_configs_and_does_not_replace_it() {
|
||||
// The failure this guards: a user setting `lucisv.exclude` in their
|
||||
// editor and thereby putting the project's vendored code — which the
|
||||
// checked-in `lucisv.toml` excludes — back into the index for them only.
|
||||
let tree = Tree::new("bothexcludes");
|
||||
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("vendor/ip.sv", "vendor_pkg");
|
||||
tree.package("scratch/wip.sv", "scratch_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(excluding(&["scratch"]));
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
|
||||
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "the config's exclude holds");
|
||||
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "and the pushed one applies");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_an_exclude_change_asks_for_a_rescan() {
|
||||
// `lineLength` and `indent` are read afresh by every formatting
|
||||
// request, so re-walking the workspace for them would be pure cost.
|
||||
let mut ws = Workspace::default();
|
||||
assert!(!ws.set_client_settings(ClientSettings::default()), "nothing changed");
|
||||
assert!(
|
||||
!ws.set_client_settings(ClientSettings {
|
||||
line_length: Some(120),
|
||||
indent: Some(4),
|
||||
..Default::default()
|
||||
}),
|
||||
"widths do not move files"
|
||||
);
|
||||
// QA (2026-08-26): `format_on_save` is read afresh by
|
||||
// `will_save_wait_until` exactly as `indent`/`lineLength` are by
|
||||
// `formatting` — it must not ask for a rescan either, or every
|
||||
// `lucisv.formatOnSave` toggle would pay for a full re-walk (and, on
|
||||
// a client that pulls, bump the diagnostics generation along with
|
||||
// it).
|
||||
assert!(
|
||||
!ws.set_client_settings(ClientSettings { format_on_save: true, ..Default::default() }),
|
||||
"turning the save hook on does not move files either"
|
||||
);
|
||||
// The file log changes how loudly a rescan narrates itself and nothing
|
||||
// about which files exist, so it must not buy one.
|
||||
assert!(
|
||||
!ws.set_client_settings(ClientSettings { log_files: false, ..Default::default() }),
|
||||
"turning the per-file log off does not move files either"
|
||||
);
|
||||
assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does");
|
||||
// The cap does move files, so it does.
|
||||
assert!(
|
||||
ws.set_client_settings(ClientSettings {
|
||||
exclude: vec!["a".to_string()],
|
||||
max_file_size: 4096,
|
||||
..Default::default()
|
||||
}),
|
||||
"a new cap rescans"
|
||||
);
|
||||
assert!(
|
||||
!ws.set_client_settings(ClientSettings {
|
||||
exclude: vec!["a".to_string()],
|
||||
max_file_size: 4096,
|
||||
log_files: false,
|
||||
..Default::default()
|
||||
}),
|
||||
"the same cap with a different log setting does not"
|
||||
);
|
||||
assert!(
|
||||
ws.set_client_settings(ClientSettings {
|
||||
exclude: vec!["a".to_string()],
|
||||
log_files: false,
|
||||
..Default::default()
|
||||
}),
|
||||
"and going back to the default cap does"
|
||||
);
|
||||
ws.set_client_settings(excluding(&["a"]));
|
||||
assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not");
|
||||
assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does");
|
||||
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_change_asks_for_a_rescan_too() {
|
||||
// It changes which files exist as far as this server is concerned,
|
||||
// which is the whole test for whether a rescan is owed.
|
||||
let mut ws = Workspace::default();
|
||||
assert!(ws.set_client_settings(using_filelist("files.f")), "a new filelist rescans");
|
||||
assert!(!ws.set_client_settings(using_filelist("files.f")), "the same one does not");
|
||||
assert!(ws.set_client_settings(using_filelist("other.f")), "a different one does");
|
||||
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pushed_settings_are_readable_where_formatting_needs_them() {
|
||||
let mut ws = Workspace::default();
|
||||
assert_eq!(ws.client_settings(), &ClientSettings::default(), "default until pushed");
|
||||
ws.set_client_settings(ClientSettings {
|
||||
line_length: Some(120),
|
||||
indent: Some(4),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(ws.client_settings().indent, Some(4));
|
||||
assert_eq!(ws.client_settings().line_length, Some(120));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scan_takes_only_source_extensions() {
|
||||
let tree = Tree::new("extensions");
|
||||
tree.package("a.sv", "a");
|
||||
tree.package("b.v", "b");
|
||||
tree.package("c.svh", "c");
|
||||
tree.package("d.vh", "d");
|
||||
tree.package("e.txt", "e");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
for name in ["a", "b", "c", "d"] {
|
||||
assert_eq!(ws.index().member(name, "K").len(), 1, "{name} is a source file");
|
||||
}
|
||||
assert_eq!(ws.index().member("e", "K").len(), 0, "a .txt is not");
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! `lucisv.index.maxFileSize`: a walked file over the cap is left out of
|
||||
//! the index, an open buffer never is, and every skip is reported with its
|
||||
//! size and the cap.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_walked_file_over_the_cap_is_left_out_of_the_index() {
|
||||
let tree = Tree::new("capskip");
|
||||
tree.package("small.sv", "small_pkg");
|
||||
fat_package(&tree, "netlist.sv", "netlist_pkg", 4096);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(capping(1024));
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
indexed(&ws, &["small_pkg", "netlist_pkg"]),
|
||||
["small_pkg"],
|
||||
"the big file is not in the index, and was never read"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_cap_is_a_mebibyte_and_zero_turns_it_off() {
|
||||
// The shipped default, exercised against a file that really is over
|
||||
// 1 MiB — the only way to prove the constant is the one in force.
|
||||
let tree = Tree::new("capdefault");
|
||||
tree.package("small.sv", "small_pkg");
|
||||
fat_package(&tree, "huge.sv", "huge_pkg", 1024 * 1024 + 1);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["small_pkg", "huge_pkg"]), ["small_pkg"], "capped by default");
|
||||
|
||||
// `0` is the client asking for no cap, and must be exactly the
|
||||
// behaviour that existed before there was one.
|
||||
assert!(ws.set_client_settings(wide(capping(0))), "turning the cap off rescans");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
indexed(&ws, &["small_pkg", "huge_pkg"]),
|
||||
["small_pkg", "huge_pkg"],
|
||||
"nothing capped"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_is_indexed_however_big_the_file_is() {
|
||||
// The documented exemption: the cap is about files nobody asked for.
|
||||
// A buffer the user opened is indexed and diagnosed whatever its size,
|
||||
// or the editor would refuse to understand the file on screen.
|
||||
let tree = Tree::new("capbuffer");
|
||||
fat_package(&tree, "huge.sv", "huge_pkg", 4096);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(capping(1024));
|
||||
// Whole-workspace scope so the walked file is genuinely capped by the
|
||||
// CAP, not merely unreachable by the folder scope (QA finding,
|
||||
// 2026-08-27, lead-fixed: the premise held for the wrong reason).
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::<String>::new(), "premise: capped on disk");
|
||||
|
||||
let uri = crate::uri::path_to_uri(&tree.path.join("huge.sv")).expect("uri");
|
||||
let text = fs::read_to_string(tree.path.join("huge.sv")).expect("read");
|
||||
ws.set_document(uri, text);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "the open buffer is indexed in full");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before() {
|
||||
// QA attack (index-scope, 2026-08-28, charter item 4: the cap
|
||||
// boundary). `collect_sources` walks the scope and reports
|
||||
// `Skipped` for every file over `maxFileSize` *before* it knows
|
||||
// whether an open buffer speaks for that path — that ordering is
|
||||
// pre-existing (the `spoken_for` short-circuit this round added only
|
||||
// skips the wasted disk *read*, not the cap check ahead of it). The
|
||||
// question this pins: did routing an open buffer's facts through its
|
||||
// own analysis change that reporting, or the fact that the buffer
|
||||
// still ends up indexed in full? It must not: the file is still
|
||||
// reported `Skipped` once (the disk phase honestly saying the walked
|
||||
// copy is over cap), and it still ends up indexed — now via
|
||||
// `Analyzed` rather than `Parsing`, since the round's whole point is
|
||||
// that an open buffer's own analysis is reused instead of reparsed.
|
||||
let tree = Tree::new("capbufferqa");
|
||||
fat_package(&tree, "huge.sv", "huge_pkg", 4096);
|
||||
let path = tree.path.join("huge.sv");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(capping(1024));
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::<String>::new(), "premise: capped on disk");
|
||||
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
let text = fs::read_to_string(&path).expect("read");
|
||||
ws.set_document(uri, text);
|
||||
|
||||
let mut skipped: Vec<PathBuf> = Vec::new();
|
||||
let mut analyzed: Vec<PathBuf> = Vec::new();
|
||||
let mut parsed: Vec<PathBuf> = Vec::new();
|
||||
ws.rebuild_index_with(&mut |event| match event {
|
||||
IndexEvent::Skipped { path, .. } => skipped.push(path.to_path_buf()),
|
||||
IndexEvent::Analyzed { path, .. } => analyzed.push(path.to_path_buf()),
|
||||
IndexEvent::Parsing { path, .. } => parsed.push(path.to_path_buf()),
|
||||
IndexEvent::Cached { .. } => {}
|
||||
});
|
||||
assert_eq!(skipped, vec![path.clone()], "still reported skipped once, from the disk phase");
|
||||
assert_eq!(analyzed, vec![path.clone()], "and indexed via its own analysis, not reparsed");
|
||||
assert!(parsed.is_empty(), "never re-parsed: {parsed:?}");
|
||||
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "still indexed in full, unmoved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_skipped_file_is_reported_with_its_size_and_the_cap() {
|
||||
let tree = Tree::new("capevents");
|
||||
tree.package("small.sv", "small_pkg");
|
||||
fat_package(&tree, "netlist.sv", "netlist_pkg", 4096);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(capping(1024));
|
||||
let mut skipped: Vec<(PathBuf, u64, u64)> = Vec::new();
|
||||
ws.open_whole_workspace_with(vec![tree.path.clone()], &mut |event| {
|
||||
if let IndexEvent::Skipped { path, size, cap } = event {
|
||||
skipped.push((path.to_path_buf(), size, cap));
|
||||
}
|
||||
});
|
||||
assert_eq!(skipped.len(), 1, "{skipped:?}");
|
||||
assert_eq!(skipped[0].0, tree.path.join("netlist.sv"));
|
||||
assert!(skipped[0].1 >= 4096, "the file's real size: {skipped:?}");
|
||||
assert_eq!(skipped[0].2, 1024, "and the cap it was measured against");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_watcher_sees_every_file_in_index_order_against_a_total_it_knew_first() {
|
||||
// The denominator is the work list *after* the exclude and the cap:
|
||||
// a bar counting towards a number that included files nobody was
|
||||
// going to parse would stall short of the end every time.
|
||||
let tree = Tree::new("capwatch");
|
||||
tree.package("b.sv", "b");
|
||||
tree.package("a.sv", "a");
|
||||
tree.package("skipped/c.sv", "c");
|
||||
fat_package(&tree, "d.sv", "d_pkg", 4096);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
exclude: vec!["skipped".to_string()],
|
||||
max_file_size: 1024,
|
||||
..Default::default()
|
||||
});
|
||||
let mut seen: Vec<(usize, usize, PathBuf)> = Vec::new();
|
||||
ws.open_whole_workspace_with(vec![tree.path.clone()], &mut |event| {
|
||||
if let IndexEvent::Parsing { done, total, path } = event {
|
||||
seen.push((done, total, path.to_path_buf()));
|
||||
}
|
||||
});
|
||||
assert_eq!(
|
||||
seen,
|
||||
vec![(0, 2, tree.path.join("a.sv")), (1, 2, tree.path.join("b.sv")),],
|
||||
"sorted, excluded and capped files absent, total known from the first event"
|
||||
);
|
||||
assert_eq!(ws.index().files().len(), 2, "and the index holds exactly those");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_cap_changes_nothing_about_the_real_corpus() {
|
||||
// The cap ships on, so the burden is to show it costs an existing
|
||||
// project nothing: the index the default cap builds over `corpus/`
|
||||
// must be the one no cap at all builds. It is — the largest corpus
|
||||
// file is 94 KB, eleven times under the cap — and this test is what
|
||||
// notices if a future corpus, or a future default, changes that.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
let mut capped = Workspace::default();
|
||||
capped.open_whole_workspace(vec![corpus.clone()]);
|
||||
let mut uncapped = Workspace::default();
|
||||
uncapped.set_client_settings(capping(0));
|
||||
uncapped.open_whole_workspace(vec![corpus]);
|
||||
|
||||
assert_eq!(capped.index().files(), uncapped.index().files(), "the same files, in order");
|
||||
assert_eq!(capped.index().counts(), uncapped.index().counts(), "and the same index");
|
||||
assert!(capped.index().files().len() > 500, "premise: the corpus was really scanned");
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! The closed-file view cache.
|
||||
//!
|
||||
//! Every test below observes the cache the only honest way there is: it
|
||||
//! changes a file on disk *without telling the server*, and asks whether
|
||||
//! the next view still shows the old text. A view that survives such an
|
||||
//! edit was cached; one that does not was re-read. That is a cache and not
|
||||
//! a correctness input, so "still shows the old text" is the expected
|
||||
//! answer everywhere the invalidation list does not name.
|
||||
|
||||
use super::*;
|
||||
use crate::state::views::{MAX_VIEWS, MAX_VIEW_BYTES};
|
||||
|
||||
/// A file with `n` declared modules, so its text is both readable and
|
||||
/// tellable apart.
|
||||
fn versioned(n: usize) -> String {
|
||||
(0..n).map(|k| format!("module m{k};\nendmodule\n")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_files_text_is_read_once_and_then_reused() {
|
||||
let tree = Tree::new("viewreuse");
|
||||
tree.write("sub.sv", &versioned(1));
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let path = tree.path.join("sub.sv");
|
||||
|
||||
let first = ws.file_view(&path).expect("readable").text.clone();
|
||||
assert!(first.contains("m0"), "premise: the file was read");
|
||||
// Behind the server's back — no didSave, no watcher, no rescan.
|
||||
tree.write("sub.sv", &versioned(2));
|
||||
assert_eq!(
|
||||
ws.file_view(&path).expect("readable").text,
|
||||
first,
|
||||
"the second question about one file costs no second read"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_an_open_buffer_speaks_for_has_no_view_of_its_own() {
|
||||
// The buffer's own `Document` is the authority on its text; a second
|
||||
// copy here would be a second opinion, so there is deliberately none.
|
||||
let tree = Tree::new("viewopen");
|
||||
tree.write("sub.sv", &versioned(1));
|
||||
let path = tree.path.join("sub.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(ws.file_view(&path).is_some(), "premise: readable while closed");
|
||||
|
||||
ws.set_document(uri(&format!("file://{}", path.display())), versioned(3));
|
||||
assert!(ws.file_view(&path).is_none(), "an open buffer answers for itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_way_a_files_text_can_move_drops_its_view() {
|
||||
// The four invalidation points named in `Workspace::file_view`'s doc
|
||||
// comment, each proved by the same experiment: warm the view, change
|
||||
// the file on disk, run the event, and require the next view to be
|
||||
// the new text rather than the held one.
|
||||
let path_uri = |path: &Path| uri(&format!("file://{}", path.display()));
|
||||
|
||||
for event in ["didOpen", "didClose", "update_one", "rebuild"] {
|
||||
let tree = Tree::new(&format!("viewdrop_{event}"));
|
||||
tree.write("sub.sv", &versioned(1));
|
||||
let path = tree.path.join("sub.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let held = ws.file_view(&path).expect("readable").text.clone();
|
||||
tree.write("sub.sv", &versioned(2));
|
||||
assert_eq!(ws.file_view(&path).expect("readable").text, held, "premise: {event}");
|
||||
|
||||
match event {
|
||||
// Opening the file: the buffer takes over, and closing it
|
||||
// again must not hand back the view from before the buffer
|
||||
// existed — it predates every save that buffer made.
|
||||
"didOpen" | "didClose" => {
|
||||
ws.set_document(path_uri(&path), versioned(9));
|
||||
assert!(ws.file_view(&path).is_none(), "open: no view at all");
|
||||
ws.close_document(&path_uri(&path));
|
||||
}
|
||||
"update_one" => {
|
||||
assert!(ws.update_one(&path), "the index holds this file");
|
||||
}
|
||||
"rebuild" => {
|
||||
ws.rebuild_index();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let after = ws.file_view(&path).expect("readable").text.clone();
|
||||
assert_ne!(after, held, "{event} must drop the held view");
|
||||
assert!(after.contains("m1"), "{event} must serve the file as it is now: {after}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text() {
|
||||
let tree = Tree::new("viewbound");
|
||||
let paths: Vec<PathBuf> = (0..MAX_VIEWS + 2)
|
||||
.map(|n| {
|
||||
tree.write(&format!("f{n}.sv"), &versioned(n + 1));
|
||||
tree.path.join(format!("f{n}.sv"))
|
||||
})
|
||||
.collect();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
for path in &paths {
|
||||
let _ = ws.file_view(path).expect("readable");
|
||||
}
|
||||
assert_eq!(ws.views.borrow().len(), MAX_VIEWS, "the count bound holds");
|
||||
assert_eq!(
|
||||
ws.views.borrow()[0].path,
|
||||
paths[paths.len() - 1],
|
||||
"newest first, so the oldest is what falls off"
|
||||
);
|
||||
|
||||
// One file bigger than the whole byte budget: it is still cached —
|
||||
// it is exactly the file this cache exists for — and it evicts
|
||||
// everything else rather than being refused.
|
||||
tree.write("huge.sv", &"// filler\n".repeat(MAX_VIEW_BYTES / 10 + 1));
|
||||
let huge = tree.path.join("huge.sv");
|
||||
let _ = ws.file_view(&huge).expect("readable");
|
||||
let views = ws.views.borrow();
|
||||
assert_eq!(views.len(), 1, "a file over the budget holds the cache alone");
|
||||
assert_eq!(views[0].path, huge);
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): the bound test above only ever caches *one* oversized
|
||||
/// file. The "newest is kept whatever it weighs" rule is only a bound —
|
||||
/// not a leak — if a *second* oversized file replaces the first rather
|
||||
/// than piling up beside it, which is the scenario the brief asks for by
|
||||
/// name.
|
||||
#[test]
|
||||
fn a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it() {
|
||||
let tree = Tree::new("viewhugehuge");
|
||||
let filler = "// filler\n".repeat(MAX_VIEW_BYTES / 10 + 1);
|
||||
tree.write("huge_a.sv", &filler);
|
||||
tree.write("huge_b.sv", &filler);
|
||||
let a = tree.path.join("huge_a.sv");
|
||||
let b = tree.path.join("huge_b.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let _ = ws.file_view(&a).expect("readable");
|
||||
assert_eq!(ws.views.borrow().len(), 1, "the first huge file holds the cache alone");
|
||||
let _ = ws.file_view(&b).expect("readable");
|
||||
let views = ws.views.borrow();
|
||||
assert_eq!(views.len(), 1, "the second huge file replaces it rather than growing beside it");
|
||||
assert_eq!(views[0].path, b, "the newest is what survives");
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): `update_one`'s doc comment and the README both say it
|
||||
/// drops *that path's* view and nothing else — the selectivity half of
|
||||
/// the invalidation story, which `every_way_a_files_text_can_move_drops_
|
||||
/// its_view` never exercises because it only ever warms one file's view
|
||||
/// at a time. A regression that widened `update_one` to `views.clear()`
|
||||
/// would still pass every existing test in this file.
|
||||
#[test]
|
||||
fn updating_one_file_leaves_another_files_cached_view_alone() {
|
||||
let tree = Tree::new("viewupdateoneselective");
|
||||
tree.write("a.sv", &versioned(1));
|
||||
tree.write("b.sv", &versioned(1));
|
||||
let a = tree.path.join("a.sv");
|
||||
let b = tree.path.join("b.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let view_a = ws.file_view(&a).expect("readable").text.clone();
|
||||
let view_b = ws.file_view(&b).expect("readable").text.clone();
|
||||
|
||||
tree.write("a.sv", &versioned(2));
|
||||
tree.write("b.sv", &versioned(2));
|
||||
assert!(ws.update_one(&a), "the index holds a.sv");
|
||||
|
||||
assert_ne!(ws.file_view(&a).expect("readable").text, view_a, "a.sv's view was dropped");
|
||||
assert_eq!(
|
||||
ws.file_view(&b).expect("readable").text,
|
||||
view_b,
|
||||
"b.sv's view must survive a.sv's update — update_one names one path, not the cache"
|
||||
);
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): `cached_view` moves a hit to the front so recency,
|
||||
/// not merely insertion order, decides what falls off — untested until
|
||||
/// now. Warm four files (the cap), touch the oldest again, then add a
|
||||
/// fifth: without the recency reorder the just-touched file would be the
|
||||
/// one to go (it was inserted first), and with it the file nobody has
|
||||
/// asked about since is what goes instead.
|
||||
#[test]
|
||||
fn re_hovering_the_oldest_cached_file_saves_it_from_eviction() {
|
||||
let tree = Tree::new("viewmru");
|
||||
let paths: Vec<PathBuf> = (0..MAX_VIEWS + 1)
|
||||
.map(|n| {
|
||||
tree.write(&format!("f{n}.sv"), &versioned(n + 1));
|
||||
tree.path.join(format!("f{n}.sv"))
|
||||
})
|
||||
.collect();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
// Fill the cache: f0 (oldest) through f3 (newest of the first batch).
|
||||
for path in &paths[..MAX_VIEWS] {
|
||||
let _ = ws.file_view(path).expect("readable");
|
||||
}
|
||||
// Touch the oldest again — it should now count as the most recent.
|
||||
let _ = ws.file_view(&paths[0]).expect("readable");
|
||||
// One more file arrives, forcing an eviction.
|
||||
let _ = ws.file_view(&paths[MAX_VIEWS]).expect("readable");
|
||||
|
||||
let paths_held: std::collections::HashSet<PathBuf> =
|
||||
ws.views.borrow().iter().map(|v| v.path.clone()).collect();
|
||||
assert!(
|
||||
paths_held.contains(&paths[0]),
|
||||
"the file re-hovered a moment ago must survive: {paths_held:?}"
|
||||
);
|
||||
assert!(
|
||||
!paths_held.contains(&paths[1]),
|
||||
"the file nobody has touched since must be what falls off instead: {paths_held:?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
//! The incremental scope widen (docs/features/index-scope): the tables a
|
||||
//! widen lands are the ones a whole rescan would have left, and it reads
|
||||
//! only the files the new folders brought in.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Everything a widen must leave equal to what a whole rescan leaves: the
|
||||
/// index, all three completion tables, and the include graph.
|
||||
///
|
||||
/// Rendered as strings so a failure names the table that moved rather than
|
||||
/// reporting that two opaque values differ.
|
||||
fn tables(ws: &Workspace) -> Vec<(&'static str, String)> {
|
||||
let units: Vec<String> = ws
|
||||
.candidates()
|
||||
.units("")
|
||||
.iter()
|
||||
.map(|c| format!("{} {:?} {}", c.name, c.kind, c.detail))
|
||||
.collect();
|
||||
let macros: Vec<String> =
|
||||
ws.candidates().macros("").iter().map(|m| format!("{} {}", m.name, m.detail)).collect();
|
||||
vec![
|
||||
("index", ws.index().fingerprint()),
|
||||
("words", format!("{:?}", ws.candidates().words(""))),
|
||||
("units", format!("{units:?}")),
|
||||
("macros", format!("{macros:?}")),
|
||||
("includes", ws.includes().fingerprint()),
|
||||
]
|
||||
}
|
||||
|
||||
fn same_tables(widened: &Workspace, rebuilt: &Workspace, what: &str) {
|
||||
for ((name, left), (_, right)) in tables(widened).into_iter().zip(tables(rebuilt)) {
|
||||
assert_eq!(left, right, "{what}: the {name} table a widen left is not a rebuild's");
|
||||
}
|
||||
}
|
||||
|
||||
/// The directories `open` added to the scope, and the widen that indexes
|
||||
/// them — the two-line spelling of what `server.rs`'s `didOpen` does.
|
||||
fn widen(ws: &mut Workspace, open: impl FnOnce(&mut Workspace)) -> Vec<PathBuf> {
|
||||
let before = ws.scope_dirs();
|
||||
open(ws);
|
||||
let after = ws.scope_dirs();
|
||||
let added: Vec<PathBuf> = after.iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
assert!(!added.is_empty(), "premise: this open widened the scope");
|
||||
ws.widen_index(&added);
|
||||
added
|
||||
}
|
||||
|
||||
/// A two-folder tree with an unsaved edit, a shared header included from
|
||||
/// both halves, and a name declared on each side.
|
||||
fn widen_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n wire a;\nendmodule\n");
|
||||
tree.write("rtl/defs.svh", "`define RTL_W 8\n");
|
||||
tree.package("rtl/rtl_pkg.sv", "rtl_pkg");
|
||||
tree.write("lib/sub.sv", "`include \"lib_defs.svh\"\nmodule sub;\nendmodule\n");
|
||||
tree.write("lib/lib_defs.svh", "`define LIB_W 16\n");
|
||||
tree.package("lib/lib_pkg.sv", "lib_pkg");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_leaves_the_tables_a_whole_rescan_would_have_left() {
|
||||
let tree = widen_tree("widenequal");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let sub = crate::uri::path_to_uri(&tree.path.join("lib/sub.sv")).expect("uri");
|
||||
// The hostile half: the buffer that is already open carries an edit
|
||||
// that is on no disk anywhere when the widen runs. A widen that
|
||||
// indexed only the new folder's files would lose `NEVER_SAVED`, which
|
||||
// is the objection that stopped this shape being taken in round 19.
|
||||
let edited = "module top;\n wire never_saved;\n localparam NEVER_SAVED = 1;\nendmodule\n";
|
||||
let sub_text = fs::read_to_string(tree.path.join("lib/sub.sv")).expect("read");
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
own_folder_only(&mut incremental);
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(top.clone(), edited.to_string());
|
||||
incremental.rebuild_index();
|
||||
assert_eq!(incremental.index().files().len(), 3, "premise: the rtl folder alone");
|
||||
widen(&mut incremental, |ws| ws.set_document(sub.clone(), sub_text.clone()));
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
own_folder_only(&mut rebuilt);
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(top.clone(), edited.to_string());
|
||||
rebuilt.set_document(sub.clone(), sub_text.clone());
|
||||
rebuilt.rebuild_index();
|
||||
|
||||
assert_eq!(rebuilt.index().files().len(), 6, "premise: both folders");
|
||||
assert_eq!(
|
||||
incremental.candidates().words("never_sav"),
|
||||
["NEVER_SAVED", "never_saved"],
|
||||
"the unsaved edit is in the widened tables"
|
||||
);
|
||||
same_tables(&incremental, &rebuilt, "an unsaved edit across a widen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_reads_only_the_files_the_new_folders_brought_in() {
|
||||
let tree = widen_tree("widenwork");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let sub_path = tree.path.join("lib/sub.sv");
|
||||
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
|
||||
let sub_text = fs::read_to_string(&sub_path).expect("read");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.set_document(top.clone(), fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r"));
|
||||
ws.rebuild_index();
|
||||
|
||||
let mut seen = Scan::default();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
let before = ws.scope_dirs();
|
||||
ws.set_document(sub.clone(), sub_text);
|
||||
let after = ws.scope_dirs();
|
||||
let added: Vec<PathBuf> =
|
||||
after.iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
ws.widen_index_with(&added, &mut see);
|
||||
}
|
||||
seen.parsed.sort();
|
||||
// The three `rtl/` files are already indexed and are not read again;
|
||||
// the open buffer is refreshed from the analysis it holds, which is
|
||||
// what makes an unsaved edit survive the widen.
|
||||
assert_eq!(seen.parsed, ["lib_defs.svh", "lib_pkg.sv"], "{seen:?}");
|
||||
seen.analyzed.sort();
|
||||
// Both open buffers, not only the newly opened one: every buffer's
|
||||
// held analysis is refreshed, which is what carries an unsaved edit
|
||||
// across a widen.
|
||||
assert_eq!(seen.analyzed, ["sub.sv", "top.sv"], "{seen:?}");
|
||||
assert!(seen.cached.is_empty(), "no cache in this test: {seen:?}");
|
||||
assert!(!seen.parsed.contains(&"top.sv".to_string()), "the old folder is untouched");
|
||||
assert_eq!(ws.index().files().len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_bar_counts_the_new_files_and_not_the_whole_scope() {
|
||||
let tree = widen_tree("widenbar");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let sub_path = tree.path.join("lib/sub.sv");
|
||||
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
|
||||
let sub_text = fs::read_to_string(&sub_path).expect("read");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.set_document(top, fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r"));
|
||||
ws.rebuild_index();
|
||||
|
||||
let mut totals: Vec<usize> = Vec::new();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { total, .. }
|
||||
| IndexEvent::Cached { total, .. }
|
||||
| IndexEvent::Analyzed { total, .. } => totals.push(total),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
let before = ws.scope_dirs();
|
||||
ws.set_document(sub, sub_text);
|
||||
let added: Vec<PathBuf> =
|
||||
ws.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
ws.widen_index_with(&added, &mut see);
|
||||
}
|
||||
// Two new files plus the two open buffers refreshed — never the six
|
||||
// the scope now holds. A bar that counted the whole scope would crawl.
|
||||
assert_eq!(totals, [4, 4, 4, 4], "the denominator is the widen's own work list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_into_a_folder_that_contains_the_old_one_indexes_each_file_once() {
|
||||
// A file present in both the old scope portion and the new one: the
|
||||
// added directory is the *parent* of the directory already in scope,
|
||||
// so its walk finds everything the first scan already indexed.
|
||||
let tree = Tree::new("widennested");
|
||||
tree.package("rtl/deep/a.sv", "a_pkg");
|
||||
tree.package("rtl/b.sv", "b_pkg");
|
||||
let deep = crate::uri::path_to_uri(&tree.path.join("rtl/deep/a.sv")).expect("uri");
|
||||
let shallow = crate::uri::path_to_uri(&tree.path.join("rtl/b.sv")).expect("uri");
|
||||
let deep_text = fs::read_to_string(tree.path.join("rtl/deep/a.sv")).expect("read");
|
||||
let shallow_text = fs::read_to_string(tree.path.join("rtl/b.sv")).expect("read");
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
own_folder_only(&mut incremental);
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(deep.clone(), deep_text.clone());
|
||||
incremental.rebuild_index();
|
||||
assert_eq!(incremental.index().files().len(), 1, "premise: rtl/deep alone");
|
||||
|
||||
let mut seen = Scan::default();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
let before = incremental.scope_dirs();
|
||||
incremental.set_document(shallow.clone(), shallow_text.clone());
|
||||
let added: Vec<PathBuf> =
|
||||
incremental.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
incremental.widen_index_with(&added, &mut see);
|
||||
}
|
||||
assert!(seen.parsed.is_empty(), "both files speak for themselves: {seen:?}");
|
||||
seen.analyzed.sort();
|
||||
assert_eq!(seen.analyzed, ["a.sv", "b.sv"], "{seen:?}");
|
||||
assert_eq!(incremental.index().files().len(), 2, "a.sv is indexed once, not twice");
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
own_folder_only(&mut rebuilt);
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(deep, deep_text);
|
||||
rebuilt.set_document(shallow, shallow_text);
|
||||
rebuilt.rebuild_index();
|
||||
same_tables(&incremental, &rebuilt, "a widen into a containing folder");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds() {
|
||||
// opentitan's own shape, and the jump `performance_take2.md` §5b
|
||||
// measured: at the shipped `scopeDepth: 2`, `ip/aes/dv/tb` raises to
|
||||
// `ip/aes`, and the very next file — `ip/aes/rtl/aes.sv` — raises to
|
||||
// `ip`, the *parent* of the directory already in scope. The new scope's
|
||||
// file set is a superset of the old one, so the widen owes the other
|
||||
// blocks and nothing else: `ip/aes`'s own already-indexed files are
|
||||
// never re-read, and the diff that says so is by **file against the
|
||||
// index**, not by folder against the old walk.
|
||||
let tree = Tree::new("widensubsume");
|
||||
tree.package("ip/aes/rtl/aes.sv", "aes_pkg");
|
||||
tree.package("ip/aes/rtl/aes_core.sv", "aes_core_pkg");
|
||||
tree.package("ip/aes/dv/tb/tb.sv", "aes_tb_pkg");
|
||||
tree.package("ip/aes/dv/env/aes_env.sv", "aes_env_pkg");
|
||||
tree.package("ip/kmac/rtl/kmac.sv", "kmac_pkg");
|
||||
tree.package("ip/hmac/rtl/hmac.sv", "hmac_pkg");
|
||||
// Over the cap: not indexed before the widen, so it must not count as
|
||||
// "already there" — it is walked again, skipped again, and reported.
|
||||
tree.write(
|
||||
"ip/kmac/rtl/huge.sv",
|
||||
&format!("package huge_pkg;\n{}endpackage\n", " // pad\n".repeat(200)),
|
||||
);
|
||||
|
||||
let aes = crate::uri::path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri");
|
||||
let tb = crate::uri::path_to_uri(&tree.path.join("ip/aes/dv/tb/tb.sv")).expect("uri");
|
||||
let aes_text = fs::read_to_string(tree.path.join("ip/aes/rtl/aes.sv")).expect("read");
|
||||
// An unsaved edit in a buffer that is *not* the one being opened: what
|
||||
// makes the equivalence below a real claim rather than a coincidence.
|
||||
let edited_tb =
|
||||
"package aes_tb_pkg;\n localparam K = 1;\n localparam UNSAVED = 2;\nendpackage\n";
|
||||
let settings =
|
||||
ClientSettings { index_scope_depth: 2, max_file_size: 512, ..Default::default() };
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
incremental.set_client_settings(settings.clone());
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(tb.clone(), edited_tb.into());
|
||||
incremental.rebuild_index();
|
||||
assert_eq!(
|
||||
incremental.scope_dirs(),
|
||||
[tree.path.join("ip/aes")],
|
||||
"premise: the testbench raises two levels to its own block"
|
||||
);
|
||||
assert_eq!(incremental.index().files().len(), 4, "premise: the block's four files");
|
||||
|
||||
let mut seen = Scan::default();
|
||||
let mut totals: Vec<usize> = Vec::new();
|
||||
let mut skipped: Vec<String> = Vec::new();
|
||||
let added = {
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, total, .. } => {
|
||||
seen.parsed.push(file_name(path));
|
||||
totals.push(total);
|
||||
}
|
||||
IndexEvent::Cached { path, total, .. } => {
|
||||
seen.cached.push(file_name(path));
|
||||
totals.push(total);
|
||||
}
|
||||
IndexEvent::Analyzed { path, total, .. } => {
|
||||
seen.analyzed.push(file_name(path));
|
||||
totals.push(total);
|
||||
}
|
||||
IndexEvent::Skipped { path, .. } => skipped.push(file_name(path)),
|
||||
};
|
||||
let before = incremental.scope_dirs();
|
||||
incremental.set_document(aes.clone(), aes_text.clone());
|
||||
let added: Vec<PathBuf> =
|
||||
incremental.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
incremental.widen_index_with(&added, &mut see);
|
||||
added
|
||||
};
|
||||
assert_eq!(added, [tree.path.join("ip")], "the added directory contains the old scope");
|
||||
seen.parsed.sort();
|
||||
// The two other blocks, and not one file of `ip/aes` — those the index
|
||||
// already holds, and holding them is what the file diff is for.
|
||||
assert_eq!(seen.parsed, ["hmac.sv", "kmac.sv"], "{seen:?}");
|
||||
seen.analyzed.sort();
|
||||
assert_eq!(seen.analyzed, ["aes.sv", "tb.sv"], "both buffers refresh: {seen:?}");
|
||||
assert_eq!(skipped, ["huge.sv"], "the capped file is walked and skipped again");
|
||||
assert_eq!(totals, [4, 4, 4, 4], "the bar counts the two new files and the two buffers");
|
||||
assert_eq!(incremental.index().files().len(), 6, "four held plus two new, never the cap's");
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
rebuilt.set_client_settings(settings);
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(tb, edited_tb.into());
|
||||
rebuilt.set_document(aes, aes_text);
|
||||
rebuilt.rebuild_index();
|
||||
assert_eq!(rebuilt.index().files().len(), 6, "premise: the same six files");
|
||||
same_tables(&incremental, &rebuilt, "a widen that subsumed the old scope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_lends_a_new_files_spelling_to_an_include_resolved_before_it() {
|
||||
// The include graph's own hostile case, and the reason this round
|
||||
// holds each edge as the filesystem answered it: `rtl/top.sv` was
|
||||
// indexed while `lib/` was out of scope, so its `` `include`` into
|
||||
// `lib/` could not be spelled the way the index spells that file. The
|
||||
// widen must re-spell it without re-reading `rtl/top.sv`.
|
||||
let tree = Tree::new("widenspell");
|
||||
tree.write("lib/Shared.svh", "`define SHARED 1\n");
|
||||
// The include is written in the other case, which a case-insensitive
|
||||
// filesystem happily opens; on a case-sensitive one it does not
|
||||
// resolve at all, and both workspaces agree on that too.
|
||||
tree.write("rtl/top.sv", "`include \"../lib/shared.svh\"\nmodule top;\nendmodule\n");
|
||||
tree.package("lib/lib_pkg.sv", "lib_pkg");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let lib = crate::uri::path_to_uri(&tree.path.join("lib/lib_pkg.sv")).expect("uri");
|
||||
let top_text = fs::read_to_string(tree.path.join("rtl/top.sv")).expect("read");
|
||||
let lib_text = fs::read_to_string(tree.path.join("lib/lib_pkg.sv")).expect("read");
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
own_folder_only(&mut incremental);
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(top.clone(), top_text.clone());
|
||||
incremental.rebuild_index();
|
||||
widen(&mut incremental, |ws| ws.set_document(lib.clone(), lib_text.clone()));
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
own_folder_only(&mut rebuilt);
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(top, top_text);
|
||||
rebuilt.set_document(lib, lib_text);
|
||||
rebuilt.rebuild_index();
|
||||
same_tables(&incremental, &rebuilt, "an include spelled by a file the widen brought in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_grown_past_the_threshold_leaves_the_index_when_the_scope_widens() {
|
||||
// The one thing a widen takes *out*: a buffer on the large-file fast
|
||||
// path contributes nothing, exactly as `collect_sources` says, so a
|
||||
// file the index holds whose buffer has grown past the threshold is
|
||||
// dropped — the same answer a whole rescan gives.
|
||||
let tree = Tree::new("widenlarge");
|
||||
tree.package("rtl/p.sv", "p_pkg");
|
||||
tree.package("lib/q.sv", "q_pkg");
|
||||
let small = crate::uri::path_to_uri(&tree.path.join("rtl/p.sv")).expect("uri");
|
||||
let other = crate::uri::path_to_uri(&tree.path.join("lib/q.sv")).expect("uri");
|
||||
let other_text = fs::read_to_string(tree.path.join("lib/q.sv")).expect("read");
|
||||
let huge = filler(1_000);
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
incremental.set_client_settings(ClientSettings {
|
||||
large_file_threshold: 200,
|
||||
index_scope_depth: 0,
|
||||
..Default::default()
|
||||
});
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(small.clone(), "package p_pkg;\nendpackage\n".into());
|
||||
incremental.rebuild_index();
|
||||
assert_eq!(incremental.index().files().len(), 1, "premise: rtl/p.sv is indexed");
|
||||
incremental.set_document(small.clone(), huge.clone());
|
||||
assert!(incremental.document(&small).expect("open").large, "premise: the fast path");
|
||||
widen(&mut incremental, |ws| ws.set_document(other.clone(), other_text.clone()));
|
||||
assert_eq!(
|
||||
incremental.index().files().len(),
|
||||
1,
|
||||
"the grown buffer left as the new folder arrived"
|
||||
);
|
||||
assert!(incremental.index().units("p_pkg").is_empty(), "and its names went with it");
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
rebuilt.set_client_settings(ClientSettings {
|
||||
large_file_threshold: 200,
|
||||
index_scope_depth: 0,
|
||||
..Default::default()
|
||||
});
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(small, huge);
|
||||
rebuilt.set_document(other, other_text);
|
||||
rebuilt.rebuild_index();
|
||||
same_tables(&incremental, &rebuilt, "a buffer over the threshold at widen time");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_persistent_cache_answers_for_the_files_a_widen_brings_in() {
|
||||
let tree = widen_tree("widencache");
|
||||
let store = Tree::new("widencache_store");
|
||||
let sub_path = tree.path.join("lib/sub.sv");
|
||||
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
|
||||
let sub_text = fs::read_to_string(&sub_path).expect("read");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let top_text = fs::read_to_string(tree.path.join("rtl/top.sv")).expect("read");
|
||||
|
||||
// A first session fills the store with every file of both folders.
|
||||
let mut first = Workspace::default();
|
||||
first.set_client_settings(wide(caching(&store.path)));
|
||||
first.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(first.index().files().len(), 6, "premise: the store is filled");
|
||||
|
||||
// A second session, folder-scoped, widens into `lib/`: the files it
|
||||
// brings in come from the store rather than from a parse.
|
||||
let mut second = Workspace::default();
|
||||
second.set_client_settings(caching(&store.path));
|
||||
second.open_roots(vec![tree.path.clone()]);
|
||||
second.set_document(top, top_text);
|
||||
second.rebuild_index();
|
||||
|
||||
let mut seen = Scan::default();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
let before = second.scope_dirs();
|
||||
second.set_document(sub, sub_text);
|
||||
let added: Vec<PathBuf> =
|
||||
second.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
second.widen_index_with(&added, &mut see);
|
||||
}
|
||||
seen.cached.sort();
|
||||
assert_eq!(seen.cached, ["lib_defs.svh", "lib_pkg.sv"], "from the store: {seen:?}");
|
||||
assert!(seen.parsed.is_empty(), "nothing was parsed twice: {seen:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_that_adds_nothing_new_still_refreshes_the_open_buffers() {
|
||||
// A widen whose added directory holds no file the index lacks — the
|
||||
// degenerate case, and the one where the open-buffer refresh is the
|
||||
// *whole* of the work. It must still land the buffers' current text.
|
||||
let tree = Tree::new("widenempty");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
fs::create_dir_all(tree.path.join("empty")).expect("dir");
|
||||
let a = crate::uri::path_to_uri(&tree.path.join("rtl/a.sv")).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.set_document(a.clone(), "package a_pkg;\n localparam K = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
ws.set_document(a, "package a_pkg;\n localparam EDITED = 1;\nendpackage\n".into());
|
||||
|
||||
ws.widen_index(from_ref(&tree.path.join("empty")));
|
||||
assert_eq!(ws.index().member("a_pkg", "EDITED").len(), 1, "the live edit is indexed");
|
||||
assert_eq!(ws.index().member("a_pkg", "K").len(), 0);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The closed-file view cache: the last few files an answer needed the
|
||||
//! text of, held with their line index so that answering twice about one
|
||||
//! file reads it once — and every rule that drops an entry.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use super::Workspace;
|
||||
|
||||
/// One **closed** workspace file's text and the line index over it, held by
|
||||
/// [`Workspace`] just long enough that answering twice about the same file
|
||||
/// reads it once.
|
||||
///
|
||||
/// Only closed files: an open buffer's own `Document` is the authority on its
|
||||
/// text, and caching a second copy of it would be a way for the two to
|
||||
/// disagree.
|
||||
pub struct FileView {
|
||||
/// The file this view was read from.
|
||||
pub path: PathBuf,
|
||||
/// Its text, as it was on disk when the view was made.
|
||||
pub text: String,
|
||||
/// The line index over exactly that text.
|
||||
pub lines: LineIndex,
|
||||
}
|
||||
|
||||
/// How many closed files the view cache holds, and how much text they may add
|
||||
/// up to.
|
||||
///
|
||||
/// Two bounds, because they answer two different questions. `MAX_VIEWS` is how
|
||||
/// many files one answer can name — a hover card names one or two, a
|
||||
/// references list walks a handful before it moves on — and four is a handful.
|
||||
/// `MAX_VIEW_BYTES` is the memory question, and it exists because the file
|
||||
/// this cache is *for* can be tens of megabytes on its own: without it, four
|
||||
/// netlists would be half a gigabyte of server. The newest view is kept
|
||||
/// whatever it weighs, so a single huge file simply evicts everything else
|
||||
/// rather than refusing to be cached at all.
|
||||
pub(super) const MAX_VIEWS: usize = 4;
|
||||
pub(super) const MAX_VIEW_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
impl Workspace {
|
||||
/// One **closed** file's text and line index, read at most once per file
|
||||
/// per generation of that file.
|
||||
///
|
||||
/// `None` for a file that cannot be read, and — deliberately — for one an
|
||||
/// open buffer speaks for: that buffer's `Document` already holds both,
|
||||
/// and a second copy here would be a second opinion. Callers that want
|
||||
/// "whichever text is authoritative" ask `document_for_path` first, as
|
||||
/// `locate` does.
|
||||
///
|
||||
/// **A cache, never a correctness input.** Every entry is dropped the
|
||||
/// moment anything could have moved the file's text under it, and there
|
||||
/// are exactly four such moments:
|
||||
///
|
||||
/// * [`Workspace::set_document`] — a `didOpen`/`didChange`/`didSave` for
|
||||
/// that path; the buffer becomes the authority and the disk copy is no
|
||||
/// longer what a reader wants;
|
||||
/// * [`Workspace::close_document`] — the buffer stops being the authority,
|
||||
/// and whatever was cached for that path predates the edits it may have
|
||||
/// saved;
|
||||
/// * [`Workspace::update_one`] — one file re-indexed, which is exactly the
|
||||
/// claim that its bytes changed;
|
||||
/// * [`Workspace::rebuild_index_with`] — a whole rescan, which claims
|
||||
/// nothing about *which* file moved, so the whole cache goes;
|
||||
/// * [`Workspace::begin_widen`] — a scope widen, which *does* name the
|
||||
/// files it is about to read, so it drops those and leaves the rest.
|
||||
///
|
||||
/// What survives all four is a file changed on disk with nothing telling
|
||||
/// this server so — and there the index's own spans are stale by the same
|
||||
/// event, which is what `hover`'s `spells_exactly` guard exists for: a
|
||||
/// stale view can only ever *omit* a snippet, never show a wrong line.
|
||||
pub fn file_view(&self, path: &Path) -> Option<Rc<FileView>> {
|
||||
if self.document_for_path(path).is_some() {
|
||||
return None;
|
||||
}
|
||||
if let Some(hit) = self.cached_view(path) {
|
||||
return Some(hit);
|
||||
}
|
||||
let text = fs::read_to_string(path).ok()?;
|
||||
let view =
|
||||
Rc::new(FileView { path: path.to_path_buf(), lines: LineIndex::new(&text), text });
|
||||
let mut views = self.views.borrow_mut();
|
||||
views.insert(0, Rc::clone(&view));
|
||||
trim_views(&mut views);
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// The files the view cache is holding, newest first.
|
||||
///
|
||||
/// Test-only, and it exists for one question: whether an answer read a
|
||||
/// file at all. A `Location` computed from the index alone must leave this
|
||||
/// empty, which is the whole point of `locate::definition_location` — see
|
||||
/// `docs/features/lazy-code-action/README.md`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn held_views(&self) -> Vec<PathBuf> {
|
||||
self.views.borrow().iter().map(|view| view.path.clone()).collect()
|
||||
}
|
||||
|
||||
/// The held view for `path`, moved to the front so the bounds below drop
|
||||
/// whatever has gone longest unused.
|
||||
fn cached_view(&self, path: &Path) -> Option<Rc<FileView>> {
|
||||
let mut views = self.views.borrow_mut();
|
||||
let at = views.iter().position(|view| view.path == path)?;
|
||||
views[..=at].rotate_right(1);
|
||||
views.first().cloned()
|
||||
}
|
||||
|
||||
/// Drop whatever is held for one file. Called wherever that file's text
|
||||
/// may have moved; see [`Workspace::file_view`] for the list.
|
||||
pub(super) fn forget_view(&mut self, path: &Path) {
|
||||
self.views.borrow_mut().retain(|view| view.path != path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Cut the view cache back to its two bounds, newest first.
|
||||
///
|
||||
/// The newest view is kept whatever it weighs: one netlist-shaped file can
|
||||
/// exceed the whole byte budget on its own, and a cache that refused to hold
|
||||
/// it would be useless for exactly the file it exists for.
|
||||
fn trim_views(views: &mut Vec<Rc<FileView>>) {
|
||||
let mut bytes = 0usize;
|
||||
let mut kept = 0usize;
|
||||
for view in views.iter() {
|
||||
bytes += view.text.len();
|
||||
if kept == MAX_VIEWS || (kept > 0 && bytes > MAX_VIEW_BYTES) {
|
||||
break;
|
||||
}
|
||||
kept += 1;
|
||||
}
|
||||
views.truncate(kept);
|
||||
}
|
||||
@@ -18,13 +18,31 @@ use crate::convert::Positions;
|
||||
///
|
||||
/// A change with no range replaces the whole document — what a full-sync
|
||||
/// client sends, and what still works if one arrives mid-batch.
|
||||
///
|
||||
/// `#[cfg(test)]` since the server reads where the edit ended too
|
||||
/// ([`apply_changes_at`]); the tests, and the cross-check against the
|
||||
/// reference implementation, come in by this door.
|
||||
#[cfg(test)]
|
||||
pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
|
||||
apply_changes_at(text, changes).0
|
||||
}
|
||||
|
||||
/// `apply_changes`, and where the last change ended in the text that
|
||||
/// results: the byte offset just past what it inserted. `None` when the last
|
||||
/// change replaced the whole document — that says nothing about where anyone
|
||||
/// is typing (`docs/features/port-entry-grace/README.md`).
|
||||
pub fn apply_changes_at(
|
||||
text: &str,
|
||||
changes: &[TextDocumentContentChangeEvent],
|
||||
) -> (String, Option<u32>) {
|
||||
let mut text = text.to_string();
|
||||
let mut edit_end = None;
|
||||
for change in changes {
|
||||
let Some(range) = change.range else {
|
||||
// The whole document. This also resets the state that the ranges
|
||||
// after it in the same batch are positioned against.
|
||||
text.clone_from(&change.text);
|
||||
edit_end = None;
|
||||
continue;
|
||||
};
|
||||
// A fresh line table per change: each range is positioned against the
|
||||
@@ -46,8 +64,9 @@ pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) ->
|
||||
continue;
|
||||
};
|
||||
text = format!("{before}{}{after}", change.text);
|
||||
edit_end = u32::try_from(start + change.text.len()).ok();
|
||||
}
|
||||
text
|
||||
(text, edit_end)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -84,6 +103,31 @@ mod tests {
|
||||
assert_eq!(after, "module m;\n wire ab;\nendmodule\n");
|
||||
}
|
||||
|
||||
/// Where the last change ended is the offset just past what it inserted,
|
||||
/// in the text that results — the cursor's place after typing it.
|
||||
#[test]
|
||||
fn the_edit_end_is_just_past_the_inserted_text() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let (after, end) = apply_changes_at(text, &[edit((1, 8), (1, 8), "bc")]);
|
||||
assert_eq!(after, "module m;\n wire abc;\nendmodule\n");
|
||||
assert_eq!(end, Some(20), "just past the `bc`");
|
||||
assert_eq!(&after[..20], "module m;\n wire abc");
|
||||
let (_, end) = apply_changes_at(text, &[edit((1, 7), (1, 8), "")]);
|
||||
assert_eq!(end, Some(17), "a delete ends where it started");
|
||||
}
|
||||
|
||||
/// The last change of a batch decides, and a rangeless one — a whole
|
||||
/// document — says nothing about where anyone is typing.
|
||||
#[test]
|
||||
fn the_edit_end_follows_the_last_change_and_a_whole_document_has_none() {
|
||||
let text = "module m;\nendmodule\n";
|
||||
let (_, end) = apply_changes_at(text, &[edit((0, 0), (0, 0), "x"), whole("module n;\n")]);
|
||||
assert_eq!(end, None);
|
||||
let (_, end) = apply_changes_at(text, &[whole("module n;\n"), edit((0, 9), (0, 9), "\n")]);
|
||||
assert_eq!(end, Some(10));
|
||||
assert_eq!(apply_changes_at(text, &[]), (text.to_string(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_removes_exactly_the_range() {
|
||||
let text = "module m;\n wire aaa;\nendmodule\n";
|
||||
|
||||
@@ -115,6 +115,11 @@ impl Template {
|
||||
}
|
||||
|
||||
/// Every template offered in `dialect`, the shared ones first.
|
||||
///
|
||||
/// The order is the popup's order among templates: the tier writes each one's
|
||||
/// position here into its `sortText` (`completion-ux`, 2026-11-17), so two
|
||||
/// templates reached by the same prefix show in registry order rather than by
|
||||
/// label.
|
||||
pub fn for_dialect(dialect: Dialect) -> impl Iterator<Item = &'static Template> {
|
||||
let dialect_only = match dialect {
|
||||
Dialect::SystemVerilog => SYSTEMVERILOG,
|
||||
@@ -198,13 +203,8 @@ const SYSTEMVERILOG: &[Template] = &[
|
||||
detail: "for loop with a local loop variable",
|
||||
body: &[(0, "for (int ${1:i} = 0; $1 < ${2:N}; $1++) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always_ff @(posedge clk)",
|
||||
prefix: "always_ff",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always_ff @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
// With-reset before clock-only (TODO §68.1): a flop with an async reset is
|
||||
// the commoner one to write, and the registry order is the popup order.
|
||||
Template {
|
||||
label: "always_ff with reset",
|
||||
prefix: "always_ff",
|
||||
@@ -220,6 +220,13 @@ const SYSTEMVERILOG: &[Template] = &[
|
||||
(0, "end"),
|
||||
],
|
||||
},
|
||||
Template {
|
||||
label: "always_ff @(posedge clk)",
|
||||
prefix: "always_ff",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always_ff @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always_comb begin/end",
|
||||
prefix: "always_comb",
|
||||
@@ -267,13 +274,7 @@ const VERILOG: &[Template] = &[
|
||||
detail: "for loop over an existing variable",
|
||||
body: &[(0, "for (${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always @(posedge clk)",
|
||||
prefix: "always",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
// With-reset first, as in the SystemVerilog list above.
|
||||
Template {
|
||||
label: "always @(posedge clk or negedge rst_n)",
|
||||
prefix: "always",
|
||||
@@ -289,6 +290,13 @@ const VERILOG: &[Template] = &[
|
||||
(0, "end"),
|
||||
],
|
||||
},
|
||||
Template {
|
||||
label: "always @(posedge clk)",
|
||||
prefix: "always",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always @(*)",
|
||||
prefix: "always",
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
//! `textDocument/semanticTokens/full`, `/range` and `/full/delta`.
|
||||
//!
|
||||
//! Classification comes from the lexer's token stream, refined for plain
|
||||
//! identifiers by `vlog_semantic`. The full mapping table is in
|
||||
//! `docs/features/lucisv-server/README.md`; the range and delta rules are in
|
||||
//! `docs/features/semantic-tokens-delta/README.md`.
|
||||
//! identifiers by `vlog_semantic` + `ExternalResolutions` and for module
|
||||
//! instantiations / `#(...)` parameter lists by `Document.tree`
|
||||
//! (`docs/features/instantiation-highlighting/README.md`). The full mapping
|
||||
//! table is in `docs/features/lucisv-server/README.md`; the range and delta
|
||||
//! rules are in `docs/features/semantic-tokens-delta/README.md`.
|
||||
//!
|
||||
//! One tokenizer and one encoder serve all three requests: classification
|
||||
//! produces [`Absolute`] tokens (line, column, length — the coordinates the
|
||||
//! protocol thinks in), a range answer drops the ones it does not want, and
|
||||
//! `encode` delta-encodes whatever is left from the start of the document.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use lsp_types::{
|
||||
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind};
|
||||
use vlog_semantic::{Definition, ExternalResolutions, Semantics, SymbolKind};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
mod instantiation;
|
||||
|
||||
/// The legend the server advertises. The index into this array is what the
|
||||
/// wire format carries, so the order is part of the protocol contract and
|
||||
/// must match [`Highlight`].
|
||||
@@ -133,6 +139,7 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
|
||||
/// See `docs/features/large-file-mode/README.md`.
|
||||
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
let window = crate::large::window(doc, range);
|
||||
let overrides = HashMap::new();
|
||||
let mut pieces = Vec::new();
|
||||
// The comment spans the lexer never saw go in first; `flatten` sorts, so
|
||||
// the order they are collected in cannot reach the wire.
|
||||
@@ -140,16 +147,17 @@ pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticTo
|
||||
pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
for token in &window.tokens {
|
||||
collect(token, &doc.semantics, &mut pieces);
|
||||
collect(token, doc, &overrides, &mut pieces);
|
||||
}
|
||||
encode(&within(flatten(pieces, doc), range))
|
||||
}
|
||||
|
||||
/// Classify the whole buffer, split at line boundaries, in wire order.
|
||||
fn absolute(doc: &Document) -> Vec<Absolute> {
|
||||
let overrides = instantiation::overrides(doc);
|
||||
let mut pieces = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
collect(token, &doc.semantics, &mut pieces);
|
||||
collect(token, doc, &overrides, &mut pieces);
|
||||
}
|
||||
flatten(pieces, doc)
|
||||
}
|
||||
@@ -177,12 +185,17 @@ fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
|
||||
/// after it on the same line — because [`flatten`] converts the offsets with a
|
||||
/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts,
|
||||
/// and no two pieces here can start at the same byte.
|
||||
fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
|
||||
fn collect(
|
||||
token: &Token,
|
||||
doc: &Document,
|
||||
overrides: &HashMap<u32, Highlight>,
|
||||
out: &mut Vec<Piece>,
|
||||
) {
|
||||
for comment in &token.leading {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
if let Some(ty) = classify(token, semantics) {
|
||||
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) });
|
||||
if let Some(ty) = classify(token, doc, overrides) {
|
||||
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, &doc.semantics) });
|
||||
}
|
||||
if let Some(comment) = &token.trailing {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
@@ -190,7 +203,14 @@ fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
|
||||
}
|
||||
|
||||
/// What a token is, or `None` for the ones this server does not colour.
|
||||
fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
|
||||
fn classify(
|
||||
token: &Token,
|
||||
doc: &Document,
|
||||
overrides: &HashMap<u32, Highlight>,
|
||||
) -> Option<Highlight> {
|
||||
if let Some(&ty) = overrides.get(&token.span.start) {
|
||||
return Some(ty);
|
||||
}
|
||||
match token.kind {
|
||||
TokenKind::Keyword => Some(Highlight::Keyword),
|
||||
TokenKind::Number => Some(Highlight::Number),
|
||||
@@ -201,8 +221,8 @@ fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
|
||||
// A macro *usage* lexes as an identifier whose text starts with a
|
||||
// backtick; `is_macro` is the lexer's own public test for it.
|
||||
TokenKind::Ident if token.is_macro() => Some(Highlight::Macro),
|
||||
TokenKind::Ident => Some(identifier_type(token.span.start, semantics)),
|
||||
// Punctuation: deliberately not emitted, see the feature README.
|
||||
TokenKind::Ident => Some(identifier_type(token.span.start, &doc.semantics, &doc.external)),
|
||||
// Punctuation outside `overrides`: deliberately not emitted, see the feature README.
|
||||
TokenKind::Symbol | TokenKind::Eof => None,
|
||||
}
|
||||
}
|
||||
@@ -219,16 +239,28 @@ fn modifiers(token: &Token, semantics: &Semantics) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain identifier, classified through the symbol table: its own
|
||||
/// declaration, the declaration it resolves to, or `variable` when nothing in
|
||||
/// this file knows (an external candidate, or a name a macro would produce).
|
||||
fn identifier_type(offset: u32, semantics: &Semantics) -> Highlight {
|
||||
let symbol = semantics
|
||||
.symbol_at(offset)
|
||||
.or_else(|| semantics.reference_at(offset).and_then(|r| r.resolved()))
|
||||
.and_then(|id| semantics.symbol(id));
|
||||
match symbol {
|
||||
Some(symbol) => symbol_type(symbol.kind),
|
||||
/// What symbol kind `offset` resolves to across the file and workspace overlay.
|
||||
fn resolved_kind(
|
||||
offset: u32,
|
||||
semantics: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
) -> Option<SymbolKind> {
|
||||
match external.definition_of(semantics, offset)? {
|
||||
Definition::Local(symbol) => Some(symbol.kind),
|
||||
Definition::External(defs) => defs.first().map(|def| def.kind),
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain identifier, classified through the symbol table and workspace
|
||||
/// overlay: its own declaration, the declaration it resolves to, or `variable`
|
||||
/// when nothing resolves it.
|
||||
fn identifier_type(
|
||||
offset: u32,
|
||||
semantics: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
) -> Highlight {
|
||||
match resolved_kind(offset, semantics, external) {
|
||||
Some(kind) => symbol_type(kind),
|
||||
None => Highlight::Variable,
|
||||
}
|
||||
}
|
||||
@@ -248,7 +280,7 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
SymbolKind::Typedef => Highlight::Type,
|
||||
SymbolKind::EnumVariant => Highlight::EnumMember,
|
||||
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => Highlight::Parameter,
|
||||
SymbolKind::Function | SymbolKind::Task => Highlight::Function,
|
||||
SymbolKind::Function | SymbolKind::Task | SymbolKind::Instance => Highlight::Function,
|
||||
SymbolKind::StructMember
|
||||
| SymbolKind::Constraint
|
||||
| SymbolKind::Coverpoint
|
||||
@@ -260,7 +292,6 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
| SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::Instance
|
||||
| SymbolKind::Clocking
|
||||
| SymbolKind::Block => Highlight::Variable,
|
||||
// A property and a sequence are named, instantiated by name and take
|
||||
@@ -728,9 +759,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoded tokens with the identifier refinement folded away.
|
||||
fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
|
||||
decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect()
|
||||
/// Decoded tokens with identifier refinement and AST-only punctuation
|
||||
/// (`#`, `.`, `*`) folded away so the unparsed window lexer can be compared
|
||||
/// against the full pipeline.
|
||||
fn coarsely(full: &Document, data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
|
||||
let positions = full.positions();
|
||||
decode(data)
|
||||
.into_iter()
|
||||
.filter(|&(line, character, ..)| {
|
||||
let at = positions.offset(Position { line, character });
|
||||
!full.token_at(at).is_some_and(|t| t.kind == TokenKind::Symbol)
|
||||
})
|
||||
.map(|(l, c, len, ty, _)| (l, c, len, coarse(ty)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether any construct in `doc` crosses `offset` — a block comment, a
|
||||
@@ -792,8 +833,8 @@ mod tests {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(
|
||||
coarsely(&semantic_tokens_in_window(&fast, window)),
|
||||
coarsely(&semantic_tokens_in_range(&full, window)),
|
||||
coarsely(&full, &semantic_tokens_in_window(&fast, window)),
|
||||
coarsely(&full, &semantic_tokens_in_range(&full, window)),
|
||||
"{}: lines {from}..{to}",
|
||||
path.display()
|
||||
);
|
||||
@@ -889,7 +930,8 @@ mod tests {
|
||||
// Punctuation (`,`, `;`) is deliberately not classified at all, so it
|
||||
// never reaches `pieces` — only the tokens `classify` keeps are
|
||||
// expected on the wire.
|
||||
for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) {
|
||||
let empty = HashMap::new();
|
||||
for token in window.tokens.iter().filter(|t| classify(t, &doc, &empty).is_some()) {
|
||||
let expected = positions.position(token.span.start);
|
||||
let found = decoded
|
||||
.iter()
|
||||
@@ -1291,4 +1333,129 @@ mod tests {
|
||||
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// module instantiation and `#(...)` parameter-list highlighting
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn named_tokens(text: &str) -> Vec<(String, u32, u32)> {
|
||||
with_document(text, |doc| {
|
||||
let pos = doc.positions();
|
||||
decode(&semantic_tokens(doc))
|
||||
.into_iter()
|
||||
.map(|(line, character, len, ty, mods)| {
|
||||
let start = pos.offset(Position { line, character }) as usize;
|
||||
let end = pos.offset(Position { line, character: character + len }) as usize;
|
||||
(doc.text[start..end].to_string(), ty, mods)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_instantiation_distinguishes_module_params_instance_ports_and_connections() {
|
||||
let src = "\
|
||||
module top #(
|
||||
parameter int DATA_W = 32
|
||||
) (
|
||||
input logic clk,
|
||||
input logic rst_ni
|
||||
);
|
||||
logic [DATA_W-1:0] data_q;
|
||||
pkg::uart_core #(
|
||||
.BAUD_DIV (EXT_DIV),
|
||||
.WIDTH (DATA_W),
|
||||
.DEPTH (16)
|
||||
) u_uart (
|
||||
.clk_i (clk),
|
||||
.rst_ni,
|
||||
.data_o (data_q),
|
||||
.*
|
||||
);
|
||||
assign data_q = u_uart.tx_data;
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
let find_nth = |word: &str, n: usize| {
|
||||
out.iter()
|
||||
.filter(|(w, ..)| w == word)
|
||||
.nth(n)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| panic!("{word} #{n} missing in {out:?}"))
|
||||
};
|
||||
|
||||
// Both `#` tokens (header parameter port list and instantiation overrides)
|
||||
// share `Parameter`, while `(` and `)` are never emitted.
|
||||
assert_eq!(find_nth("#", 0), ("#".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("#", 1), ("#".into(), Highlight::Parameter as u32, 0));
|
||||
assert!(!out.iter().any(|(w, ..)| w == "(" || w == ")"));
|
||||
|
||||
// Scoped module name: `pkg` is Namespace, `uart_core` is Class.
|
||||
assert_eq!(find_nth("pkg", 0), ("pkg".into(), Highlight::Namespace as u32, 0));
|
||||
assert_eq!(find_nth("uart_core", 0), ("uart_core".into(), Highlight::Class as u32, 0));
|
||||
|
||||
// Parameter overrides: `.` and parameter names share `Parameter` with `#`,
|
||||
// as do local (`DATA_W`) and external (`EXT_DIV`) parameter values; `16` stays Number.
|
||||
assert_eq!(find_nth(".", 0), (".".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("BAUD_DIV", 0), ("BAUD_DIV".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("EXT_DIV", 0), ("EXT_DIV".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth(".", 1), (".".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("WIDTH", 0), ("WIDTH".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("DATA_W", 2), ("DATA_W".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("16", 0), ("16".into(), Highlight::Number as u32, 0));
|
||||
|
||||
// Instance declaration and hierarchical use both highlight as `Function`.
|
||||
let fn_ty = Highlight::Function as u32;
|
||||
assert_eq!(find_nth("u_uart", 0), ("u_uart".into(), fn_ty, DECLARATION));
|
||||
assert_eq!(find_nth("u_uart", 1), ("u_uart".into(), fn_ty, 0));
|
||||
|
||||
// Port names (`.clk_i`, implicit `.rst_ni`, `.data_o`, wildcard `.*`) are `Property`,
|
||||
// while connected signals (`clk`, `data_q`) stay `Variable`.
|
||||
assert_eq!(find_nth(".", 3), (".".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("clk_i", 0), ("clk_i".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("clk", 1), ("clk".into(), Highlight::Variable as u32, 0));
|
||||
assert_eq!(find_nth("rst_ni", 1), ("rst_ni".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("data_o", 0), ("data_o".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("data_q", 1), ("data_q".into(), Highlight::Variable as u32, 0));
|
||||
assert_eq!(find_nth("*", 0), ("*".into(), Highlight::Property as u32, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_hashes_are_never_classified_as_parameters() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire #5 a;
|
||||
assign #(1:2:3) a = 1'b0;
|
||||
and #(2, 3) g0 (y, a, a);
|
||||
initial #10 $finish;
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
assert!(!out.iter().any(|(w, ..)| w == "#"), "delays keep `#` unemitted: {out:?}");
|
||||
assert!(out.contains(&("g0".into(), Highlight::Function as u32, DECLARATION)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfinished_port_and_param_entries_keep_their_highlights_while_typing() {
|
||||
let src = "\
|
||||
module m;
|
||||
sub #(
|
||||
.WIDTH(
|
||||
) u0 (
|
||||
.clk_i(
|
||||
.rst_ni(rst_n)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
assert!(out.contains(&("sub".into(), Highlight::Class as u32, 0)));
|
||||
assert!(out.contains(&("#".into(), Highlight::Parameter as u32, 0)));
|
||||
assert!(out.contains(&("WIDTH".into(), Highlight::Parameter as u32, 0)));
|
||||
assert!(out.contains(&("u0".into(), Highlight::Function as u32, DECLARATION)));
|
||||
assert!(out.contains(&("clk_i".into(), Highlight::Property as u32, 0)));
|
||||
assert!(out.contains(&("rst_ni".into(), Highlight::Property as u32, 0)));
|
||||
assert!(out.contains(&("rst_n".into(), Highlight::Variable as u32, 0)));
|
||||
reconstructs(MODULE, src);
|
||||
reconstructs(src, MODULE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
//! AST-guided semantic token overrides for module instantiations and `#(...)`
|
||||
//! parameter lists.
|
||||
//!
|
||||
//! Plain lexical + symbol-table classification leaves an external module's
|
||||
//! name, its `#` parameter sigil, its `.PARAM` overrides and its `.port`
|
||||
//! connections as uncoloured punctuation or generic `variable`s. Walking
|
||||
//! [`Document::tree`] supplies the syntactic role of each token directly from
|
||||
//! the parsed AST, even before workspace indexing finishes or when the
|
||||
//! instantiated unit lives outside the indexed tree.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vlog_parser::ast::{
|
||||
BindDirective, ClassDecl, ClassExtends, Connection, Connections, DataType, Expr,
|
||||
GateInstantiation, GenElse, Instantiation, Item, ItemKind, ListElem, Module, PortList, RawText,
|
||||
Typedef, TypedefKind,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{ExternalResolutions, Semantics, SymbolKind};
|
||||
|
||||
use super::{resolved_kind, Highlight};
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// Token-start byte offset -> highlight overrides derived from `doc.tree`.
|
||||
pub(super) fn overrides(doc: &Document) -> HashMap<u32, Highlight> {
|
||||
let mut out = HashMap::new();
|
||||
if doc.tokens.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let mut ctx = Ctx {
|
||||
tokens: &doc.tokens,
|
||||
semantics: &doc.semantics,
|
||||
external: &doc.external,
|
||||
out: &mut out,
|
||||
};
|
||||
ctx.items(&doc.tree.items);
|
||||
out
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
tokens: &'a [Token],
|
||||
semantics: &'a Semantics,
|
||||
external: &'a ExternalResolutions,
|
||||
out: &'a mut HashMap<u32, Highlight>,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
fn items(&mut self, items: &[Item]) {
|
||||
for item in items {
|
||||
self.item(item);
|
||||
}
|
||||
}
|
||||
|
||||
fn item(&mut self, item: &Item) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => self.module(m, item.span.end),
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
self.items(items)
|
||||
}
|
||||
ItemKind::Class(c) => self.class(c, item.span.end),
|
||||
ItemKind::Instantiation(inst) => self.instantiation(inst, item.span.end),
|
||||
ItemKind::Bind(bind) => self.bind(bind, item.span.end),
|
||||
ItemKind::GateInstantiation(gate) => self.gate(gate),
|
||||
ItemKind::GenBlock(b) => self.items(&b.items),
|
||||
ItemKind::GenIf(g) => {
|
||||
self.items(&g.then.items);
|
||||
self.gen_else(g.els.as_deref());
|
||||
}
|
||||
ItemKind::GenFor(g) => self.items(&g.body.items),
|
||||
ItemKind::GenCase(g) => {
|
||||
for arm in &g.items {
|
||||
self.items(&arm.body.items);
|
||||
}
|
||||
}
|
||||
ItemKind::DataDecl(d) => self.data_type(&d.ty),
|
||||
ItemKind::PortDecl(p) => self.data_type(&p.ty),
|
||||
ItemKind::ParamDecl(p) => self.data_type(&p.ty),
|
||||
ItemKind::Typedef(t) => self.typedef(t),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_else(&mut self, els: Option<&GenElse>) {
|
||||
match els {
|
||||
Some(GenElse::If(_, inner)) => {
|
||||
self.items(&inner.then.items);
|
||||
self.gen_else(inner.els.as_deref());
|
||||
}
|
||||
Some(GenElse::Block(block)) => self.items(&block.items),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn module(&mut self, m: &Module, end: u32) {
|
||||
if m.param_ports.is_some() {
|
||||
let last = m.imports.last().and_then(|imp| imp.paths.last());
|
||||
let from = last.map_or(m.name_span.end, |p| p.item.span.end);
|
||||
self.param_hash(from, end);
|
||||
}
|
||||
for elem in m.param_ports.iter().flatten() {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
if let PortList::Ansi(ports) = &m.ports {
|
||||
for elem in ports {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.items(&m.items);
|
||||
}
|
||||
|
||||
fn class(&mut self, c: &ClassDecl, end: u32) {
|
||||
if c.param_ports.is_some() {
|
||||
self.param_hash(c.name_span.end, end);
|
||||
for elem in c.param_ports.iter().flatten() {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ext) = &c.extends {
|
||||
self.class_extends(ext);
|
||||
}
|
||||
self.items(&c.items);
|
||||
}
|
||||
|
||||
fn class_extends(&mut self, ext: &ClassExtends) {
|
||||
self.scoped_unit(ext.name_span);
|
||||
if let Some(params) = &ext.params {
|
||||
self.param_hash(ext.name_span.end, ext.span.end);
|
||||
self.param_overrides(params);
|
||||
}
|
||||
}
|
||||
|
||||
fn typedef(&mut self, t: &Typedef) {
|
||||
if let TypedefKind::Alias(ty) = &t.kind {
|
||||
self.data_type(ty);
|
||||
}
|
||||
}
|
||||
|
||||
fn data_type(&mut self, ty: &DataType) {
|
||||
if let Some(params) = ty.params() {
|
||||
self.param_hash(params.span.start, params.span.end);
|
||||
}
|
||||
}
|
||||
|
||||
fn instantiation(&mut self, inst: &Instantiation, end: u32) {
|
||||
self.scoped_unit(inst.module_span);
|
||||
if let Some(params) = &inst.params {
|
||||
self.param_hash(inst.module_span.end, end);
|
||||
self.param_overrides(params);
|
||||
}
|
||||
for instance in &inst.instances {
|
||||
self.ident_at(instance.name_span, Highlight::Function);
|
||||
self.port_connections(&instance.conns);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self, b: &BindDirective, end: u32) {
|
||||
if let [only] = &b.target[..] {
|
||||
let kind = resolved_kind(only.span.start, self.semantics, self.external);
|
||||
if only.index.is_none() && kind != Some(SymbolKind::Instance) {
|
||||
self.ident_at(only.span, Highlight::Class);
|
||||
}
|
||||
}
|
||||
for inst in &b.instances {
|
||||
self.ident_at(inst.span, Highlight::Function);
|
||||
}
|
||||
self.instantiation(&b.inst, end);
|
||||
}
|
||||
|
||||
fn gate(&mut self, g: &GateInstantiation) {
|
||||
for inst in &g.instances {
|
||||
if let Some(span) = inst.name_span {
|
||||
self.ident_at(span, Highlight::Function);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn param_overrides(&mut self, params: &[ListElem<Connection>]) {
|
||||
for elem in params {
|
||||
match elem {
|
||||
ListElem::Ok(conn) => {
|
||||
self.named_entry(conn, Highlight::Parameter);
|
||||
if let Some(expr) = &conn.expr {
|
||||
self.param_expr(expr);
|
||||
}
|
||||
}
|
||||
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Parameter),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn port_connections(&mut self, conns: &Connections) {
|
||||
let Connections::Named(list) = conns else { return };
|
||||
for elem in list {
|
||||
match elem {
|
||||
ListElem::Ok(conn) => self.named_entry(conn, Highlight::Property),
|
||||
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Property),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn named_entry(&mut self, conn: &Connection, ty: Highlight) {
|
||||
if conn.name_span.is_empty() {
|
||||
return;
|
||||
}
|
||||
for tok in self.tokens_in(TextRange::new(conn.span.start, conn.name_span.start)) {
|
||||
if tok.is_sym(".") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
for tok in self.tokens_in(conn.name_span) {
|
||||
if (tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn recovered_entry(&mut self, raw: &RawText, ty: Highlight) {
|
||||
let mut saw_dot = false;
|
||||
for tok in self.tokens_in(raw.span) {
|
||||
if tok.kind == TokenKind::Attribute {
|
||||
continue;
|
||||
}
|
||||
if !saw_dot && tok.is_sym(".") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
saw_dot = true;
|
||||
continue;
|
||||
}
|
||||
if saw_dot && ((tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*")) {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
fn param_expr(&mut self, expr: &Expr) {
|
||||
if expr.span.is_empty() {
|
||||
return;
|
||||
}
|
||||
let start = first_token_from(self.tokens, expr.span.start);
|
||||
let slice = self.tokens.get(start..).unwrap_or(&[]);
|
||||
let len = slice.partition_point(|t| t.span.end <= expr.span.end);
|
||||
for (idx, tok) in slice[..len].iter().enumerate() {
|
||||
if tok.kind != TokenKind::Ident || tok.is_macro() {
|
||||
continue;
|
||||
}
|
||||
if resolved_kind(tok.span.start, self.semantics, self.external).is_some() {
|
||||
continue;
|
||||
}
|
||||
let abs = start + idx;
|
||||
let next = self.tokens.get(abs + 1);
|
||||
let prev = abs.checked_sub(1).and_then(|i| self.tokens.get(i));
|
||||
let ty = if next.is_some_and(|t| t.is_sym("::")) {
|
||||
Highlight::Namespace
|
||||
} else if next.is_some_and(|t| t.is_sym("(")) && !prev.is_some_and(|t| t.is_sym(".")) {
|
||||
Highlight::Function
|
||||
} else {
|
||||
Highlight::Parameter
|
||||
};
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
|
||||
fn scoped_unit(&mut self, span: TextRange) {
|
||||
let idents: Vec<&Token> = self
|
||||
.tokens_in(span)
|
||||
.iter()
|
||||
.filter(|t| t.kind == TokenKind::Ident && !t.is_macro())
|
||||
.collect();
|
||||
let Some((&last, prefix)) = idents.split_last() else { return };
|
||||
for &seg in prefix {
|
||||
self.out.insert(seg.span.start, Highlight::Namespace);
|
||||
}
|
||||
self.out.insert(last.span.start, Highlight::Class);
|
||||
}
|
||||
|
||||
fn ident_at(&mut self, span: TextRange, ty: Highlight) {
|
||||
for tok in self.tokens_in(span) {
|
||||
if tok.kind == TokenKind::Ident && !tok.is_macro() {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn param_hash(&mut self, from: u32, until: u32) {
|
||||
let start = first_token_from(self.tokens, from);
|
||||
for tok in self.tokens.get(start..).unwrap_or(&[]) {
|
||||
if tok.span.start >= until || tok.is_sym("(") || tok.is_sym(";") {
|
||||
break;
|
||||
}
|
||||
if tok.is_sym("#") {
|
||||
self.out.insert(tok.span.start, Highlight::Parameter);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tokens_in(&self, span: TextRange) -> &'a [Token] {
|
||||
if span.is_empty() {
|
||||
return &[];
|
||||
}
|
||||
let start = first_token_from(self.tokens, span.start);
|
||||
let slice = self.tokens.get(start..).unwrap_or(&[]);
|
||||
let len = slice.partition_point(|t| t.span.end <= span.end);
|
||||
&slice[..len]
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,12 @@ use crate::state::{Document, Workspace};
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
/// The class the cursor names, as the root of a type hierarchy — its own
|
||||
/// declaration, or any use of its name.
|
||||
/// declaration, or any use of its name — else the class whose body holds the
|
||||
/// cursor (its base, on `super`).
|
||||
///
|
||||
/// `None` for every other position, which is what stops an editor from opening
|
||||
/// an empty hierarchy view on a `wire`. A name that resolves to something other
|
||||
/// than a class declines the same way: there is no node to stand on.
|
||||
/// `None` outside every class, which is what stops an editor from opening an
|
||||
/// empty hierarchy view on a module's `wire`: modules stay off the type
|
||||
/// hierarchy.
|
||||
///
|
||||
/// A name two files declare returns *both* items rather than a guess, the same
|
||||
/// answer `textDocument/definition` gives for the same ambiguity — the client
|
||||
@@ -55,7 +56,47 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<TypeHierarc
|
||||
// navigation uses: this file's own symbol table, then the workspace
|
||||
// overlay.
|
||||
let items = classes_at(ws, doc, uri, offset);
|
||||
(!items.is_empty()).then_some(items)
|
||||
if !items.is_empty() {
|
||||
return Some(items);
|
||||
}
|
||||
// Anywhere else inside a class — a property, a method body, a keyword —
|
||||
// the class that encloses the cursor is the node to stand on, and `super`
|
||||
// names its base.
|
||||
let positions = doc.positions();
|
||||
let decl = enclosing_class(&doc.tree.items, offset)?;
|
||||
let class = item(uri.clone(), &positions, decl)?;
|
||||
if on_super(doc, offset) {
|
||||
let bases = bases_of(ws, doc, uri, &class);
|
||||
if !bases.is_empty() {
|
||||
return Some(bases);
|
||||
}
|
||||
}
|
||||
Some(vec![class])
|
||||
}
|
||||
|
||||
/// The innermost class declaration whose extent holds `offset`, its end
|
||||
/// included.
|
||||
///
|
||||
/// Read off the same [`classes::declarations`] walk every other answer here
|
||||
/// uses, so a class that walk cannot see (one inside a generate block) is not
|
||||
/// a node from the inside either.
|
||||
fn enclosing_class(items: &[Item], offset: u32) -> Option<Decl<'_>> {
|
||||
classes::declarations(items)
|
||||
.into_iter()
|
||||
.filter(|decl| decl.span.start <= offset && offset <= decl.span.end)
|
||||
.min_by_key(|decl| decl.span.end - decl.span.start)
|
||||
}
|
||||
|
||||
/// Whether the cursor is on `super`, the end of it included. The lexer reads
|
||||
/// `super` as an identifier, so the token's text is what is asked.
|
||||
fn on_super(doc: &Document, offset: u32) -> bool {
|
||||
use vlog_parser::token::TokenKind;
|
||||
let at = crate::state::first_token_reaching(&doc.tokens, offset);
|
||||
doc.tokens.get(at).is_some_and(|token| {
|
||||
matches!(token.kind, TokenKind::Ident | TokenKind::Keyword)
|
||||
&& token.text == "super"
|
||||
&& token.span.start <= offset
|
||||
})
|
||||
}
|
||||
|
||||
/// What this class extends: its base class, resolved in this file first and
|
||||
@@ -409,8 +450,11 @@ endclass
|
||||
}
|
||||
}
|
||||
|
||||
/// Reversed by call-hierarchy-everywhere (2026-10-14): the `class`
|
||||
/// keyword and a property are inside `base` and prepare it. A module
|
||||
/// and its wire still prepare nothing — modules stay off this view.
|
||||
#[test]
|
||||
fn a_position_on_no_class_prepares_nothing() {
|
||||
fn a_position_on_no_class_prepares_the_enclosing_one_or_nothing() {
|
||||
let text = "\
|
||||
class base;
|
||||
int x;
|
||||
@@ -421,8 +465,9 @@ module m;
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri) = workspace("none", &[("n.sv", text)]);
|
||||
assert!(prepare(&ws, &uri, 0).is_none(), "the `class` keyword");
|
||||
assert!(prepare(&ws, &uri, at(text, "int x") + 4).is_none(), "a property name");
|
||||
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("a class")[0]).0;
|
||||
assert_eq!(name(0), "base", "the `class` keyword is inside `base`");
|
||||
assert_eq!(name(at(text, "int x") + 4), "base", "a property name is inside `base`");
|
||||
assert!(prepare(&ws, &uri, at(text, "module m") + 7).is_none(), "a module is not a class");
|
||||
assert!(prepare(&ws, &uri, at(text, "wire w") + 5).is_none(), "a wire");
|
||||
}
|
||||
@@ -831,15 +876,21 @@ endclass
|
||||
// QA (2026-08-26): prepare on the keyword, and name shadowing
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Reversed by call-hierarchy-everywhere (2026-10-14): the keyword is
|
||||
/// inside `child`'s header and prepares `child` — still not `base`.
|
||||
#[test]
|
||||
fn prepare_on_the_extends_keyword_itself_prepares_nothing() {
|
||||
fn prepare_on_the_extends_keyword_itself_prepares_the_class_it_is_written_in() {
|
||||
let text = "class base;\nendclass\nclass child extends base;\nendclass\n";
|
||||
let (_tree, ws, uri) = workspace("keyword", &[("f.sv", text)]);
|
||||
assert!(prepare(&ws, &uri, at(text, "extends") + 2).is_none(), "the keyword, not a name");
|
||||
let items = prepare(&ws, &uri, at(text, "extends") + 2).expect("the enclosing class");
|
||||
assert_eq!(shape(&items[0]).0, "child", "the keyword, not a name");
|
||||
}
|
||||
|
||||
/// Reversed by call-hierarchy-everywhere (2026-10-14): the variable use
|
||||
/// is inside `child` and prepares `child`. The point of the pin stands —
|
||||
/// it never prepares the class `base` its text spells.
|
||||
#[test]
|
||||
fn a_class_name_shadowed_by_a_local_variable_prepares_the_variable_use_as_nothing() {
|
||||
fn a_class_name_shadowed_by_a_local_variable_prepares_the_enclosing_class() {
|
||||
// `base` is both a class and, inside `child`'s method, a local
|
||||
// variable name. The use on the right-hand side of the assignment
|
||||
// names the variable, not the class, and must not be treated as a
|
||||
@@ -857,10 +908,9 @@ endclass
|
||||
";
|
||||
let (_tree, ws, uri) = workspace("shadow", &[("f.sv", text)]);
|
||||
let use_offset = at(text, "base + 1");
|
||||
assert!(
|
||||
prepare(&ws, &uri, use_offset).is_none(),
|
||||
"a local variable named `base`, not the class"
|
||||
);
|
||||
let items = prepare(&ws, &uri, use_offset).expect("the enclosing class");
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(shape(&items[0]).0, "child", "a local variable named `base`, not the class");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -278,6 +278,57 @@ fn range_formatting_is_advertised_and_formats_only_the_selection() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Tab-indented, with a parse error after the block: the shape of a buffer
|
||||
/// mid-edit that "Format Selection" (TODO §66.2) must still serve.
|
||||
const TABBED_BROKEN: &str = "module m;\n\talways @* begin\n\t\tif (a) x=1;\n\t\telse x=2;\n\tend\n\tassign y = ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn range_formatting_lays_out_a_nested_selection_in_place_over_the_wire() {
|
||||
let dir = temp_dir("selectionfmt");
|
||||
let file = dir.join("m.sv");
|
||||
std::fs::write(&file, TABBED_BROKEN).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let request = |id: u32, sl: u32, el: u32| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":{sl},"character":0}},"end":{{"line":{el},"character":0}}}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(TABBED_BROKEN).expect("json")
|
||||
)),
|
||||
// The two statement lines inside the `always`.
|
||||
request(2, 2, 4),
|
||||
// The broken line itself: refused, no edit.
|
||||
request(3, 5, 6),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
assert_eq!(
|
||||
new_text(&messages, 2),
|
||||
"module m;\n\talways @* begin\n\t\tif (a) x = 1;\n\t\telse x = 2;\n\tend\n\tassign y = ;\nendmodule\n",
|
||||
"only the selected statement moves, tabs kept, error elsewhere ignored"
|
||||
);
|
||||
let refused = messages.iter().find(|m| m["id"] == 3).expect("response");
|
||||
assert!(
|
||||
refused.get("error").is_some()
|
||||
|| refused["result"].is_null()
|
||||
|| refused["result"] == serde_json::json!([]),
|
||||
"{refused}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Four items on four lines, so two ranges can straddle one they leave alone.
|
||||
const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
||||
|
||||
@@ -1040,6 +1091,64 @@ fn typing_a_newline_and_a_semicolon_round_trips_over_the_real_binary() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `begin` + Enter writes the `end` over the wire, and a pushed
|
||||
/// `lucisv.autoEnd: false` takes it back to the plain indent answer
|
||||
/// (`docs/features/completion-ux`).
|
||||
#[test]
|
||||
fn a_newline_after_begin_writes_the_end_unless_auto_end_is_off() {
|
||||
let dir = temp_dir("ontype_end");
|
||||
let file = dir.join("m.sv");
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
std::fs::write(&file, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let on_type = |id: u32| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/onTypeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":0}},"ch":"\n","options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
on_type(2),
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"autoEnd":false}}}}"#,
|
||||
),
|
||||
on_type(3),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let edits = |id: u32| {
|
||||
let response = messages.iter().find(|m| m["id"] == id).expect("a response");
|
||||
response["result"].as_array().expect("an array of edits").clone()
|
||||
};
|
||||
|
||||
let with_end = edits(2);
|
||||
assert_eq!(with_end.len(), 2, "{with_end:#?}");
|
||||
assert_eq!(with_end[0]["newText"], " ", "the body line's indent");
|
||||
assert_eq!(with_end[1]["newText"], " end\n", "the `end` under its `always_ff`");
|
||||
assert_eq!(
|
||||
with_end[1]["range"]["start"],
|
||||
serde_json::json!({ "line": 3, "character": 0 }),
|
||||
"inserted at the start of the line after the cursor's"
|
||||
);
|
||||
|
||||
let without = edits(3);
|
||||
assert_eq!(without.len(), 1, "autoEnd off: the indent alone: {without:#?}");
|
||||
assert_eq!(without[0]["newText"], " ");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_exclude_rebuilds_the_index_mid_session() {
|
||||
// The one link a unit test cannot check: that the notification handler
|
||||
@@ -2200,14 +2309,18 @@ fn inline_templates_round_trip_over_the_wire() {
|
||||
assert_eq!(item["insertText"]["value"], "${1:cond}) begin\n\t$0\nend");
|
||||
assert_eq!(item["range"]["start"], item["range"]["end"], "an insertion, not a replacement");
|
||||
|
||||
// `always @(` is the one trigger with a list: the clocked block first, the
|
||||
// combinational one second, both at the same empty range.
|
||||
let two = items(5);
|
||||
let two = two["items"].as_array().expect("a list");
|
||||
assert_eq!(two.len(), 2, "{two:#?}");
|
||||
assert_eq!(two[0]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend");
|
||||
assert_eq!(two[1]["insertText"]["value"], "*) begin\n\t$0\nend");
|
||||
assert_eq!(two[0]["range"], two[1]["range"], "both insert at the cursor");
|
||||
// `always @(` is a trigger with a list: clock and reset first, clock only
|
||||
// second, the combinational block third, all at the same empty range.
|
||||
let three = items(5);
|
||||
let three = three["items"].as_array().expect("a list");
|
||||
assert_eq!(three.len(), 3, "{three:#?}");
|
||||
assert_eq!(
|
||||
three[0]["insertText"]["value"],
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
|
||||
);
|
||||
assert_eq!(three[1]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend");
|
||||
assert_eq!(three[2]["insertText"]["value"], "*) begin\n\t$0\nend");
|
||||
assert_eq!(three[0]["range"], three[2]["range"], "all insert at the cursor");
|
||||
|
||||
assert_eq!(items(4), serde_json::Value::Null, "nowhere near a trigger");
|
||||
|
||||
@@ -2377,14 +2490,16 @@ fn keyword_and_project_completion_round_trip_over_the_wire() {
|
||||
assert_eq!(local["kind"], 6, "CompletionItemKind.Variable");
|
||||
assert!(local["sortText"].as_str().expect("sortText").starts_with('1'), "{local:#?}");
|
||||
|
||||
// `4`, not `2`: `completion-ux` (2026-11-17) put this file's own
|
||||
// declarations (`2`) and words (`3`) ahead of what other files declare.
|
||||
let macro_name = labelled("WIDGET_MACRO").expect("a `define name");
|
||||
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('2'));
|
||||
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('4'));
|
||||
|
||||
let elsewhere = labelled("widget_elsewhere").expect("a word used in the project");
|
||||
assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text");
|
||||
// `5`, not `4`: M6 inserted the template tier above the keywords, which
|
||||
// pushed the keyword and word tiers' digits down by one.
|
||||
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('5'));
|
||||
// `7`: M6 inserted the template tier above the keywords, and
|
||||
// `completion-ux` the two current-file tiers above the index.
|
||||
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('7'));
|
||||
|
||||
assert!(
|
||||
!items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))),
|
||||
@@ -2560,12 +2675,12 @@ fn a_template_completion_round_trips_over_the_wire() {
|
||||
assert_eq!(template["textEdit"]["range"]["start"]["line"], 2);
|
||||
assert_eq!(template["textEdit"]["range"]["start"]["character"], 4);
|
||||
assert_eq!(template["textEdit"]["range"]["end"]["character"], 6);
|
||||
assert!(template["sortText"].as_str().expect("sortText").starts_with('3'));
|
||||
assert!(template["sortText"].as_str().expect("sortText").starts_with('5'));
|
||||
|
||||
// The keyword survives beside it, one tier down.
|
||||
let keyword = labelled(items, "if").expect("the keyword");
|
||||
assert_eq!(keyword["kind"], 14, "CompletionItemKind.Keyword");
|
||||
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('4'));
|
||||
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('6'));
|
||||
|
||||
// A `.v` buffer is offered Verilog's `always`, never `always_ff`.
|
||||
let verilog = messages.iter().find(|m| m["id"] == 3).expect("completion response");
|
||||
@@ -3398,7 +3513,9 @@ fn the_module_hierarchy_round_trips_over_the_wire_in_both_directions() {
|
||||
"both sites of the same module, in one call"
|
||||
);
|
||||
|
||||
assert_eq!(response(5)["result"], serde_json::Value::Null, "an instance name is no module");
|
||||
// Reversed by call-hierarchy-everywhere (2026-10-14): an instance name
|
||||
// prepares the module it instantiates.
|
||||
assert_eq!(response(5)["result"][0]["name"], "hier_mid", "an instance name is its module");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -4873,7 +4990,9 @@ fn the_class_hierarchy_round_trips_over_the_wire_in_both_directions() {
|
||||
assert_eq!(subtypes[0]["uri"], leaf_uri.as_str());
|
||||
assert_eq!(subtypes[0]["kind"], 5, "SymbolKind.Class");
|
||||
|
||||
assert_eq!(response(5)["result"], serde_json::Value::Null, "a property name is no class");
|
||||
// Reversed by call-hierarchy-everywhere (2026-10-14): inside a class body
|
||||
// the enclosing class answers.
|
||||
assert_eq!(response(5)["result"][0]["name"], "type_mid", "a property is in its class");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -7243,8 +7362,16 @@ fn a_connection_list_completes_ports_over_the_wire() {
|
||||
assert_eq!(edit["range"]["start"], edit["range"]["end"], "an empty range at the cursor");
|
||||
}
|
||||
|
||||
// A port already connected is not offered again.
|
||||
assert_eq!(labels(3), vec!["data", "ready"]);
|
||||
// A port already connected is still offered, after the others and
|
||||
// marked (`completion-ux`, 2026-11-17 — it used to be dropped).
|
||||
assert_eq!(labels(3), vec!["clk", "data", "ready"]);
|
||||
let partly_items = response(3)["result"]["items"].as_array().expect("a list");
|
||||
let clk = partly_items.iter().find(|i| i["label"] == "clk").expect("clk");
|
||||
assert!(clk["sortText"].as_str().is_some_and(|s| s.starts_with('1')), "{clk:#?}");
|
||||
assert_eq!(clk["labelDetails"]["description"], "connected");
|
||||
let data = partly_items.iter().find(|i| i["label"] == "data").expect("data");
|
||||
assert!(data["sortText"].as_str().is_some_and(|s| s.starts_with('0')), "{data:#?}");
|
||||
assert!(data.get("labelDetails").is_none(), "{data:#?}");
|
||||
|
||||
// And `#(.` lists the parameters instead.
|
||||
assert_eq!(labels(4), vec!["WIRE_W"]);
|
||||
@@ -7252,6 +7379,94 @@ fn a_connection_list_completes_ports_over_the_wire() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `completion-ux` over the wire: a port item, asked by a client that reads
|
||||
/// snippets, writes `.name($1)` — pre-filled where the instantiating module
|
||||
/// has a same-named signal — and a typed keyword prefix grows a keyword
|
||||
/// ghost, following the popup's selected entry when one is sent.
|
||||
#[test]
|
||||
fn port_snippets_and_keyword_ghosts_round_trip_over_the_wire() {
|
||||
let dir = temp_dir("completionux");
|
||||
std::fs::write(
|
||||
dir.join("ux_sub.sv"),
|
||||
"module ux_sub (\n input logic clk,\n input logic data\n);\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let text = "module ux_top;\n logic clk;\n ux_sub u_sub (\n .\n );\n alw\nendmodule\n";
|
||||
let top = dir.join("ux_top.sv");
|
||||
std::fs::write(&top, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", top.display());
|
||||
let inline = |id: u32, selected: &str| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":5}},"context":{{"triggerKind":2{selected}}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"completion":{{"completionItem":{{"snippetSupport":true}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":5}},"context":{{"triggerKind":2,"triggerCharacter":"."}}}}}}"#
|
||||
)),
|
||||
inline(3, ""),
|
||||
inline(
|
||||
4,
|
||||
r#","selectedCompletionInfo":{"range":{"start":{"line":5,"character":2},"end":{"line":5,"character":5}},"text":"always_comb"}"#,
|
||||
),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let result = |id: u32| {
|
||||
messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == id)
|
||||
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"))["result"]
|
||||
.clone()
|
||||
};
|
||||
|
||||
let ports = result(2);
|
||||
let ports = ports["items"].as_array().expect("a list");
|
||||
let port = |name: &str| ports.iter().find(|i| i["label"] == name).expect("a port").clone();
|
||||
assert_eq!(port("clk")["textEdit"]["newText"], "clk(${1:clk})", "pre-filled from `logic clk`");
|
||||
assert_eq!(port("data")["textEdit"]["newText"], "data(${1})");
|
||||
assert_eq!(port("data")["insertTextFormat"], 2, "InsertTextFormat.Snippet");
|
||||
|
||||
let cursor = serde_json::json!({ "line": 5, "character": 5 });
|
||||
assert_eq!(
|
||||
result(3),
|
||||
serde_json::json!({
|
||||
"items": [{
|
||||
"insertText": { "kind": "snippet", "value": "ays_ff" },
|
||||
"range": { "start": cursor, "end": cursor }
|
||||
}]
|
||||
}),
|
||||
"the rest of the keyword, inserted at the cursor"
|
||||
);
|
||||
assert_eq!(
|
||||
result(4),
|
||||
serde_json::json!({
|
||||
"items": [{
|
||||
"insertText": { "kind": "snippet", "value": "always_comb" },
|
||||
"range": {
|
||||
"start": { "line": 5, "character": 2 },
|
||||
"end": { "line": 5, "character": 5 }
|
||||
}
|
||||
}]
|
||||
}),
|
||||
"the popup's selection, over the popup's range"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// constraint-bodies (TODO.md §20)
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -8741,3 +8956,245 @@ endmodule
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The connection being typed (TODO §68.2, `docs/features/port-entry-grace`)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// `cargo test --release -p lucisv_server --test e2e a_keystroke_in_a_port_list -- --ignored --nocapture --test-threads=1`
|
||||
///
|
||||
/// The per-keystroke cost of finding the entry being typed, on the largest
|
||||
/// corpus file with instantiations in it: a character typed into a connection
|
||||
/// name in the middle of `ibex_core.sv` (2 026 lines). Prints, asserts nothing,
|
||||
/// exactly like `a_keystroke_round_trip_over_the_wire`; the before/after
|
||||
/// numbers are in the feature README.
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/features/port-entry-grace"]
|
||||
fn a_keystroke_in_a_port_list_round_trip_over_the_wire() {
|
||||
let corpus = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/ibex/rtl/ibex_core.sv");
|
||||
let Ok(source) = std::fs::read_to_string(&corpus) else {
|
||||
eprintln!("no corpus checkout; nothing to measure");
|
||||
return;
|
||||
};
|
||||
let dir = temp_dir("portkeystroke");
|
||||
let file = dir.join("ibex_core.sv");
|
||||
std::fs::write(&file, &source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
// The fourth `.clk_i` connection (line 781 of the file), just after `.c`.
|
||||
let line = 780u32;
|
||||
let column = " .c".len() as u32;
|
||||
|
||||
let mut live = Live::start();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(&source).expect("json")
|
||||
));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&keystroke(&uri, 2, line, column));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let single = started.elapsed();
|
||||
|
||||
let runs = 10u32;
|
||||
let started = std::time::Instant::now();
|
||||
for k in 0..runs {
|
||||
live.send(&keystroke(&uri, 3 + k, line, column + 1 + k));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{},"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":4}}}}}}"#,
|
||||
50 + k
|
||||
));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
live.wait_for(|m| m["id"] == 50 + k);
|
||||
}
|
||||
let requested = started.elapsed() / runs;
|
||||
live.finish();
|
||||
eprintln!(
|
||||
"port-list keystroke round trip, ibex_core.sv: one change alone {single:?}, \
|
||||
one change a request follows {requested:?}"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A module with an instance whose connection list has an empty line in it,
|
||||
/// for a connection to be typed on (line 3, 0-based).
|
||||
const PORT_TYPING: &str =
|
||||
"module m;\n logic x, y;\n sub u0 (.a(x),\n \n .b(y));\n assign x = y;\nendmodule\n";
|
||||
|
||||
/// Open [`PORT_TYPING`] in a fresh session (`capabilities` as the client's),
|
||||
/// returning the live session and the buffer's URI.
|
||||
fn port_typing_session(name: &str, capabilities: &str) -> (Live, String, PathBuf) {
|
||||
let dir = temp_dir(name);
|
||||
let file = dir.join("m.sv");
|
||||
std::fs::write(&file, PORT_TYPING).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let mut live = Live::start();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{capabilities}}}}}"#
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(PORT_TYPING).expect("json")
|
||||
));
|
||||
(live, uri, dir)
|
||||
}
|
||||
|
||||
/// `text` typed at `(line, character)` of `uri`, as an incremental edit.
|
||||
fn typed(uri: &str, version: u32, line: u32, character: u32, text: &str) -> String {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"range":{{"start":{{"line":{line},"character":{character}}},"end":{{"line":{line},"character":{character}}}}},"text":{}}}]}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)
|
||||
}
|
||||
|
||||
/// The parse errors a publish or a pull report carries, as their start lines.
|
||||
fn error_lines(items: &serde_json::Value) -> Vec<u64> {
|
||||
items
|
||||
.as_array()
|
||||
.expect("diagnostics")
|
||||
.iter()
|
||||
.filter(|d| d["severity"] == 1)
|
||||
.filter_map(|d| d["range"]["start"]["line"].as_u64())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// TODO §68.2 over the wire: `.po(` typed into a connection list is not
|
||||
/// reported while it is the thing being typed, and is reported once the
|
||||
/// typing has stopped for the grace period (1.5 s) — with nothing else sent.
|
||||
#[test]
|
||||
fn a_connection_being_typed_is_reported_only_after_the_grace_period() {
|
||||
let (mut live, uri, dir) = port_typing_session("portgrace", "{}");
|
||||
let opened = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert!(error_lines(&opened["params"]["diagnostics"]).is_empty(), "{opened:#?}");
|
||||
|
||||
live.send(&typed(&uri, 2, 3, 4, ".po("));
|
||||
let typing = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let withheld_at = std::time::Instant::now();
|
||||
assert!(
|
||||
error_lines(&typing["params"]["diagnostics"]).is_empty(),
|
||||
"the open `(` of the entry being typed is held back: {typing:#?}"
|
||||
);
|
||||
|
||||
let released = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let waited = withheld_at.elapsed();
|
||||
assert_eq!(error_lines(&released["params"]["diagnostics"]), [3], "{released:#?}");
|
||||
assert!(waited >= std::time::Duration::from_millis(1000), "released after {waited:?}");
|
||||
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The other two releases: an edit landing outside the entry says everything
|
||||
/// at once, with no grace to wait for — and so does a save.
|
||||
#[test]
|
||||
fn a_connection_being_typed_is_reported_as_soon_as_the_typing_moves_on_or_saves() {
|
||||
let (mut live, uri, dir) = port_typing_session("portmoveon", "{}");
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
|
||||
live.send(&typed(&uri, 2, 3, 4, ".po("));
|
||||
let typing = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert!(error_lines(&typing["params"]["diagnostics"]).is_empty(), "{typing:#?}");
|
||||
|
||||
// A space typed after `logic x, y;` — outside every connection list.
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&typed(&uri, 3, 1, 13, " "));
|
||||
let moved = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert_eq!(error_lines(&moved["params"]["diagnostics"]), [3], "{moved:#?}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_millis(1000), "no grace to wait for");
|
||||
|
||||
// Back into the entry: held back again; then saved: said again.
|
||||
live.send(&typed(&uri, 4, 3, 8, "x"));
|
||||
let again = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert!(error_lines(&again["params"]["diagnostics"]).is_empty(), "{again:#?}");
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
));
|
||||
let saved = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert_eq!(error_lines(&saved["params"]["diagnostics"]), [3], "{saved:#?}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_millis(1000), "no grace to wait for");
|
||||
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A pulling client: the pull made while typing leaves the entry out, and the
|
||||
/// first pull after the grace has a new `resultId` and the full list — never
|
||||
/// "unchanged" against the report that left it out.
|
||||
#[test]
|
||||
fn a_pulling_client_sees_the_entry_at_its_first_pull_after_the_grace() {
|
||||
let pulls = r#"{"textDocument":{"diagnostic":{}}}"#;
|
||||
let (mut live, uri, dir) = port_typing_session("portpull", pulls);
|
||||
live.send(&typed(&uri, 2, 3, 4, ".po("));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"#
|
||||
));
|
||||
let typing = live.wait_for(|m| m["id"] == 2);
|
||||
assert!(error_lines(&typing["result"]["items"]).is_empty(), "{typing:#?}");
|
||||
let held = typing["result"]["resultId"].as_str().expect("a result id").to_string();
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(1700));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{held}"}}}}"#
|
||||
));
|
||||
// The release happened before this pull was sent, so a refresh request —
|
||||
// which this client never said it accepts — would arrive first.
|
||||
let after = live.wait_for(|m| {
|
||||
m["id"] == 3
|
||||
|| m["method"] == "textDocument/publishDiagnostics"
|
||||
|| m["method"] == "workspace/diagnostic/refresh"
|
||||
});
|
||||
assert_eq!(after["id"], 3, "neither pushed nor asked to refresh: {after:#?}");
|
||||
assert_eq!(after["result"]["kind"], "full", "{after:#?}");
|
||||
assert_eq!(error_lines(&after["result"]["items"]), [3], "{after:#?}");
|
||||
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A pulling client that accepts `workspace/diagnostic/refresh` — VS Code's
|
||||
/// `vscode-languageclient` does — is asked to pull again when the grace runs
|
||||
/// out, so the entry shows after the pause with nothing typed.
|
||||
#[test]
|
||||
fn a_pulling_client_that_can_refresh_is_asked_to_after_the_grace() {
|
||||
let pulls =
|
||||
r#"{"textDocument":{"diagnostic":{}},"workspace":{"diagnostics":{"refreshSupport":true}}}"#;
|
||||
let (mut live, uri, dir) = port_typing_session("portrefresh", pulls);
|
||||
live.send(&typed(&uri, 2, 3, 4, ".po("));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"#
|
||||
));
|
||||
let typing = live.wait_for(|m| m["id"] == 2);
|
||||
assert!(error_lines(&typing["result"]["items"]).is_empty(), "{typing:#?}");
|
||||
let held = typing["result"]["resultId"].as_str().expect("a result id").to_string();
|
||||
let withheld_at = std::time::Instant::now();
|
||||
|
||||
let refresh = live.wait_for(|m| {
|
||||
m["method"] == "workspace/diagnostic/refresh"
|
||||
|| m["method"] == "textDocument/publishDiagnostics"
|
||||
});
|
||||
assert_eq!(refresh["method"], "workspace/diagnostic/refresh", "{refresh:#?}");
|
||||
let waited = withheld_at.elapsed();
|
||||
assert!(waited >= std::time::Duration::from_millis(1000), "asked after {waited:?}");
|
||||
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{},"result":null}}"#, refresh["id"]));
|
||||
|
||||
// What the client does on the request: pull again, and get it all.
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{held}"}}}}"#
|
||||
));
|
||||
let after = live.wait_for(|m| m["id"] == 3);
|
||||
assert_eq!(after["result"]["kind"], "full", "{after:#?}");
|
||||
assert_eq!(error_lines(&after["result"]["items"]), [3], "{after:#?}");
|
||||
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! TODO §65.2 on a real checkout: `textDocument/references` at the `aes`
|
||||
//! instantiation in `hw/ip/aes/dv/tb/tb.sv` and at its `.clk_i` connection.
|
||||
//!
|
||||
//! Over the whole workspace (`lucisv.index.scope: "workspace"`) the server
|
||||
//! answers what the whole-set engine answers — 14 and 12, the three generated
|
||||
//! `*_pd_main.sv` tops included. Under the shipped folder scope it answers 11
|
||||
//! and 9: the testbench's folder raises two levels to `hw/ip/aes`, and the
|
||||
//! tops are not in the index. Both are pinned, because the difference *is*
|
||||
//! the finding (`docs/features/references-fanout-pd-main/README.md`).
|
||||
//!
|
||||
//! `#[ignore]`: it needs the checkout, which it only reads. Run with
|
||||
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
|
||||
//! lucisv_server --test opentitan_references -- --ignored --nocapture`;
|
||||
//! without the variable it looks in `~/.cache/lucisv-eval/ot`, and it skips
|
||||
//! (passing, with a line on stderr) when neither holds the testbench.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The testbench, relative to the checkout.
|
||||
const TB: &str = "hw/ip/aes/dv/tb/tb.sv";
|
||||
|
||||
/// The three generated tops the folder scope does not reach.
|
||||
const TOPS: [&str; 3] = [
|
||||
"hw/top_darjeeling/rtl/autogen/darjeeling_pd_main.sv",
|
||||
"hw/top_earlgrey/rtl/autogen/earlgrey_pd_main.sv",
|
||||
"hw/top_englishbreakfast/rtl/autogen/englishbreakfast_pd_main.sv",
|
||||
];
|
||||
|
||||
/// The checkout: `LUCISV_OPENTITAN`, else the eval clone; `None` when the
|
||||
/// testbench is not there.
|
||||
fn checkout() -> Option<PathBuf> {
|
||||
let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| {
|
||||
std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache/lucisv-eval/ot"))
|
||||
})?;
|
||||
root.join(TB).is_file().then_some(root)
|
||||
}
|
||||
|
||||
/// One language server over `root/hw`, with `settings` as its `lucisv`
|
||||
/// section.
|
||||
struct Server {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
inbox: Receiver<Value>,
|
||||
settings: Value,
|
||||
next_id: i64,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
fn over(hw: &Path, settings: Value) -> Server {
|
||||
// The persistent cache falls back to the OS cache directory; point it
|
||||
// somewhere a test may write, as `tests/e2e.rs` does.
|
||||
let sandbox =
|
||||
std::env::temp_dir().join(format!("lucisv_server_ot_refs_{}", std::process::id()));
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
|
||||
.env("HOME", &sandbox)
|
||||
.env("XDG_CACHE_HOME", sandbox.join("cache"))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("the server binary starts");
|
||||
let stdin = child.stdin.take().expect("stdin");
|
||||
let stdout = BufReader::new(child.stdout.take().expect("stdout"));
|
||||
let (sender, inbox) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut stdout = stdout;
|
||||
while let Some(message) = read_message(&mut stdout) {
|
||||
if sender.send(message).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut server = Server { child, stdin, inbox, settings, next_id: 0 };
|
||||
let root = uri(hw);
|
||||
server.request(
|
||||
"initialize",
|
||||
json!({
|
||||
"processId": null, "rootUri": root,
|
||||
"workspaceFolders": [{ "uri": root, "name": "hw" }],
|
||||
"capabilities": {
|
||||
"window": { "workDoneProgress": true },
|
||||
"workspace": { "configuration": true },
|
||||
},
|
||||
}),
|
||||
);
|
||||
server.notify("initialized", json!({}));
|
||||
let lucisv = server.settings.clone();
|
||||
server.notify(
|
||||
"workspace/didChangeConfiguration",
|
||||
json!({ "settings": { "lucisv": lucisv } }),
|
||||
);
|
||||
server
|
||||
}
|
||||
|
||||
fn send(&mut self, message: Value) {
|
||||
let payload = message.to_string();
|
||||
write!(self.stdin, "Content-Length: {}\r\n\r\n{payload}", payload.len()).expect("write");
|
||||
self.stdin.flush().expect("flush");
|
||||
}
|
||||
|
||||
fn notify(&mut self, method: &str, params: Value) {
|
||||
self.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
|
||||
}
|
||||
|
||||
/// The next message within `wait`, with every request the server makes
|
||||
/// of us answered on the way (`workspace/configuration` with our
|
||||
/// settings, everything else with `null`).
|
||||
fn next(&mut self, wait: Duration) -> Option<Value> {
|
||||
let message = self.inbox.recv_timeout(wait).ok()?;
|
||||
if let (Some(id), Some(method)) = (message.get("id"), message["method"].as_str()) {
|
||||
let result = if method == "workspace/configuration" {
|
||||
let items = message["params"]["items"].as_array().map_or(1, Vec::len);
|
||||
Value::Array(vec![self.settings.clone(); items])
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
let id = id.clone();
|
||||
self.send(json!({ "jsonrpc": "2.0", "id": id, "result": result }));
|
||||
}
|
||||
Some(message)
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
self.send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
|
||||
let deadline = Instant::now() + Duration::from_secs(600);
|
||||
while Instant::now() < deadline {
|
||||
let Some(message) = self.next(Duration::from_secs(1)) else { continue };
|
||||
if message["id"] == id && message.get("method").is_none() {
|
||||
return message["result"].clone();
|
||||
}
|
||||
}
|
||||
panic!("{method} was not answered");
|
||||
}
|
||||
|
||||
/// Open the testbench and wait until every scan has ended: at least one
|
||||
/// progress `end` after the open, then five quiet seconds with no bar in
|
||||
/// flight (the startup scan, the settings push and the open's widen may
|
||||
/// each run one).
|
||||
fn open_and_settle(&mut self, path: &Path) {
|
||||
let text = std::fs::read_to_string(path).expect("read the testbench");
|
||||
self.notify(
|
||||
"textDocument/didOpen",
|
||||
json!({ "textDocument": {
|
||||
"uri": uri(path), "languageId": "systemverilog", "version": 1, "text": text,
|
||||
}}),
|
||||
);
|
||||
let deadline = Instant::now() + Duration::from_secs(600);
|
||||
let (mut ended, mut in_flight, mut quiet_since) = (false, 0i32, Instant::now());
|
||||
while Instant::now() < deadline {
|
||||
if ended && in_flight <= 0 && quiet_since.elapsed() > Duration::from_secs(5) {
|
||||
return;
|
||||
}
|
||||
let Some(message) = self.next(Duration::from_secs(1)) else { continue };
|
||||
if message["method"] != "$/progress" {
|
||||
continue;
|
||||
}
|
||||
quiet_since = Instant::now();
|
||||
match message["params"]["value"]["kind"].as_str() {
|
||||
Some("begin") => in_flight += 1,
|
||||
Some("end") => {
|
||||
in_flight -= 1;
|
||||
ended = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
panic!("the scan never settled");
|
||||
}
|
||||
|
||||
/// `references` at the first `needle` on 1-based `line` of `path`, as
|
||||
/// `file:line` relative to `root`, sorted.
|
||||
fn references(&mut self, root: &Path, path: &Path, line: usize, needle: &str) -> Vec<String> {
|
||||
let text = std::fs::read_to_string(path).expect("read");
|
||||
let row = text.lines().nth(line - 1).expect("the line");
|
||||
let character = row.find(needle).expect("the needle on that line");
|
||||
let found = self.request(
|
||||
"textDocument/references",
|
||||
json!({
|
||||
"textDocument": { "uri": uri(path) },
|
||||
"position": { "line": line - 1, "character": character },
|
||||
"context": { "includeDeclaration": true },
|
||||
}),
|
||||
);
|
||||
let prefix = format!("{}/", uri(root));
|
||||
let mut out: Vec<String> = found
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let file = l["uri"].as_str().unwrap_or("?").replace(&prefix, "");
|
||||
format!("{file}:{}", l["range"]["start"]["line"].as_u64().unwrap_or(0) + 1)
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn uri(path: &Path) -> String {
|
||||
format!("file://{}", path.display())
|
||||
}
|
||||
|
||||
/// One framed message, or `None` when the stream ends.
|
||||
fn read_message(input: &mut impl BufRead) -> Option<Value> {
|
||||
let mut length = None;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if input.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
return None;
|
||||
}
|
||||
let trimmed = line.trim_end_matches(['\r', '\n']);
|
||||
if trimmed.is_empty() {
|
||||
break;
|
||||
}
|
||||
if let Some(value) = trimmed.strip_prefix("Content-Length: ") {
|
||||
length = value.parse::<usize>().ok();
|
||||
}
|
||||
}
|
||||
let mut body = vec![0u8; length?];
|
||||
input.read_exact(&mut body).ok()?;
|
||||
serde_json::from_slice(&body).ok()
|
||||
}
|
||||
|
||||
/// The `aes` and `.clk_i` answers of one server over `root/hw`.
|
||||
fn answers(root: &Path, settings: Value) -> (Vec<String>, Vec<String>) {
|
||||
let hw = root.join("hw");
|
||||
let tb = root.join(TB);
|
||||
let mut server = Server::over(&hw, settings);
|
||||
server.open_and_settle(&tb);
|
||||
let module = server.references(root, &tb, 45, "aes");
|
||||
let port = server.references(root, &tb, 50, "clk_i");
|
||||
println!("aes: {} {module:#?}\n.clk_i: {} {port:#?}", module.len(), port.len());
|
||||
(module, port)
|
||||
}
|
||||
|
||||
fn names_a_top(found: &[String], top: &str) -> bool {
|
||||
found.iter().any(|hit| hit.starts_with(&format!("{top}:")))
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN or ~/.cache/lucisv-eval/ot)"]
|
||||
fn over_the_whole_workspace_references_list_the_three_generated_tops() {
|
||||
let Some(root) = checkout() else {
|
||||
eprintln!("skipped: no opentitan checkout holding {TB}");
|
||||
return;
|
||||
};
|
||||
let (module, port) = answers(&root, json!({ "index": { "scope": "workspace" } }));
|
||||
assert_eq!(module.len(), 14, "aes: {module:#?}");
|
||||
assert_eq!(port.len(), 12, ".clk_i: {port:#?}");
|
||||
for top in TOPS {
|
||||
assert!(names_a_top(&module, top), "aes misses {top}");
|
||||
assert!(names_a_top(&port, top), ".clk_i misses {top}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN or ~/.cache/lucisv-eval/ot)"]
|
||||
fn under_the_folder_scope_references_stop_at_the_ip_block() {
|
||||
let Some(root) = checkout() else {
|
||||
eprintln!("skipped: no opentitan checkout holding {TB}");
|
||||
return;
|
||||
};
|
||||
let (module, port) = answers(&root, json!({}));
|
||||
assert_eq!(module.len(), 11, "aes: {module:#?}");
|
||||
assert_eq!(port.len(), 9, ".clk_i: {port:#?}");
|
||||
let in_block = |found: &[String]| found.iter().all(|hit| hit.starts_with("hw/ip/aes/"));
|
||||
assert!(in_block(&module) && in_block(&port), "only hw/ip/aes is in scope");
|
||||
}
|
||||
@@ -28,7 +28,7 @@ mod stmt;
|
||||
mod sva;
|
||||
mod verbatim;
|
||||
|
||||
use crate::doc::{text, Doc};
|
||||
use crate::doc::{concat, text, Doc};
|
||||
use crate::fence::{self, Region};
|
||||
use crate::printer::Printer;
|
||||
use crate::range::{self, Split};
|
||||
@@ -62,6 +62,10 @@ pub enum FormatError {
|
||||
Source(vlog_parser::Error),
|
||||
/// A safety check failed; the formatted text was discarded.
|
||||
Verification(VerificationError),
|
||||
/// A selection could not be laid out on its own — it reaches a parse
|
||||
/// error, or its target could not be found again in the output. Nothing
|
||||
/// was changed.
|
||||
Selection(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FormatError {
|
||||
@@ -69,6 +73,7 @@ impl std::fmt::Display for FormatError {
|
||||
match self {
|
||||
FormatError::Source(e) => write!(f, "{e}"),
|
||||
FormatError::Verification(e) => write!(f, "{e}"),
|
||||
FormatError::Selection(e) => write!(f, "{e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +135,41 @@ pub fn format_range(
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// A sibling run a selection lays out on its own: items at their AST depth,
|
||||
/// or statements.
|
||||
pub(crate) enum Run<'t> {
|
||||
Items(&'t [Item], usize),
|
||||
Stmts(&'t [Stmt]),
|
||||
}
|
||||
|
||||
/// Lay out one run of `file` (parsed from `source`) exactly as the
|
||||
/// whole-file printers would, every line starting with `base`.
|
||||
///
|
||||
/// No final-newline normalization and no trailing whitespace: the result
|
||||
/// replaces the run's own bytes and nothing else. Fenced regions inside the
|
||||
/// run are emitted as written, as in a whole-file run.
|
||||
pub(crate) fn print_run(
|
||||
source: &str,
|
||||
file: &SourceFile,
|
||||
config: &Config,
|
||||
run: Run<'_>,
|
||||
base: &str,
|
||||
) -> String {
|
||||
let regions = fence::collect(source, file);
|
||||
let fmt = Fmt { cfg: config, src: source, regions, splits: Vec::new() };
|
||||
let docs = match run {
|
||||
Run::Items(items, depth) => fmt.item_seq(items, depth),
|
||||
Run::Stmts(stmts) => fmt.stmt_seq(stmts),
|
||||
};
|
||||
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
|
||||
let mut out = printer.print_at(&concat(docs), base);
|
||||
// Spaces and newlines only, exactly what `render` trims.
|
||||
while out.ends_with('\n') || out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A single unverified formatting pass: parse, lay out, print.
|
||||
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
|
||||
let file = vlog_parser::parse_source(source)?;
|
||||
|
||||
@@ -6,8 +6,10 @@ pub mod fence;
|
||||
pub mod format;
|
||||
pub mod printer;
|
||||
pub mod range;
|
||||
mod selection;
|
||||
pub mod verify;
|
||||
|
||||
pub use format::{format_range, format_source, Config, FormatError};
|
||||
pub use range::LineRanges;
|
||||
pub use selection::format_selection;
|
||||
pub use verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
@@ -18,9 +18,22 @@ pub struct Printer {
|
||||
}
|
||||
|
||||
impl Printer {
|
||||
/// Render `doc` starting at column 0.
|
||||
pub fn print(&self, doc: &Doc) -> String {
|
||||
let mut out = String::new();
|
||||
let mut col = 0usize;
|
||||
self.print_at(doc, "")
|
||||
}
|
||||
|
||||
/// Render `doc` as if every line began with `base`: the text starts with
|
||||
/// `base`, every line break the printer writes repeats it before the
|
||||
/// indentation, and the width budget shrinks by it.
|
||||
///
|
||||
/// `base` is copied as written, tabs included, which is what lets a
|
||||
/// selection keep the indentation it was written at. Text that carries
|
||||
/// its own absolute indentation (`Doc::Verbatim`, `Doc::Inline`) is not
|
||||
/// shifted. With an empty `base` this is exactly [`Printer::print`].
|
||||
pub fn print_at(&self, doc: &Doc, base: &str) -> String {
|
||||
let mut out = base.to_string();
|
||||
let mut col = self.base_width(base);
|
||||
// Stack of (indent_level, mode, doc).
|
||||
let mut stack: Vec<(usize, Mode, &Doc)> = vec![(0, Mode::Break, doc)];
|
||||
|
||||
@@ -61,24 +74,22 @@ impl Printer {
|
||||
out.push(' ');
|
||||
col += 1;
|
||||
} else {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
}
|
||||
Doc::SoftLine => {
|
||||
if mode == Mode::Break {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
}
|
||||
Doc::HardLine => {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
Doc::BlankLine => {
|
||||
// Trim trailing spaces from the current line, add a blank.
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
trim_line_end(&mut out, base);
|
||||
out.push('\n');
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
Doc::IfBreak(s) => {
|
||||
if mode == Mode::Break {
|
||||
@@ -89,9 +100,7 @@ impl Printer {
|
||||
Doc::Verbatim(s) => {
|
||||
// Undo the indent the preceding line break wrote: these
|
||||
// bytes carry their own.
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
trim_line_end(&mut out, base);
|
||||
out.push_str(s);
|
||||
col = s.rsplit('\n').next().map_or(0, |last| last.chars().count());
|
||||
}
|
||||
@@ -100,14 +109,20 @@ impl Printer {
|
||||
out
|
||||
}
|
||||
|
||||
fn newline(&self, out: &mut String, col: &mut usize, ind: usize) {
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
fn newline(&self, out: &mut String, col: &mut usize, ind: usize, base: &str) {
|
||||
trim_line_end(out, base);
|
||||
out.push('\n');
|
||||
out.push_str(base);
|
||||
let spaces = ind * self.indent_width;
|
||||
out.extend(std::iter::repeat_n(' ', spaces));
|
||||
*col = spaces;
|
||||
*col = self.base_width(base) + spaces;
|
||||
}
|
||||
|
||||
/// The columns `base` occupies. A tab counts as one indent level: the
|
||||
/// printer cannot know the reader's tab stop, and the width only steers
|
||||
/// which groups break.
|
||||
fn base_width(&self, base: &str) -> usize {
|
||||
base.chars().map(|c| if c == '\t' { self.indent_width } else { 1 }).sum()
|
||||
}
|
||||
|
||||
/// Would `items` (flat) followed by the rest of the work stack fit on
|
||||
@@ -194,6 +209,23 @@ impl Printer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the trailing spaces of the line being written. Under a non-empty
|
||||
/// `base` a line holding nothing but indentation is emptied entirely, so a
|
||||
/// blank line never keeps the base's tabs; with no base this is exactly the
|
||||
/// space trim the printer always did.
|
||||
fn trim_line_end(out: &mut String, base: &str) {
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
if base.is_empty() {
|
||||
return;
|
||||
}
|
||||
let bol = out.rfind('\n').map_or(0, |i| i + 1);
|
||||
if out[bol..].chars().all(|c| c == ' ' || c == '\t') {
|
||||
out.truncate(bol);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn contains_hard_line(items: &[Doc]) -> bool {
|
||||
items.iter().any(|d| match d {
|
||||
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => true,
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Finding the run of sibling units one selected line span names.
|
||||
//!
|
||||
//! The walk starts at the file scope and goes down while the selection sits
|
||||
//! inside a single unit below its first line and reaches into exactly one of
|
||||
//! its nested scopes; it then settles on the units met there. A run that cannot be cut
|
||||
//! out of its lines cleanly, or whose ends a fenced region covers, is trimmed
|
||||
//! or given up one level at a time. The result is a [`Target`]: a path of
|
||||
//! child indices plus a run, which is what lets the same units be found again
|
||||
//! in the formatted output.
|
||||
|
||||
use crate::fence::Region;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use super::scope::{Scope, Unit};
|
||||
|
||||
/// The units a selection lays out, by position in the tree.
|
||||
///
|
||||
/// `path` holds one `(unit index, child scope index)` step per scope the walk
|
||||
/// descended into; the run is `start..start + count` of the scope it ends in.
|
||||
/// Positions, not bytes, so the target can be replayed on a reformatted text
|
||||
/// whose tree is the same.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct Target {
|
||||
pub path: Vec<(usize, usize)>,
|
||||
pub start: usize,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// What one selected line span comes to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) enum Found {
|
||||
/// No unit to lay out: blank lines, or everything met is fenced.
|
||||
Nothing,
|
||||
/// The run holds a module or package, or no run is line-clean: the
|
||||
/// request goes to `format_range` whole.
|
||||
Defer,
|
||||
Target(Target),
|
||||
}
|
||||
|
||||
/// The finder over one text and the tree parsed from it.
|
||||
pub(super) struct Locator<'s> {
|
||||
src: &'s str,
|
||||
index: LineIndex,
|
||||
regions: Vec<Region>,
|
||||
}
|
||||
|
||||
impl<'s> Locator<'s> {
|
||||
pub(super) fn new(src: &'s str, regions: Vec<Region>) -> Locator<'s> {
|
||||
Locator { src, index: LineIndex::new(src), regions }
|
||||
}
|
||||
|
||||
/// Locate the run the 1-based inclusive lines `first..=last` select.
|
||||
pub(super) fn locate(&self, root: Scope<'_>, (first, last): (u32, u32)) -> Found {
|
||||
let mut trail = vec![root];
|
||||
let mut path = Vec::new();
|
||||
let mut scope = root;
|
||||
let Some((mut a, mut b)) = self.met(scope, first, last) else { return Found::Nothing };
|
||||
while a == b {
|
||||
let Some((k, child)) = self.descend(scope, a, first, last) else { break };
|
||||
let Some(run) = self.met(child, first, last) else { break };
|
||||
path.push((a, k));
|
||||
trail.push(child);
|
||||
scope = child;
|
||||
(a, b) = run;
|
||||
}
|
||||
loop {
|
||||
let Some((a2, b2)) = self.trim_fences(scope, a, b) else { return Found::Nothing };
|
||||
if self.clean(scope, a2, b2) {
|
||||
return self.target(scope, path, a2, b2);
|
||||
}
|
||||
// Not cut cleanly at its lines: the enclosing unit is.
|
||||
trail.pop();
|
||||
let (Some((i, _)), Some(&parent)) = (path.pop(), trail.last()) else {
|
||||
return Found::Defer;
|
||||
};
|
||||
(scope, a, b) = (parent, i, i);
|
||||
}
|
||||
}
|
||||
|
||||
fn target(&self, scope: Scope<'_>, path: Vec<(usize, usize)>, a: usize, b: usize) -> Found {
|
||||
let contains_container =
|
||||
(a..=b).filter_map(|i| scope.unit(i)).any(|unit| unit.is_container());
|
||||
if contains_container {
|
||||
return Found::Defer;
|
||||
}
|
||||
Found::Target(Target { path, start: a, count: b - a + 1 })
|
||||
}
|
||||
|
||||
/// The first and last units of `scope` whose lines meet `first..=last`.
|
||||
fn met(&self, scope: Scope<'_>, first: u32, last: u32) -> Option<(usize, usize)> {
|
||||
let mut hit: Option<(usize, usize)> = None;
|
||||
for i in 0..scope.len() {
|
||||
let Some(unit) = scope.unit(i) else { continue };
|
||||
let (l0, l1) = self.lines(unit);
|
||||
if l0 <= last && first <= l1 {
|
||||
hit = Some(hit.map_or((i, i), |(a, _)| (a, i)));
|
||||
}
|
||||
}
|
||||
hit
|
||||
}
|
||||
|
||||
/// The nested scope to descend into from unit `i`: only when the
|
||||
/// selection does not touch the unit's first line, and reaches into
|
||||
/// exactly one of its scopes.
|
||||
///
|
||||
/// The last line is deliberately not asked about. A selection dragged
|
||||
/// over the final statements of a block and its closing `end` means those
|
||||
/// statements; taking the whole enclosing unit for it re-laid hundreds of
|
||||
/// unselected lines (QA note 2, lead ruling 2026-11-09). The closing line
|
||||
/// alone meets no nested unit, so it still names the unit it closes.
|
||||
fn descend<'t>(
|
||||
&self,
|
||||
scope: Scope<'t>,
|
||||
i: usize,
|
||||
first: u32,
|
||||
last: u32,
|
||||
) -> Option<(usize, Scope<'t>)> {
|
||||
let unit = scope.unit(i)?;
|
||||
let (l0, _) = self.lines(unit);
|
||||
if first <= l0 {
|
||||
return None;
|
||||
}
|
||||
let mut reached = unit
|
||||
.children()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, child)| self.met(*child, first, last).is_some());
|
||||
let only = reached.next()?;
|
||||
reached.next().is_none().then_some(only)
|
||||
}
|
||||
|
||||
/// The 1-based first and last lines of a unit's extent.
|
||||
fn lines(&self, unit: Unit<'_>) -> (u32, u32) {
|
||||
let (start, end) = unit.extent(self.src);
|
||||
let first = self.index.line_col(start as u32).0;
|
||||
let last = self.index.line_col(end.saturating_sub(1).max(start) as u32).0;
|
||||
(first, last)
|
||||
}
|
||||
|
||||
/// Drop units a fenced region of this scope reaches from both ends of the
|
||||
/// run, so no region is ever half inside the splice. `None` when nothing
|
||||
/// is left.
|
||||
fn trim_fences(&self, scope: Scope<'_>, mut a: usize, mut b: usize) -> Option<(usize, usize)> {
|
||||
while a <= b && self.fenced(scope, a) {
|
||||
a += 1;
|
||||
}
|
||||
while b > a && self.fenced(scope, b) {
|
||||
b -= 1;
|
||||
}
|
||||
(a <= b).then_some((a, b))
|
||||
}
|
||||
|
||||
/// Whether a region opened in this scope — not one nested inside the
|
||||
/// unit's own code — overlaps unit `i`'s extent.
|
||||
fn fenced(&self, scope: Scope<'_>, i: usize) -> bool {
|
||||
let Some(unit) = scope.unit(i) else { return true };
|
||||
let (start, end) = unit.extent(self.src);
|
||||
let span = unit.span();
|
||||
let (code_start, code_end) = (span.start as usize, span.end as usize);
|
||||
self.regions.iter().any(|r| {
|
||||
let overlaps = r.start < end && start < r.end;
|
||||
let nested = r.start >= code_start && r.end <= code_end;
|
||||
overlaps && !nested
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether units `a..=b` can be replaced by whole lines: only indentation
|
||||
/// before the first, nothing after the last on its line, and no sibling
|
||||
/// or dangling comment of the scope inside the bytes between.
|
||||
fn clean(&self, scope: Scope<'_>, a: usize, b: usize) -> bool {
|
||||
let (Some(first), Some(last)) = (scope.unit(a), scope.unit(b)) else { return false };
|
||||
let (start, _) = first.extent(self.src);
|
||||
let (_, end) = last.extent(self.src);
|
||||
let bol = line_start(self.src, start);
|
||||
let indent_only = self.src.get(bol..start).is_some_and(|s| s.chars().all(is_indent));
|
||||
let eol =
|
||||
self.src.get(end..).map_or(end, |rest| end + rest.find('\n').unwrap_or(rest.len()));
|
||||
let rest_blank = self.src.get(end..eol).is_some_and(|s| s.chars().all(char::is_whitespace));
|
||||
let prev_clear = a == 0 || scope.unit(a - 1).is_some_and(|u| u.extent(self.src).1 <= start);
|
||||
let next_clear = scope.unit(b + 1).is_none_or(|u| u.extent(self.src).0 >= end);
|
||||
let dangling_clear = scope
|
||||
.dangling()
|
||||
.iter()
|
||||
.all(|c| c.span.end as usize <= start || c.span.start as usize >= end);
|
||||
indent_only && rest_blank && prev_clear && next_clear && dangling_clear
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes a resolved target replaces, and the run that replaces them.
|
||||
pub(super) struct Placed<'t> {
|
||||
pub run: crate::format::Run<'t>,
|
||||
/// Start of the first unit's line: where the splice begins.
|
||||
pub bol: usize,
|
||||
/// The base indentation every line of the layout starts with, as a byte
|
||||
/// range of the source: the leading whitespace of the run's first unit
|
||||
/// that is not a directive (see [`base_indent`]).
|
||||
pub base: (usize, usize),
|
||||
/// One past the last unit's last byte.
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
/// Find `target` again in a tree, and the bytes of `src` it occupies.
|
||||
pub(super) fn resolve<'t>(src: &str, root: Scope<'t>, target: &Target) -> Option<Placed<'t>> {
|
||||
let mut scope = root;
|
||||
for &(i, k) in &target.path {
|
||||
scope = scope.unit(i)?.children().into_iter().nth(k)?;
|
||||
}
|
||||
let first = scope.unit(target.start)?;
|
||||
let last = scope.unit(target.start + target.count.checked_sub(1)?)?;
|
||||
let start = first.extent(src).0;
|
||||
let end = last.extent(src).1;
|
||||
let run = scope.run(target.start, target.count)?;
|
||||
let base = base_indent(src, scope, target, start);
|
||||
Some(Placed { run, bol: line_start(src, start), base, end })
|
||||
}
|
||||
|
||||
/// The indentation the run is laid out at: that of its first unit, unless
|
||||
/// that unit is a compiler directive and a later one is not. Directives are
|
||||
/// commonly written at column 0 while the code they guard is indented, and
|
||||
/// the code is what says where the block stands; the directive is then
|
||||
/// indented with it, as a whole-file run would.
|
||||
fn base_indent(src: &str, scope: Scope<'_>, target: &Target, start: usize) -> (usize, usize) {
|
||||
let code = (target.start..target.start + target.count)
|
||||
.filter_map(|i| scope.unit(i))
|
||||
.find(|u| !u.is_directive())
|
||||
.map(|u| u.extent(src).0);
|
||||
let own_line = |at: usize| {
|
||||
let bol = line_start(src, at);
|
||||
src.get(bol..at).is_some_and(|s| s.chars().all(is_indent)).then_some((bol, at))
|
||||
};
|
||||
code.and_then(own_line).unwrap_or((line_start(src, start), start))
|
||||
}
|
||||
|
||||
/// Every unit of a resolved target and everything nested in it, for the
|
||||
/// error-node check of a tolerant parse.
|
||||
pub(super) fn any_error(root: Scope<'_>, target: &Target) -> bool {
|
||||
let mut scope = root;
|
||||
for &(i, k) in &target.path {
|
||||
let Some(next) = scope.unit(i).and_then(|u| u.children().into_iter().nth(k)) else {
|
||||
return true;
|
||||
};
|
||||
scope = next;
|
||||
}
|
||||
(target.start..target.start + target.count).any(|i| scope.unit(i).is_none_or(unit_has_error))
|
||||
}
|
||||
|
||||
fn unit_has_error(unit: Unit<'_>) -> bool {
|
||||
unit.is_error()
|
||||
|| unit
|
||||
.children()
|
||||
.into_iter()
|
||||
.any(|s| (0..s.len()).any(|i| s.unit(i).is_none_or(unit_has_error)))
|
||||
}
|
||||
|
||||
/// The start of the line `at` is on.
|
||||
pub(super) fn line_start(src: &str, at: usize) -> usize {
|
||||
src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
fn is_indent(c: char) -> bool {
|
||||
c == ' ' || c == '\t'
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Selection formatting: lay out the smallest run of sibling items or
|
||||
//! statements the selected lines cover, at the indentation it was written
|
||||
//! at, and splice it into otherwise untouched bytes.
|
||||
//!
|
||||
//! This is what an editor's "Format Selection" wants. `format_range` (the
|
||||
//! CLI's `--lines`) re-lays whole module-level items at formatter depth;
|
||||
//! here the unit is whatever sibling list the selection lands in — a `case`
|
||||
//! inside an `always`, two statements of a function — and the parent is not
|
||||
//! touched at all. The run keeps the leading whitespace of its first line,
|
||||
//! tabs and off-grid indentation included. Every other byte of the file stays
|
||||
//! as written, the file tail included.
|
||||
//!
|
||||
//! The safety net is the usual one over the whole file: equivalence of the
|
||||
//! token streams, then convergence by replaying the located *target* (a path
|
||||
//! in the tree, not line numbers) on the output. Full spec:
|
||||
//! `docs/features/selection-formatting/README.md`.
|
||||
|
||||
mod locate;
|
||||
mod scope;
|
||||
|
||||
use crate::fence;
|
||||
use crate::format::{format_range, print_run, Config, FormatError};
|
||||
use crate::range::LineRanges;
|
||||
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
use locate::{any_error, resolve, Found, Locator, Target};
|
||||
use scope::Scope;
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::ParseDiagnostic;
|
||||
|
||||
/// Format the smallest runs of sibling items or statements `lines` covers,
|
||||
/// each at the indentation its first line was written at, leaving every other
|
||||
/// byte of `source` as it is.
|
||||
///
|
||||
/// A selection reaching a module or package item as a whole is handed to
|
||||
/// [`format_range`] unchanged. A file that does not parse is formatted only
|
||||
/// where the selection is clear of every parse error; otherwise, as on any
|
||||
/// failed check, the caller gets an error and must keep the original text.
|
||||
///
|
||||
/// Same stack requirement as [`crate::format_source`].
|
||||
pub fn format_selection(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
lines: &LineRanges,
|
||||
) -> Result<String, FormatError> {
|
||||
let tree = Tree::parse(source).map_err(FormatError::Source)?;
|
||||
let Some(root) = Scope::root(&tree.file) else {
|
||||
return format_range(source, config, lines);
|
||||
};
|
||||
let locator = Locator::new(source, fence::collect(source, &tree.file));
|
||||
let Ok(targets) = select(&locator, root, source, lines) else {
|
||||
return format_range(source, config, lines);
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Ok(source.to_string());
|
||||
}
|
||||
tree.check_clear(source, root, &targets)?;
|
||||
let output = splice(source, &tree.file, root, config, &targets)
|
||||
.ok_or_else(|| lost("the selection could not be cut out of its lines"))?;
|
||||
verify_equivalence(source, &output)?;
|
||||
let again = replay(&output, config, &targets)?;
|
||||
verify_convergence(&output, &again)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Format the output a second time with the same targets, found again by
|
||||
/// their position in its tree.
|
||||
fn replay(output: &str, config: &Config, targets: &[Target]) -> Result<String, FormatError> {
|
||||
let tree = Tree::parse(output).map_err(VerificationError::Reparse)?;
|
||||
let root = Scope::root(&tree.file).ok_or_else(|| lost("the output is not the same kind"))?;
|
||||
tree.check_clear(output, root, targets)?;
|
||||
splice(output, &tree.file, root, config, targets)
|
||||
.ok_or_else(|| lost("the selection could not be found again in the output"))
|
||||
}
|
||||
|
||||
fn lost(why: &str) -> FormatError {
|
||||
FormatError::Selection(format!("cannot format the selection: {why}"))
|
||||
}
|
||||
|
||||
/// A parsed text: strictly when it parses, tolerantly when it does not.
|
||||
struct Tree {
|
||||
file: SourceFile,
|
||||
/// The tolerant parse's diagnostics; empty for a strict parse.
|
||||
diagnostics: Vec<ParseDiagnostic>,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn parse(src: &str) -> Result<Tree, vlog_parser::Error> {
|
||||
match vlog_parser::parse_source(src) {
|
||||
Ok(file) => Ok(Tree { file, diagnostics: Vec::new() }),
|
||||
Err(e) => {
|
||||
let (file, diagnostics) = vlog_parser::parse_source_tolerant(src);
|
||||
// A tolerant parse that finds nothing wrong where the strict
|
||||
// one failed is not a tree to trust.
|
||||
if diagnostics.is_empty() {
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Tree { file, diagnostics })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse when a parse error lies inside any target: its layout would
|
||||
/// rest on error recovery's guess.
|
||||
fn check_clear(
|
||||
&self,
|
||||
src: &str,
|
||||
root: Scope<'_>,
|
||||
targets: &[Target],
|
||||
) -> Result<(), FormatError> {
|
||||
if self.diagnostics.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for target in targets {
|
||||
let placed = resolve(src, root, target).ok_or_else(|| lost("internal: lost target"))?;
|
||||
let (lo, hi) = (placed.bol, placed.end);
|
||||
let hit = self
|
||||
.diagnostics
|
||||
.iter()
|
||||
.find(|d| (d.span.start as usize) <= hi && lo <= d.span.end as usize);
|
||||
if let Some(d) = hit {
|
||||
return Err(FormatError::Selection(format!(
|
||||
"cannot format the selection: it contains a syntax error at {}:{}: {}",
|
||||
d.line, d.col, d.message
|
||||
)));
|
||||
}
|
||||
if any_error(root, target) {
|
||||
return Err(lost("it contains text that does not parse"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The request goes to `format_range` whole.
|
||||
struct Defer;
|
||||
|
||||
/// Locate one target per selected span; targets whose bytes overlap are
|
||||
/// re-selected from the hull of their spans.
|
||||
fn select(
|
||||
locator: &Locator<'_>,
|
||||
root: Scope<'_>,
|
||||
src: &str,
|
||||
lines: &LineRanges,
|
||||
) -> Result<Vec<Target>, Defer> {
|
||||
let mut picked: Vec<Picked> = Vec::new();
|
||||
for &span in lines.spans() {
|
||||
picked.extend(pick(locator, root, src, span)?);
|
||||
}
|
||||
loop {
|
||||
picked.sort_by_key(|p| p.bytes.0);
|
||||
let Some(i) = (1..picked.len()).find(|&i| picked[i].bytes.0 < picked[i - 1].bytes.1) else {
|
||||
break;
|
||||
};
|
||||
let (a, b) = (picked.remove(i), picked.remove(i - 1));
|
||||
let hull = (a.span.0.min(b.span.0), a.span.1.max(b.span.1));
|
||||
picked.extend(pick(locator, root, src, hull)?);
|
||||
}
|
||||
Ok(picked.into_iter().map(|p| p.target).collect())
|
||||
}
|
||||
|
||||
/// One located target, with the line span that chose it and the bytes it
|
||||
/// replaces.
|
||||
struct Picked {
|
||||
span: (u32, u32),
|
||||
target: Target,
|
||||
bytes: (usize, usize),
|
||||
}
|
||||
|
||||
/// The target one span selects, if any.
|
||||
fn pick(
|
||||
locator: &Locator<'_>,
|
||||
root: Scope<'_>,
|
||||
src: &str,
|
||||
span: (u32, u32),
|
||||
) -> Result<Option<Picked>, Defer> {
|
||||
match locator.locate(root, span) {
|
||||
Found::Nothing => Ok(None),
|
||||
Found::Defer => Err(Defer),
|
||||
Found::Target(target) => {
|
||||
// Resolving a target in the tree it was found in cannot fail; if
|
||||
// it ever did, the conservative answer is the old engine.
|
||||
let placed = resolve(src, root, &target).ok_or(Defer)?;
|
||||
Ok(Some(Picked { span, target, bytes: (placed.bol, placed.end) }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace every target's bytes with its layout, bottom-up so the earlier
|
||||
/// offsets stay valid. `None` when a target cannot be found or cut.
|
||||
fn splice(
|
||||
src: &str,
|
||||
file: &SourceFile,
|
||||
root: Scope<'_>,
|
||||
config: &Config,
|
||||
targets: &[Target],
|
||||
) -> Option<String> {
|
||||
let mut placed = targets.iter().map(|t| resolve(src, root, t)).collect::<Option<Vec<_>>>()?;
|
||||
placed.sort_by_key(|p| std::cmp::Reverse(p.bol));
|
||||
let mut out = src.to_string();
|
||||
let mut floor = src.len();
|
||||
for p in placed {
|
||||
let base = src.get(p.base.0..p.base.1)?;
|
||||
if p.end > floor || !base.chars().all(|c| c == ' ' || c == '\t') {
|
||||
return None;
|
||||
}
|
||||
let mut text = print_run(src, file, config, p.run, base);
|
||||
if uses_crlf(src, p.bol, p.end) {
|
||||
text = to_crlf(&text);
|
||||
}
|
||||
out = format!("{}{}{}", out.get(..p.bol)?, text, out.get(p.end..)?);
|
||||
floor = p.bol;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Whether the lines around a target end in `\r\n`: the line ending after
|
||||
/// it, or before it when it ends the file.
|
||||
fn uses_crlf(src: &str, bol: usize, end: usize) -> bool {
|
||||
match src.get(end..).and_then(|rest| rest.find('\n')) {
|
||||
Some(i) => src.get(..end + i).is_some_and(|s| s.ends_with('\r')),
|
||||
None => src.get(..bol).is_some_and(|s| s.ends_with("\r\n")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn every bare `\n` into `\r\n`; text copied from the source keeps the
|
||||
/// `\r\n` it already had.
|
||||
fn to_crlf(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len() + text.len() / 16);
|
||||
let mut prev = '\0';
|
||||
for c in text.chars() {
|
||||
if c == '\n' && prev != '\r' {
|
||||
out.push('\r');
|
||||
}
|
||||
out.push(c);
|
||||
prev = c;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The sibling lists a selection can land in, and the units they hold.
|
||||
//!
|
||||
//! A *scope* is a sibling list exactly as `fence.rs` defines one — an item
|
||||
//! list (file, module, package, generate region, generate `begin`…`end`,
|
||||
//! class) or a statement list (`begin`…`end`, `fork`…`join`, a function or
|
||||
//! task body). A *unit* is one item or statement of such a list. The match
|
||||
//! arms below mirror `fence::scan_nested` / `scan_nested_stmt` /
|
||||
//! `scan_gen_block`: a single-statement body or a block-less generate item is
|
||||
//! not a scope, so it is walked *through* to the scopes it reaches. An arm
|
||||
//! missing here only makes a selection coarser, never wrong.
|
||||
|
||||
use crate::fence;
|
||||
use crate::format::Run;
|
||||
use vlog_parser::ast::{
|
||||
GenBlock, GenElse, GenIf, Item, ItemKind, Meta, SourceFile, Stmt, StmtKind,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
/// One sibling list. Items carry the AST depth `item_seq` lays them out at.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Scope<'t> {
|
||||
Items(&'t [Item], &'t [Comment], usize),
|
||||
Stmts(&'t [Stmt], &'t [Comment]),
|
||||
}
|
||||
|
||||
/// One member of a scope.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Unit<'t> {
|
||||
Item(&'t Item, usize),
|
||||
Stmt(&'t Stmt),
|
||||
}
|
||||
|
||||
impl<'t> Scope<'t> {
|
||||
/// The scope a whole file is, or `None` for a fragment whose elements
|
||||
/// are not items or statements (enum members, cover items).
|
||||
pub(super) fn root(file: &'t SourceFile) -> Option<Scope<'t>> {
|
||||
match &file.fragment {
|
||||
None => Some(Scope::Items(&file.items, &file.dangling, 0)),
|
||||
Some(vlog_parser::ast::Fragment::Statements(stmts)) => {
|
||||
Some(Scope::Stmts(stmts, &file.dangling))
|
||||
}
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn len(&self) -> usize {
|
||||
match self {
|
||||
Scope::Items(items, ..) => items.len(),
|
||||
Scope::Stmts(stmts, _) => stmts.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn unit(&self, i: usize) -> Option<Unit<'t>> {
|
||||
match *self {
|
||||
Scope::Items(items, _, depth) => items.get(i).map(|item| Unit::Item(item, depth)),
|
||||
Scope::Stmts(stmts, _) => stmts.get(i).map(Unit::Stmt),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn dangling(&self) -> &'t [Comment] {
|
||||
match *self {
|
||||
Scope::Items(_, dangling, _) | Scope::Stmts(_, dangling) => dangling,
|
||||
}
|
||||
}
|
||||
|
||||
/// The units `start..start + count` as something the printers take.
|
||||
pub(super) fn run(&self, start: usize, count: usize) -> Option<Run<'t>> {
|
||||
let end = start.checked_add(count)?;
|
||||
match *self {
|
||||
Scope::Items(items, _, depth) => items.get(start..end).map(|s| Run::Items(s, depth)),
|
||||
Scope::Stmts(stmts, _) => stmts.get(start..end).map(Run::Stmts),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'t> Unit<'t> {
|
||||
fn meta(&self) -> &'t Meta {
|
||||
match self {
|
||||
Unit::Item(item, _) => &item.meta,
|
||||
Unit::Stmt(stmt) => &stmt.meta,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn span(&self) -> TextRange {
|
||||
match self {
|
||||
Unit::Item(item, _) => item.span,
|
||||
Unit::Stmt(stmt) => stmt.span,
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit's bytes: its first leading comment or attribute through the
|
||||
/// comments written after it on the same line.
|
||||
pub(super) fn extent(&self, src: &str) -> (usize, usize) {
|
||||
let meta = self.meta();
|
||||
let span = self.span();
|
||||
let mut start = span.start;
|
||||
if let Some(c) = meta.leading.first() {
|
||||
start = start.min(c.span.start);
|
||||
}
|
||||
if let Some(a) = meta.attrs.first() {
|
||||
start = start.min(a.span.start);
|
||||
}
|
||||
// In a CRLF file a trailing `//` comment's line ends `\r\n`, and the
|
||||
// scan above stops at the `\n`. The `\r` is the line ending, not the
|
||||
// unit: the layout does not write it, so the splice must not eat it.
|
||||
let mut end = fence::with_trailing_comments(src, span.end as usize);
|
||||
while end > span.end as usize && src.as_bytes().get(end - 1) == Some(&b'\r') {
|
||||
end -= 1;
|
||||
}
|
||||
(start as usize, end)
|
||||
}
|
||||
|
||||
/// Whether the unit is a construct `format_range` splits (a module or a
|
||||
/// package), which a selection defers to it.
|
||||
pub(super) fn is_container(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Unit::Item(Item { kind: ItemKind::Module(_) | ItemKind::Package { .. }, .. }, _)
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the unit is a compiler directive (`` `ifdef `` and kin),
|
||||
/// which is often written at column 0 whatever the code around it does.
|
||||
pub(super) fn is_directive(&self) -> bool {
|
||||
match self {
|
||||
Unit::Item(item, _) => matches!(item.kind, ItemKind::Directive(_)),
|
||||
Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Directive(_)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the unit is a node error recovery made of unparsable text.
|
||||
pub(super) fn is_error(&self) -> bool {
|
||||
match self {
|
||||
Unit::Item(item, _) => matches!(item.kind, ItemKind::Error(_)),
|
||||
Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Error(_)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The scopes directly nested in this unit, in source order.
|
||||
pub(super) fn children(&self) -> Vec<Scope<'t>> {
|
||||
let mut out = Vec::new();
|
||||
match *self {
|
||||
Unit::Item(item, depth) => item_scopes(item, depth, &mut out),
|
||||
Unit::Stmt(stmt) => stmt_scopes(stmt, &mut out),
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The scopes nested in one item at `depth`, at the depth `item_kind` lays
|
||||
/// their items out at.
|
||||
fn item_scopes<'t>(item: &'t Item, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => out.push(Scope::Items(&m.items, &m.dangling, depth + 1)),
|
||||
ItemKind::Package { items, dangling, .. }
|
||||
| ItemKind::GenerateRegion { items, dangling } => {
|
||||
out.push(Scope::Items(items, dangling, depth + 1))
|
||||
}
|
||||
ItemKind::GenBlock(b) => gen_block_scopes(b, depth, out),
|
||||
ItemKind::GenIf(g) => gen_if_scopes(g, depth, out),
|
||||
ItemKind::GenFor(g) => gen_block_scopes(&g.body, depth, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
for i in &g.items {
|
||||
gen_block_scopes(&i.body, depth + 1, out);
|
||||
}
|
||||
}
|
||||
ItemKind::Class(c) => out.push(Scope::Items(&c.items, &c.dangling, depth + 1)),
|
||||
ItemKind::Function(f) => out.push(Scope::Stmts(&f.stmts, &f.dangling)),
|
||||
ItemKind::Task(t) => out.push(Scope::Stmts(&t.stmts, &t.dangling)),
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
stmt_scopes(stmt, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_if_scopes<'t>(g: &'t GenIf, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
gen_block_scopes(&g.then, depth, out);
|
||||
match g.els.as_deref() {
|
||||
Some(GenElse::If(_, inner)) => gen_if_scopes(inner, depth, out),
|
||||
Some(GenElse::Block(b)) => gen_block_scopes(b, depth, out),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate `begin`…`end` is a scope one level in; a block-less body's
|
||||
/// one item is laid out one level in too, and walked through.
|
||||
fn gen_block_scopes<'t>(b: &'t GenBlock, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
if b.is_block {
|
||||
out.push(Scope::Items(&b.items, &b.dangling, depth + 1));
|
||||
} else {
|
||||
for item in &b.items {
|
||||
item_scopes(item, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement lists one statement holds, walking through every
|
||||
/// single-statement body.
|
||||
fn stmt_scopes<'t>(stmt: &'t Stmt, out: &mut Vec<Scope<'t>>) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
|
||||
out.push(Scope::Stmts(stmts, dangling))
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
stmt_scopes(then, out);
|
||||
if let Some(e) = els {
|
||||
stmt_scopes(e, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
for s in then.iter().chain(els.iter()) {
|
||||
stmt_scopes(s, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for i in items {
|
||||
stmt_scopes(&i.stmt, out);
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. }
|
||||
| StmtKind::Labeled { stmt: body, .. } => stmt_scopes(body, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
stmt_scopes(inner, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! The formatter still refuses every unfinished-connection shape the tolerant
|
||||
//! parser now keeps inside its own entry (TODO §68.2,
|
||||
//! `docs/features/port-entry-grace/README.md`).
|
||||
//!
|
||||
//! The recovery is the editor's: it makes the rest of a half-typed file
|
||||
//! colour and lint as if the entry were complete. The formatter never reads
|
||||
//! the tolerant tree, and these pin that a buffer with a half-typed entry in
|
||||
//! it is refused whole — never printed with the entry "completed".
|
||||
|
||||
use vlog_formatter::{format_source, Config};
|
||||
|
||||
const UNFINISHED: &[(&str, &str)] = &[
|
||||
(
|
||||
"lone dot before the next entry",
|
||||
"module m;\n sub u0 (.a(x),\n .\n .b(y));\nendmodule\n",
|
||||
),
|
||||
("lone dot before a comma", "module m;\n sub u0 (.a(x), ., .b(y));\nendmodule\n"),
|
||||
("lone dot before the close", "module m;\n sub u0 (.a(x), .);\nendmodule\n"),
|
||||
(
|
||||
"open value before the next entry",
|
||||
"module m;\n sub u0 (.a(x), .po(\n .b(y));\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"open value with a partial name",
|
||||
"module m;\n sub u0 (.a(x), .po(z\n .b(y));\nendmodule\n",
|
||||
),
|
||||
("open value before the close", "module m;\n sub u0 (.a(x), .po(\n );\nendmodule\n"),
|
||||
("open override value", "module m;\n sub #(.W(8), .D(\n .E(1)) u0 (.a(x));\nendmodule\n"),
|
||||
("missing comma across lines", "module m;\n sub u0 (.a(x)\n .b(y));\nendmodule\n"),
|
||||
("missing comma on one line", "module m;\n sub u0 (.a(x) .b(y));\nendmodule\n"),
|
||||
(
|
||||
"implicit entry missing its comma",
|
||||
"module m;\n sub u0 (.a(x), .po\n .b(y));\nendmodule\n",
|
||||
),
|
||||
("trailing comma", "module m;\n sub u0 (.a(x), .b(y),);\nendmodule\n"),
|
||||
("trailing comma in an override list", "module m;\n sub #(.W(1),) u0 (.a(x));\nendmodule\n"),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn every_unfinished_connection_is_still_refused() {
|
||||
for (name, src) in UNFINISHED {
|
||||
let got = format_source(src, &Config::default());
|
||||
assert!(got.is_err(), "{name}: the formatter printed a half-typed entry:\n{got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The completed spelling of the same entries formats — so the refusal above
|
||||
/// is about the unfinished entry and nothing else in these sources.
|
||||
#[test]
|
||||
fn the_completed_entries_format() {
|
||||
let src = "module m;\n sub u0 (.a(x), .po(), .b(y));\nendmodule\n";
|
||||
assert!(format_source(src, &Config::default()).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Selection formatting (`format_selection`): the smallest run of sibling
|
||||
//! items or statements a selection covers is laid out at the indentation it
|
||||
//! was written at, and every other byte of the file stays as written.
|
||||
//!
|
||||
//! Spec: `docs/features/selection-formatting/README.md`.
|
||||
|
||||
use vlog_formatter::{format_range, format_selection, verify_equivalence, Config, LineRanges};
|
||||
|
||||
fn select_with(src: &str, spec: &str, config: &Config) -> Result<String, String> {
|
||||
let lines = LineRanges::parse(spec).expect("line spec");
|
||||
format_selection(src, config, &lines).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn select(src: &str, spec: &str) -> String {
|
||||
select_with(src, spec, &Config::default()).expect("formats")
|
||||
}
|
||||
|
||||
/// Format, then format the result again with the same lines: the second run
|
||||
/// must change nothing.
|
||||
fn fixed(src: &str, spec: &str) -> String {
|
||||
let out = select(src, spec);
|
||||
assert_eq!(select(&out, spec), out, "a second run must change nothing");
|
||||
out
|
||||
}
|
||||
|
||||
/// Lines `first..=last` (1-based) of `src` are the target: everything before
|
||||
/// and after must come back byte for byte, and the returned middle is what
|
||||
/// replaced them.
|
||||
fn middle<'a>(src: &str, out: &'a str, first: usize, last: usize) -> &'a str {
|
||||
let lines: Vec<&str> = src.split_inclusive('\n').collect();
|
||||
let head: String = lines[..first - 1].concat();
|
||||
let tail: String = lines[last..].concat();
|
||||
assert!(out.starts_with(&head), "bytes before the target changed:\n{out}");
|
||||
assert!(out.ends_with(&tail), "bytes after the target changed:\n{out}");
|
||||
assert!(out.len() >= head.len() + tail.len(), "target overlaps the kept bytes:\n{out}");
|
||||
&out[head.len()..out.len() - tail.len()]
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The owner's shapes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A file indented four spaces, as many hand-written files are.
|
||||
const FOUR: &str = "\
|
||||
module m;
|
||||
reg [3:0] q;
|
||||
always @(posedge clk) begin
|
||||
if (rst) q<=0;
|
||||
else begin
|
||||
case (sel)
|
||||
2'b00: q<=a;
|
||||
2'b01 : q <= b;
|
||||
default:q<=c;
|
||||
endcase
|
||||
end
|
||||
end
|
||||
assign y=q;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_whole_always_keeps_its_indentation_in_a_four_space_file() {
|
||||
let out = fixed(FOUR, "3-12");
|
||||
let mid = middle(FOUR, &out, 3, 12);
|
||||
assert_eq!(
|
||||
mid,
|
||||
" always @(posedge clk) begin
|
||||
if (rst) q <= 0;
|
||||
else begin
|
||||
case (sel)
|
||||
2'b00: q <= a;
|
||||
2'b01: q <= b;
|
||||
default: q <= c;
|
||||
endcase
|
||||
end
|
||||
end
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_case_inside_an_always_is_the_only_thing_laid_out() {
|
||||
let out = fixed(FOUR, "6-10");
|
||||
let mid = middle(FOUR, &out, 6, 10);
|
||||
assert_eq!(
|
||||
mid,
|
||||
" case (sel)
|
||||
2'b00: q <= a;
|
||||
2'b01: q <= b;
|
||||
default: q <= c;
|
||||
endcase
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_inside_a_generate_for_is_laid_out_alone() {
|
||||
let src = "\
|
||||
module m;
|
||||
generate
|
||||
for (genvar i=0;i<4;i++) begin : g
|
||||
always @(posedge clk) q[i]<=d[i];
|
||||
assign w[i]=q[i];
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "4");
|
||||
let mid = middle(src, &out, 4, 4);
|
||||
assert_eq!(mid, " always @(posedge clk) q[i] <= d[i];\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statements_inside_a_function_are_laid_out_without_the_function() {
|
||||
let src = "\
|
||||
module m;
|
||||
function automatic int f(input int a);
|
||||
int r;
|
||||
r=a+1;
|
||||
return r;
|
||||
endfunction
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "4-5");
|
||||
let mid = middle(src, &out, 4, 5);
|
||||
assert_eq!(mid, " r = a + 1;\n return r;\n");
|
||||
assert!(out.contains(" int r;\n"), "the unselected statement stays: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_inside_an_else_branch_is_laid_out_alone() {
|
||||
let src = "\
|
||||
module m;
|
||||
always @* begin
|
||||
if (a) x = 1;
|
||||
else begin
|
||||
y=2;
|
||||
z = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "5-6");
|
||||
let mid = middle(src, &out, 5, 6);
|
||||
assert_eq!(mid, " y = 2;\n z = 3;\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Indentation
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn tab_indentation_is_reproduced_as_written() {
|
||||
let src = "module m;\n\talways @* begin\n\t\tx=1;\n\t\tif (a) begin\n\t\t\ty=2;\n\t\tend\n\tend\nendmodule\n";
|
||||
let out = fixed(src, "2-7");
|
||||
let mid = middle(src, &out, 2, 7);
|
||||
assert_eq!(
|
||||
mid,
|
||||
"\talways @(*) begin\n\t x = 1;\n\t if (a) begin\n\t y = 2;\n\t end\n\tend\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_grid_indentation_is_kept() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2-4");
|
||||
assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n x = 1;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_misindented_parent_does_not_move_the_selection() {
|
||||
let src = "module m;\nalways @* begin\n x=1;\n y = 2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 3, 3), " x = 1;\n");
|
||||
assert!(out.contains("\n y = 2;\n"), "the sibling is untouched: {out}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Partial selections
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn one_line_inside_a_case_lays_out_the_case() {
|
||||
let out = fixed(FOUR, "8");
|
||||
let mid = middle(FOUR, &out, 6, 10);
|
||||
assert!(mid.starts_with(" case (sel)\n"), "{mid}");
|
||||
assert!(mid.contains(" 2'b01: q <= b;\n"), "{mid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_only_range_formats_the_statement_under_it() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "4");
|
||||
assert_eq!(out, "module m;\n always @* begin\n x=1;\n y = 2;\n end\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_ending_on_the_end_line_takes_only_the_statements_it_covers() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "4-5");
|
||||
assert_eq!(middle(src, &out, 4, 4), " y = 2;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_line_alone_takes_the_unit_it_closes() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "5");
|
||||
assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_starting_on_the_first_line_takes_the_whole_unit() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "2-3");
|
||||
assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_lines_alone_change_nothing() {
|
||||
let src = "module m;\n wire a;\n\n\n wire b;\nendmodule\n";
|
||||
assert_eq!(select(src, "3-4"), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leading_and_trailing_comments_travel_with_their_unit() {
|
||||
let src = "module m;\n always @* begin\n // why\n x=1; // what\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "4");
|
||||
assert_eq!(middle(src, &out, 3, 4), " // why\n x = 1; // what\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_after_begin_is_not_line_clean_and_the_parent_is_taken() {
|
||||
let src = "module m;\n always @* begin // note\n x=1;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n // note\n x = 1;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_statements_on_one_line_are_taken_together() {
|
||||
let src = "module m;\n always @* begin\n x=1; y=2;\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 3, 3), " x = 1;\n y = 2;\n");
|
||||
assert!(out.contains(" z=3;\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_across_two_branches_takes_the_whole_if() {
|
||||
let src = "module m;\n always @* begin\n if (a) begin\n x=1;\n end else begin\n y=2;\n end\n end\nendmodule\n";
|
||||
let out = fixed(src, "4-6");
|
||||
let mid = middle(src, &out, 3, 7);
|
||||
assert_eq!(mid, " if (a) begin\n x = 1;\n end else begin\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Fences
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_fence_inside_the_target_is_emitted_as_written() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n // lucisv: off\n y = 2;\n // lucisv: on\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2-8");
|
||||
assert!(out.contains(" y = 2;\n"), "{out}");
|
||||
assert!(out.contains(" x = 1;\n") && out.contains(" z = 3;\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_around_the_target_wins() {
|
||||
let src = "module m;\n // lucisv: off\n always @* begin\n x=1;\n end\n // lucisv: on\nendmodule\n";
|
||||
assert_eq!(select(src, "4"), src);
|
||||
assert_eq!(select(src, "3-5"), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_straddling_the_target_trims_the_fenced_units() {
|
||||
let src = "module m;\n always @* begin\n a=1;\n b=2;\n // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n";
|
||||
// Lines 3-6 meet a, b, and c (fenced): c is trimmed off the end.
|
||||
let out = fixed(src, "3-6");
|
||||
assert_eq!(middle(src, &out, 3, 4), " a = 1;\n b = 2;\n");
|
||||
assert!(out.ends_with(
|
||||
" // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n"
|
||||
));
|
||||
// Lines 6-8 meet c (fenced) and d — whose extent starts at `on`: both go.
|
||||
assert_eq!(select(src, "6-8"), src);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Deferral to `format_range`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_module_header_or_whole_module_selection_is_format_range() {
|
||||
let src = "module m(input a,output b);\n wire x;\n assign x=a;\nendmodule\nmodule n;\nendmodule\n";
|
||||
for spec in ["1", "1-4", "1-6", "4", "2-5"] {
|
||||
let lines = LineRanges::parse(spec).expect("spec");
|
||||
let range = format_range(src, &Config::default(), &lines).expect("range formats");
|
||||
assert_eq!(select(src, spec), range, "spec {spec}");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Files that do not parse
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
const BROKEN: &str = "\
|
||||
module m;
|
||||
always @* begin
|
||||
x=1;
|
||||
end
|
||||
assign y = ;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn an_error_outside_the_target_does_not_stop_it() {
|
||||
let out = fixed(BROKEN, "3");
|
||||
assert_eq!(middle(BROKEN, &out, 3, 3), " x = 1;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_inside_the_target_refuses() {
|
||||
let err = select_with(BROKEN, "5", &Config::default()).expect_err("refused");
|
||||
assert!(err.contains("syntax error") || err.contains("parse"), "{err}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Idempotence and multiple ranges
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn formatting_the_same_target_twice_changes_nothing() {
|
||||
for spec in ["3-12", "6-10", "4", "8", "13"] {
|
||||
fixed(FOUR, spec);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_ranges_lay_out_two_targets_and_nothing_between() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3,5");
|
||||
assert_eq!(
|
||||
out,
|
||||
"module m;\n always @* begin\n x = 1;\n y=2;\n z = 3;\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_targets_are_reselected_from_their_hull() {
|
||||
// `4` selects the inner statement, `2` the always holding it.
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2,4");
|
||||
assert_eq!(out, "module m;\n always @(*) begin\n x = 1;\n y = 2;\n end\nendmodule\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Masked-corruption attacks on the splice
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Either a correct result (equivalent to the input, a fixed point) or a
|
||||
/// refusal — never silently wrong.
|
||||
fn correct_or_refused(src: &str, spec: &str) -> Option<String> {
|
||||
let out = select_with(src, spec, &Config::default()).ok()?;
|
||||
verify_equivalence(src, &out).expect("the result is equivalent to the input");
|
||||
assert_eq!(select(&out, spec), out, "and a fixed point");
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comment_on_the_last_line_survives() {
|
||||
let src = "module m;\n always @* begin\n x=1; /* a */ /* b */\n end\nendmodule\n";
|
||||
let out = correct_or_refused(src, "3").expect("formats");
|
||||
assert!(out.contains("/* a */") && out.contains("/* b */"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_are_kept() {
|
||||
let src = "module m;\r\n always @* begin\r\n x=1;\r\n y=2;\r\n end\r\nendmodule\r\n";
|
||||
let out = correct_or_refused(src, "3-4").expect("formats");
|
||||
assert_eq!(
|
||||
out,
|
||||
"module m;\r\n always @* begin\r\n x = 1;\r\n y = 2;\r\n end\r\nendmodule\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending() {
|
||||
// QA finding 1: the `\r` after a trailing `//` comment is the line
|
||||
// ending, not part of the unit, so the splice leaves it in place.
|
||||
let src = "module m;\r\n initial begin\r\n a = 1; // c\r\n b = 2; // d\r\n end\r\nendmodule\r\n";
|
||||
let out = correct_or_refused(src, "3-4").expect("formats");
|
||||
assert_eq!(out, src.replace("b = 2", "b = 2"));
|
||||
let out = correct_or_refused(src, "4").expect("formats");
|
||||
assert_eq!(out, src.replace("b = 2", "b = 2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_block_comment_inside_the_target_survives() {
|
||||
let src =
|
||||
"module m;\n always @* begin\n /* one\n two */\n x=1;\n end\nendmodule\n";
|
||||
let out = correct_or_refused(src, "2-6").expect("formats");
|
||||
assert!(out.contains("/* one\n two */"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_string_inside_the_target_is_kept_or_refused() {
|
||||
let src =
|
||||
"module m;\n initial begin\n $display(\"a\\\n b\");\n x=1;\n end\nendmodule\n";
|
||||
if let Some(out) = correct_or_refused(src, "2-6") {
|
||||
assert!(out.contains("\"a\\\n b\""), "{out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_at_the_end_of_a_file_without_a_final_newline() {
|
||||
let src = "always @* begin\n x=1;\nend";
|
||||
let out = correct_or_refused(src, "2").expect("formats");
|
||||
assert_eq!(out, "always @* begin\n x = 1;\nend");
|
||||
let src = "wire a;\nassign b=a;";
|
||||
let out = correct_or_refused(src, "2").expect("formats");
|
||||
assert_eq!(out, "wire a;\nassign b = a;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_characters_before_the_target_do_not_shift_it() {
|
||||
let src = "module m;\n // café — ünïcode\n wire a; // ß\n assign b=a;\nendmodule\n";
|
||||
let out = correct_or_refused(src, "4").expect("formats");
|
||||
assert_eq!(middle(src, &out, 4, 4), " assign b = a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_safety_net_rejects_a_mis_spliced_output() {
|
||||
// An off-by-one at the end of the splice duplicates the `;`; at the
|
||||
// start it drops the trailing comment's first byte. Both must be caught.
|
||||
let src = "module m;\n always @* begin\n x=1; // c\n end\nendmodule\n";
|
||||
let duplicated = "module m;\n always @* begin\n x = 1;; // c\n end\nendmodule\n";
|
||||
assert!(verify_equivalence(src, duplicated).is_err());
|
||||
let dropped = "module m;\n always @* begin\n x = 1; c\n end\nendmodule\n";
|
||||
assert!(verify_equivalence(src, dropped).is_err());
|
||||
let crlf = "module m;\r\n always @* begin\r\n /* one\r\n two */\r\n x=1;\r\n end\r\nendmodule\r\n";
|
||||
let lost_comment_line =
|
||||
"module m;\r\n always @* begin\r\n /* one */\r\n x = 1;\r\n end\r\nendmodule\r\n";
|
||||
assert!(verify_equivalence(crlf, lost_comment_line).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_zero_directive_does_not_set_the_indentation_of_the_code_it_guards() {
|
||||
let src = "module m;\n`ifdef A\n wire a;\n`endif\n wire b;\nendmodule\n";
|
||||
let out = fixed(src, "2-4");
|
||||
// The code says where the block stands; the directives are indented with
|
||||
// it, as a whole-file run indents them.
|
||||
assert_eq!(middle(src, &out, 2, 4), " `ifdef A\n wire a;\n `endif\n");
|
||||
}
|
||||
@@ -4,7 +4,8 @@ use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_semantic::{ScopeKind, SymbolKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{Duplicate, ScopeId, ScopeKind, Semantics, Symbol, SymbolKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct DuplicateDeclaration;
|
||||
@@ -60,7 +61,7 @@ impl Rule for DuplicateDeclaration {
|
||||
let mut out = Vec::new();
|
||||
for duplicate in semantics.duplicates() {
|
||||
let Some(first) = semantics.symbol(duplicate.first) else { continue };
|
||||
if !plain(duplicate.kind) || !plain(first.kind) {
|
||||
if !collides(semantics, duplicate, first) {
|
||||
continue;
|
||||
}
|
||||
let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind);
|
||||
@@ -85,6 +86,72 @@ impl Rule for DuplicateDeclaration {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a declaration `duplicate` written after `first`, of one name in
|
||||
/// one scope, is an error: both of a kind written once and once only
|
||||
/// ([`plain`]); or a **block label** beside any other kind of declaration —
|
||||
/// a net, a variable, a parameter, an instance, a port, a genvar, a typedef,
|
||||
/// a function or task (a label and those share one namespace, IEEE 1800
|
||||
/// §3.13); or two block labels unless both may be arms of one generate
|
||||
/// `if`/`case`, of which only one elaborates (§27.5). A procedural block and
|
||||
/// a `for` generate block are never such an arm, whichever comes first
|
||||
/// (generate-label-rename F3, R4; review L-2).
|
||||
fn collides(semantics: &Semantics, duplicate: &Duplicate, first: &Symbol) -> bool {
|
||||
match (duplicate.kind == SymbolKind::Block, first.kind == SymbolKind::Block) {
|
||||
(false, false) => plain(duplicate.kind) && plain(first.kind),
|
||||
(true, true) => {
|
||||
let second = shape_at(semantics, duplicate.scope, duplicate.name_span);
|
||||
shape_of(semantics, first) != LabelShape::Arm || second != LabelShape::Arm
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a block label names, as far as two labels of one name may coexist.
|
||||
#[derive(PartialEq)]
|
||||
enum LabelShape {
|
||||
/// A procedural `begin`/`fork` or a statement label.
|
||||
Procedural,
|
||||
/// A generate block that may be one arm of an `if`/`case`.
|
||||
Arm,
|
||||
/// A `for` generate block: its scope hangs off the loop header.
|
||||
Loop,
|
||||
}
|
||||
|
||||
/// The shape of a declared label, read off the scope it opened.
|
||||
fn shape_of(semantics: &Semantics, label: &Symbol) -> LabelShape {
|
||||
let Some(child) = label.child_scope.and_then(|id| semantics.scope(id)) else {
|
||||
return LabelShape::Procedural;
|
||||
};
|
||||
match (child.kind, child.parent == Some(label.scope)) {
|
||||
(ScopeKind::Generate, true) => LabelShape::Arm,
|
||||
(ScopeKind::Generate, false) => LabelShape::Loop,
|
||||
_ => LabelShape::Procedural,
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape of a redeclared label, which owns no scope: read off the scope
|
||||
/// written at its name — a generate scope of `declared_in` holding it is an
|
||||
/// arm, unless a generate scope inside that one holds it too (a `for`
|
||||
/// header, then its body). No scope holding it is a statement label.
|
||||
fn shape_at(semantics: &Semantics, declared_in: ScopeId, name: TextRange) -> LabelShape {
|
||||
let holding = |id: &ScopeId| {
|
||||
semantics.scope(*id).filter(|s| s.span.start <= name.start && name.end <= s.span.end)
|
||||
};
|
||||
let Some(outer) =
|
||||
semantics.scope(declared_in).and_then(|s| s.children.iter().find_map(holding))
|
||||
else {
|
||||
return LabelShape::Procedural;
|
||||
};
|
||||
if outer.kind != ScopeKind::Generate {
|
||||
return LabelShape::Procedural;
|
||||
}
|
||||
let inner = outer.children.iter().filter_map(holding).any(|s| s.kind == ScopeKind::Generate);
|
||||
match inner {
|
||||
true => LabelShape::Loop,
|
||||
false => LabelShape::Arm,
|
||||
}
|
||||
}
|
||||
|
||||
/// True for the declaration kinds that may be written **once** and once only.
|
||||
///
|
||||
/// Everything left out has a legal shape in which the same name is written
|
||||
@@ -122,6 +189,55 @@ mod tests {
|
||||
DuplicateDeclaration.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_block_label_beside_a_net_of_its_name_either_way_round() {
|
||||
let label_second = "module m;\n logic g;\n if (1) begin : g\n end\nendmodule\n";
|
||||
let label_first = "module m;\n if (1) begin : g\n end\n logic g;\nendmodule\n";
|
||||
for src in [label_second, label_first] {
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{src}: {found:?}");
|
||||
assert!(found[0].message.contains("`g`"), "{}", found[0].message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_block_label_beside_any_declaration_and_two_procedural_labels() {
|
||||
for src in [
|
||||
"module m (input logic g);\n if (1) begin : g\n end\nendmodule\n",
|
||||
"module m (g);\n input g;\n if (1) begin : g\n end\nendmodule\n",
|
||||
"module m;\n genvar g;\n if (1) begin : g\n end\nendmodule\n",
|
||||
"module m;\n typedef logic g;\n if (1) begin : g\n end\nendmodule\n",
|
||||
"module m;\n function void g();\n endfunction\n if (1) begin : g\n end\nendmodule\n",
|
||||
"module m;\n task g();\n endtask\n if (1) begin : g\n end\nendmodule\n",
|
||||
"module m;\n initial begin : g\n end\n initial begin : g\n end\nendmodule\n",
|
||||
] {
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{src}: {found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_arms_carrying_one_label_are_not_a_duplicate() {
|
||||
let src = "module m;\n if (1) begin : g\n end else begin : g\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
let case = "module m;\n case (1)\n 0: begin : g\n end\n default: begin : g\n end\n endcase\nendmodule\n";
|
||||
assert!(violations(case).is_empty());
|
||||
}
|
||||
|
||||
/// Review L-2: a `for` generate block is never an arm, and a procedural
|
||||
/// block beside a generate block is flagged whichever comes first.
|
||||
#[test]
|
||||
fn flags_sibling_loops_and_a_procedural_block_beside_a_generate_one() {
|
||||
let lp = " for (genvar i = 0; i < 2; i++) begin : g\n end\n";
|
||||
let arm = " if (1) begin : g\n end\n";
|
||||
let proc = " initial begin : g\n end\n";
|
||||
for (one, two) in [(lp, lp), (arm, lp), (lp, arm), (proc, arm), (arm, proc)] {
|
||||
let src = format!("module m;\n{one}{two}endmodule\n");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{src}: {found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_two_signals_of_one_name() {
|
||||
let src = "module m;\n logic a;\n logic a;\nendmodule\n";
|
||||
|
||||
@@ -190,6 +190,14 @@ mod tests {
|
||||
assert_eq!(names_in_a_project(src, &[]), names(src), "an empty project changes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_label_spelled_like_a_net_is_not_a_read_of_it() {
|
||||
// generate-label-rename F3: the colliding label is a
|
||||
// `duplicate-declaration`, never a use of the net.
|
||||
let src = "module m;\n wire g;\n if (1) begin : g\n end\nendmodule\n";
|
||||
assert!(names(src).is_empty(), "{:?}", names(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_but_undriven_signal_is_reported() {
|
||||
let src = "module m (output logic q);\n wire a;\n assign q = a;\nendmodule\n";
|
||||
|
||||
@@ -320,12 +320,13 @@ impl<'a> Parser<'a> {
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
let at = self.pos;
|
||||
list.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
list.push(self.connection_or_recover()?);
|
||||
let recovered = list.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
self.note_trailing_comma(comma);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
@@ -338,7 +339,7 @@ impl<'a> Parser<'a> {
|
||||
// the list, and after a directive only the closing bracket
|
||||
// does — an `` `ifdef`` arm may end without a comma and
|
||||
// still be followed by an `` `else`` arm.
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
if self.connection_list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -437,12 +438,13 @@ impl<'a> Parser<'a> {
|
||||
let mut conns = Vec::new();
|
||||
loop {
|
||||
let at = self.pos;
|
||||
conns.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
conns.push(self.connection_or_recover()?);
|
||||
let recovered = conns.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = conns.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
self.note_trailing_comma(comma);
|
||||
if let Some(ListElem::Ok(last)) = conns.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
@@ -450,7 +452,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
let dirs = self.take_list_directives(directives, conns.len());
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
if self.connection_list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -560,8 +562,15 @@ impl<'a> Parser<'a> {
|
||||
// arguments — so the greedy parse swallows the instance and the
|
||||
// whole instantiation collapses into one error item. Failing the
|
||||
// element here costs the one connection and keeps everything
|
||||
// else. See `docs/features/small-items-3/README.md`.
|
||||
if self.tolerant && self.cur().is_sym("(") && self.value_runs_into_next_instance() {
|
||||
// else. See `docs/features/small-items-3/README.md`. The same
|
||||
// failure covers a `.NAME(` left open at the end of its line while
|
||||
// the next line goes on with the list (`.po(` ⏎ `.b(y));`): the
|
||||
// entry ends with its line, and the diagnostic is on its `(`
|
||||
// (`docs/features/port-entry-grace/README.md`).
|
||||
if self.tolerant
|
||||
&& self.cur().is_sym("(")
|
||||
&& (self.value_runs_into_next_instance() || self.value_left_open())
|
||||
{
|
||||
return self.error("unclosed `(` in a port or parameter connection");
|
||||
}
|
||||
let mut close_comments = Vec::new();
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
//! See `docs/features/header-recovery/README.md`.
|
||||
|
||||
use super::directive::{closes_conditional, continues_conditional, opens_conditional};
|
||||
use super::recover::is_sync_stop;
|
||||
use super::*;
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
@@ -102,6 +103,176 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of a port or parameter connection list, the unfinished ones
|
||||
/// included (`docs/features/port-entry-grace/README.md`).
|
||||
///
|
||||
/// A `.` with no name after it yet — `.a(x), .` ⏎ `.b(y)` — is the entry
|
||||
/// someone is typing. In tolerant mode it becomes an error element of its
|
||||
/// own, holding just the `.`, with its one diagnostic on the `.`: the
|
||||
/// generic recovery would report the token *after* it, which belongs to
|
||||
/// the next entry, and its skip would swallow a `.b(y)` written on the
|
||||
/// same line. Strict mode, and every other entry, is
|
||||
/// [`Parser::element_or_recover`] over [`Parser::parse_connection`].
|
||||
pub(super) fn connection_or_recover(&mut self) -> PResult<ListElem<Connection>> {
|
||||
if self.tolerant && self.at_lone_dot() {
|
||||
return Ok(ListElem::Error(self.take_lone_dot()));
|
||||
}
|
||||
self.element_or_recover(|p| p.parse_connection())
|
||||
}
|
||||
|
||||
/// True on a `.` that no name can follow: the next token ends the entry
|
||||
/// (`,` `)` `;`), ends the file or an enclosing construct, or — on a later
|
||||
/// line — is a keyword or the `.` of the next entry. A keyword or a `.` on
|
||||
/// the same line (`.input(x)`, `..z (p)`) is left to the generic recovery,
|
||||
/// whose skip takes the whole `.input(x)` / `..z (p)` with it: one error
|
||||
/// element, which is what `lucisv_mcp`'s refusal names (`qa_f1.rs`).
|
||||
fn at_lone_dot(&self) -> bool {
|
||||
if !self.cur().is_sym(".") {
|
||||
return false;
|
||||
}
|
||||
let next = self.nth(1);
|
||||
let later_line = next.line != self.cur().line;
|
||||
next.kind == TokenKind::Eof
|
||||
|| next.is_sym(",")
|
||||
|| next.is_sym(")")
|
||||
|| next.is_sym(";")
|
||||
|| is_sync_stop(next)
|
||||
|| (later_line && (next.kind == TokenKind::Keyword || next.is_sym(".")))
|
||||
}
|
||||
|
||||
/// Record the lone `.` at the cursor and take it as an error element.
|
||||
/// The comments written before it are left pending, so the next entry
|
||||
/// picks them up rather than the error leaf swallowing them.
|
||||
fn take_lone_dot(&mut self) -> RawText {
|
||||
let dot = self.cur();
|
||||
let (span, col) = (dot.span, dot.col);
|
||||
self.diagnostics.push(ParseDiagnostic {
|
||||
message: "expected a name after `.`".to_string(),
|
||||
line: dot.line,
|
||||
col,
|
||||
span,
|
||||
});
|
||||
self.skip();
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// [`Parser::list_ends`] for a connection list, which reads one shape on.
|
||||
///
|
||||
/// After an entry that had to be recovered, a missing `,` normally ends
|
||||
/// the list — what follows belongs to the enclosing construct. In a
|
||||
/// connection list a `.` there is the next connection instead: the entry
|
||||
/// above was abandoned mid-typing (`.po(` ⏎ `.b(y)`), and the list reads
|
||||
/// on. No second diagnostic: the recovered entry already has one, and it
|
||||
/// is the news. Strict mode never recovers, so this is `list_ends` there.
|
||||
pub(super) fn connection_list_ends(
|
||||
&mut self,
|
||||
start: usize,
|
||||
comma: bool,
|
||||
dirs_any: bool,
|
||||
recovered: bool,
|
||||
) -> bool {
|
||||
let next_entry = self.cur().is_sym(".");
|
||||
if self.tolerant && recovered && !comma && !dirs_any && self.pos != start && next_entry {
|
||||
return false;
|
||||
}
|
||||
self.list_ends(start, comma, dirs_any, recovered)
|
||||
}
|
||||
|
||||
/// In tolerant mode, report a connection list's `,` that only the closing
|
||||
/// `)` follows — `.b(y),)`, the separator typed before the next entry.
|
||||
/// Strict mode fails there on the empty entry; tolerant mode used to end
|
||||
/// the list on the `)` without a word. The diagnostic sits on the `,`.
|
||||
/// Called right after the `,` was consumed, so it is the token behind the
|
||||
/// cursor.
|
||||
pub(super) fn note_trailing_comma(&mut self, comma: bool) {
|
||||
if !(self.tolerant && comma && self.cur().is_sym(")")) {
|
||||
return;
|
||||
}
|
||||
let Some(sep) = self.pos.checked_sub(1).and_then(|i| self.tokens.get(i)) else { return };
|
||||
let diag = ParseDiagnostic {
|
||||
message: "expected a connection after `,`".to_string(),
|
||||
line: sep.line,
|
||||
col: sep.col,
|
||||
span: sep.span,
|
||||
};
|
||||
self.diagnostics.push(diag);
|
||||
}
|
||||
|
||||
/// True when the `(` at the cursor — the one that opens a connection's
|
||||
/// value — was left open mid-typing: still open at the end of its line,
|
||||
/// the next line starting something new (a `.` entry, a `)`, a `;`, a
|
||||
/// keyword, or end of file), **and** the bracket never closes the way a
|
||||
/// value's does.
|
||||
///
|
||||
/// The last clause is what keeps every file the strict parser reads
|
||||
/// untouched: in a valid list a value's matching `)` is followed by a
|
||||
/// `,`, the list's `)`, or a directive, so `.po(top` ⏎ `.sig)` — a legal
|
||||
/// path continued on the next line — is read as written. The line clause
|
||||
/// keeps the pinned ambiguous shape `.D(` ⏎ `u0 (.a(x)));` greedy
|
||||
/// (`docs/features/header-recovery/README.md`): an identifier opening the
|
||||
/// next line is [`Parser::value_runs_into_next_instance`]'s question.
|
||||
/// Tolerant mode only; the walk ends at the first `;` or construct keyword
|
||||
/// outside the value, so it is bounded by the item.
|
||||
pub(super) fn value_left_open(&self) -> bool {
|
||||
let open = self.pos;
|
||||
let line = self.cur().line;
|
||||
let mut depth = 0u32;
|
||||
let mut i = open + 1;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.line != line || t.kind == TokenKind::Eof {
|
||||
break;
|
||||
}
|
||||
if is_open_bracket(t) {
|
||||
depth += 1;
|
||||
} else if is_close_bracket(t) {
|
||||
if depth == 0 {
|
||||
return false;
|
||||
}
|
||||
depth -= 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let Some(next) = self.tokens.get(i) else { return false };
|
||||
let starts_new = next.kind == TokenKind::Eof
|
||||
|| next.kind == TokenKind::Keyword
|
||||
|| next.is_sym(".")
|
||||
|| next.is_sym(")")
|
||||
|| next.is_sym(";");
|
||||
starts_new && !self.value_closes(open)
|
||||
}
|
||||
|
||||
/// Whether the bracket at token `open` is closed by a `)` that a valid
|
||||
/// connection list could have written next: anything but a `;`, end of
|
||||
/// file, a construct keyword, a `.` or a plain identifier after it. A
|
||||
/// `;` or construct keyword reached first, outside any bracket the value
|
||||
/// opened, means it is never closed at all.
|
||||
fn value_closes(&self, open: usize) -> bool {
|
||||
let mut depth = 0u32;
|
||||
let mut i = open + 1;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
return false;
|
||||
}
|
||||
if is_open_bracket(t) {
|
||||
depth += 1;
|
||||
} else if is_close_bracket(t) {
|
||||
if depth == 0 {
|
||||
return self.tokens.get(i + 1).is_some_and(|after| !ends_a_value_badly(after));
|
||||
}
|
||||
depth -= 1;
|
||||
} else if depth == 0 && (t.is_sym(";") || is_sync_stop(t)) {
|
||||
return false;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// True on a token that opens a bracket.
|
||||
fn at_open_bracket(&self) -> bool {
|
||||
is_open_bracket(self.cur())
|
||||
}
|
||||
|
||||
/// True on a `` `ifdef `` / `` `ifndef `` / `` `else `` / `` `elsif `` /
|
||||
/// `` `endif ``: a directive that opens, continues or closes a
|
||||
/// conditional-compilation region.
|
||||
@@ -267,12 +438,6 @@ impl<'a> Parser<'a> {
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// True on a token that opens a bracket.
|
||||
fn at_open_bracket(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// The extent a recovery covers: from `start` through the last token it
|
||||
/// took, or the empty range at `start` when it took none (the sync point
|
||||
/// was already under the cursor).
|
||||
@@ -340,3 +505,25 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True on a `(`, `[` or `{`.
|
||||
fn is_open_bracket(t: &Token) -> bool {
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// True on a `)`, `]` or `}`.
|
||||
fn is_close_bracket(t: &Token) -> bool {
|
||||
t.is_sym(")") || t.is_sym("]") || t.is_sym("}")
|
||||
}
|
||||
|
||||
/// True on a token no valid connection list writes right after a value's
|
||||
/// closing `)`: the list was never closed (`;`, end of file, a construct
|
||||
/// keyword), or the next connection follows with no `,` (`.`, or a plain
|
||||
/// identifier — a macro invocation is a directive's business and allowed).
|
||||
fn ends_a_value_badly(t: &Token) -> bool {
|
||||
t.kind == TokenKind::Eof
|
||||
|| t.is_sym(";")
|
||||
|| t.is_sym(".")
|
||||
|| is_sync_stop(t)
|
||||
|| (t.kind == TokenKind::Ident && !t.is_macro())
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! An unfinished connection stays inside its own entry (TODO §68.2,
|
||||
//! `docs/features/port-entry-grace/README.md`).
|
||||
//!
|
||||
//! The four shapes someone typing a named connection leaves behind — a lone
|
||||
//! `.`, a `.name(` still open at the end of its line, a missing `,` between
|
||||
//! two entries, a `,` with only the `)` after it — each cost exactly one
|
||||
//! diagnostic, whose span lies inside the unfinished entry (or on the single
|
||||
//! token that proves it), and every other entry, the instance and the rest of
|
||||
//! the file parse as if the entry were complete. The strict parser refuses
|
||||
//! every one of them, as before; and no valid spelling of a list reads
|
||||
//! differently in tolerant mode.
|
||||
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::{parse_source, parse_source_tolerant, ParseDiagnostic};
|
||||
|
||||
/// The file's one module. Panics unless the file is exactly one module — the
|
||||
/// shapes below must never cost the module.
|
||||
fn the_module(file: &SourceFile) -> &Module {
|
||||
assert_eq!(file.items.len(), 1, "the file is still one item: {:?}", file.items);
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected module m") };
|
||||
m
|
||||
}
|
||||
|
||||
/// The instantiations among `m`'s items, and how many items are anything
|
||||
/// else (error items included).
|
||||
fn instantiations(m: &Module) -> (Vec<&Instantiation>, usize) {
|
||||
let mut insts = Vec::new();
|
||||
let mut others = 0;
|
||||
for item in &m.items {
|
||||
match &item.kind {
|
||||
ItemKind::Instantiation(inst) => insts.push(inst),
|
||||
ItemKind::Error(raw) => panic!("an error item escaped the list: {:?}", raw.text),
|
||||
_ => others += 1,
|
||||
}
|
||||
}
|
||||
(insts, others)
|
||||
}
|
||||
|
||||
/// One entry, as the tests compare it: `Ok(name)` or `Err(raw text)`.
|
||||
fn entries(list: &[ListElem<Connection>]) -> Vec<Result<&str, &str>> {
|
||||
list.iter()
|
||||
.map(|e| match e {
|
||||
ListElem::Ok(c) => Ok(c.name.as_str()),
|
||||
ListElem::Error(raw) => Err(raw.text.as_str()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The named connections of the first instance of the first instantiation.
|
||||
fn ports(m: &Module) -> Vec<Result<&str, &str>> {
|
||||
let (insts, _) = instantiations(m);
|
||||
let Connections::Named(conns) = &insts[0].instances[0].conns else { panic!("named list") };
|
||||
entries(conns)
|
||||
}
|
||||
|
||||
/// The one diagnostic `src` produces, and the source text its span covers.
|
||||
fn one_diag(src: &str, diags: &[ParseDiagnostic]) -> (String, String) {
|
||||
assert_eq!(diags.len(), 1, "exactly one diagnostic: {diags:?}");
|
||||
(diags[0].message.clone(), src[diags[0].span.as_range()].to_string())
|
||||
}
|
||||
|
||||
/// The strict parser — the formatter's — still refuses `src`.
|
||||
fn strict_refuses(src: &str) {
|
||||
assert!(parse_source(src).is_err(), "strict mode must still refuse:\n{src}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// (a) a lone `.`
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_lone_dot_on_its_own_line_keeps_the_entries_after_it() {
|
||||
let src = "module m;\n sub u0 (.a(x),\n .\n .b(y));\n wire w;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
let (message, at) = one_diag(src, &diags);
|
||||
assert_eq!(at, ".", "on the dot itself, not on the `.b` after it");
|
||||
assert_eq!(message, "expected a name after `.`");
|
||||
assert_eq!(ports(m), [Ok("a"), Err("."), Ok("b")]);
|
||||
assert_eq!(instantiations(m).1, 1, "`wire w;` is still an item of the module");
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_dot_before_a_comma_or_the_close() {
|
||||
for (src, want) in [
|
||||
("module m;\n sub u0 (.a(x), ., .b(y));\nendmodule\n", vec![Ok("a"), Err("."), Ok("b")]),
|
||||
("module m;\n sub u0 (.a(x), .);\nendmodule\n", vec![Ok("a"), Err(".")]),
|
||||
("module m;\n sub u0 (.);\nendmodule\n", vec![Err(".")]),
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, ".", "{src}");
|
||||
assert_eq!(ports(m), want, "{src}");
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_dot_in_a_parameter_override_list() {
|
||||
let src = "module m;\n sub #(.W(8), .\n .D(2)) u0 (.a(x));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, ".");
|
||||
let (insts, _) = instantiations(m);
|
||||
assert_eq!(entries(insts[0].params.as_ref().expect("overrides")), [Ok("W"), Err("."), Ok("D")]);
|
||||
assert_eq!(insts[0].instances[0].name, "u0");
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_dot_at_the_end_of_the_file_keeps_the_instance() {
|
||||
let src = "module m;\n sub u0 (.a(x), .\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, ".");
|
||||
assert_eq!(ports(m), [Ok("a"), Err(".")]);
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// (b) `.name(` still open at the end of its line
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_open_value_followed_by_the_next_entry_ends_with_its_line() {
|
||||
for (src, raw) in [
|
||||
("module m;\n sub u0 (.a(x), .po(\n .b(y));\n wire w;\nendmodule\n", ".po("),
|
||||
("module m;\n sub u0 (.a(x), .po(z\n .b(y));\n wire w;\nendmodule\n", ".po(z"),
|
||||
("module m;\n sub u0 (.a(x),\n .po(\n .b(y),\n .c(z)\n );\n wire w;\nendmodule\n", ".po("),
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
let (message, at) = one_diag(src, &diags);
|
||||
assert_eq!(at, "(", "on the entry's own `(`: {src}");
|
||||
assert!(message.starts_with("unclosed `(`"), "{message}");
|
||||
let got = ports(m);
|
||||
assert_eq!(got[0], Ok("a"));
|
||||
assert_eq!(got[1], Err(raw), "{src}");
|
||||
assert_eq!(got[2], Ok("b"), "the entry after it survives: {src}");
|
||||
assert_eq!(instantiations(m).1, 1, "`wire w;` is an item: {src}");
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_value_followed_by_the_lists_close() {
|
||||
let src = "module m;\n sub u0 (.a(x), .po(\n );\n wire w;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, "(");
|
||||
assert_eq!(ports(m), [Ok("a"), Err(".po(")]);
|
||||
assert_eq!(instantiations(m).1, 1);
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_value_at_the_end_of_the_module() {
|
||||
let src = "module m;\n sub u0 (.a(x), .po(\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, "(");
|
||||
assert_eq!(ports(m), [Ok("a"), Err(".po(")]);
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_override_value_keeps_the_overrides_after_it_and_the_instance() {
|
||||
let src = "module m;\n sub #(.W(8), .D(\n .E(1)) u0 (.a(x));\n wire w;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, "(");
|
||||
let (insts, others) = instantiations(m);
|
||||
assert_eq!(
|
||||
entries(insts[0].params.as_ref().expect("overrides")),
|
||||
[Ok("W"), Err(".D("), Ok("E")]
|
||||
);
|
||||
assert_eq!(insts[0].instances[0].name, "u0");
|
||||
assert_eq!(others, 1);
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
/// The two pinned shapes of `error_recovery.rs` keep their old answers: an
|
||||
/// identifier opening the next line is the next-instance lookahead's, and
|
||||
/// the balanced `.D(` ⏎ `u0 (.a(x)));` stays ambiguous and greedy.
|
||||
#[test]
|
||||
fn an_identifier_on_the_next_line_is_not_this_rule() {
|
||||
let src = "module m;\n sub #(.D(\n u0 (.a(x)));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.iter().all(|d| !d.message.contains("unclosed")), "{diags:?}");
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("module") };
|
||||
assert!(matches!(m.items[0].kind, ItemKind::Error(_)), "still one error item");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// (c) a missing `,` between two entries
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_missing_comma_keeps_both_entries() {
|
||||
for src in [
|
||||
"module m;\n sub u0 (.a(x)\n .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x) .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po\n .b(y));\nendmodule\n",
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
let (message, at) = one_diag(src, &diags);
|
||||
assert!(message.starts_with("expected `,`"), "{message}");
|
||||
assert_eq!(at, ".", "on the `.` that proves the comma missing: {src}");
|
||||
assert!(ports(m).iter().all(Result::is_ok), "{:?}", ports(m));
|
||||
assert_eq!(ports(m).last(), Some(&Ok("b")));
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// (d) a trailing `,`
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comma_is_reported_on_the_comma() {
|
||||
for src in [
|
||||
"module m;\n sub u0 (.a(x), .b(y),);\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .b(y),\n );\nendmodule\n",
|
||||
"module m;\n sub #(.W(1),) u0 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub #(1,) u0 (.a(x));\nendmodule\n",
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
let (message, at) = one_diag(src, &diags);
|
||||
assert_eq!(at, ",", "{src}");
|
||||
assert_eq!(message, "expected a connection after `,`");
|
||||
assert_eq!(instantiations(m).0.len(), 1);
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
|
||||
/// A positional list may end in an omitted connection — `u (a, b,)` is legal
|
||||
/// — so the trailing-comma report is a named-list and override-list rule only.
|
||||
#[test]
|
||||
fn a_positional_lists_trailing_comma_is_still_legal() {
|
||||
let src = "module m;\n sub u0 (a, b,);\nendmodule\n";
|
||||
assert!(parse_source(src).is_ok());
|
||||
assert!(parse_source_tolerant(src).1.is_empty());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Valid input is untouched
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Spellings that come close to every shape above and are legal: each parses
|
||||
/// strictly, reports nothing tolerantly, and builds the identical tree.
|
||||
#[test]
|
||||
fn valid_lists_read_the_same_in_both_modes() {
|
||||
for src in [
|
||||
// A path continued on the next line: `(` open at the line's end and a
|
||||
// `.` opening the next — the one valid shape rule (b) has to leave be.
|
||||
"module m;\n sub u0 (.a(x),\n .po(top\n .sig), .q(r));\nendmodule\n",
|
||||
"module m;\n sub u0 (.po(top\n .sig));\nendmodule\n",
|
||||
// A value written over several lines, its `)` alone on the last one.
|
||||
"module m;\n sub u0 (.po(\n x\n ), .q(r));\nendmodule\n",
|
||||
"module m;\n sub u0 (.po(f(x\n )));\nendmodule\n",
|
||||
"module m;\n sub #(.DEPTH(\n f(1)\n )) u0 (.a(x));\nendmodule\n",
|
||||
// The implicit `.name` form, a `.*`, an empty `.name()`.
|
||||
"module m;\n sub u0 (.a,\n .b(),\n .*);\nendmodule\n",
|
||||
// A directive between entries and a macro after a value.
|
||||
"module m;\n sub u0 (.a(x),\n`ifdef B\n .b(y),\n`endif\n .c(z));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x) `COMMA_B\n );\nendmodule\n",
|
||||
// Attributes on an entry.
|
||||
"module m;\n sub u0 ((* keep *) .a(x),\n (* keep *)\n .b(y));\nendmodule\n",
|
||||
] {
|
||||
let strict = match parse_source(src) {
|
||||
Ok(tree) => tree,
|
||||
Err(e) => panic!("premise: {src:?} is valid, got {e}"),
|
||||
};
|
||||
let (tolerant, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{src}: {diags:?}");
|
||||
assert_eq!(format!("{strict:?}"), format!("{tolerant:?}"), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `.` followed by another `.` on the same line is not a lone dot: the
|
||||
/// generic recovery keeps `..z (p)` as one error element, whose text is what
|
||||
/// a refusal downstream names (`lucisv_mcp`'s `qa_f1.rs`).
|
||||
#[test]
|
||||
fn two_dots_on_one_line_stay_one_error_element() {
|
||||
for (src, want) in [
|
||||
("module m;\n sub u0 (.a(x), ..z (p));\nendmodule\n", vec![Ok("a"), Err("..z (p)")]),
|
||||
("module m;\n sub u0 (.a(x), . .b(y));\nendmodule\n", vec![Ok("a"), Err(". .b(y)")]),
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(diags.len(), 1, "{src}: {diags:?}");
|
||||
assert_eq!(ports(m), want, "{src}");
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! QA, TODO §68.2 (`docs/features/port-entry-grace/README.md`): the tolerant
|
||||
//! parser's new connection-list recovery against a wider sweep than the dev's
|
||||
//! own tests — multi-line connection values that are legal (each must read
|
||||
//! exactly as the strict parser reads it, with no diagnostic) and unfinished
|
||||
//! entries in every position QA could think of (each must stay refused by the
|
||||
//! strict parser and cost at least one tolerant diagnostic, none of them
|
||||
//! outside the source).
|
||||
|
||||
use vlog_parser::{parse_source, parse_source_tolerant};
|
||||
|
||||
/// Legal multi-line connections: an operand on the line after `(`, a
|
||||
/// keyword-led operand, a macro, a comment line, a dotted name, overrides,
|
||||
/// `.*`, attributes, generate loops, instance arrays, gates, `bind`, UDPs,
|
||||
/// conditional compilation.
|
||||
const VALID: &[&str] = &[
|
||||
"module m;\n sub u0 (.a(\n foo\n ), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a({\n x, y\n }), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x ?\n y : z), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n signed'(x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n this.x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n null), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n super.x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n $bits(x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n `MACRO(x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n // comment\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n intf.sig), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(intf\n .sig), .b(y));\nendmodule\n",
|
||||
"module m;\n sub #(.W(\n 8)) u0 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n ));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .*);\nendmodule\n",
|
||||
"module m;\n sub u0 ((* keep *) .a(\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n for (genvar i = 0; i < 4; i++) begin : g\n sub u (.a(\n x[i]), .b(y));\n end\nendmodule\n",
|
||||
"module m;\n sub u [3:0] (.a(\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n and g1 (o,\n a, b);\nendmodule\n",
|
||||
"module m;\n bind sub chk u_chk (.a(\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n intf u_if (.clk(\n clk));\n prog u_p (.a(\n x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n`ifdef FOO\n , .b(y)\n`endif\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n `ifdef FOO , .b(y) `endif\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x[\n 3:0]), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(f(\n x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x\n ), .b(\n y\n ));\nendmodule\n",
|
||||
"module m;\n sub u0 (x,\n y, z);\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n new));\nendmodule\n",
|
||||
"module m;\n sub #(\n .W(8),\n .T(\n logic [3:0])\n ) u0 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub #(.T(\n int)) u0 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n 1'b0), .b(\n '0));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n {8{1'b0}}), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)) ;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)), u1 (.a(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)) /* c */;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n // trailing\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n std::randomize(x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x inside {1, 2}), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n pkg::x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n (x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n ), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x\n ), .b(y\n ));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .b(\n y\n )\n );\n sub u1 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n `ifdef FOO\n ,.b(y)\n `endif\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x));\n checker_t c0 (.a(\n x));\nendmodule\n",
|
||||
"module m;\n myudp u (out,\n in1, in2);\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x), .b(y)); sub u1 (.a(\n x));\nendmodule\n",
|
||||
"module m;\n sub #(\n .A(\n 1\n )\n ) u0 ();\nendmodule\n",
|
||||
// Not here: "sub #(8,\n 16) u0 (x,\n y,);" — a positional list's
|
||||
// trailing omitted connection. Strict keeps it as an empty entry and
|
||||
// tolerant drops it, at c1076f9 already (QA log 2026-11-17, NOTE).
|
||||
"module m;\n sub #(8,\n 16) u0 (x,\n y, z);\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n ) ;\nendmodule\nmodule n;\nendmodule\n",
|
||||
];
|
||||
|
||||
/// Unfinished entries: first, last, only, repeated, at end of file, in `#(`,
|
||||
/// in generate and `` `ifdef `` regions, with nested open brackets, a comma
|
||||
/// inside an open value, trailing commas, keywords after the `(`.
|
||||
const UNFINISHED: &[&str] = &[
|
||||
"module m;\n sub u0 (.\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .);\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.);\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .\n .\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .pq(\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .",
|
||||
"module m;\n sub u0 (.a(x),\n .po(",
|
||||
"module m;\n sub #(.W(\n .D(1)) u0 (.a(x));\n wire w;\nendmodule\n",
|
||||
"module m;\n generate if (1) begin : g\n sub u0 (.a(x),\n .po(\n .b(y));\n end endgenerate\n wire w;\nendmodule\n",
|
||||
"module m;\n`ifdef FOO\n sub u0 (.a(x),\n .po(\n .b(y));\n`endif\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(f(\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(x[\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po({\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(a,\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),",
|
||||
"module m;\n sub u0 (.a(x), .b(y),\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),,.b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x) .b(y) .c(z));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.po(\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\nendmodule\nmodule n;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y),\n .c(\n .d(z));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(z\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(z)\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n ;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .input(\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .\n input w2;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n u1 (.a(x)));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po((\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)), u1 (.a(x));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) /*c*/;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), // c1\n . // c2\n .b(y)); // c3\n wire w;\nendmodule\n",
|
||||
"module m;\n sub #(.W(1),) u0 (.a(x),);\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n`ifdef X\n .b(y)\n`endif\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y))\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) .c(z);\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) foo;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) `M;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n .b(y)), .c(z));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(\n .c(\n .d(\n .e(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .\n .\n .\n .\n .\n .\n .\n .\n .\n .\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n endmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n end\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po( .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y));\n sub u1 (.a(x),\n .\n .b(y));\n assign q = ;\nendmodule\n",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_legal_multi_line_connections_read_the_same_in_both_modes() {
|
||||
for src in VALID {
|
||||
let strict = match parse_source(src) {
|
||||
Ok(tree) => tree,
|
||||
Err(e) => panic!("premise: {src:?} is valid, got {e}"),
|
||||
};
|
||||
let (tolerant, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{src}: {diags:?}");
|
||||
assert_eq!(format!("{strict:?}"), format!("{tolerant:?}"), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_every_unfinished_entry_is_refused_strictly_and_reported_tolerantly() {
|
||||
for src in UNFINISHED {
|
||||
assert!(parse_source(src).is_err(), "strict mode must refuse:\n{src}");
|
||||
let (_, diags) = parse_source_tolerant(src);
|
||||
assert!(!diags.is_empty(), "never silent:\n{src}");
|
||||
let lines = src.lines().count();
|
||||
assert!(diags.len() <= lines, "no diagnostic explosion ({}):\n{src}", diags.len());
|
||||
for d in &diags {
|
||||
assert!(d.span.end as usize <= src.len(), "{d:?} outside the source:\n{src}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ use vlog_semantic::{
|
||||
use super::ledger::{pieces_match, Split};
|
||||
use super::{anchor_of, Anchor, Shifts};
|
||||
use crate::rename::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::rename::Scope;
|
||||
use crate::TextEdit;
|
||||
|
||||
/// The rename's lexical contract for a file whose edits insert connection
|
||||
@@ -53,10 +53,9 @@ pub(super) fn insertions_match(
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
names: [&str; 2],
|
||||
path: &Path,
|
||||
shown: &str,
|
||||
) -> Result<(), String> {
|
||||
let refusal =
|
||||
|what: &str| format!("the rename would {what} in {}; no edits were made.", display(path));
|
||||
let refusal = |what: &str| format!("the rename would {what} in {shown}; no edits were made.");
|
||||
let Ok(old_tokens) = tokenize(before) else {
|
||||
return Err(refusal("edit a file lucisv cannot lex"));
|
||||
};
|
||||
@@ -74,8 +73,8 @@ pub(super) fn insertions_match(
|
||||
return Err(refusal(&outside));
|
||||
}
|
||||
}
|
||||
let split = Split::read(before, after, edits, path, "the rename")?;
|
||||
pieces_match(&split, edits, path, "the rename")?;
|
||||
let split = Split::read(before, after, edits, shown, "the rename")?;
|
||||
pieces_match(&split, edits, shown, "the rename")?;
|
||||
let grew = parse_source_tolerant(after).1.len() > parse_source_tolerant(before).1.len();
|
||||
match grew {
|
||||
true => Err(refusal("leave a connection list that does not parse")),
|
||||
@@ -340,7 +339,7 @@ pub(super) fn bindings_match(
|
||||
let [old, new] = names;
|
||||
return Err(format!(
|
||||
"renaming `{old}` to `{new}` would change what an implicit connection of `{instance}` binds in {}; the rename was abandoned.",
|
||||
display(path)
|
||||
scope.name_of(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,13 +9,11 @@
|
||||
//! the whole of it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
use crate::rename::display;
|
||||
use crate::TextEdit;
|
||||
|
||||
use super::{Moving, Origin};
|
||||
@@ -77,14 +75,11 @@ impl Split {
|
||||
before: &str,
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
shown: &str,
|
||||
what: &str,
|
||||
) -> Result<Split, String> {
|
||||
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
|
||||
return Err(format!(
|
||||
"{} would no longer lex after {what}; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
return Err(format!("{} would no longer lex after {what}; no edits were made.", shown));
|
||||
};
|
||||
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
|
||||
for edit in edits {
|
||||
@@ -103,7 +98,7 @@ impl Split {
|
||||
pub(super) fn positions_match(
|
||||
&self,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
shown: &str,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let clone = |pieces: &[(TextRange, Piece)]| -> Vec<Piece> {
|
||||
@@ -144,14 +139,14 @@ impl Split {
|
||||
"{what} would write {} where {} belongs in {}; no edits were made.",
|
||||
actual.describe(),
|
||||
expected.describe(),
|
||||
display(path)
|
||||
shown
|
||||
))
|
||||
}
|
||||
None => {
|
||||
return Err(format!(
|
||||
"{what} would lose {} in {}; no edits were made.",
|
||||
expected.describe(),
|
||||
display(path)
|
||||
shown
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -160,7 +155,7 @@ impl Split {
|
||||
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
|
||||
return Err(format!(
|
||||
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
|
||||
display(path)
|
||||
shown
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
@@ -174,12 +169,12 @@ impl Split {
|
||||
pub(super) fn pieces_match(
|
||||
split: &Split,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
shown: &str,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let ledger = Ledger::of(split, edits, TextRange::empty(0));
|
||||
ledger.check(&display(path), what, &Tally::new())?;
|
||||
split.positions_match(edits, path, what)
|
||||
ledger.check(shown, what, &Tally::new())?;
|
||||
split.positions_match(edits, shown, what)
|
||||
}
|
||||
|
||||
/// The range the move takes text out of file `i`, if it names that file as one
|
||||
@@ -545,7 +540,7 @@ fn and_list(names: &[String]) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::*;
|
||||
use crate::apply;
|
||||
@@ -556,11 +551,11 @@ mod tests {
|
||||
before: &str,
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
shown: &str,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let split = Split::read(before, after, edits, path, what)?;
|
||||
super::pieces_match(&split, edits, path, what)
|
||||
let split = Split::read(before, after, edits, shown, what)?;
|
||||
super::pieces_match(&split, edits, shown, what)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -587,7 +582,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn splice_attack(corrupted: &str) -> Result<(), String> {
|
||||
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
|
||||
pieces_match(PORTS, corrupted, &add_edits(), "m.sv", "adding port `cfg`")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -642,7 +637,7 @@ mod tests {
|
||||
let at = text.find("hello").expect("string") as u32;
|
||||
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
|
||||
let corrupted = apply(text, &edits);
|
||||
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
|
||||
let outcome = pieces_match(text, &corrupted, &edits, "m.sv", "an edit");
|
||||
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
|
||||
}
|
||||
|
||||
@@ -654,8 +649,7 @@ mod tests {
|
||||
let end = PORTS.find("*/").expect("comment") as u32 + 2;
|
||||
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
|
||||
let corrupted = apply(PORTS, &edits);
|
||||
let outcome =
|
||||
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
|
||||
let outcome = pieces_match(PORTS, &corrupted, &edits, "m.sv", "removing port `rst`");
|
||||
let message = outcome.expect_err("a deleted comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
@@ -690,13 +684,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn move_attack(corrupted: &str) -> Result<(), String> {
|
||||
pieces_match(
|
||||
MOVED,
|
||||
corrupted,
|
||||
&move_edits(),
|
||||
Path::new("/rtl/m.sv"),
|
||||
"converting `m`'s ports to ANSI",
|
||||
)
|
||||
pieces_match(MOVED, corrupted, &move_edits(), "m.sv", "converting `m`'s ports to ANSI")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -773,7 +761,7 @@ mod tests {
|
||||
];
|
||||
let corrupted = apply(SHARED, &edits);
|
||||
assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it");
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, "m.sv", "an edit")
|
||||
.expect_err("a doubled comment is a refusal");
|
||||
assert!(message.contains("would write the comment"), "{message}");
|
||||
}
|
||||
@@ -786,7 +774,7 @@ mod tests {
|
||||
let end = MOVED.find("\n output").expect("output") as u32;
|
||||
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
|
||||
let corrupted = apply(MOVED, &edits);
|
||||
let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
let message = pieces_match(MOVED, &corrupted, &edits, "m.sv", "an edit")
|
||||
.expect_err("a deleted comment nothing writes back is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
@@ -812,7 +800,7 @@ mod tests {
|
||||
];
|
||||
let corrupted = apply(SHARED, &edits);
|
||||
assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it");
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, "m.sv", "an edit")
|
||||
.expect_err("a duplicated comment is a refusal");
|
||||
assert!(message.contains("comments are never duplicated"), "{message}");
|
||||
}
|
||||
@@ -832,8 +820,7 @@ mod tests {
|
||||
}];
|
||||
let spliced = apply(source, &edits);
|
||||
assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}");
|
||||
let outcome =
|
||||
pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`");
|
||||
let outcome = pieces_match(source, &spliced, &edits, "top.sv", "adding port `b`");
|
||||
assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text");
|
||||
}
|
||||
|
||||
@@ -889,13 +876,7 @@ mod tests {
|
||||
|
||||
fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> {
|
||||
let corrupted = apply(ATTRIBUTED, edits);
|
||||
pieces_match(
|
||||
ATTRIBUTED,
|
||||
&corrupted,
|
||||
edits,
|
||||
Path::new("/rtl/m.sv"),
|
||||
"converting `m`'s ports to ANSI",
|
||||
)
|
||||
pieces_match(ATTRIBUTED, &corrupted, edits, "m.sv", "converting `m`'s ports to ANSI")
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -21,6 +21,10 @@ mod after;
|
||||
mod implicit;
|
||||
mod ledger;
|
||||
#[cfg(test)]
|
||||
mod qa_block_attacks;
|
||||
#[cfg(test)]
|
||||
mod qa_block_paths;
|
||||
#[cfg(test)]
|
||||
mod qa_implicit;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -33,7 +37,7 @@ use vlog_semantic::{
|
||||
ExternalResolutions, ExternalTarget, ReferenceId, Semantics, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::rename::{contains_word, display, Scope};
|
||||
use crate::rename::{contains_word, Scope};
|
||||
use crate::trace::VerifyTrace;
|
||||
use crate::{apply, Shift, TextEdit};
|
||||
|
||||
@@ -108,7 +112,7 @@ pub(crate) fn verify(
|
||||
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.",
|
||||
display(path)
|
||||
scope.name_of(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -134,9 +138,10 @@ fn tokens_verified(
|
||||
) -> Result<(), String> {
|
||||
for ((i, edits), (path, text)) in edits.iter().zip(edited) {
|
||||
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
|
||||
let shown = scope.name_of(path);
|
||||
stage.measure(|| match edits.iter().any(|e| e.range.is_empty()) {
|
||||
true => implicit::insertions_match(before, text, edits, names, path),
|
||||
false => tokens_match(before, text, &Shift::new(edits), names[1], path),
|
||||
true => implicit::insertions_match(before, text, edits, names, &shown),
|
||||
false => tokens_match(before, text, &Shift::new(edits), names[1], &shown),
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -295,23 +300,24 @@ pub(crate) fn verify_move(
|
||||
if edits.iter().any(|(i, _)| *i == copied.file) {
|
||||
return Err(format!(
|
||||
"{what} would edit {}, which it only copies out of; no edits were made.",
|
||||
display(path)
|
||||
scope.name_of(path)
|
||||
));
|
||||
}
|
||||
transit.copy(&display(path), text, copied.region, what)?;
|
||||
transit.copy(&scope.name_of(path), text, copied.region, what)?;
|
||||
}
|
||||
|
||||
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
|
||||
let Some(before) = scope.text(*i) else { return Err(abandoned) };
|
||||
let split = Split::read(before, text, edits, path, what)?;
|
||||
let shown = scope.name_of(path);
|
||||
let split = Split::read(before, text, edits, &shown, what)?;
|
||||
match region_of(moving, *i) {
|
||||
// A file the move names balances against the pieces in transit
|
||||
// rather than on its own; its positional comparison is unchanged.
|
||||
Some(region) => {
|
||||
transit.add(&display(path), region, &split, edits);
|
||||
split.positions_match(edits, path, what)?;
|
||||
transit.add(&scope.name_of(path), region, &split, edits);
|
||||
split.positions_match(edits, &shown, what)?;
|
||||
}
|
||||
None => pieces_match(&split, edits, path, what)?,
|
||||
None => pieces_match(&split, edits, &shown, what)?,
|
||||
}
|
||||
// A tolerant parse of a file that was already broken still reports its
|
||||
// old diagnostics, so the bar is "no *new* one", not "none".
|
||||
@@ -320,7 +326,7 @@ pub(crate) fn verify_move(
|
||||
if after_count > before_count {
|
||||
return Err(format!(
|
||||
"{what} would leave {} unparseable; no edits were made.",
|
||||
display(path)
|
||||
scope.name_of(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -360,7 +366,7 @@ pub(crate) fn verify_move(
|
||||
if let Some(what_moved) = before.first_difference(&after) {
|
||||
return Err(format!(
|
||||
"{what} would change what {what_moved} means in {}; no edits were made.",
|
||||
display(path)
|
||||
scope.name_of(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -437,16 +443,12 @@ fn tokens_match(
|
||||
after: &str,
|
||||
shift: &Shift,
|
||||
new_name: &str,
|
||||
path: &Path,
|
||||
shown: &str,
|
||||
) -> Result<(), String> {
|
||||
let refusal = |what: &str| {
|
||||
format!("the rename would change {what} in {}; no edits were made.", display(path))
|
||||
};
|
||||
let refusal =
|
||||
|what: &str| format!("the rename would change {what} in {shown}; no edits were made.");
|
||||
let (Ok(old), Ok(new)) = (tokenize(before), tokenize(after)) else {
|
||||
return Err(format!(
|
||||
"{} would no longer lex after the rename; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
return Err(format!("{shown} would no longer lex after the rename; no edits were made."));
|
||||
};
|
||||
if old.len() != new.len() {
|
||||
return Err(refusal("the token stream's shape"));
|
||||
@@ -651,7 +653,7 @@ mod tests {
|
||||
|
||||
fn attack(corrupted: &str) -> Result<(), String> {
|
||||
let edits = rename_edits();
|
||||
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", Path::new("/rtl/m.sv"))
|
||||
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", "m.sv")
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! QA re-attack (TODO §65.1, CLAUDE.md invariant 4) on the rename verifier
|
||||
//! over block labels, beyond the dev's `qa_block_paths`: corrupted outputs
|
||||
//! that rename an unrelated block of the same name, rebind a path to another
|
||||
//! module's block, split a same-label pair of arms, or let a genvar capture
|
||||
//! a path written inside the loop. Each lexes and parses; each must be
|
||||
//! refused. `docs/features/generate-label-rename/README.md`, QA log.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use super::verify;
|
||||
use crate::rename::Scope;
|
||||
use crate::trace::VerifyTrace;
|
||||
use crate::TextEdit;
|
||||
|
||||
/// Two modules, each with its own `g_lane`, both instantiated in `top`.
|
||||
const SUB: &str = "module sub (input logic clk);
|
||||
for (genvar i = 0; i < 2; i++) begin : g_lane
|
||||
logic sig;
|
||||
assign sig = clk;
|
||||
end : g_lane
|
||||
endmodule
|
||||
";
|
||||
|
||||
const OTHER: &str = "module other (input logic clk);
|
||||
for (genvar i = 0; i < 2; i++) begin : g_lane
|
||||
logic sig;
|
||||
assign sig = clk;
|
||||
end : g_lane
|
||||
endmodule
|
||||
";
|
||||
|
||||
const TOP: &str = "module top (input logic clk, output logic o, output logic p);
|
||||
sub u_x (.clk);
|
||||
other u_y (.clk);
|
||||
assign o = u_x.g_lane[1].sig;
|
||||
assign p = u_y.g_lane[0].sig;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// Both arms of a generate `if` carry one label, each closed by it.
|
||||
const ARMS: &str = "module arms #(parameter bit P = 0) (output logic o);
|
||||
if (P) begin : g_arm
|
||||
logic q;
|
||||
end : g_arm
|
||||
else begin : g_arm
|
||||
logic q;
|
||||
end : g_arm
|
||||
assign o = g_arm.q;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A path to the loop's own block written inside the loop's body.
|
||||
const INSIDE: &str = "module inside (output logic o);
|
||||
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
|
||||
logic sig;
|
||||
assign sig = g_lane[0].sig;
|
||||
end
|
||||
assign o = g_lane[1].sig;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A rename's edit at the `n`th (0-based) whole-word `name` in `text`.
|
||||
fn at_word(text: &str, name: &str, n: usize, new: &str) -> TextEdit {
|
||||
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
|
||||
let bytes = text.as_bytes();
|
||||
let start = text
|
||||
.match_indices(name)
|
||||
.map(|(i, _)| i)
|
||||
.filter(|&i| {
|
||||
!is_word(i.checked_sub(1).and_then(|p| bytes.get(p)))
|
||||
&& !is_word(bytes.get(i + name.len()))
|
||||
})
|
||||
.nth(n)
|
||||
.expect("occurrence");
|
||||
TextEdit {
|
||||
range: TextRange::new(start as u32, (start + name.len()) as u32),
|
||||
new_text: new.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `verify` over `files` with the given edits, keyed by file name.
|
||||
fn verdict(
|
||||
files: &[(&str, &str)],
|
||||
edits: &[(&str, Vec<TextEdit>)],
|
||||
old: &str,
|
||||
new: &str,
|
||||
) -> Result<(), String> {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
files.iter().map(|(name, text)| (Path::new("/rtl").join(name), text.to_string())).collect();
|
||||
let mut scope = Scope::build(&sources);
|
||||
let mut keyed: Vec<(usize, Vec<TextEdit>)> = edits
|
||||
.iter()
|
||||
.map(|(name, edits)| {
|
||||
let i = scope.index_of(&Path::new("/rtl").join(name)).expect("in scope");
|
||||
(i, edits.clone())
|
||||
})
|
||||
.collect();
|
||||
keyed.sort_by_key(|(i, _)| *i);
|
||||
verify(&mut scope, &keyed, old, new, &mut VerifyTrace::default())
|
||||
}
|
||||
|
||||
fn three() -> Vec<(&'static str, &'static str)> {
|
||||
vec![("sub.sv", SUB), ("other.sv", OTHER), ("top.sv", TOP)]
|
||||
}
|
||||
|
||||
/// The honest rename of `sub`'s `g_lane`: its label, its closing label and
|
||||
/// `u_x`'s path — never `other`'s block or `u_y`'s path.
|
||||
fn honest() -> Vec<(&'static str, Vec<TextEdit>)> {
|
||||
vec![
|
||||
("sub.sv", (0..2).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
|
||||
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_honest_rename_of_one_modules_block_verifies() {
|
||||
assert_eq!(verdict(&three(), &honest(), "g_lane", "g_ln"), Ok(()));
|
||||
}
|
||||
|
||||
/// Not a corruption, and pinned as such: a rename that *also* moves an
|
||||
/// unrelated same-named block together with every use of it changes no
|
||||
/// meaning, and the verifier is a meaning check — it accepts it exactly as it
|
||||
/// accepts the same shape for a net (`sig` in both modules). That the engine
|
||||
/// never produces this edit is pinned by `tests/qa_generate_label.rs`
|
||||
/// (`a_same_named_block_in_another_module_is_never_touched`).
|
||||
#[test]
|
||||
fn a_rename_that_also_moved_the_other_modules_block_consistently_is_meaning_preserving() {
|
||||
let mut edits = honest();
|
||||
edits.push(("other.sv", (0..2).map(|n| at_word(OTHER, "g_lane", n, "g_ln")).collect()));
|
||||
edits[1].1.push(at_word(TOP, "g_lane", 1, "g_ln"));
|
||||
assert_eq!(verdict(&three(), &edits, "g_lane", "g_ln"), Ok(()));
|
||||
let mut nets = vec![
|
||||
("sub.sv", (0..2).map(|n| at_word(SUB, "sig", n, "sg")).collect::<Vec<_>>()),
|
||||
("top.sv", vec![at_word(TOP, "sig", 0, "sg")]),
|
||||
];
|
||||
nets.push(("other.sv", (0..2).map(|n| at_word(OTHER, "sig", n, "sg")).collect()));
|
||||
nets[1].1.push(at_word(TOP, "sig", 1, "sg"));
|
||||
assert_eq!(verdict(&three(), &nets, "sig", "sg"), Ok(()), "the same for a net");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_moved_the_other_instances_path_instead_is_rejected() {
|
||||
let edits = vec![
|
||||
("sub.sv", (0..2).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
|
||||
("top.sv", vec![at_word(TOP, "g_lane", 1, "g_ln")]),
|
||||
];
|
||||
assert!(verdict(&three(), &edits, "g_lane", "g_ln").is_err(), "`u_y.g_ln` names nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_of_one_arm_of_a_same_label_pair_is_rejected() {
|
||||
// The first arm's labels and the path move; the second arm keeps
|
||||
// `g_arm`, so the pair no longer names one block.
|
||||
let edits = vec![(
|
||||
"arms.sv",
|
||||
vec![0, 1, 4].into_iter().map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect(),
|
||||
)];
|
||||
assert!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x").is_err());
|
||||
// …and the second arm's closing label alone left behind.
|
||||
let edits =
|
||||
vec![("arms.sv", (0..3).chain([4]).map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect())];
|
||||
assert!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x").is_err());
|
||||
// The honest one: all five.
|
||||
let edits = vec![("arms.sv", (0..5).map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect())];
|
||||
assert_eq!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x"), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_to_the_genvar_that_captures_the_path_inside_the_loop_is_rejected() {
|
||||
// `g_lane` → `gi`: inside the body `gi[0].sig` would name the genvar.
|
||||
let edits = vec![("inside.sv", (0..3).map(|n| at_word(INSIDE, "g_lane", n, "gi")).collect())];
|
||||
assert!(verdict(&[("inside.sv", INSIDE)], &edits, "g_lane", "gi").is_err());
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! TODO §65.1: masked-corruption attacks on the rename verifier over paths
|
||||
//! through a block label (CLAUDE.md invariant 4).
|
||||
//!
|
||||
//! The verifier gained **no** normalization for block labels: a closing label
|
||||
//! and a path segment are ordinary references now (`vlog_semantic` binds them
|
||||
//! — `docs/features/generate-label-rename/README.md`), so the unchanged
|
||||
//! resolution print compares them like any other use. These attacks pin that
|
||||
//! it does: each hands `verify` a rename of `g_lane` → `g_ln` with one site
|
||||
//! left out, rewritten wrongly or rewritten where no reference is, every one
|
||||
//! of which lexes, parses and — before §65.1 — verified clean.
|
||||
//!
|
||||
//! Crate-internal because `verify` is.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use super::verify;
|
||||
use crate::rename::Scope;
|
||||
use crate::trace::VerifyTrace;
|
||||
use crate::TextEdit;
|
||||
|
||||
const SUB: &str = "module sub (input logic clk, output logic o);
|
||||
for (genvar i = 0; i < 2; i++) begin : g_lane
|
||||
logic sig;
|
||||
assign sig = clk;
|
||||
end : g_lane
|
||||
assign o = g_lane[0].sig;
|
||||
// g_lane in a comment
|
||||
endmodule
|
||||
";
|
||||
|
||||
const TOP: &str = "module top (input logic clk, output logic o);
|
||||
sub u_x (.clk, .o());
|
||||
assign o = u_x.g_lane[1].sig;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A rename's edit at the `n`th (0-based) whole-word `name` in `text`.
|
||||
fn at_word(text: &str, name: &str, n: usize, new: &str) -> TextEdit {
|
||||
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
|
||||
let bytes = text.as_bytes();
|
||||
let start = text
|
||||
.match_indices(name)
|
||||
.map(|(i, _)| i)
|
||||
.filter(|&i| {
|
||||
!is_word(i.checked_sub(1).and_then(|p| bytes.get(p)))
|
||||
&& !is_word(bytes.get(i + name.len()))
|
||||
})
|
||||
.nth(n)
|
||||
.expect("occurrence");
|
||||
TextEdit {
|
||||
range: TextRange::new(start as u32, (start + name.len()) as u32),
|
||||
new_text: new.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `verify` over SUB and TOP with the given edits, keyed by file name.
|
||||
fn verdict(edits: &[(&str, Vec<TextEdit>)]) -> Result<(), String> {
|
||||
let files = vec![
|
||||
(PathBuf::from("/rtl/sub.sv"), SUB.to_string()),
|
||||
(PathBuf::from("/rtl/top.sv"), TOP.to_string()),
|
||||
];
|
||||
let mut scope = Scope::build(&files);
|
||||
let mut keyed: Vec<(usize, Vec<TextEdit>)> = edits
|
||||
.iter()
|
||||
.map(|(name, edits)| {
|
||||
let i = scope.index_of(&Path::new("/rtl").join(name)).expect("in scope");
|
||||
(i, edits.clone())
|
||||
})
|
||||
.collect();
|
||||
keyed.sort_by_key(|(i, _)| *i);
|
||||
verify(&mut scope, &keyed, "g_lane", "g_ln", &mut VerifyTrace::default())
|
||||
}
|
||||
|
||||
/// The honest edits: the label, its closing label and both path segments —
|
||||
/// SUB's first, second and third `g_lane` (the fourth is the comment).
|
||||
fn honest() -> Vec<(&'static str, Vec<TextEdit>)> {
|
||||
vec![
|
||||
("sub.sv", (0..3).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
|
||||
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_honest_rename_verifies() {
|
||||
assert_eq!(verdict(&honest()), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_left_the_same_file_path_segment_is_rejected() {
|
||||
let mut edits = honest();
|
||||
edits[0].1.remove(2);
|
||||
assert!(verdict(&edits).is_err(), "`g_lane[0].sig` would name nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_left_the_closing_label_is_rejected() {
|
||||
let mut edits = honest();
|
||||
edits[0].1.remove(1);
|
||||
assert!(verdict(&edits).is_err(), "`end : g_lane` would close `begin : g_ln`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_left_the_other_files_path_is_rejected() {
|
||||
let mut edits = honest();
|
||||
edits.remove(1);
|
||||
assert!(verdict(&edits).is_err(), "`u_x.g_lane[1].sig` would name nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_of_the_paths_alone_is_rejected() {
|
||||
let edits = vec![
|
||||
("sub.sv", vec![at_word(SUB, "g_lane", 2, "g_ln")]),
|
||||
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
|
||||
];
|
||||
assert!(verdict(&edits).is_err(), "the paths would name a block that does not exist");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_also_rewrote_the_comment_is_rejected() {
|
||||
let mut edits = honest();
|
||||
edits[0].1.push(at_word(SUB, "g_lane", 3, "g_ln"));
|
||||
assert!(verdict(&edits).is_err(), "a comment never changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_rewrote_a_segment_to_a_different_name_is_rejected() {
|
||||
let mut edits = honest();
|
||||
edits[1].1 = vec![at_word(TOP, "g_lane", 0, "g_other")];
|
||||
assert!(verdict(&edits).is_err(), "every edited token spells the new name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_also_rewrote_the_member_after_the_segment_is_rejected() {
|
||||
let mut edits = honest();
|
||||
let sig = at_word(TOP, "sig", 0, "g_ln");
|
||||
edits[1].1.push(sig);
|
||||
assert!(verdict(&edits).is_err(), "`.sig` is another declaration's reference");
|
||||
}
|
||||
@@ -16,14 +16,11 @@
|
||||
//! work log.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{ItemKind, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind};
|
||||
|
||||
use crate::rename::display;
|
||||
|
||||
use super::flow;
|
||||
use super::region::Region;
|
||||
use super::render::{self, Param, Port};
|
||||
@@ -148,18 +145,14 @@ impl Crossing {
|
||||
pub(super) fn warnings(
|
||||
&self,
|
||||
new_name: &str,
|
||||
created: &Option<PathBuf>,
|
||||
file: &Path,
|
||||
created: Option<&str>,
|
||||
file: &str,
|
||||
) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
out.push(match created {
|
||||
Some(path) => format!(
|
||||
"`{new_name}` was written to a new file, `{}`.",
|
||||
display(path)
|
||||
),
|
||||
Some(path) => format!("`{new_name}` was written to a new file, `{path}`."),
|
||||
None => format!(
|
||||
"`{new_name}` was written below its neighbour in `{}`: this editor did not say it can create files, so lucisv did not make one.",
|
||||
display(file)
|
||||
"`{new_name}` was written below its neighbour in `{file}`: this editor did not say it can create files, so lucisv did not make one."
|
||||
),
|
||||
});
|
||||
out.push(format!(
|
||||
|
||||
@@ -254,7 +254,9 @@ impl Extraction {
|
||||
out.push((path.to_path_buf(), file_edits));
|
||||
}
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(Extraction { edits: out, warnings: crossing.warnings(new_name, &created, file) })
|
||||
let created = created.as_deref().map(|path| scope.name_of(path));
|
||||
let warnings = crossing.warnings(new_name, created.as_deref(), &scope.name_of(file));
|
||||
Ok(Extraction { edits: out, warnings })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,7 +287,7 @@ fn confirm(
|
||||
if ports != wanted_ports || params != wanted_params {
|
||||
return Err(format!(
|
||||
"{what} would not leave `{new_name}` with the header lucisv intended in {}; no edits were made.",
|
||||
display(path)
|
||||
scope.name_of(path)
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
|
||||
Loaded 100 of 190 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user