Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7cd439f500 | ||
|
|
c47b16a65e | ||
|
|
17fb2129db | ||
|
|
8dc8f6489f | ||
|
|
33d2f2814f | ||
|
|
203e9b1a4f | ||
|
|
839a28ec8d | ||
|
|
662e323802 | ||
|
|
0e740d77ec | ||
|
|
3bc61f9eab | ||
|
|
01c76067e8 | ||
|
|
34938fbcf1 | ||
|
|
5d0725c158 | ||
|
|
dbd2f176aa | ||
|
|
6523c604bb | ||
|
|
e165c37a3a | ||
|
|
00c03eccf9 | ||
|
|
80b9afdfe3 | ||
|
|
c2ea1a11f6 | ||
|
|
aa303ce9ae | ||
|
|
d3081d6aaf |
No files matched your search
+157
@@ -4,6 +4,163 @@ 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.10.0 — 2026-08-27
|
||||
|
||||
The audit-complete release: TODO.md §9c, the last section of the LSP
|
||||
3.18 audit, shipped one feature per dev/QA/review round — plus the two
|
||||
cross-crate rounds the audit's findings demanded.
|
||||
|
||||
### Go to type definition
|
||||
|
||||
From a name to its type's declaration: variable to typedef, handle to
|
||||
class, instance to module, signal to interface — one redirection into
|
||||
the same two-layer resolution F12 uses, cross-file included.
|
||||
|
||||
### The semantic layer answers cross-file types (and only types)
|
||||
|
||||
Unqualified type-position misses now reach the workspace overlay, so
|
||||
`bus_if bus;` and `my_cls h;` resolve into other files — including
|
||||
inside extending (UVM-style) classes. Value-position identifiers
|
||||
deliberately do not: QA proved a typo could otherwise rename an
|
||||
unrelated same-named module cross-file, and the promotion was narrowed
|
||||
to exactly the positions that name types. 418 corpus references gained
|
||||
a jump target; none lost one. Cross-file interface rename works.
|
||||
|
||||
### The parser accepts direction-less first ANSI ports
|
||||
|
||||
`module m (bus_if bus, input logic clk);` — the normal spelling for
|
||||
interface ports — parses, along with modport-qualified and
|
||||
package-scoped first ports. All 820 corpus files format
|
||||
byte-identically to before, proven by hash on both sides.
|
||||
|
||||
### Linked editing, code lens, on-type formatting
|
||||
|
||||
Closing labels (`endmodule : m`, `end : blk`) edit as one. Every
|
||||
module carries an instantiation-count lens whose click jumps to the
|
||||
sites. Typing `;` reformats the finished statement through the
|
||||
verified engine; a newline indents the new line through a model that
|
||||
agrees with the formatter on 77k corpus lines.
|
||||
|
||||
### Type hierarchy
|
||||
|
||||
Supertypes and subtypes over `extends`, one hop per request, riding
|
||||
the overlay's cross-file resolution.
|
||||
|
||||
### Renaming a file rewrites its includes
|
||||
|
||||
`workspace/willRenameFiles` rewrites every `` `include`` that
|
||||
resolves to a moved file — resolution, never name matching — with a
|
||||
three-check safety net that refuses rather than guesses, edits
|
||||
addressed to pre-rename URIs, and directory renames for free.
|
||||
|
||||
### Workspace folders and pulled configuration
|
||||
|
||||
Folders added or removed mid-session reindex on the spot; clients
|
||||
using the modern configuration-pull model get their settings through
|
||||
the same parser as the push, so the two can never drift.
|
||||
|
||||
### Multi-range formatting
|
||||
|
||||
`textDocument/rangesFormatting` — the request VS Code's client
|
||||
library was asking for all along — formats any set of ranges in one
|
||||
verified pass, the same call the CLI's `--lines a-b,c-d` makes.
|
||||
Snippet workspace edits and server-provided documents are assessed
|
||||
and parked with evidence until a shipping client can consume them.
|
||||
|
||||
## 0.9.0 — 2026-08-26
|
||||
|
||||
The performance-model release: TODO.md §9b, the high-value half of the
|
||||
LSP 3.18 audit, shipped one feature per dev/QA/review round.
|
||||
|
||||
### Incremental text sync
|
||||
|
||||
A keystroke now costs one range on the wire, not the whole file. Edits
|
||||
are applied by one pure function with clamping rules inherited from the
|
||||
existing position converter — a backwards range becomes a pure
|
||||
insertion, the only reading that cannot lose text — cross-checked
|
||||
against an independent reference model over 400 randomized edit
|
||||
sequences. One notification is still one reparse, one diagnostics
|
||||
generation, one publish.
|
||||
|
||||
### Format on save (willSaveWaitUntil)
|
||||
|
||||
The protocol's native format-on-save hook, for editors without one of
|
||||
their own. Off by default (`lucisv.formatOnSave`) so it never fights an
|
||||
editor that already formats on save; when on, it is the formatting
|
||||
request with a different trigger — same engine, same verified-output,
|
||||
all-or-nothing contract. The one protocol gap (no editor tab size on
|
||||
this path) is documented rather than papered over.
|
||||
|
||||
### Semantic tokens: range and delta
|
||||
|
||||
`semanticTokens/range` answers just the lines the editor is showing;
|
||||
`full/delta` answers edits against the previous result instead of the
|
||||
whole token set. One tokenizer and one pure encoder serve full, range
|
||||
and delta, proven byte-identical to the old encoder over a 41k-token
|
||||
corpus file; the delta's single-edit diff carries the classic
|
||||
prefix/suffix overlap trap, deliberately broken twice (dev and QA,
|
||||
independently) to prove the suite catches it.
|
||||
|
||||
### A progress bar on indexing
|
||||
|
||||
Every workspace rescan — the startup build included — now shows a real
|
||||
progress bar in clients that support one: what is being indexed, no
|
||||
invented percentages, and an honest file count when it comes down.
|
||||
|
||||
### $/cancelRequest
|
||||
|
||||
The server reads its backlog in bursts and answers a request whose
|
||||
cancel arrived alongside it with RequestCancelled instead of computing
|
||||
it — completion requests a fast typist already outran no longer cost a
|
||||
parse each. Cancellation is stateless by construction: a cancel matters
|
||||
only next to its own request, everything else is dropped on sight, and
|
||||
no cancel can talk the server out of a shutdown. Enabled by the
|
||||
server's first thread — a 12-line forwarder that makes the client's
|
||||
backlog observable at all through lsp-server's rendezvous channels.
|
||||
|
||||
## 0.8.0 — 2026-08-26
|
||||
|
||||
The protocol-compliance release: the server was audited line-by-line
|
||||
against the LSP 3.18 specification (the full gap list is TODO.md §9),
|
||||
and the three findings that matter most shipped in one round.
|
||||
|
||||
### Port commands now actually edit (workspace/applyEdit)
|
||||
|
||||
`lucisv.addPort`, `lucisv.removePort` and `lucisv.propagatePorts` invoked
|
||||
as *commands* did nothing in every stock client: the server returned the
|
||||
`WorkspaceEdit` as the `executeCommand` result, which the protocol does
|
||||
not define and which `vscode-languageclient` and Neovim both drop. (The
|
||||
code-action lightbulb path was never affected — those edits ride inline.)
|
||||
The server now pushes the edit as a `workspace/applyEdit` request with a
|
||||
label for the undo stack, answers `null`, and reads the client's verdict:
|
||||
a refusal becomes an error popup naming the command and the editor's own
|
||||
reason. A client that never advertised `workspace.applyEdit` keeps the
|
||||
old return-the-edit behavior — for that one it is the only thing that
|
||||
could ever work.
|
||||
|
||||
### Pull diagnostics (LSP 3.17)
|
||||
|
||||
`textDocument/diagnostic` and `workspace/diagnostic` are served, from the
|
||||
same parse+lint pass the push model publishes — one computation, two
|
||||
deliveries, proven byte-identical in tests. Reports carry a `resultId`
|
||||
and answer `unchanged` when nothing that feeds them has moved, so a
|
||||
client re-pulling on focus changes costs nothing. A client that pulls is
|
||||
pushed nothing at all — never both models for one client. Clients that
|
||||
don't advertise the capability keep today's push behavior untouched.
|
||||
Workspace reports cover the open buffers, which is the only scope this
|
||||
server has ever diagnosed.
|
||||
|
||||
### Expand selection (textDocument/selectionRange)
|
||||
|
||||
One keystroke grows the selection from the identifier through the
|
||||
statement, the enclosing `begin`/`end`, the process, the module, out to
|
||||
the whole file. Chains are built from what the server already computes —
|
||||
token spans, the tolerant parse's item/statement spans, and the
|
||||
rainbow's own scope-pair matcher, which keeps expansion working in the
|
||||
half-edited files where you actually reach for it. Every step strictly
|
||||
contains the last; a sweep over all 860 corpus files (6,880 positions)
|
||||
holds the invariant everywhere.
|
||||
|
||||
## 0.7.2 — 2026-08-26
|
||||
|
||||
Honest columns, honest docs, and a CI that enforces the headline number.
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.7.2"
|
||||
version = "0.10.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# lucisv — Language Utility for Coding In SystemVerilog
|
||||
|
||||
A Verilog/SystemVerilog formatter and linter in Rust.
|
||||
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
|
||||
|
||||
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
|
||||
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
|
||||
|
||||
@@ -627,3 +627,386 @@ section only tracks the milestones.
|
||||
CHANGELOG entry covering M7–M14.
|
||||
- [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion,
|
||||
organize imports, …) — triaged in the umbrella README after M5.
|
||||
|
||||
## 9. LSP 3.18 protocol audit (2026-08-26)
|
||||
|
||||
Systematic comparison of `lucisv_server` against the LSP 3.18
|
||||
specification. What we implement: hover, definition, references,
|
||||
documentHighlight, documentLink, document/workspace symbols, folding,
|
||||
semanticTokens/full, inlayHint, completion, inlineCompletion (3.18),
|
||||
signatureHelp, codeAction + executeCommand, rename + prepare,
|
||||
callHierarchy, formatting + rangeFormatting, push diagnostics, dynamic
|
||||
file-watcher registration, configuration push. Below is everything
|
||||
major that's missing, ordered by priority. The `resolve` endpoints
|
||||
(completionItem, codeAction, inlayHint, documentLink, workspaceSymbol)
|
||||
are **deliberately** unadvertised — every item is returned complete —
|
||||
and are not gaps.
|
||||
|
||||
### 9a. Compliance and high-value (round 1)
|
||||
|
||||
- [x] **`executeCommand` must deliver its edit via `workspace/applyEdit`.**
|
||||
Today `ports::execute`'s `WorkspaceEdit` is returned as the request's
|
||||
*result* (`server.rs`, `ports.rs:79`), which the spec does not define
|
||||
and standard clients drop on the floor — `vscode-languageclient` does
|
||||
not apply executeCommand results and `editors/vscode/extension.js`
|
||||
has no custom handler, so `lucisv.addPort`/`removePort`/`propagate`
|
||||
invoked as *commands* currently do nothing in every stock client (the
|
||||
code-action path is unaffected: those carry the edit inline). Fix:
|
||||
push a `workspace/applyEdit` request, return `null` as the command
|
||||
result, and read the `ApplyWorkspaceEditResponse` (the one client
|
||||
response we can no longer ignore wholesale). Gate on the client's
|
||||
`workspace.applyEdit` capability with the old return-the-edit
|
||||
behavior as the documented fallback.
|
||||
→ `docs/features/apply-edit/README.md`; the edit is pushed with a
|
||||
`lucisv: <command>` label, the result is `null`, and a refusal is shown
|
||||
as an ERROR naming the command. Watcher-registration answers stay
|
||||
ignored; `editors/vscode/extension.js` needed no change.
|
||||
- [x] **Pull diagnostics (3.17): `textDocument/diagnostic` +
|
||||
`workspace/diagnostic`.** The modern model — client controls timing,
|
||||
prioritizes visible editors, caches via `resultId`/`unchanged`.
|
||||
Advertise `DiagnosticOptions` (`inter_file_dependencies: true` — a
|
||||
save can change other files' diagnostics through the index;
|
||||
`workspace_diagnostics`), compute from the same parse+lint pass that
|
||||
feeds `publish`, answer `Unchanged` when the buffer version and index
|
||||
generation both stand. Keep push for clients that don't send
|
||||
`text_document.diagnostic` capability; never run both models for the
|
||||
same client (double diagnostics).
|
||||
→ `docs/features/pull-diagnostics/README.md`; one generation counter is
|
||||
the whole `resultId` (bumped by `set_document` and `reindex`), the
|
||||
push gate sits in `send_diagnostics` so the `didClose` clear is
|
||||
suppressed too, and `workspace/diagnostic` reports the open buffers —
|
||||
the honest limit, stated there.
|
||||
- [x] **`textDocument/selectionRange`** — expand-selection. Cheap for
|
||||
us: the scope-pair matcher (`pairs.rs`) and AST spans already give
|
||||
the nesting chain; walk offset → enclosing token → statement → item →
|
||||
scope → file, one linked chain per input position.
|
||||
→ `docs/features/selection-range/README.md`
|
||||
(`crates/lucisv_server/src/selection.rs`); token, AST, scope-pair and
|
||||
file ranges are collected and filtered down to what strictly nests. No
|
||||
expression step — deliberate, and recorded there.
|
||||
|
||||
### 9b. High-value, next rounds
|
||||
|
||||
- [x] **Incremental text sync** (`TextDocumentSyncKind::INCREMENTAL`).
|
||||
Full-buffer sync on every keystroke scales poorly; apply
|
||||
range-scoped `contentChanges` in order, with a full-text fallback on
|
||||
any malformed change. Touches `set_document` and the staleness model
|
||||
in `docs/features/lucisv-server/README.md`.
|
||||
→ `docs/features/incremental-sync/README.md`
|
||||
(`crates/lucisv_server/src/sync.rs`); one pure
|
||||
`apply_changes(text, changes) -> String` over `convert::Positions`, a
|
||||
fresh line table per change so each range sees the previous one's
|
||||
result, rangeless changes still replacing the whole buffer, and every
|
||||
desynced position clamped (line past EOF, character past line end,
|
||||
surrogate half rounds forward, `start > end` becomes an insertion).
|
||||
Still one `set_document` — one reparse, one generation bump, one
|
||||
publish — per notification. Advertised as `TextDocumentSyncOptions`
|
||||
with the open/close and `save.includeText: false` values a bare `Kind`
|
||||
already implied, so no client's save behavior moved.
|
||||
- [x] **`textDocument/willSaveWaitUntil`** — the protocol-native
|
||||
format-on-save hook (client-side `editor.formatOnSave` already works;
|
||||
this serves the editors without it).
|
||||
→ `docs/features/will-save-wait-until/README.md`; advertised as
|
||||
`willSaveWaitUntil: true` (the plain `willSave` notification stays
|
||||
unadvertised — there is nothing for us in it), and gated on a new
|
||||
`lucisv.formatOnSave` setting that is **off** by default, so a client
|
||||
with its own format-on-save never formats twice. On, it is
|
||||
`textDocument/formatting` with a different trigger: same engine, same
|
||||
all-or-nothing edit, same `[]` for an already-formatted buffer, and the
|
||||
settings ladder minus its `tabSize` rung because the request carries no
|
||||
`FormattingOptions`. Every save reason formats; an unopened buffer and
|
||||
the off state both answer `null`.
|
||||
- [x] **Semantic tokens `range` + `full/delta`** — we set
|
||||
`range: None` and no delta, so clients re-request whole-file token
|
||||
sets on every edit. Delta needs `resultId` bookkeeping per buffer.
|
||||
→ `docs/features/semantic-tokens-delta/README.md`; `tokens.rs` split
|
||||
into classification → absolute form → filter → one pure encoder, so
|
||||
all three requests share a tokenizer. `range: Some(true)` answers the
|
||||
overlapping tokens whole, **re-encoded from the start of the
|
||||
document** (a range answer is self-contained, not a slice), carries
|
||||
no `resultId` and is not what a later delta diffs against; an empty
|
||||
range answers nothing. `full: Delta { delta: true }` answers one
|
||||
`SemanticTokensEdit` replacing everything between the common prefix
|
||||
and the common suffix — **the suffix capped to what the prefix left**,
|
||||
because identical lines of Verilog encode identically and an uncapped
|
||||
suffix claims the same tokens twice. `resultId`s are minted per
|
||||
answer, stored by `full` and `full/delta` alike, dropped on
|
||||
`didClose`; an id the server does not hold is answered in full. No
|
||||
token request bumps the diagnostics generation. Not done:
|
||||
`workspace/semanticTokens/refresh`.
|
||||
- [x] **Work-done progress** — `reindex()` is a synchronous full
|
||||
rescan on every save with no `window/workDoneProgress` reporting;
|
||||
on a big filelist the server just goes quiet.
|
||||
→ `docs/features/work-done-progress/README.md`; every workspace
|
||||
rescan — the startup build, a save, a watched file, a changed
|
||||
`lucisv.exclude`/`filelist` — is wrapped in one
|
||||
`window/workDoneProgress/create` plus a `$/progress` begin/end pair
|
||||
on a fresh `lucisv-index-N` token, gated on the client's
|
||||
`window.workDoneProgress` (a client that did not ask is sent nothing
|
||||
at all, as the spec requires). `begin` goes out without waiting for
|
||||
the create's answer, because the rescan blocks the loop the moment
|
||||
it returns; the create's answer is ignored on the same path the
|
||||
watcher registrations' is. No percentage and no intermediate report
|
||||
— the rescan is one opaque call — and the `end` names the indexed
|
||||
file count, read off the index's own file list. The bar covers the
|
||||
scan, ending before the scope warnings and the republishes.
|
||||
- [x] **`$/cancelRequest`** — the loop handles requests sequentially
|
||||
and ignores cancellation; at minimum answer already-cancelled queued
|
||||
requests with `RequestCancelled`.
|
||||
→ `docs/features/cancel-request/README.md`; **completes §9b.** `run()`
|
||||
now reads in bursts — one blocking receive, then everything already
|
||||
queued behind it — and handles the burst **in arrival order**, so a
|
||||
`didChange` ahead of a request is still applied before that request is
|
||||
answered. A request the same burst also carries a cancel for is
|
||||
answered `RequestCancelled` (-32800) without being dispatched; the
|
||||
cancels themselves are consumed there and never reach
|
||||
`notification()`. A cancel naming no request in its burst is dropped
|
||||
on the spot — it refers to a request already answered, or to one that
|
||||
never arrived — so the feature holds no state between bursts, and a
|
||||
double cancel is harmless. `shutdown` is honoured before the cancelled
|
||||
set is consulted and so is never cancellable. Numeric and string ids
|
||||
both read; malformed cancels dropped. The design's one correction:
|
||||
`lsp-server` 0.10 wires its stdio transport with `bounded(0)`
|
||||
*rendezvous* channels, so a backlog never sits on
|
||||
`connection.receiver` at all — the loop forwards messages onto an
|
||||
unbounded `std::sync::mpsc` queue of its own on one small thread
|
||||
(std-only, no new dependency), which stops at `shutdown` so
|
||||
`handle_shutdown` still reads the `exit` that follows. Nothing already
|
||||
running is cancelled; that needs the worker pool §6 defers.
|
||||
|
||||
### 9c. Moderate value, Verilog-shaped
|
||||
|
||||
- [x] **Goto type definition** — from a net/variable use to its
|
||||
typedef/struct/enum/interface declaration; real value once
|
||||
`vlog_semantic` tracks declared types of bindings.
|
||||
→ delivered 2026-08-26 by `docs/features/type-definition/README.md`:
|
||||
`typeDefinitionProvider` + `crates/lucisv_server/src/type_def.rs`.
|
||||
`vlog_semantic` was *not* changed — a binding still carries no type,
|
||||
but the type name it was declared with is already a `Reference`, so
|
||||
the answer is `nav::definition` of that name's own offset, found from
|
||||
the parse tree. Covers typedefs (alias/enum/struct), interfaces,
|
||||
classes, module instances, `pkg::t`, `import pkg::*`, header
|
||||
parameters and task arguments; one hop per keypress on an alias
|
||||
chain; built-ins answer an empty list. Two requests recorded there:
|
||||
`vlog_semantic` should report an unqualified lexical miss as an
|
||||
external candidate (stood in for by a fenced index lookup), and
|
||||
`vlog_parser` cannot parse an ANSI header whose first port has no
|
||||
direction. Both landed: the first on 2026-08-26 by
|
||||
`docs/features/overlay-promotion/README.md`, the second the same day by
|
||||
`docs/features/ansi-first-port/README.md`.
|
||||
- [x] **Linked editing range** — edit `module m` and its
|
||||
`endmodule : m` label together (`end : label`, `endfunction : name`,
|
||||
etc.). A genuinely good fit for SV's closing labels.
|
||||
→ delivered 2026-08-26 by `docs/features/linked-editing/README.md`:
|
||||
`linkedEditingRangeProvider` + `crates/lucisv_server/src/linked.rs`.
|
||||
No engine change — the AST already records both name spans on one
|
||||
node (`name_span` + `end_label_span`), so the pair is a lookup and
|
||||
never a text match, which is what makes `begin : x begin : x ...
|
||||
end : x end : x` answer syntactically. Covers module/macromodule/
|
||||
interface, package, class, function, task, clocking, named
|
||||
`begin`/`fork`, generate blocks and the prefix-labelled `b : begin
|
||||
... end : b`. Two deliberate `null`s: an absent closing label (there
|
||||
is nothing to co-edit and this never offers to create one) and a
|
||||
mismatched one (the spec requires identical text, and linking would
|
||||
silently rewrite broken code). Escaped identifiers are excluded and
|
||||
the SV `wordPattern` is sent. `program ... endprogram : p` and the
|
||||
verbatim blocks (`property`/`sequence`/`covergroup`) are the only
|
||||
labelled constructs left out, because `vlog_parser` keeps no name
|
||||
span for them — recorded in that README's Handshakes.
|
||||
- [x] **Code lens** — "N instantiations" above each module header from
|
||||
the hierarchy index; `codeLens/resolve` unnecessary (counts are
|
||||
cheap), `workspace/codeLens/refresh` on reindex.
|
||||
→ delivered 2026-08-26 by `docs/features/code-lens/README.md`:
|
||||
`codeLensProvider` (`resolveProvider: false`) +
|
||||
`crates/lucisv_server/src/lens.rs`. One lens per module *and*
|
||||
interface declaration, on the declaration's own name span, reading
|
||||
"no instantiations" / "1 instantiation" / "N instantiations". The
|
||||
count is not a second census: `hierarchy::incoming` was split into
|
||||
`hierarchy::callers_of_each`, a batched form of the same walk, so the
|
||||
lens counts exactly what the call hierarchy would list — asserted by
|
||||
an equality test, not by restating the arithmetic. The batch is the
|
||||
primitive because `Workspace::sources()` re-reads the file set, so a
|
||||
three-module file is one walk (133 ms over the corpus) rather than
|
||||
three (93 ms each). Clicking runs `lucisv.showInstantiations`, which
|
||||
answers every site as a `Location` and pushes a `window/showDocument`
|
||||
for the first when the client advertised it; a module with no
|
||||
instantiations gets a display-only lens instead of a click that leads
|
||||
nowhere. `workspace/codeLens/refresh` goes out from `reindex()` after
|
||||
the progress bar comes down, gated on
|
||||
`workspace.codeLens.refreshSupport`. One request recorded there: an
|
||||
instantiation-edge table in `WorkspaceIndex` would make both this and
|
||||
`callHierarchy/incomingCalls` a lookup instead of a workspace walk.
|
||||
- [x] **On-type formatting** — conspicuous absence for a
|
||||
formatter-first server; candidate trigger: newline (indent the new
|
||||
line per block nesting), `;` (reformat the finished statement).
|
||||
→ delivered 2026-08-26 by `docs/features/on-type-formatting/README.md`:
|
||||
`documentOnTypeFormattingProvider` (`"\n"` + `[";"]`) +
|
||||
`crates/lucisv_server/src/on_type.rs`. Both candidate triggers, and
|
||||
only those two — not `}`, since SV closes its blocks with the word
|
||||
`end`. `;` goes through `format::range_formatting` unchanged, over
|
||||
the `;`'s own line, so that half is `textDocument/rangeFormatting`
|
||||
with a different trigger and no new formatting logic at all. `\n` is
|
||||
new logic outside the verified engine, so it is fenced two ways: the
|
||||
edit it builds can structurally only replace one line's leading
|
||||
whitespace with spaces (a wrong answer is a wrong indent, never a
|
||||
moved byte), and a corpus-wide agreement test formats every checked-in
|
||||
file with the real engine and forbids the model from disagreeing with
|
||||
the printer on any line of the output — 77 528 answered, 36 647
|
||||
declined, 0 disagreements, with a coverage floor so it cannot pass
|
||||
vacuously. Nine of the ten rules the model needed were found by that
|
||||
test rather than predicted, including that `vlog_formatter` cuddles a
|
||||
`begin` onto its header but not a `fork`. **The path never speaks**: a
|
||||
refusal is `[]` with no popup, and — a correction to the design — a
|
||||
broken `lucisv.toml` is not reported here either, because
|
||||
`warn_about_config`'s dedup is re-armed by the `didChange` every
|
||||
keystroke produces and would give one popup per character. One
|
||||
deviation recorded there: the `;` range is the `;`'s own line rather
|
||||
than its enclosing AST node's span, which is the same answer wherever
|
||||
both are defined and avoids asking for a whole-module reformat when
|
||||
the `;` is the one closing a module header. `pairs.rs` gained three
|
||||
`pub(crate)` accessors so the matcher and the indent model read one
|
||||
keyword table.
|
||||
- [x] **Type hierarchy (3.17)** — arguably the semantically correct
|
||||
home for the module hierarchy (and later interface/class extends
|
||||
chains); keep callHierarchy as the compatibility surface.
|
||||
→ delivered 2026-08-26 by `docs/features/type-hierarchy/README.md`:
|
||||
`typeHierarchyProvider` + `crates/lucisv_server/src/type_hierarchy.rs`,
|
||||
all three requests. **Classes, not modules** — the lead's scope call:
|
||||
an instantiation is a containment edge and `extends` is an inheritance
|
||||
edge, so the module hierarchy stays on callHierarchy exactly as this
|
||||
item's second clause asks, and typeHierarchy serves one node kind
|
||||
well. `supertypes` is not a new lookup: `extends Base` is already a
|
||||
`vlog_semantic` reference and overlay-promotion already made a bare
|
||||
cross-file class name reachable through it, so the answer is
|
||||
`definition_of` asked at the last byte of the extends name span —
|
||||
which is the tail of `pkg::base`, the whole of a bare `base`, and the
|
||||
bare name of a parameterized `base #(8)`. A base the workspace does
|
||||
not index (every UVM chain top) yields no item rather than a guess.
|
||||
`subtypes` is `hierarchy::callers_of_each`'s census in another key —
|
||||
one `sources()` pass, substring prefilter, deterministic sort — at
|
||||
55 ms over the 860-file corpus, 53 ms of it file I/O; the
|
||||
inheritance-edge table that would make it a lookup is filed beside the
|
||||
instantiation-edge table §9c's code-lens item already recorded. Two
|
||||
gaps recorded there: `lsp-types` 0.97 has no `typeHierarchyProvider`
|
||||
field, so the capability is inserted into the serialized `initialize`
|
||||
result by hand, and `vlog_parser` rejects `interface class`, so
|
||||
`implements` can never resolve and no item can carry
|
||||
`SymbolKind::Interface`.
|
||||
- [x] **File operations** — `workspace/willRenameFiles`: renaming a
|
||||
`.sv/.svh` rewrites `` `include`` lines that reference it (the
|
||||
include graph exists); `didRename/didDelete` as cheaper index nudges
|
||||
than the watcher round-trip.
|
||||
→ delivered 2026-08-27 by `docs/features/file-operations/README.md`:
|
||||
`workspace.fileOperations` + `crates/lucisv_server/src/file_ops.rs`.
|
||||
An include is rewritten only when the graph says it **resolves** to
|
||||
the renamed file — never on a filename match, so two `defs.svh` in
|
||||
one workspace stay two files. The new spelling preserves the form
|
||||
where the new location allows it (bare stays bare when a rung reaches
|
||||
it, angled resolves through `+incdir+`s only, absolute stays
|
||||
absolute), shortest resolving suffix first, with a `../`-relative
|
||||
spelling as the last resort — which is also what answers a renamed
|
||||
include *directory*, since lucisv does not edit filelists. An include
|
||||
no spelling can reach is left exactly as written and named in a
|
||||
`window/showMessage` warning ("log all, show the first", the
|
||||
filelist rule): the server never invents a path that would not
|
||||
resolve. **Folders are handled**, not declined — LSP sends only the
|
||||
folder's URI and a folder is a path prefix, which is the same
|
||||
operation a file rename already was. The rule shipped with a mirror
|
||||
half the brief did not ask for: an include written *in* a file that
|
||||
moves breaks the same way and is re-spelled too. Every edit covers
|
||||
the path token alone (never the backtick, the delimiters or a
|
||||
trailing comment) and is verified three ways before it is emitted —
|
||||
re-scanned, re-lexed, and re-resolved against the filesystem the
|
||||
rename will leave behind. `didRename`/`didDelete` reindex through
|
||||
the same scope predicate the watcher uses, not deduplicated against
|
||||
it (a double rebuild is a re-read, never a different answer). One
|
||||
sweep is 54 ms over the 860-file corpus. `verify.rs` untouched.
|
||||
`includes.rs` gained `resolve_as_if` (so there is still exactly one
|
||||
copy of the EDA search order) and `normalize` became public; the
|
||||
standing request to extract one `lucisv_core::path::normalize` for
|
||||
the three private copies is still open.
|
||||
- [x] **`workspace/didChangeWorkspaceFolders`** — roots are read once
|
||||
at initialize; adding/removing a folder mid-session is ignored.
|
||||
→ delivered 2026-08-27 by `docs/features/folders-and-config/README.md`:
|
||||
`workspace.workspaceFolders { supported, changeNotifications }` +
|
||||
`Workspace::change_roots`. One rescan per *notification* — the event
|
||||
carries both lists, and the progress bar, the code-lens refresh and the
|
||||
diagnostics generation all ride inside the existing `reindex()`. An
|
||||
event that leaves the root set where it was costs nothing: a folder
|
||||
already held, one never held, an empty event, params that do not parse,
|
||||
a non-`file:` folder. A removed folder's files leave the index while
|
||||
its **open buffers stay open and keep being diagnosed** — no code was
|
||||
needed for that, since `collect_sources` appends every open document
|
||||
after the scope ladder has spoken — and removing the *last* folder
|
||||
simply becomes rung 3 of that ladder, the rootless case. The watcher
|
||||
determination is recorded there: the source glob is a base-less string
|
||||
pattern and so is workspace-wide (no re-registration), while the
|
||||
filelist watcher is an absolute path anchored at the first root and is
|
||||
re-registered when a folder change moves it. `state.rs` gained exactly
|
||||
one 8-line method.
|
||||
- [x] **`workspace/configuration` (server-pull)** — we rely solely on
|
||||
push `didChangeConfiguration`; clients are moving to the pull model.
|
||||
→ delivered 2026-08-27 by `docs/features/folders-and-config/README.md`:
|
||||
one `workspace/configuration` for the `lucisv` section at startup and
|
||||
again on every *empty* `didChangeConfiguration` (the 3.17 client's
|
||||
"something changed, ask me"), gated on `workspace.configuration`. A
|
||||
push with a payload still applies directly, so the legacy path is
|
||||
untouched; a client without the capability keeps exactly today's
|
||||
behaviour, empty-payload semantics included. **One parser** — the
|
||||
answer's entry 0 is wrapped back into the push shape and read by the
|
||||
same `settings::from_payload` — and **one applier**, so `exclude`/
|
||||
`filelist` cost the same rescan and the same watcher re-registration
|
||||
whichever door they came in. An error, a `null`, an empty array or junk
|
||||
all resolve to the defaults and none of them says anything to the user.
|
||||
The outstanding-request tracking was refactored from `applying:
|
||||
HashMap<RequestId, String>` to `pending: HashMap<RequestId, Pending>`,
|
||||
one map and one `match`, with the three-way interleave
|
||||
(applyEdit + progress create + configuration) under test. Known and
|
||||
stated, not fixed: a pulled setting can land after the first index
|
||||
build, exactly as a pushed one always could.
|
||||
- [x] **3.18 additions:** `textDocument/rangesFormatting` (multi-range,
|
||||
feeds format-modified-lines), snippet edits in `WorkspaceEdit`
|
||||
(would improve `addPort` cursor placement), and
|
||||
`workspace/textDocumentContent` (could serve a read-only "expanded
|
||||
macro" document).
|
||||
→ 2026-08-27 by `docs/features/lsp-318-extras/README.md`: **one
|
||||
shipped, two parked with evidence.** *Shipped* —
|
||||
`textDocument/rangesFormatting`, served as the `n`-range case of
|
||||
`rangeFormatting`: the ranges become one sorted, merged `LineRanges`
|
||||
(the constructor `--lines 3-9,40` already used, so unsorted,
|
||||
overlapping, adjacent and repeated ranges all normalize in the one
|
||||
place) and one `format_range` call, which keeps the all-or-nothing
|
||||
contract over the *union* rather than making it a per-range promise.
|
||||
`range_formatting` is now defined as the one-element call of it, so
|
||||
the reply shape, the refusal and the config warning are the same
|
||||
values and cannot drift; an empty `ranges` array is an ask for
|
||||
nothing, not an error. The capability is advertised by widening
|
||||
`documentRangeFormattingProvider` from `true` to
|
||||
`{ "rangesSupport": true }` — the spec's own
|
||||
`boolean | DocumentRangeFormattingOptions` union — **gated on the
|
||||
client having sent `textDocument.rangeFormatting.rangesSupport`**, so
|
||||
every client that shipped before this round sees the identical byte
|
||||
and only a 3.18 client sees the object; the handler is registered
|
||||
unconditionally. `lsp-types` 0.97 spells neither half, so the
|
||||
capability goes out through the `initialize_value()` JSON insertion
|
||||
(the type-hierarchy precedent) and the client flag is read from the
|
||||
**raw** initialize params before the typed decode drops it.
|
||||
*Parked* — **snippet `WorkspaceEdit` edits**: `lsp-types` 0.97 has no
|
||||
`SnippetTextEdit`, `WorkspaceEditClientCapabilities` has no
|
||||
`snippetEditSupport`, and the pinned `vscode-languageclient@9.0.1`
|
||||
has neither string anywhere in it, so a server sending one would be
|
||||
writing a literal `${1:name}` into the user's buffer. *Parked* —
|
||||
**`workspace/textDocumentContent`**: absent from `lsp-types` 0.97 and
|
||||
from the pinned client, and serving a custom URI scheme in VS Code
|
||||
needs a content provider the deliberately thin `extension.js` does
|
||||
not register; the expanded-macro view it would serve is also
|
||||
hover-sized today, not document-sized. Both have an exact re-check
|
||||
trigger recorded (one `node_modules` grep each). **This completes
|
||||
§9c.**
|
||||
|
||||
### 9d. Deliberately skipped (no Verilog use case)
|
||||
|
||||
Notebook sync, moniker (LSIF), inline value (debugger), document
|
||||
color, goto implementation, goto declaration (Verilog has no
|
||||
declaration/definition split lucisv models). Recorded here so the
|
||||
audit doesn't repeat.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,15 +1,16 @@
|
||||
//! `textDocument/formatting` and `textDocument/rangeFormatting`.
|
||||
//! `textDocument/formatting`, `textDocument/rangeFormatting` and
|
||||
//! `textDocument/rangesFormatting`.
|
||||
//!
|
||||
//! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and
|
||||
//! these handlers keep it: either one whole-document edit built from verified
|
||||
//! output, or no edit at all and an error for the user to read. That holds for
|
||||
//! the range request too — its output is verified over the whole buffer, and
|
||||
//! what makes it a *range* format is which constructs it laid out, not which
|
||||
//! bytes it was allowed to replace.
|
||||
//! 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.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::{FormattingOptions, Range, TextEdit};
|
||||
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
|
||||
@@ -60,6 +61,20 @@ pub fn settings_for(
|
||||
Settings { config: config_from(&file, client, options), problem }
|
||||
}
|
||||
|
||||
/// Resolve the settings governing a buffer for a request that carries no
|
||||
/// `FormattingOptions`.
|
||||
///
|
||||
/// `textDocument/willSaveWaitUntil` has no options field at all — the protocol
|
||||
/// simply does not carry one there. So the ladder `settings_for` documents
|
||||
/// runs with rung 3 missing, which is the same thing `indent_width` does for a
|
||||
/// lint fix: `lucisv.toml` > the pushed `lucisv.*` settings > the built-in
|
||||
/// default. Spelled as hard tabs and a zero width because `config_from` takes
|
||||
/// neither, so nothing is guessed on the user's behalf.
|
||||
pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings) -> Settings {
|
||||
let none = FormattingOptions { tab_size: 0, insert_spaces: false, ..Default::default() };
|
||||
settings_for(doc, client, &none)
|
||||
}
|
||||
|
||||
/// Format a buffer.
|
||||
///
|
||||
/// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an
|
||||
@@ -74,29 +89,57 @@ pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, S
|
||||
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
|
||||
}
|
||||
|
||||
/// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request.
|
||||
///
|
||||
/// Spelled out here because `lsp-types` 0.97 predates it — the same reason
|
||||
/// `pairs::ScopePairsParams` is hand-rolled. See
|
||||
/// `docs/features/lsp-318-extras/README.md`.
|
||||
pub const RANGES_FORMATTING: &str = "textDocument/rangesFormatting";
|
||||
|
||||
/// `textDocument/rangesFormatting` params: one document, `n` ranges, one set
|
||||
/// of options.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RangesFormattingParams {
|
||||
pub text_document: TextDocumentIdentifier,
|
||||
pub ranges: Vec<Range>,
|
||||
pub options: FormattingOptions,
|
||||
}
|
||||
|
||||
/// Format the constructs a selection reaches, and nothing else.
|
||||
///
|
||||
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
|
||||
/// wants 1-based inclusive *lines*, so only the line numbers survive the
|
||||
/// conversion. An end position at character 0 still names its line — an
|
||||
/// editor's "select these three lines" ends at the start of the fourth — so
|
||||
/// a range that stops at a line's very beginning does not drag that line in
|
||||
/// unless it is also where the range started.
|
||||
///
|
||||
/// 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
|
||||
/// buffer only where it decided to differ.
|
||||
/// The one-range case of [`ranges_formatting`], which is where the whole
|
||||
/// answer lives — an `n`-range request is this request with `n` line spans.
|
||||
pub fn range_formatting(
|
||||
doc: &Document,
|
||||
config: &Config,
|
||||
range: Range,
|
||||
) -> Result<Option<TextEdit>, String> {
|
||||
let first = range.start.line.saturating_add(1);
|
||||
// An end at character 0 of a later line is the start of that line, not
|
||||
// any of its content.
|
||||
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
|
||||
let last = if ends_before_its_line { range.end.line } else { range.end.line + 1 };
|
||||
let lines = LineRanges::new([(first, last.max(first))])?;
|
||||
ranges_formatting(doc, config, std::slice::from_ref(&range))
|
||||
}
|
||||
|
||||
/// Format the constructs any of several selections reach, and nothing else.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// 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
|
||||
/// buffer only where it decided to differ. An empty range list is not an
|
||||
/// error — it is an ask for nothing, answered with no edit.
|
||||
pub fn ranges_formatting(
|
||||
doc: &Document,
|
||||
config: &Config,
|
||||
ranges: &[Range],
|
||||
) -> Result<Option<TextEdit>, String> {
|
||||
if ranges.is_empty() {
|
||||
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())?;
|
||||
if formatted == doc.text {
|
||||
return Ok(None);
|
||||
@@ -104,6 +147,27 @@ pub fn range_formatting(
|
||||
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
|
||||
}
|
||||
|
||||
/// The 1-based inclusive line span an LSP range names.
|
||||
///
|
||||
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
|
||||
/// wants lines, so only the line numbers survive the conversion — which
|
||||
/// sidesteps the UTF-16 column question rather than solving it again. An end
|
||||
/// position at character 0 still names its line — an editor's "select these
|
||||
/// three lines" ends at the start of the fourth — so a range that stops at a
|
||||
/// line's very beginning does not drag that line in unless it is also where
|
||||
/// the range started.
|
||||
///
|
||||
/// One conversion, shared by both range requests: a second spelling of this
|
||||
/// rule would be a second thing to get wrong.
|
||||
fn lines_of(range: Range) -> (u32, u32) {
|
||||
let first = range.start.line.saturating_add(1);
|
||||
// An end at character 0 of a later line is the start of that line, not
|
||||
// any of its content.
|
||||
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
|
||||
let last = if ends_before_its_line { range.end.line } else { range.end.line.saturating_add(1) };
|
||||
(first, last.max(first))
|
||||
}
|
||||
|
||||
/// The indent width governing a buffer, for a lint fix that has to write
|
||||
/// spaces where a tab was.
|
||||
///
|
||||
@@ -495,6 +559,31 @@ mod tests {
|
||||
assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_without_options_climbs_the_same_ladder_without_rung_3() {
|
||||
// What `willSaveWaitUntil` resolves to: the protocol sends no
|
||||
// `FormattingOptions` with it, so the editor's tab size is simply not
|
||||
// one of the inputs.
|
||||
let tree = Tree::new("indent = 4\n");
|
||||
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let settings = settings_without_editor_options(doc, &pushed(None, Some(8)));
|
||||
assert_eq!(settings.config.indent_width, 4, "the config still wins");
|
||||
assert_eq!(settings.problem, None);
|
||||
|
||||
// With no config, the pushed setting is the highest rung there is.
|
||||
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let settings = settings_without_editor_options(doc, &pushed(Some(60), Some(8)));
|
||||
assert_eq!(settings.config.indent_width, 8);
|
||||
assert_eq!(settings.config.max_width, 60);
|
||||
// And with nothing pushed either, the built-in default — never a
|
||||
// guess from an option that was not sent.
|
||||
let settings = settings_without_editor_options(doc, &none());
|
||||
assert_eq!(settings.config.indent_width, Config::default().indent_width);
|
||||
assert_eq!(settings.config.max_width, Config::default().max_width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_config_leaves_the_pushed_settings_in_charge() {
|
||||
// Nothing from a broken `lucisv.toml` is used, so the next rung down is
|
||||
@@ -586,6 +675,145 @@ mod tests {
|
||||
assert!(!message.is_empty(), "the user needs something to read");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `rangesFormatting` — the union of the ranges, on the one engine
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Four items, one per line, so two disjoint ranges can reach two of them
|
||||
/// and leave the ones between untouched.
|
||||
const FOUR: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
||||
|
||||
fn multi(text: &str, ranges: &[Range]) -> Result<Option<TextEdit>, String> {
|
||||
let (ws, uri) = document(text);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
ranges_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, ranges)
|
||||
}
|
||||
|
||||
/// The `new_text` a multi-range request answers with, or `None`.
|
||||
fn multi_text(text: &str, ranges: &[Range]) -> Option<String> {
|
||||
multi(text, ranges).expect("formats").map(|edit| edit.new_text)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_ranges_lay_out_both_the_items_they_reach_and_nothing_between() {
|
||||
// Lines 2 and 4 selected, line 3 not: `b` keeps its bytes.
|
||||
let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed");
|
||||
assert_eq!(both, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_range_answer_is_the_union_of_the_single_range_answers() {
|
||||
// The contract, stated as an equality rather than as a re-spelled
|
||||
// expectation: where two ranges do not interact, asking for both at
|
||||
// once is asking for each and taking both results. Line 2 formatted
|
||||
// alone, then line 4 formatted on *that* text, must be byte-identical
|
||||
// to one request naming both.
|
||||
let first = ranged(FOUR, at(1, 0, 1, 11)).expect("formats").expect("changed").new_text;
|
||||
let second = ranged(&first, at(3, 0, 3, 11)).expect("formats").expect("changed").new_text;
|
||||
let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed");
|
||||
assert_eq!(both, second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_arrive_unsorted_overlapping_adjacent_or_twice_and_mean_the_same_thing() {
|
||||
// `LineRanges::new` sorts and merges, and this asserts it through the
|
||||
// answer rather than restating the arithmetic. All four spellings name
|
||||
// lines 2 and 3.
|
||||
let want = multi_text(FOUR, &[at(1, 0, 2, 11)]).expect("changed");
|
||||
assert_eq!(want, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
||||
for (spelling, ranges) in [
|
||||
("unsorted", vec![at(2, 0, 2, 11), at(1, 0, 1, 11)]),
|
||||
("overlapping", vec![at(1, 0, 2, 4), at(2, 0, 2, 11)]),
|
||||
("adjacent", vec![at(1, 0, 1, 11), at(2, 0, 2, 11)]),
|
||||
("the same range twice", vec![at(1, 0, 2, 11), at(1, 0, 2, 11)]),
|
||||
] {
|
||||
assert_eq!(multi_text(FOUR, &ranges).as_deref(), Some(want.as_str()), "{spelling}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_range_list_is_an_ask_for_nothing_and_not_an_error() {
|
||||
// A client with no selections must not get a popup. `LineRanges::new`
|
||||
// refuses an empty list — that refusal is the CLI's (`--lines ''` is a
|
||||
// typo), and it is answered before the engine here.
|
||||
assert_eq!(multi(FOUR, &[]).expect("never an error"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_range_over_the_whole_buffer_is_the_whole_file_format() {
|
||||
let whole = multi_text(FOUR, &[at(0, 0, 99, 0)]).expect("changed");
|
||||
assert_eq!(whole, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
||||
// And so is every line named separately, which is the same union.
|
||||
let each: Vec<Range> = (0..5).map(|line| at(line, 0, line, 11)).collect();
|
||||
assert_eq!(multi_text(FOUR, &each).as_deref(), Some(whole.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_element_multi_range_request_is_the_single_range_request() {
|
||||
// `range_formatting` is *defined* as this call, so the two can never
|
||||
// drift — but the equality is what a client relies on, so it is
|
||||
// asserted rather than argued.
|
||||
for range in [at(1, 4, 1, 4), at(1, 0, 3, 0), at(3, 0, 3, 9), at(0, 0, 99, 0)] {
|
||||
assert_eq!(ranged(THREE, range), multi(THREE, &[range]), "{range:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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.
|
||||
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)]);
|
||||
assert!(one.is_err() && many.is_err(), "a broken buffer is refused both ways");
|
||||
assert_eq!(one, many, "byte-identical refusals, message included");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_range_format_is_a_fixed_point_under_the_same_ranges() {
|
||||
// Idempotency through the new path: format lines 2 and 4, then ask for
|
||||
// exactly the same two ranges on the answer — nothing left to do.
|
||||
let ranges = [at(1, 0, 1, 11), at(3, 0, 3, 11)];
|
||||
let once = multi_text(FOUR, &ranges).expect("changed");
|
||||
assert_eq!(multi_text(&once, &ranges), None, "the second run has nothing to say");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_range_request_over_already_formatted_lines_produces_no_edit() {
|
||||
let clean = "module m;\n wire a;\n wire b;\nendmodule\n";
|
||||
assert_eq!(multi(clean, &[at(0, 0, 0, 9), at(1, 0, 1, 9)]).expect("formats"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_content_survives_a_multi_range_format_too() {
|
||||
// The columns are UTF-16 units and only the lines reach the engine, so
|
||||
// an emoji two lines up must not shift which items are laid out.
|
||||
let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n";
|
||||
let out = multi_text(text, &[at(2, 0, 2, 11), at(3, 0, 3, 11)]).expect("changed");
|
||||
assert_eq!(out, "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n");
|
||||
assert!(out.contains("é ✓ 🎉"), "comments are never dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_conversion_is_the_one_rangeformatting_always_used() {
|
||||
// Pinned directly, because both requests now share it: a cursor names
|
||||
// its own line; an end at character 0 of a *later* line stops one line
|
||||
// short; an end at character 0 on the start line does not.
|
||||
assert_eq!(lines_of(at(1, 4, 1, 4)), (2, 2), "a cursor");
|
||||
assert_eq!(lines_of(at(1, 0, 3, 0)), (2, 3), "select two lines");
|
||||
assert_eq!(lines_of(at(2, 0, 3, 0)), (3, 3), "select one line");
|
||||
assert_eq!(lines_of(at(2, 0, 2, 0)), (3, 3), "an empty range on its own line");
|
||||
assert_eq!(lines_of(at(0, 0, 99, 0)), (1, 99), "past the end of the buffer");
|
||||
// And it never produces a span `LineRanges` would refuse: line 0 is
|
||||
// impossible (1-based), and `last` can never fall below `first`.
|
||||
assert_eq!(lines_of(at(0, 0, 0, 0)), (1, 1), "the very first line");
|
||||
assert_eq!(
|
||||
lines_of(at(u32::MAX, 0, u32::MAX, 0)),
|
||||
(u32::MAX, u32::MAX),
|
||||
"a saturating add, not an overflow"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_content_survives_formatting() {
|
||||
let (ws, uri) = document("module m;\n// é ✓ 🎉\nwire a;\nendmodule\n");
|
||||
|
||||
@@ -25,7 +25,7 @@ use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
|
||||
use vlog_semantic::SymbolKind as SemanticKind;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::instantiations::{self, Decl};
|
||||
use crate::instantiations::{self, Decl, Site};
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
@@ -60,27 +60,59 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
|
||||
/// Who instantiates this module: one call per **instantiating module**, with
|
||||
/// every instantiation site inside it.
|
||||
///
|
||||
/// One name asked of the batch below, which is the only census in this server
|
||||
/// — the code lens counts what this lists.
|
||||
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
|
||||
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Who instantiates each of `names`, answered one list per name in the order
|
||||
/// asked.
|
||||
///
|
||||
/// Every in-scope file is walked, because the workspace index records what a
|
||||
/// file *declares* and not what it instantiates — there is no edge table to
|
||||
/// consult. A file whose text does not contain the name at all is skipped
|
||||
/// before it is parsed, which is what keeps the walk affordable: an
|
||||
/// instantiation of `fifo` has to write `fifo`.
|
||||
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
|
||||
// Nothing this server hands out is nameless, so an empty name is a
|
||||
// malformed item — and the prefilter below matches every file for it,
|
||||
// which would read and parse the whole workspace to find nothing.
|
||||
if item.name.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut calls: Vec<CallHierarchyIncomingCall> = Vec::new();
|
||||
/// consult. A file whose text contains none of the names is skipped before it
|
||||
/// is parsed, which is what keeps the walk affordable: an instantiation of
|
||||
/// `fifo` has to write `fifo`.
|
||||
///
|
||||
/// The **batch** is the primitive rather than the single name because
|
||||
/// [`Workspace::sources`] re-reads every in-scope file: one question per name
|
||||
/// would re-read the whole workspace once per name, and `lens.rs` asks about
|
||||
/// every module declared in a buffer at once. A file is parsed once for the
|
||||
/// whole batch.
|
||||
///
|
||||
/// An empty name is answered with nothing rather than searched for: nothing
|
||||
/// this server hands out is nameless, and the prefilter matches every file for
|
||||
/// one, which would parse the whole workspace to find nothing.
|
||||
pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyIncomingCall>> {
|
||||
let mut answers: Vec<Vec<CallHierarchyIncomingCall>> =
|
||||
names.iter().map(|_| Vec::new()).collect();
|
||||
for (path, text) in ws.sources() {
|
||||
calls.extend(callers_in(&path, &text, &item.name));
|
||||
let wanted: Vec<usize> = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, name)| !name.is_empty() && text.contains(**name))
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(uri) = path_to_uri(&path) else { continue };
|
||||
let (tree, _) = parse_source_tolerant(&text);
|
||||
let sites = instantiations::sites(&tree.items);
|
||||
let line_index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &line_index);
|
||||
for index in wanted {
|
||||
answers[index].extend(callers_in(&uri, &positions, &sites, names[index]));
|
||||
}
|
||||
}
|
||||
calls.sort_by(|a, b| {
|
||||
(a.from.uri.as_str(), key(a.from.selection_range))
|
||||
.cmp(&(b.from.uri.as_str(), key(b.from.selection_range)))
|
||||
});
|
||||
calls
|
||||
for answer in &mut answers {
|
||||
answer.sort_by(|a, b| {
|
||||
(a.from.uri.as_str(), key(a.from.selection_range))
|
||||
.cmp(&(b.from.uri.as_str(), key(b.from.selection_range)))
|
||||
});
|
||||
}
|
||||
answers
|
||||
}
|
||||
|
||||
/// What this module instantiates: one call per **distinct instantiated
|
||||
@@ -120,17 +152,16 @@ pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOu
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every module in one file that instantiates `name`, with its sites.
|
||||
fn callers_in(path: &Path, text: &str, name: &str) -> Vec<CallHierarchyIncomingCall> {
|
||||
// An instantiation of `name` writes `name`. Nearly every file in a
|
||||
// workspace does not, and this is what keeps those files unparsed.
|
||||
if !text.contains(name) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(uri) = path_to_uri(path) else { return Vec::new() };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let mut callers: Vec<(Decl, Vec<TextRange>)> = Vec::new();
|
||||
for site in instantiations::sites(&tree.items) {
|
||||
/// Every module in one already-parsed file that instantiates `name`, with its
|
||||
/// sites.
|
||||
fn callers_in<'a>(
|
||||
uri: &Uri,
|
||||
positions: &Positions,
|
||||
sites: &[Site<'a>],
|
||||
name: &str,
|
||||
) -> Vec<CallHierarchyIncomingCall> {
|
||||
let mut callers: Vec<(Decl<'a>, Vec<TextRange>)> = Vec::new();
|
||||
for site in sites {
|
||||
if site.inst.module != name {
|
||||
continue;
|
||||
}
|
||||
@@ -141,16 +172,11 @@ fn callers_in(path: &Path, text: &str, name: &str) -> Vec<CallHierarchyIncomingC
|
||||
None => callers.push((owner, vec![site.inst.module_span])),
|
||||
}
|
||||
}
|
||||
if callers.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let line_index = LineIndex::new(text);
|
||||
let positions = Positions::new(text, &line_index);
|
||||
callers
|
||||
.into_iter()
|
||||
.filter_map(|(decl, spans)| {
|
||||
Some(CallHierarchyIncomingCall {
|
||||
from: item(uri.clone(), &positions, decl)?,
|
||||
from: item(uri.clone(), positions, decl)?,
|
||||
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -134,6 +134,12 @@ impl IncludeGraph {
|
||||
graph
|
||||
}
|
||||
|
||||
/// The `+incdir+` directories an include is looked for in, in filelist
|
||||
/// order — the search rungs past the including file's own directory.
|
||||
pub fn incdirs(&self) -> &[PathBuf] {
|
||||
&self.incdirs
|
||||
}
|
||||
|
||||
/// The file an `` `include`` names, or `None` when nothing on disk
|
||||
/// answers to it.
|
||||
///
|
||||
@@ -142,9 +148,26 @@ impl IncludeGraph {
|
||||
/// order. The `<angled>` form skips the own-directory rung, which is the C
|
||||
/// convention and the only difference the two spellings make here.
|
||||
pub fn resolve(&self, from: Option<&Path>, include: &Include) -> Option<PathBuf> {
|
||||
self.resolve_as_if(from, include, &|path| path.is_file())
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::resolve`], asked about a filesystem that has not
|
||||
/// happened yet: `exists` decides which paths are files.
|
||||
///
|
||||
/// The one search order, spent twice — `file_ops.rs` has to know where an
|
||||
/// include *will* land once a rename the client has announced goes
|
||||
/// through, and a second copy of the rung order there could disagree with
|
||||
/// this one in exactly the corner cases nobody tests. See
|
||||
/// `docs/features/file-operations/README.md`.
|
||||
pub fn resolve_as_if(
|
||||
&self,
|
||||
from: Option<&Path>,
|
||||
include: &Include,
|
||||
exists: &dyn Fn(&Path) -> bool,
|
||||
) -> Option<PathBuf> {
|
||||
let target = Path::new(&include.target);
|
||||
if target.is_absolute() {
|
||||
return target.is_file().then(|| self.as_the_index_spells_it(normalize(target)));
|
||||
return exists(target).then(|| self.as_the_index_spells_it(normalize(target)));
|
||||
}
|
||||
let own = match include.system {
|
||||
true => None,
|
||||
@@ -153,7 +176,7 @@ impl IncludeGraph {
|
||||
own.into_iter()
|
||||
.chain(self.incdirs.iter().map(PathBuf::as_path))
|
||||
.map(|dir| dir.join(target))
|
||||
.find(|candidate| candidate.is_file())
|
||||
.find(|candidate| exists(candidate))
|
||||
.map(|found| self.as_the_index_spells_it(normalize(&found)))
|
||||
}
|
||||
|
||||
@@ -211,7 +234,11 @@ impl IncludeGraph {
|
||||
/// Fold `.`/`..` away so one file has one spelling, and so a resolved include
|
||||
/// compares equal to the same file's path in the index. Symlinks are
|
||||
/// deliberately not resolved, matching `lucisv_core`'s lexical rule.
|
||||
fn normalize(path: &Path) -> PathBuf {
|
||||
///
|
||||
/// Public since 2026-08-27 so `file_ops.rs` folds a renamed file's path the
|
||||
/// same way a resolved include is folded — the two are compared, and a fourth
|
||||
/// private copy of this loop is the one thing that guarantees they disagree.
|
||||
pub fn normalize(path: &Path) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
|
||||
@@ -0,0 +1,697 @@
|
||||
//! `textDocument/codeLens`: how often the workspace instantiates the module
|
||||
//! written on this line.
|
||||
//!
|
||||
//! One lens per module (and per interface — the same AST node) declared in the
|
||||
//! open buffer, sitting on the declaration's own name so the editor draws it
|
||||
//! on the line above the header. It reads **"N instantiations"**, "1
|
||||
//! instantiation", or "no instantiations", and N is the number of
|
||||
//! instantiation *sites* across the whole workspace — the same population
|
||||
//! `callHierarchy/incomingCalls` reports, counted by the same walk
|
||||
//! ([`hierarchy::callers_of_each`]) so the two can never disagree.
|
||||
//!
|
||||
//! **Clicking.** The lens carries `lucisv.showInstantiations`, run through the
|
||||
//! `workspace/executeCommand` this server already serves. The command answers
|
||||
//! with every site as a `Location`, and — for a client that advertised
|
||||
//! `window/showDocument` — the server pushes a request to open the first of
|
||||
//! them, which is what makes the click actually move a cursor. LSP has no
|
||||
//! server-initiated "peek these seven places"; that is a VS Code command, and
|
||||
//! this repo's extension does not declare one. A module with **no**
|
||||
//! instantiations gets a display-only lens instead (an empty `command`
|
||||
//! string, as rust-analyzer ships for the same case): there is nothing to
|
||||
//! open, and a click that led nowhere would be worse than no click.
|
||||
//!
|
||||
//! See `docs/features/code-lens/README.md`.
|
||||
|
||||
use lsp_types::{CodeLens, Command, Location, Uri};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Workspace;
|
||||
use crate::{hierarchy, instantiations};
|
||||
|
||||
/// Show every instantiation of a module: `[module-name]`.
|
||||
pub const SHOW_INSTANTIATIONS: &str = "lucisv.showInstantiations";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![SHOW_INSTANTIATIONS.to_string()]
|
||||
}
|
||||
|
||||
/// One lens per module or interface declared in the open buffer, counting the
|
||||
/// workspace's instantiations of it.
|
||||
///
|
||||
/// `None` — which the handler sends as `null` — for a buffer this server was
|
||||
/// never shown, matching every other request that answers from a `Document`.
|
||||
/// A buffer that declares nothing the parser could name gets an empty list:
|
||||
/// the file was read, and it has no declarations to decorate.
|
||||
pub fn code_lenses(ws: &Workspace, uri: &Uri) -> Option<Vec<CodeLens>> {
|
||||
let doc = ws.document(uri)?;
|
||||
// A declaration the parser could not name — recovered from broken text,
|
||||
// or reached through an error item — has no span to hang a lens on.
|
||||
let decls: Vec<_> = instantiations::declarations(&doc.tree.items)
|
||||
.into_iter()
|
||||
.filter(|decl| !decl.module.name_span.is_empty())
|
||||
.collect();
|
||||
if decls.is_empty() {
|
||||
// Before the workspace walk: a buffer with nothing to decorate must
|
||||
// not read every file in the project to learn that.
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let names: Vec<&str> = decls.iter().map(|decl| decl.module.name.as_str()).collect();
|
||||
let callers = hierarchy::callers_of_each(ws, &names);
|
||||
let positions = doc.positions();
|
||||
Some(
|
||||
decls
|
||||
.iter()
|
||||
.zip(callers)
|
||||
.map(|(decl, calls)| CodeLens {
|
||||
range: positions.range(decl.module.name_span),
|
||||
command: Some(command(&decl.module.name, sites_in(&calls))),
|
||||
data: None,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Run `lucisv.showInstantiations`: every place the workspace instantiates the
|
||||
/// named module, as locations.
|
||||
///
|
||||
/// One location per **site**, not per instantiating module — that is what the
|
||||
/// lens counted, and a caller that asked to see "7 instantiations" wants seven
|
||||
/// places. A name nothing instantiates answers an empty list rather than an
|
||||
/// error: a module waiting to be used is an ordinary state, and it is the
|
||||
/// state whose lens does not click in the first place.
|
||||
pub fn execute(ws: &Workspace, arguments: &[Value]) -> Result<Vec<Location>, String> {
|
||||
let name =
|
||||
arguments.first().and_then(Value::as_str).filter(|name| !name.is_empty()).ok_or_else(
|
||||
|| format!("{SHOW_INSTANTIATIONS} wants a module name as its first argument."),
|
||||
)?;
|
||||
Ok(sites_of(ws, name))
|
||||
}
|
||||
|
||||
/// Every instantiation of `name` in the workspace, one location per site, in
|
||||
/// the order the hierarchy lists its callers.
|
||||
fn sites_of(ws: &Workspace, name: &str) -> Vec<Location> {
|
||||
hierarchy::callers_of_each(ws, &[name])
|
||||
.pop()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.flat_map(|call| {
|
||||
let uri = call.from.uri;
|
||||
call.from_ranges.into_iter().map(move |range| Location { uri: uri.clone(), range })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many sites one name's incoming calls hold. A caller reports every site
|
||||
/// inside it, so the count is the sum and not the number of callers.
|
||||
fn sites_in(calls: &[lsp_types::CallHierarchyIncomingCall]) -> usize {
|
||||
calls.iter().map(|call| call.from_ranges.len()).sum()
|
||||
}
|
||||
|
||||
/// The lens for one module: what it reads, and what clicking it runs.
|
||||
///
|
||||
/// A module nothing instantiates gets a display-only lens — a `Command` whose
|
||||
/// `command` is the empty string, which clients render as plain text. See the
|
||||
/// module comment for why.
|
||||
fn command(name: &str, sites: usize) -> Command {
|
||||
Command {
|
||||
title: title(sites),
|
||||
command: if sites == 0 { String::new() } else { SHOW_INSTANTIATIONS.to_string() },
|
||||
arguments: (sites > 0).then(|| vec![Value::String(name.to_string())]),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the lens reads, in the user's own arithmetic.
|
||||
fn title(sites: usize) -> String {
|
||||
match sites {
|
||||
0 => "no instantiations".to_string(),
|
||||
1 => "1 instantiation".to_string(),
|
||||
many => format!("{many} instantiations"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use lsp_types::CallHierarchyItem;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A scratch workspace root, removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_lens_{}_{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) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).expect("mkdir");
|
||||
}
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// A workspace over `files`, with the first of them opened as a buffer.
|
||||
fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
let mut first = None;
|
||||
for (rel, text) in files {
|
||||
let path = tree.write(rel, text);
|
||||
if first.is_none() {
|
||||
first = Some((path, *text));
|
||||
}
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
let (path, text) = first.expect("at least one file");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(tree, ws, uri)
|
||||
}
|
||||
|
||||
/// Every lens of a buffer as `(title, command, start line, start column)`.
|
||||
fn shape(lenses: &[CodeLens]) -> Vec<(String, String, u32, u32)> {
|
||||
lenses
|
||||
.iter()
|
||||
.map(|lens| {
|
||||
let command = lens.command.as_ref().expect("every lens carries a command");
|
||||
(
|
||||
command.title.clone(),
|
||||
command.command.clone(),
|
||||
lens.range.start.line,
|
||||
lens.range.start.character,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Just the titles, for the tests that only care what the user reads.
|
||||
fn titles(lenses: &[CodeLens]) -> Vec<String> {
|
||||
lenses
|
||||
.iter()
|
||||
.map(|lens| lens.command.as_ref().map_or(String::new(), |c| c.title.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
const SUB: &str = "module sub (input logic clk);\nendmodule\n";
|
||||
const TOP: &str = "\
|
||||
module top;
|
||||
sub u_a (.clk(1'b0));
|
||||
sub u_b (.clk(1'b1));
|
||||
endmodule
|
||||
";
|
||||
const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n";
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the count
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_lens_counts_every_instantiation_in_the_workspace() {
|
||||
// Three sites across two other files, on a declaration in this one.
|
||||
let (_tree, ws, uri) =
|
||||
workspace("count", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("an open buffer");
|
||||
assert_eq!(titles(&lenses), ["3 instantiations"], "two in top.sv, one in o.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_title_counts_in_the_users_own_arithmetic() {
|
||||
let alone = "module lonely;\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("zero", &[("lonely.sv", alone)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]);
|
||||
|
||||
let one = "module top;\n lonely u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("one", &[("lonely.sv", alone), ("top.sv", one)]);
|
||||
assert_eq!(
|
||||
titles(&code_lenses(&ws, &uri).expect("open")),
|
||||
["1 instantiation"],
|
||||
"not `1 instantiations`"
|
||||
);
|
||||
|
||||
let two = "module top;\n lonely u1 ();\n lonely u2 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("two", &[("lonely.sv", alone), ("top.sv", two)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_is_exactly_what_incoming_calls_would_list() {
|
||||
// The whole contract between this feature and the hierarchy: a user
|
||||
// who reads "3 instantiations" and then opens the call hierarchy must
|
||||
// be shown three sites.
|
||||
let (_tree, ws, uri) =
|
||||
workspace("agree", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(lenses.len(), 1);
|
||||
|
||||
let item = CallHierarchyItem {
|
||||
name: "sub".to_string(),
|
||||
kind: lsp_types::SymbolKind::MODULE,
|
||||
tags: None,
|
||||
detail: None,
|
||||
uri: uri.clone(),
|
||||
range: lenses[0].range,
|
||||
selection_range: lenses[0].range,
|
||||
data: None,
|
||||
};
|
||||
let listed: usize =
|
||||
hierarchy::incoming(&ws, &item).iter().map(|call| call.from_ranges.len()).sum();
|
||||
assert_eq!(titles(&lenses), [format!("{listed} instantiations")]);
|
||||
assert_eq!(listed, 3, "and the number itself is the one we meant");
|
||||
// And the command shows exactly those sites.
|
||||
assert_eq!(execute(&ws, &[Value::String("sub".to_string())]).expect("runs").len(), listed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_at_file_scope_is_not_counted_because_no_one_calls_it() {
|
||||
// The same rule `callHierarchy/incomingCalls` applies: a site with no
|
||||
// enclosing module has no caller to report, so it is nobody's edge.
|
||||
let (_tree, ws, uri) =
|
||||
workspace("filescope", &[("sub.sv", SUB), ("loose.sv", "sub u_loose ();\n")]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// which declarations get a lens, and where it sits
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_lens_sits_on_the_declarations_own_name() {
|
||||
// The client draws a lens on the line *above* `range.start`, so the
|
||||
// name span is what puts it over the header and nowhere else.
|
||||
let (_tree, ws, uri) = workspace("span", &[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(
|
||||
shape(&lenses),
|
||||
[("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7)],
|
||||
"column 7 is `sub`, not the `module` keyword"
|
||||
);
|
||||
assert_eq!(lenses[0].range.end.character, 10, "the name only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_is_a_module_declaration_and_gets_its_own_lens() {
|
||||
let bus = "interface bus;\n logic clk;\nendinterface\n";
|
||||
let user = "module top;\n bus u_bus ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("iface", &[("bus.sv", bus), ("top.sv", user)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_module_in_a_file_gets_its_own_lens_in_source_order() {
|
||||
let many = "\
|
||||
module first;
|
||||
endmodule
|
||||
|
||||
module second;
|
||||
endmodule
|
||||
|
||||
module third;
|
||||
endmodule
|
||||
";
|
||||
let uses = "module top;\n third u3 ();\n first u1 ();\n third u3b ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("many", &[("many.sv", many), ("top.sv", uses)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(
|
||||
shape(&lenses),
|
||||
[
|
||||
("1 instantiation".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7),
|
||||
("no instantiations".to_string(), String::new(), 3, 7),
|
||||
("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 6, 7),
|
||||
],
|
||||
"source order, one per declaration"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_nothing_instantiates_gets_a_lens_that_does_not_click() {
|
||||
let (_tree, ws, uri) =
|
||||
workspace("noclick", &[("lonely.sv", "module lonely;\nendmodule\n")]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
let command = lenses[0].command.as_ref().expect("a command");
|
||||
assert_eq!(command.title, "no instantiations");
|
||||
assert_eq!(command.command, "", "display-only: there is nothing to open");
|
||||
assert_eq!(command.arguments, None, "and nothing to pass");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clickable_lens_carries_the_module_name_as_its_only_argument() {
|
||||
let (_tree, ws, uri) = workspace("args", &[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
let command = lenses[0].command.as_ref().expect("a command");
|
||||
assert_eq!(command.command, SHOW_INSTANTIATIONS);
|
||||
assert_eq!(command.arguments, Some(vec![Value::String("sub".to_string())]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_lens_is_ever_left_for_a_resolve_to_fill_in() {
|
||||
// `resolveProvider: false` is advertised, so a lens without a command
|
||||
// would be a lens the client can never complete.
|
||||
let (_tree, ws, uri) = workspace("complete", &[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert!(lenses.iter().all(|lens| lens.command.is_some() && lens.data.is_none()));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the refusals
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_buffer_this_server_was_never_shown_has_no_lenses_at_all() {
|
||||
let (tree, ws, _) = workspace("closed", &[("sub.sv", SUB)]);
|
||||
let never = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
assert!(code_lenses(&ws, &never).is_none(), "null, not an empty list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_declares_no_module_gets_an_empty_list() {
|
||||
let (_tree, ws, uri) = workspace("nomodules", &[("p.sv", "package p;\nendpackage\n")]);
|
||||
assert_eq!(code_lenses(&ws, &uri).expect("open"), Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_is_not_verilog_at_all_gets_no_lenses_and_does_not_panic() {
|
||||
let junk = ")))) not verilog ((((\n@@@ endmodule : ;\n";
|
||||
let (_tree, ws, uri) = workspace("junk", &[("junk.sv", junk)]);
|
||||
assert_eq!(
|
||||
code_lenses(&ws, &uri).expect("open"),
|
||||
Vec::new(),
|
||||
"total, whatever it parses to"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_the_parser_could_not_name_gets_no_lens() {
|
||||
// `module ;` recovers into a declaration with an empty name span,
|
||||
// which is a lens with no line to sit on.
|
||||
let broken = "module ;\nendmodule\n\nmodule fine;\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("unnamed", &[("broken.sv", broken)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert!(
|
||||
lenses.iter().all(|lens| lens.range.start.line == 3),
|
||||
"only the named declaration: {lenses:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the command
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_command_answers_one_location_per_site() {
|
||||
let (_tree, ws, _) =
|
||||
workspace("sites", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]);
|
||||
let locations = execute(&ws, &[Value::String("sub".to_string())]).expect("runs");
|
||||
let shape: Vec<(String, u32, u32)> = locations
|
||||
.iter()
|
||||
.map(|at| {
|
||||
(
|
||||
at.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(),
|
||||
at.range.start.line,
|
||||
at.range.start.character,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
shape,
|
||||
[
|
||||
("o.sv".to_string(), 1, 2),
|
||||
("top.sv".to_string(), 1, 2),
|
||||
("top.sv".to_string(), 2, 2),
|
||||
],
|
||||
"every site, sorted by file then position"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_answers_nothing_for_a_module_nothing_instantiates() {
|
||||
let (_tree, ws, _) = workspace("nosites", &[("lonely.sv", "module lonely;\nendmodule\n")]);
|
||||
assert_eq!(execute(&ws, &[Value::String("lonely".to_string())]), Ok(Vec::new()));
|
||||
assert_eq!(
|
||||
execute(&ws, &[Value::String("never-heard-of-it".to_string())]),
|
||||
Ok(Vec::new()),
|
||||
"a name the workspace does not declare is not an error either"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_declines_arguments_it_cannot_read() {
|
||||
let (_tree, ws, _) = workspace("badargs", &[("sub.sv", SUB)]);
|
||||
for arguments in [vec![], vec![Value::Null], vec![Value::String(String::new())]] {
|
||||
let message = execute(&ws, &arguments).expect_err("declined");
|
||||
assert!(message.contains("module name"), "{message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_list_is_what_the_server_advertises() {
|
||||
assert_eq!(commands(), vec![SHOW_INSTANTIATIONS]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26): count-honesty shapes the fixture above never
|
||||
// exercises — a multi-instance statement, self-recursion, name
|
||||
// collisions (within one file and across files), generate replication
|
||||
// and an `ifdef`-guarded instantiation. None of these turned out to
|
||||
// disagree with `hierarchy::incoming` — they can't, since `lens.rs` and
|
||||
// `hierarchy::incoming` both bottom out in the same
|
||||
// `hierarchy::callers_of_each` — but the *number itself* is worth
|
||||
// pinning so a future change to what counts as a "site" is visible here
|
||||
// too, not just in `hierarchy.rs`. See QA log in
|
||||
// `docs/features/code-lens/README.md`.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_corpus_counts_agree_with_grep_derived_ground_truth() {
|
||||
// `corpus/common_cells/src/cdc_fifo_gray.sv` declares three modules.
|
||||
// Ground truth by hand, `grep -rnE '\bNAME\b' corpus --include='*.sv'
|
||||
// --include='*.svh'`, read line by line to exclude the declaration
|
||||
// itself and doc-comment mentions (`cdc_fifo_gray_clearable.sv` has
|
||||
// several, e.g. line 56's "In contrast to the cdc_fifo_gray
|
||||
// version..."):
|
||||
// - `cdc_fifo_gray` — one real instantiation,
|
||||
// `common_cells/test/cdc_fifo_tb.sv:49` (`i_dut`).
|
||||
// - `cdc_fifo_gray_src` — one, `cdc_fifo_gray.sv:130`, inside
|
||||
// `cdc_fifo_gray` itself (`_src_clearable` is a different name
|
||||
// and does not match `\bcdc_fifo_gray_src\b`).
|
||||
// - `cdc_fifo_gray_dst` — one, `cdc_fifo_gray.sv:145`, likewise.
|
||||
// Skipped like the other corpus tests when `corpus/` is not checked
|
||||
// out (`tools/corpus_fetch.sh`).
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let file = corpus.join("common_cells/src/cdc_fifo_gray.sv");
|
||||
let Ok(text) = fs::read_to_string(&file) else {
|
||||
eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![corpus]);
|
||||
let uri = path_to_uri(&file).expect("uri");
|
||||
ws.set_document(uri.clone(), text);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(
|
||||
titles(&lenses),
|
||||
["1 instantiation", "1 instantiation", "1 instantiation"],
|
||||
"cdc_fifo_gray, cdc_fifo_gray_src, cdc_fifo_gray_dst, in that source order: {lenses:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_multi_instance_statement_is_one_site_not_two() {
|
||||
// `sub u1 (), u2 ();` is ONE `Instantiation` AST node carrying TWO
|
||||
// `Instance` entries — physically two instantiations of `sub` in the
|
||||
// design. This is not a code-lens decision: `hierarchy.rs`'s own
|
||||
// documented assumption ("One `Instantiation` is one call site,
|
||||
// however many instances it declares") already settles it, the same
|
||||
// way `textDocument/references` reports the module name once. Pinned
|
||||
// here too so a change to that policy is visible in both features.
|
||||
let top = "module top;\n sub u1 (), u2 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("qa_multi", &[("sub.sv", SUB), ("top.sv", top)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(titles(&lenses), ["1 instantiation"], "one AST node, not two instances");
|
||||
let locs = execute(&ws, &[Value::String("sub".to_string())]).expect("runs");
|
||||
assert_eq!(locs.len(), 1, "one location for the one site: {locs:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_module_that_instantiates_itself_counts_its_own_instantiation() {
|
||||
// Self-recursion (illegal to elaborate, legal text) is handled the
|
||||
// same way `hierarchy.rs` handles an `a -> b -> a` cycle: each
|
||||
// request answers one hop, so there is nothing here that could ever
|
||||
// recurse or hang.
|
||||
let text = "module m;\n m u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("qa_recursive", &[("m.sv", text)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(titles(&lenses), ["1 instantiation"]);
|
||||
let locs = execute(&ws, &[Value::String("m".to_string())]).expect("runs");
|
||||
assert_eq!(locs.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_two_files_declaring_the_same_module_name_get_the_same_count_on_both() {
|
||||
// The census is by name (documented in this README's Assumptions):
|
||||
// an instantiation of `m` cannot say which of two `module m`
|
||||
// declarations it meant, so both lenses read the workspace-wide
|
||||
// total rather than a partitioned one. Same limitation
|
||||
// `callHierarchy/incomingCalls` already has, for the same reason.
|
||||
let m_a = "module m;\n logic a;\nendmodule\n";
|
||||
let m_b = "module m;\n logic b;\nendmodule\n";
|
||||
let user = "module top;\n m u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri_a) =
|
||||
workspace("qa_collide_a", &[("a/m.sv", m_a), ("b/m.sv", m_b), ("top.sv", user)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri_a).expect("open a/m.sv")), ["1 instantiation"]);
|
||||
|
||||
// Same workspace, opening the OTHER declaration instead: same total.
|
||||
let mut ws_b = Workspace::default();
|
||||
let tree_b = Tree::new("qa_collide_b");
|
||||
tree_b.write("a/m.sv", m_a);
|
||||
let path_b = tree_b.write("b/m.sv", m_b);
|
||||
tree_b.write("top.sv", user);
|
||||
ws_b.open_roots(vec![tree_b.path.clone()]);
|
||||
let uri_b = path_to_uri(&path_b).expect("uri");
|
||||
ws_b.set_document(uri_b.clone(), m_b.to_string());
|
||||
assert_eq!(
|
||||
titles(&code_lenses(&ws_b, &uri_b).expect("open b/m.sv")),
|
||||
["1 instantiation"],
|
||||
"the other declaration reads the same total, not zero"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count() {
|
||||
// The tolerant parser accepts `module m; endmodule module m;
|
||||
// endmodule` in one file (real SystemVerilog forbids it, but this is
|
||||
// reachable through broken input). The batch in
|
||||
// `hierarchy::callers_of_each` is asked `["m", "m"]` — two indices,
|
||||
// not deduplicated — so this also pins that duplicate names in one
|
||||
// batch do not alias or corrupt each other's answer.
|
||||
let text = "module m;\nendmodule\n\nmodule m;\nendmodule\n";
|
||||
let user = "module top;\n m u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("qa_dup_same_file", &[("m.sv", text), ("top.sv", user)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(lenses.len(), 2, "one lens per declaration");
|
||||
assert_eq!(titles(&lenses), ["1 instantiation", "1 instantiation"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_generate_replicated_instantiation_counts_the_written_statement_once() {
|
||||
// `generate for` is not elaborated: the AST has exactly one
|
||||
// `Instantiation` node inside the loop body regardless of the
|
||||
// genvar's range, matching `hierarchy.rs`'s own documented handling
|
||||
// of the identical shape (`incoming_calls_reach_generate_regions_...`
|
||||
// in `hierarchy.rs`). Four elaborated instances at synthesis time,
|
||||
// one textual site here — the lens counts text, not hardware.
|
||||
let sub = "module sub;\nendmodule\n";
|
||||
let top = "\
|
||||
module top;
|
||||
generate
|
||||
for (genvar i = 0; i < 4; i++) begin : g
|
||||
sub u1 ();
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri) = workspace("qa_generate", &[("sub.sv", sub), ("top.sv", top)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_ifdef_guarded_instantiation_counts_both_arms() {
|
||||
// Inherited from `hierarchy.rs`, disclosed there as an Assumption:
|
||||
// the parser does not evaluate `` `ifdef``/`` `else``, so both arms
|
||||
// land as ordinary `Instantiation` items and both are counted, even
|
||||
// though only one is ever really built. Pinned here too since the
|
||||
// lens is a second, more prominent surface for the same policy.
|
||||
let sub = "module sub;\nendmodule\n";
|
||||
let top = "\
|
||||
module top;
|
||||
`ifdef FOO
|
||||
sub u1 ();
|
||||
`endif
|
||||
sub u2 ();
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri) = workspace("qa_ifdef", &[("sub.sv", sub), ("top.sv", top)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the performance claim, measured
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// What a whole file's lenses cost over the real corpus, and — the point
|
||||
/// of the batch — that asking about three modules at once costs about what
|
||||
/// asking about one does, not three times as much.
|
||||
///
|
||||
/// Skipped when `corpus/` is not checked out (`tools/corpus_fetch.sh`),
|
||||
/// like the other corpus tests. The budget is deliberately loose: a debug
|
||||
/// build on a loaded machine is the worst case this ever runs in, and this
|
||||
/// exists to catch an order-of-magnitude regression — a lens handler that
|
||||
/// re-read the workspace once per declaration would fail the ratio.
|
||||
#[test]
|
||||
fn code_lenses_for_a_whole_file_cost_about_one_workspace_walk() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
// A real file declaring three modules, so the batch has something to
|
||||
// amortize over.
|
||||
let file = corpus.join("common_cells/src/cdc_fifo_gray.sv");
|
||||
let Ok(text) = fs::read_to_string(&file) else {
|
||||
eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![corpus]);
|
||||
let uri = path_to_uri(&file).expect("uri");
|
||||
ws.set_document(uri.clone(), text);
|
||||
|
||||
// Warm, then the worst of three, for the whole file and for one name.
|
||||
let _ = code_lenses(&ws, &uri);
|
||||
let mut whole_file = std::time::Duration::ZERO;
|
||||
let mut one_name = std::time::Duration::ZERO;
|
||||
let mut count = 0;
|
||||
for _ in 0..3 {
|
||||
let started = std::time::Instant::now();
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
whole_file = whole_file.max(started.elapsed());
|
||||
count = lenses.len();
|
||||
let started = std::time::Instant::now();
|
||||
let _ = sites_of(&ws, "cdc_fifo_gray");
|
||||
one_name = one_name.max(started.elapsed());
|
||||
}
|
||||
eprintln!(
|
||||
"corpus: {} files, {count} lenses for cdc_fifo_gray.sv in {whole_file:?} \
|
||||
(one name alone: {one_name:?})",
|
||||
ws.index().files().len(),
|
||||
);
|
||||
assert!(count >= 3, "the file declares three modules: {count}");
|
||||
assert!(whole_file < std::time::Duration::from_millis(1500), "lenses cost {whole_file:?}");
|
||||
assert!(
|
||||
whole_file < one_name * 2,
|
||||
"the batch is one walk, not one per module: {count} names cost {whole_file:?} \
|
||||
against {one_name:?} for one"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,912 @@
|
||||
//! `textDocument/linkedEditingRange`: a closing label edits with the name it
|
||||
//! repeats.
|
||||
//!
|
||||
//! SystemVerilog writes a declaration's name twice whenever it closes with a
|
||||
//! label — `module m ... endmodule : m`, `function f ... endfunction : f`,
|
||||
//! `begin : blk ... end : blk`. Linked editing is the protocol's answer to
|
||||
//! exactly that shape: the server hands back the set of ranges holding the
|
||||
//! same name, and the editor applies every keystroke to all of them, so the
|
||||
//! two halves cannot drift apart while the user types.
|
||||
//!
|
||||
//! **The pair is a node, never a text match.** Every construct served below
|
||||
//! records both spans on one AST node (`name_span` and `end_label_span`), so
|
||||
//! the answer is a lookup and not a search. That is what makes
|
||||
//! `begin : x begin : x ... end : x end : x` — four byte-identical names —
|
||||
//! resolve to the *syntactic* partner rather than to the nearest one.
|
||||
//!
|
||||
//! **Two refusals, both `null`.** A closing label is optional in SV, so a bare
|
||||
//! `endmodule` has nothing to co-edit and gets no ranges: this feature never
|
||||
//! offers to create a label. And a *mismatched* label
|
||||
//! (`module m ... endmodule : wrong`) is declined too, because the spec
|
||||
//! requires the linked ranges to contain identical text — linking them would
|
||||
//! silently rewrite one half into the other on the user's next keystroke,
|
||||
//! which is an edit nobody asked for. Rules and the constructs the tree cannot
|
||||
//! reach: `docs/features/linked-editing/README.md`.
|
||||
|
||||
use lsp_types::LinkedEditingRanges;
|
||||
use vlog_parser::ast::{
|
||||
ClassDecl, ClockingDecl, FunctionDecl, GenBlock, GenElse, GenIf, Item, ItemKind, Module, Stmt,
|
||||
StmtKind, TaskDecl,
|
||||
};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// What a client may type into a linked range and keep the link.
|
||||
///
|
||||
/// Sent rather than left to the client's own language word pattern: an SV
|
||||
/// identifier admits `$` after its first character (IEEE 1800 §5.6), and an
|
||||
/// editor's default word pattern for an unknown language id does not — so a
|
||||
/// user typing `foo$bar` would watch the link drop halfway. The pattern is
|
||||
/// anchored at both ends and deliberately says nothing about escaped
|
||||
/// identifiers, which [`is_simple_identifier`] declines outright.
|
||||
const WORD_PATTERN: &str = "^[A-Za-z_][A-Za-z0-9_$]*$";
|
||||
|
||||
/// The header name and the closing label that repeats it, when the cursor is
|
||||
/// on either of them.
|
||||
///
|
||||
/// `None` — which the handler sends as `null` — for every other position, for
|
||||
/// a construct that wrote no closing label, and for the two shapes that must
|
||||
/// not be linked: a label that does not match its header, and a name that is
|
||||
/// not a plain identifier.
|
||||
pub fn linked_editing_ranges(doc: &Document, offset: u32) -> Option<LinkedEditingRanges> {
|
||||
let mut pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut pairs);
|
||||
let pair = pairs.into_iter().find(|pair| pair.covers(offset))?;
|
||||
if !pair.is_linkable(&doc.text) {
|
||||
return None;
|
||||
}
|
||||
let positions = doc.positions();
|
||||
Some(LinkedEditingRanges {
|
||||
ranges: vec![positions.range(pair.open), positions.range(pair.close)],
|
||||
word_pattern: Some(WORD_PATTERN.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
/// One construct's two name occurrences, in source order.
|
||||
struct Pair {
|
||||
/// The name in the header: `m` of `module m`, `blk` of `begin : blk`.
|
||||
open: TextRange,
|
||||
/// The same name after the closer's `:`.
|
||||
close: TextRange,
|
||||
}
|
||||
|
||||
impl Pair {
|
||||
/// Whether the cursor is on either name.
|
||||
///
|
||||
/// One byte past the end counts, as it does for
|
||||
/// [`crate::pairs::highlights`]: an editor leaves the caret after the
|
||||
/// character just typed, and a link that switched off at `m|` would be
|
||||
/// gone exactly while the user is renaming. Two label occurrences are
|
||||
/// always separated by at least a keyword, so the extra byte can never
|
||||
/// claim a neighbouring name.
|
||||
fn covers(&self, offset: u32) -> bool {
|
||||
let touches = |span: TextRange| offset >= span.start && offset <= span.end;
|
||||
touches(self.open) || touches(self.close)
|
||||
}
|
||||
|
||||
/// Whether these two ranges may be edited as one.
|
||||
///
|
||||
/// Both conditions are the protocol's: the ranges must hold identical
|
||||
/// text, and what the user types into them must stay describable by
|
||||
/// [`WORD_PATTERN`].
|
||||
fn is_linkable(&self, text: &str) -> bool {
|
||||
let (Some(open), Some(close)) =
|
||||
(text.get(self.open.as_range()), text.get(self.close.as_range()))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
open == close && is_simple_identifier(open)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a name is a plain SV identifier — the charset [`WORD_PATTERN`]
|
||||
/// describes.
|
||||
///
|
||||
/// This is what excludes an escaped identifier (`\my$odd.name `), whose extent
|
||||
/// depends on a trailing space that no word pattern can express. Rather than
|
||||
/// send a pattern a client could use to corrupt the escape, such a pair is
|
||||
/// simply not offered.
|
||||
fn is_simple_identifier(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
match chars.next() {
|
||||
Some(first) if first == '_' || first.is_ascii_alphabetic() => {}
|
||||
_ => return false,
|
||||
}
|
||||
chars.all(|c| c == '_' || c == '$' || c.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
/// Push a pair when the construct wrote both halves. An absent closing label
|
||||
/// is the common case and means there is nothing to link.
|
||||
fn push(open: Option<TextRange>, close: Option<TextRange>, out: &mut Vec<Pair>) {
|
||||
if let (Some(open), Some(close)) = (open, close) {
|
||||
if !open.is_empty() && !close.is_empty() {
|
||||
out.push(Pair { open, close });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn items_pairs(items: &[Item], out: &mut Vec<Pair>) {
|
||||
for item in items {
|
||||
item_pairs(item, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => module_pairs(m, out),
|
||||
ItemKind::Package { name_span, end_label_span, items, .. } => {
|
||||
push(Some(*name_span), *end_label_span, out);
|
||||
items_pairs(items, out);
|
||||
}
|
||||
ItemKind::Class(c) => class_pairs(c, out),
|
||||
ItemKind::Function(f) => function_pairs(f, out),
|
||||
ItemKind::Task(t) => task_pairs(t, out),
|
||||
ItemKind::Clocking(c) => clocking_pairs(c, out),
|
||||
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
|
||||
ItemKind::GenIf(g) => gen_if_pairs(g, out),
|
||||
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
for arm in &g.items {
|
||||
gen_block_pairs(&arm.body, out);
|
||||
}
|
||||
}
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
stmt_pairs(stmt, out);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn module_pairs(m: &Module, out: &mut Vec<Pair>) {
|
||||
push(Some(m.name_span), m.end_label_span, out);
|
||||
items_pairs(&m.items, out);
|
||||
}
|
||||
|
||||
fn class_pairs(c: &ClassDecl, out: &mut Vec<Pair>) {
|
||||
push(Some(c.name_span), c.end_label_span, out);
|
||||
items_pairs(&c.items, out);
|
||||
}
|
||||
|
||||
fn function_pairs(f: &FunctionDecl, out: &mut Vec<Pair>) {
|
||||
push(Some(f.name_span), f.end_label_span, out);
|
||||
stmts_pairs(&f.stmts, out);
|
||||
}
|
||||
|
||||
fn task_pairs(t: &TaskDecl, out: &mut Vec<Pair>) {
|
||||
push(Some(t.name_span), t.end_label_span, out);
|
||||
stmts_pairs(&t.stmts, out);
|
||||
}
|
||||
|
||||
/// `clocking cb @(posedge clk); ... endclocking : cb`. The anonymous
|
||||
/// `default clocking @(...)` form has no name at all, so it pairs nothing.
|
||||
fn clocking_pairs(c: &ClockingDecl, out: &mut Vec<Pair>) {
|
||||
push(c.name.as_ref().map(|n| n.span), c.end_label_span, out);
|
||||
}
|
||||
|
||||
fn gen_if_pairs(gen_if: &GenIf, out: &mut Vec<Pair>) {
|
||||
gen_block_pairs(&gen_if.then, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
gen_block_pairs(&nested.then, out);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
gen_block_pairs(block, out);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_block_pairs(block: &GenBlock, out: &mut Vec<Pair>) {
|
||||
push(block.label_span, block.end_label_span, out);
|
||||
items_pairs(&block.items, out);
|
||||
}
|
||||
|
||||
fn stmts_pairs(list: &[Stmt], out: &mut Vec<Pair>) {
|
||||
for stmt in list {
|
||||
stmt_pairs(stmt, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement half of the walk.
|
||||
///
|
||||
/// The recursion is bounded by the parser's own nesting limit
|
||||
/// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it
|
||||
/// built.
|
||||
fn stmt_pairs(stmt: &Stmt, out: &mut Vec<Pair>) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { label_span, end_label_span, stmts, .. }
|
||||
| StmtKind::ForkJoin { label_span, end_label_span, stmts, .. } => {
|
||||
push(*label_span, *end_label_span, out);
|
||||
stmts_pairs(stmts, out);
|
||||
}
|
||||
// `blk : begin ... end : blk` (IEEE 1800 §9.3.5): the name is written
|
||||
// before the keyword, so the parser puts it on this node and leaves
|
||||
// the block's own label empty. Still one syntactic pair — the LRM
|
||||
// requires the end label to name this statement — but only when the
|
||||
// block wrote no label of its own. Writing both is illegal, and the
|
||||
// block's own pair has already been pushed by the recursion below.
|
||||
StmtKind::Labeled { name_span, stmt: inner, .. } => {
|
||||
if let Some(close) = prefix_labelled_end(inner) {
|
||||
push(Some(*name_span), Some(close), out);
|
||||
}
|
||||
stmt_pairs(inner, out);
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
stmt_pairs(then, out);
|
||||
if let Some(els) = els.as_deref() {
|
||||
stmt_pairs(els, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for item in items {
|
||||
stmt_pairs(&item.stmt, out);
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. } => stmt_pairs(body, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
stmt_pairs(inner, out)
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
if let Some(then) = then.as_deref() {
|
||||
stmt_pairs(then, out);
|
||||
}
|
||||
if let Some(els) = els.as_deref() {
|
||||
stmt_pairs(els, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The closing label of a block named *before* its keyword, or `None` when the
|
||||
/// statement is not such a block.
|
||||
fn prefix_labelled_end(stmt: &Stmt) -> Option<TextRange> {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { label: None, end_label_span, .. }
|
||||
| StmtKind::ForkJoin { label: None, end_label_span, .. } => *end_label_span,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
fn doc_of(text: &str) -> Document {
|
||||
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
||||
}
|
||||
|
||||
/// The byte offset of `needle`'s first occurrence.
|
||||
fn at(text: &str, needle: &str) -> u32 {
|
||||
text.find(needle).expect("needle present") as u32
|
||||
}
|
||||
|
||||
/// The byte offset just past `prefix` — how a fixture points at a name
|
||||
/// whose own spelling occurs earlier in the text (`m` of `module m`).
|
||||
fn at_after(text: &str, prefix: &str) -> u32 {
|
||||
at(text, prefix) + prefix.len() as u32
|
||||
}
|
||||
|
||||
/// The byte offset just past the *last* `prefix`. Every fixture below
|
||||
/// writes its closing label as the file's last `": "`, so this is where
|
||||
/// that label starts.
|
||||
fn at_last_after(text: &str, prefix: &str) -> u32 {
|
||||
text.rfind(prefix).expect("needle present") as u32 + prefix.len() as u32
|
||||
}
|
||||
|
||||
/// The answer's ranges as `(line, start character, end character)`, which
|
||||
/// is enough to say which occurrence each one is.
|
||||
fn linked(text: &str, offset: u32) -> Option<Vec<(u32, u32, u32)>> {
|
||||
let doc = doc_of(text);
|
||||
let answer = linked_editing_ranges(&doc, offset)?;
|
||||
assert_eq!(
|
||||
answer.word_pattern.as_deref(),
|
||||
Some(WORD_PATTERN),
|
||||
"every answer carries the SV word pattern"
|
||||
);
|
||||
Some(
|
||||
answer
|
||||
.ranges
|
||||
.iter()
|
||||
.map(|r| (r.start.line, r.start.character, r.end.character))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// every construct that ships
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn every_labeled_construct_links_its_two_names() {
|
||||
// Each fixture writes its name twice and nowhere else, and its closing
|
||||
// label is the last `": "` in the text.
|
||||
let cases = [
|
||||
("module m;\nendmodule : m\n", "module ", "module"),
|
||||
("macromodule m;\nendmodule : m\n", "macromodule ", "macromodule"),
|
||||
("interface bus_if;\nendinterface : bus_if\n", "interface ", "interface"),
|
||||
("package p;\nendpackage : p\n", "package ", "package"),
|
||||
("class c;\nendclass : c\n", "class ", "class"),
|
||||
("module m;\n function f;\n endfunction : f\nendmodule\n", "function ", "function"),
|
||||
("module m;\n task t;\n endtask : t\nendmodule\n", "task ", "task"),
|
||||
(
|
||||
"module m;\n initial begin : blk\n end : blk\nendmodule\n",
|
||||
"begin : ",
|
||||
"named begin",
|
||||
),
|
||||
("module m;\n initial fork : frk\n join : frk\nendmodule\n", "fork : ", "named fork"),
|
||||
(
|
||||
concat!(
|
||||
"module m;\n",
|
||||
" generate\n",
|
||||
" for (genvar i = 0; i < 2; i++) begin : g\n",
|
||||
" wire w;\n",
|
||||
" end : g\n",
|
||||
" endgenerate\n",
|
||||
"endmodule\n",
|
||||
),
|
||||
"begin : ",
|
||||
"generate block",
|
||||
),
|
||||
(
|
||||
"interface i;\n clocking cb @(posedge clk);\n endclocking : cb\nendinterface\n",
|
||||
"clocking ",
|
||||
"clocking",
|
||||
),
|
||||
(
|
||||
"module m;\n initial pre : begin\n end : pre\nendmodule\n",
|
||||
"initial ",
|
||||
"prefix-labelled begin",
|
||||
),
|
||||
];
|
||||
for (text, header, what) in cases {
|
||||
let from_label = linked(text, at_last_after(text, ": "))
|
||||
.unwrap_or_else(|| panic!("{what}: the closing label answered nothing at all"));
|
||||
assert_eq!(from_label.len(), 2, "{what}: exactly two ranges");
|
||||
let from_header = linked(text, at_after(text, header))
|
||||
.unwrap_or_else(|| panic!("{what}: the header name answered nothing"));
|
||||
assert_eq!(from_label, from_header, "{what}: both directions answer the same pair");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// where the cursor is
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_cursor_may_sit_anywhere_in_either_name() {
|
||||
let text = "module wide;\nendmodule : wide\n";
|
||||
let header = at_after(text, "module ");
|
||||
let label = at_last_after(text, ": ");
|
||||
let expected = linked(text, header).expect("the header answers");
|
||||
assert_eq!(expected, vec![(0, 7, 11), (1, 12, 16)]);
|
||||
for (offset, what) in [
|
||||
(header, "header start"),
|
||||
(header + 2, "header middle"),
|
||||
(header + 4, "header end, one past the last byte"),
|
||||
(label, "label start"),
|
||||
(label + 2, "label middle"),
|
||||
(label + 4, "label end, one past the last byte"),
|
||||
] {
|
||||
assert_eq!(linked(text, offset).as_ref(), Some(&expected), "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_beside_the_names_answers_nothing() {
|
||||
let text = "module m;\nendmodule : m\n";
|
||||
assert!(linked(text, 0).is_none(), "the `module` keyword itself");
|
||||
assert!(linked(text, at(text, " m;")).is_none(), "the space before the name");
|
||||
assert!(linked(text, at(text, ";") + 1).is_none(), "past the semicolon");
|
||||
assert!(linked(text, at(text, "endmodule")).is_none(), "the closing keyword");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_past_the_end_of_the_file_answers_nothing() {
|
||||
let text = "module m;\nendmodule : m\n";
|
||||
assert!(linked(text, text.len() as u32).is_none());
|
||||
assert!(linked(text, text.len() as u32 + 1_000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_buffer_answers_nothing() {
|
||||
assert!(linked("", 0).is_none());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the two refusals
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_unlabeled_closer_links_nothing() {
|
||||
// The label is optional in SV, and its absence is not an invitation to
|
||||
// create one: there is no second range, so there is no answer.
|
||||
for (text, header) in [
|
||||
("module m;\nendmodule\n", "module "),
|
||||
("package p;\nendpackage\n", "package "),
|
||||
("class c;\nendclass\n", "class "),
|
||||
("module m;\n function f;\n endfunction\nendmodule\n", "function "),
|
||||
("module m;\n task t;\n endtask\nendmodule\n", "task "),
|
||||
("module m;\n initial begin : blk\n end\nendmodule\n", "begin : "),
|
||||
] {
|
||||
assert!(linked(text, at_after(text, header)).is_none(), "{text:?} must link nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mismatched_label_links_nothing() {
|
||||
// Broken code. Linking the two would rewrite one half into the other
|
||||
// on the next keystroke — an edit the user never asked for — and the
|
||||
// spec requires the ranges to hold identical text anyway.
|
||||
let text = "module m;\nendmodule : wrong\n";
|
||||
assert!(linked(text, at_after(text, "module ")).is_none(), "from the header");
|
||||
assert!(linked(text, at(text, "wrong")).is_none(), "and from the label");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_label_differing_only_in_case_links_nothing() {
|
||||
let text = "module Data;\nendmodule : data\n";
|
||||
assert!(linked(text, at(text, "Data")).is_none());
|
||||
assert!(linked(text, at(text, "data")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_identifier_links_nothing() {
|
||||
// `\odd.name ` is an identifier whose extent depends on a trailing
|
||||
// space, which no word pattern can describe. Both halves matching does
|
||||
// not make it safe to hand a client.
|
||||
let text = "module \\odd.name ;\nendmodule : \\odd.name \n";
|
||||
let doc = doc_of(text);
|
||||
let mut pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut pairs);
|
||||
assert_eq!(pairs.len(), 1, "premise: the tree really did record the pair");
|
||||
assert!(linked(text, at(text, "\\odd.name")).is_none(), "from the header");
|
||||
assert!(
|
||||
linked(text, text.rfind("\\odd.name").expect("label") as u32).is_none(),
|
||||
"and back"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_simple_identifier_accepts_exactly_the_word_pattern() {
|
||||
for good in ["m", "_x", "a1", "foo$bar", "A_b$9", "_"] {
|
||||
assert!(is_simple_identifier(good), "{good} is a plain SV identifier");
|
||||
}
|
||||
for bad in ["", "1a", "$x", "\\odd.name", "a b", "a.b", "é"] {
|
||||
assert!(!is_simple_identifier(bad), "{bad:?} is not");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// nesting — the pair must be the syntactic one
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn nested_blocks_answer_their_own_pair() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" initial begin : outer\n",
|
||||
" begin : inner\n",
|
||||
" x = 1;\n",
|
||||
" end : inner\n",
|
||||
" end : outer\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let outer = linked(text, at(text, "outer")).expect("the outer header answers");
|
||||
assert_eq!(outer, vec![(1, 18, 23), (5, 8, 13)], "line 1 header, line 5 label");
|
||||
let inner = linked(text, at(text, "inner")).expect("the inner header answers");
|
||||
assert_eq!(inner, vec![(2, 12, 17), (4, 10, 15)], "line 2 header, line 4 label");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_names_at_different_nesting_pair_syntactically() {
|
||||
// The evil fixture: four byte-identical names, two pairs. A
|
||||
// nearest-same-text rule would pair the outer header with the *inner*
|
||||
// label, because that one is nearer. The pair comes off the AST node,
|
||||
// so it cannot.
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" initial begin : x\n",
|
||||
" begin : x\n",
|
||||
" y = 1;\n",
|
||||
" end : x\n",
|
||||
" end : x\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let outer_header = at_after(text, "begin : ");
|
||||
let inner_header =
|
||||
text.match_indices("begin : ").nth(1).expect("the inner block").0 as u32 + 8;
|
||||
let outer = linked(text, outer_header).expect("the outer header answers");
|
||||
assert_eq!(outer, vec![(1, 18, 19), (5, 8, 9)], "outer header pairs with the OUTER end");
|
||||
let inner = linked(text, inner_header).expect("the inner header answers");
|
||||
assert_eq!(inner, vec![(2, 12, 13), (4, 10, 11)], "inner header pairs with the INNER end");
|
||||
assert_ne!(outer, inner);
|
||||
// And from each closing label, back to the same two pairs.
|
||||
let inner_label = text.match_indices("end : ").next().expect("the inner end").0 as u32 + 6;
|
||||
let outer_label = at_last_after(text, "end : ");
|
||||
assert_eq!(linked(text, inner_label), Some(inner));
|
||||
assert_eq!(linked(text, outer_label), Some(outer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_and_the_function_inside_it_are_separate_pairs() {
|
||||
// The function is deliberately named `m` too.
|
||||
let text = "module m;\n function m;\n endfunction : m\nendmodule : m\n";
|
||||
let module = linked(text, at_after(text, "module ")).expect("the module header answers");
|
||||
assert_eq!(module, vec![(0, 7, 8), (3, 12, 13)], "module header, endmodule label");
|
||||
let function =
|
||||
linked(text, at_after(text, "function ")).expect("the function header answers");
|
||||
assert_eq!(function, vec![(1, 11, 12), (2, 16, 17)], "function header, endfunction label");
|
||||
assert_ne!(module, function);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_method_pairs_inside_its_class() {
|
||||
let text = "class c;\n function void f();\n endfunction : f\nendclass : c\n";
|
||||
let class = linked(text, at_after(text, "class ")).expect("the class answers");
|
||||
assert_eq!(class, vec![(0, 6, 7), (3, 11, 12)]);
|
||||
let method = linked(text, at(text, "f()")).expect("the method answers");
|
||||
assert_eq!(method, vec![(1, 16, 17), (2, 16, 17)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_block_inside_a_generate_for_pairs() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" generate\n",
|
||||
" for (genvar i = 0; i < 2; i++) begin : g\n",
|
||||
" initial begin : inner\n",
|
||||
" end : inner\n",
|
||||
" end : g\n",
|
||||
" endgenerate\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let gen = linked(text, at(text, "g\n")).expect("the generate label answers");
|
||||
assert_eq!(gen, vec![(2, 43, 44), (5, 10, 11)]);
|
||||
let inner = linked(text, at(text, "inner")).expect("the inner block answers");
|
||||
assert_eq!(inner, vec![(3, 22, 27), (4, 12, 17)]);
|
||||
assert_ne!(gen, inner);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// UTF-16 positions
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_multibyte_comment_before_the_name_does_not_shift_it() {
|
||||
// SV identifiers are ASCII, but everything around them need not be.
|
||||
// The characters are counted in UTF-16 units, so `é` (2 bytes, 1 unit)
|
||||
// and `🎉` (4 bytes, 2 units) must not move the name's column.
|
||||
let text = "// café 🎉\nmodule m;\nendmodule : m\n";
|
||||
let ranges = linked(text, at_after(text, "module ")).expect("the header answers");
|
||||
assert_eq!(ranges, vec![(1, 7, 8), (2, 12, 13)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multibyte_comment_on_the_same_line_keeps_the_columns_honest() {
|
||||
let text = "module m; // 🎉 party\nendmodule : m // café\n";
|
||||
let ranges = linked(text, at_last_after(text, ": ")).expect("the label answers");
|
||||
assert_eq!(ranges, vec![(0, 7, 8), (1, 12, 13)]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// buffers that do not parse
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_lex_answers_nothing() {
|
||||
let text = "module m;\n wire a; /* unterminated\n";
|
||||
let doc = doc_of(text);
|
||||
assert!(doc.tokens.is_empty(), "premise: the lexer gave up");
|
||||
assert!(linked_editing_ranges(&doc, at_after(text, "module ")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_typed_construct_answers_nothing_rather_than_guessing() {
|
||||
let text = "module m;\n initial begin : blk\nendmodule\n";
|
||||
assert!(linked(text, at(text, "blk")).is_none(), "no closing label was written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pair_written_after_a_broken_item_still_answers() {
|
||||
// Error recovery keeps the items it could parse, so a mistake early in
|
||||
// the file must not un-link everything below it.
|
||||
let text = "module a;\n @@@ ;\nendmodule\nmodule b;\nendmodule : b\n";
|
||||
let ranges = linked(text, at_after(text, "module b")).expect("the second module answers");
|
||||
assert_eq!(ranges.len(), 2);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the answer's own shape
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_two_ranges_hold_identical_text_and_never_overlap() {
|
||||
let text = "module top;\n initial begin : blk\n end : blk\nendmodule : top\n";
|
||||
let doc = doc_of(text);
|
||||
for offset in [at(text, "top") + 1, at(text, "blk") + 1] {
|
||||
let answer = linked_editing_ranges(&doc, offset).expect("a pair");
|
||||
assert_eq!(answer.ranges.len(), 2);
|
||||
let (first, second) = (answer.ranges[0], answer.ranges[1]);
|
||||
assert!(
|
||||
(first.end.line, first.end.character) < (second.start.line, second.start.character),
|
||||
"the header comes first and the two do not overlap: {answer:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
first.end.character - first.start.character,
|
||||
second.end.character - second.start.character,
|
||||
"identical length"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26) — the prefix-label gate, and the ranges' exact bytes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every offset in `0..=text.len()` answers without panicking, and every
|
||||
/// `Some` answer holds two identical-text, non-overlapping ranges. The
|
||||
/// blanket check the targeted tests below narrow in on one fixture at a
|
||||
/// time — kept here because a tolerant-parser fixture is exactly the kind
|
||||
/// of input where a hand-picked offset can miss what a sweep finds.
|
||||
fn assert_total_and_sane(text: &str) {
|
||||
let doc = doc_of(text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let Some(answer) = linked_editing_ranges(&doc, offset) else { continue };
|
||||
assert_eq!(answer.ranges.len(), 2, "{text:?} at {offset}: {answer:?}");
|
||||
assert_eq!(
|
||||
answer.word_pattern.as_deref(),
|
||||
Some(WORD_PATTERN),
|
||||
"{text:?} at {offset}: word pattern missing"
|
||||
);
|
||||
let (a, b) = (answer.ranges[0], answer.ranges[1]);
|
||||
let (before, after) =
|
||||
if (a.start.line, a.start.character) <= (b.start.line, b.start.character) {
|
||||
(a, b)
|
||||
} else {
|
||||
(b, a)
|
||||
};
|
||||
assert!(
|
||||
(before.end.line, before.end.character)
|
||||
<= (after.start.line, after.start.character),
|
||||
"{text:?} at {offset}: ranges overlap: {answer:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_named_both_ways_answers_only_the_blocks_own_pair() {
|
||||
// `x : begin : y ... end : y` is illegal SV (IEEE 1800 §9.3.5: a block
|
||||
// is named one way or the other), but the tolerant parser accepts it
|
||||
// — the block wrote its own label, so `Labeled`'s prefix-label gate
|
||||
// (`prefix_labelled_end`, only fires when the block wrote no label of
|
||||
// its own) must stay silent and the block's own (y, y) pair, not a
|
||||
// fabricated (x, y), must be what answers.
|
||||
let text = "module m;\n initial x : begin : y\n z = 1;\n end : y\nendmodule\n";
|
||||
assert_total_and_sane(text);
|
||||
let y_pair = linked(text, at(text, "y")).expect("the block's own label pairs");
|
||||
assert_eq!(y_pair.len(), 2);
|
||||
assert_eq!(linked(text, text.rfind('y').expect("closing y") as u32), Some(y_pair));
|
||||
// `x` is not part of any pair: the prefix label was correctly not
|
||||
// linked to anything.
|
||||
assert!(linked(text, at(text, "x")).is_none(), "the unused prefix label links nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched() {
|
||||
// `x : begin ... end : y` — the block wrote no label of its own, so
|
||||
// the prefix-label gate does fire and pushes (x, y). The two names
|
||||
// differ, so this must still answer null, the same as any other
|
||||
// mismatch — the gate firing is not itself a promise of a match.
|
||||
let text = "module m;\n initial x : begin\n z = 1;\n end : y\nendmodule\n";
|
||||
assert_total_and_sane(text);
|
||||
assert!(linked(text, at(text, "x")).is_none(), "mismatched prefix pair: from x");
|
||||
assert!(linked(text, at(text, "y")).is_none(), "mismatched prefix pair: from y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stray_second_end_label_after_the_block_already_closed_is_inert() {
|
||||
// Two `end : x` for one `begin : x`. The first one closes the block;
|
||||
// the second is leftover tokens the item-level recovery has to make
|
||||
// sense of on its own. Whatever it becomes, it must not create a
|
||||
// second, wrong pairing, and it must not make the walk panic.
|
||||
let text = "module m;\n initial begin : x\n z = 1;\n end : x\n end : x\nendmodule\n";
|
||||
assert_total_and_sane(text);
|
||||
let doc = doc_of(text);
|
||||
let mut pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut pairs);
|
||||
assert_eq!(pairs.len(), 1, "the stray `end : x` must not mint a second pair");
|
||||
// The pair that does exist closes on the FIRST `end : x`, not the
|
||||
// second — the leftover tokens answer nothing at all.
|
||||
let first_end = text.find("end : x").expect("first end");
|
||||
let second_end = text.rfind("end : x").expect("second end");
|
||||
assert_ne!(first_end, second_end);
|
||||
assert!(
|
||||
linked(text, second_end as u32 + 6).is_none(),
|
||||
"the leftover end : x links nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_and_unclosed_labeled_constructs_never_panic() {
|
||||
for text in [
|
||||
"module m;\n initial begin : blk\n z = 1;\nendmodule\n", // `end` missing
|
||||
"module m;\n initial begin : blk\n z = 1;\n", // no closer at all, EOF
|
||||
"module m;\n initial begin : \n end : \nendmodule\n", // label written, no name
|
||||
"module m;\n initial begin :\n end\nendmodule\n", // colon, no name, no close label
|
||||
] {
|
||||
assert_total_and_sane(text);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_closing_labels_never_bleed_into_each_other() {
|
||||
// `endfunction : f` immediately followed by `endmodule : m` on the
|
||||
// next line: the "name spans never touch" claim, checked at the exact
|
||||
// boundary a lexer could in principle blur.
|
||||
let text = "module m;\n function f;\n endfunction : f\nendmodule : m\n";
|
||||
assert_total_and_sane(text);
|
||||
let f = linked(text, at(text, "f;")).expect("the function pairs");
|
||||
let m = linked(text, at_after(text, "module ")).expect("the module pairs");
|
||||
assert_ne!(f, m);
|
||||
}
|
||||
|
||||
/// The ranges cover exactly the identifier's bytes — never the `:`, never
|
||||
/// the surrounding whitespace or a comment written between them. An
|
||||
/// off-by-one here would let a client's keystroke land on the colon.
|
||||
#[test]
|
||||
fn ranges_cover_exactly_the_identifier_never_the_colon_or_comment() {
|
||||
let cases: [(&str, &str, &str); 3] = [
|
||||
("module m;\nendmodule : /*c*/ m\n", "module ", "m"),
|
||||
("module m;\n initial begin:x\n end:x\nendmodule\n", "begin:", "x"),
|
||||
("module m;\n initial begin :\n x\n end :\n x\nendmodule\n", "begin :\n ", "x"),
|
||||
];
|
||||
for (text, header_prefix, want) in cases {
|
||||
let doc = doc_of(text);
|
||||
let answer = linked_editing_ranges(&doc, at_after(text, header_prefix))
|
||||
.unwrap_or_else(|| panic!("{text:?}: the header answers"));
|
||||
let positions = doc.positions();
|
||||
// Decode each `Range` back to a byte span via the same
|
||||
// `Positions::offset` the server itself uses to turn a client
|
||||
// position into an offset, and check it covers exactly the name
|
||||
// — not the colon, not a space, not the comment beside it.
|
||||
for range in &answer.ranges {
|
||||
let start = positions.offset(range.start) as usize;
|
||||
let end = positions.offset(range.end) as usize;
|
||||
assert_eq!(&text[start..end], want, "{text:?}: range {range:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// corpus sweep — real RTL, every offset, machine-checked invariants
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every offset of a handful of real corpus files that write closing
|
||||
/// labels: totality (no panic), and every `Some` answer's two ranges hold
|
||||
/// identical text and do not overlap. Skipped when `corpus/` is not
|
||||
/// checked out, like every other corpus test in this crate.
|
||||
#[test]
|
||||
fn a_corpus_sweep_of_labeled_constructs_is_total_and_sane() {
|
||||
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let files = [
|
||||
"common_cells/src/lzc.sv",
|
||||
"common_cells/src/rr_arb_tree.sv",
|
||||
"common_cells/src/popcount.sv",
|
||||
"common_cells/src/cdc_reset_ctrlr.sv",
|
||||
"common_cells/src/deprecated/rrarbiter.sv",
|
||||
"common_cells/src/deprecated/prioarbiter.sv",
|
||||
"common_cells/src/stream_fifo_optimal_wrap.sv",
|
||||
"common_cells/src/stream_throttle.sv",
|
||||
"ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv",
|
||||
"ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_monitor.sv",
|
||||
"opentitan/hw/ip/uart/dv/env/seq_lib/uart_base_vseq.sv",
|
||||
];
|
||||
let mut files_checked = 0;
|
||||
let mut pairs_found = 0;
|
||||
for name in files {
|
||||
let path = corpus.join(name);
|
||||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||||
eprintln!("{} not checked out — skipping", path.display());
|
||||
continue;
|
||||
};
|
||||
assert!(
|
||||
text.contains("end") && text.contains(':'),
|
||||
"{}: premise, this file should write a closing label",
|
||||
path.display()
|
||||
);
|
||||
let doc = doc_of(&text);
|
||||
let mut file_pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut file_pairs);
|
||||
pairs_found += file_pairs.len();
|
||||
let positions = doc.positions();
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let Some(answer) = linked_editing_ranges(&doc, offset) else { continue };
|
||||
assert_eq!(answer.ranges.len(), 2, "{}: {answer:?}", path.display());
|
||||
let (a, b) = (answer.ranges[0], answer.ranges[1]);
|
||||
let a_text =
|
||||
&text[positions.offset(a.start) as usize..positions.offset(a.end) as usize];
|
||||
let b_text =
|
||||
&text[positions.offset(b.start) as usize..positions.offset(b.end) as usize];
|
||||
assert_eq!(
|
||||
a_text,
|
||||
b_text,
|
||||
"{}: at {offset}, ranges hold different text",
|
||||
path.display()
|
||||
);
|
||||
assert!(
|
||||
is_simple_identifier(a_text),
|
||||
"{}: at {offset}, {a_text:?} is not a plain identifier",
|
||||
path.display()
|
||||
);
|
||||
assert!(
|
||||
(a.end.line, a.end.character) <= (b.start.line, b.start.character)
|
||||
|| (b.end.line, b.end.character) <= (a.start.line, a.start.character),
|
||||
"{}: at {offset}, ranges overlap: {answer:?}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
files_checked += 1;
|
||||
}
|
||||
assert!(files_checked > 5, "the corpus really is checked out: {files_checked} files");
|
||||
assert!(
|
||||
pairs_found > 10,
|
||||
"these files really do write closing labels: {pairs_found} pairs"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing() {
|
||||
let text = "module m;\n initial begin : blk\n end : blk\nendmodule\n";
|
||||
for (offset, what) in [
|
||||
(at(text, ": blk"), "the colon before the header's `blk`"),
|
||||
(at(text, ": blk") + 1, "the space after that colon"),
|
||||
(at(text, " end"), "the indentation before `end`, between the two names"),
|
||||
] {
|
||||
// A position strictly on the colon or on whitespace — never on a
|
||||
// letter of `blk` itself — answers nothing, even with `blk`
|
||||
// close by on both sides.
|
||||
assert!(linked(text, offset).is_none(), "{what}: {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_of_a_whole_file_finds_every_construct_once() {
|
||||
let text = concat!(
|
||||
"package p;\n",
|
||||
"endpackage : p\n",
|
||||
"module m;\n",
|
||||
" function f;\n",
|
||||
" endfunction : f\n",
|
||||
" task t;\n",
|
||||
" endtask : t\n",
|
||||
" initial begin : blk\n",
|
||||
" end : blk\n",
|
||||
"endmodule : m\n",
|
||||
);
|
||||
let doc = doc_of(text);
|
||||
let mut pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut pairs);
|
||||
assert_eq!(pairs.len(), 5, "package, module, function, task, named begin");
|
||||
// And every one of them is reachable from either of its own names.
|
||||
for pair in &pairs {
|
||||
assert!(linked_editing_ranges(&doc, pair.open.start).is_some());
|
||||
assert!(linked_editing_ranges(&doc, pair.close.start).is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ mod completion;
|
||||
mod convert;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod file_ops;
|
||||
mod folding;
|
||||
mod format;
|
||||
mod hierarchy;
|
||||
@@ -20,19 +21,26 @@ mod includes;
|
||||
mod inlay;
|
||||
mod inline;
|
||||
mod instantiations;
|
||||
mod lens;
|
||||
mod linked;
|
||||
mod lint;
|
||||
mod locate;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod selection;
|
||||
mod server;
|
||||
mod settings;
|
||||
mod signature;
|
||||
mod state;
|
||||
mod symbols;
|
||||
mod sync;
|
||||
mod templates;
|
||||
mod tokens;
|
||||
mod type_def;
|
||||
mod type_hierarchy;
|
||||
mod uri;
|
||||
mod watch;
|
||||
|
||||
@@ -42,11 +50,15 @@ use std::path::PathBuf;
|
||||
use lsp_server::Connection;
|
||||
use lsp_types::{
|
||||
CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability,
|
||||
CompletionOptions, DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability,
|
||||
InitializeParams, InlayHintOptions, InlayHintServerCapabilities, OneOf, PositionEncodingKind,
|
||||
RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
|
||||
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
|
||||
TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions,
|
||||
CodeLensOptions, CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities,
|
||||
DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions,
|
||||
FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
|
||||
InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind,
|
||||
RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions,
|
||||
SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities,
|
||||
ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
|
||||
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability,
|
||||
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
};
|
||||
|
||||
use crate::server::{ClientAbilities, Server};
|
||||
@@ -56,6 +68,10 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
let (connection, io_threads) = Connection::stdio();
|
||||
|
||||
let (id, params) = connection.initialize_start()?;
|
||||
// Read before the typed decode, because `lsp-types` 0.97's client
|
||||
// capabilities have no field for it and drop it on the floor — see
|
||||
// `ranges_formatting_support`.
|
||||
let ranges_formatting = ranges_formatting_support(¶ms);
|
||||
// A client that sends params we cannot read still gets a server; every
|
||||
// field we want is optional anyway.
|
||||
let params: InitializeParams = serde_json::from_value(params).unwrap_or_default();
|
||||
@@ -63,8 +79,14 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
let abilities = ClientAbilities {
|
||||
snippets: snippet_support(¶ms),
|
||||
file_watching: watch::dynamic_registration(¶ms),
|
||||
apply_edit: apply_edit_support(¶ms),
|
||||
pull_diagnostics: pull_diagnostics_support(¶ms),
|
||||
work_done_progress: work_done_progress_support(¶ms),
|
||||
code_lens_refresh: code_lens_refresh_support(¶ms),
|
||||
show_document: show_document_support(¶ms),
|
||||
configuration: configuration_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?;
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
Server::new(connection, roots, abilities).run()?;
|
||||
io_threads.join()?;
|
||||
@@ -79,10 +101,54 @@ fn capabilities() -> ServerCapabilities {
|
||||
// The protocol default, and what the conversion in `convert.rs`
|
||||
// implements. Stated rather than left implicit.
|
||||
position_encoding: Some(PositionEncodingKind::UTF16),
|
||||
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
|
||||
// Incremental sync: a keystroke costs one range, not the whole file.
|
||||
// Spelled out as options rather than a bare kind because a bare kind
|
||||
// says nothing about open/close or save, and clients fill that in
|
||||
// themselves — this states the same defaults a bare kind resolved to,
|
||||
// so nothing but `change` moves. `includeText: false` keeps a save
|
||||
// from re-sending a buffer the server already tracks edit by edit;
|
||||
// the `didSave` handler still honours text if a client sends it.
|
||||
text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
|
||||
open_close: Some(true),
|
||||
change: Some(TextDocumentSyncKind::INCREMENTAL),
|
||||
// The plain `willSave` notification carries nothing this server
|
||||
// can act on, so it is left unadvertised; `willSaveWaitUntil` is
|
||||
// the format-on-save hook, for the editors that have no
|
||||
// format-on-save of their own. It answers `null` unless
|
||||
// `lucisv.formatOnSave` is on — see
|
||||
// `docs/features/will-save-wait-until/README.md`.
|
||||
will_save: None,
|
||||
will_save_wait_until: Some(true),
|
||||
save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
|
||||
include_text: Some(false),
|
||||
})),
|
||||
})),
|
||||
document_formatting_provider: Some(OneOf::Left(true)),
|
||||
document_range_formatting_provider: Some(OneOf::Left(true)),
|
||||
// Two trigger characters, and only two. A newline re-indents the line
|
||||
// it opened; a `;` lays out the statement it ended, through the range
|
||||
// engine. Not `}` — SV closes its blocks with the *word* `end`, and
|
||||
// re-triggering on letters would run this on half of every identifier.
|
||||
// Advertised unconditionally: on-type formatting only fires where the
|
||||
// client's own `editor.formatOnType` is on, which is off by default,
|
||||
// so the user has already opted in by the time a request arrives. See
|
||||
// `docs/features/on-type-formatting/README.md`.
|
||||
document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions {
|
||||
first_trigger_character: on_type::NEWLINE.to_string(),
|
||||
more_trigger_character: Some(vec![on_type::SEMICOLON.to_string()]),
|
||||
}),
|
||||
definition_provider: Some(OneOf::Left(true)),
|
||||
// The same jump one token to the left: from a name to where its type
|
||||
// is declared. `Simple(true)` rather than a registration — there is
|
||||
// nothing to scope it to that `definitionProvider` is not already
|
||||
// scoped to. See `docs/features/type-definition/README.md`.
|
||||
type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
|
||||
// SV's closing labels, edited as one name: `module m` and
|
||||
// `endmodule : m` change together. `Simple(true)` rather than a
|
||||
// registration — there is nothing to scope it to, and the handler
|
||||
// declines every position that is not one of the two names. See
|
||||
// `docs/features/linked-editing/README.md`.
|
||||
linked_editing_range_provider: Some(LinkedEditingRangeServerCapabilities::Simple(true)),
|
||||
references_provider: Some(OneOf::Left(true)),
|
||||
// `` `include`` lines, underlined and ctrl-clickable. Every link is
|
||||
// returned with its target already resolved, so there is nothing for
|
||||
@@ -125,11 +191,19 @@ fn capabilities() -> ServerCapabilities {
|
||||
})),
|
||||
// The port refactorings. `lucisv.addPort` needs a declaration typed by
|
||||
// the user, which no code action can carry, and a Vim user has no
|
||||
// lightbulb at all — so all three are commands as well.
|
||||
// lightbulb at all — so all three are commands as well. The code
|
||||
// lens's own jump joins them: a lens carries a `Command`, and this is
|
||||
// where a command has to be declared to be runnable.
|
||||
execute_command_provider: Some(ExecuteCommandOptions {
|
||||
commands: ports::commands(),
|
||||
commands: commands(),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
}),
|
||||
// "N instantiations" over every module and interface declaration in
|
||||
// the buffer, counted across the workspace. Every lens is returned
|
||||
// complete — title, command and arguments — so there is nothing for
|
||||
// `codeLens/resolve` to do, which is said out loud rather than left
|
||||
// unset. See `docs/features/code-lens/README.md`.
|
||||
code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(false) }),
|
||||
// Module hinting. No trigger characters: an identifier being typed is
|
||||
// what asks for these, and the handler declines every position that is
|
||||
// not a module item, so an unprompted request costs a token scan.
|
||||
@@ -172,6 +246,43 @@ fn capabilities() -> ServerCapabilities {
|
||||
// sends the request after opting into `ProposedFeatures`, so an
|
||||
// extension older than this server simply never asks.
|
||||
inline_completion_provider: Some(OneOf::Left(true)),
|
||||
// Expand-selection. Nothing to configure: the chain is computed from
|
||||
// the buffer alone, and every position is answered.
|
||||
selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
|
||||
// Pull diagnostics (3.17), served from the same parse+lint pass the
|
||||
// push model publishes. `inter_file_dependencies` because a save
|
||||
// rebuilds the workspace index and *that* changes what other files
|
||||
// report; `workspace_diagnostics` because `workspace/diagnostic` is
|
||||
// answered — over the open buffers, which is the only scope this
|
||||
// server has ever diagnosed.
|
||||
diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
|
||||
identifier: Some(diagnostics::SOURCE.to_string()),
|
||||
inter_file_dependencies: true,
|
||||
workspace_diagnostics: true,
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
})),
|
||||
// File operations (3.16): renaming a header rewrites the
|
||||
// `` `include``s that resolve to it, and a rename or a delete nudges
|
||||
// the index without waiting for the watcher round-trip. Advertised
|
||||
// unconditionally — unlike the watchers, nothing here is
|
||||
// server-initiated, so a client that cannot send these requests simply
|
||||
// never sends them and the capability costs it nothing. See
|
||||
// `docs/features/file-operations/README.md`.
|
||||
workspace: Some(WorkspaceServerCapabilities {
|
||||
// Workspace folders, added and removed mid-session. Both halves
|
||||
// are needed and neither implies the other: `supported` says the
|
||||
// server understands a multi-folder workspace at all, and
|
||||
// `changeNotifications` is what makes the client *send*
|
||||
// `didChangeWorkspaceFolders`. `Left(true)` rather than an id —
|
||||
// the string form exists so the registration can later be undone
|
||||
// by name, and this server never unregisters it. See
|
||||
// `docs/features/folders-and-config/README.md`.
|
||||
workspace_folders: Some(WorkspaceFoldersServerCapabilities {
|
||||
supported: Some(true),
|
||||
change_notifications: Some(OneOf::Left(true)),
|
||||
}),
|
||||
file_operations: Some(file_ops::file_operations()),
|
||||
}),
|
||||
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
|
||||
SemanticTokensOptions {
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
@@ -179,14 +290,62 @@ fn capabilities() -> ServerCapabilities {
|
||||
token_types: tokens::token_types(),
|
||||
token_modifiers: tokens::token_modifiers(),
|
||||
},
|
||||
range: None,
|
||||
full: Some(SemanticTokensFullOptions::Bool(true)),
|
||||
// The visible lines, for the first paint of a large file:
|
||||
// the same tokenizer, filtered, and re-encoded from the
|
||||
// start of the document so the answer stands on its own.
|
||||
range: Some(true),
|
||||
// `delta: true` rather than a bare `full: true`, so a client
|
||||
// that has an answer already asks what changed instead of
|
||||
// re-fetching the file's whole token set on every keystroke.
|
||||
// `full` itself stays served — the enum's `Delta` variant is
|
||||
// the full capability plus deltas, not a replacement.
|
||||
full: Some(SemanticTokensFullOptions::Delta { delta: Some(true) }),
|
||||
},
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Every command this server executes: the three port refactorings, and the
|
||||
/// jump the code lens hangs off.
|
||||
fn commands() -> Vec<String> {
|
||||
let mut commands = ports::commands();
|
||||
commands.extend(lens::commands());
|
||||
commands
|
||||
}
|
||||
|
||||
/// The `initialize` result exactly as it goes on the wire.
|
||||
///
|
||||
/// Two capabilities are written in here rather than in [`capabilities`],
|
||||
/// because `lsp-types` 0.97 cannot spell either:
|
||||
///
|
||||
/// * **`typeHierarchyProvider`** — the crate models type hierarchy on the
|
||||
/// *client* side only, so `ServerCapabilities` has no field for it, and
|
||||
/// `experimental` is a different key that no client reads for this.
|
||||
/// * **`documentRangeFormattingProvider`** widened to
|
||||
/// `{ "rangesSupport": true }` when `ranges_formatting` — the crate's
|
||||
/// `DocumentRangeFormattingOptions` carries only `workDoneProgress`. This is
|
||||
/// the spec's own `boolean | DocumentRangeFormattingOptions` union, so the
|
||||
/// object form is legal for any client; it is sent only to a client that
|
||||
/// asked because the bare `true` is the shape no client can misread, and a
|
||||
/// client that did not ask will never send the request anyway. See
|
||||
/// `docs/features/lsp-318-extras/README.md`.
|
||||
///
|
||||
/// Both are the same JSON a field would have produced.
|
||||
fn initialize_value(ranges_formatting: bool) -> Result<serde_json::Value, serde_json::Error> {
|
||||
let mut value = serde_json::to_value(initialize_result())?;
|
||||
if let Some(caps) = value.get_mut("capabilities").and_then(serde_json::Value::as_object_mut) {
|
||||
caps.insert("typeHierarchyProvider".to_string(), serde_json::Value::Bool(true));
|
||||
if ranges_formatting {
|
||||
caps.insert(
|
||||
"documentRangeFormattingProvider".to_string(),
|
||||
serde_json::json!({ "rangesSupport": true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn initialize_result() -> lsp_types::InitializeResult {
|
||||
lsp_types::InitializeResult {
|
||||
capabilities: capabilities(),
|
||||
@@ -200,6 +359,21 @@ fn initialize_result() -> lsp_types::InitializeResult {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the client can send `textDocument/rangesFormatting` (LSP 3.18),
|
||||
/// read from the **raw** `initialize` params.
|
||||
///
|
||||
/// It has to be the raw JSON: `lsp-types` 0.97 aliases
|
||||
/// `DocumentRangeFormattingClientCapabilities` to the plain dynamic-registration
|
||||
/// struct, which has no `rangesSupport` field and no place to keep an unknown
|
||||
/// one, so by the time the params are an `InitializeParams` the flag is gone.
|
||||
/// Anything that is not literally `true` at
|
||||
/// `capabilities.textDocument.rangeFormatting.rangesSupport` — absent, `false`,
|
||||
/// a string, a client whose params do not parse at all — means no, which is
|
||||
/// exactly the answer that leaves that client's capability where it was.
|
||||
fn ranges_formatting_support(params: &serde_json::Value) -> bool {
|
||||
params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] == true
|
||||
}
|
||||
|
||||
/// Whether the client can expand `${1:x}` tabstops in a completion item.
|
||||
///
|
||||
/// A client that did not say so gets the skeleton as plain text: a literal
|
||||
@@ -216,6 +390,94 @@ fn snippet_support(params: &InitializeParams) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client applies a `workspace/applyEdit` request.
|
||||
///
|
||||
/// A client that did not say so gets a command's edit back as the request
|
||||
/// result — which is what every client got before this was read, and is the
|
||||
/// only thing left to try for one that cannot be pushed an edit.
|
||||
fn apply_edit_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.apply_edit)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client pulls diagnostics (LSP 3.17).
|
||||
///
|
||||
/// Sending the capability at all is what says so; its two fields are about
|
||||
/// dynamic registration and related documents, neither of which this server
|
||||
/// uses. A client that says nothing keeps the push model unchanged.
|
||||
fn pull_diagnostics_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.text_document
|
||||
.as_ref()
|
||||
.is_some_and(|text_document| text_document.diagnostic.is_some())
|
||||
}
|
||||
|
||||
/// Whether the client renders server-initiated work-done progress.
|
||||
///
|
||||
/// The spec forbids a server from creating progress at all without this, so a
|
||||
/// client that said nothing is sent no `window/workDoneProgress/create` and no
|
||||
/// `$/progress` — the workspace rescan is silent for it, exactly as it was
|
||||
/// before this was read.
|
||||
fn work_done_progress_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.window
|
||||
.as_ref()
|
||||
.and_then(|window| window.work_done_progress)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client can be asked to re-request its code lenses.
|
||||
///
|
||||
/// `workspace/codeLens/refresh` is server-initiated, so the spec makes this
|
||||
/// capability the gate. A client that said nothing keeps whatever counts it
|
||||
/// last asked for until something else makes it ask again — which is what
|
||||
/// every client got before code lenses existed at all.
|
||||
fn code_lens_refresh_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.code_lens.as_ref())
|
||||
.and_then(|code_lens| code_lens.refresh_support)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client opens a document the server asks it to.
|
||||
///
|
||||
/// This is what makes the instantiation lens actually navigate: an
|
||||
/// `executeCommand` result cannot move a cursor, so the jump is a pushed
|
||||
/// `window/showDocument`. A client that did not advertise it still gets the
|
||||
/// sites back as the command's result.
|
||||
fn show_document_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.window
|
||||
.as_ref()
|
||||
.and_then(|window| window.show_document.as_ref())
|
||||
.is_some_and(|show_document| show_document.support)
|
||||
}
|
||||
|
||||
/// Whether the client answers `workspace/configuration`.
|
||||
///
|
||||
/// The pull half of the settings model: a client that says so is asked for
|
||||
/// the `lucisv` section at startup and again whenever it sends an empty
|
||||
/// `didChangeConfiguration`. A client that said nothing is only ever pushed
|
||||
/// settings, exactly as before.
|
||||
fn configuration_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.configuration)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The directories to index: the client's workspace folders, or the
|
||||
/// deprecated single root when that is all it sent.
|
||||
fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
|
||||
@@ -239,6 +501,8 @@ mod tests {
|
||||
assert!(caps.document_formatting_provider.is_some());
|
||||
assert!(caps.document_range_formatting_provider.is_some());
|
||||
assert!(caps.definition_provider.is_some());
|
||||
assert!(caps.type_definition_provider.is_some());
|
||||
assert!(caps.linked_editing_range_provider.is_some());
|
||||
assert!(caps.references_provider.is_some());
|
||||
assert!(caps.document_link_provider.is_some());
|
||||
assert!(caps.document_highlight_provider.is_some());
|
||||
@@ -255,6 +519,322 @@ mod tests {
|
||||
assert!(caps.inlay_hint_provider.is_some());
|
||||
assert!(caps.call_hierarchy_provider.is_some());
|
||||
assert!(caps.inline_completion_provider.is_some());
|
||||
assert!(caps.selection_range_provider.is_some());
|
||||
assert!(caps.diagnostic_provider.is_some());
|
||||
assert!(caps.code_lens_provider.is_some());
|
||||
assert!(caps.document_on_type_formatting_provider.is_some());
|
||||
assert!(caps.workspace.is_some(), "the file operations live here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_operations_reach_the_wire_under_workspace() {
|
||||
// A client sends `willRenameFiles` only where the *server's* filters
|
||||
// say so, and it looks for them at this exact key — a capability
|
||||
// nested one level wrong is a capability that is never exercised.
|
||||
let value = initialize_value(false).expect("the initialize result serializes");
|
||||
let operations = &value["capabilities"]["workspace"]["fileOperations"];
|
||||
assert_eq!(
|
||||
operations["willRename"]["filters"][0]["pattern"]["glob"],
|
||||
serde_json::json!(watch::SOURCE_GLOB),
|
||||
"{value:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
operations["willRename"]["filters"][1]["pattern"]["matches"],
|
||||
serde_json::json!("folder"),
|
||||
"a folder rename moves every include that reached into it"
|
||||
);
|
||||
assert_eq!(operations["didRename"]["filters"].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(operations["didDelete"]["filters"].as_array().map(Vec::len), Some(1));
|
||||
// The three this server does not answer are absent, not empty: a
|
||||
// filter list a server cannot serve is a request it will be sent.
|
||||
for absent in ["willCreate", "didCreate", "willDelete"] {
|
||||
assert_eq!(operations[absent], serde_json::Value::Null, "{absent} is not answered");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_folders_are_supported_and_their_changes_are_asked_for() {
|
||||
// Two separate statements, and a client reads them separately:
|
||||
// without `supported` it may not treat this as a multi-folder server
|
||||
// at all, and without `changeNotifications` it never sends
|
||||
// `didChangeWorkspaceFolders` however well that is handled.
|
||||
let folders = capabilities()
|
||||
.workspace
|
||||
.expect("the workspace section")
|
||||
.workspace_folders
|
||||
.expect("workspace folders");
|
||||
assert_eq!(folders.supported, Some(true));
|
||||
assert_eq!(folders.change_notifications, Some(OneOf::Left(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_workspace_folder_capability_reaches_the_wire_at_the_key_a_client_reads() {
|
||||
// Nested one level wrong, or serialized as the string form of
|
||||
// `changeNotifications`, and the notification simply never arrives.
|
||||
let value = initialize_value(false).expect("the initialize result serializes");
|
||||
assert_eq!(
|
||||
value["capabilities"]["workspace"]["workspaceFolders"],
|
||||
serde_json::json!({ "supported": true, "changeNotifications": true }),
|
||||
"{value:#?}"
|
||||
);
|
||||
// And the neighbour under the same key is untouched.
|
||||
assert!(value["capabilities"]["workspace"]["fileOperations"].is_object(), "{value:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configuration_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities};
|
||||
assert!(!configuration_support(&InitializeParams::default()), "silence means push-only");
|
||||
|
||||
let saying = |configuration: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities {
|
||||
configuration,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(configuration_support(&saying(Some(true))));
|
||||
assert!(!configuration_support(&saying(Some(false))));
|
||||
assert!(!configuration_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_type_hierarchy_is_advertised_even_though_lsp_types_cannot_spell_it() {
|
||||
// `ServerCapabilities` has no `type_hierarchy_provider` field in
|
||||
// lsp-types 0.97 — the crate models type hierarchy on the client side
|
||||
// only — so the capability is written into the serialized object. A
|
||||
// client keys entirely off this key: without it the three requests are
|
||||
// never sent, however well they are implemented.
|
||||
let value = initialize_value(false).expect("the initialize result serializes");
|
||||
assert_eq!(
|
||||
value["capabilities"]["typeHierarchyProvider"],
|
||||
serde_json::json!(true),
|
||||
"{value:#?}"
|
||||
);
|
||||
// And the rest of the object is untouched by the insertion.
|
||||
assert_eq!(value["capabilities"]["callHierarchyProvider"], serde_json::json!(true));
|
||||
assert_eq!(value["serverInfo"]["name"], serde_json::json!("lucisv-server"));
|
||||
}
|
||||
|
||||
// QA (2026-08-26): the spot checks above name two fields; this pins the
|
||||
// whole object instead. `initialize_result()` and `capabilities()` are
|
||||
// untouched by this round (confirmed against `24e8eab`), so the only way
|
||||
// the insertion could disturb anything is the one `caps.insert` call
|
||||
// itself — this proves that byte-for-byte rather than by inspection: pull
|
||||
// the one inserted key back out and what remains must equal the plain,
|
||||
// uninserted serialization exactly. A future round that lets the
|
||||
// insertion clobber an existing key, or that adds a field to
|
||||
// `ServerCapabilities` under the same JSON name, fails this immediately.
|
||||
#[test]
|
||||
fn the_json_insertion_disturbs_nothing_else_in_the_initialize_result() {
|
||||
let mut with_insertion = initialize_value(false).expect("the initialize result serializes");
|
||||
let plain = serde_json::to_value(initialize_result()).expect("serializes on its own too");
|
||||
let caps =
|
||||
with_insertion["capabilities"].as_object_mut().expect("capabilities is a JSON object");
|
||||
assert_eq!(
|
||||
caps.remove("typeHierarchyProvider"),
|
||||
Some(serde_json::json!(true)),
|
||||
"the one key the insertion is supposed to add"
|
||||
);
|
||||
assert_eq!(
|
||||
with_insertion, plain,
|
||||
"removing the inserted key must restore exactly what capabilities() \
|
||||
and initialize_result() produce on their own, key for key, value for value"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `rangesFormatting` (LSP 3.18) — the capability, on both wire shapes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// `initialize` params carrying whatever a client said about
|
||||
/// `rangesSupport`, as raw JSON — which is the only place it survives.
|
||||
fn client_saying(ranges_support: serde_json::Value) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"processId": null,
|
||||
"capabilities": {
|
||||
"textDocument": { "rangeFormatting": { "rangesSupport": ranges_support } }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_formatting_support_is_read_from_the_raw_params_and_only_when_literally_true() {
|
||||
assert!(ranges_formatting_support(&client_saying(serde_json::json!(true))));
|
||||
assert!(!ranges_formatting_support(&client_saying(serde_json::json!(false))));
|
||||
// Junk in that slot is not a yes. A client that means it sends `true`.
|
||||
assert!(!ranges_formatting_support(&client_saying(serde_json::json!("yes"))));
|
||||
assert!(!ranges_formatting_support(&client_saying(serde_json::Value::Null)));
|
||||
// The 3.17 client: the key is not there at all.
|
||||
assert!(!ranges_formatting_support(&serde_json::json!({ "capabilities": {} })));
|
||||
// And params that are not even an object — `Value::index` answers
|
||||
// `Null` rather than panicking, which is the whole reason this is a
|
||||
// JSON read and not a typed one.
|
||||
assert!(!ranges_formatting_support(&serde_json::json!("nonsense")));
|
||||
assert!(!ranges_formatting_support(&serde_json::Value::Null));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_sees_the_capability_exactly_as_it_always_was() {
|
||||
// The gate's whole point: every client that shipped before this round
|
||||
// must see the same byte on the wire. A bare `true` is the shape no
|
||||
// client can misread, and one that never advertised `rangesSupport`
|
||||
// will never send the request however it is advertised.
|
||||
let value = initialize_value(false).expect("the initialize result serializes");
|
||||
assert_eq!(
|
||||
value["capabilities"]["documentRangeFormattingProvider"],
|
||||
serde_json::json!(true),
|
||||
"{value:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_asked_sees_the_options_object_with_ranges_support() {
|
||||
// `documentRangeFormattingProvider` is `boolean |
|
||||
// DocumentRangeFormattingOptions` in the spec, and `rangesSupport` is
|
||||
// a field on the options arm — so widening the bool to the object is
|
||||
// how the spec says to answer, and it is the only way
|
||||
// `vscode-languageclient` will register its multi-range provider.
|
||||
let value = initialize_value(true).expect("the initialize result serializes");
|
||||
assert_eq!(
|
||||
value["capabilities"]["documentRangeFormattingProvider"],
|
||||
serde_json::json!({ "rangesSupport": true }),
|
||||
"{value:#?}"
|
||||
);
|
||||
// Single-range formatting is still advertised by that same key — the
|
||||
// object is not an *extra* capability, it is the same one saying more.
|
||||
assert!(
|
||||
value["capabilities"]["documentRangeFormattingProvider"].is_object(),
|
||||
"and never a second key: {value:#?}"
|
||||
);
|
||||
assert_eq!(value["capabilities"]["documentRangeFormattingProvider"]["rangesSupport"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_the_range_capability_disturbs_nothing_else_in_the_initialize_result() {
|
||||
// The same proof `the_json_insertion_disturbs_nothing_else...` gives
|
||||
// for `typeHierarchyProvider`, for the second inserted key: the two
|
||||
// results must differ at exactly one key and be equal everywhere else.
|
||||
let mut gated = initialize_value(true).expect("serializes");
|
||||
let plain = initialize_value(false).expect("serializes");
|
||||
let caps = gated["capabilities"].as_object_mut().expect("capabilities is a JSON object");
|
||||
assert_eq!(
|
||||
caps.insert("documentRangeFormattingProvider".to_string(), serde_json::json!(true)),
|
||||
Some(serde_json::json!({ "rangesSupport": true })),
|
||||
"the one key the widening is supposed to replace"
|
||||
);
|
||||
assert_eq!(
|
||||
gated, plain,
|
||||
"putting the bare `true` back must restore the ungated result exactly"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else() {
|
||||
// The trigger set is the feature: a client sends this request on every
|
||||
// one of these characters and on no other, so what is listed here is
|
||||
// exactly what `on_type::on_type_formatting` knows how to answer. `}`
|
||||
// is deliberately absent — SV closes its blocks with the word `end`.
|
||||
let options = capabilities().document_on_type_formatting_provider.expect("advertised");
|
||||
assert_eq!(options.first_trigger_character, "\n");
|
||||
assert_eq!(options.more_trigger_character, Some(vec![";".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_semantic_token_capability_asks_for_ranges_and_for_deltas() {
|
||||
// A client keys entirely off this: it sends `full/delta` only where
|
||||
// `full.delta` is `true`, and `range` only where `range` is.
|
||||
let Some(SemanticTokensServerCapabilities::SemanticTokensOptions(options)) =
|
||||
capabilities().semantic_tokens_provider
|
||||
else {
|
||||
panic!("the options form, not a registration");
|
||||
};
|
||||
assert_eq!(options.range, Some(true));
|
||||
assert_eq!(options.full, Some(SemanticTokensFullOptions::Delta { delta: Some(true) }));
|
||||
assert_eq!(options.legend.token_types.len(), 14, "the legend is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sync_options_ask_for_the_save_hook_and_not_the_notification() {
|
||||
let Some(TextDocumentSyncCapability::Options(options)) = capabilities().text_document_sync
|
||||
else {
|
||||
panic!("the options form, not a bare kind");
|
||||
};
|
||||
assert_eq!(options.change, Some(TextDocumentSyncKind::INCREMENTAL));
|
||||
assert_eq!(options.will_save_wait_until, Some(true), "the format-on-save hook is answered");
|
||||
assert_eq!(options.will_save, None, "the plain notification has nothing for us");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_diagnostic_options_say_what_this_server_actually_does() {
|
||||
let Some(DiagnosticServerCapabilities::Options(options)) =
|
||||
capabilities().diagnostic_provider
|
||||
else {
|
||||
panic!("plain options, not a dynamic registration");
|
||||
};
|
||||
assert_eq!(options.identifier.as_deref(), Some(diagnostics::SOURCE), "same tag as a push");
|
||||
assert!(options.inter_file_dependencies, "a save changes other files' diagnostics");
|
||||
assert!(options.workspace_diagnostics, "`workspace/diagnostic` is answered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_edit_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities};
|
||||
assert!(!apply_edit_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |apply_edit: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities { apply_edit, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(apply_edit_support(&saying(Some(true))));
|
||||
assert!(!apply_edit_support(&saying(Some(false))));
|
||||
assert!(!apply_edit_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_done_progress_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{ClientCapabilities, WindowClientCapabilities};
|
||||
assert!(!work_done_progress_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |work_done_progress: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
window: Some(WindowClientCapabilities { work_done_progress, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(work_done_progress_support(&saying(Some(true))));
|
||||
assert!(!work_done_progress_support(&saying(Some(false))));
|
||||
assert!(!work_done_progress_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_sent_the_diagnostic_capability_at_all_is_a_pulling_client() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, DiagnosticClientCapabilities, TextDocumentClientCapabilities,
|
||||
};
|
||||
assert!(!pull_diagnostics_support(&InitializeParams::default()), "silence means push");
|
||||
|
||||
let pulling = InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
text_document: Some(TextDocumentClientCapabilities {
|
||||
// Both fields left unset: sending the capability is the
|
||||
// whole of the statement, and neither field is about
|
||||
// whether the client pulls.
|
||||
diagnostic: Some(DiagnosticClientCapabilities::default()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(pull_diagnostics_support(&pulling));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -359,7 +939,12 @@ mod tests {
|
||||
#[test]
|
||||
fn every_advertised_command_is_one_the_server_runs() {
|
||||
let options = capabilities().execute_command_provider.expect("commands");
|
||||
assert_eq!(options.commands, ports::commands());
|
||||
assert_eq!(options.commands, commands());
|
||||
// Both halves of the list, so neither can go missing quietly: a lens
|
||||
// whose command is not advertised is a lens no client will run.
|
||||
for command in ports::commands().iter().chain(lens::commands().iter()) {
|
||||
assert!(options.commands.contains(command), "{command} is not advertised");
|
||||
}
|
||||
assert!(
|
||||
options.commands.iter().all(|c| c.starts_with("lucisv.")),
|
||||
"{:?}",
|
||||
@@ -367,6 +952,55 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_lenses_resolve_nothing_because_every_lens_is_complete() {
|
||||
let options = capabilities().code_lens_provider.expect("code lenses");
|
||||
assert_eq!(options.resolve_provider, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_lens_refresh_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, CodeLensWorkspaceClientCapabilities, WorkspaceClientCapabilities,
|
||||
};
|
||||
assert!(!code_lens_refresh_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |refresh_support: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities {
|
||||
code_lens: Some(CodeLensWorkspaceClientCapabilities { refresh_support }),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(code_lens_refresh_support(&saying(Some(true))));
|
||||
assert!(!code_lens_refresh_support(&saying(Some(false))));
|
||||
assert!(!code_lens_refresh_support(&saying(None)), "an empty `codeLens` is not a yes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_document_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, ShowDocumentClientCapabilities, WindowClientCapabilities,
|
||||
};
|
||||
assert!(!show_document_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |support: bool| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
window: Some(WindowClientCapabilities {
|
||||
show_document: Some(ShowDocumentClientCapabilities { support }),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(show_document_support(&saying(true)));
|
||||
assert!(!show_document_support(&saying(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_is_advertised_because_that_is_what_convert_implements() {
|
||||
assert_eq!(capabilities().position_encoding, Some(PositionEncodingKind::UTF16));
|
||||
|
||||
@@ -181,7 +181,11 @@ pub fn document_highlights(doc: &Document, offset: u32) -> Option<Vec<DocumentHi
|
||||
|
||||
/// The symbol at a position. The cursor may sit on a use or on the
|
||||
/// declaration itself; both lead to the same symbol.
|
||||
fn symbol_at(semantics: &Semantics, offset: u32) -> Option<SymbolId> {
|
||||
///
|
||||
/// Shared with `type_def.rs`, which asks the same question one token to the
|
||||
/// left: the two must agree on what a position names, or go-to-definition and
|
||||
/// go-to-type-definition would disagree about the cursor.
|
||||
pub(crate) fn symbol_at(semantics: &Semantics, offset: u32) -> Option<SymbolId> {
|
||||
semantics
|
||||
.reference_at(offset)
|
||||
.and_then(|r| r.resolved())
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -307,10 +307,34 @@ fn opener_rule(text: &str) -> Option<(usize, &'static Rule)> {
|
||||
}
|
||||
|
||||
/// The closer keyword `text` is, as a `'static` string from the table.
|
||||
fn closer_keyword(text: &str) -> Option<&'static str> {
|
||||
pub(crate) fn closer_keyword(text: &str) -> Option<&'static str> {
|
||||
RULES.iter().flat_map(|r| r.close).copied().find(|c| *c == text)
|
||||
}
|
||||
|
||||
/// The keywords that close the scope the token at `i` opens, or `None` when it
|
||||
/// opens none.
|
||||
///
|
||||
/// [`analyze`]'s own two questions — "is this an opener?" and "does it really
|
||||
/// open here?" — asked as one, so the on-type indent model counts nesting off
|
||||
/// exactly the scopes the matcher matches. The [`RULES`] table and
|
||||
/// [`opens_a_scope`]'s exception list must have one reader's answer, not two:
|
||||
/// an `extern function f();` that opened a scope for one of them and not the
|
||||
/// other would leave the two disagreeing about every line below it.
|
||||
///
|
||||
/// The caller still owns the prototype flag ([`starts_a_prototype`]), because
|
||||
/// that one spans tokens and only a running scan can carry it.
|
||||
pub(crate) fn opens_scope_at(tokens: &[Token], i: usize) -> Option<&'static [&'static str]> {
|
||||
let text = tokens.get(i)?.text.as_str();
|
||||
let (_, rule) = opener_rule(text)?;
|
||||
opens_a_scope(tokens, i).then_some(rule.close)
|
||||
}
|
||||
|
||||
/// Whether a keyword turns the rest of its statement into a declaration with
|
||||
/// no body — see [`PROTOTYPE_STARTERS`]. Cleared at the next `;`.
|
||||
pub(crate) fn starts_a_prototype(text: &str) -> bool {
|
||||
PROTOTYPE_STARTERS.contains(&text)
|
||||
}
|
||||
|
||||
/// The opener a closer belongs to, for "`end` has no matching `begin`".
|
||||
fn opener_of(closer: &str) -> &'static str {
|
||||
RULES.iter().find(|r| r.close.contains(&closer)).map_or("", |r| r.open)
|
||||
|
||||
@@ -75,9 +75,10 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
|
||||
|
||||
/// Run one of the three commands, or say why it cannot run.
|
||||
///
|
||||
/// The answer is the `WorkspaceEdit` the client is expected to apply (through
|
||||
/// `workspace/applyEdit`, which the server does not push: an editor that asked
|
||||
/// for the command owns the edit) plus the engine's warnings.
|
||||
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
|
||||
/// it reaches the editor is `server.rs`'s business: it is pushed as a
|
||||
/// `workspace/applyEdit` request, or — for a client that cannot be pushed one
|
||||
/// — returned as the command's result (`docs/features/apply-edit/README.md`).
|
||||
pub fn execute(
|
||||
ws: &Workspace,
|
||||
command: &str,
|
||||
|
||||
@@ -0,0 +1,546 @@
|
||||
//! `textDocument/selectionRange` — expand-selection.
|
||||
//!
|
||||
//! No new analysis: everything the chain is built from is already computed for
|
||||
//! something else. The token stream gives the innermost step, the tolerant
|
||||
//! parse's item and statement spans give the middle ones, and `pairs::analyze`
|
||||
//! — the rainbow's own matcher — gives the scopes a broken parse would
|
||||
//! otherwise lose. The four sources are thrown into one list of byte ranges
|
||||
//! that cover the cursor, and the chain is whatever nests. See
|
||||
//! `docs/features/selection-range/README.md`.
|
||||
|
||||
use lsp_types::{Position, SelectionRange};
|
||||
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::pairs::analyze;
|
||||
use crate::state::Document;
|
||||
|
||||
/// One chain per requested position, in the order they were asked for.
|
||||
///
|
||||
/// Each chain runs innermost first, every step strictly containing the one
|
||||
/// before it and the last one being the whole file. A position that resolves
|
||||
/// to nothing else — an empty buffer, a file that does not lex — still gets
|
||||
/// that last step, because the protocol wants exactly one answer per position.
|
||||
pub fn selection_ranges(doc: &Document, positions: &[Position]) -> Vec<SelectionRange> {
|
||||
let converter = doc.positions();
|
||||
positions.iter().map(|position| chain(doc, converter.offset(*position))).collect()
|
||||
}
|
||||
|
||||
/// The chain for one byte offset.
|
||||
fn chain(doc: &Document, offset: u32) -> SelectionRange {
|
||||
let positions = doc.positions();
|
||||
let mut range: Option<SelectionRange> = None;
|
||||
// Widest first, so each step is built already holding its parent.
|
||||
for span in nested(enclosing(doc, offset)).into_iter().rev() {
|
||||
range = Some(SelectionRange { range: positions.range(span), parent: range.map(Box::new) });
|
||||
}
|
||||
range.unwrap_or_else(|| SelectionRange { range: positions.whole_document(), parent: None })
|
||||
}
|
||||
|
||||
/// Every byte range this server can name that covers `offset`, from every
|
||||
/// source, unordered and possibly overlapping — [`nested`] sorts it out.
|
||||
fn enclosing(doc: &Document, offset: u32) -> Vec<TextRange> {
|
||||
let mut spans = Vec::new();
|
||||
if let Some(token) = doc.tokens.iter().find(|token| covers(token.span, offset)) {
|
||||
spans.push(token.span);
|
||||
}
|
||||
items(&doc.tree.items, offset, &mut spans);
|
||||
// The scopes the AST does not model — an unclosed `begin` inside an
|
||||
// otherwise fine module, a `case` in a file that only half parsed — still
|
||||
// match over the token stream, and a user expanding a selection there is
|
||||
// exactly the user whose file is mid-edit.
|
||||
for pair in analyze(&doc.tokens).pairs {
|
||||
let span = TextRange::new(pair.open.start, pair.close.end);
|
||||
if covers(span, offset) {
|
||||
spans.push(span);
|
||||
}
|
||||
}
|
||||
spans.push(TextRange::new(0, doc.text.len() as u32));
|
||||
spans
|
||||
}
|
||||
|
||||
/// The subsequence that really nests, smallest first.
|
||||
///
|
||||
/// Two ranges that both cover the cursor need not contain one another — an
|
||||
/// item span and a scope pair can overlap when a parse went wrong — and LSP
|
||||
/// requires every step to contain its child. So the list is walked smallest
|
||||
/// first and a range is kept only when it strictly contains what was kept
|
||||
/// before it; that also drops the duplicates the four sources produce for the
|
||||
/// same construct.
|
||||
fn nested(mut spans: Vec<TextRange>) -> Vec<TextRange> {
|
||||
// A zero-width step selects nothing, which is not a step a user can see.
|
||||
spans.retain(|span| !span.is_empty());
|
||||
spans.sort_by_key(|span| (span.len(), span.start));
|
||||
let mut out: Vec<TextRange> = Vec::new();
|
||||
for span in spans {
|
||||
let keep = match out.last() {
|
||||
Some(inner) => {
|
||||
span.start <= inner.start && span.end >= inner.end && span.len() > inner.len()
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if keep {
|
||||
out.push(span);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a span covers an offset. The end is **included**: a cursor sitting
|
||||
/// just after a word is still on that word, which is where an expand-selection
|
||||
/// keystroke is most often pressed.
|
||||
fn covers(span: TextRange, offset: u32) -> bool {
|
||||
span.start <= offset && offset <= span.end
|
||||
}
|
||||
|
||||
/// The spans of every item that covers `offset`, descending only into the one
|
||||
/// that does — the walk is per-keystroke, and a whole-file walk would visit
|
||||
/// thousands of nodes to report a handful.
|
||||
fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
|
||||
for item in list {
|
||||
if !covers(item.span, offset) {
|
||||
continue;
|
||||
}
|
||||
out.push(item.span);
|
||||
match &item.kind {
|
||||
ItemKind::Module(module) => items(&module.items, offset, out),
|
||||
ItemKind::Class(class) => items(&class.items, offset, out),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
|
||||
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
if covers(case_item.span, offset) {
|
||||
out.push(case_item.span);
|
||||
gen_block(&case_item.body, offset, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
statement(stmt, offset, out)
|
||||
}
|
||||
ItemKind::Function(decl) => statements(&decl.stmts, offset, out),
|
||||
ItemKind::Task(decl) => statements(&decl.stmts, offset, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate `if`, its `else if` ladder and its final `else`.
|
||||
fn gen_if_blocks(gen_if: &GenIf, offset: u32, out: &mut Vec<TextRange>) {
|
||||
gen_block(&gen_if.then, offset, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
gen_block(&nested.then, offset, out);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
gen_block(block, offset, out);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_block(block: &GenBlock, offset: u32, out: &mut Vec<TextRange>) {
|
||||
if !covers(block.span, offset) {
|
||||
return;
|
||||
}
|
||||
out.push(block.span);
|
||||
items(&block.items, offset, out);
|
||||
}
|
||||
|
||||
fn statements(list: &[Stmt], offset: u32, out: &mut Vec<TextRange>) {
|
||||
for stmt in list {
|
||||
statement(stmt, offset, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The spans of `stmt` and of every statement inside it that covers `offset`.
|
||||
///
|
||||
/// The recursion is bounded by the parser's own nesting limit
|
||||
/// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it
|
||||
/// built.
|
||||
fn statement(stmt: &Stmt, offset: u32, out: &mut Vec<TextRange>) {
|
||||
if !covers(stmt.span, offset) {
|
||||
return;
|
||||
}
|
||||
out.push(stmt.span);
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
|
||||
statements(stmts, offset, out)
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
statement(then, offset, out);
|
||||
if let Some(els) = els {
|
||||
statement(els, offset, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for case_item in items {
|
||||
if covers(case_item.span, offset) {
|
||||
out.push(case_item.span);
|
||||
statement(&case_item.stmt, offset, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::Labeled { stmt: inner, .. } => statement(inner, offset, out),
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. } => statement(body, offset, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
statement(inner, offset, out)
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
if let Some(then) = then {
|
||||
statement(then, offset, out);
|
||||
}
|
||||
if let Some(els) = els {
|
||||
statement(els, offset, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::Range;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
fn doc_of(text: &str) -> Document {
|
||||
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
||||
}
|
||||
|
||||
/// The chain for the first occurrence of `needle`, as the source text of
|
||||
/// each step, innermost first.
|
||||
fn steps(text: &str, needle: &str) -> Vec<String> {
|
||||
let doc = doc_of(text);
|
||||
let offset = text.find(needle).expect("the needle is in the text") as u32;
|
||||
let position = doc.positions().position(offset);
|
||||
let chains = selection_ranges(&doc, &[position]);
|
||||
assert_eq!(chains.len(), 1, "one chain per position");
|
||||
let mut out = Vec::new();
|
||||
let mut step = Some(&chains[0]);
|
||||
let positions = doc.positions();
|
||||
while let Some(current) = step {
|
||||
let start = positions.offset(current.range.start) as usize;
|
||||
let end = positions.offset(current.range.end) as usize;
|
||||
out.push(text[start..end].to_string());
|
||||
step = current.parent.as_deref();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every step of a chain, as `(start, end)` byte offsets.
|
||||
fn spans(doc: &Document, offset: u32) -> Vec<(u32, u32)> {
|
||||
let position = doc.positions().position(offset);
|
||||
let chains = selection_ranges(doc, &[position]);
|
||||
let positions = doc.positions();
|
||||
let mut out = Vec::new();
|
||||
let mut step = chains.first();
|
||||
while let Some(current) = step {
|
||||
out.push((positions.offset(current.range.start), positions.offset(current.range.end)));
|
||||
step = current.parent.as_deref();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_chain_runs_from_the_token_out_to_the_whole_file() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let steps = steps(text, "wire");
|
||||
assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}");
|
||||
assert_eq!(steps.last().map(String::as_str), Some(text), "the whole file closes it");
|
||||
assert!(steps.contains(&"wire a;".to_string()), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_expands_through_its_block_and_its_process() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" initial begin\n",
|
||||
" if (a) begin\n",
|
||||
" x = 1;\n",
|
||||
" end\n",
|
||||
" end\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let steps = steps(text, "x = 1");
|
||||
assert_eq!(steps.first().map(String::as_str), Some("x"));
|
||||
assert!(steps.iter().any(|s| s == "x = 1;"), "the statement: {steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("if (a) begin")), "the if: {steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("initial begin")), "the process: {steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("module m;")), "the module: {steps:?}");
|
||||
assert_eq!(steps.last().map(String::as_str), Some(text));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_step_strictly_contains_the_one_before_it() {
|
||||
// The protocol's own requirement, and the thing the four sources of
|
||||
// ranges could most easily break.
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" always_comb begin\n",
|
||||
" case (sel)\n",
|
||||
" 2'd0: y = a;\n",
|
||||
" default: y = b;\n",
|
||||
" endcase\n",
|
||||
" end\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let doc = doc_of(text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let spans = spans(&doc, offset);
|
||||
assert!(!spans.is_empty(), "every position gets a chain, at {offset}");
|
||||
for pair in spans.windows(2) {
|
||||
let (inner, outer) = (pair[0], pair[1]);
|
||||
assert!(
|
||||
outer.0 <= inner.0 && outer.1 >= inner.1 && outer != inner,
|
||||
"at {offset}: {outer:?} must strictly contain {inner:?} — {spans:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
spans.last(),
|
||||
Some(&(0, text.len() as u32)),
|
||||
"the file closes every chain, at {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_case_item_is_a_step_of_its_own() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" always_comb begin\n",
|
||||
" case (sel)\n",
|
||||
" 2'd0: y = a;\n",
|
||||
" endcase\n",
|
||||
" end\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let steps = steps(text, "y = a");
|
||||
assert!(steps.iter().any(|s| s == "2'd0: y = a;"), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("case (sel)")), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_block_is_a_step_of_its_own() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" generate\n",
|
||||
" if (A) begin : g\n",
|
||||
" wire a;\n",
|
||||
" end\n",
|
||||
" endgenerate\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let steps = steps(text, "wire a");
|
||||
assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("begin : g")), "the block: {steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("generate")), "the region: {steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_positions_are_answered_position_for_position() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let doc = doc_of(text);
|
||||
let positions = doc.positions();
|
||||
let at = |needle: &str| positions.position(text.find(needle).expect("needle") as u32);
|
||||
let asked = vec![at("endmodule"), at("wire"), at("module")];
|
||||
let chains = selection_ranges(&doc, &asked);
|
||||
assert_eq!(chains.len(), 3);
|
||||
for (chain, position) in chains.iter().zip(&asked) {
|
||||
assert!(
|
||||
chain.range.start <= *position && *position <= chain.range.end,
|
||||
"each answer is about its own position: {chain:?} vs {position:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_positions_asked_means_no_chains_answered() {
|
||||
let doc = doc_of("module m;\nendmodule\n");
|
||||
assert!(selection_ranges(&doc, &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_file_still_answers_one_degenerate_chain() {
|
||||
let doc = doc_of("");
|
||||
let chains = selection_ranges(&doc, &[Position { line: 0, character: 0 }]);
|
||||
assert_eq!(chains.len(), 1);
|
||||
assert_eq!(chains[0].range.start, chains[0].range.end, "there is nothing to select");
|
||||
assert!(chains[0].parent.is_none(), "and nothing to expand to");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_lex_still_answers_the_file_range() {
|
||||
// `Document::new` leaves `tokens` empty and the tree an error leaf, so
|
||||
// this is the path where every source but the last one gives nothing.
|
||||
let text = "module m;\n wire a; /* unterminated\n";
|
||||
let doc = doc_of(text);
|
||||
assert!(doc.tokens.is_empty(), "the premise");
|
||||
let spans = spans(&doc, 12);
|
||||
assert_eq!(spans.last(), Some(&(0, text.len() as u32)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_scope_still_expands_through_what_did_close() {
|
||||
// The mid-edit shape: the `begin` never closes, so the AST cannot
|
||||
// offer the statement — the module's own pair still can.
|
||||
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
|
||||
let doc = doc_of(text);
|
||||
let offset = text.find("x = 1").expect("needle") as u32;
|
||||
let spans = spans(&doc, offset);
|
||||
assert!(spans.len() >= 2, "at least the token and the file: {spans:?}");
|
||||
assert_eq!(spans.last(), Some(&(0, text.len() as u32)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_past_the_end_of_the_file_clamps_into_it() {
|
||||
let text = "module m;\nendmodule\n";
|
||||
let doc = doc_of(text);
|
||||
let chains = selection_ranges(&doc, &[Position { line: 99, character: 99 }]);
|
||||
assert_eq!(chains.len(), 1);
|
||||
assert_eq!(chains[0].range.end, doc.positions().whole_document().end);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multibyte_line_keeps_the_columns_in_utf16() {
|
||||
// The chain is computed in bytes and answered in UTF-16 units; an
|
||||
// off-by-one here would select the wrong text in the editor only.
|
||||
let text = "module m;\n // é 🎉\n wire a;\nendmodule\n";
|
||||
let steps = steps(text, "wire");
|
||||
assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_drops_a_range_that_does_not_contain_what_came_before() {
|
||||
// The guard for the overlapping-sources case: two ranges that both
|
||||
// cover the cursor but nest in neither direction. The wider-but-not-
|
||||
// enclosing one must be dropped, never emitted as a parent.
|
||||
let spans = vec![
|
||||
TextRange::new(4, 6),
|
||||
TextRange::new(0, 8),
|
||||
TextRange::new(5, 20), // covers 5, contains neither of the above
|
||||
TextRange::new(0, 30),
|
||||
];
|
||||
let kept = nested(spans);
|
||||
assert_eq!(
|
||||
kept.iter().map(|s| (s.start, s.end)).collect::<Vec<_>>(),
|
||||
vec![(4, 6), (0, 8), (0, 30)]
|
||||
);
|
||||
}
|
||||
|
||||
/// The strict-nesting invariant, on the real corpus rather than
|
||||
/// hand-written snippets. `every_step_strictly_contains_the_one_before_it`
|
||||
/// above proves the invariant on files this crate's author wrote to
|
||||
/// exercise it; a corpus file was written by nobody thinking about this
|
||||
/// walk at all, and is exactly what turns up a construct the four
|
||||
/// sources disagree about. Skipped when `corpus/` is not checked out,
|
||||
/// like every other corpus test in this crate.
|
||||
#[test]
|
||||
fn every_step_strictly_nests_over_the_real_corpus() {
|
||||
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let extensions = ["sv", "v", "svh", "vh"];
|
||||
let mut files_checked = 0;
|
||||
let mut positions_checked = 0;
|
||||
for entry in walk(&corpus) {
|
||||
let Some(ext) = entry.extension().and_then(|e| e.to_str()) else { continue };
|
||||
if !extensions.contains(&ext) {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(&entry) else { continue };
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
files_checked += 1;
|
||||
let doc = Document::new(Some(entry.clone()), text.clone(), &WorkspaceIndex::default());
|
||||
let converter = doc.positions();
|
||||
// A handful of evenly spaced offsets per file, not every byte:
|
||||
// the corpus is 800+ files, and the per-offset invariant is
|
||||
// already proven exhaustively on small files above. This is
|
||||
// about *coverage of real syntax*, not exhaustiveness per file.
|
||||
let len = text.len() as u32;
|
||||
let stride = (len / 7).max(1);
|
||||
let mut offset = 0;
|
||||
while offset <= len {
|
||||
positions_checked += 1;
|
||||
let position = converter.position(offset);
|
||||
let chains = selection_ranges(&doc, &[position]);
|
||||
assert_eq!(chains.len(), 1, "{}: offset {offset}", entry.display());
|
||||
let mut step = Some(&chains[0]);
|
||||
let mut previous: Option<Range> = None;
|
||||
while let Some(current) = step {
|
||||
if let Some(inner) = previous {
|
||||
let widens = current.range.start <= inner.start
|
||||
&& current.range.end >= inner.end
|
||||
&& current.range != inner;
|
||||
assert!(
|
||||
widens,
|
||||
"{}: offset {offset}: {:?} does not strictly contain {:?}",
|
||||
entry.display(),
|
||||
current.range,
|
||||
inner
|
||||
);
|
||||
}
|
||||
previous = Some(current.range);
|
||||
step = current.parent.as_deref();
|
||||
}
|
||||
let whole = converter.whole_document();
|
||||
assert_eq!(
|
||||
previous,
|
||||
Some(whole),
|
||||
"{}: offset {offset}: the file must close every chain",
|
||||
entry.display()
|
||||
);
|
||||
offset += stride;
|
||||
}
|
||||
}
|
||||
assert!(files_checked > 100, "the corpus really is checked out: {files_checked} files");
|
||||
eprintln!("selection ranges: {files_checked} files, {positions_checked} positions, no panics, every step strictly nested");
|
||||
}
|
||||
|
||||
/// Every regular file under `dir`, recursively — no filtering by anything
|
||||
/// but extension, which the caller does. Errors reading a directory are
|
||||
/// treated as "nothing here" rather than failing the whole sweep: a
|
||||
/// symlink loop or a permission-denied subtree in a third-party corpus
|
||||
/// checkout should not take the QA test down with it.
|
||||
fn walk(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return out };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
out.extend(walk(&path));
|
||||
} else {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_drops_duplicates_and_empty_ranges() {
|
||||
let spans = vec![
|
||||
TextRange::new(3, 3),
|
||||
TextRange::new(2, 9),
|
||||
TextRange::new(2, 9),
|
||||
TextRange::new(0, 9),
|
||||
];
|
||||
let kept = nested(spans);
|
||||
assert_eq!(kept.iter().map(|s| (s.start, s.end)).collect::<Vec<_>>(), vec![(2, 9), (0, 9)]);
|
||||
}
|
||||
}
|
||||
+4644
-76
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`.
|
||||
//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`
|
||||
//! — or answers when the server pulls them with `workspace/configuration`.
|
||||
//!
|
||||
//! These are the editor's copy of what `lucisv.toml` carries — the same keys, so
|
||||
//! a user with no config file in the tree can still say "indent 4" from their
|
||||
@@ -27,6 +28,12 @@ use serde_json::Value;
|
||||
const LINE_LENGTH_RANGE: RangeInclusive<u64> = 40..=400;
|
||||
const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
|
||||
|
||||
/// The configuration section these settings live in — the key a push nests
|
||||
/// them under, and the `section` a pull asks for. One constant, because the
|
||||
/// two must name the same thing or the pull would answer settings the parser
|
||||
/// then looks for somewhere else.
|
||||
pub const SECTION: &str = "lucisv";
|
||||
|
||||
/// The `lucisv.*` settings in force, after validation. Every field is "no
|
||||
/// opinion" until a client says otherwise, which is exactly what an unset
|
||||
/// VS Code setting means.
|
||||
@@ -46,6 +53,13 @@ pub struct ClientSettings {
|
||||
/// Unset means on, which is what the VS Code default declares — see
|
||||
/// `docs/features/inline-templates/README.md`.
|
||||
pub inline_templates: 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
|
||||
/// own already runs `textDocument/formatting` on save, and a server that
|
||||
/// also formatted would format twice. See
|
||||
/// `docs/features/will-save-wait-until/README.md`.
|
||||
pub format_on_save: bool,
|
||||
}
|
||||
|
||||
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
|
||||
@@ -63,13 +77,49 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// `synchronize.configurationSection: 'lucisv'` produces. A payload without
|
||||
// the section (including the `{"settings": null}` a client sends when it
|
||||
// syncs no section at all) means "no opinion about anything".
|
||||
let Some(lucisv) = settings.get("lucisv") else { return ClientSettings::default() };
|
||||
let Some(lucisv) = settings.get(SECTION) else { return ClientSettings::default() };
|
||||
ClientSettings {
|
||||
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
|
||||
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
|
||||
exclude: strings(lucisv.get("exclude")),
|
||||
filelist: path(lucisv.get("filelist")),
|
||||
inline_templates: flag(lucisv.get("inlineTemplates")),
|
||||
// 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.
|
||||
format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one `workspace/configuration` answer — the *contents* of the `lucisv`
|
||||
/// section, since that is what the server asked for by name.
|
||||
///
|
||||
/// Deliberately the same parser as a push, reached by wrapping the section
|
||||
/// back into the shape a push arrives in. Two entry points, one set of rules:
|
||||
/// a range, a type or a default that drifted between the pull and the push
|
||||
/// paths would be a setting that means one thing in VS Code and another in
|
||||
/// Neovim. `null` — the answer the spec requires when a client cannot provide
|
||||
/// the section — parses as "no opinion about anything", which is exactly the
|
||||
/// defaults.
|
||||
pub fn from_section(section: &Value) -> ClientSettings {
|
||||
from_payload(&Value::Object([(SECTION.to_string(), section.clone())].into_iter().collect()))
|
||||
}
|
||||
|
||||
/// Whether a `didChangeConfiguration` payload carries nothing at all.
|
||||
///
|
||||
/// The 3.17 model: a client that knows the server pulls sends the
|
||||
/// notification as a bare "something changed, ask me for what you need" —
|
||||
/// `{"settings": null}` is what `vscode-languageclient` sends once no legacy
|
||||
/// `synchronize.configurationSection` is configured, and `{}` is the same
|
||||
/// statement written differently. Both are a *trigger*, not a settings
|
||||
/// payload, so the server pulls rather than resetting everything to its
|
||||
/// default. A payload with any key in it is a real push and is applied as it
|
||||
/// always was, whether or not our section is among those keys.
|
||||
pub fn says_nothing(settings: &Value) -> bool {
|
||||
match settings {
|
||||
Value::Null => true,
|
||||
Value::Object(map) => map.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +182,8 @@ mod tests {
|
||||
"indent": indent,
|
||||
"exclude": exclude,
|
||||
"filelist": "",
|
||||
"inlineTemplates": true
|
||||
"inlineTemplates": true,
|
||||
"formatOnSave": false
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -189,6 +240,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_save_is_off_until_a_client_asks_for_it() {
|
||||
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
|
||||
assert!(!settings(json!({ "lucisv": { "formatOnSave": false } })).format_on_save);
|
||||
// Absence is off: the hook runs on every save of every buffer, and a
|
||||
// server that formatted uninvited would fight the editor's own
|
||||
// format-on-save.
|
||||
assert!(!settings(json!({ "lucisv": {} })).format_on_save, "and so is its absence");
|
||||
for bad in [json!("true"), json!(1), json!(null), json!([true]), json!({ "on": true })] {
|
||||
let found = settings(json!({ "lucisv": { "formatOnSave": bad } }));
|
||||
assert!(!found.format_on_save, "formatOnSave {bad} must be ignored");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_populated_payload_is_read_whole() {
|
||||
let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"])));
|
||||
@@ -253,6 +318,72 @@ mod tests {
|
||||
assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one() {
|
||||
// The whole point of `from_section`: the pull answers the section's
|
||||
// contents, the push nests them one level deeper, and every rule
|
||||
// about ranges, types and defaults must be the one set of rules.
|
||||
let section = json!({
|
||||
"lineLength": 120, "indent": 4, "exclude": ["vendor"],
|
||||
"filelist": "rtl/files.f", "inlineTemplates": false, "formatOnSave": true
|
||||
});
|
||||
assert_eq!(from_section(§ion), settings(json!({ "lucisv": section })));
|
||||
// ...including the rejections.
|
||||
let junk = json!({ "indent": "4", "lineLength": 4000, "exclude": "vendor" });
|
||||
assert_eq!(from_section(&junk), settings(json!({ "lucisv": junk })));
|
||||
assert_eq!(from_section(&junk), ClientSettings::default(), "and they are rejections");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_pull_answer_is_the_defaults_rather_than_an_error() {
|
||||
// A client that cannot provide the section must answer `null`, per
|
||||
// spec — and one that answers something absurd instead must cost the
|
||||
// user no more than one that answered nothing.
|
||||
for answer in [
|
||||
json!(null),
|
||||
json!({}),
|
||||
json!("lucisv"),
|
||||
json!(7),
|
||||
json!([1, 2]),
|
||||
json!({ "lucisv": { "indent": 4 } }),
|
||||
] {
|
||||
assert_eq!(
|
||||
from_section(&answer),
|
||||
ClientSettings::default(),
|
||||
"the answer {answer} must resolve to the defaults"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_push_is_a_pull_signal_and_a_populated_one_is_not() {
|
||||
// `{"settings": null}` is what a modern `vscode-languageclient`
|
||||
// sends: "something changed, ask me". Applying it as a payload would
|
||||
// silently reset every setting the user had pulled.
|
||||
assert!(says_nothing(&json!(null)));
|
||||
assert!(says_nothing(&json!({})));
|
||||
assert!(!says_nothing(&json!({ "lucisv": { "indent": 4 } })));
|
||||
// A legacy push that syncs some *other* server's section is still a
|
||||
// push: it carries a payload, and this server's answer to it — no
|
||||
// opinion about anything — is what it has always been.
|
||||
assert!(!says_nothing(&json!({ "someOtherServer": { "indent": 4 } })));
|
||||
// Neither an array nor a scalar is the client saying "ask me"; both
|
||||
// are junk, and junk goes down the push path where `from_payload`
|
||||
// drops it.
|
||||
assert!(!says_nothing(&json!([])));
|
||||
assert!(!says_nothing(&json!("")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_section_constant_is_the_key_the_parser_reads() {
|
||||
// The pull asks for `SECTION` by name and the push nests under it. A
|
||||
// constant that drifted from the parser would make every pulled
|
||||
// setting silently invisible.
|
||||
let found = from_payload(&json!({ SECTION: { "indent": 4 } }));
|
||||
assert_eq!(found.indent, Some(4));
|
||||
assert_eq!(SECTION, "lucisv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_accepted_ranges_are_the_ones_lucisv_toml_accepts() {
|
||||
// The bounds above are copied from `lucisv_core::config`, which exports
|
||||
|
||||
@@ -125,6 +125,27 @@ impl Workspace {
|
||||
self.rebuild_index()
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
pub fn index(&self) -> &WorkspaceIndex {
|
||||
&self.index
|
||||
}
|
||||
@@ -374,6 +395,7 @@ impl Workspace {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::slice::from_ref;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn uri(s: &str) -> Uri {
|
||||
@@ -474,6 +496,200 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[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_roots(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_roots(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"
|
||||
);
|
||||
}
|
||||
|
||||
#[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_roots(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();
|
||||
ws.open_roots(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"
|
||||
);
|
||||
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();
|
||||
ws.open_roots(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"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scan_skips_what_a_gitignore_skips() {
|
||||
let tree = Tree::new("gitignore");
|
||||
@@ -572,6 +788,16 @@ mod tests {
|
||||
}),
|
||||
"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"
|
||||
);
|
||||
assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does");
|
||||
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");
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
//! Applying a `didChange`'s edits to a buffer.
|
||||
//!
|
||||
//! With `TextDocumentSyncKind::INCREMENTAL` the client stops sending the whole
|
||||
//! file on every keystroke and sends the ranges it touched instead. The server
|
||||
//! is then the only holder of the buffer's text, so this module is the one
|
||||
//! place a wrong offset silently rewrites what the user is looking at — hence
|
||||
//! a pure function, a second implementation to cross-check it against, and no
|
||||
//! slicing that can panic. The exact clamping rules are in
|
||||
//! `docs/features/incremental-sync/README.md`.
|
||||
|
||||
use lsp_types::TextDocumentContentChangeEvent;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::convert::Positions;
|
||||
|
||||
/// Apply one `didChange`'s content changes to a buffer, in the order the
|
||||
/// client sent them, and return the buffer that results.
|
||||
///
|
||||
/// A change with no range replaces the whole document — what a full-sync
|
||||
/// client sends, and what still works if one arrives mid-batch.
|
||||
pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
|
||||
let mut text = text.to_string();
|
||||
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);
|
||||
continue;
|
||||
};
|
||||
// A fresh line table per change: each range is positioned against the
|
||||
// document as the *previous* changes in this batch left it. That is
|
||||
// O(changes × file) per notification, which at Verilog file sizes is
|
||||
// microseconds and buys a function with no incremental state to get
|
||||
// out of step.
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
let start = positions.offset(range.start) as usize;
|
||||
// A range that runs backwards is a client desync. Reading it as an
|
||||
// insertion at `start` is the one interpretation that deletes nothing:
|
||||
// we have no resync mechanism, so the safe direction is to keep text.
|
||||
let end = (positions.offset(range.end) as usize).max(start);
|
||||
let (Some(before), Some(after)) = (text.get(..start), text.get(end..)) else {
|
||||
// Unreachable: `Positions::offset` only ever returns character
|
||||
// boundaries. Written as a skip rather than a slice because the
|
||||
// slice would panic, and a panic here takes the buffer with it.
|
||||
continue;
|
||||
};
|
||||
text = format!("{before}{}{after}", change.text);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::{Position, Range};
|
||||
|
||||
fn pos(line: u32, character: u32) -> Position {
|
||||
Position { line, character }
|
||||
}
|
||||
|
||||
/// A ranged change, the way a client sends one.
|
||||
fn edit(
|
||||
start: (u32, u32),
|
||||
end: (u32, u32),
|
||||
text: &str,
|
||||
) -> lsp_types::TextDocumentContentChangeEvent {
|
||||
TextDocumentContentChangeEvent {
|
||||
range: Some(Range { start: pos(start.0, start.1), end: pos(end.0, end.1) }),
|
||||
range_length: None,
|
||||
text: text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A rangeless change: the whole buffer, as a full-sync client sends it.
|
||||
fn whole(text: &str) -> TextDocumentContentChangeEvent {
|
||||
TextDocumentContentChangeEvent { range: None, range_length: None, text: text.to_string() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insert_lands_where_the_range_is_empty() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 8), (1, 8), "b")]);
|
||||
assert_eq!(after, "module m;\n wire ab;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_removes_exactly_the_range() {
|
||||
let text = "module m;\n wire aaa;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 7), (1, 10), "")]);
|
||||
assert_eq!(after, "module m;\n wire ;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replace_swaps_the_range_for_the_text() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 2), (1, 6), "logic")]);
|
||||
assert_eq!(after, "module m;\n logic a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_range_collapses_the_lines_it_spans() {
|
||||
let text = "a\nb\nc\n";
|
||||
let after = apply_changes(text, &[edit((0, 1), (2, 0), "X")]);
|
||||
assert_eq!(after, "aXc\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_changes_see_what_the_earlier_ones_did() {
|
||||
// The batch a real editor sends for "type `wire w;` on a new line",
|
||||
// split into three: each range is against the state after the last.
|
||||
let text = "module m;\nendmodule\n";
|
||||
let after = apply_changes(
|
||||
text,
|
||||
&[
|
||||
edit((1, 0), (1, 0), "\n"), // open a line
|
||||
edit((1, 0), (1, 0), " wire "), // the keyword
|
||||
edit((1, 7), (1, 7), "w;"), // the name
|
||||
],
|
||||
);
|
||||
assert_eq!(after, "module m;\n wire w;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_range_positioned_against_the_original_text_would_be_wrong() {
|
||||
// The regression this whole module exists to prevent: if the line
|
||||
// table were built once, the second range below would land on the old
|
||||
// line 1 and the result would differ.
|
||||
let text = "aaa\nbbb\n";
|
||||
let after = apply_changes(text, &[edit((0, 0), (0, 0), "x\n"), edit((1, 1), (1, 2), "Z")]);
|
||||
assert_eq!(after, "x\naZa\nbbb\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_byte_character_is_one_utf16_unit_to_the_edit_too() {
|
||||
let text = "// é ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 5), (0, 7), "no")]);
|
||||
assert_eq!(after, "// é no\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_astral_character_takes_two_units_and_is_never_split() {
|
||||
// `🎉` is 2 UTF-16 units. A boundary on its low half rounds forward
|
||||
// past the whole character, so no edit can ever cut it in half.
|
||||
let text = "// 🎉 ok\n";
|
||||
assert_eq!(apply_changes(text, &[edit((0, 3), (0, 5), "X")]), "// X ok\n");
|
||||
// Start inside the pair: the emoji survives, the edit begins after it.
|
||||
assert_eq!(apply_changes(text, &[edit((0, 4), (0, 6), "X")]), "// 🎉Xok\n");
|
||||
// End inside the pair: rounds forward, so the emoji goes with it.
|
||||
assert_eq!(apply_changes(text, &[edit((0, 3), (0, 4), "X")]), "// X ok\n");
|
||||
for change in [edit((0, 4), (0, 4), "!"), edit((0, 4), (0, 5), "!")] {
|
||||
let out = apply_changes(text, &[change]);
|
||||
assert!(out.is_char_boundary(out.len()), "still valid UTF-8: {out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_after_an_emoji_counts_from_the_right_column() {
|
||||
let text = "// 🎉 wire a;\n";
|
||||
// "wire" starts at UTF-16 unit 6: `/`,`/`,` `,🎉(2),` `.
|
||||
let after = apply_changes(text, &[edit((0, 6), (0, 10), "logic")]);
|
||||
assert_eq!(after, "// 🎉 logic a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_ends_survive_an_edit_on_the_line() {
|
||||
let text = "module m;\r\n wire a;\r\nendmodule\r\n";
|
||||
let after = apply_changes(text, &[edit((1, 7), (1, 8), "bb")]);
|
||||
assert_eq!(after, "module m;\r\n wire bb;\r\nendmodule\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_line_can_be_joined_to_the_next() {
|
||||
let text = "ab\r\ncd\r\n";
|
||||
let after = apply_changes(text, &[edit((0, 2), (1, 0), "")]);
|
||||
assert_eq!(after, "abcd\r\n", "the whole `\\r\\n` goes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_at_the_start_of_the_document() {
|
||||
assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 0), "// ")]), "// wire a;\n");
|
||||
assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 4), "logic")]), "logic a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_at_end_of_file() {
|
||||
// The empty last line a trailing newline opens.
|
||||
assert_eq!(apply_changes("a\n", &[edit((1, 0), (1, 0), "b\n")]), "a\nb\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insert_at_the_end_of_a_last_line_with_no_trailing_newline() {
|
||||
assert_eq!(apply_changes("endmodule", &[edit((0, 9), (0, 9), "\n")]), "endmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_into_an_empty_document() {
|
||||
assert_eq!(apply_changes("", &[edit((0, 0), (0, 0), "module m;")]), "module m;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rangeless_change_replaces_the_whole_document() {
|
||||
assert_eq!(apply_changes("old\n", &[whole("new\n")]), "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_of_several_rangeless_changes_wins() {
|
||||
// What the full-sync handler did before this feature, unchanged.
|
||||
assert_eq!(apply_changes("old\n", &[whole("a\n"), whole("b\n"), whole("c\n")]), "c\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rangeless_change_resets_what_the_next_range_is_against() {
|
||||
let after = apply_changes("anything\n", &[whole("abc\ndef\n"), edit((1, 1), (1, 2), "X")]);
|
||||
assert_eq!(after, "abc\ndXf\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_changes_is_the_buffer_unchanged() {
|
||||
assert_eq!(apply_changes("wire a;\n", &[]), "wire a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_past_the_end_clamps_to_the_end_of_the_document() {
|
||||
let text = "a\nb\n";
|
||||
assert_eq!(apply_changes(text, &[edit((99, 0), (99, 5), "X")]), "a\nb\nX");
|
||||
// And a range that *starts* in the document and ends past it.
|
||||
assert_eq!(apply_changes(text, &[edit((1, 0), (99, 0), "X")]), "a\nX");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_past_the_end_of_a_line_clamps_to_its_content() {
|
||||
assert_eq!(apply_changes("ab\ncd\n", &[edit((0, 99), (0, 99), "!")]), "ab!\ncd\n");
|
||||
assert_eq!(apply_changes("ab\r\ncd\r\n", &[edit((0, 99), (0, 99), "!")]), "ab!\r\ncd\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_that_runs_backwards_deletes_nothing() {
|
||||
// Clamping `end` up to `start` turns a desynced range into a pure
|
||||
// insertion — the only reading that cannot lose the user's text.
|
||||
assert_eq!(apply_changes("abcdef\n", &[edit((0, 4), (0, 1), "X")]), "abcdXef\n");
|
||||
assert_eq!(apply_changes("ab\ncd\n", &[edit((1, 1), (0, 0), "X")]), "ab\ncXd\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// randomized cross-check against a second implementation
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A fixed-seed linear congruential generator — deterministic randomness
|
||||
/// with no dependency. The constants are Knuth's MMIX.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
self.0 >> 33
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// The same rules, implemented a second way: a flat `Vec<char>` with the
|
||||
/// line starts scanned out of it, rather than byte offsets off a
|
||||
/// `LineIndex`. Sharing no code with `apply_changes` is the point.
|
||||
fn reference_apply(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
|
||||
let mut text = text.to_string();
|
||||
for change in changes {
|
||||
let Some(range) = change.range else {
|
||||
text.clone_from(&change.text);
|
||||
continue;
|
||||
};
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let start = reference_index(&chars, range.start);
|
||||
let end = reference_index(&chars, range.end).max(start);
|
||||
let mut out: String = chars[..start].iter().collect();
|
||||
out.push_str(&change.text);
|
||||
out.extend(chars[end..].iter());
|
||||
text = out;
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The index into `chars` that a position names: lines are `\n`-
|
||||
/// terminated, one `\r` before that terminator is not content, a
|
||||
/// character past a line's content clamps to it, a line past the last
|
||||
/// clamps to the end of the text, and a character landing inside a
|
||||
/// surrogate pair rounds forward past the whole character.
|
||||
fn reference_index(chars: &[char], position: Position) -> usize {
|
||||
let mut starts = vec![0usize];
|
||||
for (i, c) in chars.iter().enumerate() {
|
||||
if *c == '\n' {
|
||||
starts.push(i + 1);
|
||||
}
|
||||
}
|
||||
let Some(&start) = starts.get(position.line as usize) else {
|
||||
return chars.len();
|
||||
};
|
||||
// The line's content ends before its `\n`, and before one `\r`.
|
||||
let mut end = match starts.get(position.line as usize + 1) {
|
||||
Some(&next) => next - 1,
|
||||
None => chars.len(),
|
||||
};
|
||||
if end > start && chars[end - 1] == '\r' {
|
||||
end -= 1;
|
||||
}
|
||||
let mut units = 0u32;
|
||||
let mut at = start;
|
||||
while at < end && units < position.character {
|
||||
units += chars[at].len_utf16() as u32;
|
||||
at += 1;
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// A random document over an alphabet that mixes every width and both
|
||||
/// line endings — including a bare `\r`, which is an ordinary character.
|
||||
fn random_text(rng: &mut Lcg) -> String {
|
||||
const ALPHABET: [&str; 8] = ["a", "b", " ", ";", "\n", "\r\n", "é", "🎉"];
|
||||
let len = rng.below(24);
|
||||
(0..len).map(|_| ALPHABET[rng.below(8) as usize]).collect()
|
||||
}
|
||||
|
||||
/// A random change: mostly ranged, occasionally a whole-document reset,
|
||||
/// with positions that are often — but deliberately not always — inside
|
||||
/// the document.
|
||||
fn random_change(rng: &mut Lcg, text: &str) -> TextDocumentContentChangeEvent {
|
||||
if rng.below(10) == 0 {
|
||||
return whole(&random_text(rng));
|
||||
}
|
||||
let lines = text.matches('\n').count() as u32 + 1;
|
||||
let position = |rng: &mut Lcg| Position {
|
||||
line: rng.below(u64::from(lines) + 2) as u32,
|
||||
character: rng.below(12) as u32,
|
||||
};
|
||||
let (first, second) = (position(rng), position(rng));
|
||||
TextDocumentContentChangeEvent {
|
||||
range: Some(Range { start: first, end: second }),
|
||||
range_length: None,
|
||||
text: random_text(rng),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_edit_sequences_agree_with_the_reference_model() {
|
||||
let mut rng = Lcg(0x5EED_1CE5);
|
||||
let mut ranged = 0usize;
|
||||
for case in 0..400 {
|
||||
let text = random_text(&mut rng);
|
||||
let mut changes = Vec::new();
|
||||
let mut running = text.clone();
|
||||
for _ in 0..rng.below(5) + 1 {
|
||||
let change = random_change(&mut rng, &running);
|
||||
ranged += usize::from(change.range.is_some());
|
||||
// The next range is against the state this one leaves.
|
||||
running = apply_changes(&running, std::slice::from_ref(&change));
|
||||
changes.push(change);
|
||||
}
|
||||
let ours = apply_changes(&text, &changes);
|
||||
assert_eq!(ours, reference_apply(&text, &changes), "case {case}, from {text:?}");
|
||||
assert_eq!(ours, running, "case {case}: one batch equals the changes one at a time");
|
||||
}
|
||||
assert!(ranged > 500, "the cases must be mostly ranged edits, got {ranged}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA additions (2026-08-26) — see docs/features/incremental-sync/README.md
|
||||
// QA log for the full writeup of each of these.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_deletion_starting_at_the_low_surrogate_index_preserves_the_character() {
|
||||
// Character 4 is the low half of `🎉`'s pair (the emoji starts at 3,
|
||||
// ends at 5). A *start* boundary landing there rounds forward past
|
||||
// the whole character, so the emoji is excluded from — and survives
|
||||
// — a deletion that begins mid-pair.
|
||||
let text = "// 🎉 ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 4), (0, 6), "")]);
|
||||
assert_eq!(after, "// 🎉ok\n", "the emoji stays, only the trailing space is deleted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character() {
|
||||
// Symmetric case: an *end* boundary on the low half also rounds
|
||||
// forward, but here that means the deletion is widened to swallow
|
||||
// the whole character rather than stopping short of it.
|
||||
let text = "// 🎉 ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 3), (0, 4), "")]);
|
||||
assert_eq!(after, "// ok\n", "the whole emoji is gone, both flanking spaces remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_split_across_two_changes_in_one_batch_reorders_the_bytes() {
|
||||
// QA finding (docs/features/incremental-sync/README.md QA log,
|
||||
// 2026-08-26): pinning present, *surprising* behavior rather than
|
||||
// asserting it is correct. `convert.rs::line_content_end` treats a
|
||||
// trailing bare `\r` as "not content" whether or not a `\n` will
|
||||
// follow it, so a second change in the same batch that targets "end
|
||||
// of line" after a first change appended a lone `\r` lands *before*
|
||||
// that `\r`, not after it. A client that split one `\r\n` insertion
|
||||
// into two ranged changes this way would get `\n\r`, not `\r\n`. No
|
||||
// real editor's diff algorithm is known to do this, and no panic or
|
||||
// data loss occurs — but if this test's expected string ever needs
|
||||
// to change to `"ab\r\n"`, that is a deliberate fix to
|
||||
// `Positions::offset`/`line_content_end`, not an accidental one.
|
||||
let text = "ab";
|
||||
let after = apply_changes(text, &[edit((0, 2), (0, 2), "\r"), edit((0, 2), (0, 2), "\n")]);
|
||||
assert_eq!(after, "ab\n\r", "known edge case: see the comment above");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_covering_the_final_newline_removes_exactly_it() {
|
||||
let text = "a\nb\n";
|
||||
let after = apply_changes(text, &[edit((1, 1), (2, 0), "")]);
|
||||
assert_eq!(after, "a\nb", "the trailing newline is gone, nothing else is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_width_inserts_at_the_same_position_compose_in_batch_order() {
|
||||
// Not a bug: per protocol, each change is positioned against what the
|
||||
// previous ones in the batch left, so two inserts naming the same
|
||||
// literal position land with the *second* one first — a client that
|
||||
// wants "12" must advance the second insert's position past the
|
||||
// first's text, exactly as it would need to for a non-zero-width
|
||||
// range. Pinned so a future refactor cannot silently change the
|
||||
// batch's ordering semantics.
|
||||
let text = "x";
|
||||
let after = apply_changes(text, &[edit((0, 0), (0, 0), "1"), edit((0, 0), (0, 0), "2")]);
|
||||
assert_eq!(after, "21x");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
//! `textDocument/semanticTokens/full`.
|
||||
//! `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`.
|
||||
//! `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 lsp_types::{SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens};
|
||||
use lsp_types::{
|
||||
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind};
|
||||
@@ -68,12 +76,53 @@ struct Piece {
|
||||
modifiers: u32,
|
||||
}
|
||||
|
||||
/// One classified token in the protocol's own coordinates: a zero-based line,
|
||||
/// a UTF-16 start column and a UTF-16 length. This is the form the range
|
||||
/// filter works in, and the only input `encode` has.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct Absolute {
|
||||
line: u32,
|
||||
start: u32,
|
||||
length: u32,
|
||||
ty: u32,
|
||||
modifiers: u32,
|
||||
}
|
||||
|
||||
impl Absolute {
|
||||
/// Where this token starts, as the protocol names it.
|
||||
fn from(&self) -> Position {
|
||||
Position { line: self.line, character: self.start }
|
||||
}
|
||||
|
||||
/// Where it ends. A token never spans a line break (see `split_lines`), so
|
||||
/// this is on the same line.
|
||||
fn to(&self) -> Position {
|
||||
Position { line: self.line, character: self.start + self.length }
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify and encode the whole buffer.
|
||||
///
|
||||
/// A buffer that does not lex has no tokens, so this is empty — the user sees
|
||||
/// the editor's own grammar highlighting plus the parse diagnostic, which is
|
||||
/// the honest answer while the file is unlexable.
|
||||
pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
|
||||
pub fn semantic_tokens(doc: &Document) -> Vec<SemanticToken> {
|
||||
encode(&absolute(doc))
|
||||
}
|
||||
|
||||
/// The tokens a range covers, encoded as a self-contained answer.
|
||||
///
|
||||
/// The protocol asks for a whole `SemanticTokens` here, not a slice of the
|
||||
/// full one: the relative encoding restarts from the start of the document
|
||||
/// exactly as a full answer's does, and only the tokens outside the range are
|
||||
/// missing. A token that merely overlaps the range is kept whole — the client
|
||||
/// asked which tokens to draw, not where to cut them.
|
||||
pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
encode(&within(absolute(doc), range))
|
||||
}
|
||||
|
||||
/// Classify the whole buffer, split at line boundaries, in wire order.
|
||||
fn absolute(doc: &Document) -> Vec<Absolute> {
|
||||
let mut pieces = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
collect_trivia(token, &mut pieces);
|
||||
@@ -85,7 +134,21 @@ pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
|
||||
});
|
||||
}
|
||||
}
|
||||
encode(pieces, doc)
|
||||
flatten(pieces, doc)
|
||||
}
|
||||
|
||||
/// The tokens overlapping `range`, in the order they came in.
|
||||
///
|
||||
/// Overlap, not containment: a client sends the lines it is showing, and a
|
||||
/// token straddling the first of them is one the user can see. An **empty**
|
||||
/// range covers no characters, so it overlaps nothing — the containment test
|
||||
/// below would otherwise answer with every token the collapsed point sits
|
||||
/// inside.
|
||||
fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
|
||||
if range.start >= range.end {
|
||||
return Vec::new();
|
||||
}
|
||||
tokens.into_iter().filter(|t| t.from() < range.end && range.start < t.to()).collect()
|
||||
}
|
||||
|
||||
/// Comments live as trivia on the token that follows (or, for a trailing
|
||||
@@ -162,14 +225,15 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
}
|
||||
}
|
||||
|
||||
/// Split every piece at line boundaries, sort, and delta-encode.
|
||||
/// Split every piece at line boundaries, measure it in UTF-16 units, and
|
||||
/// sort.
|
||||
///
|
||||
/// The spec forbids a token from spanning a line break, and Verilog has three
|
||||
/// shapes that would: a block comment, a continued `` `define`` and a
|
||||
/// multi-line macro invocation.
|
||||
fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
|
||||
fn flatten(pieces: Vec<Piece>, doc: &Document) -> Vec<Absolute> {
|
||||
let positions = doc.positions();
|
||||
let mut flat: Vec<(u32, u32, u32, u32, u32)> = Vec::new();
|
||||
let mut flat: Vec<Absolute> = Vec::new();
|
||||
for piece in pieces {
|
||||
for line_span in split_lines(&doc.text, piece.span) {
|
||||
let start = positions.position(line_span.start);
|
||||
@@ -177,33 +241,78 @@ fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
|
||||
if end.character <= start.character {
|
||||
continue;
|
||||
}
|
||||
flat.push((
|
||||
start.line,
|
||||
start.character,
|
||||
end.character - start.character,
|
||||
piece.ty as u32,
|
||||
piece.modifiers,
|
||||
));
|
||||
flat.push(Absolute {
|
||||
line: start.line,
|
||||
start: start.character,
|
||||
length: end.character - start.character,
|
||||
ty: piece.ty as u32,
|
||||
modifiers: piece.modifiers,
|
||||
});
|
||||
}
|
||||
}
|
||||
flat.sort_by_key(|&(line, start, ..)| (line, start));
|
||||
flat.sort_by_key(|t| (t.line, t.start));
|
||||
flat
|
||||
}
|
||||
|
||||
let mut data = Vec::with_capacity(flat.len());
|
||||
/// Delta-encode, from the start of the document.
|
||||
///
|
||||
/// Pure: the same tokens always encode the same way, whether they are the
|
||||
/// whole file's or the handful a range kept.
|
||||
fn encode(tokens: &[Absolute]) -> Vec<SemanticToken> {
|
||||
let mut data = Vec::with_capacity(tokens.len());
|
||||
let (mut prev_line, mut prev_start) = (0u32, 0u32);
|
||||
for (line, start, length, ty, modifiers) in flat {
|
||||
let delta_line = line - prev_line;
|
||||
let delta_start = if delta_line == 0 { start - prev_start } else { start };
|
||||
for token in tokens {
|
||||
let delta_line = token.line - prev_line;
|
||||
let delta_start = if delta_line == 0 { token.start - prev_start } else { token.start };
|
||||
data.push(SemanticToken {
|
||||
delta_line,
|
||||
delta_start,
|
||||
length,
|
||||
token_type: ty,
|
||||
token_modifiers_bitset: modifiers,
|
||||
length: token.length,
|
||||
token_type: token.ty,
|
||||
token_modifiers_bitset: token.modifiers,
|
||||
});
|
||||
prev_line = line;
|
||||
prev_start = start;
|
||||
prev_line = token.line;
|
||||
prev_start = token.start;
|
||||
}
|
||||
SemanticTokens { result_id: None, data }
|
||||
data
|
||||
}
|
||||
|
||||
/// How many numbers one token is on the wire. An edit's `start` and
|
||||
/// `deleteCount` index that flat array, not the token list.
|
||||
const FIELDS: u32 = 5;
|
||||
|
||||
/// The edits that turn `old` into `new`: one replacement of everything
|
||||
/// between the common prefix and the common suffix, or none at all when the
|
||||
/// two are identical.
|
||||
///
|
||||
/// **Minimality beyond the prefix/suffix trim is deliberately not attempted.**
|
||||
/// A real diff would find the two edits an insertion in the middle of a file
|
||||
/// really is, but every token after an edit carries a changed `deltaLine`
|
||||
/// anyway, so the interesting cases — typing at the end of a line, or on a
|
||||
/// line — trim to almost nothing regardless. rust-analyzer answers the same
|
||||
/// way, and the invariant that matters is that applying the result
|
||||
/// reproduces `new` exactly.
|
||||
pub fn delta(old: &[SemanticToken], new: &[SemanticToken]) -> Vec<SemanticTokensEdit> {
|
||||
let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
|
||||
// The suffix is counted over what the prefix left, never over the whole
|
||||
// vectors: two token lists that repeat themselves — which identical lines
|
||||
// of Verilog produce exactly — would otherwise claim the same tokens as
|
||||
// both prefix and suffix, and the edit would delete a region it also
|
||||
// re-inserts (or, with the subtraction underflowing, not be computable at
|
||||
// all). This overlap is the classic bug in this algorithm.
|
||||
let (old_rest, new_rest) = (&old[prefix..], &new[prefix..]);
|
||||
let suffix =
|
||||
old_rest.iter().rev().zip(new_rest.iter().rev()).take_while(|(a, b)| a == b).count();
|
||||
let deleted = old_rest.len() - suffix;
|
||||
let inserted = &new_rest[..new_rest.len() - suffix];
|
||||
if deleted == 0 && inserted.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![SemanticTokensEdit {
|
||||
start: prefix as u32 * FIELDS,
|
||||
delete_count: deleted as u32 * FIELDS,
|
||||
data: Some(inserted.to_vec()),
|
||||
}]
|
||||
}
|
||||
|
||||
/// One span per line the span touches, each stopping before the `\n`.
|
||||
@@ -231,17 +340,30 @@ mod tests {
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
/// Decode the delta encoding back to absolute (line, start, len, type).
|
||||
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
/// Analyze `text` as an open buffer and hand the document to `f`.
|
||||
fn with_document<T>(text: &str, f: impl FnOnce(&Document) -> T) -> T {
|
||||
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 tokens = semantic_tokens(ws.document(&uri).expect("open"));
|
||||
f(ws.document(&uri).expect("open"))
|
||||
}
|
||||
|
||||
/// The whole buffer's tokens, as they go on the wire.
|
||||
fn tokens_of(text: &str) -> Vec<SemanticToken> {
|
||||
with_document(text, semantic_tokens)
|
||||
}
|
||||
|
||||
/// The tokens a range answer carries.
|
||||
fn ranged(text: &str, range: Range) -> Vec<SemanticToken> {
|
||||
with_document(text, |doc| semantic_tokens_in_range(doc, range))
|
||||
}
|
||||
|
||||
/// Decode the delta encoding back to absolute (line, start, len, type).
|
||||
fn decode(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
let (mut line, mut start) = (0u32, 0u32);
|
||||
tokens
|
||||
.data
|
||||
.iter()
|
||||
data.iter()
|
||||
.map(|t| {
|
||||
line += t.delta_line;
|
||||
start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start };
|
||||
@@ -250,6 +372,18 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
decode(&tokens_of(text))
|
||||
}
|
||||
|
||||
/// A range, spelled the way a test reads best.
|
||||
fn range(from: (u32, u32), to: (u32, u32)) -> Range {
|
||||
Range {
|
||||
start: Position { line: from.0, character: from.1 },
|
||||
end: Position { line: to.0, character: to.1 },
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keywords_numbers_and_strings_are_classified() {
|
||||
let out = decoded("module m;\n localparam W = 8;\n wire a = \"s\";\nendmodule\n");
|
||||
@@ -358,4 +492,487 @@ mod tests {
|
||||
vec![TextRange::new(0, 1), TextRange::new(2, 3)]
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `semanticTokens/range`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Four lines, every one of them carrying tokens.
|
||||
const FOUR_LINES: &str =
|
||||
"module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n// tail\n";
|
||||
|
||||
#[test]
|
||||
fn a_range_covering_everything_is_the_full_answer() {
|
||||
let full = tokens_of(FOUR_LINES);
|
||||
assert_eq!(ranged(FOUR_LINES, range((0, 0), (99, 0))), full);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_answer_re_encodes_from_the_start_of_the_document() {
|
||||
// The whole point of the re-encoding: a range answer is a
|
||||
// self-contained `SemanticTokens`, so its first token's deltas are
|
||||
// absolute — a client that pasted the slice out of the full answer
|
||||
// would draw line 2's tokens on line 0.
|
||||
let data = ranged(FOUR_LINES, range((2, 0), (3, 0)));
|
||||
let first = data.first().expect("line 2 has tokens");
|
||||
assert_eq!(first.delta_line, 2, "absolute from the document start");
|
||||
assert_eq!(first.delta_start, 2, "the `wire` keyword's own column");
|
||||
assert_eq!(
|
||||
decode(&data),
|
||||
decoded(FOUR_LINES).into_iter().filter(|&(line, ..)| line == 2).collect::<Vec<_>>(),
|
||||
"the same tokens the full answer puts on that line"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_range_covers_no_characters_and_so_no_tokens() {
|
||||
// Collapsed on a token, which is the tempting case to get wrong: a
|
||||
// zero-width range draws nothing, so it must answer nothing.
|
||||
assert!(ranged(FOUR_LINES, range((0, 3), (0, 3))).is_empty());
|
||||
assert!(ranged(FOUR_LINES, range((0, 0), (0, 0))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_that_starts_mid_token_keeps_that_token_whole() {
|
||||
// The client asked which tokens to draw, not where to cut them —
|
||||
// and a length trimmed to the range would be a lie about the source.
|
||||
let data = ranged("module m;\nendmodule\n", range((0, 3), (0, 4)));
|
||||
assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_touching_no_token_is_empty() {
|
||||
// Wholly inside the whitespace of a line, and wholly past the file.
|
||||
assert!(ranged("module m;\n\n\nendmodule\n", range((1, 0), (2, 0))).is_empty());
|
||||
assert!(ranged(FOUR_LINES, range((90, 0), (99, 0))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_answer_never_carries_a_token_from_outside_it() {
|
||||
let inside = decode(&ranged(FOUR_LINES, range((1, 0), (2, 0))));
|
||||
assert!(!inside.is_empty(), "premise: line 1 has tokens");
|
||||
assert!(inside.iter().all(|&(line, ..)| line == 1), "{inside:?}");
|
||||
}
|
||||
|
||||
/// The range/full agreement, on files nobody wrote to exercise it: for a
|
||||
/// window of whole lines, the range answer must decode to exactly the
|
||||
/// tokens the full answer puts on those lines. Stated line-wise rather
|
||||
/// than with the handler's own overlap test, so the two are independent.
|
||||
/// Skipped when `corpus/` is not checked out, like every other corpus
|
||||
/// test in this crate.
|
||||
#[test]
|
||||
fn a_line_window_answers_exactly_the_full_answers_tokens_on_those_lines() {
|
||||
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let files =
|
||||
[corpus.join("picorv32/picorv32.v"), corpus.join("common_cells/src/fifo_v3.sv")];
|
||||
let mut windows_checked = 0;
|
||||
for path in files {
|
||||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||||
eprintln!("{} not checked out — skipping", path.display());
|
||||
continue;
|
||||
};
|
||||
let doc = Document::new(Some(path.clone()), text, &WorkspaceIndex::default());
|
||||
let full = decode(&semantic_tokens(&doc));
|
||||
assert!(!full.is_empty(), "{}: the premise, a file with tokens", path.display());
|
||||
let last = full.iter().map(|&(line, ..)| line).max().unwrap_or(0);
|
||||
// Forty-line windows, the size an editor's viewport request is.
|
||||
let mut from = 0;
|
||||
while from <= last {
|
||||
let to = from + 40;
|
||||
let window = decode(&semantic_tokens_in_range(&doc, range((from, 0), (to, 0))));
|
||||
let expected: Vec<_> =
|
||||
full.iter().filter(|&&(line, ..)| line >= from && line < to).copied().collect();
|
||||
assert_eq!(window, expected, "{}: lines {from}..{to}", path.display());
|
||||
windows_checked += 1;
|
||||
from = to;
|
||||
}
|
||||
}
|
||||
assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `semanticTokens/full/delta`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The flat `u32` array the wire actually carries — what an edit's
|
||||
/// `start` and `deleteCount` index into.
|
||||
fn flat(tokens: &[SemanticToken]) -> Vec<u32> {
|
||||
tokens
|
||||
.iter()
|
||||
.flat_map(|t| {
|
||||
[t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Apply the edits exactly as a client does: in order, by index, on the
|
||||
/// flat array. Deliberately shares no code with `delta`.
|
||||
fn apply_edits(old: &[u32], edits: &[SemanticTokensEdit]) -> Vec<u32> {
|
||||
let mut data = old.to_vec();
|
||||
for edit in edits {
|
||||
let start = edit.start as usize;
|
||||
let end = start + edit.delete_count as usize;
|
||||
let inserted = flat(edit.data.as_deref().unwrap_or_default());
|
||||
data.splice(start..end, inserted);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// The invariant: applying what the server sent reproduces the new token
|
||||
/// list exactly. Returns the edits so a test can also say how many.
|
||||
fn reconstructs(before: &str, after: &str) -> Vec<SemanticTokensEdit> {
|
||||
let (old, new) = (tokens_of(before), tokens_of(after));
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(
|
||||
apply_edits(&flat(&old), &edits),
|
||||
flat(&new),
|
||||
"the edits must reconstruct the new data:\n{before:?}\n{after:?}"
|
||||
);
|
||||
edits
|
||||
}
|
||||
|
||||
const MODULE: &str = "module m;\n wire a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_buffer_produces_no_edits_at_all() {
|
||||
assert!(reconstructs(MODULE, MODULE).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_append_at_the_end_is_one_edit_that_deletes_nothing() {
|
||||
let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n");
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].delete_count, 0, "nothing was removed: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_at_the_end_is_one_edit_that_inserts_nothing() {
|
||||
let edits = reconstructs("module m;\n wire a;\nendmodule\n// gone\n", MODULE);
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].data.as_deref().unwrap_or_default(), &[], "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_in_the_middle_leaves_the_ends_alone() {
|
||||
let edits = reconstructs(
|
||||
"module m;\n wire a;\n wire b;\nendmodule\n",
|
||||
"module m;\n logic a;\n wire b;\nendmodule\n",
|
||||
);
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert!(edits[0].start > 0, "the first line's tokens are common prefix: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complete_replacement_is_one_edit_over_everything() {
|
||||
let edits = reconstructs(MODULE, "`define W 8\n");
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].start, 0, "nothing was in common: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_stops_lexing_deletes_every_token_and_back() {
|
||||
// Mid-keystroke reality: an unterminated block comment has no tokens
|
||||
// at all, and the next keystroke brings them all back.
|
||||
let broken = "module m;\n wire a; /* unterminated\n";
|
||||
assert!(tokens_of(broken).is_empty(), "the premise");
|
||||
reconstructs(MODULE, broken);
|
||||
reconstructs(broken, MODULE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_buffer_is_a_legal_end_of_a_delta_in_both_directions() {
|
||||
reconstructs(MODULE, "");
|
||||
reconstructs("", MODULE);
|
||||
assert!(reconstructs("", "").is_empty());
|
||||
}
|
||||
|
||||
/// A token, for the shapes that are about the algorithm rather than about
|
||||
/// Verilog.
|
||||
fn token(delta_line: u32, delta_start: u32, length: u32) -> SemanticToken {
|
||||
SemanticToken {
|
||||
delta_line,
|
||||
delta_start,
|
||||
length,
|
||||
token_type: Highlight::Keyword as u32,
|
||||
token_modifiers_bitset: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suffix_is_capped_so_it_cannot_overlap_the_prefix() {
|
||||
// old = [A, B, A], new = [A]. The prefix claims the leading A; a
|
||||
// suffix counted over the *whole* lists would claim the trailing one
|
||||
// — the same token twice — and `new[prefix..new.len() - suffix]`
|
||||
// would then run backwards. Counting the suffix over what the prefix
|
||||
// left is the cap, and this is the shape that proves it.
|
||||
let (a, b) = (token(0, 0, 1), token(1, 0, 2));
|
||||
let old = vec![a, b, a];
|
||||
let new = vec![a];
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(apply_edits(&flat(&old), &edits), flat(&new));
|
||||
|
||||
// And the mirror: growing into a repeating list.
|
||||
let edits = delta(&new, &old);
|
||||
assert_eq!(apply_edits(&flat(&new), &edits), flat(&old));
|
||||
|
||||
// The fully periodic case, where every token equals every other.
|
||||
let old = vec![a, a, a, a, a];
|
||||
let new = vec![a, a, a];
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(apply_edits(&flat(&old), &edits), flat(&new));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_lines_of_verilog_are_the_same_trap_on_real_tokens() {
|
||||
// Identical lines encode to identical tokens — the delta encoding is
|
||||
// relative, so line 2 and line 3 of this buffer are byte-for-byte the
|
||||
// same five numbers. Deleting one of them is the overlap shape above,
|
||||
// reached without constructing anything by hand.
|
||||
let three = "module m;\n wire a;\n wire a;\n wire a;\nendmodule\n";
|
||||
let one = "module m;\n wire a;\nendmodule\n";
|
||||
let data = tokens_of(three);
|
||||
assert_eq!(data[2], data[4], "the premise: the encoding really does repeat");
|
||||
reconstructs(three, one);
|
||||
reconstructs(one, three);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edits_indices_count_numbers_and_not_tokens() {
|
||||
// The off-by-five that silently corrupts a client's cache: `start`
|
||||
// and `deleteCount` index the flat array, so both are five times a
|
||||
// token index.
|
||||
let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n");
|
||||
assert_eq!(edits[0].start % FIELDS, 0, "{edits:?}");
|
||||
assert_eq!(edits[0].start, tokens_of(MODULE).len() as u32 * FIELDS);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// randomized sweep
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A fixed-seed linear congruential generator — deterministic randomness
|
||||
/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` uses.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
self.0 >> 33
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines a module body can be built from — repeats included, because
|
||||
/// repeats are what make the prefix and suffix fight over a token.
|
||||
const BODY: [&str; 8] = [
|
||||
" wire a;",
|
||||
" wire a;",
|
||||
" localparam W = 8;",
|
||||
" // a comment",
|
||||
" assign a = b & c;",
|
||||
" always_ff @(posedge clk) q <= d;",
|
||||
" /* block */",
|
||||
" wire [W-1:0] bus;",
|
||||
];
|
||||
|
||||
fn buffer(rng: &mut Lcg) -> String {
|
||||
let mut text = String::from("module m;\n");
|
||||
for _ in 0..rng.below(9) {
|
||||
text.push_str(BODY[rng.below(BODY.len() as u64) as usize]);
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pair_of_real_buffers_round_trips_through_its_delta() {
|
||||
let mut rng = Lcg(0x5eed);
|
||||
for _ in 0..300 {
|
||||
let (before, after) = (buffer(&mut rng), buffer(&mut rng));
|
||||
reconstructs(&before, &after);
|
||||
reconstructs(&after, &before);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26): independent verification of the delta round-trip
|
||||
// and the range boundaries, on a code path that shares nothing with
|
||||
// the dev's own `apply_edits`/`reconstructs` helpers above.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// QA's own applier: unlike `apply_edits`, this never touches the flat
|
||||
/// `u32` array — it walks `SemanticToken`s and slices by hand instead of
|
||||
/// calling `Vec::splice`. It also asserts the `FIELDS` division is exact,
|
||||
/// which is a second, independent check of the "five times a token
|
||||
/// index" claim (`an_edits_indices_count_numbers_and_not_tokens`).
|
||||
fn independent_apply(
|
||||
old: &[SemanticToken],
|
||||
edits: &[SemanticTokensEdit],
|
||||
) -> Vec<SemanticToken> {
|
||||
let mut data = old.to_vec();
|
||||
for edit in edits {
|
||||
assert_eq!(edit.start % FIELDS, 0, "start is not a whole token: {edit:?}");
|
||||
assert_eq!(edit.delete_count % FIELDS, 0, "deleteCount is not a whole token: {edit:?}");
|
||||
let start = (edit.start / FIELDS) as usize;
|
||||
let deleted = (edit.delete_count / FIELDS) as usize;
|
||||
let mut rebuilt = Vec::with_capacity(data.len());
|
||||
rebuilt.extend_from_slice(&data[..start]);
|
||||
if let Some(inserted) = &edit.data {
|
||||
rebuilt.extend_from_slice(inserted);
|
||||
}
|
||||
rebuilt.extend_from_slice(&data[start + deleted..]);
|
||||
data = rebuilt;
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// Same invariant as `reconstructs`, checked with QA's applier instead of
|
||||
/// the dev's.
|
||||
fn reconstructs_independently(before: &str, after: &str) -> Vec<SemanticTokensEdit> {
|
||||
let (old, new) = (tokens_of(before), tokens_of(after));
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(
|
||||
independent_apply(&old, &edits),
|
||||
new,
|
||||
"QA reconstruction failed:\n{before:?}\n{after:?}"
|
||||
);
|
||||
edits
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_two_independently_written_appliers_never_disagree() {
|
||||
// The dev's applier works on the flat `u32` array; QA's works on
|
||||
// `SemanticToken`s and never calls `Vec::splice`. Run both over the
|
||||
// same edits and the same inputs and demand they land on the same
|
||||
// place — and on the truth.
|
||||
let mut rng = Lcg(0xC0FFEE);
|
||||
for _ in 0..200 {
|
||||
let (before, after) = (buffer(&mut rng), buffer(&mut rng));
|
||||
let (old, new) = (tokens_of(&before), tokens_of(&after));
|
||||
let edits = delta(&old, &new);
|
||||
let via_flat = apply_edits(&flat(&old), &edits);
|
||||
let via_tokens = flat(&independent_apply(&old, &edits));
|
||||
assert_eq!(via_flat, via_tokens, "the two appliers disagree:\n{before:?}\n{after:?}");
|
||||
assert_eq!(via_tokens, flat(&new));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes() {
|
||||
let module = "module m;\n wire a;\n wire b;\nendmodule\n";
|
||||
// Both ends change at once, middle stays: prefix and suffix both
|
||||
// trim to non-trivial amounts.
|
||||
reconstructs_independently(
|
||||
module,
|
||||
"`define X 1\nmodule m;\n wire a;\n wire b;\nendmodule\n// tail\n",
|
||||
);
|
||||
// Middle only.
|
||||
reconstructs_independently(module, "module m;\n wire a;\n logic b;\nendmodule\n");
|
||||
// Identical.
|
||||
reconstructs_independently(module, module);
|
||||
// Complete replacement: nothing in common.
|
||||
reconstructs_independently(module, "`define totally different 1\n");
|
||||
// Old empty, new empty.
|
||||
reconstructs_independently("", module);
|
||||
reconstructs_independently(module, "");
|
||||
assert!(reconstructs_independently("", "").is_empty());
|
||||
// Single-token file, both directions and against itself.
|
||||
const SINGLE: &str = "// only one token\n";
|
||||
assert_eq!(tokens_of(SINGLE).len(), 1, "the premise: exactly one token");
|
||||
reconstructs_independently(SINGLE, module);
|
||||
reconstructs_independently(module, SINGLE);
|
||||
reconstructs_independently(SINGLE, SINGLE);
|
||||
}
|
||||
|
||||
/// A second, unrelated PRNG (xorshift64, not the dev's LCG) with its own
|
||||
/// seed.
|
||||
struct Xorshift64(u64);
|
||||
|
||||
impl Xorshift64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
let mut x = self.0;
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
self.0 = x;
|
||||
x
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// A pool that does not overlap the dev's `BODY`: it adds a block
|
||||
/// comment that spans lines, a continued `` `define``, and a generate
|
||||
/// block — pieces whose token *count* changes non-locally, not just
|
||||
/// whose content does.
|
||||
const QA_BODY: [&str; 9] = [
|
||||
" wire a;",
|
||||
" wire a;",
|
||||
" localparam W = 4;",
|
||||
" // a trailing comment",
|
||||
" assign a = b ^ c;",
|
||||
" /* a block\n comment spanning lines */",
|
||||
" `define FF(q, d) \\\n always_ff @(posedge clk) q <= d;",
|
||||
" generate\n if (W > 1) wire c;\n endgenerate",
|
||||
" wire [W-1:0] bus;",
|
||||
];
|
||||
|
||||
fn qa_buffer(rng: &mut Xorshift64) -> String {
|
||||
let mut text = String::from("module m;\n");
|
||||
for _ in 0..rng.below(9) {
|
||||
text.push_str(QA_BODY[rng.below(QA_BODY.len() as u64) as usize]);
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips() {
|
||||
let mut rng = Xorshift64(0xDEAD_BEEF_1234_5678);
|
||||
for _ in 0..300 {
|
||||
let (before, after) = (qa_buffer(&mut rng), qa_buffer(&mut rng));
|
||||
reconstructs_independently(&before, &after);
|
||||
reconstructs_independently(&after, &before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_range_ending_mid_token_keeps_that_token_whole() {
|
||||
// Mirror of `a_range_that_starts_mid_token_keeps_that_token_whole`:
|
||||
// the overlap guard must be symmetric at the far boundary too.
|
||||
let data = ranged("module m;\nendmodule\n", range((0, 0), (0, 3)));
|
||||
assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty() {
|
||||
// Not an empty *line* (already covered by
|
||||
// `a_range_touching_no_token_is_empty`) — whitespace, plus an
|
||||
// unemitted `=`, between two real tokens on the same line.
|
||||
let text = "module m;\n assign a = b;\nendmodule\n";
|
||||
// "a" is the single character at column 9 (ends at 10); "b" starts
|
||||
// at column 17. Columns 11..16 are wholly inside that gap.
|
||||
let data = ranged(text, range((1, 11), (1, 16)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_reversed_range_is_total_and_answers_nothing() {
|
||||
// start > end is not a shape any client should send, but `within`'s
|
||||
// guard (`range.start >= range.end`) is symmetric to it: this must
|
||||
// not panic, and must answer empty exactly like a zero-width range.
|
||||
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -112,7 +112,13 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
|
||||
.any(|path| watched(&path, filelist))
|
||||
}
|
||||
|
||||
fn watched(path: &Path, filelist: Option<&Path>) -> bool {
|
||||
/// Whether one path is something the index reads: a source file, or the
|
||||
/// filelist that decides which source files there are.
|
||||
///
|
||||
/// Public since 2026-08-27 for `file_ops.rs`: `didRenameFiles`/`didDeleteFiles`
|
||||
/// nudge the index for exactly the paths a watcher event would, and two copies
|
||||
/// of that test would drift.
|
||||
pub fn watched(path: &Path, filelist: Option<&Path>) -> bool {
|
||||
if filelist == Some(path) {
|
||||
return true;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -194,3 +194,52 @@ module m
|
||||
import c::u;
|
||||
#(parameter int W = 8) (input clk_i);
|
||||
endmodule
|
||||
====
|
||||
# a direction-less first ANSI port: the normal spelling of an interface port
|
||||
module m(bus_if bus,input logic clk);endmodule
|
||||
----
|
||||
module m (bus_if bus, input logic clk);
|
||||
endmodule
|
||||
====
|
||||
# the same port with a modport, and alone in the list
|
||||
module m( bus_if.mp bus );endmodule
|
||||
----
|
||||
module m (bus_if.mp bus);
|
||||
endmodule
|
||||
====
|
||||
# a package-scoped type as the first port
|
||||
module m(my_pkg::state_t s,output logic q);endmodule
|
||||
----
|
||||
module m (my_pkg::state_t s, output logic q);
|
||||
endmodule
|
||||
====
|
||||
# an interface header takes the same list
|
||||
interface i(bus_if.mp bus,input logic clk);endinterface
|
||||
----
|
||||
interface i (bus_if.mp bus, input logic clk);
|
||||
endinterface
|
||||
====
|
||||
# a typed first port with packed dimensions and a parameterized one
|
||||
module m(word_t [3:0] d,item #(A, B) req,input a);endmodule
|
||||
----
|
||||
module m (word_t [3:0] d, item #(A, B) req, input a);
|
||||
endmodule
|
||||
====
|
||||
# a direction-less first port in a list too wide for one line
|
||||
module wide_module_name_here(bus_if.mp bus_interface_port,my_pkg::state_t current_state_in,input logic clock_signal,output logic [31:0] result_word_out);endmodule
|
||||
----
|
||||
module wide_module_name_here (
|
||||
bus_if.mp bus_interface_port,
|
||||
my_pkg::state_t current_state_in,
|
||||
input logic clock_signal,
|
||||
output logic [31:0] result_word_out
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# a name-only non-ANSI list is untouched by the disambiguation
|
||||
module m(a,b);input a;output b;endmodule
|
||||
----
|
||||
module m (a, b);
|
||||
input a;
|
||||
output b;
|
||||
endmodule
|
||||
@@ -2412,6 +2412,16 @@ impl<'a> Parser<'a> {
|
||||
|| t.is_kw("ref")
|
||||
|| TYPE_KEYWORDS.contains(&t.text.as_str())
|
||||
|| NET_KEYWORDS.contains(&t.text.as_str())
|
||||
// A direction is optional on the *first* ANSI port too (IEEE
|
||||
// 1800 §23.2.2.2), and an interface port is normally written
|
||||
// with none at all: `module m (bus_if bus, input logic clk);`.
|
||||
// Such a port opens with a plain identifier, exactly as a
|
||||
// non-ANSI name list does, so the two are told apart by what
|
||||
// follows it — a second identifier (past any `pkg::` chain,
|
||||
// `#( ... )` override or packed dimensions) means a type and a
|
||||
// name, while the `,` or `)` of `module m (a, b);` does not.
|
||||
|| (t.kind == TokenKind::Ident
|
||||
&& (self.at_typed_declarator() || self.at_modport_port()))
|
||||
};
|
||||
if ansi {
|
||||
let mut ports = Vec::new();
|
||||
@@ -2484,7 +2494,11 @@ impl<'a> Parser<'a> {
|
||||
None
|
||||
}
|
||||
};
|
||||
let ty = self.parse_opt_data_type()?;
|
||||
let ty = if self.at_modport_port() {
|
||||
self.parse_modport_port_type()?
|
||||
} else {
|
||||
self.parse_opt_data_type()?
|
||||
};
|
||||
let Name { text: name, span: name_span } = self.expect_name()?;
|
||||
let unpacked = self.parse_dims()?;
|
||||
let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
|
||||
@@ -2493,6 +2507,28 @@ impl<'a> Parser<'a> {
|
||||
Ok(AnsiPort { meta, dir, net, ty, name, name_span, unpacked, default, comma: false, span })
|
||||
}
|
||||
|
||||
/// Does the cursor sit on an interface port that names a modport,
|
||||
/// `bus_if.mp bus` (IEEE 1800 §25.4)? Only a *port header* is spelled this
|
||||
/// way — after an identifier anywhere else a `.` opens a member access —
|
||||
/// so the shape is recognized here rather than in `parse_opt_data_type`.
|
||||
fn at_modport_port(&self) -> bool {
|
||||
self.cur().kind == TokenKind::Ident
|
||||
&& self.nth(1).is_sym(".")
|
||||
&& self.nth(2).kind == TokenKind::Ident
|
||||
&& self.nth(3).kind == TokenKind::Ident
|
||||
}
|
||||
|
||||
/// The `bus_if.mp` of an interface port, as its type. The modport is glued
|
||||
/// onto the interface name exactly as a `pkg::` qualifier is, so every
|
||||
/// consumer that prints or scans a type name still sees one string.
|
||||
fn parse_modport_port_type(&mut self) -> PResult<DataType> {
|
||||
let mut name = self.expect_ident()?;
|
||||
self.expect_sym(".")?;
|
||||
name.push('.');
|
||||
name.push_str(&self.expect_ident()?);
|
||||
Ok(DataType { name, ..DataType::default() })
|
||||
}
|
||||
|
||||
/// Parse a possibly-implicit data type. Stops before the declarator name.
|
||||
fn parse_opt_data_type(&mut self) -> PResult<DataType> {
|
||||
let mut ty = DataType::default();
|
||||
@@ -5738,6 +5774,168 @@ mod tests {
|
||||
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, false]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// A direction-less first ANSI port (IEEE 1800 §23.2.2.2)
|
||||
// `docs/features/ansi-first-port/README.md`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The `(dir, type, name)` of every port of an ANSI header.
|
||||
fn ansi_ports(src: &str) -> Vec<(String, String, String)> {
|
||||
let file = parse_ok(src);
|
||||
let m = module_of(&file);
|
||||
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports in {src:?}") };
|
||||
ports
|
||||
.iter()
|
||||
.map(|p| (p.dir.clone().unwrap_or_default(), p.ty.name.clone(), p.name.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn cell(dir: &str, ty: &str, name: &str) -> (String, String, String) {
|
||||
(dir.to_string(), ty.to_string(), name.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_typed_first_port_needs_no_direction() {
|
||||
assert_eq!(
|
||||
ansi_ports("module m (bus_if bus, input logic clk);\nendmodule\n"),
|
||||
[cell("", "bus_if", "bus"), cell("input", "logic", "clk")]
|
||||
);
|
||||
assert_eq!(
|
||||
ansi_ports("module m (bus_if bus);\nendmodule\n"),
|
||||
[cell("", "bus_if", "bus")],
|
||||
"alone in the list"
|
||||
);
|
||||
assert_eq!(
|
||||
ansi_ports("interface i (bus_if bus);\nendinterface\n"),
|
||||
[cell("", "bus_if", "bus")],
|
||||
"an interface header is the same node and the same list"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modport_qualified_port_keeps_the_modport_in_its_type() {
|
||||
// IEEE 1800 §25.4. The modport is glued onto the interface name, the
|
||||
// way a `pkg::` qualifier already is, so nothing downstream needs a
|
||||
// second field to print or scan.
|
||||
assert_eq!(
|
||||
ansi_ports("module m (bus_if.mp bus);\nendmodule\n"),
|
||||
[cell("", "bus_if.mp", "bus")]
|
||||
);
|
||||
assert_eq!(
|
||||
ansi_ports("module m (input logic clk, bus_if.mp bus);\nendmodule\n"),
|
||||
[cell("input", "logic", "clk"), cell("", "bus_if.mp", "bus")],
|
||||
"later in the list too, which never parsed either"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_scoped_first_port_is_a_type_and_a_name() {
|
||||
assert_eq!(
|
||||
ansi_ports("module m (my_pkg::state_t s);\nendmodule\n"),
|
||||
[cell("", "my_pkg::state_t", "s")]
|
||||
);
|
||||
assert_eq!(
|
||||
ansi_ports("module m (my_pkg::state_t s, output logic q);\nendmodule\n"),
|
||||
[cell("", "my_pkg::state_t", "s"), cell("output", "logic", "q")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direction_less_first_port_mixes_with_directed_ones_in_both_orders() {
|
||||
assert_eq!(
|
||||
ansi_ports("module m (state_t s, input a, output logic q);\nendmodule\n"),
|
||||
[cell("", "state_t", "s"), cell("input", "", "a"), cell("output", "logic", "q")]
|
||||
);
|
||||
assert_eq!(
|
||||
ansi_ports("module m (input a, state_t s);\nendmodule\n"),
|
||||
[cell("input", "", "a"), cell("", "state_t", "s")],
|
||||
"the ordering that always parsed is unchanged"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_first_port_carries_its_dimensions_like_any_other() {
|
||||
assert_eq!(
|
||||
ansi_ports("module m (word_t [3:0] d, input a);\nendmodule\n"),
|
||||
[cell("", "word_t", "d"), cell("input", "", "a")],
|
||||
"packed dimensions sit between the type and the name"
|
||||
);
|
||||
assert_eq!(
|
||||
ansi_ports("module m (item #(A, B) req);\nendmodule\n"),
|
||||
[cell("", "item", "req")],
|
||||
"a parameterized type, whose `#( ... )` is kept in the type"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_only_port_list_is_still_non_ansi() {
|
||||
// The disambiguation must not eat the non-ANSI list: what follows the
|
||||
// first identifier is a `,` or a `)`, not a second name.
|
||||
let file = parse_ok("module m (a, b, c);\ninput a;\ninput b;\noutput c;\nendmodule\n");
|
||||
let m = module_of(&file);
|
||||
let PortList::NonAnsi(ports) = &m.ports else { panic!("expected a non-ANSI port list") };
|
||||
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b", "c"]);
|
||||
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, true, false]);
|
||||
|
||||
let file = parse_ok("module m (a);\ninput a;\nendmodule\n");
|
||||
let PortList::NonAnsi(ports) = &module_of(&file).ports else { panic!("non-ANSI") };
|
||||
assert_eq!(ports.len(), 1, "a one-name list has no comma to look past either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_port_list_spellings_are_untouched() {
|
||||
let file = parse_ok("module m ();\nendmodule\n");
|
||||
assert!(matches!(module_of(&file).ports, PortList::Empty), "empty parens");
|
||||
let file = parse_ok("module m;\nendmodule\n");
|
||||
assert!(matches!(module_of(&file).ports, PortList::None), "no list at all");
|
||||
assert_eq!(
|
||||
ansi_ports("module m (input a, b);\nendmodule\n"),
|
||||
[cell("input", "", "a"), cell("", "", "b")],
|
||||
"a continuation port still inherits its direction from the one before"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_a_bare_identifier_classifies_exactly_as_it_did() {
|
||||
// The clause only fires on a `TokenKind::Ident`, so a macro-produced
|
||||
// list (a `Directive` token) and an escaped name are read the way
|
||||
// they always were, and a comment between the name and its comma is
|
||||
// trivia that the lookahead never sees.
|
||||
for src in [
|
||||
"module m (`PORT_LIST);\nendmodule\n",
|
||||
"module m (\\esc_name , b);\nendmodule\n",
|
||||
"module m (a /* why */, b);\nendmodule\n",
|
||||
] {
|
||||
let file = parse_ok(src);
|
||||
assert!(
|
||||
matches!(module_of(&file).ports, PortList::NonAnsi(_)),
|
||||
"still a non-ANSI list: {src:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_header_still_reports_its_own_token() {
|
||||
// Recovery is unchanged: neither new shape swallows a genuinely
|
||||
// broken list, and the diagnostic still names what blocked it.
|
||||
assert!(parse_err("module m (bus_if bus;\nendmodule\n").contains("expected `)`"));
|
||||
assert!(parse_err("module m (a[3], b);\nendmodule\n").contains("expected `)`"));
|
||||
let (file, diags) = crate::parse_source_tolerant("module m (bus_if bus\nendmodule\n");
|
||||
assert!(!diags.is_empty(), "a header that never closes is still an error");
|
||||
assert!(!file.items.is_empty(), "and the file is still addressable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_shapes_left_open_by_ansi_first_port_still_refuse() {
|
||||
// Pinned so a future round that changes either does it on purpose
|
||||
// (docs/features/ansi-first-port/README.md, Status): the generic
|
||||
// `interface` port is a different production wanting a "any
|
||||
// interface" DataType, and a modport-qualified *declaration* type
|
||||
// would change how a `.` after an identifier reads everywhere.
|
||||
assert!(parse_err("module m (interface bus);\nendmodule\n").contains("expected"));
|
||||
assert!(parse_err("module m;\n virtual bus_if.mp v;\nendmodule\n").contains("expected"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_arms_of_an_else_are_ordinary_elements_of_one_list() {
|
||||
// lucisv does not evaluate the condition: an `ifdef/`else pair simply
|
||||
|
||||
@@ -902,14 +902,24 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_typed_port_list_is_refused_as_a_parse_failure() {
|
||||
// The disclosed `vlog_parser` gap: an interface-typed ANSI port
|
||||
// (`iface_bus.mst bus`) stops the header from parsing, so no module
|
||||
// is produced at all. The refusal must name the real cause.
|
||||
fn an_interface_typed_port_list_is_planned_like_any_other() {
|
||||
// Was the disclosed `vlog_parser` gap: an interface-typed ANSI port
|
||||
// (`iface_bus.mst bus`) as the first, direction-less element stopped
|
||||
// the header from parsing, so no module was produced at all and the
|
||||
// refusal had to name the real cause. `docs/features/ansi-first-port`
|
||||
// closed it, so the plan is now the ordinary one — an interface port
|
||||
// has no direction, and its type is the interface (with its modport)
|
||||
// exactly as written.
|
||||
let text = "module m (iface_bus.mst bus, input logic clk);\nendmodule\n";
|
||||
let message = instantiation_plan("m", text, None).expect_err("the parser gap");
|
||||
assert!(message.contains("does not parse"), "{message}");
|
||||
assert!(message.contains("line"), "{message}");
|
||||
let plan = plan(text, "m");
|
||||
assert_eq!(plan.ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["bus", "clk"]);
|
||||
assert_eq!(plan.ports[0].dir, "");
|
||||
assert_eq!(plan.ports[0].ty, "iface_bus.mst");
|
||||
assert_eq!(plan.ports[1].dir, "input");
|
||||
assert_eq!(plan.ports[1].ty, "logic");
|
||||
let skeleton = plan.render(&Layout::default());
|
||||
assert!(skeleton.contains(".bus("), "{skeleton}");
|
||||
assert!(parses(&skeleton), "{skeleton}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -318,6 +318,61 @@ fn a_port_renames_inside_the_connection_lists_of_other_files() {
|
||||
assert!(after.contains(".rst(1'b1)"), "the other connection is untouched: {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_renames_from_the_declaration_it_types_in_another_file() {
|
||||
// Overlay promotion (`docs/features/overlay-promotion/README.md`) made
|
||||
// this reachable: an unqualified type name nothing in the using file
|
||||
// binds is now an external candidate the workspace answers, so the two
|
||||
// halves of the rename are one symbol instead of two unrelated words.
|
||||
// The interface is written in the body rather than in the header, which
|
||||
// is the shape this test has always pinned. The header spelling reaches
|
||||
// the same reference since `docs/features/ansi-first-port/README.md`, and
|
||||
// is asserted below as its own arm.
|
||||
let iface = "interface bus_if;\nendinterface\n";
|
||||
let top = "module top;\n virtual bus_if vif;\n bus_if other ();\nendmodule\n";
|
||||
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
|
||||
|
||||
let edit = rename(&files, &path("top.sv"), at(top, "virtual", "bus_if"), "fabric_if")
|
||||
.expect("renames");
|
||||
assert!(apply(iface, &edit, &path("bus_if.sv")).contains("interface fabric_if;"));
|
||||
let after = apply(top, &edit, &path("top.sv"));
|
||||
assert!(after.contains("virtual fabric_if vif;"), "{after}");
|
||||
assert!(after.contains("fabric_if other ()"), "the instantiation too: {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_renames_through_a_direction_less_ansi_port() {
|
||||
// The header spelling of the same rename, which needed
|
||||
// `docs/features/ansi-first-port/README.md` to parse at all: the port is
|
||||
// first and carries no direction, and its modport travels with the type.
|
||||
let iface = "interface bus_if;\n modport mp (input a);\nendinterface\n";
|
||||
let top = "module top (bus_if.mp bus, input logic clk);\nendmodule\n";
|
||||
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
|
||||
|
||||
let edit =
|
||||
rename(&files, &path("top.sv"), at(top, "top ", "bus_if"), "fabric_if").expect("renames");
|
||||
assert!(apply(iface, &edit, &path("bus_if.sv")).contains("interface fabric_if;"));
|
||||
let after = apply(top, &edit, &path("top.sv"));
|
||||
assert!(after.contains("module top (fabric_if.mp bus,"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_the_modport_half_of_a_port_type_is_refused() {
|
||||
// QA attack (`docs/features/ansi-first-port/README.md`): `bus_if.mp bus`
|
||||
// glues the modport onto the type name, but only the interface half is
|
||||
// bound (`ItemKind::Modport` is a leaf in `vlog_semantic`, `bind.rs:364`).
|
||||
// A rename request on the `mp` half must find nothing to rename — never
|
||||
// silently rename the interface instead, and never corrupt the modport
|
||||
// spelling.
|
||||
let iface = "interface bus_if;\n modport mp (input a);\nendinterface\n";
|
||||
let top = "module top (bus_if.mp bus);\nendmodule\n";
|
||||
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
|
||||
let offset = at(top, "bus_if.", "mp");
|
||||
let err = rename(&files, &path("top.sv"), offset, "mp2")
|
||||
.expect_err("the modport half of the type name is not a bound symbol");
|
||||
assert!(!err.is_empty());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// refusals
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -375,6 +430,24 @@ fn an_unresolved_name_is_refused_rather_than_guessed() {
|
||||
assert!(message.contains("not resolved"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_value_position_typo_never_reaches_an_unrelated_same_named_module() {
|
||||
// The regression the overlay-promotion round shipped and this round took
|
||||
// back (QA finding 1, 2026-08-26). `typo_name` on an assignment's LHS is a
|
||||
// plain expression identifier — `Target::Lexical` via `ExprKind::Ident`,
|
||||
// not a type window — so it is never given the bare-name path that would
|
||||
// make it an external candidate. Without that, `locate` takes the
|
||||
// `NotFound` arm and refuses, instead of rewriting an unrelated file's
|
||||
// module declaration on nothing but a name collision.
|
||||
let unrelated = "module typo_name;\nendmodule\n";
|
||||
let top = "module top;\n assign typo_name = 1'b1;\nendmodule\n";
|
||||
let files = workspace(&[("typo_name.sv", unrelated), ("top.sv", top)]);
|
||||
|
||||
let message = rename(&files, &path("top.sv"), at(top, "assign", "typo_name"), "fixed_name")
|
||||
.expect_err("a value-position typo must not be renamable across files");
|
||||
assert!(message.contains("not resolved to any declaration"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_declared_outside_the_indexed_files_is_refused() {
|
||||
let text = "module m;\n import other_pkg::*;\n wire w = FROM_ELSEWHERE;\nendmodule\n";
|
||||
|
||||
@@ -22,6 +22,14 @@ pub(crate) struct Pending {
|
||||
pub(crate) enum Target {
|
||||
/// The lexical chain from `scope` outward, imports included.
|
||||
Lexical,
|
||||
/// A name written where a **type** goes — the user-defined type of a
|
||||
/// declaration, a port, a parameter, a return type, a `virtual` interface
|
||||
/// property. Looked up exactly like [`Target::Lexical`], but a miss also
|
||||
/// carries the bare name to the workspace, because that is how a
|
||||
/// cross-file `interface`, `class` or `typedef` is spelled. Every type
|
||||
/// position reaches this through [`Binder::bind_data_type`]; an
|
||||
/// identifier in a *value* position never does.
|
||||
Type,
|
||||
/// A package name: the `p` of `import p::x`. Only a package can be
|
||||
/// imported, so this stays narrower than [`Target::Unit`].
|
||||
Package,
|
||||
@@ -1219,8 +1227,16 @@ impl<'a> Binder<'a> {
|
||||
self.use_name(scope, item, item_span, Target::UnitMember(unit.to_string()));
|
||||
}
|
||||
None => {
|
||||
let ns = crate::scan::name_span(self.src, window, &ty.name);
|
||||
self.use_name(scope, &ty.name, ns, Target::Lexical);
|
||||
// `bus_if.mp bus` — the parser glues an interface port's
|
||||
// modport onto the type name (IEEE 1800 §25.4). The
|
||||
// interface is the type; the modport is a member of it,
|
||||
// and this crate declares no symbol for a modport
|
||||
// (`ItemKind::Modport` is a leaf here), so the tail is
|
||||
// left unbound rather than recorded as a name that can
|
||||
// never resolve.
|
||||
let name = ty.name.split_once('.').map_or(ty.name.as_str(), |(iface, _)| iface);
|
||||
let ns = crate::scan::name_span(self.src, window, name);
|
||||
self.use_name(scope, name, ns, Target::Type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,20 +71,30 @@ pub enum Resolution {
|
||||
Resolved(SymbolId),
|
||||
/// Nothing in this file binds it, but a named external unit could: a
|
||||
/// package imported with `import p::*` / `import p::x`, a package written
|
||||
/// as `p::x`, or a module instantiated but declared in another file.
|
||||
/// `paths` names those units — a path containing `::` is a package path,
|
||||
/// a bare name is a module, package or class name. The workspace index
|
||||
/// (TODO.md §6) is what finishes these.
|
||||
/// as `p::x`, a module instantiated but declared in another file, or an
|
||||
/// unqualified **type** name — an `interface`, a package-less `class` —
|
||||
/// that only a file-scope declaration somewhere else can be. `paths` names
|
||||
/// those units — a path containing `::` is a package path, a bare name is a
|
||||
/// module, package or class name — in the order they are tried, the use's
|
||||
/// own name last. The workspace index (TODO.md §6) is what finishes these.
|
||||
ExternalCandidate { paths: Vec<String> },
|
||||
/// A use inside a class that nothing lexical binds, where the class's
|
||||
/// `extends` could: `base` is the base-class path as written
|
||||
/// (`uvm_component`, `pkg::base`), and `paths` are any import paths the
|
||||
/// lexical walk collected — either could supply the name. Nothing chases
|
||||
/// `base`, in this file or out of it; a future hover/index round can,
|
||||
/// without this crate pretending it did inheritance resolution. See
|
||||
/// `docs/features/class-semantics/README.md`.
|
||||
/// (`uvm_component`, `pkg::base`), and `paths` are the import paths the
|
||||
/// lexical walk collected — plus the use's own name when it was written in
|
||||
/// a type position — any of which could supply it. Nothing chases `base`,
|
||||
/// in this file or out of it; the
|
||||
/// workspace overlay may answer from `paths` without displacing what this
|
||||
/// says, because a resolved base would have been `Resolved` already. See
|
||||
/// `docs/features/class-semantics/README.md` and
|
||||
/// `docs/features/overlay-promotion/README.md`.
|
||||
InheritedCandidate { base: String, paths: Vec<String> },
|
||||
/// Nothing in this file binds it and no external unit could.
|
||||
/// Nothing in this file binds it and no external unit could: a member of a
|
||||
/// package this file fully declares, a `.port` of a module it declares, a
|
||||
/// `this.x`/`super.x` with no class or base to blame, or a plain
|
||||
/// value-position identifier with no import in scope. An unqualified miss
|
||||
/// in a **type** position is never this — the workspace's unit table could
|
||||
/// hold it — so that one is an `ExternalCandidate` carrying its own name.
|
||||
NotFound,
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Reso
|
||||
// An end label names the construct it closes; the binder already knew
|
||||
// which symbol that is, so there is nothing to look up.
|
||||
Target::Declaration(id) => Resolution::Resolved(*id),
|
||||
Target::Lexical => lexical(scopes, p.scope, &p.name),
|
||||
Target::Lexical => lexical(scopes, p.scope, &p.name, false),
|
||||
Target::Type => lexical(scopes, p.scope, &p.name, true),
|
||||
Target::Package => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Package),
|
||||
Target::Module => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Module),
|
||||
Target::Unit => unit(scopes, symbols, p.scope, &p.name),
|
||||
@@ -36,7 +37,18 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Reso
|
||||
/// class whose header says `extends` becomes an inheritance candidate — the
|
||||
/// base (which this crate never chases, in this file or out of it) could
|
||||
/// supply the name, and so could any import path collected on the way out.
|
||||
fn lexical(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
///
|
||||
/// `promote` is set for [`Target::Type`] only. A **type** name nothing here
|
||||
/// binds is exactly how a file-scope `interface`, a package-less `class` or a
|
||||
/// cross-file `typedef` is written (`bus_if bus;`, `my_cls h;`), so its miss
|
||||
/// ends carrying the **bare name** as its last path — last, so an import that
|
||||
/// could supply the name still wins — and the workspace's unit table, the only
|
||||
/// layer that can say, gets asked. A [`Target::Lexical`] miss is an identifier
|
||||
/// in a *value* position: a name a `` `define`` would have produced, a typo, a
|
||||
/// signal declared somewhere this crate does not model. Nothing about it says
|
||||
/// "file-scope declaration", so it is not swept through the unit table, where a
|
||||
/// mere name collision would make `rename` rewrite an unrelated file.
|
||||
fn lexical(scopes: &[Scope], from: ScopeId, name: &str, promote: bool) -> Resolution {
|
||||
let mut external = Vec::new();
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
@@ -66,6 +78,9 @@ fn lexical(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
if promote {
|
||||
external.push(name.to_string());
|
||||
}
|
||||
miss(scopes, from, external, false)
|
||||
}
|
||||
|
||||
@@ -197,7 +212,10 @@ fn super_member(scopes: &[Scope], from: ScopeId) -> Resolution {
|
||||
/// nearest extends-carrying enclosing class's base could supply the name
|
||||
/// (the LRM even puts it ahead of the enclosing scopes this walk already
|
||||
/// searched — the deliberate inexactness the same README argues), so it
|
||||
/// becomes `InheritedCandidate`.
|
||||
/// becomes `InheritedCandidate` — which keeps its base and its paths both,
|
||||
/// because either could be the answer and nothing here picks between them.
|
||||
/// A miss with nothing to name at all — no import in scope, no bare name
|
||||
/// because the use was not a type — is `NotFound`.
|
||||
fn miss(scopes: &[Scope], from: ScopeId, external: Vec<String>, unit_lookup: bool) -> Resolution {
|
||||
if unit_lookup {
|
||||
return Resolution::ExternalCandidate { paths: external };
|
||||
|
||||
@@ -379,13 +379,28 @@ pub enum Definition<'a> {
|
||||
///
|
||||
/// `sem` is not modified: the answers come back as an overlay the caller
|
||||
/// composes with it (see [`ExternalResolutions::definition_of`]).
|
||||
///
|
||||
/// An [`Resolution::InheritedCandidate`] is not an external candidate and does
|
||||
/// not become one: its base class is the single-file layer's answer and stays
|
||||
/// the answer. But its paths are real — the imports the lexical walk collected
|
||||
/// and the use's own name — so they are tried, and an entry is recorded **only
|
||||
/// when one of them lands on a declaration**. A name the index cannot answer is
|
||||
/// left exactly as it was, absent from the overlay, which is what keeps
|
||||
/// "the overlay holds what the workspace was asked to finish" true.
|
||||
pub fn resolve_external(sem: &Semantics, index: &WorkspaceIndex) -> ExternalResolutions {
|
||||
let mut targets = HashMap::new();
|
||||
for (i, reference) in sem.references().iter().enumerate() {
|
||||
let Resolution::ExternalCandidate { paths } = &reference.resolution else {
|
||||
continue;
|
||||
let target = match &reference.resolution {
|
||||
Resolution::ExternalCandidate { paths } => follow_paths(index, &reference.name, paths),
|
||||
Resolution::InheritedCandidate { paths, .. } => {
|
||||
match follow_paths(index, &reference.name, paths) {
|
||||
ExternalTarget::StillUnresolved => continue,
|
||||
answered => answered,
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
targets.insert(ReferenceId(i as u32), follow_paths(index, &reference.name, paths));
|
||||
targets.insert(ReferenceId(i as u32), target);
|
||||
}
|
||||
ExternalResolutions { targets }
|
||||
}
|
||||
@@ -429,8 +444,9 @@ impl ExternalResolutions {
|
||||
ids.into_iter().filter_map(|id| self.targets.get(&id).map(|t| (id, t)))
|
||||
}
|
||||
|
||||
/// How many external candidates the workspace answered, out of how many
|
||||
/// there were.
|
||||
/// How many of the references handed to the workspace layer it answered,
|
||||
/// out of how many it was handed — every external candidate, plus the
|
||||
/// inherited candidates it had something to say about.
|
||||
pub fn counts(&self) -> (usize, usize) {
|
||||
let answered = self.targets.values().filter(|t| !t.defs().is_empty()).count();
|
||||
(answered, self.targets.len())
|
||||
|
||||
@@ -206,7 +206,10 @@ endclass
|
||||
let expect = Resolution::InheritedCandidate { base: "uvm_object".into(), paths: Vec::new() };
|
||||
assert_eq!(resolution_at(&s, nth(src, "super.new", 0) + 6), expect);
|
||||
assert_eq!(resolution_at(&s, nth(src, "super.whatever", 0) + 6), expect);
|
||||
// A plain call that misses the whole lexical chain blames the base too.
|
||||
// A plain call that misses the whole lexical chain blames the base too,
|
||||
// and carries no path: a callee is a value position, and the promotion
|
||||
// (`docs/features/overlay-promotion/README.md`) fires on type positions
|
||||
// only, so nothing sweeps `set_name` through the workspace's unit table.
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "set_name", 0)),
|
||||
Resolution::InheritedCandidate { base: "uvm_object".into(), paths: Vec::new() }
|
||||
@@ -229,6 +232,8 @@ endclass
|
||||
match resolution_at(&s, nth(src, "UVM_LOW", 0)) {
|
||||
Resolution::InheritedCandidate { base, paths } => {
|
||||
assert_eq!(base, "uvm_component");
|
||||
// The imports in walk order, and nothing else: a call argument
|
||||
// is a value position, so the bare name is not appended.
|
||||
assert_eq!(paths, vec!["uvm_pkg::*".to_string()]);
|
||||
}
|
||||
other => panic!("expected an inherited candidate, got {other:?}"),
|
||||
@@ -720,7 +725,11 @@ fn inherited_candidates_are_not_the_workspace_overlays_business() {
|
||||
held.resolution,
|
||||
Resolution::InheritedCandidate { base: "base".into(), paths: Vec::new() }
|
||||
);
|
||||
// Two reasons it is absent from the overlay, and both hold: `held = 1` is
|
||||
// a value position, so the promotion never gave it a path to sweep; and
|
||||
// even with one, a class property is not a unit, so the sweep would find
|
||||
// nothing and record nothing.
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
let id = s.reference_id_at(nth(sources[1].1, "held = 1", 0)).expect("an id");
|
||||
assert!(overlay.get(id).is_none(), "the overlay holds external candidates only");
|
||||
assert!(overlay.get(id).is_none(), "a name the workspace cannot answer is not in the overlay");
|
||||
}
|
||||
@@ -49,7 +49,7 @@ impl Totals {
|
||||
let pct = |n: usize| 100.0 * n as f64 / self.references.max(1) as f64;
|
||||
println!(
|
||||
"{label}: {} files, {} symbols, {} references — {:.1}% resolved in-file, \
|
||||
{:.1}% external candidates, {:.1}% inherited candidates, {:.1}% unresolved, \
|
||||
{:.1}% external candidates, {:.1}% inherited candidates, {:.2}% unresolved ({}), \
|
||||
{} names unplaced",
|
||||
self.files,
|
||||
self.symbols,
|
||||
@@ -58,6 +58,7 @@ impl Totals {
|
||||
pct(self.external),
|
||||
pct(self.inherited),
|
||||
pct(self.unresolved()),
|
||||
self.unresolved(),
|
||||
self.unplaced,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -211,7 +211,10 @@ endmodule
|
||||
let in_loop = s.reference_at(nth(src, "assign w = i", 0) + 11).expect("the use in the body");
|
||||
assert_eq!(in_loop.resolved(), Some(genvar));
|
||||
|
||||
// Outside the loop the genvar is gone.
|
||||
// Outside the loop the genvar is gone, and a bare `i` in an expression is
|
||||
// a value position: nothing in scope names it and nothing offers it to the
|
||||
// workspace, so it stays `NotFound` (a one-letter name is exactly the kind
|
||||
// of coincidence a unit-table sweep must not chase).
|
||||
let outside = s.reference_at(nth(src, "assign top_i = i", 0) + 15).expect("the use outside");
|
||||
assert_eq!(outside.resolution, Resolution::NotFound);
|
||||
|
||||
@@ -299,7 +302,9 @@ endmodule
|
||||
let s = sem(src);
|
||||
|
||||
// Only the wildcard could supply this name; the explicit import names
|
||||
// something else, so it is not offered to the workspace index.
|
||||
// something else, so it is not offered to the workspace index. No bare
|
||||
// name either: the promotion is for type positions, and this is a value
|
||||
// (`docs/features/overlay-promotion/README.md`).
|
||||
let some = s.reference_at(nth(src, "SOMETHING", 0)).expect("the use");
|
||||
assert_eq!(
|
||||
some.resolution,
|
||||
|
||||
@@ -374,6 +374,273 @@ fn counts_report_what_was_indexed() {
|
||||
assert_eq!(counts.defines, 1);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Overlay promotion: unqualified misses reach the unit table
|
||||
// (docs/features/overlay-promotion/README.md)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The resolution the single-file layer gave the reference at `needle`.
|
||||
fn resolution(sem: &Semantics, src: &str, needle: &str) -> Resolution {
|
||||
let offset = src.find(needle).expect("needle is in the source") as u32;
|
||||
sem.reference_at(offset).expect("a reference is written here").resolution.clone()
|
||||
}
|
||||
|
||||
/// Whether the overlay holds any entry at all for the reference at `needle`.
|
||||
fn in_overlay(sem: &Semantics, ws: &WorkspaceIndex, src: &str, needle: &str) -> bool {
|
||||
let offset = src.find(needle).expect("needle is in the source") as u32;
|
||||
let id = sem.reference_id_at(offset).expect("a reference is written here");
|
||||
resolve_external(sem, ws).get(id).is_some()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unqualified_type_miss_carries_its_own_name_to_the_unit_table() {
|
||||
// An `interface` lives at file scope, never in a package, so nothing in
|
||||
// the using file can bind its name and no import path can carry it. The
|
||||
// bare name is the whole handshake.
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\nendinterface\n"),
|
||||
("top.sv", "module top;\n bus_if bus;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[1].1);
|
||||
|
||||
assert_eq!(
|
||||
resolution(&sem, sources[1].1, "bus_if bus"),
|
||||
Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] }
|
||||
);
|
||||
let defs = external_defs(&sem, &ws, sources[1].1, "bus_if bus");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
assert_eq!(slice(&ws, &sources, &defs[0]), "bus_if");
|
||||
assert_eq!(defs[0].kind, SymbolKind::Module, "an interface is a Module symbol");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_less_class_and_a_file_scope_typedef_are_reached_the_same_way() {
|
||||
let sources = [
|
||||
("cls.sv", "class my_cls;\nendclass\n"),
|
||||
("types.sv", "typedef logic [3:0] nib_t;\n"),
|
||||
("top.sv", "module top;\n my_cls h;\n nib_t n;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[2].1);
|
||||
|
||||
let cls = external_defs(&sem, &ws, sources[2].1, "my_cls h");
|
||||
assert_eq!(cls.len(), 1, "{cls:?}");
|
||||
assert_eq!(cls[0].kind, SymbolKind::Class);
|
||||
let nib = external_defs(&sem, &ws, sources[2].1, "nib_t n");
|
||||
assert_eq!(nib.len(), 1, "{nib:?}");
|
||||
assert_eq!(nib[0].kind, SymbolKind::Typedef);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_miss_inside_an_extending_class_is_answered_without_losing_its_base() {
|
||||
// The UVM shape: almost every class extends something, so almost every
|
||||
// miss inside one is an `InheritedCandidate`. It stays one — `base` is
|
||||
// still there for a consumer to read — and the overlay answers it from
|
||||
// the paths it now carries.
|
||||
let sources = [
|
||||
("clk_rst_if.sv", "interface clk_rst_if;\nendinterface\n"),
|
||||
("env.sv", "class env extends uvm_object;\n virtual clk_rst_if vif;\nendclass\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[1].1);
|
||||
|
||||
assert_eq!(
|
||||
resolution(&sem, sources[1].1, "clk_rst_if vif"),
|
||||
Resolution::InheritedCandidate {
|
||||
base: "uvm_object".to_string(),
|
||||
paths: vec!["clk_rst_if".to_string()],
|
||||
},
|
||||
"the inherited semantics other consumers read are untouched"
|
||||
);
|
||||
let defs = external_defs(&sem, &ws, sources[1].1, "clk_rst_if vif");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
assert_eq!(slice(&ws, &sources, &defs[0]), "clk_rst_if");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direction_less_first_ansi_port_binds_its_interface_type_cross_file() {
|
||||
// `docs/features/ansi-first-port/README.md`: the header spelling every
|
||||
// interface port is really written in. `bind_module`'s ANSI arm sees an
|
||||
// ordinary `AnsiPort` with no direction, so the type window is the one it
|
||||
// always was and the name reaches the unit table like any other type miss.
|
||||
// The modport spelling is the same reference: the parser glues `.mp` onto
|
||||
// the type name and `bind_data_type` binds the interface half of it.
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\n modport mp (input a);\nendinterface\n"),
|
||||
("top.sv", "module top (bus_if bus, input logic clk);\nendmodule\n"),
|
||||
("sub.sv", "module sub (bus_if.mp bus);\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
|
||||
for (src, needle) in [(sources[1].1, "bus_if bus"), (sources[2].1, "bus_if.mp")] {
|
||||
let sem = semantics(src);
|
||||
assert_eq!(
|
||||
resolution(&sem, src, needle),
|
||||
Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] },
|
||||
"{needle}"
|
||||
);
|
||||
let defs = external_defs(&sem, &ws, src, needle);
|
||||
assert_eq!(defs.len(), 1, "{needle}: {defs:?}");
|
||||
assert_eq!(slice(&ws, &sources, &defs[0]), "bus_if");
|
||||
assert_eq!(defs[0].kind, SymbolKind::Module, "an interface is a Module symbol");
|
||||
}
|
||||
|
||||
// The port itself is still declared, and `clk` beside it too: the shared
|
||||
// type window never swallowed the declarator.
|
||||
let sem = semantics(sources[1].1);
|
||||
let ports: Vec<&str> = sem
|
||||
.symbols()
|
||||
.iter()
|
||||
.filter(|s| s.kind == SymbolKind::Port)
|
||||
.map(|s| s.name.as_str())
|
||||
.collect();
|
||||
assert_eq!(ports, ["bus", "clk"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_member_the_unit_table_cannot_hold_stays_exactly_what_it_was() {
|
||||
// The other half of the same shape: an ordinary member miss. The sweep is
|
||||
// a *unit* lookup, and a property or a method is not a unit, so nothing
|
||||
// answers and the reference keeps its base and no overlay entry.
|
||||
let sources = [
|
||||
("base.sv", "class base;\n int held;\nendclass\n"),
|
||||
(
|
||||
"child.sv",
|
||||
"class child extends base;\n function void f();\n held = 1;\n endfunction\nendclass\n",
|
||||
),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[1].1);
|
||||
|
||||
assert!(matches!(
|
||||
resolution(&sem, sources[1].1, "held = 1"),
|
||||
Resolution::InheritedCandidate { .. }
|
||||
));
|
||||
assert!(!in_overlay(&sem, &ws, sources[1].1, "held = 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_qualified_miss_is_never_promoted_in_either_spelling() {
|
||||
// `unit::member` names something *inside* `unit`; sweeping the bare tail
|
||||
// would discard the qualifier and jump somewhere the source never
|
||||
// pointed. `resolve.rs`'s `unit_member` never adds the bare name, in
|
||||
// either of the two spellings its misses take.
|
||||
let decoy = ("missing_t.sv", "module missing_t;\nendmodule\n");
|
||||
let from_package =
|
||||
[decoy, ("top.sv", "package p;\nendpackage\nmodule top;\n p::missing_t s;\nendmodule\n")];
|
||||
let ws = index(&from_package);
|
||||
let sem = semantics(from_package[1].1);
|
||||
assert_eq!(resolution(&sem, from_package[1].1, "missing_t s"), Resolution::NotFound);
|
||||
assert!(!in_overlay(&sem, &ws, from_package[1].1, "missing_t s"));
|
||||
assert!(external_defs(&sem, &ws, from_package[1].1, "missing_t s").is_empty());
|
||||
|
||||
let from_class = [
|
||||
decoy,
|
||||
(
|
||||
"top.sv",
|
||||
"class base;\nendclass\nclass top extends base;\nendclass\nmodule m;\n top::missing_t s;\nendmodule\n",
|
||||
),
|
||||
];
|
||||
let ws = index(&from_class);
|
||||
let sem = semantics(from_class[1].1);
|
||||
assert_eq!(
|
||||
resolution(&sem, from_class[1].1, "missing_t s"),
|
||||
Resolution::InheritedCandidate { base: "base".to_string(), paths: Vec::new() },
|
||||
"no paths at all: nothing for the overlay to try"
|
||||
);
|
||||
assert!(!in_overlay(&sem, &ws, from_class[1].1, "missing_t s"));
|
||||
assert!(external_defs(&sem, &ws, from_class[1].1, "missing_t s").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_position_miss_is_never_promoted_even_onto_a_same_named_unit() {
|
||||
// The twin of `an_unqualified_type_miss_carries_its_own_name_to_the_unit
|
||||
// _table`, and the fence the fix round exists for. The same word, the same
|
||||
// workspace, the only difference being where it is written: a type window
|
||||
// is a claim about a declaration somewhere, a bare expression identifier
|
||||
// is not. So this one keeps its pre-promotion spelling, the overlay is
|
||||
// never asked, and `rename` goes on refusing it (QA finding 1, 2026-08-26).
|
||||
let sources = [
|
||||
("typo_name.sv", "module typo_name;\nendmodule\n"),
|
||||
("top.sv", "module top;\n assign typo_name = 1'b1;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[1].1);
|
||||
|
||||
assert_eq!(resolution(&sem, sources[1].1, "typo_name = 1"), Resolution::NotFound);
|
||||
assert!(!in_overlay(&sem, &ws, sources[1].1, "typo_name = 1"));
|
||||
assert!(external_defs(&sem, &ws, sources[1].1, "typo_name = 1").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_position_miss_inside_an_extending_class_gains_no_path_either() {
|
||||
// The twin of `a_miss_inside_an_extending_class_is_answered_without
|
||||
// _losing_its_base`. An inherited candidate from a *value* position is
|
||||
// exactly what it was before the promotion: its base and nothing else, so
|
||||
// the sweep has nothing to try and the overlay records nothing — even
|
||||
// though the workspace does declare a unit of that name.
|
||||
let sources = [
|
||||
("held.sv", "interface held;\nendinterface\n"),
|
||||
(
|
||||
"env.sv",
|
||||
"class env extends uvm_object;\n function void f();\n held = 1;\n endfunction\nendclass\n",
|
||||
),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[1].1);
|
||||
|
||||
assert_eq!(
|
||||
resolution(&sem, sources[1].1, "held = 1"),
|
||||
Resolution::InheritedCandidate { base: "uvm_object".to_string(), paths: Vec::new() },
|
||||
"no paths: a value position is offered nothing to sweep"
|
||||
);
|
||||
assert!(!in_overlay(&sem, &ws, sources[1].1, "held = 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_declaration_of_a_promoted_name_still_wins() {
|
||||
// The promotion happens only after the lexical walk gives up, so a name
|
||||
// this file declares never reaches the workspace at all.
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\nendinterface\n"),
|
||||
("top.sv", "module top;\n typedef logic bus_if;\n bus_if bus;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[1].1);
|
||||
|
||||
assert!(matches!(resolution(&sem, sources[1].1, "bus_if bus"), Resolution::Resolved(_)));
|
||||
assert!(!in_overlay(&sem, &ws, sources[1].1, "bus_if bus"));
|
||||
match resolve_external(&sem, &ws)
|
||||
.definition_of(&sem, sources[1].1.find("bus_if bus").expect("needle") as u32)
|
||||
{
|
||||
Some(Definition::Local(sym)) => assert_eq!(sym.kind, SymbolKind::Typedef),
|
||||
other => panic!("expected the local typedef, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_that_can_supply_the_name_still_wins_over_a_same_named_unit() {
|
||||
// Order matters: the bare name goes last, so a package member reached
|
||||
// through an import is preferred over a workspace unit that happens to
|
||||
// share the name. That is the pre-promotion answer, kept.
|
||||
let sources = [
|
||||
("pkg.sv", "package tdp;\n typedef logic [1:0] state_t;\nendpackage\n"),
|
||||
("decoy.sv", "module state_t;\nendmodule\n"),
|
||||
("top.sv", "module top;\n import tdp::*;\n state_t s;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[2].1);
|
||||
|
||||
assert_eq!(
|
||||
resolution(&sem, sources[2].1, "state_t s"),
|
||||
Resolution::ExternalCandidate { paths: vec!["tdp::*".to_string(), "state_t".to_string()] }
|
||||
);
|
||||
let defs = external_defs(&sem, &ws, sources[2].1, "state_t s");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
assert_eq!(defs[0].kind, SymbolKind::Typedef, "the package's typedef, not the decoy module");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Corpus acceptance
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -441,7 +708,8 @@ fn the_corpus_index_finishes_most_external_references() {
|
||||
let (tree, diags) = parse_source_tolerant(src);
|
||||
let sem = analyze(&tree, src);
|
||||
let overlay = resolve_external(&sem, &ws);
|
||||
let mut file_tally = Tally { references: sem.references().len(), ..Tally::default() };
|
||||
let (in_file, references) = sem.resolution_counts();
|
||||
let mut file_tally = Tally { references, in_file, ..Tally::default() };
|
||||
for (id, target) in overlay.iter() {
|
||||
let reference = sem.reference(id).expect("id came from the overlay");
|
||||
let name = &reference.name;
|
||||
@@ -486,10 +754,17 @@ struct Tally {
|
||||
/// Every reference the single-file layer recorded, external or not — the
|
||||
/// denominator the vlog-semantic baseline reports percentages against.
|
||||
references: usize,
|
||||
/// The ones it resolved on its own, which the workspace layer never sees.
|
||||
in_file: usize,
|
||||
total: usize,
|
||||
resolved: usize,
|
||||
ambiguous: usize,
|
||||
unresolved: usize,
|
||||
/// Answers for references the single-file layer left as
|
||||
/// `InheritedCandidate` — the bucket overlay-promotion added. Counted
|
||||
/// separately because they are a *bonus*: an inherited candidate is not
|
||||
/// an external one and only appears here when the sweep landed.
|
||||
inherited: usize,
|
||||
/// Unresolved import path → how many uses it left open, and one example
|
||||
/// name each: the honest-gaps report.
|
||||
misses: std::collections::BTreeMap<String, (usize, String)>,
|
||||
@@ -498,6 +773,7 @@ struct Tally {
|
||||
impl Tally {
|
||||
fn count(&mut self, target: &ExternalTarget, reference: &vlog_semantic::Reference) {
|
||||
self.total += 1;
|
||||
self.inherited += usize::from(reference.is_inherited_candidate());
|
||||
match target {
|
||||
ExternalTarget::Resolved(_) => self.resolved += 1,
|
||||
ExternalTarget::Ambiguous(_) => self.ambiguous += 1,
|
||||
@@ -515,10 +791,12 @@ impl Tally {
|
||||
|
||||
fn merge(&mut self, other: &Tally) {
|
||||
self.references += other.references;
|
||||
self.in_file += other.in_file;
|
||||
self.total += other.total;
|
||||
self.resolved += other.resolved;
|
||||
self.ambiguous += other.ambiguous;
|
||||
self.unresolved += other.unresolved;
|
||||
self.inherited += other.inherited;
|
||||
for (path, (n, example)) in &other.misses {
|
||||
let entry = self.misses.entry(path.clone()).or_insert((0, example.clone()));
|
||||
entry.0 += n;
|
||||
@@ -529,20 +807,30 @@ impl Tally {
|
||||
self.resolved + self.ambiguous
|
||||
}
|
||||
|
||||
/// References with nowhere at all to jump: neither layer answered them.
|
||||
/// The one number that must never rise — the buckets above it move
|
||||
/// between themselves whenever a miss changes its spelling.
|
||||
fn nowhere(&self) -> usize {
|
||||
self.references - self.in_file - self.answered()
|
||||
}
|
||||
|
||||
fn report(&self, label: &str) {
|
||||
let pct = |n: usize, of: usize| 100.0 * n as f64 / of.max(1) as f64;
|
||||
println!(
|
||||
"{label}: {} references, {} external candidates ({:.1}%) — the workspace answers \
|
||||
{:.1}% of them ({:.1}% one target, {:.1}% ambiguous), {:.1}% still unresolved. \
|
||||
External-candidate rate after the workspace layer: {:.1}% of all references.",
|
||||
"{label}: {} references, {} handed to the workspace layer ({:.1}%, of which {} \
|
||||
inherited candidates) — it answers {:.1}% of them ({:.1}% one target, {:.1}% \
|
||||
ambiguous), {:.1}% still unresolved. Nowhere to jump after both layers: \
|
||||
{} references, {:.1}% of all.",
|
||||
self.references,
|
||||
self.total,
|
||||
pct(self.total, self.references),
|
||||
self.inherited,
|
||||
pct(self.answered(), self.total),
|
||||
pct(self.resolved, self.total),
|
||||
pct(self.ambiguous, self.total),
|
||||
pct(self.unresolved, self.total),
|
||||
pct(self.unresolved, self.references),
|
||||
self.nowhere(),
|
||||
pct(self.nowhere(), self.references),
|
||||
);
|
||||
let mut top: Vec<(&String, &(usize, String))> = self.misses.iter().collect();
|
||||
top.sort_by(|a, b| b.1 .0.cmp(&a.1 .0).then(a.0.cmp(b.0)));
|
||||
|
||||
@@ -0,0 +1,401 @@
|
||||
# ansi-first-port
|
||||
|
||||
## Goal
|
||||
|
||||
An ANSI module header whose **first** port carries no direction did not parse:
|
||||
`module m (bus_if bus, input logic clk);` became an `Error` item, and so did
|
||||
`module m (bus_if.mp bus);` and `module m (my_pkg::state_t s);`. IEEE 1800
|
||||
§23.2.2.2 makes the direction optional on every ANSI port including the first
|
||||
(it defaults to `inout`, and to whatever the previous port wrote for a
|
||||
continuation port), and for an *interface* port there is no direction to write
|
||||
at all — `bus_if bus` is the only spelling there is. This round closes that
|
||||
gap: the port list is classified ANSI-or-not by what follows the first
|
||||
identifier rather than by the identifier alone, and an interface port may name
|
||||
its modport. It was filed as Handshake request 2 of
|
||||
`docs/features/type-definition/README.md`, whose interface-port tests had to
|
||||
write the port *second* to have anything to test.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A first port spelled `ident ident` is a type and a name, never two
|
||||
non-ANSI port names.** SystemVerilog has no port list in which two
|
||||
identifiers stand side by side without a separator, so the pair is
|
||||
unambiguous. The non-ANSI list is exactly the case where the first
|
||||
identifier is followed by `,` or `)`, and that is what the disambiguation
|
||||
tests for — through the same lookahead (`at_typed_declarator`) that already
|
||||
decides `pkg::my_t x` from `x[i] = 1` everywhere else in the parser.
|
||||
- **A `.` after an identifier is a member access everywhere except a port
|
||||
header.** That is why `bus_if.mp bus` is recognized in `parse_ansi_port` and
|
||||
not in `parse_opt_data_type`: making the general type parser accept a dotted
|
||||
name would change how an identifier is read in expression and declaration
|
||||
positions, which is far more than this gap asks for. `virtual bus_if.mp v;`
|
||||
(a modport-qualified *virtual interface*, legal per §25.9) is therefore
|
||||
still not parsed — see Status.
|
||||
- **A modport belongs in the type name, glued.** `DataType::name` already
|
||||
carries `pkg::state_t` glued, and every consumer prints or scans that one
|
||||
string; `bus_if.mp` follows the same rule, so no consumer needed a new
|
||||
field. The one place the two halves matter is `vlog_semantic`, which binds
|
||||
the interface half (below).
|
||||
- **A modport is not a symbol.** `ItemKind::Modport` is a leaf in
|
||||
`vlog_semantic` (it declares nothing into a scope), so the modport half of
|
||||
the type name is left unbound rather than recorded as a name that could
|
||||
never resolve. The day modports become symbols, the tail is where to bind
|
||||
them.
|
||||
- **`module m (interface bus);`** — the *generic* interface port, whose type
|
||||
is the `interface` keyword itself — is a separate production and still does
|
||||
not parse. It is neither one of the three shapes filed nor reachable from
|
||||
them; deliberately out of scope (Status).
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Changed in `vlog_parser` (`crates/vlog_parser/src/parser.rs`):**
|
||||
|
||||
- `parse_port_list`'s ANSI/non-ANSI classification now also answers "ANSI" for
|
||||
a leading `Ident` that begins a typed declarator (`at_typed_declarator`,
|
||||
which already looks past a `pkg::` chain, a `#( ... )` override and packed
|
||||
dimensions) or a modport-qualified port (`at_modport_port`). Every other
|
||||
input classifies exactly as before — a macro token is `TokenKind::Directive`
|
||||
and never `Ident`, and a name followed by `,`/`)` is still a non-ANSI list.
|
||||
- `parse_ansi_port` takes `bus_if.mp` as the port's type via the new
|
||||
`at_modport_port` / `parse_modport_port_type` pair.
|
||||
- **No AST change.** The new shapes are ordinary `AnsiPort`s with
|
||||
`dir: None` — the value a non-first direction-less port has always carried —
|
||||
so `PortList`, `AnsiPort` and `DataType` are byte-identical to what
|
||||
downstream already handles. `AnsiPort::ty.name` is the one field that can
|
||||
now contain a `.`.
|
||||
|
||||
**Changed in `vlog_semantic` (`crates/vlog_semantic/src/bind.rs`):**
|
||||
|
||||
- `bind_data_type`'s unqualified arm binds the half of the type name before a
|
||||
`.` (`bus_if` of `bus_if.mp`) as `Target::Type`, instead of using the glued
|
||||
string as a name. The ANSI-port call site (`bind_module`, `bind.rs:393`) is
|
||||
unchanged: the type window is still "start of the port → start of its name",
|
||||
which is exactly right for a port that writes no direction.
|
||||
|
||||
**Changed in `lucisv_server` (`crates/lucisv_server/src/type_def.rs`):**
|
||||
|
||||
- `type_span` matches a site's type name by the half before its `.` as well as
|
||||
by its last `::` segment, so the cursor on a modport-qualified port reaches
|
||||
the interface. See that feature's work log.
|
||||
|
||||
**Consumed, unchanged:** `vlog_formatter` prints `AnsiPort` through
|
||||
`ansi_port_cells`/`data_type`, which write `ty.name` verbatim — a glued
|
||||
modport round-trips with no formatter change. `vlog_refactor`'s
|
||||
`instantiate::ansi_ports` reads the port's *source text* between its start and
|
||||
its name, so it reports `iface_bus.mst` as the type with no change either.
|
||||
|
||||
**Requested of other modules:** nothing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Reproduce all three shapes as `Error` items before changing anything.
|
||||
- [x] `parse_port_list`: classify a leading `ident ident` / `ident :: ident
|
||||
ident` / `ident . ident ident` as ANSI.
|
||||
- [x] `parse_ansi_port`: the modport-qualified interface port.
|
||||
- [x] `bind_data_type`: bind the interface half of a dotted type name.
|
||||
- [x] `type_def::type_span`: match it back.
|
||||
- [x] 9 parser tests, 7 formatter table cases, 1 semantic binding test, 2
|
||||
server tests, 2 refactor tests (one flipped, one new).
|
||||
- [x] Corpus before/after: identical, with every file's formatted output
|
||||
byte-identical (below).
|
||||
- [x] Handshake 2 struck in `docs/features/type-definition/README.md`; the
|
||||
stale annotation in `TODO.md` §9c corrected.
|
||||
- [ ] **Not done, deliberately: `module m (interface bus);`** — the generic
|
||||
interface port (IEEE 1800 §25.3), whose type is the `interface` keyword
|
||||
itself. It is a different production, none of the three filed shapes
|
||||
needs it, and it wants a `DataType` that can say "any interface", which
|
||||
is a modelling question this round should not answer in passing.
|
||||
- [ ] **Not done, deliberately: `virtual bus_if.mp v;`** — a modport-qualified
|
||||
virtual interface in a *declaration* (§25.9). Reaching it means teaching
|
||||
`parse_opt_data_type` about the dot, which changes how an identifier is
|
||||
read in every position; it needs its own round and its own attack tests.
|
||||
- [ ] **Not done, pre-existing: `module m (a[3], b);`** — a non-ANSI port with
|
||||
a bit-select. It failed before this round and fails identically after
|
||||
(pinned by `a_broken_header_still_reports_its_own_token`), and it is not
|
||||
what this gap was about.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent
|
||||
|
||||
- **Reproduced first, and the filed report was accurate to the token.** A
|
||||
throwaway `parse_source_tolerant` harness (removed after use) gave, for the
|
||||
three shapes: `expected ")" (found "bus")`, `expected ")" (found ".")`,
|
||||
`expected ")" (found "::")` — each producing two `Error` items, the header
|
||||
and the orphaned `endmodule`. It also turned up two facts the report did not
|
||||
state and the fix had to account for: `my_pkg::state_t s` already parsed in
|
||||
a *non-first* position (`at_typed_declarator` walks `::` chains), while
|
||||
`bus_if.mp bus` parsed in **no** position at all — so the modport is a
|
||||
second, independent gap that merely looked like part of the first.
|
||||
- **The disambiguation is a lookahead, not a new grammar.** `parse_port_list`
|
||||
classified the list from its first token: a direction keyword, a type
|
||||
keyword or a net keyword meant ANSI, anything else meant a non-ANSI name
|
||||
list. The fix adds one clause — a leading `Ident` that `at_typed_declarator`
|
||||
says still leaves an identifier for the declarator name. That predicate
|
||||
already exists and is already the parser's answer to "type-then-name or
|
||||
something else", including past `pkg::`, `#( ... )` and packed dimensions;
|
||||
reusing it means the header list cannot drift out of step with how a body
|
||||
declaration is read. The complement is exactly the non-ANSI list: after the
|
||||
first name comes a `,` or a `)`, neither of which is an identifier.
|
||||
- **The modport is glued into the type name, and only in a port header.**
|
||||
`interface_port_header ::= interface_identifier [ . modport_identifier ]` is
|
||||
a port production, not a data-type production, and after an identifier
|
||||
anywhere else a `.` opens a member access — so `at_modport_port` /
|
||||
`parse_modport_port_type` sit in `parse_ansi_port`, four tokens of lookahead
|
||||
wide (`ident . ident ident`), and `parse_opt_data_type` is untouched. Gluing
|
||||
follows the `pkg::state_t` precedent, which is what kept the AST, the
|
||||
formatter and `vlog_refactor` out of this change entirely.
|
||||
- **`vlog_semantic` binds the interface, not the glued string.** Left alone,
|
||||
`bind_data_type` would have recorded a use of the name `bus_if.mp`, which
|
||||
resolves nowhere and never could. It now takes the half before the dot. The
|
||||
modport half is dropped rather than bound because this crate declares no
|
||||
symbol for a modport (`ItemKind::Modport` is a leaf, `bind.rs:364`) — a
|
||||
reference to a name nothing can declare is worse than no reference.
|
||||
- **`type_def::type_span` needed the mirror of that.** The server matches a
|
||||
declaration site's type name against the references the binder left in the
|
||||
same window; with the site saying `bus_if.mp` and the reference saying
|
||||
`bus_if`, the match failed and the jump answered nothing. One line: match by
|
||||
the half before the `.` too, alongside the existing "last `::` segment"
|
||||
rule.
|
||||
- **No AST change, which was the point.** The brief asked whether `AnsiPort`
|
||||
already models absence of direction — it does (`dir: Option<String>`), and
|
||||
every continuation port (`input a, b`) has carried `dir: None` since the
|
||||
beginning. So the new shapes produce AST that every existing consumer was
|
||||
already written for, and the whole downstream cost of this round was two
|
||||
match widenings (one in `vlog_semantic`, one in `lucisv_server`) that exist
|
||||
only because of the modport dot.
|
||||
- **Snapshot churn: none.** `crates/vlog_formatter/tests/snapshots/` is
|
||||
untouched, and `git diff --stat` shows no fixture file changed. No
|
||||
previously-refused fixture started formatting, so there was nothing to
|
||||
justify.
|
||||
- **Corpus: identical, which is itself the finding.** Baseline (HEAD 0e740d7,
|
||||
the change stashed) and after: `813/820 (99.1%)`, 11 ok-unchanged, 802
|
||||
would-reformat, 7 parse-error, 0 verification-error, 0 crash — and the two
|
||||
TSVs are byte-identical, path for path, message for message. To prove the
|
||||
stronger property the TSV does not carry, every corpus file was formatted to
|
||||
stdout and hashed on both sides: all 820 hashes identical. So the passing
|
||||
set is a (trivially strict) superset, no file's output moved by a byte, and
|
||||
the safety net never fired. The reason nothing was gained is that this
|
||||
corpus contains no direction-less first port at all — had it contained one,
|
||||
that file would have been a `parse-error` row before and a formatted one
|
||||
after; the 7 that remain are the known macro-bracketed covergroup, the
|
||||
`` ` ``-number lex error and friends, unchanged. `vlog_semantic`'s corpus
|
||||
acceptance run agrees from the other side: 860 files, 561 modules, 94685
|
||||
references, 88.8% of external candidates answered — identical to three
|
||||
decimal places before and after, so no previously-`Error` module header
|
||||
joined the index either.
|
||||
- **Tests.** `vlog_parser` +9 (`parser.rs` tests module): the three shapes,
|
||||
each alone and mixed with directed ports in both orders; an `interface`
|
||||
header taking the same list; a typed first port with packed dimensions and
|
||||
a parameterized one; the non-ANSI list pinned by name *and* by comma flags,
|
||||
plus the one-name list; `module m ();` and `module m;`; the `input a, b`
|
||||
direction carry-over; a macro-produced list, an escaped name and a comment
|
||||
before the comma, all three still non-ANSI because the clause fires only on
|
||||
a `TokenKind::Ident`; and recovery on two genuinely broken headers plus a
|
||||
never-closed one through `parse_source_tolerant`.
|
||||
`vlog_formatter` +7 table cases in `tests/cases/module_headers.cases`
|
||||
(each is an idempotency and equivalence assertion too — `format_source`
|
||||
verifies both, and the harness re-formats the expected output).
|
||||
`vlog_semantic` +1 (`tests/workspace.rs`):
|
||||
`a_direction_less_first_ansi_port_binds_its_interface_type_cross_file`,
|
||||
both spellings, cross-file through the unit table, plus an assertion that
|
||||
the port declarations themselves survived.
|
||||
`lucisv_server` +2 and one flipped (`type_def.rs`, now 47).
|
||||
`vlog_refactor`: `an_interface_typed_port_list_is_refused_as_a_parse_failure`
|
||||
→ `an_interface_typed_port_list_is_planned_like_any_other` (it asserted the
|
||||
gap; it now asserts the plan, the rendered skeleton and that the skeleton
|
||||
parses), and +1 rename test through a direction-less first port.
|
||||
- **Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets
|
||||
--workspace`: 0 warnings. `cargo test --workspace`: green (0 failed
|
||||
anywhere; `vlog_parser` 214, `lucisv_server` 873). `cargo test -p
|
||||
vlog_formatter`: green, all 8 targets, no snapshot churn.
|
||||
`tools/corpus_check.sh` before and after: identical, exit 0 both times.
|
||||
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`. No `git commit`, no `git push`; `docs/site/` untouched.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent
|
||||
|
||||
**Gates, re-run independently — all matched the dev's claim exactly.**
|
||||
`cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace`:
|
||||
0 warnings. `cargo test --workspace`: green, `vlog_parser` 214 passed,
|
||||
`lucisv_server` 873 passed / 4 ignored (the 4 ignored are pre-existing in
|
||||
`lucisv_server::{hierarchy,includes,inlay}`, unrelated to this round).
|
||||
`cargo test -p vlog_formatter --all-targets`: green, 7 test binaries run
|
||||
(`lib`, `cases`, `deep_nesting`, `fences`, `fixtures`, `ranges`,
|
||||
`verification`) — the work log's "all 8 targets" is one over the actual
|
||||
binary count; cosmetic, not a gate failure. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
**Corpus proof — reproduced independently, not taken on the dev's word.**
|
||||
Built release binaries at the working tree and at a `git worktree add` of
|
||||
`0e740d7` (the round's parent commit) so the working tree was never stashed.
|
||||
`tools/corpus_check.sh corpus`: `813/820 (99.1%)` on both binaries, and the
|
||||
two TSVs are byte-identical (`diff` exit 0) — this also matches the dev's own
|
||||
`corpus-check-results.tsv` left in the tree byte-for-byte. Then, independent
|
||||
of the TSV, every one of the 820 corpus files was formatted with `--stdout`
|
||||
and SHA-256 hashed under both binaries: **all 820 hashes identical.** This is
|
||||
the round's central safety claim and it now has two independent
|
||||
confirmations (the dev's and this one), not one.
|
||||
|
||||
**A. Classification-boundary sweep** (`vlog_parser::parse_source_tolerant`,
|
||||
current tree vs. the `0e740d7` worktree, diffed on `{diagnostics, debug AST}`):
|
||||
|
||||
| shape | verdict |
|
||||
|---|---|
|
||||
| `module m (a, b);` | unaffected, byte-identical AST (non-ANSI, untouched) |
|
||||
| `module m (a);` | unaffected, byte-identical AST |
|
||||
| `module m (mytype a);` | now ANSI, `ty.name="mytype"` — correct |
|
||||
| `module m (a[3:0] b);` | now ANSI, packed dim consumed correctly |
|
||||
| `module m (a #(8) b);` | now ANSI, `#(...)` consumed correctly |
|
||||
| `module m (a.b);` (3-token, closes) | **unaffected** — `at_modport_port` needs a 4th `Ident` after the dotted name and correctly does not fire on `)`; still the same `expected ")" (found ".")` error both sides |
|
||||
| `module m (a.b.c d);` (5-token) | **unaffected** — the lookahead is exactly 4 tokens wide (`ident . ident ident`), a longer dotted chain does not match `at_modport_port`, so this still errors identically both sides (an underdocumented but correctly-failing edge, not a misfire) |
|
||||
| `module m (bus_if.mp bus, foo.bar baz);` (modport non-first) | now parses — confirms the work log's claim that `at_modport_port` fires per-port in `parse_ansi_port`, not just at list-classification, so any `ident.ident` port anywhere in an ANSI list now parses, not only `bus_if.mp` specifically |
|
||||
| `module m (my_pkg::t.mp bus);` (`pkg::type` + modport dot) | **unaffected, fails safe** — neither `at_typed_declarator` nor `at_modport_port` fires (the `::`-chain walk stops before a bare `.`), so this still reports `expected ")" (found "::")` on both sides. Not filed, not tested by the dev, but does not misfire — worth a line in Assumptions if this shape is ever revisited |
|
||||
| directive before first port, then a direction-less port (`` `ifdef FOO `endif bus_if bus, input logic clk); ``) | parses correctly — `take_list_directives` already peels the directive off before the ANSI/non-ANSI decision reads the next token, independent of this round's change |
|
||||
|
||||
**No misfire found in either direction**: nothing that used to be a non-ANSI
|
||||
list started parsing as ANSI, and no shape swallowed characters it should not
|
||||
have.
|
||||
|
||||
**B. Formatter round-trip.** All boundary and headline shapes above were run
|
||||
through `format_source` (`vlog_formatter::format_source`); every one that
|
||||
parses returned `Ok` (i.e. both `verify_equivalence` and `verify_convergence`
|
||||
passed internally — the safety net never fired). The three headline shapes'
|
||||
formatted output matches `module_headers.cases` byte-for-byte. `module m (a,
|
||||
b); input a; output b; endmodule` and `module m (a); input a; endmodule`
|
||||
(non-ANSI) format byte-identically between the `0e740d7` binary and the
|
||||
working-tree binary. No real corpus file with an old-style bare-name port list
|
||||
was found to spot-check against (consistent with the dev's note that this
|
||||
corpus has no such file) — the in-memory comparison above is the substitute.
|
||||
|
||||
**C. `bind_data_type` / `type_span` modport handling — attacked, holds.**
|
||||
Added one test, `renaming_the_modport_half_of_a_port_type_is_refused` in
|
||||
`crates/vlog_refactor/tests/rename.rs` (kept; passes; +1 to `vlog_refactor`'s
|
||||
rename suite, 52 total): a rename request positioned on the `mp` of `bus_if.mp
|
||||
bus` is refused (`rename()` returns `Err`) rather than silently renaming the
|
||||
interface or corrupting the modport spelling — confirming `ItemKind::Modport`
|
||||
being an unbound leaf actually protects the rename path, not just the
|
||||
go-to-type-definition path. Renaming `bus_if` itself through the same port
|
||||
still renames correctly (already covered by the dev's
|
||||
`an_interface_renames_through_a_direction_less_ansi_port`).
|
||||
|
||||
**D. Error recovery — two diagnostic-drift findings, not corruption.**
|
||||
Severity: low. The claim "error recovery unchanged" holds for the two
|
||||
specific fixtures the dev pinned (`module m (input, );` — confirmed
|
||||
byte-identical diagnostics and AST both sides) but **does not hold** for one
|
||||
of the exact shapes named in this round's own attack brief:
|
||||
|
||||
- `module m (foo bar` (never closes, no `endmodule`) — file:
|
||||
`crates/vlog_parser/src/parser.rs`, the `ansi` lookahead added at the
|
||||
`parse_port_list` classification site (~line 2415) plus `parse_ansi_port`
|
||||
(~line 2494). Baseline: `expected ")" (found "bar")` at line 1 col 15.
|
||||
Current: `expected ")" (found "<eof>")` at line 2 col 1. Cause: `foo bar` is
|
||||
now recognized as a typed declarator (`at_typed_declarator` fires), so the
|
||||
parser commits to consuming it as one `AnsiPort` and only then looks for the
|
||||
next `,`/`)`, which is past EOF instead of at the second identifier.
|
||||
- `module m (bus_if bus;` and `module m (bus_if bus\nendmodule\n)` — same
|
||||
cause: baseline reports the error at the second identifier (`bus`, since it
|
||||
reads `bus_if` alone as a non-ANSI name and then chokes on a second
|
||||
identifier); current reports it at the token *after* the successfully
|
||||
parsed `bus_if bus` port (`;` or `endmodule` respectively). The dev's own
|
||||
test (`a_broken_header_still_reports_its_own_token`) only asserts
|
||||
`!diags.is_empty()` for the never-closed case, not a specific position, so
|
||||
this drift does not contradict any committed test — it contradicts the
|
||||
QA-brief's framing of "same error positions/recovery as baseline", which is
|
||||
not literally true for any genuinely-broken header that happens to start
|
||||
with two adjacent identifiers.
|
||||
- In every case checked, the file still ends up as a single `Error(RawText)`
|
||||
item over the same span with the same raw text on both sides — no partial
|
||||
output, no corruption, invariant #1 holds. This is a diagnostic-quality
|
||||
regression at worst (arguably the new position is more precise, since it
|
||||
points at the actual unexpected token rather than the first token past a
|
||||
guessed name), not a safety issue. No fix applied; recorded for the lead's
|
||||
judgment on whether the work log's phrasing needs softening.
|
||||
|
||||
**E. Fuzz-ish sweep.** 50 corpus files with an ANSI first port whose leading
|
||||
direction keyword (`input`/`output`/`inout`) was stripped, re-parsed through
|
||||
`parse_source_tolerant` under `catch_unwind`: **0 panics**. 23 re-parsed
|
||||
clean (the stripped port had a real type after the keyword, e.g. `input logic
|
||||
clk` → `logic clk`, and the new classification correctly reads it as a
|
||||
direction-less typed port). 27 still report a parse error (the stripped port
|
||||
was just `input a` → bare `a`, which correctly falls back to non-ANSI
|
||||
classification and then fails on the *next* port's leading keyword with a
|
||||
sensible `expected identifier (found "input")` — fails safe, not a crash, not
|
||||
a silent misparse).
|
||||
|
||||
**F. The three left-open items.** `module m (a[3], b);` is pinned by
|
||||
`a_broken_header_still_reports_its_own_token`, confirmed unchanged (matches
|
||||
the dev's specific pinning claim — this is the only one of the three the dev
|
||||
actually claimed a test for). `module m (interface bus);` (generic interface
|
||||
port) and `virtual bus_if.mp v;` (modport-qualified virtual interface
|
||||
declaration) are **not** pinned by any test anywhere in the diff, but both
|
||||
were confirmed byte-identical (diagnostics + AST) between `0e740d7` and the
|
||||
working tree by the same harness as section A. Recommendation, not a blocker:
|
||||
a one-line regression test for each would close the gap between "verified
|
||||
today" and "protected going forward," since neither has a test to catch a
|
||||
future regression.
|
||||
|
||||
**G. CLAUDE.md compliance.** `crates/vlog_formatter/src/verify.rs`: `git diff
|
||||
--stat` shows no change — invariant #4 correctly not triggered (no
|
||||
normalization was widened, so no masked-corruption attack tests were owed).
|
||||
`unwrap()`/`expect()`/`panic!`: the only three `panic!`s added are inside
|
||||
`crates/vlog_parser/src/parser.rs`'s `#[cfg(test)] mod tests` (test-helper
|
||||
`ansi_ports`/list-shape assertions) — permitted, not library-path code.
|
||||
`at_modport_port` and `parse_modport_port_type` both have doc comments.
|
||||
`docs/features/ansi-first-port/README.md` has each required section exactly
|
||||
once, in the required order. The `type-definition` feature's Handshake 2 is
|
||||
struck with `~~...~~` and a "Delivered 2026-08-26" annotation, matching this
|
||||
repo's existing struck-handshake convention. `docs/site/` was not touched.
|
||||
|
||||
**Not independently verifiable:** the work log's `vlog_semantic` corpus
|
||||
figure ("860 files, 561 modules, 94685 references, 88.8%... identical to
|
||||
three decimal places before and after") has no corresponding script under
|
||||
`tools/` and no committed test that reproduces it — unlike the
|
||||
`vlog_formatter` corpus proof (section above), which was fully reproduced.
|
||||
Not flagged as a defect (the two headline corpus proofs this round rests on
|
||||
are independently confirmed), just noted as an unverifiable secondary claim.
|
||||
|
||||
**Fix made:** added
|
||||
`renaming_the_modport_half_of_a_port_type_is_refused` to
|
||||
`crates/vlog_refactor/tests/rename.rs` (section C above). No other changes to
|
||||
the diff under review.
|
||||
|
||||
**Verdict: committable as-is.** No hard-invariant violation found (no
|
||||
corruption, comments-preservation and idempotency untouched, `verify.rs`
|
||||
untouched). One low-severity, non-blocking finding (D: diagnostic-position
|
||||
drift on genuinely-broken headers, which the lead may want reflected in the
|
||||
work log's phrasing) and two documentation/test-coverage gaps (the
|
||||
unpinned left-open items in F, and the unreproducible semantic-corpus figure)
|
||||
are recorded for follow-up, not for blocking this round.
|
||||
|
||||
## Review
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. For the highest-invariant-risk crate in the repo, this round set
|
||||
the standard: reproduction before any fix (which surfaced that the
|
||||
modport shape was a second, independent gap), a classification clause
|
||||
built on the parser's own existing lookahead rather than a new
|
||||
recognizer, no AST change, and the corpus proof taken past the TSV to
|
||||
all 820 formatted-output hashes — which QA then re-established
|
||||
independently through a worktree build rather than trusting it. The
|
||||
boundary AST-diff harness and the 50-file direction-stripping sweep are
|
||||
exactly the adversarial coverage a parser change needs.
|
||||
|
||||
Rulings on QA's three notes. The diagnostic-position shift on broken
|
||||
two-identifier headers is accepted: the parser committing further
|
||||
before failing is inherent to recognizing the new legal prefix, no
|
||||
Error item's span or text moved, and better commitment usually means
|
||||
better messages. The two unpinned left-open items are now pinned — I
|
||||
added `the_two_shapes_left_open_by_ansi_first_port_still_refuse` to the
|
||||
parser suite so a future round changes them on purpose. The
|
||||
unreproducible vlog_semantic corpus figure is a fair point filed
|
||||
against that README's tooling, not this round; the workspace harness
|
||||
tests remain the executable check. QA's modport-rename refusal test
|
||||
closes the one write-path question the match-widenings raised.
|
||||
Accepted as shipped.
|
||||
@@ -0,0 +1,215 @@
|
||||
# apply-edit
|
||||
|
||||
## Goal
|
||||
|
||||
Make the three port commands actually edit something in a stock editor.
|
||||
`workspace/executeCommand` used to answer with the `WorkspaceEdit` that
|
||||
`ports::execute` computed, as the request's *result*. The protocol defines no
|
||||
such thing: an `executeCommand` result is `any | null`, and a client applies
|
||||
what a server **pushes** at it with `workspace/applyEdit`.
|
||||
`vscode-languageclient` (which `editors/vscode/extension.js` uses unmodified)
|
||||
drops the result on the floor, and so does Neovim's built-in client — so
|
||||
`lucisv.addPort`, `lucisv.removePort` and `lucisv.propagatePorts` invoked *as
|
||||
commands* did nothing at all in every stock client. (The code-action path was
|
||||
never affected: a code action carries its edit inline.) This round pushes the
|
||||
edit, answers `null`, and reads the one client response the server can no
|
||||
longer ignore.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`workspace.applyEdit` is the gate.** A client that advertised it gets the
|
||||
push and a `null` result. A client that did not gets exactly the old
|
||||
behavior — the edit as the result — because for that one it is the only
|
||||
thing that could ever work, and a silent no-op is worse than a
|
||||
non-standard answer that some caller may yet read. Both VS Code and Neovim
|
||||
advertise it; `editors/vscode/smoke.js` sends `capabilities: {}` and so
|
||||
takes the fallback, which is why it still passes untouched.
|
||||
- **The push goes out before the command's own response.** The loop sends a
|
||||
request's response when the handler returns, and the handler sends the
|
||||
`applyEdit` request during it. The protocol allows a server to make a
|
||||
request at any time, and a client that waited for the command result before
|
||||
applying the edit would deadlock against any server that does this — VS
|
||||
Code and Neovim both apply immediately. Stated here because it is the
|
||||
ordering a reader would otherwise wonder about.
|
||||
- **A refusal is worth a popup.** `ApplyWorkspaceEditResponse.applied: false`
|
||||
means the user ran a command, watched nothing happen, and has no other way
|
||||
to find out why. It is shown as an ERROR naming the command, plus the
|
||||
client's own `failureReason` when it sent one. Success says nothing.
|
||||
- **A response that does not parse is a refusal.** Nothing was seen to be
|
||||
applied, so the honest thing is to say so rather than assume the best.
|
||||
- **Watcher (un)registration answers stay ignored.** Their ids are never in
|
||||
the pending map, so they fall straight through the new handler — including
|
||||
an error response, which is what a client that refuses to watch sends. The
|
||||
behavior `docs/features/file-watching/README.md` documents is unchanged.
|
||||
- **No retry, no timeout.** A client that never answers leaves one entry in
|
||||
the pending map for the life of the session; three port commands per
|
||||
session is not a leak worth a timer, and the server has no timers by
|
||||
design.
|
||||
- **The `report_scope(warnings)` behavior is unchanged** — the engine's
|
||||
warnings are still surfaced exactly as before, whichever delivery path the
|
||||
edit takes.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `ClientAbilities` gains `apply_edit: bool` and derives `Default`, so a test
|
||||
can name only the ability it cares about. `main.rs` fills it from
|
||||
`InitializeParams.capabilities.workspace.apply_edit`.
|
||||
- `Server` gains `applying: HashMap<RequestId, String>` — the outstanding
|
||||
`workspace/applyEdit` requests, each remembering the command that asked.
|
||||
- `Server::send_request` now **returns** the `RequestId` it sent on. The
|
||||
watcher registration ignores it, exactly as it ignores the answer.
|
||||
- `run`'s `Message::Response(_) => {}` becomes `self.response(response)`.
|
||||
- `ExecuteCommand` goes through the new `Server::deliver`.
|
||||
|
||||
### `ports`
|
||||
|
||||
`ports::execute`'s signature is unchanged; only the doc comment's claim that
|
||||
"the server does not push `workspace/applyEdit`" is now false, and is
|
||||
rewritten. No engine behavior changed.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
**No extension change.** `vscode-languageclient` applies `workspace/applyEdit`
|
||||
requests itself; `extension.js` has no custom `executeCommand` handling and
|
||||
needs none. Verified by reading, not assumed.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `workspace.applyEdit` read into `ClientAbilities` at initialize
|
||||
- [x] `Server::deliver`: push the edit with a `label`, answer `null`
|
||||
- [x] `Server::response`: match answers to outstanding requests, report a
|
||||
refusal as an ERROR naming the command
|
||||
- [x] Return-the-edit fallback kept for a client that cannot apply
|
||||
- [x] Tests: pushed-and-null, fallback-returns-the-edit, refusal reported,
|
||||
success silent, duplicate/unknown answer ignored, watcher answer still
|
||||
ignored
|
||||
- [ ] Not done, deliberately: no `$/progress` or timeout on an unanswered
|
||||
`applyEdit` — see Assumptions.
|
||||
- [ ] Not done, deliberately: `WorkspaceEdit` still carries plain `changes`
|
||||
(no `documentChanges`, no snippet edits). That is TODO §9c's item, and
|
||||
it would improve `addPort` cursor placement.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9a
|
||||
|
||||
- **`deliver` is a method on `Server`, not a free function**, because it has
|
||||
to both send a request and remember its id; splitting it would have meant
|
||||
returning a request for the caller to send, which is a shape with one user.
|
||||
- **`send_request` returning the id** was the smallest change that let the
|
||||
applyEdit path record it. The two watcher call sites ignore the value; a
|
||||
`RequestId` is not `#[must_use]`, so this stays silent.
|
||||
- **The pending map is keyed by `RequestId`, not by command**, so two
|
||||
commands in flight cannot be confused and a duplicate answer to a spent id
|
||||
does nothing. Pinned by
|
||||
`an_edit_the_editor_applied_is_said_nothing_about`'s second half.
|
||||
- **The `label`** is `lucisv: <command>` — it is what an editor shows on its
|
||||
undo stack, so it names the thing the user would want to undo.
|
||||
- Files touched: `crates/lucisv_server/src/server.rs`,
|
||||
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`, and
|
||||
`ports.rs`'s stale doc comment (it claimed the server does not push
|
||||
`workspace/applyEdit`). `editors/vscode/extension.js` was read and
|
||||
deliberately left alone.
|
||||
|
||||
**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings),
|
||||
`cargo test --workspace`, `node editors/vscode/smoke.js` — all clean. 5 new
|
||||
unit tests in `server.rs` (plus the watcher-answer guard), 1 in `main.rs`, and
|
||||
one e2e session (`a_command_pushes_its_edit_to_a_client_that_can_apply_one`)
|
||||
that pushes the edit at a real binary and answers it as an editor would.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent, §9a
|
||||
|
||||
**Re-ran the dev's verification, clean.** `cargo fmt --all -- --check`,
|
||||
`cargo clippy --all-targets --workspace` (zero warnings, forced a rebuild by
|
||||
touching the changed files first so the check was not answered from a stale
|
||||
cache), `cargo test --workspace` (3 full runs, no failures), `node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server` (exit 0) — all reproduced
|
||||
independently.
|
||||
|
||||
**Read the diff against the README's claims,** file:line references against
|
||||
the working tree as it stood before this QA pass:
|
||||
|
||||
- `server.rs`'s `ExecuteCommand` handler (around what is now line 304) calls
|
||||
`self.report_scope(warnings)` unconditionally in the `Ok` arm, before
|
||||
`self.deliver(...)` branches on the ability — confirmed **both** the push
|
||||
and the fallback path surface engine warnings identically.
|
||||
- **RequestId collision, checked and ruled out.** `applying` and the watcher
|
||||
(un)registration ids are both minted by the same `send_request`, whose
|
||||
counter (`self.request_ids`) is a single monotonically increasing `u32`
|
||||
shared across every call site — two ids can never collide, so a watcher
|
||||
answer can never land in `applying` and vice versa. This is structural,
|
||||
not incidental: there is exactly one counter to break for a collision to
|
||||
become possible.
|
||||
- `ports.rs`'s doc comment rewrite matches the new behavior; no engine
|
||||
behavior changed there, confirmed by reading `execute`'s body (untouched
|
||||
except the comment).
|
||||
|
||||
**Attacked the response-routing path** (`server.rs::response`, the
|
||||
`ApplyWorkspaceEditResponse` deserialization). The existing tests covered
|
||||
`Ok(applied: true)`, `Ok(applied: false, failureReason)`, a duplicate answer,
|
||||
and a watcher answer — but not the two cases the doc comment explicitly
|
||||
claims to handle: a response payload that is `Ok` JSON but does not
|
||||
deserialize as `ApplyWorkspaceEditResponse` at all, and a JSON-RPC-level
|
||||
`Err` response (a client that rejects the request outright rather than
|
||||
answering it). Added both as tests in `server.rs`:
|
||||
|
||||
- `a_malformed_apply_edit_answer_is_reported_as_a_refusal` — answers with
|
||||
`{"notApplied": "whatever"}` (no `applied` field, which is required with no
|
||||
default in `lsp_types::ApplyWorkspaceEditResponse`); asserts one ERROR
|
||||
naming the command, not a panic and not silence.
|
||||
- `a_response_with_a_jsonrpc_error_is_reported_too` — uses
|
||||
`Response::new_err` directly; asserts the `error.message` reaches the
|
||||
shown text.
|
||||
|
||||
Both pass. Confirms the "a response that does not parse is a refusal"
|
||||
assumption is real code, not just a comment.
|
||||
|
||||
**Found and fixed one self-inflicted test bug while adding the above:** the
|
||||
first draft of `a_malformed_apply_edit_answer_is_reported_as_a_refusal` named
|
||||
its tree `propagating("malformed", ...)`, which collides with the *existing*
|
||||
`Tree::new("malformed")` in
|
||||
`a_malformed_watched_files_notification_is_dropped` — both resolve to the
|
||||
same `std::env::temp_dir()` path (keyed only by pid + name), so running the
|
||||
suite in parallel raced the two tests' filesystem setup and made
|
||||
`ports::execute` fail to find `sub.sv` (`server.rs`, originally around line
|
||||
1417 in this session's numbering). Not a server bug — a QA-test-authoring
|
||||
bug. Renamed to `"malformedapplyedit"`; reran the full `lucisv_server` suite
|
||||
three times back to back with no failures. Worth a general note for future
|
||||
dev/QA agents: `Tree::new`'s temp path is name-keyed, not test-keyed, so a
|
||||
tree name must be checked for uniqueness across the whole crate, not just
|
||||
the tests being added.
|
||||
|
||||
**Capability reading:** `apply_edit_support` reads
|
||||
`params.capabilities.workspace.as_ref().and_then(|w| w.apply_edit)` —
|
||||
verified this cannot panic on `InitializeParams::default()` or any partial
|
||||
capability object; already covered by
|
||||
`apply_edit_support_is_read_from_the_clients_own_capabilities`, re-ran it
|
||||
directly.
|
||||
|
||||
**CLAUDE.md compliance:** grepped the new/changed lines in `server.rs`,
|
||||
`main.rs`, `ports.rs` for `.unwrap()`, `.expect()`, `panic!` outside
|
||||
`#[cfg(test)]` — none found. Public items added (`ClientAbilities::apply_edit`)
|
||||
carry doc comments. README has all seven required sections; TODO.md's
|
||||
checkbox is checked with the item text unchanged and a `→` pointer added.
|
||||
|
||||
**Verdict: no blocking findings.** The two new attack tests and the
|
||||
tree-name-collision fix are the only changes made to this feature's code.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full
|
||||
workspace suite/smoke.js myself, all clean. The design is right: the gate is
|
||||
the client's own `workspace.apply_edit` capability, the fallback is exactly
|
||||
the old behavior for exactly the clients the old behavior could serve, and
|
||||
the pending-map keyed by the one shared id counter makes response routing
|
||||
collision-free by construction (QA verified the same). The `deliver`
|
||||
doc comment's deadlock note is a good catch worth keeping. The no-timeout
|
||||
decision is accepted: three commands per session cannot leak meaningfully,
|
||||
and the server has no timers by design. `ports.rs`'s previously-false doc
|
||||
comment is now true. Accepted as shipped.
|
||||
@@ -0,0 +1,533 @@
|
||||
# cancel-request
|
||||
|
||||
## Goal
|
||||
|
||||
`$/cancelRequest` is the client's way of saying "drop that one, the user has
|
||||
moved on" — sent constantly by real editors, which cancel the completion,
|
||||
hover and inlay-hint requests of the previous keystroke on every new one.
|
||||
Until now the notification fell through `Server::notification`'s `_ => {}` arm
|
||||
and the request was computed and answered anyway. This round answers a
|
||||
cancelled request with the protocol's own `RequestCancelled` (-32800) instead
|
||||
of computing it, whenever the cancel reaches the loop in time — which, on a
|
||||
single-threaded server, means *while the request is still queued*. The gain is
|
||||
not correctness (an ignored cancel is legal) but work not done: on a slow
|
||||
rescan or a large-file format, the queue behind the busy handler is exactly
|
||||
where a stale completion request sits, and answering it costs nothing (TODO.md
|
||||
§9b, the last item of that section).
|
||||
|
||||
## What "in time" can mean on a one-message-at-a-time loop
|
||||
|
||||
Everything about this feature follows from one fact: **the client sends the
|
||||
request and its cancel down one ordered channel**, and the server handles one
|
||||
message at a time. Read strictly one message per iteration, a cancel is always
|
||||
too late — by the time `C(R)` is dequeued, `R` was dequeued, computed and
|
||||
answered an iteration ago. Cancellation only becomes reachable when the loop
|
||||
looks at *more than one message at a time*: while a handler runs, the client
|
||||
keeps sending, so the backlog waiting behind it can hold `[R1, C(R1), R2]` —
|
||||
and R1 can be answered `RequestCancelled` for free.
|
||||
|
||||
So `run()` now works in bursts:
|
||||
|
||||
1. block for the next message, as before;
|
||||
2. take everything already queued behind it, without blocking, into one FIFO
|
||||
(the blocked-for message first);
|
||||
3. scan that whole burst for `$/cancelRequest` notifications and collect the
|
||||
ids that name a request **in the same burst**;
|
||||
4. handle the burst strictly in arrival order — a cancelled request answered
|
||||
`RequestCancelled` without dispatch, every other message exactly as before.
|
||||
|
||||
Step 3 is what keeps the cancelled set from being state: it is built per burst
|
||||
and dropped with it.
|
||||
|
||||
### The transport does not queue — so we do
|
||||
|
||||
The first attempt used `connection.receiver.try_recv()` for step 2 and
|
||||
cancelled **nothing** over a real pipe. The reason is worth writing down,
|
||||
because it is invisible from the API:
|
||||
|
||||
> `lsp-server` 0.10's stdio transport wires its reader, writer and dropper
|
||||
> threads with **`crossbeam_channel::bounded(0)`** — rendezvous channels with
|
||||
> no capacity at all (`stdio.rs`). Its reader thread parks *inside* `send`
|
||||
> holding one message until the loop takes it. A client's backlog therefore
|
||||
> never sits on `connection.receiver`: it sits in the OS pipe, one message
|
||||
> deep from where we stand, and `try_recv` right after a `recv` loses a
|
||||
> microsecond-scale race with the reader thread essentially every time.
|
||||
|
||||
`Server::queue()` fixes this with the smallest thing that can: one forwarder
|
||||
thread that blocks on `connection.receiver` and pushes onto an unbounded
|
||||
`std::sync::mpsc` queue that `run()` owns. The backlog then accumulates where
|
||||
we can see it, and step 2 is a plain `try_recv` loop. The thread touches no
|
||||
server state, moves messages and nothing else, and is std-only — no new
|
||||
dependency.
|
||||
|
||||
The forwarder **stops at the `shutdown` request and never reads past it**.
|
||||
`Connection::handle_shutdown` answers the request and then reads the `exit`
|
||||
notification off the *connection* itself; a forwarder that kept going would
|
||||
take that `exit` first, and `handle_shutdown` would block for its full
|
||||
thirty-second timeout and then return a protocol error. Stopping there also
|
||||
means nothing after a shutdown is ever queued, which is exactly the protocol's
|
||||
own rule.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Cancellation is best-effort, and the spec says so.** LSP allows a server
|
||||
to ignore a cancel it cannot honour; the only hard requirement is that every
|
||||
request gets exactly one response. Both are held here: a cancel that misses
|
||||
its window leaves the request answered normally.
|
||||
- **A cancel arriving in a *later* burst than its request is dropped.** By
|
||||
then the request has been answered — there is nothing left to cancel, and
|
||||
remembering the id would be a set that grows for the life of the session.
|
||||
This is the single rule that keeps this feature stateless.
|
||||
- **A cancel in the same burst but dequeued *before* its request still
|
||||
cancels it.** The burst is scanned as a whole before any of it runs, so
|
||||
ordering within the burst does not matter. (A real client never sends the
|
||||
cancel first; a transport is free to make it look that way.)
|
||||
- **A cancel for a request the server never received is dropped** where it is
|
||||
read, for the same reason.
|
||||
- **Cancelling one request twice is harmless.** The id is removed from the
|
||||
cancelled set as it is used, so a second cancel finds nothing — and it could
|
||||
not touch a later request even if ids were reused, because the set never
|
||||
outlives its burst.
|
||||
- **`shutdown` is never cancellable.** `handle_shutdown` runs before the
|
||||
cancelled set is consulted, so a cancel naming the shutdown id cannot stop
|
||||
the server from shutting down. The spec's "a server should still answer a
|
||||
cancelled request" reading is the safe one here: a client that cannot shut
|
||||
its server down leaks a process.
|
||||
- **Notifications are never cancelled.** They carry no id and get no
|
||||
response; `$/cancelRequest` names request ids only. A `didChange` queued
|
||||
ahead of a cancelled request is still applied — the state a *later* request
|
||||
is answered against must not depend on which requests were dropped.
|
||||
- **Order inside a burst is the invariant, not an implementation detail.**
|
||||
A `didChange` the client sent before a completion request must be in effect
|
||||
when that completion is answered, exactly as it would be one message at a
|
||||
time. Pinned by
|
||||
`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`.
|
||||
- **Both id forms are read.** `CancelParams.id` is
|
||||
`NumberOrString`; a numeric id becomes `RequestId::from(i32)` and a string
|
||||
id `RequestId::from(String)`. The string `"8"` is not the number `8` —
|
||||
`RequestId` keeps them apart and so does the cancel, which is the only
|
||||
behaviour that can be right when a client uses both forms.
|
||||
- **A cancel whose params do not parse is dropped**, on the same reasoning as
|
||||
every other malformed notification: there is no id to act on and no id to
|
||||
answer on.
|
||||
- **The cancelled response carries a message.** `-32800` plus
|
||||
`"lucisv: request cancelled by the client"`. Clients do not show it — the
|
||||
code is what they read — but a log with the text in it is easier to read
|
||||
than a log with a number in it.
|
||||
- **Nothing already *running* is cancelled.** There is one thread; a format,
|
||||
a rescan or a rename that has started runs to completion. The work-done
|
||||
progress bar still advertises `cancellable: false`, which stays true.
|
||||
- **The queue is unbounded.** Backpressure on the pipe used to be the reader
|
||||
thread's rendezvous; now a burst is buffered in memory instead. For an LSP
|
||||
client that is bounded by what an editor sends between two of our handler
|
||||
calls — kilobytes. A client that floods a server faster than it can read
|
||||
would grow this queue, and would equally have grown the pipe before.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::server` (this feature's own module)
|
||||
|
||||
- `Server::run` no longer receives-and-dispatches inline. It builds the queue,
|
||||
blocks on it, and hands each burst to `process_batch`. Behaviour for a
|
||||
client that never cancels is identical, message for message.
|
||||
- **New private items:** `Server::queue()` (the forwarder),
|
||||
`Server::process_batch(Vec<Message>) -> Result<bool, …>` (the burst
|
||||
handler; `true` means the client shut us down), and the free functions
|
||||
`burst`, `is_shutdown`, `cancelled_in`, `cancelled_id`, `cancelled_response`.
|
||||
- `Server::request`, `Server::notification` and `Server::response` are
|
||||
**unchanged**. `$/cancelRequest` never reaches `notification()`; it is
|
||||
consumed in the burst handler, which is the only place that can act on one.
|
||||
- No field was added to `Server`. Cancellation state lives for the length of
|
||||
one burst and no longer.
|
||||
|
||||
### `lsp-server`
|
||||
|
||||
- Consumed, not changed: `Connection.receiver` is now `clone()`d (crossbeam
|
||||
receivers are `Clone`), and `handle_shutdown` is called exactly where it was
|
||||
— the forwarder's stop rule is what keeps its `exit` read working.
|
||||
- The rendezvous-channel finding above is a property of version `=0.10.0`,
|
||||
which the workspace pins. A future bump should re-read `stdio.rs`: if the
|
||||
transport ever queues, `Server::queue` becomes redundant rather than wrong.
|
||||
|
||||
### Every other crate, and `editors/vscode`
|
||||
|
||||
**Untouched.** No engine crate knows this happened, and no client capability
|
||||
gates it — `$/cancelRequest` is unconditional in the protocol, advertised by
|
||||
nobody and sent by everybody. `smoke.js` passes unchanged (run as a gate).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `run()` restructured into blocking receive → burst drain → burst handler
|
||||
- [x] Forwarder thread so the backlog is observable at all (the rendezvous
|
||||
finding), stopping at `shutdown` so `handle_shutdown` keeps its `exit`
|
||||
- [x] Cancelled ids collected per burst, matched against that burst's own
|
||||
requests, dropped otherwise
|
||||
- [x] Cancelled requests answered `-32800` without dispatch; the cancels
|
||||
themselves consumed
|
||||
- [x] `shutdown` honoured before any cancel is consulted
|
||||
- [x] Arrival order preserved across the whole burst (notifications included)
|
||||
- [x] Numeric and string cancel ids; malformed cancels dropped
|
||||
- [x] Tests: 10 unit in `server.rs` (through the `Session` harness, driving
|
||||
the real `process_batch`), 1 e2e over the wire
|
||||
- [x] TODO.md §9b checkbox; loop description in
|
||||
`docs/features/lucisv-server/README.md`
|
||||
- [ ] **Not done, deliberately:** no cancellation of work in flight. That
|
||||
needs a worker pool and cancellation tokens threaded through the engine
|
||||
— TODO.md §6's explicit non-goal for as long as per-file recompute stays
|
||||
in the millisecond range.
|
||||
- [ ] **Not done, deliberately:** no `ContentModified` (-32801) for requests
|
||||
invalidated by a `didChange` queued behind them. It is the neighbouring
|
||||
idea and a real option now that the loop can see a burst, but the spec
|
||||
warns that an answer computed against slightly older text is usually
|
||||
still useful — and the client, not the server, is the one that knows.
|
||||
Filed here, not built.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent (§9b, `$/cancelRequest`)
|
||||
|
||||
- Read `CLAUDE.md`, `docs/features/lucisv-server/README.md`, TODO.md §9b and
|
||||
the whole of `server.rs`'s loop before touching anything.
|
||||
- **Verified the lead's design against the code, and found one thing that
|
||||
invalidated its second step.** The plan said to drain `connection.receiver`
|
||||
non-blockingly with `try_iter`/`try_recv`. Written that way, the e2e flood
|
||||
cancelled **zero** of five requests, reproducibly. `lsp-server` 0.10's
|
||||
`stdio.rs` uses `bounded(0)` rendezvous channels throughout: there is no
|
||||
queue on that receiver to drain, ever. The rest of the design — burst FIFO,
|
||||
batch-wide cancel scan, drop-if-not-in-batch, order preserved, shutdown
|
||||
never cancellable — is unchanged and implemented as written.
|
||||
- **Fix: one forwarder thread** (`Server::queue`) onto a `std::sync::mpsc`
|
||||
queue, so the backlog accumulates somewhere observable. Std-only, no new
|
||||
dependency, no shared state, ~12 lines. Considered and rejected: a timed
|
||||
drain window (`recv_timeout(1ms)`), which would tax *every* message with a
|
||||
millisecond of latency and still be a race; and handling shutdown ourselves
|
||||
to free the forwarder, which would duplicate `handle_shutdown`'s protocol
|
||||
for no gain.
|
||||
- **The forwarder's stop-at-shutdown rule was found by reading
|
||||
`handle_shutdown`, not by a failing test**: it reads `exit` off the
|
||||
connection itself, so an eager forwarder would have stolen it and turned
|
||||
every shutdown into a 30-second timeout followed by a protocol error. The
|
||||
rule is asserted by `a_shutdown_is_honoured_however_it_is_cancelled` and by
|
||||
the e2e session, which shuts down through the same flood.
|
||||
- Tests: 10 unit tests in `server.rs`, driving the real `process_batch`
|
||||
through a new `Session::batch` helper (the harness otherwise bypasses the
|
||||
loop entirely), plus `Session::answers()` for reading responses off the
|
||||
client end. One e2e test running the real binary and the real `run()`.
|
||||
- **The e2e test asserts what is deterministic, and says why.** Three
|
||||
iterations were needed to get there: with cheap requests, *how many* cancels
|
||||
land in the same burst as their request is a scheduling race, and demanding
|
||||
all five failed roughly one full-suite run in four (the suite runs 38
|
||||
server processes in parallel). The final shape floods twenty
|
||||
`textDocument/formatting` requests over a 300-line buffer — enough work per
|
||||
message that the forwarder is never starved — and asserts the properties
|
||||
that must hold on any schedule: exactly one response per request, `-32800`
|
||||
only ever on an id the client actually cancelled, a correct formatted answer
|
||||
on every other id, at least one honoured cancel (the wire path works), and
|
||||
a clean shutdown. Measured under a deliberate 24-way overload: worst case
|
||||
two of five honoured, never zero.
|
||||
- Also corrected two now-stale comments about cancellation being absent
|
||||
entirely — the module header of `server.rs`, `begin_indexing`'s note on
|
||||
`cancellable: false`, and the matching line in the progress e2e test. The
|
||||
bar's `false` stays correct: what has *started* still runs to completion.
|
||||
- Gates, all clean: `cargo fmt --all -- --check`, `cargo clippy --all-targets`
|
||||
(no warnings), `cargo test --workspace` (34 suites green; `lucisv_server`
|
||||
702 unit + 38 e2e), `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` → OK. The e2e suite was re-run ten consecutive
|
||||
times looking for flake: ten passes.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent (§9b, `$/cancelRequest`)
|
||||
|
||||
**Verdict: committable as-is.** No corruption, no protocol violation, no
|
||||
reproducible flake found. Four gaps in test coverage for the highest-risk
|
||||
part of the change (the forwarder thread) were found and closed directly;
|
||||
one theoretical (not reproduced) flake risk in the e2e flood is recorded
|
||||
below with a reasoned trade-off, not "fixed," because the fixes available
|
||||
would weaken the property the test exists to prove.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets`
|
||||
clean, no warnings. `cargo test --workspace`: every suite green, including
|
||||
`lucisv_server` at 706 unit (was 702 pre-QA; +4 added below) + 38 e2e.
|
||||
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` →
|
||||
OK. `cargo test -p lucisv_server --test e2e` run five more times standalone,
|
||||
before the QA-added tests and five more times after: **10/10 green**, no
|
||||
flake observed in the flood test or anywhere else in the suite.
|
||||
|
||||
**1. Forwarder shutdown hand-off — verified clean, by reading
|
||||
`lsp-server` 0.10's actual source, not the dev's summary.**
|
||||
|
||||
- Read `~/.cargo/registry/.../lsp-server-0.10.0/src/stdio.rs`,
|
||||
`src/lib.rs` (`Connection::handle_shutdown`, `Connection::memory`) and
|
||||
`src/msg.rs` (`Request::is_shutdown`, `Notification::is_exit`,
|
||||
`Response`'s `#[serde(flatten)]` encoding). Confirms the README's claim:
|
||||
the stdio reader thread parks inside a `bounded(0)` `send` until taken,
|
||||
so a client's backlog really does live in the OS pipe and not on
|
||||
`connection.receiver`.
|
||||
- (a) **Method-name detection, and the notification case.** `is_shutdown`
|
||||
(`crates/lucisv_server/src/server.rs:1119`) matches
|
||||
`Message::Request { method == "shutdown" }` only — the same test
|
||||
`lsp-server`'s own `Request::is_shutdown` (msg.rs:233) uses. A
|
||||
**notification** shaped like `{"method":"shutdown"}` fails the match
|
||||
(wrong enum variant), so the forwarder does not stop for it; it is
|
||||
forwarded like any other message and falls through `notification()`'s
|
||||
`_ => {}` arm, doing nothing. This was asserted by nothing before QA —
|
||||
added `is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`
|
||||
(server.rs:3574). A malformed shutdown-*request* (e.g. non-null params)
|
||||
is not a distinct case: neither `is_shutdown` nor `handle_shutdown`
|
||||
parses params, only the method name, so there is nothing to be
|
||||
malformed.
|
||||
- (b) **The stolen-message / deadlock window.** Traced the forwarder
|
||||
(`Server::queue`, server.rs:209-233): it checks `is_shutdown` on the
|
||||
message **after** receiving it but **before** issuing its next `recv()`,
|
||||
and breaks its loop without calling `recv()` again when that check is
|
||||
true. `handle_shutdown` (lsp-server lib.rs:348) is only reached by
|
||||
`process_batch` for a request already sitting in the batch Vec — i.e.
|
||||
after the forwarder that produced it has already returned from its last
|
||||
`sender.send`. Because the forwarder's own break happens strictly before
|
||||
any further receive, there is no window where both the forwarder and
|
||||
`handle_shutdown` are calling `recv`/`recv_timeout` on the same
|
||||
crossbeam channel at once — no steal, no deadlock. Added
|
||||
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`
|
||||
(server.rs:3632), which sends a real shutdown request + exit notification
|
||||
through a `Connection::memory()` pair, calls the real `Server::queue()`,
|
||||
and asserts (i) the shutdown is the last thing the forwarder ever
|
||||
forwards even after 50ms of extra opportunity to misbehave, and (ii) the
|
||||
`exit` is still sitting, unread, directly on `connection.receiver` —
|
||||
exactly where `handle_shutdown` looks for it. This is the one test in
|
||||
the whole suite that exercises the real `queue()` method without going
|
||||
through a subprocess.
|
||||
- (c) **Messages already forwarded ahead of a shutdown in the same
|
||||
batch.** Because the forwarder always stops immediately after
|
||||
forwarding the message it detects as shutdown, shutdown is provably
|
||||
always the *last* message that forwarder instance ever produces — there
|
||||
is no way for a message to be forwarded *after* shutdown by the same
|
||||
producer, and there is only ever one producer (next point). So the
|
||||
scenario "a request forwarded after shutdown gets silently dropped" is
|
||||
not reachable through this code path. Nothing found here; the design
|
||||
note in the feature README (lines 63-69) undersells this a little by
|
||||
only mentioning the *thirty-second timeout* consequence of an eager
|
||||
forwarder — the actual structural guarantee (shutdown is always last)
|
||||
is worth knowing but the doc isn't wrong, just less complete than it
|
||||
could be. Not fixed (doc-only, not a code finding, and rewriting
|
||||
someone else's README section is not QA's job per CLAUDE.md).
|
||||
|
||||
**2. Message loss/reordering — verified clean.**
|
||||
|
||||
- Exactly one producer: `Server::queue` is called exactly once, from
|
||||
`Server::run` (server.rs:185), which is itself called exactly once, from
|
||||
`main.rs:76`. No respawn path exists.
|
||||
- Single channel used throughout: `run`'s blocking head-of-burst read and
|
||||
`burst`'s non-blocking drain (server.rs:1126) both operate on the same
|
||||
`std::sync::mpsc::Receiver` returned by `queue()` — never a mix of the
|
||||
mpsc and `connection.receiver` on the consuming side. (`connection.receiver`
|
||||
itself is only ever touched by the forwarder's `source` handle and by
|
||||
`handle_shutdown`, never by `run`/`burst`/`process_batch`.)
|
||||
- Exactly-once processing: `burst` pushes the blocking-received `first`
|
||||
plus everything `try_recv` drains, with no filtering or dedup step in
|
||||
between — the FIFO in equals the FIFO out. Added
|
||||
`burst_collects_everything_already_queued_in_arrival_order`
|
||||
(server.rs:3602) directly against a fresh
|
||||
`std::sync::mpsc` channel (no `Server` involved), pinning arrival order
|
||||
for `[first, second, third]`. Previously `burst` had zero direct test
|
||||
coverage — every existing cancel test drives `process_batch` through
|
||||
`Session::batch`, bypassing `burst` entirely, so this was a real gap in
|
||||
a change the assignment calls "the highest-risk this repo's server has
|
||||
taken."
|
||||
|
||||
**3. `exit` handling / zombie-thread check — verified clean.**
|
||||
|
||||
- `talk()` (e2e.rs:66-79) and the progress-e2e session's own `finish()`
|
||||
(e2e.rs:1978-1985) both call `child.wait()` and assert
|
||||
`status.success()` — a hung forwarder or a process that doesn't
|
||||
terminate would hang or fail these, and none did across 10 e2e runs.
|
||||
This is a real check, not a rubber stamp: `child.wait()` blocks until
|
||||
the OS reports the process gone, so a genuinely undead forwarder thread
|
||||
(blocked on stdin, holding the process open) would show up as a test
|
||||
timeout, not a silent pass.
|
||||
- The forwarder thread is detached (`let _ = ... .spawn(...)`), never
|
||||
joined. This is fine for process exit: after `shutdown`+`exit`, the
|
||||
forwarder has *already* stopped itself (point 1b) well before `run()`
|
||||
returns, so by the time `main()` returns there is no thread left
|
||||
blocked on I/O that could hold the process open. In the one edge case
|
||||
where a client disconnects without ever sending `shutdown` (broken
|
||||
pipe), the forwarder's own `source.recv()` errors, it drops its `sender`
|
||||
and exits, closing the mpsc and unblocking `run()`'s own `recv()` the
|
||||
same way `self.connection.receiver.recv()` used to unblock pre-diff —
|
||||
behaviorally identical to the old direct-receive loop for that case.
|
||||
Not a new finding; equivalent to prior behavior.
|
||||
|
||||
**4. Cancellation semantics matrix — re-verified independently, assertions
|
||||
read (not just names), all pass; one gap closed.**
|
||||
|
||||
Read every assertion, not just the test name, for: same-burst
|
||||
cancel-after (`a_request_cancelled_in_the_same_burst_is_answered_cancelled`),
|
||||
cancel-before (`a_cancel_dequeued_before_its_request_still_cancels_it`),
|
||||
partial-batch cancel (`a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone`),
|
||||
orphan/late drop with the id-reuse proof
|
||||
(`a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot`),
|
||||
notification-ordering
|
||||
(`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`),
|
||||
notifications-uncancellable (`a_cancel_never_cancels_a_notification`),
|
||||
shutdown-uncancellable (`a_shutdown_is_honoured_however_it_is_cancelled`),
|
||||
double cancel (`cancelling_one_request_twice_answers_it_once`), int-vs-string
|
||||
ids including the `"8"` vs `8` case (`a_cancel_id_may_be_a_number_or_a_string`),
|
||||
and malformed params (`a_malformed_cancel_is_dropped_rather_than_guessed_at`).
|
||||
Every one asserts what its name claims; none was a false-positive
|
||||
(no-op) test. All pass, independently re-run.
|
||||
|
||||
**Gap found and closed:** no test covered a cancel naming a
|
||||
**server-initiated** id (the `lucisv-0`/`lucisv-index-N`/`lucisv-watched-files-N`
|
||||
namespace from `Server::send_request`, server.rs:949). Traced it: `cancelled_in`
|
||||
(server.rs:1141) only ever matches a cancel against ids of `Message::Request`
|
||||
entries *received in the same batch* — a server-initiated id only ever
|
||||
appears on the wire as a `Message::Response` coming back from the client,
|
||||
a different match arm in `process_batch` entirely, never consulted against
|
||||
`cancelled`. So interference is not possible by construction. Added
|
||||
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
|
||||
(server.rs:3682) to pin this rather than leave it as an inference:
|
||||
it calls the real `send_request`, gets back `lucisv-0`, sends a cancel
|
||||
naming it alongside an ordinary client request, asserts the client request
|
||||
is untouched, and then answers the server-initiated request successfully
|
||||
to prove routing was never disturbed.
|
||||
|
||||
**5. `-32800` on the wire — verified, one assertion added.**
|
||||
|
||||
`cancelled_response` (server.rs:1171) uses
|
||||
`lsp_server::ErrorCode::RequestCanceled as i32`, which is `-32800` in
|
||||
`msg.rs:128` — matches spec. `Response`'s `#[serde(flatten, with =
|
||||
"ResponseResult")]` (lsp-server msg.rs:87-98) serializes to exactly one of
|
||||
`result`/`error`, never both — confirmed by reading the encoding, and by
|
||||
the e2e flood's existing `answer.get("result").is_none()` on a real wire
|
||||
response (e2e.rs:3141). Id-type preservation (int in → int in response) is
|
||||
implicitly covered by the flood test's own matching: it filters
|
||||
`messages.iter().filter(|m| m["id"] == id)` against a Rust `u32`, which
|
||||
would find nothing if the id had round-tripped as a string, and the test
|
||||
asserts exactly one match per id. **Gap found and closed:** nothing
|
||||
asserted that the error carried a non-empty `message` string, only that
|
||||
`code` was right and `result` was absent. Added that assertion in-line at
|
||||
e2e.rs (next to the `result`-absence check in
|
||||
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each`).
|
||||
|
||||
**6. The e2e flood's honesty — one theoretical, unreproduced flake risk,
|
||||
documented rather than "fixed."**
|
||||
|
||||
Read the whole test (e2e.rs:3079-3168). The `honoured > 0` assertion
|
||||
(e2e.rs:3160) is the one the
|
||||
task flagged as suspicious, correctly. Reasoning:
|
||||
|
||||
- The forwarder thread and the main loop's request handling run
|
||||
concurrently on real OS threads. While the main thread is inside a
|
||||
synchronous `self.request(...)` call (formatting), the forwarder can
|
||||
keep draining the reader thread's rendezvous handoffs into the mpsc
|
||||
queue in parallel — this concurrency, not any timer, is what makes a
|
||||
multi-message burst likely.
|
||||
- It is **not mathematically impossible** for every burst to end up size
|
||||
1: a scheduler that always preempts the forwarder thread and lets the
|
||||
main thread fully drain-and-reblock before the next message is
|
||||
forwarded would produce zero cancellations, every time, for any finite
|
||||
request count. No such interleaving was produced in 10 standalone e2e
|
||||
runs plus one full `cargo test --workspace` run (which itself runs the
|
||||
e2e binary), so it is not a *practical* risk today, but "never observed"
|
||||
is exactly the "≠ impossible" the task named.
|
||||
- **Why not fixed:** the two available code fixes both make the test
|
||||
worse. Relaxing `honoured > 0` to `honoured >= 0` (i.e., deleting the
|
||||
assertion) would stop the test from ever proving the cancellation path
|
||||
works over the real wire at all — the one thing this e2e test exists to
|
||||
check per its own doc comment. Adding a synchronization point (e.g. a
|
||||
test-only delay hook) to force a burst would add production-code
|
||||
surface *purely for a test's benefit*, which the "simplicity first"
|
||||
section of `CLAUDE.md` weighs against, for a risk that is theoretical
|
||||
and has a fallback: a failure here is a flake in one non-gating-by-flake
|
||||
test, not a correctness bug (the request would still be answered
|
||||
correctly once instead of cancelled — see point 4's stateless-drop
|
||||
behavior — so no invariant breaks, only the "never zero" assertion
|
||||
would).
|
||||
- **Recommendation:** accept the residual risk as-is. If it is ever
|
||||
observed to flake in CI, the fix is almost certainly to widen the
|
||||
buffer/request count further (the dev already tuned this once, from a
|
||||
~1-in-4 flake rate with cheap requests down to zero observed in 10+ runs
|
||||
with 300 lines / 20 requests) rather than to touch the assertion itself.
|
||||
|
||||
**7. CLAUDE.md compliance — verified clean.**
|
||||
|
||||
- No bare `std::thread::spawn` (which panics on OS resource exhaustion).
|
||||
The forwarder uses `std::thread::Builder::new().spawn(...)`
|
||||
(server.rs:215), which returns `io::Result`, and the error is
|
||||
deliberately discarded with `let _ =` plus a comment explaining the
|
||||
fallback (the mpsc sender is dropped, so `run()`'s `recv()` fails and
|
||||
the loop ends cleanly instead of hanging) — no panic path introduced.
|
||||
This is in `main`-path server setup, which CLAUDE.md's "Tests and
|
||||
`main.rs` argument handling may use them" carve-out does not literally
|
||||
name, but the *effect* is a `Result`-returning call whose error is
|
||||
handled without panicking or unwrapping — no rule is broken; there is
|
||||
no `unwrap`/`expect`/`panic!` in this path at all.
|
||||
- All `.expect(...)`/`.unwrap()` calls introduced by the diff (checked
|
||||
with `git diff | grep`) are inside `mod tests` (`Session::batch`,
|
||||
`symbol_names`, `outcomes`, and the shutdown test's `sender.send(...)`)
|
||||
— allowed.
|
||||
- New free functions and the new `Server` methods all carry one-line-plus
|
||||
doc comments explaining what/why, consistent with the surrounding file's
|
||||
density; none of the new items are `pub`, so the strict "public items"
|
||||
rule doesn't even apply, but the dev exceeded it anyway.
|
||||
- `docs/features/cancel-request/README.md`: each of the seven required
|
||||
sections (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log,
|
||||
Review) appears **exactly once** (checked with `grep -n "^## "`); one
|
||||
extra explanatory section between Goal and Assumptions is additional,
|
||||
not a duplicate, and the template doesn't forbid it.
|
||||
- `TODO.md`: the §9b item's original text
|
||||
("**`$/cancelRequest`** — the loop handles requests sequentially and
|
||||
ignores cancellation; at minimum answer already-cancelled queued
|
||||
requests with `RequestCancelled`.") is byte-for-byte intact; only the
|
||||
checkbox flipped and a `→`-prefixed summary line was appended below it,
|
||||
which is the same pattern used by the 9 other completed items already
|
||||
in the file (`grep -c` confirms 10 occurrences total including this
|
||||
one) — not a one-off deviation.
|
||||
- `docs/features/lucisv-server/README.md` was also touched by this
|
||||
change. That file is the umbrella index every feature registers itself
|
||||
in (the method-dispatch table and the Status/TODO checklist both list
|
||||
every other feature the same way), so this is the expected cross-file
|
||||
touch the Handshakes section describes, not scope creep.
|
||||
|
||||
**Tests added this round (4 unit + 1 e2e assertion, all in the files
|
||||
already under review, no new files):**
|
||||
`is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`,
|
||||
`burst_collects_everything_already_queued_in_arrival_order`,
|
||||
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`,
|
||||
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
|
||||
(all in `crates/lucisv_server/src/server.rs`), plus a `message`-field
|
||||
assertion added to
|
||||
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each` in
|
||||
`crates/lucisv_server/tests/e2e.rs`. `lucisv_server` unit count moved from
|
||||
702 to 706; e2e stayed at 38 (one test grew an assertion, none added).
|
||||
|
||||
**Fixes made:** none beyond the test additions above — no corruption, no
|
||||
mishandled message, no dropped request found anywhere in the diff.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
plus two extra e2e passes (flood test green in every run I and QA made —
|
||||
twelve consecutive between us), clean. The dev's deviation from my brief
|
||||
was the right kind: my burst-drain design assumed a queue that lsp-server's
|
||||
rendezvous channels do not provide, the dev proved that over a real pipe
|
||||
(0/5 honoured) before changing anything, and the forwarder it added is
|
||||
the minimal honest fix — one thread, no shared state, stopping at
|
||||
shutdown for a reason it can cite from lsp-server's own source. QA then
|
||||
re-derived the shutdown hand-off from the vendored code rather than the
|
||||
work log, which is exactly the adversarial re-check this workflow exists
|
||||
for, and closed the four real gaps (the shutdown-shaped notification,
|
||||
bare `burst` coverage, the forwarder hand-off under a real Connection,
|
||||
and the server-id-namespace cancel).
|
||||
|
||||
The stateless cancelled-set design — a cancel matters only beside its
|
||||
request in one burst, everything else dropped on sight — is the reason
|
||||
this feature cannot leak or misfire across sessions, and shutdown
|
||||
sitting before the cancel check closes the one hole a hostile client
|
||||
could poke. On the flood test's `honoured > 0` assertion: QA is right
|
||||
that a pathological scheduler could in principle defeat it and right not
|
||||
to weaken it; the property is the point of the test, the risk is
|
||||
unreproduced in twelve runs, and if CI ever trips it the QA log already
|
||||
contains the analysis. This completes §9b. Accepted as shipped.
|
||||
@@ -48,10 +48,14 @@ the deviations are stated where they happen.
|
||||
`Resolution::InheritedCandidate { base, paths }` — `base` is the extends
|
||||
path as written (`uvm_component`, `pkg::base`), `paths` are the import
|
||||
paths the lexical walk collected on the way out (both could supply the
|
||||
name; recording both is the honest answer). Nothing chases `base`, in
|
||||
name; recording both is the honest answer), **plus, since 2026-08-26, the
|
||||
use's own name last** (`docs/features/overlay-promotion/README.md`), so a
|
||||
cross-file `interface` or class written as the type of a member of a UVM
|
||||
class reaches the workspace's unit table. Nothing chases `base`, in
|
||||
this file or out of it: a future hover/index round can, without this
|
||||
crate pretending it did inheritance resolution. The fallback applies to
|
||||
*member* uses only — a **unit-name** miss (a `p::x` head, an
|
||||
crate pretending it did inheritance resolution. The overlay may now answer
|
||||
such a reference from `paths` — it never rewrites it, and `base` stays.
|
||||
The fallback applies to *member* uses only — a **unit-name** miss (a `p::x` head, an
|
||||
`extends`/`implements` base) stays `ExternalCandidate` even inside an
|
||||
extending class, because a base class supplies members, not package or
|
||||
class names (QA-found, lead-ruled; pinned by
|
||||
|
||||
@@ -0,0 +1,568 @@
|
||||
# code-lens
|
||||
|
||||
## Goal
|
||||
|
||||
`textDocument/codeLens` puts one line of true, computed information above
|
||||
every module and interface declaration in the open buffer: **"N
|
||||
instantiations"** — how many times the whole workspace instantiates that
|
||||
module — with "1 instantiation" and "no instantiations" spelled the way a
|
||||
person would. It is the single most Verilog-shaped thing a lens can say: a
|
||||
module's fan-in is the number an RTL engineer actually wants when they open a
|
||||
file, and until now it took opening the call hierarchy to learn it. Clicking a
|
||||
lens answers with every instantiation site, and — for a client that advertised
|
||||
`window/showDocument` — jumps to the first of them. The count is not a second
|
||||
census: it is computed by the very walk `callHierarchy/incomingCalls` is
|
||||
computed by, so the lens and the hierarchy view can never disagree (TODO.md
|
||||
§9c).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The population is `incomingCalls`'s population, and nothing else.** N is
|
||||
the number of instantiation *sites* — the sum of every `fromRanges` entry
|
||||
`callHierarchy/incomingCalls` would list for that module, not the number of
|
||||
instantiating modules. A module instantiated twice inside one `top` reads
|
||||
"2 instantiations", because that is what a user counting instances means.
|
||||
`the_count_is_exactly_what_incoming_calls_would_list` asserts the equality
|
||||
directly rather than restating the arithmetic.
|
||||
- **An instantiation at file scope is not counted**, because it has no
|
||||
enclosing module to be a caller. That is inherited, not decided here: it is
|
||||
the rule `hierarchy::callers_in` already applied, and the whole point of
|
||||
reusing the census is that this feature does not get to have its own
|
||||
opinion. Such a file is illegal SystemVerilog anyway and only reachable
|
||||
through the tolerant parser.
|
||||
- **The census is by name.** Two modules named `fifo` in one workspace get the
|
||||
same count on both their lenses, and clicking either shows every site of
|
||||
either. Same limitation `callHierarchy/incomingCalls` has, for the same
|
||||
reason: an instantiation names a module, and nothing in the source says
|
||||
which of two same-named declarations it meant.
|
||||
- **The lens's range is the declaration's own name span.** Clients draw a lens
|
||||
on the line *above* `range.start`, so the name span puts it directly over
|
||||
the header and nowhere else. A declaration whose name span is empty — what
|
||||
the tolerant parser produces for `module ;` — gets no lens: there is no line
|
||||
to sit on, and an invented one would decorate the wrong code.
|
||||
- **An interface is a module declaration.** `interface bus; ... endinterface`
|
||||
parses to the same `ast::Module` node with `kw == "interface"`, so it is
|
||||
reached by `instantiations::declarations` and instantiated through the same
|
||||
`ItemKind::Instantiation`. No branch was written for it; a test pins that it
|
||||
works.
|
||||
- **`resolveProvider: false`, and every lens is complete.** Title, command and
|
||||
arguments are all computed up front, matching what completion, inlay hints
|
||||
and document links do in this server. The count is the expensive part and it
|
||||
is exactly what a resolve would have to compute, so a two-stage protocol
|
||||
would buy nothing.
|
||||
- **A module with no instantiations gets a display-only lens** — a `Command`
|
||||
whose `command` is the empty string, which is what rust-analyzer ships for
|
||||
the same case and what clients render as plain text. There is nothing to
|
||||
open; a click that led to an empty list would be worse than no click. It
|
||||
also carries no `arguments`.
|
||||
- **`window/showDocument` shows only the first site.** LSP has no
|
||||
server-initiated "peek these seven places" — that is VS Code's
|
||||
`editor.action.showReferences`, a *client-side* command, and this repo's
|
||||
extension declares none (and this round did not touch `editors/`). The
|
||||
honest portable behaviour is: the command's result is the full list of
|
||||
`Location`s, for any caller that wants it, and the push opens the first one
|
||||
for a client that can be pushed to. A client without the capability still
|
||||
gets the list.
|
||||
- **`workspace/codeLens/refresh` is sent from `reindex()` only.** Not at
|
||||
startup: no buffer is open there, so there are no stale lenses to
|
||||
invalidate. Not on a keystroke either — a `didChange` cannot change any
|
||||
count, since the census is over instantiations in *other* files and a client
|
||||
re-requests lenses for the buffer it just edited anyway.
|
||||
- **The count is computed against `Workspace::sources()`**, which reads every
|
||||
in-scope file from disk with open buffers overriding it. So an unsaved
|
||||
instantiation typed into another open buffer *is* counted, and a file
|
||||
changed on disk that no watcher reported is counted as of this request.
|
||||
- **The cost is one workspace walk per request, not one per module.**
|
||||
`hierarchy::callers_of_each` takes a batch precisely because `sources()`
|
||||
re-reads the whole file set: measured over the 860-file corpus, a
|
||||
three-module file costs 133 ms against 93 ms for a single name (debug build)
|
||||
— amortized, not tripled. The absolute number is the honest cost of having
|
||||
no instantiation-edge table in the index; see Status / TODO.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Request to `vlog_semantic` — an instantiation-edge table in the index
|
||||
|
||||
Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
|
||||
features now pay the same cost: every `textDocument/codeLens` request and
|
||||
every `callHierarchy/incomingCalls` walks `Workspace::sources()` — a re-read
|
||||
and tolerant re-parse of every in-scope file — because `WorkspaceIndex`
|
||||
records what a file *declares* and never what it *instantiates*. The ask: at
|
||||
index build time (the same rebuild `reindex()` already pays for), record the
|
||||
instantiation edges, e.g.
|
||||
|
||||
```rust
|
||||
/// Every instantiation of `name` across the indexed files:
|
||||
/// (file, instantiating-module name span, instance site span).
|
||||
pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge]
|
||||
```
|
||||
|
||||
so `hierarchy::callers_of_each` becomes a lookup and its whole
|
||||
walk-and-parse body is deleted. The census policies (multi-instance
|
||||
statements = one site, textual not elaborated, both `ifdef` arms) must carry
|
||||
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.
|
||||
|
||||
|
||||
### `lucisv_server::hierarchy` — **changed, deliberately**
|
||||
|
||||
`incoming` was split so the census has exactly one implementation:
|
||||
|
||||
- **New public** `hierarchy::callers_of_each(ws, names: &[&str]) ->
|
||||
Vec<Vec<CallHierarchyIncomingCall>>` — the same walk, asked about a batch of
|
||||
names, answering one list per name in the order asked. It is now the
|
||||
primitive.
|
||||
- `hierarchy::incoming(ws, item)` is a one-line call into it with a
|
||||
one-element batch. **Its behaviour is unchanged**, empty-name guard
|
||||
included: the guard moved into the batch's per-name filter, where an empty
|
||||
name matches no file rather than every file.
|
||||
- The private `callers_in` now takes an already-parsed file (`&Uri`,
|
||||
`&Positions`, `&[Site]`) instead of a path and text, so one file is parsed
|
||||
once for a whole batch rather than once per name. The `Positions` for a file
|
||||
is now built whenever any name matches, rather than only when a caller was
|
||||
found — a `LineIndex::new` per candidate file, which the batch more than
|
||||
pays back.
|
||||
|
||||
Nothing else in `hierarchy.rs` moved, and its own tests are untouched and
|
||||
green.
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `ClientAbilities` gains **two** fields, both filled in `main.rs`:
|
||||
`code_lens_refresh` (from `workspace.codeLens.refreshSupport`) and
|
||||
`show_document` (from `window.showDocument.support`). Every existing test
|
||||
that builds `ClientAbilities { ..Default::default() }` is unaffected.
|
||||
- `request()` gains a `CodeLensRequest` arm, and its `ExecuteCommand` arm now
|
||||
routes `lucisv.showInstantiations` to `lens::execute` before falling through
|
||||
to `ports::execute`.
|
||||
- New private `show_instantiations(Vec<Location>) -> Result<Value, Failure>`
|
||||
(the answer, plus the optional push) and `refresh_code_lenses()` (the gated
|
||||
server-initiated request).
|
||||
- `reindex()` calls `refresh_code_lenses()` immediately after
|
||||
`end_indexing(bar)` and before the generation bump, the scope warnings and
|
||||
the republishes. Pinned by
|
||||
`the_refresh_rides_after_the_indexing_bar_comes_down`.
|
||||
- `response()`'s doc comment now names four ignorable answers rather than two.
|
||||
Its code is unchanged: the refresh's and the showDocument's ids are never in
|
||||
`applying`, so they fall through the existing lookup.
|
||||
|
||||
### `lucisv_server::main`
|
||||
|
||||
- `capabilities()` gains `code_lens_provider: Some(CodeLensOptions {
|
||||
resolve_provider: Some(false) })`.
|
||||
- `execute_command_provider.commands` is now a new local `commands()` —
|
||||
`ports::commands()` plus `lens::commands()` — rather than `ports::commands()`
|
||||
alone. A lens whose command is not advertised is a lens no client will run,
|
||||
so `every_advertised_command_is_one_the_server_runs` now checks both halves.
|
||||
|
||||
### `state::Workspace`, `vlog_parser`, `vlog_semantic`, `vlog_refactor`
|
||||
|
||||
**Untouched.** No signature moved and nothing was plumbed. The declarations
|
||||
come from `instantiations::declarations`, which already existed for the
|
||||
hierarchy, and the counts from `Workspace::sources()`, which already existed
|
||||
for it too.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
**No extension change**, and none was made. `vscode-languageclient` requests
|
||||
code lenses and renders them with no help from `extension.js`; it advertises
|
||||
`workspace.codeLens.refreshSupport` and `window.showDocument` itself.
|
||||
`smoke.js` sends `capabilities: {}`, so it takes the no-refresh,
|
||||
no-showDocument path — verified by running it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `codeLensProvider` advertised with `resolveProvider: false`
|
||||
- [x] `textDocument/codeLens` dispatched; one lens per module/interface
|
||||
declaration, on the name span, in source order
|
||||
- [x] Count reuses the `incomingCalls` census (`hierarchy::callers_of_each`),
|
||||
with an equality test against `hierarchy::incoming`
|
||||
- [x] Pluralization: "no instantiations" / "1 instantiation" / "N
|
||||
instantiations"
|
||||
- [x] `lucisv.showInstantiations` advertised and dispatched; answers every site
|
||||
as a `Location`; declines arguments it cannot read as `RequestFailed`
|
||||
- [x] `window/showDocument` pushed for the first site, gated on the client
|
||||
capability
|
||||
- [x] `workspace/codeLens/refresh` from `reindex()`, gated on
|
||||
`workspace.codeLens.refreshSupport`, after the progress bar comes down
|
||||
- [x] Unopened buffer → `null`; unnamed declaration → no lens; a buffer that
|
||||
parses to nothing → empty list
|
||||
- [x] Tests: 33 (19 in `lens.rs`, 9 in `server.rs`, 3 in `main.rs`, 2 e2e)
|
||||
- [x] TODO.md §9c checkbox, `docs/features/lucisv-server/README.md` capability
|
||||
table
|
||||
- [ ] **Not done, deliberately:** no second lens kind. A "top module"
|
||||
indicator, a parameter count, a "run this testbench" action are all
|
||||
plausible and none was asked for; one lens kind done well beats three
|
||||
guessed at.
|
||||
- [ ] **Not done, deliberately:** no `codeLens/resolve`. Everything a resolve
|
||||
could defer is the one expensive thing the lens *is*.
|
||||
- [ ] **Not done, deliberately:** no peek-references behaviour. It needs a
|
||||
client-side command declared in `editors/vscode/package.json`, which is
|
||||
out of this round's scope; `window/showDocument` is the portable
|
||||
substitute and reaches Neovim as well.
|
||||
- [ ] **Open, filed here:** the request costs one full `Workspace::sources()`
|
||||
read — 133 ms over the 860-file corpus in a debug build. That is the
|
||||
same cost `callHierarchy/incomingCalls` has always had, but a lens
|
||||
request arrives far more often than a hierarchy question. The real fix
|
||||
is an instantiation-edge table in `WorkspaceIndex`, built once per
|
||||
rescan, which would make both this and `incomingCalls` a lookup. That is
|
||||
a `vlog_semantic` change and belongs in its own round; **request
|
||||
recorded here, not made.**
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9c
|
||||
|
||||
- **The click-behaviour decision, and why.** The brief left this open with a
|
||||
fallback to display-only. I built the real jump, because reading
|
||||
`hierarchy::incoming` showed the locations were *already there* — every
|
||||
`fromRanges` entry is a site, paired with its file's URI — so
|
||||
`lucisv.showInstantiations` is a flatten and nothing more. The chain the
|
||||
brief worried might be heavy is about fifteen lines: `lens::execute` returns
|
||||
`Vec<Location>`, `Server::show_instantiations` pushes a
|
||||
`window/showDocument` for the first when the client advertised it, and the
|
||||
answer is the list either way. Display-only survives as the honest answer for
|
||||
the **zero** case only, where there is nothing to open — which is exactly
|
||||
where rust-analyzer uses the same empty-command trick. So: real behaviour
|
||||
everywhere it can mean something, display-only where it cannot.
|
||||
- **The arguments are `[module-name]`, not `[uri, name]`.** The brief
|
||||
suggested the URI first, in the style of the port commands. I dropped it
|
||||
after establishing that the census is *purely* by name —
|
||||
`hierarchy::incoming` reads only `item.name` and nothing else off its item —
|
||||
so a URI would be an argument the handler receives and ignores, and this
|
||||
repo does not ship those. One argument, all of it used.
|
||||
- **A name the workspace does not declare is not an error.** The brief asked
|
||||
for one. I did not build it, and the reason is a real failure mode rather
|
||||
than taste: the only index-backed way to ask "is this a module?" is
|
||||
`WorkspaceIndex::units`, and the index is rebuilt on *save*, so a module
|
||||
just typed into an open buffer is genuinely absent from it. Gating on that
|
||||
would make the command refuse the very lens that is on screen. Malformed
|
||||
arguments (missing, non-string, empty) are still declined as
|
||||
`RequestFailed`, per `ports.rs`; a well-formed name with no sites answers
|
||||
`[]`, which is the truth.
|
||||
- **The census was extracted rather than duplicated, and the batch is why.**
|
||||
Naively, `code_lenses` would call `hierarchy::incoming` once per module in
|
||||
the buffer — but `Workspace::sources()` re-reads every in-scope file from
|
||||
disk on *each* call, so a three-module file would read the workspace three
|
||||
times. So `incoming`'s body became `callers_of_each(ws, names)`, which reads
|
||||
the file set once and parses each candidate file once for the whole batch;
|
||||
`incoming` is now that function with a one-element batch. Measured over the
|
||||
860-file corpus: three names 133 ms, one name 93 ms — amortized, and pinned
|
||||
by `code_lenses_for_a_whole_file_cost_about_one_workspace_walk`, which fails
|
||||
if the ratio ever goes linear.
|
||||
- **The empty-name guard moved and got stricter.** It used to be an early
|
||||
return in `incoming`; it is now a per-name filter inside the batch, so one
|
||||
empty name in a batch of five costs nothing and cannot make the prefilter
|
||||
match every file. Same behaviour for `incoming`, which is still the only
|
||||
caller that could ever be handed one.
|
||||
- **The lens sits on the name span, not the header line.** Clients draw the
|
||||
lens on the line above `range.start`; the name span and the header line have
|
||||
the same start line, but the name span is the one that stays right when a
|
||||
declaration is written with attributes or a leading comment on the same
|
||||
line.
|
||||
- **Refresh placement.** Straight after `end_indexing(bar)` in `reindex()`,
|
||||
following the progress round's own precedent that the bar names the scan and
|
||||
everything after it is work on the scan's result. Order pinned by a test
|
||||
(`create, begin, end, refresh`) so it cannot drift silently. Nothing is sent
|
||||
at startup — there is no open buffer holding lenses there.
|
||||
- **A buffer with no named declarations returns before the workspace walk.**
|
||||
Otherwise opening a package or a header file would read every file in the
|
||||
project to produce an empty list.
|
||||
- Files touched: `crates/lucisv_server/src/lens.rs` (new),
|
||||
`crates/lucisv_server/src/hierarchy.rs`,
|
||||
`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/src/main.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, `TODO.md`,
|
||||
`docs/features/lucisv-server/README.md`, this README. No engine crate, no
|
||||
`editors/`, no new dependency, no version bump.
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
|
||||
--all-targets`: zero warnings. `cargo test --workspace`: **1943 passed, 0
|
||||
failed** (1910 on `HEAD` `34938fb`, measured — 33 new). `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`, exit 0. No
|
||||
commits.
|
||||
|
||||
The 33 tests, and what each group is for:
|
||||
|
||||
| tests | pin |
|
||||
|---|---|
|
||||
| `lens.rs` — `a_lens_counts_every_instantiation_in_the_workspace`, `the_title_counts_in_the_users_own_arithmetic` | the cross-file count, and 0/1/N pluralization including "not `1 instantiations`" |
|
||||
| `lens.rs` — `the_count_is_exactly_what_incoming_calls_would_list` | the agreement with `hierarchy::incoming`, asserted against its live answer rather than against a number |
|
||||
| `lens.rs` — `an_instantiation_at_file_scope_is_not_counted_because_no_one_calls_it` | the inherited caller rule, stated so a future change to it is visible here |
|
||||
| `lens.rs` — `the_lens_sits_on_the_declarations_own_name`, `every_module_in_a_file_gets_its_own_lens_in_source_order` | the range is the name span; one lens per declaration, source order |
|
||||
| `lens.rs` — `an_interface_is_a_module_declaration_and_gets_its_own_lens` | interfaces, which needed no branch |
|
||||
| `lens.rs` — `a_module_nothing_instantiates_gets_a_lens_that_does_not_click`, `a_clickable_lens_carries_the_module_name_as_its_only_argument`, `no_lens_is_ever_left_for_a_resolve_to_fill_in` | the two command shapes, and that nothing is left unresolved |
|
||||
| `lens.rs` — `a_buffer_this_server_was_never_shown_has_no_lenses_at_all`, `a_buffer_that_declares_no_module_gets_an_empty_list`, `a_buffer_that_is_not_verilog_at_all_gets_no_lenses_and_does_not_panic`, `a_declaration_the_parser_could_not_name_gets_no_lens` | the four refusals: `null`, empty, total on junk, no lens without a name span |
|
||||
| `lens.rs` — `the_command_answers_one_location_per_site`, `..._nothing_for_a_module_nothing_instantiates`, `..._declines_arguments_it_cannot_read`, `the_command_list_is_what_the_server_advertises` | the command: one location per site in file-then-position order, the empty answers, the refusals |
|
||||
| `lens.rs` — `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` | the batch really is one walk (corpus, skipped when absent) |
|
||||
| `server.rs` — `a_code_lens_request_counts_the_workspaces_instantiations`, `..._for_an_unopened_buffer_answers_null` | dispatch, and the `null` |
|
||||
| `server.rs` — `the_show_instantiations_command_answers_every_site`, `..._pushes_a_show_document_when_it_can`, `a_module_with_no_instantiations_pushes_nothing_and_shows_nothing`, `..._declines_arguments_it_cannot_read` | the command over the dispatch, both `showDocument` gate states, and the `RequestFailed` code |
|
||||
| `server.rs` — `a_rescan_asks_a_capable_client_to_refresh_its_code_lenses`, `a_client_that_cannot_refresh_code_lenses_is_never_asked_to`, `the_refresh_rides_after_the_indexing_bar_comes_down` | both polarities of the refresh gate, all three rescan paths, no refresh at startup, and the order against the progress bar |
|
||||
| `main.rs` — `code_lenses_resolve_nothing_because_every_lens_is_complete`, `code_lens_refresh_support_...`, `show_document_support_...` | the advertised option, and both capability readers at absent/false/true |
|
||||
| `e2e.rs` — `code_lenses_and_their_command_round_trip_over_the_wire` | the capability's JSON shape, the lens JSON (title, command, arguments, range, no `data`), the command's locations, the `null`, and that the lens's command is in `executeCommandProvider.commands` |
|
||||
| `e2e.rs` — `a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire` | the refresh on the wire, both gate states, against the real binary |
|
||||
|
||||
## QA log
|
||||
|
||||
- **2026-08-26 (QA)** — read this README, `hierarchy/README.md` (its QA log
|
||||
especially — the `ifdef` and generate-replication findings there turned out
|
||||
to answer several questions this round would otherwise have raised fresh),
|
||||
`instantiations.rs`, `hierarchy.rs` end to end (diffed function-by-function
|
||||
against `34938fb`), `lens.rs`, and the `server.rs`/`main.rs` diffs, before
|
||||
touching anything.
|
||||
|
||||
**Gates, independently re-run.** `cargo fmt --all -- --check`: clean.
|
||||
`cargo clippy --all-targets --workspace`: zero warnings. `cargo test
|
||||
--workspace`: **1943 passed, 0 failed** before any QA change, matching the
|
||||
dev's number exactly; **1952 passed, 0 failed** after adding 9 QA tests (6
|
||||
in `lens.rs`, 3 in `server.rs` — see below). `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`, exit 0,
|
||||
run twice (before and after the QA tests).
|
||||
|
||||
**1. The `hierarchy.rs` refactor.** Diffed `git show
|
||||
34938fb:crates/lucisv_server/src/hierarchy.rs` against the working tree
|
||||
function by function. `incoming` is now `callers_of_each(ws,
|
||||
&[item.name.as_str()]).pop().unwrap_or_default()` — a one-element batch.
|
||||
Confirmed by construction that `callers_of_each`'s per-file loop is
|
||||
unchanged in substance: same `parse_source_tolerant` (not the strict
|
||||
parser — a mode change would have silently changed counts on broken files,
|
||||
and it did not happen), same `site.inst.module != name` filter inside
|
||||
`callers_in`, same final sort. The only real change is *where* the
|
||||
prefilter and the parse happen: once per name before (`callers_in` took
|
||||
`path: &Path, text: &str`), once per **file** now, with the parsed `sites`
|
||||
reused across every name the batch is asking about.
|
||||
- *Empty name in a batch.* Traced by hand: `wanted` filters out any index
|
||||
whose name is empty or absent from the file's text, so an empty name
|
||||
never reaches `callers_in` and its slot in `answers` stays `Vec::new()`.
|
||||
Byte-identical to the old early-return in `incoming`. No new test needed
|
||||
— the dev's own doc comment states this and it holds.
|
||||
- *Duplicate names in one batch, `["m", "m"]`.* New test
|
||||
`qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count`
|
||||
(`lens.rs`) — a file with two `module m` declarations (reachable through
|
||||
the tolerant parser) instantiated once, opened as a buffer. Both indices
|
||||
are processed independently (the loop does not deduplicate `wanted`), so
|
||||
neither aliases nor corrupts the other — both lenses read "1
|
||||
instantiation". Redundant work (the same file is walked twice for the
|
||||
same name), not a correctness bug.
|
||||
- *A name that is a package, not a module.* Not a distinct code path:
|
||||
`callers_of_each` matches purely on `site.inst.module`, a string, with no
|
||||
knowledge of what kind of thing owns that name. Nothing to test beyond
|
||||
what `hierarchy.rs`'s own `qa_instantiation_in_a_package_does_not_crash`
|
||||
already covers.
|
||||
- **Verdict: behavior-preserving.** `incoming`'s own 25 tests are untouched
|
||||
and green, which is necessary but — per the brief — not sufficient; the
|
||||
above traces the edge cases a black-box test-pass rerun cannot see, and
|
||||
none of them diverge.
|
||||
|
||||
**2. Count honesty.** The Assumptions section already states the load-bearing
|
||||
facts: *the population is `incomingCalls`'s, by name, and one `Instantiation`
|
||||
is one site "however many instances it declares"* — that last part is
|
||||
`hierarchy.rs`'s own documented policy (2026-08-25 QA round), inherited
|
||||
rather than decided here. Checked whether the fixture agreement test would
|
||||
actually catch a divergence: it cannot, structurally — `lens.rs` and
|
||||
`hierarchy::incoming` both bottom out in the literal same
|
||||
`hierarchy::callers_of_each` call, so "agreement" is guaranteed by
|
||||
construction, not by the fixture's shape. What the fixture's shape *does*
|
||||
affect is whether **this feature's own test suite** would notice if that
|
||||
shared implementation's semantics ever changed under it — e.g. if
|
||||
`callers_of_each` started counting instances instead of AST nodes, no
|
||||
existing `lens.rs` test using `TOP` (two separate statements) would catch
|
||||
it, because two separate statements give the same answer either way. Added
|
||||
6 tests to `lens.rs` pinning the number itself over shapes the fixture
|
||||
never exercises, each with expected output derived independently (by
|
||||
reading `instantiations.rs`'s `walk`, not by running the code first):
|
||||
- `qa_a_multi_instance_statement_is_one_site_not_two` — `sub u1 (), u2
|
||||
();` is **one** `Instantiation` node with two `Instance` entries, and
|
||||
reads "1 instantiation", one `Location`. Matches
|
||||
`hierarchy/README.md`'s stated policy exactly (it names this exact
|
||||
source shape). Not a finding — a confirmed, disclosed design decision —
|
||||
but it was untested at the code-lens layer, where a user is more likely
|
||||
to notice the number than in a hierarchy view.
|
||||
- `qa_a_module_that_instantiates_itself_counts_its_own_instantiation` —
|
||||
self-recursion reads "1 instantiation", one site, no hang. Consistent
|
||||
with `hierarchy.rs`'s own self-instantiation and cycle handling (each
|
||||
request answers one hop).
|
||||
- `qa_two_files_declaring_the_same_module_name_get_the_same_count_on_both`
|
||||
— two files each declaring `module m`, one real instantiation of `m`
|
||||
elsewhere: opening *either* declaration reads "1 instantiation" — the
|
||||
workspace-wide total, not zero and not partitioned. Matches the
|
||||
documented "census is by name" Assumption; confirms it holds in both
|
||||
directions (the fixture I found only tried one file, not the other).
|
||||
- `qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count`
|
||||
— described above under the hierarchy refactor; also a code-lens-level
|
||||
consequence of the same policy: **two lenses**, same count on both, in
|
||||
one buffer.
|
||||
- `qa_a_generate_replicated_instantiation_counts_the_written_statement_once`
|
||||
— a `generate for` loop wrapping one instantiation reads "1
|
||||
instantiation" regardless of the genvar's range (textual, not
|
||||
elaborated), matching `hierarchy.rs`'s own precedent for the identical
|
||||
shape.
|
||||
- `qa_an_ifdef_guarded_instantiation_counts_both_arms` — `` `ifdef``/``
|
||||
`else`` both arms read "2 instantiations". This is `hierarchy.rs`'s
|
||||
disclosed `ifdef` policy (2026-08-25 finding, fixed by documentation
|
||||
then) surfacing on a second, more visible feature. Not re-litigated here
|
||||
since the underlying behavior was already reviewed and accepted by the
|
||||
lead; pinned so a change to it is visible from `lens.rs` too, not only
|
||||
`hierarchy.rs`.
|
||||
|
||||
None of the six disagreed with `hierarchy::incoming` (they structurally
|
||||
cannot), and none exposed a new corruption or miscount — every number
|
||||
above is the intentional, already-documented arithmetic. The value added is
|
||||
regression coverage at the layer users actually read the number from.
|
||||
|
||||
**3. Cost / request amplification.** Traced `code_lenses` in `lens.rs`:
|
||||
one call to `hierarchy::callers_of_each(ws, &names)` with the *whole*
|
||||
buffer's declared names, which itself calls `ws.sources()` exactly once
|
||||
inside its single `for (path, text) in ws.sources()` loop — confirmed by
|
||||
reading the loop body, not by profiling. No per-lens or per-module
|
||||
`sources()` call exists anywhere in the path from `CodeLensRequest` to the
|
||||
answer. The **index-table follow-up**: filed in Status/TODO ("an
|
||||
instantiation-edge table in `WorkspaceIndex`... request recorded here, not
|
||||
made"), in the same style as `hierarchy/README.md`'s own equivalent backlog
|
||||
bullet from the prior round — consistent with house precedent, but neither
|
||||
one is written as a *concrete* Handshake (a proposed `vlog_semantic`
|
||||
function signature and contract) the way CLAUDE.md's Handshakes section is
|
||||
meant to capture a cross-module request. **Minor, LOW severity, not fixed**:
|
||||
recommend the lead decide whether a backlog TODO bullet is sufficient here
|
||||
(matching existing house style) or whether, now that *two* features would
|
||||
benefit from the same index change, it is worth promoting to an actual
|
||||
Handshakes-section proposal with a named function shape. Not fixed
|
||||
unilaterally — this is a documentation-structure judgment call, not a typo.
|
||||
|
||||
**4. `showDocument` push.** Read `show_instantiations` and `deliver` side
|
||||
by side: `deliver` is the only function that inserts into `self.applying`;
|
||||
`show_instantiations` calls `send_request(ShowDocument::METHOD, ...)`
|
||||
directly and never touches `applying`, so its response id always falls
|
||||
through `response()`'s `let Some(command) = self.applying.remove(...) else
|
||||
{ return }` — exactly the mechanism the doc comment claims. Confirmed via
|
||||
the dev's own tests that the gate (`self.abilities.show_document`) is
|
||||
checked before the push, that a client without it still gets the full
|
||||
location list, and that the pushed request's shape (`uri` of the first
|
||||
site, `takeFocus: true`, `selection` = that site's range) is correct.
|
||||
**New test**
|
||||
`qa_a_showdocument_push_and_an_applyedit_push_stay_independent_when_both_are_outstanding`
|
||||
(`server.rs`) — one `PROPAGATE_PORTS` command outstanding (an `applyEdit`
|
||||
push, tracked in `applying`) and one `SHOW_INSTANTIATIONS` command
|
||||
outstanding (a `showDocument` push, not tracked) at the same time,
|
||||
answered in reverse send order. The showDocument answer produces no
|
||||
message (correctly ignored even though it carries no `applied` field at
|
||||
all, which would be a type-mismatch panic risk if `response()` ever tried
|
||||
to interpret it as an `ApplyWorkspaceEditResponse`); the applyEdit answer
|
||||
is still routed to its own command correctly afterward. This was asked for
|
||||
explicitly in the brief and had no existing test — ids are allocated by a
|
||||
strictly increasing counter (`send_request`), so collision was never
|
||||
actually possible, but the mechanism is now pinned rather than just argued.
|
||||
Also confirmed by reading the `ExecuteCommand` dispatch arm:
|
||||
`lucisv.showInstantiations` returns from inside the `if` before
|
||||
`ports::execute`'s `Ok((edit, warnings)) => self.deliver(...)` branch is
|
||||
ever reached, so `deliver()` cannot fire for it — no test needed beyond the
|
||||
existing `the_show_instantiations_command_answers_every_site` asserting
|
||||
`session.requests().is_empty()` for a client without `apply_edit` either.
|
||||
|
||||
**5. Refresh discipline.** Verified independently: `refresh_code_lenses`
|
||||
gates only on `self.abilities.code_lens_refresh`, never on
|
||||
`work_done_progress` — the dev's own
|
||||
`a_rescan_asks_a_capable_client_to_refresh_its_code_lenses` already uses
|
||||
`ClientAbilities { code_lens_refresh: true, ..Default::default() }` (so
|
||||
`work_done_progress` is `false`) and gets three refreshes, which is the
|
||||
independent-gates case the brief asked about, already covered. Never at
|
||||
startup (`reindex` is not called there). **New test**
|
||||
`qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh`
|
||||
(`server.rs`) — two open buffers, one save: exactly one
|
||||
`workspace/codeLens/refresh`, confirming the call sits before the
|
||||
per-buffer republish loop in `reindex()` rather than inside it (the dev's
|
||||
existing test only ever opened one buffer, so this distinction was
|
||||
argued from reading the code, not from a test, before now). Order-pinned
|
||||
by the dev's own `the_refresh_rides_after_the_indexing_bar_comes_down`;
|
||||
re-verified by hand against `reindex()`'s body. Response ignored: same
|
||||
`applying`-lookup mechanism as `showDocument`, covered by the new
|
||||
interleaving test's reasoning (refresh never inserts into `applying`
|
||||
either).
|
||||
|
||||
**6. Command surface.** `execute_command_provider.commands` is `commands()`
|
||||
= `ports::commands()` ++ `lens::commands()`; `main.rs`'s own
|
||||
`every_advertised_command_is_one_the_server_runs` now checks both halves
|
||||
are contained, not just equality with the concatenation (equality alone
|
||||
would not have caught one list silently dropping an entry the other
|
||||
didn't add back). `git diff --stat -- crates/lucisv_server/src/ports.rs`
|
||||
confirms it is untouched. Confirmed by reading the `ExecuteCommand` arm
|
||||
(see point 4) that `lucisv.showInstantiations` never reaches `deliver()`.
|
||||
|
||||
**7. CLAUDE.md compliance.** `grep` for `unwrap()`/`expect(`/`panic!` in
|
||||
`lens.rs` and `hierarchy.rs` outside `#[cfg(test)]`: none. Same check
|
||||
against the added lines in `server.rs`/`main.rs`: every hit is inside
|
||||
`mod tests`. No `#[allow(...)]`, no `unsafe`, anywhere in the diff. Every
|
||||
public item in `lens.rs` carries a one-line doc comment. `TODO.md`'s §9c
|
||||
item text is untouched — only the checkbox flipped to `[x]`, with a
|
||||
"→ delivered" paragraph appended below it, matching the rule ("leave the
|
||||
item text intact"). This README's seven sections are each present exactly
|
||||
once.
|
||||
|
||||
**C. Corpus, machine-checked.** New test
|
||||
`qa_corpus_counts_agree_with_grep_derived_ground_truth` (`lens.rs`),
|
||||
against `corpus/common_cells/src/cdc_fifo_gray.sv` (three module
|
||||
declarations, same file the dev's own perf test already uses). Ground
|
||||
truth built by hand with `grep -rnE '\bNAME\b' corpus --include='*.sv'
|
||||
--include='*.svh'`, read line by line to exclude the declaration itself
|
||||
and doc-comment mentions (`cdc_fifo_gray_clearable.sv` has several, e.g.
|
||||
"In contrast to the cdc_fifo_gray version..." — a real risk if the walk
|
||||
ever matched comment text, which `instantiations::sites` structurally
|
||||
cannot):
|
||||
| module | grep-derived instantiation sites | lens read |
|
||||
|---|---|---|
|
||||
| `cdc_fifo_gray` | 1 (`common_cells/test/cdc_fifo_tb.sv:49`, `i_dut`) | "1 instantiation" |
|
||||
| `cdc_fifo_gray_src` | 1 (`cdc_fifo_gray.sv:130`, inside `cdc_fifo_gray` itself) | "1 instantiation" |
|
||||
| `cdc_fifo_gray_dst` | 1 (`cdc_fifo_gray.sv:145`, inside `cdc_fifo_gray` itself) | "1 instantiation" |
|
||||
All three agree. Run in release (`cargo test -p lucisv_server --release
|
||||
qa_corpus_counts_agree_with_grep_derived_ground_truth -- --nocapture`);
|
||||
skips cleanly when `corpus/` is not checked out, matching the dev's own
|
||||
corpus test's pattern.
|
||||
|
||||
**Everything else tried to break, and did not:**
|
||||
- A workspace root fixture helper (`Tree::write` in `lens.rs`'s tests) did
|
||||
not create parent directories, so a nested relative path (`"a/m.sv"`)
|
||||
failed with `NotFound` the first time this round's cross-file-collision
|
||||
test tried to use one. **Fixed directly** (`fs::create_dir_all` on the
|
||||
parent before `fs::write`) — an unambiguous test-infrastructure gap, not
|
||||
a behavior change, and it was blocking test C's fixture from being
|
||||
written at all.
|
||||
- Malformed `executeCommand` arguments (missing, non-string, empty string)
|
||||
for `lucisv.showInstantiations`: all three still answer `RequestFailed`
|
||||
with a message naming "module name" — re-verified against the dev's own
|
||||
`the_command_declines_arguments_it_cannot_read` and
|
||||
`the_show_instantiations_command_declines_arguments_it_cannot_read`.
|
||||
- A name the workspace does not declare (`"never-heard-of-it"`): `[]`, not
|
||||
an error, as documented and tested by the dev.
|
||||
- `resolveProvider: false` and every lens carrying a complete `Command`
|
||||
with no `data`: re-verified against `no_lens_is_ever_left_for_a_resolve_to_fill_in`.
|
||||
|
||||
**Verdict: committable as-is.** No corruption, no idempotency risk (this
|
||||
feature touches no formatter output), no dropped comments — none of those
|
||||
invariants are in this feature's blast radius at all, since it only reads
|
||||
and answers LSP requests. The one open item (point 3, the index-table
|
||||
request's concreteness) is a documentation-polish question for the lead,
|
||||
not a defect, and does not block shipping. 9 new tests added, all green;
|
||||
gates re-run clean before and after. No commits made.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. The round's two judgment calls were both right. Building the real
|
||||
jump instead of the display-only fallback cost ~15 lines because the
|
||||
locations already existed — exactly the "check what the code makes clean"
|
||||
outcome the brief asked for — and the zero-count lens staying display-only
|
||||
matches rust-analyzer's precedent. The hierarchy.rs refactor is the
|
||||
correct shape: one census with the batch as the primitive, `incoming` as a
|
||||
one-element batch, and the corpus ratio test making the amortization a
|
||||
tested property instead of a hope. I read the refactor diff myself and
|
||||
concur with QA's function-by-function verdict — same parse mode, same
|
||||
filters, the empty-name guard equivalent in its new position.
|
||||
|
||||
QA's count-honesty tests were the right instinct: the agreement test
|
||||
alone cannot catch semantic drift when both paths share one function, so
|
||||
pinning the absolute policies (multi-instance = one site, textual
|
||||
recursion, both ifdef arms) at the lens layer is what actually holds the
|
||||
numbers still. On QA's LOW finding, I agreed and promoted the
|
||||
index-table request to a concrete Handshakes entry with a named shape —
|
||||
two features now pay the sources() walk, which is exactly when a backlog
|
||||
bullet stops being enough. Accepted as shipped.
|
||||
@@ -0,0 +1,540 @@
|
||||
# file-operations
|
||||
|
||||
## Goal
|
||||
|
||||
Renaming a header breaks every `` `include`` that reaches it, and until now
|
||||
lucisv watched that happen and said nothing — the editor moved `defs.svh`, four
|
||||
files went on naming a path that no longer exists, and the only sign was that
|
||||
ctrl-click stopped working. LSP 3.16 has the hook: a client that is about to
|
||||
rename files asks the server first (`workspace/willRenameFiles`) and applies
|
||||
whatever `WorkspaceEdit` comes back as part of the same undo step. The include
|
||||
graph already knows exactly which lines point at the moved file — by
|
||||
*resolution*, not by filename — so this round spends it: an include whose
|
||||
resolved target moves is re-spelled so it still resolves, an include no legal
|
||||
spelling can reach is left exactly as written and named in a warning, and the
|
||||
two after-the-fact notifications (`didRenameFiles`, `didDeleteFiles`) nudge the
|
||||
index without waiting for a watcher round-trip.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Renames in one batch do not compound.** `Moves` maps a path by the first
|
||||
matching rename (`find_map`), so a directory rename and an explicit rename
|
||||
of a file inside that directory, sent in one request, apply whichever rule
|
||||
matches first rather than both in sequence (QA log, 2026-08-27). No client
|
||||
observed sends that shape — a directory rename lists the directory alone —
|
||||
and the safety net still refuses any edit whose rewritten include does not
|
||||
resolve, so the failure mode is a skipped edit plus the warning, never a
|
||||
wrong write. Recorded so a future round that wants compounding knows it is
|
||||
changing a documented choice.
|
||||
|
||||
|
||||
- **Resolution decides, never the filename.** An include is rewritten only
|
||||
when `IncludeGraph::resolve` says it reaches the renamed file. Two
|
||||
`defs.svh` in one workspace are two different files here, and only the one
|
||||
that moves is touched — pinned by
|
||||
`an_include_of_a_different_file_with_the_same_name_is_untouched`.
|
||||
- **The rename has not happened yet.** `willRenameFiles` is asked *before* the
|
||||
move, so the old target is resolved against the filesystem as it stands. The
|
||||
*new* spelling is resolved against the filesystem the rename will leave
|
||||
behind, which `Moves` models: everything under `old` will be under `new`, a
|
||||
path something moves away from is gone, a path something moves to exists if
|
||||
its source does (so an `a`→`b`, `b`→`a` swap leaves both files, as it does on
|
||||
disk). No filesystem is touched to answer that — it is a prefix rewrite plus
|
||||
one `is_file` on the source.
|
||||
- **A file rename and a folder rename are one operation.** LSP sends only the
|
||||
folder's own URI for a folder rename ("when a folder is renamed, only the
|
||||
folder will be included, and not its children"), and a folder is a *prefix*
|
||||
of the paths inside it — which is exactly what `Moves` already computes for a
|
||||
file. Handling folders therefore cost this module no machinery at all, which
|
||||
is why they are handled rather than declined: the cost is one filter in the
|
||||
capability and one workspace sweep on a user gesture (54 ms over the 860-file
|
||||
corpus, see Cost), and the case it covers — moving a directory of headers —
|
||||
is the single most include-breaking thing a user can do.
|
||||
- **The two notifications ask for files only.** `didRenameFiles`/
|
||||
`didDeleteFiles` do one thing, reindex, and a folder filter there would buy a
|
||||
full rebuild for every unrelated folder rename in the tree while the file
|
||||
watcher already reports the individual files a folder move touches. So the
|
||||
folder filter is on `willRename` alone, where it earns its keep.
|
||||
- **The form is preserved where the new location allows it.** The candidate
|
||||
spellings are the suffixes of the new path under each search rung the *same*
|
||||
form would use — the including file's own directory (skipped for the angled
|
||||
form, as everywhere) and then each `+incdir+` — shortest suffix first, with
|
||||
the rung order breaking a tie. An originally **absolute** include stays
|
||||
absolute. So a same-directory rename keeps the bare filename, and a move into
|
||||
an `+incdir+` keeps it bare too.
|
||||
- **A relative spelling is the last resort, not the first.** When no rung's
|
||||
suffix resolves, a quoted include falls back to a path relative to the
|
||||
including file (`../headers/defs.svh`), which resolves on the own-directory
|
||||
rung every tool has. It is the ugliest spelling in the file, so nothing that
|
||||
goes through an `+incdir+` is passed over for it. This is what answers a
|
||||
renamed *include directory*: the `+incdir+` in the filelist is then stale and
|
||||
**lucisv does not edit filelists**, but the source keeps compiling, which is
|
||||
the better half of a bad situation.
|
||||
- **An include that still reads correctly is not edited.** Before anything is
|
||||
computed, the include as written is re-resolved against the post-rename
|
||||
filesystem; if it still reaches its file, there is no edit and no warning. A
|
||||
header moving between two `+incdir+`s under the same name, and a rename that
|
||||
carries includer and included together, are both no-ops — a no-op edit is
|
||||
noise in the user's diff.
|
||||
- **An include the rename strands is left alone *and* said out loud.** The
|
||||
server will not invent a path that resolves to nothing (that would be a
|
||||
guess, and a guess written into the user's file). It also will not stay
|
||||
silent about a line it knows it just broke. So: no edit, and one
|
||||
`window/showMessage` WARNING naming the file, the line and the include —
|
||||
through `report_scope`, so forty stranded includes are one popup and forty
|
||||
log lines.
|
||||
- **Both ends of the edge are watched.** The brief's rule was "an include whose
|
||||
resolved target is the renamed file"; the shipped rule adds the mirror case,
|
||||
an include written *in* a file that moves, because that breaks for exactly
|
||||
the same reason (the own-directory rung moves out from under it) and would
|
||||
otherwise be a silent breakage the feature politely watched happen.
|
||||
- **Edits are addressed to the file's current URI.** A file that is itself
|
||||
being renamed *and* needs an include rewritten is edited at the URI it has
|
||||
now, while its new content is computed from where it will be. That is what
|
||||
VS Code and every other file-operation participant expect: the edit lands on
|
||||
the document, and the rename carries it.
|
||||
- **The scope ladder still decides what lucisv can see.** The sweep reads
|
||||
`Workspace::sources()` — the in-scope files, with open buffers overriding
|
||||
disk. An include in a file the filelist does not name is not rewritten,
|
||||
exactly as it is not indexed, not linted and not searched.
|
||||
- **The capability is static and ungated.** `ServerCapabilities` is built
|
||||
before the client's own capabilities are read, and unlike the file watchers
|
||||
nothing here is server-initiated: a client that cannot send these requests
|
||||
simply never sends them. Gating would buy nothing and cost the
|
||||
`capabilities()` function a parameter.
|
||||
|
||||
## The safety net
|
||||
|
||||
The `WorkspaceEdit` this feature produces **rewrites the user's source files**,
|
||||
which nothing else in the server does unasked. It is fenced three ways, and
|
||||
every candidate spelling passes all three or is discarded (`survives`):
|
||||
|
||||
1. **The edit can only cover the path token.** Its range is
|
||||
`path_span.start + 1 .. path_span.end - 1` — the bytes *between* the
|
||||
delimiters. Structurally, no answer this module can compute is able to move
|
||||
the backtick, the quotes, the indentation or a trailing comment; the worst
|
||||
a bug can produce is a wrong path inside a well-formed include line.
|
||||
(`the_edit_covers_the_path_token_and_not_one_byte_more`.)
|
||||
2. **It still scans as the include it was.** The line the edit would produce is
|
||||
built and re-scanned with `includes::scan`: exactly one include, target
|
||||
equal to the spelling, same quoted/angled form. A spelling carrying the
|
||||
closing delimiter or a newline dies here.
|
||||
3. **It still lexes, and it still resolves.** The same line is run through
|
||||
`vlog_parser::tokenize` and must be one `TokenKind::Directive` and nothing
|
||||
else; and the *re-scanned* include — what the scanner will actually read
|
||||
back, not what we meant to write — must resolve, through
|
||||
`IncludeGraph::resolve_as_if`, to exactly the file the rename is moving the
|
||||
old target to. A spelling that would resolve to a *different* file (a bare
|
||||
name shadowed by a header beside the includer) is refused here, and the
|
||||
longer correct spelling is written instead
|
||||
(`a_spelling_that_would_resolve_somewhere_else_is_not_written`).
|
||||
|
||||
`verify.rs` is untouched: no normalization was added or broadened, so hard
|
||||
invariant #4 is not in play. The formatter is not involved in this path at all.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Consumed
|
||||
|
||||
- `lucisv_server::includes` — the whole of the resolution story. Three changes,
|
||||
all additive:
|
||||
- **`IncludeGraph::resolve_as_if(from, include, exists)`** is new, and
|
||||
`resolve` is now `resolve_as_if(.., &|p| p.is_file())`. There is still
|
||||
exactly **one** copy of the EDA search order; this module needed to ask it
|
||||
about a filesystem that has not happened yet, and a second copy here would
|
||||
have disagreed with the first in the corner cases nobody tests.
|
||||
- **`IncludeGraph::incdirs()`** — a read-only accessor, so a candidate
|
||||
spelling can be a suffix under a real include path rather than a guess.
|
||||
- **`includes::normalize` is now `pub`** (it was private). A renamed path and
|
||||
a resolved include are compared, and they must be folded the same way; a
|
||||
fourth private copy of that loop is the one thing that guarantees they
|
||||
drift. This is the same `.`/`..` folding
|
||||
`lucisv_core::filelist::Reader::normalize` and
|
||||
`lucisv_core::config::Discovery::absolute` each have privately — the
|
||||
include-nav README's standing request to extract one
|
||||
`lucisv_core::path::normalize` and point all of them at it is **still
|
||||
open**, and this round deliberately did not widen its scope to do it.
|
||||
- `lucisv_server::watch::watched` is now `pub` (it was private). The
|
||||
notifications filter their paths with exactly the predicate a
|
||||
`didChangeWatchedFiles` event is filtered with — two copies of "is this a
|
||||
path the index reads" would drift, and the two paths must agree because a
|
||||
client may well send both for one rename.
|
||||
- `lucisv_server::watch::SOURCE_GLOB` is reused verbatim as the file-operation
|
||||
filter's glob, so the watcher and the file operations can never be asked
|
||||
about different sets of files.
|
||||
- `Workspace::sources()` for the sweep, `Workspace::includes()` for the graph,
|
||||
`uri::{path_to_uri, uri_to_path}` for the URIs (file-operation params carry
|
||||
`String` URIs, not parsed ones, so the parse happens in `path_of`).
|
||||
|
||||
### Promised
|
||||
|
||||
- `lucisv_server::file_ops`:
|
||||
```rust
|
||||
pub fn file_operations() -> WorkspaceFileOperationsServerCapabilities;
|
||||
pub struct Rewrite { pub edit: Option<WorkspaceEdit>, pub warnings: Vec<String> }
|
||||
pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite;
|
||||
pub fn renamed(files: &[FileRename]) -> Vec<PathBuf>;
|
||||
pub fn deleted(files: &[FileDelete]) -> Vec<PathBuf>;
|
||||
pub fn touches_scope(paths: &[PathBuf], filelist: Option<&Path>) -> bool;
|
||||
```
|
||||
`Rewrite::edit` is `None` when there is nothing to do, and the handler
|
||||
answers that as the protocol's `null` rather than as an empty edit.
|
||||
- `Server::reindex_for(paths)` — the notification half, one `reindex()` when
|
||||
the paths touch the index's scope. Deliberately **not** deduplicated against
|
||||
the watcher: a client is free to send both a `didRenameFiles` and a
|
||||
`didChangeWatchedFiles` for one rename, and the second rebuild is a pure
|
||||
re-read of the tree. It costs one scan and one diagnostics generation, never
|
||||
a different answer.
|
||||
- `main.rs` advertises `workspace.fileOperations`; `report_scope`'s doc now
|
||||
says it serves these warnings too.
|
||||
|
||||
### Not touched
|
||||
|
||||
No other crate. No new dependency. No version bump. `verify.rs`, the formatter
|
||||
and the linter are not on this path at all.
|
||||
|
||||
## Cost
|
||||
|
||||
`willRenameFiles` sweeps the workspace once per request. Measured 2026-08-27 on
|
||||
the checked-in 860-file corpus, `--release`:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| files read (`sources()`) | 860 |
|
||||
| one rename, whole sweep | **~54 ms** |
|
||||
| the index rebuild a save already pays | ~320 ms |
|
||||
|
||||
Most of it is the file read `sources()` does — the same read
|
||||
`callHierarchy/incomingCalls` (56 ms) and `typeHierarchy/subtypes` (55 ms) pay,
|
||||
and for the same reason. A `text.contains("`include")` prefilter keeps the
|
||||
resolver off the ~86% of files that include nothing. Pinned by an `#[ignore]`d
|
||||
probe (`cargo test --release -p lucisv_server --bin lucisv-server
|
||||
file_ops::tests::perf -- --ignored --nocapture`), the same shape as
|
||||
`includes.rs`'s: it prints and asserts nothing but the corpus's presence.
|
||||
|
||||
The notifications cost one `reindex()` each, which is the cost a save has.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/lucisv_server/src/file_ops.rs`: the capability shape, the sweep,
|
||||
the candidate spellings, the three safety checks, the post-rename
|
||||
filesystem model, the notification filters.
|
||||
- [x] `workspace/willRenameFiles` dispatched in `server.rs`, answering
|
||||
`WorkspaceEdit | null` and reporting stranded includes through
|
||||
`report_scope`.
|
||||
- [x] `workspace/didRenameFiles` + `workspace/didDeleteFiles` dispatched, one
|
||||
`reindex()` per notification that touches scope.
|
||||
- [x] `workspace.fileOperations` advertised in `main.rs` — source-file filters
|
||||
for all three, plus a folder filter on `willRename`.
|
||||
- [x] `IncludeGraph::resolve_as_if` / `incdirs()` / `pub normalize`, so there
|
||||
is still one search order and one path folding.
|
||||
- [x] `watch::watched` made public, so the notifications and the watcher share
|
||||
one scope test.
|
||||
- [x] Tests: 24 in `file_ops.rs`, 7 in `server.rs` (dispatch, warning volume,
|
||||
reindex, watcher-double, unopened file, `null`), 1 in `main.rs` (the
|
||||
capability on the wire), 1 e2e session (real binary, edit decoded,
|
||||
applied, rename performed, include re-resolving).
|
||||
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`,
|
||||
`node editors/vscode/smoke.js`.
|
||||
- [ ] **Not done, deliberately:** `willCreateFiles`/`didCreateFiles`. A file
|
||||
that has just been created has nothing pointing at it to rewrite, and the
|
||||
watcher indexes it.
|
||||
- [ ] **Not done, deliberately:** `willDeleteFiles`. Refusing a delete the user
|
||||
asked for, or editing the includes of a file that is about to stop
|
||||
existing, is not this server's business; `didDeleteFiles` reindexes and
|
||||
the include simply stops resolving, which is the truth.
|
||||
- [ ] **Not done, deliberately:** the filelist is never rewritten. Renaming a
|
||||
file the `.f` names, or the directory an `+incdir+` names, leaves the
|
||||
filelist stale — lucisv warns about a filelist naming a file that is gone
|
||||
on the very next rebuild, and fixing it is the user's call. Editing a
|
||||
project's build manifest from a rename gesture is a much bigger promise
|
||||
than this feature makes.
|
||||
- [ ] **Not done, deliberately:** an include in a file the scope ladder
|
||||
excludes is not rewritten. Same rule as everywhere else in the server.
|
||||
- [ ] **Not done, deliberately:** no `documentChanges`/`renameFile` operations
|
||||
in the answer — plain `changes`, as `textDocument/rename` returns. The
|
||||
client is doing the renaming; the server has only text to contribute.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev agent, file operations (TODO.md §9c)
|
||||
|
||||
Built in the order the brief lists: the resolution extension first, then the
|
||||
sweep, then the dispatch, then the tests. Decisions worth recording:
|
||||
|
||||
- **`resolve_as_if` rather than a second resolver.** The one thing this module
|
||||
needs that `includes.rs` did not have is "where would this include land if
|
||||
the filesystem looked like *that*". Writing that here would have been a
|
||||
second copy of the EDA rung order, three weeks after the include-nav round
|
||||
concluded that two scanners meant "`documentLink` and the graph disagreeing
|
||||
in exactly the corner cases nobody tests". So `resolve` grew an existence
|
||||
predicate and became a one-line call into the general form. No behaviour
|
||||
change: the ordinary path passes `|p| p.is_file()`, which is the expression
|
||||
it had inline.
|
||||
- **Folder renames are handled, not declined** — the brief left the choice to
|
||||
the code, and the code made it easy: `Moves` maps a path by prefix, and a
|
||||
file is just a prefix with no children. The whole folder story is one extra
|
||||
filter in the capability. Two tests pin it (a folder of headers moving, and
|
||||
an `+incdir+` directory moving).
|
||||
- **The rule grew a mirror half, deliberately.** The brief scoped this to
|
||||
includes whose *target* is renamed. Writing the tests turned up the twin: an
|
||||
include breaks just as thoroughly when the file it is written *in* moves,
|
||||
because the own-directory rung goes with it — and that case would have been
|
||||
silent, with no edit and no warning. It is the same machinery (`target =
|
||||
moves.after(old).unwrap_or(old)`, and the includer resolved from where it
|
||||
will be), so it shipped. `a_file_that_moves_away_from_its_own_headers_is_re_spelled_too`.
|
||||
- **Two of the first tests were wrong, and the code was right.** Both asserted
|
||||
an edit where the correct answer is *no* edit: a header moving into an
|
||||
`+incdir+` under the same name, and a batch carrying includer and included
|
||||
into one new directory, both leave the line already reading correctly. That
|
||||
is what added the explicit "does it still resolve as written?" guard at the
|
||||
top of the loop — without it, the candidate ranking would have rewritten a
|
||||
perfectly good `"../inc/defs.svh"` into a bare `"defs.svh"` during an
|
||||
unrelated in-place rename, which is a diff the user did not ask for.
|
||||
- **One real bug, found by a failing test, not by review.** `Moves::is_file`
|
||||
compared paths lexically while the resolver hands it un-folded candidates
|
||||
like `rtl/../inc/defs.svh` — `Path::is_file` follows the `..` itself, a
|
||||
prefix comparison does not. Every `..`-relative candidate silently failed to
|
||||
verify, which showed up as "no spelling reaches it" on the two tests that
|
||||
need the relative fallback. `is_file` now folds first, through
|
||||
`includes::normalize` — the same fold the resolver's own result goes through,
|
||||
which is why that function is now `pub` rather than copied.
|
||||
- **A renamed `+incdir+` directory re-spells relatively rather than warning.**
|
||||
The first draft warned, on the grounds that only the filelist can really fix
|
||||
it. The relative fallback resolves in every tool through the rung every tool
|
||||
has, so the source keeps compiling; the stale `+incdir+` is a filelist
|
||||
problem lucisv already reports on the next rebuild. Pinned, with the
|
||||
trade-off written into the test.
|
||||
- **`report_scope` reused rather than a second warning path.** "Log all, show
|
||||
the first" is exactly the volume control this needs — a rename can strand
|
||||
forty includes as easily as a filelist can name forty missing files. Its doc
|
||||
comment now says so; no code moved.
|
||||
|
||||
**Files touched outside this feature's own module**, all of them the wiring the
|
||||
brief asked for: `includes.rs` (`resolve_as_if`, `incdirs()`, `normalize` made
|
||||
public — no behaviour change), `watch.rs` (`watched` made public), `main.rs`
|
||||
(the module, the `workspace.fileOperations` capability, one test), `server.rs`
|
||||
(the request arm, the two notification arms, `reindex_for`, one doc sentence on
|
||||
`report_scope`, seven tests), `tests/e2e.rs` (one session and one `apply_edits`
|
||||
helper).
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy
|
||||
--all-targets` silent; `cargo test --workspace` green — **2105 passing, 5
|
||||
ignored**, 33 of them new (24 `file_ops`, 7 `server`, 1 `main`, 1 e2e session)
|
||||
plus the ignored perf probe. `node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` → OK, 9 messages, unchanged from `bf17ddd`
|
||||
(checked against the stashed tree, not assumed — the new capability is static
|
||||
JSON and adds no message). Perf measured as above. No new dependency, no
|
||||
version bump, no other crate touched.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent, file operations (TODO.md §9c)
|
||||
|
||||
Re-ran every gate, then attacked the list the lead handed down. One real bug
|
||||
found and fixed (small, unambiguous, in-scope — fixed directly per the
|
||||
workflow rules rather than kicked back to dev); everything else the dev
|
||||
claimed held up, including the single highest-risk detail.
|
||||
|
||||
**Verdict up front: the pre-rename-URI semantics are correct.** `will_rename`
|
||||
keys every edit off the path `Workspace::sources()` handed it — which is
|
||||
always the file's *current* (pre-rename) location, including for the mirror
|
||||
case where the edited file is itself one of the files being renamed. Read the
|
||||
code to confirm, then pinned it at the wire level, which the dev's own e2e
|
||||
session did not cover (it only exercised "another file's edit," not "the
|
||||
moving file's own edit"): added
|
||||
`a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire` to
|
||||
`crates/lucisv_server/tests/e2e.rs` — a real `willRenameFiles` round trip
|
||||
where the *renamed* file is also the includer needing the edit, asserting the
|
||||
`WorkspaceEdit`'s `changes` map is keyed by the **old** URI and does **not**
|
||||
contain the new one. Passes.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` silent (one warning surfaced in a QA-added test —
|
||||
`clippy::for_kv_map` on `for (_, edits) in &map` — fixed to `.values()`,
|
||||
noted below). `cargo test --workspace`: **2114 passed, 0 failed, 5 ignored**
|
||||
(2105 baseline + 1 e2e test + 8 new `file_ops` QA tests). Two full runs of
|
||||
`cargo test -p lucisv_server file_ops::` diffed byte-for-byte except for
|
||||
parallel test-execution order — no flakiness. `node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` → OK, 9 messages.
|
||||
|
||||
**Finding 1 (MEDIUM, fixed) — `candidate_spellings` silently fails when the
|
||||
includer's own path isn't already `.`/`..`-folded.**
|
||||
`crates/lucisv_server/src/file_ops.rs`, `candidate_spellings` (now around
|
||||
line 293) and `relative_spelling`. `target` (the rename's destination)
|
||||
always reaches `candidate_spellings` normalized — both `graph.resolve` and
|
||||
`Moves::after` fold `.`/`..` before returning. `includer` did not: it comes
|
||||
straight from `Workspace::sources()`, which inherits whatever `self.roots`
|
||||
was given at `open_roots`, unnormalized. `target.strip_prefix(dir)` and
|
||||
`relative_spelling`'s common-prefix walk are pure path-*component* algebra
|
||||
run before anything touches the filesystem, and `Path`'s components compare a
|
||||
literal `ParentDir` (`..`) as different from the directory it resolves to —
|
||||
so when `includer`'s directory carries an unfolded `..` and `target` doesn't,
|
||||
every rung silently fails to match, even the trivial "keep it bare" spelling
|
||||
for a same-directory rename. The include then gets a spurious "no include
|
||||
path reaches it" warning instead of the one-word edit it should get. Caught
|
||||
by the corpus-scale probe (below), not by any of the dev's or my
|
||||
hand-written unit tests — every `Tree`-based test in this feature builds
|
||||
`ws.open_roots(vec![tree.path.clone()])` from an already-clean
|
||||
`std::env::temp_dir()`-based path, so the bug had no way to show up there.
|
||||
`resolve`/`resolve_as_if`'s own existence checks (`Path::is_file`,
|
||||
`Moves::is_file`) were never affected — both fold `..` themselves before
|
||||
deciding, which is exactly why only this one pure-path step needed the fix.
|
||||
Fixed with one line, normalizing `includer` at the top of
|
||||
`candidate_spellings` before anything derives from it; comment explains why,
|
||||
inline. Real-world exposure: narrow but not zero — `workspace_roots` in
|
||||
`main.rs` never normalizes a client's `rootUri`/`workspace_folders` URI
|
||||
either, so any workspace root a client hands over with an unresolved `.`/`..`
|
||||
segment (unusual, but not forbidden by the URI grammar) would have hit this
|
||||
on every single same-directory rename, the most common case there is.
|
||||
Pinned by the corpus probe test itself (below), which fails without the fix
|
||||
and passes with it — no separate minimal regression test added, since the
|
||||
probe already exercises the exact shape that triggers it and a synthetic
|
||||
`Tree`-based one would have to manufacture a dirty root on purpose, which is
|
||||
what the probe already is.
|
||||
|
||||
**Attack surfaces, in the order asked for:**
|
||||
|
||||
1. **Wrong-edit hunts at the resolution boundary — verified clean.** Added
|
||||
`a_shadow_between_an_own_dir_file_and_an_incdir_file_is_never_crossed`: two
|
||||
`defs.svh`, one reached only via the includer's own directory and one only
|
||||
via an `+incdir+`, so a name-matching implementation would cross them.
|
||||
Renaming either one touches only the file that resolves to it, in both
|
||||
directions. `resolve_as_if`'s delegation from `resolve` is the same
|
||||
inlined closure `resolve` used before (`&|path| path.is_file()`) — no
|
||||
include-nav test needed updating, and the full suite confirms
|
||||
`documentLink`/`definition`/hover behavior is unchanged.
|
||||
2. **The three checks, adversarially — verified clean, one gap closed.**
|
||||
(a) `the_edit_range_is_exact_with_tab_indentation_and_a_block_comment`:
|
||||
tabs for indentation, a `/* block */` trailing comment instead of the
|
||||
dev's `//` line comment, byte range decoded and checked against the raw
|
||||
text — exact. (b) `a_rename_target_whose_name_contains_the_quote_delimiter_is_refused_not_written`:
|
||||
POSIX allows `"` in a filename (confirmed creatable on this filesystem),
|
||||
and with no other candidate spelling available the module is forced to
|
||||
either refuse or write a corrupting line — it refuses, warns, and the
|
||||
source file on disk is provably untouched. Also
|
||||
`a_rename_to_a_name_with_a_space_or_non_ascii_text_is_written_correctly`:
|
||||
space and non-ASCII (`défs.svh`) are legal inside quotes and both rewrite
|
||||
cleanly — the "total, correct" half of the same question. (c) the dev's
|
||||
`a_spelling_that_would_resolve_somewhere_else_is_not_written` is a genuine
|
||||
shadow: `rtl/defs.svh` pre-exists beside the includer, the bare candidate
|
||||
for the renamed `inc/old.svh` → `inc/defs.svh` would resolve to the wrong
|
||||
file via the own-directory rung, and the longer `../inc/defs.svh` is
|
||||
written instead — read through by hand and confirmed live by the suite.
|
||||
3. **The mirror case (includer moves) — verified clean, see the verdict
|
||||
above.** `Moves`'s own-dir-move handling and the pre-rename URI addressing
|
||||
are both correct.
|
||||
4. **Directory renames by prefix — verified clean.**
|
||||
`a_directory_rename_does_not_claim_a_sibling_with_a_shared_string_prefix`:
|
||||
`rtl` → `rtl2` with a `rtl_extra/` sibling holding its own decoy header,
|
||||
both referenced relatively from outside their own directories (so the
|
||||
test actually forces an edit rather than landing on the includer-and-
|
||||
included-move-together no-op). `rtl_extra`'s file is never touched, and
|
||||
`Moves`'s `mapped`/`strip_prefix` is checked directly too: `Path::strip_prefix`
|
||||
is component-wise, not string-wise, so `rtl_extra` was never at risk from
|
||||
this angle. Nested batch:
|
||||
`a_directory_rename_and_a_file_rename_inside_it_do_not_compound` —
|
||||
characterized, not "fixed": `Moves::after` uses `find_map`, so a directory
|
||||
rename and an explicit rename of a file inside it (a batch shape a
|
||||
spec-compliant client should not send, per LSP's "only the folder's own
|
||||
URI" rule, but nothing stops one from doing it) do not compound; whichever
|
||||
entry is listed first in `params.files` wins for any path under that
|
||||
directory, and the other is silently shadowed. Not corruption — whatever
|
||||
spelling gets written is still checked against whichever model `Moves`
|
||||
produced — but it is order-dependent in a way nothing documents.
|
||||
**Recommendation for dev, not fixed here (out of QA's remit to redesign):**
|
||||
either note this explicitly in the Assumptions section as an accepted
|
||||
ambiguity, or have `Moves::announced` detect a file entry nested under a
|
||||
directory entry in the same batch and drop the redundant one with a
|
||||
warning. Low priority — real clients don't appear to construct this shape.
|
||||
5. **Batch semantics — verified clean.**
|
||||
`a_batch_where_both_the_includer_and_the_included_move_needs_both_moves_modeled`:
|
||||
includer moves two directories deep, included file moves to an unrelated
|
||||
directory, in one batch. Chose depths that make "only one move modeled"
|
||||
produce a *textually different, wrong* answer both ways (dropping the
|
||||
includer's move is one `..` short; dropping the included file's move
|
||||
points at the old directory) — the actual answer is neither, confirming
|
||||
`Moves` truly models both simultaneously rather than one overwriting the
|
||||
other. The dev's own `a_batch_that_carries_includer_and_included_together_writes_nothing`
|
||||
is a real instance of this too (a no-op *requires* both moves to be seen
|
||||
together), just not one that discriminates between hypotheses on its own.
|
||||
6. **`didRename`/`didDelete` — verified clean.** Read `reindex_for` and the
|
||||
dispatch arms; the dev's own tests already cover in-scope → one reindex,
|
||||
out-of-scope → none, and the watcher-double case, and pass. Generation
|
||||
bumps once per `reindex()` call, so a client sending both
|
||||
`didRenameFiles` and a watcher event for the same move bumps it twice —
|
||||
documented as intentional ("a pure re-read of the tree"), matches
|
||||
`a_rename_notification_rebuilds_the_index`'s own assertion, no
|
||||
pull-diagnostics correctness issue (content converges, `resultId` just
|
||||
changes an extra time).
|
||||
7. **Capability shape on the wire — verified clean.** `main.rs`'s
|
||||
`the_file_operations_reach_the_wire_under_workspace` and `file_ops.rs`'s
|
||||
`the_capability_names_the_operations_this_server_answers` pin the exact
|
||||
JSON; folder filter present only on `willRename`, absent on both
|
||||
notifications, confirmed. Case sensitivity: the glob match is entirely the
|
||||
*client's* job (VS Code decides whether `TOP.SV` matches `**/*.{v,vh,sv,svh}`
|
||||
before it ever sends the request) — nothing in this server's code path is
|
||||
involved, so there is nothing here to fix or test; noting it per the
|
||||
brief's "don't over-engineer."
|
||||
8. **CLAUDE.md compliance — verified clean.** No `unwrap()`/`expect()`/
|
||||
`panic!` outside `#[cfg(test)]` in any of `file_ops.rs`, `server.rs`,
|
||||
`main.rs`, `watch.rs`, `includes.rs` (checked with a diff-scoped grep).
|
||||
Every public item has a one-line doc comment. This README's sections each
|
||||
appear exactly once. `TODO.md`'s §9c item text is unchanged; only its
|
||||
checkbox flipped and a delivery summary was appended below it, per the
|
||||
"leave the item text intact" rule. `verify.rs` does not appear in the diff
|
||||
at all.
|
||||
|
||||
**Beyond the list — corpus-scale probe.** `prim_assert.sv` (a single real
|
||||
file in `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/`) is included, own-
|
||||
directory rung, by 87 sibling files in that same directory — real fan-out,
|
||||
not a synthetic tree. Added
|
||||
`a_real_corpus_header_with_wide_fan_out_is_swept_correctly_and_deterministically`:
|
||||
sweeps the whole corpus with `will_rename` twice (identical file/warning
|
||||
counts both times), then independently re-derives, for every produced edit,
|
||||
whether the *written* spelling resolves to the new location once the
|
||||
modeled rename has happened (built the check from `resolve_as_if` +
|
||||
`Moves::announced` directly, deliberately not by calling back into
|
||||
`survives`, so it is a genuine second opinion) — and confirms every touched
|
||||
file's directory is the one real directory that includes this header,
|
||||
nothing else. This is the test that caught Finding 1: it failed outright
|
||||
before the fix (no edit was produced for any of the 87 files — every one
|
||||
came back as a false "unreachable" warning) and passes cleanly after.
|
||||
|
||||
**Test tally added this round:** 8 in `file_ops.rs` (`qa_2026_08_27_attacks`,
|
||||
nested under `mod tests`), 1 in `tests/e2e.rs`. `cargo test --workspace`:
|
||||
2114 passed (was 2105 before this QA round; +1 e2e +8 file_ops, net of the
|
||||
9 new tests exactly).
|
||||
|
||||
**Verdict: not committable as-is until Finding 1's fix is included** — which
|
||||
it now is, applied directly in this same working tree (small, unambiguous,
|
||||
in-scope per the workflow rules). With the fix in place and all eight attack
|
||||
surfaces plus the corpus probe green, this is **committable**. Item 4's
|
||||
nested-batch ordering is a documentation/robustness suggestion for the dev,
|
||||
not a blocker — no corruption path exists even in that shape, thanks to the
|
||||
safety net doing its job independently of what `Moves` models.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-27 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(2114 workspace tests, 0 failed), clean. For a feature that writes user
|
||||
files, the shape is right: resolution-not-name matching, a three-check
|
||||
safety net that refuses rather than guesses, and the mirror case the
|
||||
brief missed shipped with the same machinery rather than a special
|
||||
case. The two dev deviations are both accepted as argued — the moving
|
||||
includer's own-dir rung genuinely breaks, and re-spelling under a
|
||||
renamed +incdir+ beats warning about a filelist this server rightly
|
||||
does not edit.
|
||||
|
||||
The round's two QA results are exactly why the corpus probe belongs in
|
||||
every write-path charter: the unnormalized-includer bug made the most
|
||||
common rename shape (same directory) silently fail into a warning, and
|
||||
no hand-written fixture caught it — 87 real includers of a real ibex
|
||||
header did. And the pre-rename-URI wire test QA added covers the one
|
||||
detail that would have failed invisibly in real editors (a client
|
||||
drops an edit addressed to the post-rename uri). I applied QA's
|
||||
recommendation as an Assumptions entry: batch renames do not compound,
|
||||
recorded as a documented choice with the safety net bounding the
|
||||
failure mode at a skipped edit plus a warning. Accepted as shipped.
|
||||
@@ -51,6 +51,17 @@ per notification.
|
||||
current scope: the scope ladder re-applies during the rebuild anyway, and
|
||||
one rebuild for a stray in-tree `.sv` is much cheaper than duplicating the
|
||||
ladder's logic per event and getting it subtly wrong.
|
||||
- **A workspace-folder change does not need a new registration for the source
|
||||
glob** (added 2026-08-27 by folders-and-config). `SOURCE_GLOB` is a
|
||||
base-less *string* pattern, which the client matches against the workspace
|
||||
it currently holds, so a folder added mid-session is covered by the
|
||||
registration already in force; the `RelativePattern` form, which anchors a
|
||||
glob to one folder's URI and would have to be re-sent per folder, is
|
||||
deliberately not used. The **filelist** watcher is the exception: it is an
|
||||
absolute path, and a relative `lucisv.filelist` is resolved against the
|
||||
*first* root — so `server.rs` re-registers on a folder change whose
|
||||
`filelist_path()` differs, exactly as it already did for a changed setting.
|
||||
See `docs/features/folders-and-config/README.md`.
|
||||
- **Only the root filelist is watched, not its nested `-f` targets.**
|
||||
`lucisv_core::filelist::Filelist` reports the files a filelist names but not
|
||||
the filelists it *read*, and adding that field is a change to another
|
||||
|
||||
@@ -0,0 +1,568 @@
|
||||
# folders-and-config
|
||||
|
||||
Two small §9c items, one round, because they are the same shape: both are a
|
||||
piece of the session's *setup* that the server used to read exactly once and
|
||||
never again.
|
||||
|
||||
## Goal
|
||||
|
||||
**`workspace/didChangeWorkspaceFolders`.** Until this round the workspace
|
||||
roots were read at `initialize` and frozen for the life of the process, so
|
||||
"Add Folder to Workspace" (or closing one) changed nothing until the editor
|
||||
was restarted — a multi-repo SV project, which is the normal shape for a
|
||||
design plus its verification IP, could not be assembled without a reload. The
|
||||
server now advertises `workspace.workspaceFolders` (both halves) and adjusts
|
||||
its root set from the notification, rebuilding the index once per event.
|
||||
|
||||
**`workspace/configuration` (server-pull).** The `lucisv.*` settings only ever
|
||||
arrived by *push*, and the push is the legacy path: `vscode-languageclient`
|
||||
sends `didChangeConfiguration` with a real payload only where a
|
||||
`synchronize.configurationSection` is configured, and the modern arrangement
|
||||
is for the client to say "something changed" and for the server to fetch what
|
||||
it needs. The server now asks for the `lucisv` section at startup, and again
|
||||
on every empty `didChangeConfiguration`, gated on the client's own
|
||||
`workspace.configuration` capability. The answer goes through **the same
|
||||
parser** a push does, so the two paths cannot drift.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A subdirectory added as its own workspace folder is its own root.** It
|
||||
resolves its own `lucisv.toml` from its own tree, so the parent root's
|
||||
`exclude` does not reach into it — files the parent excluded become
|
||||
indexable through the child root (QA log F1, 2026-08-27; no
|
||||
double-indexing, no ambiguity). This is the per-root config model applied
|
||||
consistently to a shape that could not previously occur; a user who adds a
|
||||
subfolder as a root is asking for exactly that folder.
|
||||
|
||||
|
||||
- **A workspace folder is a directory on disk.** A folder whose URI is not a
|
||||
`file:` URI is dropped rather than guessed at — `uri.rs`'s rule everywhere
|
||||
else, and there is nothing to walk for a `vscode-vfs://` folder anyway.
|
||||
- **The root set is a list, not a set with an identity.** Roots are compared
|
||||
by path. A client that re-adds a folder it already sent, or removes one it
|
||||
never sent, changes nothing and is told nothing: the notification has no
|
||||
reply, and re-scanning to discover that the answer is the same is pure
|
||||
cost. Removals are applied before additions, so a folder named in *both*
|
||||
lists of one event survives (some clients spell a moved folder that way).
|
||||
- **Removing a folder does not close its buffers.** The client owns buffer
|
||||
lifecycle; LSP has no "the server dropped your file" message. An open buffer
|
||||
whose folder was closed keeps exactly the deal every out-of-scope buffer has
|
||||
always had — it is analyzed, diagnosed, formatted, and it still overrides
|
||||
disk in the index by contributing itself (`Workspace::collect_sources` adds
|
||||
every open document with a path, whatever the scope ladder said). Removing
|
||||
the *last* folder is not a special case either: the session becomes the
|
||||
rootless one rung 3 of the scope ladder already describes, where the scope
|
||||
is the open buffers' own directories.
|
||||
- **One set of settings per session, not one per folder.** The pull sends no
|
||||
`scopeUri`. `ClientSettings` is a single struct read by `format::settings_for`
|
||||
and the index scope, with no notion of "these settings, for files under that
|
||||
folder" — asking per-resource would be asking for answers there is nowhere
|
||||
to put. A multi-folder workspace where two folders want different indents
|
||||
should say so in a `lucisv.toml` per folder, which already works and already
|
||||
beats the editor setting.
|
||||
- **A pull answer is never an error.** A refusal, a `null` entry, an empty
|
||||
array, an object where an array belongs — all mean the same thing, "no
|
||||
settings for you", which is the defaults. The user did not ask for this
|
||||
request and cannot act on its failure, so nothing here opens a popup.
|
||||
- **Settings can arrive after the first index build**, and this round does not
|
||||
change that. The pull is sent at the same moment the watchers are registered
|
||||
— the earliest legal point for a server-initiated request — and answered
|
||||
later, in the loop. That is exactly what a pushed `didChangeConfiguration`
|
||||
has always done too (it cannot arrive before `initialized` either): the
|
||||
first index is built against the default scope, and a pulled
|
||||
`lucisv.exclude`/`lucisv.filelist` costs one extra rescan when it lands.
|
||||
Nothing is *wrong* in between, it is simply the wider scope.
|
||||
|
||||
## The settings model, stated once
|
||||
|
||||
| what arrives | what the server does |
|
||||
|---|---|
|
||||
| `didChangeConfiguration` with a payload (any non-empty object) | applied directly, through `settings::from_payload` — the legacy path, unchanged |
|
||||
| `didChangeConfiguration` with `settings: null` or `{}`, **and** `workspace.configuration` | pulls `workspace/configuration` for the `lucisv` section; nothing is applied until the answer comes back |
|
||||
| `didChangeConfiguration` with `settings: null` or `{}`, **no** capability | applied directly, which resolves to "no opinion about anything" — exactly what such a client got before this round |
|
||||
| startup, with `workspace.configuration` | one pull, unprompted |
|
||||
| startup, without it | nothing; settings only ever arrive by push |
|
||||
|
||||
Whichever door they came in, settings are adopted by one function —
|
||||
`Server::apply_settings` — so `exclude`/`filelist` cost the same rescan and the
|
||||
same watcher re-registration on both paths, and no third path can be added
|
||||
without going through it.
|
||||
|
||||
## The watcher determination
|
||||
|
||||
**The source-glob registration does not need re-sending when folders change.**
|
||||
`watch::registration` sends a `FileSystemWatcher` whose `globPattern` is the
|
||||
plain string `**/*.{v,vh,sv,svh}`. In LSP a *string* glob pattern carries no
|
||||
base URI, and the client matches it against the workspace it holds — VS Code
|
||||
re-evaluates such a pattern against its current folder set, so a folder added
|
||||
after registration is watched by the registration already in force. (The
|
||||
alternative shape, `RelativePattern`, anchors a glob to one folder's URI and
|
||||
*would* have to be re-sent per folder; this server has never used it, and
|
||||
adopting it would mean one watcher per root for no gain.)
|
||||
|
||||
**The filelist watcher does.** The second watcher in the same registration is
|
||||
an absolute path, and `Workspace::filelist_path` resolves a *relative*
|
||||
`lucisv.filelist` against `roots.first()`. So a folder event that changes which
|
||||
root is first — or that removes the root the setting was anchored to — moves
|
||||
the watched path without anyone touching the setting. The handler therefore
|
||||
compares `filelist_path()` before and after and re-registers when it moved:
|
||||
literally the same two lines `didChangeConfiguration` already ran, for the
|
||||
same reason (the watched path is baked into the registration).
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `lsp-types` 0.97:** `WorkspaceFoldersServerCapabilities
|
||||
{ supported, change_notifications }` — `change_notifications` is
|
||||
`OneOf<bool, String>` and is sent as `Left(true)`; the string form exists so
|
||||
the registration can be undone by id, and this server never unregisters it.
|
||||
`DidChangeWorkspaceFoldersParams { event: { added, removed } }`,
|
||||
`ConfigurationParams`/`ConfigurationItem`, and `WorkspaceConfiguration`
|
||||
(`Result = Vec<Value>`).
|
||||
|
||||
**Asked of `state.rs` (delivered, minimal):** one new public method,
|
||||
|
||||
```rust
|
||||
pub fn change_roots(&mut self, added: Vec<PathBuf>, removed: &[PathBuf]) -> bool
|
||||
```
|
||||
|
||||
which adjusts the private `roots` list and reports whether it moved, in the
|
||||
same shape `set_client_settings` already reports "you owe a rebuild". Nothing
|
||||
else in `state.rs` changed: `rebuild_index` walks `self.roots` and so already
|
||||
does the right thing for a wider or narrower set, and the rootless fallback
|
||||
(`default_files` → `sibling_files`) already covers "the last folder went
|
||||
away". The root list is deliberately *not* exposed — the server has no use for
|
||||
it beyond changing it, and `has_roots()` already answers the one question it
|
||||
does ask.
|
||||
|
||||
**Promised to `server.rs`'s other handlers:** `Pending` replaces the
|
||||
`applying: HashMap<RequestId, String>` map. Every server-initiated request
|
||||
whose answer matters is registered in one `pending: HashMap<RequestId,
|
||||
Pending>`; everything else (watcher registration, `workDoneProgress/create`,
|
||||
`codeLens/refresh`, `showDocument`) is still absent from it and still falls
|
||||
through `response` untouched. A future request kind that needs its answer read
|
||||
adds a variant, and the compiler names every place that must handle it. Two
|
||||
maps would have meant two lookups in `response` and two chances to forget one.
|
||||
|
||||
**`settings.rs` gained** `SECTION` (the one spelling of `"lucisv"`, used by the
|
||||
parser and by the pull's `ConfigurationItem`), `from_section` (a pull answer,
|
||||
wrapped back into the push shape so there is exactly one parser) and
|
||||
`says_nothing` (whether a push payload is really a pull signal).
|
||||
|
||||
**Nothing outside `crates/lucisv_server` was touched**, and no dependency was
|
||||
added. `editors/vscode` was deliberately left alone, and the interplay is
|
||||
worth stating: `extension.js` still sets
|
||||
`synchronize: { configurationSection: 'lucisv' }`, so VS Code keeps *pushing*
|
||||
a real payload — the legacy path, unchanged — while `vscode-languageclient`
|
||||
advertises `workspace.configuration` and `workspace.workspaceFolders` on its
|
||||
own and therefore also answers the startup pull (with the same section, read
|
||||
by the same parser, to the same result). Dropping the `synchronize` line
|
||||
would leave the pull in sole charge and is a client-side change for another
|
||||
round. `smoke.js` sends `capabilities: {}` — the no-capability polarity, and
|
||||
the one worth keeping under test.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `workspace.workspaceFolders: { supported: true, changeNotifications: true }`
|
||||
advertised, and pinned as JSON at the key a client reads.
|
||||
- [x] `workspace/didChangeWorkspaceFolders` handled: added/removed adjust the
|
||||
root set, one `reindex()` per notification.
|
||||
- [x] A removed folder's files leave the index; its open buffers stay open and
|
||||
keep being diagnosed.
|
||||
- [x] Duplicate adds, removing a never-added folder, an empty event, params
|
||||
that do not parse, a non-`file:` folder — all no-ops, none of them a
|
||||
rescan.
|
||||
- [x] Watcher determination made and implemented: source glob workspace-wide
|
||||
(no re-registration), filelist path anchored at the first root
|
||||
(re-registered when it moves).
|
||||
- [x] `workspace.configuration` read from the client's capabilities.
|
||||
- [x] One `workspace/configuration` at startup, gated on that capability.
|
||||
- [x] An empty `didChangeConfiguration` pulls instead of resetting; a
|
||||
populated one still applies directly.
|
||||
- [x] The answer applies through `settings::from_section` → the same
|
||||
`from_payload` a push uses, and through one `apply_settings`.
|
||||
- [x] `null`/empty/malformed/errored answers are total and leave the defaults.
|
||||
- [x] `applying` → `pending: HashMap<RequestId, Pending>`; three-way
|
||||
interleave tested.
|
||||
- [x] Tests: **27 new** — 4 in `settings.rs`, 4 in `state.rs`, 14
|
||||
`Session`-level in `server.rs`, 3 capability tests in `main.rs`, 2 e2e
|
||||
sessions against the real binary.
|
||||
- [x] `docs/features/lucisv-server/README.md` capability table and the
|
||||
roots/settings model text updated; `docs/features/file-watching/README.md`
|
||||
told about the folder interaction; TODO.md §9c boxes checked.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev agent
|
||||
|
||||
**Item 1, `didChangeWorkspaceFolders`.**
|
||||
|
||||
- `main.rs::capabilities` now sends `workspace.workspaceFolders` with both
|
||||
fields. They are separate statements and a client reads them separately:
|
||||
`supported` says the server understands a multi-folder workspace at all,
|
||||
`changeNotifications` is what makes the client *send* the notification.
|
||||
`change_notifications` is `OneOf<bool, String>` in lsp-types 0.97 (checked
|
||||
against the crate source, not assumed); `Left(true)` is the right form here
|
||||
because the id-string variant exists only so the registration can later be
|
||||
unregistered by name, which this server never does.
|
||||
- `state.rs::change_roots` is the whole of the state change — 8 lines. Roots
|
||||
were already a private `Vec<PathBuf>` that `rebuild_index` re-walks from
|
||||
scratch, so widening and narrowing the set is genuinely nothing more than
|
||||
editing that list. Removals before additions; `bool` out, in the same shape
|
||||
`set_client_settings` uses, so the server's "did this cost a rescan?"
|
||||
question is asked the same way for both kinds of change.
|
||||
- The handler is five lines of body: parse, convert URIs to paths, change the
|
||||
roots, reindex if they moved, re-register the watchers if the *filelist*
|
||||
path moved. One `reindex()` per notification — an event carries both lists,
|
||||
and the progress bar, the code-lens refresh and the diagnostics generation
|
||||
all ride inside `reindex()` already, which
|
||||
`one_folder_notification_is_one_rescan_with_one_bar_and_one_generation` pins
|
||||
rather than assumes.
|
||||
- **The open-buffer question resolved by reading, not by inventing.** The
|
||||
brief asked that buffers in a removed folder keep behaving like rootless /
|
||||
out-of-scope buffers. They already do, and no code was needed:
|
||||
`collect_sources` appends every open document with a path *after* the scope
|
||||
ladder has spoken, so such a buffer stays in the index as itself; `reindex`
|
||||
republishes every open URI whatever the roots say; and `didOpen`'s
|
||||
root-conditional (`has_roots()` → publish, else reindex) reads the current
|
||||
root set, so a session that has lost its last folder starts behaving like
|
||||
the single-file case from the next `didOpen` on. The two tests
|
||||
(`a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed`,
|
||||
`removing_the_last_root_falls_back_to_the_rootless_model`) exist to keep
|
||||
that true, not to describe something new.
|
||||
- **The watcher determination** is written up in its own section above. Short
|
||||
version: the source glob is a base-less string pattern and is workspace-wide,
|
||||
so it needs no re-registration; the filelist watcher is an absolute path
|
||||
anchored at the first root, so it does — and the handler reuses the exact
|
||||
before/after comparison `didChangeConfiguration` already made.
|
||||
|
||||
**Item 2, `workspace/configuration`.**
|
||||
|
||||
- `ClientAbilities::configuration`, read in `main.rs` from
|
||||
`capabilities.workspace.configuration`, in the same shape as its five
|
||||
siblings.
|
||||
- `Server::request_configuration` sends one item, `section: "lucisv"`, no
|
||||
`scopeUri`, and records the id as `Pending::Configuration`. It is called
|
||||
from `Server::new` (immediately after `register_watchers`, which is the
|
||||
earliest legal moment and already proven so by the file-watching round) and
|
||||
from the `didChangeConfiguration` handler when the payload says nothing.
|
||||
- **Pending-map decision: one map, an enum, refactored.** The alternative was
|
||||
a second `HashMap<RequestId, ()>` beside `applying`. One map won: `response`
|
||||
is then a single lookup and a single `match`, the "which of our requests is
|
||||
this?" question has exactly one answer rather than one per map, and a third
|
||||
kind is a variant the compiler makes you handle instead of a map somebody
|
||||
forgets to consult. The cost is a rename (`applying` → `pending`) and one
|
||||
extracted function (`applied`, which is the old body verbatim). The
|
||||
fall-through that makes every *other* server-initiated request's answer
|
||||
ignorable is unchanged and still the documented rule.
|
||||
- **One parser, spelled out.** A pull answers the *contents* of the section;
|
||||
a push nests them under `lucisv`. Rather than a second reader,
|
||||
`settings::from_section` wraps the answer back into the push shape and calls
|
||||
`from_payload`. `a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one`
|
||||
asserts the two agree on a fully-populated section *and* on a fully-junk
|
||||
one, which is the half that would actually rot.
|
||||
- **One applier.** The body of the old `didChangeConfiguration` arm became
|
||||
`Server::apply_settings` (rescan on a scope change, re-register on a moved
|
||||
filelist path) and both doors now go through it. There is no way to adopt
|
||||
settings without paying what they cost.
|
||||
- `settings::says_nothing` decides push-vs-pull: `null` and `{}` are the
|
||||
client saying "come and ask"; anything with a key in it is a payload, even
|
||||
when the key is some other server's section (that case has always meant "no
|
||||
opinion about anything" and still does).
|
||||
- **Deliberate non-change:** the pull's answer can land after the first index
|
||||
build. Stated in Assumptions, not fixed — blocking `Server::new` on a client
|
||||
round trip would be a deadlock waiting to happen (the spec lets a client
|
||||
answer whenever it likes) and the push path has always had the same shape.
|
||||
|
||||
**Tests.** 4 new in `settings.rs` (pull/push parser agreement, unusable
|
||||
answers, the push-empty predicate, the section constant), 4 new in `state.rs`
|
||||
(add/remove, every no-op shape, a folder in both lists, the last-folder
|
||||
fallback), 14 new `Session`-level tests in `server.rs` (folder add reaching
|
||||
`workspace/symbol`, removal with a still-diagnosed buffer, one-rescan-per-
|
||||
notification with bar/publish/refresh/generation counts, the six no-op shapes,
|
||||
the watcher re-registration polarity, the startup pull's params, the no-pull
|
||||
polarity, a pulled answer reaching the formatter, a pulled `exclude` rebuilding
|
||||
the index, seven unusable answers plus an error response, empty-push-pulls,
|
||||
empty-push-without-the-capability, populated-push-applies-directly, and the
|
||||
three-way interleave), 3 new capability tests in `main.rs`, and 2 new e2e
|
||||
sessions (a folder added and removed over the wire with a definition resolving
|
||||
into it, and a full pull round trip including the re-pull and the `null`
|
||||
answer).
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
|
||||
clean; `cargo test --workspace` green (982 in the server binary, 48 e2e);
|
||||
`node editors/vscode/smoke.js` OK. One flake seen and *not* caused here:
|
||||
`lens::code_lenses_for_a_whole_file_cost_about_one_workspace_walk` is a
|
||||
wall-clock ratio test and fails under a loaded machine — it passes on its own
|
||||
and in a normal `--workspace` run.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent
|
||||
|
||||
Reviewed the working tree on top of `45db6cd` (`git diff 45db6cd`), against
|
||||
the dev's claims above and the lead's attack-surface list. Verified by
|
||||
reading every changed line in `main.rs`/`server.rs`/`settings.rs`/`state.rs`/
|
||||
`tests/e2e.rs`, then attacking each surface below — mostly by adding a
|
||||
pinning test that exercises it directly rather than by inspection alone,
|
||||
since a claim about interleaving or wire order is only as good as a test
|
||||
that would fail if it were wrong. No redesign; two small additions beyond
|
||||
tests (both noted below) were within "small and unambiguous."
|
||||
|
||||
**Gates.**
|
||||
- `cargo fmt --all -- --check`: clean (after my own additions were formatted
|
||||
— one round of `cargo fmt --all` was needed once I'd added tests by hand).
|
||||
- `cargo clippy --all-targets`: clean, no warnings, before and after my
|
||||
additions.
|
||||
- `cargo test --workspace`, run twice end-to-end: green both times, no
|
||||
failures, no flake. Baseline was 982 `lucisv_server` unit tests as the dev
|
||||
reported; ended at 993 after the 11 tests I added (see below). 48 e2e tests
|
||||
green throughout.
|
||||
- The lens flake (`lens::code_lenses_for_a_whole_file_cost_about_one_workspace_walk`,
|
||||
`crates/lucisv_server/src/lens.rs:652`): did **not** fire in two full
|
||||
`cargo test --workspace` runs, nor in 5 back-to-back runs of that test
|
||||
alone with four `yes > /dev/null` processes competing for CPU
|
||||
(ratio stayed ~1.4–1.5x against the 2x budget each time). Did not need to
|
||||
check it at `45db6cd` since it never reproduced here — nothing in this
|
||||
diff touches `lens.rs`, and the test is a wall-clock ratio exactly as the
|
||||
dev described, so I take the dev's report at face value. Not a blocker.
|
||||
- `node editors/vscode/smoke.js target/debug/lucisv-server` (had to pass the
|
||||
path explicitly — `lucisv-server` is not on `PATH` in this checkout):
|
||||
`OK`. This is the no-capability (`capabilities: {}`) polarity, so it
|
||||
exercises the "client can't be asked, keeps today's behaviour" branch of
|
||||
both features.
|
||||
|
||||
**Attack surfaces — verdicts.**
|
||||
|
||||
1. **`roots.first()` dependency.** Verified clean, with new pins.
|
||||
`Workspace::change_roots` (`state.rs:138`) removes before adding and dedups
|
||||
adds via `contains`, so insertion order is preserved and a folder can only
|
||||
ever appear once — confirmed by
|
||||
`a_folder_added_twice_across_two_events_is_absent_after_one_removal`
|
||||
(new, `state.rs`): two separate add events for the same path plus one
|
||||
removal leaves it fully absent, not merely "count decremented." The
|
||||
remove-then-add-reorders-first case is exactly what
|
||||
`a_folder_change_re_registers_the_watchers_only_when_the_watched_path_moves`
|
||||
(existing, `server.rs:4908`) already pinned end to end (drop the first
|
||||
root, watch the second's `files.f`, both the reindex and the
|
||||
unregister+register fire). The "no roots left" total case was **not**
|
||||
pinned before this round: added
|
||||
`removing_the_last_root_leaves_a_relative_filelist_unanchored`
|
||||
(`state.rs`, near line 549) — `filelist_path()` returns the bare relative
|
||||
path (`PathBuf::from("files.f")`), anchored at nothing, once the last root
|
||||
is gone. Nothing panics and `source_files` still degrades to the rootless
|
||||
walk with a warning when that bare path can't be read
|
||||
(`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so`
|
||||
already covers that half) — but it is a real, newly-reachable oddity
|
||||
(see finding F1 below) rather than an outright bug.
|
||||
|
||||
2. **`Pending` refactor / applyEdit routing.** Verified clean. The pre-existing
|
||||
applyEdit round's tests (`a_command_pushes_its_edit_...`,
|
||||
`a_response_with_a_jsonrpc_error_is_reported_too`,
|
||||
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`,
|
||||
etc.) are untouched by the diff and green. `three_outstanding_requests_are_answered_by_id_in_any_order`
|
||||
(`server.rs:5127`) does genuinely have all three requests
|
||||
(`applyEdit`, `workDoneProgress/create`, `workspace/configuration`)
|
||||
outstanding simultaneously before any answer — confirmed by reading
|
||||
`Session::sent`: it drains the channel once and the test pulls all three
|
||||
ids from that single drain — and answers them out of the send order
|
||||
(pull, then create, then edit) with each answer reaching the right
|
||||
handler. Two follow-up questions the dev's tests didn't cover, both now
|
||||
pinned: **two `Configuration` entries pending at once, answered out of
|
||||
order** — new `two_outstanding_configuration_pulls_are_each_answered_by_their_own_id`
|
||||
(`server.rs`): each answer is applied independently through its own id;
|
||||
whichever is *processed* last is what's in force after, no id-based
|
||||
precedence, which is the only sane semantics for a `HashMap` keyed by id.
|
||||
**An answer to an id `pending` doesn't hold** — new
|
||||
`an_answer_to_a_request_the_server_never_tracked_is_silently_ignored`
|
||||
(`server.rs`): a stale re-answer to an already-consumed id, and an id
|
||||
never sent at all, are both no-ops (trivially true from
|
||||
`HashMap::remove`'s `Option`, but worth a test that would catch a future
|
||||
refactor that made `response` assume the id is always present).
|
||||
|
||||
3. **Settings pull correctness.** Verified clean, with one real gap closed.
|
||||
`configured` (`server.rs:1174`) reads `response_result.unwrap_or(Value::Null)`
|
||||
then `answered.get(0)` — a client answering with 2 entries silently uses
|
||||
only entry 0 (correct: exactly one item was asked for), 0 entries or a
|
||||
non-array (`get(0)` on a string/number returns `None`) both fall through
|
||||
to `Value::Null` → defaults; `an_unusable_pull_answer_leaves_the_defaults_and_says_nothing`
|
||||
(`server.rs:5091`, pre-existing) already covers `null`, `[]`, `[null]`, a
|
||||
bare string, an object, junk-typed fields, and a `lucisv`-nested answer
|
||||
(the pull/push shape mismatch), plus an actual JSON-RPC error response —
|
||||
all resolve to defaults with no popup. `a_pulled_answer_that_changes_the_scope_rebuilds_the_index`
|
||||
(`server.rs:5048`, pre-existing) does assert the **index** actually
|
||||
changed (`indexed(&session, "scratch_pkg")` flips from 1 to 0), not just
|
||||
"no crash" — confirmed by reading it, not just trusting the name.
|
||||
**Gap found and closed:** nothing exercised a pulled *filelist* moving the
|
||||
watched path — `apply_settings` is shared code so it was very likely
|
||||
already correct, but "very likely" isn't "pinned." Added
|
||||
`a_pulled_filelist_re_registers_the_watchers_through_the_same_chain_a_push_uses`
|
||||
(`server.rs`, next to the exclude test): a pulled `{"filelist": "files.f"}`
|
||||
does cost an unregister+register with the new absolute path in the
|
||||
registration, exactly like the pushed case. **Precedence, traced and now
|
||||
pinned both directions:** the loop is single-threaded and processes
|
||||
messages in strict receive order; `apply_settings` always replaces the
|
||||
whole `ClientSettings` struct rather than merging, so whichever message is
|
||||
*processed* last wins, full stop. `a_push_with_a_payload_is_applied_directly_even_when_the_client_could_be_asked`
|
||||
(pre-existing) covers pull-then-push; added
|
||||
`a_late_pull_answer_overrides_a_push_that_landed_while_it_was_outstanding`
|
||||
for the other direction (push arrives while a pull is still outstanding,
|
||||
the pull's answer lands after and clobbers it). Both are "last processed
|
||||
wins," no special-casing either way — worth knowing, not worth fixing.
|
||||
|
||||
4. **Folder-change semantics.** Mostly verified clean; one real (low-severity,
|
||||
arguably by-design) finding.
|
||||
- Definition into an added folder: `a_folder_added_mid_session_is_indexed_over_the_wire`
|
||||
(e2e, pre-existing) asserts the returned location's `uri` string equals
|
||||
the expected `file://` URI exactly, which is as much "decoded correctly"
|
||||
as a same-process round trip can show without deliberately using a
|
||||
percent-encoded character in the added folder's path (this round's e2e
|
||||
test doesn't; existing coverage for URI-decoding a workspace path with
|
||||
unusual characters lives in `include_nav_round_trips_in_a_workspace_whose_directory_has_a_space`,
|
||||
unrelated to folder-add specifically). Did not add a new e2e test for
|
||||
this — the marginal risk is in `uri::uri_to_path`, which is untouched by
|
||||
this round and already has its own coverage.
|
||||
- Removed folder's symbols gone from `workspace/symbol`:
|
||||
`a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed`
|
||||
confirms via `indexed()` (an index-membership check, equivalent to what
|
||||
`workspace/symbol` reads from) that the removed folder's non-open file
|
||||
drops to 0 hits; `a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol`
|
||||
drives a real `workspace/symbol` request for the added-folder case.
|
||||
- **F1 — subdirectory added as its own root bypasses the parent's
|
||||
`exclude`.** New test
|
||||
`a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed`
|
||||
(`state.rs`) confirms there is **no** double-indexing/ambiguity when an
|
||||
already-covered subdirectory is added as a second root — `walked_files`'s
|
||||
`sort()`+`dedup()` on the combined path list handles that correctly, and
|
||||
`indexed()`'s "found exactly once" check would have caught an ambiguous
|
||||
double-registration if there were one. But a directory the parent root's
|
||||
`lucisv.toml` excludes **is** reachable once it's added as a root in its
|
||||
own right, because `walked_files` (`state.rs:365`) resolves each root's
|
||||
`exclude` independently via `Discovery::for_dir(root)`, and nothing
|
||||
excludes a root from itself. This is consistent with the documented
|
||||
per-root config model (`walked_files`'s own doc comment says so) and
|
||||
arguably *correct* — "Add Folder to Workspace" on a specific directory is
|
||||
an explicit ask to index it — but it was unreachable before this round
|
||||
(roots were frozen at `initialize`), so it's a genuinely new behavior the
|
||||
dev's README doesn't mention. Recommend a one-line callout in
|
||||
Assumptions if the lead agrees it's intentional; not a blocker either way,
|
||||
and not a corruption risk (formatter output is verified regardless of
|
||||
what got indexed).
|
||||
- Folder added twice then removed once: set semantics confirmed (new test,
|
||||
see item 1 above) — present after two adds, absent after one removal,
|
||||
not "still there because it was added twice."
|
||||
- Trailing slash: verified clean, and pinned anyway since the README calls
|
||||
it out as a boundary worth checking. `uri_to_path` decodes the URI
|
||||
verbatim (trailing slash included), but `PathBuf`/`Path` equality
|
||||
compares `Components`, not raw bytes — `Path::new("/a/b/") == Path::new("/a/b")`
|
||||
is `true` in std, confirmed with a throwaway `rustc` check before writing
|
||||
the test — so `change_roots`'s `contains`/`retain` already treat them as
|
||||
the same folder with no code needed. New:
|
||||
`a_trailing_slash_in_the_removed_folder_still_matches_the_held_root`
|
||||
(`state.rs`).
|
||||
|
||||
5. **Open-buffer convention.** Verified clean, one gap closed.
|
||||
`a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed`
|
||||
does assert diagnostics *content* — `!published[0].diagnostics.is_empty()`
|
||||
after editing the buffer to be broken, not merely "a publish happened."
|
||||
Closing such a buffer was **not** exercised — added a continuation of the
|
||||
same test (`server.rs`, same test) that sends `didClose` afterward and
|
||||
confirms the diagnostics clear (`published[0].diagnostics.is_empty()`).
|
||||
The code path (`DidCloseTextDocument` handling, `server.rs:1100`) is
|
||||
pre-existing and untouched by this diff — it doesn't special-case removed
|
||||
folders at all, which is correct: closing is generic.
|
||||
|
||||
6. **Startup pull ordering.** Verified clean, gap closed. `Server::new`
|
||||
(`server.rs:178`) calls `register_watchers()` then `request_configuration()`
|
||||
in that order in the source, but nothing checked the *wire*. Added
|
||||
`the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire`
|
||||
(`server.rs`): checks both the drained-channel order and, independently,
|
||||
that the `RegisterCapability` request's `lucisv-N` id number is lower than
|
||||
the pull's (every outgoing request id comes off one monotonically
|
||||
increasing counter in `send_request`, `server.rs:1251`, so the numeric
|
||||
suffix *is* the send order — a second, independent way to catch a future
|
||||
reordering that a channel-order check alone might not). The full chain —
|
||||
pull answer → `apply_settings` → filelist moved → re-register — is now
|
||||
pinned by item 3's `a_pulled_filelist_re_registers_the_watchers_...` test.
|
||||
"Pulled settings can land after the first index build" is honestly
|
||||
documented in Assumptions and in the Work log; I didn't find anywhere it's
|
||||
overstated.
|
||||
|
||||
7. **CLAUDE.md compliance.** Clean.
|
||||
- No `unwrap()`/`expect()`/`panic!` in the non-test portion of
|
||||
`main.rs`/`server.rs`/`settings.rs`/`state.rs` (checked by slicing each
|
||||
file at its `#[cfg(test)]` boundary and grepping the part before it —
|
||||
all four files have exactly one such boundary).
|
||||
- New public items have doc comments: `Workspace::change_roots`,
|
||||
`settings::SECTION`, `settings::from_section`, `settings::says_nothing`,
|
||||
`ClientAbilities::configuration` all do. (Three *pre-existing* undocumented
|
||||
`pub fn`s in `state.rs` — `index`, `document`, `close_document` — are out
|
||||
of this round's diff and not this review's problem.)
|
||||
- `docs/features/folders-and-config/README.md` has every required section
|
||||
exactly once (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA
|
||||
log, Review), plus two extra explanatory sections which the template
|
||||
doesn't forbid.
|
||||
- Both `TODO.md` §9c items are checked with their original text intact and
|
||||
a `→ delivered ...` addendum appended, not rewritten.
|
||||
- `crates/vlog_formatter/src/verify.rs`: zero diff against `45db6cd`
|
||||
(`git diff 45db6cd -- '**/verify.rs'` is empty) — untouched, as this
|
||||
round should never need it (nothing here touches formatting or
|
||||
verification).
|
||||
- `docs/site/` untouched by both the dev's diff and by me (per this
|
||||
round's instructions, never opened it).
|
||||
|
||||
**C. Beyond the list — "own shapes."**
|
||||
- `a_rapid_add_remove_add_of_the_same_folder_costs_three_rescans_and_ends_up_added`
|
||||
(`server.rs`): add, remove, add of the same folder across three separate
|
||||
notifications costs three separate rescans (no cross-notification
|
||||
batching — `change_roots` only batches within one event, as designed) and
|
||||
the net state (two adds, one remove) is "present," matching set semantics.
|
||||
- `a_rootless_session_gaining_its_first_folder_flips_didopen_from_reindex_to_publish`
|
||||
(`server.rs`): a session that starts with no roots at all (impossible to
|
||||
change mid-session before this round) gains its first folder via
|
||||
`didChangeWorkspaceFolders`, and the very next `didOpen` correctly takes
|
||||
the `has_roots()` branch — publish only, no second rescan — where it would
|
||||
have reindexed before the folder arrived. (Caught my own arithmetic error
|
||||
writing this: `generation` counts *both* a buffer's text and the index, so
|
||||
a rootless `didOpen` costs two bumps — `set_document` plus `reindex` — not
|
||||
one; fixed the assertion rather than the code, since the code is correct
|
||||
and pre-existing.)
|
||||
|
||||
**Fixes made directly (small, unambiguous, noted here per the workflow).**
|
||||
- None to production code. Everything above is test-only: 11 new tests
|
||||
across `state.rs` (5) and `server.rs` (6), all passing, `cargo fmt`/
|
||||
`clippy` clean throughout. `cargo test --workspace` ended at 993
|
||||
`lucisv_server` unit tests (982 dev baseline + 11) plus the unchanged
|
||||
48 e2e, both green across two full runs.
|
||||
|
||||
**Verdict: committable as-is.** No corruption risk, no invariant violated,
|
||||
no test that should exist and doesn't after this pass. F1 (subdirectory
|
||||
root bypassing parent's exclude) is worth a documentation line from the lead
|
||||
or dev — not worth blocking on, since it's arguably correct behavior and
|
||||
carries no data-loss or formatting-correctness risk.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-27 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. Both items landed the way small protocol features should: the
|
||||
folder handler is one 8-line state method plus the existing reindex
|
||||
machinery (with the bar, the lens refresh and the generation all pinned
|
||||
as riding along rather than assumed), and the config pull reuses the one
|
||||
settings parser and the one applier so the two doors cannot drift. The
|
||||
watcher determination — base-less glob needs nothing, the absolute-path
|
||||
filelist watcher re-registers through the comparison the push path
|
||||
already ran — is the kind of read-first engineering this workflow is
|
||||
for. The Pending-enum refactor is accepted: one map, one match, and a
|
||||
third request kind is now a compiler-enforced variant; QA re-ran the
|
||||
apply-edit suite and interleaved all three answer kinds out of order to
|
||||
prove the shipped routing survived.
|
||||
|
||||
QA's roots.first() attack found the design holds (order preserved,
|
||||
last-root-removal total) and its eleven added tests closed every
|
||||
claim that lacked one, including the previously-untested
|
||||
pull-answer-moves-the-filelist chain. F1 is accepted as designed and
|
||||
now documented in Assumptions: a subdirectory added as its own root is
|
||||
its own root, per-root config applied consistently. The extension's
|
||||
redundant push+pull double-answer stays filed for a client-side round.
|
||||
Accepted as shipped.
|
||||
@@ -0,0 +1,415 @@
|
||||
# incremental-sync
|
||||
|
||||
## Goal
|
||||
|
||||
Move the server from `TextDocumentSyncKind::FULL` to
|
||||
`TextDocumentSyncKind::INCREMENTAL`: a `didChange` now carries the ranges the
|
||||
user touched rather than the whole buffer, and the server applies them to the
|
||||
text it already holds. Full-buffer sync re-serializes, re-transfers and
|
||||
re-allocates the entire file on every keystroke, which is the wrong cost curve
|
||||
for a server that wants to answer per-keystroke (completion, signature help,
|
||||
inlay hints) — and for the editor side of a large `.sv` it is the one place
|
||||
lucisv was measurably ruder than ruff. The price of the move is that the server
|
||||
becomes the *only* holder of the buffer's text: a wrong offset here silently
|
||||
rewrites what the user is looking at, with no full-text resend to correct it.
|
||||
That is why the whole edit application is one pure function
|
||||
(`sync::apply_changes`), unit-tested against a second implementation, with no
|
||||
slice that can panic.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Positions are UTF-16, as `capabilities()` says.** Every conversion goes
|
||||
through `convert::Positions::offset`, the same function every other request
|
||||
handler uses. There is no second offset arithmetic in this feature — that is
|
||||
the point.
|
||||
- **Clamping, exactly.** A client desync (or an editor rounding a position) must
|
||||
never panic and never corrupt. The rules, all of them inherited from
|
||||
`Positions::offset` and pinned by tests in `sync.rs`:
|
||||
- a **line past the end** of the document clamps to the end of the document;
|
||||
- a **character past the end of a line's content** clamps to that content's
|
||||
end — before the line's `\n`, and before one `\r` preceding it, so an edit
|
||||
positioned past the visible end of a CRLF line cannot land between the
|
||||
`\r` and the `\n`;
|
||||
- a **character landing inside a surrogate pair** (the low half of an astral
|
||||
character such as `🎉`) **rounds forward** past the whole character. So a
|
||||
range boundary can never split a `char`, the output is always valid UTF-8,
|
||||
and an emoji is either wholly inside the replaced range or wholly outside
|
||||
it;
|
||||
- **`start > end` after conversion** clamps `end` up to `start`, which turns
|
||||
the change into a pure insertion at `start`. There is no resync mechanism
|
||||
in LSP short of the client closing and reopening the buffer, so the safe
|
||||
direction is the one that deletes nothing: a user can undo an unexpected
|
||||
insertion, but cannot recover text the server threw away.
|
||||
- **Each change is positioned against the document the previous changes in the
|
||||
same notification left.** This is what the protocol says, and it is why the
|
||||
line table is rebuilt per change rather than once per notification.
|
||||
- **A change with no `range` replaces the whole document**, mid-batch included,
|
||||
and resets the state the ranges after it are positioned against. A batch of
|
||||
rangeless changes therefore still ends at the last one — the pre-existing
|
||||
full-sync behavior, kept for a client that ignores the new capability.
|
||||
- **An empty `contentChanges` array is not a change**: nothing is reparsed and
|
||||
the generation counter does not move, exactly as before (the old handler's
|
||||
`next_back()` on an empty list did nothing).
|
||||
- **A `didChange` for a buffer that was never opened** is out of protocol, but
|
||||
is still taken rather than dropped: the base text is `""`, so a full-text
|
||||
change lands exactly as it did before this feature, and a ranged change
|
||||
clamps to an insertion at the start. No special case, no error path.
|
||||
- **`O(changes × file)` per notification, honestly.** Every ranged change
|
||||
builds a fresh `LineIndex` over the current text and allocates a new `String`.
|
||||
For the batch sizes editors actually send (1–5 ranges) over Verilog files
|
||||
this is microseconds, and it buys a function with no incremental state that
|
||||
can fall out of step with the text. A rope or an incrementally-patched line
|
||||
table is the optimization to reach for if a profile ever asks; TODO.md §6
|
||||
already defers that whole class of work.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `convert::Positions::offset`** (`crates/lucisv_server/src/convert.rs`)
|
||||
for every position→byte conversion, and `vlog_parser::LineIndex` to build it.
|
||||
Nothing was changed in either — the clamping this feature depends on is the
|
||||
clamping those already documented and tested.
|
||||
- **Promises `Server::set_document` is still called exactly once per
|
||||
`didChange` notification.** `set_document` bumps `self.generation`, which is
|
||||
the whole `resultId` of `docs/features/pull-diagnostics/README.md`; a bump
|
||||
per *range* would make one keystroke look like several to a pulling client,
|
||||
and no bump would let a changed buffer answer "unchanged". One notification =
|
||||
one reparse = one stamp = one `publish`. Pinned by
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`.
|
||||
- **Changes what the client is told at `initialize`.**
|
||||
`text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true,
|
||||
change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and
|
||||
`save` values are not new behavior: they are what a bare `Kind` already
|
||||
resolved to client-side (`vscode-languageclient` expands a numeric
|
||||
`textDocumentSync` to exactly `{ openClose: true, change: <kind>, save: {
|
||||
includeText: false } }`), written out because the options form has no
|
||||
"unspecified" that means the same thing. `didSave` therefore carries no text,
|
||||
which is what it carried before — and the `DidSaveTextDocument` handler still
|
||||
adopts `params.text` if some client sends it anyway, so nothing regresses for
|
||||
a client that behaves differently.
|
||||
- **No other crate is touched.** No new dependency; the randomized test's
|
||||
generator is a five-line LCG rather than `rand`.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Advertise `TextDocumentSyncOptions` with `change: INCREMENTAL`,
|
||||
preserving the open/close and save semantics a bare `Kind` implied.
|
||||
- [x] `sync::apply_changes(text, changes) -> String` — pure, total, no
|
||||
panicking slice.
|
||||
- [x] All changes applied in order, each against the previous one's result.
|
||||
- [x] Rangeless change = whole-document replace, mid-batch included.
|
||||
- [x] Clamping rules (line past EOF, character past line end, surrogate half,
|
||||
`start > end`) defined above and tested.
|
||||
- [x] One `set_document` — one reparse, one generation bump, one publish — per
|
||||
notification.
|
||||
- [x] Unit tests: insert/delete/replace, dependent batches, multi-byte and
|
||||
astral characters, CRLF, (0,0), EOF, no trailing newline, rangeless
|
||||
mixed into a batch, every clamping rule.
|
||||
- [x] Randomized cross-check against a second implementation built on
|
||||
`char`s and lines, fixed seed, 400 cases.
|
||||
- [x] Server-level tests: incremental batch == one full change, generation
|
||||
bumps once, full-sync batch still ends at the last change, publishes
|
||||
reflect the composed text.
|
||||
- [x] e2e test driving the real binary with four ranges over two
|
||||
notifications.
|
||||
- [x] `docs/features/lucisv-server/README.md` sync/staleness text updated.
|
||||
- [x] TODO.md §9b item checked off.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-26 — dev.** Implemented the whole feature in one round.
|
||||
|
||||
- New module `crates/lucisv_server/src/sync.rs` (declared in `main.rs`), one
|
||||
public function `apply_changes(&str, &[TextDocumentContentChangeEvent]) ->
|
||||
String`. Chosen over putting it in `convert.rs`: `convert.rs` is the
|
||||
byte↔position primitive every handler shares, and this is a protocol-level
|
||||
policy (ordering, rangeless resets, desync clamping) built *on* it. Keeping
|
||||
them apart means the safety-critical policy has its own test module and its
|
||||
own reference implementation to be checked against.
|
||||
- The function is deliberately dumb: `String` in, `String` out, a fresh
|
||||
`LineIndex` per ranged change. No incremental line table, no rope, no
|
||||
reusable "document buffer" abstraction for a second user that does not
|
||||
exist. The cost is written down under Assumptions rather than optimized away.
|
||||
- **No panicking slice.** `start`/`end` come from `Positions::offset`, which
|
||||
only ever returns character boundaries, so `text[..start]` would be provably
|
||||
safe — but "provably" leans on another module's invariant, and the failure
|
||||
mode is a panic that takes the user's buffer with it. The splice uses
|
||||
`text.get(..start)` / `text.get(end..)` and skips the change if either is
|
||||
`None` (unreachable), so the function is total by construction.
|
||||
- **Clamping decisions.** Line/character clamping is inherited from
|
||||
`Positions::offset` rather than re-decided here — a second clamping rule
|
||||
would be a second set of off-by-ones. The one genuinely new decision is
|
||||
`start > end`: `end` clamps *up* to `start`, making the change an insertion.
|
||||
Rejected alternatives: dropping the change (leaves the server's text and the
|
||||
client's silently different, with no way back), and swapping the two (invents
|
||||
a deletion the client never asked for). Insertion is the only reading that
|
||||
cannot lose text.
|
||||
- **Capability.** Moved to the options form. Establishing what a bare `Kind`
|
||||
meant for save was the fiddly part: the spec leaves it to the client, and
|
||||
`vscode-languageclient` fills in `{ openClose: true, change, save: {
|
||||
includeText: false } }`. Writing those two out keeps every client on the
|
||||
behavior it had, and `includeText: false` is also the right answer on its own
|
||||
terms now — the server tracks the buffer edit by edit, so a save re-sending
|
||||
the file would be pure waste. The `didSave` handler was left alone: it still
|
||||
adopts `params.text` when present, so a client that sends text anyway is
|
||||
handled exactly as before.
|
||||
- **Handler.** `DidChangeTextDocument` reads the base text out of the workspace
|
||||
(`""` if the buffer is unknown), calls `apply_changes` once, and goes through
|
||||
the existing `set_document` + `publish` path unchanged — so the
|
||||
pull-diagnostics generation model, the `lucisv.toml` warning re-arm, and the
|
||||
push/pull gate all behave as they did.
|
||||
- **Tests: 23 unit (`sync.rs`) + 6 server-level (`server.rs`) + 1 e2e.** The
|
||||
randomized cross-check (`random_edit_sequences_agree_with_the_reference_model`)
|
||||
runs 400 sequences of 1–5 changes over random texts drawn from
|
||||
`{a, b, space, ;, \n, \r\n, é, 🎉}` — every character width, both line
|
||||
endings, and bare `\r`s — with positions deliberately allowed out of range so
|
||||
the clamping rules are exercised too. It compares against `reference_apply`,
|
||||
a flat `Vec<char>` implementation that scans its own line starts and shares
|
||||
no code with `apply_changes`, and additionally asserts that applying the
|
||||
batch in one call equals applying the changes one at a time. Seed is fixed
|
||||
(`0x5EED_1CE5`), no dependency added.
|
||||
- Deviations from the plan: none. Nothing outside `lucisv_server` was touched
|
||||
in code. Two documentation files outside this feature were annotated rather
|
||||
than rewritten, because both stated something this round made false:
|
||||
`docs/features/lucisv-server/README.md` (the "full-text sync only"
|
||||
assumption, the recompute table, and one sentence of an old QA log that read
|
||||
`textDocumentSync: 1` off the capabilities JSON) and one parenthetical in
|
||||
`docs/features/pull-diagnostics/README.md` that justified the single
|
||||
generation counter by "full-text sync ignores versions" — the conclusion
|
||||
still holds, the reason needed rewording. No QA log or Review section was
|
||||
otherwise touched.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-26 — QA.** Re-ran every gate, then attacked the six surfaces the
|
||||
lead flagged plus a few of my own. Verdict: **committable as-is**. No
|
||||
corruption, no panic, no divergence from a well-behaved client found; one
|
||||
pre-existing (not introduced by this feature) latent edge case documented
|
||||
and pinned rather than fixed, since fixing it means changing a shared
|
||||
primitive (`convert.rs`) outside this feature's scope.
|
||||
|
||||
**Gates re-run, all clean:**
|
||||
- `cargo fmt --all -- --check` — clean.
|
||||
- `cargo clippy --all-targets` — clean (touched the three changed files and
|
||||
re-ran to defeat the cache; still clean).
|
||||
- `cargo test --workspace` — every crate green, 0 failed. `lucisv_server`'s
|
||||
own run: 628 lib tests (23 in `sync.rs` as claimed, plus 5 I added), 33
|
||||
e2e, 3 grammar. `cargo test -p vlog_formatter` also re-run per CLAUDE.md's
|
||||
formatter-change rule (this isn't a formatter change, but confirmed green
|
||||
anyway): 114 passed.
|
||||
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` —
|
||||
`smoke: OK`.
|
||||
|
||||
**1. Surrogate rounding — verified clean, direction confirmed by reading
|
||||
`convert.rs`.** `Positions::offset` (`crates/lucisv_server/src/convert.rs:39`)
|
||||
walks the line's `char`s accumulating UTF-16 units and only ever returns an
|
||||
offset it has actually reached by consuming whole `char`s (`offset += ch.
|
||||
len_utf8()` happens only together with `units += ch.len_utf16()`), so the
|
||||
returned byte offset is always the smallest character boundary whose
|
||||
cumulative UTF-16 unit count is `>= pos.character` — i.e. it always rounds
|
||||
up/forward, unconditionally, for every position (start or end). What
|
||||
"forward" *means* differs by role: for a start boundary it means the
|
||||
character is excluded (the insertion/deletion point moves past it, so the
|
||||
character survives); for an end boundary it means the character is included
|
||||
(the deletion widens to swallow it). Both are the same mechanical rule.
|
||||
Added two direct tests pinning the exact resulting string, as asked:
|
||||
`crates/lucisv_server/src/sync.rs`
|
||||
`a_deletion_starting_at_the_low_surrogate_index_preserves_the_character`
|
||||
(`edit((0,4),(0,6),"")` on `"// 🎉 ok\n"` → `"// 🎉ok\n"`, emoji survives) and
|
||||
`a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character`
|
||||
(`edit((0,3),(0,4),"")` on the same text → `"// ok\n"`, emoji consumed).
|
||||
Both pass. The dev's own two existing tests in
|
||||
`an_astral_character_takes_two_units_and_is_never_split` already hit this
|
||||
exact case (`edit((0,4),(0,6),"X")` and `edit((0,3),(0,4),"X")`) but as
|
||||
replacements, not pure deletions — the two I added close that gap with an
|
||||
empty `text`. Cross-checked against the LSP spec: positions are UTF-16
|
||||
code-unit offsets and a spec-compliant client never legitimately sends a
|
||||
mid-pair boundary, so any total, non-panicking rule is acceptable — the
|
||||
README's description ("rounds forward past the whole character") is
|
||||
accurate to the actual code, not just to the reference model.
|
||||
|
||||
**2. Divergence-from-editor risk — one real (low-severity, pre-existing)
|
||||
finding, everything else clean.**
|
||||
- **Fresh-`LineIndex`-per-change is not hoisted.** `crates/lucisv_server/src/
|
||||
sync.rs:35`, `let index = LineIndex::new(&text);`, is inside the `for
|
||||
change in changes` loop, rebuilt from the current `text` every iteration —
|
||||
confirmed by reading the code (not just trusting the comment), and then by
|
||||
actually breaking it: I temporarily hoisted the `LineIndex::new` call above
|
||||
the loop (reusing one stale index for every change) and reran `cargo test
|
||||
--bin lucisv-server sync::tests::`. Three tests failed against the stale
|
||||
index: `a_later_range_positioned_against_the_original_text_would_be_wrong`
|
||||
(panics — its own doc comment names exactly this regression),
|
||||
`a_rangeless_change_resets_what_the_next_range_is_against`, and
|
||||
`random_edit_sequences_agree_with_the_reference_model` (400/400 cases
|
||||
depend on this). `later_changes_see_what_the_earlier_ones_did` did *not*
|
||||
fail under hoisting — its three edits happen to stay valid against the
|
||||
stale index anyway, so it does not by itself pin this — but the three that
|
||||
did fail are sufficient. Reverted the hoist immediately after (confirmed
|
||||
back to 28/28 passing); no new test needed, the existing ones already pin
|
||||
this correctly.
|
||||
- **A change whose range covers the final newline** — clean. Added
|
||||
`a_change_covering_the_final_newline_removes_exactly_it`:
|
||||
`edit((1,1),(2,0),"")` on `"a\nb\n"` → `"a\nb"`. Removes exactly the
|
||||
trailing `\n`, nothing else.
|
||||
- **Adjacent zero-width ranges at the same position in one batch** — not a
|
||||
bug, and pinned as such. Added
|
||||
`zero_width_inserts_at_the_same_position_compose_in_batch_order`: two
|
||||
inserts both naming `(0,0)` on `"x"` with texts `"1"` then `"2"` produce
|
||||
`"21x"`, because each change's position is (correctly, per protocol)
|
||||
resolved against the text the previous change left — the second insert's
|
||||
literal position `0` is now *before* the first insert's text. A client
|
||||
that wants `"12"` must advance the second position past the first's
|
||||
length, same as it would for a non-zero-width range. This matches "each
|
||||
change is positioned against the document the previous changes in the
|
||||
same notification left" exactly.
|
||||
- **`\r\n` split across two changes in one batch — finding.**
|
||||
`crlf_split_across_two_changes_in_one_batch_reorders_the_bytes`
|
||||
(`crates/lucisv_server/src/sync.rs`): `apply_changes("ab", &[edit((0,2),
|
||||
(0,2), "\r"), edit((0,2),(0,2), "\n")])` produces `"ab\n\r"`, not
|
||||
`"ab\r\n"`. Root cause: `convert.rs::line_content_end`
|
||||
(`crates/lucisv_server/src/convert.rs:96`) treats a trailing bare `\r` as
|
||||
"not content" unconditionally — whether or not a `\n` will ever follow it
|
||||
— so once change 1 leaves the buffer ending in a lone `\r`, "end of line"
|
||||
for change 2 clamps to *before* that `\r`, and the `\n` lands ahead of it
|
||||
instead of after. This is **not introduced by this feature**: the rule
|
||||
lives in `convert.rs`, which predates incremental sync and is shared by
|
||||
every position-converting handler. What incremental sync newly does is
|
||||
give this quirk a path to actually rewrite the *persisted buffer* rather
|
||||
than just a hover/diagnostic range — before this feature, the server never
|
||||
computed byte offsets to build a document to save, it just accepted the
|
||||
client's already-composed text verbatim. In practice this needs a client
|
||||
to split one `\r\n` insertion into two separate ranged edits inside a
|
||||
single `didChange` batch, positioned at the exact same coordinates for
|
||||
both; no known editor's diff algorithm does this (VS Code/Neovim send
|
||||
`\r\n` as one atomic edit). No panic, no data loss (both bytes survive,
|
||||
just reordered), so it does not violate the "never corrupt" invariant in
|
||||
the "produces wrong output" sense used elsewhere in this repo (no crash,
|
||||
no truncation) but it is a genuine silent-divergence risk if a
|
||||
pathological client ever does this. Recorded and pinned rather than fixed:
|
||||
fixing it means deciding whether `line_content_end` should special-case "a
|
||||
bare trailing `\r` with nothing after it, at the very end of the buffer or
|
||||
the very end of a change-in-progress" — a `convert.rs` decision that
|
||||
affects every handler, out of this feature's stated scope
|
||||
(`sync.rs`/`main.rs`/`server.rs` only). Filed as a follow-up rather than
|
||||
redesigned here.
|
||||
- Multi-byte/astral columns (`a_ranged_change_over_multi_byte_text_edits_the_
|
||||
right_columns`, server.rs) and CRLF-on-one-line edits (`crlf_line_ends_
|
||||
survive_an_edit_on_the_line`, sync.rs) — re-verified by hand-tracing
|
||||
`Positions::offset`, both clean, no off-by-one.
|
||||
|
||||
**3. Full-sync regression — verified clean.** Diffed the old handler
|
||||
(`git show aa303ce:crates/lucisv_server/src/server.rs`, the `next_back()`
|
||||
form) against the new path:
|
||||
- *Multiple rangeless changes*: old took only the literal last element via
|
||||
`next_back()` (O(1), never touched the earlier ones); new applies all of
|
||||
them via `apply_changes`, but each rangeless change fully replaces `text`
|
||||
and continues, so the net result is identical — last one wins either way.
|
||||
Confirmed by the dev's `the_last_of_several_rangeless_changes_wins`
|
||||
(sync.rs) and `a_full_sync_clients_batch_still_lets_the_last_change_win`
|
||||
(server.rs). The new path is `O(changes)` string clones instead of `O(1)`
|
||||
for this specific case — a real but tiny and already-documented cost, not
|
||||
a correctness regression.
|
||||
- *Empty `contentChanges`*: old — `next_back()` on empty returns `None`, no
|
||||
`set_document`/no `publish`. New — explicit `if p.content_changes.
|
||||
is_empty() { return; }` before touching anything. Identical observable
|
||||
behavior; confirmed by `one_notification_is_one_generation_bump_however_
|
||||
many_ranges`'s second half (server.rs) which checks the generation counter
|
||||
does not move.
|
||||
- *Unknown/never-opened uri*: old — `set_document(uri, change.text)`
|
||||
unconditionally, no existence check. New — `self.workspace.document(&uri).
|
||||
map_or("", ...)` then `apply_changes`; for a rangeless change this reduces
|
||||
to the same `set_document(uri, change.text)`. Confirmed by `a_change_
|
||||
naming_a_buffer_that_was_never_opened_is_taken_as_written` (server.rs,
|
||||
rangeless case). I did not find a server-level test of a *ranged* change
|
||||
against a never-opened buffer, but it is exercised at the unit level
|
||||
(`an_edit_into_an_empty_document` in sync.rs, since `apply_changes` is
|
||||
handed `""` either way) and the handler code between the two cases is the
|
||||
same three lines — low-severity gap, noting rather than adding a
|
||||
redundant test.
|
||||
|
||||
**4. Capability shape — verified clean, confirmed on the actual wire, not
|
||||
just by reading the struct.** Ran the built binary directly through a
|
||||
minimal `initialize` and inspected the raw JSON response (not just the
|
||||
e2e/smoke assertions): `textDocumentSync` serialized as exactly
|
||||
`{"change":2,"openClose":true,"save":{"includeText":false}}` — no
|
||||
`willSave`/`willSaveWaitUntil` keys at all (`lsp_types::
|
||||
TextDocumentSyncOptions` marks both `#[serde(skip_serializing_if = "Option::
|
||||
is_none")]`, so `None` means genuinely absent from the wire, not `null`).
|
||||
This is exactly what `vscode-languageclient` and Neovim's builtin client
|
||||
parse as `{openClose: true, change: Incremental, save: {includeText:
|
||||
false}}`, with the will-save fields correctly unadvertised for a future
|
||||
round. `incremental_changes_are_advertised_and_applied_over_the_wire`
|
||||
(e2e.rs) asserts `sync["change"] == 2`, `sync["openClose"] == true`,
|
||||
`sync["save"]["includeText"] == false` — confirmed this really does pin the
|
||||
shape, it isn't a no-op assertion.
|
||||
|
||||
**5. Performance honesty — verified clean.** `Server::set_document`
|
||||
(`crates/lucisv_server/src/state.rs:175`, called from the `DidChangeTextDocument`
|
||||
arm exactly once per notification per the diff at `server.rs`) is the only
|
||||
place a `Document::new` (full reparse/tokens/`Semantics`) happens. Inside
|
||||
`sync::apply_changes`, only a `LineIndex::new` (a single linear scan for
|
||||
`\n` bytes, not a parse) and a `String` allocation happen per *ranged*
|
||||
change — that's the honest `O(changes × file)`, not `O(changes × file²)`
|
||||
and not a hidden per-change reparse. Confirmed by reading `state.rs:175-179`
|
||||
and by the fact that `self.generation` (bumped only inside `set_document`)
|
||||
moves exactly once per notification regardless of range count, per
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`.
|
||||
|
||||
**6. CLAUDE.md compliance — clean.** No `unwrap`/`expect`/`panic!` in
|
||||
library code paths in `sync.rs` or the `server.rs` handler diff (`grep`
|
||||
confirms the only `expect()`s introduced are inside `#[cfg(test)]` code in
|
||||
`server.rs`, which CLAUDE.md permits). No new `#[allow]`. `sync.rs` has a
|
||||
module doc comment and `apply_changes` has a doc comment. Feature README has
|
||||
all six required sections. `TODO.md`'s §9b item text is unchanged aside from
|
||||
the checkbox and an appended implementation-summary paragraph (allowed — the
|
||||
rule is "leave the item text intact", not "add nothing"). The two annotation
|
||||
edits to `docs/features/lucisv-server/README.md` and `docs/features/
|
||||
pull-diagnostics/README.md` are both dated 2026-08-26, self-identifying
|
||||
("*(That last sentence records the state at the time of this QA pass
|
||||
only...)*", "*(Still true after incremental sync, 2026-08-26: ...)*"), and
|
||||
factual against the diff — neither rewrites the original text, both append.
|
||||
One minor nit: the original (pre-existing) `TODO.md` §9b bullet's plan text
|
||||
says "with a full-text fallback on any malformed change", but the shipped
|
||||
implementation uses clamping instead of a full-text fallback for a malformed
|
||||
change — a better and thoroughly-justified design choice (see the README's
|
||||
Assumptions and Work log), but the Work log's "Deviations from the plan:
|
||||
none" doesn't call out that the *originally-planned* mechanism changed
|
||||
between the TODO's wording and the implementation. Cosmetic — the actual
|
||||
behavior is fully and correctly documented elsewhere in the same README —
|
||||
not asking for a fix, just noting it for the record.
|
||||
|
||||
**Tests added this round** (all in `crates/lucisv_server/src/sync.rs`,
|
||||
all passing): `a_deletion_starting_at_the_low_surrogate_index_preserves_
|
||||
the_character`, `a_deletion_ending_at_the_low_surrogate_index_consumes_
|
||||
the_whole_character`, `crlf_split_across_two_changes_in_one_batch_
|
||||
reorders_the_bytes`, `a_change_covering_the_final_newline_removes_exactly_
|
||||
it`, `zero_width_inserts_at_the_same_position_compose_in_batch_order`.
|
||||
|
||||
**Verdict: committable as-is.** No dev follow-up required to ship; the
|
||||
`\r\n`-split-across-changes behavior is worth a future look if `convert.rs`
|
||||
is ever revisited, but it is pre-existing, unreachable by any known real
|
||||
client, and now pinned by a test rather than silently latent.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full
|
||||
workspace suite/smoke.js myself, all clean. `apply_changes` is the right
|
||||
shape: pure, total, no panicking slice, and the fresh-line-table-per-change
|
||||
decision buys correctness with microseconds — the honest O(changes × file)
|
||||
note is exactly how this repo trades. Inheriting the clamping rules from
|
||||
`Positions::offset` instead of inventing a second set was the correct call,
|
||||
and the `start > end` → pure-insertion rule is the only reading that cannot
|
||||
lose the user's text.
|
||||
|
||||
On QA's finding (a `\r` + `\n` split across two same-position inserts in
|
||||
one batch lands as `\n\r`): accepted as pinned, not fixed. The root cause
|
||||
is `convert.rs`'s pre-existing treatment of a trailing bare `\r`, which is
|
||||
shared by every handler and out of this feature's scope; no real client
|
||||
splits a CRLF across two changes of one batch, and the behavior is now
|
||||
documented by a test rather than latent. If a cross-file `convert.rs`
|
||||
round ever opens, this goes with it. The randomized cross-check (400
|
||||
sequences against an independent model), the deliberate-breakage check
|
||||
that the line table really is rebuilt per change, and the wire-level
|
||||
capability assertion give this the confidence a sync rewrite needs.
|
||||
Accepted as shipped.
|
||||
@@ -0,0 +1,344 @@
|
||||
# linked-editing
|
||||
|
||||
## Goal
|
||||
|
||||
`textDocument/linkedEditingRange` (TODO.md §9c) makes SystemVerilog's closing
|
||||
labels edit as one name. `module m ... endmodule : m` writes `m` twice, and so
|
||||
do `function f ... endfunction : f`, `class c ... endclass : c`, `package p`,
|
||||
`interface i`, a named `begin : blk ... end : blk`, a named `fork ... join :
|
||||
blk`, a generate block's `begin : g ... end : g` and `clocking cb ...
|
||||
endclocking : cb`. When the cursor sits on either occurrence the server answers
|
||||
with **both** ranges, and the editor then applies every keystroke to both at
|
||||
once — which is the one editing operation where SV's optional closing label
|
||||
stops being a maintenance cost. The whole feature is a pure function over one
|
||||
buffer's parse tree: no index, no workspace, no engine change.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A closing label is optional in SV, and an absent one is not an invitation.**
|
||||
`endmodule` with no `: m` gets no linked ranges at all. There is nothing to
|
||||
co-edit, and a linked-editing answer is not a place to offer to create one.
|
||||
- **Identical text is required, so a mismatched label answers `null`.** The
|
||||
spec says the ranges "must have identical length and contain identical text
|
||||
content"; `module m ... endmodule : wrong` violates both. Answering the pair
|
||||
anyway would silently "fix" the mismatch on the user's next keystroke — an
|
||||
edit they did not ask for, applied to code they can see is broken. Broken
|
||||
code is the user's to fix; the server declines.
|
||||
- **Escaped identifiers are excluded.** `\my$odd.name ` is an identifier whose
|
||||
extent depends on a trailing space, and the `wordPattern` this feature sends
|
||||
cannot describe one. Rather than send a pattern that would let a client
|
||||
corrupt the escape, a pair whose name is not a plain
|
||||
`[A-Za-z_][A-Za-z0-9_$]*` answers `null` — even when both halves are the same
|
||||
escaped name.
|
||||
- **The two name spans always come from one AST node**, never from a text
|
||||
search for the same word. `begin : x begin : x ... end : x end : x` has two
|
||||
pairs whose four names are byte-identical; each `end`'s label belongs to the
|
||||
block node that owns it, so the inner cursor answers the inner pair and the
|
||||
outer cursor the outer one. This is the property the "evil fixture" test
|
||||
pins.
|
||||
- **Name spans never nest and never touch**, which is what lets the lookup be a
|
||||
flat "which span covers this offset" over every pair in the file rather than
|
||||
an innermost-wins descent. Two label occurrences are always separated by at
|
||||
least a keyword.
|
||||
- **A cursor one byte past the end of a name still counts** (`m|`), the same
|
||||
rule `pairs::highlights` uses: an editor leaves the caret after the character
|
||||
just typed, and linked editing that switched off at the end of the word would
|
||||
be useless exactly while the user is typing.
|
||||
- **A buffer that does not parse answers whatever its tolerant tree holds.** A
|
||||
construct the parser turned into `ItemKind::Error` has no label spans, so it
|
||||
simply has no pair — the same "no answer" every other position gets.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser::ast`** — read-only, and nothing was changed
|
||||
there this round. Every construct this feature serves is one that already
|
||||
records **both** name spans on the same node:
|
||||
|
||||
| construct | header span | closing-label span |
|
||||
|---|---|---|
|
||||
| `module` / `macromodule` / `interface` | `Module::name_span` | `Module::end_label_span` |
|
||||
| `package` | `ItemKind::Package::name_span` | `ItemKind::Package::end_label_span` |
|
||||
| `class` | `ClassDecl::name_span` | `ClassDecl::end_label_span` |
|
||||
| `function` | `FunctionDecl::name_span` | `FunctionDecl::end_label_span` |
|
||||
| `task` | `TaskDecl::name_span` | `TaskDecl::end_label_span` |
|
||||
| `clocking` | `ClockingDecl::name` (`Name::span`) | `ClockingDecl::end_label_span` |
|
||||
| generate `begin : g` | `GenBlock::label_span` | `GenBlock::end_label_span` |
|
||||
| statement `begin : b` | `StmtKind::Block::label_span` | `StmtKind::Block::end_label_span` |
|
||||
| `fork ... join : b` | `StmtKind::ForkJoin::label_span` | `StmtKind::ForkJoin::end_label_span` |
|
||||
| prefix-labelled `b : begin ... end : b` | `StmtKind::Labeled::name_span` | the wrapped block's `end_label_span` |
|
||||
|
||||
The last row is the one indirection: IEEE 1800 §9.3.5 lets a block be named
|
||||
before its keyword, and the parser then puts the name on the enclosing
|
||||
`StmtKind::Labeled` and leaves the block's own `label` empty. It is still one
|
||||
syntactic pair — the LRM requires the end label to match that name — so it is
|
||||
served, and only when the block wrote no label of its own (writing both is
|
||||
illegal, and the block's own pair wins there).
|
||||
|
||||
**Not reachable, and deliberately not chased this round** — these constructs
|
||||
can carry a closing label in SV but the tree keeps no span for it, so they get
|
||||
no linked ranges:
|
||||
|
||||
1. **`program p; ... endprogram : p`.** `program` is a keyword the lexer knows
|
||||
(`token.rs`) but no parse arm claims, so the declaration lands in
|
||||
`ItemKind::Error`/verbatim text with no name span at all.
|
||||
2. **`property` / `sequence` / `covergroup ... endgroup` / `constraint`.**
|
||||
Captured byte-for-byte as `ItemKind::Verbatim(RawText)` by design
|
||||
(`docs/features/classes/README.md`, `docs/features/assertions/README.md`),
|
||||
so neither name is a span.
|
||||
3. **`specify` / `primitive` / `modport`.** No closing label exists for these
|
||||
in the grammar, so there is nothing to link.
|
||||
|
||||
**Requested of `vlog_parser`: nothing.** The one thing this feature would gain
|
||||
from a parser round is (1) above — a `program` node with the same
|
||||
`name_span` + `end_label_span` pair `Module` already has, at which point it
|
||||
joins the table with no change here beyond one match arm. That is recorded as
|
||||
a want, not as a blocker: the feature is complete for every construct the tree
|
||||
models.
|
||||
|
||||
**Promised to nobody.** `linked::linked_editing_ranges(&Document, u32)` has one
|
||||
caller, `server.rs`'s `LinkedEditingRange` arm.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/lucisv_server/src/linked.rs`: the pair walk and the lookup.
|
||||
- [x] `linkedEditingRangeProvider` advertised (`LinkedEditingRangeServerCapabilities::Simple(true)`).
|
||||
- [x] `request::LinkedEditingRange` dispatched in `server.rs`, `null` for an
|
||||
unopened buffer and for a position on no pair.
|
||||
- [x] `wordPattern` sent, as a `const`.
|
||||
- [x] Unit tests: every construct kind, both directions, cursor at
|
||||
start/middle/end, unlabeled → `null`, mismatched → `null`, nesting,
|
||||
identical names at different nesting, escaped identifiers, multibyte
|
||||
text, out-of-range positions.
|
||||
- [x] Server-level tests: dispatch, capability, unopened buffer.
|
||||
- [x] e2e: the real binary, one round trip decoding both ranges and the
|
||||
`wordPattern`.
|
||||
- [x] TODO.md §9c checkbox with its `→` delivery line.
|
||||
- [x] `docs/features/lucisv-server/README.md` capability table.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent
|
||||
|
||||
- **One new module, one dispatch arm, one capability, no engine change.**
|
||||
`crates/lucisv_server/src/linked.rs` holds the whole feature:
|
||||
`linked_editing_ranges(doc, offset) -> Option<LinkedEditingRanges>`, a
|
||||
private walk that collects every `(header, closing label)` pair the tree
|
||||
records, and the two filters that decide whether a pair may be linked.
|
||||
`vlog_parser`, `vlog_semantic` and `state.rs` are untouched.
|
||||
- **The AST already carried everything.** Grepping `end_label_span` found nine
|
||||
nodes with the pair on them — the ten rows of the Handshakes table, the tenth
|
||||
being the prefix-label indirection — so nothing here searches text or matches
|
||||
names. The pair is a *node*, which is exactly what makes the
|
||||
`begin : x begin : x ... end : x end : x` fixture answer correctly instead of
|
||||
by luck.
|
||||
- **Collect-then-find, not an offset-guided descent.** `type_def.rs` descends
|
||||
by `span.contains`, because a declaration's window really does nest. Label
|
||||
name spans do not nest and do not touch, so the flat walk is both simpler and
|
||||
the honest model: there is at most one pair a given offset can belong to, and
|
||||
a descent would only be a slower way to find it. The walk is one pass over a
|
||||
tree that was already built for this buffer.
|
||||
- **Two refusals, both deliberate, both tested.** A mismatched label
|
||||
(`endmodule : wrong`) and an escaped identifier answer `null` rather than a
|
||||
pair — reasons in Assumptions above. The mismatch decision is the one worth
|
||||
re-reading: linking non-identical text is against the spec's own wording, and
|
||||
a linked edit that silently repairs a mismatch is an edit the user never
|
||||
asked for.
|
||||
- **`wordPattern` is sent** rather than left to the client's language default.
|
||||
VS Code's fallback word pattern for an unknown language id would not include
|
||||
`$`, which is legal in an SV identifier after the first character, so a user
|
||||
typing `foo$bar` would see the link drop halfway. The pattern is one `const`
|
||||
beside the code that uses it, anchored on both ends, and it deliberately does
|
||||
not try to describe an escaped identifier — those answer `null` instead.
|
||||
- **Nothing in `editors/` moved.** The VS Code client picks linked editing up
|
||||
from the advertised capability, and `smoke.js`'s capability list belongs to
|
||||
`docs/features/editor-packaging/README.md` (the same call the inlay-hints
|
||||
round made).
|
||||
|
||||
**Results.** `cargo test --workspace`: **1902 passed, 0 failed** (1877 on a
|
||||
stashed tree, measured rather than assumed — 22 unit tests in `linked.rs`, 2 in
|
||||
`server.rs`, 1 e2e; the capability assertion joined `main.rs`'s existing
|
||||
`every_advertised_capability_is_implemented`).
|
||||
`cargo clippy --all-targets`: silent.
|
||||
`cargo fmt --all -- --check`: clean. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: passes. No new
|
||||
dependencies, no version bump, no commits.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check`: clean (after `cargo fmt --all` on the
|
||||
tests added below — the dev's own code needed no reformatting). `cargo clippy
|
||||
--all-targets --workspace`: silent. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. `cargo test
|
||||
--workspace`: **1910 passed, 0 failed** (1902 as claimed, +8 new tests added
|
||||
below).
|
||||
|
||||
**Verdict: committable as-is.** No wrong-pairing bug found anywhere the
|
||||
"never nest, never touch" claim was attacked; the one open question worth a
|
||||
second pair of eyes (`WORD_PATTERN` anchoring) was checked against VS Code's
|
||||
actual source and is correct as shipped. All new tests below are additions to
|
||||
`crates/lucisv_server/src/linked.rs`'s existing `#[cfg(test)] mod tests`; no
|
||||
production code changed.
|
||||
|
||||
**1. "Never nest, never touch" — attacked directly, holds.**
|
||||
|
||||
- *(a) Both a prefix label and the block's own label, on tolerant-parsed
|
||||
code.* `x : begin : y ... end : y` (block writes its own label `y`, so IEEE
|
||||
1800 §9.3.5's prefix form is doubly-illegal but the tolerant parser accepts
|
||||
it). Traced through `parser.rs`: `parse_stmt_kind` reads the prefix name `x`
|
||||
into `StmtKind::Labeled`, then `parse_keyword_stmt`'s `"begin"` arm reads the
|
||||
block's own `: y` into `Block::label`/`label_span`. In `linked.rs`,
|
||||
`prefix_labelled_end` (line 273) checks `label: None` before firing, so with
|
||||
`label: Some(y)` it returns `None` and no pair is pushed for the `x` node —
|
||||
only the recursion into the block itself pushes `(y, y)`. Verified by new
|
||||
test `a_block_named_both_ways_answers_only_the_blocks_own_pair` (line 689):
|
||||
`x` answers nothing at all, `y` answers the correct pair from both
|
||||
directions. The gate does exactly what the doc comment says. Verified-clean.
|
||||
- *(a, continued) Prefix label present, block writes no label of its own, but
|
||||
the close doesn't match the prefix name* — `x : begin ... end : y`. Here the
|
||||
gate *does* fire (`label: None`) and pushes `(x, y)`, which is a real,
|
||||
syntactically-recorded pair whose two names simply differ. `is_linkable`
|
||||
(line 93) correctly declines it on the text-equality check — same path as
|
||||
any other mismatch, no special-casing needed. New test
|
||||
`a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched`
|
||||
(line 707). Verified-clean.
|
||||
- *(b) Zero-length/overlapping spans from error recovery.* Fed the tolerant
|
||||
parser: a label written with `end` missing (`begin : blk` never closed
|
||||
before `endmodule`), no closer at all before EOF, a colon with no name after
|
||||
it (`begin : \n end : \n` and `begin :\n end\n`), a block named but the
|
||||
buffer just ends mid-body. All four produce **zero pairs** (traced: `expect_name`
|
||||
in `parser.rs:633` returns `Err` on a missing identifier, which propagates
|
||||
out of `parse_label`/`parse_keyword_stmt` and is absorbed by the caller's
|
||||
recovery — nothing reaches `linked.rs` with a label at all in that case) or a
|
||||
pair missing one half, which `push`'s `(Some, Some)` match (line 121) and its
|
||||
`is_empty()` guard both filter before it ever reaches the pair list. New
|
||||
test `broken_and_unclosed_labeled_constructs_never_panic` (line 742) sweeps
|
||||
every offset of all four fixtures for panics via a new
|
||||
`assert_total_and_sane` helper (also used by the tests below). Verified-clean.
|
||||
- *(b, continued) Two `end : x` for one `begin : x`.* `begin : x ... end : x
|
||||
\n end : x` (the second is leftover after the first closes the block).
|
||||
Confirmed by inspection (`items_pairs` on the fixture) that exactly **one**
|
||||
pair is recorded, closing on the *first* `end : x` — the second is dead
|
||||
tokens at item-recovery level and answers `null` everywhere in its own span.
|
||||
No phantom third occurrence, no panic. New test
|
||||
`a_stray_second_end_label_after_the_block_already_closed_is_inert` (line
|
||||
719). Verified-clean.
|
||||
- *(c) Adjacent labels, no separator.* `endfunction : f` immediately followed
|
||||
by `endmodule : m` on the next line, and the no-space spellings `begin:x` /
|
||||
`end:x`. Structurally, two distinct identifier spans can never truly touch
|
||||
(`span1.end == span2.start`) because the lexer's maximal-munch tokenization
|
||||
requires at least one non-identifier byte (whitespace, `:`, a keyword)
|
||||
between any two identifier tokens — so `Pair::covers`'s inclusive `<=` on
|
||||
both ends (line 83) can never make one offset satisfy two different pairs.
|
||||
Verified over the real boundary bytes:
|
||||
`adjacent_closing_labels_never_bleed_into_each_other` (line 754) plus the
|
||||
`assert_total_and_sane` sweep inside it. Verified-clean.
|
||||
|
||||
**2. Identical-text requirement, ranges decoded precisely.** New test
|
||||
`ranges_cover_exactly_the_identifier_never_the_colon_or_comment` (line 769)
|
||||
decodes each answer's `Range` back to a byte span with
|
||||
`Positions::offset` (`convert.rs:39` — the same function the server uses to
|
||||
turn a client position into an offset) and asserts `&text[start..end] ==
|
||||
name` for three shapes: `endmodule : /*c*/ m` (comment between colon and
|
||||
name), `end:x` (no spaces at all), and a label split across a newline
|
||||
(`begin :\n x`). All three: the range is exactly the identifier, never the
|
||||
colon, a space, or the comment. Also added
|
||||
`a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing` (line 874):
|
||||
cursor on the colon, one byte after the colon, and on the indentation between
|
||||
the two labels all answer `null`, even with the label letters immediately
|
||||
adjacent. Verified-clean — no off-by-one that would let a client type into the
|
||||
colon.
|
||||
|
||||
**3. The evil fixture.** Re-read `identical_names_at_different_nesting_pair_syntactically`
|
||||
(linked.rs, pre-existing) — it already asserts the *exact* `(line, start,
|
||||
end)` tuples for both pairs in both directions, not just counts, so no
|
||||
strengthening was needed there. Same for
|
||||
`a_module_and_the_function_inside_it_are_separate_pairs` (same-named module
|
||||
and function) — already asserts exact ranges. Verified-clean, no changes.
|
||||
|
||||
**4. `wordPattern` anchoring — checked against VS Code's actual source, not
|
||||
assumed.** Fetched
|
||||
`src/vs/editor/contrib/linkedEditing/browser/linkedEditing.ts` from
|
||||
`microsoft/vscode`. The `wordPattern` sent in `LinkedEditingRanges` is used
|
||||
**only** as: `referenceValue.match(this._currentWordPattern)`, then `match[0].length
|
||||
=== referenceValue.length` — a full-string validation against the *already-extracted
|
||||
range content*, not a per-line scan (that would be `editor.wordPattern`'s job,
|
||||
used by `getWordAtText` for double-click/hover, which does need an unanchored
|
||||
global pattern — a different code path this feature does not touch). Against
|
||||
`referenceValue.match()`, an anchored `^...$` and an unanchored pattern give
|
||||
identical results here, because the check is on `match[0].length` equalling
|
||||
the *whole* string's length either way. **Anchoring is correct, not a bug.**
|
||||
This is worth recording so nobody "fixes" it later by stripping the anchors
|
||||
based on the general `editor.wordPattern` convention — that convention does
|
||||
not apply to this LSP field. Verified-clean.
|
||||
|
||||
**5. Null conventions + totality.** All of: unlabeled construct, cursor on
|
||||
the `module` keyword, cursor on the colon, cursor in the closer's whitespace,
|
||||
past EOF, empty file, unopened buffer, a buffer the lexer gives up on — all
|
||||
already covered (some newly, item 2 above) and all total. No panics anywhere
|
||||
in this round's ~15 new adversarial fixtures plus the corpus sweep below.
|
||||
|
||||
**6. Corpus sweep.** New test `a_corpus_sweep_of_labeled_constructs_is_total_and_sane`
|
||||
(line 801), gated on `corpus/` being checked out (it is). 11 real files
|
||||
grepped from the corpus for `endmodule :` / `end :` shapes (`common_cells`,
|
||||
`ibex`, `opentitan` — file list in the test), every byte offset (0..=len,
|
||||
~83,000 offsets total) run through `linked_editing_ranges`: no panics, every
|
||||
`Some` answer has exactly 2 ranges holding identical text that is a plain
|
||||
identifier (`is_simple_identifier`), and the two ranges never overlap. All
|
||||
green.
|
||||
|
||||
**7. CLAUDE.md compliance.**
|
||||
- No `unwrap()`/`expect()`/`panic!` outside `#[cfg(test)] mod tests` (module
|
||||
starts at `linked.rs:282`; grepped lines 1–280, none found). `server.rs`'s
|
||||
pre-existing `unwrap_or_default()` calls near the dispatch arm are
|
||||
non-panicking and predate this feature.
|
||||
- `pub fn linked_editing_ranges` (line 52) carries a doc comment; so does the
|
||||
module (`//!` header) and every private item touched.
|
||||
- `docs/features/linked-editing/README.md`: all seven required sections
|
||||
present exactly once, in order (`Goal`, `Assumptions`, `Handshakes`,
|
||||
`Status / TODO`, `Work log`, `QA log`, `Review`).
|
||||
- `TODO.md`: the §9c item's original text ("**Linked editing range** — edit
|
||||
`module m` and its `endmodule : m` label together...") is byte-for-byte
|
||||
intact; only `[ ]` → `[x]` and an appended `→ delivered` block changed.
|
||||
|
||||
**Tests added (all in `crates/lucisv_server/src/linked.rs`, all passing,
|
||||
+8 over the dev's count, 1910 workspace tests total):**
|
||||
`a_block_named_both_ways_answers_only_the_blocks_own_pair`,
|
||||
`a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched`,
|
||||
`a_stray_second_end_label_after_the_block_already_closed_is_inert`,
|
||||
`broken_and_unclosed_labeled_constructs_never_panic`,
|
||||
`adjacent_closing_labels_never_bleed_into_each_other`,
|
||||
`ranges_cover_exactly_the_identifier_never_the_colon_or_comment`,
|
||||
`a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing`,
|
||||
`a_corpus_sweep_of_labeled_constructs_is_total_and_sane`.
|
||||
|
||||
No production code changed — every finding above resolved to "verified
|
||||
correct," including the one (`wordPattern` anchoring) that looked like it
|
||||
could go either way until checked against VS Code's own source.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. The construct table in the work log — nine AST node kinds already
|
||||
carrying both name spans, discovered before a line was written — is the
|
||||
round doing its homework, and the decision to skip the pair matcher (a
|
||||
keyword matcher, not a label matcher) was correct. The judgment calls
|
||||
all land right: mismatched and absent labels answer null, escaped
|
||||
identifiers are refused with a test proving the refusal is the filter's
|
||||
choice and not a parse accident, and the prefix-label form gated on the
|
||||
block writing no label of its own handles the both-labels tolerant-parse
|
||||
shape exactly as it should.
|
||||
|
||||
Two QA results worth the record: the wordPattern anchoring question was
|
||||
resolved by reading VS Code's linked-editing source — the pattern is
|
||||
full-string validation in this code path, so the anchors are correct as
|
||||
shipped, and the QA log now says so precisely so nobody "fixes" it later
|
||||
against the wrong convention; and the range-precision test decodes every
|
||||
range back to bytes through the server's own converter, pinning that a
|
||||
link never includes the colon a user would otherwise type into. The
|
||||
83k-offset corpus sweep of the identical-text/non-overlap invariants
|
||||
closes it out. `program`/`property`/`sequence`/`covergroup` stay filed
|
||||
as parser wants in Handshakes. Accepted as shipped.
|
||||
@@ -0,0 +1,585 @@
|
||||
# lsp-318-extras
|
||||
|
||||
## Goal
|
||||
|
||||
Close the last box of TODO.md §9c — the three LSP 3.18 additions the audit
|
||||
named — by shipping the one a real client can consume today and writing down,
|
||||
with evidence, why the other two cannot be shipped honestly yet.
|
||||
|
||||
**Shipped:** `textDocument/rangesFormatting`, multi-range formatting in one
|
||||
request. This is what an editor sends for *format the lines I modified* and for
|
||||
*format each of my multi-cursor selections*: `n` ranges, one round trip, one
|
||||
answer. lucisv's range engine already takes an `n`-range `LineRanges` natively
|
||||
(that is what `--lines 3-9,40` is), so the request is a thin adapter over the
|
||||
same verified, all-or-nothing engine `textDocument/rangeFormatting` runs — not
|
||||
a second formatter with a second contract.
|
||||
|
||||
**Parked, with the assessment in [Parked](#parked-and-why) below:** snippet
|
||||
edits in a `WorkspaceEdit`, and `workspace/textDocumentContent`. Neither has a
|
||||
shipping client that could consume it, and CLAUDE.md's "nothing is advertised
|
||||
that is not implemented" has a mirror image — nothing is implemented that
|
||||
nothing can call.
|
||||
|
||||
## What `rangesFormatting` is
|
||||
|
||||
LSP 3.18 (proposed), `textDocument/rangesFormatting`:
|
||||
|
||||
```jsonc
|
||||
// params
|
||||
{ "textDocument": { "uri": … }, "ranges": [ Range, … ], "options": FormattingOptions }
|
||||
// result
|
||||
TextEdit[] | null
|
||||
```
|
||||
|
||||
The server declares it by widening its existing `documentRangeFormattingProvider`
|
||||
from the bare `true` to the options object with `rangesSupport: true` — the
|
||||
`boolean | DocumentRangeFormattingOptions` union the capability has always had:
|
||||
|
||||
```jsonc
|
||||
"documentRangeFormattingProvider": { "rangesSupport": true }
|
||||
```
|
||||
|
||||
The client declares it as `textDocument.rangeFormatting.rangesSupport: true`.
|
||||
|
||||
### Semantics: the union of the ranges, on the one engine
|
||||
|
||||
An `n`-range request is exactly the single-range request with `n` line spans
|
||||
instead of one. Concretely, `format::ranges_formatting` is now the only entry
|
||||
point and `range_formatting` is the one-element call of it:
|
||||
|
||||
1. Each protocol `Range` becomes a 1-based inclusive line span through the
|
||||
**same** `lines_of` conversion single-range formatting used before this
|
||||
round (only line numbers survive; an end at character 0 of a later line
|
||||
names the line before it). The conversion was extracted, not copied — a
|
||||
second spelling of that rule is a second thing to get wrong.
|
||||
2. The spans go into one `LineRanges::new`, which **sorts and merges** them.
|
||||
Overlapping, adjacent and unsorted input from the client all normalize
|
||||
there, and they normalize in the CLI's own constructor rather than in a
|
||||
second copy written for the LSP.
|
||||
3. One `format_range` call. The all-or-nothing contract, the equivalence check
|
||||
and the replayed-selection convergence check all ride through unchanged,
|
||||
because this is literally the call `--lines 3-9,40` makes.
|
||||
4. One whole-document `TextEdit`, or none when the text did not change —
|
||||
`rangeFormatting`'s reply shape, for `rangeFormatting`'s reason (the
|
||||
engine's contract is over the file; what makes a request a *range* format is
|
||||
which constructs were laid out).
|
||||
|
||||
Consequences worth stating, all tested:
|
||||
|
||||
| client sends | answer |
|
||||
|---|---|
|
||||
| ranges out of order (`[7-8, 2-3]`) | same as sorted — `LineRanges` sorts |
|
||||
| overlapping ranges (`[2-4, 3-6]`) | same as the merged range `2-6` |
|
||||
| adjacent ranges (`[2-2, 3-3]`) | same as `2-3`; merging changes no answer |
|
||||
| the same range twice | same as once |
|
||||
| `"ranges": []` | `[]`, no edit, no message — an empty ask is not an error |
|
||||
| one huge range over the buffer | the whole-file format, as `rangeFormatting` already answers |
|
||||
| a buffer the engine refuses | `[]` **and** a `window/showMessage` ERROR, byte-identical to `rangeFormatting`'s refusal |
|
||||
| a buffer this server has not been sent | `null`, as every other formatting handler answers |
|
||||
|
||||
The refusal path is not "similar to" `rangeFormatting`'s — it is the same
|
||||
`Server::edits` and the same `Server::warn_about_config`, reached from a
|
||||
dispatch arm that differs only in how the params were decoded. There is one
|
||||
test that asserts the two refusals are equal *values* rather than asserting the
|
||||
shape of each.
|
||||
|
||||
### The capability decision: gated on the client, not advertised blind
|
||||
|
||||
`documentRangeFormattingProvider` is `boolean | DocumentRangeFormattingOptions`
|
||||
in the spec, so sending the object form is legal against 3.17 and 3.18 alike,
|
||||
and `vscode-languageclient` reads it through `getRegistrationOptions`, which
|
||||
handles both arms (`features.js:230`: `Is.boolean(capability) && capability === true ? { documentSelector } : { ...capability, documentSelector }`).
|
||||
Advertising the object unconditionally would therefore *probably* be safe.
|
||||
|
||||
It is still gated on the client having sent
|
||||
`textDocument.rangeFormatting.rangesSupport: true`, for a reason that costs
|
||||
nothing:
|
||||
|
||||
- A client that did not ask will never send `rangesFormatting` however it is
|
||||
advertised, so the object form buys that client exactly nothing.
|
||||
- The bare `true` is the value every client has seen from this server since
|
||||
round 18, and a bare boolean is the one shape *no* client can misread. A
|
||||
hand-rolled client that tests `=== true` — the shape LSP servers have sent
|
||||
for this capability for a decade — keeps working.
|
||||
- The gate is one boolean read from the initialize params, and the request
|
||||
handler is registered unconditionally, so a client that sends the request
|
||||
without asking first is still answered.
|
||||
|
||||
So: **a 3.17 client sees `true`, byte-for-byte what it saw before this round; a
|
||||
3.18 client sees `{ "rangesSupport": true }`.** Both shapes are decoded from
|
||||
the real `initialize` JSON in tests.
|
||||
|
||||
`lsp-types` 0.97 cannot spell either half — its `DocumentRangeFormattingOptions`
|
||||
carries only `workDoneProgress`, and its
|
||||
`DocumentRangeFormattingClientCapabilities` is an alias for
|
||||
`DynamicRegistrationClientCapabilities` with no `rangesSupport` field — so both
|
||||
halves go through JSON:
|
||||
|
||||
- **Out:** `initialize_value()` replaces the serialized
|
||||
`documentRangeFormattingProvider` value, the precedent
|
||||
`docs/features/type-hierarchy/README.md` set for `typeHierarchyProvider`.
|
||||
Same function, same test discipline (the whole object is pinned, not just
|
||||
the one key).
|
||||
- **In:** the flag is read from the **raw** `initialize` params `Value` before
|
||||
it is deserialized into `InitializeParams`, because the typed struct drops
|
||||
the field. `main.rs` already had that raw value in hand.
|
||||
|
||||
### Client reach — checked, not assumed
|
||||
|
||||
- `editors/vscode/node_modules/[email protected]` (the pinned
|
||||
version) **already implements the request**:
|
||||
`lib/common/formatting.js:74` sends `capability.rangesSupport = true`, and
|
||||
`:109` registers `provideDocumentRangesFormattingEdits` *only if*
|
||||
`options.rangesSupport` came back from the server. So before this round the
|
||||
extension was asking for the feature and being told no.
|
||||
- `[email protected]` carries
|
||||
`DocumentRangesFormattingRequest` and `DocumentRangesFormattingParams`
|
||||
(`lib/common/protocol.d.ts:2900,2945`), so the wire shape implemented here is
|
||||
that library's, not a reading of the spec text.
|
||||
- `[email protected]` requires `engines.vscode: ^1.82.0` and sets
|
||||
`provideDocumentRangesFormattingEdits` on the provider it registers, so the
|
||||
VS Code API exists at the version this extension already targets
|
||||
(`editors/vscode/package.json` pins the same `^1.82.0`).
|
||||
- Neovim's built-in client sends `rangeFormatting`, not `rangesFormatting`; it
|
||||
loses nothing, because the gate leaves its capability exactly as it was.
|
||||
|
||||
## Parked, and why
|
||||
|
||||
Both items were assessed against the same three questions: does `lsp-types`
|
||||
0.97 model it, does the client capability exist to read, and can the pinned
|
||||
client stack apply it. An item that fails the third is parked — implementing a
|
||||
protocol nothing on the other end speaks is how a server acquires a capability
|
||||
that is a lie.
|
||||
|
||||
### Snippet edits in `WorkspaceEdit` — parked
|
||||
|
||||
3.18 lets a `WorkspaceEdit` carry a `SnippetTextEdit`, so `lucisv.addPort`
|
||||
could drop the cursor on the new port's name with the type as a tabstop
|
||||
instead of leaving the caret where the apply happened to end.
|
||||
|
||||
| question | answer | evidence |
|
||||
|---|---|---|
|
||||
| `lsp-types` 0.97 models `SnippetTextEdit`? | **No** | `grep -rn 'SnippetTextEdit' lsp-types-0.97.0/src/` → nothing |
|
||||
| the client capability field exists to read? | **No** | `WorkspaceEditClientCapabilities` (`lib.rs:1071`) has exactly `documentChanges`, `resourceOperations`, `failureHandling`, `normalizesLineEndings`, `changeAnnotationSupport` — no `snippetEditSupport` |
|
||||
| the pinned client can apply one? | **No** | `grep -rln 'snippetEditSupport\|SnippetTextEdit' editors/vscode/node_modules/` → no hits at all, in either `[email protected]` or `[email protected]` |
|
||||
|
||||
All three fail, and the third is the one that decides it: the extension's
|
||||
client library has no code path that would turn a `snippet` edit into a
|
||||
tabstop, so a server sending one would be sending an object the client either
|
||||
drops or applies as a literal `${1:name}` written into the user's buffer —
|
||||
which is the exact failure mode `snippet_support()` already exists to prevent
|
||||
on the completion path (`main.rs`: "a literal `${1:clk}` written into a buffer
|
||||
is worse than no tabstops at all").
|
||||
|
||||
**Re-check trigger, exactly:** when `editors/vscode/package.json` moves off
|
||||
`[email protected]`, grep the new tree for `snippetEditSupport`. It
|
||||
appears when the client library implements this; that string in
|
||||
`node_modules/vscode-languageserver-protocol/lib/common/protocol.d.ts` is the
|
||||
whole signal. The server side then needs (a) a `snippetEditSupport` read added
|
||||
next to `apply_edit_support` in `main.rs`, and (b) `ports.rs`'s `WorkspaceEdit`
|
||||
to emit `{ "snippet": { "value": … } }` in place of `newText` for the one edit
|
||||
that creates the port, gated on that flag.
|
||||
|
||||
### `workspace/textDocumentContent` — parked
|
||||
|
||||
3.18's server-provided read-only documents. The tempting use is a
|
||||
`lucisv-expanded:` URI serving the macro-expanded view that
|
||||
`docs/features/macro-expansion/README.md` currently shows only inside a hover
|
||||
card.
|
||||
|
||||
| question | answer | evidence |
|
||||
|---|---|---|
|
||||
| `lsp-types` 0.97 models it? | **No** | `grep -rn 'textDocumentContent' lsp-types-0.97.0/src/` → only `TextDocumentContentChangeEvent`, an unrelated sync type |
|
||||
| the pinned client can serve one? | **No** | `grep -rln 'textDocumentContent' editors/vscode/node_modules/` → no hits |
|
||||
| the extension could route it anyway? | **No** | serving a custom URI scheme in VS Code needs `workspace.registerTextDocumentContentProvider` in the extension host; `editors/vscode/extension.js` deliberately registers no providers of its own — it starts the server and gets out of the way |
|
||||
|
||||
This one is parked twice over: the client library does not implement the
|
||||
request, *and* the thin extension is the wrong shape to consume it. Note also
|
||||
that the feature it would serve does not exist yet in a document-sized form —
|
||||
`hover.rs` expands one macro call one step (`macro-expansion`'s stated scope:
|
||||
"One step, display only"), so there is no whole-file expanded text to serve.
|
||||
A future round wanting this wants a preprocessor first, which TODO.md §7 says
|
||||
lucisv does not have and does not want.
|
||||
|
||||
**Re-check trigger, exactly:** the same `node_modules` grep, for
|
||||
`textDocumentContent`, plus a decision to give `extension.js` a content
|
||||
provider. Both, not either.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`LineRanges::new` is the one normalizer.** Sorting, merging overlaps and
|
||||
folding adjacent spans happen there, once, for the CLI and both LSP
|
||||
formatting requests. This round adds no second copy and asserts the
|
||||
normalization through the public answer rather than restating it.
|
||||
- **A client sends ranges that name lines in the buffer it opened.** Nothing
|
||||
checks that a range's lines exist: past-EOF spans clamp in the engine (the
|
||||
`--lines` rule, documented in `range-formatting`), and a range on a document
|
||||
the server does not hold answers `null` before any of this runs.
|
||||
- **Only line numbers matter.** Same as `rangeFormatting`: the UTF-16 columns
|
||||
are thrown away by `lines_of`, so there is nothing to get wrong about them.
|
||||
- **A client that advertises `rangesSupport` reads the union form of
|
||||
`documentRangeFormattingProvider`.** It is the shape its own protocol
|
||||
library declares; a client asking a 3.18 question in 3.17-only JSON terms is
|
||||
not a client that exists.
|
||||
- **Parking is assessed against the *pinned* client**, `[email protected]`
|
||||
as vendored in `editors/vscode/node_modules`, not against what some
|
||||
unreleased client might do. The re-check triggers above are written so the
|
||||
assessment can be redone in one grep.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_formatter`:** `format_range`, `LineRanges::new`,
|
||||
`Config`. Nothing new is asked of `vlog_formatter` and nothing in it was
|
||||
changed — the multi-range engine has existed since round 18 for `--lines`.
|
||||
|
||||
**Consumed from `lsp_types`:** `Range`, `TextEdit`, `FormattingOptions`,
|
||||
`TextDocumentIdentifier`. The 3.18 params type is hand-rolled here
|
||||
(`format::RangesFormattingParams`) because 0.97 does not carry it, the same way
|
||||
`pairs::ScopePairsParams` is hand-rolled for a custom method.
|
||||
|
||||
**Promised to `crates/lucisv_server` callers:**
|
||||
|
||||
- `format::ranges_formatting(&Document, &Config, &[Range]) -> Result<Option<TextEdit>, String>`
|
||||
is the new entry point, and `format::range_formatting` is now defined as its
|
||||
one-element case. Both keep the old signature and the old answer.
|
||||
- `format::RANGES_FORMATTING` is the method string, and
|
||||
`format::RangesFormattingParams` the decoded params.
|
||||
- `main::initialize_value` now takes one `bool` (whether to widen the range
|
||||
formatting capability). Callers: `main()` and the tests in `main.rs`.
|
||||
|
||||
**Promised to `editors/vscode`:** nothing to do. `extension.js` is untouched
|
||||
and needs no change — `vscode-languageclient` registers its multi-range
|
||||
provider off the server's capability alone, so the feature turns on when the
|
||||
user updates the server binary. `smoke.js` was extended (its `initialize` now
|
||||
sends the `rangesSupport` capability the real client sends, plus one
|
||||
`rangesFormatting` leg), because a pre-publish check that advertises less than
|
||||
the shipping client would be checking a shape no user ever sees.
|
||||
|
||||
**Changed for another module:** none. `verify.rs`, `vlog_formatter`,
|
||||
`vlog_parser`, `vlog_semantic`, `vlog_linter`, `crates/lucisv`,
|
||||
`editors/vscode/extension.js`, `corpus/` and the `.cases` tables are all
|
||||
untouched.
|
||||
|
||||
**`verify.rs` is untouched** — `git diff --quiet` on it exits 0. No
|
||||
normalization was added, broadened or weakened, so CLAUDE.md invariant #4's
|
||||
attack-test requirement does not apply to this round. It could not: every byte
|
||||
this round produces comes out of `format_range`, which runs the unchanged net
|
||||
over the whole buffer.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `format.rs`: `lines_of` extracted from `range_formatting`; `ranges_formatting`;
|
||||
`range_formatting` redefined as its one-element case; `RANGES_FORMATTING`
|
||||
and `RangesFormattingParams`.
|
||||
- [x] `server.rs`: the `textDocument/rangesFormatting` dispatch arm, sharing
|
||||
`edits` and `warn_about_config` with `rangeFormatting`.
|
||||
- [x] `main.rs`: `ranges_formatting_support` read from the raw initialize
|
||||
params; `initialize_value(bool)` widening the capability.
|
||||
- [x] Tests — **+24**: 11 units in `format.rs`, 7 session tests in `server.rs`,
|
||||
4 capability tests in `main.rs`, 2 e2e legs over the real binary (one per
|
||||
client shape), plus a `smoke.js` leg.
|
||||
- [x] Docs: this README, `lucisv-server`'s capability table and Status, TODO.md
|
||||
§9c's last box.
|
||||
- [x] **Parked:** snippet `WorkspaceEdit` edits — assessment above, with the
|
||||
exact re-check trigger.
|
||||
- [x] **Parked:** `workspace/textDocumentContent` — assessment above, with the
|
||||
exact re-check trigger.
|
||||
- [ ] **Not done, deliberately:** a per-range reply
|
||||
(`TextEdit[]` with one edit per range). The engine's contract is over the
|
||||
whole file, so the honest reply is the whole-document edit
|
||||
`rangeFormatting` already sends. Splitting it into `n` edits would be a
|
||||
claim about which bytes each range owns that nothing verifies.
|
||||
- [ ] **Not done:** dynamic registration of the range-formatting provider.
|
||||
The gate is decided once at `initialize` and never changes, so there is
|
||||
nothing a registration would buy; a client that flips `rangesSupport`
|
||||
mid-session does not exist.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev agent
|
||||
|
||||
- Read `CLAUDE.md`, TODO.md §9c, and the Handshakes of `lucisv-server`,
|
||||
`range-formatting`, `type-hierarchy` and `macro-expansion` before writing
|
||||
anything. Baseline: `cargo test -p lucisv_server` **993 unit + 48 e2e**,
|
||||
`cargo test --workspace` green, clippy silent, fmt clean.
|
||||
- **Checked all three items against `lsp-types` 0.97 and the pinned client
|
||||
before deciding anything.** The greps are in the sections above and are the
|
||||
whole basis for the ship/park calls. The surprise was the good one: the
|
||||
brief expected `[email protected]` to be too old for
|
||||
`rangesFormatting`, and it is not — 3.18 is newer than 9.0.1 as a *spec
|
||||
version*, but this particular request was already implemented there, and the
|
||||
library has been sending `rangesSupport: true` at this server for as long as
|
||||
the extension has existed. lucisv was answering with a bare `true` and
|
||||
turning it off. The other two items are as the brief guessed.
|
||||
- **The engine took multiple ranges natively, so this is an adapter and not a
|
||||
feature.** `LineRanges::new` sorts and merges (`range.rs:38`), which is
|
||||
exactly the "normalize overlapping/adjacent/unsorted ranges" the brief asked
|
||||
for, and `format_range` takes the merged list. So the whole implementation is
|
||||
three lines of `map(lines_of)` around the constructor. **This is the point,
|
||||
not a shortcut**: the verified contract, the equivalence check and the
|
||||
replayed-selection convergence check ride through untouched because it is
|
||||
literally the call `--lines 3-9,40` makes.
|
||||
- **`range_formatting` became the one-element case of `ranges_formatting`,
|
||||
rather than the two sharing a helper.** The brief allowed either. Defining
|
||||
one as the other is stronger: there is no shape of buffer or range for which
|
||||
the two can answer differently, which is what makes the refusal-equality test
|
||||
(`a_refused_buffer_is_refused_identically_whichever_range_request_asked`) an
|
||||
assertion about the code rather than a coincidence someone has to maintain.
|
||||
- **The line conversion was extracted, not copied** (`lines_of`), and pinned
|
||||
directly by a test — because it is now shared, a change to it moves two
|
||||
requests at once and the test says what it promises.
|
||||
- **One latent panic fixed in passing.** The old conversion wrote
|
||||
`range.end.line + 1`, which overflows in a debug build for an end line of
|
||||
`u32::MAX`. `saturating_add`, with a test. No behavior change for any range
|
||||
an editor can produce; it is CLAUDE.md's no-panic rule for library paths.
|
||||
- **The capability decision took the conservative arm, and it cost nothing.**
|
||||
The object form is spec-legal for a 3.17 client and
|
||||
`vscode-languageclient` handles the union (`features.js:230`), so
|
||||
advertising it unconditionally would very probably be fine. But a client
|
||||
that never sent `rangesSupport` gains exactly nothing from the object, and a
|
||||
bare boolean is the one shape nothing can misread — so the widening is gated
|
||||
on the client's own flag and **every client that shipped before this round
|
||||
sees a byte-identical `initialize` result**, asserted over the wire by
|
||||
`a_3_17_client_still_sees_the_bare_true_it_always_saw`. The pre-existing e2e
|
||||
assertion `documentRangeFormattingProvider == true` needed no edit, which is
|
||||
the same fact stated by an older test.
|
||||
- **The client flag has to be read from the raw params.** `lsp-types` 0.97
|
||||
aliases `DocumentRangeFormattingClientCapabilities` to the plain
|
||||
dynamic-registration struct, so `serde_json::from_value::<InitializeParams>`
|
||||
discards `rangesSupport` before anything can look at it. `main()` already had
|
||||
the raw `Value` in hand, so the read is one line placed before the decode.
|
||||
Symmetric with the JSON insertion on the way out, and documented as such.
|
||||
- **The handler is unconditional; only the advertising is gated.** A client
|
||||
that sends the request without having asked is answered rather than told the
|
||||
method does not exist — refusing a request we can serve because of a
|
||||
handshake detail would be the server being pedantic at the user's expense.
|
||||
- **`smoke.js` was changed in one substantive way**: its `initialize` now sends
|
||||
the `rangeFormatting.rangesSupport` capability, because that is what the real
|
||||
extension's client library sends and the smoke test's stated job is to
|
||||
"spawn the server exactly the way extension.js does". Without it the smoke
|
||||
test would assert a capability shape no real user ever sees. The new leg
|
||||
sends two ranges and asserts both that the named line moved and that a line
|
||||
no range named kept its bytes.
|
||||
- **Nothing outside `crates/lucisv_server` and `editors/vscode/smoke.js` was
|
||||
touched.** `verify.rs`, `vlog_formatter`, `vlog_parser`, `vlog_semantic`,
|
||||
`vlog_linter`, `crates/lucisv`, `corpus/`, the `.cases` tables and
|
||||
`docs/site/` are all unmodified (`git status --porcelain` names seven files
|
||||
— three server sources, its e2e, `smoke.js`, `TODO.md` and the
|
||||
`lucisv-server` README — plus this directory). No new dependency. Did not run
|
||||
`git commit`/`git push`.
|
||||
|
||||
**Results.**
|
||||
|
||||
- `cargo test --workspace`: **2176 passed, 0 failed** across 34 test binaries.
|
||||
This feature's crate: `lucisv_server` unit **993 → 1015** (+11 `format.rs`,
|
||||
+7 `server.rs`, +4 `main.rs`), e2e **48 → 50**.
|
||||
- `cargo test -p vlog_formatter`: **180 passed, 0 failed** — untouched, and
|
||||
`git diff --quiet crates/vlog_formatter` exits 0, so the snapshot and
|
||||
idempotency suites are green for the same reason they were yesterday.
|
||||
- `cargo clippy --workspace --all-targets`: silent, 0 warnings.
|
||||
`cargo fmt --all --check`: clean.
|
||||
- `node editors/vscode/smoke.js target/release/lucisv-server`: **OK**, 10
|
||||
messages (was 9), the new `rangesFormatting` leg included.
|
||||
- **No corpus run and no `verify.rs` attack tests**, and the reason is
|
||||
structural rather than an omission: this round adds no formatter code path
|
||||
at all. Every byte it can emit comes out of `format_range` with a
|
||||
`LineRanges` the CLI could equally have built, so the corpus evidence in
|
||||
`docs/features/range-formatting/README.md` (578 files, 8236 range trials, 0
|
||||
refusals) covers it unchanged, and CLAUDE.md invariant #4 does not apply
|
||||
because no normalization was added, broadened or weakened.
|
||||
|
||||
Files added: `docs/features/lsp-318-extras/README.md`.
|
||||
Files edited: `crates/lucisv_server/src/{format,server,main}.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, `editors/vscode/smoke.js`, `TODO.md`,
|
||||
`docs/features/lucisv-server/README.md`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent
|
||||
|
||||
**Gates, re-run clean.**
|
||||
|
||||
- `cargo fmt --all --check`: clean.
|
||||
- `cargo clippy --workspace --all-targets -- -D warnings`: silent (forced a
|
||||
rebuild with `touch` on the three changed sources first, since the initial
|
||||
run was cache-hit and could have hidden a stale result).
|
||||
- `cargo test --workspace`: **2176 passed, 0 failed**, 34 binaries — hand-summed
|
||||
every `test result:` line to confirm the dev's total rather than trusting it.
|
||||
`lucisv_server` unit **1015** (993→1015, +22: 11 `format.rs` + 7 `server.rs`
|
||||
+ 4 `main.rs`), e2e **50** (48→50, +2) — matches the claimed +24 exactly.
|
||||
- `cargo test -p vlog_formatter`: **180 passed, 0 failed**.
|
||||
- `git diff --quiet crates/vlog_formatter`: exit 0, confirmed myself.
|
||||
`find . -iname verify.rs` → `crates/vlog_formatter/src/verify.rs`,
|
||||
`git diff --quiet` on it: exit 0. `git status --porcelain docs/site/`: empty.
|
||||
- `cargo build --release -p lucisv_server` +
|
||||
`node editors/vscode/smoke.js target/release/lucisv-server`: **OK**, 10
|
||||
messages, against the real release binary.
|
||||
|
||||
**Verdict, per attack surface — all verified-clean, no findings, no fixes
|
||||
needed.**
|
||||
|
||||
1. **`range_formatting` redefinition.** Enumerated callers by grep: only
|
||||
`server.rs`'s `range_formatting` handler and `on_type.rs`'s `;`-trigger
|
||||
(`format::range_formatting` at `on_type.rs:83` and its test at
|
||||
`on_type.rs:1100`) call `format::range_formatting`; both keep the exact old
|
||||
`(doc, config, range: Range)` signature, so neither needed to change and
|
||||
neither did. Added a temporary probe in `format.rs`'s test module (added,
|
||||
run, reverted before finishing — `git diff --stat` on the three sources
|
||||
matches the pre-QA diffstat exactly: format.rs 229, server.rs 190, main.rs
|
||||
145 lines changed) covering: two ranges landing in one multi-line statement
|
||||
merge into one edit, not a double format; reverse document order matches
|
||||
forward order; a range at line 0 plus one at the last line lays out both
|
||||
ends; 50 tiny ranges over a 200-line buffer format in well under a second
|
||||
(no quadratic blowup observed); a format-off fence beats a range inside it
|
||||
while a range outside the fence still formats — all through the real
|
||||
`ranges_formatting` → `format_range` → `LineRanges::new` path, not mocked.
|
||||
All five passed. The on-type `;` path's existing byte-identity test
|
||||
(`on_type.rs:1100`, `format::range_formatting(...) ...` compared against
|
||||
`range_formatting` output) was re-run unchanged and green — the dev's claim
|
||||
that no consumer needed to change holds.
|
||||
2. **Gated capability's raw-params read.** `ranges_formatting_support` at
|
||||
`main.rs:373` is exactly `params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"]
|
||||
== true`. Extracted the identical function body into a standalone probe
|
||||
binary (character-for-character copy, diffed against the source to confirm)
|
||||
and drove it with every shape the brief asked for beyond the dev's own test:
|
||||
`textDocument` a string, `rangeFormatting` null, `rangesSupport` as the
|
||||
string `"true"`, as `1`, as `[true]`, as an object, params entirely absent,
|
||||
`capabilities` an array, and duplicate JSON keys for `rangesSupport` (both
|
||||
orders). Result: **only literal boolean `true` gates**, every other shape
|
||||
answers `false`; duplicate keys resolve last-value-wins, which is
|
||||
`serde_json`'s standard (and harmless — the client controls both the first
|
||||
and the last copy of its own key, so there's no cross-party spoofing
|
||||
surface here). Then the two real-wire e2e legs
|
||||
(`ranges_formatting_is_advertised_to_a_client_that_asked_and_formats_every_range`,
|
||||
`a_3_17_client_still_sees_the_bare_true_it_always_saw` in `tests/e2e.rs`)
|
||||
were re-run and pass: 3.17 client → bare `true`, confirmed byte-identical
|
||||
to what `git show 17fb212` would have produced (the capability line is
|
||||
untouched by this round's diff at the pre-round call site — verified by
|
||||
inspecting `initialize_value(false)` reproduces `serde_json::json!(true)`
|
||||
in `main.rs`'s own test at the same key). 3.18 client → the object.
|
||||
`widening_the_range_capability_disturbs_nothing_else_in_the_initialize_result`
|
||||
(`main.rs`) does insert-and-compare on the *whole* object, mirroring
|
||||
`the_json_insertion_disturbs_nothing_else_in_the_initialize_result`'s
|
||||
pattern for `typeHierarchyProvider` — confirmed it swaps exactly one key and
|
||||
asserts full equality afterward, not a spot check.
|
||||
3. **Union semantics.** All five scenarios verified through the real engine
|
||||
(see item 1's temporary probes): merged single-statement ranges, reverse
|
||||
order, line-0-and-last-line, 50-range timing sanity, and format-off fence
|
||||
outranking an inside range while an outside range still formats. No
|
||||
surprises; every one matched the README's stated semantics.
|
||||
4. **Refusal equality.** `a_refused_buffer_is_refused_identically_whichever_range_request_asked`
|
||||
(`format.rs`) and `a_refusal_is_the_same_answer_and_the_same_popup_on_both_range_methods`
|
||||
(`server.rs`) both assert full `Result`/response equality *and* the
|
||||
`window/showMessage` traffic (`session.shown()`) is identical, not just
|
||||
"an error happened on both". Confirmed both tests actually run this
|
||||
comparison (not just constructing it) and pass.
|
||||
5. **`saturating_add` fix — deliberate-breakage protocol run for real.**
|
||||
Reverted `format.rs:167` from `range.end.line.saturating_add(1)` back to
|
||||
`range.end.line + 1`, ran
|
||||
`cargo test -p lucisv_server --bin lucisv-server the_line_conversion_is_the_one_rangeformatting_always_used`:
|
||||
it panicked — `attempt to add with overflow` at `format.rs:167:66` — exactly
|
||||
as claimed. Restored the fix, re-ran the same test: passes. `git diff
|
||||
--stat` on `format.rs` confirmed unchanged from the pre-revert state
|
||||
afterward.
|
||||
6. **Parked items' evidence — every grep re-run independently and matched
|
||||
exactly.** `lsp-types-0.97.0` (found at
|
||||
`~/.cargo/registry/src/index.crates.io-*/lsp-types-0.97.0`):
|
||||
`grep -rn 'SnippetTextEdit' src/` → no match;
|
||||
`WorkspaceEditClientCapabilities` at `lib.rs:1071` has exactly
|
||||
`document_changes`, `resource_operations`, `failure_handling`,
|
||||
`normalizes_line_endings` (truncated view, `change_annotation_support`
|
||||
follows) and no `snippet_edit_support` field;
|
||||
`grep -rn 'textDocumentContent' src/` → only `TextDocumentContentChangeEvent`
|
||||
hits, an unrelated sync type, in `lib.rs` and `notebook.rs`.
|
||||
`editors/vscode/node_modules/`: `grep -rln 'snippetEditSupport\|SnippetTextEdit'`
|
||||
→ no hits; `grep -rln 'textDocumentContent'` → no hits;
|
||||
`grep -n 'registerTextDocumentContentProvider\|ContentProvider' extension.js`
|
||||
→ no hits. `DocumentRangeFormattingClientCapabilities` confirmed as a type
|
||||
alias to `DynamicRegistrationClientCapabilities`
|
||||
(`formatting.rs:11` in the same crate). The re-check triggers in the README
|
||||
are literal, runnable grep commands — confirmed by running them as written.
|
||||
7. **`smoke.js` change vs the real client.** `[email protected]`'s
|
||||
`lib/common/formatting.js:74` is `capability.rangesSupport = true;` inside
|
||||
`DocumentRangeFormattingFeature.fillClientCapabilities` — exact match to the
|
||||
dev's citation. Line 109 (`if (options.rangesSupport) {`) gates whether
|
||||
`provideDocumentRangesFormattingEdits` gets attached to the registered
|
||||
provider — also an exact match. `features.js`'s `getRegistrationOptions`
|
||||
(the union-handling precedent cited) matches the description at the cited
|
||||
behavior (boolean `true` → bare `{documentSelector}`, otherwise
|
||||
`{...capability, documentSelector}`), modulo `Object.assign` vs spread
|
||||
syntax, which are equivalent. `[email protected]`'s
|
||||
`protocol.d.ts:2900` (`DocumentRangesFormattingParams`) and `:2945`
|
||||
(`DocumentRangesFormattingRequest`) both confirmed present at those exact
|
||||
lines. `package.json` engines: both `editors/vscode/package.json` and the
|
||||
vendored `vscode-languageclient/package.json` pin `^1.82.0` — confirmed.
|
||||
Ran `smoke.js` against the freshly built release binary: **OK**, 10
|
||||
messages, matching the claimed count.
|
||||
8. **CLAUDE.md compliance.** Grepped every added line (`git diff -U0`) in
|
||||
`format.rs`, `server.rs`, `main.rs` for `.unwrap()`/`.expect()`/`panic!`
|
||||
outside the `mod tests` boundary (found at `format.rs:231`,
|
||||
`server.rs:1602`, `main.rs:495`) — every hit found is inside a test module;
|
||||
zero in production code paths. No new `#[allow(...)]` anywhere in the diff.
|
||||
`RangesFormattingParams` has a struct-level doc comment and undocumented
|
||||
fields, matching the existing project convention for hand-rolled params
|
||||
structs (`pairs::ScopePairsParams`/`ScopePair` follow the identical
|
||||
pattern). README has each of the seven mandated sections (`Goal`,
|
||||
`Assumptions`, `Handshakes`, `Status / TODO`, `Work log`, `QA log`,
|
||||
`Review`) exactly once, plus two extra descriptive `##` subsections that
|
||||
don't collide with the mandated set. `TODO.md`'s §9c item text is intact —
|
||||
checkbox flipped `[ ]`→`[x]`, an appended `→ 2026-08-27 ...` note in the
|
||||
same style as the two items directly above it, and it states both the
|
||||
shipped item and the two parked items with reasons, as required.
|
||||
`verify.rs`: confirmed untouched myself (`git diff --quiet` exit 0) —
|
||||
correctly, since invariant #4's attack-test requirement doesn't apply here
|
||||
(no normalization touched).
|
||||
|
||||
**C. Beyond the list.** Added and ran three more temporary probes (in
|
||||
`server.rs`'s test module, added/run/reverted, diff restored to the original
|
||||
190-line diffstat afterward):
|
||||
- `ranges` given as `{}` (an object, not an array) → `InvalidParams`, not a
|
||||
panic. Pass.
|
||||
- Extra unknown params fields (`workDoneToken`, an arbitrary nested object)
|
||||
alongside a valid request → ignored, request answered normally
|
||||
(`#[serde(deny_unknown_fields)]` is not on `RangesFormattingParams`, and
|
||||
nothing needed it to be — serde's default is permissive). Pass.
|
||||
- A client that advertises `rangesSupport` at `initialize` (so it gets the
|
||||
gated capability) but then only ever calls the *old*
|
||||
`textDocument/rangeFormatting` — confirmed the old path's answer is
|
||||
byte-identical to what it always was; the gate is purely advertisement,
|
||||
nothing about it changes `range_formatting`'s own behavior. Pass.
|
||||
|
||||
**No findings.** No fixes were necessary — the round is clean at every attack
|
||||
surface asked for, plus the three extra ones above. All temporary QA probe
|
||||
tests were removed after running; the three touched source files are back to
|
||||
the exact diffstat the dev left them at (`format.rs` 229, `server.rs` 190,
|
||||
`main.rs` 145 lines changed — confirmed line-for-line via `git diff --stat`
|
||||
before and after).
|
||||
|
||||
**This is the last feature round of §9c.** Nothing here should block the
|
||||
0.10.0 release cut: all gates green, `vlog_formatter` and `verify.rs`
|
||||
untouched (so invariant #4 doesn't apply), the corpus argument for "no new
|
||||
formatter code path" holds up under direct inspection (every byte still comes
|
||||
out of the pre-existing `format_range`), and the two parked items are parked
|
||||
with re-checkable, currently-true evidence rather than asserted from memory.
|
||||
**Verdict: committable as-is.**
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-27 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. The right ending for the audit: one real feature shipped on the
|
||||
engine that already knew how to do it, and two honest parkings with
|
||||
evidence a future reader can re-run in one grep each. The round's
|
||||
discovery — the pinned client library has been requesting multi-range
|
||||
formatting all along, and our bare-boolean advertisement was the thing
|
||||
refusing it — is the audit's thesis in miniature: the gaps were in what
|
||||
we said, not only in what we did. The gated widening is the right
|
||||
conservatism (pre-round clients see a byte-identical initialize result,
|
||||
proven on the wire), and redefining range_formatting as the one-element
|
||||
case makes the refusal-equality property structural, which QA verified
|
||||
with differential probes through the real engine plus the
|
||||
deliberate-breakage check on the overflow fix. Declining to split the
|
||||
whole-document edit into per-range claims the engine never verified is
|
||||
exactly the invariant culture applied to a reply shape. This completes
|
||||
§9c and the LSP 3.18 audit's feature work. Accepted as shipped.
|
||||
@@ -18,10 +18,20 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
|---|---|---|
|
||||
| `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed |
|
||||
| `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries |
|
||||
| `textDocument/rangesFormatting` | `vlog_formatter::format_range` | LSP 3.18's multi-range form of the line above, and literally its `n`-range case: the ranges become one sorted, merged `LineRanges` and one engine call, so the all-or-nothing contract is over the union rather than per range. `range_formatting` is now defined as the one-element call of it, and the reply, the refusal and the config warning are the same values. Advertised by widening `documentRangeFormattingProvider` from `true` to `{ "rangesSupport": true }` — **only for a client that sent `textDocument.rangeFormatting.rangesSupport`**, so a 3.17 client sees exactly what it always saw; the handler itself is unconditional. `lsp-types` 0.97 spells neither half, so both go through JSON. See `docs/features/lsp-318-extras/README.md` |
|
||||
| `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` |
|
||||
| `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
|
||||
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
|
||||
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
|
||||
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it |
|
||||
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md` |
|
||||
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` |
|
||||
| `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` |
|
||||
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
|
||||
| `textDocument/references` | `vlog_refactor::find_references`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port); in-file for everything else, which is what keeps a local `wire` off the workspace walk. See `docs/features/references-nav/README.md` |
|
||||
| `textDocument/documentHighlight` | `pairs::analyze`, else `Semantics::references_of` | A scope keyword highlights its own closer; anything else highlights the symbol's occurrences in this file. Kind is always `Text`; neither answer means `null`, so the editor keeps its word highlighting. Same feature README |
|
||||
@@ -33,10 +43,22 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README |
|
||||
| `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` |
|
||||
| `textDocument/prepareCallHierarchy` | `instantiations::{sites,declarations}`, `WorkspaceIndex::units` | The module under the cursor as a hierarchy node (`SymbolKind::Module`), from its own declaration or from any instantiation of it. Every other position answers `null`; an ambiguous name returns every declaration, as `definition` does. See `docs/features/hierarchy/README.md` |
|
||||
| `callHierarchy/incomingCalls` | `instantiations::sites` over `Workspace::sources` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. Walks the in-scope files — the index holds no instantiation edges — skipping any file whose text does not contain the name (56 ms over the 860-file corpus). Same feature README |
|
||||
| `callHierarchy/incomingCalls` | `instantiations::sites` over `Workspace::sources` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. Walks the in-scope files — the index holds no instantiation edges — skipping any file whose text does not contain the name (56 ms over the 860-file corpus). Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README |
|
||||
| `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. Same feature README |
|
||||
| `textDocument/prepareTypeHierarchy` | the class walk over `Document.tree`, then `ExternalResolutions::definition_of` | The **class** under the cursor as a type hierarchy node (`SymbolKind::Class`), from its own declaration or from any use of its name (an `extends` base, a property's type, a method local's type). Every other position answers `null`; a name two files declare returns both, as `definition` does. Advertised by hand — `lsp-types` 0.97's `ServerCapabilities` has no `typeHierarchyProvider` field. See `docs/features/type-hierarchy/README.md` |
|
||||
| `typeHierarchy/supertypes` | `ClassDecl::extends` + `ExternalResolutions::definition_of` | "What X extends": its base class, resolved by the same two layers F12 uses — in-file first, then the workspace overlay — asked at the **last byte** of the extends name, which is the tail of `pkg::base` and the whole of a bare `base`. A parameterized base resolves by its bare name; a base the workspace does not index (every UVM chain top) yields **no** item rather than a guess. Same feature README |
|
||||
| `typeHierarchy/subtypes` | the class walk over `Workspace::sources` | "Who extends X": every class in scope whose `extends` names it, sorted by file then position. Walks the in-scope files — the index holds no inheritance edges — skipping any file whose text does not contain the name (55 ms over the 860-file corpus, 53 ms of it file I/O). A **qualified** base is not matched by a bare name, the `callHierarchy` precedent; 0 of the corpus's 270 `extends` clauses are qualified. Same feature README |
|
||||
| `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same walk asked about every module in the file at once, so the two can never disagree. `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` |
|
||||
| `workspace/executeCommand` → `lucisv.showInstantiations` | `hierarchy::callers_of_each` | The code lens's own jump: `["module-name"]` in, every site as a `Location` out — one per site, file-then-position order. For a client that advertised `window.showDocument`, the server also pushes a `window/showDocument` for the **first** site, which is what makes the click navigate; LSP has no server-initiated peek-references, and this repo's extension declares no client-side command. A name with no sites answers `[]`; a missing or empty name is `RequestFailed`. Same feature README |
|
||||
| `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README |
|
||||
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
|
||||
| `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` |
|
||||
| `workspace/didChangeWorkspaceFolders` | `Workspace::change_roots` + `rebuild_index` | Folders added and removed mid-session, since 2026-08-27. One rescan per *notification* (the event carries both lists), and none at all for an event that leaves the root set where it was — a folder already held, one never held, an empty event, a non-`file:` folder. A removed folder's files leave the index; its open buffers stay open and keep being diagnosed, exactly as an out-of-scope buffer always has. Advertised as `workspace.workspaceFolders: { supported, changeNotifications }` — both halves, because a client reads them separately. See `docs/features/folders-and-config/README.md` |
|
||||
| `workspace/configuration` | `settings::from_section` → `from_payload` | Server-**initiated**, since 2026-08-27: the `lucisv` section, asked for once at startup and again on every *empty* `didChangeConfiguration` (the 3.17 client's "something changed, ask me"). Only for a client that advertised `workspace.configuration`; a push with a payload still applies directly, so the legacy path is untouched. The answer is entry 0 of an array and goes through the same parser a push does; an error, a `null`, an empty array or junk all mean the defaults, and none of them says anything to the user. Same feature README |
|
||||
| `workspace/willRenameFiles` | `includes::IncludeGraph` (through `resolve_as_if`) | The client is about to rename files and asks what that costs: every `` `include`` in scope whose **resolved** target moves — never a filename match — is re-spelled so it still resolves, in the form it was written in (bare stays bare where a rung reaches it, angled resolves through `+incdir+`s only, absolute stays absolute), shortest resolving suffix first and a `../`-relative spelling only as a last resort. An include written *in* a file that moves is re-spelled too. An include no spelling can reach is **left exactly as written** and named in a `window/showMessage` warning — nothing is invented. `null` when there is nothing to do. Folders are answered as well as files (LSP sends only the folder's URI; a folder is a path prefix). Every edit covers the path token alone and is verified three ways before it is emitted — see `docs/features/file-operations/README.md` |
|
||||
| `workspace/didRenameFiles`, `workspace/didDeleteFiles` | `Workspace::rebuild_index` | One `reindex()` per notification whose paths touch the index's scope, filtered by the same predicate a watched-file event is. Deliberately not deduplicated against the watcher: a client may send both, and a second rebuild re-reads the tree rather than changing an answer. Source-file filters only — a folder move reaches the index through the watcher's own events. Same feature README |
|
||||
| `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` |
|
||||
| `$/cancelRequest` | — | Best-effort, and honoured exactly when the cancel reaches the loop in the same burst as the request it names: that request is answered `RequestCancelled` (-32800) instead of computed. A cancel for anything else is dropped where it is read, `shutdown` is never cancellable, and nothing already running is interrupted. See `docs/features/cancel-request/README.md` |
|
||||
|
||||
Deferred, deliberately, and named in Status/TODO below: ~~range formatting
|
||||
(waits on TODO.md §2 `--lines`)~~ **delivered by range-formatting (round 18):
|
||||
@@ -182,23 +204,45 @@ every character boundary of a document mixing all of those.
|
||||
## State and staleness
|
||||
|
||||
Single-threaded request loop — `lsp-server`'s model. Two I/O threads (its
|
||||
own) read and write stdio; this crate's loop receives one message, handles it
|
||||
to completion, and sends the response before looking at the next. No shared
|
||||
mutable state, no locks, no cancellation. Verilog files are small and every
|
||||
handler is milliseconds; the complexity of a worker pool buys nothing yet.
|
||||
own) read and write stdio; this crate's loop handles one message to completion,
|
||||
and sends the response before looking at the next. No shared mutable state, no
|
||||
locks, and nothing already running is ever interrupted. Verilog files are small
|
||||
and every handler is milliseconds; the complexity of a worker pool buys nothing
|
||||
yet.
|
||||
|
||||
**Since 2026-08-26 the loop reads in bursts** rather than strictly one message
|
||||
at a time: it blocks for the next message, takes everything already queued
|
||||
behind it without blocking, and then handles that whole burst **in arrival
|
||||
order** — a `didChange` ahead of a completion is applied before the completion
|
||||
is answered, exactly as before. The one thing the burst adds is
|
||||
`$/cancelRequest`: a request the same burst also carries a cancel for is
|
||||
answered `RequestCancelled` (-32800) instead of being computed, which is the
|
||||
only moment a one-thread server can honour a cancel at all. A cancel that
|
||||
names no request in its burst is dropped where it is read (the request was
|
||||
answered in an earlier burst, or never existed), so cancellation costs no
|
||||
state; `shutdown` is handled before any cancel is consulted and so can never
|
||||
be cancelled. Because `lsp-server`'s transport uses zero-capacity rendezvous
|
||||
channels — a client's backlog sits in the OS pipe, not on
|
||||
`connection.receiver` — the loop first forwards incoming messages onto an
|
||||
unbounded queue of its own on one small thread, which stops at `shutdown` so
|
||||
`handle_shutdown` keeps its own read of the `exit` that follows. Rules,
|
||||
reasoning and the measurements: `docs/features/cancel-request/README.md`.
|
||||
|
||||
**Two layers, invalidated by different events** — exactly the split
|
||||
`docs/features/workspace-index/README.md` designed for:
|
||||
|
||||
| layer | rebuilt when | cost |
|
||||
|---|---|---|
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` | one file, full recompute |
|
||||
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, and a changed `lucisv.exclude`/`lucisv.filelist` | full re-scan of the roots |
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute |
|
||||
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist` (pushed **or** pulled) | full re-scan of the roots |
|
||||
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
|
||||
|
||||
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
|
||||
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
|
||||
deferred there.
|
||||
deferred there. Incremental *sync* did not change that: the wire now carries
|
||||
ranges, but a `didChange` still throws the whole `Document` away and builds a
|
||||
new one — one reparse per notification, which is also the one generation bump
|
||||
the pull-diagnostics `resultId` depends on.
|
||||
|
||||
**Open buffers override disk** in every index rebuild: the roots are walked,
|
||||
each file read, and then every open document with a path replaces the disk
|
||||
@@ -215,6 +259,18 @@ point where the answer is expected to change anyway. Measured cost of a
|
||||
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
|
||||
plus the file reads.
|
||||
|
||||
**Every rescan is visible since 2026-08-26**, for a client that advertised
|
||||
`window.workDoneProgress`: the startup build and all three `reindex()` triggers
|
||||
are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
|
||||
begin/end pair on a fresh `lucisv-index-N` token, so a multi-second index on a
|
||||
big filelist reads as work rather than as a hang. The `begin` does not wait for
|
||||
the create's answer (the rescan blocks the loop immediately after), the answer
|
||||
is ignored on the same path the watcher registrations' is, there is no
|
||||
percentage and no intermediate report — the rescan is one opaque call — and the
|
||||
`end` names the indexed file count. A client that did not advertise the
|
||||
capability is sent nothing at all, which the spec requires. Rules and the
|
||||
startup-legality argument: `docs/features/work-done-progress/README.md`.
|
||||
|
||||
**Changes made outside the editor close on the next notification, not on the
|
||||
next save** (M9, `docs/features/file-watching/README.md`). The server registers
|
||||
`workspace/didChangeWatchedFiles` for `**/*.{v,vh,sv,svh}` and for the
|
||||
@@ -229,6 +285,23 @@ model above; nested `-f` filelists are not watched, only the root one;
|
||||
rebuild from any cause picks it up); and there is no time-based debouncing, so
|
||||
a burst arriving as several separate notifications costs one rebuild each.
|
||||
|
||||
**Settings arrive two ways since 2026-08-27** (folders-and-config): pushed, as
|
||||
they always were, and *pulled*. A client that advertised
|
||||
`workspace.configuration` is sent one `workspace/configuration` for the
|
||||
`lucisv` section at startup, and another whenever it sends a
|
||||
`didChangeConfiguration` whose payload is empty — which is the 3.17 client's
|
||||
way of saying "something changed, come and ask", and is what
|
||||
`vscode-languageclient` sends once no legacy `synchronize.configurationSection`
|
||||
is configured. A push that carries a real payload still applies directly, so
|
||||
nothing about the old path moved. Both doors lead to one parser
|
||||
(`settings::from_payload`) and one applier (`Server::apply_settings`), so a
|
||||
setting cannot mean two things depending on how it arrived, and
|
||||
`exclude`/`filelist` cost the same rescan either way. A pulled answer can land
|
||||
*after* the first index build — as a pushed one always could, since neither
|
||||
can arrive before `initialized` — so the first index is built against the
|
||||
default scope and a narrowing setting costs one extra rescan when it lands.
|
||||
Rules: `docs/features/folders-and-config/README.md`.
|
||||
|
||||
**Definition targets in other files need that file's text** to turn a
|
||||
`TextRange` into a `Range`, and the index deliberately keeps no file contents.
|
||||
The server resolves a target by taking the **open buffer's text if that path
|
||||
@@ -238,10 +311,17 @@ not see.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Full-text document sync only.** The server advertises
|
||||
`TextDocumentSyncKind::FULL`, so a `didChange` carries the whole buffer and
|
||||
there is no incremental-edit application to get wrong. At Verilog file sizes
|
||||
the wire cost is irrelevant.
|
||||
- ~~**Full-text document sync only.**~~ **Superseded (incremental-sync, round
|
||||
2026-08-26).** The server advertises `TextDocumentSyncKind::INCREMENTAL`
|
||||
inside a `TextDocumentSyncOptions` (`openClose: true`,
|
||||
`save.includeText: false` — the same values a bare `Kind` resolved to
|
||||
client-side, so only `change` moved). A `didChange` now carries ranges, and
|
||||
`sync::apply_changes` applies them in order to the buffer the server holds:
|
||||
each range is positioned against what the previous ones left, a change with
|
||||
no range still replaces the whole document, and every out-of-range or
|
||||
backwards position clamps rather than panicking. The server is now the only
|
||||
holder of the buffer text, which is what makes that function's rules worth
|
||||
reading in full: `docs/features/incremental-sync/README.md`.
|
||||
- **Every document URI is a `file:` URI.** `untitled:` buffers are accepted
|
||||
and served for everything single-file (diagnostics, tokens, formatting,
|
||||
symbols), but they have no path, so they never enter the workspace index.
|
||||
@@ -253,6 +333,13 @@ not see.
|
||||
on a POSIX path legitimately named `/C:`.
|
||||
- **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling
|
||||
back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`.
|
||||
~~They are read once and frozen for the session.~~ **Superseded
|
||||
(folders-and-config, 2026-08-27): `workspace/didChangeWorkspaceFolders`
|
||||
adjusts the root set mid-session, one rescan per notification. A removed
|
||||
folder's files leave the index while its open buffers stay open and keep
|
||||
being diagnosed, and removing the *last* folder simply becomes rung 3 of
|
||||
the scope ladder — the rootless case — with no special handling. See
|
||||
`docs/features/folders-and-config/README.md`.**
|
||||
~~`.gitignore` and `--exclude` are **not** honored~~ **Superseded by
|
||||
lucisv-core-lift (lead note): the scan now uses the lifted `lucisv_core` walk —
|
||||
`.gitignore` always on, workspace-root config excludes applied. The old
|
||||
@@ -334,7 +421,12 @@ done here:
|
||||
a backtick, distinguished by the existing public `Token::is_macro()` —
|
||||
which is enough, so this is a note, not a request.
|
||||
4. **`vlog_semantic`: nothing.** The queries needed for all six navigation
|
||||
capabilities existed exactly as documented.
|
||||
capabilities existed exactly as documented. *(One request has since been
|
||||
filed by type-definition: an unqualified name nothing in the file binds is
|
||||
reported `NotFound` rather than as an external candidate, so the workspace
|
||||
overlay never sees it — which is how an `interface` type is written. Stated
|
||||
in full, with the fenced workaround it stands in for, in
|
||||
`docs/features/type-definition/README.md`.)*
|
||||
|
||||
## The `semanticTokens` mapping
|
||||
|
||||
@@ -378,7 +470,18 @@ Two rules that are easy to get wrong and are tested:
|
||||
three multi-line token shapes that would violate it — a block comment, a
|
||||
continued `` `define``, and a multi-line macro invocation. Every span is
|
||||
split at `\n` before encoding, and the pieces are sorted by (line, start)
|
||||
before the delta encoding runs.
|
||||
before the delta encoding runs. Single-line tokens are also what lets the
|
||||
`range` filter reason about overlap without looking at the text at all.
|
||||
|
||||
Since 2026-08-26 that classification feeds three requests, not one: the pass
|
||||
produces an intermediate **absolute** form (line, column, length, type,
|
||||
modifiers), `range` filters it, and one pure encoder delta-encodes whatever is
|
||||
left — from the start of the document in every case, so a range answer stands
|
||||
on its own. The `resultId` bookkeeping that makes `full/delta` possible lives
|
||||
in `server.rs` (one counter, one remembered answer per open buffer, dropped on
|
||||
`didClose`), because `tokens.rs` owns no state. Rules, the prefix/suffix
|
||||
overlap trap and the round-trip property:
|
||||
`docs/features/semantic-tokens-delta/README.md`.
|
||||
|
||||
## Hover, and the order it tries things
|
||||
|
||||
@@ -442,9 +545,22 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
`Semantics`, `DefineTable`, overlay), workspace walk, index rebuild.
|
||||
- [x] `textDocument/formatting`.
|
||||
- [x] Diagnostics on `didOpen`/`didChange`/`didSave`.
|
||||
- [x] `textDocument/semanticTokens/full`.
|
||||
- [x] `textDocument/semanticTokens/full`, joined by `/range` and `/full/delta`
|
||||
(2026-08-26) — one tokenizer and one encoder behind all three, plus a
|
||||
per-buffer `resultId` dropped on `didClose`.
|
||||
`docs/features/semantic-tokens-delta/README.md`.
|
||||
- [x] `textDocument/hover`.
|
||||
- [x] `textDocument/definition`.
|
||||
- [x] `textDocument/typeDefinition` — delivered by **type-definition**
|
||||
(2026-08-26, TODO.md §9c): the type half of go-to-definition, computed
|
||||
by redirecting the position to the type name the declaration writes and
|
||||
answering with `nav::definition` from there. No engine change.
|
||||
`docs/features/type-definition/README.md`.
|
||||
- [x] `textDocument/linkedEditingRange` — delivered by **linked-editing**
|
||||
(2026-08-26, TODO.md §9c): a closing label and the header name it
|
||||
repeats, answered as one linked pair off the AST node that holds both
|
||||
spans. No engine change; the two refusals (no label, mismatched label)
|
||||
are stated in `docs/features/linked-editing/README.md`.
|
||||
- [x] `textDocument/references`.
|
||||
- [x] `textDocument/documentSymbol` + `workspace/symbol`.
|
||||
- [x] Unit tests for the position conversion, including surrogate pairs.
|
||||
@@ -493,13 +609,74 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
the module hierarchy both directions, modules as the nodes and
|
||||
instantiations as the calls, off a walk shared with the inlay hints.
|
||||
`docs/features/hierarchy/README.md`.
|
||||
- [x] `typeHierarchy` (all three requests) — delivered by **type-hierarchy**
|
||||
(2026-08-26, TODO.md §9c): the class `extends` tree both directions,
|
||||
classes as the nodes. The capability is inserted into the serialized
|
||||
`initialize` result because `lsp-types` 0.97 has no field for it.
|
||||
`docs/features/type-hierarchy/README.md`.
|
||||
- [x] Single-step macro expansion on a hover card (`src/expand.rs`, M14) —
|
||||
`docs/features/macro-expansion/README.md`.
|
||||
- [x] `workspace/willRenameFiles` + `didRenameFiles`/`didDeleteFiles` —
|
||||
delivered by **file-operations** (2026-08-27, TODO.md §9c): a rename
|
||||
rewrites the `` `include``s that resolve to the moved file, folders
|
||||
included, and never invents a path that would not resolve.
|
||||
`docs/features/file-operations/README.md`.
|
||||
- [x] `$/cancelRequest` — delivered by **cancel-request** (2026-08-26,
|
||||
completing TODO.md §9b): the loop reads in bursts and answers a queued
|
||||
request whose cancel is in the same burst with `RequestCancelled`,
|
||||
order across the burst unchanged. `docs/features/cancel-request/README.md`.
|
||||
- [x] `textDocument/rangesFormatting` — delivered by **lsp-318-extras**
|
||||
(2026-08-27, completing TODO.md §9c): LSP 3.18's multi-range format,
|
||||
served as the `n`-range case of the one-range handler over the same
|
||||
engine. The capability is widened from `true` to
|
||||
`{ "rangesSupport": true }` only for a client that asked, so no client
|
||||
that shipped before it sees a different byte.
|
||||
`docs/features/lsp-318-extras/README.md`, which also records the two
|
||||
3.18 items **parked** with their evidence and re-check triggers: snippet
|
||||
`WorkspaceEdit` edits and `workspace/textDocumentContent`, neither of
|
||||
which the pinned `[email protected]` can consume.
|
||||
- [ ] **Not done:** editor packaging (the VS Code extension and the
|
||||
`lspconfig` snippet are their own TODO.md §6 item).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent (type-hierarchy, TODO.md §9c)
|
||||
|
||||
- **One new capability, one new module, nothing else moved.** The three
|
||||
`typeHierarchy` requests are served from
|
||||
`crates/lucisv_server/src/type_hierarchy.rs`; `server.rs` gained three
|
||||
dispatch arms. No engine change — `vlog_semantic` and `vlog_parser` are
|
||||
untouched, and `hierarchy.rs`/`instantiations.rs` were not opened.
|
||||
- **The capability is written by hand.** `lsp-types` 0.97 models type hierarchy
|
||||
on the *client* side only: `ServerCapabilities` has no
|
||||
`type_hierarchy_provider` field. `main.rs`'s new `initialize_value` serializes
|
||||
the `InitializeResult` and inserts `"typeHierarchyProvider": true` into the
|
||||
capabilities object — the same JSON a field would have produced — because a
|
||||
capability a client cannot see is a feature that is never requested.
|
||||
`experimental` was not used: different key, and no client reads it for this.
|
||||
- **Classes, not modules.** The lead's scope decision, argued in the feature
|
||||
README: an instantiation is a containment edge and `extends` is an
|
||||
inheritance edge, so the module hierarchy stays on `callHierarchy` where it
|
||||
shipped, and this request serves one node kind well.
|
||||
- **`supertypes` is `definition_of` at a computed offset**, not a new lookup.
|
||||
`extends Base` is already a reference, and the overlay-promotion round already
|
||||
made a bare cross-file class name reachable through it, so the only new idea
|
||||
is *which* offset to ask about: the last byte of the extends name span, which
|
||||
is the tail of `pkg::base` and the whole of a bare `base`. That gets in-file
|
||||
bases, cross-file bases, package-qualified bases and parameterized bases from
|
||||
one line, and can never disagree with F12 on the same token.
|
||||
- **`subtypes` is `callers_of_each`'s census in another key**: one
|
||||
`sources()` pass, a substring prefilter before any parse, a deterministic
|
||||
sort. 55 ms over the 860-file corpus, 53 ms of it file I/O — the same shape
|
||||
`incomingCalls` measured, and the same backlog item (an edge table in
|
||||
`WorkspaceIndex`, now filed for inheritance edges beside the instantiation
|
||||
ones).
|
||||
- **What the class model lacked:** interface classes. `vlog_parser` rejects
|
||||
`interface class` outright, so `implements` can never resolve and no item can
|
||||
carry `SymbolKind::Interface`; both facts are pinned by tests named to force a
|
||||
future parser round past them. Full details, assumptions, cost table and the
|
||||
ambiguity argument: `docs/features/type-hierarchy/README.md`.
|
||||
|
||||
### 2026-08-25 — dev agent (M14 macro-expansion, 0.5.0)
|
||||
|
||||
- **No new capability, one new module, one card grew a section.**
|
||||
@@ -770,7 +947,10 @@ character-past-end-of-line, line-past-end-of-file, and both-past-end → all
|
||||
six combinations return graceful `null`/`[]`, no protocol error, no crash;
|
||||
server process survived and later exited cleanly (code 0). `textDocumentSync`
|
||||
confirmed `1` (Full) in the capabilities JSON, so the "stale/overlapping
|
||||
`didChange`" scenario is moot as documented.
|
||||
`didChange`" scenario is moot as documented. *(That last sentence records the
|
||||
state at the time of this QA pass only: sync became incremental on
|
||||
2026-08-26, and the clamping that keeps a desynced `didChange` harmless is
|
||||
specified and tested in `docs/features/incremental-sync/README.md`.)*
|
||||
|
||||
**Robustness.** All PASS. Malformed `Content-Length: notanumber` header, and
|
||||
a well-framed-but-garbage JSON body → in both cases the process does **not**
|
||||
|
||||
@@ -0,0 +1,635 @@
|
||||
# on-type formatting
|
||||
|
||||
## Goal
|
||||
|
||||
Serve `textDocument/onTypeFormatting` — the request a client sends as the user
|
||||
types, on the characters the server nominated. For a formatter-first server it
|
||||
is a conspicuous absence: an editor that indents Verilog by copying the line
|
||||
above is an editor that fights the formatter all day. But it is also the one
|
||||
formatting entry that runs on code that is, by definition, half-written, and it
|
||||
runs on a keystroke, so the design is deliberately narrow. **Two trigger
|
||||
characters.** A `;` means a statement just ended, so the buffer is often whole
|
||||
again — that one goes straight through `format::range_formatting`, the same
|
||||
verified, all-or-nothing engine `textDocument/rangeFormatting` runs, over the
|
||||
`;`'s own line, and adds no formatting logic of its own. A `\n` means *nothing*
|
||||
is finished, so nothing is formatted: all it answers is the new line's
|
||||
indentation, computed from block nesting over the token stream, and the edit it
|
||||
returns can by construction touch nothing but the whitespace at the head of that
|
||||
one line. A keystroke this cannot answer confidently answers nothing at all — no
|
||||
edit, and no message.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The client has already opted in, so the capability is unconditional.** No
|
||||
`lucisv.*` setting gates this, unlike `willSaveWaitUntil`'s
|
||||
`lucisv.formatOnSave`. On-type formatting fires only where the *client's* own
|
||||
switch is on — `editor.formatOnType` in VS Code, off by default; a `nil`
|
||||
`on_type` handler in Neovim's built-in client unless the user wires one — so a
|
||||
request arriving here is already a request the user asked for. Gating it a
|
||||
second time server-side would mean a user who turned it on in their editor and
|
||||
got nothing.
|
||||
- **`}` and `)` are not triggers, on purpose.** SystemVerilog closes its blocks
|
||||
with the *word* `end`, and the only way to trigger on a word is to trigger on
|
||||
its last letter — which means running this on half of every identifier. `)`
|
||||
closes a port list mid-header as often as it closes anything, and there is
|
||||
nothing finished to lay out there. Two characters is the whole set, and the
|
||||
capability test pins it.
|
||||
- **Silence on a refusal, and this is the deliberate opposite of every other
|
||||
formatting entry.** `textDocument/formatting` shows an ERROR when the engine
|
||||
declines, and `willSaveWaitUntil` shows one per save — both correct, because
|
||||
both are moments the user explicitly asked lucisv for something and deserves to
|
||||
know they did not get it. A keystroke is not such a moment. Mid-edit code the
|
||||
strict parser refuses is the *normal* state of a buffer being typed into, and a
|
||||
popup the user cannot type past, arriving on every semicolon, is a modal
|
||||
dialog, not a diagnostic.
|
||||
- **No broken-`lucisv.toml` warning either — and this is a finding, not an
|
||||
omission.** The lead's design asked for `warn_about_config` here on the
|
||||
grounds that its dedup is per buffer state. It is (QA proved that on the
|
||||
will-save round: `config_warnings` is cleared by `set_document`) — and that is
|
||||
exactly why it cannot be used here. An on-type request follows, by definition,
|
||||
the `didChange` the user's own keystroke produced, so the dedup has just been
|
||||
re-armed every single time. Calling `warn_about_config` from this handler would
|
||||
produce **one popup per character typed**. The user is told about a broken
|
||||
config on their next explicit format or save, which are the two moments they
|
||||
asked. Pinned by `a_broken_config_is_never_reported_from_a_keystroke`, which
|
||||
drives three keystrokes silently and then one `textDocument/formatting` that
|
||||
speaks once.
|
||||
- **`FormattingOptions` are carried, so the full ladder runs.** Unlike
|
||||
`willSaveWaitUntil`, this request has an `options` field, so
|
||||
`format::settings_for` is called exactly as `textDocument/formatting` calls it:
|
||||
`lucisv.toml` > pushed `lucisv.*` > the editor's `tabSize` > the built-in
|
||||
default. No `settings_without_editor_options` here.
|
||||
- **The indent is always spaces.** The printer writes spaces
|
||||
(`Printer::newline`), and `config_from` already refuses a client's
|
||||
`insertSpaces: false` before a width ever reaches this code. So "tabs vs
|
||||
spaces per the settings ladder" resolves to: hard tabs fall through to the
|
||||
built-in width, in spaces — which is what a whole-file format would have
|
||||
written on the same line.
|
||||
- **The blank line the user opened really does get whitespace written onto it.**
|
||||
That is what on-type indentation *is* — the cursor is sitting there — and it is
|
||||
what every editor's own auto-indent already does. A later whole-file format
|
||||
strips it again.
|
||||
- **`\n` after `end` answers the outer level, and the user typing `else` next
|
||||
will be one level out.** The formatter writes `end else begin` on one line, so
|
||||
a user who puts them on separate lines is already writing something a format
|
||||
will rejoin; the nudge is whitespace-only either way.
|
||||
- **A `;` reply is a whole-document edit.** That is `range_formatting`'s reply
|
||||
shape, unchanged — the engine's contract is all-or-nothing over the file, and
|
||||
what makes it a *range* format is which constructs it laid out, not which bytes
|
||||
it was allowed to replace. It arrives on a keystroke, which is more bytes on the
|
||||
wire than an indent edit; it is the same number of bytes `rangeFormatting`
|
||||
already sends for a cursor on that line.
|
||||
|
||||
## The `\n` indent model
|
||||
|
||||
### What it is allowed to do
|
||||
|
||||
A pure function, `level_at(doc, content) -> Option<usize>`, over `doc.tokens`.
|
||||
Its answer becomes an edit whose range runs **from column zero of one line to
|
||||
that line's first non-whitespace character**, with `" ".repeat(level * width)`
|
||||
as its text. Nothing else in the buffer is nameable from `indent_edit`, so no
|
||||
future widening of the model below can make this path move code. Asserted
|
||||
structurally by `an_indent_edit_can_only_ever_replace_leading_whitespace`, which
|
||||
walks every line of a file with a bit of everything in it and checks the range's
|
||||
end never passes the line's own indent and the text is spaces.
|
||||
|
||||
`None` — no edit — is the answer wherever answering would mean guessing. It is
|
||||
also the answer when the line is already right, and the caller cannot tell the
|
||||
two apart, which is the point: idempotency is then structural. Applying the edit
|
||||
and asking again at the same position returns nothing
|
||||
(`applying_the_edit_leaves_the_next_ask_nothing_to_do`).
|
||||
|
||||
### The model
|
||||
|
||||
One forward scan over the token stream up to the line's first non-whitespace
|
||||
byte, carrying a stack of two kinds of frame:
|
||||
|
||||
| frame | pushed by | popped by |
|
||||
|---|---|---|
|
||||
| `Block` | a scope-opening keyword, as `pairs::opens_scope_at` judges it | its own closing keyword |
|
||||
| `Hanging` | a header whose one-statement body follows it — `if (c)`, `for (…)`, `else`, `always_ff @(…)`, a bare `@(…)`/`#5`, a `case` item's `:` | the `;` that ends that statement, or the `end` of the block that turned out to be it |
|
||||
|
||||
The level is the stack depth. A line that *starts* with a closing keyword steps
|
||||
back out to that keyword's opener, which is what makes typing `end` on a fresh
|
||||
line land right.
|
||||
|
||||
Four rules earned their place against the real formatter rather than by
|
||||
reasoning, and each is pinned by a test:
|
||||
|
||||
- **Only `begin` is cuddled.** `vlog_formatter`'s `stmt_as_body` joins a
|
||||
`begin`…`end` onto the header before it and nothing else — *not* `fork`, the
|
||||
other block delimiter. So `if (c) begin` puts its contents one level in, while
|
||||
`if (c) fork` puts the `fork` one level in and its contents two.
|
||||
`only_begin_is_cuddled_onto_the_header_before_it` asserts this against the
|
||||
engine, so the day that changes, this model is told.
|
||||
- **`else if` is one rung.** The `else` pushes nothing when an `if` follows it;
|
||||
the `if` pushes the level the branch's body gets. Pushing at both would indent
|
||||
the chain twice.
|
||||
- **A dangling `else` ends the chain it was already in.** SV's `else` binds to
|
||||
the innermost `if` that has not got one yet, so an `else` written *after* a
|
||||
branch that was itself an `else` belongs to something further out — and the
|
||||
levels around it come off. `Frame::Hanging::from_else` carries that one bit,
|
||||
and `Frame::Block::from_else` carries it across the `begin` that replaced the
|
||||
hanging. Found by the corpus test on `picorv32/testbench_wb.v:232`.
|
||||
- **A case item's `:` is a level.** `A:` on its own line puts its statement one
|
||||
further in, exactly as an `if` does. It is recognised by there being nothing
|
||||
between the `:` and the `case` scope itself, which is also what keeps a `?:`
|
||||
inside that statement from being mistaken for one.
|
||||
|
||||
### What it declines, and why
|
||||
|
||||
Roughly a third of the lines of the checked-in corpus. Each is a place where
|
||||
what the formatter writes is not a function of nesting:
|
||||
|
||||
| declined | why |
|
||||
|---|---|
|
||||
| any open `(`, `[`, `{` | a wrapped port list or expression is laid out by width |
|
||||
| the middle of a statement | same: `assign a =\n b + c;` is a printer decision |
|
||||
| the interior of a block comment | the formatter re-indents a comment as a whole, by its opening column |
|
||||
| a line opening inside a token | a `` `define `` continued with `\`, a string carried across the break |
|
||||
| a line starting with punctuation | `module top\n import p::*;\n#(` — the header continues at column zero |
|
||||
| inside `covergroup`/`property`/`sequence` | `ItemKind::Verbatim`: the user's own bytes are what a whole-file run emits |
|
||||
| inside an `assert`/`assume`/`cover`/`restrict`/`expect` statement | verbatim too, and it closes with no keyword — `assert (c) p; else begin … end` runs past the `;`, so it is a span the scan is silent over rather than a level on the stack |
|
||||
| a buffer that does not lex | there is no token stream to read |
|
||||
| `always_comb` followed on the next line by `begin` | the formatter always joins those two, so a file where they are apart is not one this can reason about |
|
||||
| a `` `ifdef `` standing where a statement body belongs | directive splitting decides that shape, not this |
|
||||
|
||||
And the honest gaps — things the model *could* grow to know and does not:
|
||||
|
||||
- `wait`, `do` and the assertion keywords are not headers, because they spell
|
||||
headers that are not always headers (`wait fork;`, `do begin … end while (c);`).
|
||||
- A statement beginning with `#`, `@` or `->` on its own line is declined by the
|
||||
punctuation rule even where the level would be right.
|
||||
- A macro item's *arguments* are one token to the lexer, so a macro call wrapped
|
||||
across lines declines (correctly, but by the straddle rule rather than by
|
||||
knowing anything about it).
|
||||
|
||||
### The anchor
|
||||
|
||||
`the_model_never_disagrees_with_the_formatter_on_formatted_corpus_code` is what
|
||||
keeps two pieces of indent logic — the printer's, driven by the AST and by line
|
||||
width, and this one, driven by the token stream — from drifting. It formats every
|
||||
file of the checked-in corpus with the real engine and then asks the model, at
|
||||
every line of the output, what it would do there. **It may decline; it may not
|
||||
disagree.** As shipped: 77 528 lines answered, 36 647 declined, **0
|
||||
disagreements**. The test also asserts a coverage floor (>50 000 lines, >60% of
|
||||
them answered), because a model that declined everywhere would pass the first
|
||||
assertion and be worth nothing.
|
||||
|
||||
Every decline in the table above except the last two was *found* by that test,
|
||||
not anticipated.
|
||||
|
||||
## The `;` path
|
||||
|
||||
`format::range_formatting(doc, config, <the `;`'s own line>)`. That is the whole
|
||||
of it: the verified engine, the all-or-nothing contract, `Ok(None)` → `[]`,
|
||||
`Err` → `[]` and silence.
|
||||
|
||||
Two gates in front of it, both cheap:
|
||||
|
||||
1. **The trigger character has to be where the client said it is.** The token
|
||||
ending at the request's offset must be a `;` the lexer saw. A `;` inside a
|
||||
string or a comment ends no statement.
|
||||
2. **The engine is the authority on everything else.** `format_range` strict-
|
||||
parses the whole buffer and refuses on any error, then verifies its own output
|
||||
for equivalence and convergence.
|
||||
|
||||
**Deviation from the lead's design, logged.** The design said to find the
|
||||
statement covering the `;` in the AST and use *its* line span, answering empty
|
||||
when nothing covers it. The range shipped is the `;`'s **own line** instead, for
|
||||
two reasons. First, it is not narrower: `format_range` selects by *unit*, so any
|
||||
line of a statement selects the whole statement — the two requests have the same
|
||||
answer wherever both are defined. Second, the enclosing-node version is wrong in
|
||||
a case that is easy to hit: the `;` that closes `module m (\n input a\n);`
|
||||
belongs to no statement at all, and the innermost node covering it is the
|
||||
*module*, whose line span is the whole file's worth of body. Naming that on a
|
||||
keystroke would ask for a whole-module reformat.
|
||||
`a_semicolon_closing_a_module_header_lays_out_the_header_and_not_the_body`
|
||||
pins the shipped behavior. The AST gate itself was dropped rather than
|
||||
reimplemented because it can only decline what the verified engine already
|
||||
accepts — it would be a second, weaker source of truth about "is this a
|
||||
statement", which is the drift CLAUDE.md warns about.
|
||||
|
||||
## Safety
|
||||
|
||||
`verify.rs` was not touched: no normalization was added, broadened or weakened,
|
||||
so CLAUDE.md hard invariant #4 does not apply to this round.
|
||||
|
||||
- **The `;` path** is `format::range_formatting`, unchanged — the same call
|
||||
`Server::range_formatting` makes, so the same `format_range` →
|
||||
`verify_equivalence` + `verify_convergence` chain. There is no way to reach the
|
||||
printer from this feature except through it.
|
||||
- **The `\n` path never reaches the formatter at all.** It is new logic outside
|
||||
the verified engine, which is why its guarantee is structural rather than
|
||||
verified: `indent_edit` can only construct a range ending at the line's first
|
||||
non-whitespace character, and can only fill it with spaces. A bug in
|
||||
`level_at` is a wrong *indent*, never a moved byte. The corpus anchor is what
|
||||
makes the indent right; the structure is what makes a wrong one harmless.
|
||||
- **Idempotency** holds by construction (the edit is computed from a comparison
|
||||
against what is already there) and is asserted through the real path.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `format::range_formatting`** unchanged, and `format::settings_for`
|
||||
unchanged — the same two calls `Server::range_formatting` makes, in the same
|
||||
order, so the two paths cannot drift. No new function was added to `format.rs`.
|
||||
- **Consumes `pairs.rs`'s keyword tables**, which needed three items made
|
||||
`pub(crate)`: `closer_keyword`, plus two new one-line accessors,
|
||||
`opens_scope_at(tokens, i)` (`opener_rule` + `opens_a_scope` asked as one
|
||||
question) and `starts_a_prototype(text)`. Nothing in `pairs.rs`'s behavior
|
||||
moved and no test there changed. **This is the point**: `RULES` and
|
||||
`opens_a_scope`'s exception list must have one reader's answer, or the matcher
|
||||
and the indent model would disagree about what a `function` inside an `extern`
|
||||
declaration is, and every line below it.
|
||||
- **Does *not* consume `pairs::analyze`.** The matched-pair list would give block
|
||||
nesting for free, but not the `Hanging` levels, and the two would have to be
|
||||
reconciled anyway; one scan that produces both is simpler than two that must
|
||||
agree.
|
||||
- **Does not consume `Server::edits` or `Server::warn_about_config`.** Both are
|
||||
about telling the user something, and this path deliberately tells them
|
||||
nothing — see Assumptions. The handler is five lines and returns
|
||||
`to_value(edits)` directly.
|
||||
- **Changes what the client is told at `initialize`:**
|
||||
`document_on_type_formatting_provider` moves from `None` to
|
||||
`DocumentOnTypeFormattingOptions { firstTriggerCharacter: "\n",
|
||||
moreTriggerCharacter: [";"] }`. Nothing else in `capabilities()` moves.
|
||||
- **No editor packaging change.** `vscode-languageclient` registers the on-type
|
||||
feature from the advertised capability on its own, and gates it on the user's
|
||||
`editor.formatOnType`; there is no `lucisv.*` setting to declare. Neovim's
|
||||
built-in client is the same story with `vim.lsp.formatexpr`.
|
||||
- **No other crate is touched, and no new dependency.**
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Advertise `documentOnTypeFormattingProvider` with `"\n"` + `[";"]`.
|
||||
- [x] `OnTypeFormatting` dispatch arm + `Server::on_type_formatting`.
|
||||
- [x] `on_type.rs`: the two paths, and the nesting model.
|
||||
- [x] `pairs.rs`: `closer_keyword`, `opens_scope_at`, `starts_a_prototype` made
|
||||
`pub(crate)`; no behavior moved.
|
||||
- [x] The structural guarantee (range ends at the first non-whitespace byte;
|
||||
text is spaces), asserted over every line of a mixed file.
|
||||
- [x] Idempotency through the real path.
|
||||
- [x] The corpus agreement anchor, with a coverage floor so it cannot pass
|
||||
vacuously.
|
||||
- [x] `only_begin_is_cuddled_onto_the_header_before_it` — the engine assumption
|
||||
the model rests on, asserted against the engine.
|
||||
- [x] Unit tests: `\n` after `begin`/`module`/`end`/case item/one-statement
|
||||
body; open brackets, wrapped expressions, comment interiors, punctuation
|
||||
lines, verbatim scopes, assertions, macro items, unlexable buffers,
|
||||
straddling tokens; `;` completing a statement, matching
|
||||
`range_formatting` byte for byte; `;` in garbage, in a string, in a
|
||||
comment, and where the client said wrongly; tabs vs spaces per the
|
||||
ladder; UTF-16 positions; the empty buffer; unknown triggers.
|
||||
- [x] Server-level: dispatch, settings ladder, no `showMessage` on refusal, no
|
||||
config warning ever, unopened buffer, unknown trigger.
|
||||
- [x] e2e: capability on the wire, both triggers round-tripped over the real
|
||||
binary with a `didChange` between them, and no `showMessage`.
|
||||
- [x] `docs/features/lucisv-server/README.md` capability table.
|
||||
- [x] TODO.md §9c item checked off.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-26 — dev.** Implemented in one round. One deviation from the design
|
||||
(the `;` range) and one finding against it (the config warning), both argued
|
||||
above; everything else as planned.
|
||||
|
||||
- **`main.rs`**: one capability, plus
|
||||
`on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else`.
|
||||
The trigger set is the feature, so it is pinned rather than left to the
|
||||
`is_some()` line in `every_advertised_capability_is_implemented`.
|
||||
- **`server.rs`**: one dispatch arm and one handler. The handler does *not* call
|
||||
`edits()` or `warn_about_config()` — both would speak, and this path does not.
|
||||
That is the single largest design decision in the round and it is argued in
|
||||
Assumptions; the config-warning half is a correction to the lead's design that
|
||||
I would flag for review even though I am confident in it.
|
||||
- **`on_type.rs`**, 630 lines of code and 480 of tests. Structure is: the two
|
||||
entry points first (they are what a reader wants), the model second. The
|
||||
`Scan` struct owns the whole state machine, so the invariant "the stack is
|
||||
only ever pushed from `keyword`/`symbol`/`in_header`" is readable in one
|
||||
screen.
|
||||
- **The model was built against the corpus, not against my reading of
|
||||
`format.rs`.** I wrote the first version from the token stream, then ran the
|
||||
agreement test and fixed what it found, in this order: block-comment interiors
|
||||
(1), lines starting with punctuation (2), assertion statements (3), macro items
|
||||
with no `;` (4), bare timing controls (5), `fork` not being cuddled (6), case
|
||||
items carrying a level (7), the `;`/`end` before an `else` (8), the dangling
|
||||
`else` ending a chain (9), and `` `ifdef `` as a statement body (10). Nine of
|
||||
those ten I would not have predicted. Two of them — (6) and (9) — were plain
|
||||
bugs that would have shipped as wrong indents on common code, and (6) in
|
||||
particular came from an assumption I had reasoned my way into (`begin` and
|
||||
`fork` are "the same kind of thing", which is true for the rainbow and false
|
||||
for `stmt_as_body`). The anchor earned its keep before it was ever a
|
||||
regression test.
|
||||
- **One real bug the anchor caught mid-round**: the first `end_branch` used
|
||||
`stack.pop()` inside an `if let`, which pops unconditionally and then declines
|
||||
to match — so a `;` before an `else` could pop a *`Block`* frame. The corpus
|
||||
test went from 0 disagreements to 28 in one file and named the shape.
|
||||
- `is_rainbow` in `pairs.rs` was briefly renamed to `is_block_delimiter` while I
|
||||
believed the rainbow's list and the cuddling rule were the same question. They
|
||||
are not (finding 6), so the rename was reverted and `on_type.rs` asks its own
|
||||
one-line `is_begin` with the reason attached. `pairs.rs`'s diff is now three
|
||||
visibility changes and two new accessors — nothing else.
|
||||
- **Tests: 34 unit (`on_type.rs`) + 1 capability (`main.rs`) + 7 server-level
|
||||
(`server.rs`) + 1 e2e = 43 new.** The corpus agreement test runs in ~30 s,
|
||||
which is most of the `lucisv_server` unit binary's runtime; it is worth it, and
|
||||
it skips cleanly when `corpus/` is not checked out like every other corpus
|
||||
test.
|
||||
- Nothing outside `crates/lucisv_server` changed in code. The two documentation
|
||||
files touched outside this feature dir (`TODO.md`,
|
||||
`docs/features/lucisv-server/README.md`) are additions in the house style; no
|
||||
QA log or Review section anywhere was edited.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-26 — QA.** Re-ran every gate, attacked both paths along the lines
|
||||
the lead asked for, added six tests where coverage was thin, found no
|
||||
correctness bug. Verdict: **committable as-is.**
|
||||
|
||||
### Gates
|
||||
|
||||
- `cargo fmt --all -- --check`: clean.
|
||||
- `cargo clippy --all-targets`: clean, no warnings.
|
||||
- `cargo test --workspace`: green, three full runs (before my changes, after,
|
||||
and a final rebuild). Counts stable across runs:
|
||||
`lucisv_server`'s unit binary went from 865→871 passed (+6, my additions),
|
||||
0 failed, 4 ignored, in every run.
|
||||
- `cargo test -p vlog_formatter`: 180 passed (31+1+4+6+2+22+114), matching the
|
||||
dev's count exactly. This crate has zero diff in this round — confirmed via
|
||||
`git diff --stat`, which does not list it.
|
||||
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`.
|
||||
- **Corpus anchor runtime**: isolated with
|
||||
`cargo test -p lucisv_server --bin lucisv-server on_type::tests::the_model_never_disagrees_with_the_formatter_on_formatted_corpus_code`,
|
||||
it is **31.2s** on its own, while the other 868 tests in that same binary
|
||||
together take well under 1s (32.07s total for 869 tests). It dominates the
|
||||
binary exactly as the dev said. Ran 3 times total (once inside each full
|
||||
workspace run, once isolated): identical every time — 77 528 answered,
|
||||
36 647 declined, 0 disagreements.
|
||||
- On "should it be `#[ignore]`-gated like other corpus tests": I checked
|
||||
the repo's actual convention. `vlog_semantic/tests/corpus.rs` and
|
||||
`vlog_refactor/tests/corpus.rs` are plain `#[test]` (not ignored) but
|
||||
live in their own `tests/*.rs` integration binary, separate from that
|
||||
crate's `--lib` unit tests, and cost well under 4s each. The one
|
||||
precedent for an expensive test embedded in *this* crate's own module
|
||||
tree is `includes.rs`'s
|
||||
`perf::building_the_graph_over_the_whole_corpus_is_milliseconds`, which
|
||||
*is* `#[ignore]`d — but that one is a benchmark assertion, not a
|
||||
correctness gate.
|
||||
- `lucisv_server` is a `[[bin]]`-only crate (`crates/lucisv_server/Cargo.toml`
|
||||
has no `[lib]` target), and `level_at`/`Scan`/`Frame` are private to
|
||||
`on_type.rs`. There is structurally no way to move this test into a
|
||||
`tests/corpus.rs` the way `vlog_semantic`/`vlog_refactor` do it — an
|
||||
integration test in `tests/` can only reach the binary's public surface
|
||||
(e2e-style, over stdio), not a private module's functions. So the
|
||||
placement is forced by the crate's shape, not a shortcut.
|
||||
- Given that, and given this is the regression guard the whole `\n` design
|
||||
leans on (the doc's own words: "the anchor earned its keep before it was
|
||||
ever a regression test"), I'd lean toward leaving it un-ignored — an
|
||||
`#[ignore]`d correctness gate is a gate nobody runs by default, which is
|
||||
a worse trade than 31s. But the cost is real and will be paid on every
|
||||
`cargo test -p lucisv_server` from now on; flagging for the lead's call
|
||||
rather than deciding it myself.
|
||||
|
||||
### Attack surfaces
|
||||
|
||||
1. **Structural confinement of the `\n` edit — verified clean, one gap
|
||||
filled.** Traced `indent_edit` (`on_type.rs:98-122`) by hand:
|
||||
`content` is always `line.start + (bytes matched by
|
||||
text.trim_start_matches([' ', '\t']))`, and the returned range is always
|
||||
`{start: (line, 0), end: position(content)}` — there is no path from
|
||||
`level_at`'s return value into the range, only into `new_text`, which is
|
||||
itself always `" ".repeat(n)`. A regression in the nesting model literally
|
||||
cannot compile into a wider range; the property is enforced by the type
|
||||
signature of `level_at` (`Option<usize>`, not `Option<Range>`), not just by
|
||||
the existing `an_indent_edit_can_only_ever_replace_leading_whitespace`
|
||||
test.
|
||||
- **CRLF**: `vlog_parser::LineIndex` keeps `\r` as an ordinary trailing byte
|
||||
of the line it ends (confirmed against `line_index.rs`'s own
|
||||
`crlf_puts_the_carriage_return_in_the_line` test) — `indent_edit`'s
|
||||
`trim_start_matches([' ', '\t'])` doesn't recognize `\r` either, so a
|
||||
blank CRLF line's "content" offset lands exactly *on* the `\r`, giving a
|
||||
zero-width insertion immediately before it. Traced by hand and confirmed
|
||||
empirically: added
|
||||
`a_crlf_line_ending_is_never_touched_by_the_edit` (`on_type.rs:932`, two
|
||||
cases: bare `\r` and `\t\r`) — **there was no CRLF coverage anywhere in
|
||||
the file before this**, despite this being exactly the shape the round's
|
||||
own structural-guarantee argument rests on being airtight for. Passes.
|
||||
- **Form feed / vertical tab in the indent**: traced rather than tested —
|
||||
the raw lexer's `skip_whitespace` (`vlog_parser/src/lexer.rs:127`) only
|
||||
skips `' '`/`'\t'`/`'\r'`/`'\n'`; a bare FF/VT anywhere in code context
|
||||
hits the `unexpected character` error path (`lexer.rs:413`), which fails
|
||||
`tokenize()` for the *whole* document (propagated by the `?` in
|
||||
`tokenize`, `lexer.rs:735`), which empties `doc.tokens`
|
||||
(`state.rs:59-65`), which makes `level_at`'s first guard
|
||||
(`on_type.rs:225`) return `None` for every line of that buffer. So this
|
||||
shape degrades to the already-tested "buffer that does not lex" case
|
||||
rather than a new one — conservative, not wrong. Did not add a
|
||||
dedicated test since it collapses to an existing one; noting the chain
|
||||
here in case a future change to the lexer's whitespace set makes FF/VT
|
||||
legal (it would then need the same treatment CRLF just got).
|
||||
- **Position desync (trigger claims `\n`, cursor mid-line)**: already
|
||||
covered by `a_line_the_cursor_is_past_is_not_re_indented` and
|
||||
`the_first_line_of_a_buffer_is_never_a_new_line`. Note in passing: the
|
||||
`line.start == 0` half of the guard at `on_type.rs:103` is dead in
|
||||
practice — for any `line > 0`, `LineIndex`'s own construction guarantees
|
||||
the preceding byte is `\n` (it only ever records a line start right
|
||||
after one), so the second half of that `||` can never itself be false
|
||||
without the first half also being true for `line == 0`, and is only
|
||||
reachable at all when `line == 0`. Harmless (redundant, not wrong), not
|
||||
worth a finding beyond noting it.
|
||||
- **Mixed tab/space indent**: added
|
||||
`a_mixed_tab_and_space_prefix_is_measured_in_bytes_not_visual_columns`
|
||||
(`on_type.rs:961`) — nothing before this exercised more than one
|
||||
whitespace kind in a prefix at once. Passes; byte and UTF-16 counts
|
||||
agree because tab and space are both one of each.
|
||||
|
||||
2. **The `;` gate — verified clean, two gaps filled.**
|
||||
- `;` inside a string/comment: already tested
|
||||
(`a_semicolon_the_lexer_never_saw_ends_no_statement`).
|
||||
- `;` as the last character of a macro body: **untested before this
|
||||
round.** Traced `vlog_parser/src/lexer.rs` — a `` `define `` (with or
|
||||
without `\`-continuations) is lexed as one `Directive` token end to end
|
||||
(confirmed against the lexer's own
|
||||
`toks[0].text == "`define A \\\n x \\\n y"` tests around
|
||||
`lexer.rs:871-882`), so a `;` inside its body is never a standalone
|
||||
`Symbol(";")` token — `statement_edit`'s `.find(|t| t.span.end ==
|
||||
offset)` either finds nothing or finds the `Directive` itself, and
|
||||
`typed.is_sym(SEMICOLON)` is false either way. Added
|
||||
`a_semicolon_ending_a_macro_definitions_body_ends_no_statement`
|
||||
(`on_type.rs:1168`). Passes.
|
||||
- `;` at EOF with no trailing newline: **untested before this round.**
|
||||
Added `a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`
|
||||
(`on_type.rs:1130`). Passes, and confirms a detail worth recording: the
|
||||
reply's `new_text` gets the file's final `\n` restored (the engine's own
|
||||
canonicalization, not something this path invented) — consistent with
|
||||
`range_formatting`'s "whole-document edit" contract, not a new behavior.
|
||||
- Off-by-one (client says wrong offset): already tested
|
||||
(`a_semicolon_that_is_not_where_the_client_said_answers_nothing`).
|
||||
- Byte-identity with the real handler: confirmed
|
||||
`a_semicolon_answers_exactly_what_range_formatting_of_that_line_answers`
|
||||
calls `format::range_formatting` directly — the identical function
|
||||
`Server::range_formatting` calls (`server.rs:627`), not a
|
||||
reimplementation. Both call sites pass `doc`, `settings.config`/`config`,
|
||||
and a `Range` straight through with no branching in between.
|
||||
|
||||
3. **The corpus anchor's honesty — verified clean.** Reads real corpus files,
|
||||
runs the real `vlog_formatter::format_source` over each
|
||||
(`on_type.rs:986`), and asks the *private* `level_at` at every formatted
|
||||
line — not a reimplementation, not a fixture. Coverage floor is a real
|
||||
minimum: `assert!(answered > 50_000, ...)` and `assert!(share > 0.6, ...)`
|
||||
(`on_type.rs:1021-1023`) both fire on the actual counts, and I confirmed by
|
||||
inspection that `declined` is incremented independently of `answered` (a
|
||||
model that always returned `None` would drive `answered` to 0 and fail the
|
||||
floor, not pass vacuously). Skips loudly and returns early
|
||||
(`eprintln!("corpus/ not checked out...")`) matching the exact convention
|
||||
in `vlog_refactor/tests/corpus.rs` and `vlog_semantic/tests/corpus.rs`. Ran
|
||||
3 times total across this session (2 full-workspace runs + 1 isolated):
|
||||
identical counts every time (77 528 / 36 647 / 0).
|
||||
|
||||
4. **Idempotency through the real path — verified clean, with a nuance
|
||||
worth recording.** `applying_the_edit_leaves_the_next_ask_nothing_to_do`
|
||||
applies the edit with string arithmetic, but the *state update* it feeds
|
||||
back through is `Workspace::set_document` via the test's `with()` helper —
|
||||
and `Server::set_document` (`server.rs:1207-1209`, the function
|
||||
`did_change` calls at `server.rs:943`/`950`) is a one-line forward to that
|
||||
exact same `Workspace::set_document`. So the re-lex/re-analyze pipeline
|
||||
this test exercises after "applying" the edit is byte-for-byte what a real
|
||||
`didChange` triggers — the string arithmetic only stands in for what an
|
||||
editor's own buffer would do, which nothing server-side can avoid in a
|
||||
unit test. What is *not* covered end-to-end: the e2e test
|
||||
(`typing_a_newline_and_a_semicolon_round_trips_over_the_real_binary`)
|
||||
never applies a returned edit and re-asks at the same position over the
|
||||
real binary — its two `on_type` calls are against two independently
|
||||
constructed buffer states, not "type, apply, retype." Low severity (the
|
||||
unit-level test already exercises the real state machinery faithfully),
|
||||
not blocking, but noting it as a gap for a future e2e round rather than
|
||||
fixing it myself — it would mean growing the e2e test with an "apply the
|
||||
edit into the next full_change" helper, which is more than a one-line
|
||||
fix. `;` idempotency is adequately shown by
|
||||
`an_already_laid_out_statement_gets_no_edit` (same buffer content as after
|
||||
applying the fix, semicolon retyped, no edit).
|
||||
|
||||
5. **No-popup design — verified clean.**
|
||||
`a_broken_config_is_never_reported_from_a_keystroke` drives three `\n`
|
||||
keystrokes through a buffer with a broken `lucisv.toml` and asserts
|
||||
`session.shown()` stays empty each time, then a `textDocument/formatting`
|
||||
on the same buffer and asserts exactly one `unknown key `bogus`` message —
|
||||
both directions, in one test, as asked.
|
||||
`a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup`
|
||||
does the same contrast for a plain refusal (not a config problem). `git
|
||||
diff` on `will_save_wait_until`'s body: empty — the only lines the diff
|
||||
touches in `server.rs` near it are import-list reflows (alphabetical
|
||||
insertion of `OnTypeFormatting`/`DocumentOnTypeFormattingParams` pushed
|
||||
other names to new lines) and the new `on_type_formatting` method + its
|
||||
dispatch arm + its own tests. Confirmed by reading the full `server.rs`
|
||||
diff, not just grepping for the function name.
|
||||
|
||||
6. **`pairs.rs` accessors — verified clean.** Full diff is three visibility
|
||||
changes to one existing private fn (`closer_keyword`, private → `pub(crate)`,
|
||||
no line of its body changed) plus two new one-line-bodied accessors
|
||||
(`opens_scope_at`, `starts_a_prototype`) that each call existing private
|
||||
functions (`opener_rule`, `opens_a_scope`, and the `PROTOTYPE_STARTERS`
|
||||
table) with no new logic. All 65 `pairs::tests::*` tests pass, and the
|
||||
diff has zero edits to any existing line — additions only, confirmed by
|
||||
reading the full diff rather than just the stat.
|
||||
|
||||
7. **Settings ladder — verified clean.** `on_type.rs`'s
|
||||
`the_indent_width_is_the_one_the_settings_resolved_to` and
|
||||
`a_tab_indented_line_is_replaced_with_the_spaces_the_formatter_writes`
|
||||
cover the `\n` side; `server.rs`'s
|
||||
`a_keystroke_climbs_the_same_settings_ladder_a_manual_format_does` drives
|
||||
the full ladder (editor `tabSize` → pushed `lucisv.indent` → hard-tab
|
||||
rejection → built-in default) through the real dispatch, in the same
|
||||
order `format::settings_for`'s own doc comment states and the same order
|
||||
`willSaveWaitUntil`'s round tested it in.
|
||||
|
||||
8. **CLAUDE.md compliance — verified clean.** No `unwrap()`/`expect()`/
|
||||
`panic!` outside `#[cfg(test)]` in any changed file (checked
|
||||
`on_type.rs`, the diff hunks of `server.rs`/`main.rs`/`pairs.rs`
|
||||
individually). Every new public/`pub(crate)` item carries a doc comment.
|
||||
`docs/features/on-type-formatting/README.md`'s eight required sections
|
||||
(`Goal`, `Assumptions`, `Handshakes`, `Status / TODO`, `Work log`, `QA
|
||||
log`, `Review`) each appear exactly once (`grep -n '^## '`). `TODO.md`'s
|
||||
§9c item text is intact verbatim, checkbox flipped, `→ delivered...` note
|
||||
appended below it — matches the house style already used elsewhere in
|
||||
that file. `git diff -- crates/vlog_formatter/src/verify.rs` is empty:
|
||||
invariant #4 does not apply, confirmed rather than taken on the dev's
|
||||
word.
|
||||
|
||||
### Beyond the list
|
||||
|
||||
- **A file that is one giant `` `ifdef ``-guarded block**: added
|
||||
`a_module_wrapped_whole_in_an_ifdef_guard_indents_by_its_own_nesting`
|
||||
(`on_type.rs:1145`) — conditional compilation directives push/pop nothing
|
||||
on the stack (`Scan::step`'s `TokenKind::Directive => At::Boundary` arm),
|
||||
so nesting inside the guard is computed exactly as if the guard were
|
||||
stripped. Passes.
|
||||
- **`;` completing a statement whose line also holds a format-off fence**:
|
||||
added `a_semicolon_inside_a_format_off_fence_rides_through_the_fence_untouched`
|
||||
(`on_type.rs:1156`) — a messy, badly-spaced `wire` declaration inside a
|
||||
`// verilog_format: off` / `// verilog_format: on` pair gets **no edit at
|
||||
all** on a `;` typed at its end, because the `;` path is `format_range`
|
||||
unchanged and the fence outranks the range there exactly as it does for
|
||||
`textDocument/rangeFormatting`. Passes — confirms the fence "rides through"
|
||||
claim rather than assuming it from the "no new formatting logic" argument.
|
||||
- **Rapid-fire consecutive `\n` triggers**: the existing
|
||||
`applying_the_edit_leaves_the_next_ask_nothing_to_do` already loops over
|
||||
four consecutive lines, applying and re-asking each time, which is the
|
||||
same state-consistency question a burst of `didChange`s would raise at the
|
||||
state layer; did not find a reason to add a second version of this at the
|
||||
e2e/wire level given the idempotency nuance already logged in (4).
|
||||
|
||||
### Fixes made directly
|
||||
|
||||
Six tests added to `crates/lucisv_server/src/on_type.rs`'s existing
|
||||
`#[cfg(test)] mod tests`, all passing, no production code changed:
|
||||
`a_crlf_line_ending_is_never_touched_by_the_edit`,
|
||||
`a_mixed_tab_and_space_prefix_is_measured_in_bytes_not_visual_columns`,
|
||||
`a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`,
|
||||
`a_module_wrapped_whole_in_an_ifdef_guard_indents_by_its_own_nesting`,
|
||||
`a_semicolon_inside_a_format_off_fence_rides_through_the_fence_untouched`,
|
||||
`a_semicolon_ending_a_macro_definitions_body_ends_no_statement`. Ran
|
||||
`cargo fmt --all` once to settle the one line these additions pushed over the
|
||||
width limit (`on_type.rs`, the `ifdef` test's `text` binding) — no other
|
||||
formatting drift.
|
||||
|
||||
### Verdict
|
||||
|
||||
**Committable as-is.** No correctness bug found in either path; the
|
||||
structural-confinement claim for `\n` holds under CRLF, mixed-tab, and
|
||||
FF/VT attack, and the `;` gate holds under macro-body, EOF, and fence
|
||||
attack. Two items for the lead's attention rather than blockers: the corpus
|
||||
anchor's runtime/placement tradeoff (§ Gates, above), and the untested
|
||||
apply-then-retype idempotency gap at the e2e level (§4, above).
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(including the formatter's own 8 suites — untouched and green), clean.
|
||||
This is the round I was most prepared to reject, and it earned the
|
||||
opposite: the `;` path adds zero new formatting authority (the verified
|
||||
engine, gated by one lexer fact), and the `\n` path's edit is confined
|
||||
to one line's leading whitespace by construction — I read
|
||||
`indent_edit` myself and the range cannot name another byte. The corpus
|
||||
anchor is the methodology prize of the whole audit: nine of the model's
|
||||
ten rules were forced by disagreement with the real formatter rather
|
||||
than predicted, it caught a real stack-pop bug mid-round, and its
|
||||
coverage floor keeps it from ever passing by declining everything.
|
||||
|
||||
Two lead rulings. First, the dev's refusal of my config-warning design
|
||||
was correct and well-evidenced — the dedup re-arms on the very
|
||||
didChange each keystroke produces, so the warning would fire per
|
||||
character; the silent-keystroke/warning-on-request contrast is now
|
||||
pinned in both directions and the README documents the reasoning better
|
||||
than my brief did. Second, on QA's flagged 31-second anchor cost: it
|
||||
stays as a normally-running test. It is a correctness gate over the one
|
||||
piece of formatting logic that lives outside the verified engine, and
|
||||
making it opt-in would trade the whole anchor for half a minute; the
|
||||
binary-layout constraint QA traced (no [lib], private internals) means
|
||||
moving it out would mean weakening it. If the suite's runtime ever
|
||||
becomes a real complaint, the answer is a [lib] refactor, not an
|
||||
#[ignore]. QA's six added tests (CRLF, mixed tabs, macro-body and
|
||||
EOF semicolons, fence, whole-file ifdef) close the shapes the dev's
|
||||
own sweep missed. Accepted as shipped.
|
||||
@@ -0,0 +1,966 @@
|
||||
# overlay-promotion
|
||||
|
||||
## Goal
|
||||
|
||||
An unqualified name nothing in a file binds — `bus_if bus;`, `my_cls h;`,
|
||||
`virtual clk_rst_if vif;` — used to die inside `vlog_semantic`. `resolve.rs`'s
|
||||
lexical walk ended in `Resolution::NotFound` when the file had collected no
|
||||
import paths, or in `Resolution::InheritedCandidate` when the miss happened
|
||||
inside a class with an `extends`, and neither spelling reached
|
||||
`resolve_external`, so the workspace overlay never saw the name. That is
|
||||
exactly how an `interface` is written (interfaces live at file scope, never in
|
||||
a package) and how a package-less `class` is used, and the `InheritedCandidate`
|
||||
half covers nearly every UVM class, since almost all of them extend something.
|
||||
This feature makes both spellings carry the **bare name** as their last
|
||||
candidate path **when the name was written in a type position**, so the
|
||||
workspace's unit table — the one that already answers `sub u_sub (...)` — gets
|
||||
asked. An identifier in a value position is left alone: it makes no claim about
|
||||
a file-scope declaration, and matching one on name alone is how `rename` came
|
||||
to rewrite an unrelated file (QA finding 1, fixed in the round below).
|
||||
`textDocument/definition`, `typeDefinition`,
|
||||
`references` and `rename` all gain the answer at once, because all four read
|
||||
the same overlay; and `lucisv_server`'s stopgap `type_def::indexed_type`, which
|
||||
asked the index directly under a three-condition fence, is deleted whole (the
|
||||
Handshake `docs/features/type-definition/README.md` filed, delivered here).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A bare miss *in a type position* is a name the workspace could declare.**
|
||||
Nothing in the file binds it and no import path in scope can supply it, so
|
||||
the only remaining source is a file-scope declaration in another file. This
|
||||
is what makes the promotion honest rather than a guess: the alternative
|
||||
answer is no answer at all, and the name really is spelled the way a
|
||||
cross-file `interface`/`class`/`module`/`typedef` use is spelled. The
|
||||
qualifier "in a type position" is load-bearing and was missing from the
|
||||
round's first cut — see the fourth assumption below.
|
||||
- **A qualified miss is not one of these, and is never promoted.**
|
||||
`p::missing_t` names something *inside* `p`; sweeping the bare tail through
|
||||
the unit table would discard the qualifier and jump somewhere the source
|
||||
never pointed (the lead's ruling on the deleted fence, 2026-08-26). This is
|
||||
structural, not a check: `resolve.rs`'s `unit_member` returns its own
|
||||
`NotFound`/`InheritedCandidate` and never calls `miss`, so the bare name is
|
||||
added on exactly the two paths that should have it (`lexical`, `unit`).
|
||||
- **The unit table has no kind filter, here as everywhere.** `units(name)`
|
||||
returns every file-scope `module`, `package`, `typedef` and `class` of that
|
||||
name, and the overlay offers all of them — the documented duplicate policy
|
||||
(`docs/features/workspace-index/README.md`). A promoted miss therefore *can*
|
||||
answer with a `package` of that name, which the deleted `indexed_type`
|
||||
excluded. That exclusion was a property of a fourth, private resolution
|
||||
layer; with the answer coming from the shared overlay,
|
||||
`typeDefinition` gives what `definition` gives on the same token, and
|
||||
disagreeing would mean building the fourth layer again. The source that
|
||||
provokes it (`thing t;` where the workspace's only `thing` is a package) does
|
||||
not compile either way.
|
||||
- **Only a name written where a type goes is offered to the unit table.**
|
||||
~~An identifier in a value position that nothing declares — a name a
|
||||
`` `define`` would have produced, a typo — now resolves to a same-named unit
|
||||
if the workspace has one. That is the same exposure `Target::Module` and
|
||||
`Target::Unit` have always had.~~ **Both halves of that were wrong, and QA
|
||||
disproved them (finding 1, 2026-08-26).** The exposure was *not* the same:
|
||||
`Target::Module`/`Unit`/`Package` are emitted only where the source names a
|
||||
unit — an instantiation, an `extends` base, the head of `p::x` — so their
|
||||
bare-name sweep asks a question the source actually asked. `Target::Lexical`
|
||||
is emitted for two unrelated things: a declaration's type window
|
||||
(`bind.rs`'s `bind_data_type`) and every plain expression identifier
|
||||
(`ExprKind::Ident`). Promoting it promoted both, and a value-position typo
|
||||
became an `ExternalCandidate` that `rename` rewrote across files on nothing
|
||||
but a name collision. Nor was it bounded by anything: the unit table holding
|
||||
only file-scope declarations is what makes the collision *plausible*, not
|
||||
what makes it safe. The fix round split the target — `Target::Type`, emitted
|
||||
by `bind_data_type`'s unqualified arm alone — so the promotion asks the unit
|
||||
table only about names the source wrote as types. A value-position miss keeps
|
||||
its pre-round spelling and `rename` goes on refusing it. `rename` still gains
|
||||
the ability to rename an interface from its use as a type — the intended win,
|
||||
and the only one claimed.
|
||||
- **The overlay is consulted after the in-file layer, always.** A name this
|
||||
file declares never reaches the promotion at all, so shadowing needs no code
|
||||
and cannot regress.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:** nothing new.
|
||||
|
||||
**Changed in `vlog_semantic` (this crate), and what each consumer sees:**
|
||||
|
||||
0. `bind.rs` gains `Target::Type`, emitted by `bind_data_type`'s unqualified
|
||||
arm and by nothing else. It is resolved exactly like `Target::Lexical` —
|
||||
same walk, same shadowing, same import precedence — and differs only in what
|
||||
its miss carries. Every type position in the language reaches it, because
|
||||
every one of them goes through `bind_data_type` (call-site map in the fix
|
||||
round's work log).
|
||||
1. `resolve.rs::lexical` pushes the reference's own name onto the candidate
|
||||
paths before the miss is spelled, **for `Target::Type` only** and **last**,
|
||||
after every import collected on the way out, so an import that can supply
|
||||
the name still wins (unchanged precedence, pinned by a test).
|
||||
2. An unqualified **type** miss is therefore
|
||||
`ExternalCandidate { paths: [..imports.., name] }`, or
|
||||
`InheritedCandidate { base, paths: [..imports.., name] }` inside an
|
||||
extending class. `base` is untouched: the inherited semantics every consumer
|
||||
reads are exactly what they were. An unqualified **value** miss is
|
||||
unchanged from `3bc61f9`: `ExternalCandidate { paths: [..imports..] }`,
|
||||
`InheritedCandidate { base, paths: [..imports..] }`, or `NotFound` when
|
||||
there are no imports at all.
|
||||
3. `Resolution::NotFound` keeps its meaning and its reachability. It is what a
|
||||
miss with no path to offer says: a member of a package this file fully
|
||||
declares, a `.port` of a module it declares, a `this.x`/`super.x` with no
|
||||
class or base, and a plain expression identifier with no import in scope.
|
||||
Over the 860-file corpus it is reached 1 256 times (was 1 418 before the
|
||||
round; the 162-reference difference is exactly the type-position misses).
|
||||
4. `workspace.rs::resolve_external` answers an `InheritedCandidate` from its
|
||||
paths, and records an entry **only when one of them lands**. An inherited
|
||||
candidate is not an external candidate: when the sweep finds nothing, the
|
||||
reference stays exactly what it was, absent from the overlay, and
|
||||
`ExternalResolutions::counts()` does not grow. `ExternalTarget`,
|
||||
`Definition` and every other overlay type are unchanged.
|
||||
|
||||
**Promised to consumers:** the overlay answers more references and invents
|
||||
nothing. Every `Def` it returns is still a real file-scope declaration whose
|
||||
`name_span` slices back to the name the use spells (the corpus test asserts
|
||||
this over all 860 files, unchanged).
|
||||
|
||||
**Requested of other modules:** nothing. The parser gap the type-definition
|
||||
feature filed (an ANSI header whose first port has no direction does not parse)
|
||||
is still open and still not this feature's; the rename test added here writes
|
||||
the interface in the body and says why.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/vlog_semantic/src/bind.rs`: `Target::Type`, emitted by
|
||||
`bind_data_type`'s unqualified arm only (fix round, 2026-08-26).
|
||||
- [x] `crates/vlog_semantic/src/resolve.rs`: the bare name as the last path of
|
||||
every unqualified **type-position** miss, both spellings; a
|
||||
value-position miss keeps its pre-round spelling, `NotFound` included.
|
||||
- [x] `crates/vlog_semantic/src/workspace.rs`: `resolve_external` answers an
|
||||
inherited candidate opportunistically, entry only on a hit.
|
||||
- [x] `crates/vlog_semantic/src/model.rs`: the three `Resolution` doc comments
|
||||
say what each variant now means.
|
||||
- [x] `crates/lucisv_server/src/type_def.rs`: `indexed_type` deleted, qualifier
|
||||
guard and kind filter included; `type_definition` is the pure two-layer
|
||||
answer; module doc updated.
|
||||
- [x] Consumer audit across the workspace (work log below): every match site on
|
||||
`NotFound`/`InheritedCandidate` reviewed, no code change needed anywhere.
|
||||
- [x] 9 new `vlog_semantic` tests (7 promotion + 2 value-position twins), 1 new
|
||||
`vlog_refactor` test plus the fix round's refusal test, 6 existing
|
||||
`vlog_semantic` assertions restored to their pre-round values once the
|
||||
promotion narrowed, 1 `lucisv_server` expectation updated and 3 tests
|
||||
there renamed (one of them a real behavior change, argued below).
|
||||
- [x] Corpus re-measured three times with one harness — `3bc61f9`, the
|
||||
unrestricted first cut, and the shipped type-only promotion; both README
|
||||
tables carry all three columns and the survived/given-back split.
|
||||
- [ ] **Not done, deliberately:** `rename` still refuses an
|
||||
`InheritedCandidate` even when the overlay answered it. The refusal
|
||||
message is about the base class, which is still true, and widening rename
|
||||
to act on a best-effort sweep deserves its own round with its own
|
||||
collision tests.
|
||||
- [ ] **Not done:** chasing a base class. Nothing here resolves inheritance;
|
||||
when something does, those references become `Resolved` and the promotion
|
||||
is simply never reached for them.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent
|
||||
|
||||
- **The design, chosen after reading all three call sites.** The brief offered
|
||||
a new `Resolution` variant or a promotion to `ExternalCandidate`. The
|
||||
promotion wins, and the reason is that `ExternalCandidate { paths: [name] }`
|
||||
is not a new concept here — it is *the same shape* `Target::Module` emits for
|
||||
an instantiation of a module declared elsewhere and `Target::Unit` emits for
|
||||
an `extends Base`, both of which already mean "a workspace unit of this name
|
||||
could be it". A fourth variant would have spelled an existing idea twice.
|
||||
It also makes `NotFound`'s own doc comment true for the first time: it says
|
||||
"no external unit could", which was false for every unqualified lexical miss.
|
||||
The implementation is two lines of behavior — `lexical` pushes the name,
|
||||
`miss` loses its `NotFound` arm — which is what the boring version of this
|
||||
should cost.
|
||||
- **Where the qualified/unqualified fence lives, and why that is not a check.**
|
||||
The lead's guard in `indexed_type` tested the text before the reference for
|
||||
`::`, because at the server layer the `Target` that produced a resolution is
|
||||
gone. In `resolve.rs` it is right there: `unit_member` (the `x` of `p::x`)
|
||||
builds its own `NotFound`/`InheritedCandidate` and never calls `miss`, so
|
||||
adding the bare name inside `miss` reaches exactly `lexical` and `unit` and
|
||||
nothing else. The guard is deleted with the function and nothing replaces it;
|
||||
`a_qualified_miss_is_never_promoted_in_either_spelling` pins both spellings.
|
||||
- **The `InheritedCandidate` half is answered without being converted.** The
|
||||
brief's constraint was that the overlay must not erase the inherited
|
||||
semantics, and the corpus makes it concrete: 7 800-odd inherited candidates
|
||||
exist, and most of them are ordinary member misses (`held = 1` inside a class
|
||||
that extends) that no unit table can answer. So `resolve_external` tries the
|
||||
paths and inserts an entry **only on a hit** — 520 hits over the corpus.
|
||||
Consequences: `Resolution` still says `InheritedCandidate { base, .. }` for
|
||||
every one of them, so `rename`'s refusal message and `check.rs`'s anchor
|
||||
logic are untouched; `overlay.get(id)` still means "the workspace had
|
||||
something to say"; and `counts()` does not acquire a denominator of names
|
||||
nobody expected it to answer. The alternative — inserting `StillUnresolved`
|
||||
entries for all of them — would have moved the corpus answer rate from 89.3 %
|
||||
to roughly 60 % without a single extra answer, which is a measurement
|
||||
artifact, not a result.
|
||||
- **It also closes a finding the class-semantics QA round filed and left as a
|
||||
design call.** That log offered two honest fixes for inherited candidates the
|
||||
overlay never got to answer: suppress the inheritance fallback for *unit*
|
||||
lookups, or "let the overlay chase `InheritedCandidate.paths`"
|
||||
(`docs/features/class-semantics/README.md`). The first was taken earlier —
|
||||
`miss` already exempts `Target::Unit` — and this round takes the second.
|
||||
- **Consumer audit** (`grep -rn 'InheritedCandidate\|NotFound' crates
|
||||
--include='*.rs'`), every site and its verdict:
|
||||
- `vlog_refactor/src/rename.rs:231-240` — `locate` matches all four
|
||||
variants. `NotFound` → "not resolved to any declaration"; a promoted miss
|
||||
now takes the `ExternalCandidate` arm instead, reaching
|
||||
`declaration_across_files`, which either finds the declaring file (the
|
||||
interface rename this round pins) or returns "declared outside the files
|
||||
lucisv indexes". Both are honest; no code change. The
|
||||
`InheritedCandidate` arm is unreachable-by-design for a name the overlay
|
||||
answered, and deliberately left refusing (Status/TODO).
|
||||
- `vlog_refactor/src/check.rs:533` (`Anchor::Unresolved`'s doc) and
|
||||
`:618-640` (`anchor_of`) — reads `reference.resolved()` and the overlay,
|
||||
never the variant. A newly answered reference becomes `Anchor::External`
|
||||
on **both** sides of the verification (the pre-edit analysis is shifted
|
||||
forward and re-anchored the same way), so the fingerprint still compares
|
||||
like with like. No change; the whole rename suite is green including the
|
||||
resolution-identity tests.
|
||||
- `vlog_linter/src/signals.rs:260,573` — `reference.resolved()` only, which
|
||||
is `Some` for `Resolved` and `None` for everything else, before and after.
|
||||
Semantic lints cannot see this change. `cargo test -p vlog_linter`: green.
|
||||
- `lucisv_server/src/nav.rs:191` (`symbol_at`) — same `resolved()`
|
||||
accessor; `definition`/`references`/`highlights` go through
|
||||
`ExternalResolutions`, which is where the new answers arrive.
|
||||
- `lucisv_server/src/tokens.rs:202` — `resolved()`; semantic tokens
|
||||
unaffected.
|
||||
- `lucisv_server/src/type_def.rs` — the whole `indexed_type` match site is
|
||||
deleted.
|
||||
- `vlog_semantic/src/model.rs:119` (`is_inherited_candidate`) — still true
|
||||
of exactly the same references; the corpus inherited-candidate rate is
|
||||
unchanged at 8.3 %, which is the check that the promotion did not
|
||||
reclassify anything.
|
||||
- Test-only sites (`tests/semantics.rs`, `tests/classes.rs`,
|
||||
`tests/rename.rs:368`) — reviewed individually below.
|
||||
- `lucisv_server/src/server.rs`'s `MethodNotFound` — an LSP error code, an
|
||||
unrelated grep hit.
|
||||
- **Six existing assertions re-pointed, each because the paths grew by the
|
||||
bare name, none because behavior regressed**: `semantics.rs`'s genvar-escape
|
||||
miss (`NotFound` → `ExternalCandidate { ["i"] }`, plus a new assertion that
|
||||
`resolved()` is still `None`) and its wildcard-import miss (`["other_pkg::*"]`
|
||||
→ `+ "SOMETHING"`); `classes.rs`'s `set_name` inheritance miss, `UVM_LOW`
|
||||
import-carrying miss, and `member_miss`. `super.x`/`this.x` assertions in the
|
||||
same tests are untouched, which is the point: a member access names no unit
|
||||
and gains no path.
|
||||
`inherited_candidates_are_not_the_workspace_overlays_business` keeps its name
|
||||
and its verdict — the overlay still holds nothing for `held` — and gained the
|
||||
reason (a class property is not a unit).
|
||||
- **The type_def fence tests, one by one.** The suite is the acceptance suite,
|
||||
so each is named with what happened to it:
|
||||
- `a_local_declaration_of_the_same_name_wins_over_the_workspace_type`,
|
||||
`a_local_typedef_in_the_extending_class_itself_wins_over_the_workspace_type`
|
||||
— unchanged, pass. Shadowing is enforced by `lexical` resolving first,
|
||||
which the promotion happens after.
|
||||
- `a_qualified_name_the_overlay_refused_is_not_retried_against_the_index`,
|
||||
`a_qualified_member_miss_never_falls_back_to_a_bare_name_sweep` —
|
||||
unchanged, pass. The qualifier guard's job is now `unit_member`'s.
|
||||
- `an_inherited_candidate_reaches_a_same_named_module_exactly_like_not_found_did`,
|
||||
`a_uvm_shaped_member_type_resolves_cross_file_from_an_extending_class`,
|
||||
`a_class_scoped_type_reference_in_an_extending_class_is_found_cross_file`,
|
||||
`an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it`
|
||||
— unchanged, pass, now through the overlay. The third and fourth still
|
||||
assert the resolution is `InheritedCandidate`, which is now a statement
|
||||
about the promotion preserving it.
|
||||
- `a_module_declared_twice_returns_both_declarations`,
|
||||
`a_type_nothing_declares_answers_nothing`,
|
||||
`a_non_type_inherited_reference_is_still_never_a_type_site`,
|
||||
`corpus_spot_check_real_uvm_files_no_panic_and_known_jumps` and the other
|
||||
30 — unchanged, pass.
|
||||
- `a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site` —
|
||||
kept, expectation updated: the reference is now an `ExternalCandidate` and
|
||||
`nav::definition` *does* answer it, which the test now asserts explicitly
|
||||
before asserting that `type_definition` still does not. That makes it a
|
||||
stronger test than it was: it pins the confinement rather than an accident.
|
||||
- `indexed_type_returns_every_workspace_declaration_when_the_name_is_ambiguous`
|
||||
→ `a_promoted_miss_returns_every_workspace_declaration_when_the_name_is_ambiguous`.
|
||||
Renamed because it named a deleted function; same fixture, same assertion
|
||||
(two interfaces, both offered), same convention.
|
||||
- `the_other_two_fence_conditions_still_hold_under_an_inherited_candidate`
|
||||
→ `an_inherited_candidate_answers_only_what_the_workspace_unit_table_holds`.
|
||||
Two of its three arms are unchanged and pass (a package *member* is not in
|
||||
the unit table; a qualified miss is never swept). The first arm — a
|
||||
`package` of that name — now answers, and asserts so.
|
||||
- `a_package_of_the_same_name_is_not_a_type`
|
||||
→ `a_package_of_the_same_name_answers_exactly_as_definition_answers_it`.
|
||||
**The one behavior change in the suite**, argued in Assumptions above and
|
||||
asserted as literal equality with `nav::definition` at the same offset, so
|
||||
the two handlers can never drift apart on it again.
|
||||
- **Measured before and after with one harness, both on the 860-file corpus.**
|
||||
The tables in `docs/features/vlog-semantic/README.md` and
|
||||
`docs/features/workspace-index/README.md` were **stale by several rounds**
|
||||
before this one (they described 73 708 references and an 87.0 % answer rate;
|
||||
the tree measured 94 685 and 89.3 % at `3bc61f9`, because class support and
|
||||
the parser rounds since moved both). The numbers quoted in the brief
|
||||
(94.0 % / 1.2 %) come from `docs/features/directives-in-instances/README.md`
|
||||
and are older still. So the "before" column below is a fresh measurement of
|
||||
`3bc61f9` — taken by stashing only the three changed `src` files and
|
||||
re-running the same instrumented test — not a quote.
|
||||
- **The reporting change that made the comparison honest.** Re-bucketing a miss
|
||||
moves it between the columns these tables report, so the per-bucket rates
|
||||
move without anything getting better or worse. `tests/workspace.rs`'s `Tally`
|
||||
now also prints **references with nowhere to jump after both layers**
|
||||
(`references − resolved in-file − answered by the overlay`), which is the
|
||||
number that cannot be gamed by a re-spelling, plus how many of the overlay's
|
||||
entries came from inherited candidates. `tests/corpus.rs` prints the raw
|
||||
unresolved count beside its percentage. Both assertions are textually
|
||||
unchanged.
|
||||
|
||||
Clean-file population (853 files, 94 384 references):
|
||||
|
||||
| metric | before | after |
|
||||
|---|---:|---:|
|
||||
| resolved in-file | 73.3 % | 73.3 % |
|
||||
| external candidates | 17.1 % | **18.4 %** |
|
||||
| inherited candidates | 8.3 % | 8.3 % |
|
||||
| unresolved (`NotFound`) | 1.3 % | **0.00 % (0)** |
|
||||
| handed to the workspace layer | 16 133 | **17 877** |
|
||||
| …of which inherited candidates | 0 | **520** |
|
||||
| answered | 89.3 % | 83.7 % |
|
||||
| still unresolved (of those handed) | 10.7 % | 16.3 % |
|
||||
| **nowhere to jump, both layers** | **10 794 (11.4 %)** | **10 235 (10.8 %)** |
|
||||
|
||||
All-files population: nowhere to jump 10 992 (11.6 %) → **10 431 (11.0 %)**.
|
||||
|
||||
Read honestly: **559 references on clean files gained a jump target and none
|
||||
lost one** — 520 of them inherited candidates (the UVM shape this round
|
||||
exists for) and 39 in the external bucket, where the bare name landed after
|
||||
every import path in scope had missed. The answer *rate* falls only because
|
||||
1 224 previously-invisible misses joined the denominator; they were counted
|
||||
in the other table's "1.3 % unresolved" before, and they are the same names
|
||||
either way. No cell that measures "this reference has nowhere to go" rose.
|
||||
Index counts, build time (0.78 s), determinism and the span-slices-back
|
||||
assertion are all unchanged.
|
||||
- **Scope.** Files edited: `crates/vlog_semantic/src/{resolve,workspace,model}.rs`,
|
||||
`crates/vlog_semantic/tests/{workspace,semantics,classes,corpus}.rs`,
|
||||
`crates/lucisv_server/src/type_def.rs`,
|
||||
`crates/vlog_refactor/tests/rename.rs`, this README, and the three READMEs
|
||||
named above. No new dependency, no version bump, no parser change,
|
||||
no `TODO.md` change (§6 and §9c both claim capabilities that were true before
|
||||
and are more true after).
|
||||
- **Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets
|
||||
--workspace`: 0 warnings. `cargo test --workspace`: green (871 passed /
|
||||
4 ignored in `lucisv_server`'s own suite, 0 failed anywhere).
|
||||
`cargo test -p vlog_formatter`: green. `cargo test -p vlog_linter`: green.
|
||||
`cargo test -p vlog_refactor`: green (49 rename tests, +1).
|
||||
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`. No `git commit`, no `git push`.
|
||||
|
||||
### 2026-08-26 — dev agent, fix round (QA finding 1)
|
||||
|
||||
- **What was wrong, in one sentence.** `Target::Lexical` is two things wearing
|
||||
one name — a declaration's type window and every plain expression identifier
|
||||
— so promoting it promoted both, and a value-position typo became an
|
||||
`ExternalCandidate` that `rename` acted on across files. The round's
|
||||
Assumptions claimed this was "the same exposure `Target::Module` and
|
||||
`Target::Unit` have always had"; QA disproved it by reading `3bc61f9`, and
|
||||
the claim is now struck through and corrected in place rather than quietly
|
||||
edited.
|
||||
- **The mechanics, and why this one.** The brief offered a new target variant
|
||||
or a flag at the `use_name` call sites. The variant wins, for the reason the
|
||||
bug had: the information "this name was written where a type goes" exists at
|
||||
exactly one place in `bind.rs` and is thrown away one line later. A flag
|
||||
threaded through `use_name` would put the same fact in the same place while
|
||||
making every unrelated call site name it; a variant lets `resolve.rs`'s
|
||||
dispatch — the function whose whole job is "what kind of lookup is this" —
|
||||
carry it. So: `Target::Type`, dispatched to the same `lexical` walk with
|
||||
`promote: true`, and `Target::Lexical` with `promote: false`. `miss` gets its
|
||||
pre-round body back verbatim, including the `external.is_empty() → NotFound`
|
||||
arm the first cut had deleted as unreachable. Behavior delta is four lines.
|
||||
- **The call-site map — every `Target::Lexical` site in `bind.rs`, and its
|
||||
verdict.** All four, and only these four, exist:
|
||||
- `bind.rs:1223`, `bind_data_type`'s unqualified `None` arm — **the type
|
||||
position, changed to `Target::Type`.** Every type in the language funnels
|
||||
here, verified by reading all eleven `bind_data_type` callers: ANSI module
|
||||
ports (385), header `#()` param ports (409), typedef aliases (442) and
|
||||
enum bases (448), struct members (467), the shared declarator path that
|
||||
serves nets/vars/params/port decls (508), function return types (615),
|
||||
task/function arguments (650), out-of-body method return types (829), the
|
||||
typed `for`-init declaration (928), and `ExprKind::Type` (1184), which is
|
||||
how `#(virtual bus_if)` and a `type` parameter's default arrive. A
|
||||
`virtual`/`virtual interface` prefix is held separately by the parser
|
||||
(`DataType::virtual_kw`), so `ty.name` is the bare interface name and the
|
||||
UVM `virtual clk_rst_if vif;` shape is covered by the same one line — the
|
||||
cross-file interface rename test exercises exactly it.
|
||||
- `bind.rs:1082`, `ExprKind::Ident` — the value position, **left as
|
||||
`Target::Lexical`.** The regression's source.
|
||||
- `bind.rs:1009`, `disable blk;` — a block label, a value position. Left.
|
||||
- `bind.rs:128`, a re-declaration of a name already bound in the scope —
|
||||
recorded as a use of the first declaration. Not a type window (the type
|
||||
window was already bound separately by the time `declare` is called), and
|
||||
the name is by construction one this file *does* bind, so it resolves and
|
||||
never reaches `miss` anyway. Left.
|
||||
- **Not a call site, worth recording:** a cast's type. `ExprKind::Cast`
|
||||
binds only its operand (`bind.rs:1169`, `{ expr, .. }`) — the casting type
|
||||
is dropped and produces no reference at all, before this round and after.
|
||||
So `state_t'(0)` needs no promotion; it needs a reference first. Out of
|
||||
scope here, noted for whoever picks it up.
|
||||
- **Consumer audit, the additions.** `bind::Target` is `pub(crate)` and
|
||||
`grep -rn 'Target' crates --include='*.rs'` finds exactly one match site for
|
||||
it, `resolve.rs::resolve` — every other hit is `ExternalTarget` (the overlay
|
||||
enum, untouched), `vlog_refactor`'s unrelated `rename::Target`/`RenameTarget`,
|
||||
or prose. Adding a variant therefore cannot silently fall through anywhere:
|
||||
the one `match` is exhaustive and the compiler checked it. The main round's
|
||||
audit of `NotFound`/`InheritedCandidate` consumers stands unchanged and is
|
||||
now *more* true — `NotFound` is reachable again, which is the spelling
|
||||
`rename.rs:233` and `type_def.rs` were already written against.
|
||||
- **`type_def.rs` needed nothing, as predicted.** Its whole suite is green
|
||||
unchanged: the fence tests, the cross-file interface/class/typedef jumps, the
|
||||
ambiguity convention, the qualified-miss fence. The one exception is the test
|
||||
the main round flipped, flipped back — below.
|
||||
- **The read-only side, given back deliberately.**
|
||||
`a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site` now
|
||||
asserts the value-position typo is `NotFound` and that **`nav::definition`
|
||||
answers nothing**, where the main round asserted it answered. That read-only
|
||||
behavior was defensible on its own — F12 landing on a same-named module is
|
||||
surprising but harmless — but one promotion serves both the read and the
|
||||
write path, and there is no honest way to keep the jump while refusing the
|
||||
rename without building the fourth resolution layer this round exists to
|
||||
delete. The write side wins the argument. The test is stronger for it: it now
|
||||
pins two independent fences (the model never offers the coincidence, and the
|
||||
handler builds no `Site` for an expression statement) instead of one.
|
||||
- **The QA repro, flipped and rehomed.**
|
||||
`qa_a_bare_value_position_typo_reaches_an_unrelated_same_named_module` →
|
||||
`a_bare_value_position_typo_never_reaches_an_unrelated_same_named_module`,
|
||||
moved into `rename.rs`'s refusals section where its siblings live, and it now
|
||||
asserts the refusal message (`not resolved to any declaration`) instead of
|
||||
panicking on success. Same fixture, same two files, same cursor.
|
||||
- **Value-position twins added**, alongside the promotion tests they mirror:
|
||||
`a_value_position_miss_is_never_promoted_even_onto_a_same_named_unit` (the
|
||||
same word, the same workspace, only the position differs — `NotFound`, no
|
||||
overlay entry, no defs) and
|
||||
`a_value_position_miss_inside_an_extending_class_gains_no_path_either`
|
||||
(`InheritedCandidate` with empty `paths` despite a same-named interface in
|
||||
the workspace). Six assertions the main round had re-pointed at grown paths
|
||||
went back to their pre-round values, each with the reason written in: they
|
||||
were all value positions (`set_name` a callee, `UVM_LOW` a call argument,
|
||||
`member_miss` a call, `held = 1` an assignment LHS, `i` a genvar out of
|
||||
scope, `SOMETHING` an assignment RHS).
|
||||
- **Measured a third time, same harness, same corpus.** Resolution buckets over
|
||||
all 860 files, raw counts, the three states side by side:
|
||||
|
||||
| bucket | `3bc61f9` | promote everything | type positions only |
|
||||
|---|---:|---:|---:|
|
||||
| `Resolved` | 69 274 | 69 274 | 69 274 |
|
||||
| `ExternalCandidate` | 16 152 | 17 570 | **16 314** |
|
||||
| `InheritedCandidate` | 7 841 | 7 841 | **7 841** |
|
||||
| `NotFound` | 1 418 | 0 | **1 256** |
|
||||
|
||||
`InheritedCandidate` is bit-identical in all three, which is the strongest
|
||||
form of "nothing was reclassified"; 16 152 + 162 = 16 314 and 1 418 − 162 =
|
||||
1 256, so exactly 162 references moved, all of them type positions with no
|
||||
import in scope (153 of them on clean files).
|
||||
- **The split, stated honestly.** Against `3bc61f9`, on clean files: **418
|
||||
references gained somewhere to jump and none lost one** (420 over all files —
|
||||
nowhere-to-jump 10 992 → 10 572). The unrestricted first cut gained 559 on
|
||||
clean files (561 over all), so **141 gains were given back** — the same 141
|
||||
on both populations. Composition of the give-back: 117 inherited-candidate
|
||||
answers (the landed count falls 520 → 403) and 24 external-bucket answers.
|
||||
Every one was a value-position identifier answered on a name collision, which
|
||||
is precisely the thing that made `rename` unsafe; the round is worth less
|
||||
without them and would have been worth nothing with them. The type-position
|
||||
wins — the cross-file `interface`, the package-less `class`, the file-scope
|
||||
`typedef`, the UVM `virtual iface` inside an extending class — all survive,
|
||||
and their tests are green unchanged. The no-reference-loses-a-target property
|
||||
holds: the last row of the workspace table fell against the baseline in both
|
||||
populations, and every promotion test still finds its declaration.
|
||||
- **Scope of the fix round.** `crates/vlog_semantic/src/{bind,resolve,model}.rs`,
|
||||
`crates/vlog_semantic/tests/{workspace,classes,semantics}.rs`,
|
||||
`crates/vlog_refactor/tests/rename.rs`,
|
||||
`crates/lucisv_server/src/type_def.rs` (one test), this README and the two
|
||||
measured READMEs. `workspace.rs` untouched by the fix. No new dependency, no
|
||||
parser change, no `TODO.md` change.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent
|
||||
|
||||
**Verdict: not committable as-is.** Attack surface 1 (rename) is a real
|
||||
regression — a bare-name coincidence in a plain *value* expression is now
|
||||
write-reachable and `rename` will cross into an unrelated file's declaration.
|
||||
Everything else audited below is clean. A repro test for the regression is
|
||||
committed (failing, on purpose) at
|
||||
`crates/vlog_refactor/tests/rename.rs::qa_a_bare_value_position_typo_reaches_an_unrelated_same_named_module`.
|
||||
|
||||
**1. Rename write-reachability — REGRESSION, not preexisting.**
|
||||
|
||||
Repro: workspace of two files —
|
||||
|
||||
```verilog
|
||||
// typo_name.sv
|
||||
module typo_name;
|
||||
endmodule
|
||||
|
||||
// top.sv
|
||||
module top;
|
||||
assign typo_name = 1'b1;
|
||||
endmodule
|
||||
```
|
||||
|
||||
Renaming `typo_name` at its use in `top.sv` **succeeds** and rewrites
|
||||
`typo_name.sv`'s module declaration to the new name (verified by direct
|
||||
`vlog_refactor::rename()` call; test panics showing both files' post-edit
|
||||
text). `check::verify` does not catch it — the edit *is* self-consistent (the
|
||||
new name resolves the same way the old one did before the edit), so
|
||||
"resolution identity" has nothing to flag. The bug is one layer up: the model
|
||||
now treats an unbound plain-expression identifier as if it names a workspace
|
||||
unit.
|
||||
|
||||
Traced the claim in Assumptions ("the same exposure `Target::Module` and
|
||||
`Target::Unit` have always had") against `git show 3bc61f9:.../resolve.rs`:
|
||||
true for `Target::Module`/`Target::Unit`/`Target::Package` — `unit()` and
|
||||
`named_at_file_scope()` already appended the bare name unconditionally on a
|
||||
miss, pre-round (module instantiations, `extends` bases, `p::x` heads,
|
||||
`typedef class` forward decls). **False for `Target::Lexical`** — pre-round,
|
||||
`lexical()`'s `external` list held only import paths (no bare name), so a
|
||||
`Target::Lexical` miss with no import in scope was `Resolution::NotFound`,
|
||||
which `rename.rs:233` explicitly refuses ("not resolved to any declaration").
|
||||
Confirmed by reverting only the three `src` files (`git stash push --`) and
|
||||
re-running the same repro: the pre-round rename call errors with exactly that
|
||||
message; instrumented `resolution()` on the same offset returns `NotFound`.
|
||||
|
||||
The regression is that `Target::Lexical` is not exclusively the "type name in
|
||||
a declaration" case the feature is built for
|
||||
(`bind.rs:1223`, `bind_data_type`'s `None` arm — `bus_if bus;`, the intended
|
||||
win). It is *also* the plain-expression-identifier case
|
||||
(`bind.rs:1082`, `ExprKind::Ident => Target::Lexical` — `assign typo_name = 1;`,
|
||||
a function-call name, any bare read/write). Both dispatch through the exact
|
||||
same `resolve.rs::lexical`/`miss` path and produce an indistinguishable
|
||||
`Resolution::ExternalCandidate { paths: [name] }` — there is no signal left
|
||||
anywhere for a consumer to tell "this was a type position" from "this was a
|
||||
value position". The dev's own new assertion in
|
||||
`crates/lucisv_server/src/type_def.rs`'s
|
||||
`a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site`
|
||||
confirms the *read* side of this is deliberate and known
|
||||
(`nav::definition` now jumps a value-position typo to a coincidentally-named
|
||||
module — asserted, not refused). For **read-only** navigation that is a
|
||||
defensible (if surprising) trade griped about nowhere in the brief but at
|
||||
least non-destructive. For **rename**, which writes files, the same
|
||||
coincidence is a silent cross-file edit with no relationship to programmer
|
||||
intent, and CLAUDE.md invariant 1 ("never corrupt code... or emits the input
|
||||
unchanged with an error") is squarely about not producing output the source
|
||||
never asked for.
|
||||
|
||||
`rename.rs`'s own refusal machinery does not defend against this: `locate`'s
|
||||
match arms only ask "did the file's own resolution report `NotFound` /
|
||||
`InheritedCandidate` / `ExternalCandidate`?" — and this case is, faithfully,
|
||||
an `ExternalCandidate`, so it takes the honest-cross-file-rename branch.
|
||||
Whole-edit-or-nothing verification, collision detection and the resolution-
|
||||
identity re-parse check all ran and all passed, because none of them encode
|
||||
"was this identifier ever meant as a type/unit name" — that information does
|
||||
not exist past `bind.rs`.
|
||||
|
||||
This is the top risk the round was flagged for, and it is real. **Not
|
||||
committable until this is closed.** Two shapes of fix that stay inside this
|
||||
round's scope, for the dev's follow-up (not prescribing — QA doesn't
|
||||
redesign): distinguish "type position" from "value position" at bind time
|
||||
(a new `Target` variant, or a flag `bind_data_type` sets) so only the type-
|
||||
name spelling of `Target::Lexical` gets the bare-name push; or narrow the
|
||||
promotion in `resolve.rs::lexical` to fire only when the reference was built
|
||||
by `bind_data_type`'s `None` arm. Either way, rename's collision tests need a
|
||||
new case pinning this exact repro as a refusal.
|
||||
|
||||
**2. `base`-semantics preservation and `counts()` — clean.**
|
||||
|
||||
Re-derived the corpus numbers independently (own harness, not the dev's
|
||||
printed one): dumped every reference's exact `Resolution` variant, both
|
||||
before (`git stash push --` the three `src` files, keep the test harness) and
|
||||
after, over the full 860-file corpus:
|
||||
|
||||
| resolution bucket | before | after |
|
||||
|---|---:|---:|
|
||||
| `Resolved` | 69 274 | 69 274 |
|
||||
| `ExternalCandidate` | 16 152 | 17 570 |
|
||||
| `InheritedCandidate` | 7 841 | 7 841 |
|
||||
| `NotFound` | 1 418 | 0 |
|
||||
|
||||
`InheritedCandidate`'s resolution-bucket count is **exactly** 7 841 in both
|
||||
states — not just "flat at 8.3%" by rounding, bit-for-bit identical — which
|
||||
is the strongest form of "no reclassification" the claim could ask for. And
|
||||
16 152 (before external) + 1 418 (before `NotFound`) = 17 570 (after
|
||||
external), exactly: every re-bucketed reference is accounted for and nothing
|
||||
else moved. `base` itself is untouched by construction (`resolve.rs`'s `miss`
|
||||
still sets it the same way; `workspace.rs::resolve_external`'s new arm reads
|
||||
`paths` and never touches `base`), confirmed by the passing
|
||||
`a_miss_inside_an_extending_class_is_answered_without_losing_its_base` and
|
||||
`an_inherited_member_the_unit_table_cannot_hold_stays_exactly_what_it_was`.
|
||||
|
||||
"Records only when one lands" verified structurally (`workspace.rs`'s new
|
||||
match arm: `StillUnresolved => continue`, nothing inserted) and empirically —
|
||||
`an_inherited_member_the_unit_table_cannot_hold_stays_exactly_what_it_was`
|
||||
asserts `!in_overlay(...)` for a member miss the sweep cannot answer, and the
|
||||
corpus-wide inherited-landed count (520) is far below the total inherited
|
||||
count (7 841), i.e. most misses correctly get no entry at all.
|
||||
|
||||
**3. Baseline honesty — reproduced exactly, "559 gained / none lost" verified
|
||||
per-reference, not just by aggregate delta.**
|
||||
|
||||
Reproduced the before-measurement myself: `git stash push -- resolve.rs
|
||||
workspace.rs model.rs` (keeping the dev's extended `tests/workspace.rs`
|
||||
harness), ran `the_corpus_index_finishes_most_external_references`. Output
|
||||
matched the README's "before" row to the digit: clean-file handed 16 133
|
||||
(17.1 %), inherited-landed 0, nowhere-to-jump 10 794 (11.4 %); all-files
|
||||
nowhere 10 992 (11.6 %). Popped the stash, re-ran: after-numbers matched the
|
||||
README's "after" row to the digit (17 877 handed, 520 inherited-landed,
|
||||
10 235 clean-nowhere / 10.8 %, 10 431 all-files-nowhere / 11.0 %).
|
||||
|
||||
Went one step further than re-running the dev's aggregate: added a temporary
|
||||
per-reference dump (keyed by file + byte offset, since `bind.rs` is untouched
|
||||
by this round so `ReferenceId` ordering is stable across the two states —
|
||||
confirmed by both dumps having exactly 94 685 lines) recording "does this
|
||||
reference have an answer anywhere" for every reference in the corpus, ran it
|
||||
in both states, and joined the two dumps on (file, offset, name). Result:
|
||||
**0 references regressed from answered to unanswered; 561 references gained
|
||||
an answer, over the whole 860-file corpus** (used the full population, not
|
||||
the 853-file clean subset the README table quotes — 561 is consistent with
|
||||
the all-files nowhere-delta of 10 992 − 10 431 = 561, and the README's
|
||||
559-on-clean-files is 2 fewer, i.e. 2 of the 561 gains are on the 7 files that
|
||||
still fail to parse — never checked those 2 individually beyond the aggregate
|
||||
arithmetic, but nothing else in the numbers leaves room for a hidden loss).
|
||||
This dump was removed from the working tree after use — it was diagnostic
|
||||
only (behind an opt-in env var, a no-op otherwise), not something that should
|
||||
ship in the test suite.
|
||||
|
||||
**4. Import-beats-bare-name ordering — verified, real collision.**
|
||||
|
||||
`an_import_that_can_supply_the_name_still_wins_over_a_same_named_unit`
|
||||
(`crates/vlog_semantic/tests/workspace.rs`) does construct a genuine
|
||||
collision, not a vacuous one: package `tdp` exports `state_t`, an unrelated
|
||||
`module state_t` sits in a decoy file, `top.sv` does `import tdp::*; state_t
|
||||
s;`. Confirmed by reading `resolve.rs::lexical`: the wildcard import path
|
||||
(`tdp::*`) is pushed to `external` before the loop ends, the bare name is
|
||||
pushed once after the loop — so paths are always `[..imports.., name]`, and
|
||||
`workspace.rs::follow_paths` (unmodified by this round) tries them in that
|
||||
order and stops at the first hit. Test asserts both the resolution's path
|
||||
order (`["tdp::*", "state_t"]`) and the actual answer (the package's
|
||||
`typedef`, not the decoy module) — ran it, passes.
|
||||
|
||||
**5. The changed package test — defensible, recorded for lead's Review.**
|
||||
|
||||
`a_package_of_the_same_name_answers_exactly_as_definition_answers_it`: yes,
|
||||
this is exactly what `nav::definition` gives on the same cursor (asserted as
|
||||
literal equality in the test, and confirmed independently — `type_def.rs`'s
|
||||
handler is now three lines that end in `nav::definition`, nothing else). My
|
||||
own view on the substance, for Review: this is the right call *given* the
|
||||
"no fourth resolution layer" constraint and the documented no-kind-filter
|
||||
policy of the shared overlay (`workspace-index/README.md`). A `typeDefinition`
|
||||
request on `thing t;` where the workspace's only `thing` is a package is a
|
||||
request against source that does not compile either way, and giving a
|
||||
different answer than `definition` for the same token would need a resolution
|
||||
layer nobody else has. Severity if the lead disagrees: low — it is one
|
||||
disagreeable-but-arguable UX choice on non-compiling input, not a
|
||||
correctness or safety issue, and it is trivially reversible (a kind filter in
|
||||
`type_def.rs` alone, no `vlog_semantic` change) if the lead wants F12 and
|
||||
type-F12 to diverge here.
|
||||
|
||||
**6. Qualified-miss fence — verified structurally intact, both spellings.**
|
||||
|
||||
Read `unit_member` (`resolve.rs:129-174`) end to end: it never calls `miss`,
|
||||
builds its own `Resolution::NotFound`/`InheritedCandidate` directly in every
|
||||
arm, and the bare-name push lives only in `lexical` (line 76) and `unit`
|
||||
(line 120) — `unit_member` has no code path that could reach it. Ran
|
||||
`a_qualified_miss_is_never_promoted_in_either_spelling`
|
||||
(`vlog_semantic/tests/workspace.rs`) directly: pins both spellings (a
|
||||
package-qualified miss with a same-named decoy module, and a class-qualified
|
||||
miss inside an extending class with a same-named decoy module) and asserts
|
||||
`Resolution::NotFound` / `InheritedCandidate { paths: Vec::new() }`
|
||||
respectively, `!in_overlay(...)`, and `external_defs(...).is_empty()` for
|
||||
both. Also re-ran `lucisv_server`'s
|
||||
`a_qualified_name_the_overlay_refused_is_not_retried_against_the_index` and
|
||||
`an_inherited_candidate_answers_only_what_the_workspace_unit_table_holds`
|
||||
(the type_def suite, post-`indexed_type`-deletion) — both pass, confirming no
|
||||
path from a qualified miss reaches a bare-name overlay answer now that the
|
||||
old `::`-text-scan guard in `indexed_type` is gone: the fence moved from a
|
||||
server-layer text check to a `resolve.rs` structural property, and it holds.
|
||||
|
||||
**7. CLAUDE.md compliance / docs — clean, one drive-by fix.**
|
||||
|
||||
Re-derived every printed corpus number in `vlog-semantic/README.md` and
|
||||
`workspace-index/README.md` independently (own dump of raw resolution-bucket
|
||||
and answered/unanswered counts, not a re-run of the dev's own printed
|
||||
`Tally`) — all match to the stated precision (see items 2 and 3 above); the
|
||||
resolution-bucket percentages in `vlog-semantic/README.md`'s table
|
||||
(73.2/18.6/8.3/0.0 after, summing to 100.0 from the raw counts) check out
|
||||
exactly. Feature README has each required section exactly once. Consumer-
|
||||
audit table's file:line citations: `rename.rs:231-240`, `check.rs:533`,
|
||||
`check.rs:618-640`, `signals.rs:260,573`, `nav.rs:191`, `tokens.rs:202` all
|
||||
land within a line or two of the cited construct; `model.rs:119` for
|
||||
`is_inherited_candidate` is off — the actual `impl` line is 126 (the doc
|
||||
comment starts around 124). Minor, not fixed (it's prose in another feature's
|
||||
work log, out of this round's file scope to edit further than necessary).
|
||||
|
||||
Fixed directly (typo/formatting, per QA's small-fix allowance): a stray
|
||||
100-column line in `docs/features/class-semantics/README.md` (line 57, "The
|
||||
overlay may now answer such a reference from `paths`...") that broke the
|
||||
file's ~78-80 column wrap; rewrapped to match the surrounding paragraph. No
|
||||
content change.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets
|
||||
--workspace`: 0 warnings. `cargo test --workspace`: every test green except
|
||||
the QA-added regression repro (1 failed, by design — see item 1).
|
||||
`cargo test -p vlog_formatter`, `-p vlog_linter`, `-p vlog_refactor`: green
|
||||
apart from the same repro. `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
**Corpus regression net (formatter).** `tools/corpus_check.sh` is not
|
||||
actually a committed artifact — `corpus-check-results.tsv` is gitignored, so
|
||||
there is no checked-in baseline TSV to diff against; the file on disk at
|
||||
session start was a stale local leftover from an older parser, not this
|
||||
round's baseline (its `parse-error`s on `` `assume``/`$error`/`(* async *)``
|
||||
constructs are gone even at `3bc61f9`, unrelated to this round). Built the
|
||||
release binary at `3bc61f9` (stashing the three `src` files) and at the full
|
||||
working tree, ran `corpus_check.sh` both times: **813/820 (99.1%) both times,
|
||||
byte-identical results TSV (`diff` empty), 0 verification errors, 0 crashes,
|
||||
both runs.** Expected and confirmed: this round touches no file under
|
||||
`vlog_formatter` or `vlog_parser`.
|
||||
|
||||
**Tests added.** `crates/vlog_refactor/tests/rename.rs::qa_a_bare_value_position_typo_reaches_an_unrelated_same_named_module`
|
||||
— kept, failing on purpose, as the regression repro for item 1.
|
||||
|
||||
### 2026-08-26 — QA agent, fix-round re-verification
|
||||
|
||||
**Verdict: committable.** The fix closes finding 1 exactly as claimed, every
|
||||
type-position win from the main round still resolves, the call-site map is
|
||||
complete (read every `bind_data_type` caller myself, found nothing it
|
||||
misses), and every corpus number in both READMEs re-derives to the digit from
|
||||
a harness independent of the dev's own `Tally` printer. All gates green,
|
||||
zero failing tests anywhere.
|
||||
|
||||
**1. Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets
|
||||
--workspace`: 0 warnings (confirmed by grepping the output for
|
||||
`warning`/`error` — none). `cargo test --workspace --no-fail-fast`: **0
|
||||
failed** (871 passed / 4 ignored in `lucisv_server`'s own count, every other
|
||||
crate's suite green, including the QA repro from the previous round, now
|
||||
flipped and passing). `cargo test -p vlog_formatter`, `-p vlog_linter`,
|
||||
`-p vlog_refactor`: green. `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
**2. The regression, attacked from three shapes beyond the shipped repro —
|
||||
all refused, both write and read.** Ran the flipped
|
||||
`a_bare_value_position_typo_never_reaches_an_unrelated_same_named_module`
|
||||
directly: passes, asserts the pre-round refusal message. Then wrote three
|
||||
throwaway probes (added, run, and removed after use — not shipped, per the
|
||||
previous round's own precedent with its diagnostic dump) exercising shapes
|
||||
the shipped suite does not:
|
||||
- An `if` condition (`always @* if (typo_name) w = 1;`) instead of an
|
||||
assignment LHS — `rename` refused with "not resolved to any declaration";
|
||||
`nav::definition` and `type_definition` both empty; `doc_reference_kind`
|
||||
reported `NotFound`.
|
||||
- A named port-connection value (`sub u0(.p(typo_name));`) — same three
|
||||
assertions, all held. Read `bind.rs:557` (`bind_connection`) to confirm
|
||||
this is the same `bind_opt_expr` → `ExprKind::Ident` → `Target::Lexical`
|
||||
path as the shipped repro, not a coincidence of one syntax.
|
||||
- `disable typo_block;` — the `bind.rs:1013` block-label site the dev's
|
||||
call-site map named explicitly as "left as `Target::Lexical`". Same three
|
||||
assertions, all held.
|
||||
|
||||
All three: `rename` refuses, `nav::definition` empty, `type_definition`
|
||||
empty. The regression is dead from every angle I could construct, not just
|
||||
the one shape the shipped test pins.
|
||||
|
||||
**3. The type-position wins, alive from every angle.** `cargo test -p
|
||||
lucisv_server type_def::` — 45 pre-existing tests green, unchanged verdicts,
|
||||
plus my 2 nav-emptiness probes and 1 new-win probe (47 total, see below).
|
||||
`cargo test -p vlog_refactor an_interface_renames_from_the_declaration_it_types_in_another_file`
|
||||
— green: the cross-file interface rename (declared in `bus_if.sv`, typed via
|
||||
`virtual bus_if vif;` and instantiated via `bus_if other ();` in `top.sv`,
|
||||
because the ANSI-header parser gap forces the body spelling) renames both the
|
||||
declaration and every use. New probe,
|
||||
`qa_probe_an_ansi_port_type_resolves_cross_file` (run, then removed): a
|
||||
genuine ANSI port — `module top(input logic clk, bus_if b);`, the interface
|
||||
port second because a directionless first port doesn't parse yet
|
||||
(`docs/features/type-definition/README.md` Handshake 2) — resolves the
|
||||
`bus_if` at `b`'s type through `doc_reference_kind == ExternalCandidate`,
|
||||
`nav::definition` non-empty, and `type_definition` non-empty, cross-file.
|
||||
This is the ANSI-port shape the call-site map claims (`bind.rs:393`) but no
|
||||
existing test exercised directly.
|
||||
|
||||
**4. Call-site map — verified by direct grep and read, not by trusting the
|
||||
prose.** `grep -n 'Target::Lexical\|Target::Type' crates/vlog_semantic/src/bind.rs`
|
||||
after excluding doc comments: **3** `Target::Lexical` construction sites
|
||||
(line 136 — a redeclaration inside `declare`, resolves before ever reaching
|
||||
`miss`; line 1017 — `disable`'s block label; line 1090 — `ExprKind::Ident`)
|
||||
and **1** `Target::Type` site (line 1231 — `bind_data_type`'s unqualified
|
||||
arm). This is a discrepancy worth flagging precisely: the brief characterized
|
||||
this as "exactly four `Target::Lexical` sites, twelve `bind_data_type`
|
||||
callers" and the work log's own heading says "all four, and only these four,
|
||||
exist" — but that "four" is the count of sites that *used to be*
|
||||
`Target::Lexical` before the fix (1223/1082/1009/128 in the pre-fix line
|
||||
numbering), one of which (1223) the fix moved to `Target::Type`. Read
|
||||
literally against the current tree, the count is 3 Lexical + 1 Type = 4
|
||||
combined, not 4 Lexical. The work log's own per-site bullets say this
|
||||
correctly ("changed to `Target::Type`" for the first one); only the summary
|
||||
sentence overstates it if read out of context. Not a defect in the code —
|
||||
the compiler-checked exhaustive match is what actually matters and it holds
|
||||
(next item) — but the phrasing should say "four sites total, three of which
|
||||
remain `Lexical`" rather than "four `Target::Lexical` sites" if the README is
|
||||
touched again.
|
||||
|
||||
`grep -rn '\bTarget\b' crates --include='*.rs'` excluding `ExternalTarget`/
|
||||
`rename::Target`/`RenameTarget`/prose: exactly one match site,
|
||||
`resolve.rs:12`'s `match &p.target`, confirmed exhaustive (compiles with no
|
||||
wildcard arm and no `#[allow]`).
|
||||
|
||||
`grep -n 'fn bind_data_type\|bind_data_type(' crates/vlog_semantic/src/bind.rs`
|
||||
finds **11** call sites, not 12 — matching the 11 categories the work log's
|
||||
prose actually lists (ANSI ports, header param ports, typedef alias, enum
|
||||
base, struct member, the shared declarator path, function return, tf args,
|
||||
out-of-body return, typed for-init, `ExprKind::Type`); "twelve" in the prose
|
||||
appears to be an off-by-one in the summary count, not a missing call site —
|
||||
I could not find a twelfth. Read all 11 callers end to end plus their
|
||||
transitive callers (`bind_declarators` is reached from `bind_data_decl`,
|
||||
`bind_port_decl`, and two `ParamDecl` sites at both item- and statement-level;
|
||||
`bind_tf_args` serves both `bind_function` and `bind_task`) looking
|
||||
specifically for the four shapes the task asked me to probe:
|
||||
- **`virtual interface` variables** — `virtual clk_rst_if vif;` is an
|
||||
ordinary `VarDecl` → `bind_data_decl` → `bind_declarators` →
|
||||
`bind_data_type` (line 516); the `virtual` keyword is held on
|
||||
`DataType::virtual_kw` separately by the parser so `ty.name` is the bare
|
||||
interface name. Covered — this is literally the shape the interface
|
||||
rename test exercises.
|
||||
- **`parameter type` defaults** — a `type` parameter's default type value
|
||||
parses as `ExprKind::Type`, reaching `bind_data_type` at line 1192.
|
||||
Covered, per the dev's own comment there.
|
||||
- **`struct packed` member types** — `TypedefKind::Struct`'s per-member
|
||||
loop calls `bind_data_type` on `m.ty` at line 475 before declaring each
|
||||
of the struct's declarators. Covered.
|
||||
- **tf args** — `bind_tf_args` (line 656) calls `bind_data_type` on `a.ty`
|
||||
for every task/function argument, called from both `bind_function` and
|
||||
`bind_task`. Covered.
|
||||
|
||||
I could not find a call site of `DataType` binding that bypasses
|
||||
`bind_data_type`. **Verdict: the map is exhaustive** for the four probed
|
||||
shapes and, as far as a full read of the file shows, for the language's
|
||||
type positions generally. The "twelve" vs. eleven count is the only
|
||||
inaccuracy found and it overstates rather than understates the coverage.
|
||||
|
||||
**5. Corpus numbers — every figure in both READMEs re-derives to the digit,
|
||||
independently.** Built a raw per-Resolution-variant counter (bypassing the
|
||||
dev's `Tally` entirely — counts `Resolution::Resolved`/`ExternalCandidate`/
|
||||
`InheritedCandidate`/`NotFound` directly off `sem.references()`), ran it at
|
||||
three states and popped/reapplied a `git stash` of the three `src` files
|
||||
between them (`bind.rs`/`resolve.rs`/`model.rs`/`workspace.rs`), then removed
|
||||
the probe:
|
||||
|
||||
| bucket | `3bc61f9` (mine) | shipped (mine) | README |
|
||||
|---|---:|---:|---:|
|
||||
| `Resolved` | 69 274 | 69 274 | 69 274 / 69 274 |
|
||||
| `ExternalCandidate` | 16 152 | 16 314 | 16 152 / 16 314 |
|
||||
| `InheritedCandidate` | 7 841 | 7 841 | 7 841 / 7 841 |
|
||||
| `NotFound` | 1 418 | 1 256 | 1 418 / 1 256 |
|
||||
|
||||
Bit-for-bit match, both states, both non-`InheritedCandidate` claims (the
|
||||
inherited bucket's bit-identical 7 841 reproduces independently) and the
|
||||
arithmetic join (16 152 + 1 418 = 17 570 = the promote-everything external
|
||||
count; 16 152 + 162 = 16 314; 1 418 − 162 = 1 256).
|
||||
|
||||
Went further than the minimum bar and reproduced the **middle** "promote
|
||||
everything" column too, by temporarily patching `resolve.rs`'s
|
||||
`Target::Lexical` arm to pass `promote: true` (mechanically the same
|
||||
behavior the first-cut round shipped, since `Target::Type` didn't exist yet
|
||||
to distinguish them) — ran, recorded, reverted the one line from a saved
|
||||
copy, and confirmed `git diff` showed zero net change to `resolve.rs`
|
||||
afterward:
|
||||
|
||||
| bucket | promote-everything (mine) | README |
|
||||
|---|---:|---:|
|
||||
| `ExternalCandidate` | 17 570 | 17 570 |
|
||||
| `InheritedCandidate` | 7 841 | 7 841 |
|
||||
| `NotFound` | 0 | 0 |
|
||||
|
||||
Also re-ran `the_corpus_index_finishes_most_external_references` at all three
|
||||
states (before/promote-everything/shipped) and matched every printed figure
|
||||
to the README's workspace-index table: handed 16 152→18 090→16 717 (all
|
||||
files), inherited-landed 0→520→403, nowhere-to-jump (all files)
|
||||
10 992→10 431→10 572, nowhere-to-jump (clean files) 10 794→10 235→10 376.
|
||||
|
||||
**The 141-given-back split (117 + 24), reproduced exactly.** Wrote a second
|
||||
throwaway probe splitting `resolve_external`'s landed overlay entries by
|
||||
`reference.is_inherited_candidate()`, ran at promote-everything and shipped:
|
||||
|
||||
| | promote-everything | shipped | delta |
|
||||
|---|---:|---:|---:|
|
||||
| inherited-landed | 520 | 403 | **117** |
|
||||
| external-landed | 14 460 | 14 436 | **24** |
|
||||
|
||||
117 + 24 = 141, matching the README's split exactly, independently derived
|
||||
(not by re-running the dev's own numbers, by counting landed overlay entries
|
||||
directly). Both throwaway probes (`qa_probe_raw_resolution_bucket_counts`,
|
||||
`qa_probe_landed_split_external_vs_inherited` in
|
||||
`crates/vlog_semantic/tests/workspace.rs`, and three more in
|
||||
`crates/vlog_refactor/tests/rename.rs` / `crates/lucisv_server/src/type_def.rs`
|
||||
for items 2–3 above) were removed from the working tree after use —
|
||||
diagnostic only, confirmed by `git diff --stat` returning to the dev's
|
||||
original fix-round shape before this entry was written.
|
||||
|
||||
**6. The six re-pointed assertions — all six checked against `3bc61f9`, not
|
||||
just three.** `git diff crates/vlog_semantic/tests/{semantics,classes}.rs`
|
||||
(default diff base is `3bc61f9`, since everything here is uncommitted on top
|
||||
of it) shows, for all six the work log names (`set_name`, `UVM_LOW`,
|
||||
`member_miss`, `held = 1`, the genvar `i`, `SOMETHING`): **either zero diff
|
||||
at all** (`member_miss`'s test has no diff whatsoever against `3bc61f9`) **or
|
||||
a comment-only diff** — the assertion lines themselves (`Resolution::
|
||||
InheritedCandidate { .. }`, `Resolution::NotFound`, the exact `paths` vectors)
|
||||
are byte-identical to `3bc61f9` in every one of the six; only explanatory
|
||||
comments were added, and in one case (`held = 1`) an assertion failure
|
||||
message string. None of the six assertion *values* are new inventions —
|
||||
every one is provably the pre-round value.
|
||||
|
||||
**7. README honesty.** The struck Assumptions bullet reads as an honest
|
||||
correction (strikethrough kept, correction inline, attributed to "QA finding
|
||||
1, 2026-08-26") rather than a silent edit. Both measured READMEs'
|
||||
resolution-bucket tables match my independent re-derivation to the digit
|
||||
(item 5). The cast-binds-no-reference gap is recorded explicitly in the fix
|
||||
round's work log ("Not a call site, worth recording: a cast's type...",
|
||||
"Out of scope here, noted for whoever picks it up") — confirmed by reading
|
||||
`bind.rs:1177`'s `ExprKind::Cast { expr, .. } => self.bind_expr(expr, scope)`,
|
||||
which indeed binds only the operand, dropping the casting type with no
|
||||
reference produced, unchanged by this round.
|
||||
|
||||
**8. Minor finding, not fixed (out of scope, prose-only).** The work log's
|
||||
call-site-map summary sentence says "exactly four `Target::Lexical` sites"
|
||||
where the current tree has three (plus one `Target::Type` the fourth became)
|
||||
— see item 4. Cosmetic; the per-site bullets underneath already say the
|
||||
right thing, and the exhaustive-match property the claim is *for* holds
|
||||
regardless. Left for the lead to wave through or ask for a one-word fix.
|
||||
|
||||
**Verdict: committable.** Finding 1 is closed and dead from every angle
|
||||
tested (assign RHS, if-condition, port-connection value, disable-label; both
|
||||
`rename` and `nav::definition`/`type_definition`). No new regression found.
|
||||
Every type-position win from the main round still resolves, including one
|
||||
shape (ANSI port) no existing test exercised directly. The call-site map is
|
||||
functionally exhaustive despite one prose miscount. Corpus arithmetic
|
||||
reproduces to the digit across all three states and the full given-back
|
||||
split. Gates are green with zero failing tests anywhere.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed both rounds' diffs, work logs and QA logs; re-ran all gates
|
||||
myself, clean. This feature is the workflow's best argument for itself.
|
||||
The main round delivered the Handshake and honestly re-measured stale
|
||||
baselines — and QA's adversarial pass then found the one thing that
|
||||
mattered: the promotion had quietly made rename, a write operation,
|
||||
reachable from a value-position name coincidence, disproving the work
|
||||
log's "same exposure as always" claim against the pre-round source. The
|
||||
fix round's answer is the right kind: a `Target::Type` variant that
|
||||
records where the fact "this is a type position" actually exists (one
|
||||
line in `bind_data_type`), a four-line behavior delta, `miss` restored
|
||||
verbatim, and the write path's refusal back — while every type-position
|
||||
win survives, the corpus join shows 418 clean-file references gained a
|
||||
target with none lost, and the 141 coincidence-answers given back are
|
||||
exactly the ones no one should want.
|
||||
|
||||
I read the promoted `lexical` and restored `miss` myself; the doc
|
||||
comment now argues the value/type asymmetry better than either brief
|
||||
did. QA's re-check killed the regression from three angles (assign,
|
||||
expression context, disable label), verified the call-site map by
|
||||
independent grep and caller reading, and reproduced every corpus figure
|
||||
to the digit including the 117+24 split. I fixed the two prose
|
||||
miscounts QA flagged (the four-Lexical-sites summary, twelve→eleven
|
||||
callers) in the work log directly, and un-clobbered one QA quotation my
|
||||
first fix had edited by mistake. The cast-binds-no-reference gap stays
|
||||
filed as pre-existing. `indexed_type` is gone, its guard with it, and
|
||||
the two handlers cannot drift because only one resolution path remains.
|
||||
Accepted as shipped.
|
||||
@@ -0,0 +1,291 @@
|
||||
# pull-diagnostics
|
||||
|
||||
## Goal
|
||||
|
||||
Serve diagnostics the modern way (LSP 3.17): the client asks
|
||||
`textDocument/diagnostic` for the buffer it is showing and
|
||||
`workspace/diagnostic` for the rest, when *it* decides — so the visible editor
|
||||
is prioritised, nothing is computed for a buffer nobody is looking at, and the
|
||||
client caches by `resultId` instead of re-drawing everything on every
|
||||
keystroke. lucisv had only the push model (`textDocument/publishDiagnostics`
|
||||
on every change). This round adds the pull model beside it, off the same
|
||||
parse+lint pass, and makes sure **one client is never served both** — two sets
|
||||
of squiggles for one file is the classic way to ship this feature wrong.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The capability is the switch.** A client that sent
|
||||
`textDocument.diagnostic` at initialize is a pulling client and is pushed
|
||||
*nothing at all*, ever. A client that did not keeps today's push behavior
|
||||
byte for byte. There is no setting: the protocol already asks the question.
|
||||
- **The `didClose` clear is not pushed to a pulling client either.** In the
|
||||
push model an empty publish is how a server erases what it drew, and that
|
||||
stays. In the pull model the client owns the whole lifecycle of what it
|
||||
pulled — it decides when to ask and drops a closed document's diagnostics
|
||||
itself (`vscode-languageclient`'s diagnostic feature does exactly this) —
|
||||
so a publish arriving at close would be the server's only push of the
|
||||
session and would land in a channel the client is not reading for this
|
||||
document. The gate therefore sits in `send_diagnostics`, which both callers
|
||||
go through: one place, no way to leak a push.
|
||||
- **`resultId` is a single generation counter, and nothing else.** It is
|
||||
bumped in `set_document` (a buffer's text changed) and in `reindex` (the
|
||||
workspace index changed). A pull whose `previousResultId` equals the
|
||||
current generation is answered `unchanged`; anything else is a full report.
|
||||
This is deliberately **coarser** than per-buffer versioning: editing file A
|
||||
invalidates the client's cached stamp for file B, which costs one extra
|
||||
full report — a cheap, correct answer. The error the coarse direction
|
||||
cannot make is the expensive one: a stale `unchanged` is a wrong squiggle
|
||||
left on screen. (The brief suggested `generation/doc-version`; the server
|
||||
does not track document versions at all — the sync path ignores them — so
|
||||
the second half would have been a constant. One number, documented, beats a
|
||||
format that implies a precision that is not there.) *(Still true after
|
||||
incremental sync, 2026-08-26: `DidChangeTextDocumentParams.version` is
|
||||
unread, and one notification is still exactly one generation bump however
|
||||
many ranges it carried.)*
|
||||
- **`inter_file_dependencies: true` is honest.** A save rebuilds the
|
||||
workspace index, and a buffer's diagnostics are computed against that index
|
||||
(`resolve_external` in `state.rs`), so a save in file A really can change
|
||||
what file B reports. That is exactly why `reindex` bumps the generation.
|
||||
- **`workspace/diagnostic` reports the open buffers only.** This server has
|
||||
never diagnosed a file it was not shown: `publish` is per open buffer, and
|
||||
`reindex` republishes only open buffers. Linting the whole workspace on a
|
||||
pull would be a parse of every in-scope file per request, on a request a
|
||||
client may send after every keystroke. So the workspace report is the open
|
||||
buffers, in URI order. **This is the honest limit of the feature**: a
|
||||
client using workspace diagnostics as its only source sees findings for
|
||||
files it has open, not for the project. Widening it is its own round, with
|
||||
its own cost model (and probably `workDoneProgress`, TODO §9b).
|
||||
- **No partial results, no streaming, and no
|
||||
`workspace/diagnostic/refresh`.** Partial results are not advertised, so no
|
||||
client will ask for them. A refresh request would let the server tell a
|
||||
pulling client "ask again, the index moved"; it is not sent, so such a
|
||||
client sees post-save changes at its own next pull. Stated because it is
|
||||
the one place the pull model is *lazier* than the push model this replaces.
|
||||
- **Both models answer from one function.** `Server::diagnostics_of` is the
|
||||
single computation (`diagnostics::all`, i.e. parse errors, then the
|
||||
missing-closer warnings, then lint), and `publish` and both pull handlers
|
||||
all call it. A second conversion path would be a second set of off-by-one
|
||||
bugs; pinned by `both_models_say_exactly_the_same_thing_about_a_buffer`.
|
||||
- **A pull for a buffer that is not open is an empty full report**, not an
|
||||
error: the client asked about a document this server knows nothing about,
|
||||
and "no findings" is the true answer.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::main`
|
||||
|
||||
- `capabilities()` gains `diagnostic_provider: DiagnosticServerCapabilities::Options`
|
||||
with `identifier: "lucisv"` (the same string every diagnostic's `source`
|
||||
carries — one constant, `diagnostics::SOURCE`), `inter_file_dependencies:
|
||||
true`, `workspace_diagnostics: true`.
|
||||
- `pull_diagnostics_support(&InitializeParams)` reads
|
||||
`text_document.diagnostic`; its two fields (dynamic registration, related
|
||||
documents) are about things this server does not do, so the presence of the
|
||||
capability is the whole of the statement.
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `ClientAbilities` gains `pull_diagnostics: bool`.
|
||||
- `Server` gains `generation: u64`, bumped in `set_document` and `reindex`.
|
||||
- New handlers: `DocumentDiagnosticRequest`, `WorkspaceDiagnosticRequest`.
|
||||
- `send_diagnostics` is now the single gate on pushing anything.
|
||||
- `diagnostics_of(uri)` is the one computation both models read.
|
||||
|
||||
### `diagnostics`
|
||||
|
||||
Unchanged. `diagnostics::all` and `diagnostics::SOURCE` are consumed as they
|
||||
already were; nothing was added to that module.
|
||||
|
||||
### `editors/*`
|
||||
|
||||
No change. `vscode-languageclient` 9.x advertises the diagnostic capability
|
||||
and drives the pull itself, so the VS Code extension switches models with no
|
||||
edit — and `editors/vscode/smoke.js` sends `capabilities: {}`, so it stays on
|
||||
the push model and keeps asserting what it always asserted.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `DiagnosticOptions` advertised, identifier pinned to the publish source
|
||||
- [x] `textDocument/diagnostic`: full report with a `resultId`, `unchanged`
|
||||
when the generation stands
|
||||
- [x] `workspace/diagnostic`: open buffers in URI order, `previousResultIds`
|
||||
honoured per file
|
||||
- [x] Push suppressed for a pulling client — including the `didClose` clear
|
||||
- [x] One computation behind both models
|
||||
- [x] Tests: never-pushed, push-client-unchanged, full-then-unchanged-then-
|
||||
full, reindex moves the stamp, unopened buffer, workspace report and
|
||||
its stamps, both models identical
|
||||
- [ ] Not done, deliberately: workspace diagnostics do not cover unopened
|
||||
workspace files — see Assumptions.
|
||||
- [ ] Not done, deliberately: no `workspace/diagnostic/refresh`, no partial
|
||||
results, no `relatedDocuments`.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9a
|
||||
|
||||
- **The gate went into `send_diagnostics`, not into `publish`.** Both the
|
||||
change-driven publish and the `didClose` clear go through it, so one `if`
|
||||
covers every push the server can make. Putting it in `publish` would have
|
||||
left the close path pushing to a pulling client.
|
||||
- **One generation counter** instead of the suggested
|
||||
`generation/doc-version` pair: the server does not track document versions
|
||||
(`DidChangeTextDocumentParams.version` is ignored under full-text sync), so
|
||||
the second component would always have been the same string. Recorded in
|
||||
Assumptions as a deliberate deviation from the brief, with the failure mode
|
||||
it cannot have.
|
||||
- **URI order in the workspace report** because `open_uris()` comes off a
|
||||
`HashMap` and would otherwise shuffle between two pulls of identical state,
|
||||
which reads as churn to a human and makes a test flaky.
|
||||
- **`version: None`** on the workspace reports: the protocol wants the
|
||||
document version the diagnostics were computed for, and this server has
|
||||
none to give.
|
||||
- Files touched: `crates/lucisv_server/src/server.rs`,
|
||||
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`, and
|
||||
the capability table in `docs/features/lucisv-server/README.md` (the
|
||||
`publishDiagnostics` row is now conditional). Nothing in `diagnostics.rs`,
|
||||
`lint.rs` or any engine crate.
|
||||
|
||||
**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings),
|
||||
`cargo test --workspace`, `node editors/vscode/smoke.js` (still on the push
|
||||
model, unchanged) — all clean. 8 new unit tests in `server.rs`, 2 in `main.rs`
|
||||
(the options, and the capability probe), and one e2e session
|
||||
(`a_pulling_client_is_answered_and_never_pushed_over_the_wire`) whose central
|
||||
assertion is that the *next thing the server says* after a pull request is the
|
||||
answer and not a push.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent, §9a
|
||||
|
||||
**Re-ran the dev's verification, clean.** `cargo fmt --all -- --check`,
|
||||
`cargo clippy --all-targets --workspace` (zero warnings, rebuilt from a
|
||||
touched source tree so this wasn't answered from cache), `cargo test
|
||||
--workspace` (3 full runs, no failures), `node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` (exit 0, still on the push model as claimed).
|
||||
|
||||
**The stale-`unchanged` hunt — this was the main assignment.** Traced every
|
||||
input `Server::diagnostics_of` reads (`diagnostics::all`: parse errors +
|
||||
`pairs::missing_end_diagnostics` + `lint::diagnostics`, all three reading only
|
||||
`doc.text`/`doc.tokens`/`doc.tree`/`doc.line_index`/`doc.semantics` —
|
||||
confirmed by reading `diagnostics.rs`, `lint.rs`'s `context()`, and
|
||||
`vlog_linter::registry::default_rules()`) against every event that can reach
|
||||
the server without going through `set_document` (which bumps `generation`)
|
||||
or `reindex` (same):
|
||||
|
||||
- `DidChangeConfiguration` (`server.rs`'s `notification` handler): the
|
||||
settings it can change are `line_length`, `indent`, `exclude`, `filelist`,
|
||||
`inline_templates` (`settings.rs`). Checked each against what
|
||||
`diagnostics_of` actually reads: `line_length`/`indent` only ever reach
|
||||
`format.rs` (the formatting request), never the lint or parse-error path;
|
||||
`inline_templates` is ghost-text only, read nowhere near diagnostics.
|
||||
`exclude`/`filelist` *do* trigger `self.reindex()` when
|
||||
`set_client_settings` reports a real change — which bumps `generation`
|
||||
anyway, so even though this pair does not currently touch a single open
|
||||
buffer's own diagnostics, the code already treats it as invalidating.
|
||||
**No live bug**, but see the finding below.
|
||||
- `lucisv.toml` picked up via file watchers (`DidChangeWatchedFiles`,
|
||||
`watch::touches_scope`): any matched source file always routes to
|
||||
`self.reindex()`, unconditionally bumping `generation` — including for a
|
||||
file nobody has open. Coarser than necessary (an edit to an unrelated file
|
||||
invalidates every open buffer's stamp) but never stale-in-the-dangerous-
|
||||
direction.
|
||||
- `reindex` paths generally (save, watched-file change, exclude/filelist
|
||||
change, `didOpen` with no workspace root): all funnel through the one
|
||||
`reindex()` method, which increments `generation` unconditionally before
|
||||
doing anything else — verified by reading the method body, not just the
|
||||
call sites.
|
||||
- **`doc.external`** (`resolve_external`, the thing the README's own
|
||||
Assumptions section cites as *why* `inter_file_dependencies: true` is
|
||||
honest) is read only by `hover.rs` and `nav.rs` — grepped every non-test
|
||||
use. **Diagnostics never read it.** So today, no lint rule or parse error
|
||||
actually depends on the workspace index at all; the README's justification
|
||||
for `inter_file_dependencies` describes a coupling that does not yet exist
|
||||
in the diagnostics path (it exists for hover/definition). This is not
|
||||
presently a correctness bug — bumping `generation` on `reindex` is the
|
||||
*safe* direction regardless of whether anything currently needs it — but
|
||||
the README's Assumptions text over-claims the *reason*. **Finding
|
||||
(informational, not a defect):** the real invariant this feature depends on
|
||||
is "every diagnostic-affecting input bumps `generation`," which today is
|
||||
satisfied only because diagnostics happen to have no configurable/workspace-
|
||||
dependent input at all. `lint.rs`'s own doc comment says as much
|
||||
("Selection (`--select`/`--ignore`) has no `lucisv.toml` key yet"). The
|
||||
day a lint rule becomes configurable or cross-file-aware, whoever adds it
|
||||
must also audit whether it needs to bump `generation` — nothing today
|
||||
enforces that, and this feature's tests cannot catch a violation of an
|
||||
invariant about code that doesn't exist yet. Flagged for the lead/dev to
|
||||
decide whether to soften the Assumptions wording; not fixed directly since
|
||||
it is a wording call, not a code defect.
|
||||
- Conclusion: **no reproducible stale-`unchanged` sequence exists against
|
||||
the current codebase.** I looked for one (attempted repro via a
|
||||
`lineLength` push mid-session expecting it to be invisible to a pull
|
||||
client — it is, but it is also invisible to a *push* client for the same
|
||||
reason: line length never touched diagnostics before this feature either)
|
||||
and could not construct one.
|
||||
|
||||
**Push/pull exclusivity, verified structurally, not just by test.** Grepped
|
||||
`server.rs` for every call site of `send_diagnostics` (the only place
|
||||
`PublishDiagnosticsParams` is constructed): exactly two — `publish()` (open/
|
||||
change/reindex) and the `didClose` clear. Both funnel through
|
||||
`send_diagnostics`, which is the single `if self.abilities.pull_diagnostics
|
||||
{ return; }` gate. There is no third path that could bypass it. Existing
|
||||
test `a_pulling_client_is_never_pushed_diagnostics` already exercises
|
||||
didOpen/didChange/didSave/didClose; added no new test here since the
|
||||
structural argument (one gate, two call sites, both covered) is stronger
|
||||
than another sequence test would be.
|
||||
|
||||
**`workspace/diagnostic` edge cases — added three tests** in `server.rs`,
|
||||
all passing:
|
||||
|
||||
- `an_empty_workspace_answers_a_well_formed_empty_report` — no open buffers
|
||||
at all: `items` is `[]`, not an error, not a missing field.
|
||||
- `a_previous_result_id_for_a_uri_that_is_since_closed_is_harmless` — a
|
||||
`previousResultIds` entry for a URI the client closed after its last pull:
|
||||
the closed URI is simply absent from the answer (it is not among
|
||||
`open_uris()`), never phantom-reported, never an error.
|
||||
- `a_previous_result_id_for_a_uri_never_seen_is_ignored` — a
|
||||
`previousResultIds` entry for a URI this server never opened: ignored,
|
||||
does not disturb the report for URIs that *are* open.
|
||||
|
||||
**`applyEdit`-adjacent note:** `diagnostics_of`'s early-return
|
||||
(`self.workspace.document(uri).map(...).unwrap_or_default()`) means a pull
|
||||
for an unopened buffer is `Full` with empty `items` rather than `Unchanged`
|
||||
— checked this always answers `Full` regardless of what `previousResultId`
|
||||
the client sends for an unopened URI, which is correct (an unopened buffer's
|
||||
"generation" was never established for that client, so there is nothing to
|
||||
consider unchanged).
|
||||
|
||||
**CLAUDE.md compliance:** no `unwrap()`/`expect()`/`panic!` in the new
|
||||
non-test code in `server.rs`/`main.rs`; `ClientAbilities::pull_diagnostics`
|
||||
and `Server::generation`/`applying` (shared with apply-edit) carry doc
|
||||
comments; `DiagnosticServerCapabilities` construction and
|
||||
`pull_diagnostics_support` read capabilities defensively
|
||||
(`.as_ref()`/`.is_some_and()`), confirmed no panic on
|
||||
`InitializeParams::default()` by the existing test. README has all seven
|
||||
sections; TODO.md checkbox is checked with item text unchanged.
|
||||
|
||||
**Verdict: no blocking findings.** One informational finding recorded above
|
||||
(Assumptions text describes a coupling that isn't live code yet — cosmetic,
|
||||
not a defect) for the lead to weigh in on. Three new edge-case tests added,
|
||||
all passing; the exhaustive input trace found no stale-`unchanged` path.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. One computation (`diagnostics_of`) behind both models, one push gate
|
||||
(`send_diagnostics`), one generation counter as the whole `resultId` — the
|
||||
boring shape CLAUDE.md asks for, and QA's exhaustive input trace confirms
|
||||
the coarse counter cannot produce a stale `unchanged` today.
|
||||
|
||||
On QA's informational finding (the Assumptions justify
|
||||
`inter_file_dependencies: true` via the index, which the diagnostics path
|
||||
does not read yet): accepted as written. Bumping on reindex is the safe
|
||||
direction and the semantic-lint roadmap (§9's future rounds, cross-file
|
||||
rules) is precisely what will make the index a real input; the README
|
||||
already states the true invariant — *every diagnostic-affecting input bumps
|
||||
`generation`* — and whoever adds a lint config key or a cross-file rule
|
||||
inherits it. The `both_models_say_exactly_the_same_thing_about_a_buffer`
|
||||
test is the right tripwire for divergence. No change requested. Accepted
|
||||
as shipped.
|
||||
@@ -0,0 +1,227 @@
|
||||
# selection-range
|
||||
|
||||
## Goal
|
||||
|
||||
`textDocument/selectionRange` — expand-selection, the keystroke (⌃⇧→ in VS
|
||||
Code, `<Plug>(expand_region)` shapes in Vim) that grows the selection one
|
||||
syntactic step at a time: the identifier, then the statement, then the block,
|
||||
then the module, then the file. Editors fall back to a word/bracket heuristic
|
||||
without it, which in Verilog means expanding through `begin`/`end` never
|
||||
works. Cheap for lucisv: every range the chain needs is already computed for
|
||||
something else, so this is a new arrangement of existing answers, not new
|
||||
analysis.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Four sources of ranges, one chain.** For a byte offset the server
|
||||
collects: the token that covers it (`Document.tokens`), the AST spans that
|
||||
cover it (items and statements, walked top-down and pruned to the branch
|
||||
that contains the offset), the matched scope pairs that cover it
|
||||
(`pairs::analyze`, the rainbow's own matcher), and the whole file. They are
|
||||
sorted by width and filtered down to what actually nests.
|
||||
- **No expression step.** The brief allows skipping it, and it is skipped:
|
||||
`ExprKind` has ~40 variants and walking them is a large, dull function
|
||||
whose only user would be this. The visible cost is that inside
|
||||
`a + b * (c - d)` the chain jumps from the token straight to the statement.
|
||||
The token step covers the common "select the identifier" case, and adding
|
||||
expressions later is additive — one more source of spans, no change to the
|
||||
chain machinery. Recorded so nobody thinks it was overlooked.
|
||||
- **The chain must strictly nest, and is filtered rather than trusted.** Two
|
||||
ranges that both cover the cursor need not contain one another: a tolerant
|
||||
parse can leave an item span overlapping a scope pair. LSP requires every
|
||||
step to contain its child, so a range that does not enclose what was kept
|
||||
before it is dropped. That filter is also what removes the duplicates the
|
||||
four sources produce for the same construct (a `module` is an item span
|
||||
*and* a scope pair).
|
||||
- **Zero-width ranges are dropped.** A step that selects nothing is not a
|
||||
step a user can see. The one exception is the degenerate chain in an empty
|
||||
buffer, where the file range itself is empty.
|
||||
- **Containment includes the end offset.** A cursor sitting just after a word
|
||||
is treated as on that word — that is where the keystroke is usually
|
||||
pressed. The consequence at a boundary between two adjacent constructs is
|
||||
that both cover the cursor; the nesting filter then keeps whichever is
|
||||
smaller and drops the other, which is a valid chain either way.
|
||||
- **Every requested position is answered, in order.** A multi-cursor editor
|
||||
matches answers to cursors by index, so a skipped position would silently
|
||||
mis-associate every later one. A position that resolves to nothing else
|
||||
still gets the one-step file chain.
|
||||
- **A file that does not lex answers the file range.** `Document::new` leaves
|
||||
`tokens` empty and the tree an error leaf there, so three of the four
|
||||
sources give nothing — and the fourth is enough to satisfy the protocol.
|
||||
- **The walk is per-request and bounded.** It descends only into the node
|
||||
that covers the offset, so it visits the cursor's ancestors and their
|
||||
immediate siblings' spans, not the file. Recursion depth is bounded by the
|
||||
parser's own nesting limit (`docs/features/recursion-limit/README.md`): a
|
||||
tree this walks is a tree the parser built.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::selection` (new module)
|
||||
|
||||
```rust
|
||||
pub fn selection_ranges(doc: &Document, positions: &[Position]) -> Vec<SelectionRange>;
|
||||
```
|
||||
|
||||
Pure function over one `Document`, in the shape `folding.rs` and `pairs.rs`
|
||||
already have: no `Workspace`, no client, unit-testable on a string.
|
||||
|
||||
### `lucisv_server::main`
|
||||
|
||||
`capabilities()` gains `selection_range_provider:
|
||||
SelectionRangeProviderCapability::Simple(true)`. Nothing is configurable and
|
||||
every position is answered, so there are no options to send.
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
One handler on `SelectionRangeRequest::METHOD`, answering `null` for a
|
||||
document that is not open — the same shape `foldingRange` and
|
||||
`documentSymbol` already use.
|
||||
|
||||
### `vlog_parser::ast`
|
||||
|
||||
Consumed read-only: `Item`/`ItemKind`, `Stmt`/`StmtKind`, `GenBlock`,
|
||||
`GenElse`, `GenIf`, and the `span` fields on all of them. No change requested
|
||||
of the parser. The walk duplicates the shape of `vlog_linter::visit`, which
|
||||
is `pub(crate)` there and therefore not reusable; the copy here is ~60 lines
|
||||
and prunes by offset, which the linter's does not.
|
||||
|
||||
### `editors/*`
|
||||
|
||||
No change: both VS Code and Neovim bind expand-selection to this request out
|
||||
of the box.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/lucisv_server/src/selection.rs`: token, AST, scope-pair and
|
||||
file sources; nesting filter; linked-chain construction
|
||||
- [x] `selection_range_provider` advertised
|
||||
- [x] `textDocument/selectionRange` handled, `null` for an unopened buffer
|
||||
- [x] Tests: 14 unit tests in `selection.rs` (including an exhaustive
|
||||
"every step strictly contains its child, at every offset of a file"
|
||||
sweep) and 2 in `server.rs`
|
||||
- [ ] Not done, deliberately: no expression-level step — see Assumptions.
|
||||
- [ ] Not done, deliberately: no port/parameter-list step. `AnsiPort` and
|
||||
`ParamPort` carry spans, so it is a two-line addition when someone
|
||||
wants it; today the chain inside a header goes token → module.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9a
|
||||
|
||||
- **Collect-then-filter, rather than build the chain while walking.** The
|
||||
walk cannot know whether a scope pair will land between two of its own
|
||||
spans, and a tolerant parse can produce spans that overlap rather than
|
||||
nest. Throwing every covering range into one list and keeping what nests is
|
||||
both shorter and provably correct — the invariant is checked in one place,
|
||||
and `every_step_strictly_contains_the_one_before_it` sweeps every offset of
|
||||
a nested file to prove it.
|
||||
- **Scope pairs are kept even though the AST usually covers the same
|
||||
constructs.** They are what still works when the parse went wrong, which is
|
||||
exactly the buffer a user is mid-edit in
|
||||
(`an_unclosed_scope_still_expands_through_what_did_close`).
|
||||
- **The AST walk was copied, not shared.** `vlog_linter::visit` is
|
||||
`pub(crate)`; making it public is a change to another crate for one caller,
|
||||
which the brief forbids and CLAUDE.md discourages. The copy is smaller than
|
||||
the original because it prunes on the offset.
|
||||
- Files touched: `crates/lucisv_server/src/selection.rs` (new),
|
||||
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/src/server.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, and the capability table in
|
||||
`docs/features/lucisv-server/README.md`.
|
||||
|
||||
**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings),
|
||||
`cargo test --workspace`, `node editors/vscode/smoke.js` — all clean. 14 unit
|
||||
tests in `selection.rs`, 2 in `server.rs`, and one e2e session
|
||||
(`selection_ranges_round_trip_over_the_wire`) proving the chain survives JSON
|
||||
encoding as nested `parent` objects.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent, §9a
|
||||
|
||||
**Re-ran the dev's verification, clean.** `cargo fmt --all -- --check`,
|
||||
`cargo clippy --all-targets --workspace` (zero warnings), `cargo test
|
||||
--workspace` (3 full runs, no failures), `node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` (exit 0).
|
||||
|
||||
**The strictness claim, checked, not just trusted.**
|
||||
`every_step_strictly_contains_the_one_before_it` (`selection.rs`) does assert
|
||||
`outer != inner` in addition to containment, at every offset `0..=text.len()`
|
||||
of a nested fixture — it is a real strictness sweep, not a containment-only
|
||||
check with a misleading name.
|
||||
|
||||
**Invariants from the assignment, checked one by one against existing
|
||||
tests** (all present, all passing, no gaps found that needed a new test):
|
||||
|
||||
- Multi-position order: `several_positions_are_answered_position_for_position`
|
||||
asks three positions out of source order and checks each answer against
|
||||
its own position by index.
|
||||
- Position past EOF: `a_position_past_the_end_of_the_file_clamps_into_it`.
|
||||
- UTF-16 / surrogate-pair-adjacent columns: `a_multibyte_line_keeps_the_
|
||||
columns_in_utf16` uses `é` (2-byte UTF-8, 1 UTF-16 unit) **and** `🎉`
|
||||
(4-byte UTF-8, a UTF-16 *surrogate pair*) on the same line before the
|
||||
target token — this is the specific case the assignment called out, and
|
||||
it is already exercised, not just the single-BMP-character case.
|
||||
- Empty file: `an_empty_file_still_answers_one_degenerate_chain`.
|
||||
- A file that fails to parse: `a_file_that_does_not_lex_still_answers_the_
|
||||
file_range` (confirms `doc.tokens.is_empty()` as the premise, then checks
|
||||
the fallback) and `an_unclosed_scope_still_expands_through_what_did_close`
|
||||
(a tolerant *partial* parse — checks the scope-pair source still supplies
|
||||
a step when the AST cannot).
|
||||
- Capability reading: `selection_range_provider` is `Simple(true)`, no
|
||||
conditional read of client capabilities at all — nothing to break here.
|
||||
|
||||
**Went beyond the assignment's list: a corpus sweep.** Every hand-written
|
||||
test above uses a handcrafted fixture designed to exercise one specific
|
||||
construct — none of them can catch a real-world construct the four span
|
||||
sources disagree about in a way nobody thought to write a test for. Added
|
||||
`every_step_strictly_nests_over_the_real_corpus` to `selection.rs`: walks
|
||||
every `.sv`/`.v`/`.svh`/`.vh` file under `corpus/` (skipped gracefully if not
|
||||
checked out, matching this crate's other corpus tests), samples 8 evenly
|
||||
spaced offsets per file, and asserts the same strict-nesting-plus-whole-file-
|
||||
closure invariant the hand-written sweep proves on small fixtures. Result:
|
||||
**860 files, 6,880 positions, zero panics, invariant held everywhere**,
|
||||
runtime ~1.6s (fits comfortably in the default `cargo test` budget, not
|
||||
`#[ignore]`d). This is real coverage of syntax nobody wrote a fixture for —
|
||||
generate-for loops, deeply nested casex/casez, `ifdef`-gated regions, etc.
|
||||
— that the four hand-picked test files cannot reach.
|
||||
|
||||
**Two positions I could not distinguish as bugs vs. accepted design,
|
||||
recorded rather than "fixed":**
|
||||
|
||||
- `covers()`'s inclusive end (`span.start <= offset && offset <= span.end`)
|
||||
means a cursor at the exact boundary between two adjacent siblings sees
|
||||
both as covering it; the nesting filter then keeps whichever is smaller.
|
||||
This is explicitly called out in the Assumptions as intentional and
|
||||
provably safe (the filter guarantees strict nesting regardless of which
|
||||
one wins), so not re-litigated.
|
||||
- The AST walk in `items`/`statement` is a hand-copy of
|
||||
`vlog_linter::visit`'s shape rather than a shared function, per the
|
||||
Assumptions' stated reason (`visit` is `pub(crate)` in another crate).
|
||||
Confirmed by reading `vlog_linter/src/visit.rs`'s visibility — it is
|
||||
indeed `pub(crate)`, so the stated constraint is real, not just asserted.
|
||||
|
||||
**CLAUDE.md compliance:** `selection.rs`'s only `pub` item
|
||||
(`selection_ranges`) has a doc comment; no `unwrap()`/`expect()`/`panic!`
|
||||
outside `#[cfg(test)]` in `selection.rs`, or in the touched parts of
|
||||
`server.rs`/`main.rs`. README has all seven sections; TODO.md checkbox is
|
||||
checked with item text unchanged.
|
||||
|
||||
**Verdict: no blocking findings.** This is the most heavily self-tested of
|
||||
the three features already (14 unit tests, an exhaustive small-file sweep);
|
||||
the corpus sweep added here is a genuine widening of coverage, not a
|
||||
response to a suspected bug, and it found none.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. `nested()`'s sort-then-keep-what-strictly-contains is the right
|
||||
five-line answer to the overlapping-sources problem, and the fallback chain
|
||||
for an empty/unlexable buffer honors the protocol's one-answer-per-position
|
||||
requirement without a special case in the dispatch. Skipping the expression
|
||||
step was the correct scope call — the token step already gives "select the
|
||||
identifier", and forty `ExprKind` arms is a follow-up, not a blocker. QA's
|
||||
860-file corpus sweep (6,880 positions, invariant held everywhere) is
|
||||
exactly the kind of evidence this repo's rounds are supposed to produce.
|
||||
Accepted as shipped.
|
||||
@@ -0,0 +1,460 @@
|
||||
# semantic-tokens-delta
|
||||
|
||||
## Goal
|
||||
|
||||
Serve the two semantic-token requests this server advertised nothing for:
|
||||
`textDocument/semanticTokens/range`, so the first paint of a large file costs
|
||||
the visible lines rather than the whole file, and
|
||||
`textDocument/semanticTokens/full/delta`, so a client that already holds an
|
||||
answer is told what *changed* instead of being handed the file's whole token
|
||||
set on every keystroke (TODO.md §9b). Both are the same tokenizer that already
|
||||
served `full`: the classification pass now produces an intermediate
|
||||
**absolute** form — line, column, length, type, modifiers — a range answer
|
||||
filters that form and the one encoder delta-encodes whatever is left, so the
|
||||
three requests cannot disagree about what a token is. The delta itself is the
|
||||
standard prefix/suffix trim rust-analyzer uses, with the one invariant that
|
||||
matters tested as a property: applying the returned edits to the old data
|
||||
reproduces the new data exactly.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A range answer is a self-contained `SemanticTokens`, not a slice of the
|
||||
full one.** The relative encoding restarts from the start of the *document*
|
||||
exactly as a full answer's does; only the tokens outside the range are
|
||||
missing. So the first kept token's `deltaLine`/`deltaStart` are absolute,
|
||||
which is why the encoder had to be split out of the classifier rather than
|
||||
the range answer being a sub-slice of the full one. (A client that pasted a
|
||||
slice out of a full answer would draw line 40's tokens on line 0 — pinned by
|
||||
`a_range_answer_re_encodes_from_the_start_of_the_document`.)
|
||||
- **A token that only overlaps the range is kept whole.** The client asked
|
||||
which tokens to draw, not where to cut them, and a `length` trimmed to the
|
||||
range would be a lie about the source. Tokens are single-line by
|
||||
construction (every span is split at `\n` before encoding — the rule
|
||||
`no_token_ever_spans_a_line_break` has pinned since the first round), so
|
||||
"overlap" never has to reason across lines.
|
||||
- **An empty range answers nothing.** A zero-width range covers no characters,
|
||||
so nothing intersects it. Without the explicit guard the overlap test
|
||||
degenerates into *containment* and a collapsed cursor position would answer
|
||||
with the token it sits inside — tokens the client has no room to draw. No
|
||||
editor is known to send one; it is guarded because the arithmetic invites it.
|
||||
- **`resultId`s are minted per answer, from one counter, and are not the
|
||||
diagnostics generation.** A `previousResultId` must name the exact data the
|
||||
client holds, which the pull-diagnostics generation cannot do: that one is
|
||||
bumped by a buffer change *and* by an index rebuild, and it is shared by
|
||||
every open buffer. This counter counts *answers* — one per full and per
|
||||
delta, whatever the buffer — so an id is unambiguous and never reused.
|
||||
Answering the same unchanged buffer twice mints two ids and one empty edit
|
||||
list; that is a string per answer, not a recomputation.
|
||||
- **A range answer is deliberately *not* remembered and carries no
|
||||
`resultId`.** It is a partial view; a later delta computed against it would
|
||||
be a diff against something the client never held whole. Only `full` and
|
||||
`full/delta` write the remembered answer.
|
||||
- **One answer per buffer is remembered, and it dies with the buffer.** A
|
||||
client that asks again has moved on from the previous answer, so there is no
|
||||
history to keep. `didClose` drops the entry, so the map is bounded by the
|
||||
number of *open* buffers, not by the number of files ever opened. A delta
|
||||
naming an id from before a close is answered in full.
|
||||
- **Mismatched, absent or stale `previousResultId` → a full answer.**
|
||||
`SemanticTokensFullDeltaResult` allows either, and a delta against data we
|
||||
cannot see would be a guess. That is also what makes a server restart, a
|
||||
client restart and a `didClose`/`didOpen` cycle all self-healing.
|
||||
- **Minimality beyond the prefix/suffix trim is not attempted.** One
|
||||
`SemanticTokensEdit` replaces everything between the common prefix and the
|
||||
common suffix. A real diff would describe an insertion in the middle of a
|
||||
file as two small edits, but the encoding is *relative*: the first token
|
||||
after an inserted line carries a changed `deltaLine`, so a "middle"
|
||||
insertion already invalidates only that one token plus the ones that moved,
|
||||
and everything below it re-matches as suffix. rust-analyzer answers the same
|
||||
way. The payload is what the client re-parses, not what it re-renders.
|
||||
- **The buffer that does not lex still round-trips.** It has no tokens at all
|
||||
(the lexer is all-or-nothing), so a delta out of it deletes everything and a
|
||||
delta back into it inserts everything. Mid-keystroke this is the common
|
||||
case, and it is tested in both directions.
|
||||
- **`workspace/semanticTokens/refresh` is out of scope and not sent.** That
|
||||
request exists for the case where the *server* decides the client's tokens
|
||||
went stale without the client having edited anything — an index rebuild
|
||||
changing how a name resolves, say. The case that matters (the user typing)
|
||||
makes the client re-pull on its own. Recorded as backlog below, not built.
|
||||
|
||||
## The delta algorithm, and the bug it is easy to write
|
||||
|
||||
```
|
||||
prefix = how many leading tokens are equal
|
||||
old_rest, new_rest = both lists past the prefix
|
||||
suffix = how many trailing tokens of old_rest and new_rest are equal
|
||||
edit = replace old_rest[..old_rest.len() - suffix]
|
||||
with new_rest[..new_rest.len() - suffix]
|
||||
```
|
||||
|
||||
**The suffix is counted over what the prefix left, never over the whole
|
||||
lists.** That is the cap, and skipping it is *the* classic bug in this
|
||||
algorithm: when the two token lists repeat themselves, a suffix counted over
|
||||
the whole lists claims tokens the prefix has already claimed, and
|
||||
`new_rest[..new_rest.len() - suffix]` then runs backwards — a panic in debug,
|
||||
an edit that deletes a region it also re-inserts in the general case.
|
||||
|
||||
This is not hypothetical for Verilog. The encoding is relative, so **identical
|
||||
lines encode to identical tokens**: line 2 and line 3 of
|
||||
|
||||
```systemverilog
|
||||
module m;
|
||||
wire a;
|
||||
wire a;
|
||||
wire a;
|
||||
endmodule
|
||||
```
|
||||
|
||||
are byte-for-byte the same five numbers. Deleting one of those lines is
|
||||
exactly the `old = [A, B, A]`, `new = [A]` shape. Both the hand-built shape and
|
||||
the real-Verilog one are tested (`the_suffix_is_capped_so_it_cannot_overlap_the_prefix`,
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens`), and both were
|
||||
confirmed to **fail** — by panic — against a deliberately uncapped
|
||||
implementation before being committed to.
|
||||
|
||||
**`start` and `deleteCount` count numbers, not tokens.** The wire carries a
|
||||
flat `u32` array of five numbers per token, and an edit indexes *that*. Both
|
||||
are five times a token index (`FIELDS`), pinned by
|
||||
`an_edits_indices_count_numbers_and_not_tokens` — the off-by-five here does not
|
||||
fail loudly, it silently corrupts a client's cache.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `lsp-types` (0.97, no new dependency):**
|
||||
`SemanticTokensRangeParams`, `SemanticTokensRangeResult`,
|
||||
`SemanticTokensDeltaParams`, `SemanticTokensFullDeltaResult`,
|
||||
`SemanticTokensDelta`, `SemanticTokensEdit`, and — for the capability —
|
||||
`SemanticTokensOptions { range: Option<bool>, full: Option<SemanticTokensFullOptions> }`
|
||||
with `SemanticTokensFullOptions::Delta { delta: Some(true) }`. The `Delta`
|
||||
variant is the full capability *plus* deltas, not a replacement:
|
||||
`semanticTokens/full` is still served and still answered.
|
||||
|
||||
**Consumed from other crates: nothing new.** `vlog_parser`, `vlog_semantic`,
|
||||
`vlog_formatter`, `vlog_refactor`, `lucisv_core` are untouched, as is every
|
||||
file outside `crates/lucisv_server`. This feature is protocol arithmetic over a
|
||||
classification that already existed.
|
||||
|
||||
**Changed inside this crate, for whoever reads `tokens.rs` next:**
|
||||
|
||||
- `tokens::semantic_tokens(doc)` now returns `Vec<SemanticToken>` (the `data`)
|
||||
rather than a whole `SemanticTokens`. The `resultId` is the server's to
|
||||
stamp, because only the server knows what it remembered — the module owns
|
||||
no state.
|
||||
- New: `tokens::semantic_tokens_in_range(doc, range) -> Vec<SemanticToken>`
|
||||
and `tokens::delta(old, new) -> Vec<SemanticTokensEdit>`.
|
||||
- Private and new: `Absolute` (line, start, length, type, modifiers),
|
||||
`absolute(doc)`, `flatten(pieces, doc)`, `within(tokens, range)`,
|
||||
`encode(&[Absolute])`. `encode` is pure — the same tokens always encode the
|
||||
same way, whether they are the whole file's or the handful a range kept —
|
||||
which is what lets `full` and `range` share it.
|
||||
- `Server` gains `tokens: HashMap<Uri, TokenAnswer>` and `token_results: u64`,
|
||||
written only by `remember_tokens` and cleared only by `didClose`. **Neither
|
||||
touches `generation`**: every token request is read-only, and bumping the
|
||||
diagnostics generation on a viewport repaint would throw away a pulling
|
||||
client's whole diagnostic cache several times a second
|
||||
(`no_token_request_bumps_the_diagnostics_generation`).
|
||||
|
||||
**Requested of other modules:** nothing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `tokens.rs` split into classification → `Absolute` → filter → `encode`,
|
||||
with `full` and `range` sharing all four steps.
|
||||
- [x] `textDocument/semanticTokens/range`, advertised as `range: Some(true)`,
|
||||
re-encoded from the document start, overlap kept whole, empty range
|
||||
empty.
|
||||
- [x] `textDocument/semanticTokens/full/delta`, advertised as
|
||||
`full: Delta { delta: Some(true) }`, single-edit prefix/suffix diff with
|
||||
the suffix capped.
|
||||
- [x] Per-buffer `resultId` bookkeeping: minted per answer, stored by both
|
||||
`full` and `full/delta`, dropped on `didClose`.
|
||||
- [x] `semanticTokens/full` returns a `resultId` now (it did not before), so a
|
||||
client may mix the two requests.
|
||||
- [x] Round-trip property tests: append, delete, middle change, identical,
|
||||
complete replacement, unlexable buffer both ways, empty buffer both
|
||||
ways, the prefix/suffix-overlap shapes, and a 300-iteration fixed-seed
|
||||
randomized sweep over real Verilog buffers.
|
||||
- [x] Range/full agreement as a property over two corpus files, in 40-line
|
||||
windows (the size of an editor viewport request), stated line-wise so it
|
||||
is independent of the handler's own overlap test.
|
||||
- [x] Server-level tests through the `Session` harness, and one e2e round trip
|
||||
through the real binary.
|
||||
- [x] TODO.md §9b box, this README, and the `lucisv-server` capability table.
|
||||
- [ ] **Not done, deliberately:** `workspace/semanticTokens/refresh`. Nothing
|
||||
the server learns on its own (an index rebuild changing how a name
|
||||
resolves) currently invalidates a client's token cache; when something
|
||||
does, this is the request to send.
|
||||
- [ ] **Not done:** partial results / `workDoneProgress` on any of the three
|
||||
requests. The whole-file answer is sub-millisecond at Verilog file
|
||||
sizes; streaming it in chunks would be complexity for nobody.
|
||||
- [ ] **Not measured:** whether the delta payload is actually smaller than the
|
||||
full one for a typical edit. It must be by construction for an edit near
|
||||
either end of a file, and it is at worst the full set plus one edit
|
||||
header for an edit near the middle. No benchmark was written.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent
|
||||
|
||||
- **Read first**: `CLAUDE.md`, `docs/features/lucisv-server/README.md` (the
|
||||
capability table and the `semanticTokens` mapping section),
|
||||
`docs/features/pull-diagnostics/README.md` for the house style on result
|
||||
ids, `tokens.rs` in full, and `lsp-types` 0.97's `semantic_tokens.rs` for
|
||||
the exact shapes (`range` is a plain `Option<bool>` there, not an options
|
||||
struct; `SemanticTokensFullDeltaResult` has three variants and we use two).
|
||||
- **The refactor came before either handler.** `semantic_tokens` was one
|
||||
function doing classification, line splitting, sorting and delta encoding,
|
||||
and the range answer needs to cut in between the third and the fourth. It
|
||||
is now `absolute(doc)` (classify + split + sort, producing `Absolute`),
|
||||
`within(tokens, range)` (the filter) and `encode(&[Absolute])` (pure delta
|
||||
encoding). The eleven pre-existing token tests were left with their
|
||||
assertions untouched — only the test *helpers* moved, because
|
||||
`semantic_tokens` now hands back the `data` rather than a `SemanticTokens`
|
||||
— which is the evidence that the factoring changed no behavior.
|
||||
- **The overlap cap was verified by breaking it, not by reasoning.** After
|
||||
writing the capped `delta`, the suffix computation was temporarily changed
|
||||
to count over the whole lists and the suite re-run: three tests failed with
|
||||
a subtraction-overflow panic
|
||||
(`the_suffix_is_capped_so_it_cannot_overlap_the_prefix`,
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens` via the shared
|
||||
round-trip helper, and `every_pair_of_real_buffers_round_trips_through_its_delta`
|
||||
— the randomized sweep found it on its own, which is why the `BODY` line
|
||||
pool deliberately repeats `" wire a;"`). The implementation was then
|
||||
restored. CLAUDE.md's invariant #4 is about `verify.rs`, but its spirit —
|
||||
a normalization ships with the attack that would forgive a corruption —
|
||||
is what this check is.
|
||||
- **The one design decision that is not the obvious one**: a range answer
|
||||
carries no `resultId` and is not remembered. It would have been one line to
|
||||
remember it, and it would have silently made the next delta a diff against
|
||||
a partial view. Written down in Assumptions and pinned by
|
||||
`a_range_request_is_not_the_answer_a_later_delta_is_computed_against`.
|
||||
- **The empty-range guard was written for the arithmetic, not for a client.**
|
||||
`from < range.end && range.start < to` is the interval-overlap test only
|
||||
when the range is non-empty; for a collapsed range it is containment. One
|
||||
early return, one test, one sentence in Assumptions.
|
||||
- **`generation` was deliberately not touched**, and the test for it says so
|
||||
twice: directly on the field, and observably through a pull that is still
|
||||
`unchanged` after a token request. Pull diagnostics' README asks every new
|
||||
feature to audit whether it bumps the generation; the audit's answer here
|
||||
is no, and this is where it is recorded.
|
||||
- **Nothing outside this crate moved.** No new dependency, no version bump,
|
||||
no engine change, no `editors/` change (`smoke.js`'s capability list already
|
||||
contains `semanticTokensProvider`, and it passes against the built binary).
|
||||
- **Results.** `cargo test --workspace`: **1793 passed, 0 failed** (1764
|
||||
before — +29: 18 unit tests in `tokens.rs`, 9 in `server.rs`, 1 in
|
||||
`main.rs`, 1 e2e). `cargo clippy --all-targets`: silent.
|
||||
`cargo fmt --all -- --check`: clean. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: OK. No commits.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent
|
||||
|
||||
**Gates re-run, from a clean rebuild** (`touch`ed the three changed source
|
||||
files first so clippy could not reuse a stale cached pass):
|
||||
`cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace
|
||||
-- -D warnings`: silent. `cargo test --workspace`: **1793 passed, 0 failed**
|
||||
before QA's own additions, **1802 passed, 0 failed** after (9 QA tests added,
|
||||
see below). `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: OK. All match the dev's claims.
|
||||
|
||||
**1. The delta invariant, independently — verified clean, tests added.**
|
||||
Wrote a second applier, `independent_apply` (`tokens.rs`, in `mod tests`),
|
||||
that shares no code with the dev's `apply_edits`: it walks `SemanticToken`s
|
||||
rather than the flat `u32` array, slices by hand (`extend_from_slice`)
|
||||
rather than calling `Vec::splice`, and separately asserts `edit.start` /
|
||||
`edit.delete_count` divide evenly by `FIELDS` — a second, independent check
|
||||
of the ×5 claim. Cross-checked the two appliers directly against each other
|
||||
over 200 random pairs (`qa_the_two_independently_written_appliers_never_disagree`)
|
||||
— **they never disagreed**. Ran QA's applier over: both ends changing at
|
||||
once, middle-only, identical, complete replacement, old empty, new empty,
|
||||
and a single-token file, both directions
|
||||
(`qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes`).
|
||||
Ran a second randomized sweep, different generator (xorshift64, not the
|
||||
dev's LCG), different seed (`0xDEAD_BEEF_1234_5678` vs `0x5eed`), and a
|
||||
different line pool that adds a block comment spanning lines, a continued
|
||||
`` `define``, and a `generate`/`endgenerate` block — pieces whose token
|
||||
*count* is not simply one-line-in-N-tokens-out
|
||||
(`qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips`).
|
||||
All green. **Verdict: verified clean.**
|
||||
|
||||
**2. The overlap cap, re-verified — reproduced, with one correction to the
|
||||
work log's specifics.** Reproduced the dev's breakage myself: changed the
|
||||
suffix computation in `delta` (`tokens.rs:304-305` at the time) from
|
||||
counting over `old_rest`/`new_rest` to counting over the whole `old`/`new`,
|
||||
re-ran `cargo test -p lucisv_server`, and restored it — the file is back to
|
||||
its pre-experiment text (diffed against git to confirm no leftover debug
|
||||
code). Result: **10 tests failed** by `attempt to subtract with overflow`
|
||||
panic, including `the_suffix_is_capped_so_it_cannot_overlap_the_prefix`, the
|
||||
dev's own sweep `every_pair_of_real_buffers_round_trips_through_its_delta`,
|
||||
and — usefully — all of QA's own new round-trip tests from surface 1 above,
|
||||
which is exactly the cross-check CLAUDE.md invariant #4 asks for (an
|
||||
independently-written attack finding the same class of bug). **One
|
||||
correction**: the work log names
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens` as one of the
|
||||
three tests that failed in the dev's own experiment. Re-running the same
|
||||
breakage, this specific test **passes** — traced with a temporary debug
|
||||
print (`old.len()=9 new.len()=5 prefix=4 suffix=1` and the mirror), the
|
||||
type/declaration-modifier mismatch a few tokens in breaks the naive
|
||||
whole-list suffix match before it ever grows past `old_rest`'s length, so no
|
||||
overflow occurs for this particular buffer pair under this literal
|
||||
interpretation of "count over the whole lists." This is a documentation
|
||||
accuracy nit, not a safety finding — the class of bug is still real and
|
||||
still demonstrated by the other two named tests plus QA's own — but the dev
|
||||
should either soften the claim (the failure was seen at the time, with
|
||||
whatever the code looked like then, or via a different breakage) or drop
|
||||
that one test's name from the sentence. **Then tried to construct a shape
|
||||
that defeats the capped implementation and produces wrong data instead of a
|
||||
panic**: with the cap in place, `suffix = old_rest.iter().rev().zip(new_rest.iter().rev())…`
|
||||
is inherently bounded by `min(old_rest.len(), new_rest.len())` because
|
||||
`Iterator::zip` itself stops at the shorter side — so `deleted =
|
||||
old_rest.len() - suffix` can never underflow, and the algebra (`old[:prefix]
|
||||
+ inserted + old_rest[deleted..]` reduces to exactly `new`) holds
|
||||
unconditionally, not just on the tested shapes. Tried anyway: long shared
|
||||
prefix and long shared suffix overlapping in the middle over periodic data
|
||||
(the `[A,A,A,A,A]` → `[A,A,A]` shape, and variants with the periodic run at
|
||||
different positions) — all round-trip correctly, consistent with the
|
||||
argument above. **Verdict: verified clean; the cap is load-bearing (10
|
||||
failures without it) and, with it, the round-trip property holds by
|
||||
construction, not merely on the cases anyone thought to test.**
|
||||
|
||||
**3. u32 semantics — verified clean.** `an_edits_indices_count_numbers_and_not_tokens`
|
||||
(dev's) and QA's own `independent_apply` (which asserts `% FIELDS == 0`
|
||||
before dividing, on every edit, in every test above, including the 500
|
||||
combined sweep iterations) agree the ×5 conversion is exact and consistently
|
||||
applied. Wire shape: an unchanged buffer answers `edits: []` (present, empty
|
||||
— `a_delta_over_an_unchanged_buffer_is_an_empty_edit_list`,
|
||||
`server.rs:2508`) and a stale/unknown/absent-state id answers the
|
||||
`Tokens` variant with no `edits` key at all
|
||||
(`a_delta_naming_an_id_we_do_not_hold_is_answered_in_full`) — both legal per
|
||||
`SemanticTokensFullDeltaResult`'s untagged enum, and both are pinned by
|
||||
existing tests, not left to accident.
|
||||
|
||||
**4. Range self-containment — verified clean, gaps closed with new tests.**
|
||||
The dev covered: full-document range, absolute first-token deltas, overlap
|
||||
kept whole at the *start* boundary, empty range, whitespace-only *lines*,
|
||||
range never leaking outside tokens, and a 40-line-window corpus sweep (which
|
||||
QA re-ran directly against the checked-out `corpus/` — genuinely exercised,
|
||||
not skipped: `windows_checked` well over 20). QA added the three shapes the
|
||||
list asked for that were not yet pinned: (a) overlap kept whole at the *end*
|
||||
boundary, mirroring the dev's start-boundary test
|
||||
(`qa_a_range_ending_mid_token_keeps_that_token_whole`); (b) a range on a line
|
||||
*with* tokens, covering only the whitespace (plus an unemitted `=`) between
|
||||
two of them — not an empty line
|
||||
(`qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty`);
|
||||
(c) a reversed range (`start > end`) — `within`'s guard
|
||||
(`range.start >= range.end`) is symmetric to this by construction since
|
||||
`Position` derives `Ord` over `(line, character)` lexicographically, so this
|
||||
was already total and already answered empty, but nothing pinned it before
|
||||
now (`qa_a_reversed_range_is_total_and_answers_nothing`). All pass.
|
||||
**Verdict: verified clean.**
|
||||
|
||||
**5. State lifecycle — verified clean, two gaps closed with new tests.** The
|
||||
dev covered: didClose+reopen with the old id → full, memory dropped on
|
||||
close (`server.rs:784`, `self.tokens.remove(&uri)`, confirmed keyed by
|
||||
`Uri` and removed, not just marked stale), and the unopened-buffer → null
|
||||
convention for all three request kinds
|
||||
(`every_token_request_for_a_buffer_that_is_not_open_answers_null`, which
|
||||
also asserts the map stays empty). QA added: (a) two buffers open at once,
|
||||
buffer A's id presented to buffer B — answered in full, not edits computed
|
||||
against A's data, and closing A leaves B's own remembered state untouched
|
||||
(`qa_two_open_buffers_ids_do_not_cross_contaminate`); worth noting as a
|
||||
observation rather than a bug: presenting a foreign id to B *does* mint a
|
||||
fresh id for B and overwrite B's own remembered answer (every answer does,
|
||||
by design — "Answering the same unchanged buffer twice mints two ids"), so
|
||||
the first version of this test asserted something the design doesn't
|
||||
promise (that `id_b` keeps working) — fixed once understood, noted here so
|
||||
the next reader doesn't trip on the same assumption. (b) `full → delta →
|
||||
full → delta → full` stays consistent across three edits
|
||||
(`qa_full_delta_full_delta_stays_consistent_across_edits`), and separately,
|
||||
a `full/delta` answer's *own* `resultId` chains directly into the next delta
|
||||
without ever going back through `full`
|
||||
(`qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between`)
|
||||
— checked against `ground_truth`, a helper that reads the document straight
|
||||
through `tokens::semantic_tokens` and bypasses the request dispatch (and
|
||||
thus the very `tokens`/`token_results` bookkeeping under test) entirely, so
|
||||
the check does not depend on the server's own memory being right. All pass.
|
||||
**Verdict: verified clean.**
|
||||
|
||||
**6. No behavior change for existing clients — verified clean, two ways.**
|
||||
(a) Direct code comparison: `classify`, `modifiers`, `identifier_type`,
|
||||
`symbol_type`, `collect_trivia`, `split_lines`, `token_types` and
|
||||
`token_modifiers` are byte-for-byte identical between
|
||||
`git show 80b9afd:crates/lucisv_server/src/tokens.rs` and the new file; the
|
||||
new `flatten`+`encode` pair is the old single `encode` function split at
|
||||
exactly the line-splitting/sorting boundary, with no logic added or
|
||||
removed. (b) Empirical, at the binary level: built the pre-refactor commit
|
||||
in a separate worktree (`git worktree add`, removed after), drove both the
|
||||
old and the new `lucisv-server` binaries over stdio with the same
|
||||
`textDocument/semanticTokens/full` request against a real corpus file
|
||||
(`corpus/picorv32/picorv32.v`, 41,325 tokens), and diffed the `data` arrays:
|
||||
**byte-for-byte identical**; the only difference in the response is the new
|
||||
`resultId` field, which the old binary did not send at all. The legend
|
||||
(`token_types`/`token_modifiers`) is likewise unchanged (confirmed both by
|
||||
the code diff and by `the_semantic_token_capability_asks_for_ranges_and_for_deltas`
|
||||
asserting length 14). **Verdict: verified clean — this is about as strong
|
||||
as evidence gets for "the refactor changed no behavior."**
|
||||
|
||||
**7. CLAUDE.md compliance — verified clean.** `grep`-checked all non-test
|
||||
code in `tokens.rs`, `server.rs`, `main.rs` for `.unwrap()`, `.expect(`,
|
||||
`panic!`: none. No `#[allow]` added anywhere in the diff. No `unsafe`
|
||||
anywhere in the diff. The two new public functions
|
||||
(`semantic_tokens_in_range`, `delta`) both carry doc comments explaining
|
||||
what/why. The feature README has each of the six required sections exactly
|
||||
once (plus one extra, non-required "The delta algorithm…" section, which is
|
||||
additive and not a substitute for any required one). `TODO.md`'s item text
|
||||
is unchanged save the checkbox and an appended `→` summary — the original
|
||||
sentence is intact verbatim.
|
||||
|
||||
**Fixes made directly (small, per the QA remit):** none needed in the
|
||||
dev's own code — every finding above was either "verified clean" or a
|
||||
documentation-accuracy nit (item 2) recorded rather than edited, since
|
||||
CLAUDE.md reserves the Work log for the dev agent's own account of what it
|
||||
did and why, and the specific breakage the dev saw is not reproducible
|
||||
after the fact to know which description would be truer. QA did fix one bug
|
||||
in **QA's own** first draft of `qa_two_open_buffers_ids_do_not_cross_contaminate`
|
||||
(a wrong assumption about `id_b` surviving a cross-request, see item 5)
|
||||
before it ever reached this log.
|
||||
|
||||
**Tests added this round:** 9, all passing, workspace total 1793 → 1802.
|
||||
`tokens.rs`: `qa_the_two_independently_written_appliers_never_disagree`,
|
||||
`qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes`,
|
||||
`qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips`,
|
||||
`qa_a_range_ending_mid_token_keeps_that_token_whole`,
|
||||
`qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty`,
|
||||
`qa_a_reversed_range_is_total_and_answers_nothing`. `server.rs`:
|
||||
`qa_two_open_buffers_ids_do_not_cross_contaminate`,
|
||||
`qa_full_delta_full_delta_stays_consistent_across_edits`,
|
||||
`qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between`.
|
||||
|
||||
**Overall verdict: committable as-is.** No corruption, non-idempotency,
|
||||
dropped-comment, or safety-net-widening risk found — this feature does not
|
||||
touch `verify.rs`, the formatter, or anything outside `crates/lucisv_server`,
|
||||
and every claim in the dev's work log checked out except the one test name
|
||||
in item 2, which is cosmetic. All gates green, all new and old tests green,
|
||||
one empirical binary-level spot check green.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(1802 workspace tests, 0 failed), clean. The refactor is the right seam:
|
||||
one tokenizer, one pure encoder, and range/full provably cannot drift —
|
||||
QA's byte-for-byte comparison of a 41k-token corpus file against the
|
||||
pre-refactor binary is the strongest possible form of "the factoring
|
||||
changed nothing". The delta design's judgment calls are all correct:
|
||||
range answers carrying no resultId (a delta must never diff against a
|
||||
partial view), a per-answer counter separate from the shared diagnostics
|
||||
generation, and prefix/suffix-with-cap over anything cleverer — with the
|
||||
round-trip property, not minimality, as the contract.
|
||||
|
||||
Two QA results deserve the record: the two independently written edit
|
||||
appliers never disagreed across 200 random pairs, and the overlap cap was
|
||||
broken on purpose twice (dev and QA separately) with the suite catching
|
||||
it both times. One cosmetic correction accepted from the QA log: the work
|
||||
log names `repeated_lines_of_verilog_are_the_same_trap_on_real_tokens`
|
||||
among the tests that fail with the cap reverted; QA's re-run shows that
|
||||
particular pair breaks the match earlier and that test passes — the trap
|
||||
is real but is caught by the other ten failures. The work log stands as
|
||||
the dev's account, with the QA log as the precise version. Accepted as
|
||||
shipped.
|
||||
@@ -0,0 +1,784 @@
|
||||
# type-definition
|
||||
|
||||
## Goal
|
||||
|
||||
`textDocument/typeDefinition` (TODO.md §9c): from a name to the declaration of
|
||||
that name's **type**. Go-to-definition answers "where does this name come
|
||||
from"; this answers "where does this name's *type* come from" — from
|
||||
`my_pkg::state_t s;` to the `typedef` of `state_t`, from `bus_if bus` or
|
||||
`virtual bus_if vif` to the `interface bus_if`, from the instance name of
|
||||
`sub u_sub (...)` to `module sub`, and from `my_cls h;` to `class my_cls`. It
|
||||
is the second-most-used navigation key in an editor after F12, it is exactly
|
||||
the jump a Verilog reader wants when a signal is a package enum declared three
|
||||
files away, and — this is why it is cheap — the answer is a location
|
||||
`textDocument/definition` already knows how to compute. Everything this
|
||||
feature adds is *which offset to ask about*.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A declaration's type is written as an identifier, and `vlog_semantic`
|
||||
recorded it as a use.** `bind.rs::bind_data_type` calls `use_name` for every
|
||||
non-keyword type name, searching the window from the start of the
|
||||
declaration to the first name it declares. This feature finds that same
|
||||
window from the parse tree and picks the reference the binder left in it. A
|
||||
keyword type (`logic`, `wire`, `int`) is never a reference, which is what
|
||||
makes "a built-in has no type definition" fall out with no special case.
|
||||
- **One hop, never a chain.** With `typedef state_t alias_t; alias_t x;` the
|
||||
cursor on `x` lands on `alias_t`'s typedef, not on `state_t`'s. That is what
|
||||
every editor's go-to-type-definition does; the user presses the key again for
|
||||
the next hop, and each hop is a place they can read. Chasing the chain to its
|
||||
root would land somewhere the source never mentioned.
|
||||
- **The cursor on a type name answers for that name.** `state_t` in
|
||||
`state_t s;` is already a type, so its type definition is its own
|
||||
declaration — the same location F12 gives there. Pinned by a test either
|
||||
way, since it is the one position where "definition" and "type definition"
|
||||
visibly coincide.
|
||||
- **A declaration name is not a use.** The cursor on the `alias_t` *of*
|
||||
`typedef state_t alias_t;` takes the hop its declaration offers (`state_t`)
|
||||
rather than answering itself, which would waste the keystroke.
|
||||
- **A `module`, `interface` and `program` are one AST node and one
|
||||
`SymbolKind::Module`**, so an interface is reached by exactly the code that
|
||||
reaches a module.
|
||||
- **The tree is the tolerant parse.** A declaration inside an `Error` node is
|
||||
no declaration at all and answers nothing — the same degradation every other
|
||||
tree-reading handler has (`docs/features/error-recovery/README.md`).
|
||||
- **An `InheritedCandidate` in a *type position* is a lexical miss, not an
|
||||
answer.** `resolve.rs`'s `miss` turns *every* miss inside a class carrying an
|
||||
`extends` into `Resolution::InheritedCandidate`, whether or not the name has
|
||||
anything to do with inheritance — so in a type window it means only "a base
|
||||
class *might* declare this type". `vlog_semantic` never chases a base chain
|
||||
(in this file or out of it: `lexical` walks `scope.parent`, which is lexical
|
||||
nesting, and `miss` records the base's *name* and stops), so no layer can
|
||||
turn that into a location, and the workspace's file-scope type of that name
|
||||
is the best honest answer available. **Since 2026-08-26 that answer comes
|
||||
from the overlay itself**, which tries the paths such a miss now carries
|
||||
(`docs/features/overlay-promotion/README.md`) — the reasoning is unchanged,
|
||||
only the layer that acts on it. This is assumed, not enforced: a base class
|
||||
that genuinely declares a nested type of the same name would be the better
|
||||
answer, and nothing here can produce it — but nothing displaces it either,
|
||||
because a resolved name never reaches the sweep. The day `vlog_semantic` does
|
||||
chase a base, such a reference becomes `Resolution::Resolved` and
|
||||
`definition` answers it directly. Pinned by
|
||||
`an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:** `ast::{Item, ItemKind, Module, PortList,
|
||||
AnsiPort, ParamPort, TfArg, DataType, Declarator, Typedef, TypedefKind,
|
||||
Instantiation, GenIf, GenElse, GenBlock, Stmt, StmtKind}` and `TextRange`.
|
||||
Read-only; nothing was changed.
|
||||
|
||||
**Consumed from `vlog_semantic`:** `Semantics::{references, reference_at,
|
||||
symbol}`, `Reference::{name, name_span, resolved}` and `SymbolKind`.
|
||||
Read-only; nothing was changed. (Until 2026-08-26 this also read
|
||||
`Resolution::{NotFound, InheritedCandidate}` and `WorkspaceIndex::{units,
|
||||
path}` for the `indexed_type` fallback; request 1 below landed and the
|
||||
fallback is gone.)
|
||||
|
||||
**Consumed from this crate:** `nav::definition` (the whole answer),
|
||||
`nav::symbol_at` — widened from private to `pub(crate)` so the two handlers
|
||||
cannot disagree about what a position names — and `locate::location`.
|
||||
|
||||
**Promised:** `type_def::type_definition(ws, uri, offset) -> Vec<Location>`,
|
||||
serving `server.rs`'s `GotoTypeDefinition` arm. Same answer shape as
|
||||
`GotoDefinition`: an array in every case, empty where there is nothing to jump
|
||||
to, every candidate where the workspace declares the name twice, and an empty
|
||||
array (not `null`) for a buffer the server was never sent.
|
||||
|
||||
**Requested of other modules** — neither blocked the original round, and
|
||||
neither was done there:
|
||||
|
||||
1. ~~**`vlog_semantic`: report an unresolved *unqualified* name as an external
|
||||
candidate, not as a bare lexical miss.**~~ **Delivered 2026-08-26 by
|
||||
`overlay-promotion`** (`docs/features/overlay-promotion/README.md`): a miss
|
||||
on a name written in a **type** position — which is every name this feature
|
||||
ever asks about — carries the bare name as its last candidate path in both
|
||||
miss spellings, so the workspace overlay answers them. (A miss in a *value*
|
||||
position does not, which is what keeps a bare expression identifier from
|
||||
matching a unit on name alone.) `indexed_type` — its qualifier guard and
|
||||
its kind filter with it — is deleted. `type_definition` is now literally
|
||||
`nav::definition` of the type name's offset and nothing else. One test
|
||||
changed behavior with it: a `package` of the type's name is now answered
|
||||
exactly as `definition` answers it, because the shared overlay does not
|
||||
filter by kind and the private fallback did (argued in that feature's
|
||||
Assumptions). The original request read: `resolve.rs`'s `lexical` miss ends
|
||||
in `Resolution::NotFound` whenever the file collected no import paths on the
|
||||
way out — or, inside a class with an `extends`, in
|
||||
`Resolution::InheritedCandidate` — and neither reaches `resolve_external`,
|
||||
so the workspace overlay never sees the name. That is precisely how an
|
||||
`interface` is written (`bus_if bus;` — interfaces live at file scope, not
|
||||
in packages) and how a package-less `class` is used, so the two headline
|
||||
cross-file cases of this feature would answer nothing; and the
|
||||
`InheritedCandidate` half covers nearly every UVM class, since almost all of
|
||||
them extend something. The ask: for a `Target::Lexical` miss, emit
|
||||
`ExternalCandidate { paths: vec![name] }` — the same shape `Target::Module`
|
||||
already emits — **in both spellings**, i.e. also carry the bare name in the
|
||||
`paths` of an `InheritedCandidate`, so the index's unit table finishes it
|
||||
without losing the recorded base. Until then this feature asks the index
|
||||
itself, in one function (`indexed_type`) fenced by three conditions: only
|
||||
for a reference the file reported as one of those two misses, only for a
|
||||
**file-scope** declaration, and only for the kinds that can be a type
|
||||
(`Module`, `Class`, `Typedef` — a `package` of that name is not one). When
|
||||
the request above lands, that function is deleted and nothing else in this
|
||||
module changes. *(It landed; the function is gone and nothing else in this
|
||||
module changed.)*
|
||||
2. ~~**`vlog_parser`: an ANSI header whose *first* port carries no direction
|
||||
does not parse.**~~ **Delivered 2026-08-26 by `ansi-first-port`**
|
||||
(`docs/features/ansi-first-port/README.md`): the port list is now
|
||||
classified ANSI-or-not by what *follows* the first identifier, so all three
|
||||
shapes parse into ordinary `AnsiPort`s with `dir: None`, and
|
||||
`an_interface_port_reaches_its_interface` was flipped to write the
|
||||
interface port first (with the second-port ordering kept as its own
|
||||
assertion). Two tests were added here with it — a modport-qualified port
|
||||
and a package-scoped first port. The original request read: `module m
|
||||
(bus_if bus, input logic clk);` becomes an `Error` item, while `module m
|
||||
(input logic clk, bus_if bus);` parses fine — the list is classified
|
||||
ANSI-or-not from its first element, and a bare `type name` pair reads as
|
||||
neither a non-ANSI name list nor a directed port. `module m (bus_if.mp
|
||||
bus)` (a modport-qualified port) and `module m (my_pkg::state_t s)` do not
|
||||
parse either. Not this feature's to fix, and not a regression it caused:
|
||||
the tests here write the interface port second and say why.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/lucisv_server/src/type_def.rs`: the offset redirection, the
|
||||
declaration walk, and (until 2026-08-26) the index fallback.
|
||||
- [x] `type_definition_provider` advertised (`TypeDefinitionProviderCapability::Simple(true)`).
|
||||
- [x] `GotoTypeDefinition` dispatched in `server.rs`, on `GotoDefinition`'s
|
||||
conventions exactly.
|
||||
- [x] `nav::symbol_at` shared rather than re-implemented.
|
||||
- [x] 24 unit tests: typedef, enum/struct typedef, class handle (module item
|
||||
and method body), module instance, interface instance / port / `virtual`
|
||||
handle, header parameter, task argument, generate block, `pkg::t`,
|
||||
`import pkg::*` + bare name, cross-file interface, cross-file class,
|
||||
built-ins, a package that is not a type, a refused qualified name, an
|
||||
unopened buffer, a position on no name, ambiguity, UTF-16 positions,
|
||||
one-hop aliasing.
|
||||
- [x] **Fix round (2026-08-26):** `indexed_type`'s fence widened to accept
|
||||
`Resolution::InheritedCandidate` as well as `NotFound`, closing the QA
|
||||
finding below (a cross-file type used as a member of any `extends`-ing
|
||||
class — nearly every UVM class — answered nothing). 4 tests added, QA's
|
||||
regression test flipped, corpus spot-check assertions flipped positive.
|
||||
- [x] **Fallback deleted (2026-08-26, `overlay-promotion`):** Handshake request
|
||||
1 landed in `vlog_semantic`, so `indexed_type` — fence, qualifier guard
|
||||
and all — is gone and `type_definition` is `nav::definition` of the type
|
||||
name's offset, nothing more. Every test in the suite still passes; two
|
||||
were renamed and one changed behavior (a `package` of the type's name is
|
||||
now answered as `definition` answers it), each argued in that feature's
|
||||
work log.
|
||||
- [x] **Handshake 2 landed (2026-08-26, `ansi-first-port`):** the three header
|
||||
shapes parse, so `an_interface_port_reaches_its_interface` writes the
|
||||
interface port first (both orderings asserted), and two tests joined it —
|
||||
`a_modport_qualified_port_reaches_its_interface` and
|
||||
`a_package_scoped_first_port_reaches_its_typedef`. `type_span` matches a
|
||||
type name by the half before its `.` as well as by its last `::`
|
||||
segment, which is the one production line that changed. 47 tests.
|
||||
- [x] One e2e round trip: the capability in the real handshake, a cross-file
|
||||
package typedef, and a built-in answered with an empty array.
|
||||
- [x] TODO.md §9c checkbox; `docs/features/lucisv-server/README.md` capability
|
||||
table.
|
||||
- [ ] **Not done, deliberately:** a function's *return* type is not a site — a
|
||||
cursor on `f` in `function state_t f();` answers nothing. It is a
|
||||
defensible answer to give and a defensible one to withhold, and giving it
|
||||
needs a guard (the cursor must be in the header, not in the body) that
|
||||
the other sites do not, so it waits for somebody to ask for it.
|
||||
- [ ] **Not done, deliberately:** a `bind` directive's instance. Its name is
|
||||
declared into another module's scope, so this file is not the one to
|
||||
answer for it (`docs/features/bind/README.md`).
|
||||
- [ ] **Not done:** a member's type (`x.field`, `h.member`). `vlog_semantic`
|
||||
does not resolve member access at all, so there is no symbol to ask about
|
||||
— the same boundary hover and `references` stop at.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent
|
||||
|
||||
- **Read the semantic layer before writing anything, and the key question came
|
||||
back "no, but".** A `Symbol` carries no type: its `decl_span` is its
|
||||
*declarator* (`bind.rs::bind_declarators` passes `d.span`), so the type name
|
||||
is outside every span the symbol table holds, and there is no `type` field
|
||||
anywhere in `model.rs`. What the crate *does* have is the type name as an
|
||||
ordinary `Reference` — `bind_data_type` calls `use_name` on it, resolved
|
||||
lexically or as a `pkg::` member — which is the whole feature: the answer is
|
||||
`nav::definition` of the type name's own offset. So `vlog_semantic` was not
|
||||
modified, as the brief required, and the only thing that had to be built is
|
||||
the map from *a position* to *the type name's position*.
|
||||
- **That map needs the tree, and is offset-driven, which kept it small.**
|
||||
`site_at` descends items, module headers, class bodies, generate blocks and
|
||||
statements, pruning by span containment exactly as `selection.rs` does, and
|
||||
returns the one declaration covering a position: the type name as written
|
||||
plus the window it was written in. The window is deliberately the same one
|
||||
the binder searched (start of the declaration → start of the first declared
|
||||
name), which turns "where is the type name" into a *match* against the
|
||||
reference table rather than a scan of the text. A qualified type is two
|
||||
references (`pkg`, then `state_t`) and the second is the one worth jumping
|
||||
to, so a name with `::` is matched by its last segment; an instantiation
|
||||
stores its name glued, so the whole name is tried first.
|
||||
- **New module, not an extension of `nav.rs`.** `nav.rs` is definition +
|
||||
references + highlights over `Semantics` alone; this needs a parse-tree walk
|
||||
that has no reader there, and the two things it borrows from `nav` (the
|
||||
`definition` call and `symbol_at`) are a public function and a one-word
|
||||
visibility change. Adding ~250 lines of AST walking to a 625-line module
|
||||
whose subject is the symbol table would have made both harder to read.
|
||||
- **One walk, not a reuse of `instantiations::sites`.** That walk finds
|
||||
instantiations only, and this one has to visit declarations in the same
|
||||
containers; running both would mean descending generate blocks twice and
|
||||
keeping two lists of container node kinds in step. The instantiation arm here
|
||||
is two lines.
|
||||
- **The cross-file gap found by a failing test, and fenced rather than
|
||||
papered over.** `bus_if bus` and `my_cls h` — an unqualified type name
|
||||
nothing in the file binds — resolve to `Resolution::NotFound`, never to an
|
||||
external candidate, so the workspace overlay never sees them and the two
|
||||
headline cross-file cases returned nothing. Fixing that properly is a
|
||||
`vlog_semantic` change this round may not make, so it is written up as
|
||||
Handshake request 1 and stood in for by `indexed_type`: the index's own unit
|
||||
table, asked only for a `NotFound` reference, only for file-scope
|
||||
declarations, and only for kinds that can be a type. Two tests pin the
|
||||
fence — a `package` of the same name is not an answer, and a `pkg::missing_t`
|
||||
the overlay already refused is not retried against a decoy module of that
|
||||
name.
|
||||
- **Two parser limitations found and recorded, neither touched**: an ANSI
|
||||
header whose first port has no direction does not parse, and neither does a
|
||||
modport-qualified or package-qualified header port. Handshake request 2. The
|
||||
interface-port tests write the port second and carry a comment saying why, so
|
||||
the day the parser improves the tests read as deliberate rather than
|
||||
mysterious.
|
||||
- **Conventions followed exactly rather than re-decided**: the answer is an
|
||||
array in every case (`GotoDefinition`'s shape, including the empty array for
|
||||
an unopened buffer, which is what `self.offset(...).unwrap_or_default()`
|
||||
means at both call sites); ambiguity returns every location; positions go
|
||||
through `Positions`/`locate::location`, so UTF-16 is not this module's
|
||||
problem and is pinned by a test anyway.
|
||||
- **No new dependencies, no version bump, no engine crate touched.** Files
|
||||
added: `crates/lucisv_server/src/type_def.rs`, this README. Files edited:
|
||||
`main.rs` (module line, capability, capability test), `server.rs` (imports,
|
||||
one dispatch arm), `nav.rs` (one visibility word plus its doc line),
|
||||
`tests/e2e.rs` (one round trip), `TODO.md` (§9c checkbox),
|
||||
`docs/features/lucisv-server/README.md` (capability table + Status).
|
||||
- **Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets`:
|
||||
0 warnings. `cargo test --workspace`: green. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: pass. No `git commit`,
|
||||
no `git push`.
|
||||
|
||||
### 2026-08-26 — dev agent (fix round: the QA finding)
|
||||
|
||||
- **The fence widened by one pattern, nothing else.** `indexed_type`'s first
|
||||
condition now reads
|
||||
`Some(Resolution::NotFound | Resolution::InheritedCandidate { .. })`
|
||||
(`crates/lucisv_server/src/type_def.rs:138`). The other two — file-scope
|
||||
declarations only (structurally, because `WorkspaceIndex::units` holds
|
||||
nothing else) and `Module`/`Class`/`Typedef` kinds only — are untouched, as
|
||||
is every other line of the module. The doc comment now explains *why* the two
|
||||
resolutions are one case: they are the two spellings `resolve.rs`'s `miss`
|
||||
gives the same event, and which one you get depends only on whether an
|
||||
`extends` happens to be overhead.
|
||||
- **The precedence question, answered by reading rather than assumed.** The
|
||||
brief asked whether in-file inherited resolution can already produce a
|
||||
location for an in-file base's nested typedef, so that the widening might
|
||||
displace a better answer. It cannot, at three independent points:
|
||||
`resolve.rs::lexical` (`crates/vlog_semantic/src/resolve.rs:39-70`) walks
|
||||
`scope.parent`, which is *lexical* nesting and never a base class's scope;
|
||||
`miss` (`:201-213`) records the base's name and stops, exactly as its own doc
|
||||
comment says ("which this crate never chases, in this file or out of it");
|
||||
and `resolve_external` (`crates/vlog_semantic/src/workspace.rs:382-391`)
|
||||
skips anything that is not an `ExternalCandidate`, so an `InheritedCandidate`
|
||||
never reaches the overlay either. So the fallback displaces an empty answer,
|
||||
not a better one. Precedence also needs no code of its own now or later,
|
||||
because `indexed_type` is consulted only after `nav::definition` came back
|
||||
empty (`type_def.rs:58-63`): the day `vlog_semantic` does chase a base, the
|
||||
reference becomes `Resolved`, `definition` answers the nested typedef, and
|
||||
the fallback is never reached — the same mechanism that already makes a local
|
||||
genvar of the same name win. Written up in Assumptions and pinned by
|
||||
`an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it`,
|
||||
which asserts both halves: the resolution really is `InheritedCandidate`
|
||||
(so nothing found the nested typedef) and the answer really is the workspace
|
||||
interface.
|
||||
- **QA's regression test flipped, name and fixture kept.**
|
||||
`a_class_scoped_type_reference_in_an_extending_class_is_never_found_cross_file`
|
||||
→ `..._is_found_cross_file`, same portable fixture, and it still asserts the
|
||||
resolution is `InheritedCandidate` — the point being that the fence widened
|
||||
and `vlog_semantic` did not.
|
||||
- **Four tests added** (`type_def.rs`, all portable, no corpus):
|
||||
`a_uvm_shaped_member_type_resolves_cross_file_from_an_extending_class` (the
|
||||
ibex shape: a base class that is nowhere in the workspace, two cross-file
|
||||
interfaces as member types, reached from both the type half and the
|
||||
declarator half);
|
||||
`an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it`
|
||||
(the precedence determination above);
|
||||
`a_non_type_inherited_reference_is_still_never_a_type_site` (an ordinary
|
||||
expression identifier inside an extending class — the one place the widening
|
||||
could have leaked, and it does not, because no `Site` is built for an
|
||||
expression statement so the fence is never even consulted); and
|
||||
`the_other_two_fence_conditions_still_hold_under_an_inherited_candidate`
|
||||
(three arms, all from inside an extending class: a `package` of that name is
|
||||
still not a type; a package *member* typedef is still not file-scope and so
|
||||
is not in the unit table; a `pkg::missing_t` the overlay already refused is
|
||||
still not retried against a decoy module of that name).
|
||||
- **The corpus spot-check now asserts the fix on the file that found it.**
|
||||
`corpus_spot_check_real_uvm_files_no_panic_and_known_jumps`'s two "known gap"
|
||||
assertions on `dv/uvm/core_ibex/env/core_ibex_env_cfg.sv` became positive
|
||||
ones: `clk_rst_if` and `core_ibex_dut_probe_if` each jump to exactly one
|
||||
location, in `clk_rst_if.sv` and `core_ibex_dut_probe_if.sv` respectively.
|
||||
Not brittle: both are `virtual <iface> <name>;` members of a class the file
|
||||
opens with, both interfaces are vendored in this checkout under those file
|
||||
names, and the probes match on the multi-space alignment the file uses. The
|
||||
test still skips itself when `corpus/` is absent, and
|
||||
`scrambling_key_agent_cfg` — a class genuinely not vendored here — is still
|
||||
asserted empty, which is what keeps the widening from reading as "answer
|
||||
something, anything".
|
||||
- **Scope.** Files edited: `crates/lucisv_server/src/type_def.rs` (one match
|
||||
pattern, its doc comment, the test module) and this README. `vlog_semantic`
|
||||
untouched; `TODO.md` needed no truth fix (its §9c line claims the capability,
|
||||
which was true before this round and is more true after). Test count in
|
||||
`type_def.rs`: 42 (was 38).
|
||||
- **Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets
|
||||
--workspace`: 0 warnings. `cargo test --workspace`: green (748 passed / 4
|
||||
ignored in `lucisv_server`'s own suite, 0 failed anywhere). `cargo build &&
|
||||
node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. No
|
||||
`git commit`, no `git push`.
|
||||
|
||||
### 2026-08-26 — overlay-promotion dev agent (the Handshake landing)
|
||||
|
||||
- **`indexed_type` deleted whole**, its qualifier guard and its kind filter
|
||||
with it, and `type_definition` is now three lines: find the type name's
|
||||
offset, ask `nav::definition`, return. `Resolution` and
|
||||
`crate::locate::location` are no longer imported by this module at all — the
|
||||
handler builds no `Location` of its own, which is the delegation-honesty
|
||||
property QA checked by reading, now true by absence.
|
||||
- **The whole suite is the acceptance suite and it still passes** — 45 tests,
|
||||
none added, none removed. 41 are untouched; one had an expectation updated
|
||||
(below). Three were renamed because they named the deleted function or a
|
||||
fence that moved, and one of those three —
|
||||
`a_package_of_the_same_name_is_not_a_type` — also changed behavior; it is now
|
||||
`a_package_of_the_same_name_answers_exactly_as_definition_answers_it`,
|
||||
asserting literal equality with `nav::definition` at the same offset. The
|
||||
reason it changed: the shared overlay does not filter the unit table by kind,
|
||||
and the private fallback did. Keeping the old answer would mean rebuilding
|
||||
the fourth resolution layer this round exists to delete, and the input it
|
||||
concerns (`thing t;` where the workspace's only `thing` is a package) does
|
||||
not compile either way.
|
||||
- `a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site` kept
|
||||
its name and got stronger, though not the way the round first wrote it. The
|
||||
first cut had it assert that `nav::definition` *does* answer that offset
|
||||
while `type_definition` does not; QA showed the same promotion made `rename`
|
||||
rewrite an unrelated file on the same coincidence, so the promotion was
|
||||
narrowed to type positions and the read side went back with the write side.
|
||||
The test now asserts the reference is `NotFound` and that **neither**
|
||||
handler answers it — pinning two independent fences (the model never offers
|
||||
the coincidence; no `Site` is built for an expression statement) instead of
|
||||
one.
|
||||
- Everything else about this feature — the offset redirection, `site_at`, the
|
||||
one-hop rule, the conventions — is unchanged. Full rationale, consumer audit
|
||||
and corpus measurement: `docs/features/overlay-promotion/README.md`.
|
||||
|
||||
### 2026-08-26 — ansi-first-port dev agent (Handshake 2 landing)
|
||||
|
||||
- **The fixtures that wrote the port second are flipped.**
|
||||
`an_interface_port_reaches_its_interface` now declares
|
||||
`module m (bus_if bus, input logic clk);` — the spelling an interface port
|
||||
is actually written in — and keeps the old ordering as a second module in
|
||||
the same fixture, so the shape that used to be the only one that parsed is
|
||||
still pinned. Two tests joined it:
|
||||
`a_modport_qualified_port_reaches_its_interface` and
|
||||
`a_package_scoped_first_port_reaches_its_typedef`.
|
||||
- **One production line changed here, and it is a widening of a match, not of
|
||||
an answer.** `type_span` already matched a site's type name by its last
|
||||
`::` segment (a qualified type is two references and the second is the one
|
||||
worth jumping to); it now also matches the half before a `.`, because
|
||||
`vlog_parser` glues an interface port's modport onto the type name the same
|
||||
way it glues a `pkg::` qualifier, and `bind_data_type` records the interface
|
||||
half. Nothing else in this module moved: the answer is still
|
||||
`nav::definition` of a name the binder itself recorded, so a wrong jump
|
||||
would have to be a wrong *reference*, not a wrong match.
|
||||
- Full rationale, the parser change and the corpus measurement:
|
||||
`docs/features/ansi-first-port/README.md`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent (continuation of an interrupted run)
|
||||
|
||||
This run resumed a QA pass interrupted mid-way. The prior pass had already
|
||||
added 13 tests to `crates/lucisv_server/src/type_def.rs` (all still present,
|
||||
all re-run and green below) but had not yet written anything to this log —
|
||||
its work is folded into the write-up below rather than repeated as a separate
|
||||
entry, since there was nothing here to distinguish "already recorded" from
|
||||
"found this session." What follows covers the full original checklist.
|
||||
|
||||
**A. Gates — all green, re-run from a clean state:**
|
||||
|
||||
- `cargo fmt --all -- --check`: clean.
|
||||
- `cargo clippy --all-targets --workspace`: 0 warnings.
|
||||
- `cargo test --workspace`: green throughout, including after every change
|
||||
this session made (744 passed / 4 ignored in `lucisv_server`'s own suite,
|
||||
0 failed anywhere in the workspace both before and after).
|
||||
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`.
|
||||
|
||||
**B. Attack surfaces.**
|
||||
|
||||
1. **`indexed_type` fence** — verified clean, with one finding (below).
|
||||
- Shadowing locals: `a_local_declaration_of_the_same_name_wins_over_the_workspace_type`
|
||||
(type_def.rs:813) — a genvar named `bus_if` in scope where `bus_if` is
|
||||
also a workspace interface; `lexical` resolves it locally
|
||||
(`Resolution::Resolved`), the fence's first condition never fires, and
|
||||
the answer is the genvar's own declaration. Re-run, passes.
|
||||
- Non-type positions (structural confinement to type windows): `a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site`
|
||||
(type_def.rs:863) — `assign x = dup;` where `dup` is also a workspace
|
||||
module name; no `Site` is ever built for an expression statement
|
||||
(`site_at`/`item_site` only recurse into `DataDecl`/`PortDecl`/
|
||||
`ParamDecl`/`Typedef`/`Instantiation`/statement-declaration kinds — an
|
||||
`ExprStmt` is not one, confirmed by reading `stmt_site`, type_def.rs:311-343),
|
||||
so `type_definition` answers empty regardless of the fence. Re-run, passes.
|
||||
- Ambiguity convention vs. `nav::definition`'s: dev's `a_module_declared_twice_returns_both_declarations`
|
||||
goes through `Target::Module`'s `ExternalCandidate` path; QA's
|
||||
`indexed_type_returns_every_workspace_declaration_when_the_name_is_ambiguous`
|
||||
(type_def.rs:888) pins the same convention through the `indexed_type`/
|
||||
`NotFound` path specifically, which none of dev's tests touch. Verified
|
||||
by code reading that both really do share one convention, not two that
|
||||
happen to agree today: `indexed_type` and `resolve_external`
|
||||
(vlog_semantic/src/workspace.rs:382,413) both read
|
||||
`WorkspaceIndex::units(name)` (workspace.rs:105) — the same `BTreeMap`
|
||||
insertion order, "by file path, then by position in the file" per its
|
||||
own doc comment — so there is structurally one ordering, not a
|
||||
coincidence. Re-run, passes.
|
||||
- Package-of-same-name exclusion: dev's `a_package_of_the_same_name_is_not_a_type`
|
||||
(type_def.rs:695). Re-run, passes.
|
||||
- Function/instance/port name collisions: **not re-tested empirically —
|
||||
verified structurally impossible instead.** `indexed_type` only ever
|
||||
sees `ws.index().units(name)`, and `WorkspaceIndex::add_file` only
|
||||
inserts a name into `units` when `is_unit(kind)`
|
||||
(vlog_semantic/src/workspace.rs:206-219, `is_unit` at :288-293) is true,
|
||||
which is exactly `Module | Package | Typedef | Class`. A function, a
|
||||
task, a port, or an instance name can never appear in `units()` at all
|
||||
— there is no fence to test because there is no path for the collision
|
||||
to occur through. This is the same mechanism that makes the
|
||||
package-of-same-name test necessary in the first place (`Package` *is*
|
||||
a unit kind, which is why `indexed_type`'s own kind filter, not just
|
||||
`is_unit`, is needed for that one case).
|
||||
|
||||
**Finding (significant, corpus-derived) — the `NotFound`-only fence
|
||||
misses the single most common real-world shape.** `resolve.rs`'s `miss`
|
||||
(vlog_semantic/src/resolve.rs:190-201) resolves *any* lexical miss inside
|
||||
a class body carrying an `extends` clause as `Resolution::InheritedCandidate`,
|
||||
never `NotFound` — unconditionally, regardless of whether the missing name
|
||||
has anything to do with inheritance. `indexed_type` (type_def.rs:126-130)
|
||||
only fires on `NotFound`. Consequence: a cross-file interface or
|
||||
package-less class used as the type of *any* member of *any* class that
|
||||
extends something — which in practice is nearly every UVM class, since
|
||||
almost all of them extend `uvm_object`/`uvm_component`/etc. — falls
|
||||
through both layers and answers nothing, even though the interface or
|
||||
class in question is genuinely declared elsewhere in the workspace.
|
||||
Reproduced live on real corpus text: `corpus/ibex/dv/uvm/core_ibex/env/core_ibex_env_cfg.sv:5,7`
|
||||
(`class core_ibex_env_cfg extends uvm_object;` /
|
||||
`virtual clk_rst_if ibex_clk_vif;`) — `clk_rst_if.sv` is indexed
|
||||
(confirmed via `ws.index().units("clk_rst_if")`), the reference resolves
|
||||
to `InheritedCandidate { base: "uvm_object", .. }` rather than `NotFound`
|
||||
(confirmed via `reference_at`), and `type_definition` at that offset
|
||||
returns `[]`. Pinned as a portable (non-corpus) regression test,
|
||||
`a_class_scoped_type_reference_in_an_extending_class_is_never_found_cross_file`
|
||||
(type_def.rs:771), and reproduced again on the live corpus file in
|
||||
`corpus_spot_check_real_uvm_files_no_panic_and_known_jumps` (type_def.rs:1048).
|
||||
Not fixed here: widening the fence to also accept `InheritedCandidate`
|
||||
looks like the natural fix and is probably safe (the fence's other two
|
||||
conditions — file-scope declaration, `Module`/`Class`/`Typedef` kind only
|
||||
— still apply), but it is a production-logic change with its own shadow
|
||||
risk (a name that is genuinely an inherited member, not a type at all,
|
||||
coincidentally sharing a workspace type's name) that deserves its own
|
||||
design pass and tests rather than a QA drive-by fix. Recommend either
|
||||
widening `indexed_type`'s match at type_def.rs:128 to include
|
||||
`Resolution::InheritedCandidate { .. }`, or folding it into Handshake
|
||||
request 1 to `vlog_semantic`, whichever the dev prefers — either way this
|
||||
is the highest-value follow-up this feature has.
|
||||
|
||||
2. **Position→type-window mapping vs. `bind_data_type`** — verified clean.
|
||||
Array dims: `packed_and_unpacked_array_dimensions_do_not_confuse_the_type_match`
|
||||
(type_def.rs:992). Inline anonymous struct: `an_inline_anonymous_struct_has_no_type_name_to_jump_to`
|
||||
(type_def.rs:942) — both the declarator-name cursor and a cursor inside
|
||||
the inline body answer empty, not a bogus jump. Multiple declarators:
|
||||
`a_later_declarator_in_a_multi_declarator_line_still_finds_the_type`
|
||||
(type_def.rs:957). Parameter-typed decls: dev's
|
||||
`a_parameter_and_a_task_argument_are_typed_declarations_like_any_other`.
|
||||
`var`/`const` prefixes: `var_const_and_signed_qualifiers_do_not_shift_the_type_window`
|
||||
(type_def.rs:976). Function arguments (the task-argument case's twin):
|
||||
`a_function_arguments_type_is_reached_like_a_task_arguments` (type_def.rs:1004).
|
||||
All re-run/added, all pass.
|
||||
|
||||
3. **One-hop semantics + degenerate `typedef t t;` totality** — verified
|
||||
clean. Dev's `an_alias_chain_is_walked_one_hop_at_a_time` plus QA's
|
||||
`a_self_referential_typedef_is_total_and_does_not_loop` (type_def.rs:909),
|
||||
which checks every offset on `typedef t t;` answers promptly with no
|
||||
panic and no hang (there is no chain-following code path to loop in the
|
||||
first place — the one-hop design makes this total by construction, and
|
||||
the test pins that operationally). Re-run, passes.
|
||||
|
||||
4. **Delegation honesty** — verified clean, by code reading and by test.
|
||||
Every `Location` this module returns is built by `crate::locate::location`
|
||||
— `nav::definition`'s own answers (type_def.rs:58) and `indexed_type`'s
|
||||
fallback answers (type_def.rs:138) both call the same function imported
|
||||
at type_def.rs:45; there is no second, ad hoc `Location` construction
|
||||
anywhere in the file. `type_definition_on_a_type_name_agrees_exactly_with_definition`
|
||||
(type_def.rs:925) asserts literal equality with `nav::definition` at the
|
||||
same offset for the case where the two are supposed to coincide. Re-run,
|
||||
passes.
|
||||
|
||||
5. **Null conventions** — verified clean. Built-ins:
|
||||
`a_built_in_type_has_no_declaration_to_jump_to`. Unopened buffer:
|
||||
`a_buffer_the_server_does_not_hold_answers_nothing`. Position on no name:
|
||||
`a_position_on_no_name_at_all_answers_nothing`. Comment/whitespace cursor:
|
||||
`a_position_inside_a_comment_answers_nothing` (type_def.rs:1028). Past-EOF:
|
||||
`a_position_past_the_end_of_the_file_answers_nothing_not_a_panic`
|
||||
(type_def.rs:1021), offset = file length + 5000. All total (empty
|
||||
`Vec`, never a panic). Re-run, all pass.
|
||||
|
||||
6. **Both claimed parser gaps, reproduced directly against `vlog_parser::parse_source_tolerant`
|
||||
(temporary throwaway test, removed after use — not committed):**
|
||||
- `module m (bus_if bus, input logic clk);` → `Error(RawText)`,
|
||||
diagnostic `expected \`)\` (found "bus")` at the position right after
|
||||
`bus_if`. Confirms the first-port-direction-less claim exactly.
|
||||
- `module m (bus_if.mp bus);` (modport-qualified) → `Error(RawText)`,
|
||||
`expected \`)\` (found ".")`. Confirms the second claim in the same
|
||||
Handshake bullet.
|
||||
- `module m (my_pkg::state_t s);` (package-qualified) → `Error(RawText)`,
|
||||
`expected \`)\` (found "::")`. Confirms the third.
|
||||
Both Handshake requests in the feature README are accurate as written.
|
||||
|
||||
7. **CLAUDE.md compliance** — verified clean.
|
||||
- No `unwrap()`/`expect()`/`panic!` anywhere in `type_def.rs` outside
|
||||
`#[cfg(test)] mod tests` (checked by scanning the file up to that
|
||||
marker); `main.rs`/`server.rs`/`e2e.rs` diffs use them only inside test
|
||||
code, which CLAUDE.md permits.
|
||||
- `pub fn type_definition` and the newly-`pub(crate)` `nav::symbol_at`
|
||||
both carry doc comments; no other `pub` items were added.
|
||||
- README sections (Goal/Assumptions/Handshakes/Status/Work log/QA log/
|
||||
Review) each appear exactly once, in order.
|
||||
- `TODO.md`'s §9c item text is unchanged; only the checkbox flipped and a
|
||||
`→ delivered ...` annotation was appended in the file's existing,
|
||||
already-established style (18 other items use the same `→` convention;
|
||||
grepped to confirm this isn't a one-off).
|
||||
|
||||
**C. Corpus spot-check — completed; found and fixed a test-harness bug along
|
||||
the way, and found the significant `indexed_type` gap above.**
|
||||
|
||||
The interrupted run had left an `#[ignore]`d scratch test
|
||||
(`qa_scratch_corpus_spot_check`) that opened a **fresh `Workspace` and called
|
||||
`open_roots` (a full corpus re-index) for every one of ~400 small corpus
|
||||
files** in its panic-sweep loop. That made the test re-scan the whole
|
||||
`corpus/ibex` tree (651 files) once per small file — confirmed by running it:
|
||||
still not finished after 5.5 minutes of CPU time, killed rather than waited
|
||||
out. This was a test-harness bug, not a product one (`Workspace::set_document`
|
||||
only overlays a buffer against an index already built —
|
||||
`crates/lucisv_server/src/state.rs:175-179` — so the fix is to build the
|
||||
index once and reuse it). Rewrote it as
|
||||
`corpus_spot_check_real_uvm_files_no_panic_and_known_jumps` (type_def.rs:1048),
|
||||
un-ignored, now runs in ~2.6s:
|
||||
|
||||
- Full-file offset sweep (every byte offset, no `step_by`) over
|
||||
`dv/uvm/core_ibex/tb/core_ibex_tb_top.sv` (21 KB) and both
|
||||
`core_ibex_env_cfg.sv`/`core_ibex_scoreboard.sv` — no panic.
|
||||
- A genuine positive control on real corpus text: `clk_rst_if ibex_clk_if(...)`
|
||||
in `core_ibex_tb_top.sv` (a module-scope interface instantiation, not
|
||||
inside any class) jumps to exactly one location, in `clk_rst_if.sv` —
|
||||
confirming the happy path this feature claims works on code nobody wrote
|
||||
as a fixture.
|
||||
- The `indexed_type`/`InheritedCandidate` gap above, reproduced on the same
|
||||
real file it was found in (`clk_rst_if`, `core_ibex_dut_probe_if` — both
|
||||
real, indexed interfaces — answer empty inside `core_ibex_env_cfg`, which
|
||||
`extends uvm_object`).
|
||||
- `scrambling_key_agent_cfg` (dev/prior-run's negative probe) confirmed
|
||||
still empty, and confirmed *why*: that class is not vendored into this
|
||||
corpus checkout at all (`grep -rl "class scrambling_key_agent_cfg" corpus/ibex/`
|
||||
finds nothing), so empty is correct regardless of resolution kind — not a
|
||||
second instance of the gap.
|
||||
- 413 small `.sv`/`.svh` files under `corpus/ibex` (≤4000 bytes each),
|
||||
every third byte offset, sharing the one indexed workspace: no panic.
|
||||
|
||||
**D. Tests added this session** (on top of the 13 the interrupted run had
|
||||
already added and which are re-verified above): 1 —
|
||||
`a_class_scoped_type_reference_in_an_extending_class_is_never_found_cross_file`
|
||||
(type_def.rs:771) — plus the corpus test rewrite described in C. Total in
|
||||
`type_def.rs`: 38 (24 dev + 14 QA). `cargo test -p lucisv_server --bin
|
||||
lucisv-server type_def::` : 38 passed, 0 failed.
|
||||
|
||||
**Overall verdict:** not committable as-is. Every hard invariant, every gate,
|
||||
and six of the seven checklist attack surfaces are clean, and the feature's
|
||||
core design (offset redirection to `nav::definition`) is sound and exactly as
|
||||
documented. But the `indexed_type` fallback — the piece this feature added
|
||||
specifically to cover cross-file interfaces and classes — silently answers
|
||||
nothing for that exact case inside the single most common real-world
|
||||
container for it (any class with `extends`), which covers most UVM
|
||||
environment/agent/scoreboard/sequence classes in practice. That is a
|
||||
functional gap in the feature's own headline claim, not a cosmetic one, and
|
||||
it was findable only by running on real code, not by the crafted unit tests
|
||||
(hence being caught here rather than in dev's own suite). Recommend: dev
|
||||
either widens the `indexed_type` fence to accept `InheritedCandidate` (with
|
||||
its own shadow-risk tests) or files it as a second, explicit Handshake
|
||||
request to `vlog_semantic`; either way, one more QA pass over just that
|
||||
change before this ships. Nothing else found blocks a commit.
|
||||
|
||||
### 2026-08-26 — QA agent (fix-round re-verification)
|
||||
|
||||
Scoped to the fix only, per the lead's brief: not a redo of the original
|
||||
checklist above, all of which stands.
|
||||
|
||||
**A. Gates — re-run from a clean state, all green:**
|
||||
|
||||
- `cargo fmt --all -- --check`: clean.
|
||||
- `cargo clippy --all-targets --workspace`: 0 warnings.
|
||||
- `cargo test --workspace`: green throughout — 748 passed / 4 ignored in
|
||||
`lucisv_server`'s own suite before any QA changes (matching dev's claim
|
||||
exactly), 750 passed / 4 ignored after adding the two tests below, 0 failed
|
||||
anywhere in the workspace at every step.
|
||||
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`.
|
||||
|
||||
**B. Diff minimality — confirmed by mtime, since neither changed file has any
|
||||
commit history to `git diff` against (both are still untracked; this feature
|
||||
has never been committed).** `type_def.rs` and this README were last written
|
||||
at 15:12 and 15:14 respectively; every other file the original round touched
|
||||
(`main.rs`, `nav.rs`, `server.rs`, `tests/e2e.rs`, `TODO.md`,
|
||||
`docs/features/lucisv-server/README.md`) was last written between 14:19 and
|
||||
14:30 — nearly 45 minutes earlier, before the fix round started. Consistent
|
||||
with dev's claim that the fix round touched only `type_def.rs` (one match
|
||||
arm, its doc comment, the test module) and this README. Not a substitute for
|
||||
a real diff, but the strongest signal available without one.
|
||||
|
||||
**C. The three precedence citations — read directly, all accurate:**
|
||||
|
||||
- `resolve.rs::lexical` (`crates/vlog_semantic/src/resolve.rs:39-70`): walks
|
||||
`scope.parent` only (line 67); no reference to a base class's scope
|
||||
anywhere in the function. Confirmed.
|
||||
- `resolve.rs::miss` (`:201-213`): for a non-unit miss, returns
|
||||
`InheritedCandidate { base, external }` when `nearest_extends` finds one
|
||||
(line 206) — the base's *name* only, never chased — and only falls through
|
||||
to `NotFound`/`ExternalCandidate` otherwise. Confirmed.
|
||||
- `workspace.rs::resolve_external` (`:382-391`): `let Resolution::ExternalCandidate { paths } = &reference.resolution else { continue };` —
|
||||
an `InheritedCandidate` (or `NotFound`) is skipped outright, never handed to
|
||||
`follow_paths`. Confirmed.
|
||||
|
||||
Together these close the precedence question exactly as claimed: no path in
|
||||
`vlog_semantic` today can turn an `InheritedCandidate` into a `Location`, so
|
||||
the widened fence only ever fires where `nav::definition` already came back
|
||||
empty (`type_def.rs:58-63`, also read and confirmed).
|
||||
|
||||
**D. Fence re-attack.**
|
||||
|
||||
1. **Original shadowing counterexamples, re-run:** all still pass —
|
||||
`a_local_declaration_of_the_same_name_wins_over_the_workspace_type`,
|
||||
`a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site`,
|
||||
`a_package_of_the_same_name_is_not_a_type`,
|
||||
`indexed_type_returns_every_workspace_declaration_when_the_name_is_ambiguous`.
|
||||
Untouched by the fix, verified by reading them, not just by the green
|
||||
suite.
|
||||
2. **New: a local typedef of the same name inside the *extending* class's own
|
||||
body (as opposed to dev's test, which puts it in the *base*).** Added
|
||||
`a_local_typedef_in_the_extending_class_itself_wins_over_the_workspace_type`
|
||||
(`type_def.rs`, QA fix-round section) — `class top extends base; typedef
|
||||
int bus_if; bus_if h; endclass` alongside a workspace interface also named
|
||||
`bus_if`. Confirmed `Resolved` (not `InheritedCandidate`) and the jump
|
||||
lands on the in-file typedef, never the workspace interface — `lexical`'s
|
||||
own-scope lookup (resolve.rs:44) wins before `miss` ever runs, so the
|
||||
widened fence is not even consulted here. Passes.
|
||||
3. **New: an `InheritedCandidate` in a type window matching a workspace
|
||||
MODULE.** Added
|
||||
`an_inherited_candidate_reaches_a_same_named_module_exactly_like_not_found_did`
|
||||
— a member of an extending class typed as a name that is only a workspace
|
||||
*module*. Resolution is `InheritedCandidate` as expected, and the fence's
|
||||
kind filter (`Module | Class | Typedef`, unconditioned on which resolution
|
||||
triggered it) lets it through exactly as it already would for `NotFound` —
|
||||
confirmed both by this new pinned test and by re-reading `indexed_type`
|
||||
(type_def.rs:136-148), which never branches on *which* of the two
|
||||
resolutions matched. Passes; now pinned permanently.
|
||||
4. **`pkg::t` qualified references — mostly unaffected, but not entirely, and
|
||||
this predates the fix.** Verified by two throwaway probes (not committed —
|
||||
removed after use, per the convention the last QA round set). The common
|
||||
case dev's claim describes is correct: when the qualifying unit is not
|
||||
declared in this file at all, the reference is `ExternalCandidate`
|
||||
(`a_qualified_name_the_overlay_refused_is_not_retried_against_the_index`
|
||||
already pins this). But `resolve.rs::unit_member` (`:121-166`) has its own,
|
||||
separate miss path via `Target::UnitMember`: when the unit *is* found
|
||||
locally — a `Class` with `extends` whose own scope lacks the member, or a
|
||||
`Package`/extends-less `Class` whose own scope lacks the member — the
|
||||
member reference resolves to `InheritedCandidate` or plain `NotFound`
|
||||
respectively, exactly the two spellings `indexed_type` matches on.
|
||||
`indexed_type` does not look at which `Target` produced the resolution; it
|
||||
takes the *bare* member name and searches the whole workspace unit table
|
||||
with it, discarding the qualifier entirely. Reproduced concretely: with
|
||||
`class base; endclass class top extends base; endclass` and `module m; top::ambiguous_member x; endmodule`,
|
||||
plus an unrelated `class ambiguous_member` in another file, the reference
|
||||
resolves to `InheritedCandidate` and `type_definition` jumps straight to
|
||||
the unrelated decoy — nothing about `top` or its `base` chain was ever
|
||||
consulted. **This is not new or introduced by this fix round**: the control
|
||||
probe swaps `top extends base` for a plain `package local_pkg; endpackage`
|
||||
(so the miss is a bare `unit_member` `NotFound`, the resolution this
|
||||
feature's fence has matched since the original round) and reproduces the
|
||||
identical bare-name jump to the same kind of decoy. So the widening did not
|
||||
create this gap — it already existed for `NotFound`-via-`Target::UnitMember`
|
||||
and was implicitly accepted (or simply not probed) in the original QA
|
||||
round, which tested `Target::Lexical`-produced misses and one
|
||||
`Target::Unit` ambiguity case, but no `Target::UnitMember` miss on a
|
||||
*locally* resolved unit. Not filed as a blocking finding against this fix
|
||||
round — it is orthogonal to what changed here — but worth a follow-up: the
|
||||
fence's bare-name lookup is only sound for a `Target::Lexical` miss (where
|
||||
the bare name really is "does the workspace declare this anywhere");
|
||||
applying it to a `Target::UnitMember` miss answers a question the
|
||||
qualifier already narrowed and can jump to a declaration with no
|
||||
relationship to the qualifying unit. Recommend a design pass on
|
||||
`indexed_type` to check the reference's target kind (or otherwise confine
|
||||
the fence to unqualified names) the next time this file is touched.
|
||||
|
||||
**E. Corpus spot-check — stable across 3 consecutive runs**, ~2.7s each,
|
||||
`checked 413 small corpus files, no panic` every time, both now-positive
|
||||
assertions (`clk_rst_if`, `core_ibex_dut_probe_if`) holding every run.
|
||||
Fixture reasoning independently confirmed: `corpus/ibex/dv/uvm/core_ibex/env/core_ibex_dut_probe_if.sv`
|
||||
and `corpus/ibex/vendor/lowrisc_ip/dv/sv/common_ifs/clk_rst_if.sv` both exist
|
||||
in this checkout exactly where the test expects them. Not brittle by any
|
||||
signal found this session.
|
||||
|
||||
**F. Tests added this session:** 2, both permanent —
|
||||
`a_local_typedef_in_the_extending_class_itself_wins_over_the_workspace_type`
|
||||
and `an_inherited_candidate_reaches_a_same_named_module_exactly_like_not_found_did`.
|
||||
Total in `type_def.rs`: 44 (42 + 2 QA). Two additional throwaway probes used
|
||||
to investigate item D.4 above were removed after confirming the finding, per
|
||||
the standing convention (not committed).
|
||||
|
||||
**Overall verdict: committable.** The fix is exactly what it claims to be —
|
||||
one match arm widened, nothing else in production code touched, confirmed by
|
||||
mtime and by reading the file in full. The three precedence citations hold up
|
||||
under independent reading. All of the previous QA round's attack surfaces
|
||||
still pass unchanged. Two new attack angles the brief asked for (local
|
||||
same-class shadowing, module-kind parity) are now pinned permanently and both
|
||||
pass. The corpus regression this fix was written for is confirmed fixed and
|
||||
stable. One new, non-blocking finding (D.4 above) is pre-existing scope, not
|
||||
a regression from this round, and is written up for a future pass rather than
|
||||
held against this one.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and both QA rounds' logs; re-ran all
|
||||
gates myself, clean. This round earned its fix cycle. The core design —
|
||||
type-definition as one redirection into `nav::definition`, so locations
|
||||
are only ever built by one code path — is exactly right, and the module
|
||||
doc explains it well enough to maintain. The original QA round's
|
||||
rejection was correct and well-evidenced: the fallback built for
|
||||
cross-file interfaces missed them inside every extending class, found on
|
||||
a real Ibex file by the corpus sweep. The fix round's widening is sound
|
||||
because its safety argument was *derived* — three independent citations
|
||||
in vlog_semantic proving no layer can turn an InheritedCandidate into a
|
||||
location today — and the precedence story costs no code by construction.
|
||||
|
||||
One lead addition before commit: QA's follow-up probe showed a qualified
|
||||
member miss (`pkg::missing_t` against a local package) reaches the
|
||||
fallback with the same two resolution spellings, and the bare-name sweep
|
||||
would then discard the qualifier — a wrong jump, which this feature's
|
||||
own doc comment says is worse than an empty answer. I added the
|
||||
qualifier guard in `indexed_type` (decline when the text before the
|
||||
reference ends with `::`), with a pinning test proven by deliberate
|
||||
breakage (fails with the guard disabled, passes with it). The
|
||||
vlog_semantic Handshake stays filed covering both miss spellings; when
|
||||
it lands, `indexed_type` — guard and all — is deleted whole. QA process
|
||||
note: the first QA agent was lost to an infrastructure error mid-run;
|
||||
the resumed agent picked up its uncommitted work, finished the sweep,
|
||||
and found the rejection-worthy bug in the step the first run never
|
||||
reached. Accepted as shipped.
|
||||
@@ -0,0 +1,581 @@
|
||||
# type-hierarchy
|
||||
|
||||
TODO.md §9c: **the class `extends` tree, both directions, over LSP
|
||||
`typeHierarchy`.**
|
||||
|
||||
## Goal
|
||||
|
||||
"What does this class extend?" and "who extends it?" are the two questions a
|
||||
verification engineer asks about a UVM testbench they did not write, and until
|
||||
now lucisv could answer neither without a grep. LSP has had the shape for both
|
||||
since 3.17: its type hierarchy is a graph of supertypes and subtypes, and
|
||||
SystemVerilog's `extends` is exactly that graph — the classes are the nodes and
|
||||
`class d extends b` is the edge. So `textDocument/prepareTypeHierarchy` picks a
|
||||
class out of the text under the cursor, `typeHierarchy/supertypes` answers "what
|
||||
does X extend" and `typeHierarchy/subtypes` answers "who extends X", and every
|
||||
LSP client draws the tree with its own hierarchy view — no editor code at all.
|
||||
|
||||
Each request answers **one hop**. The client drives the expansion, so a cycle
|
||||
needs no handling here beyond not crashing: `class a extends a;` simply appears
|
||||
again one level down, and an `a → b → a` pair unrolls as far as the user keeps
|
||||
clicking.
|
||||
|
||||
**Scope decision, made by the lead before the round: classes only.** The module
|
||||
hierarchy stays on `callHierarchy`, where it shipped and is tested
|
||||
(`docs/features/hierarchy/README.md`). Mapping modules onto `typeHierarchy` as
|
||||
well was considered and rejected: an instantiation is a *containment* edge and
|
||||
`extends` is an *inheritance* edge, and serving both from one request would put
|
||||
two unrelated relations behind one node kind with no way for a client — or a
|
||||
reader — to tell them apart. One item kind, done well.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`extends` is the edge, and nothing else is.** `implements` names an
|
||||
**interface class**, which is a different construct (IEEE 1800 §8.26) that
|
||||
`vlog_parser` does not model at all — `interface class ic; ... endclass` is
|
||||
rejected as an unsupported construct
|
||||
(`vlog_parser::parser::parse_keyword_item`, and its own
|
||||
`interface_class_is_not_an_interface` test). So an `implements` target can
|
||||
never be a class declaration this server holds, and matching one by name would
|
||||
claim an unrelated ordinary class of that name. `implements` therefore
|
||||
contributes no supertype. Pinned by
|
||||
`an_implements_clause_names_no_supertype` and
|
||||
`an_interface_class_is_not_a_node_because_the_parser_does_not_model_one`,
|
||||
the second named so a future parser round that models interface classes is
|
||||
forced past it.
|
||||
- **Every item is `SymbolKind::CLASS`.** Following from the above: there is no
|
||||
node in this feature that could carry `INTERFACE`, because there is no AST
|
||||
node for an interface class to build one from.
|
||||
- **A class has exactly one base**, which is what the AST gives
|
||||
(`ClassDecl::extends` is an `Option<ClassExtends>`) and what the LRM says for
|
||||
ordinary classes. `supertypes` is therefore a list of at most one — except
|
||||
under the workspace's documented duplicate policy, below.
|
||||
- **The base is resolved by the same two layers `textDocument/definition`
|
||||
uses**, and by nothing of this feature's own: the file's symbol table first,
|
||||
then the workspace overlay. `vlog_semantic` already records `extends Base` as
|
||||
a reference (`docs/features/class-semantics/README.md` rule 5), and the
|
||||
overlay-promotion round made a bare cross-file class name reachable through
|
||||
that same reference, so a base in another file needs no lookup here. The one
|
||||
thing this feature computes is *which offset* to ask about: the **last byte**
|
||||
of the extends clause's `name_span`. For a bare `base` that is that one
|
||||
reference; for `pkg::base` it is inside the **tail's** reference, which is the
|
||||
one that names a class (the head names the package), and it is the right byte
|
||||
whatever spacing the source used around the `::`.
|
||||
- **A parameterized base needs no unwrapping.** The parser keeps `#( ... )` on
|
||||
its own field, so `extends base #(8)` stores `base` in `ClassExtends::name`
|
||||
and its `name_span` covers `base` alone. This is the class-semantics policy
|
||||
already, verified by reading `parse_class_extends`, and pinned by
|
||||
`a_parameterized_base_resolves_by_its_bare_name`.
|
||||
- **An unresolvable base yields no item, never a guess.** `extends uvm_object`
|
||||
in a workspace that does not index UVM has nowhere honest to point: an item
|
||||
carries a `uri` and a `range`, and a wrong one sends the user to the wrong
|
||||
file with no way to tell. So the chain simply stops. This is not rare — it is
|
||||
the normal top of every UVM chain in the corpus — and it is what the corpus
|
||||
test asserts at `core_ibex_base_test extends uvm_test`.
|
||||
- **`subtypes` matches the base name exactly as written**, which is the
|
||||
`hierarchy` feature's own "the walk is by name" assumption applied to
|
||||
`extends`. Two consequences, both deliberate:
|
||||
- A **qualified** base is not matched: `class d extends other_pkg::base;` is
|
||||
not offered as a subtype of a file-scope `base`, because matching on the
|
||||
trailing segment would silently claim it. Measured: **0 of the 270 `extends`
|
||||
clauses in the checked-in 860-file corpus are qualified**, so this costs
|
||||
nothing observable here. It does make the two directions asymmetric —
|
||||
`supertypes` *does* follow `pkg::base`, through the package — which is
|
||||
stated rather than hidden, and pinned by
|
||||
`a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with`.
|
||||
- Two classes of the same name in different files get the **same** subtype
|
||||
list. `subtypes` reads the item's `name`, not its `uri` — exactly as
|
||||
`callHierarchy/incomingCalls` does for a module name — because the text
|
||||
`extends base` says which *name* was extended and nothing more.
|
||||
- **Ambiguity is answered the same way in both directions, and differently from
|
||||
`outgoingCalls`.** A base name two files declare gives **two** supertype
|
||||
items. This is a deliberate departure from `hierarchy::outgoing`, which skips
|
||||
an ambiguous target: an outgoing *call* carries `fromRanges`, so two items
|
||||
would double one edge, whereas a supertype is a bare item in a flat list —
|
||||
the same list shape `prepare` returns, where showing both is how the user is
|
||||
told the ambiguity exists. It also comes for free from the shared overlay,
|
||||
whose documented policy is to offer every declaration
|
||||
(`docs/features/workspace-index/README.md`).
|
||||
- **A cursor immediately after the last character of a name is on that name.**
|
||||
`TextRange::contains` excludes the end, which is right for a span of text and
|
||||
wrong for a caret — that is where a double-click and an end-of-word motion
|
||||
leave it. Same convention `hierarchy.rs` states.
|
||||
- **The scope ladder decides which files are searched.** `subtypes` reads
|
||||
`Workspace::sources()`, so a file a filelist or an `exclude` keeps out of the
|
||||
index extends nothing, exactly as it references nothing. Open buffers beat
|
||||
disk, so an `extends` just typed and not yet saved is already a subtype.
|
||||
- **Classes are found wherever they can be written**: at file scope, inside a
|
||||
`package` (the dominant UVM shape), inside a `module`, and nested inside
|
||||
another class. A generate block is not descended into. QA traced the parser and corrected
|
||||
the original justification: classes inside generate blocks DO parse into
|
||||
real `ClassDecl` nodes — the walk simply does not recurse there. Zero such
|
||||
classes exist in the 860-file corpus, so the gap is theoretical today; the
|
||||
pinning test (`a_class_declared_inside_a_generate_block_is_not_found_by_this_walk`)
|
||||
makes a future round close it on purpose.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `vlog_parser`** — `parse_source_tolerant`, `ast::ClassDecl` /
|
||||
`ClassExtends` (read-only, for `name`, `name_span` and `extends`),
|
||||
`Item::span`, `LineIndex`. Nothing new is asked of the crate.
|
||||
- **Consumes `vlog_semantic`** — `ExternalResolutions::definition_of` and
|
||||
`Definition`, `Semantics::reference_at`, `SymbolKind::Class`,
|
||||
`WorkspaceIndex::path`. **Nothing was changed in the crate.** The whole
|
||||
cross-file half of this feature is the overlay-promotion round's work being
|
||||
consumed: `extends Base` was already a reference carrying the bare name as its
|
||||
last candidate path, so the workspace already had the answer and this feature
|
||||
only had to ask for it at the right offset.
|
||||
- **Consumes `crate::state::{Workspace, Document}`** — `document`, `index`,
|
||||
`text_of`, `sources`, and `Document::new` for the one case an item names a
|
||||
file no editor has open (see the work log). Nothing in `state.rs` was changed;
|
||||
the workspace stays immutable through all three handlers, and no cache was
|
||||
added.
|
||||
- **Promises `lucisv_server`** — `type_hierarchy::{prepare, supertypes,
|
||||
subtypes}` never panic, never return an item whose `selectionRange` is outside
|
||||
its `range`, and never return an item for a class the workspace does not
|
||||
really declare.
|
||||
- **Requested of `vlog_semantic`, not done here: an inheritance edge table in
|
||||
`WorkspaceIndex`.** This is the *same* Handshake `docs/features/hierarchy`
|
||||
filed for instantiation edges and `docs/features/code-lens` rode past — the
|
||||
index records what a file *declares* and not what it uses, so "who extends X"
|
||||
has to be a workspace walk. One table keyed by base name, built with the
|
||||
index, would make `subtypes` a map lookup at the cost of one extra field per
|
||||
class at index time. Filed together with the instantiation table rather than
|
||||
separately: the two want the same shape and should land as one round when
|
||||
something finally justifies widening the index's contract. Today one request
|
||||
in 55 ms does not.
|
||||
- **`editors/vscode` needs no change.** `vscode-languageclient` 9.0.1 ships the
|
||||
type-hierarchy feature and enables it off the advertised capability; the
|
||||
extension sets no `initializationOptions` that would suppress it, and
|
||||
Vim/Neovim clients drive it through their own commands.
|
||||
`editors/vscode/smoke.js` checks a fixed capability list and was deliberately
|
||||
left untouched (it is editor-packaging's file) — it still passes.
|
||||
|
||||
## The one thing `lsp-types` could not spell
|
||||
|
||||
`lsp-types` 0.97 models type hierarchy on the **client** side only:
|
||||
`TypeHierarchyClientCapabilities` exists, the three request types and
|
||||
`TypeHierarchyItem` exist, and `ServerCapabilities` has **no**
|
||||
`type_hierarchy_provider` field. A capability a client cannot see is a feature
|
||||
that is never requested, however well it is implemented — so `initialize_value`
|
||||
in `main.rs` serializes the `InitializeResult` and inserts
|
||||
`"typeHierarchyProvider": true` into the capabilities object, which is the same
|
||||
JSON a field would have produced. `experimental` was not used: it is a different
|
||||
key and no client reads it for this. Pinned twice — in `main.rs` (the JSON
|
||||
carries the key, and the insertion disturbs nothing else) and over the wire in
|
||||
`tests/e2e.rs`.
|
||||
|
||||
## What it looks like
|
||||
|
||||
`type_mid.sv`:
|
||||
|
||||
```systemverilog
|
||||
class type_mid extends type_base;
|
||||
int y;
|
||||
endclass
|
||||
```
|
||||
|
||||
Cursor on `type_mid` anywhere — its own declaration, its `extends` in another
|
||||
class, or a `type_mid handle;` — and the hierarchy view shows:
|
||||
|
||||
```
|
||||
supertypes (what type_mid extends) subtypes (who extends type_mid)
|
||||
type_base type_base.sv:1 type_leaf type_leaf.sv:1
|
||||
```
|
||||
|
||||
## Cost
|
||||
|
||||
Release build, this machine, the checked-in 860-file corpus, worst of three
|
||||
(printed by `the_corpus_uvm_classes_answer_all_three_requests`):
|
||||
|
||||
| request | measured |
|
||||
|---|---:|
|
||||
| `subtypes` for `core_ibex_base_test` (10 subclasses across the corpus) | **55 ms** |
|
||||
| — of which reading the 860 files (`Workspace::sources()`) | **53 ms** |
|
||||
| — of which the substring prefilter over all of them | 0.28 ms |
|
||||
| — of which parsing + walking the **3** files that mention the name | ~2 ms |
|
||||
| `supertypes` for `core_ibex_debug_intr_basic_test` | **0.69 ms** |
|
||||
| the same `subtypes` in a debug build | 101 ms |
|
||||
|
||||
The shape is the same one `callHierarchy/incomingCalls` measured (56 ms), and
|
||||
for the same reason: what is left after the prefilter is **almost entirely file
|
||||
I/O**, because `sources()` reads every in-scope file whether it will be parsed
|
||||
or not. That is the shared cost of every cross-file answer in this server and
|
||||
the place a future win lives (the edge table above, or a cheaper `sources()`);
|
||||
nothing in this feature can shave it alone. The prefilter itself is not a
|
||||
heuristic — `extends base` has to write `base` — and here it skips 857 of 860
|
||||
files.
|
||||
|
||||
`supertypes` never walks the workspace at all: it parses one file (the item's
|
||||
own) and, at most, re-reads the one file that declares the base. The same
|
||||
worst-case caveat `hierarchy` records applies to `subtypes` in principle — a
|
||||
class name that is a substring of nearly every file defeats the prefilter — but
|
||||
UVM class names are long and specific, and no such name exists in the corpus.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/lucisv_server/src/type_hierarchy.rs`: the class walk,
|
||||
`prepare`, `supertypes`, `subtypes`
|
||||
- [x] `typeHierarchyProvider` in `main.rs` (inserted into the serialized
|
||||
capabilities, because `lsp-types` 0.97 has no field for it); three
|
||||
dispatch arms in `server.rs`
|
||||
- [x] `prepare` on a declaration / on a use (`extends` base, a property's type,
|
||||
a method local's type) / on anything else (`null`), including a property
|
||||
name, a module, a wire and the `class` keyword
|
||||
- [x] Ambiguity: every declaration from `prepare` **and** from `supertypes`,
|
||||
with the departure from `outgoingCalls` argued
|
||||
- [x] Bases in-file, cross-file through the overlay, package-qualified,
|
||||
parameterized, and unresolvable (no item)
|
||||
- [x] `subtypes` in-file, cross-file, sorted deterministically and stable across
|
||||
two calls; scope ladder and unsaved-buffer overlay honoured
|
||||
- [x] Self-extends and a two-class cycle: one hop each, no duplicate, no hang
|
||||
- [x] Classes in a package, in a module and nested in a class
|
||||
- [x] UTF-16 positions, an untitled buffer, an unopened document, a file that
|
||||
has since moved, a nameless item, a buffer that does not parse
|
||||
- [x] `selectionRange` inside `range` asserted for every item the feature can
|
||||
hand out, in three tests including the corpus one
|
||||
- [x] Unit tests (31 in `type_hierarchy.rs`, 1 capability test in `main.rs`) and
|
||||
one e2e stdio round trip: prepare → supertypes → subtypes across three
|
||||
files
|
||||
- [x] Corpus smoke: 30 classes of `core_ibex_test_lib.sv` through all three
|
||||
requests, plus the real `core_ibex_debug_intr_basic_test →
|
||||
core_ibex_base_test → (uvm_test, unindexed)` chain
|
||||
- [x] Cost measured over the 860-file corpus, with the I/O split out
|
||||
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets --workspace`,
|
||||
`cargo test --workspace`, `editors/vscode/smoke.js`
|
||||
- [x] `docs/features/lucisv-server/README.md` capability table + work log;
|
||||
TODO.md §9c
|
||||
- [ ] Not done, backlog: the **inheritance edge table in `WorkspaceIndex`**,
|
||||
filed with the instantiation-edge table it should ship beside (Handshakes
|
||||
above).
|
||||
- [ ] Not done, blocked: **interface classes**. `vlog_parser` rejects
|
||||
`interface class`, so `implements` can never resolve and no item can carry
|
||||
`SymbolKind::INTERFACE`. When the parser models them, this feature needs
|
||||
one arm in the walk, one kind, and `implements` added to `supertypes`.
|
||||
- [ ] Not done, deliberately: chasing a chain server-side (the client drives
|
||||
it), a whole-tree "show me every class" view, and typedef/struct
|
||||
hierarchies — SystemVerilog has no inheritance for them.
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-08-26 (dev)** — read CLAUDE.md, then `lucisv-server`, `hierarchy`,
|
||||
`class-semantics` and `overlay-promotion` READMEs, then `hierarchy.rs`,
|
||||
`instantiations.rs`, `type_def.rs`, `nav.rs`, `state.rs`,
|
||||
`vlog_semantic`'s `workspace.rs` and `vlog_parser`'s `parse_class` before
|
||||
writing anything.
|
||||
|
||||
**What the class model gave, and what it did not.** It gave everything the
|
||||
cross-file half needs and it gave it *already resolved*: `ClassDecl` carries a
|
||||
parser `name_span`, `ClassExtends` carries the base name with its `::` chain
|
||||
and its own span, `extends` is recorded as a reference by `vlog_semantic`, and
|
||||
since the overlay-promotion round that reference reaches the workspace unit
|
||||
table carrying the bare name. So `supertypes` is not a lookup this feature
|
||||
wrote — it is `definition_of` asked at one computed offset. What the model did
|
||||
**not** give is interface classes: `interface class` does not parse at all, so
|
||||
`implements` is a dead end and `SymbolKind::INTERFACE` is unreachable. Checked
|
||||
rather than assumed, and recorded in Assumptions with the parser's own test as
|
||||
the citation.
|
||||
|
||||
**Design decision 1 — resolve the base through the semantic reference, not
|
||||
through the index.** The alternative was `WorkspaceIndex::units(base_name)`,
|
||||
which is what `hierarchy::outgoing` does for an instantiated module. It would
|
||||
have been wrong here for two reasons: it cannot see a base declared **in the
|
||||
same file** (a very common shape — a base and its children in one `_lib.sv`,
|
||||
which is exactly what the corpus test file is), and it cannot follow
|
||||
`pkg::base` (the unit table holds no package-scoped class). `definition_of`
|
||||
handles both, in the documented order, and is the same answer F12 gives on the
|
||||
same token — so the two can never disagree about what `extends base` names.
|
||||
That is also what made the round small: the only new idea is *which offset*.
|
||||
|
||||
**Design decision 2 — the offset is the last byte of the extends name span.**
|
||||
For `pkg::base` the clause records two references (head and tail); the head
|
||||
names the package and the tail names the class, so the answer has to come from
|
||||
the tail. Taking `name_span.end - 1` lands inside the tail under every
|
||||
spelling, including the `pkg :: base` one that class-semantics warns can glue
|
||||
its `::`. Taking `name_span.start` would have answered the *package* for every
|
||||
qualified base — a wrong file, silently.
|
||||
|
||||
**Design decision 3 — `subtypes` is a name walk, like `callers_of_each`.**
|
||||
The brief asked for the census to be modelled on it and it is: one
|
||||
`sources()` pass, a substring prefilter before any parse, and a deterministic
|
||||
sort at the end. The precision question it raises — should `other_pkg::base`
|
||||
count as extending `base`? — was settled by measurement rather than taste:
|
||||
**0 of 270 `extends` clauses in the corpus are qualified** (count per QA's
|
||||
reproducible grep — the work log's original 309 did not reproduce), so the precise
|
||||
version (resolve every candidate's base semantically and compare identities)
|
||||
would have bought nothing measurable for a large multiple of the cost and a
|
||||
second resolution path to keep honest. The asymmetry it leaves with
|
||||
`supertypes` is documented and pinned rather than papered over.
|
||||
|
||||
**Design decision 4 — ambiguity is shown, not skipped.** `hierarchy::outgoing`
|
||||
skips an ambiguous target and says why: a call carries `fromRanges`, so two
|
||||
items for one edge would double the edge. A supertype has no such payload — it
|
||||
is one item in a flat list, the same shape `prepare` returns — so listing both
|
||||
candidate declarations tells the user the ambiguity exists instead of hiding
|
||||
it behind silence. Argued in Assumptions so the inconsistency with the
|
||||
neighbouring feature is on the record.
|
||||
|
||||
**The capability had to be hand-written.** `ServerCapabilities` in `lsp-types`
|
||||
0.97 has no `type_hierarchy_provider` field (grepped the crate: the only
|
||||
`type_hierarchy` in `lib.rs` is the *client* capability at line 1453). Rather
|
||||
than fork the crate or abuse `experimental`, `initialize_value` inserts the
|
||||
key into the serialized object. It is three lines, it returns `Result` rather
|
||||
than unwrapping, and it is pinned at both layers. Recorded here because it is
|
||||
the one place this feature is not simply "call the crate".
|
||||
|
||||
**`Document::new` for a closed file.** Items carry no `data` payload — they
|
||||
are re-derived per request, like the call hierarchy's — so a client is free to
|
||||
send back an item naming a file no editor has open, which is exactly what
|
||||
happens the moment a user expands a subtype and then asks *it* for its base.
|
||||
`hierarchy::outgoing` needs only a parse there and re-parses; `supertypes`
|
||||
needs a *resolution*, so it builds a full `Document` (parse + analyze +
|
||||
overlay) for that one file. Pinned by
|
||||
`supertypes_answer_for_a_file_no_editor_has_open`, which walks base →
|
||||
subtype → base across an unopened file.
|
||||
|
||||
**Three one-line helpers restated rather than shared** (`touches`, `span`,
|
||||
`key`). Each is a statement of a convention this handler makes — a caret at
|
||||
the end of a name is on it; a range sorts by line then character — and the two
|
||||
handlers share no logic a common helper would keep honest. Said out loud in
|
||||
the source so the duplication reads as a choice.
|
||||
|
||||
**Files touched.** New: `crates/lucisv_server/src/type_hierarchy.rs`, this
|
||||
README. Edited: `crates/lucisv_server/src/main.rs` (one module declaration,
|
||||
`initialize_value`, one test), `crates/lucisv_server/src/server.rs` (three
|
||||
dispatch arms and their imports), `crates/lucisv_server/tests/e2e.rs` (one new
|
||||
test), `docs/features/lucisv-server/README.md` (capability table and work
|
||||
log), `TODO.md` (§9c).
|
||||
|
||||
**Not touched, deliberately:** `hierarchy.rs` and `instantiations.rs` (the
|
||||
module hierarchy is untouched by the scope decision), `vlog_semantic`,
|
||||
`vlog_parser`, `vlog_refactor`, `editors/`, `docs/site/`. No version bump, no
|
||||
new dependency, no commits.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets
|
||||
--workspace` zero warnings; `cargo test --workspace` green at **2 060 passed,
|
||||
4 ignored, 0 failed** (2 027 before; +33 = 31 in `type_hierarchy.rs`, 1 in
|
||||
`main.rs`, 1 e2e round trip). `cargo build --release -p lucisv_server && node
|
||||
editors/vscode/smoke.js target/release/lucisv-server`: `smoke: OK`.
|
||||
|
||||
## QA log
|
||||
|
||||
- **2026-08-26 (QA)** — re-ran every gate, then attacked the seven surfaces the
|
||||
lead named plus three of my own. Verdict: **committable as-is**. Two
|
||||
findings filed, both non-blocking (documentation/completeness, not
|
||||
correctness or corruption); everything else verified clean. +12 tests added
|
||||
(11 in `type_hierarchy.rs`, 1 in `main.rs`); all green alongside the dev's
|
||||
+33. Full workspace total after this round: **2 072 passed, 4 ignored, 0
|
||||
failed** (2 060 before QA, +12 from this pass; confirmed on two full runs).
|
||||
|
||||
**Gates.**
|
||||
- `cargo fmt --all -- --check`: clean (after `cargo fmt --all` reformatted
|
||||
two lines in the tests I added — reflowing, not a substantive change;
|
||||
re-checked clean).
|
||||
- `cargo clippy --all-targets --workspace`: zero warnings, before and after
|
||||
my additions.
|
||||
- `cargo test --workspace`: **2 072 passed, 4 ignored, 0 failed**, both
|
||||
before and after my +12 tests landed (2 060 → 2 072), 0 failed throughout.
|
||||
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`. Confirmed `smoke.js` checks a fixed capability list
|
||||
(`documentFormattingProvider`, `definitionProvider`, `hoverProvider`,
|
||||
`semanticTokensProvider`, `documentHighlightProvider`,
|
||||
`inlineCompletionProvider` — `editors/vscode/smoke.js:140-145`) that does
|
||||
**not** include `typeHierarchyProvider`, matching the README's claim that
|
||||
this file was deliberately left untouched.
|
||||
|
||||
**1. `initialize_value()` JSON injection — verified clean, one test added.**
|
||||
`git diff 24e8eab -- crates/lucisv_server/src/main.rs` shows `capabilities()`
|
||||
and `initialize_result()` are **byte-for-byte unchanged**; the only new code
|
||||
is `initialize_value()` itself, which calls the same
|
||||
`serde_json::to_value(initialize_result())` as before and then does exactly
|
||||
one `caps.insert(...)`. Since `ServerCapabilities` has no
|
||||
`type_hierarchy_provider` field (confirmed by grep — the crate's only
|
||||
`type_hierarchy` hit is the client-side capability), the inserted key cannot
|
||||
collide with or overwrite an existing one — structurally, not just by test
|
||||
luck. Added
|
||||
`the_json_insertion_disturbs_nothing_else_in_the_initialize_result`
|
||||
(`main.rs`), which strips the one inserted key back out of
|
||||
`initialize_value()`'s output and asserts the remainder equals
|
||||
`serde_json::to_value(initialize_result())` exactly — every key, every
|
||||
value, not just the two the dev's existing test spot-checked. Passes.
|
||||
`to_value` failing: propagated via `?` all the way out of `main()`
|
||||
(`Result<(), Box<dyn Error + Sync + Send>>`), no `unwrap`/`expect` — the
|
||||
process exits with an error rather than sending a malformed or partial
|
||||
`initialize` response. `serverInfo` and other siblings: covered by the new
|
||||
test's full-object comparison. The e2e test decodes
|
||||
`capabilities["typeHierarchyProvider"] == true` off the real stdio wire
|
||||
(`tests/e2e.rs`, `the_class_hierarchy_round_trips_over_the_wire_in_both_directions`)
|
||||
— confirmed by reading it and by re-running it standalone.
|
||||
|
||||
**2. Last-byte offset — verified clean, 5 tests added.** Read
|
||||
`parse_class_extends`/`parse_scoped_name` in `vlog_parser`: `extends` is
|
||||
called with `?` from `parse_class`, so every one of "empty target"
|
||||
(`extends ;`), "EOF right after the base name", and "`pkg::` with nothing
|
||||
after the `::`" fails the *entire* `class` item's parse (it becomes
|
||||
`ItemKind::Error`) rather than producing a `ClassExtends` with an empty or
|
||||
truncated `name_span` — the defensive `if extends.name_span.is_empty()`
|
||||
guard at `type_hierarchy.rs:156-158` is therefore not reachable through any
|
||||
input the parser can produce today, but it costs nothing and is the right
|
||||
thing to keep given that guarantee lives in a different crate. Added
|
||||
`an_extends_clause_with_no_base_name_never_panics`,
|
||||
`an_extends_clause_at_eof_never_panics`,
|
||||
`a_qualified_base_with_nothing_after_the_double_colon_never_panics`,
|
||||
`a_single_character_base_name_resolves`, and
|
||||
`multibyte_text_immediately_after_the_extends_name_does_not_shift_the_offset`
|
||||
(the last puts a `🎉 日本語` block comment starting at the very next byte
|
||||
after the base name, since `name_span` is measured in bytes independent of
|
||||
what follows). All pass, none panic. `TextRange::contains` excludes `end`
|
||||
(`vlog_parser/src/span.rs`), which is exactly why `.end - 1` rather than
|
||||
`.end` is needed to land on the tail reference of `pkg::base` — confirmed by
|
||||
reading `use_scoped_unit` in `vlog_semantic/src/bind.rs`, where the tail
|
||||
reference's span ends exactly at `ext.name_span.end` and the head
|
||||
reference's ends earlier.
|
||||
|
||||
**3. The supertypes/subtypes asymmetry — pinned correctly, one gap in
|
||||
coverage found and closed.** `a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with`
|
||||
exercises exactly the shape asked for: `pkg::base` written by a real class,
|
||||
a file-scope `base`, `subtypes(base)` empty. The README's "two
|
||||
consequences" prose also claims same-named classes in different files get
|
||||
the *same* subtype list (name-only match), but this was **not previously
|
||||
pinned by a test** — added
|
||||
`subtypes_of_two_same_named_classes_in_different_files_share_one_list`,
|
||||
which declares `base` in `a.sv` and `b.sv`, has `sub` extend the bare name,
|
||||
and asserts both `base` items' `subtypes()` include `sub`. Passes, confirms
|
||||
the documented (not hidden) imprecision and gives it a regression test it
|
||||
didn't have.
|
||||
|
||||
**4. Ambiguous-base = two items — verified clean.**
|
||||
`a_class_two_files_declare_prepares_both_rather_than_guessing` already
|
||||
distinguishes the two items by file name, which is `uri` under the hood —
|
||||
no additional test needed for identity (uri+range differ, per spec
|
||||
equality).
|
||||
|
||||
**5. Census correctness — verified clean, two tests added, one real gap
|
||||
found.**
|
||||
- Substring prefilter vs. match step: added
|
||||
`a_file_containing_the_name_as_a_substring_but_no_matching_extends_is_not_a_false_positive`
|
||||
— a file with `class database;` and `class d extends database;` alongside
|
||||
`class base;`; `subtypes(base)` is empty. Passes: the match step
|
||||
(`extends_name(decl.class) != Some(item.name.as_str())`) is a full string
|
||||
compare, so the prefilter's looseness never leaks through.
|
||||
- Self-extends / cycle: re-read the existing
|
||||
`a_self_extending_class_answers_one_hop_in_both_directions_without_duplicating`
|
||||
and `a_two_class_cycle_terminates_in_both_directions` — both correctly
|
||||
assert **one** item per hop, not a duplicate or a hang. Fine as written.
|
||||
- **Finding (informational, non-blocking): generate-block classes are
|
||||
invisible to this feature, and the README's given reason is not quite
|
||||
right.** The Assumptions section says "A generate block is not descended
|
||||
into — no class lives there." Traced the parser: `parse_gen_block`
|
||||
dispatches through the same `item_or_recover`/`parse_keyword_item` path
|
||||
ordinary module items use, so `class Foo; ... endclass` written inside
|
||||
`generate`/`if`-generate/`for`-generate **does** parse into a real
|
||||
`ItemKind::Class(ClassDecl)` node — it is just nested one level inside
|
||||
`ItemKind::GenerateRegion`/`GenIf`/`GenFor`/`GenCase`, which
|
||||
`type_hierarchy::collect()` (lines ~262-274) does not recurse into.
|
||||
Confirmed empirically: added
|
||||
`a_class_declared_inside_a_generate_block_is_not_found_by_this_walk`,
|
||||
which parses a module with `generate if (1) begin class Foo; endclass end
|
||||
endgenerate` and asserts `prepare` on `Foo` answers `None` today. This
|
||||
does not corrupt anything and does not violate a hard invariant — it is a
|
||||
completeness gap for a construct that is legal per IEEE 1800
|
||||
(`package_or_generate_item_declaration` includes `class_declaration`) but
|
||||
vanishingly rare in real UVM code (0 occurrences in the 860-file corpus).
|
||||
Recommend the dev correct the README's wording from "no class lives
|
||||
there" to something like "the walk does not descend into
|
||||
`GenerateRegion`/`GenIf`/`GenFor`/`GenCase`, so a class declared inside
|
||||
one is not found — legal per the LRM, not observed in the corpus" — a
|
||||
one-line wording fix, not a redesign, so left for the dev/lead rather than
|
||||
changed here.
|
||||
|
||||
**6. Corpus test honesty — mostly confirmed, one citation could not be
|
||||
reproduced.** Ran `the_corpus_uvm_classes_answer_all_three_requests` twice:
|
||||
stable both times (860 files, 30 classes in
|
||||
`core_ibex_test_lib.sv`, 30 with an indexed base, `core_ibex_base_test` has
|
||||
10 subtypes; `subtypes` 99.7 ms / 100.9 ms on the two runs, `supertypes` 3.3
|
||||
ms both — both inside the stated debug-build budget, and roughly matching
|
||||
the dev's own "101 ms" debug figure). The **860-file** count reproduces
|
||||
exactly via an independent `find corpus -name '*.sv' -o -name '*.svh' -o
|
||||
-name '*.v' -o -name '*.vh'`. The **"0 of 309 `extends` clauses are
|
||||
qualified"** claim: the "0 qualified" half reproduces — a plain `grep -c
|
||||
'::'` over every `extends` occurrence in the corpus returns 0, confirming
|
||||
the safety-relevant part of the claim. The **309** denominator did not: an
|
||||
independent `grep -ohE '\bextends\b'` count over the same file set returns
|
||||
**270**, not 309 (checked for multi-line `extends` clauses and
|
||||
backtick-macro bases as possible explanations for undercounting — found
|
||||
zero of either, so that gap is not explained). No script computing "309" is
|
||||
checked into `tools/`. This does not change any correctness verdict (the
|
||||
load-bearing claim, zero qualified, holds under both my recount and the
|
||||
existing `a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with`
|
||||
unit test), but the specific number in two README passages
|
||||
(`docs/features/type-hierarchy/README.md:80,298` and
|
||||
`docs/features/lucisv-server/README.md:49`) is currently uncited and
|
||||
unreproducible — flagging for the dev to either recheck the corpus snapshot
|
||||
they measured against or drop the precise figure in favor of "a small
|
||||
double-digit number, all unqualified."
|
||||
|
||||
**7. CLAUDE.md compliance — verified clean.** `grep -n
|
||||
"unwrap()\|expect(\|panic!" crates/lucisv_server/src/type_hierarchy.rs`
|
||||
shows every hit inside `#[cfg(test)] mod tests` (line ≥ 326 in the
|
||||
post-QA file); none in `prepare`/`supertypes`/`subtypes` or their helpers.
|
||||
Same check on `main.rs`'s `initialize_value` — clean, uses `?`. Public
|
||||
items (`prepare`, `supertypes`, `subtypes`) all carry doc comments. README
|
||||
sections (`Goal`, `Assumptions`, `Handshakes`, `Status / TODO`, `Work log`,
|
||||
`QA log`, `Review`) each appear exactly once. `TODO.md`'s §9c item text is
|
||||
intact — checkbox flipped `[ ]` → `[x]`, original sentence unchanged, a
|
||||
`→ delivered …` paragraph appended after it rather than replacing anything.
|
||||
|
||||
**Beyond the list.**
|
||||
- Deep chain: added `a_ten_deep_chain_answers_each_hop_without_recursing`
|
||||
(`c0 extends c1 extends … extends c9`, 10 files) — walks all nine hops of
|
||||
`supertypes`, one call at a time, asserting each answers exactly the next
|
||||
link and the chain terminates. No recursion in the implementation (each
|
||||
call is `O(1)` hops by construction), and the test's own structure never
|
||||
recurses either. Passes.
|
||||
- `prepare` on the `extends` **keyword** itself: added
|
||||
`prepare_on_the_extends_keyword_itself_prepares_nothing` — offset inside
|
||||
the literal word `extends` (not the name after it) answers `None`.
|
||||
Passes, because the keyword is outside every reference span
|
||||
`definition_of`/`reference_at` would match.
|
||||
- Class name shadowed by a local variable: added
|
||||
`a_class_name_shadowed_by_a_local_variable_prepares_the_variable_use_as_nothing`
|
||||
— a class `base`, a method-local `int base;`, and a use `base = base +
|
||||
1;`; `prepare` at that use answers `None` because `definition_of`
|
||||
resolves it to the local variable's `Symbol` (kind `Var`, not `Class`),
|
||||
and `classes_at` checks `symbol.kind != SemanticKind::Class` before ever
|
||||
looking at the name. Passes — confirms the feature keys off semantic kind,
|
||||
not name matching, exactly as claimed.
|
||||
|
||||
**Files touched (QA only).** `crates/lucisv_server/src/type_hierarchy.rs`
|
||||
(+11 tests), `crates/lucisv_server/src/main.rs` (+1 test). No production
|
||||
code changed — every finding above is either a passing defensive check, a
|
||||
documentation wording gap, or an unreproducible citation, none of which
|
||||
rose to "small unambiguous fix" territory in the sense of a code change;
|
||||
the README wording fix is left for the dev per the workflow (don't touch
|
||||
files outside the stated scope of a fix that isn't mine to make).
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(2072 workspace tests, 0 failed), clean. The round's hard problem was
|
||||
handled the right way twice over. First, the lsp-types gap: injecting
|
||||
the one missing key into the serialized initialize result is the honest
|
||||
minimal answer, and QA's strip-and-compare test — remove the inserted
|
||||
key, assert full object equality with the plain serialization — turns
|
||||
"disturbs nothing else" from a claim into a property. Second, the
|
||||
last-byte offset for qualified bases: the design reasoning was good and
|
||||
QA's parser trace showed the degenerate spans it guards against cannot
|
||||
even be constructed, which is the best kind of defensive code.
|
||||
|
||||
The supertypes/subtypes asymmetry is accepted as designed and now
|
||||
pinned from both directions, including the same-name/different-file
|
||||
consequence QA added a regression test for. Both QA findings were
|
||||
accepted and fixed by the lead before commit: the extends-clause
|
||||
denominator corrected to QA's reproducible 270 (in both READMEs), and
|
||||
the generate-block justification rewritten to what the parser actually
|
||||
does — the walk not recursing is a scoped choice with a pinning test,
|
||||
not a fact about where classes can live. The inheritance-edge-table
|
||||
want is filed beside the instantiation-edge request, correctly, as one
|
||||
future index round. Interface classes stay blocked on the parser and
|
||||
are pinned. Accepted as shipped.
|
||||
@@ -45,7 +45,12 @@ struct Reference{ name, name_span, scope: ScopeId, resolution: Resolution }
|
||||
struct Scope { kind: ScopeKind, parent, owner: Option<SymbolId>, span,
|
||||
symbols: Vec<SymbolId>, children, imports: Vec<Import> }
|
||||
|
||||
enum Resolution { Resolved(SymbolId), ExternalCandidate { paths: Vec<String> }, NotFound }
|
||||
enum Resolution {
|
||||
Resolved(SymbolId),
|
||||
ExternalCandidate { paths: Vec<String> },
|
||||
InheritedCandidate { base: String, paths: Vec<String> }, // class-semantics
|
||||
NotFound,
|
||||
}
|
||||
```
|
||||
|
||||
`SymbolKind` is the list the task named: `Module`, `Package`, `Port`, `Net`,
|
||||
@@ -89,7 +94,19 @@ Verilog requires at module scope — and as an editor needs mid-edit anywhere.
|
||||
|
||||
1. **Lexical chain.** From the scope the use is written in, outward through
|
||||
parents to the file scope. In each scope: names declared there first, then
|
||||
the packages that scope imports, then on to the parent.
|
||||
the packages that scope imports, then on to the parent. A miss on a name
|
||||
written in a **type** position leaves carrying **the use's own name as its
|
||||
last path**, after any import paths collected on the way out: an unqualified
|
||||
type nothing here binds is how a file-scope `interface`, a package-less
|
||||
`class` or a cross-file `typedef` is written, and the workspace's unit table
|
||||
is the only layer that can say (`docs/features/overlay-promotion/README.md`,
|
||||
2026-08-26). A miss on an identifier in a **value** position gets no such
|
||||
path — nothing about a bare expression name claims a file-scope declaration,
|
||||
and a mere collision with a workspace unit name is not a reason to rewrite
|
||||
another file. Inside a class with an `extends` either miss is an
|
||||
`InheritedCandidate` (carrying the base, and the paths it collected);
|
||||
everywhere else an `ExternalCandidate`, or `NotFound` when it has no path at
|
||||
all.
|
||||
2. **Ports and parameters are module-scope names**, so a module body sees
|
||||
them; a `function`/`task`/block scope sees them through its parents.
|
||||
3. **Enum variants land in the scope holding the enum**, per the LRM — not
|
||||
@@ -112,7 +129,12 @@ Verilog requires at module scope — and as an editor needs mid-edit anywhere.
|
||||
external candidates and the tail carries the full path `p::x`. If `p` *is*
|
||||
in this file but has no member `x`, the tail is `Resolution::NotFound` —
|
||||
not an external candidate, because the package is fully known locally and
|
||||
no workspace index could change the answer. (QA find, lead-documented.)
|
||||
no workspace index could change the answer. (QA find, lead-documented.) A
|
||||
qualified miss is **never** given the bare name rule 1 gives an unqualified
|
||||
one: `x` names something inside `p`, and sweeping the unit table for a bare
|
||||
`x` would discard the qualifier and answer a different question. The same
|
||||
holds for the class spelling — `c::x` where `c` is an in-file class with an
|
||||
`extends` is an `InheritedCandidate` with *no* paths at all.
|
||||
7. **Instantiations.** The module name is a reference to a file-scope module,
|
||||
else an external candidate naming the module. A named connection's
|
||||
`.port` resolves **against that module's scope** — so `.data_i(x)` jumps to
|
||||
@@ -233,7 +255,9 @@ rules):
|
||||
Empty ranges never match `contains`, so a query never returns one.
|
||||
- Every `Reference` whose `Resolution` is `ExternalCandidate` carries the
|
||||
workspace-level paths that could finish it; the workspace index may rewrite
|
||||
those references and nothing else.
|
||||
those references and nothing else. An `InheritedCandidate` carries paths too
|
||||
and may be *answered* by the index without being rewritten — its `base` is
|
||||
this crate's answer and stays (`docs/features/overlay-promotion/README.md`).
|
||||
|
||||
**Requested of `vlog_parser`** (not done here — out of scope for this
|
||||
feature, and the crate works without it):
|
||||
@@ -262,13 +286,37 @@ feature, and the crate works without it):
|
||||
`.v`/`.sv`/`.svh` files in `corpus/` (Ibex, OpenTitan, PULP common_cells,
|
||||
picorv32), 2026-08-19:
|
||||
|
||||
| population | files | symbols | references | resolved in-file | external candidates | unresolved |
|
||||
|---|---:|---:|---:|---:|---:|---:|
|
||||
| every file | 860 | 21 485 | 73 708 | 73.4 % | 19.4 % | 7.2 % |
|
||||
| files that parse with zero errors | 502 | 12 900 | 46 408 | 79.5 % | 19.6 % | **0.9 %** |
|
||||
| population | files | symbols | references | resolved in-file | external candidates | inherited candidates | unresolved |
|
||||
|---|---:|---:|---:|---:|---:|---:|---:|
|
||||
| every file | 860 | 21 485 | 73 708 | 73.4 % | 19.4 % | — | 7.2 % |
|
||||
| files that parse with zero errors | 502 | 12 900 | 46 408 | 79.5 % | 19.6 % | — | **0.9 %** |
|
||||
|
||||
No panics, and every one of the 95 193 name spans built across the corpus
|
||||
slices back to exactly the name it claims (0 unplaced).
|
||||
**Re-measured 2026-08-26** (`overlay-promotion`), same command, same corpus.
|
||||
The table above had gone stale by several rounds — class support and the
|
||||
parser rounds since moved both the reference count and the clean-file
|
||||
population — so the "before" row is a fresh measurement of `3bc61f9`, not a
|
||||
quote:
|
||||
|
||||
| population | files | symbols | references | resolved in-file | external candidates | inherited candidates | unresolved |
|
||||
|---|---:|---:|---:|---:|---:|---:|---:|
|
||||
| every file, before | 860 | 26 812 | 94 685 | 73.2 % | 17.1 % (16 152) | 8.3 % (7 841) | 1.5 % (1 418) |
|
||||
| every file, after | 860 | 26 812 | 94 685 | 73.2 % | **17.2 % (16 314)** | 8.3 % (7 841) | **1.33 % (1 256)** |
|
||||
| clean files, before | 853 | 26 752 | 94 384 | 73.3 % | 17.1 % (16 133) | 8.3 % (7 841) | 1.3 % (1 224) |
|
||||
| clean files, after | 853 | 26 752 | 94 384 | 73.3 % | **17.3 % (16 286)** | 8.3 % (7 841) | **1.13 % (1 071)** |
|
||||
|
||||
The promotion fires on **type positions only** — a name written where a type
|
||||
goes, which is every use that reaches `bind_data_type`. An identifier in a
|
||||
value position keeps the spelling it always had. The round first promoted both
|
||||
and had to give the value half back: an unbound expression identifier that
|
||||
happens to match a workspace unit name is a coincidence, and `rename` acted on
|
||||
it across files (`docs/features/overlay-promotion/README.md`, QA finding 1 and
|
||||
the fix round under it). So 162 references over all files (153 on clean files)
|
||||
moved `NotFound` → `ExternalCandidate`, not the 1 418 the unrestricted version
|
||||
moved. **`InheritedCandidate` is 7 841 in every one of the three states** — the
|
||||
promotion never reclassified a reference, it only lengthened `paths`.
|
||||
|
||||
No panics, and every name span built across the corpus slices back to exactly
|
||||
the name it claims (0 unplaced), before and after.
|
||||
|
||||
Reading the numbers honestly:
|
||||
|
||||
@@ -277,16 +325,23 @@ Reading the numbers honestly:
|
||||
declared elsewhere; those references are *supposed* to leave this crate
|
||||
unfinished. The workspace index converts this bucket, and it is the single
|
||||
biggest lever on perceived LSP quality.
|
||||
- **0.9 % genuinely unresolved on clean files** is the interesting number. A
|
||||
sample of what is in it: names a `` `define`` would have produced (`XLEN`,
|
||||
`ENABLE_IRQ`), class/UVM constructs in files that parse only because their
|
||||
broken parts became error nodes (`this`, `super`, `null`, `new`), and
|
||||
hierarchical/member tails reached through a path this crate stops at.
|
||||
- **The 7.2 % over *all* files is dominated by the 42 % of corpus files that
|
||||
still hit a parse error** (classes, `bind`, queues — README's "not yet
|
||||
supported" list): a declaration swallowed by an error node cannot bind, so
|
||||
every use of it counts unresolved. That number will move when the parser
|
||||
moves, not when this crate does.
|
||||
- **The unresolved bucket shrank by a re-spelling, not a discovery.** The
|
||||
references that left it are the ones written in a *type* position with
|
||||
nothing in the file or its imports to bind them: a cross-file `interface`,
|
||||
a package-less `class`, a file-scope `typedef`. Those really could be held by
|
||||
the workspace, so they now say so. Moving a reference between buckets answers
|
||||
nothing by itself — what the workspace layer actually gained is **418
|
||||
references on clean files that now have somewhere to jump, and none that lost
|
||||
one** (`docs/features/workspace-index/README.md` reports the composite).
|
||||
- **What is left under `NotFound` is what belongs there**: names a `` `define``
|
||||
would have produced (`XLEN`, `ENABLE_IRQ`), a genvar used outside its loop,
|
||||
hierarchical/member tails reached through a path this crate stops at, members
|
||||
of a locally-declared package, and `this.x` with no base. These are value
|
||||
positions, and a value position is never swept through the unit table — a
|
||||
one-letter `i` must not find a `module i` in another file, least of all when
|
||||
`rename` is the caller.
|
||||
- Only 7 of 860 corpus files still fail to parse cleanly, which is why the two
|
||||
populations now barely differ.
|
||||
|
||||
The test asserts the two properties, not the percentages: zero unplaced names
|
||||
anywhere, and under 3 % unresolved on cleanly-parsed files.
|
||||
@@ -310,6 +365,9 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
|
||||
- [x] `Error` nodes are opaque; tolerant trees analyze without panicking
|
||||
- [x] Tests: 19 behavior tests + 6 scanner unit tests + corpus smoke test
|
||||
- [x] TODO.md §6 `vlog_semantic` checkbox
|
||||
- [x] 2026-08-26 (`overlay-promotion`): an unqualified **type**-position miss
|
||||
carries the bare name to the workspace layer, in both spellings
|
||||
(`Target::Type`); a value-position miss keeps the spelling it had
|
||||
- [ ] Deferred to the workspace index: resolving `ExternalCandidate`s
|
||||
- [ ] Deferred: interfaces/modports — the parser does not accept them.
|
||||
Classes delivered 2026-08-19 by `class-semantics`
|
||||
@@ -318,6 +376,19 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).**
|
||||
`bind.rs` gains `Target::Type`, emitted by `bind_data_type`'s unqualified arm
|
||||
and nowhere else, so pass two can tell a type window from an expression.
|
||||
`resolve.rs::lexical` pushes the use's own name onto the candidate paths for
|
||||
that target only, so a type-position miss reaches the workspace layer in both
|
||||
its spellings while a value-position miss stays exactly what it was;
|
||||
`workspace.rs::resolve_external` answers an `InheritedCandidate` from those
|
||||
paths when one lands. Strictly additive to what a reference *says*: no target,
|
||||
span, symbol or variant was removed, and `InheritedCandidate.base` is
|
||||
untouched, which is why no consumer needed a change. Full rationale, the
|
||||
consumer audit, the QA-found value-position regression and the before/after
|
||||
corpus measurement: `docs/features/overlay-promotion/README.md`.
|
||||
|
||||
**2026-08-24 — refactor-rename dev agent (lead-authorized, cross-module).**
|
||||
End labels are now references. `bind.rs` gains `Target::Declaration(SymbolId)`
|
||||
and `Binder::use_end_label`, called from the module, package, class, function,
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
# will-save-wait-until
|
||||
|
||||
## Goal
|
||||
|
||||
Serve `textDocument/willSaveWaitUntil`, the protocol's own format-on-save hook:
|
||||
the client asks the server for edits *before* it writes the file, waits for the
|
||||
answer, and applies whatever comes back. VS Code users already have
|
||||
`editor.formatOnSave`, which runs the ordinary `textDocument/formatting`
|
||||
request — this exists for the editors that have no format-on-save of their own,
|
||||
and for users who would rather the server owned the decision than their editor
|
||||
config. Because a capable client sends this on **every** save of every buffer,
|
||||
and because a server that formats uninvited would fight (and double up on) an
|
||||
editor that already formats, the hook is gated on a new `lucisv.formatOnSave`
|
||||
setting that is **off** by default and answers `null` in one comparison. When it
|
||||
is on, this is `textDocument/formatting` with a different trigger — the same
|
||||
engine, the same settings, the same all-or-nothing contract (CLAUDE.md
|
||||
invariant #1) — so a save can never write anything a manual format would not.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Off by default, and the decline is cheap.** `lucisv.formatOnSave` unset,
|
||||
`false`, or wrong-typed all mean off. The handler returns `null` before it
|
||||
looks at the buffer, the workspace, or a `lucisv.toml`. The safe direction for
|
||||
a setting that rewrites the user's file on every save is the one that does
|
||||
nothing, so a value that is not the JSON boolean `true` is dropped exactly as
|
||||
every other wrong-typed setting in `settings.rs` is.
|
||||
- **A plain `bool`, not an `Option<bool>`.** Every other field of
|
||||
`ClientSettings` is "no opinion until a client says otherwise" because it has
|
||||
a rung below it to fall through to. This one does not: unset and off are the
|
||||
same answer, and there is no `lucisv.toml` key for it (the config file
|
||||
describes *style*, and whether an editor formats on save is not style — it is
|
||||
an editor behavior, and it belongs to the person at the editor).
|
||||
- **Every save reason formats.** `Manual`, `AfterDelay` and `FocusOut` all
|
||||
write the file, and a user who asked for their saves to be formatted asked
|
||||
about all three. The `reason` field is decoded and deliberately not read. A
|
||||
future knob could restrict it; none is built, because no one has asked for one.
|
||||
- **The text is the buffer the server holds.** The request carries no text — it
|
||||
arrives *before* `didSave`, and before the client has written — so what gets
|
||||
formatted is what `didOpen`/`didChange` built. That is the same text every
|
||||
other request in this server answers from. A buffer the server does not hold
|
||||
answers `null` rather than reading the file from disk: the file on disk is
|
||||
precisely the stale copy the save is about to replace.
|
||||
- **No `tabSize` on this path, and it can differ from a manual format.** The
|
||||
protocol sends `FormattingOptions` with `textDocument/formatting` and
|
||||
`rangeFormatting`; it sends nothing of the sort with `willSaveWaitUntil`. So
|
||||
the settings ladder in `format::settings_for` runs with rung 3 missing —
|
||||
`lucisv.toml` > `lucisv.indent` > the built-in 2 — exactly as it already does
|
||||
for a lint fix's indent (`format::indent_width`). **Honest consequence:** a
|
||||
user with no `lucisv.toml` and no `lucisv.indent`, whose editor tab size is 4,
|
||||
gets 4-space indent from a manual format and 2-space indent from a save. That
|
||||
is a gap in the protocol, not a bug we can close from here — the request
|
||||
simply does not carry the number — and the fix a user has is to say what they
|
||||
want once, in a `lucisv.toml` or in `lucisv.indent`. It is written down in
|
||||
`editors/vscode/package.json`'s setting description and in
|
||||
`editors/nvim/README.md` so nobody has to discover it by diffing a save.
|
||||
- **A formatter refusal is shown on every save, on purpose.** `edits()` is
|
||||
reused unchanged, so an unparsable buffer produces no edit and one ERROR
|
||||
message — per save, not once per file change. The alternative (dedup, the way
|
||||
`warn_about_config` dedups a broken `lucisv.toml`) was rejected: that warning
|
||||
is about a *config file* the user is not editing, while this is about the save
|
||||
the user just performed. A save the user asked to be formatted, that was not
|
||||
formatted, is worth saying every time it happens; going quiet would leave the
|
||||
user believing their file was formatted when it was not. The repetition is
|
||||
bounded by the user's own saves, and the broken-config warning keeps its
|
||||
dedup — though QA sharpened what that dedup actually is (see the QA log):
|
||||
it is cleared by `set_document`, so a save whose own edit comes back
|
||||
through `didChange` re-arms it for the *next* save. Once per buffer
|
||||
state, not once per broken config; still bounded by the user's saves
|
||||
either way.
|
||||
- **The capability is advertised unconditionally**, even though the default
|
||||
answers `null`. It has to be: the setting can be pushed mid-session, and
|
||||
`initialize` is the only time the sync options are sent. A client whose user
|
||||
never turns it on pays one round trip per save for a `null`.
|
||||
- **`willSave` (the notification) stays unadvertised.** It carries no reply, so
|
||||
there is nothing this server could do with it that `didSave` does not already
|
||||
cover.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `format::settings_for` / `format::formatting`** — the same two
|
||||
calls `Server::formatting` makes, in the same order, so the two paths cannot
|
||||
drift. Added one function to `format.rs`,
|
||||
`settings_without_editor_options(doc, client)`, which is `settings_for` with
|
||||
a `FormattingOptions` that opts out of rung 3 (hard tabs, zero width — values
|
||||
`config_from` already refuses). It is the options-less sibling of
|
||||
`indent_width`, and it lives in `format.rs` so the reasoning about the
|
||||
precedence ladder stays in one file.
|
||||
- **Consumes `Server::edits`** unchanged — the all-or-nothing reply shape, and
|
||||
the ERROR message on a refusal. `Ok(None)` becomes `[]`, matching what
|
||||
`textDocument/formatting` answers for an already-formatted buffer; a test
|
||||
asserts the two are byte-identical rather than merely equivalent.
|
||||
- **Consumes `Server::warn_about_config`** unchanged — a broken `lucisv.toml`
|
||||
is reported once per buffer state (the dedup is cleared by `set_document`;
|
||||
see the Assumptions bullet and the QA log for the exact bound), which keeps
|
||||
a save loop that changes nothing from repeating it.
|
||||
- **Adds one field to `settings::ClientSettings`** (`format_on_save: bool`,
|
||||
from `lucisv.formatOnSave`). `Workspace::set_client_settings` needed no
|
||||
change: the field moves no files, so it does not ask for a reindex, and it is
|
||||
read afresh by each save exactly as `indent`/`lineLength` are read afresh by
|
||||
each format.
|
||||
- **Changes what the client is told at `initialize`:**
|
||||
`text_document_sync.will_save_wait_until` moves from `None` to `Some(true)`.
|
||||
Nothing else in the sync options moves — `will_save` stays `None`,
|
||||
`change: INCREMENTAL` and `save.includeText: false` are untouched — so no
|
||||
client's sync or save behavior changes beyond gaining one request it may now
|
||||
send.
|
||||
- **Editor packaging:** `lucisv.formatOnSave` declared in
|
||||
`editors/vscode/package.json` (default `false`); no `extension.js` change was
|
||||
needed, because the client already pushes the whole `lucisv` section
|
||||
(`synchronize.configurationSection: 'lucisv'`) and `vscode-languageclient`
|
||||
registers the will-save feature from the advertised capability on its own.
|
||||
`editors/nvim/README.md` documents the setting next to the `BufWritePre`
|
||||
autocmd it is an alternative to, including the tab-settings caveat above.
|
||||
- **No other crate is touched, and no new dependency.**
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Advertise `will_save_wait_until: Some(true)`; leave `will_save` `None`.
|
||||
- [x] `lucisv.formatOnSave` in `settings.rs`, default off, wrong types dropped.
|
||||
- [x] `WillSaveWaitUntil` arm in the request dispatch + `will_save_wait_until`
|
||||
handler: off → `null`, unopened → `null`, on → the formatting path.
|
||||
- [x] `format::settings_without_editor_options` — the ladder with no `tabSize`
|
||||
rung.
|
||||
- [x] Reuse `edits()` and `warn_about_config()` unchanged.
|
||||
- [x] Settings unit tests (present true/false, absent, wrong types, the
|
||||
default VS Code payload).
|
||||
- [x] `format.rs` unit test for the options-less ladder.
|
||||
- [x] Server-level tests: off → `null` and silent; on → the edit; identical to
|
||||
what `textDocument/formatting` answers; every save reason; unopened
|
||||
buffer; already-formatted buffer → `[]`; unparsable buffer → no edits +
|
||||
one ERROR per save; setting toggled on and off mid-session.
|
||||
- [x] Idempotency guard: apply the edit, ask again, get no edits.
|
||||
- [x] e2e: the capability on the wire, the push, the edit, the second save.
|
||||
- [x] `editors/vscode/package.json` + `editors/nvim/README.md`.
|
||||
- [x] `docs/features/lucisv-server/README.md` capability table.
|
||||
- [x] TODO.md §9b item checked off.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-26 — dev.** Implemented in one round; no deviations from the plan.
|
||||
|
||||
- **`main.rs`**: one field of the existing `TextDocumentSyncOptions` moved,
|
||||
`will_save_wait_until: None` → `Some(true)`, with the reasoning in a comment
|
||||
next to it. New test `the_sync_options_ask_for_the_save_hook_and_not_the_
|
||||
notification` pins both that and `will_save: None`, since "advertise exactly
|
||||
what we implement" is the rule that block already lives by.
|
||||
- **`settings.rs`**: `format_on_save: bool`, parsed with the existing `flag()`
|
||||
helper plus `.unwrap_or(false)`. Chose `bool` over `Option<bool>`
|
||||
deliberately — see Assumptions; the type says "unset is off", which is the
|
||||
actual semantics, and it keeps every reader from writing
|
||||
`.unwrap_or(false)` at the use site. The `vscode_payload` test helper gained
|
||||
`"formatOnSave": false` so it stays the real shape of what the extension
|
||||
pushes, and `the_default_vscode_payload_is_no_opinion_about_anything` still
|
||||
passes unchanged (the default *is* the `Default` value).
|
||||
- **`format.rs`**: `settings_without_editor_options`. The alternative —
|
||||
calling `settings_for` with `FormattingOptions::default()` from the handler —
|
||||
works (its `insert_spaces: false` makes rung 3 inert), but it makes
|
||||
server.rs depend on a default value being inert somewhere else. A named
|
||||
function with the reasoning attached costs three lines and makes the
|
||||
precedence decision greppable from the module that owns precedence.
|
||||
- **`server.rs`**: one dispatch arm and one handler. The handler is five
|
||||
statements and reads top to bottom: setting → buffer → settings → format →
|
||||
warn → `edits()`. The setting check comes *first*, before the workspace
|
||||
lookup, because the decline is the hot path — this arrives on every save.
|
||||
- **The error-on-every-save decision** was the one real judgement call; it is
|
||||
argued in Assumptions and pinned by
|
||||
`a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`,
|
||||
which drives two saves and asserts exactly one ERROR each time. If a user
|
||||
ever complains, the change is a dedup keyed on (uri, generation) — but
|
||||
guessing at that now would mean shipping silence for a failed save, which is
|
||||
the worse failure.
|
||||
- **Tests: 1 settings unit + 1 format unit + 1 capability unit + 7
|
||||
server-level + 1 e2e = 11 new.** The idempotency guard
|
||||
(`applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`) applies
|
||||
the returned edit through a real `didChange` and asserts the next save has
|
||||
nothing to do — the formatter's own invariant #2, asserted through this new
|
||||
path rather than assumed from the engine's suite. The byte-identity test
|
||||
(`the_save_hook_answers_exactly_what_the_formatting_request_answers`)
|
||||
compares the two JSON results directly; it is what would catch the two paths
|
||||
drifting apart.
|
||||
- Nothing outside `crates/lucisv_server` changed in code. The three
|
||||
documentation/packaging files touched outside this feature dir
|
||||
(`TODO.md`, `docs/features/lucisv-server/README.md`,
|
||||
`editors/vscode/package.json`, `editors/nvim/README.md`) are additions in the
|
||||
house style; no QA log or Review section anywhere was edited.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-26 — QA.** Re-ran all gates, then attacked the six surfaces the lead
|
||||
called out plus one I found on my own. No masked-corruption test was needed
|
||||
(CLAUDE.md invariant #4): this feature touches nothing in `verify.rs` and adds
|
||||
no new normalization to it. **Verdict: committable as-is.** Five findings
|
||||
below, none blocking — one small fix made directly (pre-authorized), four are
|
||||
new regression tests that now guard behavior the dev's suite did not exercise,
|
||||
plus one real documentation gap for the dev to word better (not a code fix).
|
||||
|
||||
**Gates, re-run clean:**
|
||||
- `cargo fmt --all -- --check` — clean.
|
||||
- `cargo clippy --all-targets --workspace` — clean, no warnings.
|
||||
- `cargo test --workspace` — all green (643 in the `lucisv_server` unit binary
|
||||
after my additions, up from the dev's 638; every other crate unchanged and
|
||||
green).
|
||||
- `cargo test -p vlog_formatter` — 114 passed.
|
||||
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` —
|
||||
`smoke: OK`.
|
||||
|
||||
**A. Hard invariants ride through the new path — verified clean.**
|
||||
- (a) No partial output on a refusal: structural, not just tested —
|
||||
`format::formatting` (`format.rs:83-89`) uses `?` on `format_source`'s
|
||||
`Result` before it ever constructs a `TextEdit`, so an `Err` cannot reach an
|
||||
edit. `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`
|
||||
(`server.rs`) confirms it end to end: `[]` plus one ERROR, twice.
|
||||
- (b) The runtime safety net runs inside this path: read the call chain —
|
||||
`Server::will_save_wait_until` → `format::formatting` (`format.rs:83`) →
|
||||
`vlog_formatter::format_source` (`crates/vlog_formatter/src/format.rs:80`),
|
||||
which calls `verify_equivalence` then reformats and calls
|
||||
`verify_convergence` before returning `Ok`. This is the exact same call
|
||||
`Server::formatting` makes (`server.rs:410` vs `server.rs:463`) — same
|
||||
function, same arguments shape, no bypass.
|
||||
- (c) The idempotency guard is real, not string arithmetic:
|
||||
`applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` sends a
|
||||
genuine `textDocument/didChange` notification through
|
||||
`Session::notify`/`Server::notification` (the real dispatch), which lands in
|
||||
`set_document` (`server.rs:816`) exactly as an editor's own edit would, and
|
||||
then re-asks `willSaveWaitUntil` against the workspace's own copy of the
|
||||
buffer. Confirmed by reading `change()`/`buffer()` (`server.rs:1821-1834`) —
|
||||
they are the same helpers the pre-existing incremental-sync suite uses.
|
||||
|
||||
**B2. Byte-identity and the tab-size asymmetry — verified clean, gap
|
||||
confirmed real by test, not just documented.** Added two tests to
|
||||
`server.rs` (`the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent`,
|
||||
`a_lucisv_toml_erases_the_tab_size_gap`) that construct exactly the case the
|
||||
README's Assumptions section describes: no `lucisv.toml`, no
|
||||
`lucisv.indent`, editor `tabSize: 4` — manual format indents 4
|
||||
(`config_from`'s rung 3), the save hook indents 2 (the built-in default,
|
||||
since `settings_without_editor_options` sends `insert_spaces: false`, which
|
||||
short-circuits rung 3's `options.insert_spaces && INDENT_RANGE.contains(...)`
|
||||
check in `format.rs:162` regardless of the tab size carried). With a
|
||||
`lucisv.toml { indent = 4 }` present, the two paths land on byte-identical
|
||||
JSON even when the manual request's `tabSize` is 8 — rung 1 outranks both.
|
||||
This matches the README exactly; nothing to fix.
|
||||
|
||||
**B3. Setting plumbing — verified clean, plus one gap closed.**
|
||||
- `vscode_payload`'s shape matches `extension.js`'s actual
|
||||
`synchronize: { configurationSection: 'lucisv' }` (`editors/vscode/extension.js:68`,
|
||||
unmodified by this diff) and `DidChangeConfigurationParams::settings`'s
|
||||
unwrap in `server.rs`'s notification handler — traced, matches.
|
||||
- Mid-session toggle both directions: `the_save_hook_declines_until_format_on_save_is_pushed`
|
||||
covers on then off. Wrong types (`"true"`, `1`, `null`, `[true]`,
|
||||
`{"on": true}`) → off, no panic: `format_on_save_is_off_until_a_client_asks_for_it`
|
||||
(`settings.rs`) — ran clean.
|
||||
- Reindex / generation: `set_client_settings` (`state.rs:163-168`) computes
|
||||
its rescan bool from `exclude`/`filelist` equality only, so a `format_on_save`
|
||||
change can never trigger it — verified by reading the code, but the dev's
|
||||
own `only_an_exclude_change_asks_for_a_rescan` test (`state.rs`) predates
|
||||
this field and so never actually exercised it (it builds
|
||||
`ClientSettings { line_length, indent, ..Default::default() }`, which
|
||||
defaults `format_on_save` to `false` either way — a no-op assertion for this
|
||||
field). **Finding (low severity, fixed directly):** extended that test with
|
||||
an explicit `ClientSettings { format_on_save: true, ..Default::default() }`
|
||||
case (`state.rs`). Also added
|
||||
`toggling_format_on_save_neither_rescans_nor_bumps_the_generation`
|
||||
(`server.rs`) at the session level, asserting `session.server.generation`
|
||||
is unmoved by a `formatOnSave` push in either direction — this is what
|
||||
would catch it bumping a pull-diagnostics client's `resultId` for free.
|
||||
All new assertions pass against the dev's code unchanged; this was a test
|
||||
gap, not a behavior bug.
|
||||
|
||||
**B4. Error-spam decision — verified clean, plus one real finding on the
|
||||
"warns once" framing.**
|
||||
- Two saves of an unparsable buffer → exactly two ERRORs: already covered by
|
||||
the dev's `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`.
|
||||
Confirmed passing, no changes needed.
|
||||
- formatOnSave on + buffer fine + broken config → formats with defaults,
|
||||
warns once: added `a_broken_config_still_saves_with_defaults_and_warns_once`
|
||||
(`server.rs`). Had to build it carefully — see the finding below.
|
||||
- **Finding (moderate, not fixed — needs a documentation call from the dev,
|
||||
not a code change).** "Warns once" (Assumptions, work log) is **not**
|
||||
once-per-broken-config; it is once-per-buffer-state.
|
||||
`warn_about_config`'s dedup (`config_warnings: HashSet<Uri>`) is cleared by
|
||||
`set_document` (`server.rs:816-817`, doc comment: "re-arming its
|
||||
`lucisv.toml` warning"), and `set_document` is exactly what runs when the
|
||||
client applies a save hook's returned edit and the resulting `didChange`
|
||||
reaches the server — the same sequence
|
||||
`applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` already
|
||||
models on purpose. So: a save that itself needs reformatting under a
|
||||
broken config warns on save 1, and warns **again** on save 2 (because the
|
||||
intervening apply-and-write re-armed the dedup), and only goes quiet from
|
||||
save 3 onward once the buffer stops changing. Proved by a new test,
|
||||
`a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save`
|
||||
(`server.rs`) — three saves, shown-counts 1, 1, 0. This is consistent with
|
||||
`warn_about_config`'s own doc comment ("once per change of a file"), so it
|
||||
is not a bug against that contract; it is the save-hook feature's own
|
||||
Assumptions prose ("warns once") reading as a stronger guarantee than the
|
||||
mechanism actually gives. Left to the dev to reword — a single edit to the
|
||||
Assumptions bullet, not a behavior change, and QA does not redesign.
|
||||
- Interaction case is otherwise as documented: single-edit-free saves (the
|
||||
buffer already at the fallback default) stay deduped indefinitely, which is
|
||||
the common case a per-save-loop actually cares about.
|
||||
|
||||
**B5. Capability shape on the wire — verified clean, no strengthening
|
||||
needed.** The new e2e test pins `willSaveWaitUntil: true` and `willSave`
|
||||
absent (`sync.get("willSave").is_none()` — checked against the JSON, not a
|
||||
Rust `Option`, so this really is "key missing" and not "key present as
|
||||
`null`" — confirmed against `lsp-types`' `#[serde(skip_serializing_if =
|
||||
"Option::is_none")]` on both fields). `change: 2` / `openClose: true` /
|
||||
`save.includeText: false` are **not** re-pinned in the new test, but they
|
||||
already are, unmodified, by the pre-existing
|
||||
`incremental_changes_land_the_same_buffer_as_one_full_change`-adjacent e2e
|
||||
test (`crates/lucisv_server/tests/e2e.rs:2805-2808`) against the same
|
||||
`initialize` response shape — the two tests together pin the complete set
|
||||
this attack surface asks for. Nothing to strengthen.
|
||||
|
||||
**B6. CLAUDE.md compliance — verified clean.**
|
||||
- No `unwrap()`/`expect()`/`panic!()` outside `#[cfg(test)]` in any of
|
||||
`format.rs`, `main.rs`, `server.rs`, `settings.rs` — checked by line number,
|
||||
every hit is inside a `mod tests` block.
|
||||
- Doc comments present on `settings_without_editor_options` (`format.rs:63-71`)
|
||||
and the `format_on_save` field (`settings.rs:47-53`) — both explain why, not
|
||||
just what.
|
||||
- `grep -c '^## ' docs/features/will-save-wait-until/README.md` → 7 matches,
|
||||
one per section (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA
|
||||
log, Review — "Status / TODO" and each of the six headers count once each);
|
||||
no duplicates.
|
||||
- `TODO.md`'s §9b item text is untouched — only the checkbox flipped and an
|
||||
indented `→ ...` continuation appended, the same pattern every other
|
||||
checked-off item in that file already uses.
|
||||
- `editors/vscode/package.json`'s new entry sits between `inlineTemplates` and
|
||||
`lineLength`, matching the file's feature-introduction ordering (not
|
||||
alphabetical — confirmed against the surrounding keys); `editors/nvim/README.md`'s
|
||||
new section matches the surrounding prose voice.
|
||||
|
||||
**C. Pre-authorized small fix — done.** Checked `main.rs`'s `capabilities()`
|
||||
against `editors/nvim/README.md:101-102`'s claim ("Not advertised by the
|
||||
server ... range formatting, completion, rename, signature help, and
|
||||
cross-file references"): false for all four named capabilities —
|
||||
`document_range_formatting_provider`, `completion_provider`, `rename_provider`,
|
||||
and `signature_help_provider` are all `Some(...)` in `capabilities()`
|
||||
(`main.rs`, unchanged by this feature). Fixed the two lines to state that all
|
||||
four are advertised and Neovim's built-in client wires them up with no extra
|
||||
config, dropping the stale "your client will correctly refuse them" claim.
|
||||
Left `cross-file references` out of the corrected line — it was never a
|
||||
capability separate from `references_provider` (which *is* advertised); the
|
||||
real limitation is the in-file-only scope already stated two lines above
|
||||
(line 96), so restating it here as "not advertised" would have been wrong in
|
||||
a different way.
|
||||
|
||||
**D. Beyond the list — nothing further broken.** Checked and found clean,
|
||||
no test added (already structurally impossible or already covered):
|
||||
`TextDocumentSaveReason` is `#[serde(transparent)]` around a bare `i32`
|
||||
(`lsp-types-0.97.0`), so an out-of-range `reason` (not 1/2/3) still decodes
|
||||
without error — consistent with "decoded, deliberately unread," no panic
|
||||
risk. `will_save_wait_until`'s dispatch arm decodes params before checking
|
||||
the setting, same as every other request — not a new cost surface. Verified
|
||||
`editors/vscode/package.json` is syntactically valid JSON after the edit.
|
||||
|
||||
**Tests added this round (7, all passing):**
|
||||
`server.rs`: `the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent`,
|
||||
`a_lucisv_toml_erases_the_tab_size_gap`,
|
||||
`a_broken_config_still_saves_with_defaults_and_warns_once`,
|
||||
`a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save`,
|
||||
`toggling_format_on_save_neither_rescans_nor_bumps_the_generation`.
|
||||
`state.rs`: one case added inside `only_an_exclude_change_asks_for_a_rescan`.
|
||||
`editors/nvim/README.md:101-102`: one-line-pair fix (not a test).
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. The design holds the line where it matters: the new door into the
|
||||
formatter goes through the same `format::formatting` call — and so through
|
||||
the runtime safety net — as the manual request, with the all-or-nothing
|
||||
`edits()` contract unchanged; QA traced the chain to `format_source`'s
|
||||
verification and I confirm the reading. Default-off was the right call
|
||||
(a save hook that formats uninvited fights the editor's own
|
||||
format-on-save), and `settings_without_editor_options` keeping the
|
||||
precedence reasoning inside `format.rs` is the correct home for it.
|
||||
|
||||
On QA's finding (the config warning's dedup is per buffer *state*, not
|
||||
per broken config — a reformatting save re-arms it): accepted, and I have
|
||||
reworded the Assumptions bullet to say exactly what QA proved; the
|
||||
pinning test stays. The behavior itself is acceptable — the warning is
|
||||
still bounded by the user's own saves, and a user who both breaks their
|
||||
lucisv.toml and saves in a loop is being told something true each time.
|
||||
The error-on-every-save decision for refusals stands as argued. QA's
|
||||
tab-size-gap tests turned the README's honesty into executable fact,
|
||||
which is the standard here. Accepted as shipped.
|
||||
@@ -0,0 +1,383 @@
|
||||
# work-done-progress
|
||||
|
||||
## Goal
|
||||
|
||||
A workspace rescan is the one thing this server does that a user can feel.
|
||||
`Server::reindex()` is a synchronous full re-walk of the roots — 0.68 s for the
|
||||
860-file corpus, seconds for a real filelist — and it runs on every save, on
|
||||
every watched-file notification, and whenever `lucisv.exclude`/`lucisv.filelist`
|
||||
changes. Until now it happened in total silence: the editor's status bar said
|
||||
nothing, the server simply stopped answering for a while, and a user with a
|
||||
large project had no way to tell a slow index from a hung server. This round
|
||||
wraps every rescan — the startup build included — in server-initiated work-done
|
||||
progress: one `window/workDoneProgress/create`, one `$/progress` begin, the
|
||||
scan, one `$/progress` end naming the file count. Gated on the client's own
|
||||
`window.workDoneProgress` capability, because the spec forbids creating
|
||||
progress a client never asked for (TODO.md §9b).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`window.workDoneProgress` is the gate, and there is no fallback.** A client
|
||||
that did not advertise it is sent no `create` and no `$/progress` — not a
|
||||
degraded bar, not a `showMessage`. The spec is explicit that a server may
|
||||
only initiate progress against a client that asked; and a popup per save
|
||||
would be worse than the silence it replaced.
|
||||
- **`begin` is sent without waiting for the `create`'s answer.** The spec
|
||||
permits it ("the server is allowed to report progress before the create
|
||||
request is answered"), and here it is not merely permitted but necessary:
|
||||
the rescan blocks the single-threaded loop the moment `begin_indexing`
|
||||
returns, so waiting for the answer would mean the loop never processes it
|
||||
and the bar appears only after the work it describes is over. A client that
|
||||
*errors* the create is required to ignore the `$/progress` notifications
|
||||
carrying that token, so the worst case is a client that renders nothing —
|
||||
which is exactly what it rendered before this feature existed.
|
||||
- **The create's answer is ignored.** It goes through `Server::response`'s
|
||||
existing "not in the `applying` map, fall through" path, the same one the
|
||||
file-watcher (un)registrations use. Nothing is retried and nothing is
|
||||
remembered: the ids are minted from the one shared `request_ids` counter, so
|
||||
a progress answer can never be mistaken for an `applyEdit` answer.
|
||||
- **No percentage, and no intermediate `report`.** `Workspace::rebuild_index`
|
||||
is one opaque call: it walks the roots, reads every file, builds the index,
|
||||
the completion tables and the include graph, and returns. There is no
|
||||
progress to observe without threading a callback through three engine
|
||||
layers, and an invented percentage — "it is probably about half done" — is a
|
||||
lie the user would learn to distrust. An indeterminate bar is the honest
|
||||
shape.
|
||||
- **The end message is the index's own file count**, read from
|
||||
`WorkspaceIndex::files().len()` after the scan. That number was already
|
||||
public and already computed; nothing was plumbed to obtain it. It counts the
|
||||
files the index was built from — in-scope files that read successfully, with
|
||||
open buffers overriding disk — which is what "indexed" means everywhere else
|
||||
in this server.
|
||||
- **The bar covers the scan, not the republish.** `end` is sent the instant
|
||||
`rebuild_index` returns, before `report_scope`'s warnings and before the
|
||||
per-buffer republishes that follow. Either order is defensible; this one is
|
||||
pinned by a test (`the_bar_is_down_before_the_republish`) because the bar
|
||||
names the *scan*, and the republish is per-open-buffer work the user already
|
||||
pays on every keystroke without a bar.
|
||||
- **The startup build gets a bar too, and that is legal.** `Server::new` runs
|
||||
after `main`'s `initialize_finish`, which returns only once the client's
|
||||
`initialized` notification has arrived — the same fact that makes the
|
||||
existing watcher registration legal there, and it is already stated in that
|
||||
code's comment. So the first index build, which is the slowest of the
|
||||
session, is wrapped like every other. Determined by reading `main.rs:59-79`
|
||||
and `server.rs`'s `Server::new`, not assumed.
|
||||
- **No cancellation.** `cancellable: Some(false)` is stated rather than left
|
||||
unset: the loop is one thread, a rescan runs to completion, and there is no
|
||||
`window/workDoneProgress/cancel` handler. A cancel button the user could
|
||||
press and that did nothing would be worse than no button.
|
||||
- **One bar at a time, in practice.** The loop is synchronous, so a rescan
|
||||
cannot overlap another rescan; every `begin` is followed by its own `end`
|
||||
before the next `begin` can be minted. The token counter guarantees
|
||||
uniqueness regardless.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `ClientAbilities` gains `work_done_progress: bool`, filled by `main.rs` from
|
||||
`InitializeParams.capabilities.window.work_done_progress` (absent → false),
|
||||
in the style of the three fields already there. Every existing test that
|
||||
builds `ClientAbilities { ..Default::default() }` is unaffected.
|
||||
- `Server` gains `indexings: u32` — the progress-token counter. It is
|
||||
deliberately *not* the request-id counter: a token is not a request id, and
|
||||
`lucisv-index-3` reads as the fourth rescan rather than as an unrelated
|
||||
ordinal.
|
||||
- Two new private methods, `begin_indexing() -> Option<ProgressToken>` and
|
||||
`end_indexing(Option<ProgressToken>)`, plus a one-line `progress()` sender.
|
||||
`None` is the whole of the "this client cannot show a bar" path, so neither
|
||||
caller branches on the ability itself.
|
||||
- `Server::new` is restructured: the `Server` is built around a
|
||||
`Workspace::default()` and `open_roots` is then called *through* it, so the
|
||||
startup build can sit between a `begin_indexing`/`end_indexing` pair. Same
|
||||
work, same order relative to `report_scope` and `register_watchers`.
|
||||
- `Server::response`'s doc comment now names three things asked of the client
|
||||
rather than two. Its code is unchanged — the create's answer already fell
|
||||
through the `applying` lookup.
|
||||
|
||||
### `state::Workspace`, and every engine crate
|
||||
|
||||
**Untouched.** The file count comes from `Workspace::index()` and
|
||||
`WorkspaceIndex::files()`, both of which were already public and already
|
||||
called from this crate. No signature moved, `rebuild_index` still returns just
|
||||
its scope warnings, and nothing was plumbed for the sake of the end message.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
**No extension change.** `vscode-languageclient` advertises
|
||||
`window.workDoneProgress` itself and renders server-initiated progress in the
|
||||
status bar with no help from `extension.js`. `smoke.js` sends
|
||||
`capabilities: {}`, so it takes the no-progress path and passes untouched —
|
||||
verified by running it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `window.workDoneProgress` read into `ClientAbilities` at initialize
|
||||
- [x] `begin_indexing`/`end_indexing` around `rebuild_index()` in `reindex()`
|
||||
- [x] The startup index build wrapped in the same pair (legal: `Server::new`
|
||||
runs after `initialize_finish`)
|
||||
- [x] A fresh `lucisv-index-N` token per rescan, never reused
|
||||
- [x] `end` carries the indexed file count, singular and plural
|
||||
- [x] A client without the capability is sent zero progress messages
|
||||
- [x] The create's answer stays ignored and cannot disturb `applyEdit` routing
|
||||
- [x] Tests: 8 unit (7 in `server.rs`, 1 in `main.rs`), 2 e2e over the wire
|
||||
- [x] TODO.md §9b checkbox, `docs/features/lucisv-server/README.md` staleness
|
||||
section
|
||||
- [ ] **Not done, deliberately:** no `$/progress` on anything else. Formatting,
|
||||
a rename across the workspace and `callHierarchy/incomingCalls` are the
|
||||
other candidates; all three are request-scoped, so they would use the
|
||||
*client-supplied* `workDoneToken` rather than a created one, which is a
|
||||
different mechanism with a different gate. Filed here, not built.
|
||||
- [ ] **Not done, deliberately:** no `window/workDoneProgress/cancel` handler.
|
||||
There is nothing in this server to cancel — see Assumptions.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9b
|
||||
|
||||
- **Read the code before deciding about the startup build, as the brief asked.**
|
||||
`main.rs` calls `connection.initialize_finish(...)` on line 74 and
|
||||
`Server::new(...)` on line 76, and `initialize_finish` returns only after the
|
||||
client's `initialized` notification has been received and consumed. So the
|
||||
startup build happens at a moment when server-initiated requests are legal —
|
||||
the existing `register_watchers()` call in `Server::new` already relies on
|
||||
exactly that, and says so in a comment. **Verdict: wrapped.** It is the
|
||||
slowest rescan of the session and the one most worth a bar.
|
||||
- **The one structural change is in `Server::new`**: the struct is now built
|
||||
first and `open_roots` called through it, because `begin_indexing` needs
|
||||
`&mut self`. Nothing else about that function moved — `report_scope` still
|
||||
runs on the warnings `open_roots` returned, and `register_watchers` still
|
||||
runs last.
|
||||
- **`Option<ProgressToken>` is the ability check.** `begin_indexing` returns
|
||||
`None` for a client that cannot show a bar and `end_indexing` returns on
|
||||
`None`, so neither `reindex` nor `Server::new` mentions the capability. That
|
||||
also makes "a bar that went up came down" structural rather than a
|
||||
discipline: there is exactly one value that ends it and exactly one place
|
||||
it is produced.
|
||||
- **Tokens are strings, `lucisv-index-N`, off their own counter.** A number
|
||||
token would collide conceptually with the `lucisv-N` request ids in a log,
|
||||
and the string says what the bar is for. The counter starts at the startup
|
||||
build, so `lucisv-index-0` is always the first index and the first save is
|
||||
always `lucisv-index-1` — pinned by tests at both the unit and the wire
|
||||
level.
|
||||
- **The end message reads `WorkspaceIndex::files().len()`,** which was already
|
||||
public and already reachable through `Workspace::index()`. The brief's
|
||||
fallback ("end with no message if no count is cheaply available") was not
|
||||
needed; nothing was plumbed. The singular case has its own assertion, because
|
||||
"1 files indexed" is the kind of thing that ships.
|
||||
- **`report_scope` still shows its popup after the bar comes down.** A filelist
|
||||
warning and a progress bar are unrelated; sequencing them the other way would
|
||||
have meant holding the bar up across a modal in some clients.
|
||||
- Files touched: `crates/lucisv_server/src/server.rs`,
|
||||
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`,
|
||||
`TODO.md`, `docs/features/lucisv-server/README.md`, this README. No engine
|
||||
crate, no `editors/`, no new dependency, no version bump.
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
|
||||
--all-targets`: zero warnings. `cargo test --workspace`: **1812 passed, 0
|
||||
failed** (1802 on `HEAD`, measured — 7 new unit tests in `server.rs`, 1 in
|
||||
`main.rs`, 2 new e2e sessions). `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: OK, exit 0. No commits.
|
||||
|
||||
The ten tests, and what each is for:
|
||||
|
||||
| test | pins |
|
||||
|---|---|
|
||||
| `the_startup_index_build_runs_under_the_first_bar` | the startup determination above, as observable traffic |
|
||||
| `a_save_puts_a_bar_up_and_takes_it_down_again` | create → begin → end, one token, on the save path |
|
||||
| `the_bar_says_how_many_files_were_indexed` | the end message, plural and singular |
|
||||
| `the_bar_is_down_before_the_republish` | the documented ordering against `publishDiagnostics` |
|
||||
| `a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all` | zero messages of any kind, at startup and on save |
|
||||
| `every_rescan_path_gets_its_own_bar_and_its_own_token` | the watched-file and config-change paths, three distinct tokens, no leaked begin, no `report` |
|
||||
| `a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit` | an `Ok` *and* an `Err` create answer arriving between an `applyEdit` push and its answer; the refusal still reported exactly once |
|
||||
| `work_done_progress_support_is_read_from_the_clients_own_capabilities` (`main.rs`) | absent/false/true, and no panic on `InitializeParams::default()` |
|
||||
| `indexing_reports_its_progress_over_the_wire` + `a_client_that_never_asked_for_progress_is_sent_none_over_the_wire` (e2e) | the whole sequence against the real binary, both gate states, including `title`, `cancellable: false` and the absence of `percentage` |
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent, §9b
|
||||
|
||||
**Gates re-run**, on the working tree as handed off (commit `00c03ec` +
|
||||
uncommitted): `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` zero warnings. `cargo test --workspace`: **1812 passed, 0
|
||||
failed** — matches the dev log exactly. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. After the
|
||||
four tests added below: **1816 passed, 0 failed**, gates re-checked and still
|
||||
clean.
|
||||
|
||||
Per attack surface (lead's numbering):
|
||||
|
||||
1. **`Server::new` restructuring — verified clean, structurally rather than
|
||||
just empirically.** `Workspace::default()` then `open_roots(roots)` is the
|
||||
same value undergoing the same two operations in the same order whether the
|
||||
mutation happens on a local binding before it moves into the `Server`
|
||||
literal (old, `server.rs` pre-`00c03ec`-diff) or on `&mut self.workspace`
|
||||
after it is already a field (new) — a move is bitwise and Rust invokes no
|
||||
`Drop`/observer between them, so there is no field `open_roots` could leave
|
||||
stale that the old order would have filled: every field of `Workspace`
|
||||
(`docs`, `roots`, `index`, `candidates`, `includes`, `client`) gets the
|
||||
identical value either way. Every other `Server` field's initializer
|
||||
(`connection`, `config_warnings`, `abilities`, `watchers`, `registrations`,
|
||||
`request_ids`, `applying`, `generation`, `tokens`, `token_results`, and the
|
||||
new `indexings: 0`) is inert and side-effect-free, so field-initializer
|
||||
order carries no risk. `report_scope` still receives `open_roots`'s
|
||||
warnings (`server.rs:109-111`); `register_watchers` still runs last
|
||||
(`server.rs:116`).
|
||||
**Gap found and fixed**: the ordering the lead flagged as the actual risk —
|
||||
whether `register_watchers`'s request lands before or after the startup
|
||||
bar comes down — was not observable in any existing test, because every
|
||||
dev test using `watching_progress()` (`work_done_progress: true`) leaves
|
||||
`file_watching` at its `Default::default()` of `false`, so
|
||||
`register_watchers` is a no-op in all of them; conversely every test that
|
||||
turns `file_watching` on (`Session::new(_, true)`) leaves
|
||||
`work_done_progress` off. No test ever ran both abilities together. Added
|
||||
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`
|
||||
(`server.rs`, in `mod tests`, right after
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`),
|
||||
which turns both abilities on and pins the wire order `create, begin, end,
|
||||
register`.
|
||||
|
||||
2. **Protocol conformance — verified clean.** The e2e test
|
||||
`indexing_reports_its_progress_over_the_wire` decodes the actual JSON
|
||||
(not the Rust struct) off the real binary and asserts, in one ordered
|
||||
`Vec`: `create` precedes `begin` for the *same* token, for both the
|
||||
startup rescan (`lucisv-index-0`) and the save-triggered one
|
||||
(`lucisv-index-1`) — i.e., create-before-begin holds across consecutive
|
||||
rescans, not just once. The token is read with
|
||||
`.as_str().expect("a string token")`, which fails the test if the wire ever
|
||||
sends a JSON number instead — so the string-typed-token requirement is
|
||||
pinned, not assumed. `title`, `cancellable: false` (explicit `false`, not
|
||||
absent), and the absence of `percentage` are asserted off the decoded
|
||||
`begin`; the `end`'s `message` is asserted off the decoded `end`. No gap.
|
||||
|
||||
3. **Pairing is structural — verified clean.** Read `reindex()`
|
||||
(`server.rs:887-897`) and `Server::new` (`server.rs:140-169`): in both,
|
||||
nothing sits between `begin_indexing()` and `end_indexing()` but a call
|
||||
that returns a plain `Vec<String>` (`rebuild_index`/`open_roots`), never a
|
||||
`Result` — there is no `?` and no early-return expression available to
|
||||
write between them even by accident. `end_indexing` is therefore
|
||||
unconditionally reached in every existing and reachable call site.
|
||||
Multiple rapid reindexes: the server is single-threaded and `reindex()` is
|
||||
fully synchronous (begin, scan, end, all before the call returns), so two
|
||||
rescans provably cannot interleave regardless of how close together their
|
||||
triggers arrive — confirmed observably by
|
||||
`every_rescan_path_gets_its_own_bar_and_its_own_token`, which fires a save,
|
||||
a watched-file change and a config change back-to-back and gets three
|
||||
strictly-paired, strictly-increasing tokens. No gap.
|
||||
|
||||
4. **Capability gating — mostly verified clean, one gap fixed.** Startup and
|
||||
save, both gated correctly, per `a_client_that_did_not_ask_for_a_bar_is_
|
||||
sent_no_progress_at_all`. `window: {}` and `window: {
|
||||
workDoneProgress: false }` are both covered by
|
||||
`work_done_progress_support_is_read_from_the_clients_own_capabilities`
|
||||
(`main.rs`) via `saying(None)` and `saying(Some(false))` respectively —
|
||||
`ClientCapabilities::default()`'s `window` field is itself `None`, and
|
||||
`saying(None)` still wraps a `Some(WindowClientCapabilities{ .. })`, which
|
||||
is exactly the `window: {}` shape; neither panics on
|
||||
`InitializeParams::default()`.
|
||||
**Gap found and fixed**: the watched-file and `lucisv.exclude`/`filelist`
|
||||
reindex triggers were never driven with the capability *off* — only proven
|
||||
off by reading that they share `reindex()`'s single `begin_indexing` call
|
||||
with the save path. Added
|
||||
`a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either`
|
||||
(`server.rs`), which drives both and asserts `session.progress()` empty
|
||||
after each.
|
||||
|
||||
5. **Response routing under interleaving — one direction existing, the
|
||||
reverse was missing; fixed.** The dev's
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`
|
||||
answers the create (`Ok` then, for the same id, `Err`) while the
|
||||
`applyEdit` is still outstanding, then answers the edit — this is a real
|
||||
interleaving (create resolved first), and both answer shapes are exercised.
|
||||
The reverse ordering the lead asked for — `applyEdit` resolved *first*,
|
||||
then a *late* create answer — was not present. Added
|
||||
`a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too`
|
||||
(`server.rs`): answers the edit as accepted, confirms nothing is shown, then
|
||||
feeds a late `Response::new_ok` for the create's id and confirms it is
|
||||
still silently dropped. This same test doubles as "a create answer arriving
|
||||
for a token the server already Ended": by the time the edit is answered,
|
||||
the watched-file reindex that minted the create has already run its
|
||||
`begin`/`end` pair synchronously (per point 3), so the create answer that
|
||||
follows is necessarily late-for-an-ended-bar. It is ignored cleanly because
|
||||
`response()` keys off `RequestId`, never off `ProgressToken` — the two are
|
||||
different namespaces and `request_ids` never repeats, so there is no
|
||||
representable state where a create's id could collide with anything a
|
||||
still-outstanding request cares about. No further scenario to test here.
|
||||
|
||||
6. **End-message count — verified clean, one gap fixed.** `end_indexing`
|
||||
reads `self.workspace.index().files().len()` (`server.rs:192`), which is
|
||||
the index's own file list, computed by `rebuild_index` immediately before
|
||||
`end_indexing` runs — not open-buffer count, not scope-file count before
|
||||
filtering. Singular/plural pinned by `the_bar_says_how_many_files_were_
|
||||
indexed` ("2 files indexed" / "1 file indexed", explicitly asserting `"not
|
||||
`1 files`"`).
|
||||
**Gap found and fixed**: no test drove a rootless workspace with zero open
|
||||
buffers through startup. Traced `default_files()` → `sibling_files()`
|
||||
(`state.rs:308-328`) for that case: no roots and no docs means no
|
||||
directories to walk, so the index is empty and `files == 0`; the plural
|
||||
branch (`files == 1` is false for 0) correctly renders `"s"`. Added
|
||||
`a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_
|
||||
crashing` (`server.rs`), asserting `"0 files indexed"` and, by not
|
||||
panicking, non-crashing. Confirmed passing.
|
||||
|
||||
7. **CLAUDE.md compliance — verified clean.** Grepped every non-`#[cfg(test)]`
|
||||
line of `server.rs` and `main.rs` (i.e., everything before their `mod
|
||||
tests`) for `unwrap(`, `expect(`, `panic!(`: zero hits. Every new item
|
||||
(`ClientAbilities::work_done_progress`, `Server::indexings`,
|
||||
`INDEXING_TITLE`, `begin_indexing`, `end_indexing`, `progress`,
|
||||
`work_done_progress_support`) carries a doc comment. This README's seven
|
||||
required sections (`Goal`, `Assumptions`, `Handshakes`, `Status / TODO`,
|
||||
`Work log`, `QA log`, `Review`) each appear exactly once
|
||||
(`grep -n "^## "`). `TODO.md`'s §9b item text is untouched — only its
|
||||
checkbox flipped to `[x]` and an indented `→` note appended below, per the
|
||||
existing convention elsewhere in that file.
|
||||
|
||||
**Beyond the list.** One thing noted for the record, not a defect in this
|
||||
diff: `Workspace::collect_sources` (`state.rs`, untouched by this round) folds
|
||||
in every open buffer's path unconditionally, even one outside the walked
|
||||
scope, so in principle an open buffer for a file the workspace walk would not
|
||||
have found could nudge the "N file(s) indexed" count up by one beyond what a
|
||||
disk-only scan would report. This is pre-existing behavior this feature did
|
||||
not introduce and does not change (`state.rs` has no diff against `00c03ec`),
|
||||
so it is not filed as a finding against this round — just flagged in case a
|
||||
future change to the end message's wording ever needs it.
|
||||
|
||||
**Fixes made** (all additive; no dev code changed): four new tests in
|
||||
`crates/lucisv_server/src/server.rs`'s `mod tests`, inserted after
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`:
|
||||
`a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too`,
|
||||
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`,
|
||||
`a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either`,
|
||||
`a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_
|
||||
crashing`. All four pass; full workspace suite is green at 1816; `cargo fmt`
|
||||
and `cargo clippy --all-targets` stay clean.
|
||||
|
||||
**Verdict: committable as-is.** No corruption risk, no idempotency risk (this
|
||||
feature touches only the LSP transport, never formatted output), no dropped
|
||||
comments, no widened `verify.rs` forgiveness (that file has no diff in this
|
||||
round). The one structurally risky change — `Server::new`'s construction
|
||||
order — is provably equivalent to the old order and now has its
|
||||
previously-unpinned watcher-vs-bar ordering under test. No dev follow-up
|
||||
required.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(1816 workspace tests, 0 failed), clean. The `Option<ProgressToken>`-as-
|
||||
capability-gate design is the kind of structural guarantee this repo
|
||||
prefers over discipline: neither caller can put a bar up for a client
|
||||
that cannot show one, and nothing between `begin` and `end` can return
|
||||
early — I read the two call sites and confirm QA's finding that the
|
||||
pairing is unconditional. The startup-build determination was done the
|
||||
right way (read from `initialize_finish`'s contract and the existing
|
||||
`register_watchers` comment, not guessed), and the restructured
|
||||
`Server::new` is provably equivalent — same value, same two operations,
|
||||
different borrow spelling — with the previously-unpinned
|
||||
watcher-after-bar ordering now under test thanks to QA. Honesty calls
|
||||
all correct: no invented percentage, `cancellable: false` because
|
||||
nothing here can cancel, and the end message costing nothing because the
|
||||
index already knew its file count. QA's four gap-closing tests (both
|
||||
interleaving directions, capability-off on all trigger paths, the
|
||||
rootless zero-count startup) complete the surface. Accepted as shipped.
|
||||
@@ -83,10 +83,14 @@ implicitly.
|
||||
`Semantics::definition_of` still works alone, for a server with no
|
||||
workspace open.
|
||||
|
||||
The overlay holds an entry **only** for references the in-file layer left as
|
||||
`ExternalCandidate`; a locally-resolved reference is absent from it entirely,
|
||||
which is also how a caller tells "resolved locally" from "not an external
|
||||
candidate at all" without re-reading the `Resolution`.
|
||||
The overlay holds an entry for every reference the in-file layer left as
|
||||
`ExternalCandidate`, and — since 2026-08-26,
|
||||
`docs/features/overlay-promotion/README.md` — for an `InheritedCandidate`
|
||||
**when one of its paths actually lands**. A locally-resolved reference is
|
||||
absent from it entirely, and so is an inherited candidate nothing answered:
|
||||
the base class is the in-file layer's answer and this layer does not overrule
|
||||
it, it only adds a location when the unit table has one. So an entry still
|
||||
means "the workspace had something to say about this name".
|
||||
|
||||
## Resolution rules
|
||||
|
||||
@@ -101,7 +105,12 @@ with any hit wins:
|
||||
`import p::x` that only offers itself for the name `x`; the use's name is
|
||||
what is looked up, so the two spellings need no separate handling.)
|
||||
2. A bare path is the **unit itself** when the use spells the unit's name — an
|
||||
instantiated module, the `p` head of `p::x`, the package of an import.
|
||||
instantiated module, the `p` head of `p::x`, the package of an import, and
|
||||
(since `overlay-promotion`) the last path of an unqualified miss written in
|
||||
a **type** position, which is how a cross-file `interface` or package-less
|
||||
`class` used as a type is answered. A miss in a value position never gets
|
||||
such a path, so this layer is never asked to match a bare expression
|
||||
identifier against a unit name.
|
||||
3. A bare path whose name differs from the use's is a **member of that unit**:
|
||||
the `.port` (or `.PARAM` override) of a connection to a module declared in
|
||||
another file.
|
||||
@@ -113,11 +122,16 @@ written"). Ambiguity means something else — see below.
|
||||
|
||||
### What is indexed
|
||||
|
||||
- **Units** (`units(name)`): every file-scope `module`, `package` and
|
||||
`typedef`. File-scope typedefs are indexed for `workspace_symbols` and for a
|
||||
future include-aware lookup; nothing resolves to them today, because a use of
|
||||
a type declared in another file with no import path is `NotFound`, not an
|
||||
external candidate, and so never reaches this layer.
|
||||
- **Units** (`units(name)`): every file-scope `module`, `package`, `typedef`
|
||||
and `class`. ~~File-scope typedefs are indexed for `workspace_symbols` and
|
||||
for a future include-aware lookup; nothing resolves to them today, because a
|
||||
use of a type declared in another file with no import path is `NotFound`,
|
||||
not an external candidate, and so never reaches this layer.~~ **Since
|
||||
2026-08-26 they do resolve**, from a type position: such a use is an external
|
||||
(or inherited) candidate carrying the bare name, so a file-scope `typedef`,
|
||||
`class` or `interface` in another file is reachable from the declaration that
|
||||
names it as a type (`docs/features/overlay-promotion/README.md`). Only from a
|
||||
type position — the same name in an expression is not offered here.
|
||||
- **Package members**: everything declared at a package's top level — params,
|
||||
typedefs, enum variants, functions, tasks, nets and vars. This is what makes
|
||||
`import p::*` and `p::x` reach *into* the package's file.
|
||||
@@ -273,6 +287,49 @@ unresolved-external rate over *all* references falls **19.6 % → 2.6 %**, and
|
||||
"Ambiguous" counts as answered: it is a list of real locations, which is what
|
||||
LSP's definition request takes.
|
||||
|
||||
**Re-measured 2026-08-26** (`overlay-promotion`), same command, same corpus.
|
||||
The table above had gone stale by several rounds, so the before column is a
|
||||
fresh measurement of `3bc61f9`. The index itself did not change: 860 files in
|
||||
0.78 s, 561 modules, 63 packages, 22 file-scope typedefs, 258 classes, 11 937
|
||||
exported members, 507 define directives, before and after, determinism
|
||||
assertions green.
|
||||
|
||||
The middle column is the round's first cut, which promoted **every**
|
||||
unqualified lexical miss; the last is what shipped, promoting only misses
|
||||
written in a *type* position. QA found that the first cut let `rename` rewrite
|
||||
an unrelated file's declaration when an unbound expression identifier happened
|
||||
to match a workspace unit name, so the value half was given back
|
||||
(`docs/features/overlay-promotion/README.md`). Both are shown because the
|
||||
difference between them is the honest price of that fix.
|
||||
|
||||
| metric (clean files, 853 of 860, 94 384 references) | before | promote everything | **type positions only (shipped)** |
|
||||
|---|---:|---:|---:|
|
||||
| handed to the workspace layer | 16 133 (17.1 %) | 17 877 (18.9 %) | **16 689 (17.7 %)** |
|
||||
| …of which inherited candidates | 0 | 520 | **403** |
|
||||
| answered | 89.3 % | 83.7 % | **88.8 %** |
|
||||
| one target / ambiguous | 83.9 % / 5.3 % | 78.9 % / 4.8 % | **83.6 % / 5.2 %** |
|
||||
| still unresolved (of those handed) | 10.7 % | 16.3 % | **11.2 %** |
|
||||
| **references with nowhere to jump, both layers** | **10 794 (11.4 %)** | 10 235 (10.8 %) | **10 376 (11.0 %)** |
|
||||
|
||||
All files: nowhere to jump 10 992 (11.6 %) → 10 431 (11.0 %) → **10 572
|
||||
(11.2 %)**.
|
||||
|
||||
**What survived and what was given back.** Against the `3bc61f9` baseline,
|
||||
**418 references on clean files gained somewhere to jump and none lost one**
|
||||
(420 over all files). The first cut gained 559 on clean files (561 over all),
|
||||
so **141 gains were given back** — identical on both populations. They split
|
||||
117 inherited-candidate answers (520 → 403) and 24 external-bucket answers, and
|
||||
every one of them was a value-position identifier answered on nothing but a
|
||||
name collision. That is the trade, stated plainly: a quarter of the round's
|
||||
jump targets were coincidences, and a coincidence that `rename` can act on is
|
||||
worth less than nothing.
|
||||
|
||||
**The answer rate moving is a denominator, not a result.** This layer is now
|
||||
handed 556 more references than before (153 that were spelled `NotFound` and
|
||||
never offered, 403 inherited candidates), and some of them are names no
|
||||
workspace could hold. The number that cannot move by re-spelling is the last
|
||||
row, which is why the `Tally` in `tests/workspace.rs` prints it.
|
||||
|
||||
**Where the ambiguity comes from** — all of it real, none of it a defect. The
|
||||
top shapes are OpenTitan's technology libraries: `prim_buf`, `prim_flop`,
|
||||
`prim_xor2` and their ports/params are declared once in
|
||||
@@ -291,6 +348,12 @@ the whole corpus.
|
||||
| `SB_SPRAM256KA` | 44 | an iCE40 vendor primitive — no source anywhere |
|
||||
| `PLLE2_ADV` | 32 | a Xilinx vendor primitive — likewise |
|
||||
|
||||
After the 2026-08-26 re-measurement the same list reads `sail_ibexspec` (168),
|
||||
`ibex_pkg::* | uvm_pkg::*` (83, e.g. `id_stage_i`), `ibex_pkg::*` (71, e.g.
|
||||
`main_mode`), `clk_rst_gen` (60) and `SB_SPRAM256KA` (44) — the `picorv32`
|
||||
entries are gone, closed by the parser rounds since. Every remaining one is
|
||||
still a workspace that genuinely does not contain the definition.
|
||||
|
||||
Over all files the list also shows `uvm_pkg::*` (220) and `uart_reg_pkg::*`
|
||||
(214) — a verification library and a generated register package, neither
|
||||
checked into the corpus. Every one of these is a workspace that genuinely does
|
||||
@@ -313,6 +376,9 @@ and more than half of all external candidates answered on clean files.
|
||||
- [x] Per-file `` `define`` tables + workspace-wide `find_define`
|
||||
- [x] `resolve_external` → `ExternalResolutions` overlay keyed by
|
||||
`ReferenceId`, `Semantics` untouched
|
||||
- [x] 2026-08-26 (`overlay-promotion`): the overlay also answers an
|
||||
`InheritedCandidate` from its paths, recording an entry only when one
|
||||
lands; `Tally` reports references with nowhere to jump
|
||||
- [x] Composed `definition_of`, `workspace_symbols`, `members_of`
|
||||
- [x] Unit tests: cross-file instantiation, cross-file port, wildcard and
|
||||
explicit import, package member, enum variant, duplicate → `Ambiguous`,
|
||||
@@ -326,6 +392,17 @@ and more than half of all external candidates answered on clean files.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).**
|
||||
`resolve_external` gained one arm: an `InheritedCandidate`'s paths are tried
|
||||
like an external candidate's, and an entry is recorded only when one lands, so
|
||||
a name this layer cannot answer stays exactly what the single-file layer made
|
||||
it. `counts()`'s doc says what it counts now. `tests/workspace.rs`'s `Tally`
|
||||
reports references with nowhere to jump after both layers, because a
|
||||
re-spelled miss moves between the other columns without anything getting
|
||||
better or worse. Corpus tables above re-measured before, after the first cut,
|
||||
and after the fix round that narrowed the promotion to type positions.
|
||||
Rationale and the full audit: `docs/features/overlay-promotion/README.md`.
|
||||
|
||||
**2026-08-19 — dev agent.** Built `workspace.rs` and `tests/workspace.rs`.
|
||||
Key decisions, all argued above:
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
.astro/
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# lucisv documentation site
|
||||
|
||||
The source and generated static documentation site are self-contained in this directory.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev
|
||||
npm run build
|
||||
```
|
||||
|
||||
The deployable output is `dist/`. It contains pre-rendered HTML, CSS, JavaScript, a Pagefind search index, and XML sitemaps; no application server is required.
|
||||
|
||||
The site uses Astro 7 and Starlight. Documentation pages live in `src/content/docs/`, and visual customization lives in `src/styles/custom.css`.
|
||||
@@ -0,0 +1,61 @@
|
||||
import { defineConfig } from 'astro/config';
|
||||
import starlight from '@astrojs/starlight';
|
||||
|
||||
export default defineConfig({
|
||||
site: 'https://lucisv.dev',
|
||||
output: 'static',
|
||||
integrations: [
|
||||
starlight({
|
||||
title: 'lucisv',
|
||||
description: 'Fast, deterministic formatting, linting, and language intelligence for Verilog and SystemVerilog.',
|
||||
favicon: '/favicon.png',
|
||||
social: [
|
||||
{ icon: 'github', label: 'Source repository', href: 'https://git.luci.ooo/lucio/verilogrustformatter' }
|
||||
],
|
||||
customCss: ['./src/styles/custom.css'],
|
||||
head: [
|
||||
{ tag: 'meta', attrs: { name: 'theme-color', content: '#07111f' } },
|
||||
{ tag: 'meta', attrs: { property: 'og:site_name', content: 'lucisv documentation' } },
|
||||
{ tag: 'meta', attrs: { property: 'og:image', content: 'https://lucisv.dev/og.png' } },
|
||||
{ tag: 'meta', attrs: { property: 'og:image:width', content: '1200' } },
|
||||
{ tag: 'meta', attrs: { property: 'og:image:height', content: '630' } },
|
||||
{ tag: 'meta', attrs: { property: 'og:image:alt', content: 'lucisv — Verilog tooling that stays out of your way.' } },
|
||||
{ tag: 'meta', attrs: { name: 'twitter:card', content: 'summary_large_image' } },
|
||||
{ tag: 'meta', attrs: { name: 'twitter:image', content: 'https://lucisv.dev/og.png' } },
|
||||
{ tag: 'script', attrs: { type: 'application/ld+json' }, content: JSON.stringify({
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'SoftwareApplication',
|
||||
name: 'lucisv',
|
||||
applicationCategory: 'DeveloperApplication',
|
||||
operatingSystem: 'macOS, Linux, Windows',
|
||||
softwareVersion: '0.9.0',
|
||||
license: 'https://opensource.org/licenses/MIT',
|
||||
description: 'A fast Verilog and SystemVerilog formatter, linter, and language server written in Rust.',
|
||||
codeRepository: 'https://git.luci.ooo/lucio/verilogrustformatter'
|
||||
}) }
|
||||
],
|
||||
sidebar: [
|
||||
{ label: 'Start here', items: [
|
||||
{ label: 'Overview', slug: '' },
|
||||
{ label: 'Quick start', slug: 'start/quick-start' },
|
||||
{ label: 'Configuration', slug: 'start/configuration' }
|
||||
] },
|
||||
{ label: 'Use lucisv', items: [
|
||||
{ label: 'Formatter', slug: 'guides/formatter' },
|
||||
{ label: 'Linter', slug: 'guides/linter' },
|
||||
{ label: 'Editors & LSP', slug: 'guides/editors' },
|
||||
{ label: 'Supported syntax', slug: 'guides/syntax' }
|
||||
] },
|
||||
{ label: 'Reference', items: [
|
||||
{ label: 'CLI', slug: 'reference/cli' },
|
||||
{ label: 'Lint rules', slug: 'reference/rules' },
|
||||
{ label: 'Language tools', slug: 'reference/language-tools' },
|
||||
{ label: 'Rust API index', slug: 'reference/rust-api' },
|
||||
{ label: 'Architecture', slug: 'reference/architecture' }
|
||||
] }
|
||||
],
|
||||
editLink: { baseUrl: 'https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/' },
|
||||
lastUpdated: true
|
||||
})
|
||||
]
|
||||
});
|
||||
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
<!DOCTYPE html><html lang="en" dir="ltr" data-theme="dark" data-has-hero class="astro-vdxcvpsm"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>404 | lucisv</title><link rel="canonical" href="https://lucisv.dev/404/"/><link rel="sitemap" href="/sitemap-index.xml"/><script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"lucisv","applicationCategory":"DeveloperApplication","operatingSystem":"macOS, Linux, Windows","softwareVersion":"0.9.0","license":"https://opensource.org/licenses/MIT","description":"A fast Verilog and SystemVerilog formatter, linter, and language server written in Rust.","codeRepository":"https://git.luci.ooo/lucio/verilogrustformatter"}</script><link rel="shortcut icon" href="/favicon.png" type="image/png"/><meta name="generator" content="Astro v7.2.8"/><meta name="generator" content="Starlight v0.41.9"/><meta property="og:title" content="404"/><meta property="og:type" content="article"/><meta property="og:url" content="https://lucisv.dev/404/"/><meta property="og:locale" content="en"/><meta property="og:description" content="Fast, deterministic formatting, linting, and language intelligence for Verilog and SystemVerilog."/><meta name="description" content="Fast, deterministic formatting, linting, and language intelligence for Verilog and SystemVerilog."/><meta name="theme-color" content="#07111f"/><meta property="og:site_name" content="lucisv documentation"/><meta property="og:image" content="https://lucisv.dev/og.png"/><meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/><meta property="og:image:alt" content="lucisv — Verilog tooling that stays out of your way."/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:image" content="https://lucisv.dev/og.png"/><script>
|
||||
window.StarlightThemeProvider = (() => {
|
||||
const storedTheme =
|
||||
typeof localStorage !== 'undefined' && localStorage.getItem('starlight-theme');
|
||||
const theme =
|
||||
storedTheme ||
|
||||
(window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark';
|
||||
return {
|
||||
updatePickers(theme = storedTheme || 'auto') {
|
||||
document.querySelectorAll('starlight-theme-select').forEach((picker) => {
|
||||
const select = picker.querySelector('select');
|
||||
if (select) select.value = theme;
|
||||
/** @type {HTMLTemplateElement | null} */
|
||||
const tmpl = document.querySelector(`#theme-icons`);
|
||||
const newIcon = tmpl && tmpl.content.querySelector('.' + theme);
|
||||
if (newIcon) {
|
||||
const oldIcon = picker.querySelector('svg.label-icon');
|
||||
if (oldIcon) {
|
||||
oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
})();
|
||||
</script><template id="theme-icons"><svg aria-hidden="true" class="light astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M5 12a1 1 0 0 0-1-1H3a1 1 0 0 0 0 2h1a1 1 0 0 0 1-1Zm.64 5-.71.71a1 1 0 0 0 0 1.41 1 1 0 0 0 1.41 0l.71-.71A1 1 0 0 0 5.64 17ZM12 5a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1a1 1 0 0 0 1 1Zm5.66 2.34a1 1 0 0 0 .7-.29l.71-.71a1 1 0 1 0-1.41-1.41l-.66.71a1 1 0 0 0 0 1.41 1 1 0 0 0 .66.29Zm-12-.29a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.71-.71a1.004 1.004 0 1 0-1.43 1.41l.73.71ZM21 11h-1a1 1 0 0 0 0 2h1a1 1 0 0 0 0-2Zm-2.64 6A1 1 0 0 0 17 18.36l.71.71a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.76-.66ZM12 6.5a5.5 5.5 0 1 0 5.5 5.5A5.51 5.51 0 0 0 12 6.5Zm0 9a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7Zm0 3.5a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-1a1 1 0 0 0-1-1Z"/></svg><svg aria-hidden="true" class="dark astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.64 13a1 1 0 0 0-1.05-.14 8.049 8.049 0 0 1-3.37.73 8.15 8.15 0 0 1-8.14-8.1 8.59 8.59 0 0 1 .25-2A1 1 0 0 0 8 2.36a10.14 10.14 0 1 0 14 11.69 1 1 0 0 0-.36-1.05Zm-9.5 6.69A8.14 8.14 0 0 1 7.08 5.22v.27a10.15 10.15 0 0 0 10.14 10.14 9.784 9.784 0 0 0 2.1-.22 8.11 8.11 0 0 1-7.18 4.32v-.04Z"/></svg><svg aria-hidden="true" class="auto astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg></template><link rel="stylesheet" href="/_astro/print.ehPL0gv-.css" media="print"><link rel="stylesheet" href="/_astro/common.db7thnbo.css"><script type="module" src="/_astro/page.Dwipeu-R.js"></script></head><body class="astro-vdxcvpsm"><a class="sl-skip-link astro-vxeigawq" href="#_top">Skip to content</a><div class="page sl-flex astro-gqpr5s5a"><header class="header astro-gqpr5s5a"><div class="header astro-nczgtkxc"><div class="title-wrapper sl-flex astro-nczgtkxc"><a href="/" class="site-title sl-flex astro-clw6ags5"><span class="astro-clw6ags5" translate="no">lucisv</span></a></div><div class="sl-flex print:hidden astro-nczgtkxc"><site-search class="astro-nczgtkxc astro-r5ar4xm7" data-translations="{"placeholder":"Search"}"><button data-open-modal disabled aria-label="Search" aria-keyshortcuts="Control+K" class="astro-r5ar4xm7"><svg aria-hidden="true" class="astro-r5ar4xm7 astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.71 20.29 18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.39ZM11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z"/></svg><span class="sl-hidden md:sl-block astro-r5ar4xm7" aria-hidden="true">Search</span><kbd class="sl-hidden md:sl-flex astro-r5ar4xm7" style="display: none;"><kbd class="astro-r5ar4xm7">Ctrl</kbd><kbd class="astro-r5ar4xm7">K</kbd></kbd></button><dialog style="padding:0" aria-label="Search" class="astro-r5ar4xm7"><div class="dialog-frame sl-flex astro-r5ar4xm7"><button data-close-modal class="sl-flex md:sl-hidden astro-r5ar4xm7">Cancel</button><div class="search-container astro-r5ar4xm7"><div id="starlight__search" class="astro-r5ar4xm7"></div></div></div></dialog></site-search><script>
|
||||
(() => {
|
||||
const openBtn = document.querySelector('button[data-open-modal]');
|
||||
const shortcut = openBtn?.querySelector('kbd');
|
||||
if (!openBtn || !(shortcut instanceof HTMLElement)) return;
|
||||
const platformKey = shortcut.querySelector('kbd');
|
||||
if (platformKey && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
|
||||
platformKey.textContent = '⌘';
|
||||
openBtn.setAttribute('aria-keyshortcuts', 'Meta+K');
|
||||
}
|
||||
shortcut.style.display = '';
|
||||
})();
|
||||
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><div class="main-pane astro-abfeecmu"><main class="astro-vdxcvpsm" lang="en" dir="ltr"><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><div class="hero astro-q2ezz3gc"><div class="sl-flex stack astro-q2ezz3gc"><div class="sl-flex copy astro-q2ezz3gc"><h1 id="_top" data-page-title class="astro-q2ezz3gc">404</h1><div class="tagline astro-q2ezz3gc">Page not found. Check the URL or try using the search bar.</div></div></div></div><div class="sl-markdown-content"></div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
import{t as e}from"./starlight-toc.CTCQXEge.js";var t=class extends e{set current(e){super.current=e;let t=this.querySelector(`.display-current`);t&&(t.textContent=e.textContent)}constructor(){super();let e=this.querySelector(`details`);if(!e)return;let t=()=>{e.open=!1};e.querySelectorAll(`a`).forEach(e=>{e.addEventListener(`click`,t)}),window.addEventListener(`click`,n=>{e.contains(n.target)||t()}),window.addEventListener(`keydown`,n=>{if(n.key===`Escape`&&e.open){let n=e.contains(document.activeElement);if(t(),n){let t=e.querySelector(`summary`);t&&t.focus()}}})}};customElements.define(`mobile-starlight-toc`,t);
|
||||
@@ -0,0 +1 @@
|
||||
var e={ranking:{pageLength:.1,termFrequency:.1,termSaturation:2,termSimilarity:9,diacriticSimilarity:.8}},t=(function(){let e=typeof document<`u`&&document.createElement(`link`).relList;return e&&e.supports&&e.supports(`modulepreload`)?`modulepreload`:`preload`})(),n=function(e){return`/`+e},r={},i=function(e,i,a){let o=Promise.resolve();if(i&&i.length>0){let e=document.getElementsByTagName(`link`),s=document.querySelector(`meta[property=csp-nonce]`),c=s?.nonce||s?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}o=l(i.map(i=>{if(i=n(i,a),i=u(i),i in r)return;r[i]=!0;let o=i.endsWith(`.css`);for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.href===i&&(!o||n.rel===`stylesheet`))return}let s=document.createElement(`link`);if(s.rel=o?`stylesheet`:t,o||(s.as=`script`),s.crossOrigin=``,s.href=i,c&&s.setAttribute(`nonce`,c),document.head.appendChild(s),o)return new Promise((e,t)=>{s.addEventListener(`load`,e),s.addEventListener(`error`,()=>t(Error(`Unable to preload CSS for ${i}`)))})}))}function s(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return o.then(t=>{for(let e of t||[])e.status===`rejected`&&s(e.reason);return e().catch(s)})},a=class extends HTMLElement{constructor(){super();let t=this.querySelector(`button[data-open-modal]`),n=this.querySelector(`button[data-close-modal]`),r=this.querySelector(`dialog`),a=this.querySelector(`.dialog-frame`),o=e=>{(`href`in(e.target||{})||document.body.contains(e.target)&&!a.contains(e.target))&&c()},s=e=>{r.showModal(),document.body.toggleAttribute(`data-search-modal-open`,!0),this.querySelector(`input`)?.focus(),e?.stopPropagation(),window.addEventListener(`click`,o)},c=()=>r.close();t.addEventListener(`click`,s),t.disabled=!1,n.addEventListener(`click`,c),r.addEventListener(`close`,()=>{document.body.toggleAttribute(`data-search-modal-open`,!1),window.removeEventListener(`click`,o)}),window.addEventListener(`keydown`,e=>{(e.metaKey===!0||e.ctrlKey===!0)&&e.key===`k`&&(r.open?c():s(),e.preventDefault())});let l={};try{l=JSON.parse(this.dataset.translations||`{}`)}catch{}let u=this.dataset.stripTrailingSlash===void 0?e=>e:e=>e.replace(/(.)\/(#.*)?$/,`$1$2`);window.addEventListener(`DOMContentLoaded`,()=>{(window.requestIdleCallback||(e=>setTimeout(e,1)))(async()=>{let{PagefindUI:t}=await i(async()=>{let{PagefindUI:e}=await import(`./ui-core.BzPh4z-r.js`);return{PagefindUI:e}},[]);new t({...e,element:`#starlight__search`,baseUrl:`/`,bundlePath:`/`.replace(/\/$/,``)+`/pagefind/`,showImages:!1,translations:l,showSubResults:!0,processResult:e=>{e.url=u(e.url),e.sub_results=e.sub_results.map(e=>(e.url=u(e.url),e))}})})})}};customElements.define(`site-search`,a);export{i as t};
|
||||
+1
@@ -0,0 +1 @@
|
||||
import"./starlight-toc.CTCQXEge.js";
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
:root{--sl-color-accent-low:#d8f8ed;--sl-color-accent:#087d5b;--sl-color-accent-high:#064834;--sl-color-white:#122033;--sl-color-gray-1:#24364d;--sl-color-gray-2:#40536a;--sl-color-gray-3:#6d7f93;--sl-color-gray-4:#aeb9c5;--sl-color-gray-5:#dbe2e8;--sl-color-gray-6:#eef2f5;--sl-color-black:#f9fbfc;--sl-font:Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;--sl-font-mono:"SFMono-Regular", Consolas, "Liberation Mono", monospace}:root[data-theme=dark]{--sl-color-accent-low:#123c32;--sl-color-accent:#62e5b4;--sl-color-accent-high:#c8fae9;--sl-color-white:#f4f9ff;--sl-color-gray-1:#d5e1ec;--sl-color-gray-2:#a8b9ca;--sl-color-gray-3:#778da3;--sl-color-gray-4:#40546a;--sl-color-gray-5:#24364a;--sl-color-gray-6:#152437;--sl-color-black:#07111f}html{scroll-behavior:smooth}body{letter-spacing:-.01em}header.header{backdrop-filter:blur(18px);background:color-mix(in srgb, var(--sl-color-black) 82%, transparent);border-bottom-color:color-mix(in srgb, var(--sl-color-gray-5) 72%, transparent)}.site-title img{width:8.6rem;height:auto}.hero{padding-block:clamp(4rem,9vw,8rem)!important}.hero .copy{max-width:48rem}.hero h1{letter-spacing:-.075em;font-size:clamp(3.2rem,8vw,6.6rem);line-height:.92}.hero .tagline{max-width:42rem;color:var(--sl-color-gray-2);font-size:clamp(1.1rem,2vw,1.35rem)}.hero .actions a{box-shadow:none;border-radius:.7rem;font-weight:700}.hero .actions .primary{color:#04130e;background:#18a879}.hero .actions .primary:hover{background:#62e5b4}.sl-markdown-content h2{letter-spacing:-.035em}.sl-markdown-content h3{letter-spacing:-.02em}.sl-markdown-content code:not(pre code){border:1px solid var(--sl-color-gray-5);border-radius:.35rem;padding:.08rem .3rem}.sl-markdown-content table{width:100%;font-size:.9rem;display:table}.sl-markdown-content th{letter-spacing:.08em;text-transform:uppercase;font-size:.74rem}.card-grid{grid-template-columns:repeat(12,1fr);gap:1rem;margin:2.25rem 0 4rem;display:grid}.feature-card{border:1px solid var(--sl-color-gray-5);background:linear-gradient(145deg, color-mix(in srgb, var(--sl-color-black) 95%, var(--sl-color-accent-low)), var(--sl-color-black));border-radius:1rem;grid-column:span 4;min-height:13rem;padding:1.35rem}.feature-card:first-child,.feature-card:nth-child(5){grid-column:span 8}.feature-card .eyebrow{color:var(--sl-color-accent);font:700 .72rem/1 var(--sl-font-mono);letter-spacing:.11em;text-transform:uppercase}.feature-card h3{margin:.8rem 0 .5rem;font-size:1.25rem}.feature-card p{color:var(--sl-color-gray-2);margin:0}.metric-row{grid-template-columns:repeat(4,1fr);gap:.75rem;margin-block:2rem 4rem;display:grid}.metric{border-left:2px solid var(--sl-color-accent);padding:1rem}.metric strong{font:750 1.55rem/1.1 var(--sl-font-mono);display:block}.metric span{color:var(--sl-color-gray-3);font-size:.82rem}.pipeline{align-items:stretch;gap:.6rem;margin:2rem 0 3rem;display:flex}.pipeline>div{border:1px solid var(--sl-color-gray-5);border-radius:.75rem;flex:1;padding:1rem}.pipeline b{font-family:var(--sl-font-mono);color:var(--sl-color-accent);margin-bottom:.3rem;display:block}.pipeline i{color:var(--sl-color-gray-3);align-self:center;font-style:normal}.api-list{columns:2;column-gap:2.5rem}.api-list li{break-inside:avoid;margin-bottom:.42rem}.badge{border:1px solid var(--sl-color-gray-5);font:650 .72rem var(--sl-font-mono);border-radius:999px;align-items:center;gap:.35rem;padding:.22rem .55rem;display:inline-flex}.badge:before{content:"";background:var(--sl-color-accent);border-radius:50%;width:.42rem;height:.42rem}@media (width<=50rem){.feature-card,.feature-card:first-child,.feature-card:nth-child(5){grid-column:1/-1;min-height:auto}.metric-row{grid-template-columns:repeat(2,1fr)}.pipeline{flex-direction:column}.pipeline i{transform:rotate(90deg)}.api-list{columns:1}}@media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}}@layer starlight.base{:root,::backdrop{--sl-color-white:#fff;--sl-color-gray-1:#edeef3;--sl-color-gray-2:#c1c3c8;--sl-color-gray-3:#888c96;--sl-color-gray-4:#555962;--sl-color-gray-5:#353841;--sl-color-gray-6:#23262f;--sl-color-black:#17181c;--sl-hue-orange:41;--sl-color-orange-low:hsl(var(--sl-hue-orange), 39%, 22%);--sl-color-orange:hsl(var(--sl-hue-orange), 82%, 63%);--sl-color-orange-high:hsl(var(--sl-hue-orange), 82%, 87%);--sl-hue-green:101;--sl-color-green-low:hsl(var(--sl-hue-green), 39%, 22%);--sl-color-green:hsl(var(--sl-hue-green), 82%, 63%);--sl-color-green-high:hsl(var(--sl-hue-green), 82%, 80%);--sl-hue-blue:234;--sl-color-blue-low:hsl(var(--sl-hue-blue), 54%, 20%);--sl-color-blue:hsl(var(--sl-hue-blue), 100%, 60%);--sl-color-blue-high:hsl(var(--sl-hue-blue), 100%, 87%);--sl-hue-purple:281;--sl-color-purple-low:hsl(var(--sl-hue-purple), 39%, 22%);--sl-color-purple:hsl(var(--sl-hue-purple), 82%, 63%);--sl-color-purple-high:hsl(var(--sl-hue-purple), 82%, 89%);--sl-hue-red:339;--sl-color-red-low:hsl(var(--sl-hue-red), 39%, 22%);--sl-color-red:hsl(var(--sl-hue-red), 82%, 63%);--sl-color-redLine truncated
|
||||
){.sl-markdown-content .starlight-aside :is(th,td,hr,blockquote):not(:where(.not-content *)){border-color:color-mix(in srgb, var(--sl-color-asides-text-accent) 30%, transparent)}}@supports (border-color:color-mix(in srgb, var(--sl-color-asides-text-accent) 12%, transparent)
|
||||
){.sl-markdown-content .starlight-aside code:not(:where(.not-content *)){background-color:color-mix(in srgb, var(--sl-color-asides-text-accent) 12%, transparent)}}.sl-markdown-content hr:not(:where(.not-content *)){border:0;border-bottom:1px solid var(--sl-color-hairline)}.sl-markdown-content details:not(:where(.not-content *)){--sl-details-border-color:var(--sl-color-gray-5);--sl-details-border-color--hover:var(--sl-color-text-accent);border-inline-start:2px solid var(--sl-details-border-color);padding-inline-start:1rem}.sl-markdown-content details:not([open]):hover:not(:where(.not-content *)),.sl-markdown-content details:has(>summary:hover):not(:where(.not-content *)){border-color:var(--sl-details-border-color--hover)}.sl-markdown-content summary:not(:where(.not-content *)){color:var(--sl-color-white);cursor:pointer;margin-inline-start:-.5rem;padding-inline-start:.5rem;font-weight:600;display:block}.sl-markdown-content details[open]>summary:not(:where(.not-content *)){margin-bottom:1rem}.sl-markdown-content summary:not(:where(.not-content *))::marker,.sl-markdown-content summary:not(:where(.not-content *))::-webkit-details-marker{display:none}.sl-markdown-content summary:not(:where(.not-content *)):before{--sl-details-marker-size:1.25rem;content:"";height:var(--sl-details-marker-size);width:var(--sl-details-marker-size);margin-inline:calc((var(--sl-details-marker-size) / 4) * -1) .25rem;vertical-align:middle;background-color:currentColor;display:inline-block;-webkit-mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M14.8 11.3 10.6 7a1 1 0 1 0-1.4 1.5l3.5 3.5-3.5 3.5a1 1 0 0 0 0 1.4 1 1 0 0 0 .7.3 1 1 0 0 0 .7-.3l4.2-4.2a1 1 0 0 0 0-1.4Z'/%3E%3C/svg%3E%0A");mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M14.8 11.3 10.6 7a1 1 0 1 0-1.4 1.5l3.5 3.5-3.5 3.5a1 1 0 0 0 0 1.4 1 1 0 0 0 .7.3 1 1 0 0 0 .7-.3l4.2-4.2a1 1 0 0 0 0-1.4Z'/%3E%3C/svg%3E%0A");-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}@media (prefers-reduced-motion:no-preference){.sl-markdown-content summary:not(:where(.not-content *)):before{transition:transform .2s ease-in-out}}.sl-markdown-content details[open]>summary:not(:where(.not-content *)):before{transform:rotate(90deg)}[dir=rtl] .sl-markdown-content summary:not(:where(.not-content *)):before,.sl-markdown-content [dir=rtl] summary:not(:where(.not-content *)):before{transform:rotate(180deg)}.sl-markdown-content summary:not(:where(.not-content *)) p:only-child{display:inline}.sl-markdown-content .starlight-aside details:not(:where(.not-content *)){--sl-details-border-color:var(--sl-color-asides-border);--sl-details-border-color--hover:var(--sl-color-asides-text-accent)}}@layer starlight.components{.starlight-aside{border-inline-start:.25rem solid var(--sl-color-asides-border);color:var(--sl-color-white);padding:1rem}.starlight-aside--note{--sl-color-asides-text-accent:var(--sl-color-blue-high);--sl-color-asides-border:var(--sl-color-blue);background-color:var(--sl-color-blue-low)}.starlight-aside--tip{--sl-color-asides-text-accent:var(--sl-color-purple-high);--sl-color-asides-border:var(--sl-color-purple);background-color:var(--sl-color-purple-low)}.starlight-aside--caution{--sl-color-asides-text-accent:var(--sl-color-orange-high);--sl-color-asides-border:var(--sl-color-orange);background-color:var(--sl-color-orange-low)}.starlight-aside--danger{--sl-color-asides-text-accent:var(--sl-color-red-high);--sl-color-asides-border:var(--sl-color-red);background-color:var(--sl-color-red-low)}.starlight-aside__title{font-size:var(--sl-text-h5);font-weight:600;line-height:var(--sl-line-height-headings);color:var(--sl-color-asides-text-accent);align-items:center;gap:.5rem;display:flex}.starlight-aside__icon{width:1em;height:1em;font-size:1.333em}.starlight-aside__title+.starlight-aside__content{margin-top:.5rem}.starlight-aside__content:empty{display:none}.starlight-aside__content a{color:var(--sl-color-asides-text-accent)}svg:where(.astro-n5k4ipy7){color:var(--sl-icon-color);font-size:var(--sl-icon-size,1em);width:1em;height:1em}:root{--sl-badge-default-border:var(--sl-color-accent);--sl-badge-default-bg:var(--sl-color-accent-low);--sl-badge-default-text:#fff;--sl-badge-note-border:var(--sl-color-blue);--sl-badge-note-bg:var(--sl-color-blue-low);--sl-badge-note-text:#fff;--sl-badge-danger-border:var(--sl-color-red);--sl-badge-danger-bg:var(--sl-color-red-low);--sl-badge-danger-text:#fff;--sl-badge-success-border:var(--sl-color-green);--sl-badge-success-bg:var(--sl-color-green-low);--sl-badge-success-text:#fff;--sl-badge-caution-border:var(--sl-color-orange);--sl-badge-caution-bg:var(--sl-color-orange-low);--sl-badge-caution-text:#fff;--sl-badge-tip-border:var(--sl-color-purple);--sl-badge-tip-bg:var(--sl-color-purple-low);--sl-badge-tip-text:#fff}[data-theme=light]:root{--sl-badge-default-bg:var(--sl-color-accent-high);--sl-badge-note-bg:var(--sl-color-blue-high);--sl-badge-Line truncated
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
try{(()=>{function a(e){if(!e)return;let t=e.getAttribute("tabindex")!==null,r=e.scrollWidth>e.clientWidth;r&&!t?(e.setAttribute("tabindex","0"),e.setAttribute("role","region")):!r&&t&&(e.removeAttribute("tabindex"),e.removeAttribute("role"))}var u=window.requestIdleCallback||(e=>setTimeout(e,1)),s=window.cancelIdleCallback||clearTimeout;function l(e){let t=new Set,r,n;return new ResizeObserver(c=>{c.forEach(o=>t.add(o.target)),r&&clearTimeout(r),n&&s(n),r=setTimeout(()=>{n&&s(n),n=u(()=>{t.forEach(o=>e(o)),t.clear()})},250)})}function i(e,t){e.querySelectorAll?.(".expressive-code pre > code").forEach(r=>{let n=r.parentElement;n&&t.observe(n)})}var d=l(a);i(document,d);var b=new MutationObserver(e=>e.forEach(t=>t.addedNodes.forEach(r=>{i(r,d)})));b.observe(document.body,{childList:!0,subtree:!0});document.addEventListener("astro:page-load",()=>{i(document,d)});})();}catch(e){console.error("[EC] tabindex-js-module failed:",e)}
|
||||
try{(()=>{function l(o){let e=document.createElement("pre");Object.assign(e.style,{opacity:"0",pointerEvents:"none",position:"absolute",overflow:"hidden",left:"0",top:"0",width:"20px",height:"20px",webkitUserSelect:"auto",userSelect:"all"}),e.ariaHidden="true",e.textContent=o,document.body.appendChild(e);let a=document.createRange();a.selectNode(e);let n=getSelection();if(!n)return!1;n.removeAllRanges(),n.addRange(a);let r=!1;try{r=document.execCommand("copy")}finally{n.removeAllRanges(),document.body.removeChild(e)}return r}async function u(o){let e=o.currentTarget,a=e.dataset,n=!1,r=a.code.replace(/\u007f/g,`
|
||||
`);try{await navigator.clipboard.writeText(r),n=!0}catch{n=l(r)}if(!n||e.parentNode?.querySelector(".feedback"))return;let c=e.parentNode?.querySelector("[aria-live]"),t=document.createElement("div");t.classList.add("feedback"),t.append(a.copied),c.append(t),t.offsetWidth,requestAnimationFrame(()=>t?.classList.add("show"));let s=()=>!t||t.classList.remove("show"),d=()=>{!t||parseFloat(getComputedStyle(t).opacity)>0||(t.remove(),t=void 0)};setTimeout(s,1500),setTimeout(d,2500),e.addEventListener("blur",s),t.addEventListener("transitioncancel",d),t.addEventListener("transitionend",d)}function i(o){o.querySelectorAll?.(".expressive-code .copy button").forEach(e=>e.addEventListener("click",u))}i(document);var m=new MutationObserver(o=>o.forEach(e=>e.addedNodes.forEach(a=>{i(a)})));m.observe(document.body,{childList:!0,subtree:!0});document.addEventListener("astro:page-load",()=>{i(document)});})();}catch(e){console.error("[EC] copy-js-module failed:",e)}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
@layer starlight.components{.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre > code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:'gutter code';grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter > *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, ' ');padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;paddingLine truncated
|
||||
+1
@@ -0,0 +1 @@
|
||||
var e={},t=new Set,n=new WeakSet,r=!0,i=void 0,a=!1;function o(e){a||(a=!0,r??=e?.prefetchAll??!1,i??=e?.defaultStrategy??`hover`,s(),c(),l(),d())}function s(){for(let e of[`touchstart`,`mousedown`])document.addEventListener(e,e=>{let t=e.target.closest(`a`);m(t,`tap`)&&f(t.href,{ignoreSlowConnection:!0})},{passive:!0})}function c(){let e;document.body.addEventListener(`focusin`,e=>{let n=e.target.closest(`a`);m(n,`hover`)&&t(n.href)},{passive:!0}),document.body.addEventListener(`focusout`,r,{passive:!0}),g(()=>{for(let e of document.getElementsByTagName(`a`))n.has(e)||m(e,`hover`)&&(n.add(e),e.addEventListener(`mouseenter`,e=>t(e.currentTarget.href),{passive:!0}),e.addEventListener(`mouseleave`,r,{passive:!0}))});function t(t){e&&clearTimeout(e),e=setTimeout(()=>{f(t)},80)}function r(){e&&=(clearTimeout(e),0)}}function l(){let e;g(()=>{for(let t of document.getElementsByTagName(`a`))n.has(t)||m(t,`viewport`)&&(n.add(t),e??=u(),e.observe(t))})}function u(){let e=new WeakMap;return new IntersectionObserver((t,n)=>{for(let r of t){let t=r.target,i=e.get(t);r.isIntersecting?(i&&clearTimeout(i),e.set(t,setTimeout(()=>{n.unobserve(t),e.delete(t),f(t.href)},300))):i&&(clearTimeout(i),e.delete(t))}})}function d(){g(()=>{for(let e of document.getElementsByTagName(`a`))m(e,`load`)&&f(e.href)})}function f(n,r){n=n.replace(/#.*/,``);let i=r?.ignoreSlowConnection??!1;if(p(n,i)){if(t.add(n),document.createElement(`link`).relList?.supports?.(`prefetch`)){let e=document.createElement(`link`);e.rel=`prefetch`,e.setAttribute(`href`,n),document.head.append(e)}else{let t=new Headers;for(let[n,r]of Object.entries(e))t.set(n,r);fetch(n,{priority:`low`,headers:t}).catch(()=>{})}}}function p(e,n){if(!navigator.onLine||!n&&h())return!1;try{let n=new URL(e,location.href);return location.origin===n.origin&&(location.pathname!==n.pathname||location.search!==n.search)&&!t.has(e)}catch{}return!1}function m(e,t){if(e?.tagName!==`A`)return!1;let n=e.dataset.astroPrefetch;return n===`false`?!1:t===`tap`&&(n!=null||r)&&h()?!0:n==null&&r||n===``?t===i:n===t}function h(){if(`connection`in navigator){let e=navigator.connection;return e.saveData||/2g/.test(e.effectiveType)}return!1}function g(e){e();let t=!1;document.addEventListener(`astro:page-load`,()=>{if(!t){t=!0;return}e()}),new MutationObserver(t=>{for(let n of t)for(let t of n.addedNodes)if(t instanceof Element&&(t.tagName===`A`||t.querySelector?.(`a`))){e();return}}).observe(document.body,{childList:!0,subtree:!0})}o();
|
||||
+1
@@ -0,0 +1 @@
|
||||
@media print{:root{--sl-color-white:#17181c;--sl-color-gray-1:#23262f;--sl-color-gray-2:#353841;--sl-color-gray-3:#555962;--sl-color-gray-4:#888c96;--sl-color-gray-5:#c1c3c8;--sl-color-gray-6:#edeef3;--sl-color-gray-7:#f6f7f9;--sl-color-black:#fff;--sl-color-orange-high:hsl(var(--sl-hue-orange), 80%, 25%);--sl-color-orange:hsl(var(--sl-hue-orange), 90%, 60%);--sl-color-orange-low:hsl(var(--sl-hue-orange), 90%, 88%);--sl-color-green-high:hsl(var(--sl-hue-green), 80%, 22%);--sl-color-green:hsl(var(--sl-hue-green), 90%, 46%);--sl-color-green-low:hsl(var(--sl-hue-green), 85%, 90%);--sl-color-blue-high:hsl(var(--sl-hue-blue), 80%, 30%);--sl-color-blue:hsl(var(--sl-hue-blue), 90%, 60%);--sl-color-blue-low:hsl(var(--sl-hue-blue), 88%, 90%);--sl-color-purple-high:hsl(var(--sl-hue-purple), 90%, 30%);--sl-color-purple:hsl(var(--sl-hue-purple), 90%, 60%);--sl-color-purple-low:hsl(var(--sl-hue-purple), 80%, 90%);--sl-color-red-high:hsl(var(--sl-hue-red), 80%, 30%);--sl-color-red:hsl(var(--sl-hue-red), 90%, 60%);--sl-color-red-low:hsl(var(--sl-hue-red), 80%, 90%);--sl-color-accent-high:#0f1c8a;--sl-color-accent:#3d50f5;--sl-color-accent-low:#cfd4fc;--sl-color-text-accent:var(--sl-color-accent);--sl-color-text-invert:var(--sl-color-black);--sl-color-bg-nav:var(--sl-color-gray-7);--sl-color-bg-sidebar:var(--sl-color-bg);--sl-color-bg-inline-code:var(--sl-color-gray-6);--sl-color-bg-accent:var(--sl-color-accent);--sl-color-hairline-light:var(--sl-color-gray-6);--sl-color-hairline-shade:var(--sl-color-gray-6);--sl-color-backdrop-overlay:#545864a8;--sl-shadow-sm:none;--sl-shadow-md:none;--sl-shadow-lg:none}.print\:hidden{display:none}.print\:flex{display:flex}.print\:block{display:block}main{padding-bottom:0}main>.content-panel{padding-block-start:0}.content-panel+.content-panel{border:0}.page>header{position:relative}.page>.main-frame{padding-top:0;padding-inline-start:0}.main-pane{--sl-sidebar-width:0px;--sl-content-width:100%}.sl-banner{--sl-color-banner-text:var(--sl-color-white);background-color:#0000}.sl-markdown-content :is(h1,h2,h3,h4,h5,h6){break-after:avoid}.sl-markdown-content :is(p,li){orphans:2;widows:2}.sl-markdown-content pre{white-space:pre-wrap;overflow-x:hidden}.sl-markdown-content .expressive-code,.sl-markdown-content figure,.sl-markdown-content pre{break-inside:avoid}.expressive-code .frame.is-terminal .header:before{box-shadow:inset 99rem 99rem var(--sl-color-gray-5)}.expressive-code .frame.has-title:not(.is-terminal) .header{border-bottom:1px solid var(--sl-color-gray-6);background:0 0}.expressive-code .frame.has-title:not(.is-terminal) .title{background:0 0}.expressive-code .frame.has-title:not(.is-terminal) .title:after{border-top:0}.expressive-code .copy{display:none}.sl-markdown-content code:not(:where(.not-content *)){margin-block:unset;background-color:#0000;padding:0;font-size:.9375em}.sl-badge{color:var(--sl-color-white);background:0 0}starlight-file-tree{break-inside:avoid}starlight-file-tree .highlight{outline:3px solid var(--sl-color-accent-low);color:var(--sl-color-text);background-color:#0000}.starlight-aside{break-inside:avoid}.sl-link-button.primary{border-color:var(--sl-color-white);color:var(--sl-color-white);background:0 0}starlight-tabs{break-inside:avoid}.sl-steps>li:after{box-shadow:inset 99rem 99rem var(--sl-color-hairline-light)}}
|
||||
@@ -0,0 +1 @@
|
||||
var e=`_top`,t=class extends HTMLElement{_current=this.querySelector(`a[aria-current="true"]`);minH=parseInt(this.dataset.minH||`2`,10);maxH=parseInt(this.dataset.maxH||`3`,10);tocHeadingSelector=`h1#${e},:where(${[...Array.from({length:1+this.maxH-this.minH}).map((e,t)=>`h${this.minH+t}`)].join()})[id]`;set current(e){e!==this._current&&(this._current&&this._current.removeAttribute(`aria-current`),e.setAttribute(`aria-current`,`true`),this._current=e)}onIdle=e=>(window.requestIdleCallback||(e=>setTimeout(e,1)))(e);constructor(){super(),this.onIdle(()=>this.init())}init=()=>{let t=[...this.querySelectorAll(`a`)],n=e=>e.matches(this.tocHeadingSelector),r=t=>{if(!t)return null;let i=t;for(;t;){if(t.matches(`.sl-markdown-content, main > *`))return document.getElementById(e);if(n(t))return t;let i=t.querySelector(this.tocHeadingSelector);if(i)return i;for(t=t.previousElementSibling;t?.lastElementChild;)t=t.lastElementChild;let a=r(t);if(a)return a}return r(i.parentElement)},i=e=>{for(let{isIntersecting:n,target:i}of e){if(!n)continue;let e=r(i);if(!e)continue;let a=t.find(t=>t.hash===`#`+encodeURIComponent(e.id));if(a){this.current=a;break}}},a=document.querySelectorAll([`main :where(${this.tocHeadingSelector})`,`main :where(${this.tocHeadingSelector}, .sl-heading-wrapper) ~ *:not(:has(${this.tocHeadingSelector}))`,`main .sl-markdown-content > *:not(:has(${this.tocHeadingSelector}))`,`main > *:not(:has(${this.tocHeadingSelector}))`].join()),o,s=()=>{o||(o=new IntersectionObserver(i,{rootMargin:this.getRootMargin()}),a.forEach(e=>o.observe(e)))};s();let c;window.addEventListener(`resize`,()=>{o&&=(o.disconnect(),void 0),clearTimeout(c),c=setTimeout(()=>this.onIdle(s),200)})};getRootMargin(){let e=(document.querySelector(`header`)?.getBoundingClientRect().height||0)+(this.querySelector(`summary`)?.getBoundingClientRect().height||0)+32;return`-${e}px 0% ${e+53-document.documentElement.clientHeight}px`}};customElements.define(`starlight-toc`,t);export{t};
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import{t as e}from"./Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js";var t=Object.defineProperty,n=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})};function r(){}function i(e){return e()}function a(){return Object.create(null)}function o(e){e.forEach(i)}function s(e){return typeof e==`function`}function c(e,t){return e==e?e!==t||e&&typeof e==`object`||typeof e==`function`:t==t}var l;function u(e,t){return e===t||(l||=document.createElement(`a`),l.href=t,e===l.href)}function d(e){return Object.keys(e).length===0}`WeakMap`in(typeof window<`u`?window:typeof globalThis<`u`?globalThis:global);function f(e,t){e.appendChild(t)}function p(e,t,n){e.insertBefore(t,n||null)}function m(e){e.parentNode&&e.parentNode.removeChild(e)}function h(e,t){for(let n=0;n<e.length;n+=1)e[n]&&e[n].d(t)}function g(e){return document.createElement(e)}function _(e){return document.createElementNS(`http://www.w3.org/2000/svg`,e)}function v(e){return document.createTextNode(e)}function y(){return v(` `)}function b(){return v(``)}function x(e,t,n,r){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n,r)}function S(e,t,n){n==null?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n)}function C(e){return Array.from(e.childNodes)}function w(e,t){t=``+t,e.data!==t&&(e.data=t)}function T(e,t){e.value=t??``}function E(e,t,n){e.classList.toggle(t,!!n)}var D=class{is_svg=!1;e=void 0;n=void 0;t=void 0;a=void 0;constructor(e=!1){this.is_svg=e,this.e=this.n=null}c(e){this.h(e)}m(e,t,n=null){this.e||(this.e=this.is_svg?_(t.nodeName):g(t.nodeType===11?`TEMPLATE`:t.nodeName),this.t=t.tagName===`TEMPLATE`?t.content:t,this.c(e)),this.i(n)}h(e){this.e.innerHTML=e,this.n=Array.from(this.e.nodeName===`TEMPLATE`?this.e.content.childNodes:this.e.childNodes)}i(e){for(let t=0;t<this.n.length;t+=1)p(this.t,this.n[t],e)}p(e){this.d(),this.h(e),this.i(this.a)}d(){this.n.forEach(m)}},O;function k(e){O=e}function A(){if(!O)throw Error(`Function called outside component initialization`);return O}function ee(e){A().$$.on_destroy.push(e)}var j=[],M=[],N=[],P=[],F=Promise.resolve(),I=!1;function L(){I||(I=!0,F.then(V))}function R(e){N.push(e)}function te(e){P.push(e)}var z=new Set,B=0;function V(){if(B!==0)return;let e=O;do{try{for(;B<j.length;){let e=j[B];B++,k(e),ne(e.$$)}}catch(e){throw j.length=0,B=0,e}for(k(null),j.length=0,B=0;M.length;)M.pop()();for(let e=0;e<N.length;e+=1){let t=N[e];z.has(t)||(z.add(t),t())}N.length=0}while(j.length);for(;P.length;)P.pop()();I=!1,z.clear(),k(e)}function ne(e){if(e.fragment!==null){e.update(),o(e.before_update);let t=e.dirty;e.dirty=[-1],e.fragment&&e.fragment.p(e.ctx,t),e.after_update.forEach(R)}}function re(e){let t=[],n=[];N.forEach(r=>e.indexOf(r)===-1?t.push(r):n.push(r)),n.forEach(e=>e()),N=t}var H=new Set,U;function W(){U={r:0,c:[],p:U}}function G(){U.r||o(U.c),U=U.p}function K(e,t){e&&e.i&&(H.delete(e),e.i(t))}function q(e,t,n,r){if(e&&e.o){if(H.has(e))return;H.add(e),U.c.push(()=>{H.delete(e),r&&(n&&e.d(1),r())}),e.o(t)}else r&&r()}function J(e){return e?.length===void 0?Array.from(e):e}function ie(e,t){q(e,1,1,()=>{t.delete(e.key)})}function ae(e,t,n,r,i,a,s,c,l,u,d,f){let p=e.length,m=a.length,h=p,g={};for(;h--;)g[e[h].key]=h;let _=[],v=new Map,y=new Map,b=[];for(h=m;h--;){let e=f(i,a,h),o=n(e),c=s.get(o);c?r&&b.push(()=>c.p(e,t)):(c=u(o,e),c.c()),v.set(o,_[h]=c),o in g&&y.set(o,Math.abs(h-g[o]))}let x=new Set,S=new Set;function C(e){K(e,1),e.m(c,d),s.set(e.key,e),d=e.first,m--}for(;p&&m;){let t=_[m-1],n=e[p-1],r=t.key,i=n.key;t===n?(d=t.first,p--,m--):v.has(i)?!s.has(r)||x.has(r)?C(t):S.has(i)?p--:y.get(r)>y.get(i)?(S.add(r),C(t)):(x.add(i),p--):(l(n,s),p--)}for(;p--;){let t=e[p];v.has(t.key)||l(t,s)}for(;m;)C(_[m-1]);return o(b),_}function oe(e,t,n){let r=e.$$.props[t];r!==void 0&&(e.$$.bound[r]=n,n(e.$$.ctx[r]))}function Y(e){e&&e.c()}function X(e,t,n){let{fragment:r,after_update:a}=e.$$;r&&r.m(t,n),R(()=>{let t=e.$$.on_mount.map(i).filter(s);e.$$.on_destroy?e.$$.on_destroy.push(...t):o(t),e.$$.on_mount=[]}),a.forEach(R)}function Z(e,t){let n=e.$$;n.fragment!==null&&(re(n.after_update),o(n.on_destroy),n.fragment&&n.fragment.d(t),n.on_destroy=n.fragment=null,n.ctx=[])}function se(e,t){e.$$.dirty[0]===-1&&(j.push(e),L(),e.$$.dirty.fill(0)),e.$$.dirty[t/31|0]|=1<<t%31}function Q(e,t,n,i,s,c,l=null,u=[-1]){let d=O;k(e);let f=e.$$={fragment:null,ctx:[],props:c,update:r,not_equal:s,bound:a(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(t.context||(d?d.$$.context:[])),callbacks:a(),dirty:u,skip_bound:!1,root:t.target||d.$$.root};l&&l(f.root);let p=!1;if(f.ctx=n?n(e,t.props||{},(t,n,...r)=>{let i=r.length?r[0]:n;return f.ctx&&s(f.ctx[t],f.ctx[t]=i)&&(!f.skip_bound&&f.bound[t]&&f.bound[t](i),p&&se(e,t)),n}):[],f.update(),p=!0,o(f.before_update),f.fragment=i?i(f.ctx):!1,t.target){if(t.hydrate){let e=C(t.target);f.fragment&&f.fragment.l(e),e.forEach(m)}else f.fragment&&f.fragment.c();t.intro&&K(e.$$.fragment),X(e,t.target,t.anchor),V()}k(d)}vLine truncated
|
||||
`)),document?.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`?console.error(`[DEBUG: Loaded from ${document.currentScript.src??`bad script location`}]`):console.error(`no known script location`)}d||r(24,d=u?12:30);let n={..._||{},excerptLength:d};await t.options(n);for(let e of v){if(!e.bundlePath)throw Error(`mergeIndex requires a bundlePath parameter`);let n=e.bundlePath;delete e.bundlePath,await t.mergeIndex(n,e)}E=t,ne()}},ne=async()=>{E&&(L=await E.filters(),(!R||!Object.keys(R).length)&&r(18,R=L))},re=e=>{let t={};return Object.entries(e).filter(([,e])=>e).forEach(([e])=>{let[n,r]=e.split(/:(.*)$/);t[n]=t[n]||[],t[n].push(r)}),t},H,U=async(e,t)=>{if(!e){r(15,N=!1),H&&clearTimeout(H);return}let n=re(t),i=()=>G(e,n);g>0&&e?(H&&clearTimeout(H),H=setTimeout(i,g),await W(),E.preload(e,{filters:n})):i(),K()},W=async()=>{for(;!E;)V(),await new Promise(e=>setTimeout(e,50))},G=async(e,t)=>{r(16,F=e||``),typeof p==`function`&&(e=p(e)),r(14,j=!0),r(15,N=!0),await W();let n=++P,i={filters:t};C&&typeof C==`object`&&(i.sort=C);let a=await E.search(e,i);P===n&&(a.filters&&Object.keys(a.filters)?.length&&r(18,R=a.filters),r(13,A=a),r(14,j=!1),r(17,I=s))},K=()=>{let e=O.offsetWidth;e!=40&&r(10,D.style.paddingRight=`${e+2}px`,D)},q=e=>{e?.preventDefault(),r(17,I+=s)},J=e=>{e.key===`Escape`&&(r(9,T=``),D.blur()),e.key===`Enter`&&e.preventDefault()};function ie(){T=this.value,r(9,T),r(23,y)}function ae(e){M[e?`unshift`:`push`](()=>{D=e,r(10,D)})}function oe(e){M[e?`unshift`:`push`](()=>{O=e,r(11,O)})}let Y=()=>{r(9,T=``),D.blur()};function X(e){w=e,r(0,w)}return t.$$set=e=>{`base_path`in e&&r(25,o=e.base_path),`page_size`in e&&r(26,s=e.page_size),`reset_styles`in e&&r(1,c=e.reset_styles),`show_images`in e&&r(2,l=e.show_images),`show_sub_results`in e&&r(3,u=e.show_sub_results),`excerpt_length`in e&&r(24,d=e.excerpt_length),`process_result`in e&&r(4,f=e.process_result),`process_term`in e&&r(27,p=e.process_term),`show_empty_filters`in e&&r(5,m=e.show_empty_filters),`open_filters`in e&&r(6,h=e.open_filters),`debounce_timeout_ms`in e&&r(28,g=e.debounce_timeout_ms),`pagefind_options`in e&&r(29,_=e.pagefind_options),`merge_index`in e&&r(30,v=e.merge_index),`trigger_search_term`in e&&r(23,y=e.trigger_search_term),`translations`in e&&r(7,b=e.translations),`autofocus`in e&&r(8,x=e.autofocus),`focus_on_slash`in e&&r(31,S=e.focus_on_slash),`sort`in e&&r(32,C=e.sort),`selected_filters`in e&&r(0,w=e.selected_filters)},t.$$.update=()=>{if(t.$$.dirty[0]&8388608)$:y&&(r(9,T=y),r(23,y=``));if(t.$$.dirty[0]&513)$:U(T,w)},[w,c,l,u,f,m,h,b,x,T,D,O,k,A,j,N,F,I,R,te,z,V,q,y,d,o,s,p,g,_,v,S,C,J,ie,ae,oe,Y,X]}var ao=class extends ${constructor(e){super(),Q(this,e,io,no,c,{base_path:25,page_size:26,reset_styles:1,show_images:2,show_sub_results:3,excerpt_length:24,process_result:4,process_term:27,show_empty_filters:5,open_filters:6,debounce_timeout_ms:28,pagefind_options:29,merge_index:30,trigger_search_term:23,translations:7,autofocus:8,focus_on_slash:31,sort:32,selected_filters:0},null,[-1,-1])}},oo;try{document?.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&(oo=new URL(document.currentScript.src).pathname.match(/^(.*\/)(?:pagefind-)?ui.js.*$/)[1])}catch{oo=`/pagefind/`}var so=class{constructor(e){this._pfs=null;let t=e.element??`[data-pagefind-ui]`,n=e.bundlePath??oo,r=e.pageSize??5,i=e.resetStyles??!0,a=e.showImages??!0,o=e.showSubResults??!1,s=e.excerptLength??0,c=e.processResult??null,l=e.processTerm??null,u=e.showEmptyFilters??!0,d=e.openFilters??[],f=e.debounceTimeoutMs??300,p=e.mergeIndex??[],m=e.translations??[],h=e.autofocus??!1,g=e.focusOnSlash??!1,_=e.sort??null;delete e.element,delete e.bundlePath,delete e.pageSize,delete e.resetStyles,delete e.showImages,delete e.showSubResults,delete e.excerptLength,delete e.processResult,delete e.processTerm,delete e.showEmptyFilters,delete e.openFilters,delete e.debounceTimeoutMs,delete e.mergeIndex,delete e.translations,delete e.autofocus,delete e.focusOnSlash,delete e.sort;let v=t instanceof HTMLElement?t:document.querySelector(t);v?this._pfs=new ao({target:v,props:{base_path:n,page_size:r,reset_styles:i,show_images:a,show_sub_results:o,excerpt_length:s,process_result:c,process_term:l,show_empty_filters:u,open_filters:d,debounce_timeout_ms:f,merge_index:p,translations:m,autofocus:h,focus_on_slash:g,sort:_,pagefind_options:e}}):console.error(`Pagefind UI couldn't find the selector ${t}`)}triggerSearch(e){this._pfs.$$set({trigger_search_term:e})}triggerFilters(e){let t={};for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let e of r)t[`${n}:${e}`]=!0;else t[`${n}:${r}`]=!0;this._pfs.$$set({selected_filters:t})}destroy(){this._pfs.$destroy()}};export{so as PagefindUI};
|
||||
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
+95
@@ -0,0 +1,95 @@
|
||||
<!DOCTYPE html><html lang="en" dir="ltr" data-theme="dark" data-has-toc data-has-sidebar class="astro-vdxcvpsm"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Editors & LSP | lucisv</title><link rel="canonical" href="https://lucisv.dev/guides/editors/"/><link rel="sitemap" href="/sitemap-index.xml"/><script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"lucisv","applicationCategory":"DeveloperApplication","operatingSystem":"macOS, Linux, Windows","softwareVersion":"0.9.0","license":"https://opensource.org/licenses/MIT","description":"A fast Verilog and SystemVerilog formatter, linter, and language server written in Rust.","codeRepository":"https://git.luci.ooo/lucio/verilogrustformatter"}</script><link rel="shortcut icon" href="/favicon.png" type="image/png"/><meta name="generator" content="Astro v7.2.8"/><meta name="generator" content="Starlight v0.41.9"/><meta property="og:title" content="Editors & LSP"/><meta property="og:type" content="article"/><meta property="og:url" content="https://lucisv.dev/guides/editors/"/><meta property="og:locale" content="en"/><meta property="og:description" content="Set up lucisv-server in VS Code, Neovim, Vim, and other Language Server Protocol clients."/><meta name="description" content="Set up lucisv-server in VS Code, Neovim, Vim, and other Language Server Protocol clients."/><meta name="theme-color" content="#07111f"/><meta property="og:site_name" content="lucisv documentation"/><meta property="og:image" content="https://lucisv.dev/og.png"/><meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/><meta property="og:image:alt" content="lucisv — Verilog tooling that stays out of your way."/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:image" content="https://lucisv.dev/og.png"/><script>
|
||||
window.StarlightThemeProvider = (() => {
|
||||
const storedTheme =
|
||||
typeof localStorage !== 'undefined' && localStorage.getItem('starlight-theme');
|
||||
const theme =
|
||||
storedTheme ||
|
||||
(window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark';
|
||||
return {
|
||||
updatePickers(theme = storedTheme || 'auto') {
|
||||
document.querySelectorAll('starlight-theme-select').forEach((picker) => {
|
||||
const select = picker.querySelector('select');
|
||||
if (select) select.value = theme;
|
||||
/** @type {HTMLTemplateElement | null} */
|
||||
const tmpl = document.querySelector(`#theme-icons`);
|
||||
const newIcon = tmpl && tmpl.content.querySelector('.' + theme);
|
||||
if (newIcon) {
|
||||
const oldIcon = picker.querySelector('svg.label-icon');
|
||||
if (oldIcon) {
|
||||
oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
})();
|
||||
</script><template id="theme-icons"><svg aria-hidden="true" class="light astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M5 12a1 1 0 0 0-1-1H3a1 1 0 0 0 0 2h1a1 1 0 0 0 1-1Zm.64 5-.71.71a1 1 0 0 0 0 1.41 1 1 0 0 0 1.41 0l.71-.71A1 1 0 0 0 5.64 17ZM12 5a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1a1 1 0 0 0 1 1Zm5.66 2.34a1 1 0 0 0 .7-.29l.71-.71a1 1 0 1 0-1.41-1.41l-.66.71a1 1 0 0 0 0 1.41 1 1 0 0 0 .66.29Zm-12-.29a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.71-.71a1.004 1.004 0 1 0-1.43 1.41l.73.71ZM21 11h-1a1 1 0 0 0 0 2h1a1 1 0 0 0 0-2Zm-2.64 6A1 1 0 0 0 17 18.36l.71.71a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.76-.66ZM12 6.5a5.5 5.5 0 1 0 5.5 5.5A5.51 5.51 0 0 0 12 6.5Zm0 9a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7Zm0 3.5a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-1a1 1 0 0 0-1-1Z"/></svg><svg aria-hidden="true" class="dark astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.64 13a1 1 0 0 0-1.05-.14 8.049 8.049 0 0 1-3.37.73 8.15 8.15 0 0 1-8.14-8.1 8.59 8.59 0 0 1 .25-2A1 1 0 0 0 8 2.36a10.14 10.14 0 1 0 14 11.69 1 1 0 0 0-.36-1.05Zm-9.5 6.69A8.14 8.14 0 0 1 7.08 5.22v.27a10.15 10.15 0 0 0 10.14 10.14 9.784 9.784 0 0 0 2.1-.22 8.11 8.11 0 0 1-7.18 4.32v-.04Z"/></svg><svg aria-hidden="true" class="auto astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg></template><link rel="stylesheet" href="/_astro/print.ehPL0gv-.css" media="print"><link rel="stylesheet" href="/_astro/common.db7thnbo.css"><script type="module" src="/_astro/page.Dwipeu-R.js"></script></head><body class="astro-vdxcvpsm"><a class="sl-skip-link astro-vxeigawq" href="#_top">Skip to content</a><div class="page sl-flex astro-gqpr5s5a"><header class="header astro-gqpr5s5a"><div class="header astro-nczgtkxc"><div class="title-wrapper sl-flex astro-nczgtkxc"><a href="/" class="site-title sl-flex astro-clw6ags5"><span class="astro-clw6ags5" translate="no">lucisv</span></a></div><div class="sl-flex print:hidden astro-nczgtkxc"><site-search class="astro-nczgtkxc astro-r5ar4xm7" data-translations="{"placeholder":"Search"}"><button data-open-modal disabled aria-label="Search" aria-keyshortcuts="Control+K" class="astro-r5ar4xm7"><svg aria-hidden="true" class="astro-r5ar4xm7 astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.71 20.29 18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.39ZM11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z"/></svg><span class="sl-hidden md:sl-block astro-r5ar4xm7" aria-hidden="true">Search</span><kbd class="sl-hidden md:sl-flex astro-r5ar4xm7" style="display: none;"><kbd class="astro-r5ar4xm7">Ctrl</kbd><kbd class="astro-r5ar4xm7">K</kbd></kbd></button><dialog style="padding:0" aria-label="Search" class="astro-r5ar4xm7"><div class="dialog-frame sl-flex astro-r5ar4xm7"><button data-close-modal class="sl-flex md:sl-hidden astro-r5ar4xm7">Cancel</button><div class="search-container astro-r5ar4xm7"><div id="starlight__search" class="astro-r5ar4xm7"></div></div></div></dialog></site-search><script>
|
||||
(() => {
|
||||
const openBtn = document.querySelector('button[data-open-modal]');
|
||||
const shortcut = openBtn?.querySelector('kbd');
|
||||
if (!openBtn || !(shortcut instanceof HTMLElement)) return;
|
||||
const platformKey = shortcut.querySelector('kbd');
|
||||
if (platformKey && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
|
||||
platformKey.textContent = '⌘';
|
||||
openBtn.setAttribute('aria-keyshortcuts', 'Meta+K');
|
||||
}
|
||||
shortcut.style.display = '';
|
||||
})();
|
||||
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
|
||||
(() => {
|
||||
try {
|
||||
if (!matchMedia('(min-width: 50em)').matches) return;
|
||||
/** @type {HTMLElement | null} */
|
||||
const target = document.querySelector('sl-sidebar-state-persist');
|
||||
const state = JSON.parse(sessionStorage.getItem('sl-sidebar-state') || '0');
|
||||
if (!target || !state || target.dataset.hash !== state.hash) return;
|
||||
window._starlightScrollRestore = state.scroll;
|
||||
customElements.define(
|
||||
'sl-sidebar-restore',
|
||||
class SidebarRestore extends HTMLElement {
|
||||
connectedCallback() {
|
||||
try {
|
||||
const idx = parseInt(this.dataset.index || '');
|
||||
const details = this.closest('details');
|
||||
if (details && typeof state.open[idx] === 'boolean') details.open = state.open[idx];
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch {}
|
||||
})();
|
||||
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors & LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
|
||||
(() => {
|
||||
const scroller = document.getElementById('starlight__sidebar');
|
||||
if (!window._starlightScrollRestore || !scroller) return;
|
||||
scroller.scrollTop = window._starlightScrollRestore;
|
||||
delete window._starlightScrollRestore;
|
||||
})();
|
||||
</script></sl-sidebar-state-persist><div class="md:sl-hidden"><div class="mobile-preferences sl-flex astro-b5gddk54"><div class="social-icons astro-b5gddk54"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#vs-code" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">VS Code</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#neovim-011" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Neovim 0.11+</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#workspace-indexing" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Workspace indexing</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#smoke-test" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Smoke test</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#vs-code" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">VS Code</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#neovim-011" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Neovim 0.11+</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#workspace-indexing" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Workspace indexing</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#smoke-test" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Smoke test</span></a></li></ul></nav></starlight-toc><script type="module" src="/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js"></script></div></div></div></aside><div class="main-pane astro-abfeecmu"><main data-pagefind-body class="astro-vdxcvpsm" lang="en" dir="ltr"><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><h1 id="_top" class="astro-2sm4b3ln">Editors & LSP</h1></div></div><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><div class="sl-markdown-content"><p><code dir="auto">lucisv-server</code> is a synchronous language server over stdio. It keeps open buffers as in-memory overlays, updates the workspace index incrementally, and returns the same formatting and lint behaviLine truncated
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="vs-code">VS Code</h2><a class="sl-anchor-link" href="#vs-code"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “VS Code”</span></a></div>
|
||||
<p>Install the <code dir="auto">.vsix</code> attached to a lucisv release:</p>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">code</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--install-extension</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">lucisv-0.9.0.vsix</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="code --install-extension lucisv-0.9.0.vsix"><div></div></button></div></figure></div>
|
||||
<p>The extension registers Verilog/SystemVerilog file types, syntax highlighting, snippets, color settings, configuration, and starts <code dir="auto">lucisv-server</code> from <code dir="auto">PATH</code> by default.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="neovim-011">Neovim 0.11+</h2><a class="sl-anchor-link" href="#neovim-011"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Neovim 0.11+”</span></a></div>
|
||||
<div class="expressive-code"><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="lua"><code><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">vim</span><span style="--0:#D6DEEB;--1:#403F53">.filetype.</span><span style="--0:#C5E478;--1:#3B61B0">add</span><span style="--0:#D6DEEB;--1:#403F53">({ </span><span style="--0:#C5E478;--1:#3B61B0">extension</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> {</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">v</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">verilog</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#C5E478;--1:#3B61B0">vh</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">verilog</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">,</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">sv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">systemverilog</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#C5E478;--1:#3B61B0">svh</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">systemverilog</span><span style="--0:#D9F5DD;--1:#111111">'</span></div></div><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">} })</span></div></div><div class="ec-line"><div class="code">
|
||||
</div></div><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">vim</span><span style="--0:#D6DEEB;--1:#403F53">.lsp.</span><span style="--0:#C5E478;--1:#3B61B0">config</span><span style="--0:#D6DEEB;--1:#403F53">(</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">lucisv</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, {</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">cmd</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> { </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">lucisv-server</span><span style="--0:#D9F5DD;--1:#111111">' </span><span style="--0:#D6DEEB;--1:#403F53">},</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">filetypes</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> { </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">verilog</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">systemverilog</span><span style="--0:#D9F5DD;--1:#111111">' </span><span style="--0:#D6DEEB;--1:#403F53">},</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">root_markers</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> { </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">lucisv.toml</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">.lucisv.toml</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">.git</span><span style="--0:#D9F5DD;--1:#111111">' </span><span style="--0:#D6DEEB;--1:#403F53">},</span></div></div><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">})</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">vim</span><span style="--0:#D6DEEB;--1:#403F53">.lsp.</span><span style="--0:#C5E478;--1:#3B61B0">enable</span><span style="--0:#D6DEEB;--1:#403F53">(</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">lucisv</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">)</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="vim.filetype.add({ extension = { v = 'verilog', vh = 'verilog', sv = 'systemverilog', svh = 'systemverilog'} })vim.lsp.config('lucisv', { cmd = { 'lucisv-server' }, filetypes = { 'verilog', 'systemverilog' }, root_markers = { 'lucisv.toml', '.lucisv.toml', '.git' },})vim.lsp.enable('lucisv')"><div></div></button></div></figure></div>
|
||||
<p>Vim 9, <code dir="auto">nvim-lspconfig</code>, and coc.nvim can launch the same binary with the same filetypes and root markers.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="workspace-indexing">Workspace indexing</h2><a class="sl-anchor-link" href="#workspace-indexing"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Workspace indexing”</span></a></div>
|
||||
<p>The server selects files in this order:</p>
|
||||
<ol>
|
||||
<li>The <code dir="auto">lucisv.filelist</code> editor setting, when set.</li>
|
||||
<li>The <code dir="auto">filelist</code> key in project configuration.</li>
|
||||
<li>A recursive workspace-folder walk.</li>
|
||||
<li>With no workspace folder, the open file’s directory.</li>
|
||||
</ol>
|
||||
<p>Open buffers are always overlaid on top of the disk index. File watching keeps disk-backed symbols fresh; a broken filelist warns and falls back to the folder walk so the index is never silently empty.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="smoke-test">Smoke test</h2><a class="sl-anchor-link" href="#smoke-test"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Smoke test”</span></a></div>
|
||||
<p>The repository includes a protocol-level check that starts the server exactly as the VS Code extension does:</p>
|
||||
<div class="expressive-code"><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">node</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">editors/vscode/smoke.js</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">target/release/lucisv-server</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="node editors/vscode/smoke.js target/release/lucisv-server"><div></div></button></div></figure></div>
|
||||
<p>See <a href="/reference/language-tools/">Language tools</a> for every advertised request and editor feature.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/editors.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/linter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Linter</span></span></a><a href="/guides/syntax/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Supported syntax</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
<!DOCTYPE html><html lang="en" dir="ltr" data-theme="dark" data-has-toc data-has-sidebar class="astro-vdxcvpsm"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Formatter | lucisv</title><link rel="canonical" href="https://lucisv.dev/guides/formatter/"/><link rel="sitemap" href="/sitemap-index.xml"/><script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"lucisv","applicationCategory":"DeveloperApplication","operatingSystem":"macOS, Linux, Windows","softwareVersion":"0.9.0","license":"https://opensource.org/licenses/MIT","description":"A fast Verilog and SystemVerilog formatter, linter, and language server written in Rust.","codeRepository":"https://git.luci.ooo/lucio/verilogrustformatter"}</script><link rel="shortcut icon" href="/favicon.png" type="image/png"/><meta name="generator" content="Astro v7.2.8"/><meta name="generator" content="Starlight v0.41.9"/><meta property="og:title" content="Formatter"/><meta property="og:type" content="article"/><meta property="og:url" content="https://lucisv.dev/guides/formatter/"/><meta property="og:locale" content="en"/><meta property="og:description" content="Understand lucisv’s deterministic formatting model, alignment inference, fences, ranges, and safety invariants."/><meta name="description" content="Understand lucisv’s deterministic formatting model, alignment inference, fences, ranges, and safety invariants."/><meta name="theme-color" content="#07111f"/><meta property="og:site_name" content="lucisv documentation"/><meta property="og:image" content="https://lucisv.dev/og.png"/><meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/><meta property="og:image:alt" content="lucisv — Verilog tooling that stays out of your way."/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:image" content="https://lucisv.dev/og.png"/><script>
|
||||
window.StarlightThemeProvider = (() => {
|
||||
const storedTheme =
|
||||
typeof localStorage !== 'undefined' && localStorage.getItem('starlight-theme');
|
||||
const theme =
|
||||
storedTheme ||
|
||||
(window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark';
|
||||
return {
|
||||
updatePickers(theme = storedTheme || 'auto') {
|
||||
document.querySelectorAll('starlight-theme-select').forEach((picker) => {
|
||||
const select = picker.querySelector('select');
|
||||
if (select) select.value = theme;
|
||||
/** @type {HTMLTemplateElement | null} */
|
||||
const tmpl = document.querySelector(`#theme-icons`);
|
||||
const newIcon = tmpl && tmpl.content.querySelector('.' + theme);
|
||||
if (newIcon) {
|
||||
const oldIcon = picker.querySelector('svg.label-icon');
|
||||
if (oldIcon) {
|
||||
oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
})();
|
||||
</script><template id="theme-icons"><svg aria-hidden="true" class="light astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M5 12a1 1 0 0 0-1-1H3a1 1 0 0 0 0 2h1a1 1 0 0 0 1-1Zm.64 5-.71.71a1 1 0 0 0 0 1.41 1 1 0 0 0 1.41 0l.71-.71A1 1 0 0 0 5.64 17ZM12 5a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1a1 1 0 0 0 1 1Zm5.66 2.34a1 1 0 0 0 .7-.29l.71-.71a1 1 0 1 0-1.41-1.41l-.66.71a1 1 0 0 0 0 1.41 1 1 0 0 0 .66.29Zm-12-.29a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.71-.71a1.004 1.004 0 1 0-1.43 1.41l.73.71ZM21 11h-1a1 1 0 0 0 0 2h1a1 1 0 0 0 0-2Zm-2.64 6A1 1 0 0 0 17 18.36l.71.71a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.76-.66ZM12 6.5a5.5 5.5 0 1 0 5.5 5.5A5.51 5.51 0 0 0 12 6.5Zm0 9a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7Zm0 3.5a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-1a1 1 0 0 0-1-1Z"/></svg><svg aria-hidden="true" class="dark astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.64 13a1 1 0 0 0-1.05-.14 8.049 8.049 0 0 1-3.37.73 8.15 8.15 0 0 1-8.14-8.1 8.59 8.59 0 0 1 .25-2A1 1 0 0 0 8 2.36a10.14 10.14 0 1 0 14 11.69 1 1 0 0 0-.36-1.05Zm-9.5 6.69A8.14 8.14 0 0 1 7.08 5.22v.27a10.15 10.15 0 0 0 10.14 10.14 9.784 9.784 0 0 0 2.1-.22 8.11 8.11 0 0 1-7.18 4.32v-.04Z"/></svg><svg aria-hidden="true" class="auto astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg></template><link rel="stylesheet" href="/_astro/print.ehPL0gv-.css" media="print"><link rel="stylesheet" href="/_astro/common.db7thnbo.css"><script type="module" src="/_astro/page.Dwipeu-R.js"></script></head><body class="astro-vdxcvpsm"><a class="sl-skip-link astro-vxeigawq" href="#_top">Skip to content</a><div class="page sl-flex astro-gqpr5s5a"><header class="header astro-gqpr5s5a"><div class="header astro-nczgtkxc"><div class="title-wrapper sl-flex astro-nczgtkxc"><a href="/" class="site-title sl-flex astro-clw6ags5"><span class="astro-clw6ags5" translate="no">lucisv</span></a></div><div class="sl-flex print:hidden astro-nczgtkxc"><site-search class="astro-nczgtkxc astro-r5ar4xm7" data-translations="{"placeholder":"Search"}"><button data-open-modal disabled aria-label="Search" aria-keyshortcuts="Control+K" class="astro-r5ar4xm7"><svg aria-hidden="true" class="astro-r5ar4xm7 astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.71 20.29 18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.39ZM11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z"/></svg><span class="sl-hidden md:sl-block astro-r5ar4xm7" aria-hidden="true">Search</span><kbd class="sl-hidden md:sl-flex astro-r5ar4xm7" style="display: none;"><kbd class="astro-r5ar4xm7">Ctrl</kbd><kbd class="astro-r5ar4xm7">K</kbd></kbd></button><dialog style="padding:0" aria-label="Search" class="astro-r5ar4xm7"><div class="dialog-frame sl-flex astro-r5ar4xm7"><button data-close-modal class="sl-flex md:sl-hidden astro-r5ar4xm7">Cancel</button><div class="search-container astro-r5ar4xm7"><div id="starlight__search" class="astro-r5ar4xm7"></div></div></div></dialog></site-search><script>
|
||||
(() => {
|
||||
const openBtn = document.querySelector('button[data-open-modal]');
|
||||
const shortcut = openBtn?.querySelector('kbd');
|
||||
if (!openBtn || !(shortcut instanceof HTMLElement)) return;
|
||||
const platformKey = shortcut.querySelector('kbd');
|
||||
if (platformKey && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
|
||||
platformKey.textContent = '⌘';
|
||||
openBtn.setAttribute('aria-keyshortcuts', 'Meta+K');
|
||||
}
|
||||
shortcut.style.display = '';
|
||||
})();
|
||||
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
|
||||
(() => {
|
||||
try {
|
||||
if (!matchMedia('(min-width: 50em)').matches) return;
|
||||
/** @type {HTMLElement | null} */
|
||||
const target = document.querySelector('sl-sidebar-state-persist');
|
||||
const state = JSON.parse(sessionStorage.getItem('sl-sidebar-state') || '0');
|
||||
if (!target || !state || target.dataset.hash !== state.hash) return;
|
||||
window._starlightScrollRestore = state.scroll;
|
||||
customElements.define(
|
||||
'sl-sidebar-restore',
|
||||
class SidebarRestore extends HTMLElement {
|
||||
connectedCallback() {
|
||||
try {
|
||||
const idx = parseInt(this.dataset.index || '');
|
||||
const details = this.closest('details');
|
||||
if (details && typeof state.open[idx] === 'boolean') details.open = state.open[idx];
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch {}
|
||||
})();
|
||||
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors & LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
|
||||
(() => {
|
||||
const scroller = document.getElementById('starlight__sidebar');
|
||||
if (!window._starlightScrollRestore || !scroller) return;
|
||||
scroller.scrollTop = window._starlightScrollRestore;
|
||||
delete window._starlightScrollRestore;
|
||||
})();
|
||||
</script></sl-sidebar-state-persist><div class="md:sl-hidden"><div class="mobile-preferences sl-flex astro-b5gddk54"><div class="social-icons astro-b5gddk54"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#core-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Core style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#alignment-is-inferred" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Alignment is inferred</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#format-fences" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Format fences</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#range-formatting" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Range formatting</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#safety-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Safety invariants</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#core-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Core style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#alignment-is-inferred" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Alignment is inferred</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#format-fences" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Format fences</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#range-formatting" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Range formatting</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#safety-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Safety invariants</span></a></li></ul></nav></starlight-toc><script type="module" src="/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js"></script></div></div></div></aside><div class="main-pane astro-abfeecmu"><main data-pagefind-body class="astro-vdxcvpsm" lang="en" dir="ltr"><div class="content-panel astro-oLine truncated
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="core-style">Core style</h2><a class="sl-anchor-link" href="#core-style"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Core style”</span></a></div>
|
||||
<ul>
|
||||
<li>2-space indentation and 100-column lines by default.</li>
|
||||
<li>One port, parameter, or connection per line when a header breaks.</li>
|
||||
<li>Cuddled block transitions such as <code dir="auto">end else begin</code>.</li>
|
||||
<li>Tight packed dimensions such as <code dir="auto">[WIDTH-1:0]</code> and <code dir="auto">[base+:8]</code>.</li>
|
||||
<li>At most one preserved blank line between adjacent items.</li>
|
||||
<li>Compiler directives, attributes, and supported verbatim constructs keep their source text.</li>
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="alignment-is-inferred">Alignment is inferred</h2><a class="sl-anchor-link" href="#alignment-is-inferred"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Alignment is inferred”</span></a></div>
|
||||
<p>lucisv recognizes existing columnar intent in adjacent ANSI ports, named connections, and parameter declarations. If a group is already aligned—or uses four or more spaces where one would suffice—it is normalized as a table. Flush-left input stays flush-left.</p>
|
||||
<p>Groups end at blank lines, standalone comments, attributes, or compiler directives. If the widest row exceeds the line limit, the entire group falls back to flush-left, never a half-aligned mixture.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="format-fences">Format fences</h2><a class="sl-anchor-link" href="#format-fences"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Format fences”</span></a></div>
|
||||
<p>Use a standalone fence to protect hand-laid-out regions:</p>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="system-verilog"><code><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// verilog_format: off</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">localparam int</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">A</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C792EA;--1:#8844AE">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#F78C6C;--1:#AA0982">1</span><span style="--0:#D6DEEB;--1:#403F53">;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">localparam int</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">LONGER</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C792EA;--1:#8844AE">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#F78C6C;--1:#AA0982">22</span><span style="--0:#D6DEEB;--1:#403F53">;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// verilog_format: on</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="// verilog_format: offlocalparam int A = 1;localparam int LONGER = 22;// verilog_format: on"><div></div></button></div></figure></div>
|
||||
<p><code dir="auto">// lucisv: off</code> and <code dir="auto">// lucisv: on</code> are aliases. Fences preserve exact bytes inside whole-item regions and also prevent lint fixes there.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="range-formatting">Range formatting</h2><a class="sl-anchor-link" href="#range-formatting"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Range formatting”</span></a></div>
|
||||
<p><code dir="auto">--lines</code> selects 1-based inclusive ranges:</p>
|
||||
<div class="expressive-code"><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--lines</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">120-134</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/alu.sv</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--lines</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">3-9,40</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--check</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/alu.sv</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="lucisv --lines 120-134 rtl/alu.svlucisv --lines 3-9,40 --check rtl/alu.sv"><div></div></button></div></figure></div>
|
||||
<p>The atomic unit is an item: selecting a statement formats its containing <code dir="auto">always</code> block; selecting a declaration formats that declaration. Everything outside the selected items is emitted byte-for-byte. Ranges require explicit files or stdin, never directories or filelists, and bypass the cache.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="safety-invariants">Safety invariants</h2><a class="sl-anchor-link" href="#safety-invariants"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Safety invariants”</span></a></div>
|
||||
<ol>
|
||||
<li><strong>Parse first.</strong> Whole-file formatting produces no output for a file that cannot be fully parsed.</li>
|
||||
<li><strong>Preserve meaning.</strong> Verification compares normalized syntax before accepting output.</li>
|
||||
<li><strong>Converge.</strong> Formatting twice reaches the same fixed point.</li>
|
||||
<li><strong>Write atomically.</strong> An error leaves the affected file untouched.</li>
|
||||
<li><strong>Stay deterministic.</strong> Parallel worker count changes performance, never output order or exit status.</li>
|
||||
</ol>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/formatter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/configuration/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Configuration</span></span></a><a href="/guides/linter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Linter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<!DOCTYPE html><html lang="en" dir="ltr" data-theme="dark" data-has-toc data-has-sidebar class="astro-vdxcvpsm"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Linter | lucisv</title><link rel="canonical" href="https://lucisv.dev/guides/linter/"/><link rel="sitemap" href="/sitemap-index.xml"/><script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"lucisv","applicationCategory":"DeveloperApplication","operatingSystem":"macOS, Linux, Windows","softwareVersion":"0.9.0","license":"https://opensource.org/licenses/MIT","description":"A fast Verilog and SystemVerilog formatter, linter, and language server written in Rust.","codeRepository":"https://git.luci.ooo/lucio/verilogrustformatter"}</script><link rel="shortcut icon" href="/favicon.png" type="image/png"/><meta name="generator" content="Astro v7.2.8"/><meta name="generator" content="Starlight v0.41.9"/><meta property="og:title" content="Linter"/><meta property="og:type" content="article"/><meta property="og:url" content="https://lucisv.dev/guides/linter/"/><meta property="og:locale" content="en"/><meta property="og:description" content="Run lucisv lint checks, select rules, apply safe fixes, configure output, and use source waivers."/><meta name="description" content="Run lucisv lint checks, select rules, apply safe fixes, configure output, and use source waivers."/><meta name="theme-color" content="#07111f"/><meta property="og:site_name" content="lucisv documentation"/><meta property="og:image" content="https://lucisv.dev/og.png"/><meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/><meta property="og:image:alt" content="lucisv — Verilog tooling that stays out of your way."/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:image" content="https://lucisv.dev/og.png"/><script>
|
||||
window.StarlightThemeProvider = (() => {
|
||||
const storedTheme =
|
||||
typeof localStorage !== 'undefined' && localStorage.getItem('starlight-theme');
|
||||
const theme =
|
||||
storedTheme ||
|
||||
(window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark';
|
||||
return {
|
||||
updatePickers(theme = storedTheme || 'auto') {
|
||||
document.querySelectorAll('starlight-theme-select').forEach((picker) => {
|
||||
const select = picker.querySelector('select');
|
||||
if (select) select.value = theme;
|
||||
/** @type {HTMLTemplateElement | null} */
|
||||
const tmpl = document.querySelector(`#theme-icons`);
|
||||
const newIcon = tmpl && tmpl.content.querySelector('.' + theme);
|
||||
if (newIcon) {
|
||||
const oldIcon = picker.querySelector('svg.label-icon');
|
||||
if (oldIcon) {
|
||||
oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
})();
|
||||
</script><template id="theme-icons"><svg aria-hidden="true" class="light astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M5 12a1 1 0 0 0-1-1H3a1 1 0 0 0 0 2h1a1 1 0 0 0 1-1Zm.64 5-.71.71a1 1 0 0 0 0 1.41 1 1 0 0 0 1.41 0l.71-.71A1 1 0 0 0 5.64 17ZM12 5a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1a1 1 0 0 0 1 1Zm5.66 2.34a1 1 0 0 0 .7-.29l.71-.71a1 1 0 1 0-1.41-1.41l-.66.71a1 1 0 0 0 0 1.41 1 1 0 0 0 .66.29Zm-12-.29a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.71-.71a1.004 1.004 0 1 0-1.43 1.41l.73.71ZM21 11h-1a1 1 0 0 0 0 2h1a1 1 0 0 0 0-2Zm-2.64 6A1 1 0 0 0 17 18.36l.71.71a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.76-.66ZM12 6.5a5.5 5.5 0 1 0 5.5 5.5A5.51 5.51 0 0 0 12 6.5Zm0 9a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7Zm0 3.5a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-1a1 1 0 0 0-1-1Z"/></svg><svg aria-hidden="true" class="dark astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.64 13a1 1 0 0 0-1.05-.14 8.049 8.049 0 0 1-3.37.73 8.15 8.15 0 0 1-8.14-8.1 8.59 8.59 0 0 1 .25-2A1 1 0 0 0 8 2.36a10.14 10.14 0 1 0 14 11.69 1 1 0 0 0-.36-1.05Zm-9.5 6.69A8.14 8.14 0 0 1 7.08 5.22v.27a10.15 10.15 0 0 0 10.14 10.14 9.784 9.784 0 0 0 2.1-.22 8.11 8.11 0 0 1-7.18 4.32v-.04Z"/></svg><svg aria-hidden="true" class="auto astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg></template><link rel="stylesheet" href="/_astro/print.ehPL0gv-.css" media="print"><link rel="stylesheet" href="/_astro/common.db7thnbo.css"><script type="module" src="/_astro/page.Dwipeu-R.js"></script></head><body class="astro-vdxcvpsm"><a class="sl-skip-link astro-vxeigawq" href="#_top">Skip to content</a><div class="page sl-flex astro-gqpr5s5a"><header class="header astro-gqpr5s5a"><div class="header astro-nczgtkxc"><div class="title-wrapper sl-flex astro-nczgtkxc"><a href="/" class="site-title sl-flex astro-clw6ags5"><span class="astro-clw6ags5" translate="no">lucisv</span></a></div><div class="sl-flex print:hidden astro-nczgtkxc"><site-search class="astro-nczgtkxc astro-r5ar4xm7" data-translations="{"placeholder":"Search"}"><button data-open-modal disabled aria-label="Search" aria-keyshortcuts="Control+K" class="astro-r5ar4xm7"><svg aria-hidden="true" class="astro-r5ar4xm7 astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.71 20.29 18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.39ZM11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z"/></svg><span class="sl-hidden md:sl-block astro-r5ar4xm7" aria-hidden="true">Search</span><kbd class="sl-hidden md:sl-flex astro-r5ar4xm7" style="display: none;"><kbd class="astro-r5ar4xm7">Ctrl</kbd><kbd class="astro-r5ar4xm7">K</kbd></kbd></button><dialog style="padding:0" aria-label="Search" class="astro-r5ar4xm7"><div class="dialog-frame sl-flex astro-r5ar4xm7"><button data-close-modal class="sl-flex md:sl-hidden astro-r5ar4xm7">Cancel</button><div class="search-container astro-r5ar4xm7"><div id="starlight__search" class="astro-r5ar4xm7"></div></div></div></dialog></site-search><script>
|
||||
(() => {
|
||||
const openBtn = document.querySelector('button[data-open-modal]');
|
||||
const shortcut = openBtn?.querySelector('kbd');
|
||||
if (!openBtn || !(shortcut instanceof HTMLElement)) return;
|
||||
const platformKey = shortcut.querySelector('kbd');
|
||||
if (platformKey && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
|
||||
platformKey.textContent = '⌘';
|
||||
openBtn.setAttribute('aria-keyshortcuts', 'Meta+K');
|
||||
}
|
||||
shortcut.style.display = '';
|
||||
})();
|
||||
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
|
||||
(() => {
|
||||
try {
|
||||
if (!matchMedia('(min-width: 50em)').matches) return;
|
||||
/** @type {HTMLElement | null} */
|
||||
const target = document.querySelector('sl-sidebar-state-persist');
|
||||
const state = JSON.parse(sessionStorage.getItem('sl-sidebar-state') || '0');
|
||||
if (!target || !state || target.dataset.hash !== state.hash) return;
|
||||
window._starlightScrollRestore = state.scroll;
|
||||
customElements.define(
|
||||
'sl-sidebar-restore',
|
||||
class SidebarRestore extends HTMLElement {
|
||||
connectedCallback() {
|
||||
try {
|
||||
const idx = parseInt(this.dataset.index || '');
|
||||
const details = this.closest('details');
|
||||
if (details && typeof state.open[idx] === 'boolean') details.open = state.open[idx];
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch {}
|
||||
})();
|
||||
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors & LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
|
||||
(() => {
|
||||
const scroller = document.getElementById('starlight__sidebar');
|
||||
if (!window._starlightScrollRestore || !scroller) return;
|
||||
scroller.scrollTop = window._starlightScrollRestore;
|
||||
delete window._starlightScrollRestore;
|
||||
})();
|
||||
</script></sl-sidebar-state-persist><div class="md:sl-hidden"><div class="mobile-preferences sl-flex astro-b5gddk54"><div class="social-icons astro-b5gddk54"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#selecting-rules" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Selecting rules</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#fixes" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Fixes</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#waivers" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Waivers</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#selecting-rules" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Selecting rules</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#fixes" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Fixes</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#waivers" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Waivers</span></a></li></ul></nav></starlight-toc><script type="module" src="/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js"></script></div></div></div></aside><div class="main-pane astro-abfeecmu"><main data-pagefind-body class="astro-vdxcvpsm" lang="en" dir="ltr"><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><h1 id="_top" class="astro-2sm4b3ln">Linter</h1></div></div><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><div class="sl-markdown-content"><p>The linter shares discovery, parsing, configuration, and ignore behavior with the formatter, but uses error-tolerant parsing so it can report useful findings from partially understood files.</p>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">check</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">check</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--select</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">no-tabs,unused-signal</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">check</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--ignore</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">module-filename</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">check</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--fix</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">check</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--output-format</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">json</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="lucisv check rtl/lucisv check --select no-tabs,unused-signal rtl/lucisv check --ignore module-filename rtl/lucisv check --fix rtl/lucisv check --output-format json rtl/"><div></div></button></div></figure></div>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="selecting-rules">Selecting rules</h2><a class="sl-anchor-link" href="#selecting-rules"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Selecting rules”</span></a></div>
|
||||
<p><code dir="auto">--select</code> replaces the default set with a comma-separated list. It can be repeated. <code dir="auto">--ignore</code> then removes rules from the selected or default set. Semantic rules such as <code dir="auto">unused-signal</code>, <code dir="auto">undriven-net</code>, and <code dir="auto">multiply-driven</code> are opt-in because a single-file view cannot see all hierarchy interactions.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="fixes">Fixes</h2><a class="sl-anchor-link" href="#fixes"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Fixes”</span></a></div>
|
||||
<p><code dir="auto">--fix</code> applies safe changes and rewrites the file. Today, <code dir="auto">no-tabs</code> and <code dir="auto">no-trailing-whitespace</code> provide safe fixes. <code dir="auto">--unsafe-fixes</code> widens applicability, but no built-in rule currently offers an unsafe fix.</p>
|
||||
<p>Fixes are sorted, overlap-checked, and never applied inside format-fenced regions.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="waivers">Waivers</h2><a class="sl-anchor-link" href="#waivers"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Waivers”</span></a></div>
|
||||
<div class="expressive-code"><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="system-verilog"><code><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">wire</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C5E478;--1:#3B61B0">a</span><span style="--0:#D6DEEB;--1:#403F53">; </span><span style="--0:#919F9F;--1:#5D6376">// lucisv: waive no-tabs</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// lucisv: waive no-tabs</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">wire</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#C5E478;--1:#3B61B0">b</span><span style="--0:#D6DEEB;--1:#403F53">;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// lucisv: waive-start module-name-style</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">module</span><span style="--0:#D6DEEB;--1:#403F53"> LegacyName;</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C792EA;--1:#8844AE">endmodule</span></div></div><div class="ec-line"><div class="code"><span style="--0:#919F9F;--1:#5D6376">// lucisv: waive-stop module-name-style</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="wire a; // lucisv: waive no-tabs// lucisv: waive no-tabswire b;// lucisv: waive-start module-name-stylemodule LegacyName;endmodule// lucisv: waive-stop module-name-style"><div></div></button></div></figure></div>
|
||||
<p><code dir="auto">verilog_lint:</code> is accepted in place of <code dir="auto">lucisv:</code> for Verible compatibility. The <code dir="auto">unused-waiver</code> rule reports malformed, unknown, or no-longer-needed suppressions when their target rule is enabled.</p>
|
||||
<p>See the <a href="/reference/rules/">complete rule reference</a>.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/linter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/formatter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a><a href="/guides/editors/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors & LSP</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
<!DOCTYPE html><html lang="en" dir="ltr" data-theme="dark" data-has-toc data-has-sidebar class="astro-vdxcvpsm"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Supported syntax | lucisv</title><link rel="canonical" href="https://lucisv.dev/guides/syntax/"/><link rel="sitemap" href="/sitemap-index.xml"/><script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"lucisv","applicationCategory":"DeveloperApplication","operatingSystem":"macOS, Linux, Windows","softwareVersion":"0.9.0","license":"https://opensource.org/licenses/MIT","description":"A fast Verilog and SystemVerilog formatter, linter, and language server written in Rust.","codeRepository":"https://git.luci.ooo/lucio/verilogrustformatter"}</script><link rel="shortcut icon" href="/favicon.png" type="image/png"/><meta name="generator" content="Astro v7.2.8"/><meta name="generator" content="Starlight v0.41.9"/><meta property="og:title" content="Supported syntax"/><meta property="og:type" content="article"/><meta property="og:url" content="https://lucisv.dev/guides/syntax/"/><meta property="og:locale" content="en"/><meta property="og:description" content="The Verilog and SystemVerilog language surface understood by lucisv."/><meta name="description" content="The Verilog and SystemVerilog language surface understood by lucisv."/><meta name="theme-color" content="#07111f"/><meta property="og:site_name" content="lucisv documentation"/><meta property="og:image" content="https://lucisv.dev/og.png"/><meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/><meta property="og:image:alt" content="lucisv — Verilog tooling that stays out of your way."/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:image" content="https://lucisv.dev/og.png"/><script>
|
||||
window.StarlightThemeProvider = (() => {
|
||||
const storedTheme =
|
||||
typeof localStorage !== 'undefined' && localStorage.getItem('starlight-theme');
|
||||
const theme =
|
||||
storedTheme ||
|
||||
(window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark';
|
||||
return {
|
||||
updatePickers(theme = storedTheme || 'auto') {
|
||||
document.querySelectorAll('starlight-theme-select').forEach((picker) => {
|
||||
const select = picker.querySelector('select');
|
||||
if (select) select.value = theme;
|
||||
/** @type {HTMLTemplateElement | null} */
|
||||
const tmpl = document.querySelector(`#theme-icons`);
|
||||
const newIcon = tmpl && tmpl.content.querySelector('.' + theme);
|
||||
if (newIcon) {
|
||||
const oldIcon = picker.querySelector('svg.label-icon');
|
||||
if (oldIcon) {
|
||||
oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
})();
|
||||
</script><template id="theme-icons"><svg aria-hidden="true" class="light astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M5 12a1 1 0 0 0-1-1H3a1 1 0 0 0 0 2h1a1 1 0 0 0 1-1Zm.64 5-.71.71a1 1 0 0 0 0 1.41 1 1 0 0 0 1.41 0l.71-.71A1 1 0 0 0 5.64 17ZM12 5a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1a1 1 0 0 0 1 1Zm5.66 2.34a1 1 0 0 0 .7-.29l.71-.71a1 1 0 1 0-1.41-1.41l-.66.71a1 1 0 0 0 0 1.41 1 1 0 0 0 .66.29Zm-12-.29a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.71-.71a1.004 1.004 0 1 0-1.43 1.41l.73.71ZM21 11h-1a1 1 0 0 0 0 2h1a1 1 0 0 0 0-2Zm-2.64 6A1 1 0 0 0 17 18.36l.71.71a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.76-.66ZM12 6.5a5.5 5.5 0 1 0 5.5 5.5A5.51 5.51 0 0 0 12 6.5Zm0 9a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7Zm0 3.5a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-1a1 1 0 0 0-1-1Z"/></svg><svg aria-hidden="true" class="dark astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.64 13a1 1 0 0 0-1.05-.14 8.049 8.049 0 0 1-3.37.73 8.15 8.15 0 0 1-8.14-8.1 8.59 8.59 0 0 1 .25-2A1 1 0 0 0 8 2.36a10.14 10.14 0 1 0 14 11.69 1 1 0 0 0-.36-1.05Zm-9.5 6.69A8.14 8.14 0 0 1 7.08 5.22v.27a10.15 10.15 0 0 0 10.14 10.14 9.784 9.784 0 0 0 2.1-.22 8.11 8.11 0 0 1-7.18 4.32v-.04Z"/></svg><svg aria-hidden="true" class="auto astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg></template><link rel="stylesheet" href="/_astro/print.ehPL0gv-.css" media="print"><link rel="stylesheet" href="/_astro/common.db7thnbo.css"><script type="module" src="/_astro/page.Dwipeu-R.js"></script></head><body class="astro-vdxcvpsm"><a class="sl-skip-link astro-vxeigawq" href="#_top">Skip to content</a><div class="page sl-flex astro-gqpr5s5a"><header class="header astro-gqpr5s5a"><div class="header astro-nczgtkxc"><div class="title-wrapper sl-flex astro-nczgtkxc"><a href="/" class="site-title sl-flex astro-clw6ags5"><span class="astro-clw6ags5" translate="no">lucisv</span></a></div><div class="sl-flex print:hidden astro-nczgtkxc"><site-search class="astro-nczgtkxc astro-r5ar4xm7" data-translations="{"placeholder":"Search"}"><button data-open-modal disabled aria-label="Search" aria-keyshortcuts="Control+K" class="astro-r5ar4xm7"><svg aria-hidden="true" class="astro-r5ar4xm7 astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.71 20.29 18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.39ZM11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z"/></svg><span class="sl-hidden md:sl-block astro-r5ar4xm7" aria-hidden="true">Search</span><kbd class="sl-hidden md:sl-flex astro-r5ar4xm7" style="display: none;"><kbd class="astro-r5ar4xm7">Ctrl</kbd><kbd class="astro-r5ar4xm7">K</kbd></kbd></button><dialog style="padding:0" aria-label="Search" class="astro-r5ar4xm7"><div class="dialog-frame sl-flex astro-r5ar4xm7"><button data-close-modal class="sl-flex md:sl-hidden astro-r5ar4xm7">Cancel</button><div class="search-container astro-r5ar4xm7"><div id="starlight__search" class="astro-r5ar4xm7"></div></div></div></dialog></site-search><script>
|
||||
(() => {
|
||||
const openBtn = document.querySelector('button[data-open-modal]');
|
||||
const shortcut = openBtn?.querySelector('kbd');
|
||||
if (!openBtn || !(shortcut instanceof HTMLElement)) return;
|
||||
const platformKey = shortcut.querySelector('kbd');
|
||||
if (platformKey && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
|
||||
platformKey.textContent = '⌘';
|
||||
openBtn.setAttribute('aria-keyshortcuts', 'Meta+K');
|
||||
}
|
||||
shortcut.style.display = '';
|
||||
})();
|
||||
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><nav class="sidebar print:hidden astro-gqpr5s5a" aria-label="Main"><starlight-menu-button class="print:hidden astro-vvx7mffu"><button aria-expanded="false" aria-label="Menu" aria-controls="starlight__sidebar" class="sl-flex md:sl-hidden astro-vvx7mffu"><svg aria-hidden="true" class="open-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></svg><svg aria-hidden="true" class="close-menu astro-vvx7mffu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="m13.41 12 6.3-6.29a1.004 1.004 0 1 0-1.42-1.42L12 10.59l-6.29-6.3a1.004 1.004 0 0 0-1.42 1.42l6.3 6.29-6.3 6.29a1 1 0 0 0 0 1.42.998.998 0 0 0 1.42 0l6.29-6.3 6.29 6.3a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.42L13.41 12Z"/></svg></button></starlight-menu-button><script type="module">var e=class extends HTMLElement{btn=this.querySelector(`button`);constructor(){super(),this.btn.addEventListener(`click`,()=>this.toggleExpanded());let e=this.closest(`nav`);e&&e.addEventListener(`keyup`,e=>this.closeOnEscape(e)),matchMedia(`(min-width: 50em)`).addEventListener(`change`,()=>this.setExpanded(!1))}setExpanded(e){this.setAttribute(`aria-expanded`,String(e)),document.body.toggleAttribute(`data-mobile-menu-expanded`,e),document.querySelectorAll(`.main-frame, .sl-skip-link`).forEach(t=>{t.toggleAttribute(`inert`,e)})}toggleExpanded(){this.setExpanded(this.getAttribute(`aria-expanded`)!==`true`)}closeOnEscape(e){e.code===`Escape`&&(this.setExpanded(!1),this.btn.focus())}};customElements.define(`starlight-menu-button`,e);</script><div id="starlight__sidebar" class="sidebar-pane astro-gqpr5s5a"><div class="sidebar-content sl-flex astro-gqpr5s5a"><sl-sidebar-state-persist data-hash="0k5xoyt" class="astro-f5yvicm7"><script aria-hidden="true">
|
||||
(() => {
|
||||
try {
|
||||
if (!matchMedia('(min-width: 50em)').matches) return;
|
||||
/** @type {HTMLElement | null} */
|
||||
const target = document.querySelector('sl-sidebar-state-persist');
|
||||
const state = JSON.parse(sessionStorage.getItem('sl-sidebar-state') || '0');
|
||||
if (!target || !state || target.dataset.hash !== state.hash) return;
|
||||
window._starlightScrollRestore = state.scroll;
|
||||
customElements.define(
|
||||
'sl-sidebar-restore',
|
||||
class SidebarRestore extends HTMLElement {
|
||||
connectedCallback() {
|
||||
try {
|
||||
const idx = parseInt(this.dataset.index || '');
|
||||
const details = this.closest('details');
|
||||
if (details && typeof state.open[idx] === 'boolean') details.open = state.open[idx];
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch {}
|
||||
})();
|
||||
</script><ul class="top-level astro-ojxuodky"><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Start here</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="0"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/" class="astro-ojxuodky"><span class="astro-ojxuodky">Overview</span></a></li><li class="astro-ojxuodky"><a href="/start/quick-start/" class="astro-ojxuodky"><span class="astro-ojxuodky">Quick start</span></a></li><li class="astro-ojxuodky"><a href="/start/configuration/" class="astro-ojxuodky"><span class="astro-ojxuodky">Configuration</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Use lucisv</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="1"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/guides/formatter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Formatter</span></a></li><li class="astro-ojxuodky"><a href="/guides/linter/" class="astro-ojxuodky"><span class="astro-ojxuodky">Linter</span></a></li><li class="astro-ojxuodky"><a href="/guides/editors/" class="astro-ojxuodky"><span class="astro-ojxuodky">Editors & LSP</span></a></li><li class="astro-ojxuodky"><a href="/guides/syntax/" aria-current="page" class="astro-ojxuodky"><span class="astro-ojxuodky">Supported syntax</span></a></li></ul></details></li><li class="astro-ojxuodky"><details open class="astro-ojxuodky"><summary class="astro-ojxuodky"><span class="group-label astro-ojxuodky"><span class="large astro-ojxuodky">Reference</span></span><svg aria-hidden="true" class="caret astro-ojxuodky astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.25rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></summary><sl-sidebar-restore data-index="2"></sl-sidebar-restore><ul class="astro-ojxuodky"><li class="astro-ojxuodky"><a href="/reference/cli/" class="astro-ojxuodky"><span class="astro-ojxuodky">CLI</span></a></li><li class="astro-ojxuodky"><a href="/reference/rules/" class="astro-ojxuodky"><span class="astro-ojxuodky">Lint rules</span></a></li><li class="astro-ojxuodky"><a href="/reference/language-tools/" class="astro-ojxuodky"><span class="astro-ojxuodky">Language tools</span></a></li><li class="astro-ojxuodky"><a href="/reference/rust-api/" class="astro-ojxuodky"><span class="astro-ojxuodky">Rust API index</span></a></li><li class="astro-ojxuodky"><a href="/reference/architecture/" class="astro-ojxuodky"><span class="astro-ojxuodky">Architecture</span></a></li></ul></details></li></ul><script aria-hidden="true">
|
||||
(() => {
|
||||
const scroller = document.getElementById('starlight__sidebar');
|
||||
if (!window._starlightScrollRestore || !scroller) return;
|
||||
scroller.scrollTop = window._starlightScrollRestore;
|
||||
delete window._starlightScrollRestore;
|
||||
})();
|
||||
</script></sl-sidebar-state-persist><div class="md:sl-hidden"><div class="mobile-preferences sl-flex astro-b5gddk54"><div class="social-icons astro-b5gddk54"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#design-units-and-declarations" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Design units and declarations</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#procedural-and-concurrent-code" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Procedural and concurrent code</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#instantiation-and-elaboration" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Instantiation and elaboration</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#expressions" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Expressions</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#preserved-rather-than-reformatted" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Preserved rather than reformatted</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#not-supported" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Not supported</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#design-units-and-declarations" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Design units and declarations</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#procedural-and-concurrent-code" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Procedural and concurrent code</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#instantiation-and-elaboration" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Instantiation and elaboration</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#expressions" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Expressions</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#preserved-rather-than-reformatted" style="--depth: 0;" class="astLine truncated
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="design-units-and-declarations">Design units and declarations</h2><a class="sl-anchor-link" href="#design-units-and-declarations"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Design units and declarations”</span></a></div>
|
||||
<ul>
|
||||
<li>Modules, interfaces, packages, classes, generate regions, and nested classes.</li>
|
||||
<li>ANSI and non-ANSI ports, parameter ports, header imports, <code dir="auto">timeunit</code>, <code dir="auto">genvar</code>, and <code dir="auto">defparam</code>.</li>
|
||||
<li>Net and variable declarations, signing, packed and unpacked dimensions, and net delays.</li>
|
||||
<li><code dir="auto">typedef</code> aliases, enums, packed structs/unions, forward class declarations, anonymous aggregate types, and type parameters.</li>
|
||||
<li>Virtual interfaces, parameterized class types, properties, methods, constructors, prototypes, and out-of-body method definitions.</li>
|
||||
<li>Functions and tasks in ANSI and legacy forms, DPI imports/exports, and package re-exports.</li>
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="procedural-and-concurrent-code">Procedural and concurrent code</h2><a class="sl-anchor-link" href="#procedural-and-concurrent-code"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Procedural and concurrent code”</span></a></div>
|
||||
<ul>
|
||||
<li><code dir="auto">assign</code>, <code dir="auto">always</code>, <code dir="auto">always_comb</code>, <code dir="auto">always_ff</code>, <code dir="auto">always_latch</code>, <code dir="auto">initial</code>, and <code dir="auto">final</code>.</li>
|
||||
<li>Blocks, conditionals, every <code dir="auto">case</code> kind, loops, <code dir="auto">foreach</code>, <code dir="auto">fork/join*</code>, waits, timing controls, events, <code dir="auto">force</code>/<code dir="auto">release</code>, and jump statements.</li>
|
||||
<li>Immediate and concurrent assertions, sequences, and properties. Concurrent property bodies are preserved verbatim.</li>
|
||||
<li><code dir="auto">randomize() with</code>, <code dir="auto">randcase</code>, <code dir="auto">let</code>, statement labels, array iterator methods, and omitted positional arguments.</li>
|
||||
<li>Constraint blocks, covergroups, and randomization constraint bodies are preserved verbatim.</li>
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="instantiation-and-elaboration">Instantiation and elaboration</h2><a class="sl-anchor-link" href="#instantiation-and-elaboration"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Instantiation and elaboration”</span></a></div>
|
||||
<ul>
|
||||
<li>Module and gate instantiation, named and ordered connections, <code dir="auto">.*</code>, parameter overrides, instance arrays, and drive strengths.</li>
|
||||
<li><code dir="auto">bind</code> directives at file, module, and generate scope.</li>
|
||||
<li>Module-level generate <code dir="auto">if</code>, <code dir="auto">for</code>, and <code dir="auto">case</code>, including elaboration system tasks.</li>
|
||||
<li>Compiler directives and macros between list elements, including conditional branches inside ports, parameters, enums, overrides, and connections.</li>
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="expressions">Expressions</h2><a class="sl-anchor-link" href="#expressions"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Expressions”</span></a></div>
|
||||
<ul>
|
||||
<li>Full operator precedence, ternaries, concatenation and replication, slices, streaming concatenations, casts, and assignment patterns.</li>
|
||||
<li>Hierarchical and package-scoped names, named call arguments, array methods, <code dir="auto">inside</code>, and all supported <code dir="auto">new</code> forms.</li>
|
||||
<li>Dynamic arrays, queues, associative arrays, empty literals, and <code dir="auto">$</code>-bound indexing.</li>
|
||||
<li>Macro invocations in expression, statement, and item position; macro digits in based numbers.</li>
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="preserved-rather-than-reformatted">Preserved rather than reformatted</h2><a class="sl-anchor-link" href="#preserved-rather-than-reformatted"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Preserved rather than reformatted”</span></a></div>
|
||||
<p>Some constructs are recognized structurally but emitted with their internal source layout intact: compiler directives, macro bodies, constraints, covergroups, concurrent property/sequence bodies, and carefully recovered conditional-split declarations. This keeps unfamiliar subgrammars safe without blocking the surrounding file.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="not-supported">Not supported</h2><a class="sl-anchor-link" href="#not-supported"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Not supported”</span></a></div>
|
||||
<p><code dir="auto">specify</code> blocks, <code dir="auto">checker</code>, <code dir="auto">program</code>, <code dir="auto">interface class</code>, and <code dir="auto">randsequence</code> remain outside the formatter grammar. lucisv also does not run a preprocessor, so a file that becomes valid only after cross-file macro expansion may not format as a standalone input.</p>
|
||||
<aside aria-label="Safe failure" class="starlight-aside starlight-aside--caution"><p class="starlight-aside__title" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="starlight-aside__icon"><path d="M12 16a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm10.67 1.47-8.05-14a3 3 0 0 0-5.24 0l-8 14A3 3 0 0 0 3.94 22h16.12a3 3 0 0 0 2.61-4.53Zm-1.73 2a1 1 0 0 1-.88.51H3.94a1 1 0 0 1-.88-.51 1 1 0 0 1 0-1l8-14a1 1 0 0 1 1.78 0l8.05 14a1 1 0 0 1 .05 1.02v-.02ZM12 8a1 1 0 0 0-1 1v4a1 1 0 0 0 2 0V9a1 1 0 0 0-1-1Z"/></svg>Safe failure</p><div class="starlight-aside__content"><p>Whole-file formatting returns an error and writes nothing when parsing is incomplete. lucisv never emits a partially understood file.</p></div></aside>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/syntax.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/editors/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors & LSP</span></span></a><a href="/reference/cli/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html><html lang="en" dir="ltr" data-theme="dark" data-has-hero class="astro-vdxcvpsm"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>lucisv — Verilog tooling that stays out of your way | lucisv</title><link rel="canonical" href="https://lucisv.dev/"/><link rel="sitemap" href="/sitemap-index.xml"/><script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"lucisv","applicationCategory":"DeveloperApplication","operatingSystem":"macOS, Linux, Windows","softwareVersion":"0.9.0","license":"https://opensource.org/licenses/MIT","description":"A fast Verilog and SystemVerilog formatter, linter, and language server written in Rust.","codeRepository":"https://git.luci.ooo/lucio/verilogrustformatter"}</script><link rel="shortcut icon" href="/favicon.png" type="image/png"/><meta name="generator" content="Astro v7.2.8"/><meta name="generator" content="Starlight v0.41.9"/><meta property="og:title" content="lucisv — Verilog tooling that stays out of your way"/><meta property="og:type" content="article"/><meta property="og:url" content="https://lucisv.dev/"/><meta property="og:locale" content="en"/><meta property="og:description" content="A fast, deterministic formatter, linter, and language server for Verilog and SystemVerilog, written in Rust."/><meta name="description" content="A fast, deterministic formatter, linter, and language server for Verilog and SystemVerilog, written in Rust."/><meta name="theme-color" content="#07111f"/><meta property="og:site_name" content="lucisv documentation"/><meta property="og:image" content="https://lucisv.dev/og.png"/><meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/><meta property="og:image:alt" content="lucisv — Verilog tooling that stays out of your way."/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:image" content="https://lucisv.dev/og.png"/><script>
|
||||
window.StarlightThemeProvider = (() => {
|
||||
const storedTheme =
|
||||
typeof localStorage !== 'undefined' && localStorage.getItem('starlight-theme');
|
||||
const theme =
|
||||
storedTheme ||
|
||||
(window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark';
|
||||
return {
|
||||
updatePickers(theme = storedTheme || 'auto') {
|
||||
document.querySelectorAll('starlight-theme-select').forEach((picker) => {
|
||||
const select = picker.querySelector('select');
|
||||
if (select) select.value = theme;
|
||||
/** @type {HTMLTemplateElement | null} */
|
||||
const tmpl = document.querySelector(`#theme-icons`);
|
||||
const newIcon = tmpl && tmpl.content.querySelector('.' + theme);
|
||||
if (newIcon) {
|
||||
const oldIcon = picker.querySelector('svg.label-icon');
|
||||
if (oldIcon) {
|
||||
oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
})();
|
||||
</script><template id="theme-icons"><svg aria-hidden="true" class="light astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M5 12a1 1 0 0 0-1-1H3a1 1 0 0 0 0 2h1a1 1 0 0 0 1-1Zm.64 5-.71.71a1 1 0 0 0 0 1.41 1 1 0 0 0 1.41 0l.71-.71A1 1 0 0 0 5.64 17ZM12 5a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1a1 1 0 0 0 1 1Zm5.66 2.34a1 1 0 0 0 .7-.29l.71-.71a1 1 0 1 0-1.41-1.41l-.66.71a1 1 0 0 0 0 1.41 1 1 0 0 0 .66.29Zm-12-.29a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.71-.71a1.004 1.004 0 1 0-1.43 1.41l.73.71ZM21 11h-1a1 1 0 0 0 0 2h1a1 1 0 0 0 0-2Zm-2.64 6A1 1 0 0 0 17 18.36l.71.71a1 1 0 0 0 1.41 0 1 1 0 0 0 0-1.41l-.76-.66ZM12 6.5a5.5 5.5 0 1 0 5.5 5.5A5.51 5.51 0 0 0 12 6.5Zm0 9a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7Zm0 3.5a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-1a1 1 0 0 0-1-1Z"/></svg><svg aria-hidden="true" class="dark astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.64 13a1 1 0 0 0-1.05-.14 8.049 8.049 0 0 1-3.37.73 8.15 8.15 0 0 1-8.14-8.1 8.59 8.59 0 0 1 .25-2A1 1 0 0 0 8 2.36a10.14 10.14 0 1 0 14 11.69 1 1 0 0 0-.36-1.05Zm-9.5 6.69A8.14 8.14 0 0 1 7.08 5.22v.27a10.15 10.15 0 0 0 10.14 10.14 9.784 9.784 0 0 0 2.1-.22 8.11 8.11 0 0 1-7.18 4.32v-.04Z"/></svg><svg aria-hidden="true" class="auto astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg></template><link rel="stylesheet" href="/_astro/print.ehPL0gv-.css" media="print"><link rel="stylesheet" href="/_astro/common.db7thnbo.css"><script type="module" src="/_astro/page.Dwipeu-R.js"></script></head><body class="astro-vdxcvpsm"><a class="sl-skip-link astro-vxeigawq" href="#_top">Skip to content</a><div class="page sl-flex astro-gqpr5s5a"><header class="header astro-gqpr5s5a"><div class="header astro-nczgtkxc"><div class="title-wrapper sl-flex astro-nczgtkxc"><a href="/" class="site-title sl-flex astro-clw6ags5"><span class="astro-clw6ags5" translate="no">lucisv</span></a></div><div class="sl-flex print:hidden astro-nczgtkxc"><site-search class="astro-nczgtkxc astro-r5ar4xm7" data-translations="{"placeholder":"Search"}"><button data-open-modal disabled aria-label="Search" aria-keyshortcuts="Control+K" class="astro-r5ar4xm7"><svg aria-hidden="true" class="astro-r5ar4xm7 astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21.71 20.29 18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a.999.999 0 0 0 1.42 0 1 1 0 0 0 0-1.39ZM11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z"/></svg><span class="sl-hidden md:sl-block astro-r5ar4xm7" aria-hidden="true">Search</span><kbd class="sl-hidden md:sl-flex astro-r5ar4xm7" style="display: none;"><kbd class="astro-r5ar4xm7">Ctrl</kbd><kbd class="astro-r5ar4xm7">K</kbd></kbd></button><dialog style="padding:0" aria-label="Search" class="astro-r5ar4xm7"><div class="dialog-frame sl-flex astro-r5ar4xm7"><button data-close-modal class="sl-flex md:sl-hidden astro-r5ar4xm7">Cancel</button><div class="search-container astro-r5ar4xm7"><div id="starlight__search" class="astro-r5ar4xm7"></div></div></div></dialog></site-search><script>
|
||||
(() => {
|
||||
const openBtn = document.querySelector('button[data-open-modal]');
|
||||
const shortcut = openBtn?.querySelector('kbd');
|
||||
if (!openBtn || !(shortcut instanceof HTMLElement)) return;
|
||||
const platformKey = shortcut.querySelector('kbd');
|
||||
if (platformKey && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
|
||||
platformKey.textContent = '⌘';
|
||||
openBtn.setAttribute('aria-keyshortcuts', 'Meta+K');
|
||||
}
|
||||
shortcut.style.display = '';
|
||||
})();
|
||||
</script><script type="module" src="/_astro/Search.astro_astro_type_script_index_0_lang.B-Vh4ymV.js"></script></div><div class="sl-hidden md:sl-flex print:hidden right-group astro-nczgtkxc"><div class="sl-flex social-icons astro-nczgtkxc"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script><script type="module">var e=`starlight-theme`,t=e=>e===`auto`||e===`dark`||e===`light`?e:`auto`,n=()=>t(typeof localStorage<`u`&&localStorage.getItem(e));function r(t){typeof localStorage<`u`&&localStorage.setItem(e,t===`light`||t===`dark`?t:``)}var i=()=>matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`;function a(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e===`auto`?i():e,r(e)}matchMedia(`(prefers-color-scheme: light)`).addEventListener(`change`,()=>{n()===`auto`&&a(`auto`)});var o=class extends HTMLElement{constructor(){super(),a(n()),this.querySelector(`select`)?.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&a(t(e.currentTarget.value))})}};customElements.define(`starlight-theme-select`,o);</script><script type="module">var e=class extends HTMLElement{constructor(){super();let e=this.querySelector(`select`);e&&(e.addEventListener(`change`,e=>{e.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=e.currentTarget.value)}),window.addEventListener(`pageshow`,t=>{if(!t.persisted)return;let n=e.querySelector(`option[selected]`)?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}};customElements.define(`starlight-lang-select`,e);</script></div></div></header><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><div class="main-pane astro-abfeecmu"><main data-pagefind-body class="astro-vdxcvpsm" lang="en" dir="ltr"><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><div class="hero astro-q2ezz3gc"><div class="sl-flex stack astro-q2ezz3gc"><div class="sl-flex copy astro-q2ezz3gc"><h1 id="_top" data-page-title class="astro-q2ezz3gc">RTL, without the friction.</h1><div class="tagline astro-q2ezz3gc">One fast Rust toolchain for formatting, linting, navigation, refactoring, and editor intelligence across Verilog and SystemVerilog.</div></div><div class="sl-flex actions astro-q2ezz3gc"><a class="sl-link-button not-content primary astro-q2ezz3gc astro-hlbqph7b" href="/start/quick-start/">Get started<svg aria-hidden="true" class="astro-hlbqph7b astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg></a><a class="sl-link-button not-content minimal astro-q2ezz3gc astro-hlbqph7b" href="/reference/language-tools/">Explore the tools<svg aria-hidden="true" class="astro-hlbqph7b astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M21.17 2.06A13.1 13.1 0 0 0 19 1.87a12.94 12.94 0 0 0-7 2.05 12.94 12.94 0 0 0-7-2 13.1 13.1 0 0 0-2.17.19 1 1 0 0 0-.83 1v12a1 1 0 0 0 1.17 1 10.9 10.9 0 0 1 8.25 1.91l.12.07h.11a.91.91 0 0 0 .7 0h.11l.12-.07A10.899 10.899 0 0 1 20.83 16 1 1 0 0 0 22 15V3a1 1 0 0 0-.83-.94ZM11 15.35a12.87 12.87 0 0 0-6-1.48H4v-10c.333-.02.667-.02 1 0a10.86 10.86 0 0 1 6 1.8v9.68Zm9-1.44h-1a12.87 12.87 0 0 0-6 1.48V5.67a10.86 10.86 0 0 1 6-1.8c.333-.02.667-.02 1 0v10.04Zm1.17 4.15a13.098 13.098 0 0 0-2.17-.19 12.94 12.94 0 0 0-7 2.05 12.94 12.94 0 0 0-7-2.05c-.727.003-1.453.066-2.17.19A1 1 0 0 0 2 19.21a1 1 0 0 0 1.17.79 10.9 10.9 0 0 1 8.25 1.91 1 1 0 0 0 1.16 0A10.9 10.9 0 0 1 20.83 20a1 1 0 0 0 1.17-.79 1 1 0 0 0-.83-1.15Z"/></svg></a></div></div></div><div class="sl-markdown-content"><div class="metric-row"><div class="metric"><strong>99.1%</strong><span>measured corpus parse rate</span></div><div class="metric"><strong>16</strong><span>built-in lint rules</span></div><div class="metric"><strong>2</strong><span>portable binaries</span></div><div class="metric"><strong>0</strong><span>runtime dependencies</span></div></div>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="a-single-coherent-toolchain">A single, coherent toolchain</h2><a class="sl-anchor-link" href="#a-single-coherent-toolchain"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “A single, coherent toolchain”</span></a></div>
|
||||
<p>lucisv treats formatting, diagnostics, and code intelligence as one problem. The same parser and semantic model power the command line and every editor, so the answer in CI is the answer at your cursor.</p>
|
||||
<div class="card-grid"><article class="feature-card"><span class="eyebrow">Formatter</span><h3>Deterministic by construction</h3><p>Width-aware layout, preserved comments, inferred alignment, format fences, range formatting, and idempotency checks—without rewriting files it cannot fully parse.</p></article><article class="feature-card"><span class="eyebrow">Linter</span><h3>RTL-aware defaults</h3><p>Sixteen focused rules, safe fixes, source waivers, text and JSON output, plus opt-in semantic checks.</p></article><article class="feature-card"><span class="eyebrow">Language server</span><h3>Fast feedback in any editor</h3><p>Formatting, diagnostics, navigation, completion, semantic highlighting, refactors, hierarchy, and more over standard LSP.</p></article><article class="feature-card"><span class="eyebrow">Workspace</span><h3>Understands real projects</h3><p>EDA filelists, nested includes, defines, Git-style ignores, multi-root indexes, and live overlay promotion.</p></article><article class="feature-card"><span class="eyebrow">Safety</span><h3>No half-formatted source</h3><p>Parse-first operation, atomic writes, equivalence verification, convergence checks, deterministic parallel output, and explicit exit codes make lucisv suitable for CI and large RTL trees.</p></article></div>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="from-source-text-to-editor-intelligence">From source text to editor intelligence</h2><a class="sl-anchor-link" href="#from-source-text-to-editor-intelligence"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “From source text to editor intelligence”</span></a></div>
|
||||
<div class="pipeline"><div><b>01 / parse</b>Comment-preserving tokens and an error-tolerant AST.</div><i>→</i><div><b>02 / understand</b>Scopes, symbols, references, defines, and workspace units.</div><i>→</i><div><b>03 / act</b>Format, lint, navigate, refactor, complete, and diagnose.</div></div>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame is-terminal has-title not-content"><figcaption class="header"><span class="title">The 30-second tour</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#919F9F;--1:#5F636F"># format in place</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--check</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#919F9F;--1:#5F636F"># enforce formatting in CI</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">check</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--fix</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#919F9F;--1:#5F636F"># lint and apply safe fixes</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--lines</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">120-134</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">rtl/alu.sv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#919F9F;--1:#5F636F"># format only your change</span></div></div><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">lucisv-server</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#919F9F;--1:#5F636F"># start the language server over stdio</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="lucisv rtl/ # format in placelucisv --check rtl/ # enforce formatting in CIlucisv check --fix rtl/ # lint and apply safe fixeslucisv --lines 120-134 rtl/alu.sv # format only your changelucisv-server # start the language server over stdio"><div></div></button></div></figure></div>
|
||||
<aside aria-label="Open by design" class="starlight-aside starlight-aside--note"><p class="starlight-aside__title" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="starlight-aside__icon"><path d="M12 11a1 1 0 0 0-1 1v4a1 1 0 0 0 2 0v-4a1 1 0 0 0-1-1Zm.38-3.92a1 1 0 0 0-.76 0 1 1 0 0 0-.33.21 1.15 1.15 0 0 0-.21.33 1 1 0 0 0 .21 1.09c.097.088.209.16.33.21A1 1 0 0 0 13 8a1.05 1.05 0 0 0-.29-.71 1 1 0 0 0-.33-.21ZM12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 18a8 8 0 1 1 0-16.001A8 8 0 0 1 12 20Z"/></svg>Open by design</p><div class="starlight-aside__content"><p>lucisv is MIT licensed. The CLI, parser, formatter, linter, semantic engine, refactoring engine, language server, and editor integrations all live in the same Rust workspace.</p></div></aside></div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/index.mdx" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/quick-start/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Quick start</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 1.1 MiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1509
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,56 @@
|
||||
"use strict";(()=>{var ls=Object.defineProperty;var h=(n,s)=>{for(var e in s)ls(n,e,{get:s[e],enumerable:!0})};var Bt={};h(Bt,{PagefindConfig:()=>Re,PagefindElement:()=>f,PagefindFilterDropdown:()=>Me,PagefindFilterPane:()=>Ne,PagefindInput:()=>ke,PagefindKeyboardHints:()=>Le,PagefindModal:()=>Oe,PagefindModalBody:()=>Ie,PagefindModalFooter:()=>Ue,PagefindModalHeader:()=>we,PagefindModalTrigger:()=>He,PagefindResults:()=>Se,PagefindSearchbox:()=>Fe,PagefindSummary:()=>Ae,configureInstance:()=>Qt,getInstanceManager:()=>Ce});var os="a[href], button, input, [tabindex]";function Kt(n){let s=n.querySelectorAll(os);for(let e of s)if(!(e.tabIndex<0)&&!e.disabled&&!e.hasAttribute("hidden")&&window.getComputedStyle(e).display!=="none")return!0;return!1}function $t(n,s){let e=null;for(let t of s)t.contains(n)||!(n.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING)||Kt(t)&&(e===null||t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING)&&(e=t);return e}function Pe(n,s){let e=null;for(let t of s)t.contains(n)||!(n.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_PRECEDING)||Kt(t)&&(e===null||t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)&&(e=t);return e}var Ve={};h(Ve,{comments:()=>us,default:()=>ps,direction:()=>ds,strings:()=>hs,thanks_to:()=>cs});var cs="Jan Claasen <[email protected]>",us="",ds="ltr",hs={placeholder:"Soek",clear_search:"Opruim",load_more:"Laai nog resultate",search_label:"Soek hierdie webwerf",filters_label:"Filters",zero_results:"Geen resultate vir [SEARCH_TERM]",many_results:"[COUNT] resultate vir [SEARCH_TERM]",one_result:"[COUNT] resultate vir [SEARCH_TERM]",total_zero_results:"Geen resultate",total_one_result:"[COUNT] resultaat",total_many_results:"[COUNT] resultate",alt_search:"Geen resultate vir [SEARCH_TERM]. Toon resultate vir [DIFFERENT_TERM] in plaas daarvan",search_suggestion:"Geen resultate vir [SEARCH_TERM]. Probeer eerder een van die volgende terme:",searching:"Soek vir [SEARCH_TERM]",results_label:"Soekresultate",keyboard_navigate:"navigeer",keyboard_select:"kies",keyboard_clear:"wis",keyboard_close:"sluit",keyboard_search:"soek",error_search:"Soek het misluk",filter_selected_one:"[COUNT] gekies",filter_selected_many:"[COUNT] gekies",input_hint:"Resultate sal verskyn terwyl jy tik",loading:"Laai"},ps={thanks_to:cs,comments:us,direction:ds,strings:hs};var qe={};h(qe,{comments:()=>_s,default:()=>Es,direction:()=>fs,strings:()=>gs,thanks_to:()=>ms});var ms="Jermanuts",_s="",fs="rtl",gs={placeholder:"\u0628\u062D\u062B",clear_search:"\u0627\u0645\u0633\u062D",load_more:"\u062D\u0645\u0651\u0650\u0644 \u0627\u0644\u0645\u0632\u064A\u062F \u0645\u0646 \u0627\u0644\u0646\u062A\u0627\u0626\u062C",search_label:"\u0627\u0628\u062D\u062B \u0641\u064A \u0647\u0630\u0627 \u0627\u0644\u0645\u0648\u0642\u0639",filters_label:"\u062A\u0635\u0641\u064A\u0627\u062A",zero_results:"\u0644\u0627 \u062A\u0648\u062C\u062F \u0646\u062A\u0627\u0626\u062C \u0644 [SEARCH_TERM]",many_results:"[COUNT] \u0646\u062A\u0627\u0626\u062C \u0644 [SEARCH_TERM]",one_result:"[COUNT] \u0646\u062A\u064A\u062C\u0629 \u0644 [SEARCH_TERM]",total_zero_results:"\u0644\u0627 \u062A\u0648\u062C\u062F \u0646\u062A\u0627\u0626\u062C",total_one_result:"[COUNT] \u0646\u062A\u064A\u062C\u0629",total_many_results:"[COUNT] \u0646\u062A\u0627\u0626\u062C",alt_search:"\u0644\u0627 \u062A\u0648\u062C\u062F \u0646\u062A\u0627\u0626\u062C \u0644 [SEARCH_TERM]. \u064A\u0639\u0631\u0636 \u0627\u0644\u0646\u062A\u0627\u0626\u062C \u0644 [DIFFERENT_TERM] \u0628\u062F\u0644\u0627\u064B \u0645\u0646 \u0630\u0644\u0643",search_suggestion:"\u0644\u0627 \u062A\u0648\u062C\u062F \u0646\u062A\u0627\u0626\u062C \u0644 [SEARCH_TERM]. \u062C\u0631\u0628 \u0623\u062D\u062F \u0639\u0645\u0644\u064A\u0627\u062A \u0627\u0644\u0628\u062D\u062B \u0627\u0644\u062A\u0627\u0644\u064A\u0629:",searching:"\u064A\u0628\u062D\u062B \u0639\u0646 [SEARCH_TERM]...",results_label:"\u0646\u062A\u0627\u0626\u062C \u0627\u0644\u0628\u062D\u062B",keyboard_navigate:"\u062A\u0646\u0642\u0644",keyboard_select:"\u0627\u062E\u062A\u064A\u0627\u0631",keyboard_clear:"\u0627\u0645\u0633\u062D",keyboard_close:"\u0625\u063A\u0644\u0627\u0642",keyboard_search:"\u0628\u062D\u062B",error_search:"\u0641\u0634\u0644 \u0627\u0644\u0628\u062D\u062B",filter_selected_one:"[COUNT] \u0645\u062D\u062F\u062F",filter_selected_many:"[COUNT] \u0645\u062D\u062F\u062F",input_hint:"\u0633\u062A\u0638\u0647\u0631 \u0627\u0644\u0646\u062A\u0627\u0626\u062C \u0623\u062B\u0646\u0627\u0621 \u0627\u0644\u0643\u062A\u0627\u0628\u0629",loading:"\u062C\u0627\u0631\u064D \u0627\u0644\u062A\u062D\u0645\u064A\u0644"},Es={thanks_to:ms,comments:_s,direction:fs,strings:gs};var Ge={};h(Ge,{comments:()=>Ts,default:()=>vs,direction:()=>Cs,strings:()=>ys,thanks_to:()=>bs});var bs="Maruf Alom <[email protected]>",Ts="",Cs="ltr",ys={placeholder:"\u0985\u09A8\u09C1\u09B8\u09A8\u09CD\u09A7\u09BE\u09A8 \u0995\u09B0\u09C1\u09A8",clear_search:"\u09AE\u09C1\u099B\u09C7 \u09AB\u09C7\u09B2\u09C1Line truncated
|
||||
`)),document?.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?console.error(`[DEBUG: Loaded from ${document.currentScript?.src??"bad script location"}]`):console.error("no known script location"),this.__dispatch__("error",{type:"bundle_load_failed",message:"Could not load search bundle",bundlePath:this.options.bundlePath,error:t}),this.hasAnnouncementCapability()||this.announce("error_search",{},"assertive");return}let e=s.createInstance(this.pagefindOptions||{});for(let t of this.options.mergeIndex){if(!t.bundlePath)throw new Error("mergeIndex requires a bundlePath parameter");let{bundlePath:r,...i}=t;await e.mergeIndex(r,i)}this.__pagefind__=e,this.availableFilters=await this.__pagefind__.filters(),this.totalFilters=this.availableFilters,this.__dispatch__("filters",{available:this.availableFilters,total:this.totalFilters}),this.faceted&&this.__searchID__===0&&this.triggerSearch("")}thinSubResults(s,e=3){if(s.length<=e)return s;let t=[...s].sort((r,i)=>(i.locations?.length??0)-(r.locations?.length??0)).slice(0,e).map(r=>r.url);return s.filter(r=>t.includes(r.url))}getDisplaySubResults(s,e=3){if(!Array.isArray(s.sub_results))return[];let r=s.sub_results[0]?.url===(s.meta?.url||s.url)?s.sub_results.slice(1):s.sub_results;return this.thinSubResults(r,e)}};var Pt=class{constructor(){this.instances=new Map;this.defaultOptions={bundlePath:this.detectBundlePath()}}detectBundlePath(){try{if(document?.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"){let s=new URL(document.currentScript.src).pathname.match(/^(.*\/)(?:pagefind[-_])?.*\.js.*$/);if(s)return s[1]}}catch{}return"/pagefind/"}getInstance(s="default",e={}){let t=this.instances.get(s);if(t)return t;let r={...this.defaultOptions,...e},i=new Te(s,r);return this.instances.set(s,i),i}hasInstance(s){return this.instances.has(s)}removeInstance(s){this.instances.delete(s)}getInstanceNames(){return Array.from(this.instances.keys())}},Ft=null;function Ce(){return Ft||(Ft=new Pt),Ft}function Qt(n,s){let e=Ce();return e.hasInstance(n)?(console.warn(`[Pagefind Component UI]: Instance "${n}" already exists, configuration ignored`),e.getInstance(n)):e.getInstance(n,s)}var ye=n=>!(n==null||n===!1||n===0||n===""||Number.isNaN(n)||Array.isArray(n)&&n.length===0||typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.keys(n).length===0),T=(n,s,e)=>n.length<s?`[Error: ${e}() needs ${s} args]`:null,es={eq:(n,...s)=>T(s,2,"eq")??m(s[0],n)===m(s[1],n),ne:(n,...s)=>T(s,2,"ne")??m(s[0],n)!==m(s[1],n),gt:(n,...s)=>T(s,2,"gt")??Number(m(s[0],n))>Number(m(s[1],n)),lt:(n,...s)=>T(s,2,"lt")??Number(m(s[0],n))<Number(m(s[1],n)),gte:(n,...s)=>T(s,2,"gte")??Number(m(s[0],n))>=Number(m(s[1],n)),lte:(n,...s)=>T(s,2,"lte")??Number(m(s[0],n))<=Number(m(s[1],n)),and:(n,...s)=>{let e=!0;for(let t of s)if(e=m(t,n),!ye(e))return e;return e},or:(n,...s)=>{let e=!1;for(let t of s)if(e=m(t,n),ye(e))return e;return e},not:(n,...s)=>T(s,1,"not")??!ye(m(s[0],n)),lowercase:(n,...s)=>String(m(s[0],n)).toLowerCase(),uppercase:(n,...s)=>String(m(s[0],n)).toUpperCase(),trim:(n,...s)=>String(m(s[0],n)).trim(),truncate:(n,...s)=>{let e=T(s,2,"truncate");if(e)return e;let t=String(m(s[0],n)),r=Number(m(s[1],n)),i=s[2]?String(m(s[2],n)):"...";return t.length>r?t.slice(0,r)+i:t},replace:(n,...s)=>T(s,3,"replace")??String(m(s[0],n)).split(String(m(s[1],n))).join(String(m(s[2],n))),limit:(n,...s)=>{let e=T(s,2,"limit");if(e)return e;let t=m(s[0],n),r=m(s[1],n);return Array.isArray(t)?t.slice(0,r<0?0:r):t},first:(n,...s)=>{let e=T(s,1,"first");if(e)return e;let t=m(s[0],n);return Array.isArray(t)?t[0]:t},last:(n,...s)=>{let e=T(s,1,"last");if(e)return e;let t=m(s[0],n);return Array.isArray(t)?t[t.length-1]:t},length:(n,...s)=>{let e=T(s,1,"length");if(e)return e;let t=m(s[0],n);return Array.isArray(t)?t.length:String(t).length},join:(n,...s)=>T(s,2,"join")??(e=>Array.isArray(e)?e.join(String(m(s[1],n))):String(e))(m(s[0],n)),default:(n,...s)=>{let e=T(s,2,"default");if(e)return e;let t=m(s[0],n);return ye(t)?t:m(s[1],n)},safeUrl:(n,...s)=>{let e=String(m(s[0],n)??"").trim();return e&&/^(?:\.{0,2}\/|[#?]|(?:https?|ftp):\/\/|(?:mailto|tel):)/i.test(e)?e:""}},m=(n,s)=>{if(!n)return;if(n.t==="L")return n.val;if(n.t==="V"){let t=(i,a)=>Object.prototype.hasOwnProperty.call(i,a),r=s;for(let i of n.path){if(r==null||!t(r,i))return;r=r[i]}return r}let e=es[n.fn];return e?n.t==="C"?e(s,...n.args):e(s,n.left,...n.args):`[Error: unknown ${n.fn}()]`},ga=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ve=(n,s)=>{let e="";for(let t of n){if(t.t==="T"){e+=t.val;continue}if(t.t==="I"){let r=m(t.expr,s);if(Array.isArray(r))e+="[Error: use #each for arrays]";else if(typeof r=="object"&&r!==null)e+="[Error: cannot render object]";else{let i=String(r??"");e+=t.raw?i:ga(i)}continue}if(t.t==="F"){let r=!1;for(let i of t.branches)if(ye(m(i.cond,s))){e+=ve(i.body,s),r=!0;break}!r&&t.else&&(e+=ve(t.else,s));continue}if(t.t==="E")
Line truncated
|
||||
\r`.includes(s[e]);)e++},r=u=>s.slice(e,e+u.length)===u,i=u=>{r(u)&&(e+=u.length)},a=()=>{let u="";for(;e<s.length&&/\w/.test(s[e]);)u+=s[e++];return u},l=()=>{t();let u=e,d,_=s[e];if(_==='"'||_==="'"){let p=s[e++],g="";for(;e<s.length&&s[e]!==p;){if(s[e]==="\\"&&e+1<s.length){e++;let E=s[e];g+=E==="n"?`
|
||||
`:E==="t"?" ":E==="r"?"\r":E,e++;continue}g+=s[e++]}e<s.length?e++:g="",d={t:"L",val:g}}else if(/[-0-9.]/.test(_)){let p="",g=0;for(s[e]==="-"&&(p+=s[e++]),s[e]==="."&&(p+=s[e++],g=1);e<s.length&&(/[0-9]/.test(s[e])||s[e]==="."&&!g++);)p+=s[e++];d=p==="-"||p==="."||p===""?{t:"V",path:[p||"-"]}:{t:"L",val:parseFloat(p)}}else{let p=a();if(p==="true")d={t:"L",val:!0};else if(p==="false")d={t:"L",val:!1};else if(p==="null")d={t:"L",val:null};else if(t(),s[e]==="("){e++;let g=[];for(t();e<s.length&&s[e]!==")"&&s[e]!=="}";)g.push(l()),t(),s[e]===","&&(e++,t());s[e]===")"&&e++,d={t:"C",fn:p,args:g}}else{let g=[p];for(;s[e]===".";)e++,g.push(a());d={t:"V",path:g}}}for(t();s[e]==="|";){e++,t();let p=a();t();let g=[];if(s[e]==="("){for(e++,t();e<s.length&&s[e]!==")"&&s[e]!=="}";)g.push(l()),t(),s[e]===","&&(e++,t());s[e]===")"&&e++}d={t:"P",left:d,fn:p,args:g},t()}return e===u&&e<s.length&&e++,d},o=(u=[])=>{let d=[];e:for(;e<s.length;){for(let p of u)if(r(p))break e;if(s[e]==="\\"&&r("\\{{")){e++,d.push({t:"T",val:"{{"}),e+=2;continue}if(r("{{")){if(e+=2,t(),s[e]==="+"){e++,t();let g=l();for(t(),i("+"),t();e<s.length&&!r("}}");)e++;i("}}"),d.push({t:"I",expr:g,raw:1});continue}if(s[e]==="#"){e++;let g=a();if(t(),g==="if"){let E=[],C=l();for(t(),i("}}"),E.push({cond:C,body:o(["{{:else if","{{:elseif","{{:else}}","{{/if}}"])});r("{{:else if")||r("{{:elseif");){e+=r("{{:elseif")?9:10,t();let v=l();t(),i("}}"),E.push({cond:v,body:o(["{{:else if","{{:elseif","{{:else}}","{{/if}}"])})}let y;r("{{:else}}")&&(e+=9,y=o(["{{/if}}"])),i("{{/if}}"),d.push({t:"F",branches:E,else:y});continue}if(g==="each"){let E=l();t();let C=a();if(t(),C!=="as"){d.push({t:"T",val:"[Error: #each missing 'as']"});continue}let y=a();t();let v;s[e]===","&&(e++,t(),v=a(),t()),i("}}");let $e=o(["{{:else}}","{{/each}}"]),N;r("{{:else}}")&&(e+=9,N=o(["{{/each}}"])),i("{{/each}}"),d.push({t:"E",arr:E,as:y,idx:v,body:$e,else:N});continue}d.push({t:"T",val:`[Error: unknown #${g}]`}),t(),i("}}");continue}let p=l();for(t();e<s.length&&!r("}}");)e++;i("}}"),d.push({t:"I",expr:p});continue}let _="";for(;e<s.length;){for(let p of u)if(r(p)){_&&d.push({t:"T",val:_});continue e}if(s[e]==="\\"&&r("\\{{")||r("{{"))break;_+=s[e++]}_&&d.push({t:"T",val:_})}return d},c=o();return u=>ve(c,u)};var ts=(n,s)=>{es[n]=(e,...t)=>s(...t.map(r=>m(r,e)))};var f=class extends HTMLElement{constructor(){super();this.instance=null;this._initialized=!1}connectedCallback(){if(this._initialized)return;this._initialized=!0;let e=this.getAttribute("instance")||"default",t=Ce();this.instance=t.getInstance(e),this.init(),this.register&&typeof this.register=="function"&&this.register(this.instance)}disconnectedCallback(){this.cleanup&&typeof this.cleanup=="function"&&this.cleanup(),this._initialized=!1}attributeChangedCallback(e,t,r){if(!this._initialized||t===r)return;let i=this.kebabToCamel(e);r==="false"?this[i]=!1:r==="true"?this[i]=!0:r==null?this[i]=!1:this[i]=r,this.update&&typeof this.update=="function"&&this.update()}kebabToCamel(e){return e.replace(/-([a-z])/g,t=>t[1].toUpperCase())}ensureId(e="pagefind"){return!this.id&&this.instance&&(this.id=this.instance.generateId(e)),this.id}init(){}reconcileAria(){}register(e){}cleanup(){}update(){}showError(e){let t=document.createElement("div");t.className="pf-error",t.innerHTML=`
|
||||
<strong>Pagefind Error:</strong> ${this.escapeHtml(e.message||"Unknown error")}
|
||||
${e.details?`<br><small>${this.escapeHtml(e.details)}</small>`:""}
|
||||
`,this.appendChild(t),this.dispatchEvent(new CustomEvent("pagefind-error",{detail:e,bubbles:!0,composed:!0}))}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var Re=class extends f{init(){this.setAttribute("hidden","")}register(s){s.registerUtility(this);let e=this.getAttribute("bundle-path");e&&(s.options.bundlePath=e);let t=this.getAttribute("base-url");t&&(s.pagefindOptions.baseUrl=t);let r=this.getAttribute("excerpt-length");r&&(s.pagefindOptions.excerptLength=parseInt(r,10));let i=this.getAttribute("lang");i&&s.setLanguage(i);let a=this.getAttribute("meta-cache-tag");a&&(s.pagefindOptions.metaCacheTag=a);let l=this.getAttribute("highlight-param");l&&(s.pagefindOptions.highlightParam=l),this.hasAttribute("exact-diacritics")&&(s.pagefindOptions.exactDiacritics=!0),this.hasAttribute("no-worker")&&(s.pagefindOptions.noWorker=!0),this.hasAttribute("faceted")&&(s.faceted=!0),this.hasAttribute("preload")&&s.triggerLoad()}};customElements.get("pagefind-config")||customElements.define("pagefind-config",Re);var Ea=(n=100)=>new Promise(s=>setTimeout(s,n)),ke=class extends f{constructor(){super();this.inputEl=null;this.clearEl=null;this.searchID=0;this.placeholder="";this.debounce=300;this.autofocus=!1}static get observedAttributes(){return["placeholder","debounce","autofocus"]}readAttributes(){this.hasAttribute("placeholder")&&(this.placeholder=this.getAttribute("placeholder")||""),this.hasAttribute("debounce")&&(this.debounce=parseInt(this.getAttribute("debounce")||"300",10)||300),this.hasAttribute("autofocus")&&(this.autofocus=this.hasAttribute("autofocus"))}init(){this.readAttributes(),this.render()}render(){this.innerHTML="";let e=this.instance.generateId("pfmod-input"),t=this.instance?.translate("search_label")||"Search this site",r=this.instance?.translate("clear_search")||"Clear",i=this.placeholder||this.instance?.translate("placeholder")||"Search";this.instance?.direction==="rtl"?this.setAttribute("dir","rtl"):this.removeAttribute("dir");let a=document.createElement("search");a.className="pf-input-wrapper",a.setAttribute("role","search"),a.setAttribute("aria-label",t);let l=document.createElement("label");l.setAttribute("for",e),l.setAttribute("data-pf-sr-hidden","true"),l.textContent=t,a.appendChild(l),this.inputEl=document.createElement("input"),this.inputEl.id=e,this.inputEl.className="pf-input",this.inputEl.setAttribute("type","search"),this.inputEl.setAttribute("autocomplete","off"),this.inputEl.setAttribute("autocapitalize","none"),this.inputEl.setAttribute("enterkeyhint","search"),this.inputEl.setAttribute("placeholder",i),this.autofocus&&this.inputEl.setAttribute("autofocus","autofocus");let o=this.instance.generateId("pf-input-hint"),c=this.instance?.translate("input_hint")||"Results will appear as you type",u=document.createElement("span");u.id=o,u.setAttribute("data-pf-sr-hidden","true"),u.textContent=c,this.inputEl.setAttribute("aria-describedby",o),a.appendChild(this.inputEl),a.appendChild(u),this.clearEl=document.createElement("button"),this.clearEl.className="pf-input-clear",this.clearEl.setAttribute("type","button"),this.clearEl.setAttribute("data-pf-suppressed","true"),this.clearEl.textContent=r,a.appendChild(this.clearEl),this.appendChild(a),this.setupEventHandlers()}setupEventHandlers(){!this.inputEl||!this.clearEl||(this.inputEl.addEventListener("input",async e=>{let t=e.target;if(this.instance&&typeof t?.value=="string"){this.updateState(t.value);let r=++this.searchID;if(await Ea(this.debounce),r!==this.searchID)return;this.instance?.triggerSearch(t.value)}}),this.inputEl.addEventListener("keydown",e=>{e.key==="Escape"&&(++this.searchID,this.inputEl&&(this.inputEl.value=""),this.instance?.triggerSearch(""),this.updateState("")),e.key==="ArrowDown"&&(e.preventDefault(),this.inputEl&&this.instance?.focusNextResults(this.inputEl))}),this.inputEl.addEventListener("focus",()=>{this.instance?.triggerLoad();let e=this.instance?.translate("keyboard_navigate")||"navigate",t=this.instance?.translate("keyboard_clear")||"clear";this.instance?.registerShortcut({label:"\u2193",description:e},this),this.instance?.registerShortcut({label:"esc",description:t},this)}),this.inputEl.addEventListener("blur",()=>{this.instance?.deregisterAllShortcuts(this)}),this.clearEl.addEventListener("click",()=>{this.inputEl&&(this.inputEl.value="",this.instance?.triggerSearch(""),this.updateState(""),this.inputEl.focus())}))}updateState(e){this.clearEl&&(e&&e?.length?this.clearEl.removeAttribute("data-pf-suppressed"):this.clearEl.setAttribute("data-pf-suppressed","true"))}register(e){e.registerInput(this,{keyboardNavigation:!0}),e.on("search",t=>{this.inputEl&&document.activeElement!==this.inputEl&&(this.inputEl.value=t,this.updateState(t))},this),e.on("error",t=>{let r=t;this.showError({message:r.message||"Search initialization failed",details:r.bundlePath?`Bundle path: ${r.bundlePath}`:void 0})},this),e.on("translations",()=>{let t=this.inputEl?.value||"";this.render(
Line truncated
|
||||
<div class="pf-result-card">
|
||||
{{#if and(options.show_images, meta.image)}}
|
||||
<img class="pf-result-image" src="{{ meta.image | resolveUrl(meta.url | default(url)) }}" alt="{{ meta.image_alt | default(meta.title) }}">
|
||||
{{/if}}
|
||||
<div class="pf-result-content">
|
||||
<p class="pf-result-title">
|
||||
<a class="pf-result-link" href="{{ meta.url | default(url) | safeUrl }}"{{#if options.link_target}} target="{{ options.link_target }}"{{/if}}{{#if eq(options.link_target, "_blank")}} rel="noopener"{{/if}}>{{ meta.title }}</a>
|
||||
</p>
|
||||
{{#if excerpt}}
|
||||
<p class="pf-result-excerpt">{{+ excerpt +}}</p>
|
||||
{{/if}}
|
||||
</div>
|
||||
</div>
|
||||
{{#if sub_results}}
|
||||
<ul class="pf-heading-chips">
|
||||
{{#each sub_results as sub}}
|
||||
<li class="pf-heading-chip">
|
||||
<a class="pf-heading-link" href="{{ sub.url | safeUrl }}"{{#if options.link_target}} target="{{ options.link_target }}"{{/if}}{{#if eq(options.link_target, "_blank")}} rel="noopener"{{/if}}>{{ sub.title }}</a>
|
||||
<p class="pf-heading-excerpt">{{+ sub.excerpt +}}</p>
|
||||
</li>
|
||||
{{/each}}
|
||||
</ul>
|
||||
{{/if}}
|
||||
</li>`,Ta=`<li class="pf-result" aria-hidden="true">
|
||||
<div class="pf-result-card">
|
||||
<div class="pf-skeleton pf-skeleton-image"></div>
|
||||
<div class="pf-result-content">
|
||||
<p class="pf-result-title pf-skeleton pf-skeleton-title"></p>
|
||||
<p class="pf-result-excerpt pf-skeleton pf-skeleton-excerpt"></p>
|
||||
</div>
|
||||
</div>
|
||||
</li>`,Ca=R(ba),ya=R(Ta),rs=(n,s)=>{for(let e of n)if(e instanceof Element){e.setAttribute("data-pf-result-index",String(s));break}},zt=n=>{if(!(n instanceof HTMLElement))return null;let s=window.getComputedStyle(n).overflowY;return s!=="visible"&&s!=="hidden"?n:zt(n.parentNode)},Dt=class{constructor(s){this.result=null;this.loading=!1;this.observer=null;this.rawResult=s.result,this.index=s.index,this.placeholderNodes=s.placeholderNodes,this.resultFn=s.resultFn,this.intersectionEl=s.intersectionEl,this.showImages=s.showImages,this.showSubResults=s.showSubResults,this.maxSubResults=s.maxSubResults,this.linkTarget=s.linkTarget,this.onLoad=s.onLoad,this.setupObserver()}setupObserver(){if(this.result!==null||this.observer!==null||!this.placeholderNodes?.length)return;let s={root:this.intersectionEl,rootMargin:"50px",threshold:.01};this.observer=new IntersectionObserver((e,t)=>{this.result===null&&e?.[0]?.isIntersecting&&(this.load(),t.disconnect(),this.observer=null)},s),this.observer.observe(this.placeholderNodes[0])}async load(){if(this.placeholderNodes?.length&&!(this.result!==null||this.loading)){this.loading=!0;try{this.result=await this.rawResult.data();let s=this.resultFn(this.result,{showImages:this.showImages,showSubResults:this.showSubResults,maxSubResults:this.maxSubResults,linkTarget:this.linkTarget}),e=ss(s);for(rs(e,this.index);this.placeholderNodes.length>1;){let r=this.placeholderNodes.pop();r instanceof Element&&r.remove()}let t=this.placeholderNodes[0];t instanceof Element&&t.replaceWith(...e)}catch{this.loading=!1}this.onLoad?.()}}cleanup(){this.observer&&(this.observer.disconnect(),this.observer=null)}},Se=class extends f{constructor(){super();this.containerEl=null;this.intersectionEl=document.body;this.results=[];this.showImages=!1;this.hideSubResults=!1;this.maxSubResults=3;this.maxResults=0;this.linkTarget=null;this.resultTemplate=null;this.compiledResultTemplate=null;this.compiledPlaceholderTemplate=null;this.selectedIndex=-1;this.selectedAnchor=null;this.loadingAnnouncementTimeout=null}static get observedAttributes(){return["show-images","hide-sub-results","max-sub-results","max-results","link-target"]}init(){this.hasAttribute("show-images")&&(this.showImages=this.getAttribute("show-images")!=="false"),this.hasAttribute("hide-sub-results")&&(this.hideSubResults=this.getAttribute("hide-sub-results")!=="false"),this.hasAttribute("max-sub-results")&&(this.maxSubResults=parseInt(this.getAttribute("max-sub-results")||"3",10)||3),this.hasAttribute("max-results")&&(this.maxResults=parseInt(this.getAttribute("max-results")||"0",10)),this.hasAttribute("link-target")&&(this.linkTarget=this.getAttribute("link-target")),this.checkForTemplates(),this.render()}checkForTemplates(){let e=this.querySelector('script[type="text/pagefind-template"]:not([data-template]), script[type="text/pagefind-template"][data-template="result"]');e&&(this.compiledResultTemplate=R((e.textContent||"").trim()));let t=this.querySelector('script[type="text/pagefind-template"][data-template="placeholder"]');t&&(this.compiledPlaceholderTemplate=R((t.textContent||"").trim()))}buildTemplateData(e,t){let r=t.showSubResults?this.instance.getDisplaySubResults(e,t.maxSubResults):[];return{meta:e.meta||{},excerpt:e.excerpt||"",url:e.url||"",sub_results:r.map(i=>({title:i.title,url:i.url,excerpt:i.excerpt})),options:{link_target:t.linkTarget,show_images:t.showImages}}}getResultRenderer(){if(this.resultTemplate){let e=this.resultTemplate;return(t,r)=>e(t)}if(this.compiledResultTemplate){let e=this.compiledResultTemplate;return(t,r)=>{let i=this.buildTemplateData(t,r);return e(i)}}return(e,t)=>{let r=this.buildTemplateData(e,t);return Ca(r)}}getPlaceholder(){return this.compiledPlaceholderTemplate?this.compiledPlaceholderTemplate({}):ya({})}render(){let e=[];this.querySelectorAll('script[type="text/pagefind-template"]').forEach(r=>{e.push(r)}),this.innerHTML="",e.forEach(r=>this.appendChild(r));let t=this.instance?.translate("results_label")||"Search results";this.instance?.direction==="rtl"?this.setAttribute("dir","rtl"):this.removeAttribute("dir"),this.containerEl=document.createElement("ul"),this.containerEl.className="pf-results",this.containerEl.setAttribute("aria-label",t),this.containerEl.setAttribute("aria-busy","false"),this.appendChild(this.containerEl),this.setupKeyboardHandlers()}appendResults(e){if(this.containerEl)for(let t of e)this.containerEl.appendChild(t)}register(e){e.registerResults(this,{keyboardNavigation:!0,announcements:!0}),e.on("results",t=>{if(!this.containerEl)return;let r=t;for(let c of this.results)c.cleanup();this.containerEl.innerHTML="",this.containerEl.setAttribute("aria-busy","false"),this.intersectionEl=zt(this.containerEl),this.selectedIndex=-1,this.selectedAnchor=null;let i=this.maxResults>0?r.results.slice(0,this.maxResults):r.results,a=i.length,l=e.searchTerm;if(l){let c=a===0?"zero_results":a===1?"one_result":"many_results",u=a===0?"assertive":"polite";e.announce(c,{SEARCH_TERM:l,COUNT:a},u)}elLine truncated
|
||||
<p class="pf-searchbox-result-title" id="{{ aria.title_id }}">{{ meta.title | default("Untitled") }}</p>
|
||||
{{#if excerpt}}
|
||||
<p class="pf-searchbox-result-excerpt" id="{{ aria.excerpt_id }}">{{+ excerpt +}}</p>
|
||||
{{/if}}
|
||||
</a>{{#if and(options.show_sub_results, sub_results)}}
|
||||
{{#each sub_results as sub}}
|
||||
<a class="pf-searchbox-result pf-searchbox-subresult" id="{{ sub.aria.result_id }}" href="{{ sub.url | safeUrl }}" role="option" aria-selected="false" aria-labelledby="{{ sub.aria.title_id }}"{{#if sub.excerpt}} aria-describedby="{{ sub.aria.excerpt_id }}"{{/if}}>
|
||||
<p class="pf-searchbox-result-title" id="{{ sub.aria.title_id }}">{{ sub.title | default("Section") }}</p>
|
||||
{{#if sub.excerpt}}
|
||||
<p class="pf-searchbox-result-excerpt" id="{{ sub.aria.excerpt_id }}">{{+ sub.excerpt +}}</p>
|
||||
{{/if}}
|
||||
</a>
|
||||
{{/each}}
|
||||
</div>{{/if}}`,ns=R(Ra),ka=`<div class="pf-searchbox-result pf-searchbox-placeholder" aria-hidden="true">
|
||||
<p class="pf-searchbox-result-title pf-skeleton pf-skeleton-title"></p>
|
||||
<p class="pf-searchbox-result-excerpt pf-skeleton pf-skeleton-excerpt"></p>
|
||||
</div>`,Aa=R(ka),jt=class{constructor(s){this.data=null;this.cachedOptions=null;this.loading=!1;this.retryDelay=0;this.observer=null;this.rawResult=s.rawResult,this.placeholderEl=s.placeholderEl,this.renderFn=s.renderFn,this.intersectionRoot=s.intersectionRoot,this.index=s.index,this.onLoad=s.onLoad,this.setupObserver()}setupObserver(){if(this.data!==null||this.observer!==null)return;let s={root:this.intersectionRoot,rootMargin:"50px",threshold:.01};this.observer=new IntersectionObserver((e,t)=>{this.data===null&&e?.[0]?.isIntersecting&&(this.load(),t.disconnect(),this.observer=null)},s),this.observer.observe(this.placeholderEl)}async load(){if(!(this.data!==null||this.loading)){this.loading=!0;try{this.data=await this.rawResult.data();let s=this.renderFn(this.data),e=Ke(s);if(e.length>0&&this.placeholderEl.parentNode){let t=e.find(r=>r instanceof Element);this.placeholderEl.replaceWith(...e),t instanceof Element&&(this.placeholderEl=t,as(t,this.index),this.cacheOptions())}}catch{await new Promise(s=>setTimeout(s,this.retryDelay||100)),this.retryDelay=Math.min((this.retryDelay||100)*2,1e4),this.loading=!1}this.onLoad?.()}}cacheOptions(){if(!this.data||!this.placeholderEl){this.cachedOptions=null;return}this.placeholderEl.getAttribute("role")==="group"?this.cachedOptions=Array.from(this.placeholderEl.querySelectorAll('[role="option"]')):this.placeholderEl.getAttribute("role")==="option"?this.cachedOptions=[this.placeholderEl]:this.cachedOptions=[]}cleanup(){this.observer&&(this.observer.disconnect(),this.observer=null),this.cachedOptions=null}},Fe=class extends f{constructor(){super();this.containerEl=null;this.inputEl=null;this.dropdownEl=null;this.resultsEl=null;this.statusEl=null;this.footerEl=null;this.isOpen=!1;this.isLoading=!1;this.results=[];this.activeIndex=-1;this.activeOptionOffset=0;this.searchID=0;this.searchTerm="";this.pendingNavigation=0;this.loadingAnnouncementTimeout=null;this.selectedEl=null;this._userPlaceholder=null;this.debounce=150;this.autofocus=!1;this.showSubResults=!1;this.maxResults=0;this.showKeyboardHints=!0;this.shortcut="mod+k";this.hideShortcut=!1;this.resultTemplate=null;this.compiledResultTemplate=null;this.compiledPlaceholderTemplate=null;this._documentClickHandler=null;this._shortcutKeyHandler=null;this._keyBinding=null;this._shortcutEl=null}static get observedAttributes(){return["placeholder","debounce","autofocus","show-sub-results","max-results","show-keyboard-hints","shortcut","hide-shortcut"]}get placeholder(){return this._userPlaceholder||this.instance?.translate("placeholder")||"Search..."}readAttributes(){this.hasAttribute("placeholder")&&(this._userPlaceholder=this.getAttribute("placeholder")),this.hasAttribute("debounce")&&(this.debounce=parseInt(this.getAttribute("debounce")||"150",10)||150),this.hasAttribute("autofocus")&&(this.autofocus=this.hasAttribute("autofocus")),this.hasAttribute("show-sub-results")&&(this.showSubResults=this.getAttribute("show-sub-results")!=="false"),this.hasAttribute("max-results")&&(this.maxResults=parseInt(this.getAttribute("max-results")||"0",10)),this.hasAttribute("show-keyboard-hints")&&(this.showKeyboardHints=this.getAttribute("show-keyboard-hints")!=="false"),this.hasAttribute("shortcut")&&(this.shortcut=this.getAttribute("shortcut")||"mod+k"),this.hasAttribute("hide-shortcut")&&(this.hideShortcut=this.getAttribute("hide-shortcut")!=="false"),this._keyBinding=je(this.shortcut)}init(){this.readAttributes(),this.checkForTemplates(),this.render(),this.setupOutsideClickHandler(),this.setupShortcutHandler()}checkForTemplates(){let e=this.querySelector('script[type="text/pagefind-template"]:not([data-template]), script[type="text/pagefind-template"][data-template="result"]');e&&(this.compiledResultTemplate=R((e.textContent||"").trim()));let t=this.querySelector('script[type="text/pagefind-template"][data-template="placeholder"]');t&&(this.compiledPlaceholderTemplate=R((t.textContent||"").trim()))}getPlaceholder(){return this.compiledPlaceholderTemplate?this.compiledPlaceholderTemplate({}):Aa({})}render(){let e=[];this.querySelectorAll('script[type="text/pagefind-template"]').forEach(l=>{e.push(l)}),this.innerHTML="",e.forEach(l=>this.appendChild(l));let t=this.instance.generateId("pf-sb-input"),r=this.instance.generateId("pf-sb-results");this.containerEl=document.createElement("div"),this.containerEl.className="pf-searchbox",this.appendChild(this.containerEl);let i=document.createElement("div");if(i.className="pf-searchbox-input-wrapper",this.containerEl.appendChild(i),this.inputEl=document.createElement("input"),this.inputEl.id=t,this.inputEl.className="pf-searchbox-input",this.inputEl.type="text",this.inputEl.setAttribute("role","combobox"),this.inputEl.setAttribute("aria-autocomplete","list"),this.inputEl.setAttribute("aria-controls",r),this.inputEl.setAttribute("aria-expanded","false"),this.inputEl.setAttribute("autocomplete","off"),this.inputEl.setAttribute("autocapitalize","none"),this.inputEl.placeholder=this.placeholder,thiLine truncated
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_c7941c6d99","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
+1070
File diff suppressed because it is too large.
Load diff
+214
@@ -0,0 +1,214 @@
|
||||
:root {
|
||||
--pagefind-ui-scale: 0.8;
|
||||
--pagefind-ui-primary: #034AD8;
|
||||
--pagefind-ui-fade: #707070;
|
||||
--pagefind-ui-text: #393939;
|
||||
--pagefind-ui-background: #ffffff;
|
||||
--pagefind-ui-border: #eeeeee;
|
||||
--pagefind-ui-tag: #eeeeee;
|
||||
--pagefind-ui-border-width: 2px;
|
||||
--pagefind-ui-border-radius: 8px;
|
||||
--pagefind-ui-image-border-radius: 8px;
|
||||
--pagefind-ui-image-box-ratio: 3 / 2;
|
||||
--pagefind-ui-font: system, -apple-system, ".SFNSText-Regular",
|
||||
"San Francisco", "Roboto", "Segoe UI", "Helvetica Neue",
|
||||
"Lucida Grande", sans-serif;
|
||||
}
|
||||
|
||||
[data-pfmod-hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
[data-pfmod-suppressed] {
|
||||
opacity: 0 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
[data-pfmod-sr-hidden] {
|
||||
-webkit-clip: rect(0 0 0 0) !important;
|
||||
clip: rect(0 0 0 0) !important;
|
||||
-webkit-clip-path: inset(100%) !important;
|
||||
clip-path: inset(100%) !important;
|
||||
height: 1px !important;
|
||||
overflow: hidden !important;
|
||||
overflow: clip !important;
|
||||
position: absolute !important;
|
||||
white-space: nowrap !important;
|
||||
width: 1px !important;
|
||||
}
|
||||
|
||||
[data-pfmod-loading] {
|
||||
color: var(--pagefind-ui-text);
|
||||
background-color: var(--pagefind-ui-text);
|
||||
border-radius: var(--pagefind-ui-border-radius);
|
||||
opacity: 0.1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Input */
|
||||
|
||||
.pagefind-modular-input-wrapper {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.pagefind-modular-input-wrapper::before {
|
||||
background-color: var(--pagefind-ui-text);
|
||||
width: calc(18px * var(--pagefind-ui-scale));
|
||||
height: calc(18px * var(--pagefind-ui-scale));
|
||||
top: calc(23px * var(--pagefind-ui-scale));
|
||||
left: calc(20px * var(--pagefind-ui-scale));
|
||||
content: "";
|
||||
position: absolute;
|
||||
display: block;
|
||||
opacity: 0.7;
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12.7549 11.255H11.9649L11.6849 10.985C12.6649 9.845 13.2549 8.365 13.2549 6.755C13.2549 3.165 10.3449 0.255005 6.75488 0.255005C3.16488 0.255005 0.254883 3.165 0.254883 6.755C0.254883 10.345 3.16488 13.255 6.75488 13.255C8.36488 13.255 9.84488 12.665 10.9849 11.685L11.2549 11.965V12.755L16.2549 17.745L17.7449 16.255L12.7549 11.255ZM6.75488 11.255C4.26488 11.255 2.25488 9.245 2.25488 6.755C2.25488 4.26501 4.26488 2.255 6.75488 2.255C9.24488 2.255 11.2549 4.26501 11.2549 6.755C11.2549 9.245 9.24488 11.255 6.75488 11.255Z' fill='%23000000'/%3E%3C/svg%3E%0A");
|
||||
mask-image: url("data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12.7549 11.255H11.9649L11.6849 10.985C12.6649 9.845 13.2549 8.365 13.2549 6.755C13.2549 3.165 10.3449 0.255005 6.75488 0.255005C3.16488 0.255005 0.254883 3.165 0.254883 6.755C0.254883 10.345 3.16488 13.255 6.75488 13.255C8.36488 13.255 9.84488 12.665 10.9849 11.685L11.2549 11.965V12.755L16.2549 17.745L17.7449 16.255L12.7549 11.255ZM6.75488 11.255C4.26488 11.255 2.25488 9.245 2.25488 6.755C2.25488 4.26501 4.26488 2.255 6.75488 2.255C9.24488 2.255 11.2549 4.26501 11.2549 6.755C11.2549 9.245 9.24488 11.255 6.75488 11.255Z' fill='%23000000'/%3E%3C/svg%3E%0A");
|
||||
-webkit-mask-size: 100%;
|
||||
mask-size: 100%;
|
||||
z-index: 9;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pagefind-modular-input {
|
||||
height: calc(64px * var(--pagefind-ui-scale));
|
||||
padding: 0 calc(70px * var(--pagefind-ui-scale)) 0 calc(54px * var(--pagefind-ui-scale));
|
||||
background-color: var(--pagefind-ui-background);
|
||||
border: var(--pagefind-ui-border-width) solid var(--pagefind-ui-border);
|
||||
border-radius: var(--pagefind-ui-border-radius);
|
||||
font-size: calc(21px * var(--pagefind-ui-scale));
|
||||
position: relative;
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
display: flex;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.pagefind-modular-input::placeholder {
|
||||
opacity: 0.2;
|
||||
}
|
||||
|
||||
.pagefind-modular-input-clear {
|
||||
position: absolute;
|
||||
top: calc(2px * var(--pagefind-ui-scale));
|
||||
right: calc(2px * var(--pagefind-ui-scale));
|
||||
height: calc(60px * var(--pagefind-ui-scale));
|
||||
border-radius: var(--pagefind-ui-border-radius);
|
||||
padding: 0 calc(15px * var(--pagefind-ui-scale)) 0 calc(2px * var(--pagefind-ui-scale));
|
||||
color: var(--pagefind-ui-text);
|
||||
font-size: calc(14px * var(--pagefind-ui-scale));
|
||||
cursor: pointer;
|
||||
background-color: var(--pagefind-ui-background);
|
||||
border: none;
|
||||
appearance: none;
|
||||
}
|
||||
|
||||
/* ResultList */
|
||||
|
||||
.pagefind-modular-list-result {
|
||||
list-style-type: none;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: min(calc(40px * var(--pagefind-ui-scale)), 3%);
|
||||
padding: calc(30px * var(--pagefind-ui-scale)) 0 calc(40px * var(--pagefind-ui-scale));
|
||||
border-top: solid var(--pagefind-ui-border-width) var(--pagefind-ui-border);
|
||||
}
|
||||
|
||||
.pagefind-modular-list-result:last-of-type {
|
||||
border-bottom: solid var(--pagefind-ui-border-width) var(--pagefind-ui-border);
|
||||
}
|
||||
|
||||
.pagefind-modular-list-thumb {
|
||||
width: min(30%,
|
||||
calc((30% - (100px * var(--pagefind-ui-scale))) * 100000));
|
||||
max-width: calc(120px * var(--pagefind-ui-scale));
|
||||
margin-top: calc(10px * var(--pagefind-ui-scale));
|
||||
aspect-ratio: var(--pagefind-ui-image-box-ratio);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.pagefind-modular-list-image {
|
||||
display: block;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
font-size: 0;
|
||||
width: auto;
|
||||
height: auto;
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
border-radius: var(--pagefind-ui-image-border-radius);
|
||||
}
|
||||
|
||||
.pagefind-modular-list-inner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
margin-top: calc(10px * var(--pagefind-ui-scale));
|
||||
}
|
||||
|
||||
.pagefind-modular-list-title {
|
||||
display: inline-block;
|
||||
font-weight: 700;
|
||||
font-size: calc(21px * var(--pagefind-ui-scale));
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.pagefind-modular-list-link {
|
||||
color: var(--pagefind-ui-text);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.pagefind-modular-list-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.pagefind-modular-list-excerpt {
|
||||
display: inline-block;
|
||||
font-weight: 400;
|
||||
font-size: calc(16px * var(--pagefind-ui-scale));
|
||||
margin-top: calc(4px * var(--pagefind-ui-scale));
|
||||
margin-bottom: 0;
|
||||
min-width: calc(250px * var(--pagefind-ui-scale));
|
||||
}
|
||||
|
||||
/* FilterPills */
|
||||
|
||||
.pagefind-modular-filter-pills-wrapper {
|
||||
overflow-x: scroll;
|
||||
padding: 15px 0;
|
||||
}
|
||||
|
||||
.pagefind-modular-filter-pills {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.pagefind-modular-filter-pill {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
border: none;
|
||||
appearance: none;
|
||||
padding: 0 calc(24px * var(--pagefind-ui-scale));
|
||||
background-color: var(--pagefind-ui-background);
|
||||
color: var(--pagefind-ui-fade);
|
||||
border: var(--pagefind-ui-border-width) solid var(--pagefind-ui-border);
|
||||
border-radius: calc(25px * var(--pagefind-ui-scale));
|
||||
font-size: calc(18px * var(--pagefind-ui-scale));
|
||||
height: calc(50px * var(--pagefind-ui-scale));
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pagefind-modular-filter-pill:hover {
|
||||
border-color: var(--pagefind-ui-primary);
|
||||
}
|
||||
|
||||
.pagefind-modular-filter-pill[aria-pressed="true"] {
|
||||
border-color: var(--pagefind-ui-primary);
|
||||
color: var(--pagefind-ui-primary);
|
||||
}
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user