Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63bbc23e37 | ||
|
|
a0ae5e5fa8 | ||
|
|
965c4ee25a | ||
|
|
999edd0203 | ||
|
|
1c6ed7e70d | ||
|
|
ef9ce984b7 | ||
|
|
40a7b478c5 | ||
|
|
5461179e18 | ||
|
|
bff31bb80f | ||
|
|
ee0faa2e18 | ||
|
|
15c78c1c32 | ||
|
|
132f6e9186 | ||
|
|
d1821ff859 | ||
|
|
3d0a0af893 | ||
|
|
eb87a555b3 | ||
|
|
b57ae35be4 | ||
|
|
96425f6cb9 | ||
|
|
de6f04bf7d | ||
|
|
b96827c51d | ||
|
|
a426c4dbfe | ||
|
|
9b93f33ae3 | ||
|
|
35f0b8d371 | ||
|
|
159f6a0bd8 | ||
|
|
a045cd7649 | ||
|
|
f3af34980a | ||
|
|
c2f107444c | ||
|
|
baf0bf16f0 | ||
|
|
81df63d942 | ||
|
|
a0c290ccc2 | ||
|
|
58112d4d3b | ||
|
|
51869c8bf4 | ||
|
|
5051bbdf15 | ||
|
|
29096cbbac | ||
|
|
c40e720518 | ||
|
|
4e62a14af6 | ||
|
|
cbb80e884f | ||
|
|
3ee1c558b3 | ||
|
|
fae939119a | ||
|
|
2734885f2b | ||
|
|
53bc293c37 | ||
|
|
bce167c052 | ||
|
|
dd4aa498bb | ||
|
|
7d637323a5 | ||
|
|
df85fd3b54 | ||
|
|
bbf87976a1 | ||
|
|
2a2334ef5a |
No files matched your search
@@ -43,7 +43,12 @@ jobs:
|
||||
run: tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"
|
||||
- name: Extract the release notes from CHANGELOG.md
|
||||
run: tools/release_notes.sh "${GITHUB_REF_NAME#v}" > dist/RELEASE_NOTES.md
|
||||
# LUCISV_API_URL is an optional repository Actions variable naming a
|
||||
# direct http://host:port for the Gitea API, so the uploads do not go
|
||||
# through Cloudflare's 100-second origin timeout (0.29.0 and 0.30.0
|
||||
# both died there with a 524). Unset, the public URL is used.
|
||||
- name: Create the release and attach the artifacts
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
LUCISV_API_URL: ${{ vars.LUCISV_API_URL }}
|
||||
run: tools/publish_release.sh "$GITHUB_REF_NAME" dist
|
||||
+421
@@ -4,6 +4,427 @@ 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.35.0 — 2026-09-02
|
||||
|
||||
### Format fences reach statements and class bodies
|
||||
|
||||
`// verilog_format: off` / `// lucisv: off` (and the `lucisv:` spelling)
|
||||
now protect statements inside `begin … end`, `fork … join`, function
|
||||
and task bodies and `always`/`initial`/`final` blocks, and items inside
|
||||
a class body — not only items at module scope. A fenced region is
|
||||
copied byte for byte, keeps its own indentation, and is a fixed point
|
||||
under a second pass; an unmatched `off` runs to the end of its own
|
||||
list. `--lines` range formatting honours a fenced statement inside the
|
||||
selected range. Four opentitan files that already carried fences inside
|
||||
functions and class bodies now keep those bytes.
|
||||
|
||||
One rule is applied uniformly: a fence must start its line (whitespace
|
||||
or a finished block comment may precede it). A fence written after code
|
||||
on the same line — `module m; // lucisv: off` — is an ordinary comment,
|
||||
as the fence documentation has said since the feature shipped; it used
|
||||
to open a region at module scope by accident.
|
||||
|
||||
Not yet fenceable, with reasons in the feature README: port lists,
|
||||
case-item label lists, same-line fences, and a property's local
|
||||
declarations.
|
||||
|
||||
## 0.34.0 — 2026-09-02
|
||||
|
||||
### Rename tells you what it could not reach
|
||||
|
||||
- **Macro arguments are named.** A rename now lists every file where the
|
||||
old name appears inside a macro invocation that the rename did not
|
||||
read (`` `uvm_info(..., $sformatf("%0d", sig)) `` in a file with no
|
||||
other relationship to the name), one warning per file, so nothing is
|
||||
silently left behind. Answered from a new per-file census in the
|
||||
index without reading any file (under a millisecond on opentitan).
|
||||
- The index store format changed (`FACTS_FORMAT` 17); it rebuilds once.
|
||||
|
||||
### Grammar
|
||||
|
||||
- **Modport method prototypes** (`modport mp (import task drive(int x),
|
||||
input clk);`) parse, format and resolve: hover on the prototype's
|
||||
name lands on the interface's task.
|
||||
- **Unnamed DPI formals** (`import "DPI-C" function int f(int, chandle);`)
|
||||
parse and format; an unnamed formal anywhere else is still an error.
|
||||
- `const /*c*/ ref` keeps its comment.
|
||||
|
||||
### CLI
|
||||
|
||||
- `lucisv check --rules-doc` prints the generated rule reference.
|
||||
|
||||
### Internal
|
||||
|
||||
- Every file over 1 200 lines was decomposed (parser, formatter, server,
|
||||
semantic and refactor crates) as pure moves with byte-identical
|
||||
output; `vlog_refactor`'s `Scope` moved to the crate root.
|
||||
|
||||
## 0.33.0 — 2026-09-02
|
||||
|
||||
### Assertions are code now
|
||||
|
||||
`property`/`sequence` declarations and concurrent assertions (`assert`,
|
||||
`assume`, `cover`, `restrict property`, `expect`, `cover sequence`,
|
||||
`default disable iff`) were verbatim text: kept byte for byte, invisible
|
||||
to everything else. They are real nodes now — every sequence and
|
||||
property operator (`##`, `[*n]`, `|->`, `|=>`, `throughout`, `within`,
|
||||
`intersect`, `until`, `implies`, `iff`, `nexttime`, `always`,
|
||||
`eventually`, `first_match`, `accept_on`…, property `if`/`case`, typed
|
||||
formals, local variables, match items) with the LRM's precedence, no
|
||||
new reserved words, and a byte-exact fallback for anything the grammar
|
||||
cannot take (it fires on none of 4 792 corpus and opentitan files).
|
||||
|
||||
- **Rename and references see inside assertions.** A signal named only
|
||||
in a property is renamed with its declaration; a property's formal is
|
||||
scoped to the property. Anything that still falls back warns instead
|
||||
of staying silent.
|
||||
- **Formatting**: one rule — the spec's top-level `|->`/`|=>`/`##`/
|
||||
`and`/`or` break one per line when the spec does not fit; everything
|
||||
else inline. 13 corpus and 36 opentitan files move, all inside
|
||||
assertion text; every `` `ASSERT* `` macro invocation is
|
||||
byte-identical.
|
||||
- Properties and sequences appear in document symbols; `undriven-net`
|
||||
sees a net driven or read inside an assertion.
|
||||
- The index store format changed; it rebuilds once after updating.
|
||||
|
||||
## 0.32.0 — 2026-09-02
|
||||
|
||||
### `bind` directives mean something now
|
||||
|
||||
- **Bind targets are real.** `bind top.gen[0].u_core chk u_chk (.clk(clk));`
|
||||
parses and formats with its indexed path; a lone target
|
||||
(`bind prim_fifo_sync …`) is a reference to the module, so go-to-
|
||||
definition and hover work on it. An instance path records nothing —
|
||||
no file knows an elaborated hierarchy, and a guess would be wrong.
|
||||
- **Bind connections resolve where the LRM says they live**: the
|
||||
`.port` half against the module being bound in, the expression half
|
||||
in the *target* module's scope first (then the workspace, then the
|
||||
scope the directive is written in). Hover on `.x(top_sig)` in a bind
|
||||
finds `top_sig` in the target.
|
||||
- The index store format changed (`FACTS_FORMAT` 15); it rebuilds once.
|
||||
|
||||
### Two macro-and-directive shapes that used to leave a file unformattable
|
||||
|
||||
- **A spaced macro call in an expression** — `assign x = \`WIDTH (a + b);`,
|
||||
a parameter override `` `MACRO (1) `` — keeps the author's space
|
||||
between the macro name and its `(`. The gap is token text (a macro
|
||||
defined with formals reads it differently), so the formatter keeps
|
||||
it rather than guessing; the safety net still refuses either
|
||||
rewrite.
|
||||
- **A conditional directive inside a connection value** — `.a(` ⏎
|
||||
`` `ifdef X `` ⏎ … ⏎ `` `endif `` ⏎ `)` — no longer turns the whole
|
||||
instantiation into opaque bytes: the directive region is kept
|
||||
byte-for-byte as a verbatim value, and the instantiation keeps its
|
||||
edge, code lens, hierarchy entry and port references. In opentitan
|
||||
the two `padring` instantiations in `chip_earlgrey_{asic,cw340}.sv`
|
||||
lay out canonically and gain their edges; the `` `ifdef `` that
|
||||
splits two instantiation *heads* (`tb.sv`) stays as it was.
|
||||
|
||||
### Editor
|
||||
|
||||
- **`lucisv.instantiate`** — an execute command
|
||||
(`[uri, position, module]`) that inserts the same instantiation
|
||||
skeleton the inline ghost offers, as plain text through
|
||||
`workspace/applyEdit`. For clients without inline completion; the
|
||||
Neovim README shows the keymap.
|
||||
|
||||
## 0.31.0 — 2026-09-02
|
||||
|
||||
### Comments are never dropped — now at every gap
|
||||
|
||||
A comment written between two tokens that no AST node owned was never
|
||||
deleted, but it was printed one node later, and the safety net refused
|
||||
the whole file for it (exit 2, no output). Three rounds had filed their
|
||||
leftovers (52 covergroup gaps, 41 fragment gaps, 40 constraint gaps) and
|
||||
plain RTL had never been measured. This release gives every such gap an
|
||||
owner: about seventy named comment slots across expressions (`q[/*c*/ i]`,
|
||||
`pkg /*c*/ ::name`, `x /*c*/ inside {…}`, casts, unary/postfix operators),
|
||||
statements (`if`/`case`/`for`/`foreach`/`do…while` headers, `@`/`#`
|
||||
timing, the gap before every `;`, block and generate labels) and
|
||||
declarations (qualifier runs like `pure /*c*/ static`, function/task
|
||||
headers and ports, module/package/class headers, typedefs, enums,
|
||||
structs, declarators, port lists, connections, instantiations).
|
||||
|
||||
Four exhaustive gap fuzzers — a `/*C*/` in every inter-token gap of
|
||||
fixture sets for covergroups (329 gaps), fragments (153), constraints
|
||||
(395) and ordinary RTL (352) — all format and re-format identically, and
|
||||
are the regression gate from here on. The formatter's output for every
|
||||
comment-free construct is unchanged: all 860 corpus files and 3 975
|
||||
opentitan files are byte-identical to 0.30.0. `verify.rs` is untouched;
|
||||
ten new attack pairs assert a comment moved across any newly slotted
|
||||
token is still refused.
|
||||
|
||||
- **Escaped names inside scoped names** (`\my-pkg ::\state-t` as a
|
||||
type, an instantiated module, a `bind` target) now keep their
|
||||
terminating space instead of being refused.
|
||||
|
||||
### Editor
|
||||
|
||||
- **Go to definition on a macro use** (`` `WIDTH ``, `` `uvm_info ``)
|
||||
jumps to the `` `define`` — the file's own definition first, otherwise
|
||||
every workspace candidate the include graph cannot rule out; nothing
|
||||
for a macro nothing defines.
|
||||
- **A cast's type is a reference.** `state_t'(0)` and `pkg::t'(x)` now
|
||||
light up find-all-references, go-to-type-definition and rename of
|
||||
the typedef (`FACTS_FORMAT` 13 → 14: the index rebuilds once).
|
||||
- **Rename warns about what it could not finish.** A `u_x.sig` whose
|
||||
module is indexed nowhere is left unchanged and now *named* — one
|
||||
line per file and unit — instead of silently skipped.
|
||||
|
||||
## 0.30.0 — 2026-09-02
|
||||
|
||||
Two lanes, run in parallel: semantic lints on by default, and the
|
||||
vendor/formal collateral grammar.
|
||||
|
||||
### Semantic lints on by default
|
||||
|
||||
`unused-signal`, `undriven-net` and `multiply-driven` shipped off
|
||||
because a per-file analysis cannot see a signal read or driven from
|
||||
another file's hierarchy. The index now carries a per-file identifier
|
||||
census (`FileFacts::words`, `FACTS_FORMAT` 12 → 13 — one harvest,
|
||||
which also builds the completion word table so the server no longer
|
||||
re-lexes every file at startup: scan time −28 %), and the linter gains
|
||||
a mention oracle: `unused-signal` and `undriven-net` say nothing when
|
||||
the name is mentioned in any other indexed file. The three rules are
|
||||
on whenever an oracle exists — always in the editor, and in the CLI
|
||||
when it walks a project — and stay off for a single file or stdin.
|
||||
With them came the missing off switch: `[lint] select = […]` /
|
||||
`ignore = […]` in `lucisv.toml` (CLI flags win key by key) and
|
||||
`lucisv.lint.select` / `lucisv.lint.ignore` in the editor.
|
||||
|
||||
Measured: corpus `unused-signal` 52 → 44 and `undriven-net` 3 → 0 with
|
||||
every silencing hand-checked as a genuine cross-file use, nothing
|
||||
added; across opentitan — lint-clean under its own tools — 14
|
||||
findings, spot-checked true. Store +14 %.
|
||||
|
||||
### Vendor and formal collateral grammar
|
||||
|
||||
The gap analysis ranked `specify`/UDP/`checker`/`interface class` as
|
||||
Medium on the strength of "13 corpus checker files"; the round's
|
||||
census found those were UVM protocol-checker *filenames*, and that
|
||||
every construct here has zero declarations in the corpus and in
|
||||
opentitan. So this is a completeness round for vendored cell, IO and
|
||||
memory models and formal collateral — and it is proven
|
||||
output-neutral: formatted output is byte-identical for all 860 corpus
|
||||
files and all 3 975 opentitan files against the previous release.
|
||||
|
||||
Five keywords reserved on a measured zero-collision census
|
||||
(`checker`, `endchecker`, `config`, `endconfig`, `library`); five
|
||||
deliberately not (`expect` has 41 real task-call sites — the statement
|
||||
form is recognised only when its parentheses hold a sequence operator).
|
||||
`specify … endspecify`, `primitive … endprimitive` with `table`,
|
||||
`checker … endchecker` and `config … endconfig` parse as opaque blocks
|
||||
that format byte-for-byte and fold in the editor; `library …;` lines
|
||||
parse; `specparam` is a real declaration that hovers and resolves;
|
||||
`alias a = b = c;` parses with every term a reference; `union tagged`
|
||||
formats; `interface class … endclass` parses as a class and
|
||||
`implements` now contributes supertypes to the type hierarchy. Filed:
|
||||
the `tagged` pattern grammar, checker/UDP names as instantiable
|
||||
symbols, the reverse `implements` edge.
|
||||
|
||||
## 0.29.0 — 2026-09-02
|
||||
|
||||
Fragment mode, and `` `define`` continuation.
|
||||
|
||||
The gap analysis had this one wrong in an interesting way: class-body
|
||||
and module-item `` `include`` fragments already parsed, because the
|
||||
file-scope item loop *is* the class-item loop. What did not parse were
|
||||
three narrower shapes — a bare statement list, an enum-member list
|
||||
(riscv-dv's `CUSTOM_1,` file, included between enum members), a
|
||||
covergroup-item list — and all three failed at one call site. They are
|
||||
now `SourceFile::fragment`, detected by a whole-file rule that cannot
|
||||
misfire on a valid file: the first structural item failed (directives,
|
||||
macros and stray `;` do not count, and a tolerant parse that quietly
|
||||
recorded a diagnostic counts as failed — an existing parity test
|
||||
caught `if … else` reading as a generate-if to one parser and a
|
||||
statement to the other), the file does not open with a design-unit
|
||||
keyword, and a shape consumes the file to its end, tried
|
||||
narrowest-first because the wider grammars mis-read the narrower. A
|
||||
fragment formats at indent zero through the existing printers, its
|
||||
declarations bind, and its enum variants are deliberately *not*
|
||||
exported (a package that includes the fragment is the real home of
|
||||
`CUSTOM_1`; resolving it elsewhere would name something that does not
|
||||
exist).
|
||||
|
||||
The other opentitan `.svh` that would not parse was never a fragment
|
||||
problem: a `` `define`` whose formal-argument list spans two lines with
|
||||
no backslash, which every tool accepts. The lexer now continues such a
|
||||
directive until the list closes.
|
||||
|
||||
Opentitan: 12 → 10 failing files, exactly the two predicted, nothing
|
||||
else moved. Corpus baseline 813 → 814 of 820. Comment-gap fuzzer:
|
||||
every remaining failing slot proven to fail identically outside a
|
||||
fragment (§2.9-22). Formatter output unchanged for every file that
|
||||
parsed before.
|
||||
|
||||
## 0.28.0 — 2026-09-02
|
||||
|
||||
Covergroup bodies — round 2 of coverage_gaps C1, closing it.
|
||||
|
||||
`covergroup … endgroup` was a flat token scan into verbatim text: no
|
||||
name span, no coverpoint names, nothing inside bound. Now a covergroup
|
||||
is a real node — the header with its argument list, `with function
|
||||
sample(…)` and `@(…)` event, labelled and unlabelled coverpoints,
|
||||
`bins`/`ignore_bins`/`illegal_bins` with arrays, value lists, `$`,
|
||||
transition lists (`=>`, `[*n]`, `[->n]`, `[=n]`), `default` and
|
||||
`default sequence`, `with (…)` filters, `wildcard`, `iff`, crosses with
|
||||
`binsof … intersect … && !binsof` select expressions, `option.`/
|
||||
`type_option.` assignments, `` `ifdef `` arms, and the `endgroup : g`
|
||||
label — behind the same rewind snapshot as constraints, so an unknown
|
||||
shape restores both comment buckets and re-runs the old scan character
|
||||
for character. No keywords were reserved. Two disambiguations are by
|
||||
position, the LRM's own rule (a coverpoint bin's `(…)` is a transition
|
||||
list, a cross bin's is a select expression), which replaced a lookahead
|
||||
scan and took opentitan's fallback count from two to zero.
|
||||
|
||||
Two guards were added to shared expression machinery and are the
|
||||
round's one risk, stated plainly: an index cannot begin with `*`, `->`
|
||||
or `=` (so `1'b1[*5]` reads as a transition repeat), and a bin's own
|
||||
`with (…)` filter is not consumed as an array-method iterator
|
||||
argument. The whole corpus and the whole opentitan tree re-verified
|
||||
under both.
|
||||
|
||||
Layout is canonical (one cover item per line, `{ }` bin bodies like
|
||||
constraint sets, the label at the header's column); `verify.rs`
|
||||
untouched, twelve attack pairs. The comment-gap fuzzer was built in
|
||||
from the start: 329 gaps, the 52 that fail are all the shared-machinery
|
||||
slots already filed as §2.9-22 — and that classification is asserted by
|
||||
a test that runs each shape outside a covergroup and requires the same
|
||||
failure. Every sampled expression, bin value and `iff` binds to the
|
||||
class's properties; `cg_inst.cp` resolves cross-file; renaming a `rand`
|
||||
field rewrites the coverpoints that sample it. `FACTS_FORMAT` 11 → 12.
|
||||
|
||||
Opentitan: 544 of 544 covergroups structured, 87 of 87 DV covergroup
|
||||
files idempotent with comment streams byte-identical, 81 of 3 963 files
|
||||
re-laid-out and every one verified, the sweep's failure set and per-file
|
||||
diagnostics identical. Corpus: 10 files change layout, all verify;
|
||||
+1 139 references, 1 135 answered.
|
||||
|
||||
## 0.27.0 — 2026-09-02
|
||||
|
||||
Constraint bodies — round 1 of coverage_gaps C1, the DV correctness
|
||||
item.
|
||||
|
||||
`constraint c { … }`, `constraint C::c { … }` and `randomize() with
|
||||
{ … }` were opaque verbatim text: no name span, nothing inside bound,
|
||||
so renaming a `rand` field left `constraint c { user_id < 5; }` as
|
||||
non-compiling code with, at best, a generic warning. Now a constraint
|
||||
declaration is a real node — `soft`, `dist` (`:=`/`:/`), `->`
|
||||
implication, `if`/`else`, `foreach`, `solve … before`, `unique`,
|
||||
`disable soft`, `` `ifdef `` arms — and the parser attempts the
|
||||
structured body behind a rewind snapshot: any shape it does not know
|
||||
restores the cursor *and both pending-comment buckets* and re-runs the
|
||||
verbatim capture character for character, so an unknown body is the
|
||||
old behavior, not an approximation. No keywords were reserved —
|
||||
`soft`/`dist`/`solve`/`before` are matched by text — so `logic before;`
|
||||
keeps working and the editor grammar is untouched.
|
||||
|
||||
Layout is canonical: one constraint item per line, `}` at the header's
|
||||
column, `dist` weights broken like a braced list; a `with` block keeps
|
||||
its one-line-or-not shape. `verify.rs` untouched; the constraint attack
|
||||
pairs re-derived and extended (a dropped `soft`, `:=` for `:/`,
|
||||
swapped `solve`/`before`, a dropped `else` set, a flattened
|
||||
implication, a comment moved across `}`). Every operand binds to the
|
||||
class's properties (`this.` implicit; `foreach` variables nest; a
|
||||
`with` block resolves against the randomized object's class first), so
|
||||
hover, definition, references and rename reach inside; renaming a
|
||||
`rand` field from its declaration rewrites its constraint uses in-file
|
||||
and cross-file. `FACTS_FORMAT` 10 → 11. Lint rules read constraint
|
||||
operands instead of treating the body as opaque.
|
||||
|
||||
QA's finding — a comment right after `soft`, `dist`, `solve`,
|
||||
`before` or the constraint name was dropped, so the safety net refused
|
||||
the file — was answered with an exhaustive gap fuzzer (a block comment
|
||||
in every inter-token gap of fifteen fixtures, 358 gaps, format and
|
||||
idempotency both demanded) and fourteen named comment fields; the
|
||||
forty gaps that remain are shared expression machinery that behaves
|
||||
identically outside a constraint (`q[/*c*/ i]`, `inside {[/*c*/ 0:3]}`,
|
||||
scoped-name chains) and are filed as a parser-wide round. No opentitan
|
||||
file hits one.
|
||||
|
||||
Opentitan: 1 993 of 2 009 constraint bodies parse structured (the 16
|
||||
fallbacks are macro-item bodies and non-LRM shapes), all laid out,
|
||||
token-equivalent and idempotent; 48 DV files across 16 IPs re-format
|
||||
idempotently with their comment streams byte-identical; the sweep's
|
||||
failure set unchanged and the tolerant-diagnostic count per file
|
||||
identical. Corpus: 37 files change layout, all verified; +1 646
|
||||
references, 84 % answered. Covergroups are round 2.
|
||||
|
||||
## 0.26.0 — 2026-09-02
|
||||
|
||||
Two lanes, run in parallel: member completion, and escaped identifiers.
|
||||
|
||||
### Member completion — a dot means members
|
||||
|
||||
Typing `item.` used to get the whole-index dump — every keyword and
|
||||
every project word, capped at 512 — because the empty word after a dot
|
||||
fell through to the ordinary tiers. Now the answer after `.` or `::` is
|
||||
exclusively the members of what precedes it: a class's properties and
|
||||
methods (inherited ones included, through the same base chain hover
|
||||
follows), a struct's fields (`reg2hw.ctrl.` via the synthesized nested
|
||||
keys), an interface's signals, modports and clocking blocks (`vif.`,
|
||||
`vif.cb.`), a package's members (`tlul_pkg::`), `this.`/`super.`. The
|
||||
walk is published from `vlog_semantic` (`Semantics::member_site`,
|
||||
`WorkspaceIndex::members_of_chain`) and the resolver's own member
|
||||
resolution is rewritten to call it, so the popup cannot list a name
|
||||
hover would not resolve. A dot inside an instantiation's `(…)` or
|
||||
`#(…)` lists the module's ports or parameters, already-connected ones
|
||||
dropped. `.` and `:` are trigger characters. An unreadable head answers
|
||||
nothing — never the dump. Cheaper than what it replaces: 6–62 µs
|
||||
against 212 µs.
|
||||
|
||||
QA's finding, fixed at the root: `#(.` offered header `localparam`s
|
||||
because the binder had discarded the `parameter`/`localparam` keyword.
|
||||
`SymbolKind::LocalParam` is now bound from the keyword (sticky across
|
||||
continuation entries, as the ghost skeleton already read it), shows as
|
||||
"localparam" on the hover card, is excluded from override lists only,
|
||||
and still resolves for hierarchical reads. `FACTS_FORMAT` 9 → 10.
|
||||
|
||||
### Escaped identifiers format
|
||||
|
||||
`wire \my-signal ;` was refused outright: the lexer ends an escaped
|
||||
identifier before its terminating whitespace and the formatter emitted
|
||||
every name bare, so `\my-signal;` re-lexed as one token and the safety
|
||||
net — correctly — rejected the file. Fifty name-emission sites now go
|
||||
through one choke point that writes the IEEE 1800 §5.6.1 space;
|
||||
`verify.rs` untouched, eight masked-corruption attack pairs; the corpus
|
||||
is byte-identical by construction. Netlists and generated RTL format.
|
||||
One shape is refused rather than corrupted and filed (`\my-pkg ::x`,
|
||||
whose segments the parser joins).
|
||||
|
||||
## 0.25.0 — 2026-09-01
|
||||
|
||||
Struct members — `s.field`, `reg2hw.ctrl.q` and the anonymous
|
||||
aggregates resolve.
|
||||
|
||||
`typedef struct packed {…} bus_t; bus_t s; s.field` recorded nothing.
|
||||
The in-file gap was a single resolver gate: a struct typedef's member
|
||||
scope already existed, hung off the typedef, and lookup simply never
|
||||
entered it. Now any symbol whose child scope is a struct scope — a
|
||||
typedef, an anonymous `struct {…} s;` declarator, or an inline nested
|
||||
field — answers member access with one rule, and fields carry their
|
||||
own type so `s.hdr.addr` hops through a member. Unions are the same
|
||||
node. Anonymous `enum {A, B} x;` variants land in the enclosing scope
|
||||
exactly like typedef'd ones (the open handshake since types-decls).
|
||||
|
||||
Across files, struct members are exported under the typedef's name,
|
||||
and inline nested fields — the shape opentitan's generated register
|
||||
packages use everywhere — under a synthesized `owner.field` key
|
||||
carried as the field's type, so `hw2reg.status.txfull.d` lands on
|
||||
`txfull`'s `d` and never `rxfull`'s two lines up (bare-name keys would
|
||||
collide on `q`/`d`/`qe` in every register package). Same-named struct
|
||||
typedefs in two packages answer ambiguity, never a guess. `FACTS_FORMAT`
|
||||
8 → 9 (older stores rebuild once); `typeDefinition` works inside a
|
||||
`typedef struct` body.
|
||||
|
||||
Unresolved names on the corpus fell 1 203 → 1 162; its store shrank
|
||||
1.1 % (a resolved local fact encodes smaller than the external
|
||||
candidate it replaced) while opentitan's register packages grow theirs
|
||||
4.3 %. QA: 28 live opentitan probes across six IPs with three planted
|
||||
sibling-field pairs, zero wrong answers, hover under 0.5 ms. Known
|
||||
remaining shape: an indexed link mid-chain (`reg2hw.key_share0[i].q`),
|
||||
pre-existing and filed.
|
||||
|
||||
## 0.24.0 — 2026-09-01
|
||||
|
||||
Interface semantics — interfaces, modports and clocking blocks become
|
||||
|
||||
@@ -29,6 +29,47 @@ doing anything.
|
||||
- Match the style of the surrounding code (comment density, naming,
|
||||
module layout).
|
||||
|
||||
## File and function size
|
||||
|
||||
Files and functions are sized for a human reader, not a compiler.
|
||||
|
||||
- **Target 300–600 production lines per file.** At 800, consider
|
||||
splitting. Above 1,200, an explicit reason not to split goes in the
|
||||
feature README. Test lines do not count, but a `#[cfg(test)]` block
|
||||
that dwarfs its file moves to its own module or `tests/` file.
|
||||
- **Functions: 10–50 lines.** Investigate anything over 80; anything
|
||||
over 150 needs a reason in a comment (a dispatch table over an enum
|
||||
is the usual one).
|
||||
- Looser for declarative tables, generated code, snapshots and
|
||||
repetitive tests. Complexity matters more than the count: 800 lines
|
||||
of grammar productions read more easily than 250 lines of state.
|
||||
- **The real test is one sentence.** A human should be able to say what
|
||||
a file is responsible for in one sentence and predict which parts a
|
||||
change touches. Several "and" clauses mean the file wants to be
|
||||
several modules.
|
||||
- A split is a **pure move**: public paths stay the same (re-export from
|
||||
the old `mod`), behaviour and output stay byte-identical, the test
|
||||
count does not drop. Measured, not asserted — the corpus and
|
||||
opentitan byte-identity gates are the proof.
|
||||
|
||||
Measured 2026-09-02 (production lines): `vlog_parser/src/parser.rs`
|
||||
8 786, `vlog_formatter/src/format.rs` 5 444, `vlog_parser/src/ast.rs`
|
||||
3 313, `lucisv_server/src/server.rs` 2 559 (+6 300 test),
|
||||
`vlog_semantic/src/bind.rs` 2 378, `vlog_semantic/src/workspace.rs`
|
||||
1 975, `vlog_refactor/src/ports.rs` 1 778,
|
||||
`lucisv_server/src/completion.rs` 1 716 — thirteen files over 800.
|
||||
Every one of them was where feature lanes collided, which is the other
|
||||
reason to split them. **Decomposed the same day by TODO §28** (four
|
||||
lanes, pure moves, output byte-identical): `parser/` (19 modules) and
|
||||
`ast/` (8), `format/` (15), `server/` (11 + tests) and `completion/`
|
||||
(6), `bind/` (8), `workspace/` (5), `ports/` (6), `rename/` (4). Measured
|
||||
after the round (non-blank, non-comment, outside tests): two files over
|
||||
600 — `lucisv_server/src/perf.rs` 895 (one cohesive subsystem; the reason
|
||||
is in the decomposition-server README) and `vlog_parser/src/lexer.rs`
|
||||
762 — and 183 under it. Nothing new may push a file back over the
|
||||
thresholds: a dev adding to a file near 600 puts the code in a new
|
||||
module.
|
||||
|
||||
## Rust standards
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.24.0"
|
||||
version = "0.35.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -128,6 +128,10 @@ line-length = 100 # 40..400, same as --line-length
|
||||
indent = 2 # 1..8, same as --indent
|
||||
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
|
||||
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
|
||||
|
||||
[lint]
|
||||
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
|
||||
ignore = ["module-filename"] # removed after selection
|
||||
```
|
||||
|
||||
`filelist` names the project's sources the way the rest of the EDA world
|
||||
@@ -156,8 +160,9 @@ with a file that sets only `line-length` uses both). `exclude` is the
|
||||
exception: config patterns are *added* to `--exclude`, not replaced by it.
|
||||
|
||||
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
|
||||
supported subset (tables, multi-line arrays, string escapes) is a hard error
|
||||
naming the file and line — exit 2, with nothing written. This is deliberate:
|
||||
supported subset (tables other than `[lint]`, multi-line arrays, string
|
||||
escapes) is a hard error naming the file and line — exit 2, with nothing
|
||||
written. This is deliberate:
|
||||
a silently ignored `line_length` typo costs more than a strict parser does.
|
||||
|
||||
## Linting
|
||||
@@ -193,12 +198,12 @@ what it can see.
|
||||
| `undriven-net` † | — | everything read is driven by something |
|
||||
| `multiply-driven` † | — | one driver per variable |
|
||||
|
||||
† Off by default — `--select` them. These three read the file's *symbol
|
||||
table*, not just its syntax, which is what lets them tell one `count` from
|
||||
another; they are off because a single-file analysis cannot see a signal used
|
||||
from another file's hierarchy. See
|
||||
`docs/features/semantic-lints/README.md`. The table above is not the whole
|
||||
set — naming-style rules ship too, and
|
||||
† On by default when lucisv can see a project (a multi-file CLI run or the
|
||||
language server), and off for a single file or stdin unless `--select` names
|
||||
them. These three read the file's *symbol table*, not just its syntax; the
|
||||
project-wide identifier census keeps a hierarchical use in another file from
|
||||
becoming a false positive. See `docs/features/semantic-lints-on/README.md`.
|
||||
The table above is not the whole set — naming-style rules ship too, and
|
||||
`cargo run -p vlog_linter --example rules_markdown` prints the generated
|
||||
reference for every rule with its default.
|
||||
|
||||
@@ -233,7 +238,7 @@ generic pretty-printing IR, language formatting rules, and a thin CLI:
|
||||
|---|---|---|
|
||||
| `crates/vlog_parser` | `ruff_python_parser` + `ruff_python_ast` | Hand-written lexer and recursive-descent parser producing a comment-preserving AST |
|
||||
| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer |
|
||||
| `crates/vlog_formatter/src/format.rs` | `ruff_python_formatter` | Per-node formatting rules |
|
||||
| `crates/vlog_formatter/src/format/` | `ruff_python_formatter` | Per-node formatting rules, one module per grammar domain (`item`, `module`, `instance`, `decl`, `stmt`, `expr`, `class`, `cover`, `sva`, …) |
|
||||
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
|
||||
| `crates/lucisv` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
|
||||
|
||||
@@ -297,8 +302,8 @@ both layouts are fixed points of re-formatting:
|
||||
|
||||
### Turning the formatter off
|
||||
|
||||
Items between a `// verilog_format: off` and a `// verilog_format: on`
|
||||
comment are emitted as the exact source bytes they were written with,
|
||||
Everything between a `// verilog_format: off` and a `// verilog_format: on`
|
||||
comment is emitted as the exact source bytes it was written with,
|
||||
indentation included — the escape hatch for hand-aligned tables and the
|
||||
like. `// lucisv: off` / `// lucisv: on` is an accepted alias.
|
||||
|
||||
@@ -312,12 +317,30 @@ module m;
|
||||
endmodule
|
||||
```
|
||||
|
||||
The fence must be a line comment on its own line, and its text must match
|
||||
exactly — `// lucisv: off for now` is an ordinary comment, not a fence. An
|
||||
`off` with no matching `on` runs to the end of the enclosing item list
|
||||
(module body, package body, generate block, or the file). Fences select
|
||||
whole items; one written between two *statements* has no effect yet. Full
|
||||
rules: `docs/features/format-fences/README.md`.
|
||||
A fence works between **items** — module, package and class members, and
|
||||
top-level items — and between **statements**: inside `begin`…`end`,
|
||||
`fork`…`join*`, and function, task, `initial`, `always` and `final` bodies.
|
||||
|
||||
```systemverilog
|
||||
class scoreboard;
|
||||
function void build_phase();
|
||||
// verilog_format: off
|
||||
uvm_config_db#(cfg_t)::set(this, "env.agent", "cfg",
|
||||
cfg.agent_cfg); // hand-wrapped, left alone
|
||||
// verilog_format: on
|
||||
endfunction
|
||||
endclass
|
||||
```
|
||||
|
||||
The fence must be a line comment that begins its own line, and its text must
|
||||
match exactly — `// lucisv: off for now` is an ordinary comment, not a fence,
|
||||
and so is one written after code on the same line (`wire a; // lucisv: off`,
|
||||
`begin // lucisv: off`). An `off` with no matching `on` runs to the end of the
|
||||
enclosing list and no further: the module body, the class body, the
|
||||
`begin`…`end`, the function body, or the file. A fence inside a port list, a
|
||||
parameter list or a `case` **label** list is still an ordinary comment. Full
|
||||
rules: `docs/features/format-fences/README.md` and
|
||||
`docs/features/statement-fences/README.md`.
|
||||
|
||||
### Range formatting (`--lines`)
|
||||
|
||||
@@ -397,24 +420,28 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
methods with `virtual`/`static`/`local`/`protected`/`automatic`, `function
|
||||
new`, `extern` and `pure virtual` prototypes and their out-of-body
|
||||
definitions, plus everything that already works at module scope (`typedef`,
|
||||
`localparam`, `import`, directives, macro items, nested classes). `constraint
|
||||
c { ... }` and `covergroup … endgroup` are **passed through verbatim** — two
|
||||
grammars with no layout convention worth inventing. See
|
||||
`docs/features/classes/README.md`
|
||||
`localparam`, `import`, directives, macro items, nested classes).
|
||||
`constraint c { ... }` and `covergroup … endgroup` are structured too:
|
||||
constraint expressions, `soft`/`dist`, implication, `foreach`, `solve
|
||||
before`, coverpoints, bins, transitions and crosses all format canonically
|
||||
and participate in rename, references and semantic lints. An unrecognized
|
||||
body rewinds to its exact source bytes instead of blocking the surrounding
|
||||
file. See `docs/features/constraint-bodies/README.md` and
|
||||
`docs/features/covergroup-bodies/README.md`
|
||||
- Concurrent assertions (IEEE 1800 §16): `assert`/`assume`/`cover`/`restrict
|
||||
property ( ... )` with an optional `label:` prefix and an action block
|
||||
(`else $error(...)`, `$info(...); else ...`, `else begin ... end`, and any
|
||||
statement that nests blocks: `if (c) begin ... end else ...`,
|
||||
`fork ... join_none`, `case ... endcase`), wherever
|
||||
a module item or a statement can appear — module and package bodies,
|
||||
generate regions, `begin`/`end`, and at file scope. Plus `sequence ...
|
||||
endsequence` and `property ... endproperty` declarations. All of it is
|
||||
**passed through verbatim**, for the same reason `constraint` is: the
|
||||
property/sequence expression language (`|->`, `##[1:3]`, `throughout`,
|
||||
`disable iff`, `$rose`) is a second grammar with no layout convention worth
|
||||
inventing. Only the first line is re-indented to the item's level; the
|
||||
relative layout the source wrote is what survives. See
|
||||
`docs/features/assertions/README.md`
|
||||
`fork ... join_none`, `case ... endcase`), wherever a module item or a
|
||||
statement can appear — module and package bodies, generate regions,
|
||||
`begin`/`end`, and at file scope. `sequence` and `property` declarations,
|
||||
typed formals, local variables, `expect`, `cover sequence`, and `default
|
||||
disable iff` are real nodes. The property/sequence expression grammar uses
|
||||
the LRM precedence table; top-level `|->`/`|=>`/`##`/`and`/`or` operators
|
||||
break one per line when needed. Rename, references, document symbols and
|
||||
semantic lints see inside; an unrecognized construct falls back to its exact
|
||||
source bytes and produces a rename warning. See
|
||||
`docs/features/sva-bodies/README.md`
|
||||
- Dynamic types: queues (`string q[$]`, bounded `[$:N]`), dynamic arrays
|
||||
(`int a[]`), associative arrays (`[*]`, `[string]`, `[key_t]`) — in
|
||||
declarations, class properties, typedefs and function/task arguments; the
|
||||
@@ -423,8 +450,8 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
`docs/features/dynamic-types/README.md`
|
||||
- DV statements (IEEE 1800 §7.12, §9.3.5, §11.12, §12.7.3, §13.4.2, §18.7,
|
||||
§18.16): `randomize() with { ... }` / `std::randomize(x, y) with { ... }`
|
||||
(the call is structural, the constraint block is **passed through
|
||||
verbatim**, exactly as `constraint c { ... }` is), the array-method
|
||||
(the call and its constraint block are structural, with byte-exact fallback
|
||||
for an unrecognized constraint shape), the array-method
|
||||
iterator argument `q.sum() with (item.w)`, `foreach` over a
|
||||
package-scoped or hierarchical array with selects on the way
|
||||
(`foreach (pkg::isa[i])`, `foreach (h[id].sub[k])`, `foreach (a[i][j])`),
|
||||
@@ -464,7 +491,8 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
trailing `;` is reproduced only if the source wrote one. At item and
|
||||
statement position a space before the argument list is accepted too
|
||||
(`` `uvm_field_int (a, UVM_DEFAULT) ``) and is reproduced as written; in
|
||||
*expression* position `` `A (b) `` still parses as a call applied to `(b)`.
|
||||
*expression* position the author-written gap is preserved too, because it
|
||||
can affect how a macro with formals is interpreted.
|
||||
A macro that ends its line is a complete macro, so whatever opens the next
|
||||
line — a declaration, or a statement starting with `@`, `#`, `->` or `{` —
|
||||
is its own item. See `docs/features/item-misc/README.md` and
|
||||
@@ -490,10 +518,17 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
(``sub #(`include "config.vh") u (...)``). See
|
||||
`docs/features/directives-in-lists/README.md` and
|
||||
`docs/features/directives-in-instances/README.md`
|
||||
- Programs, interface classes, `alias`, `union tagged`, `specparam`, library
|
||||
map entries, and statement-form `expect`. `specify`, UDP `primitive`/`table`,
|
||||
`checker`, and `config` blocks are recognized as opaque blocks so vendored
|
||||
simulation models and formal collateral do not block the rest of a file;
|
||||
their internal layout is preserved. See
|
||||
`docs/features/vendor-formal-grammar/README.md`
|
||||
|
||||
Not yet supported (parse errors). Roadmap ordered by measured impact on
|
||||
real RTL — see `docs/features/corpus-check/README.md` for the 820-file
|
||||
corpus baseline this ordering comes from:
|
||||
### Historical syntax roadmap
|
||||
|
||||
This roadmap records how parse coverage was raised, in measured-impact order.
|
||||
See `docs/features/corpus-check/README.md` for the 820-file corpus baseline:
|
||||
|
||||
1. ~~Macro invocation at module-item / statement position
|
||||
(`` `ASSERT_INIT(...) `` style)~~ — **done**; see
|
||||
@@ -574,8 +609,9 @@ corpus baseline this ordering comes from:
|
||||
`docs/features/dv-statements/README.md`. Emptied the `dv-statements`
|
||||
bucket (26 files) and moved the parse rate from 94.1% to 97.1%; 24 of the
|
||||
26 files format, the other 2 advanced to a macro-items blocker and to the
|
||||
`new obj` shallow-copy expression. `specify` blocks, `checker`,
|
||||
`program`, `interface class` and `randsequence` remain unsupported
|
||||
`new obj` shallow-copy expression. `randsequence` remained unsupported at
|
||||
this point; the other vendor/formal constructs listed here landed later in
|
||||
0.30.0
|
||||
11. ~~A macro statement that ends its line followed by a symbol on the next
|
||||
one, the `new obj` shallow copy (IEEE 1800 §8.12), and a based number
|
||||
whose digits come from a macro (`` 32'h`DM_ADDR ``)~~ — **done**; see
|
||||
@@ -598,6 +634,11 @@ corpus baseline this ordering comes from:
|
||||
`` `X_EACH_CSR`` (need macro expansion, a deliberate non-goal) and 5
|
||||
files that are not valid standalone Verilog
|
||||
|
||||
Fragment-mode support subsequently raised the current frozen corpus baseline
|
||||
to **814/820 (99.3%)**. The remaining six files require cross-file macro
|
||||
expansion, contain a conditional-split outlier, or are not valid standalone
|
||||
Verilog; none regressed when the vendor/formal and SVA grammars landed.
|
||||
|
||||
Like ruff, `lucisv` refuses to output anything for a file it cannot fully
|
||||
parse, so it can never corrupt code.
|
||||
|
||||
|
||||
@@ -71,6 +71,9 @@ pub struct Options {
|
||||
pub select: Vec<String>,
|
||||
/// `check` only: rules to drop from whatever `--select` left.
|
||||
pub ignore: Vec<String>,
|
||||
/// `check` only: print the generated rule reference and exit, reading no
|
||||
/// file at all.
|
||||
pub rules_doc: bool,
|
||||
/// Files, directories, or the single input `-`.
|
||||
pub inputs: Vec<String>,
|
||||
/// `-f`: EDA filelists whose files are added to [`Options::inputs`].
|
||||
@@ -188,11 +191,23 @@ OPTIONS:
|
||||
CHECK OPTIONS (`lucisv check` only):
|
||||
--select <RULES> run only these rules (comma-separated, repeatable)
|
||||
--ignore <RULES> drop these rules from the set that would run
|
||||
|
||||
Three rules read the *project* rather than one file — `unused-signal`,
|
||||
`undriven-net`, `multiply-driven`. They run by default over more than one
|
||||
file, where lucisv can ask whether another file mentions a name, and stay
|
||||
off for a single file or a stdin buffer, where it cannot. `--select` runs
|
||||
one either way; `--ignore`, or `ignore` under `[lint]` in lucisv.toml,
|
||||
turns one off.
|
||||
--output-format <FMT> `text` (default): FILE:LINE:COL: message [rule];
|
||||
`json`: one array of diagnostic objects
|
||||
--fix apply safe fixes and write the files back
|
||||
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
|
||||
one yet, so today this changes nothing)
|
||||
--rules-doc print the rule reference — every rule, what it
|
||||
reports and whether it has a fix — as Markdown on
|
||||
stdout and exit 0. Generated from the registry, so
|
||||
it always describes the rules this build ships;
|
||||
takes no files and lints nothing
|
||||
|
||||
Suppress a finding with a comment: `// lucisv: waive <rule>` on the line
|
||||
itself or on the line above it, or a `// lucisv: waive-start <rule>` /
|
||||
@@ -233,8 +248,10 @@ CONFIGURATION:
|
||||
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
|
||||
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
|
||||
read by lucisv-server only — the CLI reads a filelist only when `-f` names
|
||||
one, so `lucisv rtl/` always means the directory it was given). A command
|
||||
line flag overrides the file.
|
||||
one, so `lucisv rtl/` always means the directory it was given). One table
|
||||
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
|
||||
`--select`/`--ignore` semantics). A command line flag overrides the file's
|
||||
corresponding key; the other keys still apply.
|
||||
|
||||
RANGE FORMATTING:
|
||||
`--lines` formats one construct at a time: an item whose lines meet a range
|
||||
@@ -281,6 +298,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
unsafe_fixes: false,
|
||||
select: Vec::new(),
|
||||
ignore: Vec::new(),
|
||||
rules_doc: false,
|
||||
inputs: Vec::new(),
|
||||
filelists: Vec::new(),
|
||||
};
|
||||
@@ -360,6 +378,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let v = args.next().ok_or("--ignore requires a value")?;
|
||||
opts.ignore.extend(split_rules(&v));
|
||||
}
|
||||
"--rules-doc" => opts.rules_doc = true,
|
||||
"-h" | "--help" => {
|
||||
print_help();
|
||||
std::process::exit(0);
|
||||
@@ -373,9 +392,16 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
s => opts.inputs.push(s.to_string()),
|
||||
}
|
||||
}
|
||||
// A filelist is an input like any other, so `-f files.f` alone is a
|
||||
// complete command line and needs no positional argument.
|
||||
if opts.inputs.is_empty() && opts.filelists.is_empty() {
|
||||
// `--rules-doc` prints the rule reference and reads nothing, so it is the
|
||||
// one invocation with no input at all — and being given one means the
|
||||
// caller expected files to be linted, which they would not be.
|
||||
if opts.rules_doc {
|
||||
if !opts.inputs.is_empty() || !opts.filelists.is_empty() {
|
||||
return Err("--rules-doc takes no files".to_string());
|
||||
}
|
||||
} else if opts.inputs.is_empty() && opts.filelists.is_empty() {
|
||||
// A filelist is an input like any other, so `-f files.f` alone is a
|
||||
// complete command line and needs no positional argument.
|
||||
return Err("no input files (try `lucisv --help`)".to_string());
|
||||
}
|
||||
// Repeating the flag is the same as one comma-separated list; both spell
|
||||
@@ -418,6 +444,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
|
||||
(opts.output_format != OutputFormat::Text, "--output-format"),
|
||||
(!opts.select.is_empty(), "--select"),
|
||||
(!opts.ignore.is_empty(), "--ignore"),
|
||||
(opts.rules_doc, "--rules-doc"),
|
||||
];
|
||||
let format_only = [
|
||||
(opts.check, "--check"),
|
||||
@@ -586,4 +613,15 @@ mod tests {
|
||||
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
|
||||
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_doc_is_the_one_check_that_needs_no_input() {
|
||||
assert!(parse(&["check", "--rules-doc"]).unwrap().rules_doc);
|
||||
// ... and refuses one, rather than accepting a path it would not read.
|
||||
assert!(parse(&["check", "--rules-doc", "rtl"]).is_err());
|
||||
assert!(parse(&["check", "--rules-doc", "-f", "a.f"]).is_err());
|
||||
// Lint-only, like every other `check` flag.
|
||||
assert!(parse(&["--rules-doc"]).is_err());
|
||||
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
|
||||
}
|
||||
}
|
||||
+142
-14
@@ -5,13 +5,16 @@
|
||||
//! is handed the same `(path, config)` job list `format` gets. Only what
|
||||
//! happens to one file differs.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use lucisv_core::config::FileConfig;
|
||||
use rayon::prelude::*;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::Config;
|
||||
use vlog_linter::{apply_fixes, lint, Fix, ParsedSource, Rule, Violation};
|
||||
use vlog_linter::words;
|
||||
use vlog_linter::{apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, Violation};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::args::{Options, OutputFormat};
|
||||
@@ -22,6 +25,114 @@ use crate::args::{Options, OutputFormat};
|
||||
/// cap only bounds a rule that would fight itself forever.
|
||||
const MAX_FIX_ROUNDS: usize = 10;
|
||||
|
||||
/// One file to lint, with the rules the command line and its own
|
||||
/// `lucisv.toml` resolved to.
|
||||
pub struct Job {
|
||||
path: PathBuf,
|
||||
config: Config,
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
}
|
||||
|
||||
/// A whole `lucisv check` run: what to lint, and what the project says about
|
||||
/// names.
|
||||
pub struct Plan {
|
||||
jobs: Vec<Job>,
|
||||
/// The project's identifier census, built when at least one selected rule
|
||||
/// asks for a workspace and there is more than one file to ask about.
|
||||
census: Option<Census>,
|
||||
}
|
||||
|
||||
/// How many of the run's files write each identifier down.
|
||||
///
|
||||
/// The CLI's answer to the question the language server answers from its
|
||||
/// index: it has none, so it builds one — a read and a lex of every file in
|
||||
/// the run, before the first rule sees anything. Only the *counts* are kept;
|
||||
/// a rule asks about one name at a time and never about a file.
|
||||
pub struct Census {
|
||||
files: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
impl Census {
|
||||
/// The census of every file in the run, harvested in parallel.
|
||||
///
|
||||
/// A file that cannot be read or does not lex contributes nothing, which
|
||||
/// is the same all-or-nothing rule the rest of the run gives it: the
|
||||
/// file's own check reports the error.
|
||||
fn of(jobs: &[Job]) -> Census {
|
||||
let per_file: Vec<Vec<String>> = jobs
|
||||
.par_iter()
|
||||
.map(|job| match std::fs::read_to_string(&job.path) {
|
||||
Ok(src) => words::harvest_text(&src),
|
||||
Err(_) => Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
let mut files: HashMap<String, u32> = HashMap::new();
|
||||
for words in per_file {
|
||||
for word in words {
|
||||
*files.entry(word).or_default() += 1;
|
||||
}
|
||||
}
|
||||
Census { files }
|
||||
}
|
||||
|
||||
/// How many files in the run write `name` down.
|
||||
fn count(&self, name: &str) -> u32 {
|
||||
self.files.get(name).copied().unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's view of the census: everything the project says, minus what
|
||||
/// this file says about itself.
|
||||
struct Elsewhere<'a> {
|
||||
census: &'a Census,
|
||||
/// This file's own words, sorted — [`words::harvest`]'s answer over the
|
||||
/// tokens the file was linted from, so the subtraction is exact rather
|
||||
/// than assumed.
|
||||
own: Vec<String>,
|
||||
}
|
||||
|
||||
impl MentionOracle for Elsewhere<'_> {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
|
||||
self.census.count(name) > mine
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the run: the rules for each file, and whether a census is owed.
|
||||
///
|
||||
/// **Precedence is CLI over config, key by key**: `--select` replaces a
|
||||
/// `[lint] select`, `--ignore` replaces a `[lint] ignore`, and a key the
|
||||
/// command line does not mention is the config file's to answer — the same
|
||||
/// ladder `--line-length` and `--indent` already climb.
|
||||
///
|
||||
/// A rule that [`Rule::needs_workspace`] is on by default here exactly when
|
||||
/// the run holds more than one file: one file is one file whatever directory
|
||||
/// it was found in, and a census of it could only ever say what the file
|
||||
/// already says about itself.
|
||||
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
|
||||
let workspace = gathered.len() > 1;
|
||||
let mut jobs = Vec::with_capacity(gathered.len());
|
||||
for (path, config, file_config) in gathered {
|
||||
let select = pick(&opts.select, file_config.lint_select.as_deref());
|
||||
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
|
||||
let rules = vlog_linter::select_rules(select, ignore, workspace)
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
jobs.push(Job { path, config, rules });
|
||||
}
|
||||
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
|
||||
let census = (workspace && wanted).then(|| Census::of(&jobs));
|
||||
Ok(Plan { jobs, census })
|
||||
}
|
||||
|
||||
/// The command line's list when it said anything, else the config file's.
|
||||
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
|
||||
if cli.is_empty() {
|
||||
config.unwrap_or(&[])
|
||||
} else {
|
||||
cli
|
||||
}
|
||||
}
|
||||
|
||||
/// What linting one file produced.
|
||||
struct Report {
|
||||
path: String,
|
||||
@@ -39,13 +150,12 @@ struct Report {
|
||||
|
||||
/// Lints every gathered file and reports. Exit 1 if anything is left over,
|
||||
/// 2 if a file could not be read, written, or lexed.
|
||||
pub fn check_files(
|
||||
opts: &Options,
|
||||
jobs: &[(PathBuf, Config)],
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> ExitCode {
|
||||
let mut reports: Vec<Report> =
|
||||
jobs.par_iter().map(|(file, config)| check_one(file, config, opts, rules)).collect();
|
||||
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
let mut reports: Vec<Report> = plan
|
||||
.jobs
|
||||
.par_iter()
|
||||
.map(|job| check_one(&job.path, &job.config, opts, &job.rules, plan.census.as_ref()))
|
||||
.collect();
|
||||
// Diagnostics are printed sorted by path, then by position within the
|
||||
// file (`lint` already sorts those), so a run over a directory reads
|
||||
// top to bottom whatever order the walk or the worker pool produced.
|
||||
@@ -63,7 +173,7 @@ pub fn check_stdin(
|
||||
) -> ExitCode {
|
||||
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
|
||||
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
|
||||
let (violations, lex_error) = run_rules(src, path, config, rules);
|
||||
let (violations, lex_error) = run_rules(src, path, config, rules, None);
|
||||
// Nothing is ever written back for stdin, so `--fix` has nothing to do
|
||||
// here; the violations are reported as they are.
|
||||
let error = lex_error.map(|e| format!("{name}: {e}"));
|
||||
@@ -72,7 +182,13 @@ pub fn check_stdin(
|
||||
}
|
||||
|
||||
/// Lints one file, optionally fixing it, and never panics out of its worker.
|
||||
fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn Rule]) -> Report {
|
||||
fn check_one(
|
||||
file: &Path,
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
census: Option<&Census>,
|
||||
) -> Report {
|
||||
let path = file.display().to_string();
|
||||
let failed = |error: String| Report {
|
||||
path: path.clone(),
|
||||
@@ -88,9 +204,10 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
|
||||
};
|
||||
let outcome = crate::catch_panic(|| {
|
||||
if opts.fix {
|
||||
fix_source(&src, file, config, opts, rules)
|
||||
fix_source(&src, file, config, opts, rules, census)
|
||||
} else {
|
||||
let (violations, lex_error) = run_rules(&src, Some(file.to_path_buf()), config, rules);
|
||||
let (violations, lex_error) =
|
||||
run_rules(&src, Some(file.to_path_buf()), config, rules, census);
|
||||
(violations, None, 0, lex_error)
|
||||
}
|
||||
});
|
||||
@@ -121,6 +238,7 @@ fn run_rules(
|
||||
path: Option<PathBuf>,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
census: Option<&Census>,
|
||||
) -> (Vec<Violation>, Option<String>) {
|
||||
// One parse per file (TODO §4): the products are built here, once, and
|
||||
// lent to the context. Under `--fix` each *round* re-enters through this
|
||||
@@ -129,9 +247,17 @@ fn run_rules(
|
||||
// saves a parse; a plain `lucisv check` always does.
|
||||
let parsed = ParsedSource::parse(src);
|
||||
let lex_error = parsed.lex_error().map(|e| format!("lex error: {e}"));
|
||||
// This file's own words, off the tokens it was just lexed from rather
|
||||
// than off a second lex — what the oracle subtracts from the project's
|
||||
// census so a signal never counts as mentioned by its own declaration.
|
||||
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
|
||||
// The indent width the formatter would use is also the width a tab
|
||||
// expands to, so `--indent 4` fixes tabs into four spaces.
|
||||
let ctx = parsed.context(path).with_tab_width(config.indent_width);
|
||||
let ctx = match &elsewhere {
|
||||
Some(elsewhere) => ctx.with_oracle(elsewhere),
|
||||
None => ctx,
|
||||
};
|
||||
(lint(&ctx, rules), lex_error)
|
||||
}
|
||||
|
||||
@@ -174,10 +300,12 @@ fn fix_source(
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
census: Option<&Census>,
|
||||
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
|
||||
let mut text = src.to_string();
|
||||
let mut fixed = 0;
|
||||
let (mut violations, mut lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
let (mut violations, mut lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, census);
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round =
|
||||
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
|
||||
@@ -186,7 +314,7 @@ fn fix_source(
|
||||
}
|
||||
fixed += round.applied;
|
||||
text = round.output;
|
||||
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules, census);
|
||||
}
|
||||
let rewritten = (text != src).then_some(text);
|
||||
(violations, rewritten, fixed, lex_error)
|
||||
|
||||
+41
-14
@@ -28,7 +28,7 @@ use rayon::prelude::*;
|
||||
|
||||
use args::{Command, Options};
|
||||
use lucisv_core::cache::{content_hash, Cache, Entry};
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use lucisv_core::filelist;
|
||||
use lucisv_core::walk::{collect_files, EXTENSIONS};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
@@ -84,13 +84,19 @@ fn run(opts: &Options) -> ExitCode {
|
||||
|
||||
/// `lucisv check`: the linter over the same file set the formatter would take.
|
||||
fn run_check(opts: &Options) -> ExitCode {
|
||||
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore) {
|
||||
Ok(rules) => rules,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
// Before any rule is selected and before any path is gathered: the rule
|
||||
// reference is a property of the build, not of a run over files.
|
||||
if opts.rules_doc {
|
||||
print!("{}", vlog_linter::rules_markdown());
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
// The command line's own names are checked before anything is walked, so
|
||||
// a typo'd `--select` fails in milliseconds rather than after the scan.
|
||||
// A `lucisv.toml`'s names are checked per file below, where they are read.
|
||||
if let Err(e) = vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if opts.is_stdin() {
|
||||
let config = match stdin_config(opts) {
|
||||
Ok(c) => c,
|
||||
@@ -104,6 +110,16 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
eprintln!("error: reading stdin: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
// A stdin buffer is one text with nothing around it: there is no
|
||||
// census to build and no other file to ask about, so the rules that
|
||||
// need a project stay off. `--select` still reaches them.
|
||||
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
|
||||
Ok(rules) => rules,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
return lint::check_stdin(opts, &src, &config, &rules);
|
||||
}
|
||||
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
|
||||
@@ -113,7 +129,13 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
lint::check_files(opts, &jobs, &rules)
|
||||
match lint::plan(opts, jobs) {
|
||||
Ok(plan) => lint::check_files(opts, &plan),
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_stdin(opts: &Options) -> ExitCode {
|
||||
@@ -174,11 +196,11 @@ fn run_files(opts: &Options) -> ExitCode {
|
||||
// The cache is only read here; entries ride back with the results and
|
||||
// are recorded serially below, so nothing is shared mutably.
|
||||
let results: Vec<FileResult> =
|
||||
jobs.par_iter().map(|(file, config)| process_file(file, config, opts, &cache)).collect();
|
||||
jobs.par_iter().map(|(file, config, _)| process_file(file, config, opts, &cache)).collect();
|
||||
|
||||
let (mut changed, mut unchanged, mut errors, mut cached) = (0usize, 0usize, 0usize, 0usize);
|
||||
for (index, result) in results.into_iter().enumerate() {
|
||||
let (file, config) = &jobs[index];
|
||||
let (file, config, _) = &jobs[index];
|
||||
if let Some(content) = result.clean {
|
||||
cache.record(file, entry_for(content, config));
|
||||
}
|
||||
@@ -313,7 +335,7 @@ fn build_pool(opts: &Options) -> Result<(), String> {
|
||||
/// filelists name (exact paths, filtered by neither — they were named).
|
||||
/// Every config file is read here, before anything is written, so a broken
|
||||
/// one aborts the whole run instead of leaving it half applied.
|
||||
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
|
||||
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String> {
|
||||
let mut discovery = Discovery::new(!opts.no_config);
|
||||
let mut files = Vec::new();
|
||||
for input in &opts.inputs {
|
||||
@@ -337,8 +359,13 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
|
||||
}
|
||||
let mut jobs = Vec::with_capacity(files.len());
|
||||
for file in files {
|
||||
let config = opts.config_with(&discovery.for_file(&file)?);
|
||||
jobs.push((file, config));
|
||||
// The whole `FileConfig` rides along, not just the formatter settings
|
||||
// it resolves to: `lucisv check` needs its `[lint]` keys too, and
|
||||
// discovering them a second time would read every config file twice
|
||||
// and could answer differently if one changed underneath the run.
|
||||
let file_config = discovery.for_file(&file)?;
|
||||
let config = opts.config_with(&file_config);
|
||||
jobs.push((file, config, file_config));
|
||||
}
|
||||
Ok(jobs)
|
||||
}
|
||||
|
||||
+194
-1
@@ -662,7 +662,7 @@ fn a_broken_config_exits_2_before_writing_anything() {
|
||||
for (contents, expected) in [
|
||||
("indent = 99\n", "between 1 and 8"),
|
||||
("line-length = wide\n", "expects an integer"),
|
||||
("[tool.lucisv]\nindent = 2\n", "tables"),
|
||||
("[tool.lucisv]\nindent = 2\n", "unknown table"),
|
||||
("exclude = [\n \"a\",\n]\n", "multi-line arrays are unsupported"),
|
||||
] {
|
||||
dir.write("lucisv.toml", contents);
|
||||
@@ -1727,3 +1727,196 @@ fn help_documents_the_filelist_flag() {
|
||||
assert!(text.contains("-f <FILELIST>"), "{text}");
|
||||
assert!(text.contains("read by lucisv-server only"), "the toml key stays server-only: {text}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The semantic rules and the project census (semantic-lints-on, 2026-09-02)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A module whose `dbg_probe` only a *second* file reads, hierarchically.
|
||||
const DUT: &str = "module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n";
|
||||
const TB: &str = "module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n";
|
||||
|
||||
/// The round's headline: over a project the semantic rules run by default,
|
||||
/// and the file that reads `d.dbg_probe` is what keeps `dbg_probe` quiet.
|
||||
/// `dead`, which nothing anywhere writes down twice, is still reported.
|
||||
#[test]
|
||||
fn a_mention_in_another_file_silences_unused_signal_over_a_project() {
|
||||
let dir = TempDir::new("census");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("`dead` is declared but never used"), "{text}");
|
||||
assert!(!text.contains("dbg_probe"), "the other file reads it: {text}");
|
||||
assert_eq!(code(&out), 1);
|
||||
}
|
||||
|
||||
/// One file is not a project: there is nothing to ask, so the rules that
|
||||
/// need a workspace stay off and the run is exactly v0.29.0's.
|
||||
#[test]
|
||||
fn a_single_file_run_leaves_the_semantic_rules_off() {
|
||||
let dir = TempDir::new("alone");
|
||||
let dut = dir.write("dut.sv", DUT);
|
||||
let out = run(&["check", &dut]);
|
||||
assert_eq!(stdout(&out), "");
|
||||
assert_eq!(code(&out), 0);
|
||||
|
||||
// ... and naming the rule still runs it, oracle or no oracle.
|
||||
let named = run(&["check", &dut, "--select", "unused-signal"]);
|
||||
let text = stdout(&named);
|
||||
assert!(text.contains("dbg_probe"), "{text}");
|
||||
assert!(text.contains("dead"), "{text}");
|
||||
assert_eq!(code(&named), 1);
|
||||
}
|
||||
|
||||
/// A stdin buffer has no project either, and no file to build one from.
|
||||
#[test]
|
||||
fn a_stdin_buffer_leaves_the_semantic_rules_off() {
|
||||
let out = run_with_stdin(&["check", "-"], DUT);
|
||||
assert_eq!(stdout(&out), "");
|
||||
assert_eq!(code(&out), 0);
|
||||
let named = run_with_stdin(&["check", "-", "--select", "unused-signal"], DUT);
|
||||
assert!(stdout(&named).contains("dbg_probe"), "{}", stdout(&named));
|
||||
}
|
||||
|
||||
/// The off switch a default-on rule owes its users: `[lint] ignore` in the
|
||||
/// `lucisv.toml` governing the files.
|
||||
#[test]
|
||||
fn a_lint_table_in_the_config_turns_a_rule_off() {
|
||||
let dir = TempDir::new("lint-table");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert_eq!(stdout(&out), "", "the config silenced the rule");
|
||||
assert_eq!(code(&out), 0);
|
||||
}
|
||||
|
||||
/// `[lint] select` replaces the default set, exactly as `--select` does.
|
||||
#[test]
|
||||
fn a_lint_table_can_select_instead_of_ignore() {
|
||||
let dir = TempDir::new("lint-select");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
dir.write("lucisv.toml", "[lint]\nselect = [\"unused-signal\"]\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("`dead` is declared but never used"), "{text}");
|
||||
assert!(!text.contains("dbg_probe"), "{text}");
|
||||
}
|
||||
|
||||
/// Precedence, key by key: the command line beats the config file, and a key
|
||||
/// the command line does not mention stays the config file's.
|
||||
#[test]
|
||||
fn the_command_line_beats_the_lint_table() {
|
||||
let dir = TempDir::new("lint-precedence");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
|
||||
// `--ignore` replaces the config's ignore list, so `unused-signal` is back.
|
||||
let out = run(&["check", &dir.root(), "--ignore", "no-tabs"]);
|
||||
assert!(stdout(&out).contains("`dead` is declared but never used"), "{}", stdout(&out));
|
||||
// `--select` replaces the default set; the config's ignore still applies.
|
||||
let selected = run(&["check", &dir.root(), "--select", "unused-signal,no-tabs"]);
|
||||
assert_eq!(stdout(&selected), "", "the config's ignore survives a CLI select");
|
||||
}
|
||||
|
||||
/// An unknown rule name in a config file fails the run and says what is
|
||||
/// known — the same answer a typo'd `--select` gets, named by file.
|
||||
#[test]
|
||||
fn an_unknown_rule_in_the_lint_table_is_an_error() {
|
||||
let dir = TempDir::new("lint-unknown");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("tb.sv", TB);
|
||||
dir.write("lucisv.toml", "[lint]\nignore = [\"no-such-rule\"]\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stderr(&out);
|
||||
assert!(text.contains("unknown rule: no-such-rule"), "{text}");
|
||||
assert!(text.contains("unused-signal"), "the error lists what is known: {text}");
|
||||
assert_eq!(code(&out), 2);
|
||||
}
|
||||
|
||||
/// Per-rule tables are named rather than silently ignored, so a user who
|
||||
/// writes one finds out it does nothing yet.
|
||||
#[test]
|
||||
fn a_per_rule_lint_table_is_refused_by_name() {
|
||||
let dir = TempDir::new("lint-per-rule");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("lucisv.toml", "[lint.unused-signal]\nignore = \"tmp_*\"\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert!(stderr(&out).contains("per-rule lint settings"), "{}", stderr(&out));
|
||||
assert_eq!(code(&out), 2);
|
||||
}
|
||||
|
||||
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
|
||||
/// RTL signal only inside a macro argument — `` `uvm_info(..., $sformatf("%b",
|
||||
/// dut.sig), ...) ``, the commonest VPI-probe shape there is — must silence
|
||||
/// `unused-signal` for that signal. The lexer hands the whole invocation over
|
||||
/// as one token, so this works only because the census splits it.
|
||||
#[test]
|
||||
fn a_signal_named_only_inside_a_macro_argument_is_not_reported_unused() {
|
||||
let dir = TempDir::new("macroarg");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write(
|
||||
"tb.sv",
|
||||
"module tb;\n dut u_dut ();\n initial begin\n\
|
||||
\x20 `uvm_info(\"tb\", $sformatf(\"probe=%b\", u_dut.dbg_probe), UVM_LOW)\n\
|
||||
\x20 end\nendmodule\n",
|
||||
);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stdout(&out);
|
||||
assert!(!text.contains("dbg_probe"), "the macro argument names it: {text}");
|
||||
assert!(text.contains("`dead` is declared but never used"), "and `dead` still reports: {text}");
|
||||
// The format string is a value: a signal called `probe` in another file
|
||||
// must not be silenced by `"probe=%b"` here.
|
||||
let other = TempDir::new("macroargstring");
|
||||
other.write("a.sv", "module a;\n logic probe;\nendmodule\n");
|
||||
other.write(
|
||||
"b.sv",
|
||||
"module b;\n initial `uvm_info(\"t\", $sformatf(\"probe=%b\", 1'b0), UVM_LOW)\nendmodule\n",
|
||||
);
|
||||
assert!(
|
||||
stdout(&run(&["check", &other.root()])).contains("`probe` is declared but never used"),
|
||||
"a string's contents are not mentions"
|
||||
);
|
||||
}
|
||||
|
||||
/// `lucisv check --rules-doc` prints the generated rule reference and nothing
|
||||
/// else. Generated from the registry, so a rule added without documentation
|
||||
/// still shows up here — which is the whole point of the flag.
|
||||
#[test]
|
||||
fn rules_doc_prints_the_generated_reference() {
|
||||
let out = run(&["check", "--rules-doc"]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
let text = stdout(&out);
|
||||
assert_eq!(text.lines().next(), Some("# lucisv lint rules"), "{text}");
|
||||
for rule in vlog_linter::all_rules() {
|
||||
let heading = format!("\n## {}\n", rule.name());
|
||||
assert_eq!(
|
||||
text.matches(&heading).count(),
|
||||
1,
|
||||
"`{}` wants exactly one section in the reference",
|
||||
rule.name()
|
||||
);
|
||||
}
|
||||
// The flag is the tool now, so it agrees with the library by construction.
|
||||
assert_eq!(text, vlog_linter::rules_markdown());
|
||||
}
|
||||
|
||||
/// The flag lints nothing, so a path beside it is a command line that means
|
||||
/// two different things — refused rather than silently ignored.
|
||||
#[test]
|
||||
fn rules_doc_refuses_files_and_belongs_to_check() {
|
||||
let dir = TempDir::new("rulesdoc");
|
||||
let file = dir.write("m.sv", FORMATTED);
|
||||
let out = run(&["check", "--rules-doc", &file]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("--rules-doc takes no files"), "{}", stderr(&out));
|
||||
let out = run(&["format", "--rules-doc"]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(
|
||||
stderr(&out).contains("--rules-doc is only valid for `lucisv check`"),
|
||||
"{}",
|
||||
stderr(&out)
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
|
||||
//!
|
||||
//! Only what a three-key config file needs is supported (comments,
|
||||
//! `key = int`, `key = "string"`, `key = ["a", "b"]`); everything else is
|
||||
//! rejected by name rather than ignored. See
|
||||
//! Only what a small config file needs is supported (comments, `key = int`,
|
||||
//! `key = "string"`, `key = ["a", "b"]`, and the single table `[lint]`);
|
||||
//! everything else is rejected by name rather than ignored. See
|
||||
//! `docs/features/config-discovery/README.md` for the grammar and the
|
||||
//! reasoning behind not taking a TOML dependency.
|
||||
|
||||
@@ -29,6 +29,13 @@ pub struct FileConfig {
|
||||
/// directory, so every `FileConfig` a `Discovery` hands out carries a
|
||||
/// usable path. See `docs/features/filelist/README.md`.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// `[lint] select`: run exactly these rules, replacing the default set.
|
||||
/// The names are **not** validated here — this crate does not know the
|
||||
/// rule registry; `lucisv check` validates them the moment it resolves the
|
||||
/// run's rules, with the same error a bad `--select` gets.
|
||||
pub lint_select: Option<Vec<String>>,
|
||||
/// `[lint] ignore`: rules dropped from whatever `select` left.
|
||||
pub lint_ignore: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
|
||||
@@ -38,19 +45,36 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
|
||||
// Editors on some platforms prepend a BOM; it would otherwise garble
|
||||
// key matching on line 1 into an `unknown key` with invisible cause.
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
// Which table the keys below belong to. There is exactly one table, so
|
||||
// this is a flag rather than a path: `[lint]` opens it and nothing closes
|
||||
// it, which is TOML's own rule.
|
||||
let mut in_lint = false;
|
||||
for (index, raw) in text.lines().enumerate() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
parse_entry(line, &mut config).map_err(|e| format!("{}: {e}", index + 1))?;
|
||||
parse_entry(line, &mut config, &mut in_lint).map_err(|e| format!("{}: {e}", index + 1))?;
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Result<(), String> {
|
||||
if line.starts_with('[') {
|
||||
return Err("tables (`[section]`) are unsupported in lucisv.toml".to_string());
|
||||
// `[lint]` is the one table lucisv reads. `[lint.<rule>]` — per-rule
|
||||
// settings — is named in the error rather than ignored, so a user who
|
||||
// writes one finds out it is not supported yet instead of wondering
|
||||
// why it did nothing (topo §2.9-4 keeps the per-rule half open).
|
||||
if line == "[lint]" {
|
||||
*in_lint = true;
|
||||
return Ok(());
|
||||
}
|
||||
if line.starts_with("[lint.") {
|
||||
return Err(format!(
|
||||
"per-rule lint settings (`{line}`) are not supported yet; `[lint]` takes `select` and `ignore`"
|
||||
));
|
||||
}
|
||||
return Err(format!("unknown table `{line}` (the only table is `[lint]`)"));
|
||||
}
|
||||
let (key, value) =
|
||||
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
|
||||
@@ -59,6 +83,9 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
if value.is_empty() {
|
||||
return Err(format!("`{key}` has no value"));
|
||||
}
|
||||
if *in_lint {
|
||||
return parse_lint_entry(key, value, config);
|
||||
}
|
||||
match key {
|
||||
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
|
||||
"indent" => set_int(&mut config.indent, key, value, 1, 8),
|
||||
@@ -76,12 +103,29 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
config.filelist = Some(PathBuf::from(parse_string(value)?));
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
Err(format!("unknown key `{key}` (known keys: line-length, indent, exclude, filelist)"))
|
||||
}
|
||||
_ => Err(format!(
|
||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
||||
and select, ignore under `[lint]`)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[lint]` table.
|
||||
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
let slot = match key {
|
||||
"select" => &mut config.lint_select,
|
||||
"ignore" => &mut config.lint_ignore,
|
||||
_ => {
|
||||
return Err(format!("unknown key `{key}` under `[lint]` (known keys: select, ignore)"))
|
||||
}
|
||||
};
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
*slot = Some(parse_array(value)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_int(
|
||||
slot: &mut Option<usize>,
|
||||
key: &str,
|
||||
@@ -366,7 +410,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
|
||||
#[test]
|
||||
fn unsupported_toml_is_named_not_ignored() {
|
||||
assert!(err("[tool.lucisv]\nindent = 2").contains("tables"));
|
||||
assert!(err("[tool.lucisv]\nindent = 2").contains("unknown table"));
|
||||
assert!(err("exclude = [\n \"a\",\n]").contains("multi-line arrays are unsupported"));
|
||||
assert!(err("exclude = [\"a\\tb\"]").contains("escapes"));
|
||||
assert!(err("indent").contains("expected `key = value`"));
|
||||
@@ -376,6 +420,46 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
fn duplicate_keys_are_rejected() {
|
||||
assert!(err("indent = 2\nindent = 4").contains("duplicate key `indent`"));
|
||||
assert!(err("exclude = []\nexclude = []").contains("duplicate key `exclude`"));
|
||||
assert!(
|
||||
err("[lint]\nignore = [\"a\"]\nignore = [\"b\"]").contains("duplicate key `ignore`")
|
||||
);
|
||||
}
|
||||
|
||||
/// The `[lint]` table: the off switch a round that turns rules on by
|
||||
/// default owes its users (topo §2.9-4).
|
||||
#[test]
|
||||
fn the_lint_table_carries_select_and_ignore() {
|
||||
let config =
|
||||
parse("[lint]\nselect = [\"no-tabs\", \"unused-signal\"]\nignore = [\"no-tabs\"]")
|
||||
.expect("parses");
|
||||
assert_eq!(
|
||||
config.lint_select.as_deref(),
|
||||
Some(&["no-tabs".to_string(), "unused-signal".to_string()][..])
|
||||
);
|
||||
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
|
||||
// Both are absent unless written, and the formatter keys still work
|
||||
// above the table.
|
||||
let mixed = parse("indent = 4\n\n[lint]\nignore = [\"unused-signal\"]").expect("parses");
|
||||
assert_eq!(mixed.indent, Some(4));
|
||||
assert_eq!(mixed.lint_select, None);
|
||||
assert_eq!(parse("indent = 4").expect("parses").lint_ignore, None);
|
||||
}
|
||||
|
||||
/// Rule *names* are not this crate's business — it has no registry to
|
||||
/// check them against — but everything about the table's shape is.
|
||||
#[test]
|
||||
fn the_lint_table_rejects_what_it_does_not_support() {
|
||||
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
|
||||
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
|
||||
assert!(err("[lint.no-tabs]\nseverity = \"error\"").contains("per-rule lint settings"));
|
||||
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
|
||||
// A key before any table still belongs to the top level.
|
||||
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
|
||||
// Nothing closes the table — TOML's own rule, spelled out.
|
||||
assert_eq!(
|
||||
parse("[lint]\nselect = [\"no-tabs\"]").expect("parses").lint_select.as_deref(),
|
||||
Some(&["no-tabs".to_string()][..])
|
||||
);
|
||||
}
|
||||
|
||||
/// A throwaway directory tree under the system temp dir.
|
||||
|
||||
@@ -32,9 +32,8 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::tokenize;
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_semantic::{words, SymbolKind, WorkspaceIndex};
|
||||
|
||||
/// One name the workspace index knows, flattened for lookup.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -333,6 +332,15 @@ impl Candidates {
|
||||
matching(&self.macros, prefix, |m| &m.name)
|
||||
}
|
||||
|
||||
/// Whether the workspace `` `define``s this exact name.
|
||||
///
|
||||
/// Asked by [`Candidates::words_scan`] so the word tier does not offer a
|
||||
/// macro name as a plain word. The table is sorted by [`word_cmp`], which
|
||||
/// is a total order, so this is a binary search.
|
||||
fn has_macro(&self, name: &str) -> bool {
|
||||
self.macros.binary_search_by(|held| word_cmp(&held.name, name)).is_ok()
|
||||
}
|
||||
|
||||
/// Project words starting with `prefix`, case-insensitively.
|
||||
pub fn words(&self, prefix: &str) -> &[String] {
|
||||
matching(&self.words, prefix, |w| w.as_str())
|
||||
@@ -362,6 +370,17 @@ impl Candidates {
|
||||
|
||||
/// The best `cap` project words holding `query`'s characters in order.
|
||||
///
|
||||
/// A word the workspace `` `define``s is **not** offered here. Since
|
||||
/// 2026-09-02 the census splits a directive line into its words, so a
|
||||
/// `` `define FOO `` puts `FOO` in the word table; the macro tier already
|
||||
/// offers that name and does so **by prefix only**, which is
|
||||
/// fuzzy-completion's own ruling (`the_keyword_template_macro_and_module_
|
||||
/// tiers_did_not_go_fuzzy`). Letting the word tier reach it by
|
||||
/// subsequence would overturn that decision by a side door. The *census*
|
||||
/// keeps the word — it is a name the file writes down, which is the
|
||||
/// question `WorkspaceIndex::files_mentioning` answers — so this is a
|
||||
/// filter on one reader, not a second harvest.
|
||||
///
|
||||
/// The fuzzy sibling of [`Candidates::words`], and the one lookup here
|
||||
/// whose cost is worth stating: an unfiltered scan of opentitan's hundred
|
||||
/// thousand words is milliseconds, which no keystroke can afford, and the
|
||||
@@ -392,6 +411,9 @@ impl Candidates {
|
||||
continue;
|
||||
}
|
||||
survivors += 1;
|
||||
if self.has_macro(word) {
|
||||
continue;
|
||||
}
|
||||
if let Some(score) = query.score(word) {
|
||||
hits.push((word.as_str(), score));
|
||||
}
|
||||
@@ -715,21 +737,20 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
|
||||
/// Every distinct identifier one file's token stream contains.
|
||||
///
|
||||
/// Deduplicated as it is collected, not afterwards: a workspace holds two
|
||||
/// orders of magnitude more identifier *tokens* than distinct identifiers
|
||||
/// (900k against 17k over this repo's corpus), and copying every one of them
|
||||
/// only to sort the copies away costs more than the lexing does.
|
||||
/// **`vlog_semantic::words::harvest_text`, under this crate's old name.** The
|
||||
/// harvest moved out of the server on 2026-09-02 so the completion word table
|
||||
/// and the index's per-file census are one answer rather than two that must be
|
||||
/// kept equal by hand — the semantic lint rules read the census as "does any
|
||||
/// other file mention this name", and a completion list that disagreed with a
|
||||
/// lint finding about what a file contains would be a bug nobody could see.
|
||||
/// See `docs/features/semantic-lints-on/README.md`.
|
||||
///
|
||||
/// `pub(crate)` because a scan lexes each file as it reaches it rather than in
|
||||
/// one pass at the end: no part of a scan may be longer than one file, or the
|
||||
/// message queue goes unanswered for the length of it
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
pub(crate) fn words_in(text: &str) -> Vec<String> {
|
||||
// A file that does not lex contributes nothing rather than being guessed
|
||||
// at with a regex — the same all-or-nothing rule the lexer gives every
|
||||
// other consumer.
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
words_of_tokens(&tokens)
|
||||
words::harvest_text(text)
|
||||
}
|
||||
|
||||
/// [`words_in`] over a token stream the caller already lexed.
|
||||
@@ -739,29 +760,7 @@ pub(crate) fn words_in(text: &str) -> Vec<String> {
|
||||
/// did not lex holds no tokens and contributes nothing here either, which is
|
||||
/// the same all-or-nothing rule from the other side.
|
||||
pub(crate) fn words_of_tokens(tokens: &[Token]) -> Vec<String> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
|
||||
if !seen.contains(token.text.as_str()) {
|
||||
seen.insert(token.text.clone());
|
||||
}
|
||||
}
|
||||
seen.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Whether a token is a word worth offering.
|
||||
///
|
||||
/// `Ident` and `SystemIdent` only, so a comment (lexer trivia) and a string
|
||||
/// literal (one `String` token) can never contribute. Two `Ident` shapes are
|
||||
/// dropped:
|
||||
///
|
||||
/// * a **macro usage** (`` `WIDTH ``) — the text is the whole invocation,
|
||||
/// argument list and all, and the macro *names* have their own table;
|
||||
/// * an **escaped identifier** (`\my-port`) — inserting one needs a trailing
|
||||
/// space to terminate it, which a plain word item has no way to promise.
|
||||
fn is_word(kind: TokenKind, text: &str) -> bool {
|
||||
matches!(kind, TokenKind::Ident | TokenKind::SystemIdent)
|
||||
&& !text.starts_with('`')
|
||||
&& !text.starts_with('\\')
|
||||
words::harvest(tokens)
|
||||
}
|
||||
|
||||
/// Sort by name, case-insensitively first so [`matching`]'s binary search is
|
||||
@@ -1033,6 +1032,36 @@ mod tests {
|
||||
assert!(candidates.words("").len() >= 2, "at least `p` and `K`");
|
||||
}
|
||||
|
||||
/// The 2026-09-02 amendment, from both sides. The word table takes the
|
||||
/// census whole — including the names inside a macro invocation, which is
|
||||
/// how a UVM testbench writes down the RTL signal it reads — and subtracts
|
||||
/// exactly one thing: a name the workspace `` `define``s, which the macro
|
||||
/// tier owns and offers by prefix only.
|
||||
#[test]
|
||||
fn macro_argument_words_are_offered_and_macro_names_are_left_to_their_own_tier() {
|
||||
let candidates = built(&[
|
||||
("/dv/defs.svh", "`define CHECK_IT(a) assert (a)
|
||||
"),
|
||||
(
|
||||
"/dv/tb.sv",
|
||||
"module tb;\n dut u_dut ();\n \x20 `CHECK_IT(u_dut.dbg_probe == other_word)\nendmodule\n",
|
||||
),
|
||||
]);
|
||||
let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect();
|
||||
assert!(names.contains(&"dbg_probe"), "a macro argument is code: {names:?}");
|
||||
assert!(names.contains(&"other_word"), "{names:?}");
|
||||
// The census holds the macro name too — it is a word the file writes
|
||||
// down, and `files_mentioning` must say so ...
|
||||
assert!(names.contains(&"CHECK_IT"), "the table keeps it: {names:?}");
|
||||
// ... but the fuzzy word tier does not offer it, because the macro
|
||||
// tier does, by prefix, and that is fuzzy-completion's ruling.
|
||||
let query = Query::new("chckit");
|
||||
let fuzzy: Vec<&str> =
|
||||
candidates.words_fuzzy(&query, 20).into_iter().map(|(w, _)| w).collect();
|
||||
assert!(!fuzzy.contains(&"CHECK_IT"), "the macro tier owns it: {fuzzy:?}");
|
||||
assert!(candidates.macros("CHECK").iter().any(|m| m.name == "CHECK_IT"), "premise");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_lex_contributes_nothing_and_does_not_stop_the_rest() {
|
||||
let candidates = built(&[
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,114 @@
|
||||
//! The completion tests' harness: a scratch workspace on disk, and the
|
||||
//! handful of helpers every provider's tests ask through.
|
||||
//!
|
||||
//! `#[cfg(test)]` only; the tests themselves sit at the foot of the file
|
||||
//! whose code they pin.
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
pub(super) const SUB: &str = "\
|
||||
module sub #(
|
||||
parameter int WIDTH = 8
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [WIDTH-1:0] data,
|
||||
output logic ready
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
pub(super) struct Tree {
|
||||
pub(super) path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
pub(super) fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_completion_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
pub(super) fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// A two-file workspace with `top.sv` open, and the cursor at `needle`'s
|
||||
/// end. `sub.sv` declares [`SUB`].
|
||||
pub(super) fn asking(name: &str, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", SUB);
|
||||
opened(tree, top, needle)
|
||||
}
|
||||
|
||||
/// The same, with whatever `tree` already holds and no `sub.sv` implied.
|
||||
pub(super) fn opened(tree: Tree, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
|
||||
opened_named(tree, "top.sv", top, needle)
|
||||
}
|
||||
|
||||
/// The same again, with the buffer's file name spelled out — which is what
|
||||
/// decides its dialect.
|
||||
pub(super) fn opened_named(
|
||||
tree: Tree,
|
||||
file: &str,
|
||||
top: &str,
|
||||
needle: &str,
|
||||
) -> (Tree, Workspace, Uri, Position) {
|
||||
let path = tree.write(file, top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let position = doc.positions().position(offset);
|
||||
(tree, ws, uri, position)
|
||||
}
|
||||
|
||||
pub(super) fn items(response: Option<CompletionResponse>) -> Vec<CompletionItem> {
|
||||
match response {
|
||||
Some(CompletionResponse::List(list)) => list.items,
|
||||
Some(CompletionResponse::Array(items)) => items,
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn inserted(item: &CompletionItem) -> String {
|
||||
match item.text_edit.as_ref().expect("a text edit") {
|
||||
CompletionTextEdit::Edit(edit) => edit.new_text.clone(),
|
||||
CompletionTextEdit::InsertAndReplace(edit) => edit.new_text.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tier an item was filed under, read off its `sortText`.
|
||||
pub(super) fn tier(item: &CompletionItem) -> char {
|
||||
item.sort_text.as_ref().and_then(|s| s.chars().next()).expect("every item is sorted")
|
||||
}
|
||||
|
||||
/// Only the module skeletons — tier 0, the M4 items.
|
||||
pub(super) fn skeletons(items: &[CompletionItem]) -> Vec<&CompletionItem> {
|
||||
items.iter().filter(|item| tier(item) == TIER_MODULE).collect()
|
||||
}
|
||||
|
||||
pub(super) fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a CompletionItem> {
|
||||
items.iter().find(|item| item.label == label)
|
||||
}
|
||||
|
||||
pub(super) fn labels(items: &[CompletionItem]) -> Vec<&str> {
|
||||
items.iter().map(|item| item.label.as_str()).collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,837 @@
|
||||
//! `textDocument/completion` — module hinting, templates, keywords, and every
|
||||
//! name the project uses.
|
||||
//!
|
||||
//! One response, six tiers, ordered by `sortText`:
|
||||
//!
|
||||
//! 0. **module names** — at module-item position only, every module the
|
||||
//! workspace declares whose name contains what is typed. The item inserts
|
||||
//! the **name alone**; the instantiation follows as ghost text once the
|
||||
//! name is spelled exactly and a space follows it (`inline.rs`,
|
||||
//! 2026-08-30);
|
||||
//! 1. **what is visible here** — the declarations the scope chain at the
|
||||
//! cursor binds, from this file's `Semantics`;
|
||||
//! 2. **what the project declares** — packages, their members, typedefs,
|
||||
//! classes, modules and `` `define`` names, from the workspace index;
|
||||
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
||||
//! tabstops, offered only where the construct may be written;
|
||||
//! 4. **keywords** — every reserved word `vlog_parser` knows;
|
||||
//! 5. **project words** — every identifier the in-scope files' *token
|
||||
//! streams* contain, the rope/VS Code word-completion tier.
|
||||
//!
|
||||
//! A name is offered once, by the highest tier that claims it. Nothing is
|
||||
//! offered inside a comment or a string literal, and nothing that only ever
|
||||
//! appears inside one is ever a candidate — see `candidates.rs`.
|
||||
//!
|
||||
//! **Every tier is a table lookup.** No request here reads a file or parses
|
||||
//! one, which is what makes the answer affordable on a keystroke in a
|
||||
//! workspace the size of opentitan. The planning half of the old tier 0 —
|
||||
//! [`plan_for`] and [`module_header`](module::module_header), still here
|
||||
//! because they are still the way an instantiation is planned — is now called by `inline.rs` for exactly
|
||||
//! one module, once the user has spelled its whole name and typed the space
|
||||
//! that says so.
|
||||
//!
|
||||
//! See `docs/features/completion-core/README.md`, for tier 0
|
||||
//! `docs/features/inline-instantiation/README.md` and
|
||||
//! `docs/features/refactor-instantiate/README.md`, and for tier 3
|
||||
//! `docs/features/completion-templates/README.md`.
|
||||
//!
|
||||
//! The module is one directory: this file is the entry point, the response
|
||||
//! under construction (`Items`) and the small helpers every tier shares; the
|
||||
//! rest is one file per answer, in the order `completions` consults them:
|
||||
//!
|
||||
//! * `word` — what is typed: the identifier run at the cursor, the backtick
|
||||
//! or the `.`/`::` before it, and the spine a separator follows;
|
||||
//! * `site` — what may be written here: the module-item and statement gates
|
||||
//! over the token stream's scope chain;
|
||||
//! * `member` — the exclusive answer after a `.` or a `::`, the connection
|
||||
//! list included;
|
||||
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
|
||||
//! `instantiate.rs` share;
|
||||
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
|
||||
//! the response.
|
||||
//!
|
||||
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
|
||||
//! entry points other modules of the crate use keep their paths through the
|
||||
//! re-exports below. Each file's tests sit at its foot, on the harness in
|
||||
//! `harness.rs`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::{
|
||||
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
|
||||
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
|
||||
TextEdit, Uri,
|
||||
};
|
||||
use vlog_parser::token::{Comment, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Symbol, SymbolKind};
|
||||
|
||||
use crate::candidates::Query;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::Template;
|
||||
use member::member_answer;
|
||||
use module::module_tier;
|
||||
use site::{at_module_item, at_statement, enclosing_scopes};
|
||||
use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier};
|
||||
use word::typed_word;
|
||||
|
||||
pub(crate) use module::{nearest_definition, plan_for};
|
||||
// `perf.rs`, the one caller outside this module, is itself test-only; an
|
||||
// unconditional re-export would be an unused import in every other build.
|
||||
#[cfg(test)]
|
||||
pub(crate) use module::module_header;
|
||||
pub(crate) use site::at_instantiation_site;
|
||||
pub(crate) use tiers::layout_at;
|
||||
|
||||
#[cfg(test)]
|
||||
mod harness;
|
||||
mod member;
|
||||
mod module;
|
||||
mod site;
|
||||
mod tiers;
|
||||
mod word;
|
||||
|
||||
/// How many items one response carries, over every tier.
|
||||
///
|
||||
/// Large enough that an *empty* prefix still reaches the last tier — 64
|
||||
/// modules plus 181 keywords plus what one scope binds leaves room — and small
|
||||
/// enough to bound the payload at a few tens of kilobytes. Tiers fill in
|
||||
/// order, so a truncated list loses the least useful end of it and comes back
|
||||
/// `isIncomplete`: the protocol's way of saying "ask me again when you have
|
||||
/// typed more".
|
||||
const LIMIT: usize = 512;
|
||||
|
||||
/// How many characters must be typed before a name may match by
|
||||
/// *subsequence* rather than by prefix.
|
||||
///
|
||||
/// **VS Code's own rule**, which is the whole policy of this round: below
|
||||
/// three characters its widget filters what it holds by prefix, and so does
|
||||
/// the server; from three up both match by subsequence, so `clkenq` reaches
|
||||
/// `clk_osc_en_q`. Matching the client is the point — a server that went
|
||||
/// fuzzy at one character would answer a question the widget then filtered the
|
||||
/// answer to, and one that never went fuzzy is what this round is fixing.
|
||||
///
|
||||
/// The floor is not only manners. A one-character fuzzy query matches most of
|
||||
/// a workspace, which is a list nobody can read, and it is the one query the
|
||||
/// character-mask prefilter cannot help with at all — one bit wide, it rejects
|
||||
/// nothing, so the whole table is scanned. Measured at 2.7 ms over the real
|
||||
/// opentitan word list against the 0.05 ms `clkenq` costs.
|
||||
///
|
||||
/// See `docs/features/fuzzy-completion/README.md`.
|
||||
const FUZZY_MIN: usize = 3;
|
||||
|
||||
/// `sortText` prefixes. The client sorts on these, so they *are* the tier
|
||||
/// order; the name follows so each tier is alphabetical within itself.
|
||||
const TIER_MODULE: char = '0';
|
||||
/// Members, after a `.` or a `::`.
|
||||
///
|
||||
/// The same digit as tier 0 and not a contradiction: the member answer is
|
||||
/// **exclusive**, so no other tier's item is ever in the same response and
|
||||
/// the digit orders members among themselves and nothing else. `'0'` because
|
||||
/// these are not one tier of an answer but the whole of it. A sixth digit
|
||||
/// would say there is a ranking against the other tiers to express, and there
|
||||
/// is not.
|
||||
const TIER_MEMBER: char = '0';
|
||||
const TIER_SCOPE: char = '1';
|
||||
const TIER_INDEX: char = '2';
|
||||
const TIER_TEMPLATE: char = '3';
|
||||
const TIER_KEYWORD: char = '4';
|
||||
const TIER_WORD: char = '5';
|
||||
|
||||
/// What a multi-line item tells the client about its own whitespace.
|
||||
///
|
||||
/// Every skeleton here is laid out at the *site's* indentation already: a
|
||||
/// `Layout`'s `base` is the trigger line's leading whitespace, and every line
|
||||
/// after the first carries it. An editor that "helpfully" indents the
|
||||
/// insertion again would double it — VS Code's `SnippetSession.adjustWhitespace`
|
||||
/// prepends the insertion line's own indentation to every line after the first,
|
||||
/// and it is on by default (`SuggestController._insertSuggestion` passes
|
||||
/// `adjustWhitespace: !(insertTextRules & KeepWhitespace)`). `asIs` is the
|
||||
/// protocol's way of saying "the text is already positioned, do not touch it",
|
||||
/// and `vscode-languageclient` turns it into exactly the `keepWhitespace` flag
|
||||
/// that clears the rule. Single-line items neither need it nor are harmed by
|
||||
/// it; only the two tiers that write more than one line send it.
|
||||
///
|
||||
/// This is the sibling of the fix `inline.rs` had to make differently: an
|
||||
/// inline completion has no such field, so its bodies are *relative* instead.
|
||||
/// See `docs/features/inline-templates/README.md`, 2026-08-25.
|
||||
const KEEP_MY_INDENTATION: InsertTextMode = InsertTextMode::AS_IS;
|
||||
|
||||
/// The completions available at a position, or nothing when the cursor is
|
||||
/// somewhere no name may be written.
|
||||
///
|
||||
/// `snippets` is what the client advertised: without it a module skeleton is
|
||||
/// inserted as plain text, because a literal `${1:clk}` left in a buffer is
|
||||
/// worse than no tabstops at all.
|
||||
pub fn completions(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
snippets: bool,
|
||||
) -> Option<CompletionResponse> {
|
||||
let doc = ws.document(uri)?;
|
||||
let offset = doc.positions().offset(position);
|
||||
// A buffer that does not lex has no token stream, so nothing here can tell
|
||||
// a comment from code — and the commonest way to break the lexer is to
|
||||
// open a string or a block comment and keep typing. Declining is the safe
|
||||
// half of that trade; the buffer lexes again as soon as it is closed.
|
||||
if doc.tokens.is_empty() || in_comment_or_string(doc, offset) {
|
||||
return None;
|
||||
}
|
||||
let word = typed_word(doc, offset)?;
|
||||
|
||||
// A backtick admits exactly one kind of name, so the answer is only that
|
||||
// kind — and the backtick already typed is inside the replaced range, so
|
||||
// it is never doubled.
|
||||
if word.backtick {
|
||||
// The backtick itself is replaced, so the item may carry its own.
|
||||
let replacing = TextRange::new(word.start.saturating_sub(1), offset);
|
||||
let mut items = Items::new(doc, replacing);
|
||||
for entry in ws.candidates().macros(&word.text) {
|
||||
items.simple(
|
||||
&format!("`{}", entry.name),
|
||||
CompletionItemKind::CONSTANT,
|
||||
TIER_INDEX,
|
||||
entry.detail.clone(),
|
||||
);
|
||||
}
|
||||
return items.finish();
|
||||
}
|
||||
|
||||
// A `.` or a `::` admits exactly one kind of name too — a member of what
|
||||
// stands before it — so the answer is only those. See [`member_answer`].
|
||||
if word.sep.is_some() {
|
||||
return member_answer(ws, doc, &word, offset);
|
||||
}
|
||||
|
||||
// Both position gates read the same scope chain, and neither can be true
|
||||
// unless the word starts a line — so a keystroke in the middle of an
|
||||
// expression pays for neither.
|
||||
let starts_a_line = word.at_line_start || word.statement_head;
|
||||
let chain = match starts_a_line {
|
||||
true => enclosing_scopes(&doc.tokens, word.start),
|
||||
false => Vec::new(),
|
||||
};
|
||||
let at_item = word.at_line_start && at_module_item(doc, &chain, word.start);
|
||||
let at_statement = starts_a_line && at_statement(doc, &chain, word.start);
|
||||
|
||||
// Prefix below [`FUZZY_MIN`], subsequence from it up. One `Query` for the
|
||||
// whole request: it folds the typed characters and computes their mask
|
||||
// once, and every tier that scans a table reads the same prepared form.
|
||||
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
|
||||
|
||||
let mut items = Items::new(doc, word.range(offset));
|
||||
module_tier(&mut items, ws, doc, &word, at_item);
|
||||
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
index_tier(&mut items, ws, &word, fuzzy.as_ref());
|
||||
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
|
||||
keyword_tier(&mut items, &word);
|
||||
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
|
||||
// **The `isIncomplete` trap.** VS Code asks the server again on the next
|
||||
// keystroke *only* when the last answer said it was incomplete; otherwise
|
||||
// it filters the list it already holds. A complete two-character prefix
|
||||
// answer would therefore be filtered client-side for the rest of the word,
|
||||
// and the third keystroke — the one that turns fuzzy on — would never
|
||||
// reach here at all. So every answer below the floor says it is
|
||||
// incomplete, whatever the cap did.
|
||||
//
|
||||
// Above the floor the ordinary rule stands, and is sound because the hit
|
||||
// set only ever *shrinks* as characters are appended: if a name holds
|
||||
// `clke` in order it holds `clk` in order, so a complete answer at three
|
||||
// characters really does contain every answer to four.
|
||||
if fuzzy.is_none() {
|
||||
items.incomplete = true;
|
||||
}
|
||||
items.finish()
|
||||
}
|
||||
|
||||
/// The response under construction: the items, the names already spoken for,
|
||||
/// and whether the cap cut anything off.
|
||||
struct Items {
|
||||
/// The bytes every item replaces, as the client reads them.
|
||||
range: Range,
|
||||
items: Vec<CompletionItem>,
|
||||
seen: HashSet<String>,
|
||||
incomplete: bool,
|
||||
}
|
||||
|
||||
impl Items {
|
||||
fn new(doc: &Document, replacing: TextRange) -> Items {
|
||||
Items {
|
||||
range: doc.positions().range(replacing),
|
||||
items: Vec::new(),
|
||||
seen: HashSet::new(),
|
||||
incomplete: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the cap has been reached. Once it has, every further candidate
|
||||
/// only sets [`Items::incomplete`] — which is why the tiers ask first
|
||||
/// rather than building items nobody will see.
|
||||
fn full(&mut self) -> bool {
|
||||
if self.items.len() >= LIMIT {
|
||||
self.incomplete = true;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Add an item, unless a higher tier already offered that name or the
|
||||
/// response is full.
|
||||
fn push(&mut self, item: CompletionItem) {
|
||||
if self.full() || !self.seen.insert(item.label.clone()) {
|
||||
return;
|
||||
}
|
||||
self.items.push(item);
|
||||
}
|
||||
|
||||
/// A plain-text item that inserts exactly its own name.
|
||||
fn simple(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
|
||||
if self.full() || self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
let item = CompletionItem {
|
||||
label: name.to_string(),
|
||||
kind: Some(kind),
|
||||
detail: Some(detail),
|
||||
sort_text: Some(format!("{tier}{name}")),
|
||||
insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
|
||||
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
||||
range: self.range,
|
||||
new_text: name.to_string(),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
/// One template: the skeleton it inserts, the word it is reached by, and
|
||||
/// the shape it expands to.
|
||||
///
|
||||
/// A client that never said it understands snippets gets the same text
|
||||
/// with every hole filled in rather than nothing at all — the M4 ruling,
|
||||
/// applied to a body whose defaults were chosen so that the result parses.
|
||||
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
|
||||
if self.full() || self.seen.contains(template.label) {
|
||||
return;
|
||||
}
|
||||
let item = CompletionItem {
|
||||
label: template.label.to_string(),
|
||||
kind: Some(CompletionItemKind::SNIPPET),
|
||||
detail: Some(format!("{} — template", template.detail)),
|
||||
documentation: Some(Documentation::MarkupContent(MarkupContent {
|
||||
kind: MarkupKind::Markdown,
|
||||
value: format!("```systemverilog\n{}\n```", template.expansion()),
|
||||
})),
|
||||
// The label is prose, so the client must be told what the user
|
||||
// types to reach the item — otherwise `if` would not match
|
||||
// `if begin/end` at all.
|
||||
filter_text: Some(template.prefix.to_string()),
|
||||
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
|
||||
insert_text_format: Some(match snippets {
|
||||
true => InsertTextFormat::SNIPPET,
|
||||
false => InsertTextFormat::PLAIN_TEXT,
|
||||
}),
|
||||
insert_text_mode: Some(KEEP_MY_INDENTATION),
|
||||
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
||||
range: self.range,
|
||||
new_text: template.render(layout, snippets),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
fn finish(self) -> Option<CompletionResponse> {
|
||||
if self.items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(self.into_list())
|
||||
}
|
||||
|
||||
/// The response whether or not anything is in it.
|
||||
///
|
||||
/// [`Items::finish`]'s `None` means "this was not my question", which is
|
||||
/// the right answer for a tiered response nobody filled. For the
|
||||
/// **exclusive** member answer an empty list is the answer — the site
|
||||
/// resolved and holds no matching member — and it has to be sent rather
|
||||
/// than declined, because `None` carries no `isIncomplete` and so cannot
|
||||
/// ask the client to come back with the third character.
|
||||
fn into_list(self) -> CompletionResponse {
|
||||
CompletionResponse::List(CompletionList {
|
||||
is_incomplete: self.incomplete,
|
||||
items: self.items,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The LSP icon a declaration gets in a completion list. The same choices
|
||||
/// `symbols::lsp_kind` makes for the outline, in the other enum.
|
||||
fn completion_kind(kind: SymbolKind) -> CompletionItemKind {
|
||||
match kind {
|
||||
SymbolKind::Module | SymbolKind::Package | SymbolKind::Block => CompletionItemKind::MODULE,
|
||||
SymbolKind::Interface | SymbolKind::Modport => CompletionItemKind::INTERFACE,
|
||||
SymbolKind::Clocking => CompletionItemKind::EVENT,
|
||||
SymbolKind::Port | SymbolKind::StructMember => CompletionItemKind::FIELD,
|
||||
SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar | SymbolKind::Instance => {
|
||||
CompletionItemKind::VARIABLE
|
||||
}
|
||||
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => {
|
||||
CompletionItemKind::CONSTANT
|
||||
}
|
||||
SymbolKind::Typedef => CompletionItemKind::TYPE_PARAMETER,
|
||||
SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER,
|
||||
SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION,
|
||||
SymbolKind::Class => CompletionItemKind::CLASS,
|
||||
SymbolKind::Constraint | SymbolKind::Coverpoint | SymbolKind::Cross => {
|
||||
CompletionItemKind::PROPERTY
|
||||
}
|
||||
SymbolKind::Covergroup => CompletionItemKind::CLASS,
|
||||
// A property and a sequence are named declarations a concurrent
|
||||
// assertion calls by name, so they take the icon a function does.
|
||||
SymbolKind::Property | SymbolKind::Sequence => CompletionItemKind::FUNCTION,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a visible declaration shows beside its name: the line it was declared
|
||||
/// on, which is the cheapest honest summary there is.
|
||||
fn declaration_detail(doc: &Document, symbol: &Symbol) -> String {
|
||||
let line = doc.positions().whole_lines(symbol.decl_span).lines().next().unwrap_or("").trim();
|
||||
match line.is_empty() {
|
||||
true => kind_label(symbol.kind).to_string(),
|
||||
false => shorten(line, 80),
|
||||
}
|
||||
}
|
||||
|
||||
/// `text`, cut to `max` characters on a character boundary.
|
||||
fn shorten(text: &str, max: usize) -> String {
|
||||
match text.char_indices().nth(max) {
|
||||
Some((at, _)) => format!("{}…", &text[..at]),
|
||||
None => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `offset` sits inside a comment or a string literal — the two places
|
||||
/// a completion list has no business appearing.
|
||||
///
|
||||
/// Comments are lexer trivia hanging off the token that follows (or precedes)
|
||||
/// them, so this reads both. A linear pass over the token stream: a scan of a
|
||||
/// few tens of thousands of tokens is tens of microseconds, and a binary
|
||||
/// search would have to reason about which token a comment attached to.
|
||||
fn in_comment_or_string(doc: &Document, offset: u32) -> bool {
|
||||
for token in &doc.tokens {
|
||||
if token.kind == TokenKind::String && token.span.start < offset && offset < token.span.end {
|
||||
return true;
|
||||
}
|
||||
if token.leading.iter().chain(token.trailing.as_ref()).any(|c| in_comment(c, offset)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `offset` is inside `comment`. A `//` comment runs to the end of the
|
||||
/// line, so a cursor at its last byte is still inside it; a `/* */` one ends
|
||||
/// at its marker, and the byte after that is code again.
|
||||
fn in_comment(comment: &Comment, offset: u32) -> bool {
|
||||
if offset <= comment.span.start {
|
||||
return false;
|
||||
}
|
||||
match comment.text.starts_with("//") {
|
||||
true => offset <= comment.span.end,
|
||||
false => offset < comment.span.end,
|
||||
}
|
||||
}
|
||||
|
||||
/// One tabstop: `${n:default}`, or a bare `${n}` when there is no default to
|
||||
/// preselect. The default is escaped, because `$`, `}` and `\` are the snippet
|
||||
/// grammar's own punctuation and a type like `logic [$bits(t)-1:0]` really
|
||||
/// does contain one.
|
||||
///
|
||||
/// `pub(crate)` for `inline.rs`, whose ghost instantiation writes the same
|
||||
/// holes: one spelling of a tabstop, one place to fix an escaping bug.
|
||||
pub(crate) fn snippet_hole(n: usize, default: &str) -> String {
|
||||
if default.is_empty() {
|
||||
return format!("${{{n}}}");
|
||||
}
|
||||
let mut escaped = String::with_capacity(default.len());
|
||||
for ch in default.chars() {
|
||||
if matches!(ch, '$' | '}' | '\\') {
|
||||
escaped.push('\\');
|
||||
}
|
||||
escaped.push(ch);
|
||||
}
|
||||
format!("${{{n}:{escaped}}}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::candidates::starts_with_ignore_case;
|
||||
use crate::completion::harness::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::uri::path_to_uri;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn a_tabstop_default_is_escaped_so_the_snippet_grammar_cannot_read_it() {
|
||||
assert_eq!(snippet_hole(1, ""), "${1}");
|
||||
assert_eq!(snippet_hole(2, "8"), "${2:8}");
|
||||
assert_eq!(snippet_hole(3, "$bits(t)"), "${3:\\$bits(t)}");
|
||||
assert_eq!(snippet_hole(4, "a}b\\c"), "${4:a\\}b\\\\c}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// comments and strings, both ways round
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn nothing_is_offered_inside_a_comment_or_a_string() {
|
||||
for (name, top, needle) in [
|
||||
("line", "module top;\n // wid\nendmodule\n", "// wid"),
|
||||
("block", "module top;\n /* wid */\nendmodule\n", "/* wid"),
|
||||
("trailing", "module top;\n logic a; // wid\nendmodule\n", "// wid"),
|
||||
("string", "module top;\n initial $display(\"wid\");\nendmodule\n", "\"wid"),
|
||||
] {
|
||||
let (_tree, ws, uri, position) = asking(&format!("in{name}"), top, needle);
|
||||
assert!(completions(&ws, &uri, position, true).is_none(), "{name}: {top}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_byte_after_a_block_comment_is_code_again() {
|
||||
// The other half of the boundary: `/* x */w|` is not inside anything.
|
||||
let top = "module top;\n /* c */ wid\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("afterblock", top, "*/ wid");
|
||||
assert!(completions(&ws, &uri, position, true).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_only_a_comment_or_a_string_holds_is_never_a_candidate() {
|
||||
let tree = Tree::new("harvest");
|
||||
tree.write(
|
||||
"other.sv",
|
||||
"module other;\n // widget_in_comment\n logic widget_in_code;\n\
|
||||
initial $display(\"widget_in_string\");\nendmodule\n",
|
||||
);
|
||||
let top = "module top;\n assign x = widget\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= widget");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let labels = labels(&items);
|
||||
assert!(labels.contains(&"widget_in_code"), "{labels:?}");
|
||||
assert!(!labels.contains(&"widget_in_comment"), "a comment is not code: {labels:?}");
|
||||
assert!(!labels.contains(&"widget_in_string"), "a string is not code: {labels:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at() {
|
||||
let top = "module top;\n logic a; /* unterminated\n wid\n";
|
||||
let (_tree, ws, uri, position) = asking("nolex", top, " wid");
|
||||
assert!(completions(&ws, &uri, position, true).is_none());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `define names and the backtick
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_backtick_offers_macro_names_and_only_macro_names() {
|
||||
let tree = Tree::new("macro");
|
||||
tree.write("defs.svh", "`define WIDTH 8\n`define MAX(a, b) 0\n");
|
||||
tree.write("other.sv", "module other;\n logic WIDGET;\nendmodule\n");
|
||||
let top = "module top;\n assign x = `WI\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "`WI");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(labels(&items), ["`WIDTH"], "only a macro may follow a backtick");
|
||||
assert_eq!(inserted(&items[0]), "`WIDTH");
|
||||
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
|
||||
panic!("a plain edit");
|
||||
};
|
||||
assert_eq!(
|
||||
edit.range.start,
|
||||
Position { line: 1, character: 13 },
|
||||
"the typed backtick is replaced, not doubled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_name_without_a_backtick_is_offered_bare() {
|
||||
// Where a macro name is written without one: `` `ifdef NAME ``.
|
||||
let tree = Tree::new("macrobare");
|
||||
tree.write("defs.svh", "`define WIDTH 8\n");
|
||||
let top = "module top;\n assign x = WID\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= WID");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "WIDTH").expect("the macro name");
|
||||
assert_eq!(inserted(item), "WIDTH", "no backtick is invented");
|
||||
assert_eq!(item.detail.as_deref(), Some("`define WIDTH"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// filtering, the cap, and the scope ladder
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_prefix_filters_server_side() {
|
||||
let tree = Tree::new("prefix");
|
||||
tree.write("other.sv", "module other;\n logic aaa_one, bbb_two;\nendmodule\n");
|
||||
let top = "module top;\n assign x = aaa\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= aaa");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(!items.is_empty());
|
||||
for item in &items {
|
||||
assert!(
|
||||
starts_with_ignore_case(&item.label, "aaa"),
|
||||
"{} does not start with the typed prefix",
|
||||
item.label
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_response_is_truncated_and_says_it_is_incomplete() {
|
||||
let mut top = String::from("module top;\n");
|
||||
for i in 0..LIMIT + 40 {
|
||||
top.push_str(&format!(" logic wsig{i:04};\n"));
|
||||
}
|
||||
top.push_str(" assign x = wsig\nendmodule\n");
|
||||
let (_tree, ws, uri, position) = asking("cap", &top, "= wsig");
|
||||
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
|
||||
panic!("a completion list");
|
||||
};
|
||||
assert_eq!(list.items.len(), LIMIT);
|
||||
assert!(list.is_incomplete, "a truncated list must say so");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_outside_the_filelist_contributes_no_words() {
|
||||
// M1's ladder decides what "the project" is, and the word tier is
|
||||
// built from exactly that list.
|
||||
let tree = Tree::new("filelist");
|
||||
tree.write("listed.sv", "module listed;\n logic word_listed;\nendmodule\n");
|
||||
tree.write("unlisted.sv", "module unlisted;\n logic word_unlisted;\nendmodule\n");
|
||||
tree.write("files.f", "listed.sv\n");
|
||||
let top = "module top;\n assign x = word_\nendmodule\n";
|
||||
let path = tree.write("top.sv", top);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
filelist: Some("files.f".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
ws.rebuild_index();
|
||||
let offset = (top.find("= word_").expect("needle") + 7) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let labels = labels(&items);
|
||||
assert!(labels.contains(&"word_listed"), "{labels:?}");
|
||||
assert!(!labels.contains(&"word_unlisted"), "outside the project: {labels:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_edit_contributes_its_own_words_at_once() {
|
||||
// The buffer's own token stream is read per request, so a name typed
|
||||
// a moment ago is a candidate before anything is saved.
|
||||
let top = "module top;\n logic fresh_name;\n assign x = fre\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("unsaved", top, "= fre");
|
||||
// The file on disk is `top` too, so make the buffer differ from it.
|
||||
let edited = "module top;\n logic fresher_name;\n assign x = fre\nendmodule\n";
|
||||
let mut ws = ws;
|
||||
ws.set_document(uri.clone(), edited.to_string());
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(labels(&items).contains(&"fresher_name"), "{:?}", labels(&items));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the performance claim, measured
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// What a keystroke costs over the real corpus, and what the tables cost
|
||||
/// to build. Skipped when `corpus/` is not checked out
|
||||
/// (`tools/corpus_fetch.sh`), exactly like the other corpus tests.
|
||||
///
|
||||
/// The budgets are deliberately loose — a debug build on a loaded machine
|
||||
/// is the worst case this ever runs in — and exist to catch an *order of
|
||||
/// magnitude* regression, not to pin a number. The numbers themselves are
|
||||
/// in `docs/features/completion-core/README.md`.
|
||||
#[test]
|
||||
fn a_keystroke_over_the_whole_corpus_stays_in_budget() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let build = started.elapsed();
|
||||
|
||||
// A buffer that is not on disk: it overlays the walk, so the corpus is
|
||||
// never written to.
|
||||
let top = "module lucisv_probe;\n logic clk;\n assign x = pr\nendmodule\n";
|
||||
let uri = path_to_uri(&corpus.join("lucisv_probe.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find("= pr").expect("needle") + 4) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
// Warm, then the measurement: ten requests, worst one reported. Twice
|
||||
// — once for a typed prefix, once for the empty one, which is the
|
||||
// worst case there is (every tier matches, and the cap does the work).
|
||||
let empty = ws.document(&uri).expect("open").positions().position(offset - 2);
|
||||
let mut worst = std::time::Duration::ZERO;
|
||||
let mut worst_empty = std::time::Duration::ZERO;
|
||||
for round in 0..11 {
|
||||
let started = std::time::Instant::now();
|
||||
let typed = items(completions(&ws, &uri, position, true));
|
||||
let after_typed = started.elapsed();
|
||||
let started = std::time::Instant::now();
|
||||
let all = items(completions(&ws, &uri, empty, true));
|
||||
let after_empty = started.elapsed();
|
||||
assert!(!typed.is_empty());
|
||||
assert_eq!(all.len(), LIMIT, "the empty prefix fills the response");
|
||||
if round > 0 {
|
||||
worst = worst.max(after_typed);
|
||||
worst_empty = worst_empty.max(after_empty);
|
||||
}
|
||||
}
|
||||
// …and the fuzzy path, which is a *scan* of the whole word table
|
||||
// where the two above are a binary search into it. Six characters,
|
||||
// the shape the round is named after.
|
||||
let fuzzy = "module lucisv_probe;\n logic clk;\n assign x = clkenq\nendmodule\n";
|
||||
ws.set_document(uri.clone(), fuzzy.to_string());
|
||||
let offset = (fuzzy.find("= clkenq").expect("needle") + 8) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let mut worst_fuzzy = std::time::Duration::ZERO;
|
||||
for round in 0..11 {
|
||||
let started = std::time::Instant::now();
|
||||
let found = items(completions(&ws, &uri, position, true));
|
||||
let elapsed = started.elapsed();
|
||||
assert!(!found.is_empty(), "the buffer's own `clk` matches at least");
|
||||
if round > 0 {
|
||||
worst_fuzzy = worst_fuzzy.max(elapsed);
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"corpus: {} files, {} words, {} index names; index+tables built in {build:?}; \
|
||||
worst request {worst:?} typed / {worst_empty:?} empty / {worst_fuzzy:?} fuzzy",
|
||||
ws.index().files().len(),
|
||||
ws.candidates().words("").len(),
|
||||
ws.candidates().units("").len(),
|
||||
);
|
||||
assert!(worst < std::time::Duration::from_millis(150), "a keystroke cost {worst:?}");
|
||||
assert!(worst_empty < std::time::Duration::from_millis(150), "{worst_empty:?}");
|
||||
assert!(worst_fuzzy < std::time::Duration::from_millis(150), "{worst_fuzzy:?}");
|
||||
}
|
||||
|
||||
/// What a **member** request costs over the real corpus, against the
|
||||
/// shapes the feature is named for: a generated register struct
|
||||
/// (`uart_reg2hw_t`, eleven fields whose types are eleven more structs in
|
||||
/// the same package), one of its inner registers reached by the
|
||||
/// synthesized key, a package, and a connection list on a real wide
|
||||
/// module.
|
||||
///
|
||||
/// The member answer is a table lookup like every other tier — one
|
||||
/// `member_site` walk over one file's scopes, then one `BTreeMap` scan
|
||||
/// per unit on the chain — so it should be *cheaper* than the tiered
|
||||
/// answer, which scans three tables. Same loose budget, same reason: an
|
||||
/// order of magnitude, not a number.
|
||||
#[test]
|
||||
fn a_member_request_over_the_whole_corpus_stays_in_budget() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let uri = path_to_uri(&corpus.join("lucisv_member_probe.sv")).expect("uri");
|
||||
|
||||
let mut worst = Vec::new();
|
||||
for (what, top, needle) in [
|
||||
(
|
||||
"reg2hw.",
|
||||
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.\n end\nendmodule\n",
|
||||
" reg2hw.",
|
||||
),
|
||||
(
|
||||
"reg2hw.ctrl.",
|
||||
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n",
|
||||
" reg2hw.ctrl.",
|
||||
),
|
||||
(
|
||||
"uart_reg_pkg::",
|
||||
"module lucisv_member_probe;\n initial begin\n $display(uart_reg_pkg::);\n end\nendmodule\n",
|
||||
"uart_reg_pkg::",
|
||||
),
|
||||
// The connection list, against a real wide module in another
|
||||
// file — the position the 2026-09-02 rework exists for.
|
||||
(
|
||||
"uart_core (.",
|
||||
"module lucisv_member_probe;\n uart_core u_core (\n .\n );\nendmodule\n",
|
||||
" .",
|
||||
),
|
||||
] {
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find(needle).expect("needle") + needle.len()) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let mut slowest = std::time::Duration::ZERO;
|
||||
let mut count = 0;
|
||||
for round in 0..11 {
|
||||
let started = std::time::Instant::now();
|
||||
let found = items(completions(&ws, &uri, position, true));
|
||||
let elapsed = started.elapsed();
|
||||
count = found.len();
|
||||
if round > 0 {
|
||||
slowest = slowest.max(elapsed);
|
||||
}
|
||||
}
|
||||
assert!(count > 0, "{what} must list members over the corpus");
|
||||
worst.push(format!("{what} {count} members in {slowest:?}"));
|
||||
assert!(slowest < std::time::Duration::from_millis(150), "{what} cost {slowest:?}");
|
||||
}
|
||||
eprintln!("corpus member requests: {}", worst.join(" / "));
|
||||
}
|
||||
|
||||
/// **QA's own reproduction, against the real file.** `prim_fifo_sync`
|
||||
/// derives `localparam int DepthW = prim_util_pkg::vbits(Depth+1)` in its
|
||||
/// header; six `parameter`s stand above it. A `#(.` list must offer the
|
||||
/// six and not the seventh. Skipped when `corpus/` is not checked out,
|
||||
/// like every other corpus test.
|
||||
#[test]
|
||||
fn the_opentitan_shape_that_found_the_localparam_bug() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let top = "module lucisv_param_probe;\n prim_fifo_sync #(.) u_fifo ();\nendmodule\n";
|
||||
let uri = path_to_uri(&corpus.join("lucisv_param_probe.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find("#(.").expect("needle") + 3) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
let mut found = labels(&answer);
|
||||
found.sort();
|
||||
assert_eq!(
|
||||
found,
|
||||
vec!["Depth", "NeverClears", "OutputZeroIfEmpty", "Pass", "Secure", "Width"],
|
||||
"the six overridable parameters, and not the derived `DepthW`",
|
||||
);
|
||||
// …and `DepthW` is still *there*: a hierarchical read of it is legal
|
||||
// and still resolves, which is what the split deliberately preserved.
|
||||
assert!(
|
||||
ws.index().members_of_chain("prim_fifo_sync").iter().any(|(name, _)| *name == "DepthW"),
|
||||
"the localparam is still exported",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,913 @@
|
||||
//! Tier 0 — module names at module-item position — and the instantiation
|
||||
//! planning that `inline.rs`'s ghost and `instantiate.rs`'s command share.
|
||||
//!
|
||||
//! The tier itself is a table scan: the names the workspace declares, ranked
|
||||
//! above everything else where an instantiation may be written. The planning
|
||||
//! half is the one part of completion that costs a *parse*, and it is here
|
||||
//! rather than in `inline.rs` because there must be exactly one answer to
|
||||
//! "which file, and which header, is this module planned from" —
|
||||
//! `nearest_definition` chooses among duplicate declarations and
|
||||
//! `module_header` slices the declaring file down to its header before the
|
||||
//! plan is built. See `docs/features/inline-instantiation/README.md` and
|
||||
//! `docs/features/refactor-instantiate/README.md`.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::{InstantiationPlan, Site};
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::word::Word;
|
||||
use super::{Items, TIER_MODULE};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
|
||||
/// How many module names one response carries.
|
||||
///
|
||||
/// Its own cap, below [`LIMIT`](super::LIMIT), because tier 0 matches a
|
||||
/// *substring* and so answers far more widely than the prefix tiers: an empty word at item
|
||||
/// position matches all 1 544 modules of opentitan, and letting one tier fill
|
||||
/// the whole response would starve the five below it. It no longer bounds any
|
||||
/// *work* — the tier is a scan of a table and nothing else, where until
|
||||
/// 2026-08-30 each item cost one file read and one header parse.
|
||||
const MODULE_LIMIT: usize = 64;
|
||||
|
||||
/// How far past a module's name [`module_header`] reads looking for the end of
|
||||
/// its header, smallest first.
|
||||
///
|
||||
/// A ladder rather than one bound because the lex is the whole cost of the
|
||||
/// slice and it is linear in what it is handed, so every header would
|
||||
/// otherwise pay for the widest one. The rungs come from measuring opentitan's
|
||||
/// 344 RTL modules: **59% of headers end inside 256 bytes**, 90% inside 2 KB,
|
||||
/// and the largest — `aes_control_fsm_n`, sixty commented ports — is 6.6 KB.
|
||||
/// The top rung is well past that, because a rung that is too small is not a
|
||||
/// wrong answer but a whole-file parse, and for those files that is 2–4 ms
|
||||
/// against the 0.6 ms of lexing 16 KB.
|
||||
const HEADER_WINDOWS: [usize; 3] = [256, 2 * 1024, 16 * 1024];
|
||||
|
||||
/// Tier 0: the names of the modules that could be instantiated here, at
|
||||
/// module-item position only.
|
||||
///
|
||||
/// **Names, not skeletons, since 2026-08-30** (owner ruling). Until then each
|
||||
/// item carried the whole instantiation, which cost one `module_definition`
|
||||
/// lookup, one file read and one header parse *per candidate* — up to
|
||||
/// [`MODULE_LIMIT`] of each, on every keystroke, for a list the user reads one
|
||||
/// line of. The instantiation is now offered by `inline.rs` as ghost text,
|
||||
/// once the name before the cursor is spelled exactly and a space follows it,
|
||||
/// and is planned once.
|
||||
/// See `docs/features/inline-instantiation/README.md`.
|
||||
///
|
||||
/// What survives is the ranking, which is the tier's real job: at a position
|
||||
/// where an instantiation may be written, a module name beats every other kind
|
||||
/// of name, and it is matched as a *substring* so `reg_top` reaches
|
||||
/// `aes_reg_top`.
|
||||
pub(super) fn module_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
at_item: bool,
|
||||
) {
|
||||
if !at_item {
|
||||
return;
|
||||
}
|
||||
// The same names `vlog_refactor::module_names` answers, off the table
|
||||
// built with the index instead of off the index's whole symbol table —
|
||||
// which the old call rebuilt and re-sorted on every keystroke.
|
||||
let names = ws.candidates().modules(&word.text);
|
||||
if names.len() > MODULE_LIMIT {
|
||||
items.incomplete = true;
|
||||
}
|
||||
for name in names.into_iter().take(MODULE_LIMIT) {
|
||||
items.simple(
|
||||
name,
|
||||
CompletionItemKind::MODULE,
|
||||
TIER_MODULE,
|
||||
module_detail(ws.index(), name, doc.path.as_deref()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a module item shows beside its name: where the module is declared.
|
||||
///
|
||||
/// A lookup in the index's unit table — no file is opened. The wording is tier
|
||||
/// 2's, so a module offered by either tier reads the same.
|
||||
///
|
||||
/// **The file named is the one the ghost will read** ([`nearest_definition`]),
|
||||
/// which since round 2 (2026-08-30) is an answer even for a name two files
|
||||
/// declare: `ast_dft` under `top_earlgrey` and `ast_dft` under `top_darjeeling`
|
||||
/// are two different headers, and the popup saying which one is coming is worth
|
||||
/// more than the bare kind label it used to fall back to.
|
||||
fn module_detail(index: &WorkspaceIndex, module: &str, from: Option<&Path>) -> String {
|
||||
// An interface is instantiated exactly as a module is and rides this same
|
||||
// list, so the label is read off what the index actually holds — a card
|
||||
// that said "module" over an `interface` would be the wrong answer this
|
||||
// round exists to remove.
|
||||
let kind = index
|
||||
.units(module)
|
||||
.iter()
|
||||
.find(|def| def.kind.is_instantiable())
|
||||
.map_or(SymbolKind::Module, |def| def.kind);
|
||||
let label = kind_label(kind);
|
||||
let Some(path) = nearest_definition(index, module, from) else {
|
||||
return label.to_string();
|
||||
};
|
||||
match path.file_name().and_then(|name| name.to_str()) {
|
||||
Some(file) => format!("{label} — {file}"),
|
||||
None => label.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file whose declaration of `module` a request made in `from` should be
|
||||
/// planned from.
|
||||
///
|
||||
/// **This never refuses on multiplicity**, which is the whole of what parts it
|
||||
/// from `vlog_refactor::module_definition`. That one errors when a name is
|
||||
/// declared twice and will not guess; in opentitan `ast_dft` and `io_osc` are
|
||||
/// each declared once under `hw/top_earlgrey/ip/ast/rtl` and once under
|
||||
/// `hw/top_darjeeling/ip/ast/rtl`, so refusing meant two whole IP blocks with
|
||||
/// no ghost at all. The owner's ruling of 2026-08-30 is that every indexed
|
||||
/// module expands, so the server chooses instead of declining — and
|
||||
/// `module_definition` keeps its refusal for its own callers, which want an
|
||||
/// error message rather than a guess.
|
||||
///
|
||||
/// The rule is **nearest to the asker**: the declaration whose path shares the
|
||||
/// longest run of leading *path components* with the document being typed in,
|
||||
/// so a buffer under `hw/top_earlgrey/…` is offered top_earlgrey's copy. A tie
|
||||
/// — and a buffer with no path at all — falls to the lexicographically smallest
|
||||
/// path, so the answer never depends on the order the index happened to be
|
||||
/// built in. Where the two declarations have different headers the user gets
|
||||
/// the nearest one's; that is the accepted semantics, not an approximation.
|
||||
///
|
||||
/// A module only one file declares is chosen by exactly this path too, and
|
||||
/// picks that one file — the same answer `module_definition` gives.
|
||||
pub(crate) fn nearest_definition<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
module: &str,
|
||||
from: Option<&Path>,
|
||||
) -> Option<&'i Path> {
|
||||
index
|
||||
.units(module)
|
||||
.iter()
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.filter_map(|def| index.path(def.file))
|
||||
// Most shared leading components first; among those, the *shallowest*
|
||||
// candidate — fewest components of its own past the shared prefix —
|
||||
// then the lexicographically smallest path. The depth key is the QA
|
||||
// round-2 fix: a copy in the asking buffer's own directory and one in
|
||||
// a subdirectory of it share the same prefix with the buffer (the
|
||||
// buffer's filename never matches a directory), and without the depth
|
||||
// key the lexicographic tie-break could prefer the deeper, less
|
||||
// related copy (`rstmgr/dv/rstmgr_cnsty_chk/tb.sv` over the direct
|
||||
// sibling `rstmgr/dv/tb.sv`, because `'r' < 't'`).
|
||||
.min_by_key(|path| {
|
||||
let shared = shared_components(path, from);
|
||||
(Reverse(shared), path.components().count() - shared, *path)
|
||||
})
|
||||
}
|
||||
|
||||
/// How many leading path components `path` and `from` spell the same way.
|
||||
///
|
||||
/// Components, not bytes: `hw/top_earlgrey` and `hw/top_darjeeling` share `hw`
|
||||
/// and nothing else, where a byte-wise prefix would count `hw/top_` as shared
|
||||
/// and rank two unrelated copies by a coincidence of spelling.
|
||||
fn shared_components(path: &Path, from: Option<&Path>) -> usize {
|
||||
let Some(from) = from else { return 0 };
|
||||
path.components().zip(from.components()).take_while(|(ours, theirs)| ours == theirs).count()
|
||||
}
|
||||
|
||||
/// One module's instantiation plan, off its header alone where that is the
|
||||
/// whole of what the plan reads, and off its whole file otherwise.
|
||||
///
|
||||
/// The slice is an optimisation and never an answer of its own. Two things
|
||||
/// send this back to the whole file, and both leave the answer exactly what it
|
||||
/// was before the slice existed:
|
||||
///
|
||||
/// * the slice does not plan at all — [`module_header`] cut a header this
|
||||
/// parser does not read as one;
|
||||
/// * the plan it produced has a port with neither a direction nor a type,
|
||||
/// which is what a **non-ANSI** port list looks like once its body is gone:
|
||||
/// `module m (a); input wire a;` writes the direction below the header, and
|
||||
/// the body is the part the slice drops.
|
||||
///
|
||||
/// `pub(crate)` for `inline.rs`, which plans the one module the user has
|
||||
/// spelled out. One planner on purpose: a second answer to "what is this
|
||||
/// module's instantiation" would eventually disagree with this one, and any
|
||||
/// future non-ghost spelling of the skeleton (a command for clients without
|
||||
/// `inlineCompletion`, say — filed in `docs/topo.md` §2.9) must come through
|
||||
/// here too.
|
||||
pub(crate) fn plan_for(
|
||||
index: &WorkspaceIndex,
|
||||
module: &str,
|
||||
definition: &str,
|
||||
site: Site<'_>,
|
||||
) -> Result<InstantiationPlan, String> {
|
||||
let whole = || vlog_refactor::instantiation_plan(module, definition, Some(site));
|
||||
let Some(header) = module_header(index, module, definition) else { return whole() };
|
||||
match vlog_refactor::instantiation_plan(module, &header, Some(site)) {
|
||||
Ok(plan) if plan.ports.iter().all(|p| !p.dir.is_empty() || !p.ty.is_empty()) => Ok(plan),
|
||||
_ => whole(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text one skeleton is planned from: the declaring file's header alone
|
||||
/// where this function can find it, and the whole file where it cannot.
|
||||
///
|
||||
/// Tier 0 is the one tier that costs a *parse*, and until 2026-08-28 it parsed
|
||||
/// the whole declaring file — three hundred lines of body to read a header a
|
||||
/// few hundred bytes long, [`MODULE_LIMIT`] times per keystroke. A plan reads
|
||||
/// nothing but the header, so nothing but the header needs to be parsed.
|
||||
///
|
||||
/// The prefix is kept **byte for byte**: every span the plan reads is an offset
|
||||
/// into the text it was parsed from, so cutting the front off would move them
|
||||
/// all. Only the body is dropped, and an `endmodule` is written in its place so
|
||||
/// the declaration is closed.
|
||||
///
|
||||
/// **Every declaration of the name is tried, not just a lone one** (round 2,
|
||||
/// 2026-08-30). Until then a name two files declared made this decline outright,
|
||||
/// which cost `ast_dft` and `io_osc` their ghost; it now walks them, because
|
||||
/// the index's span is only ever a *hint* here and the guard below is what
|
||||
/// makes a hint safe. A span from the wrong file either does not spell the
|
||||
/// module's name in this text — declined, and the caller parses the whole file
|
||||
/// instead, exactly as it did before — or it does, in which case the slice is
|
||||
/// taken from a real occurrence of the name in the text actually being read.
|
||||
pub(crate) fn module_header(index: &WorkspaceIndex, module: &str, text: &str) -> Option<String> {
|
||||
index
|
||||
.units(module)
|
||||
.iter()
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.find_map(|def| header_from(module, def.name_span, text))
|
||||
}
|
||||
|
||||
/// The header of the declaration `text` spells at `name`, or `None` when it
|
||||
/// does not spell one there at all.
|
||||
fn header_from(module: &str, name: TextRange, text: &str) -> Option<String> {
|
||||
// The index's span is as of the last scan, and may belong to a sibling
|
||||
// file that declares the same module. A file edited on disk since then has
|
||||
// moved it, and a slice taken at a stale offset would be a different
|
||||
// module's header — so the name has to still be there.
|
||||
if text.get(name.start as usize..name.end as usize) != Some(module) {
|
||||
return None;
|
||||
}
|
||||
let from = name.end as usize;
|
||||
for size in HEADER_WINDOWS {
|
||||
// A window that cuts a block comment or a string in half does not lex,
|
||||
// and one that cuts the port list in half runs out of tokens before
|
||||
// the `;`. Both answer "not in this window" and are asked again at the
|
||||
// next rung; both answer `None` at the last one.
|
||||
let window = text.get(from..text.len().min(from + size))?;
|
||||
if let Ok(tokens) = vlog_parser::tokenize(window) {
|
||||
if let Some(end) = header_end(&tokens) {
|
||||
let head = text.get(..from + end as usize)?;
|
||||
return Some(format!("{head}\nendmodule\n"));
|
||||
}
|
||||
}
|
||||
if from + size >= text.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Where the header that begins just after a module's name ends: the offset
|
||||
/// one past its terminating `;`, in the window's own coordinates.
|
||||
///
|
||||
/// A **whitelist**, not a scan for the first `;`: `module aes import
|
||||
/// aes_pkg::*; #(...) (...);` writes three of them and only the last ends the
|
||||
/// header. Anything this does not recognise — a compiler directive between the
|
||||
/// name and the port list, a header longer than the window — answers `None`,
|
||||
/// and the caller parses the whole file rather than guessing.
|
||||
fn header_end(tokens: &[Token]) -> Option<u32> {
|
||||
let mut at = 0;
|
||||
loop {
|
||||
let token = tokens.get(at)?;
|
||||
match token.text.as_str() {
|
||||
";" => return Some(token.span.end),
|
||||
// A lifetime qualifier: `module automatic foo (...);`.
|
||||
"static" | "automatic" => at += 1,
|
||||
// A package import written into the header, whose own `;` is not
|
||||
// the header's.
|
||||
"import" => at = skip_to_semicolon(tokens, at + 1)?,
|
||||
// The parameter list, the port list, and an attribute instance —
|
||||
// each one parenthesised, each one skipped whole.
|
||||
"#" | "(" => at = skip_parens(tokens, at)?,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the parenthesised group starting at `at`, which a `#` may introduce.
|
||||
fn skip_parens(tokens: &[Token], mut at: usize) -> Option<usize> {
|
||||
while tokens.get(at)?.text == "#" {
|
||||
at += 1;
|
||||
}
|
||||
if tokens.get(at)?.text != "(" {
|
||||
return None;
|
||||
}
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
match tokens.get(at)?.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" if depth == 1 => return Some(at + 1),
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the next `;` written outside any parentheses.
|
||||
fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
match tokens.get(at)?.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
";" if depth == 0 => return Some(at + 1),
|
||||
_ => {}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Completion's own view of the three new kinds, and the detail card that
|
||||
/// used to hard-code "module" over an interface — the C2 wrong answer
|
||||
/// (`docs/features/interface-semantics/README.md`).
|
||||
#[test]
|
||||
fn an_interface_completes_as_an_interface() {
|
||||
assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE);
|
||||
assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE);
|
||||
assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT);
|
||||
|
||||
let index = vlog_semantic::WorkspaceIndex::build([
|
||||
(PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"),
|
||||
(PathBuf::from("/rtl/sub.sv"), SUB),
|
||||
]);
|
||||
assert!(module_detail(&index, "bus_if", None).starts_with("interface"));
|
||||
assert!(module_detail(&index, "sub", None).starts_with("module"));
|
||||
// The ghost-instantiation lookups reach an interface too.
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()),
|
||||
Some("/rtl/bus_if.sv".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 0's header slice (2026-08-28) — it must change no answer
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every header shape the slice has to survive, as (file text, module).
|
||||
///
|
||||
/// The list is the argument that the slice changes nothing: each entry is
|
||||
/// planned both ways below and the two plans are compared field by field.
|
||||
const SHAPES: &[(&str, &str)] = &[
|
||||
// The ordinary ANSI header, params and all.
|
||||
(SUB, "sub"),
|
||||
// No ports at all.
|
||||
("module bare;\nendmodule\n", "bare"),
|
||||
// An empty port list.
|
||||
("module empty ();\n logic x;\nendmodule\n", "empty"),
|
||||
// A package import written into the header: its `;` is not the
|
||||
// header's, and a slice that stopped there would report no ports.
|
||||
(
|
||||
"package p;\n localparam int W = 4;\nendpackage\n\
|
||||
module imported import p::*; #(\n parameter int W = 8\n) (\n \
|
||||
input logic clk,\n output logic [W-1:0] q\n);\n \
|
||||
assign q = '0;\nendmodule\n",
|
||||
"imported",
|
||||
),
|
||||
// Two imports, then a parameter list.
|
||||
(
|
||||
"package p;\nendpackage\npackage q;\nendpackage\n\
|
||||
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
|
||||
"twice",
|
||||
),
|
||||
// A **non-ANSI** port list: the directions live in the body, which is
|
||||
// exactly what the slice drops.
|
||||
(
|
||||
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
|
||||
always @* b = |a;\nendmodule\n",
|
||||
"old",
|
||||
),
|
||||
// Non-ANSI with nothing declaring the ports at all.
|
||||
("module silent (a, b);\nendmodule\n", "silent"),
|
||||
// A comment and an attribute inside the header.
|
||||
(
|
||||
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"noisy",
|
||||
),
|
||||
// A lifetime qualifier.
|
||||
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
|
||||
// A second module in the same file, after the one being planned.
|
||||
(
|
||||
"module first (input logic a);\nendmodule\n\
|
||||
module second (output logic b);\nendmodule\n",
|
||||
"first",
|
||||
),
|
||||
// …and before it, so the slice's prefix carries a whole module.
|
||||
(
|
||||
"module first (input logic a);\nendmodule\n\
|
||||
module second (output logic b);\nendmodule\n",
|
||||
"second",
|
||||
),
|
||||
// A compiler directive between the name and the port list, which the
|
||||
// whitelist refuses outright.
|
||||
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
|
||||
// A directive *inside* the port list, which carries a warning the two
|
||||
// plans must both raise.
|
||||
(
|
||||
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
|
||||
`endif\n);\nendmodule\n",
|
||||
"ifdefd",
|
||||
),
|
||||
// An escaped identifier for the module and for a port.
|
||||
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
|
||||
// A header longer than the first rung of the window ladder.
|
||||
(WIDE, "wide"),
|
||||
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
|
||||
// instance, `(* ... *)`, right after the module name and before the
|
||||
// parameter list — the one shape the "noisy" case above is commented
|
||||
// as covering but does not (it has two comments, no attribute).
|
||||
// **Finding, not a regression this round introduced**: a module with
|
||||
// an attribute anywhere near its header is not indexed as a `Module`
|
||||
// unit at all (see
|
||||
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
|
||||
// so this pins the safe side effect — `module_header` declines before
|
||||
// its whitelist walk ever runs — rather than the whitelist's own
|
||||
// handling of attributes, which this shape cannot reach.
|
||||
(
|
||||
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"attributed",
|
||||
),
|
||||
// An attribute instance *inside* the port list, attached to one port.
|
||||
// Same finding as `attributed`: not indexed, so not reached either.
|
||||
(
|
||||
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
|
||||
);\nendmodule\n",
|
||||
"port_attributed",
|
||||
),
|
||||
// A single import declaration naming several packages, comma
|
||||
// separated (`import a::*, b::*;`) — one statement, not two, and the
|
||||
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
|
||||
(
|
||||
"package p;\nendpackage\npackage q;\nendpackage\n\
|
||||
module chained import p::*, q::*; (input logic a);\nendmodule\n",
|
||||
"chained",
|
||||
),
|
||||
// A parameter default whose string literal carries the exact bytes
|
||||
// the whitelist watches for — `;` and `)` — which must stay inside
|
||||
// the `String` token and never be mistaken for header punctuation.
|
||||
(
|
||||
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"stringy",
|
||||
),
|
||||
// CRLF line endings through the whole header.
|
||||
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
|
||||
];
|
||||
|
||||
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
|
||||
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
|
||||
input logic port_number_one_with_a_long_name,\n \
|
||||
input logic port_number_two_with_a_long_name,\n \
|
||||
input logic port_number_three_with_a_long_name,\n \
|
||||
input logic port_number_four_with_a_long_name,\n \
|
||||
input logic port_number_five_with_a_long_name,\n \
|
||||
output logic port_number_six_with_a_long_name\n);\n \
|
||||
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
|
||||
|
||||
/// The whole argument for the slice: for every shape above, the plan built
|
||||
/// from the header alone is the plan built from the whole file. Where it
|
||||
/// would not be — a non-ANSI list, a header the whitelist refuses — the
|
||||
/// guard in [`plan_for`] sends the question back to the whole file, so the
|
||||
/// comparison holds there too.
|
||||
#[test]
|
||||
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
|
||||
for (text, module) in SHAPES {
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let site = Site { semantics: &semantics, offset: 0 };
|
||||
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
|
||||
let ours = plan_for(&index, module, text, site);
|
||||
assert_eq!(ours, whole, "{module}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
|
||||
/// trivially for a shape the whitelist declines — both sides parse the
|
||||
/// whole file, so a wrong slice could hide behind that. These shapes must
|
||||
/// actually slice, so the comparison exercises the whitelist walk it is
|
||||
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
|
||||
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
|
||||
/// `;`/`)` sitting inside a string literal, and CRLF endings.
|
||||
#[test]
|
||||
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
|
||||
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
|
||||
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, *text)]);
|
||||
assert!(
|
||||
module_header(&index, module, text).is_some(),
|
||||
"{module}: expected the header to actually slice, not fall back whole-file"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
|
||||
/// round introduced: a module with an attribute instance (`(* ... *)`)
|
||||
/// anywhere near its header — right after its name, or on one of its
|
||||
/// ports — is not indexed as a `Module` unit **at all**.
|
||||
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
|
||||
/// at the very first line (no `[def]` to anchor on) before the whitelist
|
||||
/// walk ever runs, and completion's module tier — which sources its
|
||||
/// candidate names from the same table — never offers the module in the
|
||||
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
|
||||
/// completion-core one: it is filed in `docs/features/completion-core/
|
||||
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
|
||||
/// outside this round's touched files. The two "attribute" shapes this QA
|
||||
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
|
||||
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
|
||||
/// because both sides of that comparison fall back to the same whole-file
|
||||
/// parse, which this test makes explicit rather than leaving it as an
|
||||
/// unremarked side effect of the pin.
|
||||
#[test]
|
||||
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
|
||||
for module in ["attributed", "port_attributed"] {
|
||||
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, *text)]);
|
||||
assert!(
|
||||
index.units(module).is_empty(),
|
||||
"{module}: if this starts finding a unit, module_header should be re-audited \
|
||||
for whether it now slices attributes correctly rather than by lucky fallback"
|
||||
);
|
||||
assert!(
|
||||
module_header(&index, module, text).is_none(),
|
||||
"{module}: no unit to anchor on"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The guard is not decoration: a non-ANSI module really does plan
|
||||
/// differently off its header, and really is sent back to the whole file.
|
||||
#[test]
|
||||
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
|
||||
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
|
||||
let path = PathBuf::from("/rtl/old.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, text)]);
|
||||
let header = module_header(&index, "old", text).expect("the header slices");
|
||||
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
|
||||
assert!(
|
||||
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
|
||||
"premise: the header alone knows nothing about these ports"
|
||||
);
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let site = Site { semantics: &semantics, offset: 0 };
|
||||
let guarded = plan_for(&index, "old", text, site).expect("a plan");
|
||||
assert_eq!(guarded.ports[0].dir, "input");
|
||||
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
|
||||
}
|
||||
|
||||
/// The whole answer, pinned at the prefixes the hot path is worst at — the
|
||||
/// empty one and a one-character one, where every tier is at its widest.
|
||||
/// Tier 0 answers with names, so the pin spells out every module item's
|
||||
/// label *and* the text it inserts, which is now the label again.
|
||||
#[test]
|
||||
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
|
||||
let tree = Tree::new("pinned");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
|
||||
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
|
||||
let (_tree, mut ws, uri, _) =
|
||||
opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
|
||||
|
||||
// Nothing typed, then one character — the two widest requests there
|
||||
// are. `top` is in the answer because the buffer declares it and the
|
||||
// index holds it like any other module.
|
||||
let mut answer = |typed: &str| {
|
||||
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
|
||||
+ typed.len() as u32;
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let position = doc.positions().position(offset);
|
||||
items(completions(&ws, &uri, position, true))
|
||||
};
|
||||
for (typed, expected) in
|
||||
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
|
||||
{
|
||||
let items = answer(typed);
|
||||
let found: Vec<&str> =
|
||||
skeletons(&items).iter().map(|item| item.label.as_str()).collect();
|
||||
assert_eq!(found, expected, "module items after typing {typed:?}");
|
||||
}
|
||||
|
||||
// …and the exact text each of them inserts, which is the name and
|
||||
// nothing else however many ports the module has. The instantiation is
|
||||
// `inline.rs`'s business now.
|
||||
let items = answer("");
|
||||
for name in ["sub", "alpha", "submarine"] {
|
||||
let item = find(&items, name).expect("the module item");
|
||||
assert_eq!(inserted(item), name, "the popup inserts the name alone");
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
assert_eq!(item.insert_text_mode, None, "there is no indentation to keep");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file edited on disk since the index last read it has moved every span
|
||||
/// the index holds, so the slice must not take one on trust.
|
||||
#[test]
|
||||
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
|
||||
let text =
|
||||
"module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
|
||||
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
|
||||
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
|
||||
// The same index against a file whose text has shifted underneath it.
|
||||
let moved = format!("// a line nobody told the index about\n{text}");
|
||||
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_module_name_at_item_position_completes_to_the_name_alone() {
|
||||
let top = "module top;\n logic clk;\n su\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("nameonly", top, " su");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let modules = skeletons(&items);
|
||||
assert_eq!(modules.len(), 1, "{items:#?}");
|
||||
let item = modules[0];
|
||||
assert_eq!(item.label, "sub");
|
||||
assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon");
|
||||
assert_eq!(item.detail.as_deref(), Some("module — sub.sv"));
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest");
|
||||
assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snippet_flag_no_longer_changes_the_module_item() {
|
||||
// The M4 fallback — a plain-text spelling of the skeleton for a client
|
||||
// that never advertised `snippetSupport` — has nothing left to fall
|
||||
// back from: the item is a word either way.
|
||||
let top = "module top;\n logic clk;\n su\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("plain", top, " su");
|
||||
for snippets in [true, false] {
|
||||
let items = items(completions(&ws, &uri, position, snippets));
|
||||
let item = skeletons(&items)[0];
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
assert_eq!(inserted(item), "sub", "snippets: {snippets}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole point of level 1: the popup no longer reads the files it
|
||||
/// offers names from. Proved by deleting the declaring file after the
|
||||
/// index has been built — the old tier answered nothing at all here,
|
||||
/// because every item needed that file's text.
|
||||
#[test]
|
||||
fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() {
|
||||
let tree = Tree::new("noread");
|
||||
let sub = tree.write("sub.sv", SUB);
|
||||
let (_tree, ws, uri, position) =
|
||||
opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su");
|
||||
fs::remove_file(&sub).expect("remove the declaring file");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(
|
||||
skeletons(&items).iter().map(|item| item.label.as_str()).collect::<Vec<_>>(),
|
||||
["sub"],
|
||||
"the name comes from the index's table, not from the file: {items:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_edit_replaces_exactly_the_typed_word() {
|
||||
let top = "module top;\n su\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("replace", top, " su");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
for item in &items {
|
||||
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
|
||||
panic!("a plain edit");
|
||||
};
|
||||
assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}");
|
||||
assert_eq!(edit.range.end, Position { line: 1, character: 4 });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_skeleton_is_offered_in_the_middle_of_an_expression() {
|
||||
// The other tiers answer here — a name is a name wherever it is
|
||||
// written — but a fifteen-line instantiation is not.
|
||||
for (name, top, needle) in [
|
||||
("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"),
|
||||
("decl", "module top;\n logic su\nendmodule\n", "logic su"),
|
||||
("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"),
|
||||
("header", "module top (su\n);\nendmodule\n", "top (su"),
|
||||
] {
|
||||
let (_tree, ws, uri, position) = asking(name, top, needle);
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_skeleton_is_offered_inside_a_procedural_block() {
|
||||
let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("always", top, " su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
|
||||
let top = "module top;\n initial begin\n su\n end\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("initial", top, " su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_skeleton_is_offered_inside_a_function_or_a_class() {
|
||||
let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("function", top, " su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
|
||||
let top = "package p;\n class c;\n su\n endclass\nendpackage\n";
|
||||
let (_tree, ws, uri, position) = asking("class", top, " su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_block_is_still_item_position() {
|
||||
let top = "\
|
||||
module top;
|
||||
for (genvar i = 0; i < 4; i++) begin : g
|
||||
su
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri, position) = asking("genfor", top, " su");
|
||||
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}");
|
||||
|
||||
let top = "module top;\n generate\n su\n endgenerate\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("generate", top, " su");
|
||||
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_skeleton_is_offered_outside_a_design_unit() {
|
||||
let top = "su\nmodule top;\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("toplevel", top, "su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_that_matches_no_module_offers_no_skeleton() {
|
||||
let top = "module top;\n zzz\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("nomatch", top, " zzz");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() {
|
||||
// Until 2026-08-30 tier 0 skipped it: there is no single definition to
|
||||
// build a *skeleton* from, and the skeleton was the item. A name needs
|
||||
// no definition, so round 1 offered the name and left the detail
|
||||
// blank. Round 2 (owner ruling, same day) makes the ghost choose a
|
||||
// copy rather than decline, so the popup names the copy the ghost will
|
||||
// read — `nearest_definition`'s answer, which for a buffer at the tree
|
||||
// root is the lexicographically smaller path.
|
||||
let tree = Tree::new("dup");
|
||||
tree.write("a.sv", "module dup ();\nendmodule\n");
|
||||
tree.write("b.sv", "module dup ();\nendmodule\n");
|
||||
let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "dup").expect("the name is still known");
|
||||
assert_eq!(tier(item), TIER_MODULE, "{items:#?}");
|
||||
assert_eq!(item.detail.as_deref(), Some("module — a.sv"));
|
||||
}
|
||||
|
||||
/// The nearest-definition chooser, at the level `inline.rs` consumes it.
|
||||
///
|
||||
/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling`
|
||||
/// share `hw` and nothing more, and a byte-wise prefix would count the
|
||||
/// `hw/top_` they spell alike and rank the copies by a coincidence.
|
||||
#[test]
|
||||
fn the_nearest_definition_is_the_one_sharing_the_most_path_components() {
|
||||
let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv");
|
||||
let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv");
|
||||
let text = "module ast_dft ();\nendmodule\n";
|
||||
let index =
|
||||
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
|
||||
|
||||
let asking = |from: &str| {
|
||||
nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from)))
|
||||
.expect("a definition")
|
||||
.to_path_buf()
|
||||
};
|
||||
assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey);
|
||||
assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling);
|
||||
// Near neither, and no path at all: the tie falls to the smaller path
|
||||
// rather than to whatever the index happens to hold first.
|
||||
assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling);
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "ast_dft", None).expect("a definition"),
|
||||
darjeeling.as_path()
|
||||
);
|
||||
}
|
||||
|
||||
/// QA round-2 finding, fixed at lead review: a copy in the asking
|
||||
/// buffer's own directory and one in a subdirectory of it share the same
|
||||
/// number of leading components with the buffer (its filename never
|
||||
/// matches a directory), and the lexicographic tie-break alone could pick
|
||||
/// the deeper, less related copy. The real shape is opentitan's 61-way
|
||||
/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv`
|
||||
/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`.
|
||||
#[test]
|
||||
fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() {
|
||||
let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv");
|
||||
let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv");
|
||||
let text = "module tb ();\nendmodule\n";
|
||||
for sources in [
|
||||
vec![(sibling.clone(), text), (deeper.clone(), text)],
|
||||
vec![(deeper.clone(), text), (sibling.clone(), text)],
|
||||
] {
|
||||
let index = WorkspaceIndex::build(sources);
|
||||
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv");
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
|
||||
sibling.as_path(),
|
||||
"the shallower copy is the nearer one"
|
||||
);
|
||||
}
|
||||
// …and depth only breaks a tie: a deeper copy that genuinely shares
|
||||
// more of the asking path still wins.
|
||||
let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]);
|
||||
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv");
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
|
||||
deeper.as_path(),
|
||||
"sharing more components outranks being shallow"
|
||||
);
|
||||
}
|
||||
|
||||
/// The answer is a property of the paths, not of the order the index was
|
||||
/// built in — which is what makes it the same answer twice in a row, and
|
||||
/// the same answer in two editors.
|
||||
#[test]
|
||||
fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() {
|
||||
let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv");
|
||||
let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv");
|
||||
let text = "module ast_dft ();\nendmodule\n";
|
||||
let forwards =
|
||||
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
|
||||
let backwards =
|
||||
WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]);
|
||||
for index in [&forwards, &backwards] {
|
||||
let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv");
|
||||
assert_eq!(
|
||||
nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"),
|
||||
earlgrey.as_path()
|
||||
);
|
||||
assert_eq!(
|
||||
nearest_definition(index, "ast_dft", None).expect("a definition"),
|
||||
darjeeling.as_path()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A module only one file declares goes through the same chooser and comes
|
||||
/// back with the file `vlog_refactor::module_definition` picks — the
|
||||
/// equivalence that says round 2 widened the twice-declared case and moved
|
||||
/// nothing else.
|
||||
#[test]
|
||||
fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() {
|
||||
let path = PathBuf::from("/rtl/sub.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]);
|
||||
let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition");
|
||||
assert_eq!(expected, path.as_path());
|
||||
for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] {
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "sub", from.as_deref()).expect("a definition"),
|
||||
expected,
|
||||
"{from:?}"
|
||||
);
|
||||
}
|
||||
// And a name nothing declares is `None` here where it is an `Err`
|
||||
// there — the same "no answer", spelled the way each caller reads it.
|
||||
assert!(nearest_definition(&index, "nope", None).is_none());
|
||||
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
//! What may be written here: the module-item gate and the statement gate,
|
||||
//! judged over the token stream's scope chain.
|
||||
//!
|
||||
//! Both are heuristics over `pairs::analyze` — the same scope matcher the
|
||||
//! begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
|
||||
//! an unbalanced one still answers. Tier 0, the templates, `inline.rs`'s
|
||||
//! ghost instantiation and `instantiate.rs` all ask these two questions, and
|
||||
//! they ask them here so there is one answer to "may an instantiation go
|
||||
//! here". The consts at the top are the whole of the grammar the gates know.
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use super::word::line_head_is_blank;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// The scopes a module instantiation may be written directly inside.
|
||||
const ITEM_SCOPES: &[&str] =
|
||||
&["module", "macromodule", "interface", "program", "generate", "begin"];
|
||||
|
||||
/// Scopes that make everything inside them something other than a module item:
|
||||
/// a subprogram body, a class body, a checker-ish declaration, a `case` arm's
|
||||
/// interior, a `fork` block.
|
||||
const NOT_ITEM_SCOPES: &[&str] = &[
|
||||
"function",
|
||||
"task",
|
||||
"class",
|
||||
"covergroup",
|
||||
"property",
|
||||
"sequence",
|
||||
"clocking",
|
||||
"specify",
|
||||
"primitive",
|
||||
"fork",
|
||||
"case",
|
||||
"casex",
|
||||
"casez",
|
||||
"randcase",
|
||||
];
|
||||
|
||||
/// The scopes a *statement* may be written directly inside. A `begin` or a
|
||||
/// `fork` qualifies only when it is procedural (see [`at_statement`]); a
|
||||
/// `function`/`task` body always does.
|
||||
const STATEMENT_SCOPES: &[&str] = &["begin", "fork", "function", "task"];
|
||||
|
||||
/// Keywords that make the `begin` after them procedural, so nothing inside it
|
||||
/// is a module item. `@` is on the list because it is the whole of what stands
|
||||
/// between `always` and its `begin`.
|
||||
const PROCEDURAL: &[&str] =
|
||||
&["always", "always_ff", "always_comb", "always_latch", "initial", "final", "@"];
|
||||
|
||||
/// Tokens that end whatever came before them, stopping the backward scan that
|
||||
/// looks for a [`PROCEDURAL`] keyword.
|
||||
const STATEMENT_END: &[&str] =
|
||||
&["begin", "end", "endcase", "join", "join_any", "join_none", "generate", ";"];
|
||||
|
||||
/// Whether a module instantiation may be written starting at `at`.
|
||||
///
|
||||
/// **Tier 0's own gate**, factored out so `inline.rs`'s ghost instantiation
|
||||
/// asks the identical question: the two features offer the same construct, and
|
||||
/// a second answer to "may an instantiation go here" would eventually disagree
|
||||
/// with this one. Both halves are here — the word must start its line, and the
|
||||
/// scope chain covering it must be one an item belongs to (see
|
||||
/// [`at_module_item`] for what that means and what it cannot see).
|
||||
pub(crate) fn at_instantiation_site(doc: &Document, at: u32) -> bool {
|
||||
if !line_head_is_blank(&doc.text, at) {
|
||||
return false;
|
||||
}
|
||||
at_module_item(doc, &enclosing_scopes(&doc.tokens, at), at)
|
||||
}
|
||||
|
||||
/// Whether `at` is somewhere a module instantiation could be written, judged
|
||||
/// over the token stream.
|
||||
///
|
||||
/// This is a **heuristic, not a parse**, and the README says exactly what it
|
||||
/// gets wrong. It reuses `pairs::analyze` — the same scope matcher the
|
||||
/// begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
|
||||
/// an unbalanced one still answers. Three conditions, all necessary:
|
||||
///
|
||||
/// 1. the innermost scope open here is one of [`ITEM_SCOPES`];
|
||||
/// 2. no scope in the chain is one of [`NOT_ITEM_SCOPES`], so a `begin` inside
|
||||
/// a `function` or a `case` arm is rejected however module-ish its parent;
|
||||
/// 3. the outermost `begin` in the chain is not a procedural one — a
|
||||
/// generate-`for`'s `begin` qualifies, an `always @(...)`'s does not.
|
||||
///
|
||||
/// Parentheses close the door too: an item never starts inside one, which is
|
||||
/// what keeps a port list and a connection list out.
|
||||
pub(super) fn at_module_item(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
|
||||
let tokens = &doc.tokens;
|
||||
if tokens.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(&(innermost, opener)) = chain.first() else { return false };
|
||||
if !ITEM_SCOPES.contains(&innermost) {
|
||||
return false;
|
||||
}
|
||||
if chain.iter().any(|(keyword, _)| NOT_ITEM_SCOPES.contains(keyword)) {
|
||||
return false;
|
||||
}
|
||||
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
|
||||
if let Some(&(_, span)) = outermost_begin {
|
||||
if is_procedural(tokens, span.start) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
balanced(tokens, opener.end, at)
|
||||
}
|
||||
|
||||
/// Whether `at` is somewhere a *statement* could be written, judged over the
|
||||
/// same scope chain [`at_module_item`] reads.
|
||||
///
|
||||
/// Two ways to qualify, and they are the only two this asks about:
|
||||
///
|
||||
/// 1. the innermost open scope is a `function` or a `task`, whose body is
|
||||
/// statements all the way down; or
|
||||
/// 2. it is a `begin`/`fork` whose outermost `begin` is a procedural one — the
|
||||
/// exact inverse of the test that keeps module items out of an `always`.
|
||||
///
|
||||
/// Everything else is refused, `case` arms included: a bare `if` is not a
|
||||
/// legal case item, and a gate that guesses at one would offer a template that
|
||||
/// does not compile. Parentheses close the door here too.
|
||||
pub(super) fn at_statement(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
|
||||
let tokens = &doc.tokens;
|
||||
if tokens.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(&(innermost, opener)) = chain.first() else { return false };
|
||||
if !STATEMENT_SCOPES.contains(&innermost) {
|
||||
return false;
|
||||
}
|
||||
if innermost == "begin" || innermost == "fork" {
|
||||
let in_subprogram = chain.iter().any(|(kw, _)| *kw == "function" || *kw == "task");
|
||||
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
|
||||
let procedural = match outermost_begin {
|
||||
Some(&(_, span)) => is_procedural(tokens, span.start),
|
||||
None => false,
|
||||
};
|
||||
if !in_subprogram && !procedural {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
balanced(tokens, opener.end, at)
|
||||
}
|
||||
|
||||
/// The scopes open at `at`, innermost first, as `(keyword, opener span)`.
|
||||
pub(super) fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)> {
|
||||
let analysis = pairs::analyze(tokens);
|
||||
let mut out: Vec<(&'static str, TextRange)> = analysis
|
||||
.pairs
|
||||
.iter()
|
||||
.filter(|pair| pair.open.end <= at && at <= pair.close.start)
|
||||
.map(|pair| (pair.keyword, pair.open))
|
||||
.chain(
|
||||
analysis
|
||||
.unmatched_open
|
||||
.iter()
|
||||
.filter(|open| open.span.end <= at)
|
||||
.map(|open| (open.keyword, open.span)),
|
||||
)
|
||||
.collect();
|
||||
// Innermost first: the scope that opened last is the one we are in.
|
||||
out.sort_by_key(|(_, span)| std::cmp::Reverse(span.start));
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the `begin` starting at `offset` belongs to a procedural block.
|
||||
///
|
||||
/// Read backwards from the keyword: `always @(posedge clk) begin` reaches `@`
|
||||
/// and then `always`, `initial begin` reaches `initial`, while a generate
|
||||
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
|
||||
/// `generate begin` reaches `generate`. Whichever comes first decides.
|
||||
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
|
||||
// A token starting exactly at `offset` is the first one that starts at or
|
||||
// after it: every earlier token starts before, every later token after.
|
||||
let begin = first_token_from(tokens, offset);
|
||||
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
|
||||
return false;
|
||||
}
|
||||
for token in tokens[..begin].iter().rev() {
|
||||
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
|
||||
return true;
|
||||
}
|
||||
if STATEMENT_END.iter().any(|kw| token.text == *kw) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether every parenthesis opened between `from` and `at` was closed again.
|
||||
pub(super) fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
|
||||
let mut depth = 0i32;
|
||||
// The tokens whose start falls in `[from, at)` are a contiguous run,
|
||||
// because starts rise across the vector — so the filter this replaced was
|
||||
// reading the whole buffer to reach a window the two bounds name outright.
|
||||
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
|
||||
for token in &tokens[window] {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
match token.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
depth == 0
|
||||
}
|
||||
|
||||
/// The whitespace the line holding `offset` begins with.
|
||||
pub(super) fn line_indent(text: &str, offset: u32) -> String {
|
||||
let Some(head) = text.get(..offset as usize) else { return String::new() };
|
||||
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
head.get(line_start..).unwrap_or("").chars().take_while(|c| *c == ' ' || *c == '\t').collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [`is_procedural`] used to sweep the vector for the token starting at
|
||||
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
|
||||
/// two offsets name. Both now binary-search; both must answer exactly what
|
||||
/// the sweeps answered, at every byte and for every window.
|
||||
#[test]
|
||||
fn the_scope_gates_answer_what_their_sweeps_answered() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
|
||||
let tokens = &doc.tokens;
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = tokens.iter().position(|token| token.span.start == offset);
|
||||
let searched = {
|
||||
let begin = first_token_from(tokens, offset);
|
||||
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
|
||||
};
|
||||
assert_eq!(swept, searched, "the token starting at {offset}");
|
||||
}
|
||||
// Every `begin`/`end` opener in the buffer against a spread of cursors
|
||||
// after it: the two bounds are what pick the window out.
|
||||
let openers: Vec<u32> = tokens
|
||||
.iter()
|
||||
.filter(|t| t.text == "begin" || t.text == "(")
|
||||
.map(|t| t.span.end)
|
||||
.collect();
|
||||
assert!(openers.len() > 20, "premise: plenty of windows to check");
|
||||
for from in openers {
|
||||
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
|
||||
let mut depth = 0i32;
|
||||
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
match token.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,941 @@
|
||||
//! Tiers 1 to 5: the five ordinary tiers, in the order they fill the
|
||||
//! response.
|
||||
//!
|
||||
//! What the scope chain binds, what the workspace index declares (macro
|
||||
//! names included), the templates, the keywords, and every identifier the
|
||||
//! project's token streams contain. Each is a filter over one table with the
|
||||
//! house matching rule — prefix below `FUZZY_MIN`, subsequence from it up —
|
||||
//! and each stops the moment the response is full. Tier 0 lives in
|
||||
//! `module.rs` because its planning half is a different kind of work; the
|
||||
//! member answer lives in `member.rs` because it is exclusive rather than a
|
||||
//! tier.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Semantics, Symbol};
|
||||
|
||||
use super::site::line_indent;
|
||||
use super::word::Word;
|
||||
use super::{
|
||||
completion_kind, declaration_detail, Items, LIMIT, TIER_INDEX, TIER_KEYWORD, TIER_SCOPE,
|
||||
TIER_WORD,
|
||||
};
|
||||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Candidate, Query, Score};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::{self, Gate, Template};
|
||||
|
||||
/// Tier 1: everything the scope chain at the cursor binds.
|
||||
///
|
||||
/// The one fuzzy tier with no mask table behind it, and deliberately so: what
|
||||
/// a scope chain binds is tens of names computed per request, where a table of
|
||||
/// masks would cost more to build than the scan it saved.
|
||||
pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
|
||||
let visible = visible_symbols(&doc.semantics, word.start);
|
||||
let matched: Vec<&Symbol> = match fuzzy {
|
||||
None => visible
|
||||
.into_iter()
|
||||
.filter(|symbol| starts_with_ignore_case(&symbol.name, &word.text))
|
||||
.collect(),
|
||||
Some(query) => {
|
||||
let mut hits: Vec<(&Symbol, Score)> = visible
|
||||
.into_iter()
|
||||
.filter_map(|symbol| Some((symbol, query.score(&symbol.name)?)))
|
||||
.collect();
|
||||
hits.sort_by(|a, b| rank_cmp((&a.0.name, a.1), (&b.0.name, b.1)));
|
||||
hits.into_iter().map(|(symbol, _)| symbol).collect()
|
||||
}
|
||||
};
|
||||
for symbol in matched {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(
|
||||
&symbol.name,
|
||||
completion_kind(symbol.kind),
|
||||
TIER_SCOPE,
|
||||
declaration_detail(doc, symbol),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every declaration the scope chain covering `offset` binds, innermost scope
|
||||
/// first, each name only once — the inner declaration shadows the outer one,
|
||||
/// which is the rule `vlog_semantic`'s own lookup follows.
|
||||
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
|
||||
let mut out = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut at = innermost_scope(semantics, offset);
|
||||
while let Some(id) = at {
|
||||
let Some(scope) = semantics.scope(id) else { break };
|
||||
for symbol in scope.symbols.iter().filter_map(|&id| semantics.symbol(id)) {
|
||||
if seen.insert(symbol.name.as_str()) {
|
||||
out.push(symbol);
|
||||
}
|
||||
}
|
||||
at = scope.parent;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The smallest scope whose span covers `offset`.
|
||||
pub(super) fn innermost_scope(
|
||||
semantics: &Semantics,
|
||||
offset: u32,
|
||||
) -> Option<vlog_semantic::ScopeId> {
|
||||
semantics
|
||||
.scopes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, scope)| scope.span.contains(offset))
|
||||
.min_by_key(|(_, scope)| scope.span.len())
|
||||
.map(|(i, _)| vlog_semantic::ScopeId(i as u32))
|
||||
}
|
||||
|
||||
/// Tier 2: what the workspace index declares, `` `define`` names included.
|
||||
///
|
||||
/// The index names match fuzzily from [`FUZZY_MIN`](super::FUZZY_MIN) up;
|
||||
/// the macro names do not. That is a deliberate split, not an oversight — see the feature
|
||||
/// README's *What did not go fuzzy*.
|
||||
pub(super) fn index_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
|
||||
let matched: Vec<&Candidate> = match fuzzy {
|
||||
None => ws.candidates().units(&word.text).iter().collect(),
|
||||
Some(query) => {
|
||||
let hits = ws.candidates().units_fuzzy(query, LIMIT);
|
||||
// A full return means the scan kept its best LIMIT and dropped the
|
||||
// rest, so the response is a best-of and has to say so. `full()`
|
||||
// below would only notice if every one of them reached the list,
|
||||
// and a name a higher tier already claimed does not.
|
||||
items.incomplete |= hits.len() >= LIMIT;
|
||||
hits.into_iter().map(|(unit, _)| unit).collect()
|
||||
}
|
||||
};
|
||||
for candidate in matched {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(
|
||||
&candidate.name,
|
||||
completion_kind(candidate.kind),
|
||||
TIER_INDEX,
|
||||
format!("{} — {}", kind_label(candidate.kind), candidate.detail),
|
||||
);
|
||||
}
|
||||
// Bare, with no backtick invented. A macro *use* is spelled with one and
|
||||
// the user types it (see the early return above); the places a macro name
|
||||
// is written without one — `` `ifdef NAME ``, `` `undef NAME `` — are
|
||||
// exactly where this item is the right text.
|
||||
for entry in ws.candidates().macros(&word.text) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(&entry.name, CompletionItemKind::CONSTANT, TIER_INDEX, entry.detail.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 3: the statement, item and declaration templates.
|
||||
///
|
||||
/// Above the keywords because a user who typed `if` almost always wants
|
||||
/// `if (…) begin … end` rather than the three letters they already typed, and
|
||||
/// below both semantic tiers because a name the code actually declares beats a
|
||||
/// skeleton every time. The templates a *position* rules out never reach the
|
||||
/// list at all, so the ranking argument only has to hold where they do.
|
||||
pub(super) fn template_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
snippets: bool,
|
||||
at_item: bool,
|
||||
at_statement: bool,
|
||||
) {
|
||||
if !at_item && !at_statement {
|
||||
return;
|
||||
}
|
||||
let layout = layout_at(ws, doc, word.start);
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
for template in templates::for_dialect(dialect) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
if !offered(template, at_item, at_statement) {
|
||||
continue;
|
||||
}
|
||||
if !starts_with_ignore_case(template.prefix, &word.text) {
|
||||
continue;
|
||||
}
|
||||
items.template(template, &layout, snippets);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a template's gate lets it be written where the cursor is.
|
||||
fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool {
|
||||
match template.gate {
|
||||
Gate::Statement | Gate::ElseTail => at_statement,
|
||||
Gate::Item => at_item,
|
||||
// A declaration is a module item and a block item both.
|
||||
Gate::Declaration => at_item || at_statement,
|
||||
}
|
||||
}
|
||||
|
||||
/// How generated text is indented at `offset`: the line's own indentation, and
|
||||
/// one step as `lucisv.indent` spells it.
|
||||
///
|
||||
/// Private from 2026-08-25 to 2026-09-02: `inline.rs` stopped sharing it when
|
||||
/// ghost text moved to *relative* indentation and let the editor place it
|
||||
/// (see `inline.rs`'s `render`). `pub(crate)` again for `instantiate.rs`,
|
||||
/// whose `workspace/applyEdit` is plain text no editor re-indents, so it needs
|
||||
/// exactly this — the real indentation of the real line.
|
||||
pub(crate) fn layout_at(ws: &Workspace, doc: &Document, offset: u32) -> Layout {
|
||||
let step = " ".repeat(ws.client_settings().indent.unwrap_or(2));
|
||||
Layout { base: line_indent(&doc.text, offset), step }
|
||||
}
|
||||
|
||||
/// Tier 4: every reserved word the lexer knows.
|
||||
pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
|
||||
for keyword in KEYWORDS.iter().filter(|kw| starts_with_ignore_case(kw, &word.text)) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(keyword, CompletionItemKind::KEYWORD, TIER_KEYWORD, "keyword".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 5: identifiers used anywhere in the project scope.
|
||||
///
|
||||
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
|
||||
/// buffer being typed in is harvested afresh from its own token stream, so an
|
||||
/// unsaved edit contributes to its own file's completions immediately.
|
||||
pub(super) fn word_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
// Gathering and sorting the names is the one tier whose *setup* costs
|
||||
// something, so a response that is already full skips it outright.
|
||||
if items.full() {
|
||||
return;
|
||||
}
|
||||
let names: Vec<&str> = match fuzzy {
|
||||
None => {
|
||||
let mut names: Vec<&str> =
|
||||
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
|
||||
names
|
||||
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
Some(query) => {
|
||||
// The table's hits come back ranked; the buffer's own words are
|
||||
// scored here and the two are ranked together, so a name the user
|
||||
// typed a moment ago sits where its match deserves rather than
|
||||
// after everything the table knows.
|
||||
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
|
||||
// A full return is a truncation; see `index_tier`.
|
||||
items.incomplete |= hits.len() >= LIMIT;
|
||||
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
|
||||
hits.sort_by(|a, b| rank_cmp(*a, *b));
|
||||
// A name in both lists is offered once: `Items` drops the second
|
||||
// by label, so no dedup is needed here.
|
||||
hits.into_iter().map(|(name, _)| name).collect()
|
||||
}
|
||||
};
|
||||
for name in names {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(name, CompletionItemKind::TEXT, TIER_WORD, "used in this project".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
|
||||
///
|
||||
/// The live half of the tier: the prebuilt table is as of the last index
|
||||
/// rebuild, and this is the buffer's own token stream, recomputed on every
|
||||
/// change. The filter is `candidates::is_word`'s, in the other direction —
|
||||
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
|
||||
/// identifier.
|
||||
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
|
||||
doc.tokens
|
||||
.iter()
|
||||
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
|
||||
.map(|token| token.text.as_str())
|
||||
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 3 — templates
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Only the templates — tier 3.
|
||||
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
|
||||
items
|
||||
.iter()
|
||||
.filter(|item| tier(item) == TIER_TEMPLATE)
|
||||
.map(|item| item.label.as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The items offered at `needle`'s end in a buffer named `file`.
|
||||
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
|
||||
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
|
||||
items(completions(&ws, &uri, position, true))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_template_expands_where_a_statement_may_be_written() {
|
||||
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
|
||||
let items = offering("stmt", "top.sv", top, " if");
|
||||
let item = find(&items, "if begin/end").expect("the if template");
|
||||
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
|
||||
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
|
||||
assert_eq!(
|
||||
inserted(item),
|
||||
"if (${1:cond}) begin\n $0\n end",
|
||||
"the site's own indentation, the condition first and the body last"
|
||||
);
|
||||
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
|
||||
// Dedup is by label, so the labels are prose on purpose: `if` the
|
||||
// keyword and `if begin/end` the template are two items, in that
|
||||
// order of specificity.
|
||||
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
|
||||
let items = offering("both", "top.sv", top, " if");
|
||||
let keyword = find(&items, "if").expect("the bare keyword");
|
||||
let template = find(&items, "if begin/end").expect("the template");
|
||||
assert_eq!(tier(keyword), TIER_KEYWORD);
|
||||
assert_eq!(tier(template), TIER_TEMPLATE);
|
||||
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_ranks_below_a_name_the_code_declares() {
|
||||
let top = "\
|
||||
module top;
|
||||
logic if_enable;
|
||||
always_comb begin
|
||||
if
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let items = offering("rank", "top.sv", top, " if");
|
||||
let symbol = find(&items, "if_enable").expect("a declaration in scope");
|
||||
let template = find(&items, "if begin/end").expect("the template");
|
||||
assert_eq!(tier(symbol), TIER_SCOPE);
|
||||
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statement_templates_and_item_templates_swap_places_with_the_position() {
|
||||
// One prefix, `i`, reaching `if` in one place and `initial` in the
|
||||
// other — so this is the gate and not the filter.
|
||||
let inside = offering(
|
||||
"posstmt",
|
||||
"top.sv",
|
||||
"module top;\n always_comb begin\n i\n end\nendmodule\n",
|
||||
" i",
|
||||
);
|
||||
assert!(template_labels(&inside).contains(&"if begin/end"));
|
||||
assert!(
|
||||
!template_labels(&inside).contains(&"initial begin/end"),
|
||||
"an initial block is not a statement: {:?}",
|
||||
template_labels(&inside)
|
||||
);
|
||||
|
||||
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
|
||||
assert!(template_labels(&at_item).contains(&"initial begin/end"));
|
||||
assert!(
|
||||
!template_labels(&at_item).contains(&"if begin/end"),
|
||||
"a bare if is not a module item: {:?}",
|
||||
template_labels(&at_item)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_template_is_a_module_item_and_nothing_else() {
|
||||
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
|
||||
assert_eq!(
|
||||
template_labels(&at_item),
|
||||
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
|
||||
"and `alw` finds every one of them"
|
||||
);
|
||||
|
||||
let inside = offering(
|
||||
"alwstmt",
|
||||
"top.sv",
|
||||
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
|
||||
" alw",
|
||||
);
|
||||
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
|
||||
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
|
||||
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
|
||||
|
||||
let inside = offering(
|
||||
"declstmt",
|
||||
"top.sv",
|
||||
"module top;\n always_comb begin\n log\n end\nendmodule\n",
|
||||
" log",
|
||||
);
|
||||
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_name_decides_which_dialect_is_offered() {
|
||||
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
|
||||
assert!(template_labels(&sv).contains(&"logic name;"));
|
||||
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
|
||||
|
||||
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
|
||||
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
|
||||
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
|
||||
|
||||
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
|
||||
assert_eq!(template_labels(®), ["reg name;", "reg [N:0] name;"]);
|
||||
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
|
||||
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
|
||||
|
||||
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
|
||||
assert_eq!(
|
||||
template_labels(&always),
|
||||
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
|
||||
"and no always_ff, which a .v file's compiler would reject"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_else_template_follows_an_end_on_the_same_line() {
|
||||
let top = "\
|
||||
module top;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
end el
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let items = offering("elsetail", "top.sv", top, "end el");
|
||||
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
|
||||
assert_eq!(
|
||||
inserted(find(&items, "else if").expect("the else-if template")),
|
||||
"else if (${1:cond}) begin\n $0\n end"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
|
||||
// The other half of the same rule: `x = if` is an expression, not a
|
||||
// place a template belongs — and the general tiers still answer there.
|
||||
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
|
||||
let items = offering("midline", "top.sv", top, "x = if");
|
||||
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
|
||||
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_template_is_offered_where_a_statement_cannot_go() {
|
||||
for (name, top, needle) in [
|
||||
// A generate block is item position, not statement position.
|
||||
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
|
||||
// A `case` arm wants `label:`, not a bare statement.
|
||||
(
|
||||
"casearm",
|
||||
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
|
||||
" if",
|
||||
),
|
||||
// Nothing at all is open here.
|
||||
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
|
||||
// A port list is not a statement, however much it starts a line.
|
||||
("ports", "module top (\n if\n);\nendmodule\n", " if"),
|
||||
] {
|
||||
let items = offering(name, "top.sv", top, needle);
|
||||
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subprogram_body_is_statement_position() {
|
||||
for (name, top, needle) in [
|
||||
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
|
||||
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
|
||||
(
|
||||
"fnbegin",
|
||||
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
|
||||
" if",
|
||||
),
|
||||
] {
|
||||
let items = offering(name, "top.sv", top, needle);
|
||||
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_templated_is_offered_inside_a_comment() {
|
||||
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
|
||||
assert!(completions(&ws, &uri, position, true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_without_snippet_support_gets_the_template_filled_in() {
|
||||
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
|
||||
let items = items(completions(&ws, &uri, position, false));
|
||||
let item = find(&items, "if begin/end").expect("the if template");
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
let text = inserted(item);
|
||||
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
|
||||
assert_eq!(text, "if (cond) begin\n\n end");
|
||||
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
|
||||
assert!(
|
||||
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
|
||||
"the inserted text must parse: {text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_templates_documentation_shows_what_it_expands_to() {
|
||||
let top = "module top;\n alw\nendmodule\n";
|
||||
let items = offering("tmpldocs", "top.sv", top, " alw");
|
||||
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
|
||||
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
|
||||
panic!("markdown documentation");
|
||||
};
|
||||
// Fenced with the language id the extension's TextMate grammar is
|
||||
// registered for, so the panel renders highlighted rather than grey.
|
||||
assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value);
|
||||
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
|
||||
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 4 — keywords
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
|
||||
fn every_keyword_the_lexer_knows_is_offered() {
|
||||
let top = "module top;\n assign x = alw\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("keyword", top, "= alw");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let keywords: Vec<&str> =
|
||||
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
|
||||
assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]);
|
||||
let always = find(&items, "always").expect("`always`");
|
||||
assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD));
|
||||
assert_eq!(inserted(always), "always");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_keyword_tier_is_exactly_the_lexers_list() {
|
||||
let top = "module top;\n assign x = \nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("allkeywords", top, "= ");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let offered: HashSet<&str> =
|
||||
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
|
||||
let known: HashSet<&str> = KEYWORDS.iter().copied().collect();
|
||||
assert_eq!(offered, known, "no keyword may be missing and none invented");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tiers, ordering and dedup
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() {
|
||||
let tree = Tree::new("tiers");
|
||||
tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n");
|
||||
tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n");
|
||||
let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= w");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
|
||||
assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE);
|
||||
assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX);
|
||||
assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD);
|
||||
assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD);
|
||||
|
||||
let scope = find(&items, "w_local").expect("in scope");
|
||||
let word = find(&items, "w_elsewhere").expect("a project word");
|
||||
assert!(scope.sort_text < word.sort_text, "the client sorts scope above words");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() {
|
||||
let tree = Tree::new("dedup");
|
||||
// The same name, declared here and used elsewhere in the project.
|
||||
tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n");
|
||||
let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= shared");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let hits: Vec<&CompletionItem> =
|
||||
items.iter().filter(|i| i.label == "shared_name").collect();
|
||||
assert_eq!(hits.len(), 1, "{hits:#?}");
|
||||
assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins");
|
||||
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() {
|
||||
let top = "\
|
||||
module top #(parameter int WIDTH = 8) (input logic clk);
|
||||
typedef logic [1:0] pair_t;
|
||||
logic [WIDTH-1:0] data;
|
||||
function int f(); return 0; endfunction
|
||||
assign x =
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri, position) = asking("kinds", top, "assign x =");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind;
|
||||
assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT));
|
||||
assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD));
|
||||
assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER));
|
||||
assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE));
|
||||
assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION));
|
||||
assert_eq!(
|
||||
find(&items, "data").expect("data").detail.as_deref(),
|
||||
Some("logic [WIDTH-1:0] data;"),
|
||||
"the declaration as written"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
|
||||
// `inner` is declared in a block the cursor is not in, so it may only
|
||||
// arrive as a project word — never as a visible declaration.
|
||||
let top = "\
|
||||
module top;
|
||||
initial begin : b
|
||||
integer inner_only;
|
||||
end
|
||||
initial begin
|
||||
x = inner
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "inner_only").expect("known as a word at least");
|
||||
assert_eq!(tier(item), TIER_WORD, "{item:#?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A workspace holding the name the whole round is about, a scatter to
|
||||
/// rank it against, and a `ce…` name that only a prefix reaches.
|
||||
fn typing(name: &str) -> (Tree, Workspace, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write(
|
||||
"ast.sv",
|
||||
"module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\
|
||||
endmodule\n",
|
||||
);
|
||||
let path = tree.write("top.sv", "module top;\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
(tree, ws, uri)
|
||||
}
|
||||
|
||||
/// The response to `typed`, written mid-expression in `top.sv` — the
|
||||
/// position where no tier is position-gated off.
|
||||
fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option<CompletionResponse> {
|
||||
let text = format!("module top;\n assign x = {typed}\nendmodule\n");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let offset =
|
||||
(text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32;
|
||||
let position = ws.document(uri).expect("open").positions().position(offset);
|
||||
completions(ws, uri, position, true)
|
||||
}
|
||||
|
||||
/// The headline: three characters reach a name no prefix ever would.
|
||||
#[test]
|
||||
fn three_characters_reach_a_name_a_prefix_never_would() {
|
||||
let (_tree, mut ws, uri) = typing("fuzzyhit");
|
||||
for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] {
|
||||
let found = items(after_typing(&mut ws, &uri, typed));
|
||||
let item = find(&found, "clk_osc_en_q")
|
||||
.unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found)));
|
||||
assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project");
|
||||
assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted");
|
||||
}
|
||||
}
|
||||
|
||||
/// …and the edit still replaces exactly what was typed, which is the
|
||||
/// whole reason a fuzzy hit is usable at all: `clkenq` becomes
|
||||
/// `clk_osc_en_q`, not `clkenqclk_osc_en_q`.
|
||||
#[test]
|
||||
fn a_fuzzy_hit_replaces_exactly_the_typed_word() {
|
||||
let (_tree, mut ws, uri) = typing("fuzzyedit");
|
||||
let found = items(after_typing(&mut ws, &uri, "clkenq"));
|
||||
let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit");
|
||||
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
|
||||
panic!("a plain edit");
|
||||
};
|
||||
// ` assign x = clkenq` — the word starts at column 13 and the cursor
|
||||
// is at its end.
|
||||
assert_eq!(edit.range.start, Position { line: 1, character: 13 });
|
||||
assert_eq!(edit.range.end, Position { line: 1, character: 19 });
|
||||
assert_eq!(edit.new_text, "clk_osc_en_q");
|
||||
assert_eq!(item.filter_text, None, "the client filters on the label, as it should");
|
||||
}
|
||||
|
||||
/// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters
|
||||
/// in order and must still not reach it.
|
||||
#[test]
|
||||
fn two_characters_match_by_prefix_and_nothing_else() {
|
||||
let (_tree, mut ws, uri) = typing("fuzzyfloor");
|
||||
for typed in ["c", "ce"] {
|
||||
let found = items(after_typing(&mut ws, &uri, typed));
|
||||
assert!(!found.is_empty(), "premise: {typed:?} answers something");
|
||||
for item in &found {
|
||||
assert!(
|
||||
starts_with_ignore_case(&item.label, typed),
|
||||
"{:?} is not a prefix match for {typed:?}",
|
||||
item.label
|
||||
);
|
||||
}
|
||||
}
|
||||
// The discriminator, spelled out: `ce` would reach it if it were fuzzy
|
||||
// (`c` at 0, `e` at 8), and `cen` — one character more — does.
|
||||
let two = items(after_typing(&mut ws, &uri, "ce"));
|
||||
assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two));
|
||||
assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two));
|
||||
let three = items(after_typing(&mut ws, &uri, "cen"));
|
||||
assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three));
|
||||
}
|
||||
|
||||
/// The 1- and 2-character answers, pinned against what they were before
|
||||
/// fuzzy matching existed. The keyword tier is checked as a set rather
|
||||
/// than listed, so adding a reserved word to the lexer does not break a
|
||||
/// test about completion.
|
||||
#[test]
|
||||
fn the_short_answers_are_what_they_always_were() {
|
||||
let (_tree, mut ws, uri) = typing("fuzzygolden");
|
||||
for (typed, expected) in [
|
||||
// `c` itself is in the list because the buffer being typed in
|
||||
// holds it as an `Ident` token — behaviour this round did not
|
||||
// touch, pinned here because a golden that quietly lost it would
|
||||
// be a change.
|
||||
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
|
||||
("ce", vec!["ce", "celsius"]),
|
||||
] {
|
||||
let found = items(after_typing(&mut ws, &uri, typed));
|
||||
let named: Vec<&str> = found
|
||||
.iter()
|
||||
.filter(|item| tier(item) != TIER_KEYWORD)
|
||||
.map(|item| item.label.as_str())
|
||||
.collect();
|
||||
assert_eq!(named, expected, "the names {typed:?} answers with");
|
||||
let keywords: Vec<&str> = found
|
||||
.iter()
|
||||
.filter(|item| tier(item) == TIER_KEYWORD)
|
||||
.map(|item| item.label.as_str())
|
||||
.collect();
|
||||
let expected_keywords: Vec<&str> =
|
||||
KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect();
|
||||
assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with");
|
||||
}
|
||||
}
|
||||
|
||||
/// **The `isIncomplete` trap.** VS Code asks again on the next keystroke
|
||||
/// only when the last answer said it was incomplete, so a complete
|
||||
/// two-character answer would swallow the third keystroke and fuzzy would
|
||||
/// never fire at all.
|
||||
#[test]
|
||||
fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() {
|
||||
let (_tree, mut ws, uri) = typing("fuzzyincomplete");
|
||||
for typed in ["", "c", "ce"] {
|
||||
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else {
|
||||
panic!("a completion list for {typed:?}");
|
||||
};
|
||||
assert!(list.is_incomplete, "{typed:?} must ask to be asked again");
|
||||
}
|
||||
// From the floor up the ordinary rule stands: complete when the whole
|
||||
// hit set fit, which is sound because appending a character can only
|
||||
// ever shrink it.
|
||||
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else {
|
||||
panic!("a completion list");
|
||||
};
|
||||
assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len());
|
||||
}
|
||||
|
||||
/// A prefix match is the best subsequence match there is, and the list
|
||||
/// says so — asserted on the order of the array, which is what the cap
|
||||
/// cuts and what a client that does not re-rank shows.
|
||||
#[test]
|
||||
fn a_prefix_hit_outranks_a_scattered_one() {
|
||||
let (_tree, mut ws, uri) = typing("fuzzyrank");
|
||||
let found = items(after_typing(&mut ws, &uri, "clk"));
|
||||
let at = |label: &str| {
|
||||
found
|
||||
.iter()
|
||||
.position(|item| item.label == label)
|
||||
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
|
||||
};
|
||||
assert!(
|
||||
at("clk_osc_en_q") < at("c_l_k_scatter"),
|
||||
"the prefix hit leads: {:?}",
|
||||
labels(&found)
|
||||
);
|
||||
}
|
||||
|
||||
/// Scoring the boundaries is visible in the order, not only in the score:
|
||||
/// a run that starts after an underscore beats the same letters buried
|
||||
/// mid-word.
|
||||
#[test]
|
||||
fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() {
|
||||
let tree = Tree::new("fuzzyboundary");
|
||||
tree.write(
|
||||
"ast.sv",
|
||||
"module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n",
|
||||
);
|
||||
let path = tree.write("top.sv", "module top;\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let found = items(after_typing(&mut ws, &uri, "ena"));
|
||||
let at = |label: &str| {
|
||||
found
|
||||
.iter()
|
||||
.position(|item| item.label == label)
|
||||
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
|
||||
};
|
||||
assert!(
|
||||
at("osc_ena_ready") < at("xxenaxx_ready"),
|
||||
"the boundary run leads: {:?}",
|
||||
labels(&found)
|
||||
);
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
/// Dedup survives the change: a name two tiers can reach is offered once,
|
||||
/// by the better tier, whichever way it was matched.
|
||||
#[test]
|
||||
fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() {
|
||||
let tree = Tree::new("fuzzydedup");
|
||||
// The same name, declared in this buffer (tier 1) and used in the
|
||||
// project (tier 5), reachable from `clkenq` by neither prefix.
|
||||
tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n");
|
||||
let path = tree.write("top.sv", "module top;\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let offset = (text.find("= clkenq").expect("needle") + 8) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let found = items(completions(&ws, &uri, position, true));
|
||||
let hits: Vec<&CompletionItem> =
|
||||
found.iter().filter(|item| item.label == "clk_osc_en_q").collect();
|
||||
assert_eq!(hits.len(), 1, "{hits:#?}");
|
||||
assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word");
|
||||
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE));
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
/// The tiers that did **not** go fuzzy, pinned so the split is a decision
|
||||
/// and not a drift: keywords, templates and macro names still match by
|
||||
/// prefix, and the module tier still matches by substring.
|
||||
#[test]
|
||||
fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() {
|
||||
let tree = Tree::new("fuzzyunchanged");
|
||||
tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n");
|
||||
tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n");
|
||||
let path = tree.write("top.sv", "module top;\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
|
||||
// Mid-expression: the macro name is offered bare by tier 2 and must
|
||||
// not be reachable by subsequence, and neither is a keyword.
|
||||
let found = items(after_typing(&mut ws, &uri, "clkenq"));
|
||||
assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found));
|
||||
let found = items(after_typing(&mut ws, &uri, "alws"));
|
||||
assert!(labels(&found).is_empty() || !labels(&found).contains(&"always"));
|
||||
|
||||
// A backtick still answers by prefix only.
|
||||
let text = "module top;\n assign x = `CLKENQ\nendmodule\n";
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way");
|
||||
|
||||
// …and the module tier is still a substring match, which is wider
|
||||
// than a prefix and narrower than a subsequence.
|
||||
let text = "module top;\n osc_en\nendmodule\n";
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let offset = (text.find("osc_en").expect("needle") + 6) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let found = items(completions(&ws, &uri, position, true));
|
||||
let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect();
|
||||
assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it");
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
/// The scope tier goes fuzzy too, with no mask table behind it — it is
|
||||
/// the one tier computed per request.
|
||||
#[test]
|
||||
fn a_declaration_in_scope_is_reached_by_subsequence() {
|
||||
let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq");
|
||||
let found = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&found, "clk_osc_en_q").expect("the declaration");
|
||||
assert_eq!(tier(item), TIER_SCOPE);
|
||||
assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;"));
|
||||
}
|
||||
|
||||
/// The index tier goes fuzzy too — a package member is reached the same
|
||||
/// way a project word is.
|
||||
#[test]
|
||||
fn a_project_declaration_is_reached_by_subsequence() {
|
||||
let tree = Tree::new("fuzzyindex");
|
||||
tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n");
|
||||
let path = tree.write("top.sv", "module top;\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let found = items(after_typing(&mut ws, &uri, "clkenq"));
|
||||
let item = find(&found, "CLK_OSC_EN_Q").expect("the package member");
|
||||
assert_eq!(tier(item), TIER_INDEX);
|
||||
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT));
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() {
|
||||
let tree = Tree::new("overlay");
|
||||
let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n");
|
||||
let top = "module top;\n assign x = ov\nendmodule\n";
|
||||
let (_tree, mut ws, uri, position) = opened(tree, top, "= ov");
|
||||
|
||||
let other_uri = path_to_uri(&other).expect("uri");
|
||||
ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string());
|
||||
ws.rebuild_index();
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! What is typed: the identifier run ending at the cursor and what stands
|
||||
//! around it — a backtick, a `.` or a `::`, and the spine a separator
|
||||
//! follows.
|
||||
//!
|
||||
//! Everything here reads the buffer's *text* backwards from the cursor and
|
||||
//! nothing else; the token-stream questions (is this an item position, a
|
||||
//! statement position) are `site.rs`'s. The one shape decision made here is
|
||||
//! `Word::sep`: a separator says the response is a member list and nothing
|
||||
//! else, which is why the spine is read this early.
|
||||
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// What may stand between the start of a line and a statement: the `end` of
|
||||
/// the block before it and the `else` that chains onto it. Anything else on
|
||||
/// the line means the word being typed is part of an expression, not the start
|
||||
/// of a statement.
|
||||
const STATEMENT_HEADS: &[&str] = &["end", "else", "end else"];
|
||||
|
||||
/// The identifier the user is part-way through typing, and what stands around
|
||||
/// it.
|
||||
pub(super) struct Word {
|
||||
/// The identifier run, backtick excluded. Empty when the cursor follows
|
||||
/// something that is not an identifier character.
|
||||
pub(super) text: String,
|
||||
/// Where the run starts — the byte after the backtick, when there is one.
|
||||
pub(super) start: u32,
|
||||
/// Whether a `` ` `` immediately precedes the run, making this a macro
|
||||
/// name being typed and nothing else.
|
||||
pub(super) backtick: bool,
|
||||
/// Whether nothing but whitespace precedes the run on its line.
|
||||
///
|
||||
/// Half of the *module* gate, and deliberately blunt: an instantiation is
|
||||
/// written at the start of a line, and a word that is not (`assign x =
|
||||
/// fo|`, `logic fo|`, `.clk(cl|`) is somewhere a module name would be
|
||||
/// wrong. It costs the rare user who writes two items on one line their
|
||||
/// skeleton — a far better failure than offering a fifteen-line
|
||||
/// instantiation in the middle of an expression. Every other tier ignores
|
||||
/// it: a name is a name wherever it is written.
|
||||
pub(super) at_line_start: bool,
|
||||
/// Whether the only thing before the run on its line is [`STATEMENT_HEADS`]
|
||||
/// — the `end` a statement follows, or the `else` it hangs off.
|
||||
///
|
||||
/// Half of the *template* gate, and the reason `end else if` completes: a
|
||||
/// statement is written at the start of a line or right after one of those
|
||||
/// two words, and nowhere else.
|
||||
pub(super) statement_head: bool,
|
||||
/// The `.` or `::` the run immediately follows, when it follows one.
|
||||
///
|
||||
/// Its presence alone decides the shape of the whole response: a
|
||||
/// separator says the user is naming a **member** of what stands before
|
||||
/// it, and nothing else may be written there — so the member answer is
|
||||
/// exclusive, exactly as the backtick's is. A lone `:` (a case item, a
|
||||
/// label, a ternary) is not a separator and is `None`.
|
||||
pub(super) sep: Option<Sep>,
|
||||
/// What stands before the separator, when it is a spine this can read.
|
||||
/// `None` with a `sep` set means the response is nothing at all: there is
|
||||
/// a member question here and no head to answer it about.
|
||||
pub(super) spine: Option<Spine>,
|
||||
}
|
||||
|
||||
/// The two separators that make the run after them a member name.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Sep {
|
||||
/// `handle.`, `vif.cb.`, `this.` — a member of a *value*'s type.
|
||||
Dot,
|
||||
/// `pkg::`, `cls::` — a member of a named unit.
|
||||
Scope,
|
||||
}
|
||||
|
||||
/// The head of a member access as the buffer spells it: the first identifier
|
||||
/// of the chain, and the names between it and the cursor.
|
||||
///
|
||||
/// `item.hdr.` is `head = "item"`, `mids = ["hdr"]` — exactly the two
|
||||
/// arguments [`vlog_semantic::Semantics::member_site`] takes, because they
|
||||
/// are exactly what `bind.rs`'s own `spine` records for the same expression.
|
||||
/// For [`Sep::Scope`] the head is the whole `::` path (`pkg`, `pkg::cls`) and
|
||||
/// `mids` is empty.
|
||||
pub(super) struct Spine {
|
||||
pub(super) head: String,
|
||||
pub(super) mids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Word {
|
||||
/// The bytes a completion replaces: the word as typed.
|
||||
pub(super) fn range(&self, cursor: u32) -> TextRange {
|
||||
TextRange::new(self.start, cursor)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier run ending at the cursor, and the shape of the line it sits
|
||||
/// on. `None` only when the cursor is not on a character boundary of the text
|
||||
/// the server holds.
|
||||
pub(super) fn typed_word(doc: &Document, cursor: u32) -> Option<Word> {
|
||||
let text = doc.text.get(..cursor as usize)?;
|
||||
let head = text.trim_end_matches(is_ident_char);
|
||||
let start = head.len();
|
||||
let backtick = head.ends_with('`');
|
||||
let bare = match backtick {
|
||||
true => head.get(..head.len() - 1)?,
|
||||
false => head,
|
||||
};
|
||||
let line_start = bare.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
let head = bare.get(line_start..)?;
|
||||
let at_line_start = !backtick && line_head_is_blank(&doc.text, start as u32);
|
||||
// `end else` and `end else` are the same head; nothing else is compared,
|
||||
// so one `split_whitespace` join is the whole normalization needed.
|
||||
let words = head.split_whitespace().collect::<Vec<&str>>().join(" ");
|
||||
let statement_head = !backtick && STATEMENT_HEADS.contains(&words.as_str());
|
||||
// A backtick admits only a macro name, and a macro name follows no
|
||||
// separator, so the two questions never both apply.
|
||||
let (sep, spine) = match backtick {
|
||||
true => (None, None),
|
||||
false => separator(bare),
|
||||
};
|
||||
Some(Word {
|
||||
text: text.get(start..)?.to_string(),
|
||||
start: start as u32,
|
||||
backtick,
|
||||
at_line_start,
|
||||
statement_head,
|
||||
sep,
|
||||
spine,
|
||||
})
|
||||
}
|
||||
|
||||
/// The separator `before` ends with, and the head spine standing before that.
|
||||
///
|
||||
/// `::` is checked first, so a `pkg::` is never read as the lone `:` of a
|
||||
/// case item, a block label or a ternary — that one is deliberately **not** a
|
||||
/// separator, and a request there falls through to the ordinary six tiers
|
||||
/// exactly as it always did.
|
||||
fn separator(before: &str) -> (Option<Sep>, Option<Spine>) {
|
||||
if let Some(rest) = before.strip_suffix("::") {
|
||||
return (Some(Sep::Scope), scope_head(rest));
|
||||
}
|
||||
if let Some(rest) = before.strip_suffix('.') {
|
||||
return (Some(Sep::Dot), dot_spine(rest));
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
|
||||
/// The `::` path ending at `before`: `pkg`, `pkg::cls`.
|
||||
fn scope_head(before: &str) -> Option<Spine> {
|
||||
let mut segments = Vec::new();
|
||||
let mut rest = before;
|
||||
loop {
|
||||
let (head, name) = split_ident(rest)?;
|
||||
segments.push(name.to_string());
|
||||
match head.strip_suffix("::") {
|
||||
Some(next) => rest = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
segments.reverse();
|
||||
Some(Spine { head: segments.join("::"), mids: Vec::new() })
|
||||
}
|
||||
|
||||
/// The `.`-joined spine ending at `before`: `item`, `cfg.vif`, `q[i]`,
|
||||
/// `this`, `super`.
|
||||
///
|
||||
/// **What it reads, and nothing else**: identifiers joined by `.`, each
|
||||
/// optionally carrying balanced `[…]` index suffixes, which are stripped —
|
||||
/// `q[i].` and `arr[3][k].` name a member of the element type, which is the
|
||||
/// declared type name either way. Everything else answers `None`, and `None`
|
||||
/// means the response is nothing at all rather than a guess: a call
|
||||
/// (`f().b`), a cast, a concatenation, a macro invocation, a `::`-qualified
|
||||
/// head (`pkg::cls.`, which is not how a class member is written anyway), and
|
||||
/// whitespace anywhere in the spine (`a . b`, legal SystemVerilog nobody
|
||||
/// writes — refusing it costs a popup, accepting it would mean deciding where
|
||||
/// an expression ends by scanning backwards over arbitrary text).
|
||||
fn dot_spine(before: &str) -> Option<Spine> {
|
||||
let mut segments: Vec<String> = Vec::new();
|
||||
let mut rest = before;
|
||||
loop {
|
||||
let (head, name) = split_ident(strip_indices(rest)?)?;
|
||||
segments.push(name.to_string());
|
||||
match head.strip_suffix('.') {
|
||||
Some(next) => rest = next,
|
||||
None => {
|
||||
// A head reached through `::` is a unit, not a value, and
|
||||
// `member_site` resolves the head on the lexical chain.
|
||||
if head.ends_with(':') {
|
||||
return None;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
segments.reverse();
|
||||
let mut mids = segments;
|
||||
let head = mids.remove(0);
|
||||
Some(Spine { head, mids })
|
||||
}
|
||||
|
||||
/// `text` split at the start of the identifier run it ends with, as
|
||||
/// (what precedes it, the identifier). `None` when it does not end with one,
|
||||
/// or when the run starts with a digit — that is a number, not a name.
|
||||
fn split_ident(text: &str) -> Option<(&str, &str)> {
|
||||
let head = text.trim_end_matches(is_ident_char);
|
||||
let name = text.get(head.len()..)?;
|
||||
if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
Some((head, name))
|
||||
}
|
||||
|
||||
/// `text` with every balanced `[…]` it ends with removed. `None` when a `]`
|
||||
/// has no matching `[` — an expression this cannot read, so nothing is
|
||||
/// offered for it.
|
||||
fn strip_indices(text: &str) -> Option<&str> {
|
||||
let mut rest = text;
|
||||
while rest.ends_with(']') {
|
||||
let mut depth = 0usize;
|
||||
let mut opened = None;
|
||||
for (i, byte) in rest.bytes().enumerate().rev() {
|
||||
match byte {
|
||||
b']' => depth += 1,
|
||||
b'[' => {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
opened = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
rest = rest.get(..opened?)?;
|
||||
}
|
||||
Some(rest)
|
||||
}
|
||||
|
||||
fn is_ident_char(ch: char) -> bool {
|
||||
ch.is_ascii_alphanumeric() || ch == '_' || ch == '$'
|
||||
}
|
||||
|
||||
/// Whether nothing but indentation stands before `at` on its line — half of
|
||||
/// the module gate, shared by [`typed_word`] and
|
||||
/// [`at_instantiation_site`](super::site::at_instantiation_site).
|
||||
pub(super) fn line_head_is_blank(text: &str, at: u32) -> bool {
|
||||
let Some(head) = text.get(..at as usize) else { return false };
|
||||
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
head.get(line_start..).is_some_and(|head| head.chars().all(|c| c == ' ' || c == '\t'))
|
||||
}
|
||||
@@ -23,7 +23,20 @@ pub const SOURCE: &str = "lucisv";
|
||||
/// The missing-closer warnings sit between the two: they explain a parse
|
||||
/// error rather than add an opinion, and they exist at all only when the parse
|
||||
/// already failed (`pairs::missing_end_diagnostics`).
|
||||
///
|
||||
/// `#[cfg(test)]` for the same reason `lint::diagnostics` is: the server
|
||||
/// always has a workspace and always calls [`all_in`], so this is the door the
|
||||
/// tests that predate the project-aware pass come in by.
|
||||
#[cfg(test)]
|
||||
pub fn all(doc: &Document) -> Vec<Diagnostic> {
|
||||
all_in(doc, &crate::lint::LintRun::default())
|
||||
}
|
||||
|
||||
/// [`all`] for a lint pass that knows what the project says — the workspace's
|
||||
/// rule selection and its identifier census
|
||||
/// (`docs/features/semantic-lints-on/README.md`). The parse and missing-closer
|
||||
/// halves are unaffected by either; only the lint pass reads `run`.
|
||||
pub fn all_in(doc: &Document, run: &crate::lint::LintRun) -> Vec<Diagnostic> {
|
||||
// A buffer on the large-file fast path was never parsed, so there is
|
||||
// nothing to say about it — and both passes below would read its *text*
|
||||
// (the lint context builds one, the fence filter scans for them), which is
|
||||
@@ -35,7 +48,7 @@ pub fn all(doc: &Document) -> Vec<Diagnostic> {
|
||||
}
|
||||
let mut all = diagnostics(doc);
|
||||
all.extend(crate::pairs::missing_end_diagnostics(doc));
|
||||
all.extend(crate::lint::diagnostics(doc));
|
||||
all.extend(crate::lint::diagnostics_in(doc, run));
|
||||
all
|
||||
}
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
|
||||
/// several reachable files do — the honest all-candidates list from before
|
||||
/// this feature stands: an empty include graph must never make hover worse
|
||||
/// than it was (`docs/features/include-nav/README.md`).
|
||||
fn narrowed_to_the_include_graph<'a>(
|
||||
pub(crate) fn narrowed_to_the_include_graph<'a>(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
candidates: Vec<(FileId, &'a Define)>,
|
||||
@@ -106,7 +106,7 @@ fn narrowed_to_the_include_graph<'a>(
|
||||
}
|
||||
|
||||
/// The macro's name: the identifier after the backtick, argument list excluded.
|
||||
fn macro_name(token: &Token) -> Option<&str> {
|
||||
pub(crate) fn macro_name(token: &Token) -> Option<&str> {
|
||||
let rest = token.text.strip_prefix('`')?;
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$');
|
||||
let name = match end {
|
||||
@@ -865,7 +865,10 @@ mod tests {
|
||||
let text = "module m;\n localparam WIDTH = 8;\n wire [WIDTH-1:0] a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "[WIDTH") + 1).expect("hover"));
|
||||
assert!(body.contains("**parameter**"), "got {body}");
|
||||
// The heading says what the source says. Since 2026-09-02 a
|
||||
// `localparam` is its own kind, so the label and the snippet below it
|
||||
// in the same card no longer disagree.
|
||||
assert!(body.contains("**localparam**"), "got {body}");
|
||||
// Fenced with the grammar's language id — see the macro hover test.
|
||||
assert!(
|
||||
body.contains("```systemverilog\n localparam WIDTH = 8;\n```"),
|
||||
@@ -1279,7 +1282,7 @@ endmodule
|
||||
let (dir, ws, uri) = included("pkgdecl", &[("p.sv", pkg), ("top.sv", top)]);
|
||||
|
||||
let body = text_of(&hover(&ws, &uri, at(top, "WIDTH-1")).expect("hover"));
|
||||
assert!(body.contains("**parameter** — declared in `p.sv:2`"), "got {body}");
|
||||
assert!(body.contains("**localparam** — declared in `p.sv:2`"), "got {body}");
|
||||
assert!(body.contains("```systemverilog\n localparam WIDTH = 8;\n```"), "got {body}");
|
||||
|
||||
let body = text_of(&hover(&ws, &uri, at(top, "nibble_t n")).expect("hover"));
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! `lucisv.instantiate` — the instantiation skeleton as an execute command,
|
||||
//! for clients that have no `textDocument/inlineCompletion`.
|
||||
//!
|
||||
//! Since the names-only completion popup of 2026-08-30 the full skeleton is
|
||||
//! offered by exactly one surface: ghost text. A client without that request —
|
||||
//! Neovim's built-in LSP, today — had no path to it at all
|
||||
//! (`docs/topo.md` §2.9-19). A command is the path a keybinding can take,
|
||||
//! exactly as `lucisv.removePort` is for a Vim user with no lightbulb.
|
||||
//!
|
||||
//! **One planner.** Everything here goes through `completion::plan_for` and
|
||||
//! `completion::nearest_definition`, the same two calls `inline.rs`'s ghost
|
||||
//! makes, so the command cannot offer a skeleton the ghost would not — the
|
||||
//! difference is the *rendering*: a snippet with tabstops there, plain text
|
||||
//! with each fill-in written as its default here. See
|
||||
//! `docs/features/bind-semantics/README.md`.
|
||||
|
||||
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use lsp_types::{Position, TextEdit, Uri, WorkspaceEdit};
|
||||
use serde_json::Value;
|
||||
use vlog_refactor::{InstantiationPlan, Site};
|
||||
|
||||
use crate::completion;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// Insert an instantiation of a module at a position:
|
||||
/// `[uri, position, "module_name"]`.
|
||||
pub const INSTANTIATE: &str = "lucisv.instantiate";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![INSTANTIATE.to_string()]
|
||||
}
|
||||
|
||||
/// Run `lucisv.instantiate`, or say why it cannot run.
|
||||
///
|
||||
/// The answer is a one-edit `WorkspaceEdit` inserting the skeleton at the
|
||||
/// given position. `server.rs` pushes it as a `workspace/applyEdit` the way
|
||||
/// it does every port command's — this module knows nothing about that.
|
||||
///
|
||||
/// **An escaped identifier is fine here.** The ghost declines such a plan
|
||||
/// because an inline completion has no plain-text spelling to fall back to
|
||||
/// (`inline::NoGhost::EscapedIdentifier`); a `TextEdit` is plain text by
|
||||
/// construction, so there is nothing to escape and nothing to decline.
|
||||
pub fn execute(ws: &Workspace, arguments: &[Value]) -> Result<WorkspaceEdit, String> {
|
||||
let uri: Uri =
|
||||
arguments
|
||||
.first()
|
||||
.and_then(|value| serde_json::from_value(value.clone()).ok())
|
||||
.ok_or_else(|| format!("{INSTANTIATE} wants a document URI as its first argument."))?;
|
||||
let position: Position = arguments
|
||||
.get(1)
|
||||
.and_then(|value| serde_json::from_value(value.clone()).ok())
|
||||
.ok_or_else(|| format!("{INSTANTIATE} wants a position as its second argument."))?;
|
||||
let module = arguments
|
||||
.get(2)
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| format!("{INSTANTIATE} wants a module name as its third argument."))?;
|
||||
let doc = ws.document(&uri).ok_or_else(|| {
|
||||
format!("{INSTANTIATE} can only write into a buffer lucisv has been sent.")
|
||||
})?;
|
||||
let offset = doc.positions().offset(position);
|
||||
// The same gate tier 0 and the ghost ask, so the three surfaces agree on
|
||||
// where an instantiation may go.
|
||||
if !completion::at_instantiation_site(doc, offset) {
|
||||
return Err(format!(
|
||||
"An instantiation cannot be written at {}:{}.",
|
||||
position.line, position.character
|
||||
));
|
||||
}
|
||||
let plan = plan_at(ws, doc, module)?;
|
||||
let text = plan.render(&completion::layout_at(ws, doc, offset));
|
||||
let edit =
|
||||
TextEdit { range: lsp_types::Range { start: position, end: position }, new_text: text };
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
|
||||
changes.insert(uri, vec![edit]);
|
||||
Ok(WorkspaceEdit::new(changes))
|
||||
}
|
||||
|
||||
/// The plan for `module` as read from the file that declares it.
|
||||
///
|
||||
/// The same two calls `inline.rs`'s ghost makes, in the same order and with
|
||||
/// the same view cache, so the two surfaces cannot plan different skeletons.
|
||||
/// `pub(crate)` for the test that pins exactly that.
|
||||
pub(crate) fn plan_at(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
module: &str,
|
||||
) -> Result<InstantiationPlan, String> {
|
||||
let path = completion::nearest_definition(ws.index(), module, doc.path.as_deref())
|
||||
.ok_or_else(|| format!("lucisv does not know a module called `{module}`."))?;
|
||||
// The site is only read for the ports the skeleton may auto-connect, and
|
||||
// the position was already checked above.
|
||||
let site = Site { semantics: &doc.semantics, offset: 0 };
|
||||
let text = match ws.file_view(path) {
|
||||
Some(view) => return completion::plan_for(ws.index(), module, &view.text, site),
|
||||
None => {
|
||||
ws.text_of(path).ok_or_else(|| format!("lucisv cannot read {}.", path.display()))?
|
||||
}
|
||||
};
|
||||
completion::plan_for(ws.index(), module, &text, site)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::inline;
|
||||
use crate::uri::path_to_uri;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use vlog_refactor::Layout;
|
||||
|
||||
/// 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_instantiate_{}_{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);
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
const SUB: &str =
|
||||
"module sub #(parameter int W = 8) (\n input logic clk,\n output logic [W-1:0] q\n);\nendmodule\n";
|
||||
|
||||
fn workspace(tree: &Tree, top: &str) -> (Workspace, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
let path = tree.write("top.sv", top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
fn text_of(edit: &WorkspaceEdit, uri: &Uri) -> String {
|
||||
let edits = edit.changes.as_ref().expect("changes").get(uri).expect("one file's edits");
|
||||
assert_eq!(edits.len(), 1, "one insertion, nothing else");
|
||||
edits[0].new_text.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_inserts_a_skeleton_at_the_position() {
|
||||
let tree = Tree::new("basic");
|
||||
let top = "module top;\n \nendmodule\n";
|
||||
let (ws, uri) = workspace(&tree, top);
|
||||
let position = Position { line: 1, character: 2 };
|
||||
let edit = execute(
|
||||
&ws,
|
||||
&[
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(position).expect("position"),
|
||||
Value::String("sub".to_string()),
|
||||
],
|
||||
)
|
||||
.expect("the command runs");
|
||||
let text = text_of(&edit, &uri);
|
||||
assert!(text.starts_with("sub #("), "{text:?}");
|
||||
assert!(text.contains(".W(8)"), "the parameter default is written plainly: {text:?}");
|
||||
assert!(text.contains("u_sub"), "{text:?}");
|
||||
assert!(text.contains(".clk("), "{text:?}");
|
||||
assert!(!text.contains("${"), "a plain render writes no tabstops: {text:?}");
|
||||
// The edit is an insertion: an empty range at the position asked for.
|
||||
let edits = edit.changes.as_ref().expect("changes").get(&uri).expect("edits");
|
||||
assert_eq!(edits[0].range.start, position);
|
||||
assert_eq!(edits[0].range.end, position);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_inserts_the_same_text_the_ghost_would() {
|
||||
// One planner: rendered through the ghost's own layout and hole
|
||||
// spelling, the command's plan *is* the ghost's text with the module
|
||||
// name and the space the user already typed put back in front.
|
||||
let tree = Tree::new("ghost");
|
||||
let top = "module top;\n sub \nendmodule\n";
|
||||
let (ws, uri) = workspace(&tree, top);
|
||||
let ghost = inline::inline_completions(&ws, &uri, Position { line: 1, character: 6 })
|
||||
.expect("the ghost is offered");
|
||||
// Read off the wire shape, so this pin holds against what a client
|
||||
// actually receives rather than against a private field.
|
||||
let ghost = serde_json::to_value(&ghost).expect("the ghost serializes");
|
||||
let ghost = ghost["items"][0]["insertText"]["value"].as_str().expect("a snippet value");
|
||||
let ours = {
|
||||
let doc = ws.document(&uri).expect("the buffer");
|
||||
plan_at(&ws, doc, "sub")
|
||||
.expect("the plan")
|
||||
.render_with(&relative(), &mut completion::snippet_hole)
|
||||
};
|
||||
assert_eq!(ours, format!("sub {ghost}"));
|
||||
}
|
||||
|
||||
/// `inline.rs`'s own layout, spelled here so the pin above compares like
|
||||
/// with like.
|
||||
fn relative() -> Layout {
|
||||
Layout { base: String::new(), step: "\t".to_string() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_identifier_is_inserted_as_plain_text() {
|
||||
// The ghost declines such a plan — a snippet has no way to spell a
|
||||
// `\name` containing `$`, `}` or `\` — but a `TextEdit` is plain text,
|
||||
// so the command answers where the ghost cannot.
|
||||
let tree = Tree::new("escaped");
|
||||
tree.write("esc.sv", "module \\my-sub (\n input logic \\a$b\n);\nendmodule\n");
|
||||
let top = "module top;\n \nendmodule\n";
|
||||
let path = tree.write("top.sv", top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let edit = execute(
|
||||
&ws,
|
||||
&[
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 1, character: 2 }).expect("position"),
|
||||
Value::String("\\my-sub".to_string()),
|
||||
],
|
||||
)
|
||||
.expect("the command runs");
|
||||
let text = text_of(&edit, &uri);
|
||||
assert!(text.starts_with("\\my-sub "), "{text:?}");
|
||||
assert!(text.contains("\\a$b"), "{text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_that_is_not_an_instantiation_site_is_refused() {
|
||||
let tree = Tree::new("site");
|
||||
let top = "module top;\n always_comb begin\n \n end\nendmodule\n";
|
||||
let (ws, uri) = workspace(&tree, top);
|
||||
let err = execute(
|
||||
&ws,
|
||||
&[
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 2, character: 4 }).expect("position"),
|
||||
Value::String("sub".to_string()),
|
||||
],
|
||||
)
|
||||
.expect_err("a statement is not an item position");
|
||||
assert!(err.contains("cannot be written"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_the_workspace_does_not_know_is_refused() {
|
||||
let tree = Tree::new("unknown");
|
||||
let top = "module top;\n \nendmodule\n";
|
||||
let (ws, uri) = workspace(&tree, top);
|
||||
let err = execute(
|
||||
&ws,
|
||||
&[
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 1, character: 2 }).expect("position"),
|
||||
Value::String("nowhere".to_string()),
|
||||
],
|
||||
)
|
||||
.expect_err("no such module");
|
||||
assert!(err.contains("nowhere"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_arguments_are_named_in_the_refusal() {
|
||||
let tree = Tree::new("args");
|
||||
let top = "module top;\n \nendmodule\n";
|
||||
let (ws, uri) = workspace(&tree, top);
|
||||
let uri_value = serde_json::to_value(&uri).expect("uri");
|
||||
let position = serde_json::to_value(Position { line: 1, character: 2 }).expect("position");
|
||||
assert!(execute(&ws, &[]).expect_err("no uri").contains("URI"));
|
||||
assert!(execute(&ws, std::slice::from_ref(&uri_value))
|
||||
.expect_err("no position")
|
||||
.contains("position"));
|
||||
assert!(execute(&ws, &[uri_value, position]).expect_err("no module").contains("module"));
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,102 @@
|
||||
//!
|
||||
//! `vlog_linter` is the same engine `lucisv check` runs, with the same default
|
||||
//! rule set — an editor that disagreed with CI about what a violation is would
|
||||
//! be worse than one that showed none. Selection (`--select`/`--ignore`) has no
|
||||
//! `lucisv.toml` key yet, so there is nothing here to configure; see
|
||||
//! be worse than one that showed none. Since 2026-09-02 that includes the two
|
||||
//! things a project-wide run has and a single file does not: a **census** the
|
||||
//! semantic rules ask about names in other files, taken from the workspace
|
||||
//! index, and a **selection** (`lucisv.lint.select` / `lucisv.lint.ignore`),
|
||||
//! which is the same `--select`/`--ignore` the CLI has and the same `[lint]`
|
||||
//! table `lucisv.toml` now carries. See
|
||||
//! `docs/features/semantic-lints-on/README.md` and
|
||||
//! `docs/features/server-lint/README.md`.
|
||||
|
||||
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_linter::{default_rules, lint, LintContext, Violation};
|
||||
use vlog_linter::{
|
||||
default_rules, lint, workspace_rules, LintContext, MentionOracle, Rule, Violation,
|
||||
};
|
||||
use vlog_semantic::{FileId, WorkspaceIndex};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::diagnostics::SOURCE;
|
||||
use crate::state::Document;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// What one lint pass runs: which rules, and what it may ask about the files
|
||||
/// around this one.
|
||||
///
|
||||
/// [`LintRun::default`] is a pass with no census and the rules a run without
|
||||
/// one gets — exactly what this server did before the census existed, and what
|
||||
/// every caller that has no [`Workspace`] in hand still gets.
|
||||
pub struct LintRun<'a> {
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
oracle: Option<IndexMentions<'a>>,
|
||||
}
|
||||
|
||||
impl Default for LintRun<'_> {
|
||||
fn default() -> LintRun<'static> {
|
||||
LintRun { rules: default_rules(), oracle: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> LintRun<'a> {
|
||||
/// The pass this workspace's settings and index describe for one buffer.
|
||||
///
|
||||
/// The census exists when the index holds **some other file**: an index of
|
||||
/// this buffer alone (or of nothing at all — a rootless session before its
|
||||
/// first scan) can only repeat what the buffer says about itself, and
|
||||
/// treating that as a project would switch the semantic rules on with no
|
||||
/// cross-file evidence behind them, which is the false-positive mode this
|
||||
/// whole round exists to close.
|
||||
pub fn for_document(ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
|
||||
let index = ws.index();
|
||||
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let client = ws.client_settings();
|
||||
// Every name in the settings was checked against the registry when the
|
||||
// settings were parsed, so this cannot fail; if it somehow does, the
|
||||
// defaults are the answer a dropped setting always gets here.
|
||||
let rules = vlog_linter::select_rules(&client.lint_select, &client.lint_ignore, workspace)
|
||||
.unwrap_or_else(|_| if workspace { workspace_rules() } else { default_rules() });
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
LintRun { rules, oracle }
|
||||
}
|
||||
|
||||
/// This run's context over a buffer's own parse products.
|
||||
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
|
||||
let ctx = context(doc);
|
||||
match &self.oracle {
|
||||
Some(oracle) => ctx.with_oracle(oracle),
|
||||
None => ctx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The workspace index, asked the one question a lint rule may ask about other
|
||||
/// files.
|
||||
///
|
||||
/// Answered from [`WorkspaceIndex::files_mentioning`] — the *textual* census,
|
||||
/// which holds the hierarchical uses (`tb.dut.sig`) and `bind` connections the
|
||||
/// resolved reference tables never see. The buffer's own file is subtracted:
|
||||
/// a signal's own declaration is not evidence that something else uses it.
|
||||
///
|
||||
/// **Staleness is the index's, not this type's.** A file saved but not yet
|
||||
/// rescanned answers with its last-scanned words, exactly as hover and
|
||||
/// find-references do; an open buffer's unsaved edits reach the census when
|
||||
/// its facts are folded in. No new staleness is introduced here.
|
||||
struct IndexMentions<'a> {
|
||||
index: &'a WorkspaceIndex,
|
||||
/// The buffer's own file, when the index holds it. `None` — an untitled
|
||||
/// buffer, or one outside the indexed scope — means nothing is subtracted,
|
||||
/// which can only ever make the oracle answer *yes* more often, i.e. make
|
||||
/// a rule quieter. That is the safe direction.
|
||||
own: Option<FileId>,
|
||||
}
|
||||
|
||||
impl MentionOracle for IndexMentions<'_> {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
self.index.mentioned_outside(name, self.own)
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's own parse products, lent to the linter — "one parse, two
|
||||
/// tools" (`docs/features/one-parse/README.md`): the buffer was tokenized and
|
||||
@@ -28,12 +113,12 @@ fn context(doc: &Document) -> LintContext<'_> {
|
||||
.with_semantics(&doc.semantics)
|
||||
}
|
||||
|
||||
/// Every violation the default rules find in a buffer.
|
||||
/// Every violation `run`'s rules find in a buffer.
|
||||
///
|
||||
/// This is the diagnostics path, which never looks at a fix, so the width a
|
||||
/// `no-tabs` fix would expand a tab to is left at the linter's own default.
|
||||
pub fn violations(doc: &Document) -> Vec<Violation> {
|
||||
lint(&context(doc), &default_rules())
|
||||
pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
lint(&run.context(doc), &run.rules)
|
||||
}
|
||||
|
||||
/// The findings a code action may offer a fix for, with their fixes built for
|
||||
@@ -71,10 +156,21 @@ fn fix_touches_fence(violation: &Violation, regions: &[Region]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// One LSP diagnostic per lint violation.
|
||||
/// One LSP diagnostic per lint violation, with no census.
|
||||
///
|
||||
/// `#[cfg(test)]` because the server itself always has a workspace to hand and
|
||||
/// therefore always goes through [`diagnostics_in`]; this is the door the
|
||||
/// tests that predate the project-aware pass come in by, and keeping it means
|
||||
/// they go on asserting about the same code with one fewer thing supplied.
|
||||
#[cfg(test)]
|
||||
pub fn diagnostics(doc: &Document) -> Vec<Diagnostic> {
|
||||
diagnostics_in(doc, &LintRun::default())
|
||||
}
|
||||
|
||||
/// [`diagnostics`] for a run that knows what the project says.
|
||||
pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec<Diagnostic> {
|
||||
let positions = doc.positions();
|
||||
violations(doc).iter().map(|v| diagnostic(&positions, v)).collect()
|
||||
violations_in(doc, run).iter().map(|v| diagnostic(&positions, v)).collect()
|
||||
}
|
||||
|
||||
/// The diagnostic a violation becomes.
|
||||
@@ -97,8 +193,10 @@ pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnosti
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn doc_of(text: &str) -> (Workspace, Uri) {
|
||||
@@ -201,10 +299,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_semantic_rule_reads_the_documents_own_analysis() {
|
||||
// The rule is off by default, so this goes through `context()`
|
||||
// directly — which is the point: the wiring must be in place before
|
||||
// any semantic rule is ever selected here, so the server never
|
||||
// analyzes a buffer twice per keystroke.
|
||||
// The buffer here has no project behind it, so the rule is off by
|
||||
// default and this goes through `context()` directly — which is the
|
||||
// point: whichever door a semantic rule comes in by, it must read the
|
||||
// analysis the server already made, so no keystroke analyzes twice.
|
||||
let (ws, uri) = doc_of("module m;\n wire spare;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let rule = vlog_linter::rule_by_name("unused-signal").expect("the rule exists");
|
||||
@@ -212,6 +310,112 @@ mod tests {
|
||||
assert_eq!(found.len(), 1, "{found:#?}");
|
||||
assert!(found[0].message.contains("spare"), "{}", found[0].message);
|
||||
assert!(std::ptr::eq(context(doc).semantics(), &doc.semantics), "the lent table");
|
||||
// ... including the project-aware door, which wraps that same context
|
||||
// in the census rather than building a second one.
|
||||
let run = LintRun::for_document(&ws, doc);
|
||||
assert!(std::ptr::eq(run.context(doc).semantics(), &doc.semantics), "still lent");
|
||||
}
|
||||
|
||||
/// A workspace of two files on disk, the second of which reads the
|
||||
/// first's signal through a hierarchical path — QA's cross-file
|
||||
/// false-positive repro, made real rather than synthetic.
|
||||
fn two_file_project(tag: &str) -> (Workspace, PathBuf, Uri) {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_{tag}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(
|
||||
dir.join("dut.sv"),
|
||||
"module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
std::fs::write(
|
||||
dir.join("tb.sv"),
|
||||
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = Uri::from_str(&format!("file://{}", dir.join("dut.sv").display())).expect("uri");
|
||||
ws.set_document(uri.clone(), std::fs::read_to_string(dir.join("dut.sv")).expect("read"));
|
||||
(ws, dir, uri)
|
||||
}
|
||||
|
||||
fn codes(diags: &[Diagnostic]) -> Vec<String> {
|
||||
diags
|
||||
.iter()
|
||||
.filter_map(|d| match &d.code {
|
||||
Some(NumberOrString::String(name)) => Some(name.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The round's headline, through the server: with a project behind it the
|
||||
/// semantic rules run, and the file that reads `d.dbg_probe` is what keeps
|
||||
/// `dbg_probe` quiet while `dead` is still reported.
|
||||
#[test]
|
||||
fn a_project_turns_the_semantic_rules_on_and_its_census_keeps_them_honest() {
|
||||
let (ws, dir, uri) = two_file_project("project");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let run = LintRun::for_document(&ws, doc);
|
||||
let diags = diagnostics_in(doc, &run);
|
||||
assert_eq!(codes(&diags), vec!["unused-signal"], "{diags:#?}");
|
||||
assert!(diags[0].message.contains("dead"), "{}", diags[0].message);
|
||||
assert!(!diags[0].message.contains("dbg_probe"));
|
||||
|
||||
// And the same buffer with no project behind it is v0.29.0's answer.
|
||||
assert!(diagnostics(doc).is_empty(), "no census, no semantic rules");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The off switch, over the settings door: `lucisv.lint.ignore` takes a
|
||||
/// rule out of the published set.
|
||||
#[test]
|
||||
fn the_lint_settings_select_what_the_server_publishes() {
|
||||
let (mut ws, dir, uri) = two_file_project("settings");
|
||||
ws.set_client_settings(ClientSettings {
|
||||
lint_ignore: vec!["unused-signal".to_string()],
|
||||
..ClientSettings::default()
|
||||
});
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let run = LintRun::for_document(&ws, doc);
|
||||
assert!(diagnostics_in(doc, &run).is_empty(), "the setting silenced the rule");
|
||||
|
||||
// `select` replaces the default set, exactly as `--select` does: the
|
||||
// tab is reported by default and not when something else is selected.
|
||||
ws.set_client_settings(ClientSettings::default());
|
||||
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut by_default = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
|
||||
by_default.sort();
|
||||
assert_eq!(by_default, vec!["no-tabs", "unused-signal"], "premise");
|
||||
|
||||
ws.set_client_settings(ClientSettings {
|
||||
lint_select: vec!["unused-signal".to_string()],
|
||||
..ClientSettings::default()
|
||||
});
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let run = LintRun::for_document(&ws, doc);
|
||||
assert_eq!(codes(&diagnostics_in(doc, &run)), vec!["unused-signal"], "the tab is dropped");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// An index that holds only this buffer is not a project: there is nothing
|
||||
/// to ask, so the rules that need one stay off.
|
||||
#[test]
|
||||
fn a_workspace_of_one_file_is_not_a_project() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_alone", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(dir.join("dut.sv"), "module dut;\n logic dead;\nendmodule\n")
|
||||
.expect("write");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = Uri::from_str(&format!("file://{}", dir.join("dut.sv").display())).expect("uri");
|
||||
ws.set_document(uri.clone(), "module dut;\n logic dead;\nendmodule\n".to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
assert!(diagnostics_in(doc, &LintRun::for_document(&ws, doc)).is_empty());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -22,6 +22,7 @@ mod includes;
|
||||
mod index_cache;
|
||||
mod inlay;
|
||||
mod inline;
|
||||
mod instantiate;
|
||||
mod large;
|
||||
mod lens;
|
||||
mod linked;
|
||||
@@ -278,14 +279,24 @@ fn capabilities() -> ServerCapabilities {
|
||||
// `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.
|
||||
// Names, templates and — since 2026-09-02 — members. An identifier
|
||||
// being typed asks for the first two on its own, with no trigger
|
||||
// needed; a **member** list has no identifier to be asked by, because
|
||||
// the user has typed a separator and nothing after it yet. So `.` and
|
||||
// `:` are advertised, and nothing else: they are the two bytes that
|
||||
// can turn the cursor into a member position.
|
||||
//
|
||||
// The trigger is a *prompt*, never an instruction. The handler reads
|
||||
// the buffer and decides — `server.rs` discards the request's
|
||||
// `context` — so a `.` in a connection list, a lone `:` of a case
|
||||
// item and a `::` after nothing readable all answer exactly what they
|
||||
// would have answered had the user pressed the key themselves. See
|
||||
// `docs/features/member-completion/README.md`.
|
||||
completion_provider: Some(CompletionOptions {
|
||||
// Every item is returned complete — skeleton, documentation and
|
||||
// all — so there is nothing for `completionItem/resolve` to do.
|
||||
resolve_provider: None,
|
||||
trigger_characters: None,
|
||||
trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
|
||||
all_commit_characters: None,
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
completion_item: None,
|
||||
@@ -380,10 +391,11 @@ fn capabilities() -> ServerCapabilities {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every command this server executes: the three port refactorings, and the
|
||||
/// jump the code lens hangs off.
|
||||
/// Every command this server executes: the three port refactorings, the
|
||||
/// instantiation skeleton, and the jump the code lens hangs off.
|
||||
fn commands() -> Vec<String> {
|
||||
let mut commands = ports::commands();
|
||||
commands.extend(instantiate::commands());
|
||||
commands.extend(lens::commands());
|
||||
commands
|
||||
}
|
||||
@@ -1066,7 +1078,16 @@ mod tests {
|
||||
fn completion_resolves_nothing_because_every_item_is_complete() {
|
||||
let options = capabilities().completion_provider.expect("completion");
|
||||
assert_eq!(options.resolve_provider, None);
|
||||
assert_eq!(options.trigger_characters, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_triggers_on_the_two_separators_that_start_a_member_list() {
|
||||
let options = capabilities().completion_provider.expect("completion");
|
||||
assert_eq!(
|
||||
options.trigger_characters,
|
||||
Some(vec![".".to_string(), ":".to_string()]),
|
||||
"a member list has no identifier to ask for it, so the separator must",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1133,9 +1154,14 @@ mod tests {
|
||||
fn every_advertised_command_is_one_the_server_runs() {
|
||||
let options = capabilities().execute_command_provider.expect("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()) {
|
||||
// Every half of the list, so none can go missing quietly: a lens
|
||||
// whose command is not advertised is a lens no client will run, and
|
||||
// an unadvertised `lucisv.instantiate` is the whole of §2.9-19 gone.
|
||||
for command in ports::commands()
|
||||
.iter()
|
||||
.chain(instantiate::commands().iter())
|
||||
.chain(lens::commands().iter())
|
||||
{
|
||||
assert!(options.commands.contains(command), "{command} is not advertised");
|
||||
}
|
||||
assert!(
|
||||
|
||||
@@ -24,6 +24,14 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
if let Some(location) = includes::definition(ws, doc, offset) {
|
||||
return vec![location];
|
||||
}
|
||||
// A macro *use* is one token with no `Reference` behind it, so neither
|
||||
// layer below can answer for it. Hover has always known where a
|
||||
// `` `define`` lives; this is the same lookup, returning places to jump
|
||||
// to instead of text to read.
|
||||
let macro_defs = macro_definition(ws, doc, uri, offset);
|
||||
if !macro_defs.is_empty() {
|
||||
return macro_defs;
|
||||
}
|
||||
match doc.external.definition_of(&doc.semantics, offset) {
|
||||
Some(Definition::Local(symbol)) => {
|
||||
if symbol.name_span.is_empty() {
|
||||
@@ -59,6 +67,40 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the `` `define`` under the cursor was written, when the cursor is on
|
||||
/// a macro use.
|
||||
///
|
||||
/// The same two-step lookup [`crate::hover`] does, and deliberately so: a
|
||||
/// definition this file wrote itself wins outright, and otherwise every
|
||||
/// workspace candidate the include graph could not rule out is offered. An
|
||||
/// unknown macro (`` `uvm_info`` with no UVM in the index) yields nothing,
|
||||
/// which is the same answer as "not a macro" and the right one either way.
|
||||
fn macro_definition(ws: &Workspace, doc: &Document, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
let Some(token) = doc.token_at(offset).filter(|token| token.is_macro()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(name) = crate::hover::macro_name(token) else { return Vec::new() };
|
||||
|
||||
if let Some(define) = doc.defines.latest(name) {
|
||||
if define.name_span.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(target) = path_to_uri_or_self(ws, uri) else { return Vec::new() };
|
||||
let range = doc.positions().range(define.name_span);
|
||||
return vec![Location { uri: target, range }];
|
||||
}
|
||||
|
||||
let candidates =
|
||||
crate::hover::narrowed_to_the_include_graph(ws, doc, ws.index().find_define(name));
|
||||
candidates
|
||||
.iter()
|
||||
.filter_map(|(file, define)| {
|
||||
let path = ws.index().path(*file)?;
|
||||
location(ws, path, define.name_span)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The URI to report a local definition against — the document's own.
|
||||
fn path_to_uri_or_self(ws: &Workspace, uri: &Uri) -> Option<Uri> {
|
||||
match ws.document(uri).and_then(|d| d.path.clone()) {
|
||||
@@ -508,6 +550,83 @@ mod tests {
|
||||
assert_eq!(locations[0].range.start.line, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_use_jumps_to_its_define_in_the_same_file() {
|
||||
let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let locations = definition(&ws, &uri, at(text, "`WIDTH-1") + 2);
|
||||
assert_eq!(locations.len(), 1, "the `define` this file wrote");
|
||||
assert_eq!(locations[0].range.start.line, 0);
|
||||
assert_eq!(locations[0].range.start.character, 8, "the name, not the backtick");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_nothing_defines_has_no_definition() {
|
||||
// `uvm_info` with no UVM in the index: the same empty answer a name
|
||||
// nothing declares gets, and no invented location.
|
||||
let text = "module m;\n initial `uvm_info(\"x\", \"y\", UVM_LOW)\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
assert!(definition(&ws, &uri, at(text, "`uvm_info") + 2).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_use_jumps_across_files_to_the_define() {
|
||||
let dir = temp_dir("macro_xfile");
|
||||
fs::write(dir.join("defs.svh"), "`define BUS_W 32\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n logic [`BUS_W-1:0] bus;\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "`BUS_W") + 2);
|
||||
assert_eq!(locations.len(), 1, "the one file that defines it");
|
||||
assert!(locations[0].uri.as_str().ends_with("defs.svh"), "{:?}", locations[0].uri);
|
||||
assert_eq!(locations[0].range.start.line, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_defines_of_one_macro_are_narrowed_by_the_include_graph() {
|
||||
let dir = temp_dir("macro_narrow");
|
||||
fs::write(dir.join("a.svh"), "`define MODE 1\n").expect("write");
|
||||
fs::write(dir.join("b.svh"), "`define MODE 2\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
// Only `a.svh` is reachable from this file, so only its definition is
|
||||
// offered — the narrowing `hover` already does, shared.
|
||||
let top_text = "`include \"a.svh\"\nmodule top;\n logic [`MODE:0] m;\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "`MODE:0") + 2);
|
||||
assert_eq!(locations.len(), 1, "the include graph picks one: {locations:?}");
|
||||
assert!(locations[0].uri.as_str().ends_with("a.svh"), "{:?}", locations[0].uri);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_define_inside_a_fragment_file_is_still_a_jump_target() {
|
||||
// A `.svh` that is a *fragment* — no module, no package — is indexed
|
||||
// for its defines like any other file (`fragment-mode`).
|
||||
let dir = temp_dir("macro_fragment");
|
||||
fs::write(dir.join("frag.svh"), "CUSTOM_1,\n`define TAIL 7\nCUSTOM_2\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n logic [`TAIL:0] t;\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "`TAIL") + 2);
|
||||
assert_eq!(locations.len(), 1, "the fragment's define: {locations:?}");
|
||||
assert!(locations[0].uri.as_str().ends_with("frag.svh"), "{:?}", locations[0].uri);
|
||||
assert_eq!(locations[0].range.start.line, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_nothing_declares_has_no_definition() {
|
||||
let text = "module m;\n assign x = 1;\nendmodule\n";
|
||||
|
||||
@@ -136,7 +136,17 @@ fn indent_edit(doc: &Document, position: Position, indent_width: usize) -> Optio
|
||||
/// whatever the user wrote is what a whole-file run emits, so this model has no
|
||||
/// opinion there. `constraint c { ... }` needs no entry — its body is behind a
|
||||
/// brace, and any open bracket already silences this.
|
||||
const OPAQUE: &[&str] = &["covergroup", "property", "sequence"];
|
||||
///
|
||||
/// `covergroup` **left** this list in the `covergroup-bodies` round: its items
|
||||
/// are laid out from a real tree now, at one indent from the header, which is
|
||||
/// exactly what an ordinary block frame computes. Its bins bodies are behind a
|
||||
/// `{`, so they need no entry either, for the reason a constraint's do not.
|
||||
/// The five vendor/formal blocks joined the list in `vendor-formal-grammar`
|
||||
/// (2026-09-02): a specify path, a UDP truth table, a checker body and a
|
||||
/// config's library clauses are all emitted byte-for-byte, so this model has
|
||||
/// no opinion inside any of them either.
|
||||
const OPAQUE: &[&str] =
|
||||
&["property", "sequence", "specify", "primitive", "table", "checker", "config"];
|
||||
|
||||
/// Keywords whose statement body follows them directly, after an optional
|
||||
/// `@(...)` event control or `#delay`.
|
||||
@@ -886,12 +896,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_verbatim_scope_has_no_indent_this_model_can_name() {
|
||||
// A covergroup's body is emitted byte-for-byte, so whatever the user
|
||||
// A property's body is emitted byte-for-byte, so whatever the user
|
||||
// wrote there is already what a whole-file run produces.
|
||||
let text = "module m;\n covergroup cg;\n\n cp: coverpoint x;\n endgroup\nendmodule\n";
|
||||
let text = "module m;\n property p;\n\n a |-> b;\n endproperty\nendmodule\n";
|
||||
assert_eq!(indent(text, 2), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_covergroup_body_indents_like_any_other_block() {
|
||||
// Since `covergroup-bodies` its items are laid out from a real tree,
|
||||
// so the model has an answer where it used to have none.
|
||||
let text = "module m;\n covergroup cg;\n\n cp: coverpoint x;\n endgroup\nendmodule\n";
|
||||
assert_eq!(indent(text, 2).as_deref(), Some(" "));
|
||||
// A bin body is behind a `{`, where an open bracket silences the
|
||||
// model exactly as it does inside a constraint.
|
||||
let text =
|
||||
"module m;\n covergroup cg;\n cp: coverpoint x {\n\n }\n endgroup\nendmodule\n";
|
||||
assert_eq!(indent(text, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_assertion_statement_is_silent_for_as_long_as_it_runs() {
|
||||
// `assert (c) pass; else fail;` is verbatim, and its `else` runs past
|
||||
|
||||
@@ -48,6 +48,13 @@ const RULES: &[Rule] = &[
|
||||
Rule { open: "covergroup", close: &["endgroup"] },
|
||||
Rule { open: "specify", close: &["endspecify"] },
|
||||
Rule { open: "primitive", close: &["endprimitive"] },
|
||||
// `vendor-formal-grammar`, 2026-09-02. `table`/`endtable` could not be a
|
||||
// rule before this round for a reason worth writing down: a rule only
|
||||
// fires on a `TokenKind::Keyword`, and `checker`/`config` were not
|
||||
// keywords — `table` was, so its row is simply the one nobody had added.
|
||||
Rule { open: "table", close: &["endtable"] },
|
||||
Rule { open: "checker", close: &["endchecker"] },
|
||||
Rule { open: "config", close: &["endconfig"] },
|
||||
];
|
||||
|
||||
/// Keywords that turn the rest of their statement into a declaration without a
|
||||
@@ -599,6 +606,34 @@ mod tests {
|
||||
scopes(text).unmatched_open.iter().map(|u| u.keyword).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_vendor_and_formal_blocks_are_scopes() {
|
||||
// `vendor-formal-grammar`, 2026-09-02. A rule only fires on a
|
||||
// `TokenKind::Keyword`, so `checker` and `config` became matchable
|
||||
// the moment the lexer reserved them; `table` was a keyword all along
|
||||
// and simply had no row.
|
||||
assert_eq!(
|
||||
matched("primitive p (q, a);\n table\n 0 : 1;\n endtable\nendprimitive\n"),
|
||||
["primitive..endprimitive", "table..endtable"]
|
||||
);
|
||||
assert_eq!(
|
||||
matched("checker c (logic a);\n checker d (logic b);\n endchecker\nendchecker\n"),
|
||||
["checker..endchecker", "checker..endchecker"]
|
||||
);
|
||||
assert_eq!(matched("config cfg;\n design work.top;\nendconfig\n"), ["config..endconfig"]);
|
||||
assert_eq!(
|
||||
matched("module m;\n specify\n endspecify\nendmodule\n"),
|
||||
["module..endmodule", "specify..endspecify"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_vendor_block_is_reported_against_its_own_keyword() {
|
||||
assert_eq!(unclosed("checker c (logic a);\n"), ["checker"]);
|
||||
assert_eq!(unclosed("config cfg;\n"), ["config"]);
|
||||
assert_eq!(orphan_closers("endchecker\n"), ["endchecker"]);
|
||||
}
|
||||
|
||||
/// The keyword of every closer that closed nothing.
|
||||
fn orphan_closers(text: &str) -> Vec<&'static str> {
|
||||
scopes(text).unmatched_close.iter().map(|u| u.keyword).collect()
|
||||
|
||||
@@ -122,6 +122,13 @@ pub fn execute(
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::propagate_ports(&sources, &path, offset)?
|
||||
}
|
||||
// The instantiation skeleton is not a port refactoring and computes
|
||||
// its own `WorkspaceEdit`, but `server.rs` routes every non-lens
|
||||
// `workspace/executeCommand` through here — this is the one place an
|
||||
// edit-producing command is handed to `Server::deliver`.
|
||||
crate::instantiate::INSTANTIATE => {
|
||||
return crate::instantiate::execute(ws, arguments).map(|edit| (edit, Vec::new()))
|
||||
}
|
||||
other => return Err(format!("`{other}` is not a lucisv command.")),
|
||||
};
|
||||
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
|
||||
@@ -13,11 +13,13 @@
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::locate::display_name;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
@@ -59,8 +61,9 @@ pub fn rename(
|
||||
// is the one voice that decides, and it decides over the files below. A
|
||||
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
|
||||
// the engine will say so, and saying it is cheap either way.
|
||||
let sources = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(&path, &name, Some(new_name)),
|
||||
let old_name = vlog_refactor::rename_name_at(&doc.semantics, offset);
|
||||
let sources = match &old_name {
|
||||
Some(name) => ws.rename_sources(&path, name, Some(new_name)),
|
||||
None => ws.sources(),
|
||||
};
|
||||
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
|
||||
@@ -90,7 +93,43 @@ pub fn rename(
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
Ok((WorkspaceEdit::new(changes), refactoring.warnings))
|
||||
let mut warnings = refactoring.warnings;
|
||||
if let Some(name) = &old_name {
|
||||
warnings.extend(unread_macro_warnings(ws, name, &sources));
|
||||
}
|
||||
Ok((WorkspaceEdit::new(changes), warnings))
|
||||
}
|
||||
|
||||
/// One sentence per file that writes the old name inside a macro invocation,
|
||||
/// a directive line or an attribute and was **not** among the files the engine
|
||||
/// was handed.
|
||||
///
|
||||
/// The engine warns about a macro argument in every file it reads, but the
|
||||
/// fan-out that decides which files those are has no rung for a file whose
|
||||
/// only relationship to the name is that text — deliberately: the census of
|
||||
/// every file merely *spelling* `clk` is untagged, and a rung on it would
|
||||
/// re-read the workspace and bring back the 2.5–3.0 s cost
|
||||
/// `prepare_rename_here` removed (`docs/topo.md` §2.9-18). So the index
|
||||
/// answers the narrower question instead — which files name it in text
|
||||
/// nothing can edit — off a table it already holds, reading no file and
|
||||
/// parsing nothing. The rename stays as fast as it was and stops being silent
|
||||
/// about the one shape it cannot see.
|
||||
///
|
||||
/// Subtracting the handed set leaves out every open buffer too, because
|
||||
/// [`Workspace::rename_sources`] puts every open buffer in it.
|
||||
fn unread_macro_warnings(ws: &Workspace, name: &str, sources: &[(PathBuf, String)]) -> Vec<String> {
|
||||
let index = ws.index();
|
||||
index
|
||||
.files_naming_in_macros(name)
|
||||
.filter_map(|file| index.path(file))
|
||||
.filter(|path| !sources.iter().any(|(handed, _)| handed == path))
|
||||
.map(|path| {
|
||||
format!(
|
||||
"`{name}` also appears inside a macro invocation in {}, which this rename did not read; check it by hand — a macro argument cannot be edited.",
|
||||
display_name(path)
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
const UNSAVED: &str = "lucisv can only rename inside a saved file.";
|
||||
@@ -851,4 +890,86 @@ mod tests {
|
||||
let changes = edit.changes.expect("changes");
|
||||
assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the buffer's instantiation");
|
||||
}
|
||||
|
||||
/// `sub.sv` declares the port, `top.sv` connects it, and `far.svh` names
|
||||
/// it inside a macro invocation and has no other relationship to anything
|
||||
/// in the rename — so the fan-out does not hand it to the engine and the
|
||||
/// engine cannot warn about it. The census does: §2.9-18's server half.
|
||||
const M_SUB: &str = "module sub (output logic sig);\n assign sig = 1'b0;\nendmodule\n";
|
||||
const M_TOP: &str = "module top;\n logic w;\n sub u_sub (.sig(w));\nendmodule\n";
|
||||
const M_FAR: &str = "`uvm_info(\"x\", $sformatf(\"%0d\", sig), UVM_LOW)\n";
|
||||
|
||||
/// The workspace of the two pins below, with `top.sv` open. `far` is what
|
||||
/// `far.svh` holds, which is the only difference between them.
|
||||
fn macro_workspace(tree: &Tree, far: &str) -> (Workspace, Uri) {
|
||||
tree.write("sub.sv", M_SUB);
|
||||
let top = tree.write("top.sv", M_TOP);
|
||||
tree.write("far.svh", far);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), M_TOP.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// How often a warning naming `far.svh` is in the list.
|
||||
fn far_warnings(warnings: &[String]) -> usize {
|
||||
warnings.iter().filter(|w| w.contains("far.svh")).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_only_names_the_symbol_in_a_macro_is_warned_about_unread() {
|
||||
let tree = Tree::new("macrocensus");
|
||||
let (ws, uri) = macro_workspace(&tree, M_FAR);
|
||||
|
||||
// The premise: `far.svh` is in no rung of the fan-out, so the engine
|
||||
// never sees it. Asked of the same function `rename` asks.
|
||||
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
|
||||
assert!(
|
||||
!handed.iter().any(|(path, _)| path.ends_with("far.svh")),
|
||||
"premise: the engine is not handed far.svh — {handed:?}"
|
||||
);
|
||||
|
||||
let (edit, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames");
|
||||
let changes = edit.changes.expect("changes");
|
||||
assert_eq!(changes.len(), 2, "the declaration's file and the connection's");
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
assert_eq!(changes.get(&sub_uri).map(Vec::len), Some(2), "the port and its assignment");
|
||||
assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the `.sig(` connection");
|
||||
assert!(
|
||||
!changes.contains_key(&path_to_uri(&tree.path.join("far.svh")).expect("uri")),
|
||||
"a macro argument is never edited"
|
||||
);
|
||||
|
||||
assert_eq!(far_warnings(&warnings), 1, "{warnings:?}");
|
||||
let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named");
|
||||
assert!(warning.contains("`sig`"), "{warning}");
|
||||
assert!(warning.contains("this rename did not read"), "{warning}");
|
||||
assert!(warning.contains("a macro argument cannot be edited"), "{warning}");
|
||||
}
|
||||
|
||||
/// The control: give `far.svh` a reason to be read — it instantiates
|
||||
/// `sub` — and it *is* a source, so the engine's own macro-argument
|
||||
/// warning covers it and this one must stay quiet. Exactly one warning
|
||||
/// names the file either way; two would be the bug.
|
||||
#[test]
|
||||
fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() {
|
||||
let tree = Tree::new("macrocontrol");
|
||||
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
|
||||
let (ws, uri) = macro_workspace(&tree, &far);
|
||||
|
||||
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
|
||||
assert!(
|
||||
handed.iter().any(|(path, _)| path.ends_with("far.svh")),
|
||||
"premise: instantiating `sub` puts far.svh in the source set"
|
||||
);
|
||||
|
||||
let (_, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames");
|
||||
assert_eq!(far_warnings(&warnings), 1, "no double warning: {warnings:?}");
|
||||
let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named");
|
||||
assert!(
|
||||
warning.contains("one opaque token"),
|
||||
"and it is the engine's sentence, not the census's: {warning}"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,188 @@
|
||||
//! Reading a burst of messages before any of it is served.
|
||||
//!
|
||||
//! `lsp-server` hands messages over a rendezvous channel, one at a time; the
|
||||
//! forwarder here moves them onto a queue of our own so that "everything the
|
||||
//! client has already sent" is a question with an answer. The rest of the
|
||||
//! file reads a burst without handling anything in it: which requests it
|
||||
//! cancels, which files it opens, and — for a `didOpen` — whether the index
|
||||
//! scope grew, stayed, or has to be rebuilt. The loop in `mod.rs` and the
|
||||
//! mid-scan drain in `index.rs` both read bursts through here, which is why
|
||||
//! this is its own file rather than part of either.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_server::{Connection, Message, RequestId, Response};
|
||||
use lsp_types::notification::{Cancel, DidOpenTextDocument, Notification as _};
|
||||
use lsp_types::request::{Request as _, Shutdown};
|
||||
use lsp_types::{CancelParams, NumberOrString};
|
||||
|
||||
use super::dispatch::document_uri;
|
||||
|
||||
/// Whether this message is the `shutdown` request. `lsp-server` keeps its own
|
||||
/// answer to that question private, so it is asked here by method name — the
|
||||
/// same name `handle_shutdown` matches on.
|
||||
pub(super) fn is_shutdown(message: &Message) -> bool {
|
||||
matches!(message, Message::Request(request) if request.method == Shutdown::METHOD)
|
||||
}
|
||||
|
||||
/// Move the incoming messages onto a queue of our own, and report it.
|
||||
///
|
||||
/// Necessary because `lsp-server`'s transport hands messages over
|
||||
/// *rendezvous* channels — `bounded(0)`. Its reader thread parks holding one
|
||||
/// message until this loop takes it, so a client's backlog never sits on
|
||||
/// `connection.receiver` at all: it sits in the OS pipe, invisible and one
|
||||
/// message deep. Forwarding onto an unbounded queue is what makes "everything
|
||||
/// already sent" observable without blocking, which is the whole premise of
|
||||
/// [`burst`] — and of the drain a scan does between two of its files.
|
||||
///
|
||||
/// The forwarder stops at `shutdown` and never reads past it, because
|
||||
/// `handle_shutdown` reads the `exit` notification off the *connection*
|
||||
/// itself — a forwarder that kept going would steal it and strand the
|
||||
/// handshake for thirty seconds. It owns nothing but messages in flight and
|
||||
/// touches no server state — and it never parses, which is why it is the one
|
||||
/// thread the server spawns without `vlog_parser::PARSE_STACK_SIZE`
|
||||
/// (`docs/features/recursion-limit`).
|
||||
pub(super) fn forward(
|
||||
connection: &Connection,
|
||||
) -> (std::sync::mpsc::Sender<Message>, std::sync::mpsc::Receiver<Message>) {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let source = connection.receiver.clone();
|
||||
let ours = sender.clone();
|
||||
// A failed spawn would leave the server unable to receive anything at
|
||||
// all; there is nothing useful to do with that but let `run` end when the
|
||||
// queue's sender is dropped.
|
||||
let _ = std::thread::Builder::new().name("lucisv-queue".to_string()).spawn(move || {
|
||||
while let Ok(message) = source.recv() {
|
||||
let last = is_shutdown(&message);
|
||||
if sender.send(message).is_err() || last {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
(ours, receiver)
|
||||
}
|
||||
|
||||
/// `first` plus everything already waiting on the queue behind it — the
|
||||
/// client's backlog, in arrival order. Never blocks: what is not there yet
|
||||
/// belongs to the next burst.
|
||||
pub(super) fn burst(queue: &std::sync::mpsc::Receiver<Message>, first: Message) -> Vec<Message> {
|
||||
let mut batch = vec![first];
|
||||
while let Ok(message) = queue.try_recv() {
|
||||
batch.push(message);
|
||||
}
|
||||
batch
|
||||
}
|
||||
|
||||
/// The ids this burst cancels: every `$/cancelRequest` in it that names a
|
||||
/// request the burst *also* carries.
|
||||
///
|
||||
/// A cancel naming anything else is dropped right here — it refers to a
|
||||
/// request answered in some earlier burst, or to one this server never
|
||||
/// received, and either way there is nothing left to cancel. That is what
|
||||
/// keeps this from becoming a set that grows for the life of the session.
|
||||
pub(super) fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
|
||||
let queued: HashSet<&RequestId> = batch
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Request(request) => Some(&request.id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
batch.iter().filter_map(cancelled_id).filter(|id| queued.contains(id)).collect()
|
||||
}
|
||||
|
||||
/// The request id a `$/cancelRequest` names, or `None` for any other message.
|
||||
/// Both id forms the protocol allows are read; a cancel whose params do not
|
||||
/// parse is dropped, because there is no id to act on.
|
||||
fn cancelled_id(message: &Message) -> Option<RequestId> {
|
||||
let Message::Notification(notification) = message else { return None };
|
||||
if notification.method != Cancel::METHOD {
|
||||
return None;
|
||||
}
|
||||
let params: CancelParams = serde_json::from_value(notification.params.clone()).ok()?;
|
||||
Some(match params.id {
|
||||
NumberOrString::Number(number) => RequestId::from(number),
|
||||
NumberOrString::String(text) => RequestId::from(text),
|
||||
})
|
||||
}
|
||||
|
||||
/// What a cancelled request is answered with. Every request gets exactly one
|
||||
/// response, cancelled or not — the protocol's own `RequestCancelled`
|
||||
/// (-32800), which a client reads as "the one you asked me to drop" rather
|
||||
/// than as a failure worth showing the user.
|
||||
pub(super) fn cancelled_response(id: RequestId) -> Response {
|
||||
Response::new_err(
|
||||
id,
|
||||
lsp_server::ErrorCode::RequestCanceled as i32,
|
||||
"lucisv: request cancelled by the client".to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// What a `didOpen` did to the index scope, and therefore which of the three
|
||||
/// answers it is owed.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) enum Widen {
|
||||
/// The scope did not move: the file is in a folder already covered, or the
|
||||
/// rung in force is one an open buffer cannot widen (a filelist, or the
|
||||
/// whole-workspace walk). Publish and index nothing.
|
||||
Nothing,
|
||||
/// Folders were added and nothing else changed — the cheap path, indexing
|
||||
/// only what the added folders bring in
|
||||
/// ([`Server::reindex_widened`](super::Server::reindex_widened)).
|
||||
Added(Vec<std::path::PathBuf>),
|
||||
/// Anything else. The whole rescan, which is always a correct answer.
|
||||
Whole,
|
||||
}
|
||||
|
||||
/// Which of the three [`Widen`] answers a move from `before` to `after` is.
|
||||
///
|
||||
/// **The chooser, and it is deliberately narrow**: only a scope that grew and
|
||||
/// lost nothing takes the incremental path, because that is the only shape
|
||||
/// whose result is the whole rescan's by construction — a directory that left
|
||||
/// the scope can take files out of the index, and working out *which* files is
|
||||
/// the walk the widen exists not to do. Nothing in the server takes a directory
|
||||
/// out of the folder scope today (`opened_dirs` only grows, and a `didClose`
|
||||
/// costs no rescan at all), so the third arm is a rule kept rather than a case
|
||||
/// reached; a future shrink gets a correct answer instead of a subtle one.
|
||||
///
|
||||
/// **A directory that subsumes one already in scope is an add** (2026-08-29,
|
||||
/// `docs/features/index-scope/README.md`). At `scopeDepth: 2` the second file a
|
||||
/// user opens routinely raises to a *parent* of the directory the first one
|
||||
/// raised to — opentitan's `hw/ip/aes` then `hw/ip`. That is still a pure add
|
||||
/// here, because every opened directory is raised on its own and the list keeps
|
||||
/// them all: the contained directory is in `after` beside the containing one,
|
||||
/// and nothing was lost. The overlap is not re-read either, because
|
||||
/// `Workspace::begin_widen`'s work list is diffed **by file against what the
|
||||
/// index holds** rather than by folder against the old walk.
|
||||
///
|
||||
/// Both lists come from `Workspace::scope_dirs`, which sorts and dedups, so
|
||||
/// equality is set equality and `contains` is over a handful of directories.
|
||||
pub(super) fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBuf]) -> Widen {
|
||||
if before == after {
|
||||
return Widen::Nothing;
|
||||
}
|
||||
if before.iter().any(|dir| !after.contains(dir)) {
|
||||
return Widen::Whole;
|
||||
}
|
||||
Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect())
|
||||
}
|
||||
|
||||
/// The files a burst opened, in the order the client opened them.
|
||||
///
|
||||
/// Read off the raw messages rather than off the workspace afterwards,
|
||||
/// because the workspace holds its buffers in a `HashMap` and "which file did
|
||||
/// the user just open" is a question about order.
|
||||
pub(super) fn opened_in(batch: &[Message]) -> Vec<std::path::PathBuf> {
|
||||
batch
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(notification)
|
||||
if notification.method == DidOpenTextDocument::METHOD =>
|
||||
{
|
||||
document_uri(¬ification.params)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.filter_map(|uri| crate::uri::uri_to_path(&uri))
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! What goes to the client other than a response.
|
||||
//!
|
||||
//! Three kinds of traffic, all server-initiated: the requests the server
|
||||
//! makes of the client (`send_request` and the six things asked through it —
|
||||
//! an edit to apply, a document to show, its settings, a watcher
|
||||
//! registration, a lens refresh) and the two answers it acts on; the
|
||||
//! messages a user sees or can grep for (`show_message`, `report_scope`, the
|
||||
//! plain `notify`); and the `--verbose` timing lines. The free functions at
|
||||
//! the end are the connection-level forms that work while the `Server` is
|
||||
//! borrowed elsewhere, plus the two words every log line is spelled with.
|
||||
|
||||
use lsp_server::{Connection, Message, Notification, Request, RequestId, Response};
|
||||
use lsp_types::notification::{LogMessage, Notification as _, ShowMessage};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CodeLensRefresh, RegisterCapability, Request as _, ShowDocument,
|
||||
UnregisterCapability, WorkspaceConfiguration,
|
||||
};
|
||||
use lsp_types::{
|
||||
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, ConfigurationItem, ConfigurationParams,
|
||||
Location, LogMessageParams, MessageType, RegistrationParams, ShowDocumentParams,
|
||||
ShowMessageParams, UnregistrationParams, WorkspaceEdit,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::dispatch::{to_value, Failure};
|
||||
use super::{Pending, Server};
|
||||
use crate::{settings, watch};
|
||||
|
||||
impl Server {
|
||||
/// Ask the client something, reporting the id it will answer on — a
|
||||
/// repeated id is a protocol error, so this only ever counts up.
|
||||
pub(super) fn send_request(
|
||||
&mut self,
|
||||
method: &str,
|
||||
params: impl serde::Serialize,
|
||||
) -> RequestId {
|
||||
let id = RequestId::from(format!("lucisv-{}", self.request_ids));
|
||||
self.request_ids += 1;
|
||||
let request = Request::new(id.clone(), method.to_string(), params);
|
||||
// A closed channel means the client is gone; there is nobody left to
|
||||
// report the failure to.
|
||||
let _ = self.connection.sender.send(Message::Request(request));
|
||||
id
|
||||
}
|
||||
|
||||
/// Ask the client for the `lucisv` section of its settings.
|
||||
///
|
||||
/// Silent for a client that did not advertise `workspace.configuration` —
|
||||
/// that one is only ever pushed settings, which is what every client got
|
||||
/// before this existed. No `scopeUri`: this server holds one set of
|
||||
/// settings for the whole session, not one per folder, so asking
|
||||
/// per-resource would be asking for answers it has nowhere to put.
|
||||
pub(super) fn request_configuration(&mut self) {
|
||||
if !self.abilities.configuration {
|
||||
return;
|
||||
}
|
||||
let params = ConfigurationParams {
|
||||
items: vec![ConfigurationItem {
|
||||
scope_uri: None,
|
||||
section: Some(settings::SECTION.to_string()),
|
||||
}],
|
||||
};
|
||||
let id = self.send_request(WorkspaceConfiguration::METHOD, params);
|
||||
self.pending.insert(id, Pending::Configuration);
|
||||
}
|
||||
|
||||
/// Ask the client to watch the source files and the filelist for us,
|
||||
/// replacing any registration already in force.
|
||||
///
|
||||
/// Silent for a client that cannot be asked — that one keeps the save-only
|
||||
/// staleness model, which is what it had before this feature existed.
|
||||
pub(super) fn register_watchers(&mut self) {
|
||||
if !self.abilities.file_watching {
|
||||
return;
|
||||
}
|
||||
// Unregister first, so a client that keys watchers by id is never
|
||||
// holding two registrations that both fire for `**/*.sv`.
|
||||
if let Some(id) = self.watchers.take() {
|
||||
let params = UnregistrationParams { unregisterations: vec![watch::unregistration(id)] };
|
||||
self.send_request(UnregisterCapability::METHOD, params);
|
||||
}
|
||||
let filelist = self.workspace.filelist_path();
|
||||
let registration = watch::registration(self.registrations, filelist.as_deref());
|
||||
self.registrations += 1;
|
||||
self.watchers = Some(registration.id.clone());
|
||||
let params = RegistrationParams { registrations: vec![registration] };
|
||||
self.send_request(RegisterCapability::METHOD, params);
|
||||
}
|
||||
|
||||
/// Ask the client to re-request its code lenses, because the rescan just
|
||||
/// finished may have changed every instantiation count in every buffer it
|
||||
/// is showing.
|
||||
///
|
||||
/// Silent for a client that did not advertise
|
||||
/// `workspace.codeLens.refreshSupport` — the request is server-initiated
|
||||
/// and the spec makes that capability the gate. Since scan-interleave, the
|
||||
/// startup scan can send it too: a `didOpen` answered mid-scan leaves a
|
||||
/// buffer whose lenses were computed against the half-built index, and
|
||||
/// `started` refreshes them once the bar comes down. The answer is
|
||||
/// ignorable and rides `response`'s fall-through path.
|
||||
pub(super) fn refresh_code_lenses(&mut self) {
|
||||
if !self.abilities.code_lens_refresh {
|
||||
return;
|
||||
}
|
||||
self.send_request(CodeLensRefresh::METHOD, ());
|
||||
}
|
||||
|
||||
/// Deliver a command's `WorkspaceEdit` the way the client can take it.
|
||||
///
|
||||
/// The protocol has no place for an edit in an `executeCommand` *result*:
|
||||
/// a client applies what a server pushes with `workspace/applyEdit`, and
|
||||
/// drops the result on the floor. So the edit is pushed and the result is
|
||||
/// `null` — except for a client that never advertised `workspace.applyEdit`,
|
||||
/// which gets the old return-the-edit behavior because for that one it is
|
||||
/// the only behavior that could ever work.
|
||||
///
|
||||
/// The push goes out *before* the command's own response, which the loop
|
||||
/// sends when this returns. The protocol allows a server to request at any
|
||||
/// time, and a client that waited for the command result before applying
|
||||
/// the edit would deadlock on any server that does this — VS Code and
|
||||
/// Neovim both apply it immediately.
|
||||
pub(super) fn deliver(&mut self, command: &str, edit: WorkspaceEdit) -> Result<Value, Failure> {
|
||||
if !self.abilities.apply_edit {
|
||||
return to_value(edit);
|
||||
}
|
||||
let params = ApplyWorkspaceEditParams { label: Some(format!("lucisv: {command}")), edit };
|
||||
let id = self.send_request(ApplyWorkspaceEdit::METHOD, params);
|
||||
self.pending.insert(id, Pending::ApplyEdit(command.to_string()));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Answer `lucisv.showInstantiations` with its sites, and — for a client
|
||||
/// that can be sent one — push a `window/showDocument` for the first of
|
||||
/// them, so clicking the lens actually moves a cursor.
|
||||
///
|
||||
/// `executeCommand`'s *result* cannot navigate: it goes back to whatever
|
||||
/// invoked the command, and no editor moves on one. So the locations are
|
||||
/// the answer for a caller that wants the list, and the push is what makes
|
||||
/// the lens do something in an editor. Only the **first** site is shown:
|
||||
/// `window/showDocument` opens one document, and the protocol has no
|
||||
/// server-initiated "peek these seven places" — that is a VS Code command,
|
||||
/// and this repo's extension declares none. The client's answer is
|
||||
/// ignorable and falls through `response`'s `applying` lookup, as the
|
||||
/// progress `create`'s does.
|
||||
pub(super) fn show_instantiations(
|
||||
&mut self,
|
||||
locations: Vec<Location>,
|
||||
) -> Result<Value, Failure> {
|
||||
if let Some(first) = locations.first().filter(|_| self.abilities.show_document) {
|
||||
let params = ShowDocumentParams {
|
||||
uri: first.uri.clone(),
|
||||
external: None,
|
||||
take_focus: Some(true),
|
||||
selection: Some(first.range),
|
||||
};
|
||||
self.send_request(ShowDocument::METHOD, params);
|
||||
}
|
||||
to_value(locations)
|
||||
}
|
||||
|
||||
/// What the client answered.
|
||||
///
|
||||
/// Two answers are read: a `workspace/applyEdit`'s and a
|
||||
/// `workspace/configuration`'s. Nothing else this server asks of the
|
||||
/// client has an answer worth acting on: one that refuses the
|
||||
/// file-watcher (un)registration simply keeps the save-only staleness
|
||||
/// model; one that errors a `window/workDoneProgress/create` renders no
|
||||
/// bar and ignores the `$/progress` that named that token, per spec; one
|
||||
/// that declines a `workspace/codeLens/refresh` keeps the counts it has,
|
||||
/// and the next save asks again; and one that could not open a
|
||||
/// `window/showDocument` has already told the user so itself. None of
|
||||
/// those ids is ever in `pending`, so they all fall out here — in any
|
||||
/// arrival order, since the id is the whole of the lookup.
|
||||
pub(super) fn response(&mut self, response: Response) {
|
||||
match self.pending.remove(&response.id) {
|
||||
Some(Pending::ApplyEdit(command)) => self.applied(command, response),
|
||||
Some(Pending::Configuration) => self.configured(response),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Say so when the client did not apply an edit the server pushed.
|
||||
fn applied(&mut self, command: String, response: Response) {
|
||||
// A refusal is worth saying out loud: the user ran a command, watched
|
||||
// nothing happen, and would otherwise have no idea why. An answer that
|
||||
// does not parse is a refusal too — nothing was seen to be applied.
|
||||
let reason = match response.response_result {
|
||||
Ok(value) => match serde_json::from_value::<ApplyWorkspaceEditResponse>(value) {
|
||||
Ok(applied) if applied.applied => return,
|
||||
Ok(applied) => applied.failure_reason,
|
||||
Err(problem) => Some(problem.to_string()),
|
||||
},
|
||||
Err(error) => Some(error.message),
|
||||
};
|
||||
let message = match reason {
|
||||
Some(reason) => {
|
||||
format!("lucisv: {command} — the editor did not apply the edit: {reason}")
|
||||
}
|
||||
None => format!("lucisv: {command} — the editor did not apply the edit."),
|
||||
};
|
||||
self.show_message(MessageType::ERROR, message);
|
||||
}
|
||||
|
||||
/// Adopt the settings the client answered a `workspace/configuration`
|
||||
/// with.
|
||||
///
|
||||
/// **Never an error path.** The answer is an array with one entry per
|
||||
/// requested item, and this asked for exactly one — so entry 0 is the
|
||||
/// `lucisv` section. Anything else the client can send (an error, a
|
||||
/// `null` entry, an empty array, an object where an array belongs, a
|
||||
/// string) means the same thing: the client has no settings for us, which
|
||||
/// is the defaults. Nothing here is worth a popup — the user did not ask
|
||||
/// for this request and cannot act on its failure.
|
||||
fn configured(&mut self, response: Response) {
|
||||
let answered = response.response_result.unwrap_or(Value::Null);
|
||||
let section = answered.get(0).cloned().unwrap_or(Value::Null);
|
||||
self.apply_settings(settings::from_section(§ion));
|
||||
}
|
||||
|
||||
/// Say what went wrong while working out which files to index — a
|
||||
/// filelist naming a file that has moved, an unset variable, an option
|
||||
/// lucisv does not know.
|
||||
///
|
||||
/// Every one is logged, but only the first is *shown*: a filelist that has
|
||||
/// drifted from the tree can easily carry forty stale paths, and forty
|
||||
/// popups would be worse than the problem. Said once per rebuild, which is
|
||||
/// once per save — the same rhythm the `lucisv.toml` warning has.
|
||||
///
|
||||
/// `workspace/willRenameFiles` reports through here too: an `` `include``
|
||||
/// a rename strands is the same kind of news, said at the same volume, and
|
||||
/// a rename that strands forty of them must not open forty popups.
|
||||
pub(super) fn report_scope(&self, warnings: Vec<String>) {
|
||||
for warning in &warnings {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::WARNING,
|
||||
message: format!("lucisv: {warning}"),
|
||||
},
|
||||
);
|
||||
}
|
||||
let Some(first) = warnings.first() else { return };
|
||||
let rest = warnings.len() - 1;
|
||||
let message = match rest {
|
||||
0 => format!("lucisv: {first}"),
|
||||
_ => format!("lucisv: {first} (and {rest} more — see the lucisv log)"),
|
||||
};
|
||||
self.notify(ShowMessage::METHOD, ShowMessageParams { typ: MessageType::WARNING, message });
|
||||
}
|
||||
|
||||
pub(super) fn show_message(&self, typ: MessageType, message: String) {
|
||||
self.notify(ShowMessage::METHOD, ShowMessageParams { typ, message: message.clone() });
|
||||
self.notify(LogMessage::METHOD, LogMessageParams { typ, message });
|
||||
}
|
||||
|
||||
pub(super) fn notify(&self, method: &str, params: impl serde::Serialize) {
|
||||
notify_on(&self.connection, method, params);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// timing (`--verbose`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The clock a timing line reads, started **only** when `--verbose` asked
|
||||
/// for one.
|
||||
///
|
||||
/// `None` is the whole of what verbose-off costs: one branch here, and
|
||||
/// then no clock read, no `format!` and no notification anywhere below.
|
||||
/// Every timing site starts with this.
|
||||
pub(super) fn timer(&self) -> Option<std::time::Instant> {
|
||||
self.verbose.then(std::time::Instant::now)
|
||||
}
|
||||
|
||||
/// One timing line for work that was being timed — and nothing at all,
|
||||
/// closure included, for work that was not.
|
||||
pub(super) fn timed(
|
||||
&self,
|
||||
started: Option<std::time::Instant>,
|
||||
line: impl FnOnce(&str) -> String,
|
||||
) {
|
||||
let Some(started) = started else { return };
|
||||
self.timing(line(&ms(started)));
|
||||
}
|
||||
|
||||
/// One `timing:` line in the client's output channel.
|
||||
///
|
||||
/// `MessageType::LOG` and the same `window/logMessage` the per-file index
|
||||
/// log uses — the channel is already this server's, and the one-word
|
||||
/// prefix is what lets a reader (or a `grep`) pick these out of it. Sent
|
||||
/// straight down the writer thread like every other notification, so it
|
||||
/// cannot block on anything the loop is holding.
|
||||
pub(super) fn timing(&self, line: String) {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams { typ: MessageType::LOG, message: format!("timing: {line}") },
|
||||
);
|
||||
}
|
||||
|
||||
/// One line for a request the order contract makes wait, naming which of
|
||||
/// [`Server::must_wait`]'s three clauses held it.
|
||||
///
|
||||
/// The question this answers is the one a slow-looking editor raises:
|
||||
/// "was that request slow, or was it never started?". Silent for anything
|
||||
/// that is not a request — nothing else waits.
|
||||
pub(super) fn say_held(&self, message: &Message) {
|
||||
if !self.verbose {
|
||||
return;
|
||||
}
|
||||
let Message::Request(request) = message else { return };
|
||||
self.timing(format!(
|
||||
"{} HELD behind a rescan (answering={}, wanted={}, already held={})",
|
||||
request.method,
|
||||
self.answering_a_rescan,
|
||||
self.rescan_wanted,
|
||||
self.held.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// One notification, on a connection rather than through a `Server`.
|
||||
pub(super) fn notify_on(connection: &Connection, method: &str, params: impl serde::Serialize) {
|
||||
let notification = Notification::new(method.to_string(), params);
|
||||
// A closed channel means the client is gone; there is nobody left to
|
||||
// report the failure to.
|
||||
let _ = connection.sender.send(Message::Notification(notification));
|
||||
}
|
||||
|
||||
/// How long ago, in milliseconds — the one unit every timing line is written
|
||||
/// in, to two decimals so that a sub-millisecond answer is still a number.
|
||||
pub(super) fn ms(started: std::time::Instant) -> String {
|
||||
format!("{:.2} ms", started.elapsed().as_secs_f64() * 1_000.0)
|
||||
}
|
||||
|
||||
/// The `s` a count needs, or nothing. One file is not "1 files".
|
||||
pub(super) fn plural(count: usize) -> &'static str {
|
||||
if count == 1 {
|
||||
""
|
||||
} else {
|
||||
"s"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! What the server says about a buffer's contents, and when.
|
||||
//!
|
||||
//! *When* is the change debounce: a `didChange` marks a buffer dirty and the
|
||||
//! first thing that needs its analysis flushes it, so a typing burst costs
|
||||
//! one reparse (`docs/features/change-debounce/README.md`). *What* is one
|
||||
//! parse-and-lint pass, `diagnostics_of`, that both delivery models answer
|
||||
//! from: the push (`publish`, gated so a pulling client is never pushed) and
|
||||
//! the pull (`document_report`, `workspace_report`, stamped with the
|
||||
//! generation — `docs/features/pull-diagnostics/README.md`).
|
||||
|
||||
use lsp_types::notification::{LogMessage, Notification as _, PublishDiagnostics};
|
||||
use lsp_types::{
|
||||
DocumentDiagnosticReport, FullDocumentDiagnosticReport, LogMessageParams, MessageType,
|
||||
PreviousResultId, PublishDiagnosticsParams, RelatedFullDocumentDiagnosticReport,
|
||||
RelatedUnchangedDocumentDiagnosticReport, UnchangedDocumentDiagnosticReport, Uri,
|
||||
WorkspaceDiagnosticReport, WorkspaceDocumentDiagnosticReport,
|
||||
WorkspaceFullDocumentDiagnosticReport, WorkspaceUnchangedDocumentDiagnosticReport,
|
||||
};
|
||||
|
||||
use super::client::plural;
|
||||
use super::Server;
|
||||
use crate::diagnostics;
|
||||
|
||||
impl Server {
|
||||
/// Replace a buffer's text, re-arming its `lucisv.toml` warning: the user
|
||||
/// has moved on, and a config problem is worth saying once more.
|
||||
pub(super) fn set_document(&mut self, uri: Uri, text: String) {
|
||||
self.config_warnings.remove(&uri);
|
||||
let was_large = self.workspace.document(&uri).is_some_and(|doc| doc.large);
|
||||
self.workspace.set_document(uri.clone(), text);
|
||||
self.generation += 1;
|
||||
self.announce_fast_path(&uri, was_large);
|
||||
}
|
||||
|
||||
/// Hold a buffer's newest text for later analysis. A change already held
|
||||
/// is replaced in place, so the entry's position in the flush order — the
|
||||
/// order the buffers were first dirtied in — survives a burst.
|
||||
pub(super) fn mark_dirty(&mut self, uri: Uri, text: String) {
|
||||
match self.dirty.iter_mut().find(|(pending, _)| *pending == uri) {
|
||||
Some(entry) => entry.1 = text,
|
||||
None => self.dirty.push((uri, text)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyze and republish every dirty buffer, oldest first. One flush is
|
||||
/// one `set_document` per buffer, so a whole typing burst costs one
|
||||
/// reparse per buffer it touched instead of one per keystroke.
|
||||
pub(super) fn flush_dirty(&mut self) {
|
||||
if self.dirty.is_empty() {
|
||||
return;
|
||||
}
|
||||
let started = self.timer();
|
||||
let buffers = self.dirty.len();
|
||||
for (uri, text) in std::mem::take(&mut self.dirty) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.publish(&uri);
|
||||
}
|
||||
self.timed(started, |took| {
|
||||
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
|
||||
});
|
||||
}
|
||||
|
||||
/// Say once, in the output channel, that a buffer is on the large-file
|
||||
/// fast path.
|
||||
///
|
||||
/// Once per *entry* into the mode, not once per notification: a keystroke
|
||||
/// in a 100 MB buffer must not log a line, and a buffer edited past the
|
||||
/// threshold mid-session must. Nothing is said on the way back out —
|
||||
/// leaving the mode restores every answer, which is not news.
|
||||
fn announce_fast_path(&self, uri: &Uri, was_large: bool) {
|
||||
let Some(doc) = self.workspace.document(uri).filter(|doc| doc.large && !was_large) else {
|
||||
return;
|
||||
};
|
||||
let what = match doc.path.as_deref() {
|
||||
Some(path) => path.display().to_string(),
|
||||
None => uri.as_str().to_string(),
|
||||
};
|
||||
let size = doc.text.len();
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::INFO,
|
||||
message: format!(
|
||||
"lucisv: large-file fast path: {what} ({size} bytes) — \
|
||||
syntax highlighting only, nothing is parsed or indexed"
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Everything the server has to say about a buffer — the one computation
|
||||
/// both diagnostic models answer from. A buffer that is not open has
|
||||
/// nothing said about it.
|
||||
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
|
||||
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
|
||||
// The lint pass is given the project: the rule selection
|
||||
// `lucisv.lint.*` resolved to, and the index's identifier census, which
|
||||
// is what lets the semantic rules default on here without accusing a
|
||||
// signal another file reads (`docs/features/semantic-lints-on/`).
|
||||
diagnostics::all_in(doc, &crate::lint::LintRun::for_document(&self.workspace, doc))
|
||||
}
|
||||
|
||||
/// Publish everything known about a buffer — parse errors and lint
|
||||
/// warnings — in one notification. Two publishes for one version would
|
||||
/// leave only the second on screen, since LSP replaces rather than merges.
|
||||
pub(super) fn publish(&self, uri: &Uri) {
|
||||
// `send_diagnostics` would drop this anyway for a pulling client; the
|
||||
// early return is so the parse+lint pass is not run for nobody, once
|
||||
// per open buffer, on every index rebuild.
|
||||
if self.abilities.pull_diagnostics || self.workspace.document(uri).is_none() {
|
||||
return;
|
||||
}
|
||||
self.send_diagnostics(uri.clone(), self.diagnostics_of(uri));
|
||||
}
|
||||
|
||||
/// Push one buffer's diagnostics — unless the client pulls them.
|
||||
///
|
||||
/// A client that advertised `textDocument.diagnostic` owns the timing and
|
||||
/// the lifecycle of every diagnostic it shows: it asks when it wants them
|
||||
/// and drops them when it closes the document, so a push would be a second
|
||||
/// set of squiggles arriving on a schedule it did not choose. This is the
|
||||
/// one gate that keeps the two models from ever running for one client —
|
||||
/// the `didClose` clear goes through here too, for the same reason.
|
||||
pub(super) fn send_diagnostics(&self, uri: Uri, diagnostics: Vec<lsp_types::Diagnostic>) {
|
||||
if self.abilities.pull_diagnostics {
|
||||
return;
|
||||
}
|
||||
let params = PublishDiagnosticsParams { uri, diagnostics, version: None };
|
||||
self.notify(PublishDiagnostics::METHOD, params);
|
||||
}
|
||||
|
||||
/// One buffer's diagnostics, or an unchanged report when nothing that
|
||||
/// feeds them has moved since the client's last pull.
|
||||
pub(super) fn document_report(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
previous: Option<String>,
|
||||
) -> DocumentDiagnosticReport {
|
||||
let result_id = self.result_id();
|
||||
if previous.as_deref() == Some(result_id.as_str()) {
|
||||
let unchanged = UnchangedDocumentDiagnosticReport { result_id };
|
||||
return DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport {
|
||||
related_documents: None,
|
||||
unchanged_document_diagnostic_report: unchanged,
|
||||
});
|
||||
}
|
||||
let full = FullDocumentDiagnosticReport {
|
||||
result_id: Some(result_id),
|
||||
items: self.diagnostics_of(uri),
|
||||
};
|
||||
DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
|
||||
related_documents: None,
|
||||
full_document_diagnostic_report: full,
|
||||
})
|
||||
}
|
||||
|
||||
/// Every open buffer's diagnostics, in URI order so two pulls of the same
|
||||
/// state read the same way.
|
||||
///
|
||||
/// Open buffers are the whole scope: this server has never diagnosed a
|
||||
/// file it was not shown, and pulling would be the wrong place to start —
|
||||
/// linting the workspace on a keystroke-driven request is a rescan of
|
||||
/// every file per pull. The limit is stated in the feature README.
|
||||
pub(super) fn workspace_report(
|
||||
&self,
|
||||
previous: &[PreviousResultId],
|
||||
) -> WorkspaceDiagnosticReport {
|
||||
let result_id = self.result_id();
|
||||
let mut uris = self.workspace.open_uris();
|
||||
uris.sort();
|
||||
let items = uris
|
||||
.into_iter()
|
||||
.map(|uri| {
|
||||
let known = previous.iter().any(|seen| seen.uri == uri && seen.value == result_id);
|
||||
if known {
|
||||
let unchanged =
|
||||
UnchangedDocumentDiagnosticReport { result_id: result_id.clone() };
|
||||
return WorkspaceDocumentDiagnosticReport::Unchanged(
|
||||
WorkspaceUnchangedDocumentDiagnosticReport {
|
||||
uri,
|
||||
version: None,
|
||||
unchanged_document_diagnostic_report: unchanged,
|
||||
},
|
||||
);
|
||||
}
|
||||
let full = FullDocumentDiagnosticReport {
|
||||
result_id: Some(result_id.clone()),
|
||||
items: self.diagnostics_of(&uri),
|
||||
};
|
||||
WorkspaceDocumentDiagnosticReport::Full(WorkspaceFullDocumentDiagnosticReport {
|
||||
uri,
|
||||
version: None,
|
||||
full_document_diagnostic_report: full,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
WorkspaceDiagnosticReport { items }
|
||||
}
|
||||
|
||||
/// What a report is stamped with: the generation everything was computed
|
||||
/// against. Coarse on purpose — a change anywhere costs one extra full
|
||||
/// report elsewhere, and a stale "unchanged" would cost a wrong squiggle.
|
||||
fn result_id(&self) -> String {
|
||||
self.generation.to_string()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
//! `answer_request`: the dispatch table over request methods.
|
||||
//!
|
||||
//! One `match` arm per method, each a decode and a call into the module that
|
||||
//! owns the feature, so a reader looking for "what answers hover" finds the
|
||||
//! line here and follows it. The table stays whole on purpose — a dispatch
|
||||
//! table over an enum-shaped set is the one function the size rule exempts —
|
||||
//! and everything it merely delegates to lives elsewhere: the formatting
|
||||
//! entries in `formatting.rs`, the token deltas in `semantic_tokens.rs`, the
|
||||
//! pull reports in `diagnostics.rs`, the large-buffer gate in
|
||||
//! `large_file.rs`. Below the table is its vocabulary: `Failure`, the
|
||||
//! protocol's own words for a request that could not be answered, and the
|
||||
//! decoders every arm uses.
|
||||
|
||||
use lsp_server::{Request, RequestId, Response};
|
||||
use lsp_types::request::{
|
||||
CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare,
|
||||
CodeActionRequest, CodeLensRequest, Completion, DocumentDiagnosticRequest,
|
||||
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
|
||||
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams,
|
||||
GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest,
|
||||
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
|
||||
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest,
|
||||
SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest,
|
||||
TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, WillRenameFiles,
|
||||
WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
|
||||
CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams, DocumentDiagnosticParams,
|
||||
DocumentDiagnosticReportResult, DocumentHighlightParams, DocumentLinkParams,
|
||||
DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams,
|
||||
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams,
|
||||
RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams,
|
||||
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
|
||||
SemanticTokensResult, SignatureHelpParams, TextDocumentPositionParams,
|
||||
TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, Uri,
|
||||
WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult, WorkspaceSymbolParams,
|
||||
WorkspaceSymbolResponse,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{
|
||||
code_action, completion, design_hierarchy, file_ops, folding, format, hierarchy, hover,
|
||||
includes, inlay, inline, lens, linked, nav, pairs, ports, rename, selection, signature,
|
||||
symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
impl Server {
|
||||
/// Answer one request, timing it when `--verbose` asked.
|
||||
///
|
||||
/// **The line goes out before the response it describes.** The dispatch is
|
||||
/// here and the response is sent by the caller, so a wrapper can only
|
||||
/// speak first — which is also what keeps the measurement to exactly the
|
||||
/// handler, with none of the transport in it. Nothing keys off the order:
|
||||
/// a `window/logMessage` carries no id, and a client pairs the response
|
||||
/// with its request by id whatever arrived in between.
|
||||
pub(super) fn request(&mut self, request: Request) -> Response {
|
||||
let Some(started) = self.timer() else { return self.answer_request(request) };
|
||||
let method = request.method.clone();
|
||||
let response = self.answer_request(request);
|
||||
self.timing(format!("{method} answered in {}", ms(started)));
|
||||
response
|
||||
}
|
||||
|
||||
fn answer_request(&mut self, request: Request) -> Response {
|
||||
// A request answers from a buffer's analysis, so any change the client
|
||||
// has already sent is in effect before it is answered — the order
|
||||
// contract the loop has always promised. Here is also where a typing
|
||||
// burst is coalesced: the changes before this request all become one
|
||||
// `set_document` in `flush_dirty`.
|
||||
self.flush_dirty();
|
||||
let id = request.id.clone();
|
||||
let method = request.method.clone();
|
||||
// The large-file fast path answers first, and for most methods it
|
||||
// answers "nothing" before any handler is entered. Everything it lets
|
||||
// through is either cheap on an empty analysis or is the one request
|
||||
// that does real work on a large buffer — see
|
||||
// `docs/features/large-file-mode/README.md` for the whole table.
|
||||
if let Some(answer) = self.large_file_answer(&method, &request.params) {
|
||||
return match answer {
|
||||
Ok(value) => Response::new_ok(id, value),
|
||||
Err(failure) => failure.into_response(id),
|
||||
};
|
||||
}
|
||||
let result = match method.as_str() {
|
||||
Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)),
|
||||
RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)),
|
||||
// LSP 3.18's multi-range form of the line above — `n` ranges, one
|
||||
// round trip, one answer. Answered whether or not the capability
|
||||
// was widened for this client: a request we can serve is not
|
||||
// refused because the client asked without saying it would.
|
||||
format::RANGES_FORMATTING => decode(request).and_then(|p| self.ranges_formatting(p)),
|
||||
// One keystroke, at most one edit, never a word to the user — see
|
||||
// `on_type_formatting`.
|
||||
OnTypeFormatting::METHOD => decode(request).and_then(|p| self.on_type_formatting(p)),
|
||||
// Format-on-save, protocol-native: the client asks before it
|
||||
// writes, and applies whatever comes back. Opt-in, and the decline
|
||||
// is the cheap path — see `will_save_wait_until`.
|
||||
WillSaveWaitUntil::METHOD => decode(request).and_then(|p| self.will_save_wait_until(p)),
|
||||
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.map(|offset| hover::hover(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
GotoDefinition::METHOD => decode(request).and_then(|p: GotoDefinitionParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.map(|offset| nav::definition(&self.workspace, &uri, offset))
|
||||
.unwrap_or_default();
|
||||
to_value(GotoDefinitionResponse::Array(locations))
|
||||
}),
|
||||
// The same answer shape as go-to-definition, deliberately: an
|
||||
// array in every case, empty where there is nothing to jump to,
|
||||
// and every candidate where the workspace holds the type name
|
||||
// twice. A buffer this server has not been sent is the empty
|
||||
// array too, which is what `unwrap_or_default` on the position
|
||||
// conversion means here as it does above.
|
||||
GotoTypeDefinition::METHOD => {
|
||||
decode(request).and_then(|p: GotoTypeDefinitionParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.map(|offset| type_def::type_definition(&self.workspace, &uri, offset))
|
||||
.unwrap_or_default();
|
||||
to_value(GotoTypeDefinitionResponse::Array(locations))
|
||||
})
|
||||
}
|
||||
// A closing label and the name it repeats, edited together. `null`
|
||||
// for every position that is not one of those two names — and for
|
||||
// a pair that could not be linked honestly (no label written, a
|
||||
// label that does not match, an escaped identifier), because an
|
||||
// empty `ranges` list is not what "nothing to link" means here.
|
||||
LinkedEditingRange::METHOD => {
|
||||
decode(request).and_then(|p: LinkedEditingRangeParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.and_then(|offset| {
|
||||
let doc = self.workspace.document(&uri)?;
|
||||
linked::linked_editing_ranges(doc, offset)
|
||||
})
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
// The underline half of include navigation. Unresolvable includes
|
||||
// are simply absent from the list — never an error, and never a
|
||||
// link that goes nowhere.
|
||||
DocumentLinkRequest::METHOD => decode(request).and_then(|p: DocumentLinkParams| {
|
||||
to_value(includes::document_links(&self.workspace, &p.text_document.uri))
|
||||
}),
|
||||
References::METHOD => decode(request).and_then(|p: ReferenceParams| {
|
||||
let include = p.context.include_declaration;
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.map(|offset| nav::references(&self.workspace, &uri, offset, include))
|
||||
.unwrap_or_default();
|
||||
to_value(locations)
|
||||
}),
|
||||
// Two answers behind one request: a scope keyword pairs with its
|
||||
// own closer, and anything else is a symbol whose other
|
||||
// occurrences in this file are what to draw. A cursor that is
|
||||
// neither answers `null` rather than an empty list — an empty list
|
||||
// means "no occurrences anywhere", which suppresses the editor's
|
||||
// own word highlighting, and losing that everywhere would be a
|
||||
// poor trade for gaining this.
|
||||
DocumentHighlightRequest::METHOD => {
|
||||
decode(request).and_then(|p: DocumentHighlightParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let found = self.offset(&uri, position).and_then(|offset| {
|
||||
let doc = self.workspace.document(&uri)?;
|
||||
pairs::highlights(doc, offset)
|
||||
.or_else(|| nav::document_highlights(doc, offset))
|
||||
});
|
||||
found.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
FoldingRangeRequest::METHOD => decode(request).and_then(|p: FoldingRangeParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => to_value(folding::folding_ranges(doc)),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
// Ghost port names on ordered connection lists. Range-scoped, as
|
||||
// the protocol asks: the client sends the lines it is showing and
|
||||
// gets the hints inside them.
|
||||
InlayHintRequest::METHOD => decode(request).and_then(|p: InlayHintParams| {
|
||||
to_value(inlay::inlay_hints(&self.workspace, &p.text_document.uri, p.range))
|
||||
}),
|
||||
SemanticTokensFullRequest::METHOD => {
|
||||
decode(request).and_then(|p: SemanticTokensParams| {
|
||||
self.semantic_tokens_full(&p.text_document.uri)
|
||||
.map(SemanticTokensResult::Tokens)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
// The same answer as `full`, said as what changed since the
|
||||
// client's last one — or as a whole new answer when we cannot
|
||||
// prove what it holds.
|
||||
SemanticTokensFullDeltaRequest::METHOD => {
|
||||
decode(request).and_then(|p: SemanticTokensDeltaParams| {
|
||||
self.semantic_tokens_delta(&p.text_document.uri, &p.previous_result_id)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
// The visible lines only, for the first paint of a large file.
|
||||
// Self-contained and unremembered: a range answer is not what a
|
||||
// later delta is computed against, so it carries no `resultId`.
|
||||
//
|
||||
// On a buffer over `lucisv.largeFile.threshold` this is the *only*
|
||||
// colouring request that answers, and it lexes the window rather
|
||||
// than filtering the document's tokens — there are none.
|
||||
SemanticTokensRangeRequest::METHOD => {
|
||||
decode(request).and_then(|p: SemanticTokensRangeParams| {
|
||||
let data = match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) if doc.large => tokens::semantic_tokens_in_window(doc, p.range),
|
||||
Some(doc) => tokens::semantic_tokens_in_range(doc, p.range),
|
||||
None => return Ok(Value::Null),
|
||||
};
|
||||
to_value(SemanticTokensRangeResult::Tokens(SemanticTokens {
|
||||
result_id: None,
|
||||
data,
|
||||
}))
|
||||
})
|
||||
}
|
||||
DocumentSymbolRequest::METHOD => decode(request).and_then(|p: DocumentSymbolParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => {
|
||||
to_value(DocumentSymbolResponse::Nested(symbols::document_symbols(doc)))
|
||||
}
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
CodeActionRequest::METHOD => decode(request).and_then(|p: CodeActionParams| {
|
||||
let uri = p.text_document.uri;
|
||||
let only = p.context.only;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
// A code-action request carries no `tabSize`, so the width a
|
||||
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
|
||||
// or from the built-in default.
|
||||
let tab_width =
|
||||
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
||||
let mut actions =
|
||||
code_action::code_actions(&uri, doc, p.range, only.as_deref(), tab_width);
|
||||
// The port refactorings answer for the cursor, not for a range:
|
||||
// the request's start is where the user is.
|
||||
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
||||
{
|
||||
let offset = doc.positions().offset(p.range.start);
|
||||
actions.extend(ports::code_actions(&self.workspace, &uri, offset));
|
||||
}
|
||||
to_value(actions)
|
||||
}),
|
||||
// Custom method, so it is matched by name rather than through a
|
||||
// `lsp_types::request` type. Nothing advertises it: a client that
|
||||
// does not know it never asks.
|
||||
pairs::SCOPE_PAIRS_METHOD => decode(request).and_then(|p: pairs::ScopePairsParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => to_value(pairs::scope_pairs(doc)),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
design_hierarchy::METHOD => to_value(design_hierarchy::snapshot(
|
||||
&self.workspace,
|
||||
self.hierarchy_revision,
|
||||
self.index_is_complete(),
|
||||
)),
|
||||
// A rename the engine declines comes back as a request error
|
||||
// carrying its own sentence, which is what an editor shows in the
|
||||
// rename box. `prepareRename` declines the same way, so the box
|
||||
// never opens for a rename that would then fail.
|
||||
PrepareRenameRequest::METHOD => {
|
||||
decode(request).and_then(|at: TextDocumentPositionParams| {
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
match rename::prepare(&self.workspace, &uri, offset) {
|
||||
Ok(response) => to_value(response),
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
})
|
||||
}
|
||||
Rename::METHOD => decode(request).and_then(|p: RenameParams| {
|
||||
let new_name = p.new_name;
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
match rename::rename(&self.workspace, &uri, offset, &new_name) {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
to_value(edit)
|
||||
}
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
}),
|
||||
// "N instantiations" over every module and interface declared in
|
||||
// the buffer. Every lens is complete when it is returned — there
|
||||
// is no `codeLens/resolve` — and a buffer this server has not been
|
||||
// sent answers `null`, as every other document-scoped request
|
||||
// does.
|
||||
CodeLensRequest::METHOD => decode(request).and_then(|p: CodeLensParams| {
|
||||
lens::code_lenses(&self.workspace, &p.text_document.uri)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
// The port refactorings, and the code lens's own jump. A refusal
|
||||
// is the engine's own sentence, returned as `RequestFailed`
|
||||
// exactly as a declined rename is.
|
||||
ExecuteCommand::METHOD => decode(request).and_then(|p: ExecuteCommandParams| {
|
||||
if p.command == lens::SHOW_INSTANTIATIONS {
|
||||
return match lens::execute(&self.workspace, &p.arguments) {
|
||||
Ok(locations) => self.show_instantiations(locations),
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
};
|
||||
}
|
||||
match ports::execute(&self.workspace, &p.command, &p.arguments) {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
self.deliver(&p.command, edit)
|
||||
}
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
}),
|
||||
// Pull diagnostics, LSP 3.17. Same parse+lint pass the push model
|
||||
// publishes; only the timing and the caching differ.
|
||||
DocumentDiagnosticRequest::METHOD => {
|
||||
decode(request).and_then(|p: DocumentDiagnosticParams| {
|
||||
let report = self.document_report(&p.text_document.uri, p.previous_result_id);
|
||||
to_value(DocumentDiagnosticReportResult::Report(report))
|
||||
})
|
||||
}
|
||||
WorkspaceDiagnosticRequest::METHOD => {
|
||||
decode(request).and_then(|p: WorkspaceDiagnosticParams| {
|
||||
let report = self.workspace_report(&p.previous_result_ids);
|
||||
to_value(WorkspaceDiagnosticReportResult::Report(report))
|
||||
})
|
||||
}
|
||||
// Expand-selection. One chain per position, in the order asked —
|
||||
// a client sends one position per cursor, and a multi-cursor
|
||||
// editor matches the answers up by index.
|
||||
SelectionRangeRequest::METHOD => decode(request).and_then(|p: SelectionRangeParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => to_value(selection::selection_ranges(doc, &p.positions)),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
// Module hinting. A position that is not a module item answers
|
||||
// `null` rather than an empty list, so the editor's own word
|
||||
// completion is left in charge there.
|
||||
Completion::METHOD => decode(request).and_then(|p: CompletionParams| {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
completion::completions(&self.workspace, &uri, position, self.abilities.snippets)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
// Ghost text. `null` for every position that is not one of the
|
||||
// two triggers, which is nearly all of them — the request arrives
|
||||
// on every keystroke, so the decline has to be the cheap path.
|
||||
InlineCompletionRequest::METHOD => {
|
||||
decode(request).and_then(|p: InlineCompletionParams| {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
inline::inline_completions(&self.workspace, &uri, position)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
SignatureHelpRequest::METHOD => decode(request).and_then(|p: SignatureHelpParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.and_then(|offset| signature::signature_help(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
// The module hierarchy. `prepare` answers `null` for a position
|
||||
// that is not a module name, which is what stops an editor from
|
||||
// opening an empty hierarchy view; the two directions then answer
|
||||
// one hop each, and the client drives the expansion.
|
||||
CallHierarchyPrepare::METHOD => {
|
||||
decode(request).and_then(|p: CallHierarchyPrepareParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
CallHierarchyIncomingCalls::METHOD => {
|
||||
decode(request).and_then(|p: CallHierarchyIncomingCallsParams| {
|
||||
to_value(hierarchy::incoming(&self.workspace, &p.item))
|
||||
})
|
||||
}
|
||||
CallHierarchyOutgoingCalls::METHOD => {
|
||||
decode(request).and_then(|p: CallHierarchyOutgoingCallsParams| {
|
||||
to_value(hierarchy::outgoing(&self.workspace, &p.item))
|
||||
})
|
||||
}
|
||||
// The class inheritance tree. Same contract as the call hierarchy
|
||||
// above: `prepare` answers `null` for a position that is not a
|
||||
// class name, and the two directions answer one hop each while the
|
||||
// client drives the expansion.
|
||||
TypeHierarchyPrepare::METHOD => {
|
||||
decode(request).and_then(|p: TypeHierarchyPrepareParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
TypeHierarchySupertypes::METHOD => {
|
||||
decode(request).and_then(|p: TypeHierarchySupertypesParams| {
|
||||
to_value(type_hierarchy::supertypes(&self.workspace, &p.item))
|
||||
})
|
||||
}
|
||||
TypeHierarchySubtypes::METHOD => {
|
||||
decode(request).and_then(|p: TypeHierarchySubtypesParams| {
|
||||
to_value(type_hierarchy::subtypes(&self.workspace, &p.item))
|
||||
})
|
||||
}
|
||||
// The client is about to rename files and asks what that costs.
|
||||
// Every `` `include`` that *resolves* to one of them is re-spelled
|
||||
// so it still resolves afterwards; one that no include path can
|
||||
// reach is left exactly as written and named in a warning, because
|
||||
// inventing a path that resolves to nothing would be worse than
|
||||
// the stale one. `null` when there is nothing to do.
|
||||
WillRenameFiles::METHOD => decode(request).and_then(|p: RenameFilesParams| {
|
||||
let rewrite = file_ops::will_rename(&self.workspace, &p.files);
|
||||
self.report_scope(rewrite.warnings);
|
||||
match rewrite.edit {
|
||||
Some(edit) => to_value(edit),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
WorkspaceSymbolRequest::METHOD => {
|
||||
decode(request).and_then(|p: WorkspaceSymbolParams| {
|
||||
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
|
||||
&self.workspace,
|
||||
&p.query,
|
||||
)))
|
||||
})
|
||||
}
|
||||
_ => Err(Failure::MethodNotFound(method)),
|
||||
};
|
||||
match result {
|
||||
Ok(value) => Response::new_ok(id, value),
|
||||
Err(failure) => failure.into_response(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte offset an LSP position names in an open document.
|
||||
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
|
||||
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a request could not be answered, in the protocol's own terms.
|
||||
pub(super) enum Failure {
|
||||
MethodNotFound(String),
|
||||
InvalidParams(String),
|
||||
Internal(String),
|
||||
/// The request was well-formed and the server declined it, with a reason
|
||||
/// meant for the user — LSP's `RequestFailed`.
|
||||
Request(String),
|
||||
/// The server chose not to compute an answer it could have computed, with
|
||||
/// a code that tells the client to keep what it has and ask again rather
|
||||
/// than to treat this as the answer. The large-file fast path declines
|
||||
/// `semanticTokens/full` this way; nothing else uses it.
|
||||
Declined(lsp_server::ErrorCode, String),
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
fn into_response(self, id: RequestId) -> Response {
|
||||
let (code, message) = match self {
|
||||
Failure::MethodNotFound(method) => (
|
||||
lsp_server::ErrorCode::MethodNotFound as i32,
|
||||
format!("unhandled method: {method}"),
|
||||
),
|
||||
Failure::InvalidParams(message) => {
|
||||
(lsp_server::ErrorCode::InvalidParams as i32, message)
|
||||
}
|
||||
Failure::Internal(message) => (lsp_server::ErrorCode::InternalError as i32, message),
|
||||
Failure::Request(message) => {
|
||||
(lsp_server::ErrorCode::RequestFailed as i32, format!("lucisv: {message}"))
|
||||
}
|
||||
Failure::Declined(code, message) => (code as i32, format!("lucisv: {message}")),
|
||||
};
|
||||
Response::new_err(id, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sentence every large-buffer refusal carries. One string, because a
|
||||
/// user who meets it twice should not have to work out whether they are the
|
||||
/// same thing.
|
||||
pub(super) const TOO_LARGE: &str =
|
||||
"this buffer is over lucisv.largeFile.threshold and is open on the large-file fast path";
|
||||
|
||||
/// The `textDocument.uri` a request names, read out of the raw params.
|
||||
///
|
||||
/// Before the typed decode on purpose: the fast-path gate has to know which
|
||||
/// buffer a request is about without knowing which of thirty parameter types
|
||||
/// it carries, and every document-scoped request in LSP spells it exactly
|
||||
/// here. A request with no `textDocument` (the hierarchy resolutions, the
|
||||
/// workspace-wide ones, `executeCommand`) is not gated at all, which is
|
||||
/// correct: none of them can reach a buffer's text.
|
||||
pub(super) fn document_uri(params: &Value) -> Option<Uri> {
|
||||
params.get("textDocument")?.get("uri")?.as_str()?.parse().ok()
|
||||
}
|
||||
|
||||
fn decode<P: DeserializeOwned>(request: Request) -> Result<P, Failure> {
|
||||
serde_json::from_value(request.params).map_err(|e| Failure::InvalidParams(e.to_string()))
|
||||
}
|
||||
|
||||
pub(super) fn to_value(value: impl serde::Serialize) -> Result<Value, Failure> {
|
||||
serde_json::to_value(value).map_err(|e| Failure::Internal(e.to_string()))
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! The five formatting entries — whole document, one range, several ranges,
|
||||
//! on-type, and the save hook — and what each says when the engine refuses.
|
||||
//!
|
||||
//! All five climb the same settings ladder and run the same engine
|
||||
//! (`crate::format`); what differs is the trigger, and the trigger decides
|
||||
//! the manners: a command the user pressed refuses out loud, a keystroke and
|
||||
//! a save decline in silence. The once-per-change `lucisv.toml` warning and
|
||||
//! the edit-or-nothing contract are the two pieces of server state this
|
||||
//! needs, which is why the entries live here and not in `crate::format`.
|
||||
|
||||
use lsp_types::{
|
||||
DocumentFormattingParams, DocumentOnTypeFormattingParams, DocumentRangeFormattingParams,
|
||||
MessageType, Uri, WillSaveTextDocumentParams,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::dispatch::{to_value, Failure};
|
||||
use super::Server;
|
||||
use crate::{format, on_type};
|
||||
|
||||
impl Server {
|
||||
pub(super) fn formatting(
|
||||
&mut self,
|
||||
params: DocumentFormattingParams,
|
||||
) -> Result<Value, Failure> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::formatting(doc, &settings.config);
|
||||
// A broken `lucisv.toml` is a warning, not a failure: the CLI exits 2 on
|
||||
// one, but an editor that refuses to format because of a typo in a
|
||||
// config file is an editor the user turns off. The buffer is formatted
|
||||
// with the built-in defaults, and the reason is said once per change of
|
||||
// the file — a format-on-save loop would otherwise repeat it forever.
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
/// `textDocument/rangeFormatting`, on the same engine and the same
|
||||
/// all-or-nothing contract as whole-document formatting.
|
||||
pub(super) fn range_formatting(
|
||||
&mut self,
|
||||
params: DocumentRangeFormattingParams,
|
||||
) -> Result<Value, Failure> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::range_formatting(doc, &settings.config, params.range);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
/// `textDocument/rangesFormatting` — LSP 3.18's multi-range form.
|
||||
///
|
||||
/// Line for line the handler above, with `ranges` where it has `range`:
|
||||
/// the same settings ladder, the same engine, the same `edits` and the
|
||||
/// same config warning. That is the point of the feature — a client asking
|
||||
/// for five ranges gets one verified answer instead of five requests whose
|
||||
/// edits it would have to reconcile itself. See
|
||||
/// `docs/features/lsp-318-extras/README.md`.
|
||||
pub(super) fn ranges_formatting(
|
||||
&mut self,
|
||||
params: format::RangesFormattingParams,
|
||||
) -> Result<Value, Failure> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::ranges_formatting(doc, &settings.config, ¶ms.ranges);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
/// `textDocument/onTypeFormatting` — the newline and the semicolon.
|
||||
///
|
||||
/// Two things about it are unlike every other formatting entry, and both
|
||||
/// follow from its trigger being a keystroke rather than a command:
|
||||
///
|
||||
/// * **It never speaks.** A formatter refusal is `[]` and silence, where
|
||||
/// `textDocument/formatting` shows an ERROR and `willSaveWaitUntil`
|
||||
/// shows one per save. Mid-edit code the engine declines is the *normal*
|
||||
/// case here, not a failure worth a popup on every semicolon.
|
||||
/// * **It never warns about a broken `lucisv.toml` either.** That warning
|
||||
/// is deduped per buffer *state*, and `set_document` re-arms it — so a
|
||||
/// request that by definition follows the `didChange` the user's own
|
||||
/// keystroke produced would re-arm and re-show it on every character.
|
||||
/// The user is told on their next explicit format or save, which are the
|
||||
/// two moments they asked lucisv for something.
|
||||
///
|
||||
/// The settings ladder is the one `textDocument/formatting` climbs,
|
||||
/// `tabSize` rung included: unlike `willSaveWaitUntil`, this request does
|
||||
/// carry `FormattingOptions`.
|
||||
pub(super) fn on_type_formatting(
|
||||
&mut self,
|
||||
params: DocumentOnTypeFormattingParams,
|
||||
) -> Result<Value, Failure> {
|
||||
let at = params.text_document_position;
|
||||
let Some(doc) = self.workspace.document(&at.text_document.uri) else {
|
||||
return to_value(Vec::<lsp_types::TextEdit>::new());
|
||||
};
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let edits = on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config);
|
||||
to_value(edits)
|
||||
}
|
||||
|
||||
/// `textDocument/willSaveWaitUntil` — format the buffer the client is
|
||||
/// about to write, for the editors that have no format-on-save of their
|
||||
/// own.
|
||||
///
|
||||
/// `null` unless `lucisv.formatOnSave` is on. A capable client sends this
|
||||
/// before *every* save, so declining has to be the cheap path — and an
|
||||
/// editor that already formats on save (VS Code's `editor.formatOnSave`,
|
||||
/// which runs `textDocument/formatting`) would otherwise format twice.
|
||||
///
|
||||
/// When it is on, this is `textDocument/formatting` with a different
|
||||
/// trigger: the same engine, the same settings ladder, the same
|
||||
/// all-or-nothing contract — one whole-document edit built from verified
|
||||
/// output, or no edit at all. The save's `reason` is not read: manual,
|
||||
/// after-delay and focus-out are all saves, and the user asked for their
|
||||
/// saves to be formatted. The text is the buffer the server holds, because
|
||||
/// the request carries none and the client has not written yet.
|
||||
pub(super) fn will_save_wait_until(
|
||||
&mut self,
|
||||
params: WillSaveTextDocumentParams,
|
||||
) -> Result<Value, Failure> {
|
||||
if !self.workspace.client_settings().format_on_save {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
// No `FormattingOptions` on this request — the protocol carries none —
|
||||
// so the ladder runs without its `tabSize` rung.
|
||||
let settings =
|
||||
format::settings_without_editor_options(doc, self.workspace.client_settings());
|
||||
let result = format::formatting(doc, &settings.config);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
/// Say once per change of a file that its `lucisv.toml` could not be read.
|
||||
fn warn_about_config(&mut self, uri: &Uri, problem: Option<String>) {
|
||||
if let Some(problem) = problem {
|
||||
if self.config_warnings.insert(uri.clone()) {
|
||||
self.show_message(
|
||||
MessageType::WARNING,
|
||||
format!("lucisv: {problem} — formatting with default settings"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One edit, none, or — when the formatter refused — none plus the reason.
|
||||
///
|
||||
/// It never emits partial output (CLAUDE.md invariant #1), so neither do
|
||||
/// we. Diagnostics are not used for the failure: they belong to the parse
|
||||
/// pass and are cleared on the next keystroke, which would erase an
|
||||
/// explicit format failure the user asked for.
|
||||
pub(super) fn edits(
|
||||
&mut self,
|
||||
result: Result<Option<lsp_types::TextEdit>, String>,
|
||||
) -> Result<Value, Failure> {
|
||||
match result {
|
||||
Ok(Some(edit)) => to_value(vec![edit]),
|
||||
Ok(None) => to_value(Vec::<lsp_types::TextEdit>::new()),
|
||||
Err(message) => {
|
||||
self.show_message(MessageType::ERROR, format!("lucisv: cannot format — {message}"));
|
||||
to_value(Vec::<lsp_types::TextEdit>::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
//! The rescans: how the workspace index is rebuilt, and what a rebuild owes
|
||||
//! every open buffer afterwards.
|
||||
//!
|
||||
//! Four entries — `reindex` (the whole scope), `reindex_one` (a save),
|
||||
//! `reindex_widened` (a `didOpen` that grew the scope) and `reindex_for` (a
|
||||
//! file operation, filtered) — over one loop, `scan_until_settled`, which is
|
||||
//! the whole of the coalescing rule: a rescan asked for mid-scan is one more
|
||||
//! scan when this one ends, never a scan inside a scan. `scan_once` is the
|
||||
//! scan that answers the client's messages between two of its files
|
||||
//! (`docs/features/scan-interleave/README.md`); the bar and the log it runs
|
||||
//! under are `progress.rs`'s.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::ProgressToken;
|
||||
|
||||
use super::batch::opened_in;
|
||||
use super::client::{notify_on, plural};
|
||||
use super::progress::IndexWatch;
|
||||
use super::{Server, INTERLEAVE_ABOVE};
|
||||
use crate::state::{IndexEvent, Scan, Workspace};
|
||||
use crate::{design_hierarchy, file_ops};
|
||||
|
||||
impl Server {
|
||||
/// Rescan the workspace and republish every open buffer against the new
|
||||
/// index. Every caller changed what the index should contain — a save, a
|
||||
/// new `lucisv.exclude`/`lucisv.filelist`, a watched file changing on disk,
|
||||
/// or a file the client renamed or deleted.
|
||||
pub(super) fn reindex(&mut self) {
|
||||
// A rescan asked for by a message this scan answered is *this* scan's
|
||||
// successor, not a scan inside it. See `scan_until_settled`.
|
||||
if self.scanning {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
let warnings = self.scan_until_settled(true);
|
||||
if self.stopped {
|
||||
return;
|
||||
}
|
||||
// A rescan can change any module's instantiation count, so every lens
|
||||
// a client is holding may now read wrong. Sent after the bar comes
|
||||
// down, for the same reason the bar comes down before the republishes:
|
||||
// the bar names the scan, and everything after it is work done on the
|
||||
// scan's result.
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
// Every open buffer's diagnostics are computed against the index, so a
|
||||
// pulling client's cached answers are all stale from here.
|
||||
self.generation += 1;
|
||||
self.report_scope(warnings);
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Server::reindex`] for a trigger that named exactly **one** file, when
|
||||
/// that file is one the index already holds. Reports whether it ran; a
|
||||
/// `false` means the caller owes a whole rebuild.
|
||||
///
|
||||
/// Everything a rebuild does *after* the scan happens here too, for the
|
||||
/// same reasons: the code-lens refresh (the file that moved may have
|
||||
/// changed an instantiation count in any buffer), the diagnostics
|
||||
/// generation bump (every open buffer's diagnostics are computed against
|
||||
/// the index), and a republish of every open buffer. The republish stays
|
||||
/// wholesale rather than narrowing to the buffers that could have moved:
|
||||
/// a lint reads the index, so any buffer's diagnostics may have changed,
|
||||
/// and narrowing it correctly needs a dependency graph this server does not
|
||||
/// have. Worth doing later; wrong to guess at now.
|
||||
///
|
||||
/// Three things a whole rebuild does that this deliberately does not:
|
||||
///
|
||||
/// * **no progress bar.** The bar exists because a whole scan takes
|
||||
/// perceptible seconds on a large workspace; one file is one parse, and a
|
||||
/// bar that appears and vanishes inside a frame is noise, not progress.
|
||||
/// * **no per-file log line.** Same reason, and the log's purpose — "which
|
||||
/// files is this scan reading?" — is a question about a scan.
|
||||
/// * **no scope warnings.** They come from *resolving* the scope, and the
|
||||
/// scope was not re-resolved: nothing about which files exist changed, so
|
||||
/// repeating a filelist's complaints would be repeating stale news.
|
||||
pub(super) fn reindex_one(&mut self, path: &Path) -> bool {
|
||||
// Mid-scan the cheap path is not available and is not needed: the scan
|
||||
// holds the text this file had when it started and will index *that*,
|
||||
// so patching the half-built index here would be overwritten by older
|
||||
// bytes a moment later. One more scan when this one ends is the whole
|
||||
// answer, and it is the same flag every other mid-scan trigger sets.
|
||||
// `true` because the caller's fallback — a whole rebuild, right now —
|
||||
// is exactly what must not happen.
|
||||
if self.scanning {
|
||||
self.rescan_wanted = true;
|
||||
return true;
|
||||
}
|
||||
let started = self.timer();
|
||||
if !self.workspace.update_one(path) {
|
||||
// No line: nothing was reindexed, and the caller is about to
|
||||
// rebuild the whole index — which times itself.
|
||||
return false;
|
||||
}
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
self.generation += 1;
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
|
||||
true
|
||||
}
|
||||
|
||||
/// [`Server::reindex`] for a `didOpen` that only ever **added** folders to
|
||||
/// the scope: index those folders and fold them in, leaving every file
|
||||
/// already indexed exactly as it is.
|
||||
///
|
||||
/// Everything after the scan is what a whole rescan does, for the same
|
||||
/// reasons — the widen changes which names exist, so lenses, the
|
||||
/// diagnostics generation and every open buffer's publish all move with it.
|
||||
///
|
||||
/// **Mid-scan this defers to one whole rescan rather than widening.** A
|
||||
/// scan already running holds a work list taken from the *old* scope, and
|
||||
/// folding a widen into it would mean two answers to "which files exist"
|
||||
/// inside one scan; the follow-up scan the flag asks for reads the
|
||||
/// persistent store for everything the running scan already parsed, so it
|
||||
/// is the cheap kind. This is the same flag every other mid-scan trigger
|
||||
/// sets, and it is what keeps the coalescing rule one rule
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
pub(super) fn reindex_widened(&mut self, added: Vec<std::path::PathBuf>) {
|
||||
if self.scanning {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
let started = self.timer();
|
||||
if started.is_some() {
|
||||
// The folders by name: which folder a jump widened into is the one
|
||||
// thing the file log below it does not say in one line.
|
||||
let paths: Vec<String> = added.iter().map(|p| p.display().to_string()).collect();
|
||||
let folders = added.len();
|
||||
self.timing(format!(
|
||||
"widen started: {folders} folder{} added: {}",
|
||||
plural(folders),
|
||||
paths.join(", ")
|
||||
));
|
||||
}
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan =
|
||||
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
|
||||
let total = scan.total();
|
||||
// No drain between the files: a widen is a rescan a message asked for,
|
||||
// and `must_wait` would hold every request queued behind it anyway. It
|
||||
// is also the point of the round that there is no longer a wait worth
|
||||
// interleaving — a widen indexes one folder, not the whole scope.
|
||||
loop {
|
||||
let step = |workspace: &mut Workspace, watch: &mut dyn FnMut(IndexEvent)| {
|
||||
workspace.scan_step(&mut scan, watch)
|
||||
};
|
||||
if !self.watching(bar.as_ref(), step) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (skipped, cached) = (scan.skipped(), scan.cached());
|
||||
let warnings = self.workspace.finish_scan(scan);
|
||||
self.end_indexing(bar, skipped, cached);
|
||||
self.timed(started, |took| {
|
||||
format!(
|
||||
"widen finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
|
||||
plural(total)
|
||||
)
|
||||
});
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
self.generation += 1;
|
||||
self.report_scope(warnings);
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rescan, but only when the paths a file-operation notification named are
|
||||
/// paths the index reads. The same test a watched-file notification gets.
|
||||
pub(super) fn reindex_for(&mut self, paths: Vec<std::path::PathBuf>) {
|
||||
let filelist = self.workspace.filelist_path();
|
||||
if file_ops::touches_scope(&paths, filelist.as_deref()) {
|
||||
self.reindex();
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan, and go on scanning while the messages answered along the way keep
|
||||
/// asking for one. Reports the last scan's scope warnings.
|
||||
///
|
||||
/// **The whole of the coalescing rule, and it is a loop rather than a
|
||||
/// recursion on purpose.** A `didSave`, a widened scope, a changed
|
||||
/// setting or a watched-file burst answered mid-scan sets
|
||||
/// `rescan_wanted`; any number of them is one more scan. Finishing the
|
||||
/// current scan and then running another was chosen over aborting and
|
||||
/// restarting it because it needs no way to unwind a half-published index
|
||||
/// and cannot loop for ever on its own — the follow-up scan reads the
|
||||
/// persistent cache for every file the abandoned one already parsed, so
|
||||
/// it is the cheap kind. Each scan gets its own progress token, which is
|
||||
/// what a client showing a bar expects of two scans.
|
||||
pub(super) fn scan_until_settled(&mut self, mut asked_for: bool) -> Vec<String> {
|
||||
self.scanning = true;
|
||||
let warnings = loop {
|
||||
self.answering_a_rescan = asked_for;
|
||||
let warnings = self.scan_once();
|
||||
if !std::mem::take(&mut self.rescan_wanted) || self.stopped {
|
||||
break warnings;
|
||||
}
|
||||
// Every scan after the first one here is one a message asked for,
|
||||
// whatever the first one was.
|
||||
asked_for = true;
|
||||
};
|
||||
self.answering_a_rescan = false;
|
||||
self.scanning = false;
|
||||
warnings
|
||||
}
|
||||
|
||||
/// One whole scan: the bar up, every file indexed with the client's
|
||||
/// messages answered between two of them, the bar down.
|
||||
///
|
||||
/// A scan a `shutdown` interrupted stops where it stands and reports no
|
||||
/// warnings: nothing after this may speak to a client that has gone. The
|
||||
/// records of the files it did index are already in the persistent store —
|
||||
/// they are written through per file — so the next session resumes from
|
||||
/// them, exactly as it does after any other half-done scan.
|
||||
fn scan_once(&mut self) -> Vec<String> {
|
||||
// Before the bar and before the work list is built: resolving the
|
||||
// scope and walking it is part of what a scan costs, and a number that
|
||||
// left it out would be the wrong answer to "why was that slow?".
|
||||
let started = self.timer();
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
|
||||
let interleave = scan.total() > INTERLEAVE_ABOVE;
|
||||
let total = scan.total();
|
||||
if started.is_some() {
|
||||
// Whether it interleaves is said here because it is decided here,
|
||||
// and because it is the answer to "why did my hover wait?" — a
|
||||
// scan that does not interleave answers nothing until it is done.
|
||||
let interleaving = if interleave { ", interleaved" } else { "" };
|
||||
self.timing(format!("scan started: {total} file{}{interleaving}", plural(total)));
|
||||
}
|
||||
while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch))
|
||||
{
|
||||
if interleave && self.answer_what_is_waiting(&mut scan) {
|
||||
// Nothing after this may speak to a client that has gone, the
|
||||
// timing line included.
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
let (skipped, cached) = (scan.skipped(), scan.cached());
|
||||
let warnings = self.workspace.finish_scan(scan);
|
||||
self.end_indexing(bar, skipped, cached);
|
||||
self.timed(started, |took| {
|
||||
format!(
|
||||
"scan finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
|
||||
plural(total)
|
||||
)
|
||||
});
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Do one piece of a scan with the progress bar and the per-file log
|
||||
/// watching it.
|
||||
///
|
||||
/// The fields are split apart because the watcher writes to the connection
|
||||
/// while the workspace is borrowed mutably for the work it is watching —
|
||||
/// the split `Server::new` used to make inline, made once here because a
|
||||
/// scan is now several calls instead of one. A fresh `IndexWatch` per call
|
||||
/// costs nothing and re-reads `lucisv.index.logFiles`, so a settings change
|
||||
/// answered mid-scan is honoured by the very next file's log line.
|
||||
fn watching<T>(
|
||||
&mut self,
|
||||
bar: Option<&ProgressToken>,
|
||||
step: impl FnOnce(&mut Workspace, &mut dyn FnMut(IndexEvent)) -> T,
|
||||
) -> T {
|
||||
let Server { connection, workspace, .. } = self;
|
||||
let mut watch = IndexWatch::new(connection, bar, workspace.client_settings());
|
||||
step(workspace, &mut |event| watch.see(event))
|
||||
}
|
||||
|
||||
/// Answer everything the client has already sent, against the index as far
|
||||
/// as this scan has built it. Reports whether the client shut us down.
|
||||
///
|
||||
/// **This is the round's whole point, and its whole cost.** Polling costs
|
||||
/// one `try_recv` per file and finds nothing in a scan nobody is waiting
|
||||
/// on, so a quiet scan pays nothing at all; a scan somebody *is* waiting
|
||||
/// on pays one merge per burst to make the records it has taken since the
|
||||
/// last one answerable ([`Workspace::publish_scan`]). The messages then go
|
||||
/// through the same `process_batch` the loop uses, so a `didChange` queued
|
||||
/// ahead of a hover is applied before that hover is answered and a cancel
|
||||
/// beside its request still answers it `RequestCancelled` — the order
|
||||
/// contract is the loop's, unchanged, because it is the loop's code.
|
||||
///
|
||||
/// An error here is a client that has gone: there is nobody to report it
|
||||
/// to and no reason to go on scanning, so it stops the scan the same way a
|
||||
/// `shutdown` does.
|
||||
fn answer_what_is_waiting(&mut self, scan: &mut Scan) -> bool {
|
||||
let mut batch = Vec::new();
|
||||
while let Ok(message) = self.queue.try_recv() {
|
||||
batch.push(message);
|
||||
}
|
||||
if batch.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let opened = opened_in(&batch);
|
||||
self.workspace.publish_scan(scan);
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
// The file the user has just opened is the one they are looking at, so
|
||||
// it is indexed next rather than when the alphabet reaches it — the
|
||||
// open-first rule, for a file opened after the work list was taken.
|
||||
for path in opened {
|
||||
scan.index_next(&path);
|
||||
}
|
||||
self.stopped
|
||||
}
|
||||
|
||||
/// Publish a new completed hierarchy revision after any index mutation.
|
||||
pub(super) fn hierarchy_index_changed(&mut self) {
|
||||
self.hierarchy_revision = self.hierarchy_revision.saturating_add(1);
|
||||
if !self.abilities.hierarchy_view {
|
||||
return;
|
||||
}
|
||||
notify_on(
|
||||
&self.connection,
|
||||
design_hierarchy::CHANGED_METHOD,
|
||||
serde_json::json!({ "revision": self.hierarchy_revision }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! The large-file fast path: what a buffer over `lucisv.largeFile.threshold`
|
||||
//! answers *instead of* the dispatch.
|
||||
//!
|
||||
//! Runs ahead of every request and costs one boolean when no large buffer is
|
||||
//! open. Its own file because it is a second, smaller table over the same
|
||||
//! method names as `dispatch.rs`, with a different answer for each — and
|
||||
//! because it is the one place the large-file feature lane touches on the
|
||||
//! server side (`docs/features/large-file-mode/README.md`).
|
||||
|
||||
use lsp_types::request::{
|
||||
CodeActionRequest, DocumentLinkRequest, Formatting, GotoDefinition, HoverRequest,
|
||||
OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References, Rename, Request as _,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, WillSaveWaitUntil,
|
||||
};
|
||||
use lsp_types::{GotoDefinitionResponse, Location, Position, Uri};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::dispatch::{document_uri, to_value, Failure, TOO_LARGE};
|
||||
use super::Server;
|
||||
use crate::{format, large};
|
||||
|
||||
impl Server {
|
||||
/// What a buffer over `lucisv.largeFile.threshold` answers `method`, or
|
||||
/// `None` when the normal dispatch may run.
|
||||
///
|
||||
/// Four groups, and the reason each is what it is:
|
||||
///
|
||||
/// * **`semanticTokens/full` and `/full/delta` are declined with an
|
||||
/// error.** Answering them with an empty set would be worse than not
|
||||
/// answering: VS Code marks a model whose *document* provider returned
|
||||
/// anything at all as having complete semantic tokens, and its viewport
|
||||
/// contribution then never asks for a range again — the file would lose
|
||||
/// all colour. An error leaves the model incomplete, so the range
|
||||
/// provider keeps painting. The evidence for both halves is in
|
||||
/// `docs/features/large-file-mode/README.md`.
|
||||
/// * **The formatting requests refuse out loud.** A user pressed a key and
|
||||
/// is owed a reason; silence there reads as a broken formatter. The
|
||||
/// exceptions are the two the user did not press: `onTypeFormatting`
|
||||
/// (a keystroke, and it never speaks) and `willSaveWaitUntil` (every
|
||||
/// save), which decline the way they already decline.
|
||||
/// * **`definition` and `references` scan the buffer.** The only two
|
||||
/// answers a text scan can honestly give, and the whole reason the
|
||||
/// buffer's text is still in memory.
|
||||
/// * **Everything else answers nothing, fast** — and most of it is not
|
||||
/// listed here at all: a fast-path `Document` holds the analysis of an
|
||||
/// *empty* file, so those handlers already answer empty without knowing
|
||||
/// this mode exists. Named below are only the ones that would otherwise
|
||||
/// read the text itself.
|
||||
pub(super) fn large_file_answer(
|
||||
&mut self,
|
||||
method: &str,
|
||||
params: &Value,
|
||||
) -> Option<Result<Value, Failure>> {
|
||||
// One boolean before anything is parsed: this runs ahead of every
|
||||
// request, and a session with no large buffer in it — which is every
|
||||
// session but one — must not pay a URI parse for the privilege.
|
||||
if !self.workspace.has_large_documents() {
|
||||
return None;
|
||||
}
|
||||
let uri = document_uri(params)?;
|
||||
if !self.workspace.document(&uri).is_some_and(|doc| doc.large) {
|
||||
return None;
|
||||
}
|
||||
let answer = match method {
|
||||
SemanticTokensFullRequest::METHOD | SemanticTokensFullDeltaRequest::METHOD => {
|
||||
Err(self.tokens_declined())
|
||||
}
|
||||
Formatting::METHOD | RangeFormatting::METHOD | format::RANGES_FORMATTING => {
|
||||
self.edits(Err(TOO_LARGE.to_string()))
|
||||
}
|
||||
// Silent, both of them: one fires on every keystroke and one on
|
||||
// every save.
|
||||
OnTypeFormatting::METHOD => to_value(Vec::<lsp_types::TextEdit>::new()),
|
||||
WillSaveWaitUntil::METHOD => Ok(Value::Null),
|
||||
// A rename would rewrite every *other* file and leave this one
|
||||
// untouched — the buffer is not in the index and not in
|
||||
// `sources()` — so it is refused rather than half-applied.
|
||||
// `prepareRename` declines quietly, so the box never opens.
|
||||
PrepareRenameRequest::METHOD => Ok(Value::Null),
|
||||
Rename::METHOD => Err(Failure::Request(TOO_LARGE.to_string())),
|
||||
// These three read the buffer's text rather than its analysis: the
|
||||
// include scan, the `` `include`` line lookup a hover does, and
|
||||
// the fix application a code action tries.
|
||||
HoverRequest::METHOD => Ok(Value::Null),
|
||||
DocumentLinkRequest::METHOD => to_value(Vec::<lsp_types::DocumentLink>::new()),
|
||||
CodeActionRequest::METHOD => to_value(Vec::<lsp_types::CodeActionOrCommand>::new()),
|
||||
GotoDefinition::METHOD => self.large_definition(&uri, params),
|
||||
References::METHOD => self.large_references(&uri, params),
|
||||
_ => return None,
|
||||
};
|
||||
Some(answer)
|
||||
}
|
||||
|
||||
/// The error `semanticTokens/full` is declined with.
|
||||
///
|
||||
/// `ServerCancelled` for a client that advertised `serverCancelSupport`,
|
||||
/// which is the code the spec reserves for exactly this and the code
|
||||
/// `vscode-languageclient` turns into a `CancellationError`;
|
||||
/// `ContentModified` for one that did not, which the same client turns
|
||||
/// into the same `CancellationError` (semantic tokens are on its
|
||||
/// `retryOnContentModified` list) and which every 3.16 client already
|
||||
/// understands.
|
||||
fn tokens_declined(&self) -> Failure {
|
||||
let code = match self.abilities.token_server_cancel {
|
||||
true => lsp_server::ErrorCode::ServerCancelled,
|
||||
false => lsp_server::ErrorCode::ContentModified,
|
||||
};
|
||||
Failure::Declined(code, TOO_LARGE.to_string())
|
||||
}
|
||||
|
||||
/// `textDocument/definition` on a large buffer: the first occurrence of
|
||||
/// the name under the cursor that a declaring keyword introduces.
|
||||
fn large_definition(&self, uri: &Uri, params: &Value) -> Result<Value, Failure> {
|
||||
let locations = self
|
||||
.large_scan(uri, params, |doc, offset| {
|
||||
large::definition(doc, offset).into_iter().collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
to_value(GotoDefinitionResponse::Array(locations))
|
||||
}
|
||||
|
||||
/// `textDocument/references` on a large buffer: every whole-word
|
||||
/// occurrence of the name under the cursor, capped.
|
||||
fn large_references(&self, uri: &Uri, params: &Value) -> Result<Value, Failure> {
|
||||
let include = params
|
||||
.get("context")
|
||||
.and_then(|context| context.get("includeDeclaration"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(true);
|
||||
let locations = self
|
||||
.large_scan(uri, params, |doc, offset| large::references(doc, offset, include))
|
||||
.unwrap_or_default();
|
||||
to_value(locations)
|
||||
}
|
||||
|
||||
/// Run one of the fast path's scans at the position `params` names, and
|
||||
/// turn its spans into locations in the same file.
|
||||
fn large_scan(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
params: &Value,
|
||||
scan: impl Fn(&crate::state::Document, u32) -> Vec<vlog_parser::TextRange>,
|
||||
) -> Option<Vec<Location>> {
|
||||
let position: Position = serde_json::from_value(params.get("position")?.clone()).ok()?;
|
||||
let doc = self.workspace.document(uri)?;
|
||||
let positions = doc.positions();
|
||||
let offset = positions.offset(position);
|
||||
// Both scans answer in ascending order, so one monotonic cursor
|
||||
// measures each line once — a thousand hits on one netlist line would
|
||||
// otherwise re-measure that line a thousand times over.
|
||||
let mut walker = positions.walker();
|
||||
Some(
|
||||
scan(doc, offset)
|
||||
.into_iter()
|
||||
.map(|span| Location { uri: uri.clone(), range: walker.range(span) })
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
//! The request loop: one burst in, one response per request, on one thread.
|
||||
//!
|
||||
//! `lsp-server` runs two I/O threads of its own and hands this loop framed
|
||||
//! messages over a channel. Everything below is synchronous — Verilog files
|
||||
//! are small, every handler is milliseconds, and a worker pool would buy
|
||||
//! nothing yet. A request that has already started therefore runs to
|
||||
//! completion; the one thing `$/cancelRequest` can do here is answer a request
|
||||
//! still *queued* behind the one being served, which is what the burst drain
|
||||
//! in `run` is for. See `docs/features/lucisv-server/README.md` and
|
||||
//! `docs/features/cancel-request/README.md`.
|
||||
//!
|
||||
//! The server is one directory of modules, each the answer to one question;
|
||||
//! this file holds the `Server` itself — what the client can do, what the
|
||||
//! server owns, and the loop (`run`, `process_batch`, the order contract in
|
||||
//! `must_wait`). The rest, in the order a message meets them:
|
||||
//!
|
||||
//! * `batch` — reading a burst before any of it is served: the forwarder
|
||||
//! thread, the drain, the cancels a burst carries, the `didOpen`s that widen
|
||||
//! the scope;
|
||||
//! * `dispatch` — `answer_request`, the table over request methods, with the
|
||||
//! decoding it needs and the `Failure` it answers in;
|
||||
//! * `large_file` — what a buffer over the large-file threshold answers
|
||||
//! instead of the dispatch;
|
||||
//! * `formatting` — the five formatting entries and how a refusal is said;
|
||||
//! * `semantic_tokens` — the remembered answer a token delta is computed
|
||||
//! against;
|
||||
//! * `diagnostics` — when a buffer is analyzed (the change debounce) and how
|
||||
//! what it says reaches the client, pushed or pulled;
|
||||
//! * `notification` — `handle_notification`, the table over notification
|
||||
//! methods, and the settings applier both settings doors share;
|
||||
//! * `index` — the rescans: whole, one file, widened, and the scan that
|
||||
//! answers messages while it runs;
|
||||
//! * `progress` — the indexing bar and the per-file log a rescan runs under;
|
||||
//! * `client` — what goes to the client other than a response: the requests
|
||||
//! made of it and the answers read back, the messages, the timing lines.
|
||||
//!
|
||||
//! Methods a sibling file calls are `pub(super)`; everything else is private
|
||||
//! to its file. The tests are in `tests/`, one file per feature.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
|
||||
use lsp_server::{Connection, Message, RequestId};
|
||||
use lsp_types::notification::{Cancel, Notification as _};
|
||||
use lsp_types::{SemanticToken, Uri};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Workspace;
|
||||
|
||||
use batch::{burst, cancelled_in, cancelled_response, forward};
|
||||
|
||||
mod batch;
|
||||
mod client;
|
||||
mod diagnostics;
|
||||
mod dispatch;
|
||||
mod formatting;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod notification;
|
||||
mod progress;
|
||||
mod semantic_tokens;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// What the client said it can do, read once at `initialize` because that is
|
||||
/// the only time those capabilities are sent.
|
||||
#[derive(Default)]
|
||||
pub struct ClientAbilities {
|
||||
/// Whether the client can expand a completion item's tabstops.
|
||||
pub snippets: bool,
|
||||
/// Whether the client accepts a `workspace/didChangeWatchedFiles`
|
||||
/// registration. There is no static form of that capability, so a client
|
||||
/// that says nothing keeps the save-only staleness model.
|
||||
pub file_watching: bool,
|
||||
/// Whether the client applies a `workspace/applyEdit` request. A client
|
||||
/// that cannot gets a command's edit back as the request result instead,
|
||||
/// which is what every client got before this was read.
|
||||
pub apply_edit: bool,
|
||||
/// Whether the client *pulls* diagnostics (LSP 3.17). One client is never
|
||||
/// served both models: a pulling client is pushed nothing at all.
|
||||
pub pull_diagnostics: bool,
|
||||
/// Whether the client renders server-initiated work-done progress. The
|
||||
/// spec forbids creating any without it, so a client that said nothing
|
||||
/// sees the workspace rescan exactly as it did before — silently.
|
||||
pub work_done_progress: bool,
|
||||
/// Whether the client accepts a `workspace/codeLens/refresh`. A client
|
||||
/// that said nothing is never asked, and keeps the instantiation counts it
|
||||
/// last requested until it asks again for its own reasons.
|
||||
pub code_lens_refresh: bool,
|
||||
/// Whether the client opens a document the server asks it to
|
||||
/// (`window/showDocument`). This is what lets the instantiation lens
|
||||
/// navigate; a client without it still gets the sites back as the
|
||||
/// command's result.
|
||||
pub show_document: bool,
|
||||
/// Whether the client answers `workspace/configuration` — the pull model
|
||||
/// for settings. A client that said nothing is only ever *pushed*
|
||||
/// settings, which is what every client got before this was read.
|
||||
pub configuration: bool,
|
||||
/// Whether the client understands a server-cancelled semantic-tokens
|
||||
/// request (`textDocument.semanticTokens.serverCancelSupport`). Decides
|
||||
/// which error code declines `semanticTokens/full` on a large buffer —
|
||||
/// see `docs/features/large-file-mode/README.md`.
|
||||
pub token_server_cancel: bool,
|
||||
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
|
||||
/// a notification whenever the installed workspace index changes.
|
||||
pub hierarchy_view: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
pub struct Server {
|
||||
connection: Connection,
|
||||
workspace: Workspace,
|
||||
/// Documents whose `lucisv.toml` problem has already been reported. Cleared
|
||||
/// for a document whenever its text changes, so the warning is said once
|
||||
/// per file change rather than once per format-on-save.
|
||||
config_warnings: HashSet<Uri>,
|
||||
abilities: ClientAbilities,
|
||||
/// The id of the file-watcher registration in force, if any. Kept so a
|
||||
/// changed `lucisv.filelist` can replace it: the watched filelist path is
|
||||
/// part of the registration, so a new path needs a new registration.
|
||||
watchers: Option<String>,
|
||||
/// Numbers the file-watcher registrations, so a replacement can name the
|
||||
/// one it supersedes.
|
||||
registrations: u32,
|
||||
/// Numbers the requests made *of* the client. A repeated id is a protocol
|
||||
/// error, so this only ever counts up.
|
||||
request_ids: u32,
|
||||
/// The requests the server has made of the client whose answers it will
|
||||
/// act on, by the id they were sent with. Everything *not* in here is a
|
||||
/// request whose answer is ignorable, which is what makes `response`'s
|
||||
/// fall-through correct rather than lossy.
|
||||
pending: HashMap<RequestId, Pending>,
|
||||
/// Counts everything that can change what a pull request would answer: a
|
||||
/// buffer's text, and the workspace index. It is the whole of a
|
||||
/// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`.
|
||||
generation: u64,
|
||||
/// Revision of the completed index exposed to the custom hierarchy view.
|
||||
hierarchy_revision: u64,
|
||||
/// The last full-or-delta semantic-token answer for each open buffer —
|
||||
/// what a delta is computed *against*. Dropped on `didClose`, so this
|
||||
/// only ever holds what the editor is showing. See
|
||||
/// `docs/features/semantic-tokens-delta/README.md`.
|
||||
tokens: HashMap<Uri, TokenAnswer>,
|
||||
/// Numbers the semantic-token answers. Per answer, not per generation: a
|
||||
/// client's `previousResultId` has to name the exact data it holds, and
|
||||
/// two buffers' answers are never comparable.
|
||||
token_results: u64,
|
||||
/// Numbers the progress tokens the index rescans run under. One rescan is
|
||||
/// one token, and a token is never reused: a client keys the bar it is
|
||||
/// showing off it.
|
||||
indexings: u32,
|
||||
/// Buffers that are text-current but analysis-stale: the newest applied
|
||||
/// text for each, in first-dirtied order. A `didChange` lands here instead
|
||||
/// of running a reparse, and every one of them is flushed — analyzed,
|
||||
/// republished — by the first thing that needs the analysis: the next
|
||||
/// request, the next non-`didChange` notification, or the quiet-period
|
||||
/// timer in `run`. See `docs/features/change-debounce/README.md`.
|
||||
dirty: Vec<(Uri, String)>,
|
||||
/// Everything the client has sent, forwarded off the transport's
|
||||
/// rendezvous channel by [`forward`]. Held here rather than made in `run`
|
||||
/// because a **scan** drains it too: the loop must not go quiet for the
|
||||
/// length of one (`docs/features/scan-interleave/README.md`).
|
||||
queue: std::sync::mpsc::Receiver<Message>,
|
||||
/// Whether a scan is running. A message answered mid-scan can ask for
|
||||
/// another one, and this is what turns that into the flag below rather
|
||||
/// than a scan inside a scan.
|
||||
scanning: bool,
|
||||
/// A rescan asked for while a scan was running. Coalesced: any number of
|
||||
/// requests is one more scan when this one ends, whatever asked for them.
|
||||
rescan_wanted: bool,
|
||||
/// Whether the scan now running is one a *message* asked for. The startup
|
||||
/// scan is not — nothing was queued ahead of it — and that is the whole
|
||||
/// difference between a request answered mid-scan and one that waits. See
|
||||
/// [`Server::must_wait`].
|
||||
answering_a_rescan: bool,
|
||||
/// Whether the client has shut the server down. Set by a `shutdown`
|
||||
/// answered mid-scan, which stops the scan where it stands and keeps `run`
|
||||
/// from taking another message.
|
||||
stopped: bool,
|
||||
/// Messages a mid-scan drain would have answered out of order, kept in
|
||||
/// arrival order until the rescan they are queued behind has run. See
|
||||
/// [`Server::must_wait`] — this is the order contract, not a queue of its
|
||||
/// own.
|
||||
held: Vec<Message>,
|
||||
/// `--verbose`: whether every operation says how long it took, in the
|
||||
/// client's log channel. Off is the shipped state and the whole of what it
|
||||
/// costs is the branch that reads this field — see
|
||||
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
|
||||
verbose: bool,
|
||||
}
|
||||
|
||||
/// How long a burst of `didChange` notifications may sit unanalyzed once the
|
||||
/// typing has stopped, before the quiet-period timer flushes them anyway. The
|
||||
/// coalescing this buys — one reparse per burst instead of one per keystroke —
|
||||
/// is worth nothing if diagnostics never arrive until the next request does.
|
||||
const CHANGE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(150);
|
||||
|
||||
/// How many files a scan must have to be worth answering messages in the
|
||||
/// middle of.
|
||||
///
|
||||
/// **The whole trade of `docs/features/scan-interleave/README.md`, in one
|
||||
/// number.** A mid-scan answer reads the index as far as the scan has built
|
||||
/// it, so it can be *less* than the answer the same request would get a
|
||||
/// moment later — and that is only ever worth it when "a moment later" is a
|
||||
/// wait a person can feel. Below this, a scan is over in a few milliseconds
|
||||
/// (the 860-file corpus is 340 ms, so sixty-four files is under thirty), and
|
||||
/// trading a complete answer for those milliseconds would be a bad bargain;
|
||||
/// above it, the measured wait is hundreds of milliseconds and the trade is
|
||||
/// the point of the round.
|
||||
///
|
||||
/// A count rather than a clock deliberately: a rule about elapsed time makes
|
||||
/// what a server answers depend on how loaded the machine was, which is
|
||||
/// exactly the property a test suite — and a bug report — cannot work with.
|
||||
/// The known limit of counting is a workspace of a *few very large* files,
|
||||
/// which is under this bar and can still take a second; that is written down
|
||||
/// as a deliberate not-done rather than papered over with a second rule.
|
||||
const INTERLEAVE_ABOVE: usize = 64;
|
||||
|
||||
/// A request the server sent the client and still owes itself an answer to.
|
||||
///
|
||||
/// One map rather than one per kind: `response` then has a single lookup and
|
||||
/// a single `match`, and adding a third kind is a variant the compiler makes
|
||||
/// you handle rather than a map somebody forgets to consult.
|
||||
enum Pending {
|
||||
/// A `workspace/applyEdit`, remembering the command that asked for it so
|
||||
/// a refusal can be named to the user.
|
||||
ApplyEdit(String),
|
||||
/// A `workspace/configuration` asking for the `lucisv` section.
|
||||
Configuration,
|
||||
}
|
||||
|
||||
/// One semantic-token answer, kept so the next delta request can be answered
|
||||
/// against it.
|
||||
struct TokenAnswer {
|
||||
result_id: String,
|
||||
data: Vec<SemanticToken>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// The server, with its first index built.
|
||||
///
|
||||
/// The startup scan runs at the **default** settings — including the
|
||||
/// folder scope — because neither settings door can deliver anything
|
||||
/// before `initialized`; a client whose `lucisv.index.scope` differs pays
|
||||
/// one extra rescan when its settings land, exactly as `lucisv.exclude`
|
||||
/// has always cost one.
|
||||
pub fn new(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
) -> Server {
|
||||
Server::started(
|
||||
connection,
|
||||
roots,
|
||||
abilities,
|
||||
ClientSettings::default(),
|
||||
storage,
|
||||
verbose,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Server::new`] with a client's settings already in hand — the seam the
|
||||
/// tests start a session from. Only a test has any settings this early:
|
||||
/// one whose subject is not the scope says so here rather than driving a
|
||||
/// `didChangeConfiguration` and then reasoning about the extra rescan it
|
||||
/// buys.
|
||||
///
|
||||
/// `queued` is what the client had already sent when the server was built
|
||||
/// — the opening burst, put straight onto the queue the startup scan
|
||||
/// drains. Empty for [`Server::new`]; a test fills it because racing the
|
||||
/// forwarder thread for it would make the test a coin toss rather than a
|
||||
/// check.
|
||||
fn started(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
client: ClientSettings,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
queued: Vec<Message>,
|
||||
) -> Server {
|
||||
// Started before the first scan, not in `run`: the scan below answers
|
||||
// whatever the client has already sent, and it can only do that off a
|
||||
// queue that is already being filled.
|
||||
let (forwarded, queue) = forward(&connection);
|
||||
for message in queued {
|
||||
let _ = forwarded.send(message);
|
||||
}
|
||||
let mut server = Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
registrations: 0,
|
||||
request_ids: 0,
|
||||
pending: HashMap::new(),
|
||||
generation: 0,
|
||||
hierarchy_revision: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
queue,
|
||||
scanning: false,
|
||||
rescan_wanted: false,
|
||||
answering_a_rescan: false,
|
||||
stopped: false,
|
||||
held: Vec::new(),
|
||||
verbose,
|
||||
};
|
||||
// Nothing has been built yet, so there is no rebuild to owe: the
|
||||
// `true` this returns for a non-default `client` is the rebuild that
|
||||
// is about to happen anyway.
|
||||
let _ = server.workspace.set_client_settings(client);
|
||||
// Before the first build, because it is one rung of the ladder that
|
||||
// decides where that build reads its cache from
|
||||
// (`docs/features/index-persistence/README.md`).
|
||||
server.workspace.set_storage_path(storage);
|
||||
// The earliest legal moment for anything server-initiated: `main`
|
||||
// builds this only after `initialize_finish`, which returns once the
|
||||
// client's `initialized` notification has arrived — and consumes it,
|
||||
// so the loop below never sees one to hang these off instead. The
|
||||
// first index build is the slowest one of the session, so it gets the
|
||||
// same bar every later rescan gets.
|
||||
//
|
||||
// And it answers messages while it runs, which is what stops the first
|
||||
// request of a session waiting out the whole scan
|
||||
// (`docs/features/scan-interleave/README.md`). Everything below it is
|
||||
// therefore reached with the client's opening burst already handled —
|
||||
// and skipped altogether if that burst shut the server down.
|
||||
server.workspace.adopt_roots(roots);
|
||||
let warnings = server.scan_until_settled(false);
|
||||
if server.stopped {
|
||||
return server;
|
||||
}
|
||||
server.hierarchy_index_changed();
|
||||
// A buffer can now be *opened* during the startup scan, and what was
|
||||
// published for it then was computed against a half-built index. This
|
||||
// is the same debt a rescan pays at the end of `reindex`, owed here
|
||||
// for the first time because before this round no buffer could exist
|
||||
// at this point. Nothing at all is sent when nothing is open, which is
|
||||
// every session whose client did not get a `didOpen` in edgeways.
|
||||
if !server.workspace.open_uris().is_empty() {
|
||||
server.refresh_code_lenses();
|
||||
server.generation += 1;
|
||||
for uri in server.workspace.open_uris() {
|
||||
server.publish(&uri);
|
||||
}
|
||||
}
|
||||
server.report_scope(warnings);
|
||||
server.register_watchers();
|
||||
// The pull half of the settings model. Asked here because this is the
|
||||
// same moment the watchers are registered — the earliest legal one —
|
||||
// and answered later, in the loop: the settings therefore arrive
|
||||
// *after* the first index build, exactly as a pushed
|
||||
// `didChangeConfiguration` always has (it cannot arrive before
|
||||
// `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist`
|
||||
// costs one extra rescan when it lands; nothing is stale in between,
|
||||
// it is simply the default scope until the client answers.
|
||||
server.request_configuration();
|
||||
server
|
||||
}
|
||||
|
||||
/// Receive until the client shuts us down or the channel closes.
|
||||
///
|
||||
/// One blocking receive, then everything already queued behind it, then
|
||||
/// that whole burst in arrival order. The drain is what makes
|
||||
/// `$/cancelRequest` mean anything: while a handler runs, the client's
|
||||
/// later requests and its cancels for them pile up together, and a cancel
|
||||
/// found next to its request answers that request for free.
|
||||
///
|
||||
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
|
||||
/// flushed here rather than left waiting for a request that may never
|
||||
/// come — diagnostics are the one answer the client never asks for.
|
||||
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
loop {
|
||||
// A `shutdown` the startup scan answered has already been through
|
||||
// `handle_shutdown`; there is nothing left to receive and nothing
|
||||
// left to answer.
|
||||
if self.stopped {
|
||||
return Ok(());
|
||||
}
|
||||
// Whatever a scan set aside is answered before anything newer is
|
||||
// taken — the rescan those messages were queued behind has run,
|
||||
// and they are older than everything still on the queue. Handling
|
||||
// them here rather than at the end of the scan is what keeps this
|
||||
// a loop instead of a scan inside a scan inside a scan.
|
||||
if !self.held.is_empty() {
|
||||
let batch = std::mem::take(&mut self.held);
|
||||
if self.process_batch(batch)? {
|
||||
return Ok(());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let message = if self.dirty.is_empty() {
|
||||
match self.queue.recv() {
|
||||
Ok(message) => message,
|
||||
Err(_) => return Ok(()),
|
||||
}
|
||||
} else {
|
||||
match self.queue.recv_timeout(CHANGE_DEBOUNCE) {
|
||||
Ok(message) => message,
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
self.flush_dirty();
|
||||
continue;
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => return Ok(()),
|
||||
}
|
||||
};
|
||||
let batch = burst(&self.queue, message);
|
||||
if self.process_batch(batch)? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle one burst in arrival order, reporting whether the client shut us
|
||||
/// down.
|
||||
///
|
||||
/// Order is the whole contract: a `didChange` queued ahead of a completion
|
||||
/// is applied before that completion is answered, exactly as it would be
|
||||
/// one message at a time. The only thing the burst adds is that a request
|
||||
/// this burst also carries a cancel for is answered `RequestCancelled`
|
||||
/// instead of computed — except `shutdown`, which is honoured before the
|
||||
/// cancelled set is ever consulted, so no cancel can talk the server out
|
||||
/// of shutting down.
|
||||
fn process_batch(&mut self, batch: Vec<Message>) -> Result<bool, Box<dyn Error + Sync + Send>> {
|
||||
let mut cancelled = cancelled_in(&batch);
|
||||
// Where this burst's own held messages have to be spliced in. A scan
|
||||
// this burst starts can hold messages of its *own* — ones that arrived
|
||||
// while it ran, and therefore after everything still in this burst —
|
||||
// so what is held from here goes in front of those and behind whatever
|
||||
// was already waiting when the burst began.
|
||||
let already_waiting = self.held.len();
|
||||
// The `$/cancelRequest`s this burst has already carried, kept only
|
||||
// long enough to put them back if a request behind them has to wait.
|
||||
let mut consumed_cancels: Vec<Message> = Vec::new();
|
||||
let mut messages = batch.into_iter();
|
||||
while let Some(message) = messages.next() {
|
||||
// A request that must wait takes everything behind it with it, or
|
||||
// the burst's arrival order would not survive the wait —
|
||||
// `shutdown` included, because a request sent before a shutdown
|
||||
// is a request the client is still owed an answer to.
|
||||
if self.must_wait() && matches!(message, Message::Request(_)) {
|
||||
self.say_held(&message);
|
||||
// The cancels this burst carried were consumed on the way
|
||||
// here, and `cancelled_in` runs again over the held batch — so
|
||||
// they go back in front of what they cancel rather than being
|
||||
// lost. A cancel naming nothing in the held batch is dropped
|
||||
// there exactly as it was dropped here.
|
||||
let mut rest: Vec<Message> = std::mem::take(&mut consumed_cancels);
|
||||
rest.push(message);
|
||||
rest.extend(messages);
|
||||
rest.extend(self.held.split_off(already_waiting));
|
||||
self.held.extend(rest);
|
||||
return Ok(false);
|
||||
}
|
||||
match message {
|
||||
Message::Request(request) => {
|
||||
if self.connection.handle_shutdown(&request)? {
|
||||
return Ok(true);
|
||||
}
|
||||
// Removed as it is used: a second cancel for the same id
|
||||
// then finds nothing, and the set cannot outlive the burst.
|
||||
let response = if cancelled.remove(&request.id) {
|
||||
cancelled_response(request.id)
|
||||
} else {
|
||||
self.request(request)
|
||||
};
|
||||
self.connection.sender.send(Message::Response(response))?;
|
||||
}
|
||||
// The cancels themselves are consumed here — `notification`
|
||||
// has nothing to do with one, and everything it could do has
|
||||
// already been done above. Kept only so that a request behind
|
||||
// one that has to wait takes its cancel with it.
|
||||
Message::Notification(notification) if notification.method == Cancel::METHOD => {
|
||||
consumed_cancels.push(Message::Notification(notification));
|
||||
}
|
||||
Message::Notification(notification) => self.notification(notification),
|
||||
Message::Response(response) => self.response(response),
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Whether a request reaching the dispatch right now must wait instead of
|
||||
/// being answered.
|
||||
///
|
||||
/// **This is the order contract, and it is the one thing interleaving a
|
||||
/// scan with the message loop must not cost.** The loop has always
|
||||
/// promised that everything queued *ahead* of a request is applied before
|
||||
/// that request is answered — a `didChange` before a completion, and
|
||||
/// equally a `didOpen` that widened the scope, a `didSave`, a changed
|
||||
/// setting or an added workspace folder before a go-to-definition. Those
|
||||
/// four ask for a rescan, and "applied" for them means the rescan has
|
||||
/// **run**: one message at a time, the server would have finished it
|
||||
/// before ever taking the request. Three clauses, one rule:
|
||||
///
|
||||
/// * `answering_a_rescan` — this scan is one a message asked for, so
|
||||
/// every request that arrives while it runs arrived *after* that
|
||||
/// message and is owed its effect;
|
||||
/// * `rescan_wanted` — a message in this very burst has just asked for
|
||||
/// one, and the requests behind it in the burst are owed the same;
|
||||
/// * `held` — a request is already waiting, and answering a newer one
|
||||
/// ahead of it would reorder them just as badly.
|
||||
///
|
||||
/// What is left answered mid-scan is exactly what is queued behind
|
||||
/// *nothing*: the opening burst of a session, whose scan is the server's
|
||||
/// own startup and not something a message asked for. That is the case
|
||||
/// the round is about, and it is the one a user feels
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
fn must_wait(&self) -> bool {
|
||||
self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty()
|
||||
}
|
||||
|
||||
/// Whether the installed index covers the whole scope with no indexing
|
||||
/// work outstanding — what the hierarchy snapshot reports as `complete`.
|
||||
///
|
||||
/// **Both clauses, not just `scanning`.** `!self.scanning` alone would be
|
||||
/// answering "is a scan running *this instant*", and a snapshot taken
|
||||
/// between a finished scan and a rescan already asked for would call a
|
||||
/// stale index complete. Today [`Server::must_wait`] makes that
|
||||
/// unreachable — a request arriving with `rescan_wanted` set or anything
|
||||
/// `held` is set aside rather than answered, so a snapshot only ever
|
||||
/// reaches this function when both are already clear, and `rescan_wanted`
|
||||
/// is in any case only ever set while `scanning` is true. Saying it here
|
||||
/// anyway costs nothing and means the honesty of the flag does not depend
|
||||
/// on a scheduling invariant two hundred lines away staying true; a
|
||||
/// hypothetical future exemption from `must_wait` would degrade the flag,
|
||||
/// not break it. Pinned by
|
||||
/// `a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`.
|
||||
fn index_is_complete(&self) -> bool {
|
||||
!self.scanning && !self.must_wait()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! `handle_notification`: the dispatch table over notification methods.
|
||||
//!
|
||||
//! Everything the client tells the server without expecting an answer —
|
||||
//! documents opened, changed, saved and closed; files and folders moved on
|
||||
//! disk; settings pushed — comes through the one `match` here, which stays
|
||||
//! whole for the same reason `answer_request` does. With it are the three
|
||||
//! decoders only it uses and `apply_settings`, the one applier the pushed and
|
||||
//! the pulled settings share so the two doors can never disagree about what a
|
||||
//! setting costs.
|
||||
|
||||
use lsp_server::{ExtractError, Notification};
|
||||
use lsp_types::notification::{
|
||||
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
|
||||
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, DidSaveTextDocument, Notification as _,
|
||||
};
|
||||
use lsp_types::{
|
||||
DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
|
||||
DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams,
|
||||
DidOpenTextDocumentParams, DidSaveTextDocumentParams, RenameFilesParams, Uri, WorkspaceFolder,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use super::batch::{widen_of, Widen};
|
||||
use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{file_ops, settings, sync, watch};
|
||||
|
||||
impl Server {
|
||||
/// Handle one notification, timing it when `--verbose` asked. A
|
||||
/// notification has no response, so there is no ordering question here:
|
||||
/// the line follows the work.
|
||||
pub(super) fn notification(&mut self, notification: Notification) {
|
||||
let Some(started) = self.timer() else { return self.handle_notification(notification) };
|
||||
let method = notification.method.clone();
|
||||
self.handle_notification(notification);
|
||||
self.timing(format!("{method} handled in {}", ms(started)));
|
||||
}
|
||||
|
||||
fn handle_notification(&mut self, notification: Notification) {
|
||||
let method = notification.method.clone();
|
||||
// A closing buffer's pending text is dropped *before* the flush, not
|
||||
// in the `didClose` arm below it: the flush would otherwise analyze
|
||||
// and publish diagnostics for a file the client has stopped looking
|
||||
// at, only for the close handler to clear them again a line later.
|
||||
// Every other dirty buffer still flushes, as it must — closing one
|
||||
// file says nothing about the rest (QA, change-debounce CD-1).
|
||||
if method == DidCloseTextDocument::METHOD {
|
||||
if let Some(uri) = closing_uri(¬ification) {
|
||||
self.dirty.retain(|(pending, _)| *pending != uri);
|
||||
}
|
||||
}
|
||||
// Everything but a `didChange` needs the buffers' analyses current —
|
||||
// a `didSave` rebuilds the index on top of them — so the same flush a
|
||||
// request gets happens here, with the one exception that *is* the
|
||||
// thing being deferred.
|
||||
if method != DidChangeTextDocument::METHOD {
|
||||
self.flush_dirty();
|
||||
}
|
||||
match method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
// Opening a file in a folder the index does not cover
|
||||
// *widens the scope*, so the folders it added are indexed
|
||||
// and folded into the index beside what is already there;
|
||||
// the widen rides the same bar and the same generation bump
|
||||
// every other rescan trigger does. Opening one the scope
|
||||
// already covers changes nothing about which files exist,
|
||||
// and the save path still owns rebuilding.
|
||||
//
|
||||
// Only a *pure add* takes the cheap path, and `widen_of` is
|
||||
// where that is decided: anything else — a scope directory
|
||||
// that left, which nothing does today — falls back to the
|
||||
// whole rescan (`docs/features/index-scope/README.md`).
|
||||
//
|
||||
// This is the rootless rule from before 2026-08-27,
|
||||
// generalized: rung 3 is now the default rung with a root
|
||||
// too, so "did this file widen the scope" is the one test,
|
||||
// and it answers "no" for the filelist and whole-workspace
|
||||
// rungs, which an open buffer cannot widen.
|
||||
let before = self.workspace.scope_dirs();
|
||||
self.set_document(uri.clone(), p.text_document.text);
|
||||
match widen_of(&before, &self.workspace.scope_dirs()) {
|
||||
Widen::Nothing => self.publish(&uri),
|
||||
Widen::Added(dirs) => self.reindex_widened(dirs),
|
||||
Widen::Whole => self.reindex(),
|
||||
}
|
||||
}
|
||||
}
|
||||
DidChangeTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
|
||||
// Incremental sync: the changes are ranges into the buffer
|
||||
// we hold — the newest applied text, which while dirty is
|
||||
// the pending one, not the last analyzed one — applied in
|
||||
// order. A full-sync client's rangeless change still
|
||||
// replaces the whole buffer, so "the last one wins" stays
|
||||
// true for it. A burst of changes is coalesced into one
|
||||
// `set_document` — one reparse, one generation bump — when
|
||||
// the buffer is flushed; see `mark_dirty`.
|
||||
if p.content_changes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let uri = p.text_document.uri;
|
||||
let text = {
|
||||
let base = self
|
||||
.dirty
|
||||
.iter()
|
||||
.find(|(pending, _)| *pending == uri)
|
||||
.map(|(_, text)| text.as_str())
|
||||
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
|
||||
.unwrap_or("");
|
||||
sync::apply_changes(base, &p.content_changes)
|
||||
};
|
||||
self.mark_dirty(uri, text);
|
||||
}
|
||||
}
|
||||
DidSaveTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
|
||||
if let Some(text) = p.text {
|
||||
self.set_document(p.text_document.uri.clone(), text);
|
||||
}
|
||||
// A save is one of the things that rebuild the index; the
|
||||
// others are a change to `lucisv.exclude`/`lucisv.filelist`
|
||||
// below, and a watched file changing on disk. The
|
||||
// staleness window that is left is in the feature README.
|
||||
//
|
||||
// A save names exactly one file, which is the case the
|
||||
// index can replace in place — so this is where the
|
||||
// incremental path earns its keep, and the whole rebuild is
|
||||
// the fallback for a file the index does not already hold.
|
||||
let one = crate::uri::uri_to_path(&p.text_document.uri);
|
||||
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
|
||||
self.reindex();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Something changed on disk that no buffer told us about — a `git
|
||||
// pull`, a checkout, a generated file, an externally edited
|
||||
// filelist. One rebuild per *notification*, never one per file:
|
||||
// the params carry a list, and a checkout fills it.
|
||||
DidChangeWatchedFiles::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
|
||||
let filelist = self.workspace.filelist_path();
|
||||
if watch::touches_scope(&p.changes, filelist.as_deref()) {
|
||||
// One file named is the incremental case; a checkout
|
||||
// filling the list, or the filelist itself moving, is
|
||||
// the whole rebuild.
|
||||
let one = watch::one_scope_file(&p.changes, filelist.as_deref());
|
||||
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
|
||||
self.reindex();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The client moved or removed files itself. The same nudge a
|
||||
// watched-file event gives, filtered by the same predicate, and
|
||||
// deliberately not deduplicated against it: a client is free to
|
||||
// send both, and a second rebuild is a pure re-read of the tree —
|
||||
// it costs one scan and one diagnostics generation, never a
|
||||
// different answer.
|
||||
DidRenameFiles::METHOD => {
|
||||
if let Ok(p) = extract::<RenameFilesParams>(notification) {
|
||||
self.reindex_for(file_ops::renamed(&p.files));
|
||||
}
|
||||
}
|
||||
DidDeleteFiles::METHOD => {
|
||||
if let Ok(p) = extract::<DeleteFilesParams>(notification) {
|
||||
self.reindex_for(file_ops::deleted(&p.files));
|
||||
}
|
||||
}
|
||||
// The `lucisv.*` settings, pushed at startup and on every change.
|
||||
// Nothing here trusts the payload — `settings::from_payload`
|
||||
// drops whatever it cannot use.
|
||||
//
|
||||
// An **empty** payload is not a settings payload at all: it is the
|
||||
// 3.17 client saying "something changed, ask me for what you
|
||||
// need", so a client that can be asked is asked and nothing is
|
||||
// applied until it answers. A client that cannot be asked keeps
|
||||
// the behaviour it has always had — an empty payload is no
|
||||
// opinion about anything, which resolves to the defaults.
|
||||
DidChangeConfiguration::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeConfigurationParams>(notification) {
|
||||
if settings::says_nothing(&p.settings) && self.abilities.configuration {
|
||||
self.request_configuration();
|
||||
return;
|
||||
}
|
||||
self.apply_settings(settings::from_payload(&p.settings));
|
||||
}
|
||||
}
|
||||
// The user added or removed a workspace folder mid-session. One
|
||||
// rescan per *notification* — an event carries both lists, and
|
||||
// the progress bar, the code-lens refresh and the diagnostics
|
||||
// generation all ride along inside `reindex()`. An event that
|
||||
// changes nothing (a folder already held, one never held, an
|
||||
// empty event) rescans nothing.
|
||||
DidChangeWorkspaceFolders::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeWorkspaceFoldersParams>(notification) {
|
||||
let watched = self.workspace.filelist_path();
|
||||
let added = folder_paths(&p.event.added);
|
||||
let removed = folder_paths(&p.event.removed);
|
||||
if self.workspace.change_roots(added, &removed) {
|
||||
self.reindex();
|
||||
}
|
||||
// A relative `lucisv.filelist` is anchored at the *first*
|
||||
// root, so a folder change can move the watched path
|
||||
// without anyone touching the setting. Same rule, same
|
||||
// reason as a changed setting: the path is baked into the
|
||||
// registration. The source glob itself is workspace-wide
|
||||
// and needs no re-registration — see
|
||||
// `docs/features/folders-and-config/README.md`.
|
||||
if self.workspace.filelist_path() != watched {
|
||||
self.register_watchers();
|
||||
}
|
||||
}
|
||||
}
|
||||
DidCloseTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
self.config_warnings.remove(&uri);
|
||||
// The buffer's unanalyzed change is already gone — it was
|
||||
// dropped at the top of this function, ahead of the flush
|
||||
// that would otherwise have analyzed it.
|
||||
//
|
||||
// The remembered token answer goes with the buffer: the
|
||||
// client drops what it was holding too, and nothing may
|
||||
// grow with the number of files ever opened.
|
||||
self.tokens.remove(&uri);
|
||||
self.workspace.close_document(&uri);
|
||||
// Clear what we drew: the buffer is gone.
|
||||
self.send_diagnostics(uri, Vec::new());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adopt `lucisv.*` settings, from wherever they came, and pay whatever
|
||||
/// they cost.
|
||||
///
|
||||
/// One applier for the push and the pull, so the two can never disagree
|
||||
/// about what a setting *does* any more than `settings::from_payload` and
|
||||
/// `from_section` can disagree about what it says.
|
||||
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
|
||||
let watched = self.workspace.filelist_path();
|
||||
let linted = self.lint_selection();
|
||||
// Only `exclude` and `filelist` change which files exist as far as
|
||||
// this server is concerned; the other settings are read afresh by the
|
||||
// next request that wants them and need no invalidation.
|
||||
if self.workspace.set_client_settings(settings) {
|
||||
self.reindex();
|
||||
} else if self.lint_selection() != linted {
|
||||
// `lucisv.lint.select`/`ignore` change which rules run and nothing
|
||||
// else: no file's contents moved, so there is nothing to rescan —
|
||||
// but every published squiggle was drawn under the old selection,
|
||||
// and a client that pulls has cached answers under it too.
|
||||
self.generation += 1;
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
// The watched filelist path is baked into the registration, so a new
|
||||
// one needs a new registration.
|
||||
if self.workspace.filelist_path() != watched {
|
||||
self.register_watchers();
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule selection in force, as a value two settings pushes can be
|
||||
/// compared by.
|
||||
fn lint_selection(&self) -> (Vec<String>, Vec<String>) {
|
||||
let client = self.workspace.client_settings();
|
||||
(client.lint_select.clone(), client.lint_ignore.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// A notification's params, or `Err` when they do not parse — a malformed
|
||||
/// notification is dropped, because there is no id to answer it on.
|
||||
fn extract<P: DeserializeOwned>(
|
||||
notification: Notification,
|
||||
) -> Result<P, ExtractError<Notification>> {
|
||||
let method = notification.method.clone();
|
||||
notification.extract(&method)
|
||||
}
|
||||
|
||||
/// The buffer a `didClose` names, read without consuming the notification —
|
||||
/// the close handler runs after the flush, and dropping a pending change has
|
||||
/// to happen before it. `None` for params that do not parse, which the
|
||||
/// handler below ignores in exactly the same way.
|
||||
fn closing_uri(notification: &Notification) -> Option<Uri> {
|
||||
serde_json::from_value::<DidCloseTextDocumentParams>(notification.params.clone())
|
||||
.ok()
|
||||
.map(|p| p.text_document.uri)
|
||||
}
|
||||
|
||||
/// The paths behind a `didChangeWorkspaceFolders` list.
|
||||
///
|
||||
/// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once
|
||||
/// decoded — is dropped rather than guessed at, the same rule `uri.rs` holds
|
||||
/// everywhere else: there is nothing on disk to walk for it.
|
||||
fn folder_paths(folders: &[WorkspaceFolder]) -> Vec<std::path::PathBuf> {
|
||||
folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect()
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
//! The indexing bar and the per-file log a rescan runs under.
|
||||
//!
|
||||
//! `begin_indexing` puts the bar up and `end_indexing` takes it down with
|
||||
//! the count; between them `IndexWatch` — which holds the connection rather
|
||||
//! than the `Server`, because the workspace is borrowed mutably for the
|
||||
//! whole of the rebuild it watches — turns each `IndexEvent` into a report
|
||||
//! and a log line, thinned past `MAX_REPORTS` files so a 40 000-file
|
||||
//! workspace does not send 40 000 notifications per save. Its own file
|
||||
//! because it is the one part of a rescan that is about *saying* rather than
|
||||
//! *doing*, and `index.rs` reads better without it.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_server::Connection;
|
||||
use lsp_types::notification::{LogMessage, Notification as _, Progress};
|
||||
use lsp_types::request::{Request as _, WorkDoneProgressCreate};
|
||||
use lsp_types::{
|
||||
LogMessageParams, MessageType, ProgressParams, ProgressParamsValue, ProgressToken,
|
||||
WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd,
|
||||
WorkDoneProgressReport,
|
||||
};
|
||||
|
||||
use super::client::notify_on;
|
||||
use super::Server;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::IndexEvent;
|
||||
|
||||
/// What the workspace-rescan progress bar calls itself. One title for every
|
||||
/// rescan — startup, save, watched file, changed scope — because they are the
|
||||
/// same work and a user reading the status bar wants to know that.
|
||||
const INDEXING_TITLE: &str = "Indexing Verilog workspace";
|
||||
|
||||
impl Server {
|
||||
/// Put a progress bar up for the rescan that is about to run, and report
|
||||
/// the token it must be taken down with. `None` for a client that cannot
|
||||
/// show one — the spec forbids creating progress it never asked for.
|
||||
///
|
||||
/// The `begin` goes out immediately after the `create`, without waiting
|
||||
/// for its answer: the rescan blocks this thread the moment this returns,
|
||||
/// so waiting would mean the bar appears only once the work it describes
|
||||
/// is over. The spec allows it, and a client that errors the `create`
|
||||
/// ignores the `$/progress` that follows.
|
||||
///
|
||||
/// The `begin` carries no percentage: the first one that means anything
|
||||
/// is the first file's, and it is `IndexWatch` that sends it. Every
|
||||
/// percentage from there on is measured — `n` files of a work list whose
|
||||
/// length was known before the first parse — never invented.
|
||||
pub(super) fn begin_indexing(&mut self) -> Option<ProgressToken> {
|
||||
if !self.abilities.work_done_progress {
|
||||
return None;
|
||||
}
|
||||
let token = ProgressToken::String(format!("lucisv-index-{}", self.indexings));
|
||||
self.indexings += 1;
|
||||
let params = WorkDoneProgressCreateParams { token: token.clone() };
|
||||
self.send_request(WorkDoneProgressCreate::METHOD, params);
|
||||
self.progress(
|
||||
token.clone(),
|
||||
WorkDoneProgress::Begin(WorkDoneProgressBegin {
|
||||
title: INDEXING_TITLE.to_string(),
|
||||
// Nothing already running in this server can be cancelled: the
|
||||
// loop is one thread and a rescan runs to completion — the
|
||||
// `$/cancelRequest` support only answers requests still
|
||||
// queued. Saying so is what keeps a cancel button the user
|
||||
// could press off the bar.
|
||||
cancellable: Some(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
Some(token)
|
||||
}
|
||||
|
||||
/// Take the bar down, naming what the rescan found. The count is the
|
||||
/// index's own file list, which is the only number this costs nothing to
|
||||
/// know. Called the moment the rescan returns, before the scope warnings
|
||||
/// and the republishes — the bar names the scan, and what follows it is
|
||||
/// per-open-buffer work the user already pays on every keystroke.
|
||||
///
|
||||
/// `skipped` is how many files the size cap kept out, and it is named here
|
||||
/// whether or not the per-file log is on: the log is the *detail*, and a
|
||||
/// user who turned it off should still learn that part of their workspace
|
||||
/// is not in the index. `cached` is how many were restored from the
|
||||
/// persistent index cache rather than parsed, and is named for the
|
||||
/// opposite reason — a scan that finished suspiciously fast should say
|
||||
/// why (`docs/features/index-persistence/README.md`).
|
||||
pub(super) fn end_indexing(&self, token: Option<ProgressToken>, skipped: usize, cached: usize) {
|
||||
let Some(token) = token else { return };
|
||||
let files = self.workspace.index().files().len();
|
||||
let plural = if files == 1 { "" } else { "s" };
|
||||
let mut message = format!("{files} file{plural} indexed");
|
||||
if cached > 0 {
|
||||
message.push_str(&format!(", {cached} from cache"));
|
||||
}
|
||||
if skipped > 0 {
|
||||
message.push_str(&format!(", {skipped} skipped"));
|
||||
}
|
||||
self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message: Some(message) }));
|
||||
}
|
||||
|
||||
/// One `$/progress` notification for a token the client already knows.
|
||||
fn progress(&self, token: ProgressToken, value: WorkDoneProgress) {
|
||||
progress_on(&self.connection, &token, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many `$/progress` reports one rescan may send.
|
||||
///
|
||||
/// One per file is right for the workspaces people actually have — the 860-file
|
||||
/// corpus is 860 small notifications across two thirds of a second — but a
|
||||
/// 40,000-file filelist would be 40,000 of them on every save. Past this many
|
||||
/// files the reports thin out to every ⌈total/1000⌉-th, which still moves the
|
||||
/// bar by a tenth of a percent at a time: under a pixel.
|
||||
pub(super) const MAX_REPORTS: usize = 1000;
|
||||
|
||||
/// Whether the file numbered `done` (from 0) of `total` gets a `report`.
|
||||
///
|
||||
/// The last file always reports, so a rescan's final bar position is always
|
||||
/// `total/total` at 100%. Without that, a 10,000-file scan would stop
|
||||
/// reporting at 10,000 exactly — but a 10,001-file one would stop at 10,000
|
||||
/// and leave the bar a file short of the work it had finished.
|
||||
pub(super) fn reports(done: usize, total: usize) -> bool {
|
||||
let step = total.div_ceil(MAX_REPORTS).max(1);
|
||||
(done + 1).is_multiple_of(step) || done + 1 == total
|
||||
}
|
||||
|
||||
/// Watches one index rebuild: a `$/progress` report and a log line per file,
|
||||
/// and a count of the files the size cap skipped.
|
||||
///
|
||||
/// Holds the connection rather than the `Server`, because the workspace is
|
||||
/// borrowed mutably for the whole of the rebuild being watched. Everything it
|
||||
/// sends is a notification, so nothing here can fail in a way a caller could
|
||||
/// act on.
|
||||
pub(super) struct IndexWatch<'a> {
|
||||
connection: &'a Connection,
|
||||
/// The bar to report against — `None` for a client that cannot show one,
|
||||
/// which is the same gate `begin_indexing` applied.
|
||||
bar: Option<&'a ProgressToken>,
|
||||
/// `lucisv.index.logFiles`: whether the per-file lines are sent at all.
|
||||
log_files: bool,
|
||||
}
|
||||
|
||||
impl<'a> IndexWatch<'a> {
|
||||
pub(super) fn new(
|
||||
connection: &'a Connection,
|
||||
bar: Option<&'a ProgressToken>,
|
||||
settings: &ClientSettings,
|
||||
) -> IndexWatch<'a> {
|
||||
IndexWatch { connection, bar, log_files: settings.log_files }
|
||||
}
|
||||
|
||||
/// Report one thing the rebuild just did.
|
||||
pub(super) fn see(&mut self, event: IndexEvent) {
|
||||
match event {
|
||||
IndexEvent::Parsing { done, total, path } => {
|
||||
self.say(format!("indexing: {}", path.display()));
|
||||
self.tick(done, total, path);
|
||||
}
|
||||
// A different word for a file that cost nothing, and the same
|
||||
// tick: a cached file is a file of the work list, and the bar
|
||||
// flying through them is exactly what the cache bought.
|
||||
IndexEvent::Cached { done, total, path } => {
|
||||
self.say(format!("cached: {}", path.display()));
|
||||
self.tick(done, total, path);
|
||||
}
|
||||
// A third word, and no count in the end message: an open buffer's
|
||||
// own analysis costs nothing either, but one file out of a
|
||||
// workspace is not why a scan finished fast, and a bar that grew a
|
||||
// clause on every session with a file open would say less, not
|
||||
// more. The per-file log still names it, which is where a user
|
||||
// asking "did it re-parse my huge buffer?" looks.
|
||||
IndexEvent::Analyzed { done, total, path } => {
|
||||
self.say(format!("analyzed: {}", path.display()));
|
||||
self.tick(done, total, path);
|
||||
}
|
||||
IndexEvent::Skipped { path, size, cap } => {
|
||||
self.say(format!(
|
||||
"skipped ({} > {} cap): {}",
|
||||
human_size(size),
|
||||
human_size(cap),
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the bar to `done + 1` of `total`, if this file is one of the ones
|
||||
/// that reports.
|
||||
///
|
||||
/// The message names the file rather than its path: the bar is a strip of
|
||||
/// status bar a few dozen characters wide, and the path is in the log for
|
||||
/// anyone who wants it. The percentage is `(done + 1) / total`, which
|
||||
/// only ever counts up.
|
||||
fn tick(&self, done: usize, total: usize, path: &Path) {
|
||||
let Some(token) = self.bar else { return };
|
||||
if !reports(done, total) {
|
||||
return;
|
||||
}
|
||||
let name = path.file_name().unwrap_or(path.as_os_str()).to_string_lossy();
|
||||
let report = WorkDoneProgressReport {
|
||||
cancellable: Some(false),
|
||||
message: Some(format!("{}/{total} {name}", done + 1)),
|
||||
// `total` cannot be 0 here — this is called from inside the loop
|
||||
// over the files — but a percentage is not worth a division that
|
||||
// has to be argued about.
|
||||
percentage: Some(((done + 1) * 100 / total.max(1)) as u32),
|
||||
};
|
||||
progress_on(self.connection, token, WorkDoneProgress::Report(report));
|
||||
}
|
||||
|
||||
/// One line in the client's output channel, if the user left the file log
|
||||
/// on.
|
||||
///
|
||||
/// `MessageType::LOG`, unprefixed: these are hundreds of lines per rescan
|
||||
/// in a channel that is already this server's, and "lucisv: " on every one
|
||||
/// of them would be noise plus traffic. The scope warnings, which are
|
||||
/// rare and also shown in a popup, keep their prefix.
|
||||
fn say(&self, message: String) {
|
||||
if !self.log_files {
|
||||
return;
|
||||
}
|
||||
let params = LogMessageParams { typ: MessageType::LOG, message };
|
||||
notify_on(self.connection, LogMessage::METHOD, params);
|
||||
}
|
||||
}
|
||||
|
||||
/// A byte count in the largest unit that keeps it readable.
|
||||
///
|
||||
/// The cap is written in bytes and can be set to anything, so a fixed unit is
|
||||
/// wrong at one end or the other: "0.0 MiB > 0.0 MiB cap" says nothing about a
|
||||
/// 4 KiB file under a 1 KiB cap, and "4194304 B" says nothing quickly about a
|
||||
/// netlist.
|
||||
fn human_size(bytes: u64) -> String {
|
||||
const KIB: f64 = 1024.0;
|
||||
const MIB: f64 = KIB * 1024.0;
|
||||
// The unit is chosen by what the ROUNDED number reads as, not the raw
|
||||
// size: 1 048 575 bytes is "1.0 MiB", never "1024.0 KiB" (QA log,
|
||||
// 2026-08-27 — the same class of bug the e2e's "0.0 MiB > 0.0 MiB"
|
||||
// caught at the opposite edge).
|
||||
let size = bytes as f64;
|
||||
if size < KIB {
|
||||
format!("{bytes} B")
|
||||
} else if (size / KIB).round() < KIB {
|
||||
format!("{:.1} KiB", size / KIB)
|
||||
} else {
|
||||
format!("{:.1} MiB", size / MIB)
|
||||
}
|
||||
}
|
||||
|
||||
/// One `$/progress` notification, on a connection rather than through a
|
||||
/// `Server` — what the index watcher has while the workspace is borrowed.
|
||||
fn progress_on(connection: &Connection, token: &ProgressToken, value: WorkDoneProgress) {
|
||||
let params =
|
||||
ProgressParams { token: token.clone(), value: ProgressParamsValue::WorkDone(value) };
|
||||
notify_on(connection, Progress::METHOD, params);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod human_size_tests {
|
||||
use super::human_size;
|
||||
|
||||
#[test]
|
||||
fn the_unit_is_chosen_by_what_the_rounded_number_reads_as() {
|
||||
// QA finding, 2026-08-27: a byte short of a MiB must not print as
|
||||
// "1024.0 KiB". The unit flips when the smaller unit's rounded
|
||||
// number would read as the next unit.
|
||||
assert_eq!(human_size(1_048_575), "1.0 MiB");
|
||||
assert_eq!(human_size(1_048_576), "1.0 MiB");
|
||||
assert_eq!(human_size(1023), "1023 B");
|
||||
assert_eq!(human_size(1024), "1.0 KiB");
|
||||
assert_eq!(human_size(4_096), "4.0 KiB");
|
||||
assert_eq!(human_size(2_411_724), "2.3 MiB");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Semantic tokens with a memory: the full answer that is stamped and kept,
|
||||
//! and the delta computed against it.
|
||||
//!
|
||||
//! The encoding is `crate::tokens`'; this file is only the bookkeeping the
|
||||
//! delta form needs — one remembered answer per open buffer, dropped on
|
||||
//! `didClose` — which is state and so belongs to the `Server`. See
|
||||
//! `docs/features/semantic-tokens-delta/README.md`.
|
||||
|
||||
use lsp_types::{
|
||||
SemanticToken, SemanticTokens, SemanticTokensDelta, SemanticTokensFullDeltaResult, Uri,
|
||||
};
|
||||
|
||||
use super::{Server, TokenAnswer};
|
||||
use crate::tokens;
|
||||
|
||||
impl Server {
|
||||
/// The whole buffer's tokens, stamped and remembered.
|
||||
///
|
||||
/// A client may mix `full` and `full/delta` freely — the protocol lets it
|
||||
/// — so this answer is remembered exactly as a delta's is, and its
|
||||
/// `resultId` is as good a starting point for the next delta.
|
||||
pub(super) fn semantic_tokens_full(&mut self, uri: &Uri) -> Option<SemanticTokens> {
|
||||
let data = tokens::semantic_tokens(self.workspace.document(uri)?);
|
||||
let result_id = self.remember_tokens(uri, data.clone());
|
||||
Some(SemanticTokens { result_id: Some(result_id), data })
|
||||
}
|
||||
|
||||
/// What changed since the answer the client says it holds.
|
||||
///
|
||||
/// A `previousResultId` that does not name the answer we remember — a
|
||||
/// stale one, a buffer we have no state for, one from before a
|
||||
/// `didClose` — is answered with a full set instead. The protocol allows
|
||||
/// either, and a delta against data we cannot see would be a guess.
|
||||
pub(super) fn semantic_tokens_delta(
|
||||
&mut self,
|
||||
uri: &Uri,
|
||||
previous: &str,
|
||||
) -> Option<SemanticTokensFullDeltaResult> {
|
||||
let new = tokens::semantic_tokens(self.workspace.document(uri)?);
|
||||
let known = self.tokens.get(uri).filter(|answer| answer.result_id == previous);
|
||||
let edits = known.map(|answer| tokens::delta(&answer.data, &new));
|
||||
let result_id = Some(self.remember_tokens(uri, new.clone()));
|
||||
Some(match edits {
|
||||
Some(edits) => {
|
||||
SemanticTokensFullDeltaResult::TokensDelta(SemanticTokensDelta { result_id, edits })
|
||||
}
|
||||
None => SemanticTokensFullDeltaResult::Tokens(SemanticTokens { result_id, data: new }),
|
||||
})
|
||||
}
|
||||
|
||||
/// Stamp an answer with a fresh id and keep it as the one the next delta
|
||||
/// is computed against. One buffer holds one answer: a client that asks
|
||||
/// again has moved on from the previous one.
|
||||
fn remember_tokens(&mut self, uri: &Uri, data: Vec<SemanticToken>) -> String {
|
||||
self.token_results += 1;
|
||||
let result_id = self.token_results.to_string();
|
||||
self.tokens.insert(uri.clone(), TokenAnswer { result_id: result_id.clone(), data });
|
||||
result_id
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! `workspace/applyEdit`: how a command's edit reaches the client, and what a refusal says.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `workspace/applyEdit`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_command_pushes_its_edit_when_the_client_can_apply_one() {
|
||||
// The bug this fixes: the edit used to be the request *result*, which
|
||||
// the protocol does not define and every stock client drops.
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("applyedit", abilities);
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert_eq!(result, Value::Null, "the edit is not the result any more");
|
||||
|
||||
let sent = session.sent();
|
||||
assert_eq!(sent.len(), 1, "{sent:#?}");
|
||||
assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD);
|
||||
assert_eq!(
|
||||
sent[0].params["label"],
|
||||
serde_json::json!(format!("lucisv: {}", ports::PROPAGATE_PORTS)),
|
||||
"the undo stack needs a name for it"
|
||||
);
|
||||
let changes = sent[0].params["edit"]["changes"].as_object().expect("changes");
|
||||
let edits = changes.values().next().expect("one file edited");
|
||||
assert_eq!(edits[0]["newText"], ", .rst(rst)", "{:#?}", sent[0].params);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_apply_edits_still_gets_the_edit_back() {
|
||||
// The documented fallback: for such a client, returning the edit is
|
||||
// the only thing that could ever work.
|
||||
let (_tree, mut session, params) = propagating("noapplyedit", ClientAbilities::default());
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
let changes = result["changes"].as_object().expect("the edit is the result");
|
||||
let edits = changes.values().next().expect("one file edited");
|
||||
assert_eq!(edits[0]["newText"], ", .rst(rst)");
|
||||
assert!(session.sent().is_empty(), "and nothing is pushed at it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_the_editor_refused_is_reported_to_the_user() {
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("refused", abilities);
|
||||
session.result(ExecuteCommand::METHOD, params);
|
||||
let sent = session.sent();
|
||||
let id = sent[0].id.clone();
|
||||
|
||||
session.answer(
|
||||
id,
|
||||
serde_json::json!({ "applied": false, "failureReason": "the file is read-only" }),
|
||||
);
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1);
|
||||
assert!(shown[0].1.contains("the file is read-only"), "{}", shown[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_the_editor_applied_is_said_nothing_about() {
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("applied", abilities);
|
||||
session.result(ExecuteCommand::METHOD, params);
|
||||
let id = session.sent()[0].id.clone();
|
||||
|
||||
session.answer(id.clone(), serde_json::json!({ "applied": true }));
|
||||
assert!(session.shown().is_empty(), "success is silent");
|
||||
|
||||
// And the id is spent: a duplicate answer says nothing either.
|
||||
session.answer(id, serde_json::json!({ "applied": false }));
|
||||
assert!(session.shown().is_empty(), "an answer to nothing is ignored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_apply_edit_answer_is_reported_as_a_refusal() {
|
||||
// QA attack: "a response that does not parse is a refusal" is stated
|
||||
// in the Assumptions but was only exercised through `Err` results and
|
||||
// a well-typed `applied: false`. This drives the branch where the
|
||||
// payload is `Ok` JSON that does not deserialize as
|
||||
// `ApplyWorkspaceEditResponse` at all (missing the required `applied`
|
||||
// field) — the honest-refusal path, not a panic or a silent success.
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("malformedapplyedit", abilities);
|
||||
session.result(ExecuteCommand::METHOD, params);
|
||||
let id = session.sent()[0].id.clone();
|
||||
|
||||
session.answer(id, serde_json::json!({ "notApplied": "whatever" }));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "an unparseable answer must still surface: {shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_response_with_a_jsonrpc_error_is_reported_too() {
|
||||
// The `Err` half of `response_result` — a client that rejects the
|
||||
// `applyEdit` request outright at the JSON-RPC level, rather than
|
||||
// answering it with `applied: false`.
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("rpcerror", abilities);
|
||||
session.result(ExecuteCommand::METHOD, params);
|
||||
let id = session.sent()[0].id.clone();
|
||||
|
||||
session.server.response(Response::new_err(id, 1, "internal error".to_string()));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains("internal error"), "{}", shown[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_watcher_registration_answer_is_still_ignored() {
|
||||
// The one response that was always ignored must stay ignored now that
|
||||
// responses are read at all — including an error one.
|
||||
let tree = Tree::new("registeranswer");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
let id = session.sent()[0].id.clone();
|
||||
session.answer(id.clone(), Value::Null);
|
||||
session.server.response(Response::new_err(id, 1, "no thanks".to_string()));
|
||||
assert!(session.shown().is_empty(), "nothing to tell the user");
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
//! `$/cancelRequest` (`docs/features/cancel-request/README.md`).
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// $/cancelRequest — docs/features/cancel-request/README.md
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A `textDocument/documentSymbol` request, queued. Any request would do;
|
||||
/// this one is cheap and its answer names what the buffer holds, which is
|
||||
/// what the ordering test needs.
|
||||
fn ask(id: i32, uri: &Uri) -> Message {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(id),
|
||||
DocumentSymbolRequest::METHOD.to_string(),
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
))
|
||||
}
|
||||
|
||||
/// A `$/cancelRequest` naming `id`, exactly as a client sends it — the id
|
||||
/// is passed as raw JSON so both protocol forms can be tested.
|
||||
fn cancel(id: Value) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
Cancel::METHOD.to_string(),
|
||||
serde_json::json!({ "id": id }),
|
||||
))
|
||||
}
|
||||
|
||||
/// The protocol's `RequestCancelled`.
|
||||
const CANCELLED: i32 = -32800;
|
||||
|
||||
/// Every response since the last drain, as (id, error code or `None`).
|
||||
fn outcomes(session: &Session) -> Vec<(RequestId, Option<i32>)> {
|
||||
session
|
||||
.answers()
|
||||
.into_iter()
|
||||
.map(|response| {
|
||||
let code = response.response_result.err().map(|error| error.code);
|
||||
(response.id, code)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The top-level symbol names in a `documentSymbol` answer.
|
||||
fn symbol_names(result: &Value) -> Vec<String> {
|
||||
result
|
||||
.as_array()
|
||||
.expect("an array of symbols")
|
||||
.iter()
|
||||
.map(|symbol| symbol["name"].as_str().expect("a name").to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A session with one open buffer, drained of the startup traffic.
|
||||
fn cancelling_session(name: &str, text: &str) -> (Tree, Session, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
let _ = session.drain();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
const ONE_MODULE: &str = "module m;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_request_cancelled_in_the_same_burst_is_answered_cancelled() {
|
||||
// The point of the whole feature: the client asked and changed its
|
||||
// mind while the server was busy elsewhere, so the answer costs
|
||||
// nothing to produce.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelsame", ONE_MODULE);
|
||||
let shutdown = session.batch(vec![ask(1, &uri), cancel(serde_json::json!(1))]);
|
||||
|
||||
assert!(!shutdown, "a cancel is not a shutdown");
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(1), Some(CANCELLED))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_dequeued_before_its_request_still_cancels_it() {
|
||||
// The batch is scanned as a whole before any of it runs, so a cancel
|
||||
// the transport happened to deliver first is not a cancel that
|
||||
// arrived too early.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelfirst", ONE_MODULE);
|
||||
session.batch(vec![cancel(serde_json::json!(1)), ask(1, &uri)]);
|
||||
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(1), Some(CANCELLED))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone() {
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelone", ONE_MODULE);
|
||||
session.batch(vec![ask(1, &uri), ask(2, &uri), cancel(serde_json::json!(1))]);
|
||||
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(1), Some(CANCELLED)), (RequestId::from(2), None)],
|
||||
"id 2 was answered normally, and in its own place in the queue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot() {
|
||||
// A cancel that arrives in a later burst than its request is too late
|
||||
// — that request was answered already — and remembering it would be a
|
||||
// set that grows for the life of the session. The identical id in the
|
||||
// burst after proves nothing was kept: real clients never reuse an
|
||||
// id, so only a leak could cancel this one.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancellate", ONE_MODULE);
|
||||
let shutdown = session.batch(vec![cancel(serde_json::json!(1))]);
|
||||
|
||||
assert!(!shutdown);
|
||||
assert_eq!(outcomes(&session), vec![], "a lone cancel is answered with nothing at all");
|
||||
|
||||
session.batch(vec![ask(1, &uri)]);
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(1), None)],
|
||||
"the dropped cancel did not survive into the next burst"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered() {
|
||||
// The invariant the burst must not break: order. A `didChange` the
|
||||
// client sent before its request has to be in effect when that
|
||||
// request is answered, exactly as it would be one message at a time.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelorder", ONE_MODULE);
|
||||
session.batch(vec![changed(&uri, 2, "module renamed;\nendmodule\n"), ask(1, &uri)]);
|
||||
|
||||
let answers = session.answers();
|
||||
assert_eq!(answers.len(), 1);
|
||||
let result = answers[0].response_result.clone().expect("an answer");
|
||||
assert_eq!(symbol_names(&result), vec!["renamed".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_never_cancels_a_notification() {
|
||||
// Notifications carry no id and get no response, so nothing in a
|
||||
// burst can suppress one — whatever id the cancel names.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelnotify", ONE_MODULE);
|
||||
session.batch(vec![
|
||||
changed(&uri, 2, "module renamed;\nendmodule\n"),
|
||||
cancel(serde_json::json!(1)),
|
||||
cancel(serde_json::json!("textDocument/didChange")),
|
||||
]);
|
||||
|
||||
assert_eq!(buffer(&session, &uri), "module renamed;\nendmodule\n");
|
||||
assert_eq!(outcomes(&session), vec![], "no ids were cancelled, so no responses");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shutdown_is_honoured_however_it_is_cancelled() {
|
||||
// The spec lets a server answer a cancelled request normally, and for
|
||||
// `shutdown` that is the only safe reading: a client that cannot shut
|
||||
// the server down leaks a process. `handle_shutdown` runs before the
|
||||
// cancelled set is consulted, so the cancel never gets a say.
|
||||
let (_tree, mut session, _uri) = cancelling_session("cancelshutdown", ONE_MODULE);
|
||||
// `handle_shutdown` waits for the `exit` that follows, and reads it off
|
||||
// the *connection* — so the forwarder has to have stopped first, or it
|
||||
// takes the `exit` and the handshake finds nothing. It stops at the
|
||||
// first `shutdown` it forwards, so one is sent through it and waited
|
||||
// for: once that message is off the queue the forwarder has already
|
||||
// broken out of its loop and will never read the connection again.
|
||||
// (Before 2026-08-28 the forwarder did not exist until `run`, which
|
||||
// this test never calls, so the `exit` simply sat there.)
|
||||
session
|
||||
.client
|
||||
.sender
|
||||
.send(Message::Request(Request::new(
|
||||
RequestId::from(99),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
)))
|
||||
.expect("queue a shutdown for the forwarder to stop at");
|
||||
session
|
||||
.server
|
||||
.queue
|
||||
.recv_timeout(std::time::Duration::from_secs(5))
|
||||
.expect("the forwarder stops at it");
|
||||
session
|
||||
.client
|
||||
.sender
|
||||
.send(Message::Notification(Notification::new("exit".to_string(), Value::Null)))
|
||||
.expect("queue exit");
|
||||
|
||||
let request = Message::Request(Request::new(
|
||||
RequestId::from(9),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
));
|
||||
let shutdown = session.batch(vec![request, cancel(serde_json::json!(9))]);
|
||||
|
||||
assert!(shutdown, "the loop exits");
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(9), None)],
|
||||
"shutdown was answered, and answered successfully"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_one_request_twice_answers_it_once() {
|
||||
let (_tree, mut session, uri) = cancelling_session("canceltwice", ONE_MODULE);
|
||||
session.batch(vec![
|
||||
ask(1, &uri),
|
||||
cancel(serde_json::json!(1)),
|
||||
cancel(serde_json::json!(1)),
|
||||
ask(2, &uri),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(1), Some(CANCELLED)), (RequestId::from(2), None)],
|
||||
"the second cancel changed nothing — id 2 is not collateral damage"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_id_may_be_a_number_or_a_string() {
|
||||
// The protocol allows both, and a client that numbers its requests
|
||||
// with strings is not exotic.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelstring", ONE_MODULE);
|
||||
let request = Message::Request(Request::new(
|
||||
RequestId::from("abc".to_string()),
|
||||
DocumentSymbolRequest::METHOD.to_string(),
|
||||
serde_json::json!({ "textDocument": { "uri": &uri } }),
|
||||
));
|
||||
session.batch(vec![request, cancel(serde_json::json!("abc"))]);
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from("abc".to_string()), Some(CANCELLED))]);
|
||||
|
||||
session.batch(vec![ask(7, &uri), cancel(serde_json::json!(7))]);
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(7), Some(CANCELLED))]);
|
||||
|
||||
// A string that spells a number is not the number: `RequestId` keeps
|
||||
// the two apart, and so must the cancel.
|
||||
session.batch(vec![ask(8, &uri), cancel(serde_json::json!("8"))]);
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(8), None)],
|
||||
"the string \"8\" does not cancel the number 8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_cancel_is_dropped_rather_than_guessed_at() {
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelmalformed", ONE_MODULE);
|
||||
let broken = Message::Notification(Notification::new(
|
||||
Cancel::METHOD.to_string(),
|
||||
serde_json::json!({ "id": { "nested": true } }),
|
||||
));
|
||||
session.batch(vec![ask(1, &uri), broken]);
|
||||
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(1), None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name() {
|
||||
// The forwarder stops forwarding the moment it sees this return
|
||||
// `true`. A malformed or adversarial client sending a *notification*
|
||||
// named "shutdown" must not trip it — that would silently stall the
|
||||
// whole backlog, with `handle_shutdown` never having run to explain
|
||||
// why.
|
||||
let request = Message::Request(Request::new(
|
||||
RequestId::from(1),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
));
|
||||
let notification =
|
||||
Message::Notification(Notification::new(Shutdown::METHOD.to_string(), Value::Null));
|
||||
let other_request = Message::Request(Request::new(
|
||||
RequestId::from(2),
|
||||
DocumentSymbolRequest::METHOD.to_string(),
|
||||
Value::Null,
|
||||
));
|
||||
|
||||
assert!(is_shutdown(&request));
|
||||
assert!(
|
||||
!is_shutdown(¬ification),
|
||||
"a notification named shutdown is not the shutdown request"
|
||||
);
|
||||
assert!(!is_shutdown(&other_request));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burst_collects_everything_already_queued_in_arrival_order() {
|
||||
// `burst` is what turns "one blocking receive" into "the whole
|
||||
// backlog" — the only place FIFO order could be broken. Nothing here
|
||||
// touches `Server`, so the check is on the free function alone.
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender
|
||||
.send(Message::Notification(Notification::new("second".to_string(), Value::Null)))
|
||||
.expect("send");
|
||||
sender
|
||||
.send(Message::Notification(Notification::new("third".to_string(), Value::Null)))
|
||||
.expect("send");
|
||||
|
||||
let first = Message::Notification(Notification::new("first".to_string(), Value::Null));
|
||||
let batch = burst(&receiver, first);
|
||||
|
||||
let methods: Vec<&str> = batch
|
||||
.iter()
|
||||
.map(|message| match message {
|
||||
Message::Notification(notification) => notification.method.as_str(),
|
||||
_ => "?",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
methods,
|
||||
vec!["first", "second", "third"],
|
||||
"the blocked-for message first, then the backlog, in order"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown() {
|
||||
// The handoff this whole feature depends on: once the forwarder has
|
||||
// pushed a `shutdown` request onto the queue, it must not call `recv`
|
||||
// on `connection.receiver` again — that channel is where
|
||||
// `handle_shutdown` reads the `exit` that follows. An eager forwarder
|
||||
// would steal it and strand the handshake for thirty seconds.
|
||||
let (_tree, session, _uri) = cancelling_session("forwarderstop", ONE_MODULE);
|
||||
let shutdown_id = RequestId::from(9);
|
||||
session
|
||||
.client
|
||||
.sender
|
||||
.send(Message::Request(Request::new(
|
||||
shutdown_id.clone(),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
)))
|
||||
.expect("queue shutdown");
|
||||
session
|
||||
.client
|
||||
.sender
|
||||
.send(Message::Notification(Notification::new("exit".to_string(), Value::Null)))
|
||||
.expect("queue exit");
|
||||
|
||||
// The server's own queue — the one the forwarder started at
|
||||
// construction is filling — rather than a second one: two forwarders
|
||||
// over one connection would each take half the messages.
|
||||
let queue = &session.server.queue;
|
||||
let forwarded =
|
||||
queue.recv_timeout(std::time::Duration::from_secs(1)).expect("shutdown is forwarded");
|
||||
assert!(matches!(&forwarded, Message::Request(request) if request.id == shutdown_id));
|
||||
|
||||
// Give the forwarder thread every chance to (wrongly) keep reading
|
||||
// before asserting that it did not.
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
assert!(
|
||||
queue.try_recv().is_err(),
|
||||
"the forwarder must not forward anything after the shutdown request"
|
||||
);
|
||||
|
||||
// The `exit` is still sitting on the real connection, unread — right
|
||||
// where `handle_shutdown` looks for it.
|
||||
let direct = session
|
||||
.server
|
||||
.connection
|
||||
.receiver
|
||||
.recv_timeout(std::time::Duration::from_secs(1))
|
||||
.expect("exit is still there for handle_shutdown to read");
|
||||
assert!(
|
||||
matches!(&direct, Message::Notification(notification) if notification.method == "exit")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing() {
|
||||
// `lucisv-0`, `lucisv-1`, … are ids the server hands out for requests
|
||||
// it sends *to* the client (`applyEdit`, watcher registration,
|
||||
// progress `create`) — they come back as a `Message::Response`, a
|
||||
// different match arm entirely from the `Message::Request`s a burst
|
||||
// scans for cancellable ids. A client cancelling one by name has
|
||||
// nothing to reach.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelserverid", ONE_MODULE);
|
||||
let server_id = session.server.send_request("workspace/applyEdit", serde_json::json!({}));
|
||||
assert_eq!(server_id, RequestId::from("lucisv-0".to_string()));
|
||||
|
||||
session.batch(vec![ask(1, &uri), cancel(serde_json::json!("lucisv-0"))]);
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(1), None)],
|
||||
"the client's own request was untouched by a cancel naming a server-initiated id"
|
||||
);
|
||||
|
||||
// The server-initiated request can still be answered normally — the
|
||||
// cancel did not intercept it.
|
||||
session.answer(server_id, Value::Null);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! File operations (`docs/features/file-operations/README.md`).
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// file operations (`docs/features/file-operations/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One `workspace/willRenameFiles` for `from` → `to`, driven through the
|
||||
/// real dispatch.
|
||||
fn will_rename(session: &mut Session, from: &Path, to: &Path) -> Value {
|
||||
session.result(
|
||||
WillRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{
|
||||
"oldUri": path_to_uri(from).expect("uri"),
|
||||
"newUri": path_to_uri(to).expect("uri"),
|
||||
}] }),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn will_rename_answers_the_edit_that_keeps_an_include_resolving() {
|
||||
let tree = Tree::new("willrename");
|
||||
tree.write("defs.svh", "`define W 8\n");
|
||||
tree.write("top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
|
||||
let (from, to) = (tree.path.join("defs.svh"), tree.path.join("widths.svh"));
|
||||
let answer = will_rename(&mut session, &from, &to);
|
||||
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
|
||||
let edits = &answer["changes"][uri.as_str()];
|
||||
assert_eq!(edits[0]["newText"], serde_json::json!("widths.svh"), "{answer:#?}");
|
||||
// The range is the path token: line 0, inside the quotes.
|
||||
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 10 }));
|
||||
assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 0, "character": 18 }));
|
||||
assert!(session.shown().is_empty(), "a rewrite everything could reach says nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn will_rename_works_for_a_file_no_editor_ever_opened() {
|
||||
// Includes live in unopened files; the sweep reads them off disk
|
||||
// through the same `sources()` the index is built from.
|
||||
let tree = Tree::new("willrenameunopened");
|
||||
tree.write("defs.svh", "`define W 8\n");
|
||||
tree.write("top.sv", "`include \"defs.svh\"\n");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert!(session.server.workspace.open_uris().is_empty(), "premise: nothing open");
|
||||
|
||||
let answer =
|
||||
will_rename(&mut session, &tree.path.join("defs.svh"), &tree.path.join("widths.svh"));
|
||||
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
|
||||
assert_eq!(
|
||||
answer["changes"][uri.as_str()][0]["newText"],
|
||||
serde_json::json!("widths.svh"),
|
||||
"{answer:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn will_rename_answers_null_when_there_is_nothing_to_rewrite() {
|
||||
let tree = Tree::new("willrenamenull");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("notes.md", "prose\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
|
||||
// A source file nothing includes.
|
||||
let answer =
|
||||
will_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv"));
|
||||
assert_eq!(answer, Value::Null, "{answer:#?}");
|
||||
// And a file this server has no opinion about at all.
|
||||
let answer =
|
||||
will_rename(&mut session, &tree.path.join("notes.md"), &tree.path.join("NOTES.md"));
|
||||
assert_eq!(answer, Value::Null, "{answer:#?}");
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_include_a_rename_strands_is_shown_once_and_logged() {
|
||||
// The same "first shown, all logged" rule the scope warnings follow —
|
||||
// a rename that strands forty includes must not open forty popups.
|
||||
let tree = Tree::new("willrenamewarn");
|
||||
std::fs::create_dir_all(tree.path.join("inc")).expect("mkdir");
|
||||
tree.write("inc/defs.svh", "`define W 8\n");
|
||||
tree.write("a.sv", "`include <defs.svh>\n");
|
||||
tree.write("b.sv", "`include <defs.svh>\n");
|
||||
tree.write("files.f", "+incdir+inc\na.sv\nb.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let _ = session.drain();
|
||||
|
||||
// The angled form resolves against incdirs only, so a move out of the
|
||||
// one include path cannot be spelled from either file.
|
||||
let answer =
|
||||
will_rename(&mut session, &tree.path.join("inc/defs.svh"), &tree.path.join("far.svh"));
|
||||
assert_eq!(answer, Value::Null, "nothing invented: {answer:#?}");
|
||||
let shown = session.drain();
|
||||
let popups: Vec<&Message> = shown
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Notification(n) if n.method == ShowMessage::METHOD))
|
||||
.collect();
|
||||
let logs: Vec<&Message> = shown
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Notification(n) if n.method == LogMessage::METHOD))
|
||||
.collect();
|
||||
assert_eq!(popups.len(), 1, "one popup for two stranded includes: {popups:#?}");
|
||||
assert_eq!(logs.len(), 2, "both are logged: {logs:#?}");
|
||||
}
|
||||
|
||||
/// One `workspace/didRenameFiles` for `from` → `to`.
|
||||
fn did_rename(session: &mut Session, from: &Path, to: &Path) {
|
||||
session.notify(
|
||||
DidRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{
|
||||
"oldUri": path_to_uri(from).expect("uri"),
|
||||
"newUri": path_to_uri(to).expect("uri"),
|
||||
}] }),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_notification_rebuilds_the_index() {
|
||||
let tree = Tree::new("didrename");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert_eq!(indexed(&session, "a"), 1, "premise: indexed under its old name");
|
||||
|
||||
std::fs::rename(tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")).expect("rename");
|
||||
did_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv"));
|
||||
assert_eq!(indexed(&session, "a"), 1, "still one package, found at its new path");
|
||||
|
||||
// And the same nudge from the watcher for the same move changes
|
||||
// nothing: the rebuild is a re-read of the tree, not an increment.
|
||||
session.watched(&[tree.path.join("rtl/b.sv")]);
|
||||
assert_eq!(indexed(&session, "a"), 1, "reindexing twice is harmless");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_notification_rebuilds_the_index() {
|
||||
let tree = Tree::new("diddelete");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/gone.sv", "gone_pkg");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert_eq!(indexed(&session, "gone_pkg"), 1, "premise: indexed");
|
||||
|
||||
std::fs::remove_file(tree.path.join("rtl/gone.sv")).expect("remove");
|
||||
session.notify(
|
||||
DidDeleteFiles::METHOD,
|
||||
serde_json::json!({ "files": [
|
||||
{ "uri": path_to_uri(&tree.path.join("rtl/gone.sv")).expect("uri") },
|
||||
] }),
|
||||
);
|
||||
assert_eq!(indexed(&session, "gone_pkg"), 0, "gone from the index too");
|
||||
assert_eq!(indexed(&session, "a"), 1, "and the rest survives");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_operation_notification_for_nothing_the_index_reads_costs_no_rebuild() {
|
||||
let tree = Tree::new("didrenamestray");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
|
||||
|
||||
did_rename(&mut session, &tree.path.join("README.md"), &tree.path.join("READ.md"));
|
||||
session.notify(
|
||||
DidDeleteFiles::METHOD,
|
||||
serde_json::json!({ "files": [
|
||||
{ "uri": path_to_uri(&tree.path.join("notes.txt")).expect("uri") },
|
||||
] }),
|
||||
);
|
||||
assert_eq!(session.publishes(), 0, "neither is a path the index reads");
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
//! Workspace folders (2026-08-27) and the scope a `didOpen` widens.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// workspace folders (2026-08-27)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A `workspace/didChangeWorkspaceFolders` event, as a client sends it.
|
||||
fn folder_event(added: &[&Path], removed: &[&Path]) -> Value {
|
||||
let folders = |paths: &[&Path]| -> Vec<Value> {
|
||||
paths
|
||||
.iter()
|
||||
.map(|path| {
|
||||
serde_json::json!({
|
||||
"uri": path_to_uri(path).expect("uri"),
|
||||
"name": path.file_name().and_then(|n| n.to_str()).unwrap_or("folder"),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
serde_json::json!({ "event": { "added": folders(added), "removed": folders(removed) } })
|
||||
}
|
||||
|
||||
fn folders_changed(session: &mut Session, added: &[&Path], removed: &[&Path]) {
|
||||
session.notify(DidChangeWorkspaceFolders::METHOD, folder_event(added, removed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_didopen_rebuilds_exactly_when_it_widens_the_scope() {
|
||||
// Superseded this round (index-scope, 2026-08-27): the test that stood
|
||||
// here — `a_rootless_session_gaining_its_first_folder_flips_didopen_
|
||||
// from_reindex_to_publish` — pinned `didOpen`'s *root*-conditional,
|
||||
// rootless reindexing and rooted publishing. Rung 3 is now the default
|
||||
// rung with a root as well, so the root set is not the question any
|
||||
// more; the question is whether the file just opened brought a folder
|
||||
// the index does not cover, and this is the same case list under the
|
||||
// rule that replaced it. The pinned property is strictly stronger: it
|
||||
// holds in a rootless session and in a rooted one, and it is the same
|
||||
// one line of code for both.
|
||||
let outside = Tree::new("didopenscopeoutside");
|
||||
outside.package("a.sv", "a");
|
||||
let folder = Tree::new("didopenscopefolder");
|
||||
folder.package("rtl/b.sv", "b");
|
||||
folder.package("rtl/beside.sv", "beside");
|
||||
|
||||
let mut session = Session::new(Vec::new(), false);
|
||||
assert!(!session.server.workspace.has_roots(), "premise: rootless");
|
||||
|
||||
// `generation` counts a buffer's text *and* the index, so an open that
|
||||
// widens is `set_document`'s bump plus `reindex`'s own — two.
|
||||
let before = session.server.generation;
|
||||
let _ =
|
||||
session.open(&outside.path.join("a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(session.server.generation, before + 2, "a new folder widens by reindexing");
|
||||
|
||||
folders_changed(&mut session, &[&folder.path], &[]);
|
||||
assert!(session.server.workspace.has_roots(), "the workspace now has a root");
|
||||
|
||||
// A root does not make the scope wide: this file's folder has still
|
||||
// never been opened from, so it widens and rebuilds exactly as the
|
||||
// rootless one did.
|
||||
let after_folder = session.server.generation;
|
||||
let uri = session
|
||||
.open(&folder.path.join("rtl/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
after_folder + 2,
|
||||
"a folder outside the scope widens it, root or no root"
|
||||
);
|
||||
assert_eq!(indexed(&session, "b"), 1, "and the widened scope really was scanned");
|
||||
assert!(session.published().iter().any(|p| p.uri == uri), "and it is published too");
|
||||
|
||||
// The second file in a folder already in scope costs only
|
||||
// `set_document`'s bump: nothing about which files exist moved.
|
||||
let quiet = session.server.generation;
|
||||
let uri = session.open(
|
||||
&folder.path.join("rtl/beside.sv"),
|
||||
"package beside;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
quiet + 1,
|
||||
"a file the scope already covers must not cost a rescan"
|
||||
);
|
||||
assert!(
|
||||
session.published().iter().any(|p| p.uri == uri),
|
||||
"it is still published, just not rescanned"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
|
||||
// The chooser, as a table. Everything but "grew and lost nothing"
|
||||
// falls back to the whole rescan, which is always a correct answer.
|
||||
let a = PathBuf::from("/w/a");
|
||||
let b = PathBuf::from("/w/b");
|
||||
let c = PathBuf::from("/w/c");
|
||||
let all = [a.clone(), b.clone(), c.clone()];
|
||||
|
||||
assert_eq!(widen_of(&[], &[]), Widen::Nothing, "a scope that never moved");
|
||||
assert_eq!(
|
||||
widen_of(&all, &all),
|
||||
Widen::Nothing,
|
||||
"and one an open buffer could not widen — a filelist or the wide rung, both empty"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(std::slice::from_ref(&a), &[a.clone(), b.clone()]),
|
||||
Widen::Added(vec![b.clone()]),
|
||||
"one folder added: only that folder is indexed"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(&[], &all),
|
||||
Widen::Added(all.to_vec()),
|
||||
"the first open of a session adds every directory it has"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(std::slice::from_ref(&b), &[a.clone(), b.clone(), c.clone()]),
|
||||
Widen::Added(vec![a.clone(), c.clone()]),
|
||||
"two added around one held: both, and never the held one"
|
||||
);
|
||||
// The `scopeDepth: 2` shape `performance_take2.md` §5b measured: the
|
||||
// newly opened file raises to a directory that *contains* one already
|
||||
// in scope. The contained directory is still in `after` — every opened
|
||||
// directory is raised on its own and none of them is ever dropped — so
|
||||
// this is an add like any other, and the widen's own file diff is what
|
||||
// stops the overlap being read twice
|
||||
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
|
||||
let ip = PathBuf::from("/w");
|
||||
assert_eq!(
|
||||
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
|
||||
Widen::Added(vec![ip]),
|
||||
"a folder that subsumes the old scope is an add, not a removal"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(&[a.clone(), b.clone()], std::slice::from_ref(&a)),
|
||||
Widen::Whole,
|
||||
"a directory that left is not an add: the whole rescan settles what went with it"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(&[a.clone(), b.clone()], &[a, c]),
|
||||
Widen::Whole,
|
||||
"and a swap is a removal too, however many arrived beside it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_didopen_widen_leaves_the_index_a_whole_rescan_would_have_left() {
|
||||
// The round's claim, through the real dispatch: two jumps into two new
|
||||
// folders, each answered by indexing only that folder, and the tables
|
||||
// that come out are the ones a whole rescan produces — asked by
|
||||
// running that rescan afterwards and comparing.
|
||||
let tree = Tree::new("didopenwidenequal");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/a2.sv", "a2");
|
||||
tree.package("lib/b.sv", "b");
|
||||
tree.package("lib/b2.sv", "b2");
|
||||
tree.package("tb/c.sv", "c");
|
||||
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let _ =
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let _ =
|
||||
session.open(&tree.path.join("lib/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
|
||||
let _ =
|
||||
session.open(&tree.path.join("tb/c.sv"), "package c;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(session.server.workspace.index().files().len(), 5, "all three folders");
|
||||
assert_eq!(indexed(&session, "b2"), 1, "including files nobody opened");
|
||||
|
||||
let widened = session.server.workspace.index().fingerprint();
|
||||
let words = session.server.workspace.candidates().words("").to_vec();
|
||||
let includes = session.server.workspace.includes().fingerprint();
|
||||
session.server.workspace.rebuild_index();
|
||||
assert_eq!(widened, session.server.workspace.index().fingerprint(), "index");
|
||||
assert_eq!(words, session.server.workspace.candidates().words(""), "completion words");
|
||||
assert_eq!(includes, session.server.workspace.includes().fingerprint(), "include graph");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_asked_for_mid_scan_defers_to_one_whole_rescan_behind_it() {
|
||||
// A widen answered while a scan runs cannot fold itself in: that scan
|
||||
// holds a work list taken from the *old* scope, so folding a widen
|
||||
// into it would make "which files exist" mean two things inside one
|
||||
// scan. It sets the same `rescan_wanted` flag every other mid-scan
|
||||
// trigger sets — one more whole scan after this one, coalesced with
|
||||
// whatever else asked (`docs/features/scan-interleave/README.md`).
|
||||
//
|
||||
// Driven directly rather than over the wire, because the wire cannot
|
||||
// reach it in one step: a widen itself never drains the queue, and the
|
||||
// startup scan under the folder scope indexes nothing and so never
|
||||
// interleaves. The reachable route is a `didOpen` answered inside a
|
||||
// long *whole* rescan, which is this flag and this call.
|
||||
let tree = Tree::new("widenmidscan");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("lib/late.sv", "late");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
// The shipped depth is 2 since 2026-08-28, which would have `lib/` in
|
||||
// scope before the widen this test is about — so the premise names the
|
||||
// narrow depth rather than assuming it.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "index": { "scopeDepth": 0 } } } }),
|
||||
);
|
||||
let _ =
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(indexed(&session, "a"), 1, "premise: the first folder is in scope");
|
||||
|
||||
session.server.scanning = true;
|
||||
session.server.reindex_widened(vec![tree.path.join("lib")]);
|
||||
assert!(session.server.rescan_wanted, "the widen was deferred, not run inside the scan");
|
||||
assert_eq!(indexed(&session, "late"), 0, "and nothing was folded into the running scan");
|
||||
|
||||
// What the running scan's own loop then does with the flag.
|
||||
session.server.scanning = false;
|
||||
let warnings = session.server.scan_until_settled(true);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert!(!session.server.rescan_wanted, "one more scan is all it was owed");
|
||||
// Not indexed, and correctly so: the deferred rescan is a *whole* one
|
||||
// over the scope as it now stands, and `lib/` entered that scope only
|
||||
// because a buffer was opened from it — which this test never did.
|
||||
assert_eq!(indexed(&session, "late"), 0, "the scope itself did not move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol() {
|
||||
// The whole point: "Add Folder to Workspace" used to change nothing
|
||||
// until the editor was restarted.
|
||||
let first = Tree::new("folderadd");
|
||||
first.package("rtl/a.sv", "a");
|
||||
let second = Tree::new("folderaddsecond");
|
||||
second.package("rtl/b.sv", "b");
|
||||
|
||||
let mut session = Session::wide(vec![first.path.clone()], false);
|
||||
assert_eq!(indexed(&session, "b"), 0, "premise: the second folder is not open yet");
|
||||
|
||||
folders_changed(&mut session, &[&second.path], &[]);
|
||||
assert_eq!(indexed(&session, "b"), 1, "the added folder is scanned");
|
||||
assert_eq!(indexed(&session, "a"), 1, "and the one already open survives");
|
||||
|
||||
// And it is reachable through a real request, not only in the index.
|
||||
let hits = session.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query":"b"}));
|
||||
let found = hits.as_array().expect("a symbol list");
|
||||
assert!(
|
||||
found.iter().any(|hit| hit["location"]["uri"]
|
||||
.as_str()
|
||||
.is_some_and(|uri| uri.contains("folderaddsecond"))),
|
||||
"{found:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed() {
|
||||
// The client owns buffer lifecycle: closing a folder does not close
|
||||
// the editors that were open in it. Such a buffer keeps the deal
|
||||
// every rootless buffer has always had — it is still analyzed, still
|
||||
// published, and still overrides disk in the index.
|
||||
let first = Tree::new("folderremove");
|
||||
first.package("rtl/a.sv", "a");
|
||||
let second = Tree::new("folderremovesecond");
|
||||
second.package("rtl/open.sv", "open_pkg");
|
||||
second.package("rtl/other.sv", "other_pkg");
|
||||
|
||||
let mut session = Session::wide(vec![first.path.clone(), second.path.clone()], false);
|
||||
let uri = session.open(
|
||||
&second.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(indexed(&session, "other_pkg"), 1, "premise: the whole folder is indexed");
|
||||
|
||||
folders_changed(&mut session, &[], &[&second.path]);
|
||||
assert_eq!(indexed(&session, "other_pkg"), 0, "the folder's files left the index");
|
||||
assert_eq!(indexed(&session, "a"), 1, "the folder that stayed is untouched");
|
||||
assert_eq!(
|
||||
indexed(&session, "open_pkg"),
|
||||
1,
|
||||
"the open buffer contributes itself, as every out-of-scope buffer does"
|
||||
);
|
||||
|
||||
// The rebuild republished it, and an edit to it is still diagnosed.
|
||||
let published = session.published();
|
||||
assert!(published.iter().any(|p| p.uri == uri), "{published:#?}");
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }]),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1, "{published:#?}");
|
||||
assert_eq!(published[0].uri, uri);
|
||||
assert!(!published[0].diagnostics.is_empty(), "a broken buffer still reports");
|
||||
|
||||
// And closing it clears cleanly — the removed folder is not a special
|
||||
// case for `didClose`, which already sends an empty publish for
|
||||
// whatever buffer is named regardless of where it lived.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1, "{published:#?}");
|
||||
assert_eq!(published[0].uri, uri);
|
||||
assert!(published[0].diagnostics.is_empty(), "the close cleared it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_folder_notification_is_one_rescan_with_one_bar_and_one_generation() {
|
||||
// Everything a rescan owes rides inside `reindex()`; an event carries
|
||||
// both lists, so it must cost exactly one of each.
|
||||
let first = Tree::new("folderonce");
|
||||
first.package("rtl/a.sv", "a");
|
||||
let second = Tree::new("folderoncesecond");
|
||||
second.package("rtl/b.sv", "b");
|
||||
let third = Tree::new("folderoncethird");
|
||||
third.package("rtl/c.sv", "c");
|
||||
|
||||
let abilities =
|
||||
ClientAbilities { work_done_progress: true, code_lens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![first.path.clone(), second.path.clone()], abilities);
|
||||
session.open(&first.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let before = session.server.generation;
|
||||
let _ = session.drain();
|
||||
|
||||
// One notification that both adds and removes: two changes, one scan.
|
||||
folders_changed(&mut session, &[&third.path], &[&second.path]);
|
||||
assert_eq!(indexed(&session, "c"), 1, "the addition took");
|
||||
assert_eq!(indexed(&session, "b"), 0, "and so did the removal");
|
||||
assert_eq!(session.server.generation, before + 1, "one generation bump");
|
||||
|
||||
let messages = session.drain();
|
||||
let steps: Vec<&'static str> =
|
||||
messages.iter().cloned().filter_map(progress_step).map(|(step, _)| step).collect();
|
||||
// One bar, up and down — with a report for each of the two files the
|
||||
// new root set holds (`a.sv` and `c.sv`).
|
||||
assert_eq!(steps, vec!["create", "begin", "report", "report", "end"], "one bar");
|
||||
let publishes = messages
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Notification(n) if n.method == PublishDiagnostics::METHOD))
|
||||
.count();
|
||||
assert_eq!(publishes, 1, "the one open buffer is republished once");
|
||||
let refreshes = messages
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD))
|
||||
.count();
|
||||
assert_eq!(refreshes, 1, "the counts on screen were invalidated once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rapid_add_remove_add_of_the_same_folder_costs_three_rescans_and_ends_up_added() {
|
||||
// Three separate notifications, each of which genuinely moves the
|
||||
// root set (unlike the no-op shapes above), must cost three separate
|
||||
// rescans — `change_roots` has no batching across notifications, only
|
||||
// within one — and the state after must be consistent with the net
|
||||
// effect: two adds and one remove is "present".
|
||||
// QA (2026-08-27): "own shapes" case from the review checklist.
|
||||
let root = Tree::new("rapidflaproot");
|
||||
root.package("rtl/a.sv", "a");
|
||||
let flapping = Tree::new("rapidflapfolder");
|
||||
flapping.package("rtl/b.sv", "b");
|
||||
|
||||
let mut session = Session::wide(vec![root.path.clone()], false);
|
||||
let before = session.server.generation;
|
||||
|
||||
folders_changed(&mut session, &[&flapping.path], &[]);
|
||||
assert_eq!(indexed(&session, "b"), 1, "added");
|
||||
folders_changed(&mut session, &[], &[&flapping.path]);
|
||||
assert_eq!(indexed(&session, "b"), 0, "removed");
|
||||
folders_changed(&mut session, &[&flapping.path], &[]);
|
||||
assert_eq!(indexed(&session, "b"), 1, "added again");
|
||||
|
||||
assert_eq!(session.server.generation, before + 3, "one rescan per notification, three total");
|
||||
assert_eq!(indexed(&session, "a"), 1, "the folder that never moved is untouched throughout");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_event_that_moves_nothing_costs_nothing() {
|
||||
// Total and no-op-safe: every shape a client can send that leaves the
|
||||
// root set where it was must cost no rescan at all.
|
||||
let tree = Tree::new("foldernoop");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let before = session.server.generation;
|
||||
let _ = session.drain();
|
||||
|
||||
folders_changed(&mut session, &[], &[]);
|
||||
folders_changed(&mut session, &[&tree.path], &[]);
|
||||
folders_changed(&mut session, &[], &[&tree.path.join("never-added")]);
|
||||
folders_changed(&mut session, &[&tree.path], &[&tree.path]);
|
||||
// Params that do not parse at all, and a folder that is not a path.
|
||||
session.notify(DidChangeWorkspaceFolders::METHOD, serde_json::json!({ "nonsense": 1 }));
|
||||
session.notify(
|
||||
DidChangeWorkspaceFolders::METHOD,
|
||||
serde_json::json!({ "event": {
|
||||
"added": [{ "uri": "untitled:Untitled-1", "name": "scratch" }], "removed": [],
|
||||
} }),
|
||||
);
|
||||
|
||||
assert!(session.progress().is_empty(), "no rescan for any of them");
|
||||
assert_eq!(session.publishes(), 0, "and nothing was republished");
|
||||
assert_eq!(session.server.generation, before, "and no generation moved");
|
||||
assert_eq!(indexed(&session, "a"), 1, "the root itself survived every one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_change_re_registers_the_watchers_only_when_the_watched_path_moves() {
|
||||
// The source glob is workspace-wide — the client matches it against
|
||||
// whatever folders it holds, so a folder change needs no new
|
||||
// registration for it. The *filelist* watcher is an absolute path
|
||||
// anchored at the first root, so a folder change can move it without
|
||||
// anyone touching the setting.
|
||||
let first = Tree::new("folderwatch");
|
||||
first.package("rtl/a.sv", "a");
|
||||
first.write("files.f", "rtl/a.sv\n");
|
||||
let second = Tree::new("folderwatchsecond");
|
||||
second.package("rtl/b.sv", "b");
|
||||
second.write("files.f", "rtl/b.sv\n");
|
||||
|
||||
let mut session = Session::new(vec![first.path.clone()], true);
|
||||
let _ = session.drain();
|
||||
|
||||
// No filelist setting: nothing about the registration depends on the
|
||||
// roots, so adding a folder re-registers nothing.
|
||||
folders_changed(&mut session, &[&second.path], &[]);
|
||||
assert!(session.requests().is_empty(), "the source glob is workspace-wide");
|
||||
|
||||
// With a *relative* filelist the watched path is `<first root>/files.f`...
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
||||
let _ = session.drain();
|
||||
// ...so dropping that root moves it to the second folder's copy.
|
||||
folders_changed(&mut session, &[], &[&first.path]);
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 2, "{requests:#?}");
|
||||
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
|
||||
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
||||
assert_eq!(
|
||||
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
||||
second.path.join("files.f").to_str().expect("utf-8").to_string(),
|
||||
"{requests:#?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
//! `onTypeFormatting`, `rangesFormatting` and `willSaveWaitUntil`, through the real dispatch.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/onTypeFormatting`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One `onTypeFormatting` for a buffer: the character typed, and the
|
||||
/// position the client reports for the cursor after it.
|
||||
fn on_type(session: &mut Session, uri: &Uri, typed: &str, line: u32, character: u32) -> Value {
|
||||
on_type_with(session, uri, typed, line, character, serde_json::json!({}))
|
||||
}
|
||||
|
||||
fn on_type_with(
|
||||
session: &mut Session,
|
||||
uri: &Uri,
|
||||
typed: &str,
|
||||
line: u32,
|
||||
character: u32,
|
||||
options: Value,
|
||||
) -> Value {
|
||||
let mut all = serde_json::json!({ "tabSize": 2, "insertSpaces": true });
|
||||
if let (Some(all), Some(extra)) = (all.as_object_mut(), options.as_object()) {
|
||||
for (key, value) in extra {
|
||||
all.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
session.result(
|
||||
OnTypeFormatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
"ch": typed,
|
||||
"options": all,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_newline_re_indents_the_line_it_opened() {
|
||||
// The dispatch arm, end to end: a real request, decoded by the real
|
||||
// decoder, answered by the real handler.
|
||||
let tree = Tree::new("ontypenewline");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session
|
||||
.open(&tree.path.join("m.sv"), "module m;\n always_comb begin\n\n end\nendmodule\n");
|
||||
|
||||
let edits = on_type(&mut session, &uri, "\n", 2, 0);
|
||||
assert_eq!(edits[0]["newText"], " ", "{edits:#?}");
|
||||
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 2, "character": 0 }));
|
||||
assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 2, "character": 0 }));
|
||||
assert!(session.shown().is_empty(), "a keystroke says nothing to the user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_semicolon_lays_out_the_statement_through_the_range_engine() {
|
||||
let tree = Tree::new("ontypesemi");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let text = "module m;\n wire a;\n wire b;\nendmodule\n";
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
|
||||
let typed = on_type(&mut session, &uri, ";", 1, 11);
|
||||
assert_eq!(typed[0]["newText"], "module m;\n wire a;\n wire b;\nendmodule\n");
|
||||
// The same answer `textDocument/rangeFormatting` gives for that line,
|
||||
// byte for byte: this path is that request with a different trigger.
|
||||
let ranged = session.result(
|
||||
RangeFormatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": { "start": { "line": 1, "character": 0 },
|
||||
"end": { "line": 1, "character": 0 } },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
);
|
||||
assert_eq!(typed, ranged);
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/rangesFormatting` (LSP 3.18), through the real dispatch
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One LSP range, as a client writes it.
|
||||
fn json_range(sl: u32, sc: u32, el: u32, ec: u32) -> Value {
|
||||
serde_json::json!({
|
||||
"start": { "line": sl, "character": sc },
|
||||
"end": { "line": el, "character": ec },
|
||||
})
|
||||
}
|
||||
|
||||
fn ranges_result(session: &mut Session, uri: &Uri, ranges: Vec<Value>) -> Value {
|
||||
session.result(
|
||||
format::RANGES_FORMATTING,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"ranges": ranges,
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn range_result(session: &mut Session, uri: &Uri, range: Value) -> Value {
|
||||
session.result(
|
||||
RangeFormatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": range,
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Four items on four lines, so two ranges can straddle one they leave.
|
||||
const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
|
||||
// The dispatch arm, end to end: a real request with a real `ranges`
|
||||
// array, decoded by the hand-rolled params and answered by the real
|
||||
// handler. Lines 2 and 4, leaving line 3 exactly as written.
|
||||
let tree = Tree::new("rangesfmt");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
|
||||
let edits =
|
||||
ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0), json_range(3, 0, 4, 0)]);
|
||||
assert_eq!(
|
||||
edits[0]["newText"], "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n",
|
||||
"{edits:#?}"
|
||||
);
|
||||
// Still one whole-document edit, the shape `rangeFormatting` answers.
|
||||
assert_eq!(edits.as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 0 }));
|
||||
assert!(session.shown().is_empty(), "a clean config says nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_range_through_the_new_method_answers_what_the_old_method_answers() {
|
||||
// The two requests are the same engine, and a client must never have
|
||||
// to choose between them for correctness — only for round trips.
|
||||
let tree = Tree::new("rangesone");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
|
||||
for range in [
|
||||
json_range(1, 0, 2, 0),
|
||||
json_range(1, 4, 1, 4),
|
||||
json_range(0, 0, 99, 0),
|
||||
json_range(4, 0, 4, 9),
|
||||
] {
|
||||
let one = range_result(&mut session, &uri, range.clone());
|
||||
let many = ranges_result(&mut session, &uri, vec![range.clone()]);
|
||||
assert_eq!(one, many, "{range}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_ranges_array_is_answered_with_no_edit_and_no_word() {
|
||||
let tree = Tree::new("rangesempty");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
|
||||
assert_eq!(ranges_result(&mut session, &uri, vec![]), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "an empty ask is not a problem");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ranges_request_for_a_buffer_the_server_does_not_hold_is_null() {
|
||||
// What every other formatting handler answers for an unknown document.
|
||||
let tree = Tree::new("rangesunknown");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
assert_eq!(ranges_result(&mut session, &uri, vec![json_range(0, 0, 1, 0)]), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_is_the_same_answer_and_the_same_popup_on_both_range_methods() {
|
||||
// No partial output (CLAUDE.md invariant #1), and the multi-range path
|
||||
// reaches the *same* `edits()` — so the answer and the message must be
|
||||
// equal values, not merely similar shapes.
|
||||
let tree = Tree::new("rangesrefuse");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire ;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
let one = range_result(&mut session, &uri, json_range(0, 0, 1, 0));
|
||||
let said_once = session.shown();
|
||||
let many =
|
||||
ranges_result(&mut session, &uri, vec![json_range(0, 0, 1, 0), json_range(2, 0, 3, 0)]);
|
||||
let said_again = session.shown();
|
||||
|
||||
assert_eq!(one, serde_json::json!([]), "no edit at all");
|
||||
assert_eq!(one, many, "byte-identical answers");
|
||||
assert_eq!(said_once.len(), 1, "{said_once:?}");
|
||||
assert_eq!(said_once, said_again, "and byte-identical ERRORs: {said_again:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_config_warns_once_from_the_multi_range_path_too() {
|
||||
// It shares `warn_about_config` with the other explicit formatting
|
||||
// requests, dedup included — this is an explicit request the user made,
|
||||
// not a keystroke, so it does speak.
|
||||
let tree = Tree::new("rangesconfig");
|
||||
std::fs::write(tree.path.join(".git"), "gitdir: nowhere\n").expect("write .git");
|
||||
std::fs::write(tree.path.join("lucisv.toml"), "bogus = 1\n").expect("write config");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
let _ = session.drain();
|
||||
|
||||
let edits = ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0)]);
|
||||
assert_eq!(
|
||||
edits[0]["newText"],
|
||||
"module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"
|
||||
);
|
||||
let warned = session.shown();
|
||||
assert_eq!(warned.len(), 1, "{warned:?}");
|
||||
assert_eq!(warned[0].0, MessageType::WARNING);
|
||||
assert!(warned[0].1.contains("unknown key `bogus`"), "{warned:?}");
|
||||
// And once per buffer state, exactly as the other paths.
|
||||
let _ = ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0)]);
|
||||
assert!(session.shown().is_empty(), "said once, not once per request");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_that_do_not_carry_ranges_are_invalid_params_and_not_a_panic() {
|
||||
// The params are hand-rolled, so their refusal is ours to get right:
|
||||
// a missing `ranges` is a client bug and answers an error, never a
|
||||
// guess about what the client meant.
|
||||
let tree = Tree::new("rangesjunk");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
|
||||
let response = session.request(
|
||||
format::RANGES_FORMATTING,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
);
|
||||
let error = response.response_result.expect_err("missing `ranges` is not answerable");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::InvalidParams as i32, "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
|
||||
// The deliberate contrast with `textDocument/formatting` and the save
|
||||
// hook, both of which show an ERROR on a refusal. Mid-edit code the
|
||||
// engine declines is the *normal* case on a keystroke, and a modal the
|
||||
// user cannot type past would arrive on every semicolon.
|
||||
let tree = Tree::new("ontypequiet");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
|
||||
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
|
||||
// ...and the whole-document request on the same buffer still does say
|
||||
// something, so the silence is this path's decision and not a
|
||||
// regression in `edits()`.
|
||||
let _ = formatting_result(&mut session, &uri);
|
||||
assert_eq!(session.shown().len(), 1, "the explicit request still reports");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_config_is_never_reported_from_a_keystroke() {
|
||||
// `warn_about_config`'s dedup is cleared by `set_document`, and an
|
||||
// on-type request follows the `didChange` the user's own keystroke
|
||||
// produced — so warning here would mean one popup per character. The
|
||||
// user is told on their next explicit format instead.
|
||||
let tree = Tree::new("ontypeconfig");
|
||||
std::fs::write(tree.path.join(".git"), "gitdir: nowhere\n").expect("write .git");
|
||||
std::fs::write(tree.path.join("lucisv.toml"), "bogus = 1\n").expect("write config");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\n wire a;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
for _ in 0..3 {
|
||||
let edits = on_type(&mut session, &uri, "\n", 1, 0);
|
||||
assert_eq!(edits[0]["newText"], " ", "it still formats with the defaults");
|
||||
assert!(session.shown().is_empty(), "and still says nothing");
|
||||
}
|
||||
// The explicit request is where the user hears about it.
|
||||
let _ = formatting_result(&mut session, &uri);
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:?}");
|
||||
assert!(shown[0].1.contains("unknown key `bogus`"), "{shown:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keystroke_climbs_the_same_settings_ladder_a_manual_format_does() {
|
||||
// Unlike `willSaveWaitUntil`, this request carries `FormattingOptions`,
|
||||
// so the editor's own tab size is a rung — outranked by a pushed
|
||||
// `lucisv.indent`, exactly as `format::settings_for` documents.
|
||||
let tree = Tree::new("ontypesettings");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\n wire a;\nendmodule\n");
|
||||
|
||||
let tabbed = serde_json::json!({ "tabSize": 4 });
|
||||
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, tabbed.clone());
|
||||
assert_eq!(edits[0]["newText"], " ", "rung 3, the editor's tab size");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
|
||||
);
|
||||
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, tabbed);
|
||||
assert_eq!(edits[0]["newText"], " ", "rung 2 outranks it");
|
||||
|
||||
// Hard tabs are not a width this formatter can honour, so rung 3 drops
|
||||
// out entirely and the built-in default answers.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": {} } }),
|
||||
);
|
||||
let hard = serde_json::json!({ "tabSize": 4, "insertSpaces": false });
|
||||
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, hard);
|
||||
assert_eq!(edits[0]["newText"], " ", "never a tab, and never a guess");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keystroke_in_a_buffer_the_server_does_not_hold_answers_an_empty_array() {
|
||||
// `[]` rather than `null`: the protocol's answer for "no edits", and
|
||||
// what every other request on this path already returns.
|
||||
let tree = Tree::new("ontypeunopened");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
assert_eq!(on_type(&mut session, &uri, "\n", 1, 0), serde_json::json!([]));
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 0), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trigger_character_this_server_never_advertised_answers_nothing() {
|
||||
let tree = Tree::new("ontypeunknown");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
for typed in ["}", ")", "e"] {
|
||||
assert_eq!(on_type(&mut session, &uri, typed, 1, 11), serde_json::json!([]), "{typed}");
|
||||
}
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/willSaveWaitUntil`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The `lucisv.formatOnSave` push a client makes, on or off.
|
||||
fn format_on_save(on: bool) -> Value {
|
||||
serde_json::json!({ "settings": { "lucisv": { "formatOnSave": on } } })
|
||||
}
|
||||
|
||||
/// One `willSaveWaitUntil` for a buffer, for the reason given (1 = manual,
|
||||
/// 2 = after delay, 3 = focus out).
|
||||
fn will_save(session: &mut Session, uri: &Uri, reason: u8) -> Value {
|
||||
session.result(
|
||||
WillSaveWaitUntil::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "reason": reason }),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_hook_declines_until_format_on_save_is_pushed() {
|
||||
let tree = Tree::new("willsaveoff");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
|
||||
// The default: a client that never pushed the setting is answered
|
||||
// `null`, and told nothing at all.
|
||||
assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "off by default");
|
||||
assert!(session.shown().is_empty(), "a decline is silent");
|
||||
|
||||
// Pushed on, mid-session, with no restart.
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let edits = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(edits[0]["newText"], "module m;\n wire a;\nendmodule\n", "{edits:#?}");
|
||||
|
||||
// And off again: the hook goes back to declining.
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(false));
|
||||
assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "turned back off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggling_format_on_save_neither_rescans_nor_bumps_the_generation() {
|
||||
// QA (2026-08-26): `lucisv.formatOnSave` is read afresh by every save,
|
||||
// like `indent`/`lineLength` already are by every format — it must not
|
||||
// cost a re-walk of the workspace, and (since a rescan is what bumps
|
||||
// it) must not move the generation counter a pull-diagnostics client's
|
||||
// `resultId` is stamped with either. `only_an_exclude_change_asks_for_a_rescan`
|
||||
// (state.rs) pins the same thing one layer down; this pins it through
|
||||
// the real notification handler.
|
||||
let tree = Tree::new("willsavenoreindex");
|
||||
tree.package("kept.sv", "kept_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let before = session.server.generation;
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
assert_eq!(session.server.generation, before, "turning it on moved nothing");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(false));
|
||||
assert_eq!(session.server.generation, before, "turning it off moved nothing either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_hook_answers_exactly_what_the_formatting_request_answers() {
|
||||
// The whole contract: this is `textDocument/formatting` with a
|
||||
// different trigger, so the bytes must be identical — not merely
|
||||
// equivalent.
|
||||
let tree = Tree::new("willsavesame");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\n wire b;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
assert_eq!(will_save(&mut session, &uri, 1), formatting_result(&mut session, &uri));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_save_reason_is_a_save() {
|
||||
// Manual, after-delay and focus-out all format: the user asked for
|
||||
// their saves to be formatted, and all three write the file.
|
||||
let tree = Tree::new("willsavereason");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
for reason in [1, 2, 3] {
|
||||
let edits = will_save(&mut session, &uri, reason);
|
||||
assert_eq!(
|
||||
edits[0]["newText"], "module m;\n wire a;\nendmodule\n",
|
||||
"reason {reason}: {edits:#?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_hook_answers_null_for_a_buffer_it_does_not_hold() {
|
||||
// The request carries no text — the client has not written yet — so a
|
||||
// buffer the server never saw is one it cannot format.
|
||||
let tree = Tree::new("willsaveclosed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
assert_eq!(will_save(&mut session, &uri, 1), Value::Null);
|
||||
assert!(session.shown().is_empty(), "and nothing is said about it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_formatted_buffer_is_saved_with_no_edits() {
|
||||
// The same `[]` the formatting request gives for `Ok(None)`: an edit
|
||||
// that changes nothing still moves the cursor in some editors.
|
||||
let tree = Tree::new("willsaveclean");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let edits = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(edits, serde_json::json!([]), "{edits:#?}");
|
||||
assert_eq!(edits, formatting_result(&mut session, &uri), "the same as the request's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown() {
|
||||
// CLAUDE.md invariant #1 on the save path: no partial output, ever.
|
||||
// The message repeats per save on purpose — a save the user asked to
|
||||
// be formatted, that was not, is worth saying every time it happens.
|
||||
let tree = Tree::new("willsavebroken");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire ;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let _ = session.drain();
|
||||
|
||||
for save in 1..=2 {
|
||||
let edits = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(edits, serde_json::json!([]), "save {save}: no edit at all");
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "save {save}: {shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.starts_with("lucisv: cannot format — "), "{}", shown[0].1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do() {
|
||||
// The formatter's own idempotency, asserted through this path: the
|
||||
// buffer the client writes is a fixed point, so a save right after a
|
||||
// save cannot keep rewriting the file.
|
||||
let tree = Tree::new("willsaveidempotent");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session
|
||||
.open(&tree.path.join("m.sv"), "module m;\nwire a;\n assign a = 1;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
|
||||
let edits = will_save(&mut session, &uri, 1);
|
||||
let formatted = edits[0]["newText"].as_str().expect("newText").to_string();
|
||||
// The client applies the edit and writes; the buffer it holds is what
|
||||
// the next save asks about.
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }]));
|
||||
assert_eq!(buffer(&session, &uri), formatted);
|
||||
assert_eq!(will_save(&mut session, &uri, 1), serde_json::json!([]), "a fixed point");
|
||||
}
|
||||
|
||||
/// What `textDocument/formatting` answers for the given `tabSize`.
|
||||
fn formatting_with_tab_size(session: &mut Session, uri: &Uri, tab_size: u32) -> Value {
|
||||
session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": tab_size, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent() {
|
||||
// QA (2026-08-26): the documented gap in Assumptions/Handshakes,
|
||||
// constructed for real. No `lucisv.toml`, no `lucisv.indent` pushed,
|
||||
// and an editor whose tab size is 4: a manual format honors rung 3
|
||||
// (the editor's `tabSize`) and indents 4; the save hook has no rung 3
|
||||
// to consult at all and falls straight to the built-in default, 2.
|
||||
let tree = Tree::new("willsavetabgap");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
|
||||
let manual = formatting_with_tab_size(&mut session, &uri, 4);
|
||||
assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}");
|
||||
|
||||
let saved = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(saved[0]["newText"], "module m;\n wire a;\nendmodule\n", "{saved:#?}");
|
||||
assert_ne!(manual, saved, "the documented gap is real, not just written down");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lucisv_toml_erases_the_tab_size_gap() {
|
||||
// QA (2026-08-26): with a checked-in config, rung 1 outranks both the
|
||||
// editor's `tabSize` and the built-in default, so the two paths agree
|
||||
// exactly again — no `lucisv.toml`, and this would be the previous
|
||||
// test.
|
||||
let tree = Tree::new("willsavetabgapclosed");
|
||||
tree.write("lucisv.toml", "indent = 4\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
|
||||
// A wildly different editor tab size changes nothing: the config wins.
|
||||
let manual = formatting_with_tab_size(&mut session, &uri, 8);
|
||||
let saved = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}");
|
||||
assert_eq!(manual, saved, "the config makes the two paths agree exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_config_still_saves_with_defaults_and_warns_once() {
|
||||
// QA (2026-08-26): the interaction attack-surface 4 calls out —
|
||||
// `formatOnSave` on, the buffer itself fine, but `lucisv.toml` broken.
|
||||
// The save must not be sacrificed to a typo in a file the user is not
|
||||
// even editing: it formats with the built-in defaults, and the
|
||||
// warning follows the same per-file-change dedup a broken config
|
||||
// already gets everywhere else, so a save loop cannot turn it into
|
||||
// spam the way the formatter-refusal ERROR deliberately can.
|
||||
//
|
||||
// The buffer is already at the built-in default (2-space indent), so
|
||||
// neither save produces an edit and — crucially — neither save is
|
||||
// followed by the client-applies-the-edit `didChange` that would
|
||||
// itself re-arm the warning (`set_document` clears
|
||||
// `config_warnings`). That is what isolates the dedup this test is
|
||||
// actually about from the unrelated re-arming a *changed* buffer gets.
|
||||
let tree = Tree::new("willsavebrokenconfig");
|
||||
tree.write("lucisv.toml", "indent = 4\nbogus = 1\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let _ = session.drain();
|
||||
|
||||
let first = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(first, serde_json::json!([]), "the buffer needed no edit: {first:#?}");
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::WARNING);
|
||||
assert!(shown[0].1.contains("formatting with default settings"), "{}", shown[0].1);
|
||||
|
||||
// A second save of the same still-broken config, with nothing having
|
||||
// changed the buffer in between, says nothing new.
|
||||
let second = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(second, serde_json::json!([]), "{second:#?}");
|
||||
assert!(session.shown().is_empty(), "the warning does not repeat per save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save() {
|
||||
// QA (2026-08-26) finding, not a fix: `warn_about_config`'s dedup is
|
||||
// keyed on `set_document`, and `set_document` is exactly what runs
|
||||
// when the client applies a save hook's edit and the resulting
|
||||
// `didChange` reaches the server (see
|
||||
// `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`,
|
||||
// which does this on purpose to model the real sequence). So "warns
|
||||
// once" (Assumptions, work log) only holds once the buffer stops
|
||||
// needing edits — a save that *itself* reformats the buffer re-arms
|
||||
// the same warning for the very next save, because that save is
|
||||
// preceded by a `didChange` the dedup treats as a fresh state. Two
|
||||
// back-to-back saves of a buffer that needs reformatting under a
|
||||
// broken config warn twice, not once; the third (once the buffer is a
|
||||
// fixed point and no further `didChange` lands) is finally silent.
|
||||
// This is consistent with the doc comment on `warn_about_config`
|
||||
// ("once per change of a file") — it is the *save hook's own* prose
|
||||
// ("warns once") that does not spell out this edge, and a future
|
||||
// reader relying on literally one warning per broken config should
|
||||
// know better.
|
||||
let tree = Tree::new("willsavebrokenconfigrearm");
|
||||
tree.write("lucisv.toml", "indent = 4\nbogus = 1\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let _ = session.drain();
|
||||
|
||||
let first = will_save(&mut session, &uri, 1);
|
||||
let formatted = first[0]["newText"].as_str().expect("newText").to_string();
|
||||
assert_eq!(formatted, "module m;\n wire a;\nendmodule\n", "{first:#?}");
|
||||
assert_eq!(session.shown().len(), 1, "the first save warns");
|
||||
|
||||
// The client applies the edit and writes, exactly as
|
||||
// `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`
|
||||
// does — this is what re-arms the dedup.
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }]));
|
||||
let second = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(second, serde_json::json!([]), "already formatted: {second:#?}");
|
||||
assert_eq!(session.shown().len(), 1, "the second save warns again, not zero times");
|
||||
|
||||
// No further `didChange` follows a no-op save, so the third finally
|
||||
// stays quiet — the dedup this test is not disputing.
|
||||
let third = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(third, serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
//! The index rebuild as the client sees it: the persistent cache, the size cap, the per-file log, and one bar per rescan path.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A tree with one file the default cap would keep and one it would not.
|
||||
/// The big one is padded with a trailing comment, so what makes it big is
|
||||
/// not what makes it a package.
|
||||
fn oversized_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("rtl/keep.sv", "keep_pkg");
|
||||
let head = "package netlist_pkg;\n localparam K = 1;\nendpackage\n// ";
|
||||
let mut text = String::from(head);
|
||||
while text.len() < 4096 {
|
||||
text.push('x');
|
||||
}
|
||||
text.push('\n');
|
||||
tree.write("rtl/netlist.sv", &text);
|
||||
tree
|
||||
}
|
||||
|
||||
/// The `message` of every `$/progress` end in one drained batch, and every
|
||||
/// `window/logMessage` line in it. Read off one drain rather than through
|
||||
/// `Session::ended`/`logged`, because a test that wants both cannot drain
|
||||
/// twice.
|
||||
fn ends(messages: &[Message]) -> Vec<Option<String>> {
|
||||
messages
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams =
|
||||
serde_json::from_value(n.params.clone()).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
match work {
|
||||
WorkDoneProgress::End(end) => Some(end.message),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn log_lines(messages: &[Message]) -> Vec<String> {
|
||||
messages
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
let params: LogMessageParams =
|
||||
serde_json::from_value(n.params.clone()).expect("log params");
|
||||
Some(params.message)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_session_over_the_same_storage_folder_resumes_from_the_cache() {
|
||||
// The owner's case, end to end through the real dispatch: a session
|
||||
// indexes a tree, the editor goes away, and the next session over the
|
||||
// same storage folder gets the same index without parsing anything.
|
||||
let tree = Tree::new("resume");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
tree.package("rtl/b.sv", "b_pkg");
|
||||
let storage = Tree::new("resume_storage");
|
||||
let wide = ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut first = Session::started_in(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide.clone(),
|
||||
Some(storage.path.clone()),
|
||||
);
|
||||
let cold = first.drain();
|
||||
assert_eq!(ends(&cold), vec![Some("2 files indexed".to_string())], "a cold session");
|
||||
assert_eq!(
|
||||
log_lines(&cold).iter().filter(|line| line.starts_with("indexing: ")).count(),
|
||||
2,
|
||||
"both files were parsed: {:?}",
|
||||
log_lines(&cold)
|
||||
);
|
||||
let before = first.server.workspace.index().fingerprint();
|
||||
let answer = first.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"}));
|
||||
drop(first);
|
||||
|
||||
let mut second = Session::started_in(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide,
|
||||
Some(storage.path.clone()),
|
||||
);
|
||||
let warm = second.drain();
|
||||
assert_eq!(
|
||||
ends(&warm),
|
||||
vec![Some("2 files indexed, 2 from cache".to_string())],
|
||||
"the bar says where the files came from"
|
||||
);
|
||||
let lines = log_lines(&warm);
|
||||
assert_eq!(
|
||||
lines.iter().filter(|line| line.starts_with("cached: ")).count(),
|
||||
2,
|
||||
"and so does the log, file by file: {lines:?}"
|
||||
);
|
||||
assert!(
|
||||
!lines.iter().any(|line| line.starts_with("indexing: ")),
|
||||
"nothing was parsed: {lines:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
second.server.workspace.index().fingerprint(),
|
||||
before,
|
||||
"the same index, byte for byte"
|
||||
);
|
||||
assert_eq!(
|
||||
second.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"})),
|
||||
answer,
|
||||
"and the same answers over the wire"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_was_offered_no_storage_folder_keeps_its_index_in_memory() {
|
||||
// What every client but ours does, and what `smoke.js` does: no
|
||||
// `storagePath`, no workspace root to key an OS-directory store on,
|
||||
// so nothing is persisted and nothing is read — today's behaviour,
|
||||
// unchanged.
|
||||
let tree = Tree::new("nostorage");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let first = session.drain();
|
||||
assert_eq!(ends(&first), vec![Some("1 file indexed".to_string())]);
|
||||
assert!(
|
||||
log_lines(&first).iter().all(|line| !line.starts_with("cached: ")),
|
||||
"nothing can come from a cache that was never written: {:?}",
|
||||
log_lines(&first)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_message_names_what_the_cap_skipped() {
|
||||
// The count survives even when the per-file log is off, because it is
|
||||
// the only place a user who turned the log off would hear that part of
|
||||
// their workspace is not indexed.
|
||||
let tree = oversized_tree("capend");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())], "premise: no cap");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({
|
||||
"settings": {
|
||||
"lucisv": {
|
||||
"index": { "maxFileSize": 1024, "logFiles": false, "scope": "workspace" }
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
assert_eq!(
|
||||
session.ended(),
|
||||
vec![Some("1 file indexed, 1 skipped".to_string())],
|
||||
"the cap change rescanned, and the end message counts the skip"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capped_file_is_out_of_the_index_and_an_open_buffer_is_not() {
|
||||
let tree = oversized_tree("capserver");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.notify(DidChangeConfiguration::METHOD, capping(1024));
|
||||
assert_eq!(indexed(&session, "netlist_pkg"), 0, "the big file is not indexed");
|
||||
assert_eq!(indexed(&session, "keep_pkg"), 1, "and the small one still is");
|
||||
|
||||
// Opening it is the user saying they want it: the buffer is indexed
|
||||
// whatever the cap says.
|
||||
let text = std::fs::read_to_string(tree.path.join("rtl/netlist.sv")).expect("read");
|
||||
session.open(&tree.path.join("rtl/netlist.sv"), &text);
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": path_to_uri(&tree.path.join("rtl/netlist.sv")).expect("uri") }
|
||||
}),
|
||||
);
|
||||
assert_eq!(indexed(&session, "netlist_pkg"), 1, "an open buffer is exempt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_indexed_file_is_named_in_the_log_and_so_is_every_skip() {
|
||||
let tree = oversized_tree("caplog");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let _ = session.drain();
|
||||
session.notify(DidChangeConfiguration::METHOD, capping(1024));
|
||||
|
||||
let logged = session.logged();
|
||||
assert!(
|
||||
logged.iter().all(|(typ, _)| *typ == MessageType::LOG),
|
||||
"the file log is LOG, never a popup-worthy level: {logged:?}"
|
||||
);
|
||||
let lines: Vec<&String> = logged.iter().map(|(_, line)| line).collect();
|
||||
assert_eq!(
|
||||
lines.iter().filter(|l| l.starts_with("indexing: ")).count(),
|
||||
1,
|
||||
"one line per file parsed: {lines:?}"
|
||||
);
|
||||
assert!(
|
||||
lines.iter().any(|l| l.ends_with("rtl/keep.sv") && l.starts_with("indexing: ")),
|
||||
"named by full path: {lines:?}"
|
||||
);
|
||||
let skip = lines
|
||||
.iter()
|
||||
.find(|l| l.starts_with("skipped ("))
|
||||
.unwrap_or_else(|| panic!("a skip line: {lines:?}"));
|
||||
assert!(skip.contains("1.0 KiB cap"), "the cap it was measured against: {skip}");
|
||||
assert!(skip.contains("4.0 KiB >"), "and the size that broke it: {skip}");
|
||||
assert!(skip.ends_with("rtl/netlist.sv"), "and the file it kept out: {skip}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_log_goes_quiet_when_the_setting_is_off() {
|
||||
let tree = oversized_tree("caplogoff");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let _ = session.drain();
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({
|
||||
"settings": {
|
||||
"lucisv": {
|
||||
"index": { "maxFileSize": 1024, "logFiles": false, "scope": "workspace" }
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
let logged = session.logged();
|
||||
assert!(logged.is_empty(), "not one line, skips included: {logged:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_log_does_not_wait_for_a_progress_bar() {
|
||||
// The two features are independent: the log is a `window/logMessage`,
|
||||
// which every client gets, and the bar is gated on a capability.
|
||||
let tree = Tree::new("caplognobar");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let session = Session::wide(vec![tree.path.clone()], false);
|
||||
// One drain, both questions: `Session::drain` consumes.
|
||||
let messages = session.drain();
|
||||
assert!(
|
||||
messages.iter().cloned().filter_map(progress_step).next().is_none(),
|
||||
"premise: no bar for this client"
|
||||
);
|
||||
let logged: Vec<String> = messages
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
let params: LogMessageParams =
|
||||
serde_json::from_value(n.params).expect("log message params");
|
||||
Some(params.message)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(logged.len(), 1, "{logged:?}");
|
||||
assert!(logged[0].starts_with("indexing: "), "{logged:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_cap_rescans_and_a_new_log_setting_does_not() {
|
||||
// `lucisv.index.maxFileSize` changes which files exist, so it costs a
|
||||
// rescan exactly as `exclude` does; `logFiles` changes nothing but the
|
||||
// narration of the next one.
|
||||
let tree = Tree::new("caprescan");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let _ = session.drain();
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, capping(4096));
|
||||
assert_eq!(session.progress().len(), 4, "create, begin, one report, end");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, capping(4096));
|
||||
assert!(session.progress().is_empty(), "the same cap again buys nothing");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({
|
||||
"settings": {
|
||||
"lucisv": {
|
||||
"index": { "maxFileSize": 4096, "logFiles": false, "scope": "workspace" }
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
assert!(session.progress().is_empty(), "and neither does turning the log off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_index_scope_or_depth_rescans_through_the_real_dispatch() {
|
||||
// The other two settings that change which files exist. Driven through
|
||||
// `didChangeConfiguration` rather than `set_client_settings`, because
|
||||
// the parser, the change test and the rescan are three separate places
|
||||
// a scope setting could be dropped.
|
||||
let tree = Tree::new("scoperescan");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("include/defs.sv", "defs_pkg");
|
||||
let scoped = |scope: &str, depth: u32| {
|
||||
serde_json::json!({
|
||||
"settings": { "lucisv": { "index": { "scope": scope, "scopeDepth": depth } } }
|
||||
})
|
||||
};
|
||||
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
// The shipped depth is 2 since 2026-08-28, which already reaches the
|
||||
// sibling folder — so the narrow premise this test raises the depth
|
||||
// *from* is asked for out loud.
|
||||
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 0));
|
||||
let uri = session.open(
|
||||
&tree.path.join("rtl/a.sv"),
|
||||
"package a;\n localparam K = 1;\n\
|
||||
endpackage\n",
|
||||
);
|
||||
let _ = (uri, session.drain());
|
||||
assert_eq!(indexed(&session, "defs_pkg"), 0, "premise: the sibling folder is out of scope");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
|
||||
assert_eq!(session.progress().len(), 5, "create, begin, two reports, end");
|
||||
assert_eq!(indexed(&session, "defs_pkg"), 1, "one level up reaches the sibling folder");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
|
||||
assert!(session.progress().is_empty(), "the same depth again buys nothing");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, scoped("workspace", 1));
|
||||
assert!(!session.progress().is_empty(), "and a new scope does");
|
||||
assert_eq!(indexed(&session, "defs_pkg"), 1, "the whole workspace, now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_names_the_open_file_before_the_rest_of_the_scope() {
|
||||
// The progress half of the open-first ordering: the file the user is
|
||||
// waiting on is `1/N`, not wherever its name happens to sort. The
|
||||
// index it produces is identical either way — that is pinned in
|
||||
// `state.rs` and in `vlog_semantic`, because it is a property of the
|
||||
// builder rather than of the bar.
|
||||
let tree = Tree::new("scopeorderbar");
|
||||
tree.package("rtl/a_first.sv", "a_first");
|
||||
tree.package("rtl/m_open.sv", "m_open");
|
||||
tree.package("rtl/z_last.sv", "z_last");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/m_open.sv"), "package m_open;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
// A whole rescan, since that is what has a bar to name files on: a
|
||||
// save of one held file takes the incremental path now
|
||||
// (incremental-index, 2026-08-27).
|
||||
session.watched(&[tree.path.join("rtl/a_first.sv"), tree.path.join("rtl/z_last.sv")]);
|
||||
let named: Vec<Option<String>> =
|
||||
session.reported().into_iter().map(|(message, _)| message).collect();
|
||||
assert_eq!(
|
||||
named,
|
||||
vec![
|
||||
Some("1/3 m_open.sv".to_string()),
|
||||
Some("2/3 a_first.sv".to_string()),
|
||||
Some("3/3 z_last.sv".to_string()),
|
||||
],
|
||||
"the open buffer first, then path order"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all() {
|
||||
// The spec forbids server-initiated progress without the capability,
|
||||
// so this is not a cosmetic difference: it is a protocol violation
|
||||
// avoided.
|
||||
let tree = Tree::new("progressnone");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
assert!(session.progress().is_empty(), "not even at startup");
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert!(session.progress().is_empty(), "and not on a save either");
|
||||
// The watcher registration is the only thing such a client is asked.
|
||||
let session = Session::new(vec![tree.path.clone()], false);
|
||||
assert!(session.requests().is_empty(), "nothing at all is asked of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rescan_path_gets_its_own_bar_and_its_own_token() {
|
||||
// The three non-startup callers of the *whole* `reindex`: a save of a
|
||||
// file the index does not hold, a watcher event naming more than one
|
||||
// file, and a changed scope. One begin/end pair each, and no token
|
||||
// twice. (Superseded this round: the first two used to be a plain save
|
||||
// and a one-file watcher event, both of which take the incremental
|
||||
// path now and put no bar up at all.)
|
||||
let tree = Tree::new("progresspaths");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
let fresh = tree.path.join("rtl/c.sv");
|
||||
tree.package("rtl/c.sv", "c");
|
||||
let fresh_uri = crate::uri::path_to_uri(&fresh).expect("uri");
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": fresh_uri } }),
|
||||
);
|
||||
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
|
||||
);
|
||||
|
||||
let steps = session.progress();
|
||||
let begins: Vec<&String> =
|
||||
steps.iter().filter(|(step, _)| *step == "begin").map(|(_, token)| token).collect();
|
||||
let ends: Vec<&String> =
|
||||
steps.iter().filter(|(step, _)| *step == "end").map(|(_, token)| token).collect();
|
||||
assert_eq!(begins, vec!["lucisv-index-1", "lucisv-index-2", "lucisv-index-3"], "{steps:#?}");
|
||||
assert_eq!(ends, begins, "every bar that went up came down");
|
||||
// Superseded this round: there *are* reports now, and every one of
|
||||
// them belongs to a bar that is up. What must never happen is a
|
||||
// report on a token whose `end` has already gone out.
|
||||
let mut open: Option<&String> = None;
|
||||
for (step, token) in &steps {
|
||||
match *step {
|
||||
"begin" => open = Some(token),
|
||||
"report" => {
|
||||
assert_eq!(open, Some(token), "a report outside its own bar: {steps:#?}")
|
||||
}
|
||||
"end" => open = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit() {
|
||||
// Both request kinds are in flight at once. The progress answers —
|
||||
// one `Ok`, one `Err` — must fall straight through `response`, and the
|
||||
// one `applyEdit` answer must still be the one that speaks.
|
||||
let abilities =
|
||||
ClientAbilities { apply_edit: true, work_done_progress: true, ..Default::default() };
|
||||
let (tree, mut session, params) = propagating("progressapplyedit", abilities);
|
||||
let _ = session.drain();
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert!(result.is_null(), "the edit was pushed, not returned");
|
||||
|
||||
// Force a *whole* rescan while the edit is outstanding, so a progress
|
||||
// create sits between the push and its answer. Two files, because one
|
||||
// takes the incremental path and puts no bar up
|
||||
// (incremental-index, 2026-08-27).
|
||||
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
||||
let sent = session.sent();
|
||||
let edit =
|
||||
sent.iter().find(|request| request.method == ApplyWorkspaceEdit::METHOD).expect("the push");
|
||||
let creates: Vec<&Request> =
|
||||
sent.iter().filter(|r| r.method == WorkDoneProgressCreate::METHOD).collect();
|
||||
assert_eq!(creates.len(), 1, "one rescan, one create: {sent:#?}");
|
||||
|
||||
// Answer the create both ways a client can, then refuse the edit.
|
||||
session.answer(creates[0].id.clone(), serde_json::json!(null));
|
||||
session.server.response(Response::new_err(
|
||||
creates[0].id.clone(),
|
||||
lsp_server::ErrorCode::MethodNotFound as i32,
|
||||
"no progress here".to_string(),
|
||||
));
|
||||
assert!(session.shown().is_empty(), "a create answer says nothing to the user");
|
||||
|
||||
session.answer(edit.id.clone(), serde_json::json!({ "applied": false }));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains("lucisv.propagatePorts"), "{shown:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too() {
|
||||
// The reverse interleaving from the test above: here the outstanding
|
||||
// `applyEdit` is answered first, and the progress `create` for a
|
||||
// rescan that started while it was outstanding answers only after.
|
||||
// Same fall-through path in `response`, opposite arrival order — both
|
||||
// must leave the refusal-reporting untouched.
|
||||
let abilities =
|
||||
ClientAbilities { apply_edit: true, work_done_progress: true, ..Default::default() };
|
||||
let (tree, mut session, params) = propagating("progressapplyedit2", abilities);
|
||||
let _ = session.drain();
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert!(result.is_null(), "the edit was pushed, not returned");
|
||||
|
||||
// Two files, so the rescan is the whole one that puts a bar up.
|
||||
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
||||
let sent = session.sent();
|
||||
let edit =
|
||||
sent.iter().find(|request| request.method == ApplyWorkspaceEdit::METHOD).expect("the push");
|
||||
let create = sent
|
||||
.iter()
|
||||
.find(|request| request.method == WorkDoneProgressCreate::METHOD)
|
||||
.expect("the create");
|
||||
|
||||
// The edit resolves first, cleanly...
|
||||
session.answer(edit.id.clone(), serde_json::json!({ "applied": true }));
|
||||
assert!(session.shown().is_empty(), "an accepted edit says nothing to the user");
|
||||
|
||||
// ...and only afterward does the create answer arrive, for a bar that
|
||||
// came down long ago. It must still fall straight through.
|
||||
session.server.response(Response::new_ok(create.id.clone(), serde_json::json!(null)));
|
||||
assert!(session.shown().is_empty(), "a late create answer says nothing either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down() {
|
||||
// `Server::new` now asks a fully-capable client two things at
|
||||
// startup: the progress create/begin/end around `open_roots`, then
|
||||
// `register_watchers`. This pins the order the restructuring must
|
||||
// preserve — the watcher request must not land in the middle of the
|
||||
// bar it was rewritten to make room for.
|
||||
let tree = Tree::new("progressandwatchers");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let abilities =
|
||||
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
|
||||
let session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
|
||||
let order: Vec<String> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match &message {
|
||||
Message::Request(request) if request.method == RegisterCapability::METHOD => {
|
||||
Some("register".to_string())
|
||||
}
|
||||
_ => progress_step(message).map(|(step, _)| step.to_string()),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(order, vec!["create", "begin", "report", "end", "register"], "{order:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either() {
|
||||
// The existing off-test drives only startup and a save. `begin_indexing`
|
||||
// is called from the same `reindex()` on all three rescan triggers, but
|
||||
// the other two deserve their own witness rather than resting on that
|
||||
// being obvious from reading the code.
|
||||
let tree = Tree::new("progressnonewatch");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
let _ = session.drain();
|
||||
|
||||
session.watched(&[tree.path.join("rtl/a.sv")]);
|
||||
assert!(session.progress().is_empty(), "not on a watched file change");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
|
||||
);
|
||||
assert!(session.progress().is_empty(), "not on a changed filelist either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_crashing() {
|
||||
// No roots and no open buffers: `sibling_files` has nothing to walk,
|
||||
// so the index is empty. The end message must still be honest — and
|
||||
// the plural rule still holds, "0 files" and not "0 file".
|
||||
let session = Session::with(Vec::new(), watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("0 files indexed".to_string())]);
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
//! The large-file fast path (`docs/features/large-file-mode/README.md`).
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the large-file fast path (`docs/features/large-file-mode/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A session whose fast path starts at 100 bytes, so a test buffer can be
|
||||
/// three lines long instead of four megabytes.
|
||||
fn fast_path_settings() -> ClientSettings {
|
||||
ClientSettings { large_file_threshold: 100, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A source file that is real Verilog and over the test threshold.
|
||||
fn big_source() -> String {
|
||||
let mut text = String::from("module top;\n wire sig_a;\n");
|
||||
for i in 0..20 {
|
||||
text.push_str(&format!(" assign sig_a = w{i};\n"));
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
assert!(text.len() > 100, "the premise: over the test threshold");
|
||||
text
|
||||
}
|
||||
|
||||
/// A session with one large buffer open, and its URI.
|
||||
///
|
||||
/// Every call gets its own tree: this is the one `Tree::new` name shared
|
||||
/// by roughly a dozen tests (every large-file-mode test that does not
|
||||
/// need bespoke source text), which — unlike the rest of this module's
|
||||
/// trees, each named for the one test that uses it — would otherwise
|
||||
/// collide on the same `/tmp` directory under `cargo test`'s default
|
||||
/// parallelism and race each other's `remove_dir_all`/`create_dir_all`.
|
||||
/// The counter is what makes the shared literal safe to share.
|
||||
fn fast_path_session(abilities: ClientAbilities) -> (Tree, Session, Uri) {
|
||||
static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let tree = Tree::new(&format!("largefile{n}"));
|
||||
let path = tree.path.join("net.v");
|
||||
tree.write("net.v", &big_source());
|
||||
let mut session = Session::started(vec![tree.path.clone()], abilities, fast_path_settings());
|
||||
let uri = session.open(&path, &big_source());
|
||||
let _ = session.drain();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
/// The params a document-scoped request carries, at a position on the
|
||||
/// `sig_a` declaration.
|
||||
fn at_sig_a(uri: &Uri) -> Value {
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 1, "character": 9 },
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_over_the_threshold_opens_on_the_fast_path_and_says_so_once() {
|
||||
let (_tree, mut session, uri) = {
|
||||
let tree = Tree::new("largeannounce");
|
||||
let path = tree.path.join("net.v");
|
||||
tree.write("net.v", &big_source());
|
||||
let mut session = Session::started(
|
||||
vec![tree.path.clone()],
|
||||
ClientAbilities::default(),
|
||||
fast_path_settings(),
|
||||
);
|
||||
let uri = session.open(&path, &big_source());
|
||||
(tree, session, uri)
|
||||
};
|
||||
let lines: Vec<String> = session
|
||||
.logged()
|
||||
.into_iter()
|
||||
.map(|(_, message)| message)
|
||||
.filter(|message| message.contains("large-file fast path"))
|
||||
.collect();
|
||||
assert_eq!(lines.len(), 1, "once per entry into the mode: {lines:?}");
|
||||
assert!(lines[0].contains("net.v"), "{}", lines[0]);
|
||||
assert!(lines[0].contains("bytes"), "{}", lines[0]);
|
||||
|
||||
// A keystroke in it does not say it again.
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
!session.logged().iter().any(|(_, m)| m.contains("large-file fast path")),
|
||||
"the line is per entry, not per notification"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_buffer_is_diagnosed_as_empty_and_clears_what_it_left_behind() {
|
||||
let tree = Tree::new("largesquiggles");
|
||||
let path = tree.path.join("grow.v");
|
||||
let mut session =
|
||||
Session::started(vec![tree.path.clone()], ClientAbilities::default(), fast_path_settings());
|
||||
// Small and broken: a real diagnostic is drawn.
|
||||
let uri = session.open(&path, "module m;\n wire ;\nendmodule\n");
|
||||
let drawn = session.published();
|
||||
assert_eq!(drawn.len(), 1);
|
||||
assert!(!drawn[0].diagnostics.is_empty(), "premise: squiggles were drawn");
|
||||
|
||||
// The same buffer, edited past the threshold: one publish, empty, so
|
||||
// the squiggles go away rather than being left frozen on screen.
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }]),
|
||||
);
|
||||
let cleared = session.published();
|
||||
assert_eq!(cleared.len(), 1, "one publish, as every change makes");
|
||||
assert!(cleared[0].diagnostics.is_empty(), "and it is empty: {cleared:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_tokens_range_paints_a_large_buffer() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let data = session.result(
|
||||
SemanticTokensRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": 1, "character": 0 },
|
||||
"end": { "line": 3, "character": 0 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
let tokens = data["data"].as_array().expect("a token array").clone();
|
||||
assert!(!tokens.is_empty(), "the window was lexed: {data}");
|
||||
assert!(data["resultId"].is_null(), "a range answer is not delta material");
|
||||
// First token: `wire` on line 1, five numbers per token.
|
||||
assert_eq!(tokens.len() % 5, 0);
|
||||
assert_eq!(tokens[0], 1, "delta_line — the first line of the window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_tokens_full_is_declined_rather_than_answered_empty() {
|
||||
// The whole reason: VS Code marks a model whose document provider
|
||||
// answered *anything* as complete and never asks its range provider
|
||||
// again. An error leaves it incomplete, so the viewport keeps
|
||||
// painting. `serverCancelSupport` decides which code says so.
|
||||
let cancels = ClientAbilities { token_server_cancel: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = fast_path_session(cancels);
|
||||
let params = serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
for method in [SemanticTokensFullRequest::METHOD, SemanticTokensFullDeltaRequest::METHOD] {
|
||||
let mut params = params.clone();
|
||||
params["previousResultId"] = serde_json::json!("1");
|
||||
let error = session.request(method, params).response_result.expect_err("declined");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::ServerCancelled as i32, "{method}");
|
||||
assert!(error.message.contains("largeFile.threshold"), "{}", error.message);
|
||||
}
|
||||
|
||||
// A client that never advertised it gets the code every 3.16 client
|
||||
// already understands.
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let error = session
|
||||
.request(
|
||||
SemanticTokensFullRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
)
|
||||
.response_result
|
||||
.expect_err("declined");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::ContentModified as i32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatting_a_large_buffer_refuses_out_loud_and_edits_nothing() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let edits = session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
);
|
||||
assert_eq!(edits, serde_json::json!([]), "no edit, ever");
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "the user pressed a key and is owed a reason: {shown:?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains("largeFile.threshold"), "{}", shown[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_formatting_requests_the_user_did_not_press_stay_silent() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let edits = session.result(
|
||||
OnTypeFormatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 1, "character": 9 },
|
||||
"ch": ";",
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
);
|
||||
assert_eq!(edits, serde_json::json!([]));
|
||||
let saved = session.result(
|
||||
WillSaveWaitUntil::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "reason": 1 }),
|
||||
);
|
||||
assert_eq!(saved, Value::Null);
|
||||
assert!(session.shown().is_empty(), "neither fires on a key the user pressed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_is_refused_rather_than_applied_to_every_file_but_this_one() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
assert_eq!(
|
||||
session.result(PrepareRenameRequest::METHOD, at_sig_a(&uri)),
|
||||
Value::Null,
|
||||
"the box never opens"
|
||||
);
|
||||
let mut params = at_sig_a(&uri);
|
||||
params["newName"] = serde_json::json!("sig_b");
|
||||
let error = session.request(Rename::METHOD, params).response_result.expect_err("refused");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
|
||||
assert!(error.message.contains("largeFile.threshold"), "{}", error.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_and_references_answer_from_one_scan_of_the_buffer() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
// The cursor is on the `sig_a` of `wire sig_a;`, and every `sig_a` in
|
||||
// the file is one answer.
|
||||
let found = session.result(GotoDefinition::METHOD, at_sig_a(&uri));
|
||||
let locations = found.as_array().expect("an array");
|
||||
assert_eq!(locations.len(), 1, "{found}");
|
||||
assert_eq!(locations[0]["range"]["start"]["line"], 1);
|
||||
assert_eq!(locations[0]["uri"].as_str(), Some(uri.as_str()));
|
||||
|
||||
let mut params = at_sig_a(&uri);
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
||||
let all = session.result(References::METHOD, params.clone());
|
||||
assert_eq!(all.as_array().expect("an array").len(), 21, "the wire and its 20 uses");
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": false });
|
||||
let uses = session.result(References::METHOD, params);
|
||||
assert_eq!(uses.as_array().expect("an array").len(), 20, "minus the declaration");
|
||||
}
|
||||
|
||||
/// **The dispatch table.** Every document-scoped request, and what a
|
||||
/// buffer on the fast path answers it. The point is that the list is
|
||||
/// complete and pinned: a handler added later that reads a large buffer's
|
||||
/// *text* will fail here rather than in a user's editor.
|
||||
#[test]
|
||||
fn every_other_request_a_large_buffer_gets_answers_nothing_at_all() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let document = serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
let position = at_sig_a(&uri);
|
||||
let range = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": 0, "character": 0 },
|
||||
"end": { "line": 3, "character": 0 },
|
||||
},
|
||||
});
|
||||
let empty = serde_json::json!([]);
|
||||
// (method, params, expected answer)
|
||||
let table: Vec<(&str, Value, Value)> = vec![
|
||||
(HoverRequest::METHOD, position.clone(), Value::Null),
|
||||
(GotoTypeDefinition::METHOD, position.clone(), empty.clone()),
|
||||
(LinkedEditingRange::METHOD, position.clone(), Value::Null),
|
||||
(DocumentLinkRequest::METHOD, document.clone(), empty.clone()),
|
||||
(DocumentHighlightRequest::METHOD, position.clone(), Value::Null),
|
||||
(FoldingRangeRequest::METHOD, document.clone(), empty.clone()),
|
||||
(DocumentSymbolRequest::METHOD, document.clone(), empty.clone()),
|
||||
(CodeLensRequest::METHOD, document.clone(), empty.clone()),
|
||||
(InlayHintRequest::METHOD, range.clone(), empty.clone()),
|
||||
(
|
||||
CodeActionRequest::METHOD,
|
||||
{
|
||||
let mut params = range.clone();
|
||||
params["context"] = serde_json::json!({ "diagnostics": [] });
|
||||
params
|
||||
},
|
||||
empty.clone(),
|
||||
),
|
||||
(Completion::METHOD, position.clone(), Value::Null),
|
||||
(SignatureHelpRequest::METHOD, position.clone(), Value::Null),
|
||||
(
|
||||
InlineCompletionRequest::METHOD,
|
||||
{
|
||||
let mut params = position.clone();
|
||||
params["context"] =
|
||||
serde_json::json!({ "triggerKind": 2, "selectedCompletionInfo": null });
|
||||
params
|
||||
},
|
||||
Value::Null,
|
||||
),
|
||||
(CallHierarchyPrepare::METHOD, position.clone(), Value::Null),
|
||||
(TypeHierarchyPrepare::METHOD, position.clone(), Value::Null),
|
||||
// The one custom method: an object with both lists empty, which is
|
||||
// what "this buffer has no scopes" already looks like.
|
||||
(
|
||||
pairs::SCOPE_PAIRS_METHOD,
|
||||
document.clone(),
|
||||
serde_json::json!({ "pairs": [], "unmatched": [] }),
|
||||
),
|
||||
];
|
||||
for (method, params, expected) in table {
|
||||
assert_eq!(session.result(method, params), expected, "{method}");
|
||||
}
|
||||
// `selectionRange` is the one request that answers something: the
|
||||
// whole document is a legal expand-selection step even with nothing
|
||||
// parsed, and it costs one span.
|
||||
let mut selection = document.clone();
|
||||
selection["positions"] = serde_json::json!([{ "line": 1, "character": 9 }]);
|
||||
let chain = session.result(SelectionRangeRequest::METHOD, selection);
|
||||
assert_eq!(chain.as_array().expect("one chain per position").len(), 1);
|
||||
assert!(chain[0]["parent"].is_null(), "one step, the file: {chain}");
|
||||
// Nothing above said a word to the user.
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer() {
|
||||
let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = fast_path_session(pulling);
|
||||
let report = session.result(
|
||||
DocumentDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert_eq!(report["items"], serde_json::json!([]), "{report}");
|
||||
}
|
||||
|
||||
/// `workspace/diagnostic` walks every open buffer (`workspace_report`
|
||||
/// above), a large one included — it is not skipped, it is present with
|
||||
/// an empty **full** report, the same answer `diagnostics::all` gives
|
||||
/// `textDocument/diagnostic`. Pinned because the workspace-scoped sweep is
|
||||
/// a different code path from the per-document one already covered by
|
||||
/// `a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer`.
|
||||
#[test]
|
||||
fn a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report() {
|
||||
let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = fast_path_session(pulling);
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 1, "{report:#?}");
|
||||
assert_eq!(items[0]["uri"].as_str(), Some(uri.as_str()));
|
||||
assert_eq!(items[0]["kind"], "full", "present, not skipped: {report:#?}");
|
||||
assert_eq!(items[0]["items"], serde_json::json!([]), "{report:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change() {
|
||||
let tree = Tree::new("largethreshold");
|
||||
let path = tree.path.join("net.v");
|
||||
tree.write("net.v", &big_source());
|
||||
// Default settings: the buffer is nowhere near 4 MiB, so it is
|
||||
// analyzed in full.
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&path, &big_source());
|
||||
assert!(!session.server.workspace.document(&uri).expect("open").large);
|
||||
|
||||
// Pushed. The buffer already open does not change mode on the spot —
|
||||
// the decision is taken where a document is built.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 100 } } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
|
||||
assert!(
|
||||
!session.server.workspace.document(&uri).expect("open").large,
|
||||
"the open buffer keeps the mode it was built in"
|
||||
);
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
session.server.workspace.document(&uri).expect("open").large,
|
||||
"and takes the fast path at its next change"
|
||||
);
|
||||
|
||||
// Pulled: the same value through the other door.
|
||||
let mut session = Session::with(
|
||||
vec![tree.path.clone()],
|
||||
ClientAbilities { configuration: true, ..Default::default() },
|
||||
);
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, serde_json::json!([{ "largeFile": { "threshold": 100 } }]));
|
||||
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
|
||||
let uri = session.open(&path, &big_source());
|
||||
assert!(session.server.workspace.document(&uri).expect("open").large);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_to_a_large_buffer_moves_its_lines_and_the_next_window_agrees() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
// Insert a line at the top. `sig_a`'s declaration moves from line 1
|
||||
// to line 2, which is only true if the line index was rebuilt.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{
|
||||
"range": {
|
||||
"start": { "line": 0, "character": 0 },
|
||||
"end": { "line": 0, "character": 0 },
|
||||
},
|
||||
"text": "// a new first line\n",
|
||||
}],
|
||||
}),
|
||||
);
|
||||
let data = session.result(
|
||||
SemanticTokensRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": 2, "character": 0 },
|
||||
"end": { "line": 3, "character": 0 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
let tokens = data["data"].as_array().expect("tokens");
|
||||
assert_eq!(tokens[0], 2, "the window's own line, after the insertion");
|
||||
let found = session.result(
|
||||
GotoDefinition::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 2, "character": 9 },
|
||||
}),
|
||||
);
|
||||
assert_eq!(found[0]["range"]["start"]["line"], 2, "{found}");
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
//! The `Server` tests: one file per feature, every one driven through the
|
||||
//! real `process_batch` against a scratch workspace on disk.
|
||||
//!
|
||||
//! This file is the harness — `Tree`, a workspace root removed on drop, and
|
||||
//! `Session`, a server on an in-memory connection whose every outgoing
|
||||
//! message can be read back — followed by the helpers more than one file
|
||||
//! uses. The sibling files are the sections the one big test module used to
|
||||
//! have, under the names they had; a helper used by one section only stayed
|
||||
//! with it.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
use lsp_server::{Notification, Request, Response};
|
||||
use lsp_types::notification::{
|
||||
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
|
||||
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _, Progress,
|
||||
PublishDiagnostics, ShowMessage,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeLensRefresh, CodeLensRequest,
|
||||
Completion, DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
|
||||
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
|
||||
GotoTypeDefinition, HoverRequest, InlayHintRequest, InlineCompletionRequest,
|
||||
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
|
||||
RegisterCapability, Rename, Request as _, SelectionRangeRequest,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
|
||||
ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, UnregisterCapability,
|
||||
WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceConfiguration,
|
||||
WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
DidChangeWatchedFilesParams, FileChangeType, FileEvent, LogMessageParams, MessageType,
|
||||
ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams,
|
||||
ShowMessageParams, WorkDoneProgress, WorkDoneProgressCreateParams,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::batch::{is_shutdown, widen_of, Widen};
|
||||
use super::progress::{reports, MAX_REPORTS};
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
|
||||
|
||||
mod apply_edit;
|
||||
mod cancel;
|
||||
mod file_ops;
|
||||
mod folders;
|
||||
mod formatting;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod settings;
|
||||
mod sync;
|
||||
mod tokens;
|
||||
mod watchers;
|
||||
|
||||
/// 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_watch_{}_{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
/// A package declaring one localparam, so the index can be asked
|
||||
/// whether this file was scanned at all.
|
||||
fn package(&self, rel: &str, name: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("parent");
|
||||
}
|
||||
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
|
||||
.expect("write");
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
std::fs::write(self.path.join(rel), text).expect("write");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// A real `Server` on an in-memory connection, plus the client end of it —
|
||||
/// so a test can drive a notification and read every message it produced.
|
||||
struct Session {
|
||||
server: Server,
|
||||
client: Connection,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn new(roots: Vec<PathBuf>, file_watching: bool) -> Session {
|
||||
Session::with(roots, ClientAbilities { file_watching, ..Default::default() })
|
||||
}
|
||||
|
||||
/// A session against a client that said exactly `abilities`.
|
||||
fn with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
|
||||
Session::started(roots, abilities, ClientSettings::default())
|
||||
}
|
||||
|
||||
/// A session whose client had already asked for
|
||||
/// `lucisv.index.scope: "workspace"` when the startup scan ran — the
|
||||
/// scope every session had before 2026-08-27.
|
||||
///
|
||||
/// Used by every test in this module whose subject is not the scope:
|
||||
/// they want their whole fixture tree indexed from the first bar, and
|
||||
/// saying so here keeps the folder scope from being a hidden variable
|
||||
/// in a test about a progress report or a rename. The folder scope's
|
||||
/// own behaviour is tested by the tests named in
|
||||
/// `docs/features/index-scope/README.md`.
|
||||
fn wide(roots: Vec<PathBuf>, file_watching: bool) -> Session {
|
||||
Session::wide_with(roots, ClientAbilities { file_watching, ..Default::default() })
|
||||
}
|
||||
|
||||
/// [`Session::wide`] against a client that said exactly `abilities`.
|
||||
fn wide_with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
|
||||
let wide = ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
};
|
||||
Session::started(roots, abilities, wide)
|
||||
}
|
||||
|
||||
fn started(
|
||||
roots: Vec<PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
settings: ClientSettings,
|
||||
) -> Session {
|
||||
Session::started_in(roots, abilities, settings, None)
|
||||
}
|
||||
|
||||
/// [`Session::started`] against a client that offered a storage
|
||||
/// folder — `initializationOptions.storagePath`, which is where the
|
||||
/// persistent index cache goes.
|
||||
fn started_in(
|
||||
roots: Vec<PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
settings: ClientSettings,
|
||||
storage: Option<PathBuf>,
|
||||
) -> Session {
|
||||
let (server_end, client) = Connection::memory();
|
||||
// Verbose off, which is how the server ships: every assertion in
|
||||
// this module counts the messages a session produces, and the
|
||||
// timing lines are tested where they are observable as protocol
|
||||
// traffic — `tests/e2e.rs`, against the real binary and its flag.
|
||||
let server =
|
||||
Server::started(server_end, roots, abilities, settings, storage, false, Vec::new());
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
/// [`Session::started`] against a client that had **already sent**
|
||||
/// `queued` when the server was built.
|
||||
///
|
||||
/// The opening burst of a real editor: `initialized` is answered by
|
||||
/// `initialize_finish`, and everything the client sent behind it is
|
||||
/// sitting on the transport before the startup scan takes its first
|
||||
/// file. That is the case
|
||||
/// `docs/features/scan-interleave/README.md` is about, and the only
|
||||
/// way to reach it is to put the messages there first.
|
||||
fn started_behind(
|
||||
roots: Vec<PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
settings: ClientSettings,
|
||||
on_the_wire: Vec<Message>,
|
||||
queued: Vec<Message>,
|
||||
) -> Session {
|
||||
let (server_end, client) = Connection::memory();
|
||||
// Anything that has to reach the *connection* rather than the
|
||||
// queue — an `exit`, which `handle_shutdown` reads for itself —
|
||||
// goes here, ahead of the forwarder ever starting.
|
||||
for message in on_the_wire {
|
||||
client.sender.send(message).expect("the client's wire traffic");
|
||||
}
|
||||
let server = Server::started(server_end, roots, abilities, settings, None, false, queued);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
fn notify(&mut self, method: &str, params: impl serde::Serialize) {
|
||||
self.server.notification(Notification::new(method.to_string(), params));
|
||||
}
|
||||
|
||||
/// Drive one request through the real dispatch, as the loop would.
|
||||
fn request(&mut self, method: &str, params: impl serde::Serialize) -> Response {
|
||||
let id = RequestId::from(format!("test-{method}"));
|
||||
self.server.request(Request::new(id, method.to_string(), params))
|
||||
}
|
||||
|
||||
/// A request's result, or the reason it was refused.
|
||||
fn result(&mut self, method: &str, params: impl serde::Serialize) -> Value {
|
||||
match self.request(method, params).response_result {
|
||||
Ok(value) => value,
|
||||
Err(error) => panic!("{method} failed: {error:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer the last request the server made of us.
|
||||
fn answer(&mut self, id: RequestId, result: impl serde::Serialize) {
|
||||
self.server.response(Response::new_ok(id, result));
|
||||
}
|
||||
|
||||
/// Everything the server has said since the last drain.
|
||||
fn drain(&self) -> Vec<Message> {
|
||||
self.client.receiver.try_iter().collect()
|
||||
}
|
||||
|
||||
/// The requests the server has made of the client, as (method, params).
|
||||
fn requests(&self) -> Vec<(String, Value)> {
|
||||
self.sent().into_iter().map(|request| (request.method, request.params)).collect()
|
||||
}
|
||||
|
||||
/// The requests the server has made of the client, ids included.
|
||||
fn sent(&self) -> Vec<Request> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Request(request) => Some(request),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every progress message since the last drain, in order, as
|
||||
/// (step, token) — one `create` per request, one `begin`/`report`/`end`
|
||||
/// per `$/progress`. Order and token are the whole protocol here.
|
||||
fn progress(&self) -> Vec<(&'static str, String)> {
|
||||
self.drain().into_iter().filter_map(progress_step).collect()
|
||||
}
|
||||
|
||||
/// The `message` on every `$/progress` end since the last drain.
|
||||
fn ended(&self) -> Vec<Option<String>> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams =
|
||||
serde_json::from_value(n.params).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
match work {
|
||||
WorkDoneProgress::End(end) => Some(end.message),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every `$/progress` report since the last drain, as
|
||||
/// (message, percentage) — what the bar was told to say and where to
|
||||
/// stand.
|
||||
fn reported(&self) -> Vec<(Option<String>, Option<u32>)> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams =
|
||||
serde_json::from_value(n.params).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
match work {
|
||||
WorkDoneProgress::Report(report) => {
|
||||
Some((report.message, report.percentage))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Everything the server logged since the last drain, as
|
||||
/// (type, message) — the client's output channel, in order.
|
||||
fn logged(&self) -> Vec<(MessageType, String)> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
let params: LogMessageParams =
|
||||
serde_json::from_value(n.params).expect("log message params");
|
||||
Some((params.typ, params.message))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the server showed the user since the last drain, as
|
||||
/// (type, message).
|
||||
fn shown(&self) -> Vec<(MessageType, String)> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == ShowMessage::METHOD => {
|
||||
let params: ShowMessageParams =
|
||||
serde_json::from_value(n.params).expect("show message params");
|
||||
Some((params.typ, params.message))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many diagnostics publishes the server pushed since the last
|
||||
/// drain. With exactly one open buffer this counts index rebuilds:
|
||||
/// `reindex` republishes every open document, once.
|
||||
fn publishes(&self) -> usize {
|
||||
self.drain()
|
||||
.iter()
|
||||
.filter(|message| match message {
|
||||
Message::Notification(n) => n.method == PublishDiagnostics::METHOD,
|
||||
_ => false,
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// The diagnostics the server pushed since the last drain.
|
||||
fn published(&self) -> Vec<PublishDiagnosticsParams> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == PublishDiagnostics::METHOD => {
|
||||
Some(serde_json::from_value(n.params).expect("publish params"))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn open(&mut self, path: &Path, text: &str) -> Uri {
|
||||
let uri = path_to_uri(path).expect("uri");
|
||||
self.notify(
|
||||
DidOpenTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog",
|
||||
"version": 1, "text": text,
|
||||
}
|
||||
}),
|
||||
);
|
||||
uri
|
||||
}
|
||||
|
||||
/// Drive one burst through the real loop body — the whole of `run`
|
||||
/// except the receiving — reporting whether the client shut us down.
|
||||
fn batch(&mut self, messages: Vec<Message>) -> bool {
|
||||
self.server.process_batch(messages).expect("the burst is handled")
|
||||
}
|
||||
|
||||
/// The responses the server sent since the last drain, in order.
|
||||
fn answers(&self) -> Vec<Response> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Response(response) => Some(response),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn watched(&mut self, paths: &[PathBuf]) {
|
||||
let changes: Vec<FileEvent> = paths
|
||||
.iter()
|
||||
.map(|path| FileEvent {
|
||||
uri: path_to_uri(path).expect("uri"),
|
||||
typ: FileChangeType::CHANGED,
|
||||
})
|
||||
.collect();
|
||||
self.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
|
||||
}
|
||||
}
|
||||
|
||||
/// One message's place in the progress protocol, or `None` when it is not
|
||||
/// progress at all.
|
||||
fn progress_step(message: Message) -> Option<(&'static str, String)> {
|
||||
match message {
|
||||
Message::Request(request) if request.method == WorkDoneProgressCreate::METHOD => {
|
||||
let params: WorkDoneProgressCreateParams =
|
||||
serde_json::from_value(request.params).expect("create params");
|
||||
Some(("create", token_text(¶ms.token)))
|
||||
}
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams = serde_json::from_value(n.params).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
let step = match work {
|
||||
WorkDoneProgress::Begin(_) => "begin",
|
||||
WorkDoneProgress::Report(_) => "report",
|
||||
WorkDoneProgress::End(_) => "end",
|
||||
};
|
||||
Some((step, token_text(¶ms.token)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn token_text(token: &ProgressToken) -> String {
|
||||
match token {
|
||||
ProgressToken::String(text) => text.clone(),
|
||||
ProgressToken::Number(number) => number.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A client that shows a progress bar and nothing else.
|
||||
fn watching_progress() -> ClientAbilities {
|
||||
ClientAbilities { work_done_progress: true, ..Default::default() }
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helpers more than one file uses
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
|
||||
|
||||
const TOP: &str = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
|
||||
|
||||
/// One `didChange`, carrying whatever changes were given. The flush at the
|
||||
/// end is the quiet-period timer firing: a test drives notifications one
|
||||
/// at a time, so the burst the loop would have coalesced never forms, and
|
||||
/// without this the buffer would sit dirty forever.
|
||||
fn change(session: &mut Session, uri: &Uri, version: u32, changes: Value) {
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": version },
|
||||
"contentChanges": changes,
|
||||
}),
|
||||
);
|
||||
session.server.flush_dirty();
|
||||
}
|
||||
|
||||
/// The text the server currently holds for a buffer — the newest applied
|
||||
/// text, which while a change sits dirty is the pending one.
|
||||
fn buffer(session: &Session, uri: &Uri) -> String {
|
||||
if let Some((_, text)) = session.server.dirty.iter().find(|(pending, _)| pending == uri) {
|
||||
return text.clone();
|
||||
}
|
||||
session.server.workspace.document(uri).expect("an open buffer").text.clone()
|
||||
}
|
||||
|
||||
/// A whole-buffer `didChange`, queued.
|
||||
fn changed(uri: &Uri, version: u32, text: &str) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": version },
|
||||
"contentChanges": [{ "text": text }],
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// The `didChangeConfiguration` push that sets the index size cap.
|
||||
///
|
||||
/// It carries `scope: "workspace"` because a push replaces *every*
|
||||
/// setting: a cap pushed on its own would take the index back to the
|
||||
/// folder scope in the same breath, which is not what a test about the cap
|
||||
/// is asking. Same reason `state.rs`'s `wide()` exists.
|
||||
fn capping(bytes: u64) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"settings": {
|
||||
"lucisv": { "index": { "maxFileSize": bytes, "scope": "workspace" } }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A client that pulls diagnostics rather than being pushed them.
|
||||
fn pulling() -> ClientAbilities {
|
||||
ClientAbilities { pull_diagnostics: true, ..Default::default() }
|
||||
}
|
||||
|
||||
fn document_pull(session: &mut Session, uri: &Uri, previous: Option<&str>) -> Value {
|
||||
session.result(
|
||||
DocumentDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultId": previous,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// How many times the index holds a package of this name.
|
||||
fn indexed(session: &Session, name: &str) -> usize {
|
||||
session.server.workspace.index().member(name, "K").len()
|
||||
}
|
||||
|
||||
/// A `lucisv.filelist` push, in the shape a client sends it.
|
||||
fn filelist_push(path: &str) -> Value {
|
||||
serde_json::json!({ "settings": { "lucisv": { "filelist": path } } })
|
||||
}
|
||||
|
||||
/// Settings a test uses when its subject is not the scope, spelled once.
|
||||
fn wide_ish() -> ClientSettings {
|
||||
ClientSettings { index_scope: crate::settings::IndexScope::Workspace, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A workspace holding `sub` and two instantiations of it, with `sub.sv`
|
||||
/// open — the shape every lens test below asks about.
|
||||
fn lens_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", "module sub;\nendmodule\n");
|
||||
tree.write("top.sv", "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
|
||||
tree
|
||||
}
|
||||
|
||||
/// A two-module workspace with `top.sv` open, and the arguments that ask
|
||||
/// for the one port its instantiation is missing.
|
||||
fn propagating(name: &str, abilities: ClientAbilities) -> (Tree, Session, Value) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
let _ = session.drain();
|
||||
let params = serde_json::json!({
|
||||
"command": ports::PROPAGATE_PORTS,
|
||||
"arguments": [uri, { "line": 2, "character": 6 }],
|
||||
});
|
||||
(tree, session, params)
|
||||
}
|
||||
|
||||
/// What `textDocument/formatting` answers for the same buffer, asking for
|
||||
/// the 2-space tab an editor defaults to — which is also the built-in
|
||||
/// indent, so the two paths resolve to the same settings.
|
||||
fn formatting_result(session: &mut Session, uri: &Uri) -> Value {
|
||||
session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// The id of the one outstanding `workspace/configuration`, and the params
|
||||
/// it went out with.
|
||||
fn configuration_request(session: &Session) -> (RequestId, Value) {
|
||||
let sent = session.sent();
|
||||
let asked: Vec<&Request> =
|
||||
sent.iter().filter(|r| r.method == WorkspaceConfiguration::METHOD).collect();
|
||||
assert_eq!(asked.len(), 1, "exactly one pull is outstanding: {sent:#?}");
|
||||
(asked[0].id.clone(), asked[0].params.clone())
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
//! The indexing bar: when it goes up, what it counts, when it comes down.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_startup_index_build_runs_under_the_first_bar() {
|
||||
// It is the slowest rescan of the session, and it happens after
|
||||
// `initialize_finish` — the earliest moment a server request is legal.
|
||||
let tree = Tree::new("progressstartup");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
// One `report` because the tree holds one file: the counting reports
|
||||
// this round added ride the same path the begin/end pair does.
|
||||
assert_eq!(
|
||||
session.progress(),
|
||||
vec![
|
||||
("create", "lucisv-index-0".to_string()),
|
||||
("begin", "lucisv-index-0".to_string()),
|
||||
("report", "lucisv-index-0".to_string()),
|
||||
("end", "lucisv-index-0".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_rescan_puts_a_bar_up_and_takes_it_down_again() {
|
||||
// Superseded this round (incremental-index, 2026-08-27):
|
||||
// `a_save_puts_a_bar_up_and_takes_it_down_again` pinned the bar on a
|
||||
// save, and a save of a file the index already holds is now one parse
|
||||
// on the incremental path — see
|
||||
// `a_one_file_save_costs_no_bar_and_no_log_line` below. The bar's own
|
||||
// rule is unchanged and is pinned here on a trigger that really does
|
||||
// rescan: two files changing at once.
|
||||
let tree = Tree::new("progresssave");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
||||
// One create, one begin, one report per file, one end — the rescan's
|
||||
// own token, not the startup one.
|
||||
assert_eq!(
|
||||
session.progress(),
|
||||
vec![
|
||||
("create", "lucisv-index-1".to_string()),
|
||||
("begin", "lucisv-index-1".to_string()),
|
||||
("report", "lucisv-index-1".to_string()),
|
||||
("report", "lucisv-index-1".to_string()),
|
||||
("end", "lucisv-index-1".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fast_path_is_taken_for_one_held_file_and_for_nothing_else() {
|
||||
// The trigger table, all four rows in one place. The bar is the tell:
|
||||
// a whole rescan puts one up, the incremental path never does.
|
||||
let tree = Tree::new("fastpathtable");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let uri =
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
// 1. A save naming one file the index holds — incremental.
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert!(session.progress().is_empty(), "one held file on a save is incremental");
|
||||
|
||||
// 2. One watched file — incremental too, same rule.
|
||||
session.watched(&[tree.path.join("rtl/a.sv")]);
|
||||
assert!(session.progress().is_empty(), "and one watched file is the same case");
|
||||
|
||||
// 3. Two files in one watcher event — the whole rescan.
|
||||
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
||||
assert!(!session.progress().is_empty(), "two files is a rescan");
|
||||
|
||||
// 4. A settings change that moves which files exist — the whole
|
||||
// rescan, whatever it names.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "exclude": ["rtl/b.sv"], "index": { "scope": "workspace" } } } }),
|
||||
);
|
||||
assert!(!session.progress().is_empty(), "a settings change is a rescan");
|
||||
|
||||
// 5. A save naming a file the index does not hold — the whole rescan,
|
||||
// which is how a new file gets in at all.
|
||||
let fresh = tree.path.join("rtl/c.sv");
|
||||
tree.package("rtl/c.sv", "c");
|
||||
let fresh_uri = crate::uri::path_to_uri(&fresh).expect("uri");
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": fresh_uri } }),
|
||||
);
|
||||
assert!(!session.progress().is_empty(), "a file the index does not hold is a rescan");
|
||||
assert_eq!(indexed(&session, "c"), 1, "and the new file is in the index after it");
|
||||
}
|
||||
|
||||
/// QA (incremental-index, 2026-08-27): the fast-path discipline under a
|
||||
/// burst. `process_batch` handles one message at a time
|
||||
/// (`for message in batch`), so two `didSave`s that arrive in the same
|
||||
/// burst are not coalesced into one rescan — each is its own notification,
|
||||
/// each independently names one held file, and each takes the incremental
|
||||
/// path on its own. Not a rebuild, and not a dropped update either.
|
||||
#[test]
|
||||
fn two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates() {
|
||||
let tree = Tree::new("batchtwosaves");
|
||||
tree.write("a.sv", "module a;\nendmodule\n");
|
||||
tree.write("sub.sv", "module sub;\nendmodule\n");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let uri_a = session.open(&tree.path.join("a.sv"), "module a;\nendmodule\n");
|
||||
let uri_sub = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
let before = session.server.generation;
|
||||
|
||||
let a_with_sub = "module a;\n sub u1 ();\nendmodule\n";
|
||||
let sub_v2 = "module sub;\n logic marker;\nendmodule\n";
|
||||
let save = |uri: &Uri, text: &str| {
|
||||
Message::Notification(Notification::new(
|
||||
DidSaveTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "text": text }),
|
||||
))
|
||||
};
|
||||
session.batch(vec![save(&uri_a, a_with_sub), save(&uri_sub, sub_v2)]);
|
||||
|
||||
assert!(session.progress().is_empty(), "neither save alone is a whole rescan");
|
||||
// Each save bumps the generation twice — once in `set_document` for
|
||||
// the buffer's own new text (every text change does that, save or
|
||||
// not), once in `reindex_one` for the fast-path update — so two saves
|
||||
// is four, not two and not one shared bump for the whole batch.
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
before + 4,
|
||||
"two independent fast-path updates, not one bump shared by the batch"
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.workspace.index().instantiations_of("sub").len(),
|
||||
1,
|
||||
"a.sv's edit reached the index"
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.workspace.candidates().words("marker").len(),
|
||||
1,
|
||||
"sub.sv's own edit reached the index too, not just a.sv's"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses() {
|
||||
// Everything the fast path keeps: a pulling client's cached
|
||||
// diagnostics are stale from here, and every lens a client is holding
|
||||
// may now read a different count.
|
||||
let tree = lens_tree("fastpathafter");
|
||||
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let uri = session
|
||||
.open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
let before = session.server.generation;
|
||||
|
||||
let one_site = "module top;\n sub u_a ();\nendmodule\n";
|
||||
std::fs::write(tree.path.join("top.sv"), one_site).expect("write");
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "text": one_site }),
|
||||
);
|
||||
assert!(session.server.generation > before, "the generation moved");
|
||||
let refreshes =
|
||||
session.sent().iter().filter(|request| request.method == CodeLensRefresh::METHOD).count();
|
||||
assert_eq!(refreshes, 1, "one refresh, as a whole rescan sends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_file_save_answers_from_the_file_it_saved() {
|
||||
// The point of the whole path: one file's edit really does reach the
|
||||
// index, and the rest of the workspace really is left alone.
|
||||
let tree = lens_tree("fastpathanswer");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let two_sites = "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n";
|
||||
let uri = session.open(&tree.path.join("top.sv"), two_sites);
|
||||
let _ = session.drain();
|
||||
assert_eq!(
|
||||
session.server.workspace.index().instantiations_of("sub").len(),
|
||||
2,
|
||||
"premise: top.sv instantiates `sub` twice"
|
||||
);
|
||||
|
||||
let emptied = "module top;\nendmodule\n";
|
||||
std::fs::write(tree.path.join("top.sv"), emptied).expect("write");
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "text": emptied }),
|
||||
);
|
||||
assert!(
|
||||
session.server.workspace.index().instantiations_of("sub").is_empty(),
|
||||
"the saved file's edges are gone"
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.workspace.index().units("sub").len(),
|
||||
1,
|
||||
"and sub.sv, which nothing named, is untouched"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_file_save_costs_no_bar_and_no_log_line() {
|
||||
// The fast path's whole visible protocol delta: a save that names one
|
||||
// file the index already holds does its work inside a frame, so there
|
||||
// is no bar to put up and no scan to narrate. What it does still do —
|
||||
// the generation bump and the code-lens refresh — is pinned by
|
||||
// `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
|
||||
let tree = Tree::new("progressonefile");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let abilities = ClientAbilities { work_done_progress: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert!(session.progress().is_empty(), "one file is not a scan to report");
|
||||
assert!(session.logged().is_empty(), "and not a scan to narrate either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_says_how_many_files_were_indexed() {
|
||||
// The one number this costs nothing to know: the index's own file
|
||||
// list. Anything richer would mean plumbing a count through
|
||||
// `rebuild_index`.
|
||||
let tree = Tree::new("progresscount");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())]);
|
||||
|
||||
let one = Tree::new("progresscountone");
|
||||
one.package("rtl/a.sv", "a");
|
||||
let session = Session::wide_with(vec![one.path.clone()], watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("1 file indexed".to_string())], "not `1 files`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_counts_the_files_as_it_goes() {
|
||||
// The whole of feature 2: how many of how many, which file, and a
|
||||
// percentage that was measured rather than guessed.
|
||||
let tree = Tree::new("progressreports");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
assert_eq!(
|
||||
session.reported(),
|
||||
vec![(Some("1/2 a.sv".to_string()), Some(50)), (Some("2/2 b.sv".to_string()), Some(100)),],
|
||||
"counts ascending, the file named, the percentage monotonic and ending at 100"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reports_thin_out_when_the_workspace_is_huge() {
|
||||
// A report per file is right for hundreds and wrong for tens of
|
||||
// thousands. Past `MAX_REPORTS` files they thin out — but the last
|
||||
// file always reports, so the bar always finishes where the work did.
|
||||
let tree = Tree::new("progressflood");
|
||||
let files = MAX_REPORTS + 100;
|
||||
for i in 0..files {
|
||||
tree.package(&format!("f{i:05}.sv",), &format!("p{i}"));
|
||||
}
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let reports = session.reported();
|
||||
assert!(reports.len() <= MAX_REPORTS, "{} reports for {files} files", reports.len());
|
||||
assert!(reports.len() > MAX_REPORTS / 2, "but not silence: {}", reports.len());
|
||||
|
||||
let percentages: Vec<u32> = reports.iter().filter_map(|(_, p)| *p).collect();
|
||||
assert_eq!(percentages.len(), reports.len(), "every report carries one");
|
||||
assert!(percentages.windows(2).all(|w| w[0] <= w[1]), "monotonic: {percentages:?}");
|
||||
assert_eq!(percentages.last(), Some(&100), "and it ends at 100");
|
||||
let last = reports.last().expect("a report").0.clone().expect("a message");
|
||||
assert!(last.starts_with(&format!("{files}/{files} ")), "the last file reports: {last}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_report_schedule_never_floods_and_never_stops_short() {
|
||||
// The rule itself, across both regimes and their boundary — cheaper to
|
||||
// check exhaustively here than to build 40,000 files.
|
||||
for total in [1, 2, 999, 1000, 1001, 1999, 2000, 12_345, 40_000] {
|
||||
let reporting: Vec<usize> = (0..total).filter(|d| reports(*d, total)).collect();
|
||||
assert!(!reporting.is_empty(), "{total} files must report something");
|
||||
assert!(reporting.len() <= MAX_REPORTS, "{total} files: {} reports", reporting.len());
|
||||
assert_eq!(
|
||||
reporting.last(),
|
||||
Some(&(total - 1)),
|
||||
"{total} files: the last file must report"
|
||||
);
|
||||
assert!(reporting.windows(2).all(|w| w[0] < w[1]), "{total}: strictly ascending");
|
||||
// The percentage a client sees only ever counts up, and lands on
|
||||
// 100 exactly once, at the end.
|
||||
let percentages: Vec<usize> = reporting.iter().map(|d| (d + 1) * 100 / total).collect();
|
||||
assert!(percentages.windows(2).all(|w| w[0] <= w[1]), "{total}: monotonic");
|
||||
assert_eq!(percentages.last(), Some(&100), "{total}: ends at 100");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_is_down_before_the_republish() {
|
||||
// Pinned because either order is defensible and a reader would
|
||||
// wonder: the bar names the *scan*, so it ends the moment the scan
|
||||
// returns — the republish that follows is per-open-buffer work the
|
||||
// user already pays on every keystroke.
|
||||
let tree = Tree::new("progressorder");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
// Two files at once, so this is a whole rescan and there is a bar to
|
||||
// order the republish against (incremental-index, 2026-08-27).
|
||||
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
||||
let order: Vec<String> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match &message {
|
||||
Message::Notification(n) if n.method == PublishDiagnostics::METHOD => {
|
||||
Some("publish".to_string())
|
||||
}
|
||||
_ => progress_step(message).map(|(step, _)| step.to_string()),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(order, vec!["create", "begin", "report", "report", "end", "publish"]);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Pull diagnostics (LSP 3.17): one client is never served both models.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// pull diagnostics
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A buffer with one parse error and one lint finding in it.
|
||||
const BROKEN: &str = "module m;\n\twire ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_pulling_client_is_never_pushed_diagnostics() {
|
||||
// Never both models for one client: the second set of squiggles would
|
||||
// arrive on a schedule the client did not choose.
|
||||
let tree = Tree::new("pullnopush");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let path = tree.path.join("m.sv");
|
||||
let uri = session.open(&path, BROKEN);
|
||||
assert_eq!(session.publishes(), 0, "`didOpen` pushed nothing");
|
||||
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": BROKEN }],
|
||||
}),
|
||||
);
|
||||
assert_eq!(session.publishes(), 0, "nor did a change");
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert_eq!(session.publishes(), 0, "nor a save's republish");
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert_eq!(session.publishes(), 0, "and the close clears nothing it never drew");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushing_client_keeps_being_pushed() {
|
||||
let tree = Tree::new("pushstays");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.open(&tree.path.join("m.sv"), BROKEN);
|
||||
assert_eq!(session.publishes(), 1, "unchanged from before this feature");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pull_is_full_once_and_unchanged_until_something_moves() {
|
||||
let tree = Tree::new("pullunchanged");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
|
||||
|
||||
let first = document_pull(&mut session, &uri, None);
|
||||
assert_eq!(first["kind"], "full");
|
||||
assert!(!first["items"].as_array().expect("items").is_empty(), "{first:#?}");
|
||||
let result_id = first["resultId"].as_str().expect("a result id").to_string();
|
||||
|
||||
let again = document_pull(&mut session, &uri, Some(&result_id));
|
||||
assert_eq!(again["kind"], "unchanged", "nothing moved: {again:#?}");
|
||||
assert_eq!(again["resultId"], serde_json::json!(result_id), "and it stays namable");
|
||||
|
||||
// A buffer change moves it.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": "module m;\n wire a;\nendmodule\n" }],
|
||||
}),
|
||||
);
|
||||
let after = document_pull(&mut session, &uri, Some(&result_id));
|
||||
assert_eq!(after["kind"], "full", "the buffer changed: {after:#?}");
|
||||
assert!(after["items"].as_array().expect("items").is_empty(), "and it is clean now");
|
||||
assert_ne!(after["resultId"], serde_json::json!(result_id), "a new stamp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_rebuild_moves_the_result_id_too() {
|
||||
// `inter_file_dependencies: true` is a promise: a save rebuilds the
|
||||
// index, and what the index says can change what a *different* buffer
|
||||
// reports. A stale "unchanged" there would be a wrong squiggle.
|
||||
let tree = Tree::new("pullreindex");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
|
||||
let stamp = document_pull(&mut session, &uri, None)["resultId"]
|
||||
.as_str()
|
||||
.expect("a result id")
|
||||
.to_string();
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
let after = document_pull(&mut session, &uri, Some(&stamp));
|
||||
assert_eq!(after["kind"], "full", "the index moved: {after:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pull_for_a_buffer_that_is_not_open_is_empty_rather_than_an_error() {
|
||||
let tree = Tree::new("pullclosed");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
let report = document_pull(&mut session, &uri, None);
|
||||
assert_eq!(report["kind"], "full");
|
||||
assert!(report["items"].as_array().expect("items").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_workspace_pull_reports_every_open_buffer_and_honours_its_stamps() {
|
||||
let tree = Tree::new("workspacepull");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let first = session.open(&tree.path.join("a.sv"), BROKEN);
|
||||
let second = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n");
|
||||
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items").clone();
|
||||
assert_eq!(items.len(), 2, "{report:#?}");
|
||||
assert!(items.iter().all(|item| item["kind"] == "full"), "{report:#?}");
|
||||
let uris: Vec<&str> = items.iter().map(|item| item["uri"].as_str().unwrap_or("")).collect();
|
||||
assert!(uris.contains(&first.as_str()) && uris.contains(&second.as_str()), "{uris:?}");
|
||||
let mut sorted = uris.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(uris, sorted, "URI order, so two pulls of one state read alike");
|
||||
let stamp = items[0]["resultId"].as_str().expect("a result id").to_string();
|
||||
|
||||
// Re-asked with what the client already holds, both come back unchanged.
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultIds": [
|
||||
{ "uri": first, "value": stamp },
|
||||
{ "uri": second, "value": stamp },
|
||||
],
|
||||
}),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 2);
|
||||
assert!(items.iter().all(|item| item["kind"] == "unchanged"), "{items:#?}");
|
||||
|
||||
// A stamp from another generation is not the one we hold.
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultIds": [{ "uri": first, "value": "0" }],
|
||||
}),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert!(items.iter().all(|item| item["kind"] == "full"), "{items:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_workspace_answers_a_well_formed_empty_report() {
|
||||
// QA attack: no open buffers at all — does `workspace/diagnostic`
|
||||
// still answer a well-formed (if empty) report, rather than an error
|
||||
// or a missing field?
|
||||
let tree = Tree::new("workspaceemptypull");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
||||
);
|
||||
assert_eq!(report["items"], serde_json::json!([]), "{report:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_previous_result_id_for_a_uri_that_is_since_closed_is_harmless() {
|
||||
// QA attack: the client's `previousResultIds` can name a document it
|
||||
// has since closed (it does not have to prune its own cache eagerly).
|
||||
// That URI is no longer among the open buffers `workspace_report`
|
||||
// walks, so it must simply be absent from the answer — not an error,
|
||||
// not a phantom entry.
|
||||
let tree = Tree::new("workspaceclosedstamp");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let first = session.open(&tree.path.join("a.sv"), BROKEN);
|
||||
let closed = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n");
|
||||
let stamp = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
||||
)["items"][0]["resultId"]
|
||||
.as_str()
|
||||
.expect("a result id")
|
||||
.to_string();
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": closed } }),
|
||||
);
|
||||
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultIds": [
|
||||
{ "uri": first, "value": stamp },
|
||||
{ "uri": closed, "value": stamp },
|
||||
],
|
||||
}),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 1, "the closed uri is gone, not phantom-reported: {items:#?}");
|
||||
assert_eq!(items[0]["uri"], first.as_str(), "{items:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_previous_result_id_for_a_uri_never_seen_is_ignored() {
|
||||
// QA attack: a `previousResultIds` entry naming a document this
|
||||
// server never opened (a client warm-starting from a stale cache, or
|
||||
// simply a typo'd uri) must not confuse the match-up for the uris
|
||||
// that *are* open.
|
||||
let tree = Tree::new("workspaceneverseenstamp");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let opened = session.open(&tree.path.join("a.sv"), BROKEN);
|
||||
let never_seen = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultIds": [{ "uri": never_seen, "value": "0" }],
|
||||
}),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 1, "{items:#?}");
|
||||
assert_eq!(items[0]["uri"], opened.as_str(), "{items:#?}");
|
||||
assert_eq!(items[0]["kind"], "full");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_models_say_exactly_the_same_thing_about_a_buffer() {
|
||||
// One computation, two deliveries. A second conversion path would be
|
||||
// a second set of off-by-one bugs.
|
||||
let tree = Tree::new("samediagnostics");
|
||||
let mut pushed = Session::new(vec![tree.path.clone()], false);
|
||||
pushed.open(&tree.path.join("m.sv"), BROKEN);
|
||||
let published = pushed.published();
|
||||
assert_eq!(published.len(), 1);
|
||||
|
||||
let mut pulled = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = pulled.open(&tree.path.join("m.sv"), BROKEN);
|
||||
let report = document_pull(&mut pulled, &uri, None);
|
||||
|
||||
assert_eq!(
|
||||
report["items"],
|
||||
serde_json::to_value(&published[0].diagnostics).expect("diagnostics"),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
//! Small document requests through the real dispatch: `selectionRange`, `linkedEditingRange`, `codeLens` and its command, the hierarchy view.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/selectionRange`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_selection_range_request_answers_one_chain_per_position() {
|
||||
let tree = Tree::new("selection");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
let result = session.result(
|
||||
SelectionRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"positions": [{ "line": 1, "character": 2 }, { "line": 0, "character": 0 }],
|
||||
}),
|
||||
);
|
||||
let chains = result.as_array().expect("one chain per position");
|
||||
assert_eq!(chains.len(), 2, "{result:#?}");
|
||||
assert!(chains[0]["parent"].is_object(), "the innermost step has a parent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_range_request_for_an_unopened_buffer_answers_null() {
|
||||
let tree = Tree::new("selectionclosed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
let result = session.result(
|
||||
SelectionRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"positions": [{ "line": 0, "character": 0 }],
|
||||
}),
|
||||
);
|
||||
assert_eq!(result, Value::Null);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/linkedEditingRange`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_linked_editing_request_answers_both_halves_of_a_closing_label() {
|
||||
let tree = Tree::new("linked");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule : m\n");
|
||||
// The cursor on the header name.
|
||||
let result = session.result(
|
||||
LinkedEditingRange::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": 7 },
|
||||
}),
|
||||
);
|
||||
let ranges = result["ranges"].as_array().expect("a range list").clone();
|
||||
assert_eq!(ranges.len(), 2, "{result:#?}");
|
||||
assert_eq!(ranges[0]["start"], serde_json::json!({ "line": 0, "character": 7 }));
|
||||
assert_eq!(ranges[1]["start"], serde_json::json!({ "line": 1, "character": 12 }));
|
||||
assert!(result["wordPattern"].is_string(), "the SV word pattern is sent: {result:#?}");
|
||||
|
||||
// A position on no name at all declines, rather than answering an
|
||||
// empty list.
|
||||
let nothing = session.result(
|
||||
LinkedEditingRange::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": 0 },
|
||||
}),
|
||||
);
|
||||
assert_eq!(nothing, Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_linked_editing_request_for_an_unopened_buffer_answers_null() {
|
||||
let tree = Tree::new("linkedclosed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
let result = session.result(
|
||||
LinkedEditingRange::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": 0 },
|
||||
}),
|
||||
);
|
||||
assert_eq!(result, Value::Null);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/codeLens`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_code_lens_request_counts_the_workspaces_instantiations() {
|
||||
let tree = lens_tree("lens");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let result = session
|
||||
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
let lenses = result.as_array().expect("a lens list").clone();
|
||||
assert_eq!(lenses.len(), 1, "{result:#?}");
|
||||
assert_eq!(lenses[0]["command"]["title"], "2 instantiations");
|
||||
assert_eq!(lenses[0]["command"]["command"], lens::SHOW_INSTANTIATIONS);
|
||||
assert_eq!(lenses[0]["command"]["arguments"], serde_json::json!(["sub"]));
|
||||
assert_eq!(lenses[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 7 }));
|
||||
assert!(lenses[0]["data"].is_null(), "nothing is left for a resolve");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_code_lens_request_for_an_unopened_buffer_answers_null() {
|
||||
let tree = lens_tree("lensclosed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
let result = session
|
||||
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert_eq!(result, Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_show_instantiations_command_answers_every_site() {
|
||||
let tree = lens_tree("lenscommand");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let result = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
|
||||
);
|
||||
let locations = result.as_array().expect("a location list").clone();
|
||||
assert_eq!(locations.len(), 2, "{result:#?}");
|
||||
assert!(locations[0]["uri"].as_str().expect("uri").ends_with("top.sv"));
|
||||
assert_eq!(locations[0]["range"]["start"], serde_json::json!({ "line": 1, "character": 2 }));
|
||||
assert_eq!(locations[1]["range"]["start"], serde_json::json!({ "line": 2, "character": 2 }));
|
||||
// Nothing was pushed: this client cannot be shown a document.
|
||||
assert!(session.requests().is_empty(), "no showDocument for a client without it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_show_instantiations_command_pushes_a_show_document_when_it_can() {
|
||||
let tree = lens_tree("lensshow");
|
||||
let abilities = ClientAbilities { show_document: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
let result = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
|
||||
);
|
||||
assert_eq!(result.as_array().expect("locations").len(), 2, "and still the whole list");
|
||||
let asked = session.requests();
|
||||
assert_eq!(asked.len(), 1, "{asked:#?}");
|
||||
assert_eq!(asked[0].0, ShowDocument::METHOD);
|
||||
assert!(asked[0].1["uri"].as_str().expect("uri").ends_with("top.sv"));
|
||||
assert_eq!(asked[0].1["selection"]["start"], serde_json::json!({ "line": 1, "character": 2 }));
|
||||
assert_eq!(asked[0].1["takeFocus"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_with_no_instantiations_pushes_nothing_and_shows_nothing() {
|
||||
let tree = Tree::new("lensempty");
|
||||
tree.write("lonely.sv", "module lonely;\nendmodule\n");
|
||||
let abilities = ClientAbilities { show_document: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("lonely.sv"), "module lonely;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
let result = session
|
||||
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert_eq!(result[0]["command"]["title"], "no instantiations");
|
||||
assert_eq!(result[0]["command"]["command"], "", "display-only");
|
||||
let empty = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["lonely"] }),
|
||||
);
|
||||
assert_eq!(empty, serde_json::json!([]));
|
||||
assert!(session.requests().is_empty(), "nothing to show, nothing pushed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_show_instantiations_command_declines_arguments_it_cannot_read() {
|
||||
let tree = lens_tree("lensbadargs");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let error = session
|
||||
.request(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS }),
|
||||
)
|
||||
.response_result
|
||||
.expect_err("declined");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
|
||||
assert!(error.message.contains("module name"), "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() {
|
||||
let tree = lens_tree("lensrefresh");
|
||||
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
assert!(session.requests().is_empty(), "nothing to refresh at startup: no buffer is open");
|
||||
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
// Every rescan trigger, one refresh each.
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
session.watched(&[tree.path.join("top.sv")]);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "exclude": ["nothing"] } } }),
|
||||
);
|
||||
let methods: Vec<String> = session.requests().into_iter().map(|(method, _)| method).collect();
|
||||
assert_eq!(
|
||||
methods,
|
||||
vec![CodeLensRefresh::METHOD; 3],
|
||||
"one per rescan, on the save, watched-file and config paths"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() {
|
||||
let tree = lens_tree("lensnorefresh");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
session.watched(&[tree.path.join("top.sv")]);
|
||||
assert!(session.requests().is_empty(), "silence, on every rescan path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hierarchy_view_gets_a_snapshot_and_one_notification_per_completed_index() {
|
||||
let tree = Tree::new("hierarchyviewrefresh");
|
||||
tree.write("sub.sv", "module sub; endmodule\n");
|
||||
tree.write("top.sv", "module top; sub u (); endmodule\n");
|
||||
let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
|
||||
let started: Vec<Value> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(notification)
|
||||
if notification.method == design_hierarchy::CHANGED_METHOD =>
|
||||
{
|
||||
Some(notification.params)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(started, [serde_json::json!({ "revision": 1 })]);
|
||||
|
||||
let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({}));
|
||||
assert_eq!(snapshot["revision"], 1);
|
||||
assert_eq!(snapshot["complete"], true);
|
||||
assert_eq!(snapshot["modules"].as_array().expect("modules").len(), 2);
|
||||
|
||||
tree.write("top.sv", "module top; sub renamed (); endmodule\n");
|
||||
session.watched(&[tree.path.join("top.sv")]);
|
||||
let changed: Vec<Value> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(notification)
|
||||
if notification.method == design_hierarchy::CHANGED_METHOD =>
|
||||
{
|
||||
Some(notification.params)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(changed, [serde_json::json!({ "revision": 2 })]);
|
||||
let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({}));
|
||||
assert_eq!(snapshot["revision"], 2);
|
||||
let top = snapshot["modules"]
|
||||
.as_array()
|
||||
.expect("modules")
|
||||
.iter()
|
||||
.find(|module| module["moduleName"] == "top")
|
||||
.expect("top");
|
||||
assert_eq!(top["instances"][0]["instanceName"], "renamed");
|
||||
}
|
||||
|
||||
/// `complete` says "this is the whole workspace", and the window it has to
|
||||
/// be honest about is the one between a finished scan and a rescan already
|
||||
/// asked for — where `scanning` alone is false over an index that is about
|
||||
/// to be rebuilt. Two answers, both pinned here: the flag itself is false,
|
||||
/// and the request does not reach it at all, because `must_wait` sets a
|
||||
/// request owed a rescan aside instead of answering it.
|
||||
#[test]
|
||||
fn a_snapshot_is_never_answered_complete_while_a_rescan_is_owed() {
|
||||
let tree = Tree::new("hierarchycomplete");
|
||||
tree.write("top.sv", "module top; endmodule\n");
|
||||
let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
session.drain();
|
||||
assert!(session.server.index_is_complete(), "settled: nothing is owed");
|
||||
assert_eq!(session.result(design_hierarchy::METHOD, serde_json::json!({}))["complete"], true);
|
||||
|
||||
session.server.rescan_wanted = true;
|
||||
assert!(!session.server.scanning, "premise: no scan is running this instant");
|
||||
assert!(!session.server.index_is_complete(), "but one is owed, so nothing is complete");
|
||||
|
||||
let request = Message::Request(Request::new(
|
||||
RequestId::from(99),
|
||||
design_hierarchy::METHOD.to_string(),
|
||||
serde_json::json!({}),
|
||||
));
|
||||
assert!(!session.batch(vec![request]));
|
||||
assert_eq!(session.server.held.len(), 1, "the snapshot waits for the rescan");
|
||||
assert!(session.answers().is_empty(), "nothing was answered off the stale index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_without_the_hierarchy_view_gets_no_custom_notifications() {
|
||||
let tree = Tree::new("nohierarchyviewrefresh");
|
||||
tree.write("top.sv", "module top; endmodule\n");
|
||||
let session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert!(session.drain().into_iter().all(|message| {
|
||||
!matches!(message, Message::Notification(notification)
|
||||
if notification.method == design_hierarchy::CHANGED_METHOD)
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_refresh_rides_after_the_indexing_bar_comes_down() {
|
||||
// The documented order: the bar names the scan, and the refresh is
|
||||
// work done on the scan's result — as the republishes are.
|
||||
let tree = lens_tree("lensorder");
|
||||
let abilities =
|
||||
ClientAbilities { code_lens_refresh: true, work_done_progress: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
// Two files at once, so this is a whole rescan and there is a bar for
|
||||
// the refresh to ride after (incremental-index, 2026-08-27); the
|
||||
// one-file path's own refresh is pinned in
|
||||
// `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
|
||||
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
||||
let order: Vec<String> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Request(request) if request.method == CodeLensRefresh::METHOD => {
|
||||
Some("refresh".to_string())
|
||||
}
|
||||
other => progress_step(other).map(|(step, _)| step.to_string()),
|
||||
})
|
||||
.collect();
|
||||
// Two files in `lens_tree`, so two reports between the begin and the
|
||||
// end; the refresh is still after all of them.
|
||||
assert_eq!(order, ["create", "begin", "report", "report", "end", "refresh"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() {
|
||||
// `refresh_code_lenses()` is called once in `reindex()`, before the
|
||||
// loop that republishes every open buffer's diagnostics — not once
|
||||
// per buffer that loop republishes. Two open buffers make that
|
||||
// distinction observable: a refresh-per-publish regression would
|
||||
// send two.
|
||||
let tree = lens_tree("qa_lensrefresh_multi");
|
||||
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
session
|
||||
.open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
let methods: Vec<String> = session.requests().into_iter().map(|(method, _)| method).collect();
|
||||
assert_eq!(methods, vec![CodeLensRefresh::METHOD], "one refresh, not one per open buffer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_showdocument_push_and_an_applyedit_push_stay_independent_when_both_are_outstanding() {
|
||||
// Both `deliver` (applyEdit) and `show_instantiations` (showDocument)
|
||||
// push a server-initiated request and rely on the same mechanism —
|
||||
// `response()` only reacts to an id it finds in `applying`, and only
|
||||
// `deliver` ever inserts one. Two requests outstanding at once, one of
|
||||
// each kind, must not cross-contaminate: a showDocument answer must
|
||||
// not be mistaken for the applyEdit one (or vice versa), whichever
|
||||
// order the client answers in.
|
||||
let tree = Tree::new("qa_interleave");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
let abilities = ClientAbilities { apply_edit: true, show_document: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let top_uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
session.open(&tree.path.join("sub.sv"), SUB);
|
||||
let _ = session.drain();
|
||||
|
||||
// First outstanding request: an applyEdit push from a port command.
|
||||
let propagate = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({
|
||||
"command": ports::PROPAGATE_PORTS,
|
||||
"arguments": [top_uri, { "line": 2, "character": 6 }],
|
||||
}),
|
||||
);
|
||||
assert_eq!(propagate, Value::Null);
|
||||
|
||||
// Second outstanding request: a showDocument push from the lens's
|
||||
// own command, over the same `sub` instantiation.
|
||||
let sites = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
|
||||
);
|
||||
assert_eq!(sites.as_array().expect("locations").len(), 1);
|
||||
|
||||
let sent = session.sent();
|
||||
assert_eq!(sent.len(), 2, "{sent:#?}");
|
||||
assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD);
|
||||
assert_eq!(sent[1].method, ShowDocument::METHOD);
|
||||
let apply_id = sent[0].id.clone();
|
||||
let show_id = sent[1].id.clone();
|
||||
|
||||
// Answer the showDocument push FIRST, out of send order — it carries
|
||||
// no `applied` field at all, so if `response()` ever matched it to
|
||||
// the applyEdit command by anything other than its own id, this would
|
||||
// either panic or wrongly report a failed edit.
|
||||
session.answer(show_id, serde_json::json!({ "success": true }));
|
||||
assert!(session.shown().is_empty(), "the showDocument answer must not be interpreted");
|
||||
|
||||
// Now answer the applyEdit push — a real success — and confirm it is
|
||||
// still routed correctly to its own command.
|
||||
session.answer(apply_id, serde_json::json!({ "applied": true }));
|
||||
assert!(session.shown().is_empty(), "a successful apply reports nothing");
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
//! A scan that answers messages while it runs (`docs/features/scan-interleave/README.md`).
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// a scan that answers messages while it runs
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A tree of `files` one-package files, plus one that names the last of
|
||||
/// them — enough files that a scan over it interleaves.
|
||||
fn workspace_of(tag: &str, files: usize) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
for n in 0..files {
|
||||
tree.package(&format!("p{n:03}.sv"), &format!("p{n:03}"));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
/// A `workspace/symbol` request over the wire, by id.
|
||||
fn symbol_request(id: i32, query: &str) -> Message {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(id),
|
||||
WorkspaceSymbolRequest::METHOD.to_string(),
|
||||
serde_json::json!({ "query": query }),
|
||||
))
|
||||
}
|
||||
|
||||
/// Where the indexing bar's `end` sits among everything the server said,
|
||||
/// and where the response to `id` sits. `None` for either if it never
|
||||
/// came.
|
||||
fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
|
||||
let ended = messages.iter().position(|message| {
|
||||
matches!(message, Message::Notification(n) if n.method == Progress::METHOD
|
||||
&& n.params["value"]["kind"] == "end")
|
||||
});
|
||||
let answered = messages
|
||||
.iter()
|
||||
.position(|message| matches!(message, Message::Response(r) if r.id == RequestId::from(id)));
|
||||
(ended, answered)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_the_client_had_already_sent_is_answered_during_the_startup_scan() {
|
||||
// The round's point, over the real dispatch: a request sitting on the
|
||||
// transport when the server is built used to wait for the whole
|
||||
// startup scan, because `Server::new` ran that scan before `run()`
|
||||
// took its first message. It is now answered *inside* the scan — the
|
||||
// response goes out before the bar comes down, which is the only
|
||||
// ordering a test can check without a stopwatch.
|
||||
let tree = workspace_of("interleaveanswer", INTERLEAVE_ABOVE + 6);
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![symbol_request(7, "p0")],
|
||||
);
|
||||
let said = session.drain();
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
let answered = answered.expect("the request is answered at all");
|
||||
let ended = ended.expect("the bar comes down");
|
||||
assert!(
|
||||
answered < ended,
|
||||
"the answer must go out before the scan ends, not after it: {said:#?}"
|
||||
);
|
||||
// And the index really did finish, so nothing was traded for the
|
||||
// latency but the completeness of that one answer.
|
||||
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself() {
|
||||
// The other side of `INTERLEAVE_ABOVE`. A handful of files is over in
|
||||
// milliseconds, so a request that arrived with them is answered from
|
||||
// the *finished* index — the complete answer, which is worth more than
|
||||
// the few milliseconds an interleaved one would have saved.
|
||||
let tree = workspace_of("interleaveshort", 4);
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![symbol_request(7, "p0")],
|
||||
);
|
||||
// Nothing is answered during construction at all: the burst is still
|
||||
// on the queue for `run` to take.
|
||||
let said = session.drain();
|
||||
assert_eq!(positions(&said, 7).1, None, "{said:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after() {
|
||||
// QA attack (`docs/features/scan-interleave/README.md`, settling
|
||||
// attacks): the exact edge of `INTERLEAVE_ABOVE`. `scan_once` compares
|
||||
// with `>`, not `>=`, so a scan of *exactly* the threshold must still
|
||||
// run one-shot and one file more must interleave. Both sides in one
|
||||
// test so a future off-by-one in that comparison shows up as a single
|
||||
// failing assertion rather than two tests that each only prove half.
|
||||
let at_threshold = workspace_of("interleaveboundaryat", INTERLEAVE_ABOVE);
|
||||
let one_shot = Session::started_behind(
|
||||
vec![at_threshold.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![symbol_request(7, "p0")],
|
||||
);
|
||||
let said = one_shot.drain();
|
||||
assert_eq!(
|
||||
positions(&said, 7).1,
|
||||
None,
|
||||
"exactly INTERLEAVE_ABOVE files must run one-shot: {said:#?}"
|
||||
);
|
||||
|
||||
let above_threshold = workspace_of("interleaveboundaryabove", INTERLEAVE_ABOVE + 1);
|
||||
let interleaved = Session::started_behind(
|
||||
vec![above_threshold.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![symbol_request(7, "p0")],
|
||||
);
|
||||
let said = interleaved.drain();
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
assert!(
|
||||
answered.expect("answered mid-scan") < ended.expect("the bar comes down"),
|
||||
"one file over INTERLEAVE_ABOVE must interleave: {said:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_queued_behind_a_rescan_waits_for_that_rescan() {
|
||||
// The order contract, which interleaving must not cost: a message
|
||||
// that asks for a rescan is *applied* — rescan run and all — before
|
||||
// anything queued behind it is answered. Here the cap is pushed down
|
||||
// to nothing, which empties the index, and the request behind it must
|
||||
// see the empty one rather than the half-built one it was sent into.
|
||||
let tree = workspace_of("interleaveorder", INTERLEAVE_ABOVE + 6);
|
||||
let mut session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeConfiguration::METHOD.to_string(),
|
||||
capping(1),
|
||||
)),
|
||||
symbol_request(7, "p0"),
|
||||
],
|
||||
);
|
||||
// The configuration was applied mid-scan and the rescan it asked for
|
||||
// ran; the request behind it is still waiting, because it is owed that
|
||||
// rescan's result.
|
||||
assert!(session.server.held.len() == 1, "the request waits: {:?}", session.server.held);
|
||||
assert_eq!(session.server.workspace.index().files().len(), 0, "the cap emptied the index");
|
||||
let said = session.drain();
|
||||
assert_eq!(positions(&said, 7).1, None, "not answered yet: {said:#?}");
|
||||
|
||||
// `run` answers it before it takes anything newer, and by then the
|
||||
// rescan the client asked for has happened.
|
||||
let held = std::mem::take(&mut session.server.held);
|
||||
assert!(!session.batch(held), "the held burst is handled");
|
||||
let answered = session.answers();
|
||||
assert_eq!(answered.len(), 1, "{answered:#?}");
|
||||
assert_eq!(
|
||||
answered[0].response_result.as_ref().ok().and_then(|v| v.as_array()).map(Vec::len),
|
||||
Some(0),
|
||||
"answered from the index the push asked for, not the one it was sent into"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_request_keeps_its_place_and_takes_its_cancel_with_it() {
|
||||
// Two corners of holding, in one experiment. The burst carries a
|
||||
// cancel for the request it also carries, and the scan the burst's
|
||||
// settings push asks for holds a *newer* request of its own along the
|
||||
// way. What comes out has to be: the burst's own request first (it
|
||||
// arrived first), the newer one behind it, and the cancel still in
|
||||
// front of what it cancels — a cancel dropped by the wait would turn
|
||||
// into a computed answer the client has stopped listening for.
|
||||
let tree = workspace_of("interleaveheldorder", INTERLEAVE_ABOVE + 6);
|
||||
let mut session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeConfiguration::METHOD.to_string(),
|
||||
capping(1),
|
||||
)),
|
||||
Message::Notification(Notification::new(
|
||||
Cancel::METHOD.to_string(),
|
||||
serde_json::json!({ "id": 7 }),
|
||||
)),
|
||||
symbol_request(7, "p0"),
|
||||
symbol_request(8, "p0"),
|
||||
],
|
||||
);
|
||||
let held: Vec<String> = session
|
||||
.server
|
||||
.held
|
||||
.iter()
|
||||
.map(|message| match message {
|
||||
Message::Request(request) => format!("req {}", request.id),
|
||||
Message::Notification(n) => format!("notif {}", n.method),
|
||||
Message::Response(r) => format!("resp {}", r.id),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(held, ["notif $/cancelRequest", "req 7", "req 8"], "{held:?}");
|
||||
|
||||
let batch = std::mem::take(&mut session.server.held);
|
||||
assert!(!session.batch(batch), "the held burst is handled");
|
||||
let answered = session.answers();
|
||||
assert_eq!(answered.len(), 2, "{answered:#?}");
|
||||
assert_eq!(answered[0].id, RequestId::from(7));
|
||||
assert!(
|
||||
answered[0]
|
||||
.response_result
|
||||
.as_ref()
|
||||
.is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32),
|
||||
"the cancel survived the wait: {:#?}",
|
||||
answered[0]
|
||||
);
|
||||
assert_eq!(answered[1].id, RequestId::from(8), "and the newer one is behind it");
|
||||
assert!(answered[1].response_result.is_ok(), "which is answered normally: {:#?}", answered[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan() {
|
||||
// Three settings pushes land inside one startup scan, each of which
|
||||
// would rebuild the index on its own. They cost one more scan between
|
||||
// them, not three, and no scan runs inside another: two bars, two
|
||||
// tokens, in order.
|
||||
let tree = workspace_of("interleavecoalesce", INTERLEAVE_ABOVE + 6);
|
||||
let cap = |bytes: u64| {
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeConfiguration::METHOD.to_string(),
|
||||
capping(bytes),
|
||||
))
|
||||
};
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![cap(1), cap(2), cap(3)],
|
||||
);
|
||||
assert!(!session.server.scanning, "no scan is left running");
|
||||
assert!(!session.server.rescan_wanted, "and none is left owed");
|
||||
let bars: Vec<(&str, String)> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(progress_step)
|
||||
.filter(|(step, _)| *step != "report")
|
||||
.collect();
|
||||
assert_eq!(
|
||||
bars,
|
||||
vec![
|
||||
("create", "lucisv-index-0".to_string()),
|
||||
("begin", "lucisv-index-0".to_string()),
|
||||
("end", "lucisv-index-0".to_string()),
|
||||
("create", "lucisv-index-1".to_string()),
|
||||
("begin", "lucisv-index-1".to_string()),
|
||||
("end", "lucisv-index-1".to_string()),
|
||||
],
|
||||
"one startup scan and exactly one coalesced rescan behind it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands() {
|
||||
// A scan is interruptible now that it takes messages, and `shutdown`
|
||||
// is what interrupts it: the bar never comes down, nothing is
|
||||
// published after it, and `run` returns without taking another
|
||||
// message. What the scan had already parsed is in the persistent
|
||||
// store — it is written through per file — so the next session
|
||||
// resumes from it exactly as it does after any other half-done scan.
|
||||
let tree = workspace_of("interleaveshutdown", INTERLEAVE_ABOVE + 6);
|
||||
let shutdown = || {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(9),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
))
|
||||
};
|
||||
let mut session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
// On the connection as well as on the queue, and in this order:
|
||||
// the queued copy is what the scan's first drain is *certain* to
|
||||
// see, and the copy the forwarder carries is what stops it reading
|
||||
// — so the `exit` behind it is still there for `handle_shutdown`,
|
||||
// which reads the connection itself. Whichever of the two the
|
||||
// handshake ends up consuming, the scan stops here.
|
||||
vec![shutdown(), Message::Notification(Notification::new("exit".into(), Value::Null))],
|
||||
vec![shutdown()],
|
||||
);
|
||||
assert!(session.server.stopped, "the scan saw the shutdown");
|
||||
assert_eq!(session.ended(), Vec::<Option<String>>::new(), "the bar never came down");
|
||||
assert!(
|
||||
session.server.workspace.index().files().len() < INTERLEAVE_ABOVE + 6,
|
||||
"the scan stopped where it stood rather than running to the end"
|
||||
);
|
||||
session.server.run().expect("run returns at once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once() {
|
||||
// QA attack (`docs/features/scan-interleave/README.md`,
|
||||
// progress/log-continuity): before this round no buffer could be
|
||||
// *open* while `Server::new` was still running, so `Server::started`
|
||||
// never had to pay the one-time republish-and-refresh `reindex` has
|
||||
// always owed at the end of a rescan. A `didOpen` answered mid-scan
|
||||
// now creates exactly that buffer, and the work log says
|
||||
// `Server::started` pays the debt at the end of construction.
|
||||
//
|
||||
// Two publishes for the opened file are both correct, not a
|
||||
// duplicate: `didOpen`'s own handler has always published against
|
||||
// whatever index exists the moment a file opens (unrelated to this
|
||||
// round), which here is the half-built one — so the debt payment
|
||||
// after the bar comes down is what gives the client a diagnostics set
|
||||
// computed against the *finished* index, and it must come after the
|
||||
// `end` event, not folded into the mid-scan one.
|
||||
let tree = workspace_of("interleaveopenedpublish", INTERLEAVE_ABOVE + 6);
|
||||
let target = tree.path.join("p000.sv");
|
||||
let opened = Message::Notification(Notification::new(
|
||||
DidOpenTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": {
|
||||
"uri": path_to_uri(&target).expect("uri"),
|
||||
"languageId": "systemverilog",
|
||||
"version": 1,
|
||||
"text": "package p000;\nendpackage\n",
|
||||
}
|
||||
}),
|
||||
));
|
||||
let abilities =
|
||||
ClientAbilities { work_done_progress: true, code_lens_refresh: true, ..Default::default() };
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
abilities,
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![opened],
|
||||
);
|
||||
let said = session.drain();
|
||||
let target_uri = path_to_uri(&target).expect("uri");
|
||||
let ended = said
|
||||
.iter()
|
||||
.position(|m| {
|
||||
matches!(m, Message::Notification(n) if n.method == Progress::METHOD
|
||||
&& n.params["value"]["kind"] == "end")
|
||||
})
|
||||
.expect("the bar comes down");
|
||||
let publish_positions: Vec<usize> = said
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, m)| match m {
|
||||
Message::Notification(n)
|
||||
if n.method == PublishDiagnostics::METHOD
|
||||
&& serde_json::from_value::<PublishDiagnosticsParams>(n.params.clone())
|
||||
.is_ok_and(|p| p.uri == target_uri) =>
|
||||
{
|
||||
Some(i)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
publish_positions.len(),
|
||||
2,
|
||||
"one publish from didOpen's own handler, one from the debt Server::started pays: \
|
||||
{said:#?}"
|
||||
);
|
||||
assert!(
|
||||
publish_positions[0] < ended,
|
||||
"the first publish is didOpen's own, against the half-built index: {said:#?}"
|
||||
);
|
||||
assert!(
|
||||
publish_positions[1] > ended,
|
||||
"the second is the debt payment, against the finished index: {said:#?}"
|
||||
);
|
||||
let refreshes = said
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD))
|
||||
.count();
|
||||
assert_eq!(refreshes, 1, "exactly one lens refresh, not one per drain: {said:#?}");
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
//! Pulled settings (2026-08-27): `workspace/configuration` beside the push.
|
||||
|
||||
use super::*;
|
||||
use crate::settings;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// pulled settings (2026-08-27)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A client that answers `workspace/configuration`.
|
||||
fn pulling_settings() -> ClientAbilities {
|
||||
ClientAbilities { configuration: true, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_can_be_asked_is_asked_for_its_settings_at_startup() {
|
||||
let tree = Tree::new("pullstartup");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (_id, params) = configuration_request(&session);
|
||||
assert_eq!(
|
||||
params,
|
||||
serde_json::json!({ "items": [{ "section": "lucisv" }] }),
|
||||
"one item, our section, no scope"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
||||
// `Server::new` calls `register_watchers` and then
|
||||
// `request_configuration`, in that order — this pins it on the actual
|
||||
// wire rather than trusting the call order in the source. Every
|
||||
// outgoing request's id is `lucisv-{n}` off one monotonically
|
||||
// increasing counter, so the numeric suffix *is* the send order.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item
|
||||
// ("verify on the wire").
|
||||
let tree = Tree::new("pulloraftwatch");
|
||||
let abilities =
|
||||
ClientAbilities { file_watching: true, configuration: true, ..pulling_settings() };
|
||||
let session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let sent = session.sent();
|
||||
let index_of = |method: &str| -> usize {
|
||||
sent.iter()
|
||||
.position(|r| r.method == method)
|
||||
.unwrap_or_else(|| panic!("no {method} in {sent:#?}"))
|
||||
};
|
||||
let watchers = index_of(RegisterCapability::METHOD);
|
||||
let pull = index_of(WorkspaceConfiguration::METHOD);
|
||||
assert!(watchers < pull, "watcher registration must precede the pull: {sent:#?}");
|
||||
|
||||
let numeric_suffix = |request: &Request| -> u32 {
|
||||
request
|
||||
.id
|
||||
.to_string()
|
||||
.trim_matches('"')
|
||||
.trim_start_matches("lucisv-")
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("not a lucisv-N id: {:?}", request.id))
|
||||
};
|
||||
assert!(
|
||||
numeric_suffix(&sent[watchers]) < numeric_suffix(&sent[pull]),
|
||||
"the pull's id must be issued after the watcher registration's: {sent:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_be_asked_is_never_asked() {
|
||||
// Every client that predates this — `smoke.js` included — sends
|
||||
// `capabilities: {}` and must see nothing new at all.
|
||||
let tree = Tree::new("pullnone");
|
||||
let session = Session::new(vec![tree.path.clone()], false);
|
||||
assert!(session.requests().is_empty(), "{:#?}", session.requests());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pulled_answer_reaches_the_formatter_through_the_same_parser_a_push_uses() {
|
||||
let tree = Tree::new("pullapply");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
let (id, _) = configuration_request(&session);
|
||||
|
||||
// The editor's tab size, until the client answers.
|
||||
assert_eq!(
|
||||
formatting_result(&mut session, &uri)[0]["newText"],
|
||||
serde_json::json!("module m;\n wire a;\nendmodule\n")
|
||||
);
|
||||
|
||||
// The answer is an array with one entry per requested item, and the
|
||||
// entry is the *section*, not the `{lucisv: ...}` wrapper a push has.
|
||||
session.answer(id, serde_json::json!([{ "indent": 4, "lineLength": 120 }]));
|
||||
assert_eq!(
|
||||
formatting_result(&mut session, &uri)[0]["newText"],
|
||||
serde_json::json!("module m;\n wire a;\nendmodule\n"),
|
||||
"the pulled indent is in force"
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().line_length, Some(120));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pulled_answer_that_changes_the_scope_rebuilds_the_index() {
|
||||
// The pull applies through the same path a push does, so an `exclude`
|
||||
// that arrives this way must cost the same rescan.
|
||||
let tree = Tree::new("pullexclude");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("scratch/wip.sv", "scratch_pkg");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], pulling_settings());
|
||||
assert_eq!(indexed(&session, "scratch_pkg"), 1, "premise: indexed at first");
|
||||
|
||||
let (id, _) = configuration_request(&session);
|
||||
// The pulled section carries the scope for the same reason a pushed
|
||||
// one does: an answer is the *whole* section, so leaving it out would
|
||||
// narrow the index in the same breath as the exclude.
|
||||
session.answer(
|
||||
id,
|
||||
serde_json::json!([{ "exclude": ["scratch"], "index": { "scope": "workspace" } }]),
|
||||
);
|
||||
assert_eq!(indexed(&session, "scratch_pkg"), 0, "the pulled exclude took effect");
|
||||
assert_eq!(indexed(&session, "a"), 1, "and nothing else moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pulled_filelist_re_registers_the_watchers_through_the_same_chain_a_push_uses() {
|
||||
// `apply_settings` is the one function both doors go through, but
|
||||
// nothing pinned it for the *pull* path specifically before this: the
|
||||
// answer changing `lucisv.filelist` must move `filelist_path()` and
|
||||
// cost a watcher re-registration exactly as a pushed one does.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item
|
||||
// ("the full chain: pull answer -> apply_settings -> filelist moved
|
||||
// -> re-register").
|
||||
let tree = Tree::new("pullfilelistwatch");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
let abilities =
|
||||
ClientAbilities { configuration: true, file_watching: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
// Drains the startup watcher registration and the startup pull's own
|
||||
// request together; `configuration_request` needs only the latter.
|
||||
let (id, _) = configuration_request(&session);
|
||||
|
||||
session.answer(id, serde_json::json!([{ "filelist": "files.f" }]));
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 2, "{requests:#?}");
|
||||
assert_eq!(requests[0].0, UnregisterCapability::METHOD, "the old registration first");
|
||||
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
||||
assert_eq!(
|
||||
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
||||
tree.path.join("files.f").to_str().expect("utf-8").to_string(),
|
||||
"{requests:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_pull_answer_leaves_the_defaults_and_says_nothing() {
|
||||
// Nothing here is the user's fault and nothing here is actionable, so
|
||||
// every one of these must be as quiet as a client that answered
|
||||
// `null` — which is what the spec asks a client without the section
|
||||
// to do.
|
||||
let tree = Tree::new("pulljunk");
|
||||
for answer in [
|
||||
serde_json::json!(null),
|
||||
serde_json::json!([]),
|
||||
serde_json::json!([null]),
|
||||
serde_json::json!("lucisv"),
|
||||
serde_json::json!({ "indent": 4 }),
|
||||
serde_json::json!([{ "indent": "four", "exclude": 7 }]),
|
||||
serde_json::json!([{ "lucisv": { "indent": 4 } }]),
|
||||
] {
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, answer.clone());
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings(),
|
||||
&settings::ClientSettings::default(),
|
||||
"the answer {answer} must leave the defaults"
|
||||
);
|
||||
assert!(session.shown().is_empty(), "and must not open a popup");
|
||||
}
|
||||
|
||||
// An error response is the same news, said differently.
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.server.response(Response::new_err(
|
||||
id,
|
||||
lsp_server::ErrorCode::MethodNotFound as i32,
|
||||
"no configuration here".to_string(),
|
||||
));
|
||||
assert_eq!(session.server.workspace.client_settings(), &settings::ClientSettings::default());
|
||||
assert!(session.shown().is_empty(), "a refused pull is not worth a popup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_push_pulls_instead_of_resetting_everything_to_default() {
|
||||
// The modern client's "something changed, ask me for what you need".
|
||||
// Applying it as a payload would silently clear the settings it just
|
||||
// told us to come and fetch.
|
||||
let tree = Tree::new("pushempty");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
||||
|
||||
for empty in [serde_json::json!({ "settings": {} }), serde_json::json!({ "settings": null })] {
|
||||
let _ = session.drain();
|
||||
session.notify(DidChangeConfiguration::METHOD, empty.clone());
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings().indent,
|
||||
Some(4),
|
||||
"{empty} must not clear what was pulled"
|
||||
);
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, serde_json::json!([{ "indent": 8 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "{empty}");
|
||||
// Put it back for the next round.
|
||||
session.server.workspace.set_client_settings(settings::ClientSettings {
|
||||
indent: Some(4),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_push_to_a_client_that_cannot_be_asked_still_means_no_opinion() {
|
||||
// The legacy path, unchanged: with nobody to ask, an empty payload is
|
||||
// what it has always been — no opinion about anything.
|
||||
let tree = Tree::new("pushemptylegacy");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "indent": 4 } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, None, "cleared, as before");
|
||||
assert!(session.requests().is_empty(), "and nothing was asked of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_push_with_a_payload_is_applied_directly_even_when_the_client_could_be_asked() {
|
||||
// The legacy `synchronize.configurationSection` path survives the
|
||||
// pull model: a client that sends both must not have its own push
|
||||
// ignored in favour of a round trip.
|
||||
let tree = Tree::new("pushpayload");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, serde_json::json!([null]));
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(8));
|
||||
let sent = session.sent();
|
||||
assert!(
|
||||
!sent.iter().any(|r| r.method == WorkspaceConfiguration::METHOD),
|
||||
"a payload is not a request to go and fetch one: {sent:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_pull_answer_overrides_a_push_that_landed_while_it_was_outstanding() {
|
||||
// The other half of the precedence question: a client that both
|
||||
// pushes (the legacy `synchronize.configurationSection`) and can be
|
||||
// pulled may have its own push arrive *before* the startup pull's
|
||||
// answer does — both mechanisms firing off the same connection at
|
||||
// once. The loop is single-threaded and processes messages strictly
|
||||
// in receive order, with no notion of "the push is newer" beyond
|
||||
// that: `apply_settings` always replaces the whole struct, so
|
||||
// whichever of the two is processed *last* is simply what is in
|
||||
// force afterward. QA (2026-08-27): pinned per the dev's own review
|
||||
// checklist item ("push-with-payload arriving while a pull is
|
||||
// outstanding — which wins").
|
||||
let tree = Tree::new("latepullwins");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
|
||||
// The push lands first, while the startup pull is still outstanding.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "the push landed");
|
||||
|
||||
// The pull's answer arrives after — and, being processed last,
|
||||
// overwrites it.
|
||||
session.answer(id, serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings().indent,
|
||||
Some(4),
|
||||
"processed last, so in force last — the pull's answer, not the push"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_outstanding_requests_are_answered_by_id_in_any_order() {
|
||||
// `applyEdit`, a progress `create` and a `workspace/configuration`
|
||||
// all in flight at once. Only two of them are in `pending`, and the
|
||||
// arrival order is not the send order — the id is the whole lookup,
|
||||
// and neither answer may be delivered to the other's handler.
|
||||
let abilities = ClientAbilities {
|
||||
apply_edit: true,
|
||||
work_done_progress: true,
|
||||
configuration: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (tree, mut session, params) = propagating("threeway", abilities);
|
||||
let _ = session.drain();
|
||||
// `propagating` answered nothing, so the startup pull is already
|
||||
// spent; an empty push asks again, and that one is left outstanding
|
||||
// alongside the other two.
|
||||
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert!(result.is_null(), "the edit was pushed, not returned");
|
||||
// Two files, so the rescan is the whole one that puts a bar up.
|
||||
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
||||
|
||||
let sent = session.sent();
|
||||
let of = |method: &str| -> RequestId {
|
||||
sent.iter()
|
||||
.find(|request| request.method == method)
|
||||
.unwrap_or_else(|| panic!("no {method} in {sent:#?}"))
|
||||
.id
|
||||
.clone()
|
||||
};
|
||||
let (edit, create, pull) = (
|
||||
of(ApplyWorkspaceEdit::METHOD),
|
||||
of(WorkDoneProgressCreate::METHOD),
|
||||
of(WorkspaceConfiguration::METHOD),
|
||||
);
|
||||
|
||||
// Backwards: the pull first, then the ignorable create, then the edit.
|
||||
session.answer(pull, serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "the pull landed");
|
||||
assert!(session.shown().is_empty(), "and said nothing to the user");
|
||||
|
||||
session.answer(create, serde_json::json!(null));
|
||||
assert!(session.shown().is_empty(), "a create answer says nothing either");
|
||||
|
||||
session.answer(edit, serde_json::json!({ "applied": false }));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert!(shown[0].1.contains("lucisv.propagatePorts"), "{shown:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_outstanding_configuration_pulls_are_each_answered_by_their_own_id() {
|
||||
// A second pull can go out before the first is answered — an empty
|
||||
// `didChangeConfiguration` racing the client's answer to the startup
|
||||
// pull, say. Both ids sit in `pending` at once; each answer is
|
||||
// applied through its own id, and whichever is processed last is
|
||||
// simply what ends up in force — there is no notion of the newer
|
||||
// pull's answer winning over the older one, only processing order.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
||||
let tree = Tree::new("twopulls");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let sent = session.sent();
|
||||
let first = sent
|
||||
.iter()
|
||||
.find(|r| r.method == WorkspaceConfiguration::METHOD)
|
||||
.expect("the startup pull")
|
||||
.id
|
||||
.clone();
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
||||
let sent = session.sent();
|
||||
let second = sent
|
||||
.iter()
|
||||
.find(|r| r.method == WorkspaceConfiguration::METHOD)
|
||||
.expect("the re-pull")
|
||||
.id
|
||||
.clone();
|
||||
assert_ne!(first, second, "two distinct outstanding requests, not one reused");
|
||||
|
||||
// Answered out of order: the second (newer) pull first, then the
|
||||
// first (older, startup) one.
|
||||
session.answer(second, serde_json::json!([{ "indent": 8 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "the newer landed");
|
||||
session.answer(first, serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings().indent,
|
||||
Some(4),
|
||||
"whichever answer is processed last is what is in force — no id-based precedence"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() {
|
||||
// An id the server never sent, or a duplicate answer to one already
|
||||
// consumed, names nothing in `pending`: `response` must not panic and
|
||||
// must leave whatever settings are in force untouched.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
||||
let tree = Tree::new("forgottenid");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id.clone(), serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
||||
|
||||
// The same id, answered a second time — already removed from `pending`.
|
||||
session.answer(id, serde_json::json!([{ "indent": 8 }]));
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings().indent,
|
||||
Some(4),
|
||||
"a stale re-answer is a no-op"
|
||||
);
|
||||
|
||||
// An id that was never sent by this server at all.
|
||||
session.answer(RequestId::from("never-sent".to_string()), serde_json::json!([{ "indent": 2 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4));
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Incremental text sync and the change debounce.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// incremental text sync
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn incremental_changes_land_the_same_buffer_as_one_full_change() {
|
||||
let tree = Tree::new("incrementalsame");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
|
||||
// Three ranges, each positioned against what the last one left.
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([
|
||||
{ "range": { "start": { "line": 1, "character": 0 },
|
||||
"end": { "line": 1, "character": 0 } }, "text": "\n" },
|
||||
{ "range": { "start": { "line": 1, "character": 0 },
|
||||
"end": { "line": 1, "character": 0 } }, "text": " wire " },
|
||||
{ "range": { "start": { "line": 1, "character": 7 },
|
||||
"end": { "line": 1, "character": 7 } }, "text": "w;" },
|
||||
]),
|
||||
);
|
||||
let composed = "module m;\n wire w;\nendmodule\n";
|
||||
assert_eq!(buffer(&session, &uri), composed);
|
||||
|
||||
// The same buffer reached by a full-sync client, for comparison.
|
||||
let mut full = Session::new(vec![tree.path.clone()], false);
|
||||
let other = full.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
change(&mut full, &other, 2, serde_json::json!([{ "text": composed }]));
|
||||
assert_eq!(buffer(&full, &other), composed);
|
||||
|
||||
// And the answers computed from it agree, not just the text.
|
||||
assert_eq!(
|
||||
session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
),
|
||||
full.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": other },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_changes_coalesces_into_one_reparse() {
|
||||
// The change debounce's whole payoff: a burst of `didChange`
|
||||
// notifications costs one reparse when the next thing that needs the
|
||||
// analysis flushes them, not one per keystroke.
|
||||
let tree = Tree::new("debounce");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
|
||||
let before = session.server.generation;
|
||||
session.batch(vec![
|
||||
changed(&uri, 2, "module m;\n wire a;\nendmodule\n"),
|
||||
changed(&uri, 3, "module m;\n wire a;\n wire b;\nendmodule\n"),
|
||||
]);
|
||||
// Text-current, analysis-stale: nothing has reparsed yet, and the
|
||||
// newest text is already what the server holds.
|
||||
assert_eq!(session.server.generation, before, "no keystroke reparses on its own");
|
||||
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire b;\nendmodule\n");
|
||||
|
||||
// The first request after the burst is answered from one flush.
|
||||
session.result(
|
||||
DocumentSymbolRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert_eq!(session.server.generation, before + 1, "one reparse for the whole burst");
|
||||
assert!(session.server.dirty.is_empty(), "and nothing is left pending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone() {
|
||||
// The debounce's other half: a buffer closed mid-edit is never
|
||||
// analyzed. Its pending text is dropped ahead of the flush at the top
|
||||
// of `notification`, so the client gets the one clearing publish and
|
||||
// nothing else — while every *other* dirty buffer still flushes,
|
||||
// because closing one file says nothing about the rest (QA, CD-1).
|
||||
let tree = Tree::new("closedirty");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let closing = session.open(&tree.path.join("closing.sv"), "module a;\nendmodule\n");
|
||||
let staying = session.open(&tree.path.join("staying.sv"), "module b;\nendmodule\n");
|
||||
let _ = session.published();
|
||||
|
||||
// Both buffers go dirty with text that would diagnose if analyzed.
|
||||
let before = session.server.generation;
|
||||
for (uri, text) in [
|
||||
(&closing, "module a;\n wire ;\nendmodule\n"),
|
||||
(&staying, "module b;\n wire ;\nendmodule\n"),
|
||||
] {
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": text }],
|
||||
}),
|
||||
);
|
||||
}
|
||||
assert_eq!(session.server.generation, before, "a keystroke reparses nothing on its own");
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": closing } }),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
before + 1,
|
||||
"one reparse — the buffer still open; the closing one's text went with it"
|
||||
);
|
||||
assert!(session.server.dirty.is_empty(), "nothing left pending");
|
||||
|
||||
let published = session.published();
|
||||
let closed: Vec<_> = published.iter().filter(|p| p.uri == closing).collect();
|
||||
assert_eq!(closed.len(), 1, "exactly one publish for the closed buffer: {published:?}");
|
||||
assert!(closed[0].diagnostics.is_empty(), "and it is the clearing one: {published:?}");
|
||||
let open: Vec<_> = published.iter().filter(|p| p.uri == staying).collect();
|
||||
assert_eq!(open.len(), 1, "the other buffer publishes once: {published:?}");
|
||||
assert!(
|
||||
!open[0].diagnostics.is_empty(),
|
||||
"the other buffer's pending edit was flushed as usual: {published:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_notification_is_one_generation_bump_however_many_ranges() {
|
||||
// The pull-diagnostics `resultId` is this counter. One reparse and one
|
||||
// stamp per notification: a bump per range would make every keystroke
|
||||
// look like several to a pulling client, and none would make a
|
||||
// changed buffer answer "unchanged".
|
||||
let tree = Tree::new("incrementalgeneration");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
|
||||
let before = session.server.generation;
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([
|
||||
{ "range": { "start": { "line": 0, "character": 9 },
|
||||
"end": { "line": 0, "character": 9 } }, "text": "\n wire a;" },
|
||||
{ "range": { "start": { "line": 1, "character": 9 },
|
||||
"end": { "line": 1, "character": 9 } }, "text": "\n wire b;" },
|
||||
{ "range": { "start": { "line": 2, "character": 7 },
|
||||
"end": { "line": 2, "character": 8 } }, "text": "c" },
|
||||
]),
|
||||
);
|
||||
assert_eq!(session.server.generation, before + 1, "one stamp per notification");
|
||||
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire c;\nendmodule\n");
|
||||
|
||||
// An empty batch is not a change: nothing to reparse, nothing to stamp.
|
||||
let stamp = session.server.generation;
|
||||
change(&mut session, &uri, 3, serde_json::json!([]));
|
||||
assert_eq!(session.server.generation, stamp, "an empty batch moves nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_sync_clients_batch_still_lets_the_last_change_win() {
|
||||
// A client that ignores the new capability and keeps sending whole
|
||||
// buffers must behave exactly as it did before this feature.
|
||||
let tree = Tree::new("incrementalfullsync");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([
|
||||
{ "text": "module a;\nendmodule\n" },
|
||||
{ "text": "module b;\nendmodule\n" },
|
||||
{ "text": "module c;\nendmodule\n" },
|
||||
]),
|
||||
);
|
||||
assert_eq!(buffer(&session, &uri), "module c;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_naming_a_buffer_that_was_never_opened_is_taken_as_written() {
|
||||
// Out of protocol, but a full-text change used to be adopted whatever
|
||||
// the state was, and still is: there is no base text to be wrong
|
||||
// about. A *ranged* change against nothing lands its text at the
|
||||
// start, which is the clamping rule, not a special case.
|
||||
let tree = Tree::new("incrementalunopened");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
change(&mut session, &uri, 1, serde_json::json!([{ "text": "module m;\nendmodule\n" }]));
|
||||
assert_eq!(buffer(&session, &uri), "module m;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ranged_change_over_multi_byte_text_edits_the_right_columns() {
|
||||
// The whole reason positions are converted rather than counted: the
|
||||
// comment above the edited line is four characters and nine bytes.
|
||||
let tree = Tree::new("incrementalunicode");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "// é ✓ 🎉\nmodule m;\n wire a;\nendmodule\n");
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{
|
||||
"range": { "start": { "line": 2, "character": 7 },
|
||||
"end": { "line": 2, "character": 8 } },
|
||||
"text": "renamed",
|
||||
}]),
|
||||
);
|
||||
assert_eq!(buffer(&session, &uri), "// é ✓ 🎉\nmodule m;\n wire renamed;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ranged_change_republishes_diagnostics_for_what_it_produced() {
|
||||
let tree = Tree::new("incrementalpublish");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
let _ = session.published();
|
||||
|
||||
// Delete the `a`, leaving `wire ;` — a parse error.
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{
|
||||
"range": { "start": { "line": 1, "character": 7 },
|
||||
"end": { "line": 1, "character": 8 } },
|
||||
"text": "",
|
||||
}]),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1, "one publish per notification: {published:#?}");
|
||||
assert!(!published[0].diagnostics.is_empty(), "the broken buffer is reported");
|
||||
|
||||
// Put it back: the diagnostics clear.
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
3,
|
||||
serde_json::json!([{
|
||||
"range": { "start": { "line": 1, "character": 7 },
|
||||
"end": { "line": 1, "character": 7 } },
|
||||
"text": "a",
|
||||
}]),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1);
|
||||
assert!(published[0].diagnostics.is_empty(), "{published:#?}");
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Semantic tokens: full, range, full/delta.
|
||||
|
||||
use super::*;
|
||||
use crate::tokens;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// semantic tokens: full, range, full/delta
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn full_tokens(session: &mut Session, uri: &Uri) -> Value {
|
||||
session.result(
|
||||
SemanticTokensFullRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
)
|
||||
}
|
||||
|
||||
fn delta_tokens(session: &mut Session, uri: &Uri, previous: &str) -> Value {
|
||||
session.result(
|
||||
SemanticTokensFullDeltaRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"previousResultId": previous,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn range_tokens(session: &mut Session, uri: &Uri, from: (u32, u32), to: (u32, u32)) -> Value {
|
||||
session.result(
|
||||
SemanticTokensRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": from.0, "character": from.1 },
|
||||
"end": { "line": to.0, "character": to.1 },
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// A `data` array as the client reads it: flat numbers.
|
||||
fn numbers(value: &Value) -> Vec<u64> {
|
||||
value
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("an array of numbers, got {value:#?}"))
|
||||
.iter()
|
||||
.map(|n| n.as_u64().expect("a number"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The client's side of a delta: splice each edit into the data it holds.
|
||||
fn applied(previous: &[u64], answer: &Value) -> Vec<u64> {
|
||||
let mut data = previous.to_vec();
|
||||
let edits = answer["edits"].as_array().unwrap_or_else(|| panic!("edits in {answer:#?}"));
|
||||
for edit in edits {
|
||||
let start = edit["start"].as_u64().expect("start") as usize;
|
||||
let end = start + edit["deleteCount"].as_u64().expect("deleteCount") as usize;
|
||||
let inserted = edit.get("data").map(numbers).unwrap_or_default();
|
||||
data.splice(start..end, inserted);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
const TOKEN_SOURCE: &str = "module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_full_token_answer_is_stamped_so_a_delta_can_name_it() {
|
||||
let tree = Tree::new("tokensfull");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let full = full_tokens(&mut session, &uri);
|
||||
assert!(full["resultId"].is_string(), "{full:#?}");
|
||||
assert!(!numbers(&full["data"]).is_empty(), "the buffer really has tokens");
|
||||
assert_eq!(
|
||||
session.server.tokens[&uri].result_id,
|
||||
full["resultId"].as_str().expect("resultId"),
|
||||
"the answer is remembered under the id it was stamped with"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delta_after_a_change_reconstructs_the_new_token_set_exactly() {
|
||||
// The whole invariant, end to end through the dispatch: what the
|
||||
// client is left holding after applying the edits must be what a
|
||||
// fresh full answer would have given it.
|
||||
let tree = Tree::new("tokensdelta");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let held = numbers(&first["data"]);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": "module m;\n localparam W = 16;\n wire [W-1:0] a;\n // added\nendmodule\n" }]),
|
||||
);
|
||||
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert!(answer.get("edits").is_some(), "a known id gets edits: {answer:#?}");
|
||||
let reconstructed = applied(&held, &answer);
|
||||
let now = full_tokens(&mut session, &uri);
|
||||
assert_eq!(reconstructed, numbers(&now["data"]), "the edits must reconstruct the truth");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delta_over_an_unchanged_buffer_is_an_empty_edit_list() {
|
||||
let tree = Tree::new("tokensnochange");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert_eq!(answer["edits"], serde_json::json!([]), "{answer:#?}");
|
||||
assert_ne!(answer["resultId"], first["resultId"], "and it is a new answer to name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delta_naming_an_id_we_do_not_hold_is_answered_in_full() {
|
||||
let tree = Tree::new("tokensstale");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
// Never asked for a full answer: there is nothing to diff against.
|
||||
let cold = delta_tokens(&mut session, &uri, "1");
|
||||
assert!(cold.get("edits").is_none(), "no state, no edits: {cold:#?}");
|
||||
assert!(!numbers(&cold["data"]).is_empty(), "{cold:#?}");
|
||||
|
||||
// And an id that has since been superseded — the client fell behind,
|
||||
// or another id's answer overwrote this one.
|
||||
let _ = full_tokens(&mut session, &uri);
|
||||
let stale = delta_tokens(&mut session, &uri, "not-an-id-we-ever-sent");
|
||||
assert!(stale.get("edits").is_none(), "a stale id, a full answer: {stale:#?}");
|
||||
assert!(stale["resultId"].is_string(), "which is itself nameable: {stale:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_buffer_drops_the_answer_a_delta_would_be_computed_against() {
|
||||
// Memory: nothing may grow with the number of files ever opened. The
|
||||
// observable half is that a delta naming the old id gets a full set.
|
||||
let tree = Tree::new("tokensclose");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let path = tree.path.join("m.sv");
|
||||
let uri = session.open(&path, TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert!(!session.server.tokens.contains_key(&uri), "the state went with the buffer");
|
||||
|
||||
session.open(&path, TOKEN_SOURCE);
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert!(answer.get("edits").is_none(), "the old id names nothing now: {answer:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_answer_covers_the_lines_it_names_and_nothing_else() {
|
||||
let tree = Tree::new("tokensrange");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let whole = numbers(&full_tokens(&mut session, &uri)["data"]);
|
||||
let everything = range_tokens(&mut session, &uri, (0, 0), (99, 0));
|
||||
assert_eq!(numbers(&everything["data"]), whole, "a range over everything is the full set");
|
||||
|
||||
let one_line = range_tokens(&mut session, &uri, (1, 0), (2, 0));
|
||||
let data = numbers(&one_line["data"]);
|
||||
assert!(!data.is_empty() && data.len() < whole.len(), "{one_line:#?}");
|
||||
assert_eq!(data[0], 1, "the first token's deltaLine is absolute from the file start");
|
||||
|
||||
let nothing = range_tokens(&mut session, &uri, (2, 0), (2, 0));
|
||||
assert_eq!(numbers(¬hing["data"]), Vec::<u64>::new(), "an empty range: {nothing:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_request_is_not_the_answer_a_later_delta_is_computed_against() {
|
||||
// A range answer is a partial view, so remembering it would make the
|
||||
// next delta a diff against something the client never held whole.
|
||||
let tree = Tree::new("tokensrangestate");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let ranged = range_tokens(&mut session, &uri, (1, 0), (2, 0));
|
||||
assert!(ranged.get("resultId").is_none(), "nothing to name: {ranged:#?}");
|
||||
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert_eq!(answer["edits"], serde_json::json!([]), "the full answer still stands");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_token_request_for_a_buffer_that_is_not_open_answers_null() {
|
||||
let tree = Tree::new("tokensunopened");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = crate::uri::path_to_uri(&tree.path.join("never.sv")).expect("uri");
|
||||
|
||||
assert!(full_tokens(&mut session, &uri).is_null());
|
||||
assert!(delta_tokens(&mut session, &uri, "1").is_null());
|
||||
assert!(range_tokens(&mut session, &uri, (0, 0), (9, 0)).is_null());
|
||||
assert!(session.server.tokens.is_empty(), "and nothing was remembered about it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_token_request_bumps_the_diagnostics_generation() {
|
||||
// Every token request is read-only. Bumping the generation would
|
||||
// invalidate a pulling client's whole diagnostic cache each time the
|
||||
// editor repainted a viewport.
|
||||
let tree = Tree::new("tokensgeneration");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let before = session.server.generation;
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let _ = delta_tokens(&mut session, &uri, &previous);
|
||||
let _ = range_tokens(&mut session, &uri, (0, 0), (9, 0));
|
||||
assert_eq!(session.server.generation, before, "nothing about diagnostics moved");
|
||||
|
||||
// Said the way the client would see it: a pull stamped before the
|
||||
// token requests is still `unchanged` after them.
|
||||
let pull = document_pull(&mut session, &uri, None);
|
||||
let stamp = pull["resultId"].as_str().expect("resultId").to_string();
|
||||
let _ = full_tokens(&mut session, &uri);
|
||||
let again = document_pull(&mut session, &uri, Some(&stamp));
|
||||
assert_eq!(again["kind"], "unchanged", "{again:#?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26): state-lifecycle attack surfaces
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_two_open_buffers_ids_do_not_cross_contaminate() {
|
||||
// Buffer A's resultId presented against buffer B must not be
|
||||
// mistaken for one of B's own — they share one counter, so the
|
||||
// strings can coincide only by the map being keyed on the wrong
|
||||
// thing.
|
||||
let tree = Tree::new("tokenstwobuffers");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri_a = session.open(&tree.path.join("a.sv"), TOKEN_SOURCE);
|
||||
let uri_b = session.open(&tree.path.join("b.sv"), "module other;\n wire z;\nendmodule\n");
|
||||
|
||||
let full_a = full_tokens(&mut session, &uri_a);
|
||||
let full_b = full_tokens(&mut session, &uri_b);
|
||||
let id_a = full_a["resultId"].as_str().expect("resultId").to_string();
|
||||
let id_b = full_b["resultId"].as_str().expect("resultId").to_string();
|
||||
assert_ne!(id_a, id_b, "two answers, two distinct ids");
|
||||
|
||||
// A's id, asked of B: B has no memory of ever answering that id, so
|
||||
// this must be a full answer, not edits computed against A's data.
|
||||
let cross = delta_tokens(&mut session, &uri_b, &id_a);
|
||||
assert!(cross.get("edits").is_none(), "A's id names nothing for B: {cross:#?}");
|
||||
// That full answer itself mints a fresh id and becomes B's new
|
||||
// remembered answer (every answer does, full or delta) — so it is
|
||||
// *that* id, not `id_b`, that now names B's data.
|
||||
let cross_id = cross["resultId"].as_str().expect("resultId").to_string();
|
||||
assert_ne!(cross_id, id_b, "a fresh id was minted for the cross-request's own answer");
|
||||
let _ = id_b; // superseded by `cross_id`; kept above only to assert distinctness of the two original ids
|
||||
|
||||
let same = delta_tokens(&mut session, &uri_b, &cross_id);
|
||||
assert_eq!(same["edits"], serde_json::json!([]), "B's latest id still names B's data");
|
||||
|
||||
// And closing A must not disturb B's remembered answer.
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri_a } }),
|
||||
);
|
||||
assert!(!session.server.tokens.contains_key(&uri_a));
|
||||
assert!(session.server.tokens.contains_key(&uri_b), "B's state is untouched by A's close");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_full_delta_full_delta_stays_consistent_across_edits() {
|
||||
// Mixing the two requests repeatedly, the way a real client would:
|
||||
// each new answer must be nameable by the next delta, regardless of
|
||||
// whether the previous answer was a `full` or a `full/delta`.
|
||||
let tree = Tree::new("tokensmixedcycle");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let mut previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let mut held = numbers(&first["data"]);
|
||||
|
||||
let edits_after = [
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\n // note\nendmodule\n",
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
|
||||
];
|
||||
for (i, text) in edits_after.iter().enumerate() {
|
||||
change(&mut session, &uri, i as u32 + 2, serde_json::json!([{ "text": text }]));
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert!(answer.get("edits").is_some(), "step {i}: known id gets edits: {answer:#?}");
|
||||
held = applied(&held, &answer);
|
||||
|
||||
let truth = full_tokens(&mut session, &uri);
|
||||
assert_eq!(held, numbers(&truth["data"]), "step {i}: delta chain matches the truth");
|
||||
// The `full` answer just taken is itself a fresh, valid base for
|
||||
// the next delta in the cycle.
|
||||
previous = truth["resultId"].as_str().expect("resultId").to_string();
|
||||
held = numbers(&truth["data"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A flat `data` array computed straight off the document, bypassing the
|
||||
/// request dispatch entirely — so checking against it does not depend on
|
||||
/// the very `tokens`/`token_results` bookkeeping under test.
|
||||
fn ground_truth(session: &Session, uri: &Uri) -> Vec<u64> {
|
||||
let doc = session.server.workspace.document(uri).expect("open");
|
||||
tokens::semantic_tokens(doc)
|
||||
.iter()
|
||||
.flat_map(|t| {
|
||||
[t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset]
|
||||
})
|
||||
.map(u64::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between() {
|
||||
// A client need not re-request `full` just because it received a
|
||||
// `full/delta` answer: that answer's own `resultId` must itself be a
|
||||
// valid base for the *next* delta. Every `full_tokens` call in the
|
||||
// test above also re-remembers the answer, which would silently
|
||||
// paper over a bug where only a *full* answer's id chains correctly
|
||||
// — so this test never calls `full` again after the first one.
|
||||
let tree = Tree::new("tokensdeltachain");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let mut previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let mut held = numbers(&first["data"]);
|
||||
|
||||
let edits_after = [
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\n // note\nendmodule\n",
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
|
||||
];
|
||||
for (i, text) in edits_after.iter().enumerate() {
|
||||
change(&mut session, &uri, i as u32 + 2, serde_json::json!([{ "text": text }]));
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert!(
|
||||
answer.get("edits").is_some(),
|
||||
"step {i}: the chained id is still known: {answer:#?}"
|
||||
);
|
||||
held = applied(&held, &answer);
|
||||
previous = answer["resultId"].as_str().expect("resultId").to_string();
|
||||
assert_eq!(held, ground_truth(&session, &uri), "step {i}: the chain matches the truth");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
//! File watchers: the registration, and the rebuilds a watched-file event does or does not cost.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_is_never_sent_a_registration() {
|
||||
// Such a client keeps the save-only staleness model, and must not be
|
||||
// sent a request it has no handler for.
|
||||
let tree = Tree::new("noregister");
|
||||
let session = Session::new(vec![tree.path.clone()], false);
|
||||
assert!(session.requests().is_empty(), "nothing may be asked of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_asked_is_registered_after_initialized() {
|
||||
let tree = Tree::new("register");
|
||||
let session = Session::new(vec![tree.path.clone()], true);
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 1, "{requests:#?}");
|
||||
assert_eq!(requests[0].0, RegisterCapability::METHOD);
|
||||
assert_eq!(
|
||||
requests[0].1,
|
||||
serde_json::json!({
|
||||
"registrations": [{
|
||||
"id": "lucisv-watched-files-0",
|
||||
"method": "workspace/didChangeWatchedFiles",
|
||||
"registerOptions": {
|
||||
"watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }]
|
||||
},
|
||||
}]
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_filelist_is_watched_too() {
|
||||
let tree = Tree::new("registerfilelist");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
|
||||
let session = Session::new(vec![tree.path.clone()], true);
|
||||
let requests = session.requests();
|
||||
let watchers = &requests[0].1["registrations"][0]["registerOptions"]["watchers"];
|
||||
assert_eq!(
|
||||
watchers,
|
||||
&serde_json::json!([
|
||||
{ "globPattern": "**/*.{v,vh,sv,svh}" },
|
||||
{ "globPattern": tree.path.join("files.f").to_str().expect("utf-8") },
|
||||
]),
|
||||
"the filelist is watched by its own path"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_filelist_setting_replaces_the_registration() {
|
||||
// The watched path is baked into the registration, so the old one must
|
||||
// go and a new one take its place — otherwise the new filelist is
|
||||
// exactly the file nobody is watching.
|
||||
let tree = Tree::new("rewatch");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
tree.write("other.f", "rtl/a.sv\n");
|
||||
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
assert_eq!(session.requests().len(), 1, "the registration made at startup");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 2, "{requests:#?}");
|
||||
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
|
||||
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-0");
|
||||
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
||||
let registration = &requests[1].1["registrations"][0];
|
||||
assert_eq!(registration["id"], "lucisv-watched-files-1", "a fresh id");
|
||||
assert_eq!(
|
||||
registration["registerOptions"]["watchers"][1]["globPattern"],
|
||||
tree.path.join("files.f").to_str().expect("utf-8").to_string()
|
||||
);
|
||||
|
||||
// The same value again moves nothing, so nothing is re-registered.
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
||||
assert!(session.requests().is_empty(), "re-pushing the same path is not a change");
|
||||
|
||||
// A different one is.
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("other.f"));
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 2, "{requests:#?}");
|
||||
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-1");
|
||||
assert_eq!(
|
||||
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
||||
tree.path.join("other.f").to_str().expect("utf-8").to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_is_not_re_registered_either() {
|
||||
let tree = Tree::new("norewatch");
|
||||
tree.write("files.f", "\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
||||
assert!(session.requests().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_notification_rebuilds_the_index_once_however_many_files_it_names() {
|
||||
// The `git checkout` shape. Rebuilding per event would re-scan the
|
||||
// workspace once per changed file for a single answer.
|
||||
let tree = Tree::new("oncepernotification");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
|
||||
|
||||
for i in 0..40 {
|
||||
tree.package(&format!("rtl/f{i}.sv"), &format!("p{i}"));
|
||||
}
|
||||
let changed: Vec<PathBuf> = (0..40).map(|i| tree.path.join(format!("rtl/f{i}.sv"))).collect();
|
||||
session.watched(&changed);
|
||||
assert_eq!(session.publishes(), 1, "one rebuild for the whole list");
|
||||
assert_eq!(indexed(&session, "p0"), 1, "and it really did rebuild");
|
||||
assert_eq!(indexed(&session, "p39"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_created_file_reaches_the_index_with_no_save_anywhere() {
|
||||
let tree = Tree::new("created");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(indexed(&session, "pulled"), 0, "premise: not there yet");
|
||||
|
||||
tree.package("rtl/pulled.sv", "pulled");
|
||||
session.watched(&[tree.path.join("rtl/pulled.sv")]);
|
||||
assert_eq!(indexed(&session, "pulled"), 1, "the `git pull` case");
|
||||
|
||||
// ... and a deletion is a change in the other direction.
|
||||
std::fs::remove_file(tree.path.join("rtl/pulled.sv")).expect("remove");
|
||||
session.watched(&[tree.path.join("rtl/pulled.sv")]);
|
||||
assert_eq!(indexed(&session, "pulled"), 0, "the `git checkout` case");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_event_for_a_file_outside_the_scope_still_rebuilds_but_indexes_nothing() {
|
||||
// The ladder re-applies during the rebuild, so an unlisted file stays
|
||||
// unlisted — and one rebuild for a stray in-tree source is cheaper than
|
||||
// deciding, per event, whether the filelist names it.
|
||||
let tree = Tree::new("outsidescope");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/unlisted.sv", "unlisted");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
assert_eq!(indexed(&session, "unlisted"), 0, "premise: the filelist omits it");
|
||||
|
||||
session.watched(&[tree.path.join("rtl/unlisted.sv")]);
|
||||
assert_eq!(indexed(&session, "a"), 1, "the listed file survives the rebuild");
|
||||
assert_eq!(indexed(&session, "unlisted"), 0, "and the unlisted one stays out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrelated_file_event_costs_no_rebuild() {
|
||||
let tree = Tree::new("stray");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
|
||||
|
||||
session.watched(&[tree.path.join("README.md"), tree.path.join("target/build.log")]);
|
||||
assert_eq!(session.publishes(), 0, "a stray event is dropped, not re-scanned");
|
||||
|
||||
session
|
||||
.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes: Vec::new() });
|
||||
assert_eq!(session.publishes(), 0, "and so is an empty notification");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_still_beats_disk_after_a_watched_file_rebuild() {
|
||||
// The rule the rebuild has always had, checked on the new path into
|
||||
// it: an external change must never clobber what the user is looking
|
||||
// at. Here the file on disk is *also* the open one, rewritten behind
|
||||
// the editor's back — the buffer still wins.
|
||||
let tree = Tree::new("overlay");
|
||||
tree.package("rtl/open.sv", "on_disk");
|
||||
let path = tree.path.join("rtl/open.sv");
|
||||
|
||||
let mut session = Session::wide(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&path, "package in_buffer;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(indexed(&session, "on_disk"), 1, "premise: indexed from disk at startup");
|
||||
|
||||
tree.package("rtl/open.sv", "rewritten_on_disk");
|
||||
session.watched(std::slice::from_ref(&path));
|
||||
assert_eq!(indexed(&session, "in_buffer"), 1, "the buffer wins the rebuild");
|
||||
assert_eq!(indexed(&session, "rewritten_on_disk"), 0, "disk loses");
|
||||
assert_eq!(indexed(&session, "on_disk"), 0, "and the stale copy is gone");
|
||||
let doc = session.server.workspace.document(&uri).expect("still open");
|
||||
assert!(doc.text.contains("in_buffer"), "and the buffer's own text is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_uri_helper_and_the_watch_filter_agree_about_the_filelist() {
|
||||
// `touches_scope` compares paths, and the path it compares against is
|
||||
// whatever `filelist_path` resolved — a mismatch would silently stop
|
||||
// filelist edits from rebuilding anything.
|
||||
let tree = Tree::new("filelistevent");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
assert_eq!(indexed(&session, "b"), 0, "premise: not listed yet");
|
||||
|
||||
tree.write("files.f", "rtl/a.sv\nrtl/b.sv\n");
|
||||
session.watched(&[tree.path.join("files.f")]);
|
||||
assert_eq!(session.publishes(), 1, "the filelist's own edit rebuilds");
|
||||
assert_eq!(indexed(&session, "b"), 1, "and the newly listed file is in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_watched_files_notification_is_dropped() {
|
||||
let tree = Tree::new("malformed");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
let _ = session.drain();
|
||||
|
||||
session.notify(DidChangeWatchedFiles::METHOD, serde_json::json!({ "changes": "nonsense" }));
|
||||
assert_eq!(session.publishes(), 0, "no id to answer on, so nothing happens");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_file_uri_in_an_event_is_ignored() {
|
||||
let tree = Tree::new("nonfileuri");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
let _ = session.drain();
|
||||
|
||||
let changes = vec![FileEvent {
|
||||
uri: Uri::from_str("untitled:Untitled-1").expect("uri"),
|
||||
typ: FileChangeType::CREATED,
|
||||
}];
|
||||
session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
|
||||
assert_eq!(session.publishes(), 0);
|
||||
}
|
||||
@@ -161,6 +161,19 @@ pub struct ClientSettings {
|
||||
/// files on disk that nobody asked for, this one is about the file on
|
||||
/// screen — see `docs/features/large-file-mode/README.md`.
|
||||
pub large_file_threshold: u64,
|
||||
/// `lucisv.lint.select`: run exactly these rules, replacing the default
|
||||
/// set — `lucisv check --select` and `lucisv.toml`'s `[lint] select`, said
|
||||
/// from the editor. Empty means "no opinion", which is the default set.
|
||||
///
|
||||
/// **Names are validated here**, against the rule registry, and an unknown
|
||||
/// one is dropped like every other unreadable value in this module: the
|
||||
/// CLI can fail a run over a typo because a user typed it and is watching,
|
||||
/// while a settings push arrives on a socket and failing it would leave an
|
||||
/// editor with no diagnostics and no way to see why.
|
||||
pub lint_select: Vec<String>,
|
||||
/// `lucisv.lint.ignore`: rules dropped from whatever `select` left. Same
|
||||
/// validation, same reason.
|
||||
pub lint_ignore: Vec<String>,
|
||||
}
|
||||
|
||||
/// The settings a client that said nothing is treated as having asked for.
|
||||
@@ -185,6 +198,8 @@ impl Default for ClientSettings {
|
||||
index_persist: true,
|
||||
index_cache_path: None,
|
||||
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
|
||||
lint_select: Vec::new(),
|
||||
lint_ignore: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,6 +229,8 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// `lucisv.largeFile.threshold` nests exactly as `index.*` does, for the
|
||||
// same reason: VS Code turns every dotted segment into an object.
|
||||
let large_file = lucisv.get("largeFile");
|
||||
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
|
||||
let lint = lucisv.get("lint");
|
||||
ClientSettings {
|
||||
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
|
||||
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
|
||||
@@ -255,9 +272,21 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// prevent.
|
||||
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
|
||||
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
|
||||
lint_select: rules(lint.and_then(|l| l.get("select"))),
|
||||
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule names in a settings array, dropping every one the registry does
|
||||
/// not know.
|
||||
///
|
||||
/// Silence rather than an error, on this module's standing rule: a push is
|
||||
/// JSON on a socket, and a typo in one name must not cost the user every
|
||||
/// diagnostic in the file. A dropped name leaves the rule where it was.
|
||||
fn rules(value: Option<&Value>) -> Vec<String> {
|
||||
strings(value).into_iter().filter(|name| vlog_linter::rule_by_name(name).is_some()).collect()
|
||||
}
|
||||
|
||||
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
|
||||
/// case and all — because the enum in `package.json` is what a settings UI
|
||||
/// offers, and forgiving `"Workspace"` here would make a typo mean something
|
||||
@@ -802,4 +831,49 @@ mod tests {
|
||||
assert!(ok("line-length = 40") && ok("line-length = 400"), "the line-length edges");
|
||||
assert!(!ok("line-length = 39") && !ok("line-length = 401"), "just outside line-length");
|
||||
}
|
||||
|
||||
/// `lucisv.lint.select` / `lucisv.lint.ignore` nest like every other dotted
|
||||
/// id, and carry only names the rule registry knows.
|
||||
#[test]
|
||||
fn the_lint_selection_is_read_and_validated() {
|
||||
let read = settings(json!({"lucisv": {"lint": {
|
||||
"select": ["unused-signal", "no-tabs"],
|
||||
"ignore": ["no-tabs"],
|
||||
}}}));
|
||||
assert_eq!(read.lint_select, vec!["unused-signal", "no-tabs"]);
|
||||
assert_eq!(read.lint_ignore, vec!["no-tabs"]);
|
||||
|
||||
// A name the registry does not know is dropped, not an error: a push
|
||||
// is JSON on a socket, and one typo must not cost every diagnostic.
|
||||
let typo = settings(json!({"lucisv": {"lint": {
|
||||
"select": ["unused-signal", "unusedsignal", 7, null],
|
||||
"ignore": "no-tabs",
|
||||
}}}));
|
||||
assert_eq!(typo.lint_select, vec!["unused-signal"]);
|
||||
assert!(typo.lint_ignore.is_empty(), "an array is required");
|
||||
|
||||
// Absent, or absent-shaped, is "no opinion".
|
||||
assert!(settings(json!({"lucisv": {}})).lint_select.is_empty());
|
||||
assert!(settings(json!({"lucisv": {"lint": 3}})).lint_ignore.is_empty());
|
||||
assert!(ClientSettings::default().lint_select.is_empty());
|
||||
}
|
||||
|
||||
/// The pull door reads the same keys as the push door — the property the
|
||||
/// whole module is built on, asserted for the new keys too.
|
||||
#[test]
|
||||
fn a_pull_reads_the_lint_selection_the_same_way() {
|
||||
let pulled = from_section(&json!({"lint": {"ignore": ["unused-signal"]}}));
|
||||
assert_eq!(pulled.lint_ignore, vec!["unused-signal"]);
|
||||
assert_eq!(pulled, settings(json!({"lucisv": {"lint": {"ignore": ["unused-signal"]}}})));
|
||||
}
|
||||
|
||||
/// The rule names the settings accept are the ones `lucisv check` accepts:
|
||||
/// one registry, not a list copied into a schema.
|
||||
#[test]
|
||||
fn the_accepted_rule_names_are_the_registrys() {
|
||||
for rule in vlog_linter::all_rules() {
|
||||
let read = settings(json!({"lucisv": {"lint": {"ignore": [rule.name()]}}}));
|
||||
assert_eq!(read.lint_ignore, vec![rule.name()], "{}", rule.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,7 @@ fn utf16_len(text: &str) -> u32 {
|
||||
|
||||
/// Which of an instantiation's two lists the cursor is in.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
pub(crate) enum Kind {
|
||||
/// `sub #( ... )`
|
||||
Params,
|
||||
/// `sub u_sub ( ... )`
|
||||
@@ -116,11 +116,16 @@ enum Kind {
|
||||
}
|
||||
|
||||
/// The list the cursor is inside.
|
||||
struct List {
|
||||
module: String,
|
||||
kind: Kind,
|
||||
///
|
||||
/// `pub(crate)` since 2026-09-02: `completion.rs` asks the identical question
|
||||
/// when a `.` is typed with nothing before it, so that the popup after the dot
|
||||
/// and the signature card above it can never disagree about which module's
|
||||
/// list the cursor is in. See `docs/features/member-completion/README.md`.
|
||||
pub(crate) struct List {
|
||||
pub(crate) module: String,
|
||||
pub(crate) kind: Kind,
|
||||
/// Index of the `(` token that opens it.
|
||||
open: usize,
|
||||
pub(crate) open: usize,
|
||||
}
|
||||
|
||||
/// The innermost instantiation list the cursor sits in, if any.
|
||||
@@ -133,7 +138,7 @@ struct List {
|
||||
/// optionally with the module's own `#( ... )` in between. `foo(bar|)` inside
|
||||
/// a connected expression fails that test, because the token before `foo` is
|
||||
/// the `(` of the connection and not a name.
|
||||
fn enclosing_list(tokens: &[Token], offset: u32) -> Option<List> {
|
||||
pub(crate) fn enclosing_list(tokens: &[Token], offset: u32) -> Option<List> {
|
||||
let mut open: Vec<usize> = Vec::new();
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
if token.span.start >= offset {
|
||||
|
||||
@@ -190,6 +190,7 @@ impl Document {
|
||||
&self.semantics,
|
||||
&self.text,
|
||||
&self.line_index,
|
||||
&self.tokens,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1136,11 +1137,15 @@ impl Workspace {
|
||||
}
|
||||
},
|
||||
};
|
||||
// Lexed here rather than in one pass at the end, so that no part of a
|
||||
// scan is longer than one file — an open buffer's words are the ones
|
||||
// it was analyzed from and are not lexed a second time, exactly as
|
||||
// `Candidates::build` has always taken them.
|
||||
let words = known_words.unwrap_or_else(|| crate::candidates::words_in(text));
|
||||
// Read off the record rather than lexed here: since `FACTS_FORMAT` 13
|
||||
// a file's identifier census *is* one of its facts, so a cached hit
|
||||
// brings its words with it and a parse harvested them from the tokens
|
||||
// it already had. That retires the per-file re-lex a scan used to pay
|
||||
// for the completion word table (TODO §10's deferred item;
|
||||
// `docs/features/semantic-lints-on/README.md` has the measurement).
|
||||
// An open buffer's words are still the caller's, read off the tokens
|
||||
// it was analyzed from.
|
||||
let words = known_words.unwrap_or_else(|| facts.words().to_vec());
|
||||
scan.words.insert(path, words);
|
||||
scan.staged.push(facts);
|
||||
scan.staged_at.push(done);
|
||||
@@ -1324,7 +1329,15 @@ impl Workspace {
|
||||
}
|
||||
None => {
|
||||
self.index.update_file(path.to_path_buf(), &text);
|
||||
self.candidates.update_file(&self.index, path, &text);
|
||||
// The words come back out of the record the update
|
||||
// just wrote, so the file is lexed once rather than
|
||||
// twice (`FACTS_FORMAT` 13). A path the index somehow
|
||||
// does not hold falls back to lexing, which is what
|
||||
// this line always did.
|
||||
match self.index.facts_for(path).map(|facts| facts.words().to_vec()) {
|
||||
Some(words) => self.candidates.update_words(&self.index, path, words),
|
||||
None => self.candidates.update_file(&self.index, path, &text),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.includes.update_file(path, &text, self.index.files());
|
||||
|
||||
@@ -19,6 +19,7 @@ pub fn kind_label(kind: SymbolKind) -> &'static str {
|
||||
SymbolKind::Net => "net",
|
||||
SymbolKind::Var => "variable",
|
||||
SymbolKind::Param => "parameter",
|
||||
SymbolKind::LocalParam => "localparam",
|
||||
SymbolKind::Genvar => "genvar",
|
||||
SymbolKind::Typedef => "type",
|
||||
SymbolKind::EnumVariant => "enum variant",
|
||||
@@ -29,6 +30,12 @@ pub fn kind_label(kind: SymbolKind) -> &'static str {
|
||||
SymbolKind::Block => "block",
|
||||
SymbolKind::StructMember => "struct member",
|
||||
SymbolKind::Class => "class",
|
||||
SymbolKind::Constraint => "constraint",
|
||||
SymbolKind::Covergroup => "covergroup",
|
||||
SymbolKind::Coverpoint => "coverpoint",
|
||||
SymbolKind::Cross => "cross",
|
||||
SymbolKind::Property => "property",
|
||||
SymbolKind::Sequence => "sequence",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +53,7 @@ pub fn lsp_kind(kind: SymbolKind) -> LspKind {
|
||||
SymbolKind::Port | SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar => {
|
||||
LspKind::VARIABLE
|
||||
}
|
||||
SymbolKind::Param | SymbolKind::TfArg => LspKind::CONSTANT,
|
||||
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => LspKind::CONSTANT,
|
||||
SymbolKind::Typedef => LspKind::TYPE_PARAMETER,
|
||||
SymbolKind::EnumVariant => LspKind::ENUM_MEMBER,
|
||||
SymbolKind::Function | SymbolKind::Task => LspKind::FUNCTION,
|
||||
@@ -54,6 +61,21 @@ pub fn lsp_kind(kind: SymbolKind) -> LspKind {
|
||||
SymbolKind::Block => LspKind::MODULE,
|
||||
SymbolKind::StructMember => LspKind::FIELD,
|
||||
SymbolKind::Class => LspKind::CLASS,
|
||||
// A constraint is a named member of a class that holds a
|
||||
// declaration rather than code anyone calls, which is exactly what
|
||||
// LSP's `PROPERTY` is for; `FUNCTION` would promise a call site
|
||||
// that does not exist.
|
||||
SymbolKind::Constraint => LspKind::PROPERTY,
|
||||
// A covergroup is a named container whose members are reached with a
|
||||
// `.`, which is what `CLASS` means to an editor; a coverpoint and a
|
||||
// cross are named members of it that hold a declaration rather than
|
||||
// code, so they take `PROPERTY` for the reason a constraint does.
|
||||
SymbolKind::Covergroup => LspKind::CLASS,
|
||||
SymbolKind::Coverpoint | SymbolKind::Cross => LspKind::PROPERTY,
|
||||
// A property and a sequence are named declarations that take formal
|
||||
// arguments and are instantiated by name, which is what `FUNCTION`
|
||||
// means to an editor.
|
||||
SymbolKind::Property | SymbolKind::Sequence => LspKind::FUNCTION,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -247,9 +247,15 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
SymbolKind::Package => Highlight::Namespace,
|
||||
SymbolKind::Typedef => Highlight::Type,
|
||||
SymbolKind::EnumVariant => Highlight::EnumMember,
|
||||
SymbolKind::Param | SymbolKind::TfArg => Highlight::Parameter,
|
||||
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => Highlight::Parameter,
|
||||
SymbolKind::Function | SymbolKind::Task => Highlight::Function,
|
||||
SymbolKind::StructMember => Highlight::Property,
|
||||
SymbolKind::StructMember
|
||||
| SymbolKind::Constraint
|
||||
| SymbolKind::Coverpoint
|
||||
| SymbolKind::Cross => Highlight::Property,
|
||||
// A covergroup is a type-like container, the way a class is, and the
|
||||
// legend's indices are a wire contract that cannot gain a member.
|
||||
SymbolKind::Covergroup => Highlight::Class,
|
||||
SymbolKind::Port
|
||||
| SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
@@ -257,6 +263,9 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
| SymbolKind::Instance
|
||||
| SymbolKind::Clocking
|
||||
| SymbolKind::Block => Highlight::Variable,
|
||||
// A property and a sequence are named, instantiated by name and take
|
||||
// arguments, so they highlight the way a function does.
|
||||
SymbolKind::Property | SymbolKind::Sequence => Highlight::Function,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,7 +41,8 @@
|
||||
use lsp_types::{Location, Uri};
|
||||
use vlog_parser::ast::{
|
||||
AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind,
|
||||
Module, ParamPort, PortList, Stmt, StmtKind, TfArg, Typedef, TypedefKind,
|
||||
Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
|
||||
TypedefKind,
|
||||
};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind};
|
||||
@@ -171,7 +172,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
|
||||
ItemKind::DataDecl(d) => declarator_site(&d.ty, item.span, &d.declarators),
|
||||
ItemKind::PortDecl(p) => declarator_site(&p.ty, item.span, &p.declarators),
|
||||
ItemKind::ParamDecl(p) => declarator_site(&p.ty, item.span, &p.declarators),
|
||||
ItemKind::Typedef(t) => alias_site(t, item.span),
|
||||
ItemKind::Typedef(t) => alias_site(t, item.span, offset),
|
||||
ItemKind::Instantiation(i) => instance_site(i, item.span),
|
||||
ItemKind::Module(m) => module_site(m, offset),
|
||||
ItemKind::Class(c) => param_port_site(c.param_ports.as_deref().unwrap_or(&[]), offset)
|
||||
@@ -203,16 +204,36 @@ fn declarator_site<'a>(
|
||||
site(&ty.name, TextRange::new(span.start, first))
|
||||
}
|
||||
|
||||
/// `typedef state_t alias_t;` — the alias's own type. The other typedef
|
||||
/// spellings declare their type inline (`enum`, `struct`) or promise one
|
||||
/// elsewhere (`typedef class c;`), and so name nothing to jump to.
|
||||
fn alias_site(t: &Typedef, span: TextRange) -> Option<Site<'_>> {
|
||||
/// `typedef state_t alias_t;` — the alias's own type; and, since
|
||||
/// struct-members (2026-09-01), a `typedef struct { hdr_t hdr; … }` body,
|
||||
/// whose **fields** are declarations with types of their own and so have
|
||||
/// somewhere to jump to. An `enum` body declares its type inline and a
|
||||
/// `typedef class c;` promises one elsewhere, so both still name nothing.
|
||||
fn alias_site(t: &Typedef, span: TextRange, offset: u32) -> Option<Site<'_>> {
|
||||
match &t.kind {
|
||||
TypedefKind::Alias(ty) => site(&ty.name, TextRange::new(span.start, t.name_span.start)),
|
||||
TypedefKind::Struct(s) => struct_member_site(s, offset),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The field of a `struct`/`union` body the cursor is in, as a type site.
|
||||
///
|
||||
/// Inline nested bodies are descended first, so the innermost field wins — the
|
||||
/// generated-register-package shape (`struct packed { struct packed { logic q;
|
||||
/// } ctrl; }`) is nested arbitrarily deep. A field whose type *is* an inline
|
||||
/// aggregate has no name to jump to, and falls out through [`site`]'s own
|
||||
/// empty-name refusal rather than through a check here.
|
||||
fn struct_member_site(s: &StructType, offset: u32) -> Option<Site<'_>> {
|
||||
let member = s.members.iter().find(|m| m.span.contains(offset))?;
|
||||
if let Some(TypeExtra::Struct(nested)) = member.ty.inline() {
|
||||
if let Some(inner) = struct_member_site(nested, offset) {
|
||||
return Some(inner);
|
||||
}
|
||||
}
|
||||
declarator_site(&member.ty, member.span, &member.declarators)
|
||||
}
|
||||
|
||||
/// `sub u_sub (...)`, and every interface instance written the same way. The
|
||||
/// instance name's type is the module it instantiates.
|
||||
fn instance_site(i: &Instantiation, span: TextRange) -> Option<Site<'_>> {
|
||||
@@ -289,7 +310,7 @@ fn stmt_site(stmt: &Stmt, offset: u32) -> Option<Site<'_>> {
|
||||
// cursor on the alias name jumps one hop to the aliased type. Added
|
||||
// when `StmtKind::Typedef` landed (testbench-mopup, 2026-08-29) —
|
||||
// QA's blast-radius audit caught this arm missing.
|
||||
StmtKind::Typedef(t) => alias_site(t, stmt.span),
|
||||
StmtKind::Typedef(t) => alias_site(t, stmt.span, offset),
|
||||
StmtKind::VarDecl(d) => declarator_site(&d.ty, stmt.span, &d.declarators),
|
||||
StmtKind::ParamDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators),
|
||||
StmtKind::PortDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators),
|
||||
@@ -368,6 +389,49 @@ mod tests {
|
||||
dir
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// casts — `docs/features/comment-slots/README.md` (M11)
|
||||
//
|
||||
// The doc comment on `type_name` has always claimed case 2 "is what
|
||||
// reaches a cast (`state_t'(0)`)". It only became true when `bind_expr`
|
||||
// started binding the casting type; these pin it.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_cast_reaches_the_typedef_it_names() {
|
||||
let text = "\
|
||||
module m;
|
||||
typedef logic [1:0] state_t;
|
||||
logic [1:0] s;
|
||||
initial s = state_t'(0);
|
||||
endmodule
|
||||
";
|
||||
let (ws, uri) = document(text);
|
||||
let cursor = text.rfind("state_t'").expect("the cast") as u32 + 2;
|
||||
assert_eq!(jumps(&ws, &uri, cursor), vec![(1, 22)], "the `typedef` line's name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keyword_cast_asks_nothing_of_the_index() {
|
||||
let text = "module m;\n initial x = int'(y);\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
assert!(jumps(&ws, &uri, at(text, "int'") + 1).is_empty(), "`int` declares nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sized_or_computed_cast_answers_for_its_own_operand() {
|
||||
// `$bits(t)'(x)` and `(N)'(x)` are widths, not type names: the cursor
|
||||
// inside them is on an ordinary use, and answers as one.
|
||||
let text = "\
|
||||
module m;
|
||||
typedef logic [3:0] nib_t;
|
||||
initial a = $bits(nib_t)'(x);
|
||||
endmodule
|
||||
";
|
||||
let (ws, uri) = document(text);
|
||||
assert_eq!(jumps(&ws, &uri, at(text, "nib_t)") + 1), vec![(1, 22)], "the typedef");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// in-file types
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -125,7 +125,15 @@ pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyIt
|
||||
found
|
||||
}
|
||||
|
||||
/// The base classes of the class an item names, in the file it names.
|
||||
/// The supertypes of the class an item names, in the file it names: the one
|
||||
/// it `extends`, and every interface class it `implements`.
|
||||
///
|
||||
/// Both clauses are edges of the same graph — a class's method set comes from
|
||||
/// its base *and* from every interface it promises to implement — and both
|
||||
/// resolve through the same hop, so they are read together here. `implements`
|
||||
/// joined in `vendor-formal-grammar` (2026-09-02), when `interface class`
|
||||
/// became an ordinary class declaration and there was finally something to
|
||||
/// point at.
|
||||
fn bases_of(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
@@ -135,16 +143,24 @@ fn bases_of(
|
||||
let positions = doc.positions();
|
||||
let at = span(&positions, item.selection_range);
|
||||
let Some(decl) = find_class(&doc.tree.items, &item.name, Some(at)) else { return Vec::new() };
|
||||
let Some(extends) = decl.class.extends.as_ref() else { return Vec::new() };
|
||||
if extends.name_span.is_empty() {
|
||||
return Vec::new();
|
||||
let mut out = Vec::new();
|
||||
// The last byte of a supertype's name span. For `pkg::base` that is inside
|
||||
// the *tail's* own reference, which is the one that names a class — the
|
||||
// head names the package. For a bare `base` it is that one reference.
|
||||
// Either way the answer comes from the same two layers
|
||||
// `textDocument/definition` uses, so a supertype in another file needs no
|
||||
// lookup of this feature's own.
|
||||
if let Some(extends) = decl.class.extends.as_ref() {
|
||||
if !extends.name_span.is_empty() {
|
||||
out.extend(classes_at(ws, doc, uri, extends.name_span.end - 1));
|
||||
}
|
||||
}
|
||||
// The last byte of the base-name span. For `pkg::base` that is inside the
|
||||
// *tail's* own reference, which is the one that names a class — the head
|
||||
// names the package. For a bare `base` it is that one reference. Either
|
||||
// way the answer comes from the same two layers `textDocument/definition`
|
||||
// uses, so a base in another file needs no lookup of this feature's own.
|
||||
classes_at(ws, doc, uri, extends.name_span.end - 1)
|
||||
for name in &decl.class.implements {
|
||||
if !name.span.is_empty() {
|
||||
out.extend(classes_at(ws, doc, uri, name.span.end - 1));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every class declaration the name at `offset` resolves to, through both
|
||||
@@ -451,14 +467,18 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_class_is_not_a_node_because_the_parser_does_not_model_one() {
|
||||
// `interface class` is a different construct (IEEE 1800 §8.26) that
|
||||
// `vlog_parser` rejects, so it never becomes a `ClassDecl` and there is
|
||||
// no item — and no `SymbolKind::INTERFACE` case — to build. Pinned so a
|
||||
// future parser round that models it is forced past this test.
|
||||
fn an_interface_class_is_a_node() {
|
||||
// Was `..._is_not_a_node_because_the_parser_does_not_model_one` until
|
||||
// `vendor-formal-grammar` (2026-09-02) made `interface class` an
|
||||
// ordinary `ClassDecl` carrying the word in its prefix. It declares a
|
||||
// class symbol, so it prepares like any other class — which is what
|
||||
// gives the `implements` edge below something to point at.
|
||||
let text = "interface class ic;\n pure virtual function void f();\nendclass\n";
|
||||
let (_tree, ws, uri) = workspace("ifaceclass", &[("ic.sv", text)]);
|
||||
assert!(prepare(&ws, &uri, at(text, "ic")).is_none());
|
||||
let items = prepare(&ws, &uri, at(text, "ic")).expect("the interface class");
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].name, "ic");
|
||||
assert!(supertypes(&ws, &items[0]).is_empty(), "and it implements nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -555,16 +575,30 @@ endclass
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_implements_clause_names_no_supertype() {
|
||||
// `implements` names an *interface* class, which `vlog_parser` does not
|
||||
// model — so there is never a declaration to point at, and matching one
|
||||
// by name would claim an unrelated ordinary class. Only `extends` is an
|
||||
// edge here.
|
||||
let base = "class base;\nendclass\n";
|
||||
let child = "class child implements base;\nendclass\n";
|
||||
let (_tree, ws, uri) = workspace("implements", &[("child.sv", child), ("base.sv", base)]);
|
||||
fn an_implements_clause_names_a_supertype() {
|
||||
// Was `..._names_no_supertype` until `vendor-formal-grammar`
|
||||
// (2026-09-02): `implements` names an interface class, and now that one
|
||||
// is a `ClassDecl` there is a declaration to point at. The hop is the
|
||||
// same one `extends` takes, so a supertype in another file works with
|
||||
// no lookup of this feature's own.
|
||||
let base = "interface class api;\n pure virtual function void f();\nendclass\n";
|
||||
let child = "class child implements api;\nendclass\n";
|
||||
let (_tree, ws, uri) = workspace("implements", &[("child.sv", child), ("api.sv", base)]);
|
||||
let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone();
|
||||
assert!(supertypes(&ws, &root).is_empty(), "pinning today's answer and its reason");
|
||||
let bases = supertypes(&ws, &root);
|
||||
assert_eq!(shape(&bases[0]), ("api".to_string(), "api.sv".to_string(), 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extends_and_implements_are_both_edges_of_the_same_answer() {
|
||||
let api = "interface class api;\nendclass\n";
|
||||
let base = "class base;\nendclass\n";
|
||||
let child = "class child extends base implements api;\nendclass\n";
|
||||
let (_tree, ws, uri) =
|
||||
workspace("both", &[("child.sv", child), ("base.sv", base), ("api.sv", api)]);
|
||||
let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone();
|
||||
let names: Vec<String> = supertypes(&ws, &root).iter().map(|i| i.name.clone()).collect();
|
||||
assert_eq!(names, ["base", "api"], "the base first, then the interfaces, in source order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,9 @@
|
||||
//! A fenced region is emitted as the exact source bytes it was written with,
|
||||
//! so nothing inside it is ever laid out. This module answers the two
|
||||
//! questions that makes possible: which comments are fences, and which byte
|
||||
//! ranges they select. Full spec: `docs/features/format-fences/README.md`.
|
||||
//! ranges they select. Full spec: `docs/features/format-fences/README.md`,
|
||||
//! plus `docs/features/statement-fences/README.md` for the class-body and
|
||||
//! statement-list scopes.
|
||||
//!
|
||||
//! [`protected_regions`] and [`is_protected`] are the same answer for the
|
||||
//! tools that only *edit* fenced bytes rather than lay them out — the CLI's
|
||||
@@ -11,7 +13,10 @@
|
||||
//! there is one definition of "what is fenced": see
|
||||
//! `docs/features/shared-fence-filter/README.md`.
|
||||
|
||||
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile};
|
||||
use vlog_parser::ast::{
|
||||
Fragment, GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile, Stmt, StmtKind,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
@@ -54,7 +59,15 @@ pub struct Region {
|
||||
/// Every fenced region in `file`, sorted and non-overlapping.
|
||||
pub fn collect(src: &str, file: &SourceFile) -> Vec<Region> {
|
||||
let mut found = Vec::new();
|
||||
scan_scope(src, &file.items, &file.dangling, &mut found);
|
||||
match &file.fragment {
|
||||
// A statement fragment is one statement list standing at file scope,
|
||||
// its dangling comments ending it exactly as a file's items' do. The
|
||||
// other fragment shapes are element lists, which are not fenceable.
|
||||
Some(Fragment::Statements(stmts)) => {
|
||||
scan_stmt_scope(src, stmts, &file.dangling, &mut found)
|
||||
}
|
||||
_ => scan_scope(src, &file.items, &file.dangling, &mut found),
|
||||
}
|
||||
found.sort_by_key(|r| r.fence);
|
||||
// A region inside an already-fenced range never runs: the items holding
|
||||
// it are emitted as source bytes, so they are never formatted. Dropping
|
||||
@@ -146,50 +159,73 @@ fn scanned_regions(src: &str) -> Vec<Region> {
|
||||
regions
|
||||
}
|
||||
|
||||
/// Scan one item-list scope, then its nested scopes.
|
||||
/// Scan one flat stream of units — each unit's leading comments, then its own
|
||||
/// code extent — followed by the scope's dangling comments.
|
||||
///
|
||||
/// The scope is a flat stream of units — each item's leading comments, then
|
||||
/// the item's own code — followed by the dangling comments. A region opens at
|
||||
/// the first `off` in that stream and closes at the first `on` after it;
|
||||
/// anything else, including a second `off`, is just text.
|
||||
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
|
||||
/// A region opens at the first `off` in that stream and closes at the first
|
||||
/// `on` after it; anything else, including a second `off`, is just text. An
|
||||
/// item list and a statement list have exactly this shape, and it is the only
|
||||
/// shape a fence pairs inside, which is why both scan through here.
|
||||
fn scan_units<'u>(
|
||||
src: &str,
|
||||
units: impl Iterator<Item = (&'u [Comment], TextRange)>,
|
||||
dangling: &[Comment],
|
||||
out: &mut Vec<Region>,
|
||||
) {
|
||||
let mut open: Option<Region> = None;
|
||||
let mut scope_end = 0usize;
|
||||
for item in items {
|
||||
for c in &item.meta.leading {
|
||||
for (leading, span) in units {
|
||||
for c in leading {
|
||||
// An attribute followed by a comment puts a "leading" comment
|
||||
// *after* the item's span starts. Opening a region there would
|
||||
// *after* the unit's span starts. Opening a region there would
|
||||
// emit the attribute twice, so such comments are not fences.
|
||||
if c.span.start < item.span.start {
|
||||
if c.span.start < span.start {
|
||||
step(src, c, &mut open, out);
|
||||
}
|
||||
}
|
||||
// A leading comment always ends before its item's code does, so the
|
||||
// item's own end is the scope's high-water mark.
|
||||
scope_end = item.span.end as usize;
|
||||
// A leading comment always ends before its unit's code does, so the
|
||||
// unit's own end is the scope's high-water mark.
|
||||
scope_end = span.end as usize;
|
||||
}
|
||||
for c in dangling {
|
||||
step(src, c, &mut open, out);
|
||||
scope_end = c.span.end as usize;
|
||||
}
|
||||
if let Some(mut r) = open {
|
||||
// An unmatched `off` runs to the end of the scope. The last item's
|
||||
// An unmatched `off` runs to the end of the scope. The last unit's
|
||||
// span stops before the comment trailing it on the same line, and
|
||||
// `Meta.trailing` has no span to consult, so that comment has to be
|
||||
// picked up from the source or it would be dropped.
|
||||
r.end = with_trailing_comments(src, scope_end);
|
||||
out.push(r);
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan one item-list scope, then its nested scopes.
|
||||
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
|
||||
scan_units(src, items.iter().map(|i| (i.meta.leading.as_slice(), i.span)), dangling, out);
|
||||
for item in items {
|
||||
scan_nested(src, item, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan one statement-list scope, then its nested scopes.
|
||||
///
|
||||
/// The statement twin of [`scan_scope`], unit for unit — which is what keeps a
|
||||
/// region aligned with statement boundaries and stops an unmatched `off` at the
|
||||
/// list's end rather than at the `end`, `join` or `endfunction` past it.
|
||||
fn scan_stmt_scope(src: &str, stmts: &[Stmt], dangling: &[Comment], out: &mut Vec<Region>) {
|
||||
scan_units(src, stmts.iter().map(|s| (s.meta.leading.as_slice(), s.span)), dangling, out);
|
||||
for stmt in stmts {
|
||||
scan_nested_stmt(src, stmt, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Advance the open/closed state by one comment unit.
|
||||
fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>) {
|
||||
let start = c.span.start as usize;
|
||||
match (fence_of(&c.text), open.is_some()) {
|
||||
(Some(Fence::Off), false) => {
|
||||
(Some(Fence::Off), false) if opens_line(src, start) => {
|
||||
*open = Some(Region { fence: start, start: line_start(src, start), end: 0 })
|
||||
}
|
||||
(Some(Fence::On), true) => {
|
||||
@@ -202,8 +238,8 @@ fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>
|
||||
}
|
||||
}
|
||||
|
||||
/// Item scopes nested inside one item. Statement bodies are not scanned:
|
||||
/// statement-level fences are out of scope (see the feature README).
|
||||
/// Scopes nested inside one item: the item lists, and the statement lists an
|
||||
/// item's body reaches.
|
||||
fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
|
||||
@@ -216,6 +252,57 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
|
||||
scan_gen_block(src, &i.body, out);
|
||||
}
|
||||
}
|
||||
ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out),
|
||||
ItemKind::Function(f) => scan_stmt_scope(src, &f.stmts, &f.dangling, out),
|
||||
ItemKind::Task(t) => scan_stmt_scope(src, &t.stmts, &t.dangling, out),
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
scan_nested_stmt(src, stmt, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Statement scopes nested inside one statement.
|
||||
///
|
||||
/// A statement *list* is a scope — `begin`…`end`, `fork`…`join*`. A
|
||||
/// single-statement body is not, for the reason [`scan_gen_block`] refuses a
|
||||
/// block-less generate item: there is no list for a fence to end in, and the
|
||||
/// formatter lays that statement out inside a `Group`. So the bodies below are
|
||||
/// walked into rather than scanned, and only the block one of them holds opens
|
||||
/// a scope.
|
||||
fn scan_nested_stmt(src: &str, stmt: &Stmt, out: &mut Vec<Region>) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
|
||||
scan_stmt_scope(src, stmts, dangling, out)
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
scan_nested_stmt(src, then, out);
|
||||
if let Some(e) = els {
|
||||
scan_nested_stmt(src, e, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
for s in then.iter().chain(els.iter()) {
|
||||
scan_nested_stmt(src, s, out);
|
||||
}
|
||||
}
|
||||
// A case item's *labels* are not a fenceable stream (see the feature
|
||||
// README); the block one of them may hold is.
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for i in items {
|
||||
scan_nested_stmt(src, &i.stmt, out);
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. }
|
||||
| StmtKind::Labeled { stmt: body, .. } => scan_nested_stmt(src, body, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
scan_nested_stmt(src, inner, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -242,6 +329,30 @@ fn scan_gen_block(src: &str, b: &GenBlock, out: &mut Vec<Region>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a fence written at `at` begins the *content* of its line: nothing
|
||||
/// but whitespace and finished block comments precedes it there.
|
||||
///
|
||||
/// This is what makes `begin // lucisv: off` an ordinary comment. The parser
|
||||
/// hands a comment written after `begin` to the next *statement* as a leading
|
||||
/// one, so without this test a region would open in the middle of a line and
|
||||
/// take its first line's bytes from the wrong column. A fence preceded only by
|
||||
/// another comment (`/* a */ // lucisv: off`) still opens one: that comment is
|
||||
/// a unit of the same stream and prints on the line above.
|
||||
fn opens_line(src: &str, at: usize) -> bool {
|
||||
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
|
||||
let Some(mut before) = src.get(bol..at) else { return false };
|
||||
loop {
|
||||
before = before.trim_start();
|
||||
if before.is_empty() {
|
||||
return true;
|
||||
}
|
||||
match before.strip_prefix("/*").and_then(|b| b.split_once("*/")) {
|
||||
Some((_, rest)) => before = rest,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of the line `at` sits on, when nothing but whitespace precedes it
|
||||
/// there — otherwise `at` itself, so a fence sharing its line with another
|
||||
/// comment does not swallow it.
|
||||
@@ -323,6 +434,28 @@ mod tests {
|
||||
assert_eq!(fence_of("// off"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_only_opens_a_region_at_the_start_of_its_line() {
|
||||
// Whitespace before it, at any depth, and at the very first byte.
|
||||
assert!(opens_line("// lucisv: off\n", 0));
|
||||
assert!(opens_line("module m;\n // lucisv: off\n", 12));
|
||||
assert!(opens_line("module m;\n\t\t// lucisv: off\n", 12));
|
||||
// Another comment before it is still the start of the line's content.
|
||||
let src = "module m;\n /* a */ // lucisv: off\n";
|
||||
assert!(opens_line(src, src.find("//").expect("fence")));
|
||||
let src = "module m;\n /* a */ /* b */ // lucisv: off\n";
|
||||
assert!(opens_line(src, src.find("//").expect("fence")));
|
||||
// Code before it is not — the two shapes the parser hands to the next
|
||||
// node as a *leading* comment even though they trail code.
|
||||
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n";
|
||||
assert!(!opens_line(src, src.find("//").expect("fence")));
|
||||
let src = "module m; // lucisv: off\n wire a;\n";
|
||||
assert!(!opens_line(src, src.find("//").expect("fence")));
|
||||
// An unterminated block comment before it is not a finished comment.
|
||||
let src = "module m;\n /* a // lucisv: off\n";
|
||||
assert!(!opens_line(src, src.find("// lucisv").expect("fence")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_line_starts_at_its_indentation() {
|
||||
let src = "module m;\n // lucisv: off\n";
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,369 @@
|
||||
//! Classes and constraints: the `class` header and body, and every
|
||||
//! constraint form — the `constraint c { ... }` declaration, a
|
||||
//! `randomize() with { ... }` block, the `->`/`if`/`foreach`/`solve`/
|
||||
//! `unique` items, and the `dist` weight list an expression may end in.
|
||||
//!
|
||||
//! Covergroups, the other DV construct a class holds, are large enough
|
||||
//! to be a sibling module (`cover.rs`).
|
||||
|
||||
use crate::doc::*;
|
||||
use crate::printer::contains_hard_line;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::list::ListItem;
|
||||
use super::{join_names, named, Fmt};
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// A class: header on one line (its parameter and `extends` override
|
||||
/// lists break like any other list when they do not fit), body items at
|
||||
/// one more indent level, `endclass` with the label the source wrote.
|
||||
pub(super) fn class(&self, c: &ClassDecl, depth: usize) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
self.qualifier_run(&c.prefix, &mut docs);
|
||||
docs.push(text("class"));
|
||||
// `class /*c*/ c` — and, when a lifetime was written, whatever stood
|
||||
// on either side of it; both gaps land in the one slot, which prints
|
||||
// between the keyword run and the name.
|
||||
if c.before_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&c.before_name, &mut docs);
|
||||
}
|
||||
if let Some(lifetime) = &c.lifetime {
|
||||
docs.push(text(format!("{lifetime} ")));
|
||||
}
|
||||
docs.push(text(named(&c.name)));
|
||||
let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false);
|
||||
if let Some(params) = &c.param_ports {
|
||||
let items: Vec<ListItem> = params
|
||||
.iter()
|
||||
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
|
||||
.collect();
|
||||
let items = self.list_entries(items, &c.param_directives);
|
||||
let broken = !c.param_directives.is_empty();
|
||||
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
||||
self.slot_comments(&c.param_after_hash, &mut docs);
|
||||
docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken));
|
||||
}
|
||||
if let Some(ext) = &c.extends {
|
||||
docs.push(text(format!(" extends {}", named(&ext.name))));
|
||||
let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false);
|
||||
if let Some(params) = &ext.params {
|
||||
let items: Vec<ListItem> = params
|
||||
.iter()
|
||||
.map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma))
|
||||
.collect();
|
||||
let items = self.list_entries(items, &ext.param_directives);
|
||||
let broken = !ext.param_directives.is_empty();
|
||||
docs.push(text(if fresh { "#" } else { " #" }));
|
||||
self.slot_comments(&ext.after_hash, &mut docs);
|
||||
docs.push(self.delimited("(", items, ")", broken));
|
||||
}
|
||||
}
|
||||
if !c.implements.is_empty() {
|
||||
docs.push(text(format!(" implements {}", join_names(&c.implements))));
|
||||
}
|
||||
docs.push(self.semi(&c.before_semi));
|
||||
let mut body = Vec::new();
|
||||
if !c.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&c.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&c.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("endclass", &c.end_label, &c.end_label_comments));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `[qualifiers ]constraint [cls::]name { ... }`, or the `constraint c;`
|
||||
/// prototype.
|
||||
///
|
||||
/// A named constraint is a *block*, so it is laid out like one: the
|
||||
/// header keeps the `{`, every constraint item takes a line of its own at
|
||||
/// one further indent, and the `}` closes back at the header's column.
|
||||
/// That supersedes the `classes` README's "no layout convention worth
|
||||
/// inventing" — there was none while the body was opaque bytes; now that
|
||||
/// it is navigable, one canonical shape is worth exactly what canonical
|
||||
/// shapes are always worth.
|
||||
pub(super) fn constraint(&self, c: &ConstraintDecl) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
self.qualifier_run(&c.qualifiers, &mut docs);
|
||||
docs.push(text("constraint"));
|
||||
self.inline_comments_spaced(&c.before_name, &mut docs);
|
||||
self.scope_prefix(&c.scope, &mut docs);
|
||||
let name = named(&c.name.text);
|
||||
// `named` already wrote the space an escaped identifier needs; a
|
||||
// second one would be a gratuitous re-spacing of the header.
|
||||
let escaped = name.ends_with(' ');
|
||||
docs.push(text(name));
|
||||
let ends_line = self.inline_comments(&c.after_name, &mut docs);
|
||||
let Some(set) = &c.body else {
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
return concat(docs);
|
||||
};
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !escaped || !c.after_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.constraint_block(set, false));
|
||||
if c.semi {
|
||||
if self.inline_comments(&c.before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// The `{ ... }` of a constraint body or a nested constraint set.
|
||||
///
|
||||
/// `flat_ok` allows the whole block onto one line when nothing inside it
|
||||
/// forces a break — the shape a `randomize() with { addr == 0; }` is
|
||||
/// written in. A `constraint` declaration never passes it: a declaration
|
||||
/// is a block and reads as one.
|
||||
fn constraint_block(&self, set: &ConstraintSet, flat_ok: bool) -> Doc {
|
||||
let brk = if flat_ok { Doc::SoftLine } else { Doc::HardLine };
|
||||
let mut body = Vec::new();
|
||||
if !set.items.is_empty() {
|
||||
body.push(brk.clone());
|
||||
body.extend(self.constraint_items(&set.items));
|
||||
}
|
||||
body.extend(self.dangling(&set.dangling));
|
||||
if body.is_empty() {
|
||||
return text("{}");
|
||||
}
|
||||
group(vec![text("{"), indent(body), brk, text("}")])
|
||||
}
|
||||
|
||||
/// The block of a `randomize() with { ... }`: the same layout, but kept on
|
||||
/// the statement's line when the **source** wrote it on one line.
|
||||
///
|
||||
/// A `with` block is written inside a statement, not standing as a
|
||||
/// declaration, and `if (!req.randomize() with { addr == 0; })` is the
|
||||
/// idiom every DV testbench writes. The question is asked of the source
|
||||
/// rather than measured, for two reasons. It is a fact about the gap
|
||||
/// between two tokens, which is the one thing the formatter already reads
|
||||
/// `src` for (`glued_null_item`, `default_has_colon`). And it is a fixed
|
||||
/// point by construction: a flattened block is one line, so the next pass
|
||||
/// flattens it again; a broken one holds newlines, so the next pass
|
||||
/// breaks it again.
|
||||
///
|
||||
/// Reading the source also settles the `//` question for free: a line
|
||||
/// comment needs a newline to end, so a one-line block cannot hold one,
|
||||
/// and a flattened `}` can never land inside a comment. The
|
||||
/// `contains_hard_line` check is the belt to that braces — anything else
|
||||
/// that forces a break takes the block layout.
|
||||
pub(super) fn with_constraint_block(&self, set: &ConstraintSet) -> Doc {
|
||||
if self.src.get(set.span.as_range()).is_some_and(|s| !s.contains('\n')) {
|
||||
let flat = self.constraint_block(set, true);
|
||||
if !contains_hard_line(std::slice::from_ref(&flat)) {
|
||||
return flat;
|
||||
}
|
||||
}
|
||||
self.constraint_block(set, false)
|
||||
}
|
||||
|
||||
fn constraint_items(&self, items: &[ConstraintItem]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(self.with_meta(&item.meta, self.constraint_item(item)));
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// One constraint item, and the `;` that ends it when its kind takes one.
|
||||
///
|
||||
/// The `;` is written here rather than in each arm so that the comments
|
||||
/// the source wrote in front of it have exactly one place to be printed:
|
||||
/// on the item's side of the separator, which is where they were
|
||||
/// written. [`ConstraintItemKind::takes_semi`] is the one answer both
|
||||
/// this and the parser read.
|
||||
fn constraint_item(&self, item: &ConstraintItem) -> Doc {
|
||||
let mut docs = vec![self.constraint_item_kind(&item.kind)];
|
||||
if item.kind.takes_semi() {
|
||||
if self.inline_comments(&item.before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn constraint_item_kind(&self, kind: &ConstraintItemKind) -> Doc {
|
||||
match kind {
|
||||
ConstraintItemKind::Expr { soft, after_soft, expr } => {
|
||||
if !*soft {
|
||||
return self.expr(expr);
|
||||
}
|
||||
let mut docs = vec![text("soft")];
|
||||
self.inline_comments_spaced(after_soft, &mut docs);
|
||||
docs.push(self.expr(expr));
|
||||
concat(docs)
|
||||
}
|
||||
ConstraintItemKind::Implication { cond, comments, set } => {
|
||||
let mut head = vec![self.expr(cond)];
|
||||
self.inline_comments_spaced(&comments.before, &mut head);
|
||||
head.push(text("->"));
|
||||
let ends_line = self.inline_comments(&comments.after, &mut head);
|
||||
if ends_line {
|
||||
head.push(Doc::HardLine);
|
||||
}
|
||||
self.constraint_set_as_body(concat(head), set, &[], !ends_line)
|
||||
}
|
||||
ConstraintItemKind::If { cond, comments, then, else_comments, after_else, els } => {
|
||||
let mut head = vec![text("if")];
|
||||
self.inline_comments_spaced(&comments.after_kw, &mut head);
|
||||
head.push(self.constraint_parens(cond, comments));
|
||||
let mut docs = vec![self.constraint_set_as_body(
|
||||
concat(head),
|
||||
then,
|
||||
&comments.before_body,
|
||||
true,
|
||||
)];
|
||||
let Some(els) = els else { return concat(docs) };
|
||||
// A braced `then` cuddles the `else` onto the `}` line, the
|
||||
// way a statement `if` cuddles it onto `end`.
|
||||
docs.push(if then.braced { text(" ") } else { Doc::HardLine });
|
||||
for c in else_comments {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
// `else if` chains on one line, the way a statement `if` does:
|
||||
// an unbraced else holding exactly one `if` is the chain, and
|
||||
// indenting it once per link would stair-step the whole thing
|
||||
// off the right of the page.
|
||||
match Self::chained_if(els) {
|
||||
Some(item) => {
|
||||
let mut chain = vec![text("else")];
|
||||
self.inline_comments_spaced(after_else, &mut chain);
|
||||
chain.push(self.with_meta(&item.meta, self.constraint_item(item)));
|
||||
docs.push(concat(chain));
|
||||
}
|
||||
None => {
|
||||
docs.push(self.constraint_set_as_body(text("else"), els, after_else, true))
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
ConstraintItemKind::Foreach { array, vars, var_comments, comments, set } => {
|
||||
let mut head = vec![text("foreach")];
|
||||
self.inline_comments_spaced(&comments.after_kw, &mut head);
|
||||
head.push(text("("));
|
||||
self.inline_comments(&comments.after_open, &mut head);
|
||||
if !comments.after_open.is_empty() {
|
||||
head.push(text(" "));
|
||||
}
|
||||
head.push(self.expr(array));
|
||||
head.push(self.foreach_vars(vars, var_comments));
|
||||
if self.inline_comments(&comments.before_close, &mut head) {
|
||||
head.push(Doc::HardLine);
|
||||
} else if !comments.before_close.is_empty() {
|
||||
head.push(text(" "));
|
||||
}
|
||||
head.push(text(")"));
|
||||
self.constraint_set_as_body(concat(head), set, &comments.before_body, true)
|
||||
}
|
||||
ConstraintItemKind::SolveBefore { solve, before_comments, before } => {
|
||||
let mut docs = vec![text("solve "), self.plain_expr_list(solve)];
|
||||
self.inline_comments_spaced(before_comments, &mut docs);
|
||||
docs.push(text("before "));
|
||||
docs.push(self.plain_expr_list(before));
|
||||
concat(docs)
|
||||
}
|
||||
ConstraintItemKind::Unique { items, comments } => {
|
||||
let mut docs = vec![text("unique")];
|
||||
self.inline_comments_spaced(comments, &mut docs);
|
||||
docs.push(self.expr_list("{", items, "}"));
|
||||
concat(docs)
|
||||
}
|
||||
ConstraintItemKind::DisableSoft { expr, comments } => {
|
||||
let mut docs = vec![text("disable")];
|
||||
self.inline_comments_spaced(&comments.before, &mut docs);
|
||||
docs.push(text("soft"));
|
||||
self.inline_comments_spaced(&comments.after, &mut docs);
|
||||
docs.push(self.expr(expr));
|
||||
concat(docs)
|
||||
}
|
||||
ConstraintItemKind::Directive(raw) => self.raw_text(raw),
|
||||
ConstraintItemKind::Empty => text(";"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `( cond )` of a constraint `if`, with the comments written just
|
||||
/// inside either parenthesis printed back where they were written.
|
||||
fn constraint_parens(&self, cond: &Expr, comments: &HeaderComments) -> Doc {
|
||||
self.guard_parens(cond, &comments.after_open, &comments.before_close)
|
||||
}
|
||||
|
||||
/// The `if` an `else` chains straight onto: the single item of an
|
||||
/// unbraced `else` set, when that item is itself an `if`.
|
||||
fn chained_if(set: &ConstraintSet) -> Option<&ConstraintItem> {
|
||||
if set.braced || set.items.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let item = set.items.first()?;
|
||||
matches!(item.kind, ConstraintItemKind::If { .. }).then_some(item)
|
||||
}
|
||||
|
||||
/// A header followed by a constraint set: a braced set cuddles onto the
|
||||
/// header line, an unbraced one goes on the same line if it fits and on
|
||||
/// an indented next line if it does not — exactly what
|
||||
/// [`Fmt::stmt_as_body`] does for statements.
|
||||
fn constraint_set_as_body(
|
||||
&self,
|
||||
head: Doc,
|
||||
set: &ConstraintSet,
|
||||
before: &[Comment],
|
||||
space: bool,
|
||||
) -> Doc {
|
||||
if set.braced {
|
||||
let mut docs = vec![head];
|
||||
if self.inline_comments(before, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if space || !before.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.constraint_block(set, false));
|
||||
return concat(docs);
|
||||
}
|
||||
let body = match set.items.first() {
|
||||
Some(item) => self.with_meta(&item.meta, self.constraint_item(item)),
|
||||
None => text(""),
|
||||
};
|
||||
group(vec![head, indent(vec![Doc::Line, body])])
|
||||
}
|
||||
|
||||
/// `expr dist { 0 := 5, [1:20] :/ 20 }` — the weight list laid out like
|
||||
/// every other braced list: one per line when it does not fit. `:=` and
|
||||
/// `:/` are printed back exactly as written; they mean different things.
|
||||
pub(super) fn dist(&self, expr: &Expr, comments: &BinaryComments, weights: &[DistItem]) -> Doc {
|
||||
let items: Vec<ListItem> = weights
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let mut docs = vec![self.expr(&w.value)];
|
||||
if let (Some(op), Some(weight)) = (&w.op, &w.weight) {
|
||||
self.inline_comments_spaced(&w.op_comments.before, &mut docs);
|
||||
docs.push(text(op.clone()));
|
||||
self.inline_comments_spaced(&w.op_comments.after, &mut docs);
|
||||
docs.push(self.expr(weight));
|
||||
}
|
||||
ListItem::from_meta(&w.meta, concat(docs))
|
||||
})
|
||||
.collect();
|
||||
let mut docs = vec![self.expr(expr)];
|
||||
self.inline_comments_spaced(&comments.before, &mut docs);
|
||||
docs.push(text("dist"));
|
||||
self.inline_comments_spaced(&comments.after, &mut docs);
|
||||
docs.push(self.delimited("{", items, "}", false));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
//! Where a comment prints relative to the tokens around it: the leading
|
||||
//! and trailing comments a node owns (`Meta`), the comments written in a
|
||||
//! construct's own gaps (`slot_comments`, `inline_comments`), the ones
|
||||
//! just inside a pair of parentheses, and the dangling comments a body
|
||||
//! ends with.
|
||||
//!
|
||||
//! Every construct in the sibling modules spells its comment slots through
|
||||
//! these few functions, which is what makes "comments are never dropped
|
||||
//! and never cross a token" a property of one file rather than of every
|
||||
//! arm of every match.
|
||||
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::skip_trivia;
|
||||
use super::verbatim::Slot;
|
||||
use super::Fmt;
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// A comment, ready to be re-indented at the printer's current level.
|
||||
pub(super) fn comment(&self, c: &Comment) -> Doc {
|
||||
self.raw_lines(&c.text, c.col)
|
||||
}
|
||||
|
||||
/// Leading comments (each on its own line) preceding a node, with any
|
||||
/// fenced region they open spliced in as source bytes.
|
||||
///
|
||||
/// The break between two comments is emitted *before* the second one, not
|
||||
/// after the first: a `HardLine` followed by a `BlankLine` is three
|
||||
/// newlines, so writing both turned one blank line between two comments
|
||||
/// into two. The list still ends with the `HardLine` that puts the node
|
||||
/// itself on a fresh line.
|
||||
pub(super) fn leading_comments(&self, meta: &Meta) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for c in &meta.leading {
|
||||
self.push_comment(&mut docs, c);
|
||||
}
|
||||
if !docs.is_empty() {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// Append one leading comment — or, when it opens a fenced region, that
|
||||
/// region's source bytes — with the break that separates it from whatever
|
||||
/// precedes it. Covered comments are already inside emitted bytes.
|
||||
fn push_comment(&self, docs: &mut Vec<Doc>, c: &Comment) {
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => return,
|
||||
Slot::Opens(r) => self.verbatim(r),
|
||||
Slot::Normal => self.comment(c),
|
||||
};
|
||||
Self::push_leading(docs, doc, c.blank_before);
|
||||
}
|
||||
|
||||
/// Leading comments and `(* ... *)` attributes preceding a node, each on
|
||||
/// its own line, in the order the source wrote them.
|
||||
///
|
||||
/// The two are stored in separate lists but interleave in the source
|
||||
/// (`(* keep *)` ⏎ `// why` ⏎ `logic x;`), so they are merged by span:
|
||||
/// printing every comment and then every attribute moves a comment across
|
||||
/// an attribute in the token stream, which the safety net rejects.
|
||||
pub(super) fn leading(&self, meta: &Meta) -> Vec<Doc> {
|
||||
self.leading_from(meta, 0)
|
||||
}
|
||||
|
||||
/// The same, minus the first `skip` leading comments — the ones a
|
||||
/// statement header already printed inside its own parentheses. See
|
||||
/// [`Fmt::header_parens`].
|
||||
pub(super) fn leading_from(&self, meta: &Meta, skip: usize) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
let mut attrs = meta.attrs.iter().peekable();
|
||||
for c in meta.leading.iter().skip(skip) {
|
||||
while let Some(attr) = attrs.next_if(|a| a.span.start < c.span.start) {
|
||||
Self::push_leading(&mut docs, self.raw_text(attr), false);
|
||||
}
|
||||
self.push_comment(&mut docs, c);
|
||||
}
|
||||
for attr in attrs {
|
||||
Self::push_leading(&mut docs, self.raw_text(attr), false);
|
||||
}
|
||||
if !docs.is_empty() {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// Append one leading comment or attribute, with the break that separates
|
||||
/// it from the previous one. The break goes *before* the second entry
|
||||
/// rather than after the first: a `HardLine` followed by a `BlankLine` is
|
||||
/// three newlines, so writing both turned one blank line into two.
|
||||
fn push_leading(docs: &mut Vec<Doc>, doc: Doc, blank_before: bool) {
|
||||
if !docs.is_empty() {
|
||||
docs.push(if blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(doc);
|
||||
}
|
||||
|
||||
pub(super) fn trailing(&self, meta: &Meta) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
let ends_line = self.inline_comments(&meta.before_sep, &mut docs);
|
||||
if let Some(tr) = &meta.trailing {
|
||||
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
|
||||
docs.push(self.comment(tr));
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// Append comments written between two tokens of an expression, each
|
||||
/// spaced off what precedes it. A line comment runs to end of line, so
|
||||
/// anything after it starts a new one — including the next comment, which
|
||||
/// would otherwise be swallowed into the first one's text.
|
||||
///
|
||||
/// Returns true when the last comment was a line comment, i.e. the caller
|
||||
/// must put whatever it emits next on a fresh line.
|
||||
pub(super) fn inline_comments(&self, comments: &[Comment], docs: &mut Vec<Doc>) -> bool {
|
||||
let mut ends_line = false;
|
||||
for c in comments {
|
||||
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
|
||||
docs.push(self.comment(c));
|
||||
ends_line = is_line_comment(&c.text);
|
||||
}
|
||||
ends_line
|
||||
}
|
||||
|
||||
/// The same, plus the separator that keeps the next thing off the last
|
||||
/// comment: a space, or a line break after a line comment.
|
||||
pub(super) fn inline_comments_spaced(&self, comments: &[Comment], docs: &mut Vec<Doc>) {
|
||||
if self.inline_comments(comments, docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
}
|
||||
|
||||
/// One named comment slot between two tokens the caller emits either side
|
||||
/// of it, spaced off both — and a no-op when the slot is empty, so a
|
||||
/// construct with no comment in it is laid out exactly as it was before
|
||||
/// the slot existed.
|
||||
///
|
||||
/// This is what every slot of [`SegmentComments`] is printed with, and it
|
||||
/// is why the empty case of a `.`, a `::` or a `[` costs nothing.
|
||||
pub(super) fn slot_comments(&self, comments: &[Comment], docs: &mut Vec<Doc>) {
|
||||
if comments.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.inline_comments_spaced(comments, docs);
|
||||
}
|
||||
|
||||
/// Comments written between a construct's head and the bracket that opens
|
||||
/// one of its lists (`module m` ⏎ `// why` ⏎ `#(`, `sub u` ⏎ `// why` ⏎
|
||||
/// `(...)`). They print on the head's side of the bracket, which is where
|
||||
/// the source put them.
|
||||
///
|
||||
/// `on_fresh_line` says whether the caller has already broken the line;
|
||||
/// the return value says the same for whatever it emits next, since a line
|
||||
/// comment runs to end of line and the bracket cannot follow it.
|
||||
pub(super) fn bracket_comments(
|
||||
&self,
|
||||
comments: &[Comment],
|
||||
docs: &mut Vec<Doc>,
|
||||
on_fresh_line: bool,
|
||||
) -> bool {
|
||||
let mut fresh = on_fresh_line;
|
||||
for c in comments {
|
||||
if !fresh {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.comment(c));
|
||||
fresh = is_line_comment(&c.text);
|
||||
if fresh {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
}
|
||||
fresh
|
||||
}
|
||||
|
||||
pub(super) fn with_meta(&self, meta: &Meta, doc: Doc) -> Doc {
|
||||
let mut docs = self.leading(meta);
|
||||
docs.push(doc);
|
||||
docs.extend(self.trailing(meta));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
pub(super) fn dangling(&self, comments: &[Comment]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for c in comments {
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => continue,
|
||||
Slot::Opens(r) => self.verbatim(r),
|
||||
Slot::Normal => self.comment(c),
|
||||
};
|
||||
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
docs.push(doc);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// `( expr )` with break opportunity inside.
|
||||
pub(super) fn parens(&self, e: &Expr) -> Doc {
|
||||
group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")])
|
||||
}
|
||||
|
||||
/// `( expr )` with the comments the source wrote just inside the
|
||||
/// parentheses. A comment there forces them open, the same way a comment
|
||||
/// inside a port list does.
|
||||
pub(super) fn paren_comments(
|
||||
&self,
|
||||
inner: &Expr,
|
||||
before: &[&Comment],
|
||||
after: &[&Comment],
|
||||
) -> Doc {
|
||||
let mut docs = vec![Doc::SoftLine];
|
||||
for c in before {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.expr(inner));
|
||||
let mut outer = vec![text("("), indent(docs)];
|
||||
for c in after {
|
||||
outer.push(text(" "));
|
||||
outer.push(self.comment(c));
|
||||
}
|
||||
let ends_line = after.iter().any(|c| is_line_comment(&c.text));
|
||||
outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine });
|
||||
outer.push(text(")"));
|
||||
group(outer)
|
||||
}
|
||||
|
||||
/// `( cond )` with the comments a header kept in its own slots. The
|
||||
/// `after_kw` half is written by the caller, which owns the keyword.
|
||||
pub(super) fn header_slots(&self, cond: &Expr, comments: &HeaderComments) -> Doc {
|
||||
if comments.after_open.is_empty() && comments.before_close.is_empty() {
|
||||
return self.parens(cond);
|
||||
}
|
||||
let before: Vec<&Comment> = comments.after_open.iter().collect();
|
||||
let after: Vec<&Comment> = comments.before_close.iter().collect();
|
||||
self.paren_comments(cond, &before, &after)
|
||||
}
|
||||
|
||||
/// `( expr )` with whatever was written just inside either parenthesis:
|
||||
/// a constraint `if`'s condition, a covergroup `iff` guard, a bin's
|
||||
/// `with ( ... )` filter. One place, so the three cannot drift apart.
|
||||
pub(super) fn guard_parens(
|
||||
&self,
|
||||
e: &Expr,
|
||||
after_open: &[Comment],
|
||||
before_close: &[Comment],
|
||||
) -> Doc {
|
||||
if after_open.is_empty() && before_close.is_empty() {
|
||||
return self.parens(e);
|
||||
}
|
||||
let before: Vec<&Comment> = after_open.iter().collect();
|
||||
let after: Vec<&Comment> = before_close.iter().collect();
|
||||
self.paren_comments(e, &before, &after)
|
||||
}
|
||||
|
||||
/// The `(cond)` of a statement header, taking back the comments the parser
|
||||
/// handed to the construct's *body* because they were written before the
|
||||
/// closing `)`.
|
||||
///
|
||||
/// Nothing between `(` and `)` owns trivia, so a comment written inside a
|
||||
/// header's parentheses stays queued and lands on the next node that takes
|
||||
/// meta — the body statement, or a `case`'s first item. Printed there it
|
||||
/// would sit *after* a `)` it was written before, and `verify.rs` refuses
|
||||
/// the file, rightly: the comment moved across a token.
|
||||
///
|
||||
/// Returns the header doc and how many of `body`'s leading comments it
|
||||
/// consumed, which the caller must then skip. When the source does not
|
||||
/// have the expected shape nothing is taken and the plain parentheses are
|
||||
/// printed, so an unrecognized header is left exactly as it was.
|
||||
pub(super) fn header_parens(&self, cond: &Expr, body: &Meta) -> (Doc, usize) {
|
||||
let close = match skip_trivia(self.src, cond.span.end as usize) {
|
||||
Some(i) if self.src.as_bytes().get(i) == Some(&b')') => i as u32,
|
||||
_ => return (self.parens(cond), 0),
|
||||
};
|
||||
let taken = body.leading.iter().take_while(|c| c.span.start < close).count();
|
||||
if taken == 0 {
|
||||
return (self.parens(cond), 0);
|
||||
}
|
||||
let (before, after): (Vec<&Comment>, Vec<&Comment>) =
|
||||
body.leading[..taken].iter().partition(|c| c.span.start < cond.span.start);
|
||||
(self.paren_comments(cond, &before, &after), taken)
|
||||
}
|
||||
}
|
||||
|
||||
/// True for `// ...` comments, which must end their line.
|
||||
pub(super) fn is_line_comment(text: &str) -> bool {
|
||||
text.starts_with("//")
|
||||
}
|
||||
|
||||
/// True when a node's trailing comments end in a line comment, so anything
|
||||
/// printed after them on the same line would be swallowed into the comment's
|
||||
/// text. `trailing` prints `before_sep` first and `trailing` last.
|
||||
pub(super) fn trailing_ends_line(meta: &Meta) -> bool {
|
||||
match &meta.trailing {
|
||||
Some(tr) => is_line_comment(&tr.text),
|
||||
None => meta.before_sep.last().is_some_and(|c| is_line_comment(&c.text)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
//! Covergroups: the `covergroup` header with its sampling event, the
|
||||
//! coverpoint and cross items, bins with their value, transition and
|
||||
//! `binsof` specs, and `option`/`type_option` assignments.
|
||||
//!
|
||||
//! Its own file rather than a tail of `class.rs` because a covergroup is
|
||||
//! the one DV construct with a grammar of its own — bins, transitions,
|
||||
//! crosses, options — and the two together would be over 800 lines.
|
||||
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::{name_doc, Fmt};
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// `covergroup g (args) with function sample (args); ... endgroup : g`.
|
||||
///
|
||||
/// A covergroup is a block, so it is laid out like one: the whole header
|
||||
/// on the header line, every cover item on a line of its own at one
|
||||
/// further indent, and `endgroup` back at the header's column with
|
||||
/// whatever label the source wrote.
|
||||
pub(super) fn covergroup(&self, c: &CovergroupDecl) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
self.qualifier_run(&c.qualifiers, &mut docs);
|
||||
docs.push(text("covergroup"));
|
||||
self.inline_comments_spaced(&c.before_name, &mut docs);
|
||||
docs.push(name_doc(&c.name.text));
|
||||
if let Some(args) = &c.args {
|
||||
if !c.before_args.is_empty() {
|
||||
self.inline_comments_spaced(&c.before_args, &mut docs);
|
||||
}
|
||||
docs.push(self.tf_args(args, &[]));
|
||||
}
|
||||
match &c.event {
|
||||
Some(CoverageEvent::Sample(s)) => {
|
||||
self.inline_comments_spaced(&s.before_with, &mut docs);
|
||||
docs.push(text("with"));
|
||||
self.inline_comments_spaced(&s.after_with, &mut docs);
|
||||
docs.push(text("function"));
|
||||
self.inline_comments_spaced(&s.after_function, &mut docs);
|
||||
docs.push(name_doc(&s.name.text));
|
||||
if s.has_parens {
|
||||
if !s.before_args.is_empty() {
|
||||
self.inline_comments_spaced(&s.before_args, &mut docs);
|
||||
}
|
||||
docs.push(self.tf_args(&s.args, &[]));
|
||||
}
|
||||
}
|
||||
Some(CoverageEvent::Clocking { before, sens }) => {
|
||||
self.inline_comments_spaced(before, &mut docs);
|
||||
docs.push(self.sens_list(sens));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if self.inline_comments(&c.before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
let mut body = Vec::new();
|
||||
if !c.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.cover_items(&c.items));
|
||||
}
|
||||
body.extend(self.dangling(&c.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
let end_label = c.end_label.as_ref().map(|l| l.text.clone());
|
||||
docs.push(self.closing_labeled("endgroup", &end_label, &c.end_label_comments));
|
||||
if c.end_semi {
|
||||
if self.inline_comments(&c.before_end_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
pub(super) fn cover_items(&self, items: &[CoverItem]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(self.with_meta(&item.meta, self.cover_item(item)));
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// One cover item, and the `;` that ends it when its kind takes one — the
|
||||
/// rule [`CoverItemKind::takes_semi`] is the single answer to, read here
|
||||
/// and by the parser that consumed it.
|
||||
fn cover_item(&self, item: &CoverItem) -> Doc {
|
||||
let mut docs = vec![self.cover_item_kind(&item.kind)];
|
||||
if item.kind.takes_semi() {
|
||||
if self.inline_comments(&item.before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn cover_item_kind(&self, kind: &CoverItemKind) -> Doc {
|
||||
match kind {
|
||||
CoverItemKind::Coverpoint(cp) => {
|
||||
let mut head = Vec::new();
|
||||
self.cover_label(&cp.label, &mut head);
|
||||
head.push(text("coverpoint"));
|
||||
self.inline_comments_spaced(&cp.after_kw, &mut head);
|
||||
head.push(self.expr(&cp.expr));
|
||||
self.cover_iff(&cp.iff, &mut head);
|
||||
self.cover_body_as_body(concat(head), &cp.before_body, &cp.body)
|
||||
}
|
||||
CoverItemKind::Cross(cr) => {
|
||||
let mut head = Vec::new();
|
||||
self.cover_label(&cr.label, &mut head);
|
||||
head.push(text("cross"));
|
||||
self.inline_comments_spaced(&cr.after_kw, &mut head);
|
||||
head.push(self.plain_expr_list(&cr.items));
|
||||
self.cover_iff(&cr.iff, &mut head);
|
||||
self.cover_body_as_body(concat(head), &cr.before_body, &cr.body)
|
||||
}
|
||||
CoverItemKind::Option(o) => self.option_assign(o),
|
||||
CoverItemKind::Directive(raw) => self.raw_text(raw),
|
||||
CoverItemKind::Empty => text(";"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `name :` a coverpoint or a cross may be labelled with.
|
||||
fn cover_label(&self, label: &Option<CoverLabel>, docs: &mut Vec<Doc>) {
|
||||
let Some(l) = label else { return };
|
||||
docs.push(name_doc(&l.name.text));
|
||||
if self.inline_comments(&l.comments.before, docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(":"));
|
||||
self.inline_comments_spaced(&l.comments.after, docs);
|
||||
}
|
||||
|
||||
/// The ` iff ( expr )` guard of a coverpoint, a cross or a bin.
|
||||
fn cover_iff(&self, iff: &Option<Box<CoverIff>>, docs: &mut Vec<Doc>) {
|
||||
let Some(i) = iff else { return };
|
||||
self.inline_comments_spaced(&i.before_kw, docs);
|
||||
docs.push(text("iff"));
|
||||
self.inline_comments_spaced(&i.after_kw, docs);
|
||||
docs.push(self.guard_parens(&i.expr, &i.after_open, &i.before_close));
|
||||
}
|
||||
|
||||
/// A coverpoint or cross header followed by its `{ bins }` body, or by
|
||||
/// nothing at all — a body-less one ends in the `;` [`Fmt::cover_item`]
|
||||
/// writes.
|
||||
fn cover_body_as_body(&self, head: Doc, before: &[Comment], body: &Option<CoverBody>) -> Doc {
|
||||
let Some(body) = body else { return head };
|
||||
let mut docs = vec![head];
|
||||
if self.inline_comments(before, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.cover_block(body));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// The `{ ... }` of a coverpoint or cross body: one bin per line at one
|
||||
/// further indent, the `}` back at the header's column — a constraint
|
||||
/// set's layout, for a construct that reads the same way.
|
||||
fn cover_block(&self, body: &CoverBody) -> Doc {
|
||||
let mut inner = Vec::new();
|
||||
if !body.items.is_empty() {
|
||||
inner.push(Doc::HardLine);
|
||||
inner.extend(self.bin_items(&body.items));
|
||||
}
|
||||
inner.extend(self.dangling(&body.dangling));
|
||||
if inner.is_empty() {
|
||||
return text("{}");
|
||||
}
|
||||
group(vec![text("{"), indent(inner), Doc::HardLine, text("}")])
|
||||
}
|
||||
|
||||
fn bin_items(&self, items: &[BinItem]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(self.with_meta(&item.meta, self.bin_item(item)));
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
fn bin_item(&self, item: &BinItem) -> Doc {
|
||||
let mut docs = vec![match &item.kind {
|
||||
BinItemKind::Bin(b) => self.bin_decl(b),
|
||||
BinItemKind::Option(o) => self.option_assign(o),
|
||||
BinItemKind::Directive(raw) => self.raw_text(raw),
|
||||
BinItemKind::Empty => text(";"),
|
||||
}];
|
||||
if item.kind.takes_semi() {
|
||||
if self.inline_comments(&item.before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `option.per_instance = 1` / `type_option.weight = 5`.
|
||||
fn option_assign(&self, o: &OptionAssign) -> Doc {
|
||||
let mut docs = vec![self.expr(&o.target)];
|
||||
if self.inline_comments(&o.comments.before, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text("="));
|
||||
self.inline_comments_spaced(&o.comments.after, &mut docs);
|
||||
docs.push(self.expr(&o.value));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `[wildcard ]bins name[4] = spec [with (expr)] [iff (expr)]`.
|
||||
fn bin_decl(&self, b: &BinDecl) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
if b.wildcard {
|
||||
docs.push(text("wildcard"));
|
||||
self.inline_comments_spaced(&b.after_wildcard, &mut docs);
|
||||
}
|
||||
docs.push(text(b.kind.as_str()));
|
||||
self.inline_comments_spaced(&b.before_name, &mut docs);
|
||||
docs.push(name_doc(&b.name.text));
|
||||
if let Some(a) = &b.array {
|
||||
if !a.before.is_empty() {
|
||||
self.inline_comments_spaced(&a.before, &mut docs);
|
||||
}
|
||||
docs.push(text("["));
|
||||
self.inline_comments(&a.comments.before, &mut docs);
|
||||
if !a.comments.before.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
if let Some(size) = &a.size {
|
||||
docs.push(self.expr(size));
|
||||
}
|
||||
if self.inline_comments(&a.comments.after, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !a.comments.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text("]"));
|
||||
}
|
||||
if self.inline_comments(&b.eq_comments.before, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text("="));
|
||||
self.inline_comments_spaced(&b.eq_comments.after, &mut docs);
|
||||
docs.push(self.bin_spec(&b.spec));
|
||||
if let Some(w) = &b.with_expr {
|
||||
self.inline_comments_spaced(&w.before_kw, &mut docs);
|
||||
docs.push(text("with"));
|
||||
self.inline_comments_spaced(&w.after_kw, &mut docs);
|
||||
docs.push(self.guard_parens(&w.expr, &w.after_open, &w.before_close));
|
||||
}
|
||||
self.cover_iff(&b.iff, &mut docs);
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn bin_spec(&self, spec: &BinSpec) -> Doc {
|
||||
match spec {
|
||||
BinSpec::Values(items) => self.expr_list("{", items, "}"),
|
||||
BinSpec::Transitions(sets) => self.trans_list(sets),
|
||||
BinSpec::Default => text("default"),
|
||||
BinSpec::DefaultSequence { comments } => {
|
||||
let mut docs = vec![text("default")];
|
||||
self.inline_comments_spaced(comments, &mut docs);
|
||||
docs.push(text("sequence"));
|
||||
concat(docs)
|
||||
}
|
||||
BinSpec::Select(s) => self.select_expr(s),
|
||||
}
|
||||
}
|
||||
|
||||
/// `(a => b), (c => d)` — the transition sets of a transition bin, joined
|
||||
/// by the commas the source wrote.
|
||||
fn trans_list(&self, sets: &[TransSet]) -> Doc {
|
||||
self.plain_list(sets.iter().map(|s| (&s.meta, self.trans_set(s))).collect())
|
||||
}
|
||||
|
||||
fn trans_set(&self, set: &TransSet) -> Doc {
|
||||
let mut docs = vec![text("(")];
|
||||
for (i, r) in set.ranges.iter().enumerate() {
|
||||
if i > 0 {
|
||||
if self.inline_comments(&r.arrow_comments.before, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text("=>"));
|
||||
self.inline_comments_spaced(&r.arrow_comments.after, &mut docs);
|
||||
}
|
||||
docs.push(self.trans_range(r));
|
||||
}
|
||||
if self.inline_comments(&set.dangling, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !set.dangling.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn trans_range(&self, r: &TransRange) -> Doc {
|
||||
let mut docs = vec![self.plain_expr_list(&r.items)];
|
||||
let Some(rep) = &r.repeat else { return concat(docs) };
|
||||
if !rep.before.is_empty() {
|
||||
self.inline_comments_spaced(&rep.before, &mut docs);
|
||||
}
|
||||
docs.push(text("["));
|
||||
self.inline_comments(&rep.after_open, &mut docs);
|
||||
if !rep.after_open.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(rep.op.clone()));
|
||||
self.inline_comments(&rep.comments.before, &mut docs);
|
||||
if !rep.comments.before.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.expr(&rep.lo));
|
||||
if let Some(hi) = &rep.hi {
|
||||
self.inline_comments(&rep.colon_comments.before, &mut docs);
|
||||
if !rep.colon_comments.before.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(":"));
|
||||
self.inline_comments(&rep.colon_comments.after, &mut docs);
|
||||
if !rep.colon_comments.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.expr(hi));
|
||||
}
|
||||
if self.inline_comments(&rep.comments.after, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !rep.comments.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text("]"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `binsof(a) intersect {0} && !binsof(b)` — a cross bin's select
|
||||
/// expression, and the bare coverpoint name a coverpoint bin may name.
|
||||
fn select_expr(&self, s: &SelectExpr) -> Doc {
|
||||
match s {
|
||||
SelectExpr::Binsof(b) => {
|
||||
let mut docs = vec![text("binsof")];
|
||||
if !b.after_kw.is_empty() {
|
||||
self.inline_comments_spaced(&b.after_kw, &mut docs);
|
||||
}
|
||||
docs.push(text("("));
|
||||
self.inline_comments(&b.after_open, &mut docs);
|
||||
if !b.after_open.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.expr(&b.name));
|
||||
if self.inline_comments(&b.before_close, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !b.before_close.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
if let Some(items) = &b.intersect {
|
||||
self.inline_comments_spaced(&b.before_intersect, &mut docs);
|
||||
docs.push(text("intersect"));
|
||||
self.inline_comments_spaced(&b.after_intersect, &mut docs);
|
||||
docs.push(self.expr_list("{", items, "}"));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
SelectExpr::Not { comments, expr } => {
|
||||
let mut docs = vec![text("!")];
|
||||
if !comments.is_empty() {
|
||||
self.inline_comments(comments, &mut docs);
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.select_expr(expr));
|
||||
concat(docs)
|
||||
}
|
||||
SelectExpr::Binary { lhs, op, comments, rhs } => {
|
||||
let mut docs = vec![self.select_expr(lhs)];
|
||||
if self.inline_comments(&comments.before, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(op.clone()));
|
||||
self.inline_comments_spaced(&comments.after, &mut docs);
|
||||
docs.push(self.select_expr(rhs));
|
||||
concat(docs)
|
||||
}
|
||||
SelectExpr::Paren { comments, expr } => {
|
||||
let mut docs = vec![text("(")];
|
||||
self.inline_comments(&comments.before, &mut docs);
|
||||
if !comments.before.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.select_expr(expr));
|
||||
if self.inline_comments(&comments.after, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !comments.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
SelectExpr::Expr(e) => self.expr(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
//! Declarations and the types they name: a `DataType` with its packed
|
||||
//! dimensions, unpacked dimensions, the declarator list of a
|
||||
//! `logic a, b = 1;`, `parameter`/`localparam` and their alignment,
|
||||
//! `typedef`, and `enum`/`struct` bodies.
|
||||
//!
|
||||
//! An expression inside a dimension is printed by `expr_compact`, which
|
||||
//! belongs to the expression module; only the brackets are this one's.
|
||||
|
||||
use crate::align::{self, Align, ColSpec, Row};
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
|
||||
use super::comment::is_line_comment;
|
||||
use super::list::ListItem;
|
||||
use super::{name_doc, Fmt};
|
||||
|
||||
/// A `parameter`/`localparam` declaration's two alignment columns: the name,
|
||||
/// and the `=` of its value.
|
||||
const PARAM_DECL_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }, ColSpec { flush: 1, min: 1 }];
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// Format a data type; `None` if fully implicit.
|
||||
pub(super) fn data_type(&self, ty: &DataType) -> Option<Doc> {
|
||||
if ty.is_implicit() {
|
||||
return None;
|
||||
}
|
||||
let mut docs = Vec::new();
|
||||
let mut need_space = false;
|
||||
// `virtual clk_rst_if`, `virtual interface bus_if`.
|
||||
if let Some(v) = ty.virt {
|
||||
docs.push(text(v.text()));
|
||||
need_space = true;
|
||||
}
|
||||
if !ty.name.is_empty() {
|
||||
if need_space {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(name_doc(&ty.name));
|
||||
need_space = true;
|
||||
}
|
||||
// `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`,
|
||||
// like an instantiation's overrides and unlike the tight `#(` of a
|
||||
// parameterized name in expression position.
|
||||
if let Some(params) = ty.params() {
|
||||
if need_space {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.raw_inline(params));
|
||||
need_space = true;
|
||||
}
|
||||
if let Some(s) = &ty.signing {
|
||||
if need_space {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(s.clone()));
|
||||
need_space = true;
|
||||
}
|
||||
if !ty.packed.is_empty() {
|
||||
// A dimension that opens with a comment writes its own space.
|
||||
if need_space && ty.packed[0].comments.opens_clean() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
for d in &ty.packed {
|
||||
docs.push(self.dim(d));
|
||||
}
|
||||
need_space = true;
|
||||
}
|
||||
// An anonymous aggregate is the type itself, so it never shares the
|
||||
// line with a name — but it can follow a `virtual` prefix, and the
|
||||
// `need_space` bookkeeping above is what puts the space in.
|
||||
match ty.inline() {
|
||||
Some(TypeExtra::Enum(e)) => {
|
||||
if need_space {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.enum_type(e));
|
||||
}
|
||||
Some(TypeExtra::Struct(s)) => {
|
||||
if need_space {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.struct_type(s));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(concat(docs))
|
||||
}
|
||||
|
||||
pub(super) fn dim(&self, d: &Dim) -> Doc {
|
||||
let c = &d.comments;
|
||||
let brackets = match &d.kind {
|
||||
DimKind::Range { a, b } => {
|
||||
let rest = b.as_ref().map(|b| (":", self.expr_compact(b)));
|
||||
self.bracket_slots(c, self.expr_compact(a), rest)
|
||||
}
|
||||
// `[]` and `[*]` have no operand, so the one inner slot they own
|
||||
// is the gap before the `]`, which is where `parse_dims` puts
|
||||
// anything written between the brackets.
|
||||
DimKind::Dynamic => self.bracket_slots(c, text(""), None),
|
||||
DimKind::Wildcard => self.bracket_slots(c, text("*"), None),
|
||||
};
|
||||
if c.opens_clean() {
|
||||
return brackets;
|
||||
}
|
||||
// `logic /*c*/ [3:0]` — the gap before the `[` belongs to the
|
||||
// dimension, since nothing to its left has a slot for it. The space
|
||||
// in front is the dimension's own: a caller that would have written
|
||||
// one asks [`SegmentComments::opens_clean`] and leaves it out.
|
||||
let mut docs = Vec::new();
|
||||
self.inline_comments_spaced(&c.before_open, &mut docs);
|
||||
docs.push(brackets);
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
pub(super) fn unpacked_dims(&self, dims: &[Dim]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
if !dims.is_empty() {
|
||||
if dims[0].comments.opens_clean() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
for d in dims {
|
||||
docs.push(self.dim(d));
|
||||
}
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
fn declarators(&self, decls: &[Declarator]) -> Doc {
|
||||
let items: Vec<ListItem> = decls
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let mut docs = vec![name_doc(&d.name)];
|
||||
docs.extend(self.unpacked_dims(&d.unpacked));
|
||||
if let Some(init) = &d.init {
|
||||
self.slot_comments(&d.eq_comments.before, &mut docs);
|
||||
docs.push(text(if d.eq_comments.before.is_empty() { " =" } else { "=" }));
|
||||
if d.eq_comments.after.is_empty() {
|
||||
docs.push(group(vec![self.assign_rhs(self.expr(init))]));
|
||||
} else {
|
||||
self.inline_comments_spaced(&d.eq_comments.after, &mut docs);
|
||||
docs.push(group(vec![self.expr(init)]));
|
||||
}
|
||||
}
|
||||
ListItem::from_meta(&d.meta, concat(docs))
|
||||
})
|
||||
.collect();
|
||||
if items.len() == 1 {
|
||||
let item = items.into_iter().next().unwrap();
|
||||
let mut docs = self.leading(&Meta { leading: item.leading, ..Meta::default() });
|
||||
docs.push(item.doc);
|
||||
let mut ends_line = self.inline_comments(&item.before_sep, &mut docs);
|
||||
if let Some(tr) = item.trailing {
|
||||
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
|
||||
docs.push(self.comment(&tr));
|
||||
ends_line = is_line_comment(&tr.text);
|
||||
}
|
||||
// The caller appends the `;`; a line comment runs to end of line,
|
||||
// so it has to go on the next one.
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
return concat(docs);
|
||||
}
|
||||
// Multiple declarators: allow one-per-line continuation.
|
||||
let mut inner = Vec::new();
|
||||
let last = items.len() - 1;
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
let meta = Meta { leading: item.leading, ..Meta::default() };
|
||||
inner.extend(self.leading(&meta));
|
||||
inner.push(item.doc);
|
||||
let ends_line = self.inline_comments(&item.before_sep, &mut inner);
|
||||
if i < last {
|
||||
if ends_line {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
inner.push(text(","));
|
||||
} else if ends_line {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
if let Some(tr) = item.trailing {
|
||||
inner.push(text(" "));
|
||||
inner.push(self.comment(&tr));
|
||||
if i < last || is_line_comment(&tr.text) {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
} else if i < last {
|
||||
inner.push(Doc::Line);
|
||||
}
|
||||
}
|
||||
group(vec![indent(inner)])
|
||||
}
|
||||
|
||||
/// A `parameter`/`localparam` declaration. With an alignment plan it is
|
||||
/// laid out as cells padded to the group's columns; without one it takes
|
||||
/// the flush path every other declaration takes.
|
||||
///
|
||||
/// The two must agree byte-for-byte when the padding collapses, because
|
||||
/// that is exactly what the printer's line-limit fallback does — and the
|
||||
/// next pass, seeing no excess spaces, comes back through the flush path.
|
||||
pub(super) fn param_decl(&self, d: &ParamDecl, align: Option<&Align>) -> Doc {
|
||||
if let (Some(a), [decl]) = (align, &d.declarators[..]) {
|
||||
if let Some(init) = &decl.init {
|
||||
return align::render(
|
||||
&self.param_decl_cells(d, decl, init),
|
||||
PARAM_DECL_COLS,
|
||||
Some(a),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut docs = Vec::new();
|
||||
self.word_then(&d.kw, &d.after_kw, &mut docs);
|
||||
if d.is_type {
|
||||
docs.push(text("type "));
|
||||
}
|
||||
if let Some(t) = self.data_type(&d.ty) {
|
||||
docs.push(t);
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.declarators(&d.declarators));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A `parameter`/`localparam` declaration split at its two alignment
|
||||
/// columns: the keyword and type, the name, and the `= value`.
|
||||
fn param_decl_cells(&self, d: &ParamDecl, decl: &Declarator, init: &Expr) -> Vec<Doc> {
|
||||
let mut prefix = vec![text(d.kw.clone())];
|
||||
if d.is_type {
|
||||
prefix.push(text(" type"));
|
||||
}
|
||||
if let Some(t) = self.data_type(&d.ty) {
|
||||
prefix.push(text(" "));
|
||||
prefix.push(t);
|
||||
}
|
||||
let mut name = vec![name_doc(&decl.name)];
|
||||
name.extend(self.unpacked_dims(&decl.unpacked));
|
||||
vec![
|
||||
concat(prefix),
|
||||
concat(name),
|
||||
concat(vec![text("="), group(vec![self.assign_rhs(self.expr(init))])]),
|
||||
]
|
||||
}
|
||||
|
||||
/// The alignment plan for the `parameter`/`localparam` declarations among
|
||||
/// a run of module (or package, or class) items.
|
||||
pub(super) fn param_decl_aligns(&self, items: &[Item], depth: usize) -> Vec<Option<Align>> {
|
||||
let rows: Vec<Option<Row>> = items.iter().map(|i| self.param_decl_row(i)).collect();
|
||||
if rows.iter().all(Option::is_none) {
|
||||
return vec![None; items.len()];
|
||||
}
|
||||
// Unlike a bracketed list, an item sequence prints the blank lines the
|
||||
// source wrote, so a blank line is a boundary the next pass sees too.
|
||||
let breaks: Vec<bool> = items
|
||||
.iter()
|
||||
.map(|i| i.meta.blank_before || !i.meta.leading.is_empty() || !i.meta.attrs.is_empty())
|
||||
.collect();
|
||||
self.align_groups(&rows, &breaks, PARAM_DECL_COLS, depth)
|
||||
}
|
||||
|
||||
/// Measure a `parameter`/`localparam` item as an alignment row.
|
||||
///
|
||||
/// Only the plain shape joins a group: one declarator, with a value, no
|
||||
/// comments of its own, not inside a fenced region. Anything else formats
|
||||
/// the way it always has and splits the group in two.
|
||||
fn param_decl_row(&self, item: &Item) -> Option<Row> {
|
||||
let ItemKind::ParamDecl(d) = &item.kind else { return None };
|
||||
if !item.meta.attrs.is_empty() || self.is_verbatim(item.span) {
|
||||
return None;
|
||||
}
|
||||
let [decl] = &d.declarators[..] else { return None };
|
||||
if !decl.meta.leading.is_empty()
|
||||
|| !decl.meta.before_sep.is_empty()
|
||||
|| decl.meta.trailing.is_some()
|
||||
// A comment after the keyword makes this row a width no other row
|
||||
// shares, so it never joins an alignment group.
|
||||
|| !d.after_kw.is_empty()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let init = decl.init.as_ref()?;
|
||||
let eq = self.eq_offset(init.span.start, decl.name_span.end)?;
|
||||
// The tail is the `;` the item ends with.
|
||||
Self::row_of(&self.param_decl_cells(d, decl, init), vec![decl.name_span.start, eq], 1)
|
||||
}
|
||||
|
||||
/// Byte offset of the `=` between a declarator's name and its value, or
|
||||
/// `None` when anything but whitespace stands between the two.
|
||||
fn eq_offset(&self, value_start: u32, after_name: u32) -> Option<u32> {
|
||||
let bytes = self.src.as_bytes();
|
||||
let mut pos = value_start as usize;
|
||||
while pos > 0 && matches!(bytes[pos - 1], b' ' | b'\t' | b'\r' | b'\n') {
|
||||
pos -= 1;
|
||||
}
|
||||
(pos > after_name as usize && bytes.get(pos - 1) == Some(&b'=')).then_some(pos as u32 - 1)
|
||||
}
|
||||
|
||||
pub(super) fn data_decl(&self, d: &DataDecl) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
if let Some(net) = &d.net {
|
||||
docs.push(text(format!("{net} ")));
|
||||
}
|
||||
if let Some(delay) = &d.delay {
|
||||
docs.push(text("#"));
|
||||
docs.push(self.expr(delay));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
self.qualifier_run(&d.qualifiers, &mut docs);
|
||||
if let Some(t) = self.data_type(&d.ty) {
|
||||
docs.push(t);
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.declarators(&d.declarators));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
pub(super) fn port_decl(&self, d: &PortDecl) -> Doc {
|
||||
let mut docs = vec![text(format!("{} ", d.dir))];
|
||||
if let Some(net) = &d.net {
|
||||
docs.push(text(format!("{net} ")));
|
||||
}
|
||||
if let Some(t) = self.data_type(&d.ty) {
|
||||
docs.push(t);
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.declarators(&d.declarators));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
pub(super) fn typedef(&self, t: &Typedef) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
self.word_then("typedef", &t.after_kw, &mut docs);
|
||||
let base = match &t.kind {
|
||||
TypedefKind::ForwardClass => Some(text("class")),
|
||||
TypedefKind::Alias(ty) => self.data_type(ty),
|
||||
TypedefKind::Enum(e) => Some(self.enum_type(e)),
|
||||
TypedefKind::Struct(s) => Some(self.struct_type(s)),
|
||||
};
|
||||
match base {
|
||||
Some(d) => {
|
||||
docs.push(d);
|
||||
if t.before_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&t.before_name, &mut docs);
|
||||
}
|
||||
}
|
||||
None => self.slot_comments(&t.before_name, &mut docs),
|
||||
}
|
||||
docs.push(name_doc(&t.name));
|
||||
docs.extend(self.unpacked_dims(&t.unpacked));
|
||||
docs.push(self.semi(&t.before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `enum [base] { A, B }` — one line if it fits, else one member per line.
|
||||
/// Shared by `typedef enum ...` and by an anonymous enum standing where a
|
||||
/// type name would (`enum logic [1:0] {IDLE, STOP} state;`).
|
||||
fn enum_type(&self, e: &EnumType) -> Doc {
|
||||
let mut docs = vec![text("enum")];
|
||||
let mut spaced = false;
|
||||
if !e.after_kw.is_empty() {
|
||||
self.inline_comments_spaced(&e.after_kw, &mut docs);
|
||||
spaced = true;
|
||||
}
|
||||
if let Some(base) = &e.base {
|
||||
if let Some(d) = self.data_type(base) {
|
||||
if !spaced {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(d);
|
||||
spaced = false;
|
||||
}
|
||||
}
|
||||
if e.before_open.is_empty() {
|
||||
if !spaced {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
} else {
|
||||
self.inline_comments_spaced(&e.before_open, &mut docs);
|
||||
}
|
||||
let items = self.list_entries(self.enum_member_items(&e.members), &e.directives);
|
||||
// `e.dangling` — comments written before the closing `}` — is printed
|
||||
// inside the braces; the enum has no other place to put it, and
|
||||
// dropping it loses a comment.
|
||||
let broken = !e.directives.is_empty();
|
||||
docs.push(self.delimited_dangling("{", items, &e.dangling, "}", broken));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One list entry per enum member. Shared by the `enum { ... }` body and
|
||||
/// by an enum-member fragment, so the two lay a member out identically.
|
||||
pub(super) fn enum_member_items(&self, members: &[EnumMember]) -> Vec<ListItem> {
|
||||
members
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let mut d = vec![name_doc(&m.name)];
|
||||
// Tight against the name: `OtbnDmem[16]` is one enum name
|
||||
// range, not a name with a dimension beside it.
|
||||
d.extend(m.range.iter().map(|r| self.dim(r)));
|
||||
if let Some(v) = &m.value {
|
||||
self.slot_comments(&m.eq_comments.before, &mut d);
|
||||
d.push(text(if m.eq_comments.before.is_empty() { " =" } else { "=" }));
|
||||
if m.eq_comments.after.is_empty() {
|
||||
d.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&m.eq_comments.after, &mut d);
|
||||
}
|
||||
d.push(self.expr(v));
|
||||
}
|
||||
ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `struct|union [packed] [signing] { ... }`, always one member per line.
|
||||
/// Shared by `typedef struct ...`, an anonymous struct standing where a
|
||||
/// type name would, and a struct member whose own type is an inline
|
||||
/// struct — the recursion is what indents a nested body one more level.
|
||||
fn struct_type(&self, s: &StructType) -> Doc {
|
||||
let c = &s.header_comments;
|
||||
// `union tagged packed`, in the LRM's order, each word followed by
|
||||
// whatever the source wrote after it.
|
||||
let mut head = Vec::new();
|
||||
self.word_then(&s.kw, &c.after_kw, &mut head);
|
||||
if s.tagged {
|
||||
self.word_then("tagged", &c.after_tagged, &mut head);
|
||||
}
|
||||
if s.packed {
|
||||
self.word_then("packed", &c.after_packed, &mut head);
|
||||
}
|
||||
if let Some(sig) = &s.signing {
|
||||
self.word_then(sig, &c.after_signing, &mut head);
|
||||
}
|
||||
head.push(text("{"));
|
||||
let mut inner = Vec::new();
|
||||
for m in &s.members {
|
||||
inner.push(Doc::HardLine);
|
||||
inner.extend(self.leading(&m.meta));
|
||||
let mut d = Vec::new();
|
||||
self.qualifier_run(&m.qualifiers, &mut d);
|
||||
if let Some(ty) = self.data_type(&m.ty) {
|
||||
d.push(ty);
|
||||
d.push(text(" "));
|
||||
}
|
||||
d.push(self.declarators(&m.declarators));
|
||||
d.push(text(";"));
|
||||
inner.push(concat(d));
|
||||
inner.extend(self.trailing(&m.meta));
|
||||
}
|
||||
inner.extend(self.dangling(&s.dangling));
|
||||
concat(vec![concat(head), indent(inner), Doc::HardLine, text("}")])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
//! Expressions: the dispatch from `ExprKind` to its layout, the binary
|
||||
//! chain that breaks `a + b + c` as one unit, the ternary with comments
|
||||
//! inside it, the compact spelling used inside `[ ... ]`, and the small
|
||||
//! postfix forms (`base.name`, `base::name`, `lhs inside {…}`, `with`).
|
||||
//!
|
||||
//! `expr` is a dispatch table over `ExprKind` and stays whole; the
|
||||
//! helpers after it are the arms that grew a shape of their own.
|
||||
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::comment::is_line_comment;
|
||||
use super::list::ListItem;
|
||||
use super::{name_doc, named, Fmt};
|
||||
|
||||
/// One operator of a flattened binary chain, with the comments written on
|
||||
/// either side of it.
|
||||
struct BinaryOp<'e> {
|
||||
op: &'e str,
|
||||
before: &'e [Comment],
|
||||
after: &'e [Comment],
|
||||
}
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
fn binary_prec(op: &str) -> u8 {
|
||||
match op {
|
||||
"||" => 1,
|
||||
"&&" => 2,
|
||||
"|" => 3,
|
||||
"^" | "^~" | "~^" => 4,
|
||||
"&" => 5,
|
||||
"==" | "!=" | "===" | "!==" | "==?" | "!=?" => 6,
|
||||
"<" | "<=" | ">" | ">=" => 7,
|
||||
"<<" | ">>" | "<<<" | ">>>" => 8,
|
||||
"+" | "-" => 9,
|
||||
"*" | "/" | "%" => 10,
|
||||
"**" => 11,
|
||||
// `->` and `<->` are the lowest-precedence binary operators
|
||||
// (IEEE 1800 §11.3.2). This table is only ever compared for
|
||||
// equality — it decides which neighbours flatten into one
|
||||
// chain — and no other operator reaches the fallback.
|
||||
"->" | "<->" => 0,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when a call's callee is a **macro name the source separated from
|
||||
/// its `(`** — `` `WIDTH (a + b) ``, the expression-position spelling of
|
||||
/// the `` `uvm_field_int (x, y) `` an item already keeps
|
||||
/// (`Parser::at_spaced_macro_call`).
|
||||
///
|
||||
/// The gap is data, not layout: `` `A (b) `` and `` `A(b) `` are one token
|
||||
/// each, of *different text*, so closing it is a token rewrite the safety
|
||||
/// net refuses — pinned in both directions by
|
||||
/// `verification::{tightening,loosening}_a_*_macro_call_is_rejected`. And
|
||||
/// lucisv cannot know which spelling was meant, because that depends on
|
||||
/// whether the macro was defined with formals (IEEE 1800 §22.5.1), which
|
||||
/// lives in a file this formatter does not read.
|
||||
///
|
||||
/// The question is asked of `src` rather than of the AST for the reason
|
||||
/// [`Fmt::glued_null_item`] gives: it is a fact about the gap between two
|
||||
/// tokens, and this is the one place that gap is laid out. It is a fixed
|
||||
/// point by construction — the printed gap is one space, which reads back
|
||||
/// as a gap on the next pass.
|
||||
fn spaced_macro_callee(&self, callee: &Expr) -> bool {
|
||||
let ExprKind::Ident(name) = &callee.kind else { return false };
|
||||
name.starts_with('`')
|
||||
&& self
|
||||
.src
|
||||
.get(callee.span.end as usize..)
|
||||
.and_then(|rest| rest.chars().next())
|
||||
.is_some_and(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// One arm per `ExprKind`. A dispatch table over the enum, so it stays
|
||||
/// whole past the 150-line mark: the shapes with a layout of their own
|
||||
/// (a binary chain, a ternary with comments, `base.name`) are the
|
||||
/// functions after it.
|
||||
pub(super) fn expr(&self, e: &Expr) -> Doc {
|
||||
match &e.kind {
|
||||
ExprKind::Ident(s) => name_doc(s),
|
||||
ExprKind::Number(s) => text(s.clone()),
|
||||
ExprKind::Str(s) => text(s.clone()),
|
||||
// Only reachable through `connection`, which handles the comments.
|
||||
ExprKind::Empty(_) => text(""),
|
||||
ExprKind::Unary { op, comments, expr } => {
|
||||
let mut docs = vec![text(op.clone())];
|
||||
self.slot_comments(comments, &mut docs);
|
||||
docs.push(self.expr(expr));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::Binary { .. } => self.binary_chain(e),
|
||||
ExprKind::Ternary { cond, then, els, comments } => {
|
||||
if comments.is_empty() {
|
||||
return group(vec![
|
||||
self.expr(cond),
|
||||
indent(vec![
|
||||
Doc::Line,
|
||||
text("? "),
|
||||
self.expr(then),
|
||||
Doc::Line,
|
||||
text(": "),
|
||||
self.expr(els),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
self.ternary_with_comments(cond, then, els, comments)
|
||||
}
|
||||
ExprKind::Call { callee, args, comments } => {
|
||||
let spaced = self.spaced_macro_callee(callee);
|
||||
if comments.is_empty() {
|
||||
let mut docs = vec![self.expr(callee)];
|
||||
if spaced {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.expr_list("(", args, ")"));
|
||||
return concat(docs);
|
||||
}
|
||||
// A comment written around the brackets prints back between
|
||||
// the same two tokens it was written between: after the
|
||||
// callee, and inside the empty `()` that had nowhere else to
|
||||
// put it.
|
||||
let mut docs = vec![self.expr(callee)];
|
||||
if !comments.before_open.is_empty() {
|
||||
self.inline_comments_spaced(&comments.before_open, &mut docs);
|
||||
} else if spaced {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
let items: Vec<ListItem> =
|
||||
args.iter().map(|i| ListItem::from_meta(&i.meta, self.expr(&i.expr))).collect();
|
||||
docs.push(self.delimited_dangling("(", items, &comments.dangling, ")", false));
|
||||
concat(docs)
|
||||
}
|
||||
// `new src` — one space, never a break: the source handle is a
|
||||
// postfix expression that breaks internally if it must.
|
||||
ExprKind::New(src) => concat(vec![text("new "), self.expr(src)]),
|
||||
ExprKind::Index { base, index, comments } => {
|
||||
let mut docs = vec![self.expr(base)];
|
||||
self.slot_comments(&comments.before_open, &mut docs);
|
||||
docs.push(self.bracket_slots(comments, self.expr_compact(index), None));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::Range { base, op, msb, lsb, comments } => {
|
||||
let mut docs = vec![self.expr(base)];
|
||||
self.slot_comments(&comments.before_open, &mut docs);
|
||||
docs.push(self.bracket_slots(
|
||||
comments,
|
||||
self.expr_compact(msb),
|
||||
Some((op, self.expr_compact(lsb))),
|
||||
));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::Member { base, name, comments } => {
|
||||
self.chain_segment(base, ".", name, comments)
|
||||
}
|
||||
ExprKind::Scope { base, name, comments } => {
|
||||
self.chain_segment(base, "::", name, comments)
|
||||
}
|
||||
// Written tight, like the `::` it almost always precedes.
|
||||
ExprKind::Parameterized { base, params } => {
|
||||
concat(vec![self.expr(base), self.raw_inline(params)])
|
||||
}
|
||||
ExprKind::Concat(items) => self.expr_list("{", items, "}"),
|
||||
ExprKind::Repl { count, inner } => concat(vec![
|
||||
text("{"),
|
||||
self.expr(count),
|
||||
self.expr_list("{", inner, "}"),
|
||||
text("}"),
|
||||
]),
|
||||
// `{<<8{v}}` — written tight, like a replication.
|
||||
ExprKind::Stream { dir, slice, inner } => {
|
||||
let mut docs = vec![text("{"), text(dir.clone())];
|
||||
if let Some(s) = slice {
|
||||
docs.push(self.expr(s));
|
||||
}
|
||||
docs.push(self.expr_list("{", inner, "}"));
|
||||
docs.push(text("}"));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::Paren { inner, before, after } => {
|
||||
if before.is_empty() && after.is_empty() {
|
||||
return self.parens(inner);
|
||||
}
|
||||
let before: Vec<&Comment> = before.iter().collect();
|
||||
let after: Vec<&Comment> = after.iter().collect();
|
||||
self.paren_comments(inner, &before, &after)
|
||||
}
|
||||
// `ty'{...}` prints no brackets of its own: the assignment
|
||||
// pattern already carries the `'{` and the `}`.
|
||||
ExprKind::Cast { ty, comments, expr, pattern: true } => {
|
||||
let mut docs = vec![self.expr(ty)];
|
||||
self.slot_comments(&comments.before_tick, &mut docs);
|
||||
self.slot_comments(&comments.after_tick, &mut docs);
|
||||
docs.push(self.expr(expr));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::Cast { ty, comments, expr, .. } => {
|
||||
if comments.is_empty() {
|
||||
return concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]);
|
||||
}
|
||||
let mut docs = vec![self.expr(ty)];
|
||||
self.slot_comments(&comments.before_tick, &mut docs);
|
||||
docs.push(text("'"));
|
||||
self.slot_comments(&comments.after_tick, &mut docs);
|
||||
docs.push(text("("));
|
||||
self.slot_comments(&comments.after_open, &mut docs);
|
||||
docs.push(self.expr(expr));
|
||||
self.slot_comments(&comments.before_close, &mut docs);
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::AssignPattern(items) => {
|
||||
let items: Vec<ListItem> = items
|
||||
.iter()
|
||||
.map(|pi| {
|
||||
let mut d = Vec::new();
|
||||
if let Some(k) = &pi.key {
|
||||
d.push(self.expr(k));
|
||||
d.push(text(": "));
|
||||
}
|
||||
d.push(self.expr(&pi.value));
|
||||
ListItem::from_meta(&pi.meta, concat(d))
|
||||
})
|
||||
.collect();
|
||||
self.delimited("'{", items, "}", false)
|
||||
}
|
||||
// `'{N{0}}` — written tight, like the `{N{0}}` it replicates.
|
||||
ExprKind::AssignPatternRepl { count, inner } => concat(vec![
|
||||
text("'{"),
|
||||
self.expr(count),
|
||||
self.expr_list("{", inner, "}"),
|
||||
text("}"),
|
||||
]),
|
||||
ExprKind::Postfix { expr, op, comments } => {
|
||||
let mut docs = vec![self.expr(expr)];
|
||||
self.slot_comments(comments, &mut docs);
|
||||
docs.push(text(op.clone()));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::With { base, arg, comments } => {
|
||||
concat(vec![self.with_head(base, comments), self.expr(arg)])
|
||||
}
|
||||
ExprKind::WithConstraint { base, block, comments } => {
|
||||
let body = match &**block {
|
||||
ConstraintBody::Items(set) => self.with_constraint_block(set),
|
||||
ConstraintBody::Verbatim(raw) => self.with_block(raw),
|
||||
};
|
||||
concat(vec![self.with_head(base, comments), body])
|
||||
}
|
||||
ExprKind::Dist { expr, comments, weights } => self.dist(expr, comments, weights),
|
||||
ExprKind::Inside { lhs, ranges, comments } => {
|
||||
self.inside_head(lhs, comments, self.expr_list("{", ranges, "}"))
|
||||
}
|
||||
ExprKind::InsideMacro { lhs, set, comments } => {
|
||||
self.inside_head(lhs, comments, text(set.clone()))
|
||||
}
|
||||
// A named call argument, printed the way a named connection is:
|
||||
// `.name(value)`, tight, with a break opportunity inside.
|
||||
ExprKind::NamedArg { name, value, comments, .. } => match &value.kind {
|
||||
ExprKind::Empty(inner) => {
|
||||
let comments_inner = inner;
|
||||
let mut docs = vec![text(".")];
|
||||
self.slot_comments(&comments.after_dot, &mut docs);
|
||||
docs.push(text(named(name)));
|
||||
self.slot_comments(&comments.before_open, &mut docs);
|
||||
docs.push(text("("));
|
||||
self.slot_comments(&comments.after_open, &mut docs);
|
||||
let comments = comments_inner;
|
||||
let mut ends_line = false;
|
||||
for cm in comments {
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.comment(cm));
|
||||
ends_line = is_line_comment(&cm.text);
|
||||
}
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
_ => {
|
||||
let mut inner = vec![Doc::SoftLine, self.expr(value)];
|
||||
let ends_line = self.inline_comments(&comments.close, &mut inner);
|
||||
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
|
||||
let mut docs = vec![text(".")];
|
||||
self.slot_comments(&comments.after_dot, &mut docs);
|
||||
docs.push(text(named(name)));
|
||||
self.slot_comments(&comments.before_open, &mut docs);
|
||||
docs.push(text("("));
|
||||
self.slot_comments(&comments.after_open, &mut docs);
|
||||
docs.push(group(vec![indent(inner), close]));
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
},
|
||||
ExprKind::ValueRange { lo, hi, comments } => {
|
||||
self.bracket_slots(comments, self.expr(lo), Some((":", self.expr(hi))))
|
||||
}
|
||||
ExprKind::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")),
|
||||
// Byte for byte, like every other verbatim leaf, and `Inline`
|
||||
// rather than re-indented for the reason `raw_inline` gives: the
|
||||
// region never begins its own line, so a dedent-by-column would
|
||||
// drift instead of reaching a fixed point.
|
||||
ExprKind::Verbatim(raw) => self.raw_inline(raw),
|
||||
ExprKind::MinTypMax { min, typ, max } => {
|
||||
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Flatten a left-nested chain of same-precedence binary operators so
|
||||
/// `a + b + c` breaks as one unit instead of stair-stepping. An operator
|
||||
/// carrying comments (written after the operand before it) starts its own
|
||||
/// line, so the comment stays last on the line it was written on.
|
||||
fn binary_chain(&self, e: &Expr) -> Doc {
|
||||
let ExprKind::Binary { op, .. } = &e.kind else { unreachable!() };
|
||||
let prec = Self::binary_prec(op);
|
||||
let mut operands: Vec<&Expr> = Vec::new();
|
||||
let mut ops: Vec<BinaryOp<'_>> = Vec::new();
|
||||
fn walk<'e>(
|
||||
e: &'e Expr,
|
||||
prec: u8,
|
||||
operands: &mut Vec<&'e Expr>,
|
||||
ops: &mut Vec<BinaryOp<'e>>,
|
||||
) {
|
||||
match &e.kind {
|
||||
ExprKind::Binary { lhs, op, rhs, comments } if Fmt::binary_prec(op) == prec => {
|
||||
walk(lhs, prec, operands, ops);
|
||||
ops.push(BinaryOp { op, before: &comments.before, after: &comments.after });
|
||||
operands.push(rhs);
|
||||
}
|
||||
_ => operands.push(e),
|
||||
}
|
||||
}
|
||||
walk(e, prec, &mut operands, &mut ops);
|
||||
let mut docs = vec![self.expr(operands[0])];
|
||||
let mut cont = Vec::new();
|
||||
for (op, rhs) in ops.iter().zip(operands[1..].iter()) {
|
||||
// Comments written before the operator stay on the left operand's
|
||||
// line; the operator then starts a new one.
|
||||
self.inline_comments(op.before, &mut cont);
|
||||
if op.before.is_empty() {
|
||||
cont.push(text(format!(" {}", op.op)));
|
||||
} else {
|
||||
cont.push(Doc::HardLine);
|
||||
cont.push(text(op.op.to_string()));
|
||||
}
|
||||
// Comments written after the operator stay on the operator's line;
|
||||
// the right operand then starts a new one.
|
||||
let hard = self.inline_comments(op.after, &mut cont);
|
||||
if hard {
|
||||
cont.push(Doc::HardLine);
|
||||
} else if !op.after.is_empty() || !op.before.is_empty() {
|
||||
cont.push(text(" "));
|
||||
} else {
|
||||
cont.push(Doc::Line);
|
||||
}
|
||||
cont.push(self.expr(rhs));
|
||||
}
|
||||
docs.push(indent(cont));
|
||||
group(docs)
|
||||
}
|
||||
|
||||
/// A `? :` with comments written inside it. Each comment stays between the
|
||||
/// two tokens it was written between, and a line comment forces the break
|
||||
/// that follows it, so the layout can never fold a comment over the `?`,
|
||||
/// the `:` or an operand.
|
||||
fn ternary_with_comments(
|
||||
&self,
|
||||
cond: &Expr,
|
||||
then: &Expr,
|
||||
els: &Expr,
|
||||
comments: &TernaryComments,
|
||||
) -> Doc {
|
||||
let mut head = vec![self.expr(cond)];
|
||||
let hard = self.inline_comments(&comments.before_question, &mut head);
|
||||
let mut inner = vec![if hard { Doc::HardLine } else { Doc::Line }];
|
||||
inner.push(text("?"));
|
||||
let hard = self.inline_comments(&comments.after_question, &mut inner);
|
||||
inner.push(if hard { Doc::HardLine } else { text(" ") });
|
||||
inner.push(self.expr(then));
|
||||
let hard = self.inline_comments(&comments.before_colon, &mut inner);
|
||||
inner.push(if hard { Doc::HardLine } else { Doc::Line });
|
||||
inner.push(text(":"));
|
||||
let hard = self.inline_comments(&comments.after_colon, &mut inner);
|
||||
inner.push(if hard { Doc::HardLine } else { text(" ") });
|
||||
inner.push(self.expr(els));
|
||||
head.push(indent(inner));
|
||||
group(head)
|
||||
}
|
||||
|
||||
/// Compact rendering used inside `[...]` brackets: arithmetic and shift
|
||||
/// operators lose their surrounding spaces (`[WIDTH-1:0]`), and no line
|
||||
/// breaks are introduced.
|
||||
pub(super) fn expr_compact(&self, e: &Expr) -> Doc {
|
||||
match &e.kind {
|
||||
ExprKind::Binary { lhs, op, rhs, comments } => {
|
||||
if comments.before.is_empty() && comments.after.is_empty() {
|
||||
let tight = Self::binary_prec(op) >= 8;
|
||||
let sep = if tight { op.clone() } else { format!(" {op} ") };
|
||||
return concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]);
|
||||
}
|
||||
// A comment written next to the operator has nowhere to go in
|
||||
// the tight spelling, so the operator gets its spaces back;
|
||||
// a line comment pushes what follows onto the next line.
|
||||
let mut docs = vec![self.expr_compact(lhs)];
|
||||
self.inline_comments_spaced(&comments.before, &mut docs);
|
||||
docs.push(text(op.clone()));
|
||||
self.inline_comments_spaced(&comments.after, &mut docs);
|
||||
docs.push(self.expr_compact(rhs));
|
||||
concat(docs)
|
||||
}
|
||||
// The compact spelling has nowhere to put a comment written
|
||||
// inside the `? :` or just inside the parentheses, so a shape
|
||||
// that carries one falls back to the ordinary layout, which does.
|
||||
ExprKind::Ternary { cond, then, els, comments } if comments.is_empty() => concat(vec![
|
||||
self.expr_compact(cond),
|
||||
text(" ? "),
|
||||
self.expr_compact(then),
|
||||
text(" : "),
|
||||
self.expr_compact(els),
|
||||
]),
|
||||
ExprKind::Paren { inner, before, after } if before.is_empty() && after.is_empty() => {
|
||||
concat(vec![text("("), self.expr_compact(inner), text(")")])
|
||||
}
|
||||
ExprKind::Unary { op, comments, expr } if comments.is_empty() => {
|
||||
concat(vec![text(op.clone()), self.expr_compact(expr)])
|
||||
}
|
||||
_ => self.expr(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// `base.name` / `base::name`, with the comments the source wrote on
|
||||
/// either side of the joining token.
|
||||
fn chain_segment(
|
||||
&self,
|
||||
base: &Expr,
|
||||
joiner: &str,
|
||||
name: &str,
|
||||
comments: &SegmentComments,
|
||||
) -> Doc {
|
||||
if comments.is_empty() {
|
||||
return concat(vec![self.expr(base), text(format!("{joiner}{}", named(name)))]);
|
||||
}
|
||||
let mut docs = vec![self.expr(base)];
|
||||
self.slot_comments(&comments.before_open, &mut docs);
|
||||
docs.push(text(joiner.to_string()));
|
||||
self.slot_comments(&comments.after_open, &mut docs);
|
||||
docs.push(text(named(name)));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `lhs inside set`, with the comments written on either side of the word
|
||||
/// kept on their own side of it, as every binary operator's are.
|
||||
fn inside_head(&self, lhs: &Expr, comments: &BinaryComments, set: Doc) -> Doc {
|
||||
if comments.before.is_empty() && comments.after.is_empty() {
|
||||
return concat(vec![self.expr(lhs), text(" inside "), set]);
|
||||
}
|
||||
let mut docs = vec![self.expr(lhs)];
|
||||
self.inline_comments_spaced(&comments.before, &mut docs);
|
||||
docs.push(text("inside"));
|
||||
self.inline_comments_spaced(&comments.after, &mut docs);
|
||||
docs.push(set);
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `<base> with ` — the head both postfix `with` forms share, with the
|
||||
/// comments written on either side of the keyword printed back where they
|
||||
/// were written. Anywhere else they would move across `with` and the
|
||||
/// safety net would reject the output.
|
||||
fn with_head(&self, base: &Expr, comments: &WithComments) -> Doc {
|
||||
let mut docs = vec![self.expr(base)];
|
||||
self.inline_comments_spaced(&comments.before_kw, &mut docs);
|
||||
docs.push(text("with"));
|
||||
self.inline_comments_spaced(&comments.after_kw, &mut docs);
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! Instantiations: a module instance with its parameter overrides and
|
||||
//! named or ordered connections, the alignment of a connection list,
|
||||
//! `bind`, and gate instances.
|
||||
//!
|
||||
//! A connection's `(` is the one column an instance list aligns on; the
|
||||
//! cells, the column spec and the planner all live here, so a change to
|
||||
//! how connections align touches one file.
|
||||
|
||||
use crate::align::{self, Align, ColSpec, Row};
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
|
||||
use super::comment::is_line_comment;
|
||||
use super::list::ListItem;
|
||||
use super::{join_names, name_doc, named, Fmt};
|
||||
|
||||
/// A named connection's one alignment column: the `(` of the value. It is
|
||||
/// written tight when flush (`.clk(clk)`) and one space off the name when
|
||||
/// aligned (`.clk (clk)`), which is Verible's spelling of both.
|
||||
const CONNECTION_COLS: &[ColSpec] = &[ColSpec { flush: 0, min: 1 }];
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
pub(super) fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc {
|
||||
let mut docs = vec![name_doc(&inst.module)];
|
||||
let mut on_fresh_line = self.bracket_comments(&inst.param_comments, &mut docs, false);
|
||||
// An empty `#()` was written by hand and is reprinted as `#()`; a
|
||||
// missing one stays missing.
|
||||
if let Some(params) = &inst.params {
|
||||
let items: Vec<ListItem> = params
|
||||
.iter()
|
||||
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
|
||||
.collect();
|
||||
let items = self.list_entries(items, &inst.param_directives);
|
||||
let broken = !inst.param_directives.is_empty() || holds_verbatim_value(params);
|
||||
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
||||
self.slot_comments(&inst.after_hash, &mut docs);
|
||||
docs.push(self.delimited("(", items, ")", broken));
|
||||
on_fresh_line = false;
|
||||
}
|
||||
if let [only] = &inst.instances[..] {
|
||||
// The common case: no extra indent level, so a connection list
|
||||
// that breaks lines up under the instance itself. The comments
|
||||
// before the instance name print here — the multi-instance branch
|
||||
// below has `leading` for them, and this one had nowhere at all.
|
||||
if !self.bracket_comments(&only.meta.leading, &mut docs, on_fresh_line) {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.instance(only, depth));
|
||||
} else {
|
||||
if !on_fresh_line {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
// Several instances share one declaration: keep them on one line
|
||||
// if they fit, otherwise one per line, indented under the head.
|
||||
let last = inst.instances.len() - 1;
|
||||
let mut inner = Vec::new();
|
||||
for (i, instance) in inst.instances.iter().enumerate() {
|
||||
inner.extend(self.leading(&instance.meta));
|
||||
inner.push(self.instance(instance, depth + 1));
|
||||
if self.inline_comments(&instance.meta.before_sep, &mut inner) {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
if i < last {
|
||||
inner.push(text(","));
|
||||
}
|
||||
if let Some(tr) = &instance.meta.trailing {
|
||||
inner.push(text(" "));
|
||||
inner.push(self.comment(tr));
|
||||
if i < last {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
} else if i < last {
|
||||
inner.push(Doc::Line);
|
||||
}
|
||||
}
|
||||
docs.push(group(vec![indent(inner)]));
|
||||
}
|
||||
docs.push(self.semi(&inst.before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One instance of a module instantiation: `u0 [3:0] (.a(x))`.
|
||||
fn instance(&self, instance: &Instance, depth: usize) -> Doc {
|
||||
let mut docs = vec![name_doc(&instance.name)];
|
||||
if !instance.dims.is_empty() {
|
||||
if instance.dims[0].comments.opens_clean() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
for d in &instance.dims {
|
||||
docs.push(self.dim(d));
|
||||
}
|
||||
}
|
||||
if !self.bracket_comments(&instance.conn_comments, &mut docs, false) {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.connections(&instance.conns, &instance.conn_directives, depth + 1));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A connection list, with the `` `ifdef``-style directives written between
|
||||
/// its entries merged back into source order. A list holding one is laid
|
||||
/// out broken: a directive runs to end of line, so nothing may share it.
|
||||
fn connections(&self, conns: &Connections, directives: &[ListDirective], depth: usize) -> Doc {
|
||||
let mut broken = !directives.is_empty();
|
||||
let items: Vec<ListItem> = match conns {
|
||||
Connections::Named(list) => {
|
||||
let aligns = self.connection_aligns(list, directives, depth);
|
||||
broken |= aligns.iter().any(Option::is_some) || holds_verbatim_value(list);
|
||||
list.iter()
|
||||
.zip(&aligns)
|
||||
.map(|(c, a)| {
|
||||
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
|
||||
.with_comma(c.comma)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Connections::Ordered(list) => list
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let d = match &c.expr {
|
||||
Some(e) => self.expr(e),
|
||||
None => text(""),
|
||||
};
|
||||
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let items = self.list_entries(items, directives);
|
||||
self.delimited("(", items, ")", broken)
|
||||
}
|
||||
|
||||
/// The alignment plan for an instance's named connection list.
|
||||
fn connection_aligns(
|
||||
&self,
|
||||
conns: &[Connection],
|
||||
directives: &[ListDirective],
|
||||
depth: usize,
|
||||
) -> Vec<Option<Align>> {
|
||||
let rows: Vec<Option<Row>> = conns
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let paren = self.open_paren_offset(c.name_span.end)?;
|
||||
Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma))
|
||||
})
|
||||
.collect();
|
||||
let breaks = Self::list_breaks(conns.iter().map(|c| &c.meta), directives);
|
||||
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
|
||||
}
|
||||
|
||||
/// Byte offset of the `(` opening a named connection's value.
|
||||
fn open_paren_offset(&self, after_name: u32) -> Option<u32> {
|
||||
let bytes = self.src.as_bytes();
|
||||
let mut pos = after_name as usize;
|
||||
while matches!(bytes.get(pos), Some(b' ' | b'\t' | b'\r' | b'\n')) {
|
||||
pos += 1;
|
||||
}
|
||||
(bytes.get(pos) == Some(&b'(')).then_some(pos as u32)
|
||||
}
|
||||
|
||||
pub(super) fn connection(&self, c: &Connection) -> Doc {
|
||||
self.connection_aligned(c, None)
|
||||
}
|
||||
|
||||
fn connection_aligned(&self, c: &Connection, align: Option<&Align>) -> Doc {
|
||||
align::render(&self.connection_cells(c), CONNECTION_COLS, align)
|
||||
}
|
||||
|
||||
/// A named connection split at its one alignment column, the `(` of the
|
||||
/// value: `.data_i` and `(bus[7:0])`. Everything else — `.*`, an implicit
|
||||
/// `.clk`, a positional value, a connection with comments inside its own
|
||||
/// parens — is one cell and never joins a group.
|
||||
fn connection_cells(&self, c: &Connection) -> Vec<Doc> {
|
||||
let plain = || vec![self.connection_plain(c)];
|
||||
// An attributed connection is one cell: the attribute widens the row
|
||||
// by an amount no other row shares, so it never joins a group —
|
||||
// `list_breaks` already ends the group at it, as it does at a
|
||||
// compiler directive.
|
||||
if c.name.is_empty() || c.name == "*" || !c.meta.attrs.is_empty() {
|
||||
return plain();
|
||||
}
|
||||
// A comment written in one of the connection's own gaps makes the row
|
||||
// a width no other row shares, so it never joins an alignment group.
|
||||
if !c.after_dot.is_empty() || !c.before_open.is_empty() || !c.after_open.is_empty() {
|
||||
return plain();
|
||||
}
|
||||
let Some(e) = &c.expr else { return plain() };
|
||||
// A verbatim conditional region is many lines of bytes; a row that
|
||||
// wide shares its width with nothing, and the `)` after it has a line
|
||||
// break of its own to keep (`Fmt::verbatim_value_breaks`).
|
||||
if matches!(e.kind, ExprKind::Empty(_) | ExprKind::Verbatim(_)) {
|
||||
return plain();
|
||||
}
|
||||
let mut inner = vec![Doc::SoftLine, self.expr(e)];
|
||||
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
|
||||
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
|
||||
vec![
|
||||
text(format!(".{}", named(&c.name))),
|
||||
concat(vec![text("("), group(vec![indent(inner), close]), text(")")]),
|
||||
]
|
||||
}
|
||||
|
||||
/// True when a connection's value is a **verbatim conditional region**
|
||||
/// the source ended a line after — which it always does when the region
|
||||
/// ends on a `` `endif ``.
|
||||
///
|
||||
/// A line-oriented directive runs to the end of its line (`lexer.rs`'s
|
||||
/// `is_line_directive`), so a `)` printed after one on the same line is
|
||||
/// swallowed into the directive's own token — a rewrite the safety net
|
||||
/// refuses. The break is read back from `src` rather than stored, for the
|
||||
/// reason [`Fmt::glued_null_item`] gives, and is a fixed point by
|
||||
/// construction: the break printed here reads back as the same break.
|
||||
fn verbatim_value_breaks(&self, c: &Connection) -> bool {
|
||||
let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &c.expr else { return false };
|
||||
self.src
|
||||
.get(raw.span.end as usize..c.span.end as usize)
|
||||
.is_some_and(|gap| gap.contains('\n'))
|
||||
}
|
||||
|
||||
fn connection_plain(&self, c: &Connection) -> Doc {
|
||||
// `(* async *) .async_data_o (x)`: the attributes stay in front of
|
||||
// the connection, on its line (corpus
|
||||
// `common_cells/src/cdc_fifo_gray.sv:140`).
|
||||
if !c.meta.attrs.is_empty() {
|
||||
let mut docs = Vec::new();
|
||||
for attr in &c.meta.attrs {
|
||||
docs.push(self.raw_inline(attr));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.connection_bare(c));
|
||||
return concat(docs);
|
||||
}
|
||||
self.connection_bare(c)
|
||||
}
|
||||
|
||||
/// A connection without its attributes: `.name(expr)`, `.name()`,
|
||||
/// `.name`, `.*`, or a positional value.
|
||||
fn connection_bare(&self, c: &Connection) -> Doc {
|
||||
if c.name == "*" {
|
||||
if c.after_dot.is_empty() {
|
||||
return text(".*");
|
||||
}
|
||||
let mut docs = vec![text(".")];
|
||||
self.slot_comments(&c.after_dot, &mut docs);
|
||||
docs.push(text("*"));
|
||||
return concat(docs);
|
||||
}
|
||||
if c.name.is_empty() {
|
||||
// Positional parameter value.
|
||||
return match &c.expr {
|
||||
Some(e) => self.expr(e),
|
||||
None => text(""),
|
||||
};
|
||||
}
|
||||
// `.` then the name, with whatever the source wrote between them.
|
||||
let head = |f: &Self| {
|
||||
let mut docs = vec![text(".")];
|
||||
f.slot_comments(&c.after_dot, &mut docs);
|
||||
docs.push(text(named(&c.name)));
|
||||
docs
|
||||
};
|
||||
// …and the `(` that follows the name, with its two gaps.
|
||||
let open = |f: &Self, docs: &mut Vec<Doc>| {
|
||||
f.slot_comments(&c.before_open, docs);
|
||||
docs.push(text("("));
|
||||
f.slot_comments(&c.after_open, docs);
|
||||
};
|
||||
match &c.expr {
|
||||
None => concat(head(self)),
|
||||
Some(Expr { kind: ExprKind::Empty(comments), .. }) => {
|
||||
let mut docs = head(self);
|
||||
open(self, &mut docs);
|
||||
let mut ends_line = false;
|
||||
for cm in comments {
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.comment(cm));
|
||||
ends_line = is_line_comment(&cm.text);
|
||||
}
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
Some(e) => {
|
||||
let mut inner = vec![Doc::SoftLine, self.expr(e)];
|
||||
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
|
||||
let broke = ends_line || self.verbatim_value_breaks(c);
|
||||
let close = if broke { Doc::HardLine } else { Doc::SoftLine };
|
||||
let mut docs = head(self);
|
||||
open(self, &mut docs);
|
||||
docs.push(group(vec![indent(inner), close]));
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `bind <target> [: u_a, u_b] <instantiation>`: the head is one flat run
|
||||
/// of names, and everything after it is laid out exactly as the same
|
||||
/// instantiation written on its own would be.
|
||||
pub(super) fn bind(&self, b: &BindDirective, depth: usize) -> Doc {
|
||||
// The comments around the head have no node of their own; each prints
|
||||
// back between the two tokens it was written between.
|
||||
let mut docs = vec![text("bind")];
|
||||
self.inline_comments_spaced(&b.target_comments, &mut docs);
|
||||
// One segment at a time, for the reason `scope_prefix` prints a `::`
|
||||
// chain that way: `named` supplies the space an escaped segment needs
|
||||
// to terminate, and a joined string could not carry it.
|
||||
for (i, seg) in b.target.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text("."));
|
||||
}
|
||||
docs.push(text(named(&seg.name)));
|
||||
if let Some(index) = &seg.index {
|
||||
docs.push(text("["));
|
||||
docs.push(self.expr_compact(index));
|
||||
docs.push(text("]"));
|
||||
}
|
||||
}
|
||||
if !b.instances.is_empty() {
|
||||
docs.push(text(format!(" : {}", join_names(&b.instances))));
|
||||
}
|
||||
self.inline_comments_spaced(&b.module_comments, &mut docs);
|
||||
docs.push(self.instantiation(&b.inst, depth));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
pub(super) fn gate_instantiation(&self, g: &GateInstantiation) -> Doc {
|
||||
let mut docs = vec![text(g.gate.clone())];
|
||||
if let Some(s) = &g.strength {
|
||||
docs.push(text(format!(" {}", drive_strength(s))));
|
||||
}
|
||||
if let [delay] = g.delay.as_slice() {
|
||||
// One value prints itself, brackets and all (`#5`, `#(5)`).
|
||||
docs.push(text(" #"));
|
||||
docs.push(self.expr(delay));
|
||||
} else if !g.delay.is_empty() {
|
||||
// `#(rise, fall[, turn-off])` — the parens are the list's own.
|
||||
docs.push(text(" #("));
|
||||
for (i, d) in g.delay.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
}
|
||||
docs.push(self.expr(d));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
}
|
||||
for (i, inst) in g.instances.iter().enumerate() {
|
||||
docs.push(if i > 0 { text(", ") } else { text(" ") });
|
||||
if let Some(name) = &inst.name {
|
||||
docs.push(name_doc(name));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.expr_list("(", &inst.args, ")"));
|
||||
}
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
|
||||
/// True when any entry of a connection or override list carries a
|
||||
/// **multi-line verbatim value** — a conditional region
|
||||
/// ([`ExprKind::Verbatim`]).
|
||||
///
|
||||
/// Such a value brings its own line breaks, which `Doc::Inline` copies
|
||||
/// through without telling the enclosing group; without this the list would
|
||||
/// be measured as one short line and flattened around a value that is
|
||||
/// twenty lines tall. It is exactly the reason a list holding a
|
||||
/// [`ListDirective`] is broken, for exactly the same construct.
|
||||
fn holds_verbatim_value(list: &[Connection]) -> bool {
|
||||
list.iter().any(|c| match &c.expr {
|
||||
Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write.
|
||||
pub(super) fn drive_strength(s: &DriveStrength) -> String {
|
||||
match &s.second {
|
||||
Some(second) => format!("({}, {})", s.first, second),
|
||||
None => format!("({})", s.first),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
//! The file and its items: a source file or fragment, the sequence of
|
||||
//! items at one indent level with the blank lines the source wrote, the
|
||||
//! dispatch from `ItemKind` to the construct that prints it, and the
|
||||
//! items that are only containers or one-liners — `package`, the
|
||||
//! generate constructs, `assign`.
|
||||
//!
|
||||
//! Everything with a shape worth a file of its own — the module header,
|
||||
//! an instantiation, a declaration, a class — is dispatched to from
|
||||
//! `item_kind` and lives in a sibling module.
|
||||
|
||||
use crate::align::Align;
|
||||
use crate::doc::*;
|
||||
use crate::range::Split;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::instance::drive_strength;
|
||||
use super::list::ListItem;
|
||||
use super::verbatim::Slot;
|
||||
use super::{join_names, join_paths, named, Fmt};
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
pub(super) fn file(&self, f: &SourceFile) -> Doc {
|
||||
let mut docs = match &f.fragment {
|
||||
Some(fragment) => self.fragment(fragment),
|
||||
None => self.item_seq(&f.items, 0),
|
||||
};
|
||||
for c in &f.dangling {
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => continue,
|
||||
Slot::Opens(r) => self.verbatim(r),
|
||||
Slot::Normal => self.comment(c),
|
||||
};
|
||||
if !docs.is_empty() {
|
||||
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(doc);
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A whole file that is the middle of some body, printed at indent 0
|
||||
/// through the very printers that body uses — a statement sequence, an
|
||||
/// enum's member list, a covergroup's items. Nothing here is a layout of
|
||||
/// its own: the fragment is the piece of code it was written as, minus the
|
||||
/// construct around it, and it must come back the way that construct would
|
||||
/// have printed it. See `docs/features/fragment-mode/README.md`.
|
||||
fn fragment(&self, fragment: &Fragment) -> Vec<Doc> {
|
||||
match fragment {
|
||||
Fragment::Statements(stmts) => self.stmt_seq(stmts),
|
||||
Fragment::EnumMembers { members, directives } => {
|
||||
let items = self.list_entries(self.enum_member_items(members), directives);
|
||||
let mut docs = Vec::new();
|
||||
// The file's own dangling comments are `SourceFile::dangling`
|
||||
// and `Fmt::file` prints them, so the list has none of its own.
|
||||
self.list_rows(items, &[], &mut docs);
|
||||
docs
|
||||
}
|
||||
Fragment::CoverItems(items) => self.cover_items(items),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sequence of items at one indent level, preserving single blank lines
|
||||
/// between them. An item a fenced region swallowed emits nothing, and
|
||||
/// contributes no separator either.
|
||||
pub(super) fn item_seq(&self, items: &[Item], depth: usize) -> Vec<Doc> {
|
||||
let aligns = self.param_decl_aligns(items, depth);
|
||||
let mut docs = Vec::new();
|
||||
// The last item that actually emitted something, which is what a
|
||||
// glued null item glues to.
|
||||
let mut prev: Option<&Item> = None;
|
||||
for (item, align) in items.iter().zip(&aligns) {
|
||||
let item_docs = self.item_docs(item, align.as_ref(), depth);
|
||||
if item_docs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !docs.is_empty() && !prev.is_some_and(|p| self.glued_null_item(p, item)) {
|
||||
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.extend(item_docs);
|
||||
prev = Some(item);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// True when `item` is a null item (`;`) the source wrote on the line the
|
||||
/// item before it ended on, which is how it is printed back:
|
||||
/// `endgenerate;`, `end;`, `endmodule;`, `;;`.
|
||||
///
|
||||
/// The question is asked of the source rather than of the AST because it
|
||||
/// is a layout fact about the gap between two siblings, and this is the
|
||||
/// one place that gap is laid out — the same reason `eq_offset` and
|
||||
/// `default_has_colon` read `src` here. A null item that begins a body has
|
||||
/// no sibling to glue to and prints on its own line.
|
||||
///
|
||||
/// Anything that gives the `;` docs of its own — a leading comment, an
|
||||
/// attribute, a blank line, a format-off fence opening on it — takes the
|
||||
/// own-line path instead, so the glue only ever appends a bare `;`. Note
|
||||
/// that a `//` comment cannot stand in a newline-free gap: it would
|
||||
/// swallow the `;` that follows it. The only comment that fits is a
|
||||
/// one-line block comment, which prints inline before the `;`, in the
|
||||
/// order it was written.
|
||||
fn glued_null_item(&self, prev: &Item, item: &Item) -> bool {
|
||||
if !matches!(item.kind, ItemKind::Empty) {
|
||||
return false;
|
||||
}
|
||||
if item.meta.blank_before || !item.meta.leading.is_empty() || !item.meta.attrs.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if self.is_verbatim(item.span) || self.opens_at(item.span.start as usize).is_some() {
|
||||
return false;
|
||||
}
|
||||
self.src
|
||||
.get(prev.span.end as usize..item.span.start as usize)
|
||||
.is_some_and(|gap| !gap.contains('\n'))
|
||||
}
|
||||
|
||||
fn item(&self, item: &Item, depth: usize) -> Doc {
|
||||
concat(self.item_docs(item, None, depth))
|
||||
}
|
||||
|
||||
/// One item: its leading comments, then — unless a verbatim region is
|
||||
/// already emitting its bytes — its attributes, code and trailing
|
||||
/// comment. Comments before the `off` fence are still emitted; comments
|
||||
/// are never dropped.
|
||||
fn item_docs(&self, item: &Item, align: Option<&Align>, depth: usize) -> Vec<Doc> {
|
||||
if let Some(split) = self.split_at(item.span.start as usize) {
|
||||
if let Some(docs) = self.split_item(item, split, depth) {
|
||||
return docs;
|
||||
}
|
||||
}
|
||||
// A verbatim run whose first item carries no leading comment opens at
|
||||
// the item's own code; there is no comment to emit the bytes from.
|
||||
if let Some(region) = self.opens_at(item.span.start as usize) {
|
||||
return vec![self.verbatim(region)];
|
||||
}
|
||||
if self.is_verbatim(item.span) {
|
||||
// The item's own bytes, its attributes included, are emitted
|
||||
// verbatim by the fence; only its leading comments are ours.
|
||||
let mut docs = self.leading_comments(&item.meta);
|
||||
// The last comment asked for a line break before code that is not
|
||||
// coming. Whoever emits the next unit separates it itself.
|
||||
if matches!(docs.last(), Some(Doc::HardLine)) {
|
||||
docs.pop();
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
let mut docs = self.leading(&item.meta);
|
||||
docs.push(self.item_kind(&item.kind, align, depth));
|
||||
docs.extend(self.trailing(&item.meta));
|
||||
docs
|
||||
}
|
||||
|
||||
/// A scope-bearing item a range run descends into.
|
||||
///
|
||||
/// Its header and its closing keyword are the source's own bytes unless
|
||||
/// the caller's lines reached them, and its body is laid out one item at a
|
||||
/// time — which is what keeps a three-line edit from reformatting a
|
||||
/// two-thousand-line module. `None` for any other item kind, which
|
||||
/// `range.rs` never records a split for.
|
||||
fn split_item(&self, item: &Item, split: &Split, depth: usize) -> Option<Vec<Doc>> {
|
||||
let (items, dangling) = match &item.kind {
|
||||
ItemKind::Module(m) => (&m.items[..], &m.dangling[..]),
|
||||
ItemKind::Package { items, dangling, .. } => (&items[..], &dangling[..]),
|
||||
_ => return None,
|
||||
};
|
||||
let mut docs = Vec::new();
|
||||
match split.head {
|
||||
Some(range) => docs.push(self.slice(range)),
|
||||
None => {
|
||||
docs.extend(self.leading(&item.meta));
|
||||
docs.push(self.head_doc(&item.kind, depth)?);
|
||||
}
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
match split.tail {
|
||||
// The slice reaches over the comment written after the keyword,
|
||||
// so the trailing comment must not be printed a second time.
|
||||
Some(range) => docs.push(self.slice(range)),
|
||||
None => {
|
||||
docs.push(self.tail_doc(&item.kind)?);
|
||||
docs.extend(self.trailing(&item.meta));
|
||||
}
|
||||
}
|
||||
Some(docs)
|
||||
}
|
||||
|
||||
/// A split item's header, laid out.
|
||||
fn head_doc(&self, kind: &ItemKind, depth: usize) -> Option<Doc> {
|
||||
match kind {
|
||||
ItemKind::Module(m) => Some(self.module_head(m, depth)),
|
||||
ItemKind::Package { kw, before_name, name, before_semi, .. } => {
|
||||
Some(self.package_head(kw, before_name, name, before_semi))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A split item's closing keyword, laid out.
|
||||
fn tail_doc(&self, kind: &ItemKind) -> Option<Doc> {
|
||||
match kind {
|
||||
ItemKind::Module(m) => {
|
||||
Some(self.closing_labeled(m.end_kw(), &m.end_label, &m.end_label_comments))
|
||||
}
|
||||
ItemKind::Package { end_label, end_label_comments, .. } => {
|
||||
Some(self.closing_labeled("endpackage", end_label, end_label_comments))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn item_kind(&self, kind: &ItemKind, align: Option<&Align>, depth: usize) -> Doc {
|
||||
match kind {
|
||||
ItemKind::Module(m) => self.module(m, depth),
|
||||
ItemKind::Package {
|
||||
kw,
|
||||
before_name,
|
||||
name,
|
||||
before_semi,
|
||||
items,
|
||||
dangling,
|
||||
end_label,
|
||||
end_label_comments,
|
||||
..
|
||||
} => {
|
||||
let mut docs = vec![self.package_head(kw, before_name, name, before_semi)];
|
||||
let mut body = Vec::new();
|
||||
if !items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("endpackage", end_label, end_label_comments));
|
||||
concat(docs)
|
||||
}
|
||||
ItemKind::Directive(d) => self.raw_text(d),
|
||||
// Only error-tolerant parsing builds these, and `format_source`
|
||||
// parses strictly, so this arm exists to keep the match total.
|
||||
ItemKind::Error(d) => self.raw_text(d),
|
||||
ItemKind::MacroItem(m) => self.macro_call(m),
|
||||
// Printed exactly like the statement it looks like; the call's own
|
||||
// argument group supplies the line breaks.
|
||||
ItemKind::ElabTask(e) => concat(vec![self.expr(e), text(";")]),
|
||||
ItemKind::Import(paths) => text(format!("import {};", join_paths(paths))),
|
||||
ItemKind::Export(e) => Self::export(e),
|
||||
ItemKind::Timeunit(t) => text(format!("{t};")),
|
||||
ItemKind::Typedef(t) => self.typedef(t),
|
||||
ItemKind::ParamDecl(d) => concat(vec![self.param_decl(d, align), text(";")]),
|
||||
ItemKind::DataDecl(d) => concat(vec![self.data_decl(d), text(";")]),
|
||||
ItemKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]),
|
||||
ItemKind::ContAssign(a) => self.cont_assign(a),
|
||||
ItemKind::Always { kw, stmt } => self.stmt_as_body(text(kw.clone()), stmt),
|
||||
ItemKind::Initial(s) => self.stmt_as_body(text("initial"), s),
|
||||
ItemKind::Final(s) => self.stmt_as_body(text("final"), s),
|
||||
ItemKind::Instantiation(inst) => self.instantiation(inst, depth),
|
||||
ItemKind::Bind(b) => self.bind(b, depth),
|
||||
ItemKind::GateInstantiation(g) => self.gate_instantiation(g),
|
||||
ItemKind::Genvar(names) => text(format!("genvar {};", join_names(names))),
|
||||
ItemKind::GenerateRegion { items, dangling } => {
|
||||
let mut body = Vec::new();
|
||||
if !items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(dangling));
|
||||
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
|
||||
}
|
||||
ItemKind::GenIf(g) => self.gen_if(g, depth),
|
||||
ItemKind::GenFor(g) => self.gen_for(g, depth),
|
||||
ItemKind::GenCase(g) => self.gen_case(g, depth),
|
||||
ItemKind::Function(f) => self.function(f),
|
||||
ItemKind::Task(t) => self.task(t),
|
||||
ItemKind::Let(l) => self.let_decl(l),
|
||||
ItemKind::Class(c) => self.class(c, depth),
|
||||
ItemKind::Modport(decls) => self.modport(decls),
|
||||
ItemKind::Clocking(c) => self.clocking(c),
|
||||
ItemKind::Constraint(c) => self.constraint(c),
|
||||
ItemKind::Covergroup(c) => self.covergroup(c),
|
||||
ItemKind::PropSeqDecl(d) => self.prop_seq_decl(d),
|
||||
ItemKind::Assertion(a) => self.assertion(a),
|
||||
ItemKind::DefaultDisable(d) => self.default_disable(d),
|
||||
ItemKind::Verbatim(raw) => self.raw_text(raw),
|
||||
// A null item is its `;`. Whether it keeps the previous item's
|
||||
// line or takes one of its own is `item_seq`'s call.
|
||||
ItemKind::Empty => text(";"),
|
||||
ItemKind::Defparam(pairs) => {
|
||||
let parts: Vec<Doc> = pairs
|
||||
.iter()
|
||||
.map(|(l, r)| concat(vec![self.expr(l), text(" = "), self.expr(r)]))
|
||||
.collect();
|
||||
let mut docs = vec![text("defparam ")];
|
||||
docs.extend(join(parts, text(", ")));
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
// `alias a = b = c;` — one line, one space around every `=`, the
|
||||
// spacing every other assignment-shaped item already uses.
|
||||
ItemKind::Alias(nets) => {
|
||||
let mut docs = vec![text("alias ")];
|
||||
docs.extend(join(nets.iter().map(|n| self.expr(n)).collect(), text(" = ")));
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `package p;` — the two comment slots a package header owns.
|
||||
fn package_head(
|
||||
&self,
|
||||
kw: &str,
|
||||
before_name: &[Comment],
|
||||
name: &str,
|
||||
before_semi: &[Comment],
|
||||
) -> Doc {
|
||||
let mut docs = vec![text(kw.to_string())];
|
||||
if before_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(before_name, &mut docs);
|
||||
}
|
||||
docs.push(text(named(name)));
|
||||
docs.push(self.semi(before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn cont_assign(&self, a: &ContAssign) -> Doc {
|
||||
// `assign /*c*/ y = x;` — the first pair's own leading comments were
|
||||
// written after the keyword, and print there.
|
||||
let lead = a.assigns.first().map(|p| p.meta.leading.as_slice()).unwrap_or(&[]);
|
||||
let mut docs = vec![text("assign")];
|
||||
if lead.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(lead, &mut docs);
|
||||
}
|
||||
if let Some(s) = &a.strength {
|
||||
docs.push(text(format!("{} ", drive_strength(s))));
|
||||
}
|
||||
if let Some(delay) = &a.delay {
|
||||
docs.push(text("#"));
|
||||
docs.push(self.expr(delay));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
let items: Vec<ListItem> = a
|
||||
.assigns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| {
|
||||
// The first pair's leading comments are printed above, after
|
||||
// the keyword; printing them twice would duplicate them.
|
||||
let skip = usize::from(i == 0) * lead.len();
|
||||
let mut item = ListItem::from_meta(&p.meta, self.assign_pair(p));
|
||||
item.leading.drain(..skip.min(item.leading.len()));
|
||||
item
|
||||
})
|
||||
.collect();
|
||||
if items.len() == 1 {
|
||||
let item = items.into_iter().next().unwrap();
|
||||
docs.push(item.doc);
|
||||
// The last pair's separator is the `;`, so its `before_sep`
|
||||
// comments print in front of it.
|
||||
if self.inline_comments(&item.before_sep, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
if let Some(tr) = item.trailing {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.comment(&tr));
|
||||
}
|
||||
} else {
|
||||
let last = items.len() - 1;
|
||||
let mut inner = Vec::new();
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
inner.push(item.doc);
|
||||
if self.inline_comments(&item.before_sep, &mut inner) {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
if i < last {
|
||||
inner.push(text(","));
|
||||
} else {
|
||||
inner.push(text(";"));
|
||||
}
|
||||
if let Some(tr) = item.trailing {
|
||||
inner.push(text(" "));
|
||||
inner.push(self.comment(&tr));
|
||||
if i < last {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
} else if i < last {
|
||||
inner.push(Doc::Line);
|
||||
}
|
||||
}
|
||||
docs.push(group(vec![indent(inner)]));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `lhs = rhs`, with any comments written after the `=` printed on the
|
||||
/// `=`'s line so they stay on that side of the value.
|
||||
fn assign_pair(&self, p: &AssignPair) -> Doc {
|
||||
// `y /*c*/ =` — the comments stay on the operator's left.
|
||||
let mut head = vec![self.expr(&p.lhs)];
|
||||
self.slot_comments(&p.op_comments, &mut head);
|
||||
head.push(text(if p.op_comments.is_empty() { " =" } else { "=" }));
|
||||
if p.rhs_comments.is_empty() {
|
||||
head.push(self.assign_rhs(self.expr(&p.rhs)));
|
||||
return group(head);
|
||||
}
|
||||
let mut inner = Vec::new();
|
||||
let ends_line = self.inline_comments(&p.rhs_comments, &mut inner);
|
||||
inner.push(if ends_line { Doc::HardLine } else { text(" ") });
|
||||
inner.push(self.expr(&p.rhs));
|
||||
head.push(indent(inner));
|
||||
group(head)
|
||||
}
|
||||
|
||||
fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
|
||||
let mut docs = vec![text("if "), self.parens(&g.cond)];
|
||||
let mut cuddle = self.gen_block(&mut docs, &g.then, depth);
|
||||
let mut els = &g.els;
|
||||
while let Some(e) = els {
|
||||
match e.as_ref() {
|
||||
GenElse::If(_meta, gi) => {
|
||||
if cuddle {
|
||||
docs.push(text(" else if "));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else if "));
|
||||
}
|
||||
docs.push(self.parens(&gi.cond));
|
||||
cuddle = self.gen_block(&mut docs, &gi.then, depth);
|
||||
els = &gi.els;
|
||||
}
|
||||
GenElse::Block(b) => {
|
||||
if cuddle {
|
||||
docs.push(text(" else"));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
}
|
||||
self.gen_block(&mut docs, b, depth);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// Append a generate block; returns true if it ended with `end` (so
|
||||
/// `else` can cuddle).
|
||||
fn gen_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) -> bool {
|
||||
if b.is_block {
|
||||
if b.before_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.before_kw, docs);
|
||||
}
|
||||
docs.push(text("begin"));
|
||||
if let Some(l) = &b.label {
|
||||
self.slot_comments(&b.before_colon, docs);
|
||||
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
|
||||
if b.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.after_colon, docs);
|
||||
}
|
||||
docs.push(text(named(l)));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !b.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&b.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
|
||||
true
|
||||
} else {
|
||||
let item = &b.items[0];
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.item(item, depth + 1)])]));
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
|
||||
let mut header = Vec::new();
|
||||
self.for_open(&g.comments, &mut header);
|
||||
if g.init_genvar {
|
||||
header.push(text("genvar"));
|
||||
if g.after_genvar.is_empty() {
|
||||
header.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&g.after_genvar, &mut header);
|
||||
}
|
||||
}
|
||||
self.simple_assign(&g.init, &mut header);
|
||||
self.for_semi(&g.comments.before_first_semi, &g.comments.after_first_semi, &mut header);
|
||||
header.push(self.expr(&g.cond));
|
||||
self.for_semi(&g.comments.before_second_semi, &g.comments.after_second_semi, &mut header);
|
||||
header.push(self.for_step(&g.step));
|
||||
self.slot_comments(&g.comments.before_close, &mut header);
|
||||
header.push(text(")"));
|
||||
let mut docs = vec![concat(header)];
|
||||
self.gen_block(&mut docs, &g.body, depth);
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn gen_case(&self, g: &GenCase, depth: usize) -> Doc {
|
||||
let mut docs = vec![text("case "), self.parens(&g.expr)];
|
||||
let mut body = Vec::new();
|
||||
for item in &g.items {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading(&item.meta));
|
||||
let mut item_docs = vec![self.case_labels(&item.labels, &item.before_colon, item.span)];
|
||||
self.gen_block(&mut item_docs, &item.body, depth + 1);
|
||||
body.push(concat(item_docs));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
}
|
||||
body.extend(self.dangling(&g.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("endcase"));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
//! Comma-separated lists and how their elements are aligned: the
|
||||
//! bracketed list that breaks one element per line when it does not fit
|
||||
//! (`delimited`), the bare list with no brackets to open (`plain_list`),
|
||||
//! the `` `ifdef``-style directives written between elements, and the
|
||||
//! alignment planner that pads a run of rows to shared columns.
|
||||
//!
|
||||
//! What a *row* of a given list looks like — an ANSI port, a named
|
||||
//! connection, a `parameter` declaration — is the construct's own
|
||||
//! business and lives beside it; this module only knows how to break,
|
||||
//! separate and pad the rows it is handed.
|
||||
|
||||
use crate::align::{self, Align, ColSpec, Row};
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::comment::is_line_comment;
|
||||
use super::Fmt;
|
||||
|
||||
/// A list element ready for comma-list layout. Blank lines between elements
|
||||
/// are deliberately dropped, so only the comments ride along.
|
||||
pub(super) struct ListItem {
|
||||
pub(super) leading: Vec<Comment>,
|
||||
pub(super) doc: Doc,
|
||||
/// Comments written between the element and the separator that follows.
|
||||
pub(super) before_sep: Vec<Comment>,
|
||||
pub(super) trailing: Option<Comment>,
|
||||
/// Whether a `,` follows this entry. `None` means "decide from the
|
||||
/// position" — the last entry of the list gets none — which is right for
|
||||
/// every list that cannot hold a compiler directive. The three that can
|
||||
/// (a header's parameter ports and ports, an enum's members) set it from
|
||||
/// the source, because a directive between two elements can move the
|
||||
/// comma to the other side of it.
|
||||
comma: Option<bool>,
|
||||
/// True for a `` `ifdef``-style entry. A directive runs to end of line,
|
||||
/// so whatever follows it — a comma included — starts a new line.
|
||||
directive: bool,
|
||||
}
|
||||
|
||||
impl ListItem {
|
||||
pub(super) fn from_meta(meta: &Meta, doc: Doc) -> Self {
|
||||
ListItem {
|
||||
leading: meta.leading.clone(),
|
||||
doc,
|
||||
before_sep: meta.before_sep.clone(),
|
||||
trailing: meta.trailing.clone(),
|
||||
comma: None,
|
||||
directive: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the `,` the source wrote after this element, instead of letting
|
||||
/// the list derive one from the element's position.
|
||||
pub(super) fn with_comma(mut self, comma: bool) -> Self {
|
||||
self.comma = Some(comma);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// A bracketed expression list (concatenation, call arguments, `inside`
|
||||
/// set). Comments on an element ride along and break the list open.
|
||||
pub(super) fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
|
||||
let items: Vec<ListItem> =
|
||||
items.iter().map(|i| ListItem::from_meta(&i.meta, self.expr(&i.expr))).collect();
|
||||
self.delimited(open, items, close, false)
|
||||
}
|
||||
|
||||
/// Comma-separated list inside `open`/`close`, one per line when broken.
|
||||
/// `force_break` lays every element on its own line regardless of width.
|
||||
pub(super) fn delimited(
|
||||
&self,
|
||||
open: &str,
|
||||
items: Vec<ListItem>,
|
||||
close: &str,
|
||||
force_break: bool,
|
||||
) -> Doc {
|
||||
self.delimited_dangling(open, items, &[], close, force_break)
|
||||
}
|
||||
|
||||
/// The same, plus the comments written after the last element and before
|
||||
/// `close`. They are printed inside the brackets, each on its own line:
|
||||
/// printed after `close` they would move across it in the token stream,
|
||||
/// and a `/* verilator lint_on */`-style pragma would cover the wrong
|
||||
/// region.
|
||||
pub(super) fn delimited_dangling(
|
||||
&self,
|
||||
open: &str,
|
||||
items: Vec<ListItem>,
|
||||
dangling: &[Comment],
|
||||
close: &str,
|
||||
force_break: bool,
|
||||
) -> Doc {
|
||||
if items.is_empty() && dangling.is_empty() {
|
||||
return text(format!("{open}{close}"));
|
||||
}
|
||||
let mut inner: Vec<Doc> = Vec::new();
|
||||
if !items.is_empty() {
|
||||
inner.push(if force_break { Doc::HardLine } else { Doc::SoftLine });
|
||||
}
|
||||
let close_needs_hardline = self.list_rows(items, dangling, &mut inner) || force_break;
|
||||
// Peek at blank_before flags is handled by leading comments already;
|
||||
// blank lines inside bracketed lists are dropped deliberately.
|
||||
let mut docs = vec![text(open), indent(inner)];
|
||||
docs.push(if close_needs_hardline { Doc::HardLine } else { Doc::SoftLine });
|
||||
docs.push(text(close));
|
||||
group(docs)
|
||||
}
|
||||
|
||||
/// The elements of a list, their separators and the comments written
|
||||
/// around each one, appended to `inner`. Returns whether what follows the
|
||||
/// last element must start on a new line — a trailing comment, or a
|
||||
/// comment written where the separator would have been, cannot share it.
|
||||
///
|
||||
/// Split out of [`Fmt::delimited_dangling`] so a fragment's enum members
|
||||
/// go through the very layout their enum body would have given them, at
|
||||
/// indent 0 and with no braces around them.
|
||||
pub(super) fn list_rows(
|
||||
&self,
|
||||
items: Vec<ListItem>,
|
||||
dangling: &[Comment],
|
||||
inner: &mut Vec<Doc>,
|
||||
) -> bool {
|
||||
let last = items.len().saturating_sub(1);
|
||||
let mut close_needs_hardline = false;
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
let meta = Meta { leading: item.leading, ..Meta::default() };
|
||||
inner.extend(self.leading(&meta));
|
||||
inner.push(item.doc);
|
||||
// Comments written before the separator print on this element's
|
||||
// side of it, which is where the source put them.
|
||||
let has_before_sep = !item.before_sep.is_empty();
|
||||
// A directive swallows the rest of its line, so its comma — and
|
||||
// any comment written before that comma — must start a new one.
|
||||
// (A comment itself may share the line: the lexer stops the
|
||||
// directive's capture before a `//` or `/*`.)
|
||||
let ends_line = self.inline_comments(&item.before_sep, inner) || item.directive;
|
||||
if item.comma.unwrap_or(i < last) {
|
||||
if ends_line {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
inner.push(text(","));
|
||||
} else if has_before_sep {
|
||||
close_needs_hardline = true;
|
||||
}
|
||||
if let Some(tr) = item.trailing {
|
||||
inner.push(text(" "));
|
||||
inner.push(self.comment(&tr));
|
||||
if i < last {
|
||||
inner.push(Doc::HardLine);
|
||||
} else {
|
||||
close_needs_hardline = true;
|
||||
}
|
||||
} else if i < last {
|
||||
inner.push(Doc::Line);
|
||||
}
|
||||
}
|
||||
for c in dangling {
|
||||
inner.push(Doc::HardLine);
|
||||
inner.push(self.comment(c));
|
||||
close_needs_hardline = true;
|
||||
}
|
||||
close_needs_hardline
|
||||
}
|
||||
|
||||
/// Put a list's elements and the `` `ifdef``-style directives written
|
||||
/// between them back into source order.
|
||||
///
|
||||
/// A directive is an entry like any other except that it never takes a
|
||||
/// comma of its own unless the source wrote one after it, and that it
|
||||
/// forces the list open: `delimited_dangling`'s `force_break` must be set
|
||||
/// whenever the result holds one, or the printer could put the next entry
|
||||
/// on the directive's line, where the lexer would swallow it.
|
||||
pub(super) fn list_entries(
|
||||
&self,
|
||||
elements: Vec<ListItem>,
|
||||
directives: &[ListDirective],
|
||||
) -> Vec<ListItem> {
|
||||
if directives.is_empty() {
|
||||
return elements;
|
||||
}
|
||||
let mut out = Vec::with_capacity(elements.len() + directives.len());
|
||||
let mut pending = directives.iter().peekable();
|
||||
for (i, element) in elements.into_iter().enumerate() {
|
||||
while let Some(d) = pending.next_if(|d| d.before <= i) {
|
||||
out.push(self.directive_entry(d));
|
||||
}
|
||||
out.push(element);
|
||||
}
|
||||
for d in pending {
|
||||
out.push(self.directive_entry(d));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One directive standing between list elements, verbatim.
|
||||
///
|
||||
/// Its trailing comment goes in `before_sep` rather than `trailing`
|
||||
/// because that is where the source put it — between the directive and
|
||||
/// the comma that may follow it. `Parser::take_before_sep` already moves a
|
||||
/// trailing comment into `before_sep` in source order, so at most one of
|
||||
/// the two is ever populated and appending keeps the source's order.
|
||||
fn directive_entry(&self, d: &ListDirective) -> ListItem {
|
||||
let mut before_sep = d.meta.before_sep.clone();
|
||||
before_sep.extend(d.meta.trailing.clone());
|
||||
ListItem {
|
||||
leading: d.meta.leading.clone(),
|
||||
doc: self.raw_text(&d.raw),
|
||||
before_sep,
|
||||
trailing: None,
|
||||
comma: Some(d.comma),
|
||||
directive: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A comma-separated expression list with no brackets around it: the two
|
||||
/// halves of a `solve a, b before c, d;`.
|
||||
///
|
||||
/// Not [`Fmt::delimited`], which is written for a *bracketed* list: its
|
||||
/// closing break would land the `before` keyword — or the item's `;` —
|
||||
/// on a line of its own the moment any comment forced the group open.
|
||||
/// A list with no brackets has nothing to open, so every comment prints
|
||||
/// where it was written and only a `//` costs a line break.
|
||||
pub(super) fn plain_expr_list(&self, items: &[ExprItem]) -> Doc {
|
||||
self.plain_list(items.iter().map(|i| (&i.meta, self.expr(&i.expr))).collect())
|
||||
}
|
||||
|
||||
/// The same, over elements the caller has already rendered: a transition
|
||||
/// bin's `(a => b), (c => d)` sets are laid out by exactly this rule.
|
||||
pub(super) fn plain_list(&self, items: Vec<(&Meta, Doc)>) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
let last = items.len().saturating_sub(1);
|
||||
for (i, (meta, doc)) in items.into_iter().enumerate() {
|
||||
let leading: Vec<&Comment> = meta.leading.iter().collect();
|
||||
let mut ends_line = false;
|
||||
for c in leading {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") });
|
||||
ends_line = is_line_comment(&c.text);
|
||||
}
|
||||
docs.push(doc);
|
||||
ends_line = self.inline_comments(&meta.before_sep, &mut docs) || ends_line;
|
||||
if i < last {
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(","));
|
||||
}
|
||||
if let Some(tr) = &meta.trailing {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.comment(tr));
|
||||
if is_line_comment(&tr.text) {
|
||||
docs.push(Doc::HardLine);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if i < last {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// Plan the alignment of a sequence of candidate rows.
|
||||
///
|
||||
/// `rows[i]` is `None` for an element that cannot be aligned, and
|
||||
/// `breaks[i]` is true for one that starts a new group. Both split the
|
||||
/// sequence into maximal runs, and every element of a run that is planned
|
||||
/// aligned gets the same [`Align`] — the padding is a property of the
|
||||
/// group, never of one line.
|
||||
pub(super) fn align_groups(
|
||||
&self,
|
||||
rows: &[Option<Row>],
|
||||
breaks: &[bool],
|
||||
specs: &[ColSpec],
|
||||
depth: usize,
|
||||
) -> Vec<Option<Align>> {
|
||||
// What is left of the line once the rows' own indentation is paid
|
||||
// for. `depth` comes from the AST's nesting, so it is the same on
|
||||
// every pass — which is what keeps the verdict stable.
|
||||
let budget = self.cfg.max_width.saturating_sub(depth * self.cfg.indent_width);
|
||||
let mut out = vec![None; rows.len()];
|
||||
let mut i = 0;
|
||||
while i < rows.len() {
|
||||
if rows[i].is_none() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while j < rows.len() && rows[j].is_some() && !breaks[j] {
|
||||
j += 1;
|
||||
}
|
||||
let run: Vec<&Row> = rows[i..j].iter().flatten().collect();
|
||||
if let Some(plan) = align::plan(self.src, &run, specs, budget) {
|
||||
for slot in &mut out[i..j] {
|
||||
*slot = Some(plan.clone());
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Measure one candidate row. `None` — meaning "cannot be aligned" — when
|
||||
/// the cells did not split at every column, or when one of them holds a
|
||||
/// comment and so has no flat width.
|
||||
pub(super) fn row_of(cells: &[Doc], anchors: Vec<u32>, tail: usize) -> Option<Row> {
|
||||
if cells.len() != anchors.len() + 1 {
|
||||
return None;
|
||||
}
|
||||
let widths: Option<Vec<usize>> = cells.iter().map(align::flat_width).collect();
|
||||
Some(Row { widths: widths?, anchors, tail })
|
||||
}
|
||||
|
||||
/// Which elements of a bracketed list start a new alignment group: those
|
||||
/// with a comment or an attribute of their own — both print on their own
|
||||
/// line — and those a compiler directive was written in front of.
|
||||
///
|
||||
/// A blank line is deliberately *not* a boundary here: `delimited` drops
|
||||
/// blank lines between list elements, so a boundary drawn at one would
|
||||
/// vanish from the output and the next pass would group differently.
|
||||
pub(super) fn list_breaks<'m>(
|
||||
metas: impl Iterator<Item = &'m Meta>,
|
||||
directives: &[ListDirective],
|
||||
) -> Vec<bool> {
|
||||
let mut breaks: Vec<bool> =
|
||||
metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect();
|
||||
for d in directives {
|
||||
if let Some(b) = breaks.get_mut(d.before) {
|
||||
*b = true;
|
||||
}
|
||||
}
|
||||
breaks
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! Formatting rules: AST → Doc.
|
||||
//!
|
||||
//! Style follows Verible's defaults: 2-space indent, 100-column lines,
|
||||
//! one-element-per-line port/connection lists when a construct does not fit
|
||||
//! on a single line, cuddled `begin`/`end`.
|
||||
//!
|
||||
//! The rules are one `Fmt` whose methods are spread over the sibling
|
||||
//! modules by grammar domain — `item`, `module`, `instance`, `decl`,
|
||||
//! `routine`, `class`, `cover`, `sva`, `stmt`, `expr` — on top of the
|
||||
//! shared machinery they all print through — `comment`, `verbatim`,
|
||||
//! `phrase`, `list`. This file holds what the crate exports (`Config`,
|
||||
//! `FormatError`, `format_source`, `format_range`), the `Fmt` state, and
|
||||
//! the name helpers every module writes an identifier through.
|
||||
|
||||
mod class;
|
||||
mod comment;
|
||||
mod cover;
|
||||
mod decl;
|
||||
mod expr;
|
||||
mod instance;
|
||||
mod item;
|
||||
mod list;
|
||||
mod module;
|
||||
mod phrase;
|
||||
mod routine;
|
||||
mod stmt;
|
||||
mod sva;
|
||||
mod verbatim;
|
||||
|
||||
use crate::doc::{text, Doc};
|
||||
use crate::fence::{self, Region};
|
||||
use crate::printer::Printer;
|
||||
use crate::range::{self, Split};
|
||||
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
use vlog_parser::ast::*;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub max_width: usize,
|
||||
pub indent_width: usize,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config { max_width: 100, indent_width: 2 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything that can stop the formatter from producing output.
|
||||
#[derive(Debug)]
|
||||
pub enum FormatError {
|
||||
/// The input could not be lexed or parsed.
|
||||
Source(vlog_parser::Error),
|
||||
/// A safety check failed; the formatted text was discarded.
|
||||
Verification(VerificationError),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FormatError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FormatError::Source(e) => write!(f, "{e}"),
|
||||
FormatError::Verification(e) => write!(f, "{e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for FormatError {}
|
||||
|
||||
impl From<vlog_parser::Error> for FormatError {
|
||||
fn from(e: vlog_parser::Error) -> Self {
|
||||
FormatError::Source(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<VerificationError> for FormatError {
|
||||
fn from(e: VerificationError) -> Self {
|
||||
FormatError::Verification(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Format `source`, verifying the result before handing it back.
|
||||
///
|
||||
/// The output is only returned if it re-lexes to the same token stream as the
|
||||
/// input (comments included) and formatting it again is a fixed point;
|
||||
/// otherwise the caller gets an error and must leave the original text alone.
|
||||
///
|
||||
/// Parses `source` (twice, for verification), so call this only on a thread
|
||||
/// with at least `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one
|
||||
/// lets sufficiently nested input abort the process instead of returning
|
||||
/// `Err` (see `docs/features/recursion-limit/README.md`).
|
||||
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||
let output = format_once(source, config).map_err(FormatError::Source)?;
|
||||
verify_equivalence(source, &output)?;
|
||||
let again = format_once(&output, config).map_err(VerificationError::Reparse)?;
|
||||
verify_convergence(&output, &again)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Format only the constructs intersecting `lines`, emitting every other byte
|
||||
/// exactly as it was written.
|
||||
///
|
||||
/// The safety net is the same one and it still runs over the *whole* output:
|
||||
/// the spliced bytes are source text, the laid-out islands are ordinary
|
||||
/// formatter output, and both checks are global. Convergence is checked by
|
||||
/// replaying the same per-item decisions against the output — see
|
||||
/// `docs/features/range-formatting/README.md`.
|
||||
///
|
||||
/// Same stack requirement as [`format_source`]: needs a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
|
||||
pub fn format_range(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
lines: &range::LineRanges,
|
||||
) -> Result<String, FormatError> {
|
||||
let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?;
|
||||
let selection = range::select(source, &file, lines);
|
||||
let output = format_selected(source, config, &selection).map_err(FormatError::Source)?;
|
||||
verify_equivalence(source, &output)?;
|
||||
let again = format_selected(&output, config, &selection).map_err(VerificationError::Reparse)?;
|
||||
verify_convergence(&output, &again)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// A single unverified formatting pass: parse, lay out, print.
|
||||
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
|
||||
let file = vlog_parser::parse_source(source)?;
|
||||
let regions = fence::collect(source, &file);
|
||||
Ok(render(&Fmt { cfg: config, src: source, regions, splits: Vec::new() }, &file, config))
|
||||
}
|
||||
|
||||
/// The same pass, restricted to the units `selection` picked out.
|
||||
fn format_selected(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
selection: &range::Selection,
|
||||
) -> Result<String, vlog_parser::Error> {
|
||||
let file = vlog_parser::parse_source(source)?;
|
||||
let plan = range::plan(source, &file, selection);
|
||||
let fmt = Fmt { cfg: config, src: source, regions: plan.regions, splits: plan.splits };
|
||||
Ok(render(&fmt, &file, config))
|
||||
}
|
||||
|
||||
/// Lay the file out and print it, ending in exactly one newline.
|
||||
fn render(fmt: &Fmt, file: &SourceFile, config: &Config) -> String {
|
||||
let doc = fmt.file(file);
|
||||
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
|
||||
let mut out = printer.print(&doc);
|
||||
// Normalize trailing whitespace: exactly one final newline.
|
||||
while out.ends_with('\n') || out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
struct Fmt<'a> {
|
||||
cfg: &'a Config,
|
||||
/// The text the AST was parsed from — what `// verilog_format: off`
|
||||
/// regions and `--lines` runs are spliced out of.
|
||||
src: &'a str,
|
||||
/// The byte ranges of `src` emitted exactly as written, sorted and
|
||||
/// non-overlapping: fenced regions, plus whatever a range run left alone.
|
||||
regions: Vec<Region>,
|
||||
/// Scope-bearing items a range run descends into. Empty for a whole-file
|
||||
/// run.
|
||||
splits: Vec<Split>,
|
||||
}
|
||||
|
||||
/// A name, plus the space that terminates it when it is an escaped identifier.
|
||||
///
|
||||
/// An escaped identifier runs from its `\` to the next **whitespace**
|
||||
/// character and to nothing else (IEEE 1800-2017 §5.6.1), so `\my-signal;`
|
||||
/// lexes as one identifier that swallows the `;`, and `.\my-port(x)` as one
|
||||
/// that swallows the rest of the line. Every name the formatter writes goes
|
||||
/// through here (or through [`name_doc`], its `Doc` twin): declarators,
|
||||
/// ANSI and non-ANSI ports, parameters and their aligned cells, type names,
|
||||
/// typedef/enum/genvar/`let` names, module, package, class, function, task,
|
||||
/// modport and clocking names, instance and module-instance names, port
|
||||
/// connections and named call arguments, `extends`, scopes, hierarchical
|
||||
/// members, tf arguments, block/fork/statement labels, every `end : label`,
|
||||
/// `disable`, and the `join_names`/`join_paths` lists. The audit that built
|
||||
/// that list is a grep of `text(` and `format!(` over `format/`; a site that
|
||||
/// grows a name later belongs on it.
|
||||
///
|
||||
/// The space is unconditional. Where the layout already writes a separator
|
||||
/// the output carries two (`logic \a = 1;`) — legal, a fixed point under
|
||||
/// re-formatting, and cheaper than a second rule about what comes next.
|
||||
fn named(s: &str) -> String {
|
||||
if ends_escaped(s) {
|
||||
format!("{s} ")
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`named`] as a `Doc`.
|
||||
fn name_doc(s: &str) -> Doc {
|
||||
text(named(s))
|
||||
}
|
||||
|
||||
/// Whether `s` ends *inside* an escaped identifier, and so cannot be followed
|
||||
/// directly by punctuation.
|
||||
///
|
||||
/// Whitespace is the only terminator, so the question is exactly whether a
|
||||
/// `\` survives in the run of characters after the last whitespace — which
|
||||
/// also answers it for the composites the AST hands over already joined
|
||||
/// (`a.\b`, `pkg::\x`). Conservative by construction: a false positive
|
||||
/// writes one harmless extra space. `vlog_refactor::instantiate` carries the
|
||||
/// same two-line rule for the skeletons it splices.
|
||||
fn ends_escaped(s: &str) -> bool {
|
||||
s.rsplit(char::is_whitespace).next().unwrap_or(s).contains('\\')
|
||||
}
|
||||
|
||||
/// A comma-separated list of names, as the source wrote them. The parser
|
||||
/// keeps each name's byte range alongside its text, so the joined spelling is
|
||||
/// rebuilt here rather than stored.
|
||||
fn join_names(names: &[Name]) -> String {
|
||||
names.iter().map(|n| named(&n.text)).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// The same for a list of `pkg::item` import paths.
|
||||
fn join_paths(paths: &[ImportPath]) -> String {
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| format!("{}::{}", named(&p.pkg.text), named(&p.item.text)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// Offset of the first byte at or after `from` that is neither whitespace nor
|
||||
/// part of a comment, or `None` if the text ends first.
|
||||
///
|
||||
/// Used to ask what a node is followed by in the source — a `)` that closes
|
||||
/// the header it sits in, the optional `:` of a `default` case label — when
|
||||
/// the AST does not record it.
|
||||
fn skip_trivia(src: &str, from: usize) -> Option<usize> {
|
||||
let bytes = src.as_bytes();
|
||||
let mut i = from;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'/' if bytes.get(i + 1) == Some(&b'/') => {
|
||||
i += 2;
|
||||
while i < bytes.len() && bytes[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
b'/' if bytes.get(i + 1) == Some(&b'*') => {
|
||||
i += 2;
|
||||
while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
|
||||
i += 1;
|
||||
}
|
||||
i = (i + 2).min(bytes.len());
|
||||
}
|
||||
c if c.is_ascii_whitespace() => i += 1,
|
||||
_ => return Some(i),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
//! What a module or interface declares at its boundary: the header
|
||||
//! through its `;` (name, imports, parameter ports, ANSI or non-ANSI
|
||||
//! ports), the alignment of an ANSI port list, `modport`s and clocking
|
||||
//! blocks.
|
||||
//!
|
||||
//! The header is split from the body (`module_head` vs `module`) so a
|
||||
//! range run can keep one verbatim and lay out the other.
|
||||
|
||||
use crate::align::{self, Align, ColSpec, Row};
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
|
||||
use super::list::ListItem;
|
||||
use super::routine::TfHeader;
|
||||
use super::{join_names, join_paths, name_doc, named, Fmt};
|
||||
|
||||
/// An ANSI port's one alignment column: the name, one space off the type.
|
||||
const ANSI_PORT_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }];
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
pub(super) fn module(&self, m: &Module, depth: usize) -> Doc {
|
||||
let mut docs = vec![self.module_head(m, depth)];
|
||||
let mut body = Vec::new();
|
||||
if !m.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&m.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&m.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled(m.end_kw(), &m.end_label, &m.end_label_comments));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A module header: everything through the `;` that closes it.
|
||||
///
|
||||
/// Split out from the body so a range run can keep one and lay out the
|
||||
/// other (`range.rs`); a whole-file run always emits both.
|
||||
pub(super) fn module_head(&self, m: &Module, depth: usize) -> Doc {
|
||||
let mut docs = vec![text(m.kw.clone())];
|
||||
if m.before_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&m.before_name, &mut docs);
|
||||
}
|
||||
docs.push(text(named(&m.name)));
|
||||
let has_imports = !m.imports.is_empty();
|
||||
if has_imports {
|
||||
// One line per `import` statement the header wrote: folding two of
|
||||
// them into one comma-separated statement would rewrite a `;`.
|
||||
let mut lines = Vec::new();
|
||||
for imp in &m.imports {
|
||||
lines.push(Doc::HardLine);
|
||||
lines.extend(self.leading(&imp.meta));
|
||||
lines.push(text(format!("import {};", join_paths(&imp.paths))));
|
||||
lines.extend(self.trailing(&imp.meta));
|
||||
}
|
||||
docs.push(indent(lines));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
// After an import block the header continues at column 0, so the
|
||||
// usual single space before `#(`/`(` is dropped.
|
||||
let mut on_fresh_line = has_imports;
|
||||
on_fresh_line = self.bracket_comments(&m.param_comments, &mut docs, on_fresh_line);
|
||||
// A written-but-empty `#()` is printed back; a missing one stays
|
||||
// missing.
|
||||
if let Some(params) = &m.param_ports {
|
||||
let items: Vec<ListItem> = params
|
||||
.iter()
|
||||
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
|
||||
.collect();
|
||||
let items = self.list_entries(items, &m.param_directives);
|
||||
let broken = !m.param_directives.is_empty();
|
||||
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
||||
self.slot_comments(&m.param_after_hash, &mut docs);
|
||||
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", broken));
|
||||
on_fresh_line = false;
|
||||
}
|
||||
let on_fresh_line = self.bracket_comments(&m.port_comments, &mut docs, on_fresh_line);
|
||||
// A port list whose every element sits in an `ifdef arm still holds
|
||||
// directives while being `PortList::Empty`, so the two are laid out by
|
||||
// the same code.
|
||||
let mut broken = !m.port_directives.is_empty();
|
||||
match &m.ports {
|
||||
PortList::None => docs.push(self.semi(&m.before_semi)),
|
||||
PortList::Empty | PortList::Ansi(_) | PortList::NonAnsi(_) => {
|
||||
let items: Vec<ListItem> = match &m.ports {
|
||||
PortList::Ansi(ports) => {
|
||||
// An aligned list is a broken list: alignment only
|
||||
// means anything one element per line.
|
||||
let aligns = self.ansi_port_aligns(ports, &m.port_directives, depth + 1);
|
||||
broken |= aligns.iter().any(Option::is_some);
|
||||
ports
|
||||
.iter()
|
||||
.zip(&aligns)
|
||||
.map(|(p, a)| {
|
||||
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
|
||||
.with_comma(p.comma)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
PortList::NonAnsi(ports) => ports
|
||||
.iter()
|
||||
.map(|p| {
|
||||
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let items = self.list_entries(items, &m.port_directives);
|
||||
if !on_fresh_line {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", broken));
|
||||
docs.push(self.semi(&m.before_semi));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
pub(super) fn param_port(&self, p: &ParamPort) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
if let Some(kw) = &p.kw {
|
||||
self.word_then(kw, &p.after_kw, &mut docs);
|
||||
} else {
|
||||
self.slot_comments(&p.after_kw, &mut docs);
|
||||
}
|
||||
if p.is_type {
|
||||
docs.push(text("type "));
|
||||
}
|
||||
match self.data_type(&p.ty) {
|
||||
Some(t) => {
|
||||
docs.push(t);
|
||||
if p.before_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&p.before_name, &mut docs);
|
||||
}
|
||||
}
|
||||
None => self.slot_comments(&p.before_name, &mut docs),
|
||||
}
|
||||
docs.push(name_doc(&p.name));
|
||||
docs.extend(self.unpacked_dims(&p.unpacked));
|
||||
if let Some(d) = &p.default {
|
||||
self.eq_default(&p.eq_comments, group(vec![self.expr(d)]), &mut docs);
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn ansi_port(&self, p: &AnsiPort, align: Option<&Align>) -> Doc {
|
||||
align::render(&self.ansi_port_cells(p), ANSI_PORT_COLS, align)
|
||||
}
|
||||
|
||||
/// An ANSI port split at its one alignment column, the name: the
|
||||
/// direction/net/type prefix, then the name and everything after it. A
|
||||
/// port with no prefix at all (a continuation port, `output a, b`) is one
|
||||
/// cell, which is what takes it out of every alignment group.
|
||||
fn ansi_port_cells(&self, p: &AnsiPort) -> Vec<Doc> {
|
||||
// A comment in one of the port's own gaps makes the row a width no
|
||||
// other row shares, so it is one cell and joins no alignment group —
|
||||
// the rule an attributed connection already follows.
|
||||
if !p.after_dir.is_empty() || !p.before_name.is_empty() {
|
||||
return vec![self.ansi_port_plain(p)];
|
||||
}
|
||||
let mut prefix = Vec::new();
|
||||
if let Some(dir) = &p.dir {
|
||||
prefix.push(text(format!("{dir} ")));
|
||||
}
|
||||
if let Some(net) = &p.net {
|
||||
prefix.push(text(format!("{net} ")));
|
||||
}
|
||||
if let Some(t) = self.data_type(&p.ty) {
|
||||
prefix.push(t);
|
||||
prefix.push(text(" "));
|
||||
}
|
||||
// The trailing space of the last prefix part is the column separator,
|
||||
// which `align::render` writes instead.
|
||||
if let Some(Doc::Text(last)) = prefix.last_mut() {
|
||||
if last.ends_with(' ') {
|
||||
last.pop();
|
||||
}
|
||||
}
|
||||
let mut docs = vec![name_doc(&p.name)];
|
||||
docs.extend(self.unpacked_dims(&p.unpacked));
|
||||
if let Some(d) = &p.default {
|
||||
self.eq_default(&p.eq_comments, self.expr(d), &mut docs);
|
||||
}
|
||||
if prefix.is_empty() {
|
||||
return vec![concat(docs)];
|
||||
}
|
||||
vec![concat(prefix), concat(docs)]
|
||||
}
|
||||
|
||||
/// An ANSI port written out in one piece, for the rows that carry a
|
||||
/// comment in one of their own gaps and so cannot be aligned.
|
||||
fn ansi_port_plain(&self, p: &AnsiPort) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
if let Some(dir) = &p.dir {
|
||||
self.word_then(dir, &p.after_dir, &mut docs);
|
||||
}
|
||||
if let Some(net) = &p.net {
|
||||
docs.push(text(format!("{net} ")));
|
||||
}
|
||||
match self.data_type(&p.ty) {
|
||||
Some(t) => {
|
||||
docs.push(t);
|
||||
if p.before_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&p.before_name, &mut docs);
|
||||
}
|
||||
}
|
||||
None => self.slot_comments(&p.before_name, &mut docs),
|
||||
}
|
||||
docs.push(name_doc(&p.name));
|
||||
docs.extend(self.unpacked_dims(&p.unpacked));
|
||||
if let Some(d) = &p.default {
|
||||
self.eq_default(&p.eq_comments, self.expr(d), &mut docs);
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// The alignment plan for a module header's ANSI port list.
|
||||
fn ansi_port_aligns(
|
||||
&self,
|
||||
ports: &[AnsiPort],
|
||||
directives: &[ListDirective],
|
||||
depth: usize,
|
||||
) -> Vec<Option<Align>> {
|
||||
let rows: Vec<Option<Row>> = ports
|
||||
.iter()
|
||||
.map(|p| {
|
||||
Self::row_of(
|
||||
&self.ansi_port_cells(p),
|
||||
vec![p.name_span.start],
|
||||
usize::from(p.comma),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let breaks = Self::list_breaks(ports.iter().map(|p| &p.meta), directives);
|
||||
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
|
||||
}
|
||||
|
||||
/// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5).
|
||||
///
|
||||
/// Each modport's port list is a breakable group of its own, laid out
|
||||
/// exactly like a header port list: one line when it fits, one entry per
|
||||
/// line when it does not. A direction keyword and the names it governs are
|
||||
/// one entry, so the source's grouping (`input valid, data`) survives.
|
||||
pub(super) fn modport(&self, decls: &[ModportDecl]) -> Doc {
|
||||
let mut docs = vec![text("modport")];
|
||||
let last = decls.len().saturating_sub(1);
|
||||
let mut on_fresh_line = false;
|
||||
for (i, d) in decls.iter().enumerate() {
|
||||
if !on_fresh_line {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.extend(self.leading(&d.meta));
|
||||
docs.push(text(format!("{} ", named(&d.name))));
|
||||
let items: Vec<ListItem> = d
|
||||
.ports
|
||||
.iter()
|
||||
.map(|p| ListItem::from_meta(&p.meta, self.modport_port(p)).with_comma(p.comma))
|
||||
.collect();
|
||||
docs.push(self.delimited_dangling("(", items, &d.dangling, ")", false));
|
||||
let ends_line = self.inline_comments(&d.meta.before_sep, &mut docs);
|
||||
if i < last {
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(","));
|
||||
}
|
||||
on_fresh_line = false;
|
||||
if let Some(tr) = &d.meta.trailing {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.comment(tr));
|
||||
if i < last {
|
||||
docs.push(Doc::HardLine);
|
||||
on_fresh_line = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One direction group of a modport port list: `input valid, data`, or an
|
||||
/// `import`/`export` method prototype (`import task drive(int x)`, IEEE
|
||||
/// 1800 §25.5.4) — printed through the very header printer a real `task`
|
||||
/// or `function` declaration uses, so the two cannot drift apart.
|
||||
fn modport_port(&self, p: &ModportPort) -> Doc {
|
||||
let mut docs = vec![text(p.kw.clone())];
|
||||
if p.after_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&p.after_kw, &mut docs);
|
||||
}
|
||||
match &p.prototype {
|
||||
Some(proto) => self.tf_header(&TfHeader::of_prototype(proto), &mut docs),
|
||||
None => docs.push(text(join_names(&p.names))),
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3), one
|
||||
/// item per line — the body is a declaration list, not an expression, so
|
||||
/// there is nothing here worth collapsing onto the header's line.
|
||||
pub(super) fn clocking(&self, c: &ClockingDecl) -> Doc {
|
||||
let mut head = String::from(if c.is_default { "default clocking" } else { "clocking" });
|
||||
if let Some(n) = &c.name {
|
||||
head.push(' ');
|
||||
head.push_str(&named(&n.text));
|
||||
}
|
||||
let mut docs = vec![text(head)];
|
||||
// `default clocking cb;` selects an existing block: no event, no body.
|
||||
let Some(event) = &c.event else {
|
||||
docs.push(text(";"));
|
||||
return concat(docs);
|
||||
};
|
||||
docs.push(text(" "));
|
||||
docs.push(self.sens_list(event));
|
||||
docs.push(text(";"));
|
||||
let mut body = Vec::new();
|
||||
for item in &c.items {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading_comments(&item.meta));
|
||||
body.push(concat(vec![self.clocking_item(&item.kind), text(";")]));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
}
|
||||
body.extend(self.dangling(&c.dangling));
|
||||
docs.push(indent(body));
|
||||
if c.has_end {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("endclocking", &c.end_label, &c.end_label_comments));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One clocking-block item. A `= expression` binding
|
||||
/// (`output tms = _tms_internal;`) prints on the item's own line: the
|
||||
/// bound expression is a signal name, never long enough to be worth a
|
||||
/// breakable group.
|
||||
fn clocking_item(&self, kind: &ClockingItemKind) -> Doc {
|
||||
match kind {
|
||||
ClockingItemKind::Default { input, output } => {
|
||||
let mut s = String::from("default");
|
||||
if let Some(skew) = input {
|
||||
s.push_str(" input ");
|
||||
s.push_str(skew);
|
||||
}
|
||||
if let Some(skew) = output {
|
||||
s.push_str(" output ");
|
||||
s.push_str(skew);
|
||||
}
|
||||
text(s)
|
||||
}
|
||||
ClockingItemKind::Signals { dir, skew, signals } => {
|
||||
let mut head = dir.clone();
|
||||
if let Some(skew) = skew {
|
||||
head.push(' ');
|
||||
head.push_str(skew);
|
||||
}
|
||||
head.push(' ');
|
||||
let mut docs = vec![text(head)];
|
||||
for (i, sig) in signals.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
}
|
||||
docs.push(name_doc(&sig.name.text));
|
||||
if let Some(value) = &sig.value {
|
||||
docs.push(text(" = "));
|
||||
docs.push(self.expr(value));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! Recurring two- and three-token phrases, each printed with the
|
||||
//! comments written in its gaps: a keyword and what follows it, `= value`,
|
||||
//! the `;` that ends a statement, `end : label`, `[msb:lsb]`, the
|
||||
//! punctuation of a `for` header, the `[i, j]` of a `foreach`.
|
||||
//!
|
||||
//! They are here rather than beside one user because each has at least
|
||||
//! two — a statement `for` and a generate `for`, a declarator and a port
|
||||
//! default — and the two must agree byte for byte, since the safety net
|
||||
//! compares token streams, not intentions.
|
||||
|
||||
use crate::doc::*;
|
||||
use crate::printer::contains_hard_line;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::{join_names, named, Fmt};
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// A keyword and whatever the source wrote between it and what follows —
|
||||
/// a space when that is nothing.
|
||||
pub(super) fn word_then(&self, word: &str, comments: &[Comment], docs: &mut Vec<Doc>) {
|
||||
docs.push(text(word.to_string()));
|
||||
if comments.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(comments, docs);
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of qualifier keywords, each followed by the space or the comment
|
||||
/// the source wrote after it (`local /*c*/ static `). Always ends in a
|
||||
/// separator, so the caller writes what follows without one of its own.
|
||||
pub(super) fn qualifier_run(&self, run: &[Qualifier], docs: &mut Vec<Doc>) {
|
||||
for q in run {
|
||||
docs.push(text(q.text.clone()));
|
||||
if q.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&q.after, docs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `pkg::cls::` written in front of an out-of-body definition's name,
|
||||
/// one segment at a time so a comment beside a `::` prints where it was
|
||||
/// written — and so an escaped segment keeps the space that terminates
|
||||
/// it, which `named` supplies.
|
||||
pub(super) fn scope_prefix(&self, scope: &[ScopeSeg], docs: &mut Vec<Doc>) {
|
||||
for seg in scope {
|
||||
docs.push(text(named(&seg.name.text)));
|
||||
self.slot_comments(&seg.before_sep, docs);
|
||||
docs.push(text("::"));
|
||||
self.slot_comments(&seg.after_sep, docs);
|
||||
}
|
||||
}
|
||||
|
||||
/// `= value`, with the comments written on either side of the `=`.
|
||||
pub(super) fn eq_default(&self, comments: &BinaryComments, value: Doc, docs: &mut Vec<Doc>) {
|
||||
self.slot_comments(&comments.before, docs);
|
||||
docs.push(text(if comments.before.is_empty() { " =" } else { "=" }));
|
||||
if comments.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&comments.after, docs);
|
||||
}
|
||||
docs.push(value);
|
||||
}
|
||||
|
||||
/// The right-hand side of an `=`: normally a break opportunity that moves
|
||||
/// the value to an indented next line, but a value that already contains a
|
||||
/// forced break (a comment inside it) keeps `= {` on the head line, the
|
||||
/// way a broken port list keeps `module m (` on its own.
|
||||
pub(super) fn assign_rhs(&self, doc: Doc) -> Doc {
|
||||
if contains_hard_line(std::slice::from_ref(&doc)) {
|
||||
concat(vec![text(" "), doc])
|
||||
} else {
|
||||
indent(vec![Doc::Line, doc])
|
||||
}
|
||||
}
|
||||
|
||||
/// The `;` that ends a statement, with whatever the source wrote in front
|
||||
/// of it (`x = 1 /* inclusive */ ;`). [`StmtKind::takes_semi`] is what
|
||||
/// says which kinds reach this; every other one prints its own `;` as
|
||||
/// part of a body it does not own the end of.
|
||||
pub(super) fn semi(&self, before_semi: &[Comment]) -> Doc {
|
||||
if before_semi.is_empty() {
|
||||
return text(";");
|
||||
}
|
||||
let mut docs = Vec::new();
|
||||
if self.inline_comments(before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A closing keyword with its optional block label: `end`, `end : main`.
|
||||
/// Matches the `endmodule : m` spelling used for module footers.
|
||||
fn closing(kw: &str, label: &Option<String>) -> Doc {
|
||||
match label {
|
||||
Some(l) => text(format!("{kw} : {}", named(l))),
|
||||
None => text(kw),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same, with the comments the source wrote in the label's two gaps
|
||||
/// (`endgroup /*a*/ : /*b*/ cg`). The common case — no comment — is
|
||||
/// [`Fmt::closing`] verbatim.
|
||||
pub(super) fn closing_labeled(
|
||||
&self,
|
||||
kw: &str,
|
||||
label: &Option<String>,
|
||||
c: &LabelComments,
|
||||
) -> Doc {
|
||||
if c.is_empty() {
|
||||
return Self::closing(kw, label);
|
||||
}
|
||||
let mut docs = vec![text(kw.to_string())];
|
||||
self.label_tail(label, c, &mut docs);
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// ` : name`, with the comments written in its two gaps. A no-op when no
|
||||
/// label was written.
|
||||
pub(super) fn label_tail(
|
||||
&self,
|
||||
label: &Option<String>,
|
||||
c: &LabelComments,
|
||||
docs: &mut Vec<Doc>,
|
||||
) {
|
||||
let Some(l) = label else {
|
||||
// A comment before a `:` that was never written belongs to
|
||||
// whatever follows, and `gap_before` never took it.
|
||||
debug_assert!(c.is_empty());
|
||||
return;
|
||||
};
|
||||
self.slot_comments(&c.before_colon, docs);
|
||||
docs.push(text(if c.before_colon.is_empty() { " :" } else { ":" }));
|
||||
if c.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&c.after_colon, docs);
|
||||
}
|
||||
docs.push(text(named(l)));
|
||||
}
|
||||
|
||||
/// `[ … ]` with the comments written in a segment's or a dimension's own
|
||||
/// slots printed back between the same two tokens the source wrote them
|
||||
/// between. `rest` is the `: lsb` half of a range, absent for an index.
|
||||
///
|
||||
/// The opener's own slot (`base /*c*/ [`) belongs to whoever emitted the
|
||||
/// base, so it is not printed here.
|
||||
pub(super) fn bracket_slots(
|
||||
&self,
|
||||
comments: &SegmentComments,
|
||||
first: Doc,
|
||||
rest: Option<(&str, Doc)>,
|
||||
) -> Doc {
|
||||
let mut docs = vec![text("[")];
|
||||
self.slot_comments(&comments.after_open, &mut docs);
|
||||
docs.push(first);
|
||||
if let Some((op, second)) = rest {
|
||||
self.slot_comments(&comments.before_op, &mut docs);
|
||||
docs.push(text(op.to_string()));
|
||||
self.slot_comments(&comments.after_op, &mut docs);
|
||||
docs.push(second);
|
||||
}
|
||||
self.slot_comments(&comments.before_close, &mut docs);
|
||||
docs.push(text("]"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `for` plus its `(`, with the gap between them.
|
||||
pub(super) fn for_open(&self, comments: &ForComments, docs: &mut Vec<Doc>) {
|
||||
docs.push(text("for"));
|
||||
if comments.after_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&comments.after_kw, docs);
|
||||
}
|
||||
docs.push(text("("));
|
||||
self.slot_comments(&comments.after_open, docs);
|
||||
}
|
||||
|
||||
/// The `; ` between two sections of a `for` header, carrying whatever the
|
||||
/// source wrote in the two gaps around it.
|
||||
pub(super) fn for_semi(&self, before: &[Comment], after: &[Comment], docs: &mut Vec<Doc>) {
|
||||
self.slot_comments(before, docs);
|
||||
docs.push(text(";"));
|
||||
if after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(after, docs);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `lhs op rhs` of a `for` header's initialiser or step.
|
||||
pub(super) fn simple_assign(&self, a: &SimpleAssign, docs: &mut Vec<Doc>) {
|
||||
docs.push(self.expr(&a.lhs));
|
||||
self.slot_comments(&a.op_comments.before, docs);
|
||||
docs.push(text(if a.op_comments.before.is_empty() {
|
||||
format!(" {}", a.op)
|
||||
} else {
|
||||
a.op.clone()
|
||||
}));
|
||||
if a.op_comments.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&a.op_comments.after, docs);
|
||||
}
|
||||
docs.push(self.expr(&a.rhs));
|
||||
}
|
||||
|
||||
pub(super) fn for_step(&self, step: &ForStep) -> Doc {
|
||||
match step {
|
||||
ForStep::Assign(a) => {
|
||||
let mut docs = Vec::new();
|
||||
self.simple_assign(a, &mut docs);
|
||||
concat(docs)
|
||||
}
|
||||
ForStep::Expr(e) => self.expr(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `[i, j]` of a `foreach` header — the one bracket group that
|
||||
/// declares loop variables — with every comment written in it printed
|
||||
/// back between the two tokens it was written between.
|
||||
///
|
||||
/// Shared by the statement `foreach` and the constraint one, which write
|
||||
/// the same grammar.
|
||||
pub(super) fn foreach_vars(&self, vars: &[ForeachVar], comments: &SegmentComments) -> Doc {
|
||||
if comments.is_empty() && vars.iter().all(|v| v.before.is_empty() && v.after.is_empty()) {
|
||||
let names: Vec<Name> = vars.iter().map(|v| v.name.clone()).collect();
|
||||
return text(format!("[{}]", join_names(&names)));
|
||||
}
|
||||
let mut docs = Vec::new();
|
||||
self.slot_comments(&comments.before_open, &mut docs);
|
||||
docs.push(text("["));
|
||||
self.slot_comments(&comments.after_open, &mut docs);
|
||||
for (i, v) in vars.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(","));
|
||||
}
|
||||
self.slot_comments(&v.before, &mut docs);
|
||||
if i > 0 && v.before.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(named(&v.name.text)));
|
||||
self.slot_comments(&v.after, &mut docs);
|
||||
}
|
||||
self.slot_comments(&comments.before_close, &mut docs);
|
||||
docs.push(text("]"));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
//! Functions and tasks: the argument list a `function`, `task`,
|
||||
//! `covergroup` and `property` share (`tf_args`), the two declarations
|
||||
//! with their prototype forms, `let`, and the DPI `import`/`export`
|
||||
//! linkage.
|
||||
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::list::ListItem;
|
||||
use super::{join_paths, name_doc, named, Fmt};
|
||||
|
||||
/// The pieces of a subroutine header that a real declaration and a `modport`
|
||||
/// method prototype (IEEE 1800 §25.5.4) print identically: the keyword through
|
||||
/// the `)` of the port list.
|
||||
///
|
||||
/// Borrowed rather than owned, so [`FunctionDecl`], [`TaskDecl`] and
|
||||
/// [`TfPrototype`] — which keep the same pieces in three different shapes —
|
||||
/// all reach one printer without a clone.
|
||||
pub(super) struct TfHeader<'h> {
|
||||
kw: &'h str,
|
||||
after_kw: &'h [Comment],
|
||||
qualifiers: &'h [Qualifier],
|
||||
ret: Option<&'h DataType>,
|
||||
before_name: &'h [Comment],
|
||||
scope: &'h [ScopeSeg],
|
||||
name: &'h str,
|
||||
has_parens: bool,
|
||||
before_args: &'h [Comment],
|
||||
args: &'h [TfArg],
|
||||
args_dangling: &'h [Comment],
|
||||
}
|
||||
|
||||
impl<'h> TfHeader<'h> {
|
||||
/// The header of a `function` declaration; its `dpi` and `prefix` are the
|
||||
/// caller's, since they stand in front of the keyword.
|
||||
fn of_function(f: &'h FunctionDecl) -> Self {
|
||||
TfHeader {
|
||||
kw: "function",
|
||||
after_kw: &f.after_kw,
|
||||
qualifiers: &f.qualifiers,
|
||||
ret: f.ret.as_ref(),
|
||||
before_name: &f.before_name,
|
||||
scope: &f.scope,
|
||||
name: &f.name,
|
||||
has_parens: f.has_parens,
|
||||
before_args: &f.before_args,
|
||||
args: &f.args,
|
||||
args_dangling: &f.args_dangling,
|
||||
}
|
||||
}
|
||||
|
||||
/// The header of a `task` declaration, which has no return type.
|
||||
fn of_task(t: &'h TaskDecl) -> Self {
|
||||
TfHeader {
|
||||
kw: "task",
|
||||
after_kw: &t.after_kw,
|
||||
qualifiers: &t.qualifiers,
|
||||
ret: None,
|
||||
before_name: &t.before_name,
|
||||
scope: &t.scope,
|
||||
name: &t.name,
|
||||
has_parens: t.has_parens,
|
||||
before_args: &t.before_args,
|
||||
args: &t.args,
|
||||
args_dangling: &t.args_dangling,
|
||||
}
|
||||
}
|
||||
|
||||
/// The header a modport method prototype is written as.
|
||||
pub(super) fn of_prototype(p: &'h TfPrototype) -> Self {
|
||||
TfHeader {
|
||||
kw: p.kind.keyword(),
|
||||
after_kw: &p.after_kw,
|
||||
qualifiers: &p.qualifiers,
|
||||
ret: p.ret.as_ref(),
|
||||
before_name: &p.before_name,
|
||||
scope: &p.scope,
|
||||
name: &p.name,
|
||||
has_parens: p.has_parens,
|
||||
before_args: &p.before_args,
|
||||
args: &p.args,
|
||||
args_dangling: &p.args_dangling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// The keyword through the `)` of the port list, appended to `docs`.
|
||||
pub(super) fn tf_header(&self, h: &TfHeader, docs: &mut Vec<Doc>) {
|
||||
docs.push(text(h.kw.to_string()));
|
||||
if h.after_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(h.after_kw, docs);
|
||||
}
|
||||
self.qualifier_run(h.qualifiers, docs);
|
||||
let named_ret = match h.ret.and_then(|r| self.data_type(r)) {
|
||||
Some(t) => {
|
||||
docs.push(t);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if named_ret {
|
||||
if h.before_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(h.before_name, docs);
|
||||
}
|
||||
} else {
|
||||
self.slot_comments(h.before_name, docs);
|
||||
}
|
||||
self.scope_prefix(h.scope, docs);
|
||||
docs.push(name_doc(h.name));
|
||||
if h.has_parens {
|
||||
self.slot_comments(h.before_args, docs);
|
||||
docs.push(self.tf_args(h.args, h.args_dangling));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc {
|
||||
let items: Vec<ListItem> =
|
||||
args.iter().map(|a| ListItem::from_meta(&a.meta, self.tf_arg(a))).collect();
|
||||
self.delimited_dangling("(", items, dangling, ")", false)
|
||||
}
|
||||
|
||||
/// One formal: `input logic [7:0] a = 0`.
|
||||
///
|
||||
/// An **unnamed** formal — a DPI import's, the only one the LRM allows
|
||||
/// (§35.5.5) — is its direction and type and nothing more, so every
|
||||
/// separator that would have stood in front of the name is left out and
|
||||
/// the missing name takes no width.
|
||||
fn tf_arg(&self, a: &TfArg) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
let ty = self.data_type(&a.ty);
|
||||
if let Some(dir) = &a.dir {
|
||||
self.tf_arg_dir(dir, &a.after_const, &mut docs);
|
||||
if !a.after_dir.is_empty() {
|
||||
self.inline_comments_spaced(&a.after_dir, &mut docs);
|
||||
} else if ty.is_some() || !a.name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
}
|
||||
let typed = ty.is_some();
|
||||
docs.extend(ty);
|
||||
if a.name.is_empty() {
|
||||
if self.inline_comments(&a.before_name, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
return concat(docs);
|
||||
}
|
||||
if typed {
|
||||
if a.before_name.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&a.before_name, &mut docs);
|
||||
}
|
||||
} else {
|
||||
self.slot_comments(&a.before_name, &mut docs);
|
||||
}
|
||||
docs.push(name_doc(&a.name));
|
||||
docs.extend(self.unpacked_dims(&a.unpacked));
|
||||
if let Some(d) = &a.default {
|
||||
self.slot_comments(&a.eq_comments.before, &mut docs);
|
||||
docs.push(text(if a.eq_comments.before.is_empty() { " =" } else { "=" }));
|
||||
if a.eq_comments.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&a.eq_comments.after, &mut docs);
|
||||
}
|
||||
docs.push(self.expr(d));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A formal's direction. `const ref` is the one written as two keywords,
|
||||
/// so it is the one with a comment slot inside it (IEEE 1800 §13.5.2).
|
||||
fn tf_arg_dir(&self, dir: &str, after_const: &[Comment], docs: &mut Vec<Doc>) {
|
||||
if after_const.is_empty() {
|
||||
docs.push(text(dir.to_string()));
|
||||
return;
|
||||
}
|
||||
docs.push(text("const"));
|
||||
self.inline_comments_spaced(after_const, docs);
|
||||
docs.push(text("ref"));
|
||||
}
|
||||
|
||||
pub(super) fn function(&self, f: &FunctionDecl) -> Doc {
|
||||
let mut header = Vec::new();
|
||||
if let Some(d) = &f.dpi {
|
||||
header.push(text(dpi_import_prefix(d)));
|
||||
}
|
||||
self.qualifier_run(&f.prefix, &mut header);
|
||||
self.tf_header(&TfHeader::of_function(f), &mut header);
|
||||
header.push(self.semi(&f.before_semi));
|
||||
// A prototype (`extern`/`pure virtual`) is the header and nothing
|
||||
// else: no body, no `endfunction`.
|
||||
if f.is_prototype {
|
||||
return concat(header);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !f.stmts.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.stmt_seq(&f.stmts));
|
||||
}
|
||||
body.extend(self.dangling(&f.dangling));
|
||||
concat(vec![
|
||||
concat(header),
|
||||
indent(body),
|
||||
Doc::HardLine,
|
||||
self.closing_labeled("endfunction", &f.end_label, &f.end_label_comments),
|
||||
text(if f.end_semi { ";" } else { "" }),
|
||||
])
|
||||
}
|
||||
|
||||
pub(super) fn task(&self, t: &TaskDecl) -> Doc {
|
||||
let mut header = Vec::new();
|
||||
if let Some(d) = &t.dpi {
|
||||
header.push(text(dpi_import_prefix(d)));
|
||||
}
|
||||
self.qualifier_run(&t.prefix, &mut header);
|
||||
self.tf_header(&TfHeader::of_task(t), &mut header);
|
||||
header.push(self.semi(&t.before_semi));
|
||||
if t.is_prototype {
|
||||
return concat(header);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !t.stmts.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.stmt_seq(&t.stmts));
|
||||
}
|
||||
body.extend(self.dangling(&t.dangling));
|
||||
concat(vec![
|
||||
concat(header),
|
||||
indent(body),
|
||||
Doc::HardLine,
|
||||
self.closing_labeled("endtask", &t.end_label, &t.end_label_comments),
|
||||
text(if t.end_semi { ";" } else { "" }),
|
||||
])
|
||||
}
|
||||
|
||||
/// `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12) — a name, an
|
||||
/// optional port list laid out like a function's, and one expression.
|
||||
pub(super) fn let_decl(&self, l: &LetDecl) -> Doc {
|
||||
let mut docs = vec![text(format!("let {}", named(&l.name)))];
|
||||
if l.has_parens {
|
||||
docs.push(self.tf_args(&l.ports, &[]));
|
||||
}
|
||||
docs.push(text(" ="));
|
||||
docs.push(self.assign_rhs(self.expr(&l.value)));
|
||||
concat(vec![group(docs), text(";")])
|
||||
}
|
||||
|
||||
/// `export "DPI-C" function f;` / `export pkg::*;` — one line either way;
|
||||
/// no list here is long enough to be worth a breakable group.
|
||||
pub(super) fn export(e: &ExportDecl) -> Doc {
|
||||
match e {
|
||||
ExportDecl::Dpi(d) => {
|
||||
let mut head = format!("export {} ", d.spec);
|
||||
if let Some(c) = &d.c_identifier {
|
||||
head.push_str(&named(&c.text));
|
||||
head.push_str(" = ");
|
||||
}
|
||||
text(format!("{head}{} {};", d.kw, named(&d.name.text)))
|
||||
}
|
||||
ExportDecl::Package(paths) => text(format!("export {};", join_paths(paths))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `import "DPI-C" [context|pure ][c_name = ]` — the linkage prefix a DPI
|
||||
/// import writes in front of the function or task prototype it declares.
|
||||
fn dpi_import_prefix(d: &DpiImport) -> String {
|
||||
let mut s = format!("import {} ", d.spec);
|
||||
if let Some(p) = &d.property {
|
||||
s.push_str(p);
|
||||
s.push(' ');
|
||||
}
|
||||
if let Some(c) = &d.c_identifier {
|
||||
s.push_str(&named(&c.text));
|
||||
s.push_str(" = ");
|
||||
}
|
||||
s
|
||||
}
|
||||
@@ -0,0 +1,691 @@
|
||||
//! Statements: the `begin … end` block, a statement as the body of a
|
||||
//! header (a cuddled block or an indented line), the dispatch from
|
||||
//! `StmtKind` to its layout, `if`/`else` chains, `case` items, and the
|
||||
//! timing controls and sensitivity lists that head an `always` block or
|
||||
//! a clocking event.
|
||||
//!
|
||||
//! `stmt_kind` is a dispatch table over `StmtKind` — one arm per
|
||||
//! statement form — and stays whole; the forms with a layout of their own
|
||||
//! (`if`, `case`) are the functions after it.
|
||||
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::comment::{is_line_comment, trailing_ends_line};
|
||||
use super::{join_paths, named, skip_trivia, Fmt};
|
||||
|
||||
/// The pieces of a `begin … end` block a printer needs, gathered so the
|
||||
/// two spellings (a statement, and a body cuddled onto a header) pass one
|
||||
/// argument instead of six.
|
||||
struct BlockDoc<'a> {
|
||||
label_comments: &'a LabelComments,
|
||||
label: &'a Option<String>,
|
||||
stmts: &'a [Stmt],
|
||||
dangling: &'a [Comment],
|
||||
end_label_comments: &'a LabelComments,
|
||||
end_label: &'a Option<String>,
|
||||
}
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
fn stmt(&self, s: &Stmt) -> Doc {
|
||||
concat(self.stmt_docs(s))
|
||||
}
|
||||
|
||||
/// One statement: its leading comments, then — unless a verbatim region is
|
||||
/// already emitting its bytes — its code and trailing comment. The
|
||||
/// statement twin of `Fmt::item_docs`, with the same two rules: comments
|
||||
/// written before the `off` fence are still emitted, because comments are
|
||||
/// never dropped, and a statement the region swallowed emits nothing.
|
||||
fn stmt_docs(&self, s: &Stmt) -> Vec<Doc> {
|
||||
// A verbatim run whose first statement carries no leading comment opens
|
||||
// at the statement's own code; there is no comment to emit it from.
|
||||
if let Some(region) = self.opens_at(s.span.start as usize) {
|
||||
return vec![self.verbatim(region)];
|
||||
}
|
||||
if self.is_verbatim(s.span) {
|
||||
// The statement's own bytes, its attributes included, are emitted
|
||||
// verbatim by the fence; only its leading comments are ours.
|
||||
let mut docs = self.leading_comments(&s.meta);
|
||||
// The last comment asked for a line break before code that is not
|
||||
// coming. Whoever emits the next unit separates it itself.
|
||||
if matches!(docs.last(), Some(Doc::HardLine)) {
|
||||
docs.pop();
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
vec![self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))]
|
||||
}
|
||||
|
||||
/// Sequence of statements at one indent level, preserving single blank
|
||||
/// lines between them. A statement a fenced region swallowed emits
|
||||
/// nothing, and contributes no separator either.
|
||||
pub(super) fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for s in stmts {
|
||||
let stmt_docs = self.stmt_docs(s);
|
||||
if stmt_docs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !docs.is_empty() {
|
||||
docs.push(if s.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.extend(stmt_docs);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// Prefix (e.g. `always_ff`, `if (...)`) followed by a body statement:
|
||||
/// blocks cuddle onto the prefix line, single statements go on the same
|
||||
/// line if they fit, otherwise indented on the next line.
|
||||
pub(super) fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc {
|
||||
self.stmt_as_body_from(prefix, s, 0)
|
||||
}
|
||||
|
||||
/// The same, skipping the body's first `skip` leading comments because
|
||||
/// `prefix` already printed them inside its parentheses. See
|
||||
/// [`Fmt::header_parens`].
|
||||
fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
|
||||
match &s.kind {
|
||||
StmtKind::Block {
|
||||
label_comments,
|
||||
label,
|
||||
stmts,
|
||||
dangling,
|
||||
end_label_comments,
|
||||
end_label,
|
||||
..
|
||||
} => {
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
docs.extend(self.leading_from(&s.meta, skip));
|
||||
docs.push(self.block_doc(BlockDoc {
|
||||
label_comments,
|
||||
label,
|
||||
stmts,
|
||||
dangling,
|
||||
end_label_comments,
|
||||
end_label,
|
||||
}));
|
||||
docs.extend(self.trailing(&s.meta));
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::Timing { control, stmt: Some(inner) } => {
|
||||
// e.g. `always @(posedge clk) begin ... end`
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
docs.extend(self.leading_from(&s.meta, skip));
|
||||
let control_doc = self.timing_control(control);
|
||||
docs.push(self.stmt_as_body(control_doc, inner));
|
||||
docs.extend(self.trailing(&s.meta));
|
||||
concat(docs)
|
||||
}
|
||||
// The same three parts `stmt` prints, with the skip applied.
|
||||
_ => {
|
||||
let mut body = self.leading_from(&s.meta, skip);
|
||||
body.push(self.stmt_kind(&s.kind, &s.before_semi));
|
||||
body.extend(self.trailing(&s.meta));
|
||||
group(vec![prefix, indent(vec![Doc::Line, concat(body)])])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn block_doc(&self, b: BlockDoc<'_>) -> Doc {
|
||||
let mut docs = vec![text("begin")];
|
||||
self.label_tail(b.label, b.label_comments, &mut docs);
|
||||
let mut body = Vec::new();
|
||||
if !b.stmts.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.stmt_seq(b.stmts));
|
||||
}
|
||||
body.extend(self.dangling(b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("end", b.end_label, b.end_label_comments));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn timing_control(&self, tc: &TimingControl) -> Doc {
|
||||
match tc {
|
||||
TimingControl::Delay { after_hash, expr } => {
|
||||
let mut docs = vec![text("#")];
|
||||
self.slot_comments(after_hash, &mut docs);
|
||||
docs.push(self.expr(expr));
|
||||
concat(docs)
|
||||
}
|
||||
TimingControl::Event(sens) => self.sens_list(sens),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sens_list(&self, sens: &SensList) -> Doc {
|
||||
match sens {
|
||||
// Written without parens, printed without parens: `@ev`,
|
||||
// `@a.b` — inventing a `( ... )` changes the token stream.
|
||||
SensList::Bare { expr, after_at } => {
|
||||
let mut docs = vec![text("@")];
|
||||
self.slot_comments(after_at, &mut docs);
|
||||
docs.push(self.expr(expr));
|
||||
concat(docs)
|
||||
}
|
||||
SensList::Star { before, after } => {
|
||||
if before.is_empty() && after.is_empty() {
|
||||
return text("@(*)");
|
||||
}
|
||||
// Comments written inside the parens stay inside them, on the
|
||||
// side of the `*` they were written on.
|
||||
let mut inner = Vec::new();
|
||||
if before.is_empty() {
|
||||
// `(*` directly followed by anything but `)` lexes as an
|
||||
// attribute instance, so keep the `*` off the paren.
|
||||
inner.push(text(" "));
|
||||
}
|
||||
for c in before {
|
||||
inner.push(self.comment(c));
|
||||
inner.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") });
|
||||
}
|
||||
inner.push(text("*"));
|
||||
for c in after {
|
||||
inner.push(text(" "));
|
||||
inner.push(self.comment(c));
|
||||
if is_line_comment(&c.text) {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
}
|
||||
concat(vec![text("@("), indent(inner), text(")")])
|
||||
}
|
||||
SensList::List { items, after_at } => {
|
||||
// Each separator is printed as it was written: `,` and `or`
|
||||
// mean the same thing but are different tokens, and rewriting
|
||||
// one as the other is a token change the safety net rejects.
|
||||
let mut parts: Vec<Doc> = Vec::new();
|
||||
for i in items {
|
||||
match i.sep {
|
||||
Some(SensSep::Comma) => parts.push(text(", ")),
|
||||
Some(SensSep::Or) => parts.push(text(" or ")),
|
||||
None => {}
|
||||
}
|
||||
for c in &i.meta.leading {
|
||||
parts.push(self.comment(c));
|
||||
parts.push(if is_line_comment(&c.text) {
|
||||
Doc::HardLine
|
||||
} else {
|
||||
text(" ")
|
||||
});
|
||||
}
|
||||
if let Some(e) = &i.edge {
|
||||
parts.push(text(e.clone()));
|
||||
if i.after_edge.is_empty() {
|
||||
parts.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&i.after_edge, &mut parts);
|
||||
}
|
||||
}
|
||||
parts.push(self.expr(&i.expr));
|
||||
// `posedge clk iff enable` — the gate belongs to this
|
||||
// term, so it prints before the separator, not after it.
|
||||
if let Some(iff) = &i.iff {
|
||||
parts.push(text(" iff "));
|
||||
parts.push(self.expr(iff));
|
||||
}
|
||||
if self.inline_comments(&i.meta.before_sep, &mut parts) {
|
||||
parts.push(Doc::HardLine);
|
||||
}
|
||||
}
|
||||
let mut docs = vec![text("@")];
|
||||
self.slot_comments(after_at, &mut docs);
|
||||
docs.push(text("("));
|
||||
docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine]));
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One arm per `StmtKind`. A dispatch table over the enum, so it stays
|
||||
/// whole past the 150-line mark: the forms that grew a layout of their
|
||||
/// own (`if`, `case`) are the functions after it, and every remaining
|
||||
/// arm is a few lines of spelling.
|
||||
fn stmt_kind(&self, kind: &StmtKind, before_semi: &[Comment]) -> Doc {
|
||||
match kind {
|
||||
StmtKind::Block {
|
||||
label_comments,
|
||||
label,
|
||||
stmts,
|
||||
dangling,
|
||||
end_label_comments,
|
||||
end_label,
|
||||
..
|
||||
} => self.block_doc(BlockDoc {
|
||||
label_comments,
|
||||
label,
|
||||
stmts,
|
||||
dangling,
|
||||
end_label_comments,
|
||||
end_label,
|
||||
}),
|
||||
StmtKind::ForkJoin {
|
||||
label_comments,
|
||||
label,
|
||||
join_kw,
|
||||
stmts,
|
||||
dangling,
|
||||
end_label_comments,
|
||||
end_label,
|
||||
..
|
||||
} => {
|
||||
let mut docs = vec![text("fork")];
|
||||
self.label_tail(label, label_comments, &mut docs);
|
||||
let mut body = Vec::new();
|
||||
if !stmts.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.stmt_seq(stmts));
|
||||
}
|
||||
body.extend(self.dangling(dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled(join_kw, end_label, end_label_comments));
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::If { qualifier, after_kw, cond, then, else_comments, els } => {
|
||||
self.if_stmt(qualifier, after_kw, cond, then, else_comments, els)
|
||||
}
|
||||
StmtKind::Case { qualifier, kw, after_kw, expr, inside, items, dangling } => {
|
||||
let mut docs = Vec::new();
|
||||
if let Some(q) = qualifier {
|
||||
docs.push(text(format!("{q} ")));
|
||||
}
|
||||
self.word_then(kw, after_kw, &mut docs);
|
||||
let (parens, taken) = match items.first() {
|
||||
Some(first) => self.header_parens(expr, &first.meta),
|
||||
None => (self.parens(expr), 0),
|
||||
};
|
||||
docs.push(parens);
|
||||
if *inside {
|
||||
docs.push(text(" inside"));
|
||||
}
|
||||
docs.push(self.case_body(items, dangling, taken));
|
||||
concat(docs)
|
||||
}
|
||||
// `randcase` is a `case` body with weights for labels and no
|
||||
// selector, so it shares the body layout.
|
||||
StmtKind::RandCase { items, dangling } => {
|
||||
concat(vec![text("randcase"), self.case_body(items, dangling, 0)])
|
||||
}
|
||||
StmtKind::For { init, cond, step, comments, body } => {
|
||||
let mut header = Vec::new();
|
||||
self.for_open(comments, &mut header);
|
||||
let init_parts: Vec<Doc> = init
|
||||
.iter()
|
||||
.map(|fi| {
|
||||
let mut d = Vec::new();
|
||||
if let Some(ty) = &fi.ty {
|
||||
if let Some(t) = self.data_type(ty) {
|
||||
d.push(t);
|
||||
if fi.before_name.is_empty() {
|
||||
d.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&fi.before_name, &mut d);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.slot_comments(&fi.before_name, &mut d);
|
||||
}
|
||||
self.simple_assign(&fi.assign, &mut d);
|
||||
concat(d)
|
||||
})
|
||||
.collect();
|
||||
header.extend(join(init_parts, text(", ")));
|
||||
self.for_semi(&comments.before_first_semi, &comments.after_first_semi, &mut header);
|
||||
if let Some(c) = cond {
|
||||
header.push(self.expr(c));
|
||||
}
|
||||
self.for_semi(
|
||||
&comments.before_second_semi,
|
||||
&comments.after_second_semi,
|
||||
&mut header,
|
||||
);
|
||||
let step_parts: Vec<Doc> = step.iter().map(|s| self.for_step(s)).collect();
|
||||
header.extend(join(step_parts, text(", ")));
|
||||
self.slot_comments(&comments.before_close, &mut header);
|
||||
header.push(text(")"));
|
||||
self.stmt_as_body(concat(header), body)
|
||||
}
|
||||
StmtKind::While { cond, body } => {
|
||||
let (parens, taken) = self.header_parens(cond, &body.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("while "), parens]), body, taken)
|
||||
}
|
||||
StmtKind::DoWhile { body, cond, comments } => {
|
||||
let mut docs = vec![text("do")];
|
||||
match &body.kind {
|
||||
StmtKind::Block {
|
||||
label_comments,
|
||||
label,
|
||||
stmts,
|
||||
dangling,
|
||||
end_label_comments,
|
||||
end_label,
|
||||
..
|
||||
} => {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.block_doc(BlockDoc {
|
||||
label_comments,
|
||||
label,
|
||||
stmts,
|
||||
dangling,
|
||||
end_label_comments,
|
||||
end_label,
|
||||
}));
|
||||
docs.push(text(" "));
|
||||
self.word_then("while", &comments.after_kw, &mut docs);
|
||||
}
|
||||
_ => {
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(body)])]));
|
||||
docs.push(Doc::HardLine);
|
||||
self.word_then("while", &comments.after_kw, &mut docs);
|
||||
}
|
||||
}
|
||||
docs.push(self.header_slots(cond, comments));
|
||||
docs.push(self.semi(before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::Repeat { count, body } => {
|
||||
let (parens, taken) = self.header_parens(count, &body.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("repeat "), parens]), body, taken)
|
||||
}
|
||||
StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body),
|
||||
StmtKind::Foreach { target, vars, var_comments, comments, body } => {
|
||||
let mut head = vec![text("foreach")];
|
||||
self.slot_comments(&comments.after_kw, &mut head);
|
||||
if comments.after_kw.is_empty() {
|
||||
head.push(text(" "));
|
||||
}
|
||||
head.push(text("("));
|
||||
self.slot_comments(&comments.after_open, &mut head);
|
||||
head.push(self.expr(target));
|
||||
head.push(self.foreach_vars(vars, var_comments));
|
||||
self.slot_comments(&comments.before_close, &mut head);
|
||||
head.push(text(")"));
|
||||
self.stmt_as_body(concat(head), body)
|
||||
}
|
||||
StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs } => {
|
||||
let mut docs = vec![self.expr(lhs)];
|
||||
// Comments written before the operator print before it, each
|
||||
// kept on its own side (`x[6:0] /* opcode */ = v;`).
|
||||
if self.inline_comments(op_comments, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text(op.clone()));
|
||||
} else {
|
||||
docs.push(text(format!(" {op}")));
|
||||
}
|
||||
let mut rhs_docs = Vec::new();
|
||||
if let Some(tc) = timing {
|
||||
rhs_docs.push(self.timing_control(tc));
|
||||
rhs_docs.push(text(" "));
|
||||
}
|
||||
rhs_docs.push(self.expr(rhs));
|
||||
if rhs_comments.is_empty() {
|
||||
docs.push(self.assign_rhs(concat(rhs_docs)));
|
||||
} else {
|
||||
// As in a continuous assignment: the comments stay on the
|
||||
// operator's line, and a line comment pushes the value
|
||||
// onto the next one.
|
||||
let mut inner = Vec::new();
|
||||
let ends_line = self.inline_comments(rhs_comments, &mut inner);
|
||||
inner.push(if ends_line { Doc::HardLine } else { text(" ") });
|
||||
inner.push(concat(rhs_docs));
|
||||
docs.push(indent(inner));
|
||||
}
|
||||
concat(vec![group(docs), self.semi(before_semi)])
|
||||
}
|
||||
StmtKind::ForceRelease { kw, lhs, rhs } => {
|
||||
let mut docs = vec![text(format!("{kw} ")), self.expr(lhs)];
|
||||
if let Some(r) = rhs {
|
||||
docs.push(text(" = "));
|
||||
docs.push(self.expr(r));
|
||||
}
|
||||
docs.push(self.semi(before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::Timing { control, stmt } => {
|
||||
let control_doc = self.timing_control(control);
|
||||
match stmt {
|
||||
Some(s) => self.stmt_as_body(control_doc, s),
|
||||
None => concat(vec![control_doc, self.semi(before_semi)]),
|
||||
}
|
||||
}
|
||||
StmtKind::Wait { cond, stmt } => match stmt {
|
||||
Some(s) => {
|
||||
let (parens, taken) = self.header_parens(cond, &s.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("wait "), parens]), s, taken)
|
||||
}
|
||||
None => concat(vec![text("wait "), self.parens(cond), self.semi(before_semi)]),
|
||||
},
|
||||
StmtKind::ExprStmt(e) => concat(vec![self.expr(e), self.semi(before_semi)]),
|
||||
StmtKind::EventTrigger(e) => {
|
||||
concat(vec![text("-> "), self.expr(e), self.semi(before_semi)])
|
||||
}
|
||||
StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), self.semi(before_semi)]),
|
||||
// The item form prints its own `;`.
|
||||
StmtKind::Typedef(t) => self.typedef(t),
|
||||
StmtKind::ParamDecl(d) => {
|
||||
concat(vec![self.param_decl(d, None), self.semi(before_semi)])
|
||||
}
|
||||
StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), self.semi(before_semi)]),
|
||||
StmtKind::Return { after_kw, expr } => match expr {
|
||||
Some(e) => {
|
||||
let mut docs = Vec::new();
|
||||
self.word_then("return", after_kw, &mut docs);
|
||||
docs.push(self.expr(e));
|
||||
docs.push(self.semi(before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
None => concat(vec![text("return"), self.semi(before_semi)]),
|
||||
},
|
||||
StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]),
|
||||
StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]),
|
||||
StmtKind::Disable(name) => {
|
||||
concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)])
|
||||
}
|
||||
StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]),
|
||||
StmtKind::Import(paths) => text(format!("import {};", join_paths(paths))),
|
||||
// A statement label prints tight against its `:`, the way a case
|
||||
// label does: `check_decode: assert (...)`.
|
||||
StmtKind::Labeled { name, stmt, .. } => {
|
||||
concat(vec![text(format!("{}: ", named(name))), self.stmt(stmt)])
|
||||
}
|
||||
StmtKind::Directive(d) => self.raw_text(d),
|
||||
// See `ItemKind::Error`: unreachable from `format_source`, present
|
||||
// so the match stays total.
|
||||
StmtKind::Error(d) => self.raw_text(d),
|
||||
StmtKind::MacroStmt(m) => self.macro_call(m),
|
||||
// A concurrent assertion: verbatim source, like its item twin.
|
||||
StmtKind::Verbatim(raw) => self.raw_text(raw),
|
||||
StmtKind::Assertion(a) => self.assertion(a),
|
||||
StmtKind::Assert { kw, cond, then, els } => {
|
||||
let mut docs = vec![text(format!("{kw} ")), self.parens(cond)];
|
||||
match (then, els) {
|
||||
(None, None) => docs.push(self.semi(before_semi)),
|
||||
(Some(t), None) => {
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(t)])]));
|
||||
}
|
||||
(None, Some(e)) => {
|
||||
docs.push(text(" else"));
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(e)])]));
|
||||
}
|
||||
(Some(t), Some(e)) => {
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(t)])]));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(e)])]));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::Null => text(";"),
|
||||
}
|
||||
}
|
||||
|
||||
fn if_stmt(
|
||||
&self,
|
||||
qualifier: &Option<String>,
|
||||
after_kw: &[Comment],
|
||||
cond: &Expr,
|
||||
then: &Stmt,
|
||||
else_comments: &[Comment],
|
||||
els: &Option<Box<Stmt>>,
|
||||
) -> Doc {
|
||||
let mut head = Vec::new();
|
||||
if let Some(q) = qualifier {
|
||||
head.push(text(format!("{q} ")));
|
||||
}
|
||||
self.word_then("if", after_kw, &mut head);
|
||||
let (parens, taken) = self.header_parens(cond, &then.meta);
|
||||
head.push(parens);
|
||||
let prefix = concat(head);
|
||||
// A line comment trailing the then-branch runs to end of line, so a
|
||||
// cuddled `else` would be swallowed into its text.
|
||||
let then_is_block =
|
||||
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
|
||||
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
|
||||
if let Some(els) = els {
|
||||
// A comment written before `else` prints before it, each on its
|
||||
// own line: it is where the source put it, and after the keyword
|
||||
// it would have crossed a token.
|
||||
if !else_comments.is_empty() {
|
||||
docs.push(Doc::HardLine);
|
||||
for c in else_comments {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text("else"));
|
||||
} else if then_is_block {
|
||||
docs.push(text(" else"));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
}
|
||||
// `else if` chains stay flat.
|
||||
if let StmtKind::If {
|
||||
qualifier: eq,
|
||||
after_kw: ea,
|
||||
cond: ec,
|
||||
then: et,
|
||||
else_comments: ecm,
|
||||
els: ee,
|
||||
} = &els.kind
|
||||
{
|
||||
docs.push(text(" "));
|
||||
let mut meta_docs = self.leading(&els.meta);
|
||||
docs.append(&mut meta_docs);
|
||||
docs.push(self.if_stmt(eq, ea, ec, et, ecm, ee));
|
||||
docs.extend(self.trailing(&els.meta));
|
||||
} else {
|
||||
docs.push(self.stmt_as_body(text(""), els));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// The `A, B:` head of a case item — `default:` when the list is empty.
|
||||
/// Labels normally share one line; as soon as any of them carries a
|
||||
/// comment they go one per line, so a comment written between two labels
|
||||
/// is printed between the same two labels instead of drifting past them.
|
||||
pub(super) fn case_labels(
|
||||
&self,
|
||||
labels: &[ExprItem],
|
||||
before_colon: &[Comment],
|
||||
item: TextRange,
|
||||
) -> Doc {
|
||||
if labels.is_empty() {
|
||||
if !self.default_has_colon(item) {
|
||||
return text("default");
|
||||
}
|
||||
let mut docs = vec![text("default")];
|
||||
self.slot_comments(before_colon, &mut docs);
|
||||
docs.push(text(":"));
|
||||
return concat(docs);
|
||||
}
|
||||
let plain = labels.iter().all(|l| {
|
||||
l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none()
|
||||
});
|
||||
if plain {
|
||||
let docs: Vec<Doc> = labels.iter().map(|l| self.expr(&l.expr)).collect();
|
||||
return concat(vec![concat(join(docs, text(", "))), text(":")]);
|
||||
}
|
||||
let last = labels.len() - 1;
|
||||
let mut docs = Vec::new();
|
||||
for (i, l) in labels.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
for c in &l.meta.leading {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.expr(&l.expr));
|
||||
let ends_line = self.inline_comments(&l.meta.before_sep, &mut docs);
|
||||
if i < last {
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(","));
|
||||
} else if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
if let Some(tr) = &l.meta.trailing {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.comment(tr));
|
||||
if i == last && is_line_comment(&tr.text) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
docs.push(text(":"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn case_item(&self, item: &CaseItem) -> Doc {
|
||||
// `default;` — the colon IEEE 1800 §12.5 makes optional, with a null
|
||||
// body. The `;` closes the keyword rather than standing as a body of
|
||||
// its own, so it hugs instead of going through `stmt_as_body`.
|
||||
if item.labels.is_empty()
|
||||
&& matches!(item.stmt.kind, StmtKind::Null)
|
||||
&& is_bare(&item.stmt.meta)
|
||||
&& !self.default_has_colon(item.span)
|
||||
{
|
||||
return text("default;");
|
||||
}
|
||||
self.stmt_as_body(self.case_labels(&item.labels, &item.before_colon, item.span), &item.stmt)
|
||||
}
|
||||
|
||||
/// The items of a `case`/`randcase` body. `skip` is the number of leading
|
||||
/// comments of the *first* item the `case (...)` header already printed
|
||||
/// inside its parentheses (see [`Fmt::header_parens`]).
|
||||
fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc {
|
||||
let mut body = Vec::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 }));
|
||||
body.push(self.case_item(item));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
}
|
||||
body.extend(self.dangling(dangling));
|
||||
concat(vec![indent(body), Doc::HardLine, text("endcase")])
|
||||
}
|
||||
|
||||
/// True when the source wrote the optional `:` after a `default` case
|
||||
/// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and
|
||||
/// the token stream has to come back with exactly what was written.
|
||||
fn default_has_colon(&self, span: TextRange) -> bool {
|
||||
let after = span.start as usize + "default".len();
|
||||
matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':')
|
||||
}
|
||||
}
|
||||
|
||||
/// True when a node carries no trivia at all, so printing it cannot move a
|
||||
/// comment anywhere.
|
||||
fn is_bare(meta: &Meta) -> bool {
|
||||
meta.leading.is_empty()
|
||||
&& meta.trailing.is_none()
|
||||
&& meta.before_sep.is_empty()
|
||||
&& meta.attrs.is_empty()
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
//! Assertions (IEEE 1800-2017 §16): `property`/`sequence` declarations,
|
||||
//! concurrent assertions with their action blocks, `disable iff`, and
|
||||
//! the property-expression grammar.
|
||||
//!
|
||||
//! One layout rule, stated in `docs/features/sva-bodies/README.md`: the
|
||||
//! spec's top-level operators — `|->`, `|=>`, `##`, `and`, `or` — break
|
||||
//! one per line at the parent's indent when the spec does not fit on one
|
||||
//! line; everything else is inline. Each operand is then laid out by the
|
||||
//! same rule, so a wide operand of a broken operator breaks in turn and a
|
||||
//! narrow one does not.
|
||||
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::comment::{is_line_comment, trailing_ends_line};
|
||||
use super::{name_doc, Fmt};
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// `property p (args); … endproperty : p` and its `sequence` twin.
|
||||
pub(super) fn prop_seq_decl(&self, d: &PropSeqDecl) -> Doc {
|
||||
let end_kw = if d.kw == "sequence" { "endsequence" } else { "endproperty" };
|
||||
let mut docs = vec![text(d.kw.clone())];
|
||||
self.inline_comments_spaced(&d.before_name, &mut docs);
|
||||
docs.push(name_doc(&d.name.text));
|
||||
if let Some(args) = &d.args {
|
||||
// The parens hug the name, as a function's do; only a comment
|
||||
// written in that gap puts anything between the two.
|
||||
if !d.before_args.is_empty() {
|
||||
self.inline_comments_spaced(&d.before_args, &mut docs);
|
||||
}
|
||||
docs.push(self.tf_args(&args.args, &args.dangling));
|
||||
}
|
||||
if self.inline_comments(&d.before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
let mut body = Vec::new();
|
||||
for local in &d.locals {
|
||||
body.push(if local.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.push(self.with_meta(&local.meta, self.item_kind(&local.kind, None, 0)));
|
||||
}
|
||||
body.push(Doc::HardLine);
|
||||
body.push(self.prop_spec(&d.spec));
|
||||
if d.spec_semi {
|
||||
if self.inline_comments(&d.before_spec_semi, &mut body) {
|
||||
body.push(Doc::HardLine);
|
||||
}
|
||||
body.push(text(";"));
|
||||
}
|
||||
body.extend(self.dangling(&d.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
let end_label = d.end_label.as_ref().map(|l| l.text.clone());
|
||||
docs.push(self.closing_labeled(end_kw, &end_label, &d.end_label_comments));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `[lbl :] assert property ( spec ) action_block`.
|
||||
pub(super) fn assertion(&self, a: &AssertionDecl) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
if let Some(label) = &a.label {
|
||||
docs.push(name_doc(&label.text));
|
||||
self.slot_comments(&a.label_comments.before_colon, &mut docs);
|
||||
docs.push(text(":"));
|
||||
if a.label_comments.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&a.label_comments.after_colon, &mut docs);
|
||||
}
|
||||
}
|
||||
docs.push(text(a.kw.clone()));
|
||||
if !a.kw2.is_empty() {
|
||||
self.inline_comments_spaced(&a.after_kw, &mut docs);
|
||||
docs.push(text(a.kw2.clone()));
|
||||
}
|
||||
if a.before_open.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&a.before_open, &mut docs);
|
||||
}
|
||||
docs.push(self.prop_parens(&a.after_open, &a.spec, &a.before_close));
|
||||
self.action_block(concat(docs), &a.action)
|
||||
}
|
||||
|
||||
/// `( spec )`. The parentheses hug the spec's first and last lines — a
|
||||
/// spec that breaks does so *inside* them, one indent in, which is what
|
||||
/// every multi-line assertion in the corpus is already written as.
|
||||
fn prop_parens(
|
||||
&self,
|
||||
after_open: &[Comment],
|
||||
spec: &PropSpec,
|
||||
before_close: &[Comment],
|
||||
) -> Doc {
|
||||
let mut inner = Vec::new();
|
||||
if self.inline_comments(after_open, &mut inner) {
|
||||
inner.push(Doc::HardLine);
|
||||
} else if !after_open.is_empty() {
|
||||
inner.push(text(" "));
|
||||
}
|
||||
inner.push(self.prop_spec(spec));
|
||||
let mut docs = vec![text("("), indent(inner)];
|
||||
if self.inline_comments(before_close, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !before_close.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `head` — the assertion through its closing `)` — followed by the
|
||||
/// action block's pass and fail statements, laid out exactly as an `if`
|
||||
/// statement's branches are: a block cuddles onto the line before it, a
|
||||
/// single statement goes there if it fits and on an indented next line if
|
||||
/// it does not, and `else` follows a block on its closing line.
|
||||
fn action_block(&self, head: Doc, a: &ActionBlock) -> Doc {
|
||||
if a.pass.is_none() && a.fail.is_none() {
|
||||
let mut docs = vec![head];
|
||||
if self.inline_comments(&a.before, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
return concat(docs);
|
||||
}
|
||||
let Some(pass) = &a.pass else {
|
||||
// `assert property (p) else $error(…);` — the `else` follows the
|
||||
// spec's `)` directly, and takes the next line when it does not
|
||||
// fit beside it.
|
||||
let Some(fail) = &a.fail else { return head };
|
||||
let mut head = vec![head];
|
||||
self.inline_comments(&a.before_else, &mut head);
|
||||
let head = concat(head);
|
||||
let mut els = vec![text("else")];
|
||||
self.inline_comments(&a.after_else, &mut els);
|
||||
// A `begin ... end` fail statement cuddles onto the assertion's
|
||||
// own line, the way an `if`'s block branch does; measuring it
|
||||
// would only ever say "does not fit", because a block holds a
|
||||
// hard line break.
|
||||
if matches!(fail.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. }) {
|
||||
return concat(vec![head, text(" "), self.stmt_as_body(concat(els), fail)]);
|
||||
}
|
||||
return group(vec![
|
||||
head,
|
||||
indent(vec![Doc::Line, self.stmt_as_body(concat(els), fail)]),
|
||||
]);
|
||||
};
|
||||
// A line comment trailing the pass statement runs to end of line, so
|
||||
// a cuddled `else` would be swallowed into its text — `if_stmt`'s
|
||||
// rule, for the same reason.
|
||||
let pass_is_block = matches!(pass.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. })
|
||||
&& !trailing_ends_line(&pass.meta);
|
||||
let mut docs = vec![self.stmt_as_body(head, pass)];
|
||||
let Some(fail) = &a.fail else { return concat(docs) };
|
||||
if !a.before_else.is_empty() {
|
||||
docs.push(Doc::HardLine);
|
||||
for c in &a.before_else {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text("else"));
|
||||
} else if pass_is_block {
|
||||
docs.push(text(" else"));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
}
|
||||
self.inline_comments(&a.after_else, &mut docs);
|
||||
// The fail statement is measured on its own, not against the pass
|
||||
// statement that already broke across lines: `if_stmt` passes an
|
||||
// empty prefix here for the same reason, and the `else` above
|
||||
// supplies the separator's left half.
|
||||
docs.push(self.stmt_as_body(text(""), fail));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `default disable iff ( expr );`.
|
||||
pub(super) fn default_disable(&self, d: &DisableIff) -> Doc {
|
||||
let mut docs = vec![text("default")];
|
||||
if d.before_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&d.before_kw, &mut docs);
|
||||
}
|
||||
docs.push(self.disable_iff(d));
|
||||
if self.inline_comments(&d.before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `disable iff ( expr )`, without the `default` spelling's `;`.
|
||||
fn disable_iff(&self, d: &DisableIff) -> Doc {
|
||||
let mut docs = vec![text("disable")];
|
||||
if d.after_disable.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&d.after_disable, &mut docs);
|
||||
}
|
||||
docs.push(text("iff"));
|
||||
if d.after_iff.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&d.after_iff, &mut docs);
|
||||
}
|
||||
if d.parens {
|
||||
docs.push(self.guard_parens(&d.expr, &d.after_open, &d.before_close));
|
||||
} else {
|
||||
docs.push(self.expr(&d.expr));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A `property_spec`: the clocking event, the `disable iff` and the
|
||||
/// property expression, each on its own line when the three do not fit
|
||||
/// on one.
|
||||
fn prop_spec(&self, spec: &PropSpec) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
for c in &spec.leading {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { Doc::Line });
|
||||
}
|
||||
if let Some(sens) = &spec.clocking {
|
||||
docs.push(self.sens_list(sens));
|
||||
docs.push(Doc::Line);
|
||||
}
|
||||
if let Some(dis) = &spec.disable {
|
||||
self.slot_comments(&dis.before_kw, &mut docs);
|
||||
docs.push(self.disable_iff(dis));
|
||||
docs.push(Doc::Line);
|
||||
}
|
||||
// A comment written in front of the property expression prints where
|
||||
// it was written — after whatever `Doc::Line` the header already
|
||||
// pushed, so it starts the line rather than trailing a space onto it.
|
||||
for c in &spec.before_expr {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { Doc::Line });
|
||||
}
|
||||
docs.push(self.prop_expr(&spec.expr));
|
||||
group(docs)
|
||||
}
|
||||
|
||||
/// True when a top-level operator of a spec breaks onto its own line.
|
||||
/// The five the round's one layout rule names.
|
||||
fn breaks_line(op: &PropOp) -> bool {
|
||||
match op {
|
||||
PropOp::Delay(_) => true,
|
||||
PropOp::Word(w) => matches!(w.as_str(), "|->" | "|=>" | "and" | "or"),
|
||||
}
|
||||
}
|
||||
|
||||
/// One arm per `PropKind`. A dispatch table over the enum, so it stays
|
||||
/// whole past the 150-line mark; the `Paren` and `Call` arms spell the
|
||||
/// same `( … , match items )` shape, which a later change may fold.
|
||||
fn prop_expr(&self, e: &PropExpr) -> Doc {
|
||||
match &e.kind {
|
||||
PropKind::Expr(inner) => self.expr(inner),
|
||||
PropKind::Paren(p) => {
|
||||
let mut docs = vec![text("(")];
|
||||
if self.inline_comments(&p.after_open, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !p.after_open.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.prop_expr(&p.expr));
|
||||
docs.extend(self.match_items(&p.items));
|
||||
if self.inline_comments(&p.before_close, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !p.before_close.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
PropKind::Binary(b) => {
|
||||
let mut op = Vec::new();
|
||||
self.slot_comments(&b.comments.before, &mut op);
|
||||
match &b.op {
|
||||
PropOp::Word(w) => op.push(text(w.clone())),
|
||||
PropOp::Delay(d) => op.push(self.cycle_delay(d)),
|
||||
}
|
||||
if b.comments.after.is_empty() {
|
||||
op.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.comments.after, &mut op);
|
||||
}
|
||||
let lhs = self.prop_expr(&b.lhs);
|
||||
let rhs = self.prop_expr(&b.rhs);
|
||||
if Self::breaks_line(&b.op) {
|
||||
return group(vec![lhs, Doc::Line, concat(op), rhs]);
|
||||
}
|
||||
concat(vec![lhs, text(" "), concat(op), rhs])
|
||||
}
|
||||
PropKind::Unary(u) => {
|
||||
let mut docs = vec![text(u.op.clone())];
|
||||
if u.comments.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&u.comments, &mut docs);
|
||||
}
|
||||
if let Some(count) = &u.count {
|
||||
docs.push(self.sva_range("", &[], count));
|
||||
if u.after_count.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&u.after_count, &mut docs);
|
||||
}
|
||||
}
|
||||
docs.push(self.prop_expr(&u.expr));
|
||||
concat(docs)
|
||||
}
|
||||
PropKind::Call(c) => {
|
||||
let mut docs = vec![text(c.name.clone())];
|
||||
self.slot_comments(&c.before_open, &mut docs);
|
||||
docs.push(text("("));
|
||||
if self.inline_comments(&c.after_open, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !c.after_open.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.prop_expr(&c.expr));
|
||||
docs.extend(self.match_items(&c.items));
|
||||
if self.inline_comments(&c.before_close, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
} else if !c.before_close.is_empty() {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
PropKind::Abort(a) => {
|
||||
let mut docs = vec![text(a.kw.clone())];
|
||||
if a.comments.after_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&a.comments.after_kw, &mut docs);
|
||||
}
|
||||
docs.push(self.guard_parens(
|
||||
&a.cond,
|
||||
&a.comments.after_open,
|
||||
&a.comments.before_close,
|
||||
));
|
||||
if a.comments.before_body.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&a.comments.before_body, &mut docs);
|
||||
}
|
||||
docs.push(self.prop_expr(&a.expr));
|
||||
concat(docs)
|
||||
}
|
||||
PropKind::Delay(d) => {
|
||||
let mut docs = vec![self.cycle_delay(&d.delay)];
|
||||
if d.after_delay.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&d.after_delay, &mut docs);
|
||||
}
|
||||
docs.push(self.prop_expr(&d.expr));
|
||||
concat(docs)
|
||||
}
|
||||
PropKind::Repeat(r) => {
|
||||
let mut docs = vec![self.prop_expr(&r.expr)];
|
||||
self.slot_comments(&r.before_open, &mut docs);
|
||||
docs.push(self.sva_range(&r.op, &r.after_op, &r.range));
|
||||
concat(docs)
|
||||
}
|
||||
PropKind::If(i) => {
|
||||
let mut docs = vec![text("if")];
|
||||
if i.comments.after_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&i.comments.after_kw, &mut docs);
|
||||
}
|
||||
docs.push(self.guard_parens(
|
||||
&i.cond,
|
||||
&i.comments.after_open,
|
||||
&i.comments.before_close,
|
||||
));
|
||||
if i.comments.before_body.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&i.comments.before_body, &mut docs);
|
||||
}
|
||||
docs.push(self.prop_expr(&i.then));
|
||||
if let Some(els) = &i.els {
|
||||
self.slot_comments(&i.before_else, &mut docs);
|
||||
docs.push(text(" else"));
|
||||
if i.after_else.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&i.after_else, &mut docs);
|
||||
}
|
||||
docs.push(self.prop_expr(els));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
PropKind::Case(c) => {
|
||||
let mut docs = vec![text("case")];
|
||||
if c.comments.after_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&c.comments.after_kw, &mut docs);
|
||||
}
|
||||
docs.push(self.guard_parens(
|
||||
&c.cond,
|
||||
&c.comments.after_open,
|
||||
&c.comments.before_close,
|
||||
));
|
||||
let mut body = Vec::new();
|
||||
for item in &c.items {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.push(self.with_meta(&item.meta, self.prop_case_item(item)));
|
||||
}
|
||||
body.extend(self.dangling(&c.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("endcase"));
|
||||
concat(docs)
|
||||
}
|
||||
PropKind::Spec(spec) => self.prop_spec(spec),
|
||||
}
|
||||
}
|
||||
|
||||
fn prop_case_item(&self, item: &PropCaseItem) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
if item.is_default {
|
||||
docs.push(text("default"));
|
||||
} else {
|
||||
docs.push(self.plain_expr_list(&item.labels));
|
||||
}
|
||||
self.slot_comments(&item.before_colon, &mut docs);
|
||||
docs.push(text(":"));
|
||||
if item.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&item.after_colon, &mut docs);
|
||||
}
|
||||
docs.push(self.prop_expr(&item.expr));
|
||||
if self.inline_comments(&item.before_semi, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `, x = e, y++` — the match items of a parenthesised sequence.
|
||||
fn match_items(&self, items: &[MatchItem]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for item in items {
|
||||
self.slot_comments(&item.before_comma, &mut docs);
|
||||
docs.push(text(", "));
|
||||
docs.extend(self.leading(&item.meta));
|
||||
docs.push(self.expr(&item.lhs));
|
||||
if let Some(op) = &item.op {
|
||||
self.slot_comments(&item.comments.before, &mut docs);
|
||||
docs.push(text(format!(" {op}")));
|
||||
if item.comments.after.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&item.comments.after, &mut docs);
|
||||
}
|
||||
}
|
||||
if let Some(rhs) = &item.rhs {
|
||||
docs.push(self.expr(rhs));
|
||||
}
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// `##3`, `##[1:$]`, `##[+]`.
|
||||
fn cycle_delay(&self, d: &CycleDelay) -> Doc {
|
||||
let mut docs = vec![text("##")];
|
||||
self.slot_comments(&d.after_hash, &mut docs);
|
||||
if let Some(e) = &d.expr {
|
||||
docs.push(self.expr(e));
|
||||
}
|
||||
if let Some(range) = &d.range {
|
||||
docs.push(self.sva_range("", &[], range));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `[*3]`, `[=1:2]`, `[->1]`, `[+]`, and the bare `[2]` count of a
|
||||
/// `nexttime`. `op` is empty for the two that write none.
|
||||
fn sva_range(&self, op: &str, after_op: &[Comment], r: &SvaRange) -> Doc {
|
||||
let mut docs = vec![text("[")];
|
||||
self.slot_comments_tight(&r.after_open, &mut docs);
|
||||
if !op.is_empty() {
|
||||
docs.push(text(op.to_string()));
|
||||
self.slot_comments_tight(after_op, &mut docs);
|
||||
}
|
||||
if !r.shorthand.is_empty() {
|
||||
docs.push(text(r.shorthand.clone()));
|
||||
}
|
||||
if let Some(lo) = &r.lo {
|
||||
docs.push(self.expr(lo));
|
||||
}
|
||||
if let Some(hi) = &r.hi {
|
||||
self.slot_comments_tight(&r.before_colon, &mut docs);
|
||||
docs.push(text(":"));
|
||||
self.slot_comments_tight(&r.after_colon, &mut docs);
|
||||
docs.push(self.expr(hi));
|
||||
}
|
||||
self.slot_comments_tight(&r.before_close, &mut docs);
|
||||
docs.push(text("]"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// [`Fmt::slot_comments`] for a slot that writes no space of its own: the
|
||||
/// inside of a `[ ... ]` bound, where `[*3]` must stay tight.
|
||||
fn slot_comments_tight(&self, comments: &[Comment], docs: &mut Vec<Doc>) {
|
||||
if comments.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.inline_comments(comments, docs);
|
||||
docs.push(text(" "));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Bytes the formatter copies rather than lays out: fenced
|
||||
//! (`// verilog_format: off`) regions, the untouched runs of a `--lines`
|
||||
//! pass, compiler directives, attributes and macro invocations — and the
|
||||
//! one rule that keeps a multi-line copy a fixed point, `raw_lines`'s
|
||||
//! dedent by original column.
|
||||
//!
|
||||
//! The cut is "text that has no layout of its own": everything here is
|
||||
//! reproduced, at most re-indented, so a change to *what* is verbatim (a
|
||||
//! new fence kind, a new directive shape) lands in this file and no other.
|
||||
|
||||
use crate::doc::*;
|
||||
use crate::fence::{self, Region};
|
||||
use crate::range::Split;
|
||||
use crate::verify::line_starts_inside_string;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::Fmt;
|
||||
|
||||
/// What a comment turns into: itself, the verbatim region it opens, or
|
||||
/// nothing at all because a region already covers its bytes.
|
||||
pub(super) enum Slot<'r> {
|
||||
Normal,
|
||||
Opens(&'r Region),
|
||||
Covered,
|
||||
}
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// What to do with one comment, given the fenced regions of the source.
|
||||
pub(super) fn slot(&self, c: &Comment) -> Slot<'_> {
|
||||
match fence::region_at(&self.regions, c.span.start as usize) {
|
||||
None => Slot::Normal,
|
||||
Some(r) if r.fence == c.span.start as usize => Slot::Opens(r),
|
||||
Some(_) => Slot::Covered,
|
||||
}
|
||||
}
|
||||
|
||||
/// True if this node's code is inside a verbatim region, i.e. its bytes
|
||||
/// are already being emitted as written and it must not be laid out.
|
||||
pub(super) fn is_verbatim(&self, span: TextRange) -> bool {
|
||||
fence::region_at(&self.regions, span.start as usize).is_some()
|
||||
}
|
||||
|
||||
/// The verbatim region this byte offset *opens*, if it opens one.
|
||||
///
|
||||
/// A region's opener is the first byte of the first unit it covers: a
|
||||
/// fence comment, the first leading comment of a run's first item, or —
|
||||
/// when that item has no leading comments — the item's own code.
|
||||
pub(super) fn opens_at(&self, at: usize) -> Option<&Region> {
|
||||
fence::region_at(&self.regions, at).filter(|r| r.fence == at)
|
||||
}
|
||||
|
||||
/// The split recorded for the item starting at this byte offset.
|
||||
pub(super) fn split_at(&self, at: usize) -> Option<&Split> {
|
||||
self.splits.iter().find(|s| s.item == at)
|
||||
}
|
||||
|
||||
/// A verbatim slice of the source, by byte range.
|
||||
pub(super) fn slice(&self, (start, end): (usize, usize)) -> Doc {
|
||||
Doc::Verbatim(self.src.get(start..end).unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
/// A fenced region's source bytes.
|
||||
///
|
||||
/// A slice that is not on a character boundary cannot happen — every
|
||||
/// offset comes from a span or from a scan over ASCII delimiters — but if
|
||||
/// it ever did, an empty region loses tokens and `verify_equivalence`
|
||||
/// rejects the output, which is the failsafe. Better that than a panic.
|
||||
pub(super) fn verbatim(&self, r: &Region) -> Doc {
|
||||
Doc::Verbatim(self.src.get(r.start..r.end).unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
/// Verbatim text — a directive, an attribute, or a macro invocation —
|
||||
/// ready to be re-indented.
|
||||
///
|
||||
/// A token that carries a string literal across a line break is emitted
|
||||
/// completely untouched instead: the leading whitespace of such a
|
||||
/// continuation line is part of the string's *value*, and re-indenting it
|
||||
/// would rewrite the string. Emitting the text as a `Doc::Inline` means
|
||||
/// the printer copies the newlines through without adding indent — so
|
||||
/// nothing changes and the result is a fixed point by construction —
|
||||
/// while its column tracking resumes from the text's own last line
|
||||
/// (`Doc::Text` must not contain newlines).
|
||||
pub(super) fn raw_text(&self, raw: &RawText) -> Doc {
|
||||
if crosses_line_inside_string(&raw.text) {
|
||||
return Doc::Inline(raw.text.clone());
|
||||
}
|
||||
self.raw_lines(&raw.text, raw.col)
|
||||
}
|
||||
|
||||
/// Verbatim text that does *not* start the line it is printed on: the
|
||||
/// `#( ... )` of a parameterized type or class reference.
|
||||
///
|
||||
/// It is emitted exactly as written, continuation lines included.
|
||||
/// `raw_lines`'s dedent-by-column only reaches a fixed point when the text
|
||||
/// begins its own line — the dedent has to cancel the indent the printer
|
||||
/// adds back — and this text never does, so re-indenting it would drift.
|
||||
/// Emitting it unchanged is idempotent by construction. `Doc::Inline`
|
||||
/// rather than `Doc::Text` so a multi-line `#( ... )` keeps the printer's
|
||||
/// column honest (`Doc::Text` must not contain newlines).
|
||||
pub(super) fn raw_inline(&self, raw: &RawText) -> Doc {
|
||||
Doc::Inline(raw.text.clone())
|
||||
}
|
||||
|
||||
/// The `{ ... }` of a `randomize() with { ... }`: verbatim source spliced
|
||||
/// into the middle of a line.
|
||||
///
|
||||
/// Like [`Fmt::raw_inline`] it is reproduced byte for byte — the block is
|
||||
/// a constraint body lucisv does not model, so there is no layout to apply
|
||||
/// and re-indenting it would only drift on every pass — but the printer
|
||||
/// is told about the line breaks inside it, so the expression around it
|
||||
/// is still measured against the line width correctly.
|
||||
pub(super) fn with_block(&self, raw: &RawText) -> Doc {
|
||||
Doc::Inline(raw.text.clone())
|
||||
}
|
||||
|
||||
/// A macro invocation standing as an item or a statement. The invocation
|
||||
/// itself is verbatim source — we do not expand macros, so re-spacing the
|
||||
/// argument list would be guesswork — and the trailing `;` is reproduced
|
||||
/// only if the source wrote one.
|
||||
pub(super) fn macro_call(&self, call: &MacroCall) -> Doc {
|
||||
let body = self.raw_text(&call.raw);
|
||||
if call.semi {
|
||||
concat(vec![body, text(";")])
|
||||
} else {
|
||||
body
|
||||
}
|
||||
}
|
||||
|
||||
/// Multi-line raw text that originally started at column `col`. Every
|
||||
/// continuation line is dedented by `col - 1` before the printer prepends
|
||||
/// the current indent; without that, each pass would stack another indent
|
||||
/// on top of the previous one and formatting would never converge.
|
||||
pub(super) fn raw_lines(&self, s: &str, col: u32) -> Doc {
|
||||
if !s.contains('\n') {
|
||||
return text(s);
|
||||
}
|
||||
let dedent = col.saturating_sub(1) as usize;
|
||||
let mut docs = Vec::new();
|
||||
for (i, line) in s.split('\n').enumerate() {
|
||||
let line = if i == 0 {
|
||||
line
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
strip_blanks(line, dedent)
|
||||
};
|
||||
docs.push(text(line.trim_end()));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
|
||||
/// True if any line break in `text` falls inside a string literal, making
|
||||
/// every byte of the following line part of that string's value rather than
|
||||
/// layout. See [`crate::verify::line_starts_inside_string`].
|
||||
fn crosses_line_inside_string(text: &str) -> bool {
|
||||
text.contains('\n') && line_starts_inside_string(text).iter().skip(1).any(|&inside| inside)
|
||||
}
|
||||
|
||||
/// Drop up to `n` leading spaces or tabs.
|
||||
fn strip_blanks(line: &str, n: usize) -> &str {
|
||||
let mut rest = line;
|
||||
for _ in 0..n {
|
||||
match rest.strip_prefix(' ').or_else(|| rest.strip_prefix('\t')) {
|
||||
Some(shorter) => rest = shorter,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
rest
|
||||
}
|
||||
@@ -158,7 +158,14 @@ pub fn select(src: &str, file: &SourceFile, lines: &LineRanges) -> Selection {
|
||||
pub fn plan(src: &str, file: &SourceFile, selection: &Selection) -> Plan {
|
||||
let mut planner = Planner::new(src, file, Mode::Picks(&selection.picks));
|
||||
planner.scope(&file.items, &file.dangling);
|
||||
Plan { regions: normalize(planner.regions), splits: planner.splits }
|
||||
// The fenced regions go in alongside the runs the picks made. An *item* a
|
||||
// fence covers is already `Pick::Verbatim`, so its bytes are in a run
|
||||
// either way; a fenced **statement** inside a laid-out item has no such
|
||||
// run behind it, and without this the caller's `--lines` would reformat
|
||||
// bytes the author fenced off. `normalize` folds the two into their union.
|
||||
let mut regions = planner.regions;
|
||||
regions.extend(planner.fences.iter().copied());
|
||||
Plan { regions: normalize(regions), splits: planner.splits }
|
||||
}
|
||||
|
||||
/// Sort the collected regions and fold everything that overlaps into one.
|
||||
|
||||
@@ -20,8 +20,9 @@ module counter_properties;
|
||||
assume property (@(posedge clk_i) (!init) |-> !rst_ni);
|
||||
endmodule
|
||||
====
|
||||
# a multi-line property spec keeps its own line structure, re-indented as a
|
||||
# whole -- exactly what a `constraint` block does
|
||||
# a multi-line property spec is laid out by the round's one rule: the clocking
|
||||
# event, the `disable iff` and the property expression one per line, one indent
|
||||
# inside the parentheses, when the three do not fit on one
|
||||
# corpus/common_cells/formal/counter_properties.sv:48-50
|
||||
module counter_properties;
|
||||
assert property (@(posedge clk_i)
|
||||
@@ -31,8 +32,8 @@ endmodule
|
||||
----
|
||||
module counter_properties;
|
||||
assert property (@(posedge clk_i)
|
||||
disable iff (!rst_ni)
|
||||
(count_up && !resetting) |=> q_o == $past(q_o) + {{WIDTH-1{1'b0}}, 1'b1});
|
||||
disable iff (!rst_ni)
|
||||
(count_up && !resetting) |=> q_o == $past(q_o) + {{WIDTH - 1{1'b0}}, 1'b1});
|
||||
endmodule
|
||||
====
|
||||
# `cover property` and `restrict property`; `restrict` is not a lexer keyword,
|
||||
@@ -64,9 +65,7 @@ LoadMemEarlyResp: assume property (
|
||||
early_resp |-> data_rdata_i == spec_mem_read_fst_rdata
|
||||
);
|
||||
----
|
||||
LoadMemEarlyResp: assume property (
|
||||
early_resp |-> data_rdata_i == spec_mem_read_fst_rdata
|
||||
);
|
||||
LoadMemEarlyResp: assume property (early_resp |-> data_rdata_i == spec_mem_read_fst_rdata);
|
||||
====
|
||||
# an `else` action block, at item position inside a generate `begin`
|
||||
# corpus/common_cells/test/fifo_tb.sv:155-156
|
||||
@@ -80,7 +79,7 @@ endmodule
|
||||
module fifo_tb;
|
||||
if (FALL_THROUGH) begin
|
||||
assert property (@(posedge clk_i) ((empty & ~push) ##1 push) |-> rdata == wdata)
|
||||
else $error("Input did not fall through");
|
||||
else $error("Input did not fall through");
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
@@ -95,18 +94,21 @@ endmodule
|
||||
----
|
||||
module clk_int_div_static_tb;
|
||||
for (genvar i = 1; i < MaxClkDiv; i++) begin : gen_clk_divs
|
||||
assert_period_period: assert property (@(posedge clk_out[i]) T_clk(TClkIn*i)) else
|
||||
$error("Output period of div %d clock is incorrect.", i);
|
||||
assert_period_period: assert property (@(posedge clk_out[i]) T_clk(TClkIn * i))
|
||||
else $error("Output period of div %d clock is incorrect.", i);
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# both halves of an action block: pass statement, then `else`
|
||||
# both halves of an action block: pass statement, then `else`. A pass
|
||||
# statement that is not a block puts the `else` on the next line, which is
|
||||
# what a statement `if` already does with a non-block then-branch.
|
||||
module m;
|
||||
assert property (@(posedge clk) w) $info("pass"); else $error("fail");
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assert property (@(posedge clk) w) $info("pass"); else $error("fail");
|
||||
assert property (@(posedge clk) w) $info("pass");
|
||||
else $error("fail");
|
||||
endmodule
|
||||
====
|
||||
# an action block written as a `begin`/`end` block, with no trailing `;`
|
||||
@@ -137,7 +139,7 @@ endmodule
|
||||
module prim_alert_sender;
|
||||
if (AsyncOn) begin : gen_async_assert
|
||||
sequence PingSigInt_S;
|
||||
alert_rx_i.ping_p == alert_rx_i.ping_n [*2];
|
||||
alert_rx_i.ping_p == alert_rx_i.ping_n[*2];
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
@@ -156,11 +158,10 @@ endmodule
|
||||
----
|
||||
module clk_int_div_static_tb;
|
||||
property T_clk(real clk_period);
|
||||
realtime current_time;
|
||||
realtime actual_period;
|
||||
realtime current_time;
|
||||
realtime actual_period;
|
||||
disable iff (!rstn || !enable)
|
||||
(('1, current_time = $realtime)) |=>
|
||||
('1, actual_period = $realtime - current_time);
|
||||
(('1, current_time = $realtime)) |=> ('1, actual_period = $realtime - current_time);
|
||||
endproperty : T_clk
|
||||
endmodule
|
||||
====
|
||||
@@ -212,7 +213,9 @@ module m;
|
||||
wire w;
|
||||
endmodule
|
||||
====
|
||||
# a comment written *inside* the captured span stays inside it, printed once
|
||||
# a comment written between the clocking event and the property expression has
|
||||
# a slot of its own (`PropSpec::before_expr`) and prints back between the same
|
||||
# two tokens
|
||||
module m;
|
||||
assert property (@(posedge clk)
|
||||
// only while enabled
|
||||
@@ -221,8 +224,8 @@ endmodule
|
||||
----
|
||||
module m;
|
||||
assert property (@(posedge clk)
|
||||
// only while enabled
|
||||
en |-> ready);
|
||||
// only while enabled
|
||||
en |-> ready);
|
||||
endmodule
|
||||
====
|
||||
# a `// verilog_format: off` fence still wins: every byte as written
|
||||
@@ -250,24 +253,28 @@ else $error("line one
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assert property (@(posedge clk) a |-> b)
|
||||
else $error("line one
|
||||
assert property (@(posedge clk) a |-> b) else $error("line one
|
||||
line two indented");
|
||||
endmodule
|
||||
====
|
||||
# a property spec far past the line limit is *not* broken: the property
|
||||
# expression is a grammar lucisv does not model, so it is reproduced as written
|
||||
# a property spec far past the line limit *is* broken now: `sva-bodies` gave
|
||||
# the property expression a grammar, so the one layout rule applies -- the
|
||||
# clocking event, the `disable iff` and the expression one per line
|
||||
module m;
|
||||
assert property (@(posedge clk_i) disable iff (!rst_ni) some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assert property (@(posedge clk_i) disable iff (!rst_ni) some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name);
|
||||
assert property (@(posedge clk_i)
|
||||
disable iff (!rst_ni)
|
||||
some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name);
|
||||
endmodule
|
||||
====
|
||||
# an action block whose pass statement is an `if` with a `begin ... end`
|
||||
# body: the block -- and the `else` after it -- belong to the assertion,
|
||||
# and the item after it survives
|
||||
# body. The `else` binds to the nearest `if`, which is the dangling-else rule
|
||||
# the language has everywhere -- the pre-`sva-bodies` text scan could not see
|
||||
# that, and read it as the assertion's own fail arm. Same tokens either way;
|
||||
# the item after it still survives.
|
||||
module m;
|
||||
always @(posedge clk)
|
||||
assert property (@(posedge clk) a |-> b)
|
||||
@@ -283,8 +290,7 @@ module m;
|
||||
assert property (@(posedge clk) a |-> b)
|
||||
if (cond) begin
|
||||
x = 1;
|
||||
end
|
||||
else y = 2;
|
||||
end else y = 2;
|
||||
wire w;
|
||||
endmodule
|
||||
====
|
||||
@@ -309,8 +315,7 @@ module m;
|
||||
begin
|
||||
disable fork;
|
||||
end
|
||||
join_none
|
||||
else $error("no");
|
||||
join_none else $error("no");
|
||||
wire w;
|
||||
endmodule
|
||||
====
|
||||
@@ -1,10 +1,10 @@
|
||||
# a bind directive is a module instantiation with a target scope in front
|
||||
module m;
|
||||
bind target_mod checker u_chk(.a(x),.b(y));
|
||||
bind target_mod chk_mod u_chk(.a(x),.b(y));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
bind target_mod checker u_chk (.a(x), .b(y));
|
||||
bind target_mod chk_mod u_chk (.a(x), .b(y));
|
||||
endmodule
|
||||
====
|
||||
# implicit named connections, target on its own line
|
||||
@@ -171,11 +171,11 @@ endmodule
|
||||
====
|
||||
# a hierarchical target path
|
||||
module m;
|
||||
bind top.u_dut.u_core checker u_chk(.*);
|
||||
bind top.u_dut.u_core chk_mod u_chk(.*);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
bind top.u_dut.u_core checker u_chk (.*);
|
||||
bind top.u_dut.u_core chk_mod u_chk (.*);
|
||||
endmodule
|
||||
====
|
||||
# a bind directive at top level, outside any module
|
||||
@@ -187,7 +187,7 @@ bind cpu cpu_assert u_cpu_assert (.clk_i, .rst_ni);
|
||||
module m;
|
||||
generate
|
||||
if (Enable) begin : g_chk
|
||||
bind sub checker u_chk(.*);
|
||||
bind sub chk_mod u_chk(.*);
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
@@ -195,7 +195,7 @@ endmodule
|
||||
module m;
|
||||
generate
|
||||
if (Enable) begin : g_chk
|
||||
bind sub checker u_chk (.*);
|
||||
bind sub chk_mod u_chk (.*);
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
@@ -203,7 +203,7 @@ endmodule
|
||||
# comments attached to a bind directive are kept
|
||||
module m;
|
||||
// bind the checker in
|
||||
bind dut checker u_chk (
|
||||
bind dut chk_mod u_chk (
|
||||
// clock and reset come in implicitly
|
||||
.clk_i,
|
||||
.rst_ni // active low
|
||||
@@ -212,7 +212,7 @@ endmodule
|
||||
----
|
||||
module m;
|
||||
// bind the checker in
|
||||
bind dut checker u_chk (
|
||||
bind dut chk_mod u_chk (
|
||||
// clock and reset come in implicitly
|
||||
.clk_i,
|
||||
.rst_ni // active low
|
||||
@@ -221,7 +221,7 @@ endmodule
|
||||
====
|
||||
# an `ifdef inside the connection list of a bind
|
||||
module m;
|
||||
bind dut checker u_chk (
|
||||
bind dut chk_mod u_chk (
|
||||
.clk_i,
|
||||
`ifdef FPV
|
||||
.fpv_only_i,
|
||||
@@ -231,7 +231,7 @@ module m;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
bind dut checker u_chk (
|
||||
bind dut chk_mod u_chk (
|
||||
.clk_i,
|
||||
`ifdef FPV
|
||||
.fpv_only_i,
|
||||
@@ -243,16 +243,16 @@ endmodule
|
||||
# a bind directive inside a `verilog_format: off` fence is untouched
|
||||
module m;
|
||||
// verilog_format: off
|
||||
bind dut checker u_chk ( .clk_i ,.rst_ni );
|
||||
bind dut chk_mod u_chk ( .clk_i ,.rst_ni );
|
||||
// verilog_format: on
|
||||
bind dut2 checker u_chk2 ( .clk_i ,.rst_ni );
|
||||
bind dut2 chk_mod u_chk2 ( .clk_i ,.rst_ni );
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// verilog_format: off
|
||||
bind dut checker u_chk ( .clk_i ,.rst_ni );
|
||||
bind dut chk_mod u_chk ( .clk_i ,.rst_ni );
|
||||
// verilog_format: on
|
||||
bind dut2 checker u_chk2 (.clk_i, .rst_ni);
|
||||
bind dut2 chk_mod u_chk2 (.clk_i, .rst_ni);
|
||||
endmodule
|
||||
====
|
||||
# at the line-length boundary: exactly 100 columns stays on one line
|
||||
@@ -317,3 +317,30 @@ module m;
|
||||
dut checker_mod c_inst (.clk(clk));
|
||||
endmodule
|
||||
====
|
||||
====
|
||||
# an indexed hierarchical target -- binding SVA into a generate array (coverage_gaps M6)
|
||||
module tb;
|
||||
bind top.gen[0].u_core chk c_inst (.clk(clk));
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
bind top.gen[0].u_core chk c_inst (.clk(clk));
|
||||
endmodule
|
||||
====
|
||||
# a selector on the head alone, with an expression inside it
|
||||
module tb;
|
||||
bind arr[N-1] chk c (.*);
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
bind arr[N-1] chk c (.*);
|
||||
endmodule
|
||||
====
|
||||
# an escaped segment keeps the whitespace that terminates it
|
||||
module tb;
|
||||
bind \my-inst .u_core chk c (.*);
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
bind \my-inst .u_core chk c (.*);
|
||||
endmodule
|
||||
@@ -189,7 +189,7 @@ function void dv_base_mem::set_enable(bit enable);
|
||||
this.enable = enable;
|
||||
endfunction
|
||||
====
|
||||
# a constraint block is reproduced byte for byte, only re-indented
|
||||
# a constraint block: one item per line, at one indent step inside the header
|
||||
class item;
|
||||
constraint c_branch_addr_alignment {
|
||||
// The branch address is always required to be half-word aligned.
|
||||
@@ -208,7 +208,7 @@ class item;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a constraint written at column 1 is re-indented into the class body
|
||||
# a constraint written at column 1 takes the class body's indent, body and all
|
||||
class item;
|
||||
constraint c_dist {
|
||||
num_insns dist { 0 :/ 5, [1:20] :/ 20, [21:100] :/ 1 };
|
||||
@@ -217,11 +217,12 @@ endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_dist {
|
||||
num_insns dist { 0 :/ 5, [1:20] :/ 20, [21:100] :/ 1 };
|
||||
num_insns dist {0 :/ 5, [1:20] :/ 20, [21:100] :/ 1};
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a covergroup is reproduced byte for byte too, endgroup label included
|
||||
# a covergroup is laid out canonically since the covergroup-bodies round: the
|
||||
# header on one line, one cover item per line, the endgroup label kept
|
||||
class cov;
|
||||
covergroup branch_dest_cg with function sample (bit [31:0] addr);
|
||||
coverpoint addr {
|
||||
@@ -232,10 +233,10 @@ class cov;
|
||||
endclass
|
||||
----
|
||||
class cov;
|
||||
covergroup branch_dest_cg with function sample (bit [31:0] addr);
|
||||
covergroup branch_dest_cg with function sample(bit [31:0] addr);
|
||||
coverpoint addr {
|
||||
bins zero = { 0 };
|
||||
bins mid = default;
|
||||
bins zero = {0};
|
||||
bins mid = default;
|
||||
}
|
||||
endgroup : branch_dest_cg
|
||||
endclass
|
||||
@@ -477,7 +478,7 @@ class c;
|
||||
constraint x;
|
||||
endclass
|
||||
====
|
||||
# a string inside a constraint keeps its bytes when the block is re-indented
|
||||
# a string inside a constraint keeps its bytes when the block is laid out
|
||||
class c;
|
||||
constraint x {
|
||||
name == "a
|
||||
@@ -487,9 +488,9 @@ endclass
|
||||
----
|
||||
class c;
|
||||
constraint x {
|
||||
name == "a
|
||||
name == "a
|
||||
b";
|
||||
}
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a shallow copy: `new <expression>` (IEEE 1800 8.12)
|
||||
|
||||
@@ -214,9 +214,7 @@ module m;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
FsmStateSwReset_A:
|
||||
assert property (rst |=> state == Reset)
|
||||
else `ASSERT_ERROR(FsmStateSwReset_A)
|
||||
FsmStateSwReset_A: assert property (rst |=> state == Reset) else `ASSERT_ERROR(FsmStateSwReset_A)
|
||||
assign x = 1;
|
||||
Other_A: assert property (c) else `uvm_error("a", "b");
|
||||
endmodule
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
# Every comment slot `docs/features/comment-slots/README.md` added, one case
|
||||
# per slot, with the comment written exactly where the slot owns it. The
|
||||
# numbers in the comments are positions, not content: `/*1*/` is the first
|
||||
# gap of the construct, `/*2*/` the second, and so on, so a comment that
|
||||
# drifts across a token shows up as a renumbering rather than as a diff you
|
||||
# have to squint at.
|
||||
#
|
||||
# A comment inside a bracket pair forces that pair open, which is why a few
|
||||
# of these lay out across several lines. That is the same rule a comment
|
||||
# inside a port list has always followed.
|
||||
|
||||
# a postfix member and scope chain, both gaps of each joiner
|
||||
module m;
|
||||
assign y = a /*1*/ . /*2*/ b;
|
||||
assign z = pkg /*3*/ :: /*4*/ item;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = a /*1*/ . /*2*/ b;
|
||||
assign z = pkg /*3*/ :: /*4*/ item;
|
||||
endmodule
|
||||
====
|
||||
# an index expression, all three of its slots
|
||||
module m;
|
||||
assign y = q /*1*/ [ /*2*/ i /*3*/ ];
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = q /*1*/ [ /*2*/ i /*3*/ ];
|
||||
endmodule
|
||||
====
|
||||
# a part-select range, all five of its slots
|
||||
module m;
|
||||
assign y = q /*1*/ [ /*2*/ hi /*3*/ : /*4*/ lo /*5*/ ];
|
||||
assign z = q[hi /*6*/ -: /*7*/ w];
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = q /*1*/ [ /*2*/ hi /*3*/ : /*4*/ lo /*5*/ ];
|
||||
assign z = q[hi /*6*/ -: /*7*/ w];
|
||||
endmodule
|
||||
====
|
||||
# a value range inside an `inside` set
|
||||
module m;
|
||||
assign y = a inside {[ /*1*/ 0 /*2*/ : /*3*/ 3 /*4*/ ], 7};
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = a inside {[ /*1*/ 0 /*2*/ : /*3*/ 3 /*4*/ ], 7};
|
||||
endmodule
|
||||
====
|
||||
# the `inside` operator keeps a comment on each of its sides
|
||||
module m;
|
||||
assign y = a /*1*/ inside /*2*/ {1, 2};
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = a /*1*/ inside /*2*/ {1, 2};
|
||||
endmodule
|
||||
====
|
||||
# a packed dimension's own five slots
|
||||
module m;
|
||||
logic /*1*/ [ /*2*/ 7 /*3*/ : /*4*/ 0 /*5*/ ] w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
logic /*1*/ [ /*2*/ 7 /*3*/ : /*4*/ 0 /*5*/ ] w;
|
||||
endmodule
|
||||
====
|
||||
# a dynamic and an associative dimension keep what stands between the brackets
|
||||
module m;
|
||||
int q[ /*1*/ ];
|
||||
int a[ /*2*/ * /*3*/ ];
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
int q [ /*1*/ ];
|
||||
int a [ /*2*/ * /*3*/ ];
|
||||
endmodule
|
||||
====
|
||||
# a statement's own `;` gap, every kind that owns one
|
||||
module m;
|
||||
initial begin
|
||||
x = 1 /*1*/ ;
|
||||
y <= 2 /*2*/ ;
|
||||
f(x) /*3*/ ;
|
||||
-> ev /*4*/ ;
|
||||
#10 /*5*/ ;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
x = 1 /*1*/ ;
|
||||
y <= 2 /*2*/ ;
|
||||
f(x) /*3*/ ;
|
||||
-> ev /*4*/ ;
|
||||
#10 /*5*/ ;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a `return`, a `break` and a `continue` keep the gap before their `;`
|
||||
class c;
|
||||
function int f();
|
||||
break /*1*/ ;
|
||||
continue /*2*/ ;
|
||||
return /*3*/ x /*4*/ ;
|
||||
endfunction
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
function int f();
|
||||
break /*1*/ ;
|
||||
continue /*2*/ ;
|
||||
return /*3*/ x /*4*/ ;
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
# a statement `if` header's keyword gap
|
||||
module m;
|
||||
initial if /*1*/ (a) x = 1;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial if /*1*/ (a) x = 1;
|
||||
endmodule
|
||||
====
|
||||
# a statement `case` header's keyword gap and a `default` label's colon
|
||||
module m;
|
||||
always_comb begin
|
||||
case /*1*/ (sel)
|
||||
2'd0: y = a;
|
||||
default /*2*/ : y = c;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
case /*1*/ (sel)
|
||||
2'd0: y = a;
|
||||
default /*2*/ : y = c;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a statement `foreach` header, all four of its slots
|
||||
module m;
|
||||
initial foreach /*1*/ ( /*2*/ q[i] /*3*/ ) q[i] = i;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial foreach /*1*/ ( /*2*/ q[i] /*3*/ ) q[i] = i;
|
||||
endmodule
|
||||
====
|
||||
# a `foreach` loop-variable list keeps a comment between two slots
|
||||
module m;
|
||||
initial foreach (q[i /*1*/ , /*2*/ j]) q[i][j] = 0;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial foreach (q[i /*1*/ , /*2*/ j]) q[i][j] = 0;
|
||||
endmodule
|
||||
====
|
||||
# a `for` header's seven slots
|
||||
module m;
|
||||
initial for /*1*/ ( /*2*/ int i = 0 /*3*/ ; /*4*/ i < N /*5*/ ; /*6*/ i++ /*7*/ ) x = i;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial for /*1*/ ( /*2*/ int i = 0 /*3*/ ; /*4*/ i < N /*5*/ ; /*6*/ i++ /*7*/ ) x = i;
|
||||
endmodule
|
||||
====
|
||||
# a generate `for` header and its block label
|
||||
module m;
|
||||
for /*1*/ (genvar /*2*/ i = 0; i < N; i /*3*/ ++) /*4*/ begin /*5*/ : /*6*/ g
|
||||
sub u (.a(a[i]));
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
for /*1*/ (genvar /*2*/ i = 0; i < N; i /*3*/ ++) /*4*/ begin /*5*/ : /*6*/ g
|
||||
sub u (.a(a[i]));
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a `do ... while` header, which has no body to hand a comment back to
|
||||
module m;
|
||||
initial do x = 1; while /*1*/ ( /*2*/ c /*3*/ );
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial
|
||||
do x = 1;
|
||||
while /*1*/ (
|
||||
/*2*/
|
||||
c /*3*/
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# an event control's `@`, its edge keyword and its parenthesis
|
||||
module m;
|
||||
always @ /*1*/ (posedge /*2*/ clk) q <= d;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @ /*1*/ (posedge /*2*/ clk) q <= d;
|
||||
endmodule
|
||||
====
|
||||
# a delay control's `#`
|
||||
module m;
|
||||
initial # /*1*/ 10 x = 1;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial # /*1*/ 10 x = 1;
|
||||
endmodule
|
||||
====
|
||||
# a unary and a postfix operator keep the gap beside them
|
||||
module m;
|
||||
assign y = ~ /*1*/ a;
|
||||
initial x = b /*2*/ ++;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = ~ /*1*/ a;
|
||||
initial x = b /*2*/ ++;
|
||||
endmodule
|
||||
====
|
||||
# a cast's four slots
|
||||
module m;
|
||||
assign y = state_t /*1*/ ' /*2*/ ( /*3*/ 0 /*4*/ );
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = state_t /*1*/ ' /*2*/ ( /*3*/ 0 /*4*/ );
|
||||
endmodule
|
||||
====
|
||||
# a module header: after the keyword, after the `#`, and before the `;`
|
||||
module /*1*/ m # /*2*/ (parameter int W = 8) (input logic clk) /*3*/ ;
|
||||
endmodule
|
||||
----
|
||||
module /*1*/ m # /*2*/ (parameter int W = 8) (input logic clk) /*3*/ ;
|
||||
endmodule
|
||||
====
|
||||
# a package header and its `endpackage` label
|
||||
package /*1*/ p /*2*/ ;
|
||||
endpackage /*3*/ : /*4*/ p
|
||||
----
|
||||
package /*1*/ p /*2*/ ;
|
||||
endpackage /*3*/ : /*4*/ p
|
||||
====
|
||||
# a class header, its qualifier run and its `endclass` label
|
||||
class c;
|
||||
local /*1*/ static /*2*/ int n;
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
local /*1*/ static /*2*/ int n;
|
||||
endclass
|
||||
====
|
||||
# a parameter port's four slots
|
||||
module m #(parameter /*1*/ int /*2*/ W /*3*/ = /*4*/ 8) ();
|
||||
endmodule
|
||||
----
|
||||
module m #(parameter /*1*/ int /*2*/ W /*3*/ = /*4*/ 8) ();
|
||||
endmodule
|
||||
====
|
||||
# an ANSI port's direction and name gaps
|
||||
module m (
|
||||
input /*1*/ logic [3:0] /*2*/ a
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (input /*1*/ logic [3:0] /*2*/ a);
|
||||
endmodule
|
||||
====
|
||||
# a `localparam` item's keyword and `=` gaps
|
||||
module m;
|
||||
localparam /*1*/ int N /*2*/ = /*3*/ 4;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam /*1*/ int N /*2*/ = /*3*/ 4;
|
||||
endmodule
|
||||
====
|
||||
# a continuous assignment's keyword and operator gaps
|
||||
module m;
|
||||
assign /*1*/ y /*2*/ = /*3*/ a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign /*1*/ y /*2*/ = /*3*/ a;
|
||||
endmodule
|
||||
====
|
||||
# a function header: keyword, return type, name, arguments and `;`
|
||||
class c;
|
||||
function /*1*/ void /*2*/ f /*3*/ ( /*4*/ ) /*5*/ ;
|
||||
endfunction
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
function /*1*/ void /*2*/ f /*3*/ (
|
||||
/*4*/
|
||||
) /*5*/ ;
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
# a task/function argument's direction, name and default gaps
|
||||
class c;
|
||||
function void f(input /*1*/ int /*2*/ n /*3*/ = /*4*/ 0);
|
||||
endfunction
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
function void f(input /*1*/ int /*2*/ n /*3*/ = /*4*/ 0);
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
# an out-of-body definition's scope chain
|
||||
class c;
|
||||
extern function void f();
|
||||
endclass
|
||||
function void c /*1*/ :: /*2*/ f();
|
||||
endfunction
|
||||
----
|
||||
class c;
|
||||
extern function void f();
|
||||
endclass
|
||||
function void c /*1*/ :: /*2*/ f();
|
||||
endfunction
|
||||
====
|
||||
# a typedef's keyword, name and `;` gaps, and a struct header's
|
||||
package p;
|
||||
typedef /*1*/ struct /*2*/ packed /*3*/ {
|
||||
logic a;
|
||||
} /*4*/ w_t /*5*/ ;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
typedef /*1*/ struct /*2*/ packed /*3*/ {
|
||||
logic a;
|
||||
} /*4*/ w_t /*5*/ ;
|
||||
endpackage
|
||||
====
|
||||
# an enum's keyword, base and brace gaps, and a member's `=`
|
||||
package p;
|
||||
typedef enum /*1*/ logic [1:0] /*2*/ {A /*3*/ = /*4*/ 2'd0, B} e_t;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
typedef enum /*1*/ logic [1:0] /*2*/ {A /*3*/ = /*4*/ 2'd0, B} e_t;
|
||||
endpackage
|
||||
====
|
||||
# an instantiation's `#`, its named connections and its `;`
|
||||
module m;
|
||||
sub # /*1*/ (.W(8)) u0 (. /*2*/ clk /*3*/ ( /*4*/ clk)) /*5*/ ;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub # /*1*/ (.W(8)) u0 (. /*2*/ clk /*3*/ ( /*4*/ clk)) /*5*/ ;
|
||||
endmodule
|
||||
====
|
||||
# a `begin : label` and its `end : label`
|
||||
module m;
|
||||
initial begin /*1*/ : /*2*/ blk
|
||||
x = 1;
|
||||
end /*3*/ : /*4*/ blk
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin /*1*/ : /*2*/ blk
|
||||
x = 1;
|
||||
end /*3*/ : /*4*/ blk
|
||||
endmodule
|
||||
====
|
||||
# a `fork` label and a `join` label
|
||||
module m;
|
||||
initial fork /*1*/ : /*2*/ f
|
||||
x = 1;
|
||||
join /*3*/ : /*4*/ f
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial
|
||||
fork /*1*/ : /*2*/ f
|
||||
x = 1;
|
||||
join /*3*/ : /*4*/ f
|
||||
endmodule
|
||||
====
|
||||
# a covergroup's qualifier run and its `endgroup` label
|
||||
class c;
|
||||
local /*1*/ covergroup cg;
|
||||
cp: coverpoint a;
|
||||
endgroup /*2*/ : /*3*/ cg
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
local /*1*/ covergroup cg;
|
||||
cp: coverpoint a;
|
||||
endgroup /*2*/ : /*3*/ cg
|
||||
endclass
|
||||
====
|
||||
# a constraint's out-of-body scope and its qualifier run
|
||||
class c;
|
||||
static /*1*/ constraint c1 {
|
||||
a < 5;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
static /*1*/ constraint c1 {
|
||||
a < 5;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# every escaped segment of a scoped type name keeps its terminator
|
||||
module m;
|
||||
\my-pkg ::\state-t \st ;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
\my-pkg ::\state-t \st ;
|
||||
endmodule
|
||||
@@ -0,0 +1,652 @@
|
||||
# Constraint bodies (IEEE 1800 §18.5) — the canonical layout the
|
||||
# constraint-bodies round introduced. See
|
||||
# docs/features/constraint-bodies/README.md.
|
||||
#
|
||||
# A named constraint is a block and is laid out like one: the header keeps
|
||||
# the `{`, one constraint item per line at one further indent, and the `}`
|
||||
# closes at the header's column. A body the grammar does not recognise
|
||||
# rewinds to the byte-for-byte verbatim capture constraints had before this
|
||||
# round; a `randomize() with { ... }` block may stay on the statement's line
|
||||
# when it holds one item and nothing inside it forces a break.
|
||||
|
||||
# a constraint block: one item per line, indented one step, `}` at the header's column
|
||||
class item;
|
||||
constraint c_len {
|
||||
len > 0;
|
||||
len < 64;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_len {
|
||||
len > 0;
|
||||
len < 64;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# an empty constraint body
|
||||
class item;
|
||||
constraint c_none { }
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_none {}
|
||||
endclass
|
||||
====
|
||||
# a constraint prototype, and its `extern`/`pure static` spellings
|
||||
class item;
|
||||
constraint c_a;
|
||||
extern constraint c_b;
|
||||
pure static constraint c_c;
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_a;
|
||||
extern constraint c_b;
|
||||
pure static constraint c_c;
|
||||
endclass
|
||||
====
|
||||
# a stray `;` after the closing brace is reproduced
|
||||
class item;
|
||||
constraint c { a == 0; };
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
a == 0;
|
||||
};
|
||||
endclass
|
||||
====
|
||||
# soft constraints and a `dist` set, both weight operators kept apart
|
||||
class item;
|
||||
constraint c_dist {
|
||||
soft len dist { 0 := 5, [1:20] :/ 20, [21:100] :/ 1 };
|
||||
kind dist { READ := 1, WRITE := 1 };
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_dist {
|
||||
soft len dist {0 := 5, [1:20] :/ 20, [21:100] :/ 1};
|
||||
kind dist {READ := 1, WRITE := 1};
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a long dist set breaks one weight per line
|
||||
class item;
|
||||
constraint c_dist {
|
||||
delay dist { 0 := 500, [1:16] := 200, [17:64] := 100, [65:256] := 50, [257:1024] := 10, [1025:4096] := 1 };
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_dist {
|
||||
delay dist {
|
||||
0 := 500,
|
||||
[1:16] := 200,
|
||||
[17:64] := 100,
|
||||
[65:256] := 50,
|
||||
[257:1024] := 10,
|
||||
[1025:4096] := 1
|
||||
};
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a dist item with no weight at all
|
||||
class item;
|
||||
constraint c { a dist { 0, 1, [2:3] }; }
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
a dist {0, 1, [2:3]};
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# `inside` and `!` and index expressions inside a constraint
|
||||
class item;
|
||||
constraint c_align {
|
||||
// The branch address is always required to be half-word aligned.
|
||||
!addr[0];
|
||||
addr inside {[0:255], 512};
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_align {
|
||||
// The branch address is always required to be half-word aligned.
|
||||
!addr[0];
|
||||
addr inside {[0:255], 512};
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# an implication with a braced set, and one with a bare item
|
||||
class item;
|
||||
constraint c_impl {
|
||||
(kind != Branch) -> addr == 0;
|
||||
kind == Branch -> { addr[1:0] == 0; addr < 1024; }
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_impl {
|
||||
(kind != Branch) -> addr == 0;
|
||||
kind == Branch -> {
|
||||
addr[1:0] == 0;
|
||||
addr < 1024;
|
||||
}
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# `<->` is an operator, not an implication
|
||||
class item;
|
||||
constraint c { a <-> b; }
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
a <-> b;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a constraint if/else-if chain, braced and bare
|
||||
class item;
|
||||
constraint c_if {
|
||||
if (mode == 0) len == 1;
|
||||
else if (mode == 1) { len == 2; kind == READ; }
|
||||
else len == 3;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_if {
|
||||
if (mode == 0) len == 1;
|
||||
else if (mode == 1) {
|
||||
len == 2;
|
||||
kind == READ;
|
||||
} else len == 3;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a constraint foreach, including a skipped dimension
|
||||
class item;
|
||||
constraint c_each {
|
||||
foreach (data[i]) data[i] < 256;
|
||||
foreach (grid[, j]) { grid[j] inside {0, 1}; }
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_each {
|
||||
foreach (data[i]) data[i] < 256;
|
||||
foreach (grid[, j]) {
|
||||
grid[j] inside {0, 1};
|
||||
}
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# solve ... before, with lists on both sides
|
||||
class item;
|
||||
constraint c_order { solve kind, mode before len, addr; }
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_order {
|
||||
solve kind, mode before len, addr;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# unique and disable soft
|
||||
class item;
|
||||
constraint c_u {
|
||||
unique {a, b, c};
|
||||
disable soft len;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_u {
|
||||
unique {a, b, c};
|
||||
disable soft len;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a null constraint item is its own `;`
|
||||
class item;
|
||||
constraint c {
|
||||
a == 0;
|
||||
;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
a == 0;
|
||||
;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# comments in every slot of a constraint body
|
||||
class item;
|
||||
// why this constraint exists
|
||||
constraint c { // opening
|
||||
// before the item
|
||||
a == 0; // after the item
|
||||
b == 1;
|
||||
// before the closing brace
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
// why this constraint exists
|
||||
constraint c {
|
||||
// opening
|
||||
// before the item
|
||||
a == 0; // after the item
|
||||
b == 1;
|
||||
// before the closing brace
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a blank line between constraint items is kept
|
||||
class item;
|
||||
constraint c {
|
||||
a == 0;
|
||||
|
||||
b == 1;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
a == 0;
|
||||
|
||||
b == 1;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# an `ifdef inside a constraint body keeps both arms as ordinary items
|
||||
class item;
|
||||
constraint c {
|
||||
`ifdef FAST
|
||||
len < 4;
|
||||
`else
|
||||
len < 64;
|
||||
`endif
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
`ifdef FAST
|
||||
len < 4;
|
||||
`else
|
||||
len < 64;
|
||||
`endif
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a constraint written at column 1 is re-indented into the class body
|
||||
class item;
|
||||
constraint c_dist {
|
||||
num_insns dist { 0 :/ 5, [1:20] :/ 20, [21:100] :/ 1 };
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c_dist {
|
||||
num_insns dist {0 :/ 5, [1:20] :/ 20, [21:100] :/ 1};
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a body the grammar does not know falls back to the byte-for-byte capture
|
||||
class item;
|
||||
constraint c {
|
||||
`MY_CONSTRAINT_HALF
|
||||
len < 4;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
`MY_CONSTRAINT_HALF
|
||||
len < 4;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a nested implication inside a foreach inside an if
|
||||
class item;
|
||||
constraint c {
|
||||
if (enable) {
|
||||
foreach (q[i]) {
|
||||
q[i] > 0 -> { q[i] < 100; }
|
||||
}
|
||||
}
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
if (enable) {
|
||||
foreach (q[i]) {
|
||||
q[i] > 0 -> {
|
||||
q[i] < 100;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a randomize() with block stays on the statement line when it fits
|
||||
module m;
|
||||
initial begin
|
||||
if (!req.randomize() with { addr == 0; }) $fatal(1, "no");
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
if (!req.randomize() with {addr == 0;}) $fatal(1, "no");
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a randomize() with block of several items breaks like a constraint body
|
||||
module m;
|
||||
initial begin
|
||||
void'(std::randomize(x, y) with { x > 3; y < x; });
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
void'(std::randomize(x, y) with {
|
||||
x > 3;
|
||||
y < x;
|
||||
});
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a with block the grammar does not know keeps its bytes
|
||||
module m;
|
||||
initial begin
|
||||
void'(std::randomize(x) with { `MY_HALF x > 3; });
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
void'(std::randomize(x) with { `MY_HALF x > 3; });
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a with block carrying a comment breaks so the `}` cannot be swallowed
|
||||
module m;
|
||||
initial begin
|
||||
void'(std::randomize(x) with { x > 3; // at least four
|
||||
});
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
void'(std::randomize(x) with {
|
||||
x > 3; // at least four
|
||||
});
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a constraint carrying a multi-line string leaves the string's bytes alone
|
||||
class item;
|
||||
constraint c {
|
||||
n == "a
|
||||
b";
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
n == "a
|
||||
b";
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# an escaped identifier as a constraint name, and inside the body
|
||||
class item;
|
||||
constraint \c-1 {
|
||||
\a-1 == 0;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint \c-1 {
|
||||
\a-1 == 0;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a very long constraint expression wraps like any other expression
|
||||
class item;
|
||||
constraint c {
|
||||
a_very_long_signal_name + another_long_signal_name + a_third_long_signal_name == 0;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
a_very_long_signal_name + another_long_signal_name + a_third_long_signal_name == 0;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# ----------------------------------------------------------------------
|
||||
# Comment slots (the 2026-09-02 rework). Every keyword and punctuation
|
||||
# position this round introduced owns the comments written in front of it,
|
||||
# so none of them drifts across a token and `format_source` never has to
|
||||
# refuse the file. Each case is asserted for output *and* idempotency.
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
# a comment after `soft` prints between `soft` and the expression
|
||||
class item;
|
||||
constraint c {
|
||||
soft /* pick one */ len < 5;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
soft /* pick one */ len < 5;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# comments on both sides of `dist`, and on both sides of each weight operator
|
||||
class item;
|
||||
constraint c {
|
||||
len /* the field */ dist /* the set */ { 0 /* zero */ := /* five */ 5, [1:3] :/ /* two */ 2 };
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
len /* the field */ dist /* the set */ {0 /* zero */ := /* five */ 5, [1:3] :/ /* two */ 2};
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# comments on both sides of the `soft` of a `disable soft`
|
||||
class item;
|
||||
constraint c {
|
||||
disable /* off */ soft /* the soft one */ len;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
disable /* off */ soft /* the soft one */ len;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a comment before `before`, and one after it, in a solve list
|
||||
class item;
|
||||
constraint c {
|
||||
solve kind /* first */ before /* then */ len;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
solve kind /* first */ before /* then */ len;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a comment between `unique` and its set
|
||||
class item;
|
||||
constraint c {
|
||||
unique /* all four */ {a, b, c, d};
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
unique /* all four */ {a, b, c, d};
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# comments in the constraint header: after the keyword, and before the `{`
|
||||
class item;
|
||||
constraint /* the name */ c_len /* the body */ {
|
||||
len < 5;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint /* the name */ c_len /* the body */ {
|
||||
len < 5;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# the same two slots on a prototype and on an out-of-block definition
|
||||
class item;
|
||||
extern constraint /* named */ c_len /* nothing follows */ ;
|
||||
endclass
|
||||
|
||||
constraint item::c_len /* out of block */ {
|
||||
len < 5;
|
||||
} /* and a stray semicolon */ ;
|
||||
----
|
||||
class item;
|
||||
extern constraint /* named */ c_len /* nothing follows */;
|
||||
endclass
|
||||
|
||||
constraint item::c_len /* out of block */ {
|
||||
len < 5;
|
||||
} /* and a stray semicolon */;
|
||||
====
|
||||
# a comment written in front of the item's own `;` stays on the item's side
|
||||
class item;
|
||||
constraint c {
|
||||
len < 5 /* inclusive */ ;
|
||||
unique {a, b} /* distinct */ ;
|
||||
disable soft len /* not this one */ ;
|
||||
solve a before b /* in that order */ ;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
len < 5 /* inclusive */;
|
||||
unique {a, b} /* distinct */;
|
||||
disable soft len /* not this one */;
|
||||
solve a before b /* in that order */;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a line comment in front of the `;` forces the break the comment demands
|
||||
class item;
|
||||
constraint c {
|
||||
len < 5 // inclusive
|
||||
;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
len < 5 // inclusive
|
||||
;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# every slot of a constraint `if` header, and the one after `else`
|
||||
class item;
|
||||
constraint c {
|
||||
if /* test */ ( /* the mode */ mode == 0 /* only zero */ ) /* then */ {
|
||||
len == 1;
|
||||
} else /* otherwise */ {
|
||||
len == 2;
|
||||
}
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
if /* test */ (
|
||||
/* the mode */
|
||||
mode == 0 /* only zero */
|
||||
) /* then */ {
|
||||
len == 1;
|
||||
} else /* otherwise */ {
|
||||
len == 2;
|
||||
}
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# the `foreach` header's slots: after the keyword, inside the `(`, before the `)`, before the body
|
||||
class item;
|
||||
constraint c {
|
||||
foreach /* each */ ( /* the array */ data[i] /* done */ ) /* then */ {
|
||||
data[i] < 4;
|
||||
}
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
foreach /* each */ ( /* the array */ data[i] /* done */ ) /* then */ {
|
||||
data[i] < 4;
|
||||
}
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# a comment after the `->` of an implication, and after an `else if`
|
||||
class item;
|
||||
constraint c {
|
||||
m -> /* then */ { a == 1; }
|
||||
if (m) a == 1;
|
||||
else /* chained */ if (n) a == 2;
|
||||
}
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
constraint c {
|
||||
m -> /* then */ {
|
||||
a == 1;
|
||||
}
|
||||
if (m) a == 1;
|
||||
else /* chained */ if (n) a == 2;
|
||||
}
|
||||
endclass
|
||||
====
|
||||
# the same slots inside a randomize() with block
|
||||
module m;
|
||||
initial begin
|
||||
void'(req.randomize() with {
|
||||
soft /* pick */ addr dist /* set */ { 0 := 5 };
|
||||
addr < 9 /* inclusive */ ;
|
||||
});
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
void'(req.randomize() with {
|
||||
soft /* pick */ addr dist /* set */ {0 := 5};
|
||||
addr < 9 /* inclusive */;
|
||||
});
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,616 @@
|
||||
# Covergroup bodies (IEEE 1800 §19) — the canonical layout the
|
||||
# covergroup-bodies round introduced. See
|
||||
# docs/features/covergroup-bodies/README.md.
|
||||
#
|
||||
# A covergroup is a block and is laid out like one: the whole header on the
|
||||
# header line, one cover item per line at one further indent, and `endgroup`
|
||||
# back at the header's column with whatever label the source wrote. A
|
||||
# coverpoint or cross body is laid out like a constraint set, one bin per
|
||||
# line. A covergroup the grammar does not recognise rewinds to the
|
||||
# byte-for-byte verbatim capture covergroups had before this round.
|
||||
|
||||
# a covergroup is a block: the header on one line, one cover item per line,
|
||||
# `endgroup` back at the header's column
|
||||
class cov;
|
||||
covergroup cg;
|
||||
coverpoint addr;
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class cov;
|
||||
covergroup cg;
|
||||
coverpoint addr;
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# the whole header on one line: formals, the sample function, the end label
|
||||
class cov;
|
||||
covergroup cg (bit [3:0] a, int n) with function sample (bit [31:0] addr, bit rw);
|
||||
cp_addr : coverpoint addr {
|
||||
bins lo = { [0:9] };
|
||||
bins hi = {[10:$]};
|
||||
}
|
||||
endgroup : cg
|
||||
endclass
|
||||
----
|
||||
class cov;
|
||||
covergroup cg(bit [3:0] a, int n) with function sample(bit [31:0] addr, bit rw);
|
||||
cp_addr: coverpoint addr {
|
||||
bins lo = {[0:9]};
|
||||
bins hi = {[10:$]};
|
||||
}
|
||||
endgroup : cg
|
||||
endclass
|
||||
====
|
||||
# a clocking event header, and the option assignments a covergroup body may hold
|
||||
module m;
|
||||
covergroup cg @(posedge clk);
|
||||
option.per_instance = 1;
|
||||
option.name = "cg";
|
||||
type_option.weight = 5;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
covergroup cg @(posedge clk);
|
||||
option.per_instance = 1;
|
||||
option.name = "cg";
|
||||
type_option.weight = 5;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
endmodule
|
||||
====
|
||||
# every bin shape: wildcard, the three keywords, defaults, transitions with
|
||||
# their three repetitions, a `with` filter and a per-bin `iff`
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp : coverpoint a iff (en) {
|
||||
wildcard bins w[4] = {4'b1??1};
|
||||
ignore_bins ig = {2, 3};
|
||||
illegal_bins bad = default;
|
||||
bins seq = default sequence;
|
||||
bins t = (0 => 1, 2 => 3), (4 => 5);
|
||||
bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]);
|
||||
bins e[] = cp_x with (item % 2 == 0);
|
||||
bins v = {[0:$]} with ($countones(item) != 1);
|
||||
bins g = {1} iff (en);
|
||||
}
|
||||
endgroup : cg
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a iff (en) {
|
||||
wildcard bins w[4] = {4'b1??1};
|
||||
ignore_bins ig = {2, 3};
|
||||
illegal_bins bad = default;
|
||||
bins seq = default sequence;
|
||||
bins t = (0 => 1, 2 => 3), (4 => 5);
|
||||
bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]);
|
||||
bins e[] = cp_x with (item % 2 == 0);
|
||||
bins v = {[0:$]} with ($countones(item) != 1);
|
||||
bins g = {1} iff (en);
|
||||
}
|
||||
endgroup : cg
|
||||
endclass
|
||||
====
|
||||
# a cross body: `binsof ... intersect`, the boolean operators, a nested paren
|
||||
class c;
|
||||
covergroup cg;
|
||||
cr : cross cp_a, cp_b {
|
||||
bins sel = binsof(cp_a.x) intersect {0, [1:2]} && !binsof(cp_b);
|
||||
bins two = (binsof(cp_a) || binsof(cp_b)) && binsof(cp_c) intersect {1};
|
||||
option.weight = 0;
|
||||
}
|
||||
endgroup : cg
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cr: cross cp_a, cp_b {
|
||||
bins sel = binsof(cp_a.x) intersect {0, [1:2]} && !binsof(cp_b);
|
||||
bins two = (binsof(cp_a) || binsof(cp_b)) && binsof(cp_c) intersect {1};
|
||||
option.weight = 0;
|
||||
}
|
||||
endgroup : cg
|
||||
endclass
|
||||
====
|
||||
# an empty body prints `{}`, a null item and a stray `;` after `endgroup` are
|
||||
# both reproduced
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
}
|
||||
cr: cross a, b;
|
||||
;
|
||||
endgroup;
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {}
|
||||
cr: cross a, b;
|
||||
;
|
||||
endgroup;
|
||||
endclass
|
||||
====
|
||||
# every header and bin comment slot prints back where it was written
|
||||
class c;
|
||||
covergroup /*a*/ cg /*b*/ (int n) /*c*/ with /*d*/ function /*e*/ sample /*f*/ (int x) /*g*/ ;
|
||||
cp /*h*/ : /*i*/ coverpoint /*j*/ x /*k*/ iff /*l*/ ( /*m*/ en /*n*/ ) /*o*/ {
|
||||
wildcard /*p*/ bins /*q*/ v /*r*/ [ /*s*/ 4 /*t*/ ] /*u*/ = /*v*/ {1} /*w*/ with /*x*/ ( /*y*/ item /*z*/ ) /*A*/ iff /*B*/ ( /*C*/ en /*D*/ ) /*E*/ ;
|
||||
}
|
||||
endgroup : cg /*F*/ ;
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup /*a*/ cg /*b*/ (int n) /*c*/ with /*d*/ function /*e*/ sample /*f*/ (int x) /*g*/;
|
||||
cp /*h*/: /*i*/ coverpoint /*j*/ x /*k*/ iff /*l*/ (
|
||||
/*m*/
|
||||
en /*n*/
|
||||
) /*o*/ {
|
||||
wildcard /*p*/ bins /*q*/ v /*r*/ [ /*s*/ 4 /*t*/ ] /*u*/ = /*v*/ {1} /*w*/ with /*x*/ (
|
||||
/*y*/
|
||||
item /*z*/
|
||||
) /*A*/ iff /*B*/ (
|
||||
/*C*/
|
||||
en /*D*/
|
||||
) /*E*/;
|
||||
}
|
||||
endgroup : cg /*F*/;
|
||||
endclass
|
||||
====
|
||||
# leading, trailing and dangling comments in a covergroup body
|
||||
class c;
|
||||
covergroup cg;
|
||||
// a leading comment
|
||||
cp: coverpoint a { // trailing
|
||||
// inside
|
||||
bins v = {1}; // after
|
||||
// dangling
|
||||
}
|
||||
|
||||
cr: cross a, b;
|
||||
// last
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
// a leading comment
|
||||
cp: coverpoint a {
|
||||
// trailing
|
||||
// inside
|
||||
bins v = {1}; // after
|
||||
// dangling
|
||||
}
|
||||
|
||||
cr: cross a, b;
|
||||
// last
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# both arms of an `ifdef stand as ordinary cover items
|
||||
class c;
|
||||
covergroup cg;
|
||||
`ifdef FOO
|
||||
cp: coverpoint a;
|
||||
`else
|
||||
cp: coverpoint b;
|
||||
`endif
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
`ifdef FOO
|
||||
cp: coverpoint a;
|
||||
`else
|
||||
cp: coverpoint b;
|
||||
`endif
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a long sample-function list breaks like a port list; a long value list breaks
|
||||
# like every other braced list
|
||||
class c;
|
||||
covergroup cg_with_a_really_long_name_here with function sample (bit [31:0] address_value, bit read_write_flag, int unsigned index);
|
||||
cp: coverpoint address_value {
|
||||
bins many = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg_with_a_really_long_name_here with function sample(
|
||||
bit [31:0] address_value,
|
||||
bit read_write_flag,
|
||||
int unsigned index
|
||||
);
|
||||
cp: coverpoint address_value {
|
||||
bins many = {
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8,
|
||||
9,
|
||||
10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
14,
|
||||
15,
|
||||
16,
|
||||
17,
|
||||
18,
|
||||
19,
|
||||
20,
|
||||
21,
|
||||
22
|
||||
};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a macro supplying a coverpoint's whole bin body rewinds to the byte-for-byte
|
||||
# verbatim capture covergroups had before this round
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a `GPR_BIN_TYPES
|
||||
endgroup : cg
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a `GPR_BIN_TYPES
|
||||
endgroup : cg
|
||||
endclass
|
||||
====
|
||||
# a macro standing where a cover item belongs is passed through, the way one
|
||||
# standing where an item or a statement belongs is
|
||||
class c;
|
||||
covergroup cg;
|
||||
`MY_CP(a, b)
|
||||
cp: coverpoint a;
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
`MY_CP(a, b)
|
||||
cp: coverpoint a;
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a covergroup at package scope
|
||||
package p;
|
||||
covergroup cg;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
covergroup cg;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
endpackage
|
||||
====
|
||||
# the member qualifiers a covergroup may carry
|
||||
class c;
|
||||
local covergroup cg;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
static covergroup cg2;
|
||||
coverpoint y;
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
local covergroup cg;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
static covergroup cg2;
|
||||
coverpoint y;
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# every name goes through `name_doc`: an escaped identifier keeps its
|
||||
# terminating space
|
||||
class c;
|
||||
covergroup \cg-1 ;
|
||||
\cp-1 : coverpoint \a-1 {
|
||||
bins \b-1 = {1};
|
||||
}
|
||||
endgroup : \cg-1
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup \cg-1 ;
|
||||
\cp-1 : coverpoint \a-1 {
|
||||
bins \b-1 = {1};
|
||||
}
|
||||
endgroup : \cg-1
|
||||
endclass
|
||||
====
|
||||
# a covergroup with no items at all
|
||||
class c;
|
||||
covergroup cg;
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a blank line between two cover items is kept
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp1: coverpoint a;
|
||||
|
||||
cp2: coverpoint b;
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp1: coverpoint a;
|
||||
|
||||
cp2: coverpoint b;
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# the unsized `[]` array spelling, on both a value and a default bin
|
||||
class c;
|
||||
covergroup cg with function sample(bit a);
|
||||
cp: coverpoint a {
|
||||
bins v[] = {[0:$]};
|
||||
bins w[] = default;
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg with function sample(bit a);
|
||||
cp: coverpoint a {
|
||||
bins v[] = {[0:$]};
|
||||
bins w[] = default;
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a bare `@ev` event keeps its lack of parentheses; an `or` list keeps its
|
||||
# spelling
|
||||
module m;
|
||||
covergroup cg @ev;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
covergroup cg2 @(a or b);
|
||||
coverpoint y;
|
||||
endgroup
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
covergroup cg @ev;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
covergroup cg2 @(a or b);
|
||||
coverpoint y;
|
||||
endgroup
|
||||
endmodule
|
||||
====
|
||||
# a concatenation as the sampled expression, and an `iff` guard on it
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint {a, b, (c != d)} iff (!rst) {
|
||||
bins z = {0};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint {a, b, (c != d)} iff (!rst) {
|
||||
bins z = {0};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a `{` written on its own line cuddles onto the header
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a
|
||||
{
|
||||
bins v = {1};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins v = {1};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a covergroup whose `endgroup` label is missing keeps none
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a;
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a;
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# `option` and `type_option` inside a coverpoint body, beside its bins
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
option.weight = 3;
|
||||
type_option.merge_instances = 1;
|
||||
bins v = {1};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
option.weight = 3;
|
||||
type_option.merge_instances = 1;
|
||||
bins v = {1};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# an unlabelled coverpoint and an unlabelled cross
|
||||
class c;
|
||||
covergroup cg;
|
||||
coverpoint a;
|
||||
cross a, b;
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
coverpoint a;
|
||||
cross a, b;
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a transition bin whose ranges carry value ranges of their own
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins any2any[] = ([None:Bidir] => [None:Bidir]);
|
||||
bins two = (Read, Write => RStart);
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins any2any[] = ([None:Bidir] => [None:Bidir]);
|
||||
bins two = (Read, Write => RStart);
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a scope-qualified name in a bin value and in a `with` filter
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins on = {lc_ctrl_pkg::On};
|
||||
bins bad = {[0:$]} with (!(item inside {lc_ctrl_pkg::Off, lc_ctrl_pkg::On}));
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins on = {lc_ctrl_pkg::On};
|
||||
bins bad = {[0:$]} with (!(item inside {lc_ctrl_pkg::Off, lc_ctrl_pkg::On}));
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a covergroup nested in a class that also carries a constraint: both bodies
|
||||
# are laid out, and neither reaches into the other
|
||||
class item;
|
||||
rand int addr;
|
||||
constraint c_addr { addr < 64; }
|
||||
covergroup cg_addr with function sample (int a);
|
||||
cp: coverpoint a { bins lo = {[0:31]}; }
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class item;
|
||||
rand int addr;
|
||||
constraint c_addr {
|
||||
addr < 64;
|
||||
}
|
||||
covergroup cg_addr with function sample(int a);
|
||||
cp: coverpoint a {
|
||||
bins lo = {[0:31]};
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a comment written where the `;` of an item was not written belongs to the
|
||||
# item that follows it
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint x {
|
||||
}
|
||||
// why
|
||||
cr: cross a, b;
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint x {}
|
||||
// why
|
||||
cr: cross a, b;
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a coverpoint bin's `( ... )` is a transition list even with no arrow; a
|
||||
# cross bin's is a parenthesized select expression
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins zero_delay_5 = (1'b1[*5]);
|
||||
bins stall_long = (1'b0[*5:10] => 1'b1);
|
||||
}
|
||||
cr: cross a, b {
|
||||
bins any = (binsof(a) || binsof(b)) && !binsof(c);
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins zero_delay_5 = (1'b1[*5]);
|
||||
bins stall_long = (1'b0[*5:10] => 1'b1);
|
||||
}
|
||||
cr: cross a, b {
|
||||
bins any = (binsof(a) || binsof(b)) && !binsof(c);
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
# a call may stand as a bin spec, and a concatenation may stand as a
|
||||
# transition item
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins single_exc[] = single_masks(num_hw_apps);
|
||||
bins req_before_done = ({1'b1, pkg::False} => {1'b1, pkg::True});
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
covergroup cg;
|
||||
cp: coverpoint a {
|
||||
bins single_exc[] = single_masks(num_hw_apps);
|
||||
bins req_before_done = ({1'b1, pkg::False} => {1'b1, pkg::True});
|
||||
}
|
||||
endgroup
|
||||
endclass
|
||||
====
|
||||
@@ -63,8 +63,9 @@ class c;
|
||||
endclass
|
||||
====
|
||||
# a region between the elements of a concatenation, three brackets deep inside
|
||||
# an instantiation's parameter override -- the whole instantiation becomes the
|
||||
# block, ending at its `;`
|
||||
# an instantiation's parameter override. Since TODO 26 only the ONE override
|
||||
# value is verbatim -- the instantiation itself is structural again, so the
|
||||
# lists around the region are laid out canonically
|
||||
# hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621
|
||||
module chip;
|
||||
padring #(
|
||||
@@ -86,19 +87,16 @@ endmodule
|
||||
----
|
||||
module chip;
|
||||
padring #(
|
||||
.DioPadType ({
|
||||
.DioPadType({
|
||||
AnalogIn0, // RRAM_ANALOG
|
||||
`ifdef ANALOGSIM
|
||||
`ifdef ANALOGSIM
|
||||
'0,
|
||||
`else
|
||||
`else
|
||||
CC2,
|
||||
`endif
|
||||
`endif
|
||||
DualBidirTol // USB_N
|
||||
})
|
||||
) u_padring (
|
||||
.clk_scan_i(ast_base_clks.clk_sys),
|
||||
.scanmode_i(scanmode)
|
||||
);
|
||||
) u_padring (.clk_scan_i(ast_base_clks.clk_sys), .scanmode_i(scanmode));
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
|
||||
@@ -250,8 +250,8 @@ wire a;
|
||||
`endif
|
||||
int x [] = {1};
|
||||
====
|
||||
# over-suppression guard: directives written inside an opaque `constraint`
|
||||
# body no longer touch item-scope nesting, but the region around the body
|
||||
# over-suppression guard: directives written inside a `constraint` body are
|
||||
# constraint items, not item-scope nesting, but the region around the body
|
||||
# still counts, so a genuine split after it still recovers
|
||||
class c;
|
||||
constraint co {
|
||||
@@ -272,9 +272,9 @@ parameter int AFTER = 1;
|
||||
----
|
||||
class c;
|
||||
constraint co {
|
||||
`ifdef X
|
||||
`ifdef X
|
||||
x < 10;
|
||||
`endif
|
||||
`endif
|
||||
}
|
||||
endclass
|
||||
|
||||
@@ -287,8 +287,8 @@ const int y[] = {
|
||||
};
|
||||
parameter int AFTER = 1;
|
||||
====
|
||||
# under-suppression guard: an earlier verbatim item (a constraint) inside the
|
||||
# very region the split sits in -- the outer `ifdef must still be counted
|
||||
# under-suppression guard: an earlier constraint item inside the very region
|
||||
# the split sits in -- the outer `ifdef must still be counted
|
||||
`ifdef OUTER
|
||||
class c;
|
||||
constraint co {x < 10;}
|
||||
@@ -306,7 +306,9 @@ parameter int AFTER = 1;
|
||||
----
|
||||
`ifdef OUTER
|
||||
class c;
|
||||
constraint co {x < 10;}
|
||||
constraint co {
|
||||
x < 10;
|
||||
}
|
||||
endclass
|
||||
|
||||
`ifdef DSIM
|
||||
|
||||
@@ -852,3 +852,81 @@ module m;
|
||||
.b(y)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# a conditional directive inside a connection's VALUE: the value alone is verbatim, the instantiation is not
|
||||
module m;
|
||||
sub u_sub (
|
||||
.a(
|
||||
`ifdef X
|
||||
foo
|
||||
`else
|
||||
bar
|
||||
`endif
|
||||
),
|
||||
.b(b)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u_sub (
|
||||
.a(
|
||||
`ifdef X
|
||||
foo
|
||||
`else
|
||||
bar
|
||||
`endif
|
||||
),
|
||||
.b(b)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# the same inside a concatenation, the shape opentitan writes: the `)` follows the `}` on its line
|
||||
module m;
|
||||
sub u_sub (.pads({
|
||||
A,
|
||||
`ifdef X
|
||||
B,
|
||||
`else
|
||||
C,
|
||||
`endif
|
||||
D
|
||||
}), .b(b));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u_sub (
|
||||
.pads({
|
||||
A,
|
||||
`ifdef X
|
||||
B,
|
||||
`else
|
||||
C,
|
||||
`endif
|
||||
D
|
||||
}),
|
||||
.b(b)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# and in a parameter override value
|
||||
module m;
|
||||
sub #(.P(
|
||||
`ifdef X
|
||||
1
|
||||
`else
|
||||
2
|
||||
`endif
|
||||
)) u_sub (.a(a));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub #(
|
||||
.P(
|
||||
`ifdef X
|
||||
1
|
||||
`else
|
||||
2
|
||||
`endif
|
||||
)
|
||||
) u_sub (.a(a));
|
||||
endmodule
|
||||
@@ -280,3 +280,40 @@ import "DPI-C" function void f(input int a);
|
||||
export "DPI-C" function g;
|
||||
export p::*;
|
||||
====
|
||||
====
|
||||
# an imported prototype's formals may name only their types
|
||||
# IEEE 1800-2017 35.5.5
|
||||
package p;
|
||||
import "DPI-C" function int f(int, chandle);
|
||||
import "DPI-C" function void g(input int, logic [7:0], int named);
|
||||
import "DPI-C" context task t(chandle);
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
import "DPI-C" function int f(int, chandle);
|
||||
import "DPI-C" function void g(input int, logic [7:0], int named);
|
||||
import "DPI-C" context task t(chandle);
|
||||
endpackage
|
||||
====
|
||||
# a comment where an unnamed formal's name would have been
|
||||
package p;
|
||||
import "DPI-C" function int h(int /*why*/, chandle /*and why*/);
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
import "DPI-C" function int h(int /*why*/, chandle /*and why*/);
|
||||
endpackage
|
||||
====
|
||||
# an unnamed formal list long enough to break, one per line
|
||||
package p;
|
||||
import "DPI-C" function int a_very_long_imported_function_name(int, chandle, longint unsigned, logic [31:0]);
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
import "DPI-C" function int a_very_long_imported_function_name(
|
||||
int,
|
||||
chandle,
|
||||
longint unsigned,
|
||||
logic [31:0]
|
||||
);
|
||||
endpackage
|
||||
@@ -1,4 +1,4 @@
|
||||
#a randomize() with { ... } condition keeps its constraint block verbatim (ibex_mem_intf_response_seq_lib.sv:104)
|
||||
#a randomize() with { ... } written across lines is laid out as a constraint body, and the condition wraps as any multi-line condition does (ibex_mem_intf_response_seq_lib.sv:104)
|
||||
class c;
|
||||
task body();
|
||||
if (!req.randomize() with {
|
||||
@@ -12,10 +12,12 @@ endclass
|
||||
----
|
||||
class c;
|
||||
task body();
|
||||
if (!req.randomize() with {
|
||||
addr == item.addr;
|
||||
read_write == item.read_write;
|
||||
}) begin
|
||||
if (
|
||||
!req.randomize() with {
|
||||
addr == item.addr;
|
||||
read_write == item.read_write;
|
||||
}
|
||||
) begin
|
||||
`uvm_fatal(`gfn, "Cannot randomize response request")
|
||||
end
|
||||
endtask
|
||||
@@ -42,7 +44,7 @@ module m;
|
||||
endtask
|
||||
endmodule
|
||||
====
|
||||
#a dist { } inside the constraint block is part of the verbatim capture (ibex_mem_intf_response_driver.sv:94)
|
||||
#a dist { } inside the constraint block is a real weight list, broken one per line when it does not fit (ibex_mem_intf_response_driver.sv:94)
|
||||
class c;
|
||||
task body();
|
||||
if (!std::randomize(gnt_delay) with {
|
||||
@@ -58,18 +60,20 @@ endclass
|
||||
----
|
||||
class c;
|
||||
task body();
|
||||
if (!std::randomize(gnt_delay) with {
|
||||
gnt_delay dist {
|
||||
cfg.gnt_delay_min :/ 10,
|
||||
[cfg.gnt_delay_min+1 : cfg.gnt_delay_max-1] :/ 5
|
||||
};
|
||||
}) begin
|
||||
if (
|
||||
!std::randomize(gnt_delay) with {
|
||||
gnt_delay dist {
|
||||
cfg.gnt_delay_min :/ 10,
|
||||
[cfg.gnt_delay_min + 1:cfg.gnt_delay_max - 1] :/ 5
|
||||
};
|
||||
}
|
||||
) begin
|
||||
`uvm_fatal(`gfn, "Cannot randomize grant")
|
||||
end
|
||||
endtask
|
||||
endclass
|
||||
====
|
||||
#a constraint if inside the block is verbatim too (riscv_load_store_instr_lib.sv:79)
|
||||
#a constraint if inside the block is laid out like a statement if (riscv_load_store_instr_lib.sv:79)
|
||||
class c;
|
||||
function void f();
|
||||
if (!std::randomize(offset_, addr_) with {
|
||||
@@ -87,14 +91,16 @@ endclass
|
||||
----
|
||||
class c;
|
||||
function void f();
|
||||
if (!std::randomize(offset_, addr_) with {
|
||||
if (locality == NARROW) {
|
||||
soft offset_ inside {[-16:16]};
|
||||
} else {
|
||||
soft offset_ inside {[-64:64]};
|
||||
if (
|
||||
!std::randomize(offset_, addr_) with {
|
||||
if (locality == NARROW) {
|
||||
soft offset_ inside {[-16:16]};
|
||||
} else {
|
||||
soft offset_ inside {[-64:64]};
|
||||
}
|
||||
addr_ == base + offset_;
|
||||
}
|
||||
addr_ == base + offset_;
|
||||
}) begin
|
||||
) begin
|
||||
`uvm_fatal(`gfn, "Cannot randomize load/store offset")
|
||||
end
|
||||
endfunction
|
||||
@@ -140,7 +146,7 @@ class c;
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
#a one-line constraint block stays on its line
|
||||
#a with block the source wrote on one line stays on one line
|
||||
class c;
|
||||
function void f();
|
||||
if (!req.randomize() with { addr == 0; }) $fatal(1, "no");
|
||||
@@ -149,7 +155,7 @@ endclass
|
||||
----
|
||||
class c;
|
||||
function void f();
|
||||
if (!req.randomize() with { addr == 0; }) $fatal(1, "no");
|
||||
if (!req.randomize() with {addr == 0;}) $fatal(1, "no");
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
@@ -589,9 +595,13 @@ endclass
|
||||
----
|
||||
class c;
|
||||
task t;
|
||||
if (req.randomize() with {
|
||||
addr == 32'h1000;
|
||||
} && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here) begin
|
||||
if (
|
||||
req.randomize() with {
|
||||
addr == 32'h1000;
|
||||
} &&
|
||||
cfg.enable_the_long_named_feature_flag &&
|
||||
other_condition_name_goes_right_here
|
||||
) begin
|
||||
z = 1;
|
||||
end
|
||||
endtask
|
||||
@@ -612,8 +622,10 @@ class c;
|
||||
task t;
|
||||
if (
|
||||
req.randomize() with {
|
||||
addr == 32'h1000;
|
||||
} && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here_ok
|
||||
addr == 32'h1000;
|
||||
} &&
|
||||
cfg.enable_the_long_named_feature_flag &&
|
||||
other_condition_name_goes_right_here_ok
|
||||
) begin
|
||||
z = 1;
|
||||
end
|
||||
@@ -639,3 +651,4 @@ class c;
|
||||
endtask
|
||||
endclass
|
||||
====
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
# An escaped identifier (IEEE 1800-2017 5.6.1) runs from its backslash to the
|
||||
# next whitespace character and to nothing else, so every name the formatter
|
||||
# writes next to punctuation carries a terminating space. Where the layout
|
||||
# already writes a separator the output has two spaces (`logic \x = 1;`):
|
||||
# deliberate, and a fixed point on the next pass.
|
||||
|
||||
# escaped declarators: net, variable, list, unpacked, parameter
|
||||
module m;
|
||||
wire \my-signal ;
|
||||
logic \x = 1'b0;
|
||||
reg [7:0] \r-a , \r-b [0:3];
|
||||
parameter int \P-WIDTH = 8;
|
||||
localparam \Q = 1;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire \my-signal ;
|
||||
logic \x = 1'b0;
|
||||
reg [7:0] \r-a , \r-b [0:3];
|
||||
parameter int \P-WIDTH = 8;
|
||||
localparam \Q = 1;
|
||||
endmodule
|
||||
====
|
||||
# escaped ANSI ports, module name and end label
|
||||
module \my-mod (input logic \a-in , output wire [7:0] \b-out , input \c = 1);
|
||||
endmodule : \my-mod
|
||||
----
|
||||
module \my-mod (input logic \a-in , output wire [7:0] \b-out , input \c = 1);
|
||||
endmodule : \my-mod
|
||||
====
|
||||
# escaped non-ANSI ports, declared in the body
|
||||
module \m2 (\a-p , \b-p );
|
||||
input \a-p ;
|
||||
output \b-p ;
|
||||
endmodule
|
||||
----
|
||||
module \m2 (\a-p , \b-p );
|
||||
input \a-p ;
|
||||
output \b-p ;
|
||||
endmodule
|
||||
====
|
||||
# escaped package, typedefs, enum members and struct fields
|
||||
package \my-pkg ;
|
||||
typedef logic [7:0] \byte-t ;
|
||||
typedef enum logic [1:0] {\A-0 , \B-1 = 2'd2} \state-t ;
|
||||
typedef struct packed {logic \f-a ; logic [3:0] \f-b ;} \s-t ;
|
||||
typedef class \fwd-c ;
|
||||
endpackage : \my-pkg
|
||||
----
|
||||
package \my-pkg ;
|
||||
typedef logic [7:0] \byte-t ;
|
||||
typedef enum logic [1:0] {\A-0 , \B-1 = 2'd2} \state-t ;
|
||||
typedef struct packed {
|
||||
logic \f-a ;
|
||||
logic [3:0] \f-b ;
|
||||
} \s-t ;
|
||||
typedef class \fwd-c ;
|
||||
endpackage : \my-pkg
|
||||
====
|
||||
# escaped class, extends, members, tf arguments and end labels
|
||||
class \base-c ;
|
||||
endclass : \base-c
|
||||
class \my-c extends \base-c ;
|
||||
int \fld ;
|
||||
extern function void \do-it (input int \arg-a , output bit \arg-b );
|
||||
function void \f2 (int \q );
|
||||
this.\fld = \q ;
|
||||
endfunction : \f2
|
||||
task \tsk ();
|
||||
endtask : \tsk
|
||||
endclass : \my-c
|
||||
----
|
||||
class \base-c ;
|
||||
endclass : \base-c
|
||||
class \my-c extends \base-c ;
|
||||
int \fld ;
|
||||
extern function void \do-it (input int \arg-a , output bit \arg-b );
|
||||
function void \f2 (int \q );
|
||||
this.\fld = \q ;
|
||||
endfunction : \f2
|
||||
task \tsk ();
|
||||
endtask : \tsk
|
||||
endclass : \my-c
|
||||
====
|
||||
# escaped instance, overrides, instance array and port connections
|
||||
module m;
|
||||
\sub-mod #(.\P-A (2), .P_B(3)) \u-inst [3:0] (.\p-in (a), .\p-out (\w ), .*);
|
||||
sub \u2 (.\c-in );
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
\sub-mod #(.\P-A (2), .P_B(3)) \u-inst [3:0] (.\p-in (a), .\p-out (\w ), .*);
|
||||
sub \u2 (.\c-in );
|
||||
endmodule
|
||||
====
|
||||
# escaped names in expressions: member, index, scope, named argument
|
||||
module m;
|
||||
assign \b-out = \iface .\vld [3] & \my-pkg ::\A-0 ;
|
||||
initial begin
|
||||
$display("%d", \q .\r );
|
||||
\f (.\arg-a (1), .b(2));
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign \b-out = \iface .\vld [3] & \my-pkg ::\A-0 ;
|
||||
initial begin
|
||||
$display("%d", \q .\r );
|
||||
\f (.\arg-a (1), .b(2));
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# escaped genvar and generate block label
|
||||
module m;
|
||||
genvar \i ;
|
||||
generate
|
||||
for (\i = 0; \i < 4; \i = \i + 1) begin : \gen-blk
|
||||
wire \w ;
|
||||
end : \gen-blk
|
||||
endgenerate
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
genvar \i ;
|
||||
generate
|
||||
for (\i = 0; \i < 4; \i = \i + 1) begin : \gen-blk
|
||||
wire \w ;
|
||||
end : \gen-blk
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# escaped block, fork and statement labels, disable, foreach
|
||||
module m;
|
||||
initial begin : \blk-1
|
||||
\lbl-1 : assert (\st == 0);
|
||||
disable \blk-1 ;
|
||||
foreach (\w2 [\i ]) $display("%d", \w2 [\i ]);
|
||||
fork : \frk-1
|
||||
join : \frk-1
|
||||
end : \blk-1
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin : \blk-1
|
||||
\lbl-1 : assert (\st == 0);
|
||||
disable \blk-1 ;
|
||||
foreach (\w2 [\i ]) $display("%d", \w2 [\i ]);
|
||||
fork : \frk-1
|
||||
join : \frk-1
|
||||
end : \blk-1
|
||||
endmodule
|
||||
====
|
||||
# escaped interface, modport and clocking block
|
||||
interface \my-if (input \clk );
|
||||
logic \vld ;
|
||||
modport \mp-a (input \vld , output \clk );
|
||||
clocking \cb-1 @(posedge \clk );
|
||||
input \vld ;
|
||||
output \drv = \vld ;
|
||||
endclocking : \cb-1
|
||||
endinterface : \my-if
|
||||
----
|
||||
interface \my-if (input \clk );
|
||||
logic \vld ;
|
||||
modport \mp-a (input \vld , output \clk );
|
||||
clocking \cb-1 @(posedge \clk );
|
||||
input \vld ;
|
||||
output \drv = \vld ;
|
||||
endclocking : \cb-1
|
||||
endinterface : \my-if
|
||||
====
|
||||
# escaped import and export paths
|
||||
package p;
|
||||
import \my-pkg ::\thing ;
|
||||
import \my-pkg ::*;
|
||||
export \my-pkg ::*;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
import \my-pkg ::\thing ;
|
||||
import \my-pkg ::*;
|
||||
export \my-pkg ::*;
|
||||
endpackage
|
||||
====
|
||||
# a Vivado-style netlist fragment: brackets and dots inside the name
|
||||
module \netlist-top (\clk );
|
||||
input \clk ;
|
||||
wire \u_x/y_reg[3] ;
|
||||
wire \gen[0].u/z ;
|
||||
FDRE #(.INIT(1'b0)) \u_x/y_reg[3]_i_1 (.C(\clk ), .D(\gen[0].u/z ), .Q(\u_x/y_reg[3] ));
|
||||
and \g-1 (\u_x/y_reg[3] , \clk , \gen[0].u/z );
|
||||
endmodule
|
||||
----
|
||||
module \netlist-top (\clk );
|
||||
input \clk ;
|
||||
wire \u_x/y_reg[3] ;
|
||||
wire \gen[0].u/z ;
|
||||
FDRE #(.INIT(1'b0)) \u_x/y_reg[3]_i_1 (.C(\clk ), .D(\gen[0].u/z ), .Q(\u_x/y_reg[3] ));
|
||||
and \g-1 (\u_x/y_reg[3] , \clk , \gen[0].u/z );
|
||||
endmodule
|
||||
====
|
||||
# an escaped name inside an aligned port, parameter and connection group
|
||||
module m (
|
||||
input logic \clk-i ,
|
||||
input logic [7:0] \data-i ,
|
||||
output logic q
|
||||
);
|
||||
parameter int \P-A = 1;
|
||||
parameter int LONGER_NAME = 2;
|
||||
sub u0 (
|
||||
.\a-in (\clk-i ),
|
||||
.bbbb (\data-i ),
|
||||
.c (q)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input logic \clk-i ,
|
||||
input logic [7:0] \data-i ,
|
||||
output logic q
|
||||
);
|
||||
parameter int \P-A = 1;
|
||||
parameter int LONGER_NAME = 2;
|
||||
sub u0 (
|
||||
.\a-in (\clk-i ),
|
||||
.bbbb (\data-i ),
|
||||
.c (q)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# escaped let declaration, defparam target and call
|
||||
module m;
|
||||
let \max-2 (\a , \b ) = (\a > \b ) ? \a : \b ;
|
||||
defparam \u-inst .\P-A = 4;
|
||||
initial \x = \max-2 (1, 2);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
let \max-2 (\a , \b ) = (\a > \b ) ? \a : \b ;
|
||||
defparam \u-inst .\P-A = 4;
|
||||
initial \x = \max-2 (1, 2);
|
||||
endmodule
|
||||
====
|
||||
# escaped case labels
|
||||
module m;
|
||||
always_comb begin
|
||||
case (\st )
|
||||
\A-0 , \B-1 : \st = 1;
|
||||
default: \st = 0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
case (\st )
|
||||
\A-0 , \B-1 : \st = 1;
|
||||
default: \st = 0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# escaped connections keep their terminator when the list breaks
|
||||
module m;
|
||||
sub u0 (.\a-in (\some-long-signal-name-here ), .\b-in (\another-long-signal-name ), .\c-in (\third-long-signal-name ));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u0 (
|
||||
.\a-in (\some-long-signal-name-here ),
|
||||
.\b-in (\another-long-signal-name ),
|
||||
.\c-in (\third-long-signal-name )
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# an out-of-class method definition scoped by an escaped class name
|
||||
function void \my-c ::\do-it ();
|
||||
endfunction
|
||||
----
|
||||
function void \my-c ::\do-it ();
|
||||
endfunction
|
||||
====
|
||||
# a `pkg::type` chain whose every segment is escaped: the join keeps the
|
||||
# whitespace that terminates each one, so the three tokens stay three
|
||||
# (docs/topo.md §2.9-21, closed by docs/features/comment-slots/README.md).
|
||||
# The doubled space is what a bare escaped type name already prints.
|
||||
module m;
|
||||
\my-pkg ::\state-t \st ;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
\my-pkg ::\state-t \st ;
|
||||
endmodule
|
||||
====
|
||||
# an escaped type name widens the alignment column by its terminator
|
||||
module m (
|
||||
input \my-t \a-in-with-a-long-name ,
|
||||
input logic [31:0] bbbb_long_name_here,
|
||||
output \other-type-t \c-out-long-name
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input \my-t \a-in-with-a-long-name ,
|
||||
input logic [31:0] bbbb_long_name_here,
|
||||
output \other-type-t \c-out-long-name
|
||||
);
|
||||
endmodule
|
||||
@@ -256,6 +256,20 @@ package p;
|
||||
endfunction
|
||||
endpackage
|
||||
====
|
||||
# `const ref` is the one direction written as two keywords, so the gap
|
||||
# between them is a comment slot of its own — IEEE 1800-2017 13.5.2
|
||||
package p;
|
||||
function automatic int max(const /*hold it*/ ref int int_q[$]);
|
||||
return int_q[0];
|
||||
endfunction
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
function automatic int max(const /*hold it*/ ref int int_q [$]);
|
||||
return int_q[0];
|
||||
endfunction
|
||||
endpackage
|
||||
====
|
||||
# every new shape is left alone inside a format fence
|
||||
module m;
|
||||
// verilog_format: off
|
||||
|
||||
@@ -372,7 +372,7 @@ wire a;
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# a statement-level fence has no effect this round
|
||||
# a statement-level fence fences the statements between it and the on
|
||||
module m;
|
||||
always @(*) begin
|
||||
// lucisv: off
|
||||
@@ -382,15 +382,259 @@ y = 2;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(*) begin
|
||||
// lucisv: off
|
||||
x = 1;
|
||||
// lucisv: on
|
||||
y = 2;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a statement region keeps its own indentation, first line included
|
||||
module m;
|
||||
initial begin
|
||||
// lucisv: off
|
||||
x <= 8'h0a;
|
||||
yy <= 8'h0b;
|
||||
// lucisv: on
|
||||
z <= 1;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
// lucisv: off
|
||||
x <= 8'h0a;
|
||||
yy <= 8'h0b;
|
||||
// lucisv: on
|
||||
z <= 1;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# an unmatched off runs to the end of the block, not past its end
|
||||
module m;
|
||||
initial begin
|
||||
// lucisv: off
|
||||
x = 1;
|
||||
y = 2; // note
|
||||
end
|
||||
initial begin
|
||||
z = 3;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
// lucisv: off
|
||||
x = 1;
|
||||
y = 2; // note
|
||||
end
|
||||
initial begin
|
||||
z = 3;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# an unmatched off in a fork body stops at the join
|
||||
module m;
|
||||
initial fork
|
||||
// lucisv: off
|
||||
p1 ();
|
||||
p2 ();
|
||||
join_none
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial
|
||||
fork
|
||||
// lucisv: off
|
||||
p1 ();
|
||||
p2 ();
|
||||
join_none
|
||||
endmodule
|
||||
====
|
||||
# fences work in a function body and stop at endfunction
|
||||
module m;
|
||||
function int f();
|
||||
// lucisv: off
|
||||
int a =1;
|
||||
// lucisv: on
|
||||
return a;
|
||||
endfunction
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
function int f();
|
||||
// lucisv: off
|
||||
int a =1;
|
||||
// lucisv: on
|
||||
return a;
|
||||
endfunction
|
||||
endmodule
|
||||
====
|
||||
# a fence inside a case item's block body fences that block only
|
||||
module m;
|
||||
always @(*) begin
|
||||
case (s)
|
||||
2'b00: begin
|
||||
// lucisv: off
|
||||
a = 1;
|
||||
// lucisv: on
|
||||
b = 2;
|
||||
end
|
||||
default: c = 3;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(*) begin
|
||||
case (s)
|
||||
2'b00: begin
|
||||
// lucisv: off
|
||||
a = 1;
|
||||
// lucisv: on
|
||||
b = 2;
|
||||
end
|
||||
default: c = 3;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a fence written after begin on the same line is an ordinary comment
|
||||
module m;
|
||||
always @(*) begin // lucisv: off
|
||||
x = 1;
|
||||
y = 2;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(*) begin
|
||||
// lucisv: off
|
||||
x = 1;
|
||||
// lucisv: on
|
||||
y = 2;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a fence written after a module header on the same line is an ordinary comment
|
||||
module m; // lucisv: off
|
||||
wire a;
|
||||
wire b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// lucisv: off
|
||||
wire a;
|
||||
wire b;
|
||||
endmodule
|
||||
====
|
||||
# a fence inside a bodyless if is an ordinary comment
|
||||
module m;
|
||||
always @(*)
|
||||
// lucisv: off
|
||||
if (c) x = 1;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(*)
|
||||
// lucisv: off
|
||||
if (c) x = 1;
|
||||
endmodule
|
||||
====
|
||||
# fences work inside a class body
|
||||
class c;
|
||||
int a;
|
||||
// lucisv: off
|
||||
int b =2;
|
||||
int cc =3;
|
||||
// lucisv: on
|
||||
int d;
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
int a;
|
||||
// lucisv: off
|
||||
int b =2;
|
||||
int cc =3;
|
||||
// lucisv: on
|
||||
int d;
|
||||
endclass
|
||||
====
|
||||
# an unmatched off in a class body stops at endclass
|
||||
class c;
|
||||
// lucisv: off
|
||||
int a;
|
||||
endclass
|
||||
|
||||
class d;
|
||||
int b;
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
// lucisv: off
|
||||
int a;
|
||||
endclass
|
||||
|
||||
class d;
|
||||
int b;
|
||||
endclass
|
||||
====
|
||||
# a fence around a nested class fences the whole nested class
|
||||
class outer;
|
||||
// lucisv: off
|
||||
class inner;
|
||||
int x;
|
||||
endclass
|
||||
// lucisv: on
|
||||
int y;
|
||||
endclass
|
||||
----
|
||||
class outer;
|
||||
// lucisv: off
|
||||
class inner;
|
||||
int x;
|
||||
endclass
|
||||
// lucisv: on
|
||||
int y;
|
||||
endclass
|
||||
====
|
||||
# a port-list fence is an ordinary comment, and the port list still formats
|
||||
module m (
|
||||
// lucisv: off
|
||||
input logic a,
|
||||
output logic b
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
// lucisv: off
|
||||
input logic a,
|
||||
output logic b
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# a case-item label fence is an ordinary comment
|
||||
module m;
|
||||
always @(*) begin
|
||||
case (s)
|
||||
// lucisv: off
|
||||
2'b00: a = 1;
|
||||
2'b01: a = 2;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(*) begin
|
||||
case (s)
|
||||
// lucisv: off
|
||||
2'b00: a = 1;
|
||||
2'b01: a = 2;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a blank line before the off fence survives, collapsed to one
|
||||
module m;
|
||||
wire z;
|
||||
|
||||
Loaded 100 of 328 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user